Coverage for ase/calculators/siesta/siesta.py: 76.74%

374 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1""" 

2This module defines the ASE interface to SIESTA. 

3 

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

5 

6Home of the SIESTA package: 

7https://siesta-project.org/ 

8 

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

10 

11""" 

12 

13import os 

14import re 

15import shutil 

16import tempfile 

17from dataclasses import dataclass 

18from pathlib import Path 

19from typing import Any 

20 

21import numpy as np 

22 

23from ase import Atoms 

24from ase.calculators.calculator import FileIOCalculator, Parameters, ReadError 

25from ase.calculators.siesta.import_ion_xml import get_ion 

26from ase.calculators.siesta.parameters import PAOBasisBlock, format_fdf 

27from ase.data import atomic_numbers 

28from ase.io.siesta import read_siesta_xv 

29from ase.io.siesta_input import SiestaInput 

30from ase.units import Ry, eV 

31from ase.utils import deprecated 

32 

33meV = 0.001 * eV 

34 

35 

36def parse_siesta_version(output: bytes) -> str: 

37 match = re.search(rb'Version\s*:\s*(\S+)', output) 

38 

39 if match is None: 

40 raise RuntimeError( 

41 'Could not get Siesta version info from output {!r}'.format(output) 

42 ) 

43 

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

45 return string 

46 

47 

48def get_siesta_version(executable: str) -> str: 

49 """Return SIESTA version number. 

50 

51 Run the command, for instance 'siesta' and 

52 then parse the output in order find the 

53 version number. 

54 """ 

55 # XXX We need a test of this kind of function. But Siesta().command 

56 # is not enough to tell us how to run Siesta, because it could contain 

57 # all sorts of mpirun and other weird parts. 

58 

59 temp_dirname = tempfile.mkdtemp(prefix='siesta-version-check-') 

60 try: 

61 from subprocess import PIPE, Popen 

62 

63 proc = Popen( 

64 [executable], stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=temp_dirname 

65 ) 

66 output, _ = proc.communicate() 

67 # We are not providing any input, so Siesta will give us a failure 

68 # saying that it has no Chemical_species_label and exit status 1 

69 # (as of siesta-4.1-b4) 

70 finally: 

71 shutil.rmtree(temp_dirname) 

72 

73 return parse_siesta_version(output) 

74 

75 

76def format_block(name, block): 

77 lines = [f'%block {name}'] 

78 for row in block: 

79 data = ' '.join(str(obj) for obj in row) 

80 lines.append(f' {data}') 

81 lines.append(f'%endblock {name}') 

82 return '\n'.join(lines) 

83 

84 

85def bandpath2bandpoints(path): 

86 return '\n'.join( 

87 [ 

88 'BandLinesScale ReciprocalLatticeVectors', 

89 format_block('BandPoints', path.kpts), 

90 ] 

91 ) 

92 

93 

94class SiestaParameters(Parameters): 

95 def __init__( 

96 self, 

97 label='siesta', 

98 mesh_cutoff=200 * Ry, 

99 energy_shift=100 * meV, 

100 kpts=None, 

101 xc='LDA', 

102 basis_set='DZP', 

103 spin='non-polarized', 

104 species=(), 

105 pseudo_qualifier=None, 

106 pseudo_path=None, 

107 symlink_pseudos=None, 

108 atoms=None, 

109 restart=None, 

110 fdf_arguments=None, 

111 atomic_coord_format='xyz', 

112 bandpath=None, 

113 ): 

114 kwargs = locals() 

115 kwargs.pop('self') 

116 Parameters.__init__(self, **kwargs) 

117 

118 

119def _nonpolarized_alias(_: list, kwargs: dict[str, Any]) -> bool: 

120 if kwargs.get('spin', None) == 'UNPOLARIZED': 

121 kwargs['spin'] = 'non-polarized' 

122 return True 

123 return False 

124 

125 

126class Siesta(FileIOCalculator): 

127 """Calculator interface to the SIESTA code.""" 

128 

129 allowed_xc = { 

130 'LDA': ['PZ', 'CA', 'PW92'], 

131 'GGA': [ 

132 'PW91', 

133 'PBE', 

134 'revPBE', 

135 'RPBE', 

136 'WC', 

137 'AM05', 

138 'PBEsol', 

139 'PBEJsJrLO', 

140 'PBEGcGxLO', 

141 'PBEGcGxHEG', 

142 'BLYP', 

143 ], 

144 'VDW': ['DRSLL', 'LMKLL', 'KBM', 'C09', 'BH', 'VV'], 

145 } 

