Coverage for ase/cli/build.py: 58.82%

102 statements  

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

1# Note: 

2# Try to avoid module level import statements here to reduce 

3# import time during CLI execution 

4import sys 

5 

6import numpy as np 

7 

8 

9class CLICommand: 

10 """Build an atom, molecule or bulk structure. 

11 

12 Atom: 

13 

14 ase build <chemical symbol> ... 

15 

16 Molecule: 

17 

18 ase build <formula> ... 

19 

20 where <formula> must be one of the formulas known to ASE 

21 (see here: https://docs.ase-lib.org/ase/build/build.html#molecules). 

22 

23 Bulk: 

24 

25 ase build -x <crystal structure> <formula> ... 

26 

27 Examples 

28 -------- 

29 

30 ase build Li # lithium atom 

31 ase build Li -M 1 # ... with a magnetic moment of 1 

32 ase build Li -M 1 -V 3.5 # ... in a 7x7x7 Ang cell 

33 ase build H2O # water molecule 

34 ase build -x fcc Cu -a 3.6 # FCC copper 

35 """ 

36 

37 @staticmethod 

38 def add_arguments(parser): 

39 add = parser.add_argument 

40 add( 

41 'name', 

42 metavar='formula/input-file', 

43 help='Chemical formula or input filename.', 

44 ) 

45 add('output', nargs='?', help='Output file.') 

46 add( 

47 '-M', 

48 '--magnetic-moment', 

49 metavar='M1,M2,...', 

50 help='Magnetic moments. Use "-M 1" or "-M 2.3,-2.3"', 

51 ) 

52 add( 

53 '--modify', 

54 metavar='...', 

55 help='Modify atoms with Python statement. ' 

56 'Example: --modify="atoms.positions[-1,2]+=0.1"', 

57 ) 

58 add( 

59 '-V', 

60 '--vacuum', 

61 type=float, 

62 help='Amount of vacuum to add around isolated atoms (in Angstrom)', 

63 ) 

64 add( 

65 '-v', 

66 '--vacuum0', 

67 type=float, 

68 help='Deprecated. Use -V or --vacuum instead', 

69 ) 

70 add( 

71 '--unit-cell', 

72 metavar='CELL', 

73 help='Unit cell in Angstrom. Examples: "10.0" or "9,10,11"', 

74 ) 

75 add( 

76 '--bond-length', 

77 type=float, 

78 metavar='LENGTH', 

79 help='Bond length of dimer in Angstrom', 

80 ) 

81 add( 

82 '-x', 

83 '--crystal-structure', 

84 help='Crystal structure', 

85 choices=[ 

86 'sc', 

87 'fcc', 

88 'bcc', 

89 'hcp', 

90 'diamond', 

91 'zincblende', 

92 'rocksalt', 

93 'cesiumchloride', 

94 'fluorite', 

95 'wurtzite', 

96 ], 

97 ) 

98 add( 

99 '-a', 

100 '--lattice-constant', 

101 default='', 

102 metavar='LENGTH', 

103 help='Lattice constant or comma-separated lattice constantes in ' 

104 'Angstrom', 

105 ) 

106 add( 

107 '--orthorhombic', 

108 action='store_true', 

109 help='Use orthorhombic unit cell', 

110 ) 

111 add('--cubic', action='store_true', help='Use cubic unit cell') 

112 add( 

113 '-r', '--repeat', help='Repeat unit cell. Use "-r 2" or "-r 2,3,1"' 

114 ) 

115 add('-g', '--gui', action='store_true', help='open ase gui') 

116 add( 

117 '--periodic', 

118 action='store_true', 

119 help='make structure fully periodic', 

120 ) 

121 

122 @staticmethod 

123 def run(args, parser): 

124 from ase.db import connect 

125 from ase.io import read, write 

126 from ase.visualize import view 

127 

128 if args.vacuum0: 

129 parser.error('Please use -V or --vacuum instead!') 

130 

131 if '.' in args.name: 

132 # Read from file: 

133 atoms = read(args.name) 

134 elif args.crystal_structure: 

135 atoms = build_bulk(args) 

136 else: 

137 atoms = build_molecule(args) 

138 

139 if args.magnetic_moment: 

140 magmoms = np.array( 

141 [float(m) for m in args.magnetic_moment.split(',')] 

142 ) 

