Coverage for ase/calculators/openmx/openmx.py: 27.09%

454 statements  

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

1""" 

2The ASE Calculator for OpenMX <https://www.openmx-square.org> 

3A Python interface to the software package for nano-scale 

4material simulations based on density functional theories. 

5Copyright (C) 2017 Charles Thomas Johnson, Jae Hwan Shim and JaeJun Yu 

6 

7This program is free software: you can redistribute it and/or modify 

8it under the terms of the GNU Lesser General Public License as published by 

9the Free Software Foundation, either version 2.1 of the License, or 

10(at your option) any later version. 

11 

12This program is distributed in the hope that it will be useful, 

13but WITHOUT ANY WARRANTY; without even the implied warranty of 

14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

15GNU Lesser General Public License for more details. 

16 

17You should have received a copy of the GNU Lesser General Public License 

18along with ASE. If not, see <https://www.gnu.org/licenses/>. 

19 

20""" 

21 

22import os 

23import re 

24import subprocess 

25import time 

26import warnings 

27 

28import numpy as np 

29 

30from ase.calculators.calculator import ( 

31 Calculator, 

32 FileIOCalculator, 

33 all_changes, 

34 equal, 

35 kptdensity2monkhorstpack, 

36) 

37from ase.calculators.openmx.default_settings import default_dictionary 

38from ase.calculators.openmx.parameters import OpenMXParameters 

39from ase.calculators.openmx.reader import get_file_name, read_openmx 

40from ase.calculators.openmx.writer import write_openmx 

41from ase.config import cfg 

42from ase.geometry import cell_to_cellpar 

43 

44 

45def parse_omx_version(txt): 

46 """Parse version number from stdout header.""" 

47 match = re.search(r'Welcome to OpenMX\s+Ver\.\s+(\S+)', txt, re.M) 

48 return match.group(1) 

49 

50 

51class OpenMX(FileIOCalculator): 

52 """ 

53 Calculator interface to the OpenMX code. 

54 """ 

55 

56 implemented_properties = [ 

57 'free_energy', # Same value with energy 

58 'energy', 

59 'energies', 

60 'forces', 

61 'stress', 

62 'dipole', 

63 'chemical_potential', 

64 'magmom', 

65 'magmoms', 

66 'eigenvalues', 

67 ] 

68 

69 default_parameters = OpenMXParameters() 

70 

71 default_pbs = { 

72 'processes': 1, 

73 'walltime': '10:00:00', 

74 'threads': 1, 

75 'nodes': 1, 

76 } 

77 

78 default_mpi = {'processes': 1, 'threads': 1} 

79 

80 default_output_setting = {'nohup': True, 'debug': False} 

81 

82 def __init__( 

83 self, 

84 restart=None, 

85 ignore_bad_restart_file=FileIOCalculator._deprecated, 

86 label='./openmx', 

87 atoms=None, 

88 command=None, 

89 mpi=None, 

90 pbs=None, 

91 **kwargs, 

92 ): 

93 

94 # Initialize and put the default parameters. 

95 self.initialize_pbs(pbs) 

96 self.initialize_mpi(mpi) 

97 self.initialize_output_setting(**kwargs) 

98 

99 FileIOCalculator.__init__( 

100 self, 

101 restart, 

102 ignore_bad_restart_file, 

103 label, 

104 atoms, 

105 command, 

106 **kwargs, 

107 ) 

108 

109 def __getitem__(self, key): 

110 """Convenience method to retrieve a parameter as 

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

112 

113 Parameters 

114 ---------- 

115 key : str 

116 Name of the parameters to get. 

117 """ 

118 return self.parameters[key] 

119 

120 def __setitem__(self, key, value): 

121 self.parameters[key] = value 

122 

123 def initialize_output_setting(self, **kwargs): 

124 output_setting = {} 

125 self.output_setting = dict(self.default_output_setting) 

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

127 if key in self.default_output_setting: 

128 output_setting[key] = value 

129 self.output_setting.update(output_setting) 

130 self.__dict__.update(self.output_setting) 

131 

132 def initialize_pbs(self, pbs): 

133 if pbs: 

134 self.pbs = dict(self.default_pbs) 

