Coverage for ase/calculators/demon/demon.py: 42.55%

369 statements  

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

1"""This module defines an ASE interface to deMon. 

2 

3http://www.demon-software.com 

4 

5""" 

6 

7import os 

8import os.path as op 

9import shutil 

10import subprocess 

11 

12import numpy as np 

13 

14import ase.data 

15import ase.io 

16from ase.calculators.calculator import ( 

17 CalculatorSetupError, 

18 FileIOCalculator, 

19 Parameters, 

20 ReadError, 

21 all_changes, 

22 equal, 

23) 

24from ase.units import Bohr, Hartree 

25 

26from .demon_io import parse_xray 

27 

28m_e_to_amu = 1822.88839 

29 

30 

31class Parameters_deMon(Parameters): 

32 """Parameters class for the calculator. 

33 Documented in Base_deMon.__init__ 

34 

35 The options here are the most important ones that the user needs to be 

36 aware of. Further options accepted by deMon can be set in the dictionary 

37 input_arguments. 

38 

39 """ 

40 

41 def __init__( 

42 self, 

43 label='rundir', 

44 atoms=None, 

45 restart=None, 

46 basis_path=None, 

47 ignore_bad_restart_file=FileIOCalculator._deprecated, 

48 deMon_restart_path='.', 

49 title='deMon input file', 

50 scftype='RKS', 

51 forces=False, 

52 dipole=False, 

53 xc='VWN', 

54 guess='TB', 

55 print_out='MOE', 

56 basis=None, 

57 ecps=None, 

58 mcps=None, 

59 auxis=None, 

60 augment=None, 

61 input_arguments=None, 

62 ): 

63 if augment is None: 

64 augment = {} 

65 if auxis is None: 

66 auxis = {} 

67 if mcps is None: 

68 mcps = {} 

69 if ecps is None: 

70 ecps = {} 

71 if basis is None: 

72 basis = {} 

73 kwargs = locals() 

74 kwargs.pop('self') 

75 Parameters.__init__(self, **kwargs) 

76 

77 

78class Demon(FileIOCalculator): 

79 """Calculator interface to the deMon code.""" 

80 

81 implemented_properties = ['energy', 'forces', 'dipole', 'eigenvalues'] 

82 

83 def __init__(self, *, command=None, **kwargs): 

84 """ASE interface to the deMon code. 

85 

86 The deMon2k code can be obtained from http://www.demon-software.com 

87 

88 The DEMON_COMMAND environment variable must be set to run the 

89 executable, in bash it would be set along the lines of 

90 export DEMON_COMMAND="deMon.4.3.6.std > deMon_ase.out 2>&1" 

91 

92 Parameters 

93 ---------- 

94 

95 label : str 

96 relative path to the run directory 

97 atoms : Atoms object 

98 the atoms object 

99 command : str 

100 Command to run deMon. If not present the environment 

101 variable DEMON_COMMAND will be used 

102 restart : str 

103 Relative path to ASE restart directory for parameters and 

104 atoms object and results 

105 basis_path : str 

106 Relative path to the directory containing 

107 BASIS, AUXIS, ECPS, MCPS and AUGMENT 

108 ignore_bad_restart_file : bool 

109 Ignore broken or missing ASE restart files 

110 By default, it is an error if the restart 

111 file is missing or broken. 

112 deMon_restart_path : str 

113 Relative path to the deMon restart dir 

114 title : str 

115 Title in the deMon input file. 

116 scftype : str 

117 Type of scf 

118 forces : bool 

119 If True a force calculation will be enforced. 

120 dipole : bool 

121 If True a dipole calculation will be enforced 

122 xc : str 

123 xc-functional 

124 guess : str 

125 guess for initial density and wave functions 

126 print_out : str | list 

127 Options for the printing in deMon 

128 basis : dict 

129 Definition of basis sets. 

130 ecps : dict 

131 Definition of ECPs 

132 mcps : dict 

133 Definition of MCPs 

134 auxis : dict 

135 Definition of AUXIS 

136 augment : dict 

137 Definition of AUGMENT 

138 input_arguments : dict 

139 Explicitly given input arguments. The key is the input keyword 

140 and the value is either a str, a list of str (will be written 

141 on the same line as the keyword), 

142 or a list of lists of str (first list is written on the first 

143 line, the others on following lines.) 

144 

145 For example usage, see the tests h2o.py and h2o_xas_xes.py in 

146 the directory ase/test/demon 

147 

148 """ 

