File: siesta.py

package info (click to toggle)
python-ase 3.26.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 15,484 kB
  • sloc: python: 148,112; xml: 2,728; makefile: 110; javascript: 47
file content (811 lines) | stat: -rw-r--r-- 27,855 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
# fmt: off

"""
This module defines the ASE interface to SIESTA.

Written by Mads Engelund (see www.espeem.com)

Home of the SIESTA package:
http://www.uam.es/departamentos/ciencias/fismateriac/siesta

2017.04 - Pedro Brandimarte: changes for python 2-3 compatible

"""

import os
import re
import shutil
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List

import numpy as np

from ase import Atoms
from ase.calculators.calculator import FileIOCalculator, Parameters, ReadError
from ase.calculators.siesta.import_ion_xml import get_ion
from ase.calculators.siesta.parameters import PAOBasisBlock, format_fdf
from ase.data import atomic_numbers
from ase.io.siesta import read_siesta_xv
from ase.io.siesta_input import SiestaInput
from ase.units import Ry, eV
from ase.utils import deprecated

meV = 0.001 * eV


def parse_siesta_version(output: bytes) -> str:
    match = re.search(rb'Version\s*:\s*(\S+)', output)

    if match is None:
        raise RuntimeError('Could not get Siesta version info from output '
                           '{!r}'.format(output))

    string = match.group(1).decode('ascii')
    return string


def get_siesta_version(executable: str) -> str:
    """ Return SIESTA version number.

    Run the command, for instance 'siesta' and
    then parse the output in order find the
    version number.
    """
    # XXX We need a test of this kind of function.  But Siesta().command
    # is not enough to tell us how to run Siesta, because it could contain
    # all sorts of mpirun and other weird parts.

    temp_dirname = tempfile.mkdtemp(prefix='siesta-version-check-')
    try:
        from subprocess import PIPE, Popen
        proc = Popen([executable],
                     stdin=PIPE,
                     stdout=PIPE,
                     stderr=PIPE,
                     cwd=temp_dirname)
        output, _ = proc.communicate()
        # We are not providing any input, so Siesta will give us a failure
        # saying that it has no Chemical_species_label and exit status 1
        # (as of siesta-4.1-b4)
    finally:
        shutil.rmtree(temp_dirname)

    return parse_siesta_version(output)


def format_block(name, block):
    lines = [f'%block {name}']
    for row in block:
        data = ' '.join(str(obj) for obj in row)
        lines.append(f'    {data}')
    lines.append(f'%endblock {name}')
    return '\n'.join(lines)


def bandpath2bandpoints(path):
    return '\n'.join([
        'BandLinesScale ReciprocalLatticeVectors',
        format_block('BandPoints', path.kpts)])


class SiestaParameters(Parameters):
    def __init__(
            self,
            label='siesta',
            mesh_cutoff=200 * Ry,
            energy_shift=100 * meV,
            kpts=None,
            xc='LDA',
            basis_set='DZP',
            spin='non-polarized',
            species=(),
            pseudo_qualifier=None,
            pseudo_path=None,
            symlink_pseudos=None,
            atoms=None,
            restart=None,
            fdf_arguments=None,
            atomic_coord_format='xyz',
            bandpath=None):
        kwargs = locals()
        kwargs.pop('self')
        Parameters.__init__(self, **kwargs)


def _nonpolarized_alias(_: List, kwargs: Dict[str, Any]) -> bool:
    if kwargs.get("spin", None) == "UNPOLARIZED":
        kwargs["spin"] = "non-polarized"
        return True
    return False