135 for key in pbs: 

136 if key not in self.default_pbs: 

137 allowed = ', '.join(list(self.default_pbs.keys())) 

138 raise TypeError( 

139 'Unexpected keyword "{}" in "pbs" ' 

140 'dictionary. Must be one of: {}'.format(key, allowed) 

141 ) 

142 # Put dictionary into python variable 

143 self.pbs.update(pbs) 

144 self.__dict__.update(self.pbs) 

145 else: 

146 self.pbs = None 

147 

148 def initialize_mpi(self, mpi): 

149 if mpi: 

150 self.mpi = dict(self.default_mpi) 

151 for key in mpi: 

152 if key not in self.default_mpi: 

153 allowed = ', '.join(list(self.default_mpi.keys())) 

154 raise TypeError( 

155 'Unexpected keyword "{}" in "mpi" ' 

156 'dictionary. Must be one of: {}'.format(key, allowed) 

157 ) 

158 # Put dictionary into python variable 

159 self.mpi.update(mpi) 

160 self.__dict__.update(self.mpi) 

161 else: 

162 self.mpi = None 

163 

164 def run(self): 

165 """Check Which Running method we r going to use and run it""" 

166 if self.pbs is not None: 

167 run = self.run_pbs 

168 elif self.mpi is not None: 

169 run = self.run_mpi 

170 else: 

171 run = self.run_openmx 

172 run() 

173 

174 def run_openmx(self): 

175 def isRunning(process=None): 

176 """Check mpi is running""" 

177 return process.poll() is None 

178 

179 runfile = get_file_name('.dat', self.label, absolute_directory=False) 

180 outfile = get_file_name('.log', self.label) 

181 olddir = os.getcwd() 

182 abs_dir = os.path.join(olddir, self.directory) 

183 try: 

184 os.chdir(abs_dir) 

185 if self.command is None: 

186 self.command = 'openmx' 

187 command = self.command + ' %s > %s' 

188 command = command % (runfile, outfile) 

189 self.prind(command) 

190 p = subprocess.Popen(command, shell=True, universal_newlines=True) 

191 self.print_file(file=outfile, running=isRunning, process=p) 

192 finally: 

193 os.chdir(olddir) 

194 self.prind('Calculation Finished') 

195 

196 def run_mpi(self): 

197 """ 

198 Run openmx using MPI method. If keyword `mpi` is declared, it will 

199 run. 

200 """ 

201 

202 def isRunning(process=None): 

203 """Check mpi is running""" 

204 return process.poll() is None 

205 

206 processes = self.processes 

207 threads = self.threads 

208 runfile = get_file_name('.dat', self.label, absolute_directory=False) 

209 outfile = get_file_name('.log', self.label) 

210 olddir = os.getcwd() 

211 abs_dir = os.path.join(olddir, self.directory) 

212 try: 

213 os.chdir(abs_dir) 

214 command = self.get_command(processes, threads, runfile, outfile) 

215 self.prind(command) 

216 p = subprocess.Popen(command, shell=True, universal_newlines=True) 

217 self.print_file(file=outfile, running=isRunning, process=p) 

218 finally: 

219 os.chdir(olddir) 

220 self.prind('Calculation Finished') 

221 

222 def run_pbs(self, prefix='test'): 

223 """ 

224 Execute the OpenMX using Plane Batch System. In order to use this, 

225 Your system should have Scheduler. PBS 

226 Basically, it does qsub. and wait until qstat signal shows c 

227 Super computer user 

228 """ 

229 nodes = self.nodes 

230 processes = self.processes 

231 

232 prefix = self.prefix 

233 olddir = os.getcwd() 

234 try: 

235 os.chdir(self.abs_directory) 

236 except AttributeError: 

237 os.chdir(self.directory) 

238 

239 def isRunning(jobNum=None, status='Q', qstat='qstat'): 

240 """ 

241 Check submitted job is still Running 

242 """ 

243 

244 def runCmd(exe): 

245 p = subprocess.Popen( 

246 exe, 

247 stdout=subprocess.PIPE, 

248 stderr=subprocess.STDOUT, 

249 universal_newlines=True, 

250 ) 

251 while True: 

252 line = p.stdout.readline() 