149 

150 parameters = Parameters_deMon(**kwargs) 

151 

152 # Setup the run command 

153 if command is None: 

154 command = self.cfg.get('DEMON_COMMAND') 

155 

156 FileIOCalculator.__init__(self, command=command, **parameters) 

157 

158 def __getitem__(self, key): 

159 """Convenience method to retrieve a parameter as 

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

161 

162 Parameters 

163 ---------- 

164 key : str, the name of the parameters to get. 

165 """ 

166 return self.parameters[key] 

167 

168 def set(self, **kwargs): 

169 """Set all parameters. 

170 

171 Parameters 

172 ---------- 

173 kwargs : Dictionary containing the keywords for deMon 

174 """ 

175 # Put in the default arguments. 

176 kwargs = self.default_parameters.__class__(**kwargs) 

177 

178 if 'parameters' in kwargs: 

179 filename = kwargs.pop('parameters') 

180 parameters = Parameters.read(filename) 

181 parameters.update(kwargs) 

182 kwargs = parameters 

183 

184 changed_parameters = {} 

185 

186 for key, value in kwargs.items(): 

187 oldvalue = self.parameters.get(key) 

188 if key not in self.parameters or not equal(value, oldvalue): 

189 changed_parameters[key] = value 

190 self.parameters[key] = value 

191 

192 return changed_parameters 

193 

194 def link_file(self, fromdir, todir, filename): 

195 if op.exists(todir + '/' + filename): 

196 os.remove(todir + '/' + filename) 

197 

198 if op.exists(fromdir + '/' + filename): 

199 os.symlink(fromdir + '/' + filename, todir + '/' + filename) 

200 else: 

201 raise RuntimeError( 

202 "{} doesn't exist".format(fromdir + '/' + filename) 

203 ) 

204 

205 def calculate( 

206 self, atoms=None, properties=None, system_changes=all_changes 

207 ): 

208 """Capture the RuntimeError from FileIOCalculator.calculate 

209 and add a little debug information from the deMon output. 

210 

211 See base FileIocalculator for documentation. 

212 """ 

213 

214 if properties is None: 

215 properties = ['energy'] 

216 if atoms is not None: 

217 self.atoms = atoms.copy() 

218 

219 self.write_input(self.atoms, properties, system_changes) 

220 command = self.command 

221 

222 # basis path 

223 basis_path = self.parameters['basis_path'] 

224 if basis_path is None: 

225 basis_path = self.cfg.get('DEMON_BASIS_PATH') 

226 

227 if basis_path is None: 

228 raise RuntimeError( 

229 'Please set basis_path keyword,' 

230 + ' or the DEMON_BASIS_PATH' 

231 + ' environment variable' 

232 ) 

233 

234 # link restart file 

235 value = self.parameters['guess'] 

236 if value.upper() == 'RESTART': 

237 value2 = self.parameters['deMon_restart_path'] 

238 

239 if op.exists(self.directory + '/deMon.rst') or op.islink( 

240 self.directory + '/deMon.rst' 

241 ): 

242 os.remove(self.directory + '/deMon.rst') 

243 abspath = op.abspath(value2) 

244 

245 if op.exists(abspath + '/deMon.mem') or op.islink( 

246 abspath + '/deMon.mem' 

247 ): 

248 shutil.copy( 

249 abspath + '/deMon.mem', self.directory + '/deMon.rst' 

250 ) 

251 else: 

252 raise RuntimeError( 

253 "{} doesn't exist".format(abspath + '/deMon.rst') 

254 ) 

255 

256 abspath = op.abspath(basis_path) 

257 

258 for name in ['BASIS', 'AUXIS', 'ECPS', 'MCPS', 'FFDS']: 

259 self.link_file(abspath, self.directory, name) 

260 

261 if command is None: 

262 raise CalculatorSetupError 

263 subprocess.check_call(command, shell=True, cwd=self.directory) 

264 

265 try: 

266 self.read_results() 

267 except Exception: # XXX Which kind of exception? 

268 with open(self.directory + '/deMon.out') as fd: 

269 lines = fd.readlines() 

270 debug_lines = 10 

271 print('##### %d last lines of the deMon.out' % debug_lines) 

272 for line in lines[-20:]: 