class Siesta(FileIOCalculator):
    """Calculator interface to the SIESTA code.
    """
    allowed_xc = {
        'LDA': ['PZ', 'CA', 'PW92'],
        'GGA': ['PW91', 'PBE', 'revPBE', 'RPBE',
                'WC', 'AM05', 'PBEsol', 'PBEJsJrLO',
                'PBEGcGxLO', 'PBEGcGxHEG', 'BLYP'],
        'VDW': ['DRSLL', 'LMKLL', 'KBM', 'C09', 'BH', 'VV']}

    name = 'siesta'
    _legacy_default_command = 'siesta < PREFIX.fdf > PREFIX.out'
    implemented_properties = [
        'energy',
        'free_energy',
        'forces',
        'stress',
        'dipole',
        'eigenvalues',
        'density',
        'fermi_energy']

    # Dictionary of valid input vaiables.
    default_parameters = SiestaParameters()

    # XXX Not a ASE standard mechanism (yet).  We need to communicate to
    # ase.spectrum.band_structure.calculate_band_structure() that we expect
    # it to use the bandpath keyword.
    accepts_bandpath_keyword = True

    fileio_rules = FileIOCalculator.ruleset(
        configspec=dict(pseudo_path=None),
        stdin_name='{prefix}.fdf',
        stdout_name='{prefix}.out')

    def __init__(self, command=None, profile=None, directory='.', **kwargs):
        """ASE interface to the SIESTA code.

        Parameters:
           - label        : The basename of all files created during
                            calculation.
           - mesh_cutoff  : Energy in eV.
                            The mesh cutoff energy for determining number of
                            grid points in the matrix-element calculation.
           - energy_shift : Energy in eV
                            The confining energy of the basis set generation.
           - kpts         : Tuple of 3 integers, the k-points in different
                            directions.
           - xc           : The exchange-correlation potential. Can be set to
                            any allowed value for either the Siesta
                            XC.funtional or XC.authors keyword. Default "LDA"
           - basis_set    : "SZ"|"SZP"|"DZ"|"DZP"|"TZP", strings which specify
                            the type of functions basis set.
           - spin         : "non-polarized"|"collinear"|
                            "non-collinear|spin-orbit".
                            The level of spin description to be used.
           - species      : None|list of Species objects. The species objects
                            can be used to to specify the basis set,
                            pseudopotential and whether the species is ghost.
                            The tag on the atoms object and the element is used
                            together to identify the species.
           - pseudo_path  : None|path. This path is where
                            pseudopotentials are taken from.
                            If None is given, then then the path given
                            in $SIESTA_PP_PATH will be used.
           - pseudo_qualifier: None|string. This string will be added to the
                            pseudopotential path that will be retrieved.
                            For hydrogen with qualifier "abc" the
                            pseudopotential "H.abc.psf" will be retrieved.
           - symlink_pseudos: None|bool
                            If true, symlink pseudopotentials
                            into the calculation directory, else copy them.
                            Defaults to true on Unix and false on Windows.
           - atoms        : The Atoms object.
           - restart      : str.  Prefix for restart file.
                            May contain a directory.
                            Default is  None, don't restart.
           - fdf_arguments: Explicitly given fdf arguments. Dictonary using
                            Siesta keywords as given in the manual. List values
                            are written as fdf blocks with each element on a
                            separate line, while tuples will write each element
                            in a single line.  ASE units are assumed in the
                            input.
           - atomic_coord_format: "xyz"|"zmatrix", strings to switch between
                            the default way of entering the system's geometry
                            (via the block AtomicCoordinatesAndAtomicSpecies)
                            and a recent method via the block Zmatrix. The
                            block Zmatrix allows to specify basic geometry
                            constrains such as realized through the ASE classes
                            FixAtom, FixedLine and FixedPlane.
        """

        # Put in the default arguments.
        parameters = self.default_parameters.__class__(**kwargs)

        # Call the base class.
        FileIOCalculator.__init__(
            self,
            command=command,
            profile=profile,
            directory=directory,
            **parameters)

    def __getitem__(self, key):
        """Convenience method to retrieve a parameter as
        calculator[key] rather than calculator.parameters[key]

            Parameters:
                -key       : str, the name of the parameters to get.
        """
        return self.parameters[key]

    def species(self, atoms):
        """Find all relevant species depending on the atoms object and
        species input.

            Parameters :
                - atoms : An Atoms object.
        """
        return SiestaInput.get_species(
            atoms, list(self['species']), self['basis_set'])

    @deprecated(
        "The keyword 'UNPOLARIZED' has been deprecated,"
        "and replaced by 'non-polarized'",
        category=FutureWarning,
        callback=_nonpolarized_alias,
    )
    def set(self, **kwargs):
        """Set all parameters.

            Parameters:
                -kwargs  : Dictionary containing the keywords defined in
                           SiestaParameters.

        .. deprecated:: 3.18.2
            The keyword 'UNPOLARIZED' has been deprecated and replaced by
            'non-polarized'
        """

        # XXX Inserted these next few lines because set() would otherwise
        # discard all previously set keywords to their defaults!  --askhl
        current = self.parameters.copy()
        current.update(kwargs)
        kwargs = current

        # Find not allowed keys.
        default_keys = list(self.__class__.default_parameters)
        offending_keys = set(kwargs) - set(default_keys)
        if len(offending_keys) > 0:
            mess = "'set' does not take the keywords: %s "
            raise ValueError(mess % list(offending_keys))

        # Use the default parameters.
        parameters = self.__class__.default_parameters.copy()
        parameters.update(kwargs)
        kwargs = parameters

        # Check energy inputs.
        for arg in ['mesh_cutoff', 'energy_shift']:
            value = kwargs.get(arg)
            if value is None:
                continue
            if not (isinstance(value, (float, int)) and value > 0):
                mess = "'{}' must be a positive number(in eV), \
                    got '{}'".format(arg, value)
                raise ValueError(mess)

        # Check the functional input.
        xc = kwargs.get('xc', 'LDA')
        if isinstance(xc, (tuple, list)) and len(xc) == 2:
            functional, authors = xc
            if functional.lower() not in [k.lower() for k in self.allowed_xc]:
                mess = f"Unrecognized functional keyword: '{functional}'"
                raise ValueError(mess)

            lsauthorslower = [a.lower() for a in self.allowed_xc[functional]]
            if authors.lower() not in lsauthorslower:
                mess = "Unrecognized authors keyword for %s: '%s'"
                raise ValueError(mess % (functional, authors))

        elif xc in self.allowed_xc:
            functional = xc
            authors = self.allowed_xc[xc][0]
        else:
            found = False
            for key, value in self.allowed_xc.items():
                if xc in value:
                    found = True
                    functional = key
                    authors = xc
                    break

            if not found:
                raise ValueError(f"Unrecognized 'xc' keyword: '{xc}'")
        kwargs['xc'] = (functional, authors)

        # Check fdf_arguments.
        if kwargs['fdf_arguments'] is None:
            kwargs['fdf_arguments'] = {}

        if not isinstance(kwargs['fdf_arguments'], dict):
            raise TypeError("fdf_arguments must be a dictionary.")

        # Call baseclass.
        FileIOCalculator.set(self, **kwargs)

    def set_fdf_arguments(self, fdf_arguments):
        """ Set the fdf_arguments after the initialization of the
            calculator.
        """
        self.validate_fdf_arguments(fdf_arguments)
        FileIOCalculator.set(self, fdf_arguments=fdf_arguments)

    def validate_fdf_arguments(self, fdf_arguments):
        """ Raises error if the fdf_argument input is not a
            dictionary of allowed keys.
        """
        # None is valid
        if fdf_arguments is None:
            return

        # Type checking.
        if not isinstance(fdf_arguments, dict):
            raise TypeError("fdf_arguments must be a dictionary.")

    def write_input(self, atoms, properties=None, system_changes=None):
        """Write input (fdf)-file.
        See calculator.py for further details.

        Parameters:
            - atoms        : The Atoms object to write.
            - properties   : The properties which should be calculated.
            - system_changes : List of properties changed since last run.
        """

        super().write_input(
            atoms=atoms,
            properties=properties,
            system_changes=system_changes)

        filename = self.getpath(ext='fdf')

        more_fdf_args = {}

        # Use the saved density matrix if only 'cell' and 'positions'
        # have changed.
        if (system_changes is None or
            ('numbers' not in system_changes and
             'initial_magmoms' not in system_changes and
             'initial_charges' not in system_changes)):

            more_fdf_args['DM.UseSaveDM'] = True

        if 'density' in properties:
            more_fdf_args['SaveRho'] = True

        species, species_numbers = self.species(atoms)

        pseudo_path = (self['pseudo_path']
                       or self.profile.configvars.get('pseudo_path')
                       or self.cfg.get('SIESTA_PP_PATH'))

        if not pseudo_path:
            raise Exception(
                'Please configure pseudo_path or SIESTA_PP_PATH envvar')

        species_info = SpeciesInfo(
            atoms=atoms,
            pseudo_path=Path(pseudo_path),
            pseudo_qualifier=self.pseudo_qualifier(),
            species=species)

        writer = FDFWriter(
            name=self.prefix,
            xc=self['xc'],
            spin=self['spin'],
            mesh_cutoff=self['mesh_cutoff'],
            energy_shift=self['energy_shift'],
            fdf_user_args=self['fdf_arguments'],
            more_fdf_args=more_fdf_args,
            species_numbers=species_numbers,
            atomic_coord_format=self['atomic_coord_format'].lower(),
            kpts=self['kpts'],
            bandpath=self['bandpath'],
            species_info=species_info,
        )

        with open(filename, 'w') as fd:
            writer.write(fd)

        writer.link_pseudos_into_directory(
            symlink_pseudos=self['symlink_pseudos'],
            directory=Path(self.directory))

    def read(self, filename):
        """Read structural parameters from file .XV file
           Read other results from other files
           filename : siesta.XV
        """

        fname = self.getpath(filename)
        if not fname.exists():
            raise ReadError(f"The restart file '{fname}' does not exist")
        with fname.open() as fd:
            self.atoms = read_siesta_xv(fd)
        self.read_results()

    def getpath(self, fname=None, ext=None):
        """ Returns the directory/fname string """
        if fname is None:
            fname = self.prefix
        if ext is not None:
            fname = f'{fname}.{ext}'
        return Path(self.directory) / fname

    def pseudo_qualifier(self):
        """Get the extra string used in the middle of the pseudopotential.
        The retrieved pseudopotential for a specific element will be
        'H.xxx.psf' for the element 'H' with qualifier 'xxx'. If qualifier
        is set to None then the qualifier is set to functional name.
        """
        if self['pseudo_qualifier'] is None:
            return self['xc'][0].lower()
        else:
            return self['pseudo_qualifier']

    def read_results(self):
        """Read the results."""
        from ase.io.siesta_output import OutputReader
        reader = OutputReader(prefix=self.prefix,
                              directory=Path(self.directory),
                              bandpath=self['bandpath'])
        results = reader.read_results()
        self.results.update(results)

        self.results['ion'] = self.read_ion(self.atoms)

    def read_ion(self, atoms):
        """
        Read the ion.xml file of each specie
        """
        species, _species_numbers = self.species(atoms)

        ion_results = {}
        for species_number, spec in enumerate(species, start=1):
            symbol = spec['symbol']
            atomic_number = atomic_numbers[symbol]

            if spec['pseudopotential'] is None:
                if self.pseudo_qualifier() == '':
                    label = symbol
                else:
                    label = f"{symbol}.{self.pseudo_qualifier()}"
                pseudopotential = self.getpath(label, 'psf')
            else:
                pseudopotential = Path(spec['pseudopotential'])
                label = pseudopotential.stem

            name = f"{label}.{species_number}"
            if spec['ghost']:
                name = f"{name}.ghost"
                atomic_number = -atomic_number

            if name not in ion_results:
                fname = self.getpath(name, 'ion.xml')
                if fname.is_file():
                    ion_results[name] = get_ion(str(fname))

        return ion_results

    def band_structure(self):
        return self.results['bandstructure']

    def get_fermi_level(self):
        return self.results['fermi_energy']

    def get_k_point_weights(self):
        return self.results['kpoint_weights']

    def get_ibz_k_points(self):
        return self.results['kpoints']

    def get_eigenvalues(self, kpt=0, spin=0):
        return self.results['eigenvalues'][spin, kpt]

    def get_number_of_spins(self):
        return self.results['eigenvalues'].shape[0]