253 if line != '': 

254 # the real code does filtering here 

255 yield line.rstrip() 

256 else: 

257 break 

258 

259 jobs = runCmd('qstat') 

260 columns = None 

261 for line in jobs: 

262 if str(jobNum) in line: 

263 columns = line.split() 

264 self.prind(line) 

265 if columns is not None: 

266 return columns[-2] == status 

267 else: 

268 return False 

269 

270 inputfile = self.label + '.dat' 

271 outfile = self.label + '.log' 

272 

273 bashArgs = '#!/bin/bash \n cd $PBS_O_WORKDIR\n' 

274 jobName = prefix 

275 cmd = bashArgs + 'mpirun -hostfile $PBS_NODEFILE openmx {} > {}'.format( 

276 inputfile, outfile 

277 ) 

278 echoArgs = ['echo', f"$' {cmd}'"] 

279 qsubArgs = [ 

280 'qsub', 

281 '-N', 

282 jobName, 

283 '-l', 

284 'nodes=%d:ppn=%d' % (nodes, processes), 

285 '-l', 

286 'walltime=' + self.walltime, 

287 ] 

288 wholeCmd = ' '.join(echoArgs) + ' | ' + ' '.join(qsubArgs) 

289 self.prind(wholeCmd) 

290 out = subprocess.Popen( 

291 wholeCmd, 

292 shell=True, 

293 stdout=subprocess.PIPE, 

294 universal_newlines=True, 

295 ) 

296 out = out.communicate()[0] 

297 jobNum = int(re.match(r'(\d+)', out.split()[0]).group(1)) 

298 

299 self.prind( 

300 'Queue number is ' 

301 + str(jobNum) 

302 + '\nWaiting for the Queue to start' 

303 ) 

304 while isRunning(jobNum, status='Q'): 

305 time.sleep(5) 

306 self.prind('.') 

307 self.prind('Start Calculating') 

308 self.print_file( 

309 file=outfile, 

310 running=isRunning, 

311 jobNum=jobNum, 

312 status='R', 

313 qstat='qstat', 

314 ) 

315 

316 os.chdir(olddir) 

317 self.prind('Calculation Finished!') 

318 return jobNum 

319 

320 def clean(self, prefix='test', queue_num=None): 

321 """Method which cleans up after a calculation. 

322 

323 The default files generated OpenMX will be deleted IF this 

324 method is called. 

325 

326 """ 

327 self.prind('Cleaning Data') 

328 fileName = get_file_name('', self.label) 

329 pbs_Name = get_file_name('', self.label) 

330 files = [ 

331 # prefix+'.out',#prefix+'.dat',#prefix+'.BAND*', 

332 fileName + '.cif', 

333 fileName + '.dden.cube', 

334 fileName + '.ene', 

335 fileName + '.md', 

336 fileName + '.md2', 

337 fileName + '.tden.cube', 

338 fileName + '.sden.cube', 

339 fileName + '.v0.cube', 

340 fileName + '.v1.cube', 

341 fileName + '.vhart.cube', 

342 fileName + '.den0.cube', 

343 fileName + '.bulk.xyz', 

344 fileName + '.den1.cube', 

345 fileName + '.xyz', 

346 pbs_Name + '.o' + str(queue_num), 

347 pbs_Name + '.e' + str(queue_num), 

348 ] 

349 for f in files: 

350 try: 

351 self.prind('Removing' + f) 

352 os.remove(f) 

353 except OSError: 

354 self.prind('There is no such file named ' + f) 

355 

356 def calculate( 

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

358 ): 

359 """ 

360 Capture the RuntimeError from FileIOCalculator.calculate 

361 and add a little debug information from the OpenMX output. 

362 See base FileIOCalculator for documentation. 

363 """ 

364 if self.parameters.data_path is None: 

365 if 'OPENMX_DFT_DATA_PATH' not in cfg: 

366 warnings.warn( 

367 'Please either set OPENMX_DFT_DATA_PATH as an' 

368 'enviroment variable or specify "data_path" as' 

369 'a keyword argument' 

370 ) 

371 

372 self.prind('Start Calculation') 

373 if properties is None: 

374 properties = self.implemented_properties 

