Coverage for ase/calculators/castep.py: 50.28%
714 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1"""This module defines an interface to CASTEP for
2 use by the ASE (Webpage: https://ase-lib.org/)
4Authors:
5 Max Hoffmann, max.hoffmann@ch.tum.de
6 Joerg Meyer, joerg.meyer@ch.tum.de
7 Simon P. Rittmeyer, simon.rittmeyer@tum.de
9Contributors:
10 Juan M. Lorenzi, juan.lorenzi@tum.de
11 Georg S. Michelitsch, georg.michelitsch@tch.tum.de
12 Reinhard J. Maurer, reinhard.maurer@yale.edu
13 Simone Sturniolo, simone.sturniolo@stfc.ac.uk
14"""
16import difflib
17import glob
18import json
19import os
20import re
21import shutil
22import subprocess
23import sys
24import tempfile
25import time
26import warnings
27from collections import namedtuple
28from copy import deepcopy
29from itertools import product
30from pathlib import Path
32import numpy as np
34from ase import Atoms
35from ase.calculators.calculator import (
36 BaseCalculator,
37 compare_atoms,
38 kpts2sizeandoffsets,
39)
40from ase.config import cfg
41from ase.dft.kpoints import BandPath
42from ase.io.castep import read_bands, read_param
43from ase.io.castep.castep_input_file import CastepCell, CastepParam
44from ase.io.castep.castep_reader import read_castep_castep
45from ase.parallel import paropen
47__all__ = ['Castep', 'CastepCell', 'CastepParam', 'create_castep_keywords']
49# A convenient table to avoid the previously used "eval"
50_tf_table = {
51 '': True, # Just the keyword is equivalent to True
52 'True': True,
53 'False': False,
54}
57def _self_getter(getf):
58 # A decorator that makes it so that if no 'atoms' argument is passed to a
59 # getter function, self.atoms is used instead
61 def decor_getf(self, atoms=None, *args, **kwargs):
63 if atoms is None:
64 atoms = self.atoms
66 return getf(self, atoms, *args, **kwargs)
68 return decor_getf
71class Castep(BaseCalculator):
72 r"""CASTEP Interface Documentation
75 Introduction
76 ============
78 CASTEP_ [1]_ W_ is a software package which uses density
79 functional theory to provide a good atomic-level description of
80 all manner of materials and molecules. CASTEP can give information
81 about total energies, forces and stresses on an atomic system, as
82 well as calculating optimum geometries, band structures, optical
83 spectra, phonon spectra and much more. It can also perform
84 molecular dynamics simulations.
86 The CASTEP calculator interface class offers intuitive access to
87 all CASTEP settings and most results. All CASTEP specific settings
88 are accessible via attribute access (*i.e*. ``calc.param.keyword =
89 ...`` or ``calc.cell.keyword = ...``)
92 Getting Started:
93 ================
95 Set the environment variables appropriately for your system::
97 export CASTEP_COMMAND=' ... '
98 export CASTEP_PP_PATH=' ... '
100 Note: alternatively to CASTEP_PP_PATH one can set PSPOT_DIR
101 as CASTEP consults this by default, i.e.::
103 export PSPOT_DIR=' ... '
106 Running the Calculator
107 ======================
109 The default initialization command for the CASTEP calculator is
111 .. class:: Castep(directory='CASTEP', label='castep')
113 To do a minimal run one only needs to set atoms, this will use all
114 default settings of CASTEP, meaning LDA, singlepoint, etc..
116 With a generated *castep_keywords.json* in place all options are
117 accessible by inspection, *i.e.* tab-completion. This works best
118 when using ``ipython``. All options can be accessed via
119 ``calc.param.<TAB>`` or ``calc.cell.<TAB>`` and documentation is
120 printed with ``calc.param.<keyword> ?`` or ``calc.cell.<keyword>
121 ?``. All options can also be set directly using ``calc.keyword =
122 ...`` or ``calc.KEYWORD = ...`` or even ``ialc.KeYwOrD`` or
123 directly as named arguments in the call to the constructor (*e.g.*
124 ``Castep(task='GeometryOptimization')``). If using this
125 calculator on a machine without CASTEP, one might choose to copy a
126 *castep_keywords.json* file generated elsewhere in order to access
127 this feature: the file will be used if located in the working
128 directory, *$HOME/.ase/* or *ase/ase/calculators/* within the ASE
129 library. The file should be generated the first time it is needed,
130 but you can generate a new keywords file in the currect directory
131 with ``python -m ase.calculators.castep``.
133 All options that go into the ``.param`` file are held in an
134 ``CastepParam`` instance, while all options that go into the
135 ``.cell`` file and don't belong to the atoms object are held in an
136 ``CastepCell`` instance. Each instance can be created individually
137 and can be added to calculators by attribute assignment, *i.e.*
138 ``calc.param = param`` or ``calc.cell = cell``.
140 All internal variables of the calculator start with an underscore
141 (_). All cell attributes that clearly belong into the atoms
142 object are blocked. Setting ``calc.atoms_attribute`` (*e.g.* ``=
143 positions``) is sent directly to the atoms object.
146 Arguments:
147 ==========
149 ========================= =================================================
150 Keyword Description
151 ========================= =================================================
152 ``directory`` The relative path where all input and output
153 files
154 will be placed. If this does not exist,
155 it will be
156 created. Existing directories will be moved to
157 directory-TIMESTAMP unless
158 self._rename_existing_dir
159 is set to false.
161 ``label`` The prefix of .param, .cell, .castep, etc. files.
163 ``castep_command`` Command to run castep. Can also be set via
164 the bash
165 environment variable ``CASTEP_COMMAND``.
166 If none is
167 given or found, will default to ``castep``
169 ``check_castep_version`` Boolean whether to check if the installed castep
170 version matches the version from which the
171 available
172 options were deduced. Defaults to ``False``.
174 ``castep_pp_path`` The path where the pseudopotentials are stored.
175 Can
176 also be set via the bash environment variables
177 ``PSPOT_DIR`` (preferred) and ``CASTEP_PP_PATH``.
178 Will default to the current working directory if
179 none is given or found. Note that
180 pseudopotentials
181 may be generated on-the-fly if they are
182 not found.
184 ``find_pspots`` Boolean whether to search for pseudopotentials in
185 ``<castep_pp_path>`` or not.
186 If activated, files in
187 this directory will be checked for typical
188 names. If
189 files are not found, they will be generated
190 on the
191 fly, depending on the ``_build_missing_pspots``
192 value. A RuntimeError will be raised in case
193 multiple files per element are found. Defaults to
194 ``False``.
195 ``keyword_tolerance`` Integer to indicate the level of tolerance
196 to apply
197 validation of any parameters set in the
198 CastepCell
199 or CastepParam objects against the ones found in
200 castep_keywords. Levels are as following:
202 0 = no tolerance, keywords not found in
203 castep_keywords will raise an exception
205 1 = keywords not found will be accepted but
206 produce
207 a warning (default)
209 2 = keywords not found will be accepted silently
211 3 = no attempt is made to look for
212 castep_keywords.json at all
213 ``castep_keywords`` Can be used to pass a CastepKeywords
214 object that is
215 then used with no attempt to actually load a
216 castep_keywords.json file. Most useful for
217 debugging
218 and testing purposes.
220 ========================= =================================================
223 Additional Settings
224 ===================
226 ========================= =================================================
227 Internal Setting Description
228 ========================= =================================================
229 ``_castep_command`` (``=castep``): the actual shell command used to
230 call CASTEP.
232 ``_check_checkfile`` (``=True``): this makes write_param() only
233 write a continue or reuse statement if the
234 addressed .check or .castep_bin file exists
235 in the
236 directory.
238 ``_copy_pspots`` (``=False``): if set to True the calculator will
239 actually copy the needed pseudo-potential
240 (\*.usp)
241 file, usually it will only create symlinks.
243 ``_link_pspots`` (``=True``):
244 if set to True the calculator will
245 actually will create symlinks to the
246 needed pseudo potentials. Set this
247 option (and ``_copy_pspots``) to False
248 if you rather want to access your
249 pseudo potentials using the PSPOT_DIR
250 environment variable that is read by
251 CASTEP. *Note:* This option has no
252 effect if ``copy_pspots`` is True..
254 ``_build_missing_pspots`` (``=True``): if set to True, castep will generate
255 missing pseudopotentials on the fly. If not, a
256 RuntimeError will be raised if not all files were
257 found.
259 ``_export_settings`` (``=True``): if this is set to
260 True, all calculator internal settings shown here
261 will be included in the .param in a comment
262 line (#)
263 and can be read again by merge_param. merge_param
264 can be forced to ignore this directive using the
265 optional argument ``ignore_internal_keys=True``.
267 ``_force_write`` (``=True``): this controls wether the \*cell and
268 \*param will be overwritten.
270 ``_prepare_input_only`` (``=False``): If set to True, the calculator will
271 create \*cell und \*param file but not
272 start the calculation itself.
273 If this is used to prepare jobs locally
274 and run on a remote cluster it is recommended
275 to set ``_copy_pspots = True``.
277 ``_castep_pp_path`` (``='.'``) : the place where the calculator
278 will look for pseudo-potential files.
280 ``_find_pspots`` (``=False``): if set to True, the calculator will
281 try to find the respective
282 pseudopotentials from
283 <_castep_pp_path>. As long as there are
284 no multiple files per element in this
285 directory, the auto-detect feature
286 should be very robust. Raises a
287 RuntimeError if required files are not
288 unique (multiple files per
289 element). Non existing pseudopotentials
290 will be generated, though this could be
291 dangerous.
293 ``_rename_existing_dir`` (``=True``) : when using a new instance
294 of the calculator, this will move
295 directories out of the way that would
296 be overwritten otherwise, appending a
297 date string.
299 ``_set_atoms`` (``=False``) :
300 setting this to True will overwrite
301 any atoms object previously attached to
302 the calculator when reading a \.castep
303 file. By de- fault, the read()
304 function will only create a new atoms
305 object if none has been attached and
306 other- wise try to assign forces
307 etc. based on the atom's positions.
308 ``_set_atoms=True`` could be necessary
309 if one uses CASTEP's internal geometry
310 optimization
311 (``calc.param.task='GeometryOptimization'``)
312 because then the positions get out of
313 sync. *Warning*: this option is
314 generally not recommended unless one
315 knows one really needs it. There should
316 never be any need, if CASTEP is used as
317 a single-point calculator.
319 ``_track_output`` (``=False``) :
320 if set to true, the interface will
321 append a number to the label on all
322 input and output files, where n is the
323 number of calls to this
324 instance. *Warning*: this setting may
325 con- sume a lot more disk space because
326 of the additio- nal \*check files.
328 ``_try_reuse`` (``=_track_output``) :
329 when setting this, the in- terface will
330 try to fetch the reuse file from the
331 previous run even if _track_output is
332 True. By de- fault it is equal to
333 _track_output, but may be overridden.
335 Since this behavior may not always be
336 desirable for single-point
337 calculations. Regular reuse for *e.g.*
338 a geometry-optimization can be achieved
339 by setting ``calc.param.reuse = True``.
341 ``_pedantic`` (``=False``) if set to true, the calculator will
342 inform about settings probably wasting a lot
343 of CPU
344 time or causing numerical inconsistencies.
346 ========================= =================================================
348 Special features:
349 =================
352 ``.dryrun_ok()``
354 Runs ``castep_command seed -dryrun`` in a temporary directory
355 return True if all variables initialized ok. This is a fast way
356 to catch errors in the input. Afterwards _kpoints_used is set.
358 ``.merge_param()``
360 Takes a filename or filehandler of a .param file or CastepParam
361 instance and merges it into the current calculator instance,
362 overwriting current settings
364 ``.keyword.clear()``
366 Can be used on any option like ``calc.param.keyword.clear()`` or
367 ``calc.cell.keyword.clear()`` to return to the CASTEP default.
369 ``.initialize()``
371 Creates all needed input in the ``_directory``. This can then
372 copied to and run in a place without ASE or even python.
374 ``.set_pspot('<library>')``
376 This automatically sets the pseudo-potential for all present
377 species to ``<Species>_<library>.usp``. Make sure that
378 ``_castep_pp_path`` is set correctly. Note that there is no
379 check, if the file actually exists. If it doesn't castep will
380 crash! You may want to use ``find_pspots()`` instead.
382 ``.find_pspots(pspot=<library>, suffix=<suffix>)``
384 This automatically searches for pseudopotentials of type
385 ``<Species>_<library>.<suffix>`` or
386 ``<Species>-<library>.<suffix>`` in ``castep_pp_path` (make sure
387 this is set correctly). Note that ``<Species>`` will be searched
388 for case insensitive. Regular expressions are accepted, and
389 arguments ``'*'`` will be regarded as bash-like
390 wildcards. Defaults are any ``<library>`` and any ``<suffix>``
391 from ``['usp', 'UPF', 'recpot']``. If you have well-organized
392 folders with pseudopotentials of one kind, this should work with
393 the defaults.
395 ``print(calc)``
397 Prints a short summary of the calculator settings and atoms.
399 ``ase.io.castep.read_seed('path-to/seed')``
401 Given you have a combination of seed.{param,cell,castep} this
402 will return an atoms object with the last ionic positions in the
403 .castep file and all other settings parsed from the .cell and
404 .param file. If no .castep file is found the positions are taken
405 from the .cell file. The output directory will be set to the
406 same directory, only the label is preceded by 'copy_of\_' to
407 avoid overwriting.
409 ``.set_kpts(kpoints)``
411 This is equivalent to initialising the calculator with ``calc =
412 Castep(kpts=kpoints)``. ``kpoints`` can be specified in many
413 convenient forms: simple Monkhorst-Pack grids can be specified
414 e.g. ``(2, 2, 3)`` or ``'2 2 3'``; lists of specific weighted
415 k-points can be given in reciprocal lattice coordinates e.g.
416 ``[[0, 0, 0, 0.25], [0.25, 0.25, 0.25, 0.75]]``; a dictionary
417 syntax is available for more complex requirements e.g.
418 ``{'size': (2, 2, 2), 'gamma': True}`` will give a
419 Gamma-centered 2x2x2 M-P grid, ``{'density': 10, 'gamma': False,
420 'even': False}`` will give a mesh with density of at least 10
421 Ang (based on the unit cell of currently-attached atoms) with an
422 odd number of points in each direction and avoiding the Gamma
423 point.
425 ``.set_bandpath(bandpath)``
427 This is equivalent to initialialising the calculator with
428 ``calc=Castep(bandpath=bandpath)`` and may be set simultaneously
429 with *kpts*. It allows an electronic band structure path to be
430 set up using ASE BandPath objects. This enables a band structure
431 calculation to be set up conveniently using
432 e.g. calc.set_bandpath(atoms.cell.bandpath().interpolate(npoints=200))
434 ``.band_structure(bandfile=None)``
436 Read a band structure from _seedname.bands_ file. This returns
437 an ase BandStructure object which may be plotted with e.g.
438 ``calc.band_structure().plot()``
440 Notes/Issues:
441 ==============
443 * Currently *only* the FixAtoms *constraint* is fully supported
444 for reading and writing. There is some experimental support for
445 the FixCartesian constraint.
447 * There is no support for the CASTEP *unit system*. Units of eV
448 and Angstrom are used throughout. In particular when converting
449 total energies from different calculators, one should check that
450 the same CODATA_ version is used for constants and conversion
451 factors, respectively.
453 .. _CASTEP: https://www.castep.org/
455 .. _W: https://en.wikipedia.org/wiki/CASTEP
457 .. _CODATA: https://physics.nist.gov/cuu/Constants/index.html
459 .. [1] S. J. Clark, M. D. Segall, C. J. Pickard, P. J. Hasnip,
460 M. J. Probert,
461 K. Refson, M. C. Payne Zeitschrift für Kristallographie 220(5-6)
462 pp.567- 570 (2005) PDF_.
464 .. _PDF: https://www.tcm.phy.cam.ac.uk/castep/papers/ZKristallogr_2005.pdf
465 """
467 # Class attributes !
468 # keys set through atoms object
469 atoms_keys = [
470 'charges',
471 'ionic_constraints',
472 'lattice_abs',
473 'lattice_cart',
474 'positions_abs',
475 'positions_abs_final',
476 'positions_abs_intermediate',
477 'positions_frac',
478 'positions_frac_final',
479 'positions_frac_intermediate',
480 ]
482 atoms_obj_keys = [
483 'dipole',
484 'energy_free',
485 'energy_zero',
486 'fermi',
487 'forces',
488 'nbands',
489 'positions',
490 'stress',
491 'pressure',
492 ]
494 internal_keys = [
495 '_castep_command',
496 '_check_checkfile',
497 '_copy_pspots',
498 '_link_pspots',
499 '_find_pspots',
500 '_build_missing_pspots',
501 '_directory',
502 '_export_settings',
503 '_force_write',
504 '_label',
505 '_prepare_input_only',
506 '_castep_pp_path',
507 '_rename_existing_dir',
508 '_set_atoms',
509 '_track_output',
510 '_try_reuse',
511 '_pedantic',
512 ]
514 implemented_properties = [
515 'energy',
516 'free_energy',
517 'forces',
518 'stress',
519 'charges',
520 'magmoms',
521 ]
523 # specific to this calculator
524 implemented_properties += [
525 'energy_without_dispersion_correction',
526 'free_energy_without_dispersion_correction',
527 'energy_zero_without_dispersion_correction',
528 'energy_with_dispersion_correction',
529 'free_energy_with_dispersion_correction',
530 'energy_zero_with_dispersion_correction',
531 'energy_with_finite_basis_set_correction',
532 'pressure',
533 'hirshfeld_volume_ratios',
534 'hirshfeld_charges',
535 'hirshfeld_magmoms',
536 ]
538 def __init__(
539 self,
540 directory='CASTEP',
541 label='castep',
542 castep_command=None,
543 check_castep_version=False,
544 castep_pp_path=None,
545 find_pspots=False,
546 keyword_tolerance=1,
547 castep_keywords=None,
548 **kwargs,
549 ):
551 self.results = {}
553 from ase.io.castep import write_castep_cell
555 self._write_cell = write_castep_cell
557 if castep_keywords is None:
558 castep_keywords = CastepKeywords(
559 make_param_dict(), make_cell_dict(), [], [], 0
560 )
561 if keyword_tolerance < 3:
562 try:
563 castep_keywords = import_castep_keywords(castep_command)
564 except CastepVersionError as e:
565 if keyword_tolerance == 0:
566 raise e
567 else:
568 warnings.warn(str(e))
570 self._kw_tol = keyword_tolerance
571 keyword_tolerance = max(keyword_tolerance, 2) # 3 not accepted below
572 self.param = CastepParam(
573 castep_keywords, keyword_tolerance=keyword_tolerance
574 )
575 self.cell = CastepCell(
576 castep_keywords, keyword_tolerance=keyword_tolerance
577 )
579 ###################################
580 # Calculator state variables #
581 ###################################
582 self._calls = 0
583 self._castep_version = castep_keywords.castep_version
585 # collects content from *.err file
586 self._error = None
587 # warnings raised by the ASE interface
588 self._interface_warnings = []
590 # store to check if recalculation is necessary
591 self._old_atoms = None
592 self._old_cell = None
593 self._old_param = None
595 ###################################
596 # Internal keys #
597 # Allow to tweak the behavior #
598 ###################################
599 self._opt = {}
600 self._castep_command = get_castep_command(castep_command)
601 self._castep_pp_path = get_castep_pp_path(castep_pp_path)
602 self._check_checkfile = True
603 self._copy_pspots = False
604 self._link_pspots = True
605 self._find_pspots = find_pspots
606 self._build_missing_pspots = True
607 self._directory = os.path.abspath(directory)
608 self._export_settings = True
609 self._force_write = True
610 self._label = label
611 self._prepare_input_only = False
612 self._rename_existing_dir = True
613 self._set_atoms = False
614 self._track_output = False
615 self._try_reuse = False
617 # turn off the pedantic user warnings
618 self._pedantic = False
620 # will be set on during runtime
621 self._seed = None
623 ###################################
624 # (Physical) result variables #
625 ###################################
626 self.atoms = None
627 # initialize result variables
628 self._eigenvalues = None
629 self._efermi = None
630 self._ibz_kpts = None
631 self._ibz_weights = None
632 self._band_structure = None
634 self._number_of_cell_constraints = None
635 self._output_verbosity = None
636 self._unit_cell = None
637 self._kpoints = None
639 # pointers to other files used at runtime
640 self._check_file = None
641 self._castep_bin_file = None
643 # plane wave cutoff energy (may be derived during PP generation)
644 self._cut_off_energy = None
646 # runtime information
647 self._total_time = None
648 self._peak_memory = None
650 # check version of CASTEP options module against current one
651 if check_castep_version:
652 local_castep_version = get_castep_version(self._castep_command)
653 if not hasattr(self, '_castep_version'):
654 warnings.warn('No castep version found')
655 return
656 if local_castep_version != self._castep_version:
657 warnings.warn(
658 'The options module was generated from version %s '
659 'while your are currently using CASTEP version %s'
660 % (
661 self._castep_version,
662 get_castep_version(self._castep_command),
663 )
664 )
665 self._castep_version = local_castep_version
667 # processes optional arguments in kw style
668 for keyword, value in kwargs.items():
669 # first fetch special keywords issued by ASE CLI
670 if keyword == 'kpts':
671 self.set_kpts(value)
672 elif keyword == 'bandpath':
673 self.set_bandpath(value)
674 elif keyword == 'xc':
675 self.xc_functional = value
676 elif keyword == 'ecut':
677 self.cut_off_energy = value
678 else: # the general case
679 self.__setattr__(keyword, value)
681 # TODO: to be self.use_cache = True after revising `__setattr__`
682 self.__dict__['use_cache'] = True
684 def set_atoms(self, atoms):
685 self.atoms = atoms
687 def get_atoms(self):
688 if self.atoms is None:
689 raise ValueError('Calculator has no atoms')
690 atoms = self.atoms.copy()
691 atoms.calc = self
692 return atoms
694 def _get_name(self) -> str:
695 return self.__class__.__name__
697 def band_structure(self, bandfile=None):
698 from ase.spectrum.band_structure import BandStructure
700 if bandfile is None:
701 bandfile = os.path.join(self._directory, self._seed) + '.bands'
703 if not os.path.exists(bandfile):
704 raise ValueError(f'Cannot find band file "{bandfile}".')
706 kpts, _weights, eigenvalues, efermi = read_bands(bandfile)
708 # Get definitions of high-symmetry points
709 special_points = self.atoms.cell.bandpath(npoints=0).special_points
710 bandpath = BandPath(
711 self.atoms.cell, kpts=kpts, special_points=special_points
712 )
713 return BandStructure(bandpath, eigenvalues, reference=efermi)
715 def set_bandpath(self, bandpath):
716 """Set a band structure path from ase.dft.kpoints.BandPath object
718 This will set the bs_kpoint_list block with a set of specific points
719 determined in ASE. bs_kpoint_spacing will not be used; to modify the
720 number of points, consider using e.g. bandpath.resample(density=20) to
721 obtain a new dense path.
723 Args:
724 bandpath (:obj:`ase.dft.kpoints.BandPath` or None):
725 Set to None to remove list of band structure points. Otherwise,
726 sampling will follow BandPath parameters.
728 """
730 def clear_bs_keywords():
731 bs_keywords = product(
732 {'bs_kpoint', 'bs_kpoints'},
733 {
734 'path',
735 'path_spacing',
736 'list',
737 'mp_grid',
738 'mp_spacing',
739 'mp_offset',
740 },
741 )
742 for bs_tag in bs_keywords:
743 setattr(self.cell, '_'.join(bs_tag), None)
745 if bandpath is None:
746 clear_bs_keywords()
747 elif isinstance(bandpath, BandPath):
748 clear_bs_keywords()
749 self.cell.bs_kpoint_list = [
750 ' '.join(map(str, row)) for row in bandpath.kpts
751 ]
752 else:
753 raise TypeError(
754 'Band structure path must be an ase.dft.kpoint.BandPath object'
755 )
757 def set_kpts(self, kpts):
758 """Set k-point mesh/path using a str, tuple or ASE features
760 Args:
761 kpts (None, tuple, str, dict):
763 This method will set the CASTEP parameters kpoints_mp_grid,
764 kpoints_mp_offset and kpoints_mp_spacing as appropriate. Unused
765 parameters will be set to None (i.e. not included in input files.)
767 If kpts=None, all these parameters are set as unused.
769 The simplest useful case is to give a 3-tuple of integers specifying
770 a Monkhorst-Pack grid. This may also be formatted as a string separated
771 by spaces; this is the format used internally before writing to the
772 input files.
774 A more powerful set of features is available when using a python
775 dictionary with the following allowed keys:
777 - 'size' (3-tuple of int) mesh of mesh dimensions
778 - 'density' (float) for BZ sampling density in points per recip. Ang
779 ( kpoint_mp_spacing = 1 / (2pi * density) ). An explicit MP mesh will
780 be set to allow for rounding/centering.
781 - 'spacing' (float) for BZ sampling density for maximum space between
782 sample points in reciprocal space. This is numerically equivalent to
783 the inbuilt ``calc.cell.kpoint_mp_spacing``, but will be converted to
784 'density' to allow for rounding/centering.
785 - 'even' (bool) to round each direction up to the nearest even number;
786 set False for odd numbers, leave as None for no odd/even rounding.
787 - 'gamma' (bool) to offset the Monkhorst-Pack grid to include
788 (0, 0, 0); set False to offset each direction avoiding 0.
789 """
791 def clear_mp_keywords():
792 mp_keywords = product(
793 {'kpoint', 'kpoints'},
794 {'mp_grid', 'mp_offset', 'mp_spacing', 'list'},
795 )
796 for kp_tag in mp_keywords:
797 setattr(self.cell, '_'.join(kp_tag), None)
799 # Case 1: Clear parameters with set_kpts(None)
800 if kpts is None:
801 clear_mp_keywords()
803 # Case 2: list of explicit k-points with weights
804 # e.g. [[ 0, 0, 0, 0.125],
805 # [ 0, -0.5, 0, 0.375],
806 # [-0.5, 0, -0.5, 0.375],
807 # [-0.5, -0.5, -0.5, 0.125]]
809 elif isinstance(kpts, (tuple, list)) and isinstance(
810 kpts[0], (tuple, list)
811 ):
812 if not all(map((lambda row: len(row) == 4), kpts)):
813 raise ValueError(
814 'In explicit kpt list each row should have 4 elements'
815 )
817 clear_mp_keywords()
818 self.cell.kpoint_list = [' '.join(map(str, row)) for row in kpts]
820 # Case 3: list of explicit kpts formatted as list of str
821 # i.e. the internal format of calc.kpoint_list split on \n
822 # e.g. ['0 0 0 0.125', '0 -0.5 0 0.375', '-0.5 0 -0.5 0.375']
823 elif isinstance(kpts, (tuple, list)) and isinstance(kpts[0], str):
824 if not all(map((lambda row: len(row.split()) == 4), kpts)):
825 raise ValueError(
826 'In explicit kpt list each row should have 4 elements'
827 )
829 clear_mp_keywords()
830 self.cell.kpoint_list = kpts
832 # Case 4: list or tuple of MP samples e.g. [3, 3, 2]
833 elif isinstance(kpts, (tuple, list)) and isinstance(kpts[0], int):
834 if len(kpts) != 3:
835 raise ValueError('Monkhorst-pack grid should have 3 values')
836 clear_mp_keywords()
837 self.cell.kpoint_mp_grid = '%d %d %d' % tuple(kpts)
839 # Case 5: str representation of Case 3 e.g. '3 3 2'
840 elif isinstance(kpts, str):
841 self.set_kpts([int(x) for x in kpts.split()])
843 # Case 6: dict of options e.g. {'size': (3, 3, 2), 'gamma': True}
844 # 'spacing' is allowed but transformed to 'density' to get mesh/offset
845 elif isinstance(kpts, dict):
846 kpts = kpts.copy()
848 if (
849 kpts.get('spacing') is not None
850 and kpts.get('density') is not None
851 ):
852 raise ValueError(
853 'Cannot set kpts spacing and density simultaneously.'
854 )
855 else:
856 if kpts.get('spacing') is not None:
857 kpts = kpts.copy()
858 spacing = kpts.pop('spacing')
859 kpts['density'] = 1 / (2 * np.pi * spacing)
861 clear_mp_keywords()
862 size, offsets = kpts2sizeandoffsets(atoms=self.atoms, **kpts)
863 self.cell.kpoint_mp_grid = '%d %d %d' % tuple(size)
864 self.cell.kpoint_mp_offset = '%f %f %f' % tuple(offsets)
866 # Case 7: some other iterator. Try treating as a list:
867 elif hasattr(kpts, '__iter__'):
868 self.set_kpts(list(kpts))
870 # Otherwise, give up
871 else:
872 raise TypeError('Cannot interpret kpts of this type')
874 def todict(self, skip_default=True):
875 """Create dict with settings of .param and .cell"""
876 dct = {}
877 dct['param'] = self.param.get_attr_dict()
878 dct['cell'] = self.cell.get_attr_dict()
880 return dct
882 def check_state(self, atoms, tol=1e-15):
883 """Check for system changes since last calculation."""
884 return compare_atoms(self._old_atoms, atoms)
886 def read(self, castep_file):
887 """Read a castep file into the current instance."""
889 atoms = read_castep_castep(castep_file)
891 self.results = atoms.calc.results
893 self._cut_off_energy = atoms.calc._cut_off_energy
894 for k, v in atoms.calc._parameters_header.items():
895 setattr(self.param, k, v)
897 if self.atoms and not self._set_atoms:
898 # compensate for internal reordering of atoms by CASTEP
899 # using the fact that the order is kept within each species
901 indices = _get_indices_to_sort_back(
902 self.atoms.symbols,
903 atoms.symbols,
904 )
905 positions_frac_atoms = atoms.get_scaled_positions()[indices]
906 self.atoms.set_scaled_positions(positions_frac_atoms)
907 keys = [
908 'forces',
909 'charges',
910 'magmoms',
911 'hirshfeld_volume_ratios',
912 'hirshfeld_charges',
913 'hirshfeld_magmoms',
914 ]
915 for k in keys:
916 if k not in self.results:
917 continue
918 self.results[k] = self.results[k][indices]
920 else:
921 atoms.set_initial_charges(self.results.get('charges'))
922 atoms.set_initial_magnetic_moments(self.results.get('magmoms'))
923 atoms.calc = self
925 self._kpoints = atoms.calc._kpoints
927 self.cell.species_pot = atoms.calc._species_pot
929 self._total_time = atoms.calc._total_time
930 self._peak_memory = atoms.calc._peak_memory
932 # Read in eigenvalues from bands file
933 bands_file = castep_file[:-7] + '.bands'
934 if (
935 self.param.task.value is not None
936 and self.param.task.value.lower() == 'bandstructure'
937 ):
938 self._band_structure = self.band_structure(bandfile=bands_file)
939 else:
940 try:
941 (
942 self._ibz_kpts,
943 self._ibz_weights,
944 self._eigenvalues,
945 self._efermi,
946 ) = read_bands(bands_file)
947 except FileNotFoundError:
948 warnings.warn(
949 'Could not load .bands file, eigenvalues and '
950 'Fermi energy are unknown'
951 )
953 # TODO: deprecate once inheriting BaseCalculator
954 def get_hirsh_volrat(self):
955 """
956 Return the Hirshfeld volume ratios.
957 """
958 return self.results.get('hirshfeld_volume_ratios')
960 # TODO: deprecate once inheriting BaseCalculator
961 def get_spins(self):
962 """
963 Return the spins from a plane-wave Mulliken analysis.
964 """
965 return self.results['magmoms']
967 # TODO: deprecate once inheriting BaseCalculator
968 def get_mulliken_charges(self):
969 """
970 Return the charges from a plane-wave Mulliken analysis.
971 """
972 return self.results['charges']
974 # TODO: deprecate once inheriting BaseCalculator
975 def get_hirshfeld_charges(self):
976 """
977 Return the charges from a Hirshfeld analysis.
978 """
979 return self.results.get('hirshfeld_charges')
981 def get_total_time(self):
982 """
983 Return the total runtime
984 """
985 return self._total_time
987 def get_peak_memory(self):
988 """
989 Return the peak memory usage
990 """
991 return self._peak_memory
993 def set_label(self, label):
994 """The label is part of each seed, which in turn is a prefix
995 in each CASTEP related file.
996 """
997 # we may think about changing this in future to set `self._directory`
998 # and `self._label`, as one would expect
999 self._label = label
1001 def set_pspot(
1002 self, pspot, elems=None, notelems=None, clear=True, suffix='usp'
1003 ):
1004 """Quickly set all pseudo-potentials: Usually CASTEP psp are named
1005 like <Elem>_<pspot>.<suffix> so this function function only expects
1006 the <LibraryName>. It then clears any previous pseudopotential
1007 settings apply the one with <LibraryName> for each element in the
1008 atoms object. The optional elems and notelems arguments can be used
1009 to exclusively assign to some species, or to exclude with notelemens.
1011 Parameters ::
1013 - elems (None) : set only these elements
1014 - notelems (None): do not set the elements
1015 - clear (True): clear previous settings
1016 - suffix (usp): PP file suffix
1017 """
1018 if self._find_pspots:
1019 if self._pedantic:
1020 warnings.warn(
1021 'Warning: <_find_pspots> = True. '
1022 'Do you really want to use `set_pspots()`? '
1023 'This does not check whether the PP files exist. '
1024 'You may rather want to use `find_pspots()` with '
1025 'the same <pspot>.'
1026 )
1028 if clear and not elems and not notelems:
1029 self.cell.species_pot.clear()
1030 for elem in set(self.atoms.get_chemical_symbols()):
1031 if elems is not None and elem not in elems:
1032 continue
1033 if notelems is not None and elem in notelems:
1034 continue
1035 self.cell.species_pot = (elem, f'{elem}_{pspot}.{suffix}')
1037 def find_pspots(
1038 self,
1039 pspot='.+',
1040 elems=None,
1041 notelems=None,
1042 clear=True,
1043 suffix='(usp|UPF|recpot)',
1044 ):
1045 r"""Quickly find and set all pseudo-potentials by searching in
1046 castep_pp_path:
1048 This one is more flexible than set_pspots, and also checks if the files
1049 are actually available from the castep_pp_path.
1051 Essentially, the function parses the filenames in <castep_pp_path> and
1052 does a regex matching. The respective pattern is:
1054 r"^(<elem>|<elem.upper()>|elem.lower()>(_|-)<pspot>\.<suffix>$"
1056 In most cases, it will be sufficient to not specify anything, if you
1057 use standard CASTEP USPPs with only one file per element in the
1058 <castep_pp_path>.
1060 The function raises a `RuntimeError` if there is some ambiguity
1061 (multiple files per element).
1063 Parameters ::
1065 - pspots ('.+') : as defined above, will be a wildcard if not
1066 specified.
1067 - elems (None) : set only these elements
1068 - notelems (None): do not set the elements
1069 - clear (True): clear previous settings
1070 - suffix (usp|UPF|recpot): PP file suffix
1071 """
1072 if clear and not elems and not notelems:
1073 self.cell.species_pot.clear()
1075 if not os.path.isdir(self._castep_pp_path):
1076 if self._pedantic:
1077 warnings.warn(
1078 'Cannot search directory: {} Folder does not exist'.format(
1079 self._castep_pp_path
1080 )
1081 )
1082 return
1084 # translate the bash wildcard syntax to regex
1085 if pspot == '*':
1086 pspot = '.*'
1087 if suffix == '*':
1088 suffix = '.*'
1089 if pspot == '*':
1090 pspot = '.*'
1092 # GBRV USPPs have a strnage naming schme
1093 pattern = r'^({elem}|{elem_upper}|{elem_lower})(_|-){pspot}\.{suffix}$'
1095 for elem in set(self.atoms.get_chemical_symbols()):
1096 if elems is not None and elem not in elems:
1097 continue
1098 if notelems is not None and elem in notelems:
1099 continue
1100 p = pattern.format(
1101 elem=elem,
1102 elem_upper=elem.upper(),
1103 elem_lower=elem.lower(),
1104 pspot=pspot,
1105 suffix=suffix,
1106 )
1107 pps = []
1108 for f in os.listdir(self._castep_pp_path):
1109 if re.match(p, f):
1110 pps.append(f)
1111 if not pps:
1112 if self._pedantic:
1113 warnings.warn(
1114 'Pseudopotential for species {} not found!'.format(elem)
1115 )
1116 elif len(pps) != 1:
1117 raise RuntimeError(
1118 'Pseudopotential for species {} not unique!\n'.format(elem)
1119 + 'Found the following files in {}\n'.format(
1120 self._castep_pp_path
1121 )
1122 + '\n'.join([f' {pp}' for pp in pps])
1123 + '\nConsider a stricter search pattern in `find_pspots()`.'
1124 )
1125 else:
1126 self.cell.species_pot = (elem, pps[0])
1128 @_self_getter
1129 def get_total_energy(self, atoms):
1130 """Run CASTEP calculation if needed and return total energy."""
1131 self.update(atoms)
1132 return self.results.get('energy_without_dispersion_correction')
1134 @_self_getter
1135 def get_total_energy_corrected(self, atoms):
1136 """Run CASTEP calculation if needed and return total energy."""
1137 self.update(atoms)
1138 return self.results.get('energy_with_finite_basis_set_correction')
1140 @_self_getter
1141 def get_free_energy(self, atoms):
1142 """Run CASTEP calculation if needed and return free energy.
1143 Only defined with smearing."""
1144 self.update(atoms)
1145 return self.results.get('free_energy_without_dispersion_correction')
1147 @_self_getter
1148 def get_0K_energy(self, atoms):
1149 """Run CASTEP calculation if needed and return 0K energy.
1150 Only defined with smearing."""
1151 self.update(atoms)
1152 return self.results.get('energy_zero_without_dispersion_correction')
1154 @_self_getter
1155 def get_pressure(self, atoms):
1156 """Return the pressure."""
1157 self.update(atoms)
1158 return self.results.get('pressure')
1160 @_self_getter
1161 def get_unit_cell(self, atoms):
1162 """Return the unit cell."""
1163 self.update(atoms)
1164 return self._unit_cell
1166 @_self_getter
1167 def get_kpoints(self, atoms):
1168 """Return the kpoints."""
1169 self.update(atoms)
1170 return self._kpoints
1172 @_self_getter
1173 def get_number_cell_constraints(self, atoms):
1174 """Return the number of cell constraints."""
1175 self.update(atoms)
1176 return self._number_of_cell_constraints
1178 def update(self, atoms):
1179 """Checks if atoms object or calculator changed and
1180 runs calculation if so.
1181 """
1182 if self.calculation_required(atoms, None):
1183 self.calculate(atoms, [], [])
1185 def calculation_required(self, atoms, properties):
1186 """Checks wether anything changed in the atoms object or CASTEP
1187 settings since the last calculation using this instance.
1188 """
1189 # SPR: what happens with the atoms parameter here? Why don't we use it?
1190 # from all that I can tell we need to compare against atoms instead of
1191 # self.atoms
1192 # if not self.atoms == self._old_atoms:
1193 if atoms != self._old_atoms:
1194 return True
1195 if self._old_param is None or self._old_cell is None:
1196 return True
1197 if self.param._options != self._old_param._options:
1198 return True
1199 if self.cell._options != self._old_cell._options:
1200 return True
1201 return False
1203 def calculate(self, atoms, properties, system_changes):
1204 """Write all necessary input file and call CASTEP."""
1205 self.prepare_input_files(atoms, force_write=self._force_write)
1206 if not self._prepare_input_only:
1207 self.run()
1208 if self._seed is None:
1209 basename = os.path.basename(self._castep_file)
1210 self._seed = os.path.splitext(basename)[0]
1211 err_file = f'{self._seed}.0001.err'
1212 if os.path.exists(err_file):
1213 err_file = paropen(err_file)
1214 self._error = err_file.read()
1215 err_file.close()
1216 self.read(self._castep_file)
1218 # we need to push the old state here!
1219 # although run() pushes it, read() may change the atoms object
1220 # again.
1221 # yet, the old state is supposed to be the one AFTER read()
1222 self.push_oldstate()
1224 def push_oldstate(self):
1225 """This function pushes the current state of the (CASTEP) Atoms object
1226 onto the previous state. Or in other words after calling this function,
1227 calculation_required will return False and enquiry functions just
1228 report the current value, e.g. get_forces(), get_potential_energy().
1229 """
1230 # make a snapshot of all current input
1231 # to be able to test if recalculation
1232 # is necessary
1233 self._old_atoms = self.atoms.copy()
1234 self._old_param = deepcopy(self.param)
1235 self._old_cell = deepcopy(self.cell)
1237 def initialize(self, *args, **kwargs):
1238 """Just an alias for prepar_input_files to comply with standard
1239 function names in ASE.
1240 """
1241 self.prepare_input_files(*args, **kwargs)
1243 def prepare_input_files(self, atoms=None, force_write=None):
1244 """Only writes the input .cell and .param files and return
1245 This can be useful if one quickly needs to prepare input files
1246 for a cluster where no python or ASE is available. One can than
1247 upload the file manually and read out the results using
1248 Castep().read().
1249 """
1251 if self.param.reuse.value is None:
1252 if self._pedantic:
1253 warnings.warn(
1254 'You have not set e.g. calc.param.reuse = True. '
1255 'Reusing a previous calculation may save CPU time! '
1256 'The interface will make sure by default, .check exists. '
1257 'file before adding this statement to the .param file.'
1258 )
1259 if self.param.num_dump_cycles.value is None:
1260 if self._pedantic:
1261 warnings.warn(
1262 'You have not set e.g. calc.param.num_dump_cycles = 0. '
1263 'This can save you a lot of disk space. One only needs '
1264 '*wvfn* if electronic convergence is not achieved.'
1265 )
1266 from ase.io.castep import write_param
1268 if atoms is None:
1269 atoms = self.atoms
1270 else:
1271 self.atoms = atoms
1273 if force_write is None:
1274 force_write = self._force_write
1276 # if we have new instance of the calculator,
1277 # move existing results out of the way, first
1278 if (
1279 os.path.isdir(self._directory)
1280 and self._calls == 0
1281 and self._rename_existing_dir
1282 ):
1283 if os.listdir(self._directory) == []:
1284 os.rmdir(self._directory)
1285 else:
1286 # rename appending creation date of the directory
1287 ctime = time.localtime(os.lstat(self._directory).st_ctime)
1288 os.rename(
1289 self._directory,
1290 '%s.bak-%s'
1291 % (self._directory, time.strftime('%Y%m%d-%H%M%S', ctime)),
1292 )
1294 # create work directory
1295 if not os.path.isdir(self._directory):
1296 os.makedirs(self._directory, 0o775)
1298 # we do this every time, not only upon first call
1299 # if self._calls == 0:
1300 self._fetch_pspots()
1302 # if _try_reuse is requested and this
1303 # is not the first run, we try to find
1304 # the .check file from the previous run
1305 # this is only necessary if _track_output
1306 # is set to true
1307 if self._try_reuse and self._calls > 0:
1308 if os.path.exists(self._abs_path(self._check_file)):
1309 self.param.reuse = self._check_file
1310 elif os.path.exists(self._abs_path(self._castep_bin_file)):
1311 self.param.reuse = self._castep_bin_file
1312 self._seed = self._build_castep_seed()
1313 self._check_file = f'{self._seed}.check'
1314 self._castep_bin_file = f'{self._seed}.castep_bin'
1315 self._castep_file = self._abs_path(f'{self._seed}.castep')
1317 # write out the input file
1318 magnetic_moments = (
1319 'initial' if self.param.spin_polarized.value == 'TRUE' else None
1320 )
1321 self._write_cell(
1322 self._abs_path(f'{self._seed}.cell'),
1323 self.atoms,
1324 castep_cell=self.cell,
1325 magnetic_moments=magnetic_moments,
1326 )
1328 if self._export_settings:
1329 interface_options = self._opt
1330 else:
1331 interface_options = None
1332 write_param(
1333 self._abs_path(f'{self._seed}.param'),
1334 self.param,
1335 check_checkfile=self._check_checkfile,
1336 force_write=force_write,
1337 interface_options=interface_options,
1338 )
1340 def _build_castep_seed(self):
1341 """Abstracts to construction of the final castep <seed>
1342 with and without _tracking_output.
1343 """
1344 if self._track_output:
1345 return '%s-%06d' % (self._label, self._calls)
1346 else:
1347 return f'{(self._label)}'
1349 def _abs_path(self, path):
1350 # Create an absolute path for a file to put in the working directory
1351 return os.path.join(self._directory, path)
1353 def run(self):
1354 """Simply call castep. If the first .err file
1355 contains text, this will be printed to the screen.
1356 """
1357 # change to target directory
1358 self._calls += 1
1360 # run castep itself
1361 stdout, stderr = shell_stdouterr(
1362 '{} {}'.format(self._castep_command, self._seed),
1363 cwd=self._directory,
1364 )
1365 if stdout:
1366 print(f'castep call stdout:\n{stdout}')
1367 if stderr:
1368 print(f'castep call stderr:\n{stderr}')
1370 # shouldn't it be called after read()???
1371 # self.push_oldstate()
1373 # check for non-empty error files
1374 err_file = self._abs_path(f'{self._seed}.0001.err')
1375 if os.path.exists(err_file):
1376 with open(err_file) as err_file:
1377 self._error = err_file.read()
1378 if self._error:
1379 raise RuntimeError(self._error)
1381 def __repr__(self):
1382 """Returns generic, fast to capture representation of
1383 CASTEP settings along with atoms object.
1384 """
1385 expr = ''
1386 expr += '-----------------Atoms--------------------\n'
1387 if self.atoms is not None:
1388 expr += str('%20s\n' % self.atoms)
1389 else:
1390 expr += 'None\n'
1392 expr += '-----------------Param keywords-----------\n'
1393 expr += str(self.param)
1394 expr += '-----------------Cell keywords------------\n'
1395 expr += str(self.cell)
1396 expr += '-----------------Internal keys------------\n'
1397 for key in self.internal_keys:
1398 expr += '%20s : %s\n' % (key, self._opt[key])
1400 return expr
1402 def __getattr__(self, attr):
1403 """___getattr___ gets overloaded to reroute the internal keys
1404 and to be able to easily store them in in the param so that
1405 they can be read in again in subsequent calls.
1406 """
1407 if attr in self.internal_keys:
1408 return self._opt[attr]
1409 if attr in ['__repr__', '__str__']:
1410 raise AttributeError
1411 elif attr not in self.__dict__:
1412 raise AttributeError(f'Attribute {attr} not found')
1413 else:
1414 return self.__dict__[attr]
1416 def __setattr__(self, attr, value):
1417 """We overload the settattr method to make value assignment
1418 as pythonic as possible. Internal values all start with _.
1419 Value assigment is case insensitive!
1420 """
1422 if attr.startswith('_'):
1423 # internal variables all start with _
1424 # let's check first if they are close but not identical
1425 # to one of the switches, that the user accesses directly
1426 similars = difflib.get_close_matches(
1427 attr, self.internal_keys, cutoff=0.9
1428 )
1429 if attr not in self.internal_keys and similars:
1430 warnings.warn(
1431 'Warning: You probably tried one of: '
1432 f'{similars} but typed {attr}'
1433 )
1434 if attr in self.internal_keys:
1435 self._opt[attr] = value
1436 if attr == '_track_output':
1437 if value:
1438 self._try_reuse = True
1439 if self._pedantic:
1440 warnings.warn(
1441 'You switched _track_output on. This will '
1442 'consume a lot of disk-space. The interface '
1443 'also switched _try_reuse on, which will '
1444 'try to find the last check file. Set '
1445 '_try_reuse = False, if you need '
1446 'really separate calculations'
1447 )
1448 elif '_try_reuse' in self._opt and self._try_reuse:
1449 self._try_reuse = False
1450 if self._pedantic:
1451 warnings.warn('_try_reuse is set to False, too')
1452 else:
1453 self.__dict__[attr] = value
1454 return
1455 elif attr in ['atoms', 'cell', 'param', 'results']:
1456 if value is not None:
1457 if attr == 'atoms' and not isinstance(value, Atoms):
1458 raise TypeError(f'{value} is not an instance of Atoms.')
1459 elif attr == 'cell' and not isinstance(value, CastepCell):
1460 raise TypeError(
1461 f'{value} is not an instance of CastepCell.'
1462 )
1463 elif attr == 'param' and not isinstance(value, CastepParam):
1464 raise TypeError(
1465 f'{value} is not an instance of CastepParam.'
1466 )
1467 # These 3 are accepted right-away, no matter what
1468 self.__dict__[attr] = value
1469 return
1470 elif attr in self.atoms_obj_keys:
1471 # keywords which clearly belong to the atoms object are
1472 # rerouted to go there
1473 self.atoms.__dict__[attr] = value
1474 return
1475 elif attr in self.atoms_keys:
1476 # CASTEP keywords that should go into the atoms object
1477 # itself are blocked
1478 warnings.warn(
1479 'Ignoring setings of "%s", since this has to be set '
1480 'through the atoms object' % attr
1481 )
1482 return
1484 attr = attr.lower()
1485 if attr not in (
1486 list(self.cell._options.keys()) + list(self.param._options.keys())
1487 ):
1488 # what is left now should be meant to be a castep keyword
1489 # so we first check if it defined, and if not offer some error
1490 # correction
1491 if self._kw_tol == 0:
1492 similars = difflib.get_close_matches(
1493 attr, self.cell._options.keys() + self.param._options.keys()
1494 )
1495 if similars:
1496 raise RuntimeError(
1497 f'Option "{attr}" not known! You mean "{similars[0]}"?'
1498 )
1499 else:
1500 raise RuntimeError(f'Option "{attr}" is not known!')
1501 else:
1502 warnings.warn(
1503 'Option "%s" is not known - please set any new'
1504 ' options directly in the .cell or .param '
1505 'objects' % attr
1506 )
1507 return
1509 # here we know it must go into one of the component param or cell
1510 # so we first determine which one
1511 if attr in self.param._options.keys():
1512 comp = 'param'
1513 elif attr in self.cell._options.keys():
1514 comp = 'cell'
1515 else:
1516 raise RuntimeError(
1517 'Programming error: could not attach '
1518 'the keyword to an input file'
1519 )
1521 self.__dict__[comp].__setattr__(attr, value)
1523 def merge_param(self, param, overwrite=True, ignore_internal_keys=False):
1524 """Parse a param file and merge it into the current parameters."""
1525 if isinstance(param, CastepParam):
1526 for key, option in param._options.items():
1527 if option.value is not None:
1528 self.param.__setattr__(key, option.value)
1529 return
1531 elif isinstance(param, str):
1532 param_file = open(param)
1533 _close = True
1535 else:
1536 # in this case we assume that we have a fileobj already, but check
1537 # for attributes in order to avoid extended EAFP blocks.
1538 param_file = param
1540 # look before you leap...
1541 attributes = ['name', 'closereadlines']
1543 for attr in attributes:
1544 if not hasattr(param_file, attr):
1545 raise TypeError(
1546 '"param" is neither CastepParam nor str '
1547 'nor valid fileobj'
1548 )
1550 param = param_file.name
1551 _close = False
1553 self, int_opts = read_param(
1554 fd=param_file, calc=self, get_interface_options=True
1555 )
1557 # Add the interface options
1558 for k, val in int_opts.items():
1559 if k in self.internal_keys and not ignore_internal_keys:
1560 if val in _tf_table:
1561 val = _tf_table[val]
1562 self._opt[k] = val
1564 if _close:
1565 param_file.close()
1567 def dryrun_ok(self, dryrun_flag='-dryrun'):
1568 """Starts a CASTEP run with the -dryrun flag [default]
1569 in a temporary and check wether all variables are initialized
1570 correctly. This is recommended for every bigger simulation.
1571 """
1572 from ase.io.castep import write_param
1574 temp_dir = tempfile.mkdtemp()
1575 self._fetch_pspots(temp_dir)
1576 seed = 'dryrun'
1578 magnetic_moments = (
1579 'initial' if self.param.spin_polarized.value == 'TRUE' else None
1580 )
1581 self._write_cell(
1582 os.path.join(temp_dir, f'{seed}.cell'),
1583 self.atoms,
1584 castep_cell=self.cell,
1585 magnetic_moments=magnetic_moments,
1586 )
1587 # This part needs to be modified now that we rely on the new formats.py
1588 # interface
1589 if not os.path.isfile(os.path.join(temp_dir, f'{seed}.cell')):
1590 warnings.warn(f'{seed}.cell not written - aborting dryrun')
1591 return None
1592 write_param(
1593 os.path.join(temp_dir, f'{seed}.param'),
1594 self.param,
1595 )
1597 stdout, stderr = shell_stdouterr(
1598 ('{} {} {}'.format(self._castep_command, seed, dryrun_flag)),
1599 cwd=temp_dir,
1600 )
1602 if stdout:
1603 print(stdout)
1604 if stderr:
1605 print(stderr)
1606 with open(os.path.join(temp_dir, f'{seed}.castep')) as result_file:
1607 txt = result_file.read()
1608 ok_string = (
1609 r'.*DRYRUN finished.*No problems found with input '
1610 r'files.*'
1611 )
1612 match = re.match(ok_string, txt, re.DOTALL)
1614 m = re.search(r'Number of kpoints used =\s*([0-9]+)', txt)
1615 if m:
1616 self._kpoints = int(m.group(1))
1617 else:
1618 warnings.warn(
1619 "Couldn't fetch number of kpoints from dryrun CASTEP file"
1620 )
1622 err_file = os.path.join(temp_dir, f'{seed}.0001.err')
1623 if match is None and os.path.exists(err_file):
1624 with open(err_file) as err_file:
1625 self._error = err_file.read()
1626 shutil.rmtree(temp_dir)
1628 # re.match return None is the string does not match
1629 return match is not None
1631 def _fetch_pspots(self, directory=None):
1632 """Put all specified pseudo-potentials into the working directory."""
1633 # should be a '==' right? Otherwise setting _castep_pp_path is not
1634 # honored.
1635 if not cfg.get(
1636 'PSPOT_DIR', None
1637 ) and self._castep_pp_path == os.path.abspath('.'):
1638 # By default CASTEP consults the environment variable
1639 # PSPOT_DIR. If this contains a list of colon separated
1640 # directories it will check those directories for pseudo-
1641 # potential files if not in the current directory.
1642 # Thus if PSPOT_DIR is set there is nothing left to do.
1643 # If however PSPOT_DIR was been accidentally set
1644 # (e.g. with regards to a different program)
1645 # setting CASTEP_PP_PATH to an explicit value will
1646 # still be honored.
1647 return
1649 if directory is None:
1650 directory = self._directory
1651 if not os.path.isdir(self._castep_pp_path):
1652 warnings.warn(f'PSPs directory {self._castep_pp_path} not found')
1653 pspots = {}
1654 if self._find_pspots:
1655 self.find_pspots()
1656 if self.cell.species_pot.value is not None:
1657 for line in self.cell.species_pot.value.split('\n'):
1658 line = line.split()
1659 if line:
1660 pspots[line[0]] = line[1]
1661 for species in self.atoms.get_chemical_symbols():
1662 if not pspots or species not in pspots.keys():
1663 if self._build_missing_pspots:
1664 if self._pedantic:
1665 warnings.warn(
1666 'Warning: you have no PP specified for %s. '
1667 'CASTEP will now generate an on-the-fly '
1668 'potentials. '
1669 'For sake of numerical consistency and efficiency '
1670 'this is discouraged.' % species
1671 )
1672 else:
1673 raise RuntimeError(
1674 f'Warning: you have no PP specified for {species}.'
1675 )
1676 if self.cell.species_pot.value:
1677 for species, pspot in pspots.items():
1678 orig_pspot_file = os.path.join(self._castep_pp_path, pspot)
1679 cp_pspot_file = os.path.join(directory, pspot)
1680 if os.path.exists(orig_pspot_file) and not os.path.exists(
1681 cp_pspot_file
1682 ):
1683 if self._copy_pspots:
1684 shutil.copy(orig_pspot_file, directory)
1685 elif self._link_pspots:
1686 os.symlink(orig_pspot_file, cp_pspot_file)
1687 else:
1688 if self._pedantic:
1689 warnings.warn(ppwarning)
1692ppwarning = (
1693 'Warning: PP files have neither been '
1694 'linked nor copied to the working directory. Make '
1695 'sure to set the evironment variable PSPOT_DIR '
1696 'accordingly!'
1697)
1700def _get_indices_to_sort_back(symbols, species):
1701 """Get indices to sort spicies in .castep back to atoms.symbols."""
1702 uniques = np.unique(symbols)
1703 indices = np.full(len(symbols), -1, dtype=int)
1704 for unique in uniques:
1705 where_symbols = [i for i, s in enumerate(symbols) if s == unique]
1706 where_species = [j for j, s in enumerate(species) if s == unique]
1707 for i, j in zip(where_symbols, where_species):
1708 indices[i] = j
1709 if -1 in indices:
1710 not_assigned = [_ for _ in indices if _ == -1]
1711 raise RuntimeError(f'Atoms {not_assigned} where not assigned.')
1712 return indices
1715def get_castep_version(castep_command):
1716 """This returns the version number as printed in the CASTEP banner.
1717 For newer CASTEP versions ( > 6.1) the --version command line option
1718 has been added; this will be attempted first.
1719 """
1720 import tempfile
1722 with tempfile.TemporaryDirectory() as temp_dir:
1723 return _get_castep_version(castep_command, temp_dir)
1726def _get_castep_version(castep_command, temp_dir):
1727 jname = 'dummy_jobname'
1728 stdout, stderr = '', ''
1729 fallback_version = 16.0 # CASTEP 16.0 and 16.1 report version wrongly
1730 try:
1731 stdout, stderr = subprocess.Popen(
1732 castep_command.split() + ['--version'],
1733 stderr=subprocess.PIPE,
1734 stdout=subprocess.PIPE,
1735 cwd=temp_dir,
1736 universal_newlines=True,
1737 ).communicate()
1738 if 'CASTEP version' not in stdout:
1739 stdout, stderr = subprocess.Popen(
1740 castep_command.split() + [jname],
1741 stderr=subprocess.PIPE,
1742 stdout=subprocess.PIPE,
1743 cwd=temp_dir,
1744 universal_newlines=True,
1745 ).communicate()
1746 except Exception: # XXX Which kind of exception?
1747 msg = ''
1748 msg += 'Could not determine the version of your CASTEP binary \n'
1749 msg += 'This usually means one of the following \n'
1750 msg += ' * you do not have CASTEP installed \n'
1751 msg += ' * you have not set the CASTEP_COMMAND to call it \n'
1752 msg += ' * you have provided a wrong CASTEP_COMMAND. \n'
1753 msg += ' Make sure it is in your PATH\n\n'
1754 msg += stdout
1755 msg += stderr
1756 raise CastepVersionError(msg)
1757 if 'CASTEP version' in stdout:
1758 output_txt = stdout.split('\n')
1759 version_re = re.compile(r'CASTEP version:\s*([0-9\.]*)')
1760 else:
1761 with open(os.path.join(temp_dir, f'{jname}.castep')) as output:
1762 output_txt = output.readlines()
1763 version_re = re.compile(r'(?<=CASTEP version )[0-9.]*')
1764 # shutil.rmtree(temp_dir)
1765 for line in output_txt:
1766 if 'CASTEP version' in line:
1767 try:
1768 return float(version_re.findall(line)[0])
1769 except ValueError:
1770 # Fallback for buggy --version on CASTEP 16.0, 16.1
1771 return fallback_version
1774def create_castep_keywords(
1775 castep_command,
1776 filename='castep_keywords.json',
1777 force_write=True,
1778 path='.',
1779 fetch_only=None,
1780):
1781 """This function allows to fetch all available keywords from stdout
1782 of an installed castep binary. It furthermore collects the documentation
1783 to harness the power of (ipython) inspection and type for some basic
1784 type checking of input. All information is stored in a JSON file that is
1785 not distributed by default to avoid breaking the license of CASTEP.
1786 """
1787 # Takes a while ...
1788 # Fetch all allowed parameters
1789 # fetch_only : only fetch that many parameters (for testsuite only)
1790 suffixes = ['cell', 'param']
1792 filepath = os.path.join(path, filename)
1794 if os.path.exists(filepath) and not force_write:
1795 warnings.warn(
1796 'CASTEP Options Module file exists. '
1797 'You can overwrite it by calling '
1798 'python castep.py -f [CASTEP_COMMAND].'
1799 )
1800 return False
1802 # Not saving directly to file her to prevent half-generated files
1803 # which will cause problems on future runs
1805 castep_version = get_castep_version(castep_command)
1807 help_all, _ = shell_stdouterr(f'{castep_command} -help all')
1809 # Filter out proper keywords
1810 try:
1811 # The old pattern does not math properly as in CASTEP as of v8.0 there
1812 # are some keywords for the semi-empircal dispersion correction (SEDC)
1813 # which also include numbers.
1814 if castep_version < 7.0:
1815 pattern = r'((?<=^ )[A-Z_]{2,}|(?<=^)[A-Z_]{2,})'
1816 else:
1817 pattern = r'((?<=^ )[A-Z_\d]{2,}|(?<=^)[A-Z_\d]{2,})'
1819 raw_options = re.findall(pattern, help_all, re.MULTILINE)
1820 except Exception:
1821 warnings.warn(f'Problem parsing: {help_all}')
1822 raise
1824 types = set()
1825 levels = set()
1827 processed_n = 0
1828 to_process = len(raw_options[:fetch_only])
1830 processed_options = {sf: {} for sf in suffixes}
1832 for o_i, option in enumerate(raw_options[:fetch_only]):
1833 doc, _ = shell_stdouterr(f'{castep_command} -help {option}')
1835 # Stand Back! I know regular expressions (https://xkcd.com/208/) :-)
1836 match = re.match(
1837 r'(?P<before_type>.*)Type: (?P<type>.+?)\s+'
1838 + r'Level: (?P<level>[^ ]+)\n\s*\n'
1839 + r'(?P<doc>.*?)(\n\s*\n|$)',
1840 doc,
1841 re.DOTALL,
1842 )
1844 processed_n += 1
1846 if match is not None:
1847 match = match.groupdict()
1849 # JM: uncomment lines in following block to debug issues
1850 # with keyword assignment during extraction process from CASTEP
1851 suffix = None
1852 if re.findall(r'PARAMETERS keywords:\n\n\s?None found', doc):
1853 suffix = 'cell'
1854 if re.findall(r'CELL keywords:\n\n\s?None found', doc):
1855 suffix = 'param'
1856 if suffix is None:
1857 warnings.warn(
1858 '%s -> not assigned to either'
1859 ' CELL or PARAMETERS keywords' % option
1860 )
1862 option = option.lower()
1863 mtyp = match.get('type', None)
1864 mlvl = match.get('level', None)
1865 mdoc = match.get('doc', None)
1867 if mtyp is None:
1868 warnings.warn(f'Found no type for {option}')
1869 continue
1870 if mlvl is None:
1871 warnings.warn(f'Found no level for {option}')
1872 continue
1873 if mdoc is None:
1874 warnings.warn(f'Found no doc string for {option}')
1875 continue
1877 types = types.union([mtyp])
1878 levels = levels.union([mlvl])
1880 processed_options[suffix][option] = {
1881 'keyword': option,
1882 'option_type': mtyp,
1883 'level': mlvl,
1884 'docstring': mdoc,
1885 }
1887 processed_n += 1
1889 frac = (o_i + 1.0) / to_process
1890 sys.stdout.write(
1891 '\rProcessed: [{}] {:>3.0f}%'.format(
1892 '#' * int(frac * 20) + ' ' * (20 - int(frac * 20)),
1893 100 * frac,
1894 )
1895 )
1896 sys.stdout.flush()
1898 else:
1899 warnings.warn(f'create_castep_keywords: Could not process {option}')
1901 sys.stdout.write('\n')
1902 sys.stdout.flush()
1904 processed_options['types'] = list(types)
1905 processed_options['levels'] = list(levels)
1906 processed_options['castep_version'] = castep_version
1908 json.dump(processed_options, open(filepath, 'w'), indent=4)
1910 warnings.warn(f'CASTEP v{castep_version}, fetched {processed_n} keywords')
1911 return True
1914CastepKeywords = namedtuple(
1915 'CastepKeywords',
1916 ['CastepParamDict', 'CastepCellDict', 'types', 'levels', 'castep_version'],
1917)
1919# We keep this just for naming consistency with older versions
1922def make_cell_dict(data=None):
1923 from ase.io.castep.castep_input_file import CastepOptionDict
1925 data = data if data is not None else {}
1927 class CastepCellDict(CastepOptionDict):
1928 def __init__(self):
1929 CastepOptionDict.__init__(self, data)
1931 return CastepCellDict
1934def make_param_dict(data=None):
1935 from ase.io.castep.castep_input_file import CastepOptionDict
1937 data = data if data is not None else {}
1939 class CastepParamDict(CastepOptionDict):
1940 def __init__(self):
1941 CastepOptionDict.__init__(self, data)
1943 return CastepParamDict
1946class CastepVersionError(Exception):
1947 """No special behaviour, works to signal when Castep can not be found"""
1950def get_castep_pp_path(castep_pp_path=''):
1951 """Abstract the quest for a CASTEP PSP directory."""
1952 if castep_pp_path:
1953 return os.path.abspath(os.path.expanduser(castep_pp_path))
1954 elif 'PSPOT_DIR' in cfg:
1955 return cfg['PSPOT_DIR']
1956 elif 'CASTEP_PP_PATH' in cfg:
1957 return cfg['CASTEP_PP_PATH']
1958 else:
1959 return os.path.abspath('.')
1962def get_castep_command(castep_command=''):
1963 """Abstract the quest for a castep_command string."""
1964 if castep_command:
1965 return castep_command
1966 elif 'CASTEP_COMMAND' in cfg:
1967 return cfg['CASTEP_COMMAND']
1968 else:
1969 return 'castep'
1972def shell_stdouterr(raw_command, cwd=None):
1973 """Abstracts the standard call of the commandline, when
1974 we are only interested in the stdout and stderr
1975 """
1976 stdout, stderr = subprocess.Popen(
1977 raw_command,
1978 stdout=subprocess.PIPE,
1979 stderr=subprocess.PIPE,
1980 universal_newlines=True,
1981 shell=True,
1982 cwd=cwd,
1983 ).communicate()
1984 return stdout.strip(), stderr.strip()
1987def import_castep_keywords(
1988 castep_command='', filename='castep_keywords.json', path='.'
1989):
1990 """Search for castep keywords JSON in multiple paths"""
1992 config_paths = ('~/.ase', '~/.config/ase')
1993 searchpaths = [path] + [
1994 os.path.expanduser(config_path) for config_path in config_paths
1995 ]
1996 try:
1997 keywords_file = sum(
1998 (glob.glob(os.path.join(sp, filename)) for sp in searchpaths), []
1999 )[0]
2000 except IndexError:
2001 warnings.warn("""Generating CASTEP keywords JSON file... hang on.
2002 The CASTEP keywords JSON file contains abstractions for CASTEP input
2003 parameters (for both .cell and .param input files), including some
2004 format checks and descriptions. The latter are extracted from the
2005 internal online help facility of a CASTEP binary, thus allowing to
2006 easily keep the calculator synchronized with (different versions of)
2007 the CASTEP code. Consequently, avoiding licensing issues (CASTEP is
2008 distributed commercially by Biovia), we consider it wise not to
2009 provide the file in the first place.""")
2010 create_castep_keywords(
2011 get_castep_command(castep_command), filename=filename, path=path
2012 )
2013 keywords_file = Path(path).absolute() / filename
2015 warnings.warn(
2016 f'Stored castep keywords dictionary as {keywords_file}. '
2017 f'Copy it to {Path(config_paths[0]).expanduser() / filename} for '
2018 r'user installation.'
2019 )
2021 # Now create the castep_keywords object proper
2022 with open(keywords_file) as fd:
2023 kwdata = json.load(fd)
2025 # This is a bit awkward, but it's necessary for backwards compatibility
2026 param_dict = make_param_dict(kwdata['param'])
2027 cell_dict = make_cell_dict(kwdata['cell'])
2029 castep_keywords = CastepKeywords(
2030 param_dict,
2031 cell_dict,
2032 kwdata['types'],
2033 kwdata['levels'],
2034 kwdata['castep_version'],
2035 )
2037 return castep_keywords
2040if __name__ == '__main__':
2041 warnings.warn(
2042 'When called directly this calculator will fetch all available '
2043 'keywords from the binarys help function into a '
2044 'castep_keywords.json in the current directory %s '
2045 'For system wide usage, it can be copied into an ase installation '
2046 'at ASE/calculators. '
2047 'This castep_keywords.json usually only needs to be generated once '
2048 'for a CASTEP binary/CASTEP version.' % os.getcwd()
2049 )
2051 import optparse
2053 parser = optparse.OptionParser()
2054 parser.add_option(
2055 '-f',
2056 '--force-write',
2057 dest='force_write',
2058 help='Force overwriting existing castep_keywords.json',
2059 default=False,
2060 action='store_true',
2061 )
2062 (options, args) = parser.parse_args()
2064 if args:
2065 opt_castep_command = ''.join(args)
2066 else:
2067 opt_castep_command = ''
2068 generated = create_castep_keywords(
2069 get_castep_command(opt_castep_command), force_write=options.force_write
2070 )
2072 if generated:
2073 try:
2074 with open('castep_keywords.json') as fd:
2075 json.load(fd)
2076 except Exception as e:
2077 warnings.warn(
2078 f'{e} Ooops, something went wrong with the CASTEP keywords'
2079 )
2080 else:
2081 warnings.warn('Import works. Looking good!')