146 

147 name = 'siesta' 

148 _legacy_default_command = 'siesta < PREFIX.fdf > PREFIX.out' 

149 implemented_properties = [ 

150 'energy', 

151 'free_energy', 

152 'forces', 

153 'stress', 

154 'dipole', 

155 'eigenvalues', 

156 'density', 

157 'fermi_energy', 

158 ] 

159 

160 # Dictionary of valid input vaiables. 

161 default_parameters = SiestaParameters() 

162 

163 # XXX Not a ASE standard mechanism (yet). We need to communicate to 

164 # ase.spectrum.band_structure.calculate_band_structure() that we expect 

165 # it to use the bandpath keyword. 

166 accepts_bandpath_keyword = True 

167 

168 fileio_rules = FileIOCalculator.ruleset( 

169 configspec=dict(pseudo_path=None), 

170 stdin_name='{prefix}.fdf', 

171 stdout_name='{prefix}.out', 

172 ) 

173 

174 def __init__(self, command=None, profile=None, directory='.', **kwargs): 

175 """ASE interface to the SIESTA code. 

176 

177 Parameters 

178 ---------- 

179 - label : The basename of all files created during 

180 calculation. 

181 - mesh_cutoff : Energy in eV. 

182 The mesh cutoff energy for determining number of 

183 grid points in the matrix-element calculation. 

184 - energy_shift : Energy in eV 

185 The confining energy of the basis set generation. 

186 - kpts : Tuple of 3 integers, the k-points in different 

187 directions. 

188 - xc : The exchange-correlation potential. Can be set to 

189 any allowed value for either the Siesta 

190 XC.funtional or XC.authors keyword. Default "LDA" 

191 - basis_set : "SZ"|"SZP"|"DZ"|"DZP"|"TZP", strings which specify 

192 the type of functions basis set. 

193 - spin : "non-polarized"|"collinear"| 

194 "non-collinear|spin-orbit". 

195 The level of spin description to be used. 

196 - species : None|list of Species objects. The species objects 

197 can be used to to specify the basis set, 

198 pseudopotential and whether the species is ghost. 

199 The tag on the atoms object and the element is used 

200 together to identify the species. 

201 - pseudo_path : None|path. This path is where 

202 pseudopotentials are taken from. 

203 If None is given, then then the path given 

204 in $SIESTA_PP_PATH will be used. 

205 - pseudo_qualifier: None|string. This string will be added to the 

206 pseudopotential path that will be retrieved. 

207 For hydrogen with qualifier "abc" the 

208 pseudopotential "H.abc.psf" will be retrieved. 

209 - symlink_pseudos: None|bool 

210 If true, symlink pseudopotentials 

211 into the calculation directory, else copy them. 

212 Defaults to true on Unix and false on Windows. 

213 - atoms : The Atoms object. 

214 - restart : str. Prefix for restart file. 

215 May contain a directory. 

216 Default is None, don't restart. 

217 - fdf_arguments: Explicitly given fdf arguments. Dictonary using 

218 Siesta keywords as given in the manual. List values 

219 are written as fdf blocks with each element on a 

220 separate line, while tuples will write each element 

221 in a single line. ASE units are assumed in the 

222 input. 

223 - atomic_coord_format: "xyz"|"zmatrix", strings to switch between 

224 the default way of entering the system's geometry 

225 (via the block AtomicCoordinatesAndAtomicSpecies) 

226 and a recent method via the block Zmatrix. The 

227 block Zmatrix allows to specify basic geometry 

228 constrains such as realized through the ASE classes 

229 FixAtom, FixedLine and FixedPlane. 

230 """ 

231 

232 # Put in the default arguments. 

233 parameters = self.default_parameters.__class__(**kwargs) 

234 

235 # Call the base class. 

236 FileIOCalculator.__init__( 

237 self, 

238 command=command, 

239 profile=profile, 

240 directory=directory, 

241 **parameters, 

242 ) 

243 

244 def __getitem__(self, key): 