def generate_atomic_coordinates(atoms: Atoms, species_numbers,
                                atomic_coord_format: str):
    """Write atomic coordinates.

    Parameters
    ----------
    fd : IO
        An open file object.
    atoms : Atoms
        An atoms object.
    """
    if atomic_coord_format == 'xyz':
        return generate_atomic_coordinates_xyz(atoms, species_numbers)
    elif atomic_coord_format == 'zmatrix':
        return generate_atomic_coordinates_zmatrix(atoms, species_numbers)
    else:
        raise RuntimeError(
            f'Unknown atomic_coord_format: {atomic_coord_format}')


def generate_atomic_coordinates_zmatrix(atoms: Atoms, species_numbers):
    """Write atomic coordinates in Z-matrix format.

    Parameters
    ----------
    fd : IO
        An open file object.
    atoms : Atoms
        An atoms object.
    """
    yield '\n'
    yield var('ZM.UnitsLength', 'Ang')
    yield '%block Zmatrix\n'
    yield '  cartesian\n'

    fstr = "{:5d}" + "{:20.10f}" * 3 + "{:3d}" * 3 + "{:7d} {:s}\n"
    a2constr = SiestaInput.make_xyz_constraints(atoms)
    a2p, a2s = atoms.get_positions(), atoms.symbols
    for ia, (sp, xyz, ccc, sym) in enumerate(
            zip(species_numbers, a2p, a2constr, a2s)):
        yield fstr.format(
            sp, xyz[0], xyz[1], xyz[2], ccc[0],
            ccc[1], ccc[2], ia + 1, sym)
    yield '%endblock Zmatrix\n'

    # origin = tuple(-atoms.get_celldisp().flatten())
    # yield block('AtomicCoordinatesOrigin', [origin])