273 print(line.strip()) 

274 print('##### end of deMon.out') 

275 raise RuntimeError 

276 

277 def set_label(self, label): 

278 """Set label directory""" 

279 

280 self.label = label 

281 

282 # in our case self.directory = self.label 

283 self.directory = self.label 

284 if self.directory == '': 

285 self.directory = os.curdir 

286 

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

288 """Write input (in)-file. 

289 See calculator.py for further details. 

290 

291 Parameters 

292 ---------- 

293 atoms : The Atoms object to write. 

294 properties : The properties which should be calculated. 

295 system_changes : List of properties changed since last run. 

296 

297 """ 

298 # Call base calculator. 

299 FileIOCalculator.write_input( 

300 self, 

301 atoms=atoms, 

302 properties=properties, 

303 system_changes=system_changes, 

304 ) 

305 

306 if system_changes is None and properties is None: 

307 return 

308 

309 filename = f'{self.directory}/deMon.inp' 

310 

311 add_print = '' 

312 

313 # Start writing the file. 

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

315 # write keyword argument keywords 

316 value = self.parameters['title'] 

317 self._write_argument('TITLE', value, fd) 

318 

319 fd.write('#\n') 

320 

321 value = self.parameters['scftype'] 

322 self._write_argument('SCFTYPE', value, fd) 

323 

324 value = self.parameters['xc'] 

325 self._write_argument('VXCTYPE', value, fd) 

326 

327 value = self.parameters['guess'] 

328 self._write_argument('GUESS', value, fd) 

329 

330 # obtain forces through a single BOMD step 

331 # only if forces is in properties, or if keyword forces is True 

332 value = self.parameters['forces'] 

333 if 'forces' in properties or value: 

334 self._write_argument( 

335 'DYNAMICS', ['INT=1', 'MAX=0', 'STEP=0'], fd 

336 ) 

337 self._write_argument('TRAJECTORY', 'FORCES', fd) 

338 self._write_argument('VELOCITIES', 'ZERO', fd) 

339 add_print = add_print + ' ' + 'MD OPT' 

340 

341 # if dipole is True, enforce dipole calculation. 

342 # Otherwise only if asked for 

343 value = self.parameters['dipole'] 

344 if 'dipole' in properties or value: 

345 self._write_argument('DIPOLE', '', fd) 

346 

347 # print argument, here other options could change this 

348 value = self.parameters['print_out'] 

349 assert isinstance(value, str) 

350 value = value + add_print 

351 

352 if len(value) != 0: 

353 self._write_argument('PRINT', value, fd) 

354 fd.write('#\n') 

355 

356 # write general input arguments 

357 self._write_input_arguments(fd) 

358 

359 fd.write('#\n') 

360 

361 # write basis set, ecps, mcps, auxis, augment 

362 basis = self.parameters['basis'] 

363 if 'all' not in basis: 

364 basis['all'] = 'DZVP' 

365 self._write_basis(fd, atoms, basis, string='BASIS') 

366 

367 ecps = self.parameters['ecps'] 

368 if len(ecps) != 0: 

369 self._write_basis(fd, atoms, ecps, string='ECPS') 

370 

371 mcps = self.parameters['mcps'] 

372 if len(mcps) != 0: 

373 self._write_basis(fd, atoms, mcps, string='MCPS') 

374 

375 auxis = self.parameters['auxis'] 

376 if len(auxis) != 0: 

377 self._write_basis(fd, atoms, auxis, string='AUXIS') 

378 

379 augment = self.parameters['augment'] 

380 if len(augment) != 0: 

381 self._write_basis(fd, atoms, augment, string='AUGMENT') 

382 

383 # write geometry 

384 self._write_atomic_coordinates(fd, atoms) 

385 

386 # write xyz file for good measure. 

387 ase.io.write(f'{self.directory}/deMon_atoms.xyz', self.atoms) 

388 

389 def read(self, restart_path): 

390 """Read parameters from directory restart_path.""" 

391 

392 self.set_label(restart_path) 

393 

394 if not op.exists(restart_path + '/deMon.inp'): 

395 raise ReadError( 

396 'The restart_path file {} does not exist'.format(restart_path) 

397 ) 

398 

399 self.atoms = self.deMon_inp_to_atoms(restart_path + '/deMon.inp') 

400 

401 self.read_results() 

402 