245 """Convenience method to retrieve a parameter as 

246 calculator[key] rather than calculator.parameters[key] 

247 

248 Parameters 

249 ---------- 

250 -key : str, the name of the parameters to get. 

251 """ 

252 return self.parameters[key] 

253 

254 def species(self, atoms): 

255 """Find all relevant species depending on the atoms object and 

256 species input. 

257 

258 Parameters : 

259 - atoms : An Atoms object. 

260 """ 

261 return SiestaInput.get_species( 

262 atoms, list(self['species']), self['basis_set'] 

263 ) 

264 

265 @deprecated( 

266 "The keyword 'UNPOLARIZED' has been deprecated," 

267 "and replaced by 'non-polarized'", 

268 category=FutureWarning, 

269 callback=_nonpolarized_alias, 

270 ) 

271 def set(self, **kwargs): 

272 """Set all parameters. 

273 

274 Parameters 

275 ---------- 

276 -kwargs : Dictionary containing the keywords defined in 

277 SiestaParameters. 

278 

279 .. deprecated:: 3.18.2 

280 The keyword 'UNPOLARIZED' has been deprecated and replaced by 

281 'non-polarized' 

282 """ 

283 

284 # XXX Inserted these next few lines because set() would otherwise 

285 # discard all previously set keywords to their defaults! --askhl 

286 current = self.parameters.copy() 

287 current.update(kwargs) 

288 kwargs = current 

289 

290 # Find not allowed keys. 

291 default_keys = list(self.__class__.default_parameters) 

292 offending_keys = set(kwargs) - set(default_keys) 

293 if len(offending_keys) > 0: 

294 mess = "'set' does not take the keywords: %s " 

295 raise ValueError(mess % list(offending_keys)) 

296 

297 # Use the default parameters. 

298 parameters = self.__class__.default_parameters.copy() 

299 parameters.update(kwargs) 

300 kwargs = parameters 

301 

302 # Check energy inputs. 

303 for arg in ['mesh_cutoff', 'energy_shift']: 

304 value = kwargs.get(arg) 

305 if value is None: 

306 continue 

307 if not (isinstance(value, (float, int)) and value > 0): 

308 mess = "'{}' must be a positive number(in eV), \ 

309 got '{}'".format(arg, value) 

310 raise ValueError(mess) 

311 

312 # Check the functional input. 

313 xc = kwargs.get('xc', 'LDA') 

314 if isinstance(xc, (tuple, list)) and len(xc) == 2: 

315 functional, authors = xc 

316 if functional.lower() not in [k.lower() for k in self.allowed_xc]: 

317 mess = f"Unrecognized functional keyword: '{functional}'" 

318 raise ValueError(mess) 

319 

320 lsauthorslower = [a.lower() for a in self.allowed_xc[functional]] 

321 if authors.lower() not in lsauthorslower: 

322 mess = "Unrecognized authors keyword for %s: '%s'" 

323 raise ValueError(mess % (functional, authors)) 

324 

325 elif xc in self.allowed_xc: 

326 functional = xc 

327 authors = self.allowed_xc[xc][0] 

328 else: 

329 found = False 

330 for key, value in self.allowed_xc.items(): 

331 if xc in value: 

332 found = True 

333 functional = key 

334 authors = xc 

335 break 

336 

337 if not found: 

338 raise ValueError(f"Unrecognized 'xc' keyword: '{xc}'") 

339 kwargs['xc'] = (functional, authors) 

340 

341 # Check fdf_arguments. 

342 if kwargs['fdf_arguments'] is None: 

343 kwargs['fdf_arguments'] = {} 

344 

345 if not isinstance(kwargs['fdf_arguments'], dict): 

346 raise TypeError('fdf_arguments must be a dictionary.') 

347 

348 # Call baseclass. 

349 FileIOCalculator.set(self, **kwargs) 

350 

351 def set_fdf_arguments(self, fdf_arguments): 

352 """Set the fdf_arguments after the initialization of the 

353 calculator. 

354 """ 

355 self.validate_fdf_arguments(fdf_arguments) 

356 FileIOCalculator.set(self, fdf_arguments=fdf_arguments) 

357 

358 def validate_fdf_arguments(self, fdf_arguments): 

359 """Raises error if the fdf_argument input is not a 

360 dictionary of allowed keys. 

361 """ 