def generate_atomic_coordinates_xyz(atoms: Atoms, species_numbers):
    """Write atomic coordinates.

    Parameters
    ----------
    fd : IO
        An open file object.
    atoms : Atoms
        An atoms object.
    """
    yield '\n'
    yield var('AtomicCoordinatesFormat', 'Ang')
    yield block('AtomicCoordinatesAndAtomicSpecies',
                [[*atom.position, number]
                 for atom, number in zip(atoms, species_numbers)])
    yield '\n'

    # origin = tuple(-atoms.get_celldisp().flatten())
    # yield block('AtomicCoordinatesOrigin', [origin])


@dataclass
class SpeciesInfo:
    atoms: Atoms
    pseudo_path: Path
    pseudo_qualifier: str
    species: dict  # actually a kind of Parameters object, should refactor

    def __post_init__(self):
        pao_basis = []
        chemical_labels = []
        basis_sizes = []
        file_instructions = []

        for species_number, spec in enumerate(self.species, start=1):
            symbol = spec['symbol']
            atomic_number = atomic_numbers[symbol]

            if spec['pseudopotential'] is None:
                if self.pseudo_qualifier == '':
                    label = symbol
                else:
                    label = f"{symbol}.{self.pseudo_qualifier}"
                src_path = self.pseudo_path / f"{label}.psf"
            else:
                src_path = Path(spec['pseudopotential'])

            if not src_path.is_absolute():
                src_path = self.pseudo_path / src_path
            if not src_path.exists():
                src_path = self.pseudo_path / f"{symbol}.psml"

            name = src_path.name
            name = name.split('.')
            name.insert(-1, str(species_number))
            if spec['ghost']:
                name.insert(-1, 'ghost')
                atomic_number = -atomic_number

            name = '.'.join(name)

            instr = FileInstruction(src_path, name)
            file_instructions.append(instr)

            label = '.'.join(np.array(name.split('.'))[:-1])
            pseudo_name = ''
            if src_path.suffix != '.psf':
                pseudo_name = f'{label}{src_path.suffix}'
            string = '    %d %d %s %s' % (species_number, atomic_number, label,
                                          pseudo_name)
            chemical_labels.append(string)
            if isinstance(spec['basis_set'], PAOBasisBlock):
                pao_basis.append(spec['basis_set'].script(label))
            else:
                basis_sizes.append(("    " + label, spec['basis_set']))

        self.file_instructions = file_instructions
        self.chemical_labels = chemical_labels
        self.pao_basis = pao_basis
        self.basis_sizes = basis_sizes

    def generate_text(self):
        yield var('NumberOfSpecies', len(self.species))
        yield var('NumberOfAtoms', len(self.atoms))

        yield var('ChemicalSpecieslabel', self.chemical_labels)
        yield '\n'
        yield var('PAO.Basis', self.pao_basis)
        yield var('PAO.BasisSizes', self.basis_sizes)
        yield '\n'