403 def _write_input_arguments(self, fd): 

404 """Write directly given input-arguments.""" 

405 input_arguments = self.parameters['input_arguments'] 

406 

407 # Early return 

408 if input_arguments is None: 

409 return 

410 

411 for key, value in input_arguments.items(): 

412 self._write_argument(key, value, fd) 

413 

414 def _write_argument(self, key, value, fd): 

415 """Write an argument to file. 

416 key : a string coresponding to the input keyword 

417 value : the arguments, can be a string, a number or a list 

418 f : and open file 

419 """ 

420 

421 # for only one argument, write on same line 

422 if not isinstance(value, (tuple, list)): 

423 line = key.upper() 

424 line += ' ' + str(value).upper() 

425 fd.write(line) 

426 fd.write('\n') 

427 

428 # for a list, write first argument on the first line, 

429 # then the rest on new lines 

430 else: 

431 line = key 

432 if not isinstance(value[0], (tuple, list)): 

433 for i in range(len(value)): 

434 line += ' ' + str(value[i].upper()) 

435 fd.write(line) 

436 fd.write('\n') 

437 else: 

438 for i in range(len(value)): 

439 for j in range(len(value[i])): 

440 line += ' ' + str(value[i][j]).upper() 

441 fd.write(line) 

442 fd.write('\n') 

443 line = '' 

444 

445 def _write_atomic_coordinates(self, fd, atoms): 

446 """Write atomic coordinates. 

447 

448 Parameters 

449 ---------- 

450 - f: An open file object. 

451 - atoms: An atoms object. 

452 """ 

453 

454 fd.write('#\n') 

455 fd.write('# Atomic coordinates\n') 

456 fd.write('#\n') 

457 fd.write('GEOMETRY CARTESIAN ANGSTROM\n') 

458 

459 for i in range(len(atoms)): 

460 xyz = atoms.get_positions()[i] 

461 chem_symbol = atoms.get_chemical_symbols()[i] 

462 chem_symbol += str(i + 1) 

463 

464 # if tag is set to 1 then we have a ghost atom, 

465 # set nuclear charge to 0 

466 if atoms.get_tags()[i] == 1: 

467 nuc_charge = str(0) 

468 else: 

469 nuc_charge = str(atoms.get_atomic_numbers()[i]) 

470 

471 mass = atoms.get_masses()[i] 

472 

473 line = f'{chem_symbol:6s}'.rjust(10) + ' ' 

474 line += f'{xyz[0]:.5f}'.rjust(10) + ' ' 

475 line += f'{xyz[1]:.5f}'.rjust(10) + ' ' 

476 line += f'{xyz[2]:.5f}'.rjust(10) + ' ' 

477 line += f'{nuc_charge:5s}'.rjust(10) + ' ' 

478 line += f'{mass:.5f}'.rjust(10) + ' ' 

479 

480 fd.write(line) 

481 fd.write('\n') 

482 

483 # routine to write basis set inormation, including ecps and auxis 

484 def _write_basis(self, fd, atoms, basis=None, string='BASIS'): 

485 """Write basis set, ECPs, AUXIS, or AUGMENT basis 

486 

487 Parameters 

488 ---------- 

489 - f: An open file object. 

490 - atoms: An atoms object. 

491 - basis: A dictionary specifying the basis set 

492 - string: 'BASIS', 'ECP','AUXIS' or 'AUGMENT' 

493 """ 

494 

495 # basis for all atoms 

496 if basis is None: 

497 basis = {} 

498 line = f'{string}'.ljust(10) 

499 

500 if 'all' in basis: 

501 default_basis = basis['all'] 

502 line += f'({default_basis})'.rjust(16) 

503 

504 fd.write(line) 

505 fd.write('\n') 

506 

507 # basis for all atomic species 

508 chemical_symbols = atoms.get_chemical_symbols() 

509 chemical_symbols_set = set(chemical_symbols) 

510 

511 for _ in range(chemical_symbols_set.__len__()): 

512 symbol = chemical_symbols_set.pop() 

513 

514 if symbol in basis: 

515 line = f'{symbol}'.ljust(10) 

516 line += f'({basis[symbol]})'.rjust(16) 

517 fd.write(line) 

518 fd.write('\n') 

519 

520 # basis for individual atoms 

521 for i in range(len(atoms)): 

522 if i in basis: 