375 try: 

376 Calculator.calculate(self, atoms, properties, system_changes) 

377 self.write_input( 

378 atoms=self.atoms, 

379 parameters=self.parameters, 

380 properties=properties, 

381 system_changes=system_changes, 

382 ) 

383 self.print_input(debug=self.debug, nohup=self.nohup) 

384 self.run() 

385 # self.read_results() 

386 self.version = self.read_version() 

387 output_atoms = read_openmx(filename=self.label, debug=self.debug) 

388 self.output_atoms = output_atoms 

389 # XXX The parameters are supposedly inputs, so it is dangerous 

390 # to update them from the outputs. --askhl 

391 self.parameters.update(output_atoms.calc.parameters) 

392 self.results = output_atoms.calc.results 

393 # self.clean() 

394 except RuntimeError as e: 

395 try: 

396 with open(get_file_name('.log')) as fd: 

397 lines = fd.readlines() 

398 debug_lines = 10 

399 print('##### %d last lines of the OpenMX output' % debug_lines) 

400 for line in lines[-20:]: 

401 print(line.strip()) 

402 print('##### end of openMX output') 

403 raise e 

404 except RuntimeError as e: 

405 raise e 

406 

407 def write_input( 

408 self, atoms=None, parameters=None, properties=None, system_changes=None 

409 ): 

410 """Write input (dat)-file. 

411 See calculator.py for further details. 

412 

413 Parameters 

414 ---------- 

415 atoms : :class:`~ase.Atoms` 

416 ASE :class:`~ase.Atoms` object to write. 

417 properties : list[str] 

418 Properties which should be calculated. 

419 system_changes : list[str] 

420 Properties changed since last run. 

421 """ 

422 # Call base calculator. 

423 if system_changes is None: 

424 system_changes = [] 

425 if properties is None: 

426 properties = [] 

427 if atoms is None: 

428 atoms = self.atoms 

429 FileIOCalculator.write_input(self, atoms, properties, system_changes) 

430 write_openmx( 

431 label=self.label, 

432 atoms=atoms, 

433 parameters=self.parameters, 

434 properties=properties, 

435 system_changes=system_changes, 

436 ) 

437 

438 def print_input(self, debug=None, nohup=None): 

439 """ 

440 For a debugging purpose, print the .dat file 

441 """ 

442 if debug is None: 

443 debug = self.debug 

444 if nohup is None: 

445 nohup = self.nohup 

446 self.prind('Reading input file' + self.label) 

447 filename = get_file_name('.dat', self.label) 

448 if not nohup: 

449 with open(filename) as fd: 

450 while True: 

451 line = fd.readline() 

452 print(line.strip()) 

453 if not line: 

454 break 

455 

456 def read(self, label): 

457 self.parameters = {} 

458 self.set_label(label) 

459 if label[-5:] in ['.dat', '.out', '.log']: 

460 label = label[:-4] 

461 atoms = read_openmx(filename=label, debug=self.debug) 

462 self.update_atoms(atoms) 

463 self.parameters.update(atoms.calc.parameters) 

464 self.results = atoms.calc.results 

465 self.parameters['restart'] = self.label 

466 self.parameters['label'] = label 

467 

468 def read_version(self, label=None): 

469 version = None 

470 if label is None: 

471 label = self.label 

472 for line in open(get_file_name('.log', label)): 

473 if line.find('Ver.') != -1: 

474 version = line.split()[-1] 

475 break 

476 return version 

477 

478 def update_atoms(self, atoms): 

479 self.atoms = atoms.copy() 

480 

481 def set(self, **kwargs): 

482 """Set all parameters. 

483 

484 Parameters 

485 ---------- 

486 kwargs : dict 

487 Dictionary containing the keywords in :class:`OpenMXParameters`. 

488 """ 

489 

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

491 if key not in self.default_parameters.keys(): 

492 raise KeyError(f'Unkown keyword "{key}" and value "{value}".') 

493 if key == 'xc' and value not in self.default_parameters.allowed_xc: 

494 raise KeyError(f'Given xc "{value}" is not allowed') 

495 if key in ['dat_arguments'] and isinstance(value, dict): 

496 # For values that are dictionaries, verify subkeys, too. 

