Coverage for ase/io/cfg.py: 78.05%
164 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
1import numpy as np
3import ase
4from ase.data import chemical_symbols
5from ase.utils import reader, writer
7cfg_default_fields = np.array(['positions', 'momenta', 'numbers', 'magmoms'])
10@writer
11def write_cfg(fd, atoms):
12 """Write atomic configuration to a CFG-file (native AtomEye format).
13 See: http://mt.seas.upenn.edu/Archive/Graphics/A/
14 """
16 fd.write('Number of particles = %i\n' % len(atoms))
17 fd.write('A = 1.0 Angstrom\n')
18 cell = atoms.get_cell(complete=True)
19 for i in range(3):
20 for j in range(3):
21 fd.write('H0(%1.1i,%1.1i) = %f A\n' % (i + 1, j + 1, cell[i, j]))
23 entry_count = 3
24 for x in atoms.arrays.keys():
25 if x not in cfg_default_fields:
26 if len(atoms.get_array(x).shape) == 1:
27 entry_count += 1
28 else:
29 entry_count += atoms.get_array(x).shape[1]
31 vels = atoms.get_velocities()
32 if isinstance(vels, np.ndarray):
33 entry_count += 3
34 else:
35 fd.write('.NO_VELOCITY.\n')
37 fd.write('entry_count = %i\n' % entry_count)
39 i = 0
40 for name, aux in atoms.arrays.items():
41 if name not in cfg_default_fields:
42 if len(aux.shape) == 1:
43 fd.write('auxiliary[%i] = %s [a.u.]\n' % (i, name))
44 i += 1
45 else:
46 if aux.shape[1] == 3:
47 for j in range(3):
48 fd.write(
49 'auxiliary[%i] = %s_%s [a.u.]\n'
50 % (i, name, chr(ord('x') + j))
51 )
52 i += 1
54 else:
55 for j in range(aux.shape[1]):
56 fd.write(
57 'auxiliary[%i] = %s_%1.1i [a.u.]\n' % (i, name, j)
58 )
59 i += 1
61 # Distinct elements
62 spos = atoms.get_scaled_positions()
63 for i in atoms:
64 el = i.symbol
66 fd.write('%f\n' % ase.data.atomic_masses[chemical_symbols.index(el)])
67 fd.write(f'{el}\n')
69 x, y, z = spos[i.index, :]
70 s = f'{x:e} {y:e} {z:e} '
72 if isinstance(vels, np.ndarray):
73 vx, vy, vz = vels[i.index, :]
74 s = s + f' {vx:e} {vy:e} {vz:e} '
76 for name, aux in atoms.arrays.items():
77 if name not in cfg_default_fields:
78 if len(aux.shape) == 1:
79 s += ' %e' % aux[i.index]
80 else:
81 s += (aux.shape[1] * ' %e') % tuple(aux[i.index].tolist())
83 fd.write(f'{s}\n')
86default_color = {
87 'H': [0.800, 0.800, 0.800],
88 'C': [0.350, 0.350, 0.350],
89 'O': [0.800, 0.200, 0.200],
90}
92default_radius = {'H': 0.435, 'C': 0.655, 'O': 0.730}
95def write_clr(fd, atoms):
96 """Write extra color and radius code to a CLR-file (for use with AtomEye).
97 Hit F12 in AtomEye to use.
98 See: http://mt.seas.upenn.edu/Archive/Graphics/A/
99 """
100 color = None
101 radius = None
102 if atoms.has('color'):
103 color = atoms.get_array('color')
104 if atoms.has('radius'):
105 radius = atoms.get_array('radius')
107 if color is None:
108 color = np.zeros([len(atoms), 3], dtype=float)
109 for a in atoms:
110 color[a.index, :] = default_color[a.symbol]
112 if radius is None:
113 radius = np.zeros(len(atoms), dtype=float)
114 for a in atoms:
115 radius[a.index] = default_radius[a.symbol]
117 radius = radius.reshape((-1, 1))
119 for c1, c2, c3, r in np.append(color, radius, axis=1):
120 fd.write(f'{c1:f} {c2:f} {c3:f} {r:f}\n')
123@reader
124def read_cfg(fd):
125 """Read atomic configuration from a CFG-file (native AtomEye format).
126 See: http://mt.seas.upenn.edu/Archive/Graphics/A/
127 """
128 nat = None
129 naux = 0
130 aux = None
131 auxstrs = None
133 cell = np.zeros([3, 3])
134 transform = np.eye(3)
135 eta = np.zeros([3, 3])
137 current_atom = 0
138 current_symbol = None
139 current_mass = None
141 L = fd.readline()
142 while L:
143 L = L.strip()
144 if len(L) != 0 and not L.startswith('#'):
145 if L == '.NO_VELOCITY.':
146 vels = None
147 naux += 3
148 else:
149 s = L.split('=')
150 if len(s) == 2:
151 key, value = s
152 key = key.strip()
153 value = [x.strip() for x in value.split()]
154 if key == 'Number of particles':
155 nat = int(value[0])
156 spos = np.zeros([nat, 3])
157 masses = np.zeros(nat)
158 syms = [''] * nat
159 vels = np.zeros([nat, 3])
160 if naux > 0:
161 aux = np.zeros([nat, naux])
162 elif key == 'A':
163 pass # unit = float(value[0])
164 elif key == 'entry_count':
165 naux += int(value[0]) - 6
166 auxstrs = [''] * naux
167 if nat is not None:
168 aux = np.zeros([nat, naux])
169 elif key.startswith('H0('):
170 i, j = (int(x) for x in key[3:-1].split(','))
171 cell[i - 1, j - 1] = float(value[0])
172 elif key.startswith('Transform('):
173 i, j = (int(x) for x in key[10:-1].split(','))
174 transform[i - 1, j - 1] = float(value[0])
175 elif key.startswith('eta('):
176 i, j = (int(x) for x in key[4:-1].split(','))
177 eta[i - 1, j - 1] = float(value[0])
178 elif key.startswith('auxiliary['):
179 i = int(key[10:-1])
180 auxstrs[i] = value[0]
181 else:
182 # Everything else must be particle data.
183 # First check if current line contains an element mass or
184 # name. Then we have an extended XYZ format.
185 s = [x.strip() for x in L.split()]
186 if len(s) == 1:
187 if L in chemical_symbols:
188 current_symbol = L
189 else:
190 current_mass = float(L)
191 elif current_symbol is None and current_mass is None:
192 # Standard CFG format
193 masses[current_atom] = float(s[0])
194 syms[current_atom] = s[1]
195 spos[current_atom, :] = [float(x) for x in s[2:5]]
196 vels[current_atom, :] = [float(x) for x in s[5:8]]
197 current_atom += 1
198 elif (
199 current_symbol is not None and current_mass is not None
200 ):
201 # Extended CFG format
202 masses[current_atom] = current_mass
203 syms[current_atom] = current_symbol
204 props = [float(x) for x in s]
205 spos[current_atom, :] = props[0:3]
206 off = 3
207 if vels is not None:
208 off = 6
209 vels[current_atom, :] = props[3:6]
210 aux[current_atom, :] = props[off:]
211 current_atom += 1
212 L = fd.readline()
214 # Sanity check
215 if current_atom != nat:
216 raise RuntimeError(
217 'Number of atoms reported for CFG file (={}) and '
218 'number of atoms actually read (={}) differ.'.format(
219 nat, current_atom
220 )
221 )
223 if np.any(eta != 0):
224 raise NotImplementedError(
225 'eta != 0 not yet implemented for CFG reader.'
226 )
227 cell = np.dot(cell, transform)
229 if vels is None:
230 a = ase.Atoms(
231 symbols=syms,
232 masses=masses,
233 scaled_positions=spos,
234 cell=cell,
235 pbc=True,
236 )
237 else:
238 a = ase.Atoms(
239 symbols=syms,
240 masses=masses,
241 scaled_positions=spos,
242 momenta=masses.reshape(-1, 1) * vels,
243 cell=cell,
244 pbc=True,
245 )
247 i = 0
248 while i < naux:
249 auxstr = auxstrs[i]
250 if auxstr[-2:] == '_x':
251 a.set_array(auxstr[:-2], aux[:, i : i + 3])
252 i += 3
253 else:
254 a.set_array(auxstr, aux[:, i])
255 i += 1
257 return a