523 symbol = str(chemical_symbols[i]) 

524 symbol += str(i + 1) 

525 

526 line = f'{symbol}'.ljust(10) 

527 line += f'({basis[i]})'.rjust(16) 

528 fd.write(line) 

529 fd.write('\n') 

530 

531 # Analysis routines 

532 def read_results(self): 

533 """Read the results from output files.""" 

534 self.read_energy() 

535 self.read_forces(self.atoms) 

536 self.read_eigenvalues() 

537 self.read_dipole() 

538 self.read_xray() 

539 

540 def read_energy(self): 

541 """Read energy from deMon's text-output file.""" 

542 with open(self.label + '/deMon.out') as fd: 

543 text = fd.read().upper() 

544 

545 lines = iter(text.split('\n')) 

546 

547 for line in lines: 

548 if line.startswith(' TOTAL ENERGY ='): 

549 self.results['energy'] = float(line.split()[-1]) * Hartree 

550 break 

551 else: 

552 raise RuntimeError 

553 

554 def read_forces(self, atoms): 

555 """Read the forces from the deMon.out file.""" 

556 

557 natoms = len(atoms) 

558 filename = self.label + '/deMon.out' 

559 

560 if op.isfile(filename): 

561 with open(filename) as fd: 

562 lines = fd.readlines() 

563 

564 # find line where the orbitals start 

565 flag_found = False 

566 for i in range(len(lines)): 

567 if lines[i].rfind('GRADIENTS OF TIME STEP 0 IN A.U.') > -1: 

568 start = i + 4 

569 flag_found = True 

570 break 

571 

572 if flag_found: 

573 self.results['forces'] = np.zeros((natoms, 3), float) 

574 for i in range(natoms): 

575 line = [ 

576 s 

577 for s in lines[i + start].strip().split(' ') 

578 if len(s) > 0 

579 ] 

580 f = -np.array([float(x) for x in line[2:5]]) 

581 self.results['forces'][i, :] = f * (Hartree / Bohr) 

582 

583 def read_eigenvalues(self): 

584 """Read eigenvalues from the 'deMon.out' file.""" 

585 assert os.access(self.label + '/deMon.out', os.F_OK) 

586 

587 # Read eigenvalues 

588 with open(self.label + '/deMon.out') as fd: 

589 lines = fd.readlines() 

590 

591 # try PRINT MOE 

592 eig_alpha, occ_alpha = self.read_eigenvalues_one_spin( 

593 lines, 'ALPHA MO ENERGIES', 6 

594 ) 

595 eig_beta, occ_beta = self.read_eigenvalues_one_spin( 

596 lines, 'BETA MO ENERGIES', 6 

597 ) 

598 

599 # otherwise try PRINT MOS 

600 if len(eig_alpha) == 0 and len(eig_beta) == 0: 

601 eig_alpha, occ_alpha = self.read_eigenvalues_one_spin( 

602 lines, 'ALPHA MO COEFFICIENTS', 5 

603 ) 

604 eig_beta, occ_beta = self.read_eigenvalues_one_spin( 

605 lines, 'BETA MO COEFFICIENTS', 5 

606 ) 

607 

608 self.results['eigenvalues'] = np.array([eig_alpha, eig_beta]) * Hartree 

609 self.results['occupations'] = np.array([occ_alpha, occ_beta]) 

610 

611 def read_eigenvalues_one_spin(self, lines, string, neigs_per_line): 

612 """Utility method for retreiving eigenvalues after the string "string" 

613 with neigs_per_line eigenvlaues written per line 

614 """ 

615 eig = [] 

616 occ = [] 

617 

618 skip_line = False 

619 more_eigs = False 

620 

621 # find line where the orbitals start 

622 for i in range(len(lines)): 

623 if lines[i].rfind(string) > -1: 

624 ii = i 

625 more_eigs = True 

626 break 

627 

628 while more_eigs: 

629 # search for two empty lines in a row preceding a line with 

630 # numbers 

631 for i in range(ii + 1, len(lines)): 

632 if ( 

633 len(lines[i].split()) == 0 

634 and len(lines[i + 1].split()) == 0 

635 and len(lines[i + 2].split()) > 0 

636 ): 

637 ii = i + 2 

638 break 

639 

640 # read eigenvalues, occupations 

641 line = lines[ii].split() 