362 # None is valid 

363 if fdf_arguments is None: 

364 return 

365 

366 # Type checking. 

367 if not isinstance(fdf_arguments, dict): 

368 raise TypeError('fdf_arguments must be a dictionary.') 

369 

370 def write_input(self, atoms, properties=None, system_changes=None): 

371 """Write input (fdf)-file. 

372 See calculator.py for further details. 

373 

374 Parameters 

375 ---------- 

376 - atoms : The Atoms object to write. 

377 - properties : The properties which should be calculated. 

378 - system_changes : List of properties changed since last run. 

379 """ 

380 

381 super().write_input( 

382 atoms=atoms, properties=properties, system_changes=system_changes 

383 ) 

384 

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

386 

387 more_fdf_args = {} 

388 

389 # Use the saved density matrix if only 'cell' and 'positions' 

390 # have changed. 

391 if system_changes is None or ( 

392 'numbers' not in system_changes 

393 and 'initial_magmoms' not in system_changes 

394 and 'initial_charges' not in system_changes 

395 ): 

396 more_fdf_args['DM.UseSaveDM'] = True 

397 

398 if 'density' in properties: 

399 more_fdf_args['SaveRho'] = True 

400 

401 species, species_numbers = self.species(atoms) 

402 

403 pseudo_path = ( 

404 self['pseudo_path'] 

405 or self.profile.configvars.get('pseudo_path') 

406 or self.cfg.get('SIESTA_PP_PATH') 

407 ) 

408 

409 if not pseudo_path: 

410 raise Exception( 

411 'Please configure pseudo_path or SIESTA_PP_PATH envvar' 

412 ) 

413 

414 species_info = SpeciesInfo( 

415 atoms=atoms, 

416 pseudo_path=Path(pseudo_path), 

417 pseudo_qualifier=self.pseudo_qualifier(), 

418 species=species, 

419 ) 

420 

421 writer = FDFWriter( 

422 name=self.prefix, 

423 xc=self['xc'], 

424 spin=self['spin'], 

425 mesh_cutoff=self['mesh_cutoff'], 

426 energy_shift=self['energy_shift'], 

427 fdf_user_args=self['fdf_arguments'], 

428 more_fdf_args=more_fdf_args, 

429 species_numbers=species_numbers, 

430 atomic_coord_format=self['atomic_coord_format'].lower(), 

431 kpts=self['kpts'], 

432 bandpath=self['bandpath'], 

433 species_info=species_info, 

434 ) 

435 

436 with open(filename, 'w') as fd: 

437 writer.write(fd) 

438 

439 writer.link_pseudos_into_directory( 

440 symlink_pseudos=self['symlink_pseudos'], 

441 directory=Path(self.directory), 

442 ) 

443 

444 def read(self, filename): 

445 """Read structural parameters from file .XV file 

446 Read other results from other files 

447 filename : siesta.XV 

448 """ 

449 

450 fname = self.getpath(filename) 

451 if not fname.exists(): 

452 raise ReadError(f"The restart file '{fname}' does not exist") 

453 with fname.open() as fd: 

454 self.atoms = read_siesta_xv(fd) 

455 self.read_results() 

456 

457 def getpath(self, fname=None, ext=None): 

458 """Returns the directory/fname string""" 

459 if fname is None: 

460 fname = self.prefix 

461 if ext is not None: 

462 fname = f'{fname}.{ext}' 

463 return Path(self.directory) / fname 

464 

465 def pseudo_qualifier(self): 

466 """Get the extra string used in the middle of the pseudopotential. 

467 The retrieved pseudopotential for a specific element will be 

468 'H.xxx.psf' for the element 'H' with qualifier 'xxx'. If qualifier 

469 is set to None then the qualifier is set to functional name. 

470 """ 

471 if self['pseudo_qualifier'] is None: 

472 return self['xc'][0].lower() 

473 else: 

474 return self['pseudo_qualifier'] 

475 

476 def read_results(self): 

477 """Read the results.""" 

478 from ase.io.siesta_output import OutputReader 

479 

480 reader = OutputReader( 

481 prefix=self.prefix, 

482 directory=Path(self.directory), 

483 bandpath=self['bandpath'], 

484 ) 

485 results = reader.read_results() 

486 self.results.update(results) 

487 

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

489 