497 default_dict = self.default_parameters[key] 

498 for subkey in kwargs[key]: 

499 if subkey not in default_dict: 

500 allowed = ', '.join(list(default_dict.keys())) 

501 raise TypeError( 

502 'Unknown subkeyword "{}" of keyword ' 

503 '"{}". Must be one of: {}'.format( 

504 subkey, key, allowed 

505 ) 

506 ) 

507 

508 # Find out what parameter has been changed 

509 changed_parameters = {} 

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

511 oldvalue = self.parameters.get(key) 

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

513 changed_parameters[key] = value 

514 self.parameters[key] = value 

515 

516 # Set the parameters 

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

518 # print(' Setting the %s as %s'%(key, value)) 

519 self.parameters[key] = value 

520 

521 # If Changed Parameter is Critical, we have to reset the results 

522 for key, value in changed_parameters.items(): 

523 if key in ['xc', 'kpts', 'energy_cutoff']: 

524 self.results = {} 

525 

526 value = kwargs.get('energy_cutoff') 

527 if value is not None and not ( 

528 isinstance(value, (float, int)) and value > 0 

529 ): 

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

531 got '{}'".format('energy_cutoff', value) 

532 raise ValueError(mess) 

533 

534 atoms = kwargs.get('atoms') 

535 if atoms is not None and self.atoms is None: 

536 self.atoms = atoms.copy() 

537 

538 def set_results(self, results): 

539 # Not Implemented fully 

540 self.results.update(results) 

541 

542 def get_command(self, processes, threads, runfile=None, outfile=None): 

543 # Contruct the command to send to the operating system 

544 abs_dir = os.getcwd() 

545 command = '' 

546 self.prind(self.command) 

547 if self.command is None: 

548 self.command = 'openmx' 

549 # run processes specified by the system variable OPENMX_COMMAND 

550 if processes is None: 

551 command += cfg.get('OPENMX_COMMAND') 

552 if command is None: 

553 warnings.warn( 

554 'Either specify OPENMX_COMMAND as an environment\ 

555 variable or specify processes as a keyword argument' 

556 ) 

557 else: # run with a specified number of processes 

558 threads_string = ' -nt ' + str(threads) 

559 if threads is None: 

560 threads_string = '' 

561 command += ( 

562 'mpirun -np ' 

563 + str(processes) 

564 + ' ' 

565 + self.command 

566 + ' %s ' 

567 + threads_string 

568 + ' |tee %s' 

569 ) 

570 # str(processes) + ' openmx %s' + threads_string + ' > %s' 

571 

572 if runfile is None: 

573 runfile = os.path.join(abs_dir, f'{self.prefix} .dat') 

574 if outfile is None: 

575 outfile = os.path.join(abs_dir, f'{self.prefix} .log') 

576 try: 

577 command = command % (runfile, outfile) 

578 # command += '" > ./%s &' % outfile # outputs 

579 except TypeError: # in case the OPENMX_COMMAND is incompatible 

580 raise ValueError( 

581 "The 'OPENMX_COMMAND' environment must " 

582 + 'be a format string' 

583 + ' with four string arguments.\n' 

584 + "Example : 'mpirun -np 4 openmx ./%s -nt 2 > ./%s'.\n" 

585 + f"Got '{command}'" 

586 ) 

587 return command 

588 

589 def get_stress(self, atoms=None): 

590 if atoms is None: 

591 atoms = self.atoms 

592 

593 # Note: Stress is only supported from OpenMX 3.8+. 

594 stress = self.get_property('stress', atoms) 

595 

596 return stress 

597 

598 def get_band_structure(self, atoms=None, calc=None): 

599 """ 

600 This is band structure function. It is compatible to 

601 ase dft module""" 

602 from ase.dft import band_structure 

603 

604 if isinstance(self['kpts'], tuple): 

605 self['kpts'] = self.get_kpoints(band_kpath=self['band_kpath']) 

606 return band_structure.get_band_structure( 

607 self.atoms, 

608 self, 

609 ) 

610 

611 def get_bz_k_points(self): 

612 kgrid = self['kpts'] 

613 if type(kgrid) in [int, float]: 