642 if len(line) < neigs_per_line: 

643 # last row 

644 more_eigs = False 

645 if line[0] != str(len(eig) + 1): 

646 more_eigs = False 

647 skip_line = True 

648 

649 if not skip_line: 

650 line = lines[ii + 1].split() 

651 for l in line: 

652 eig.append(float(l)) 

653 line = lines[ii + 3].split() 

654 for l in line: 

655 occ.append(float(l)) 

656 ii = ii + 3 

657 

658 return eig, occ 

659 

660 def read_dipole(self): 

661 """Read dipole moment.""" 

662 dipole = np.zeros(3) 

663 with open(self.label + '/deMon.out') as fd: 

664 lines = fd.readlines() 

665 

666 for i in range(len(lines)): 

667 if ( 

668 lines[i].rfind('DIPOLE') > -1 

669 and lines[i].rfind('XAS') == -1 

670 ): 

671 dipole[0] = float(lines[i + 1].split()[3]) 

672 dipole[1] = float(lines[i + 2].split()[3]) 

673 dipole[2] = float(lines[i + 3].split()[3]) 

674 

675 # debye to e*Ang 

676 self.results['dipole'] = dipole * 0.2081943482534 

677 

678 break 

679 

680 def read_xray(self): 

681 """Read deMon.xry if present.""" 

682 

683 # try to read core IP from, .out file 

684 filename = self.label + '/deMon.out' 

685 core_IP = None 

686 if op.isfile(filename): 

687 with open(filename) as fd: 

688 lines = fd.readlines() 

689 

690 for i in range(len(lines)): 

691 if lines[i].rfind('IONIZATION POTENTIAL') > -1: 

692 core_IP = float(lines[i].split()[3]) 

693 

694 try: 

695 mode, ntrans, E_trans, osc_strength, trans_dip = parse_xray( 

696 self.label + '/deMon.xry' 

697 ) 

698 except ReadError: 

699 pass 

700 else: 

701 xray_results = { 

702 'xray_mode': mode, 

703 'ntrans': ntrans, 

704 'E_trans': E_trans, 

705 'osc_strength': osc_strength, # units? 

706 'trans_dip': trans_dip, # units? 

707 'core_IP': core_IP, 

708 } 

709 

710 self.results['xray'] = xray_results 

711 

712 def deMon_inp_to_atoms(self, filename): 

713 """Routine to read deMon.inp and convert it to an atoms object.""" 

714 

715 with open(filename) as fd: 

716 lines = fd.readlines() 

717 

718 # find line where geometry starts 

719 for i in range(len(lines)): 

720 if lines[i].rfind('GEOMETRY') > -1: 

721 if lines[i].rfind('ANGSTROM'): 

722 coord_units = 'Ang' 

723 elif lines.rfind('Bohr'): 

724 coord_units = 'Bohr' 

725 ii = i 

726 break 

727 

728 chemical_symbols = [] 

729 xyz = [] 

730 atomic_numbers = [] 

731 masses = [] 

732 

733 for i in range(ii + 1, len(lines)): 

734 try: 

735 line = lines[i].split() 

736 

737 if len(line) > 0: 

738 for symbol in ase.data.chemical_symbols: 

739 found = None 

740 if line[0].upper().rfind(symbol.upper()) > -1: 

741 found = symbol 

742 break 

743 

744 if found is not None: 

745 chemical_symbols.append(found) 

746 else: 

747 break 

748 

749 xyz.append( 

750 [float(line[1]), float(line[2]), float(line[3])] 

751 ) 

752 

753 if len(line) > 4: 

754 atomic_numbers.append(int(line[4])) 

755 

756 if len(line) > 5: 

757 masses.append(float(line[5])) 

758 

759 except Exception: # XXX Which kind of exception? 

760 raise RuntimeError 

761 

762 if coord_units == 'Bohr': 

763 xyz *= Bohr 

764 

765 natoms = len(chemical_symbols) 

766 

767 # set atoms object 

768 atoms = ase.Atoms(symbols=chemical_symbols, positions=xyz) 

769 

770 # if atomic numbers were read in, set them 

771 if len(atomic_numbers) == natoms: 

772 atoms.set_atomic_numbers(atomic_numbers) 

773 

774 # if masses were read in, set them 

775 if len(masses) == natoms: 

776 atoms.set_masses(masses) 

777 

778 return atoms