490 def read_ion(self, atoms): 

491 """ 

492 Read the ion.xml file of each specie 

493 """ 

494 species, _species_numbers = self.species(atoms) 

495 

496 ion_results = {} 

497 for species_number, spec in enumerate(species, start=1): 

498 symbol = spec['symbol'] 

499 atomic_number = atomic_numbers[symbol] 

500 

501 if spec['pseudopotential'] is None: 

502 if self.pseudo_qualifier() == '': 

503 label = symbol 

504 else: 

505 label = f'{symbol}.{self.pseudo_qualifier()}' 

506 pseudopotential = self.getpath(label, 'psf') 

507 else: 

508 pseudopotential = Path(spec['pseudopotential']) 

509 label = pseudopotential.stem 

510 

511 name = f'{label}.{species_number}' 

512 if spec['ghost']: 

513 name = f'{name}.ghost' 

514 atomic_number = -atomic_number 

515 

516 if name not in ion_results: 

517 fname = self.getpath(name, 'ion.xml') 

518 if fname.is_file(): 

519 ion_results[name] = get_ion(str(fname)) 

520 

521 return ion_results 

522 

523 def band_structure(self): 

524 return self.results['bandstructure'] 

525 

526 def get_fermi_level(self): 

527 return self.results['fermi_energy'] 

528 

529 def get_k_point_weights(self): 

530 return self.results['kpoint_weights'] 

531 

532 def get_ibz_k_points(self): 

533 return self.results['kpoints'] 

534 

535 def get_eigenvalues(self, kpt=0, spin=0): 

536 return self.results['eigenvalues'][spin, kpt] 

537 

538 def get_number_of_spins(self): 

539 return self.results['eigenvalues'].shape[0] 

540 

541 

542def generate_atomic_coordinates( 

543 atoms: Atoms, species_numbers, atomic_coord_format: str 

544): 

545 """Write atomic coordinates. 

546 

547 Parameters 

548 ---------- 

549 fd : IO 

550 An open file object. 

551 atoms : Atoms 

552 An atoms object. 

553 """ 

554 if atomic_coord_format == 'xyz': 

555 return generate_atomic_coordinates_xyz(atoms, species_numbers) 

556 elif atomic_coord_format == 'zmatrix': 

557 return generate_atomic_coordinates_zmatrix(atoms, species_numbers) 

558 else: 

559 raise RuntimeError( 

560 f'Unknown atomic_coord_format: {atomic_coord_format}' 

561 ) 

562 

563 

564def generate_atomic_coordinates_zmatrix(atoms: Atoms, species_numbers): 

565 """Write atomic coordinates in Z-matrix format. 

566 

567 Parameters 

568 ---------- 

569 fd : IO 

570 An open file object. 

571 atoms : Atoms 

572 An atoms object. 

573 """ 

574 yield '\n' 

575 yield var('ZM.UnitsLength', 'Ang') 

576 yield '%block Zmatrix\n' 

577 yield ' cartesian\n' 

578 

579 fstr = '{:5d}' + '{:20.10f}' * 3 + '{:3d}' * 3 + '{:7d} {:s}\n' 

580 a2constr = SiestaInput.make_xyz_constraints(atoms) 

581 a2p, a2s = atoms.get_positions(), atoms.symbols 

582 for ia, (sp, xyz, ccc, sym) in enumerate( 

583 zip(species_numbers, a2p, a2constr, a2s) 

584 ): 

585 yield fstr.format( 

586 sp, xyz[0], xyz[1], xyz[2], ccc[0], ccc[1], ccc[2], ia + 1, sym 

587 ) 

588 yield '%endblock Zmatrix\n' 

589 

590 # origin = tuple(-atoms.get_celldisp().flatten()) 

591 # yield block('AtomicCoordinatesOrigin', [origin]) 

592 

593 

594def generate_atomic_coordinates_xyz(atoms: Atoms, species_numbers): 

595 """Write atomic coordinates. 

596 

597 Parameters 

598 ---------- 

599 fd : IO 

600 An open file object. 

601 atoms : Atoms 

602 An atoms object. 

603 """ 

604 yield '\n' 

605 yield var('AtomicCoordinatesFormat', 'Ang') 