614 kgrid = kptdensity2monkhorstpack(self.atoms, kgrid, False) 

615 bz_k_points = [] 

616 n1 = kgrid[0] 

617 n2 = kgrid[1] 

618 n3 = kgrid[2] 

619 for i in range(n1): 

620 for j in range(n2): 

621 # Monkhorst Pack Grid [H.J. Monkhorst and J.D. Pack, 

622 # Phys. Rev. B 13, 5188 (1976)] 

623 for k in range(n3): 

624 bz_k_points.append( 

625 ( 

626 0.5 * float(2 * i - n1 + 1) / n1, 

627 0.5 * float(2 * j - n2 + 1) / n2, 

628 0.5 * float(2 * k - n3 + 1) / n3, 

629 ) 

630 ) 

631 return np.array(bz_k_points) 

632 

633 def get_ibz_k_points(self): 

634 if self['band_kpath'] is None: 

635 return self.get_bz_k_points() 

636 else: 

637 return self.get_kpoints(band_kpath=self['band_kpath']) 

638 

639 def get_kpoints(self, kpts=None, symbols=None, band_kpath=None, eps=1e-5): 

640 """Convert band_kpath <-> kpts""" 

641 if kpts is None: 

642 kpts = [] 

643 band_kpath = np.array(band_kpath) 

644 band_nkpath = len(band_kpath) 

645 for i, kpath in enumerate(band_kpath): 

646 end = False 

647 nband = int(kpath[0]) 

648 if band_nkpath == i: 

649 end = True 

650 nband += 1 

651 ini = np.array(kpath[1:4], dtype=float) 

652 fin = np.array(kpath[4:7], dtype=float) 

653 x = np.linspace(ini[0], fin[0], nband, endpoint=end) 

654 y = np.linspace(ini[1], fin[1], nband, endpoint=end) 

655 z = np.linspace(ini[2], fin[2], nband, endpoint=end) 

656 kpts.extend(np.array([x, y, z]).T) 

657 return np.array(kpts, dtype=float) 

658 elif band_kpath is None: 

659 band_kpath = [] 

660 points = np.asarray(kpts) 

661 diffs = points[1:] - points[:-1] 

662 kinks = abs(diffs[1:] - diffs[:-1]).sum(1) > eps 

663 N = len(points) 

664 indices = [0] 

665 indices.extend(np.arange(1, N - 1)[kinks]) 

666 indices.append(N - 1) 

667 for start, end, s_sym, e_sym in zip( 

668 indices[1:], indices[:-1], symbols[1:], symbols[:-1] 

669 ): 

670 band_kpath.append( 

671 { 

672 'start_point': start, 

673 'end_point': end, 

674 'kpts': 20, 

675 'path_symbols': (s_sym, e_sym), 

676 } 

677 ) 

678 return band_kpath 

679 

680 def get_lattice_type(self): 

681 cellpar = cell_to_cellpar(self.atoms.cell) 

682 abc = cellpar[:3] 

683 angles = cellpar[3:] 

684 min_lv = min(abc) 

685 if np.ptp(abc) < 0.01 * min_lv: 

686 if abs(angles - 90).max() < 1: 

687 return 'cubic' 

688 elif abs(angles - 60).max() < 1: 

689 return 'fcc' 

690 elif abs(angles - np.arccos(-1 / 3.0) * 180 / np.pi).max < 1: 

691 return 'bcc' 

692 elif abs(angles - 90).max() < 1: 

693 if abs(abc[0] - abc[1]).min() < 0.01 * min_lv: 

694 return 'tetragonal' 

695 else: 

696 return 'orthorhombic' 

697 elif ( 

698 abs(abc[0] - abc[1]) < 0.01 * min_lv 

699 and abs(angles[2] - 120) < 1 

700 and abs(angles[:2] - 90).max() < 1 

701 ): 

702 return 'hexagonal' 

703 else: 

704 return 'not special' 

705 

706 def get_number_of_spins(self): 

707 try: 

708 magmoms = self.atoms.get_initial_magnetic_moments() 

709 if self['scf_spinpolarization'] is None: 

710 if isinstance(magmoms[0], float): 

711 if abs(magmoms).max() < 0.1: 

712 return 1 

