Coverage for ase/io/siesta.py: 72.90%
107 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"""Helper functions for read_fdf."""
3from pathlib import Path
4from re import compile
6import numpy as np
8from ase import Atoms
9from ase.units import Bohr
10from ase.utils import reader
12_label_strip_re = compile(r'[\s._-]')
15def _labelize(raw_label):
16 # Labels are case insensitive and -_. should be ignored, lower and strip it
17 return _label_strip_re.sub('', raw_label).lower()
20def _is_block(val):
21 # Tell whether value is a block-value or an ordinary value.
22 # A block is represented as a list of lists of strings,
23 # and a ordinary value is represented as a list of strings
24 if isinstance(val, list) and len(val) > 0 and isinstance(val[0], list):
25 return True
26 return False
29def _get_stripped_lines(fd):
30 # Remove comments, leading blanks, and empty lines
31 return [_f for _f in [L.split('#')[0].strip() for L in fd] if _f]
34@reader
35def _read_fdf_lines(file):
36 # Read lines and resolve includes
37 lbz = _labelize
39 lines = []
40 for L in _get_stripped_lines(file):
41 w0 = lbz(L.split(None, 1)[0])
43 if w0 == '%include':
44 # Include the contents of fname
45 fname = L.split(None, 1)[1].strip()
46 parent_fname = getattr(file, 'name', None)
47 if isinstance(parent_fname, str):
48 fname = Path(parent_fname).parent / fname
49 lines += _read_fdf_lines(fname)
51 elif '<' in L:
52 L, fname = L.split('<', 1)
53 w = L.split()
54 fname = fname.strip()
56 if w0 == '%block':
57 # "%block label < filename" means that the block contents
58 # should be read from filename
59 if len(w) != 2:
60 raise OSError(
61 'Bad %%block-statement "%s < %s"' % (L, fname)
62 )
63 label = lbz(w[1])
64 lines.append('%%block %s' % label)
65 lines += _get_stripped_lines(open(fname))
66 lines.append('%%endblock %s' % label)
67 else:
68 # "label < filename.fdf" means that the label
69 # (_only_ that label) is to be resolved from filename.fdf
70 label = lbz(w[0])
71 fdf = read_fdf(fname)
72 if label in fdf:
73 if _is_block(fdf[label]):
74 lines.append('%%block %s' % label)
75 lines += [' '.join(x) for x in fdf[label]]
76 lines.append('%%endblock %s' % label)
77 else:
78 lines.append(
79 '{} {}'.format(label, ' '.join(fdf[label]))
80 )
81 # else:
82 # label unresolved!
83 # One should possibly issue a warning about this!
84 else:
85 # Simple include line L
86 lines.append(L)
87 return lines
90def read_fdf(fname):
91 """Read a siesta style fdf-file.
93 The data is returned as a dictionary
94 ( label:value ).
96 All labels are converted to lower case characters and
97 are stripped of any '-', '_', or '.'.
99 Ordinary values are stored as a list of strings (splitted on WS),
100 and block values are stored as list of lists of strings
101 (splitted per line, and on WS).
102 If a label occurres more than once, the first occurrence
103 takes precedence.
105 The implementation applies no intelligence, and does not
106 "understand" the data or the concept of units etc.
107 Values are never parsed in any way, just stored as
108 split strings.
110 The implementation tries to comply with the fdf-format
111 specification as presented in the siesta 2.0.2 manual.
113 An fdf-dictionary could e.g. look like this::
115 {'atomiccoordinatesandatomicspecies': [
116 ['4.9999998', '5.7632392', '5.6095972', '1'],
117 ['5.0000000', '6.5518100', '4.9929091', '2'],
118 ['5.0000000', '4.9746683', '4.9929095', '2']],
119 'atomiccoordinatesformat': ['Ang'],
120 'chemicalspecieslabel': [['1', '8', 'O'],
121 ['2', '1', 'H']],
122 'dmmixingweight': ['0.1'],
123 'dmnumberpulay': ['5'],
124 'dmusesavedm': ['True'],
125 'latticeconstant': ['1.000000', 'Ang'],
126 'latticevectors': [
127 ['10.00000000', '0.00000000', '0.00000000'],
128 ['0.00000000', '11.52647800', '0.00000000'],
129 ['0.00000000', '0.00000000', '10.59630900']],
130 'maxscfiterations': ['120'],
131 'meshcutoff': ['2721.139566', 'eV'],
132 'numberofatoms': ['3'],
133 'numberofspecies': ['2'],
134 'paobasissize': ['dz'],
135 'solutionmethod': ['diagon'],
136 'systemlabel': ['H2O'],
137 'wavefunckpoints': [['0.0', '0.0', '0.0']],
138 'writedenchar': ['T'],
139 'xcauthors': ['PBE'],
140 'xcfunctional': ['GGA']}
142 """
143 fdf = {}
144 lbz = _labelize
145 lines = _read_fdf_lines(fname)
146 while lines:
147 w = lines.pop(0).split(None, 1)
148 if lbz(w[0]) == '%block':
149 # Block value
150 if len(w) == 2:
151 label = lbz(w[1])
152 content = []
153 while True:
154 if len(lines) == 0:
155 raise OSError(
156 'Unexpected EOF reached in %s, '
157 'un-ended block %s' % (fname, label)
158 )
159 w = lines.pop(0).split()
160 if lbz(w[0]) == '%endblock':
161 break
162 content.append(w)
164 if label not in fdf:
165 # Only first appearance of label is to be used
166 fdf[label] = content
167 else:
168 raise OSError('%%block statement without label')
169 else:
170 # Ordinary value
171 label = lbz(w[0])
172 if len(w) == 1:
173 # Siesta interpret blanks as True for logical variables
174 fdf[label] = []
175 else:
176 fdf[label] = w[1].split()
177 return fdf
180def read_struct_out(fd):
181 """Read a siesta struct file"""
183 cell = []
184 for _ in range(3):
185 line = next(fd)
186 v = np.array(line.split(), float)
187 cell.append(v)
189 natoms = int(next(fd))
191 numbers = np.empty(natoms, int)
192 scaled_positions = np.empty((natoms, 3))
193 for i, line in enumerate(fd):
194 tokens = line.split()
195 numbers[i] = int(tokens[1])
196 scaled_positions[i] = np.array(tokens[2:5], float)
198 return Atoms(
199 numbers, cell=cell, pbc=True, scaled_positions=scaled_positions
200 )
203def read_siesta_xv(fd):
204 vectors = []
205 for _ in range(3):
206 data = next(fd).split()
207 vectors.append([float(data[j]) * Bohr for j in range(3)])
209 # Read number of atoms (line 4)
210 natoms = int(next(fd).split()[0])
212 # Read remaining lines
213 speciesnumber, atomnumbers, xyz, V = [], [], [], []
214 for line in fd:
215 if len(line) > 5: # Ignore blank lines
216 data = line.split()
217 speciesnumber.append(int(data[0]))
218 atomnumbers.append(int(data[1]))
219 xyz.append([float(data[2 + j]) * Bohr for j in range(3)])
220 V.append([float(data[5 + j]) * Bohr for j in range(3)])
222 vectors = np.array(vectors)
223 atomnumbers = np.array(atomnumbers)
224 xyz = np.array(xyz)
225 atoms = Atoms(numbers=atomnumbers, positions=xyz, cell=vectors, pbc=True)
226 assert natoms == len(atoms)
227 return atoms