606 yield block( 

607 'AtomicCoordinatesAndAtomicSpecies', 

608 [ 

609 [*atom.position, number] 

610 for atom, number in zip(atoms, species_numbers) 

611 ], 

612 ) 

613 yield '\n' 

614 

615 # origin = tuple(-atoms.get_celldisp().flatten()) 

616 # yield block('AtomicCoordinatesOrigin', [origin]) 

617 

618 

619@dataclass 

620class SpeciesInfo: 

621 atoms: Atoms 

622 pseudo_path: Path 

623 pseudo_qualifier: str 

624 species: dict # actually a kind of Parameters object, should refactor 

625 

626 def __post_init__(self): 

627 pao_basis = [] 

628 chemical_labels = [] 

629 basis_sizes = [] 

630 file_instructions = [] 

631 

632 for species_number, spec in enumerate(self.species, start=1): 

633 symbol = spec['symbol'] 

634 atomic_number = atomic_numbers[symbol] 

635 

636 if spec['pseudopotential'] is None: 

637 if self.pseudo_qualifier == '': 

638 label = symbol 

639 else: 

640 label = f'{symbol}.{self.pseudo_qualifier}' 

641 src_path = self.pseudo_path / f'{label}.psf' 

642 else: 

643 src_path = Path(spec['pseudopotential']) 

644 

645 if not src_path.is_absolute(): 

646 src_path = self.pseudo_path / src_path 

647 if not src_path.exists(): 

648 src_path = self.pseudo_path / f'{symbol}.psml' 

649 

650 name = src_path.name 

651 name = name.split('.') 

652 name.insert(-1, str(species_number)) 

653 if spec['ghost']: 

654 name.insert(-1, 'ghost') 

655 atomic_number = -atomic_number 

656 

657 name = '.'.join(name) 

658 

659 instr = FileInstruction(src_path, name) 

660 file_instructions.append(instr) 

661 

662 label = '.'.join(np.array(name.split('.'))[:-1]) 

663 pseudo_name = '' 

664 if src_path.suffix != '.psf': 

665 pseudo_name = f'{label}{src_path.suffix}' 

666 string = ' %d %d %s %s' % ( 

667 species_number, 

668 atomic_number, 

669 label, 

670 pseudo_name, 

671 ) 

672 chemical_labels.append(string) 

673 if isinstance(spec['basis_set'], PAOBasisBlock): 

674 pao_basis.append(spec['basis_set'].script(label)) 

675 else: 

676 basis_sizes.append((' ' + label, spec['basis_set'])) 

677 

678 self.file_instructions = file_instructions 

679 self.chemical_labels = chemical_labels 

680 self.pao_basis = pao_basis 

681 self.basis_sizes = basis_sizes 

682 

683 def generate_text(self): 

684 yield var('NumberOfSpecies', len(self.species)) 

685 yield var('NumberOfAtoms', len(self.atoms)) 

686 

687 yield var('ChemicalSpecieslabel', self.chemical_labels) 

688 yield '\n' 

689 yield var('PAO.Basis', self.pao_basis) 

690 yield var('PAO.BasisSizes', self.basis_sizes) 

691 yield '\n' 

692 

693 

694@dataclass 

695class FileInstruction: 

696 src_path: Path 

697 targetname: str 

698 

699 def copy_to(self, directory): 

700 self._link(shutil.copy, directory) 

701 

702 def symlink_to(self, directory): 

703 self._link(os.symlink, directory) 

704 

705 def _link(self, file_operation, directory): 

706 dst_path = directory / self.targetname 

707 if self.src_path == dst_path: 

708 return 

709 

710 dst_path.unlink(missing_ok=True) 

711 file_operation(self.src_path, dst_path) 

712 

713 

714@dataclass 

715class FDFWriter: 

716 name: str 

717 xc: str 

718 fdf_user_args: dict 

719 more_fdf_args: dict 

720 mesh_cutoff: float 

721 energy_shift: float 

722 spin: str 

723 species_numbers: object # ? 

724 atomic_coord_format: str 

725 kpts: object # ? 

726 bandpath: object # ? 

727 species_info: object 

728 

729 def write(self, fd): 

730 for chunk in self.generate_text(): 

731 fd.write(chunk) 

732 

733 def generate_text(self): 

734 yield var('SystemName', self.name) 

735 yield var('SystemLabel', self.name) 

736 yield '\n' 