713 else: 

714 return 2 

715 else: 

716 raise NotImplementedError 

717 else: 

718 if self['scf_spinpolarization'] == 'on': 

719 return 2 

720 elif ( 

721 self['scf_spinpolarization'] == 'nc' 

722 or np.any(self['initial_magnetic_moments_euler_angles']) 

723 is not None 

724 ): 

725 return 1 

726 except KeyError: 

727 return 1 

728 

729 def get_eigenvalues(self, kpt=None, spin=None): 

730 if self.results.get('eigenvalues') is None: 

731 self.calculate(self.atoms) 

732 if kpt is None and spin is None: 

733 return self.results['eigenvalues'] 

734 else: 

735 return self.results['eigenvalues'][spin, kpt, :] 

736 

737 def get_fermi_level(self): 

738 try: 

739 fermi_level = self.results['chemical_potential'] 

740 except KeyError: 

741 self.calculate() 

742 fermi_level = self.results['chemical_potential'] 

743 return fermi_level 

744 

745 def get_number_of_bands(self): 

746 pag = self.parameters.get 

747 dfd = default_dictionary 

748 if 'number_of_bands' not in self.results: 

749 n = 0 

750 for atom in self.atoms: 

751 sym = atom.symbol 

752 orbitals = pag('dft_data_dict', dfd)[sym]['orbitals used'] 

753 d = 1 

754 for orbital in orbitals: 

755 n += d * orbital 

756 d += 2 

757 self.results['number_of_bands'] = n 

758 return self.results['number_of_bands'] 

759 

760 def dirG(self, dk, bzone=(0, 0, 0)): 

761 nx, ny, nz = self['wannier_kpts'] 

762 dx = dk // (ny * nz) + bzone[0] * nx 

763 dy = (dk // nz) % ny + bzone[1] * ny 

764 dz = dk % nz + bzone[2] * nz 

765 return dx, dy, dz 

766 

767 def dk(self, dirG): 

768 dx, dy, dz = dirG 

769 nx, ny, nz = self['wannier_kpts'] 

770 return ny * nz * (dx % nx) + nz * (dy % ny) + dz % nz 

771 

772 def get_wannier_localization_matrix( 

773 self, nbands, dirG, nextkpoint=None, kpoint=None, spin=0, G_I=(0, 0, 0) 

774 ): 

775 # only expected to work for no spin polarization 

776 try: 

777 self['bloch_overlaps'] 

778 except KeyError: 

779 self.read_bloch_overlaps() 

780 dirG = tuple(dirG) 

781 nx, ny, nz = self['wannier_kpts'] 

782 nr3 = nx * ny * nz 

783 if kpoint is None and nextkpoint is None: 

784 return { 

785 kpoint: self['bloch_overlaps'][kpoint][dirG][:nbands, :nbands] 

786 for kpoint in range(nr3) 

787 } 

788 if kpoint is None: 

789 kpoint = (nextkpoint - self.dk(dirG)) % nr3 

790 if nextkpoint is None: 

791 nextkpoint = (kpoint + self.dk(dirG)) % nr3 

792 if dirG not in self['bloch_overlaps'][kpoint].keys(): 

793 return np.zeros((nbands, nbands), complex) 

794 return self['bloch_overlaps'][kpoint][dirG][:nbands, :nbands] 

795 

796 def prind(self, line, debug=None): 

797 """Print the value if debugging mode is on. 

798 Otherwise, it just ignored""" 

799 if debug is None: 

800 debug = self.debug 

801 if debug: 

802 print(line) 

803 

804 def print_file(self, file=None, running=None, **args): 

805 """Print the file while calculation is running""" 

806 prev_position = 0 

807 last_position = 0 

808 while not os.path.isfile(file): 

809 self.prind(f'Waiting for {file} to come out') 

810 time.sleep(5) 

811 with open(file) as fd: 

812 while running(**args): 

813 fd.seek(last_position) 

814 new_data = fd.read() 

815 prev_position = fd.tell() 

816 # self.prind('pos', prev_position != last_position) 

817 if prev_position != last_position: 

818 if not self.nohup: 

819 print(new_data) 

820 last_position = prev_position 

821 time.sleep(1)