@dataclass
class FileInstruction:
    src_path: Path
    targetname: str

    def copy_to(self, directory):
        self._link(shutil.copy, directory)

    def symlink_to(self, directory):
        self._link(os.symlink, directory)

    def _link(self, file_operation, directory):
        dst_path = directory / self.targetname
        if self.src_path == dst_path:
            return

        dst_path.unlink(missing_ok=True)
        file_operation(self.src_path, dst_path)


@dataclass
class FDFWriter:
    name: str
    xc: str
    fdf_user_args: dict
    more_fdf_args: dict
    mesh_cutoff: float
    energy_shift: float
    spin: str
    species_numbers: object  # ?
    atomic_coord_format: str
    kpts: object  # ?
    bandpath: object  # ?
    species_info: object

    def write(self, fd):
        for chunk in self.generate_text():
            fd.write(chunk)

    def generate_text(self):
        yield var('SystemName', self.name)
        yield var('SystemLabel', self.name)
        yield "\n"

        # Write explicitly given options first to
        # allow the user to override anything.
        fdf_arguments = self.fdf_user_args
        for key in sorted(fdf_arguments):
            yield var(key, fdf_arguments[key])

        # Force siesta to return error on no convergence.
        # as default consistent with ASE expectations.
        if 'SCFMustConverge' not in fdf_arguments:
            yield var('SCFMustConverge', True)
        yield '\n'

        yield var('Spin', self.spin)
        # Spin backwards compatibility.
        if self.spin == 'collinear':
            key = 'SpinPolarized'
        elif self.spin == 'non-collinear':
            key = 'NonCollinearSpin'
        else:
            key = None

        if key is not None:
            yield var(key, (True, '# Backwards compatibility.'))

        # Write functional.
        functional, authors = self.xc
        yield var('XC.functional', functional)
        yield var('XC.authors', authors)
        yield '\n'

        # Write mesh cutoff and energy shift.
        yield var('MeshCutoff', (self.mesh_cutoff, 'eV'))
        yield var('PAO.EnergyShift', (self.energy_shift, 'eV'))
        yield '\n'

        yield from self.species_info.generate_text()
        yield from self.generate_atoms_text(self.species_info.atoms)

        for key, value in self.more_fdf_args.items():
            yield var(key, value)

        if self.kpts is not None:
            kpts = np.array(self.kpts)
            yield from SiestaInput.generate_kpts(kpts)

        if self.bandpath is not None:
            lines = bandpath2bandpoints(self.bandpath)
            assert isinstance(lines, str)  # rename this variable?
            yield lines
            yield '\n'

    def generate_atoms_text(self, atoms: Atoms):
        """Translate the Atoms object to fdf-format."""

        cell = atoms.cell
        yield '\n'

        if cell.rank in [1, 2]:
            raise ValueError('Expected 3D unit cell or no unit cell.  You may '
                             'wish to add vacuum along some directions.')

        if np.any(cell):
            yield var('LatticeConstant', '1.0 Ang')
            yield block('LatticeVectors', cell)

        yield from generate_atomic_coordinates(
            atoms, self.species_numbers, self.atomic_coord_format)

        # Write magnetic moments.
        magmoms = atoms.get_initial_magnetic_moments()

        # The DM.InitSpin block must be written to initialize to
        # no spin. SIESTA default is FM initialization, if the
        # block is not written, but  we must conform to the
        # atoms object.
        if len(magmoms) == 0:
            yield '#Empty block forces ASE initialization.\n'

        yield '%block DM.InitSpin\n'
        if len(magmoms) != 0 and isinstance(magmoms[0], np.ndarray):
            for n, M in enumerate(magmoms):
                if M[0] != 0:
                    yield ('    %d %.14f %.14f %.14f \n'
                           % (n + 1, M[0], M[1], M[2]))
        elif len(magmoms) != 0 and isinstance(magmoms[0], float):
            for n, M in enumerate(magmoms):
                if M != 0:
                    yield '    %d %.14f \n' % (n + 1, M)
        yield '%endblock DM.InitSpin\n'
        yield '\n'

    def link_pseudos_into_directory(self, *, symlink_pseudos=None, directory):
        if symlink_pseudos is None:
            symlink_pseudos = os.name != 'nt'

        for instruction in self.species_info.file_instructions:
            if symlink_pseudos:
                instruction.symlink_to(directory)
            else:
                instruction.copy_to(directory)


# Utilities for generating bits of strings.
#
# We are re-aliasing format_fdf and format_block in the anticipation
# that they may change, or we might move this onto a Formatter object
# which applies consistent spacings etc.
def var(key, value):
    return format_fdf(key, value)


def block(name, data):
    return format_block(name, data)