143 atoms.set_initial_magnetic_moments( 

144 np.tile(magmoms, len(atoms) // len(magmoms)) 

145 ) 

146 

147 if args.modify: 

148 exec(args.modify, {'atoms': atoms}) 

149 

150 if args.repeat is not None: 

151 r = args.repeat.split(',') 

152 if len(r) == 1: 

153 r = 3 * r 

154 atoms = atoms.repeat([int(c) for c in r]) 

155 

156 if args.gui: 

157 view(atoms) 

158 

159 if args.output: 

160 write(args.output, atoms) 

161 elif sys.stdout.isatty(): 

162 write(args.name + '.json', atoms) 

163 else: 

164 con = connect(sys.stdout, type='json') 

165 con.write(atoms, name=args.name) 

166 

167 

168def build_molecule(args): 

169 from ase.atoms import Atoms 

170 from ase.build import molecule 

171 from ase.data import ( 

172 atomic_numbers, 

173 covalent_radii, 

174 ground_state_magnetic_moments, 

175 ) 

176 from ase.symbols import string2symbols 

177 

178 try: 

179 # Known molecule or atom? 

180 atoms = molecule(args.name) 

181 except (NotImplementedError, KeyError): 

182 symbols = string2symbols(args.name) 

183 if len(symbols) == 1: 

184 Z = atomic_numbers[symbols[0]] 

185 magmom = ground_state_magnetic_moments[Z] 

186 atoms = Atoms(args.name, magmoms=[magmom]) 

187 elif len(symbols) == 2: 

188 # Dimer 

189 if args.bond_length is None: 

190 b = ( 

191 covalent_radii[atomic_numbers[symbols[0]]] 

192 + covalent_radii[atomic_numbers[symbols[1]]] 

193 ) 

194 else: 

195 b = args.bond_length 

196 atoms = Atoms(args.name, positions=[(0, 0, 0), (b, 0, 0)]) 

197 else: 

198 raise ValueError('Unknown molecule: ' + args.name) 

199 else: 

200 if len(atoms) == 2 and args.bond_length is not None: 

201 atoms.set_distance(0, 1, args.bond_length) 

202 

203 if args.unit_cell is None: 

204 if args.vacuum: 

205 atoms.center(vacuum=args.vacuum) 

206 else: 

207 atoms.center(about=[0, 0, 0]) 

208 else: 

209 a = [float(x) for x in args.unit_cell.split(',')] 

210 if len(a) == 1: 

211 cell = [a[0], a[0], a[0]] 

212 elif len(a) == 3: 

213 cell = a 

214 else: 

215 a, b, c, alpha, beta, gamma = a 

216 degree = np.pi / 180.0 

217 cosa = np.cos(alpha * degree) 

218 cosb = np.cos(beta * degree) 

219 sinb = np.sin(beta * degree) 

220 cosg = np.cos(gamma * degree) 

221 sing = np.sin(gamma * degree) 

222 cell = [ 

223 [a, 0, 0], 

224 [b * cosg, b * sing, 0], 

225 [ 

226 c * cosb, 

227 c * (cosa - cosb * cosg) / sing, 

228 c * np.sqrt(sinb**2 - ((cosa - cosb * cosg) / sing) ** 2), 

229 ], 

230 ] 

231 atoms.cell = cell 

232 atoms.center() 

233 

234 atoms.pbc = args.periodic 

235 

236 return atoms 

237 

238 

239def build_bulk(args): 

240 from ase.build import bulk 

241 

242 L = args.lattice_constant.replace(',', ' ').split() 

243 d = {key: float(x) for key, x in zip('ac', L)} 

244 atoms = bulk( 

245 args.name, 

246 crystalstructure=args.crystal_structure, 

247 a=d.get('a'), 

248 c=d.get('c'), 

249 orthorhombic=args.orthorhombic, 

250 cubic=args.cubic, 

251 ) 

252 

253 M, X = {'Fe': (2.3, 'bcc'), 'Co': (1.2, 'hcp'), 'Ni': (0.6, 'fcc')}.get( 

254 args.name, (None, None) 

255 ) 

256 if M is not None and args.crystal_structure == X: 

257 atoms.set_initial_magnetic_moments([M] * len(atoms)) 

258 

259 return atoms