737 

738 # Write explicitly given options first to 

739 # allow the user to override anything. 

740 fdf_arguments = self.fdf_user_args 

741 for key in sorted(fdf_arguments): 

742 yield var(key, fdf_arguments[key]) 

743 

744 # Force siesta to return error on no convergence. 

745 # as default consistent with ASE expectations. 

746 if 'SCFMustConverge' not in fdf_arguments: 

747 yield var('SCFMustConverge', True) 

748 yield '\n' 

749 

750 yield var('Spin', self.spin) 

751 # Spin backwards compatibility. 

752 if self.spin == 'collinear': 

753 key = 'SpinPolarized' 

754 elif self.spin == 'non-collinear': 

755 key = 'NonCollinearSpin' 

756 else: 

757 key = None 

758 

759 if key is not None: 

760 yield var(key, (True, '# Backwards compatibility.')) 

761 

762 # Write functional. 

763 functional, authors = self.xc 

764 yield var('XC.functional', functional) 

765 yield var('XC.authors', authors) 

766 yield '\n' 

767 

768 # Write mesh cutoff and energy shift. 

769 yield var('MeshCutoff', (self.mesh_cutoff, 'eV')) 

770 yield var('PAO.EnergyShift', (self.energy_shift, 'eV')) 

771 yield '\n' 

772 

773 yield from self.species_info.generate_text() 

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

775 

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

777 yield var(key, value) 

778 

779 if self.kpts is not None: 

780 kpts = np.array(self.kpts) 

781 yield from SiestaInput.generate_kpts(kpts) 

782 

783 if self.bandpath is not None: 

784 lines = bandpath2bandpoints(self.bandpath) 

785 assert isinstance(lines, str) # rename this variable? 

786 yield lines 

787 yield '\n' 

788 

789 def generate_atoms_text(self, atoms: Atoms): 

790 """Translate the Atoms object to fdf-format.""" 

791 

792 cell = atoms.cell 

793 yield '\n' 

794 

795 if cell.rank in [1, 2]: 

796 raise ValueError( 

797 'Expected 3D unit cell or no unit cell. You may ' 

798 'wish to add vacuum along some directions.' 

799 ) 

800 

801 if np.any(cell): 

802 yield var('LatticeConstant', '1.0 Ang') 

803 yield block('LatticeVectors', cell) 

804 

805 yield from generate_atomic_coordinates( 

806 atoms, self.species_numbers, self.atomic_coord_format 

807 ) 

808 

809 # Write magnetic moments. 

810 magmoms = atoms.get_initial_magnetic_moments() 

811 

812 # The DM.InitSpin block must be written to initialize to 

813 # no spin. SIESTA default is FM initialization, if the 

814 # block is not written, but we must conform to the 

815 # atoms object. 

816 if len(magmoms) == 0: 

817 yield '#Empty block forces ASE initialization.\n' 

818 

819 yield '%block DM.InitSpin\n' 

820 if len(magmoms) != 0 and isinstance(magmoms[0], np.ndarray): 

821 for n, M in enumerate(magmoms): 

822 if M[0] != 0: 

823 yield ( 

824 ' %d %.14f %.14f %.14f \n' 

825 % (n + 1, M[0], M[1], M[2]) 

826 ) 

827 elif len(magmoms) != 0 and isinstance(magmoms[0], float): 

828 for n, M in enumerate(magmoms): 

829 if M != 0: 

830 yield ' %d %.14f \n' % (n + 1, M) 

831 yield '%endblock DM.InitSpin\n' 

832 yield '\n' 

833 

834 def link_pseudos_into_directory(self, *, symlink_pseudos=None, directory): 

835 if symlink_pseudos is None: 

836 symlink_pseudos = os.name != 'nt' 

837 

838 for instruction in self.species_info.file_instructions: 

839 if symlink_pseudos: 

840 instruction.symlink_to(directory) 

841 else: 

842 instruction.copy_to(directory) 

843 

844 

845# Utilities for generating bits of strings. 

846# 

847# We are re-aliasing format_fdf and format_block in the anticipation 

848# that they may change, or we might move this onto a Formatter object 

849# which applies consistent spacings etc. 

850def var(key, value): 

851 return format_fdf(key, value) 

852 

853 

854def block(name, data): 

855 return format_block(name, data)