Coverage for ase/calculators/vasp/interactive.py: 19.79%

96 statements  

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

1import os 

2import time 

3from subprocess import PIPE, Popen 

4 

5from ase.calculators.calculator import Calculator 

6from ase.config import cfg 

7from ase.io import read 

8 

9from .create_input import GenerateVaspInput 

10 

11 

12class VaspInteractive(GenerateVaspInput, Calculator): # type: ignore[misc] 

13 name = 'VaspInteractive' 

14 implemented_properties = ['energy', 'forces', 'stress'] 

15 

16 mandatory_input = { 

17 'potim': 0.0, 

18 'ibrion': -1, 

19 'interactive': True, 

20 } 

21 

22 default_input = { 

23 'nsw': 2000, 

24 } 

25 

26 def __init__( 

27 self, 

28 txt='interactive.log', 

29 print_log=False, 

30 process=None, 

31 command=None, 

32 path='./', 

33 **kwargs, 

34 ): 

35 

36 GenerateVaspInput.__init__(self) 

37 

38 for kw, val in self.mandatory_input.items(): 

39 if kw in kwargs and val != kwargs[kw]: 

40 raise ValueError( 

41 'Keyword {} cannot be overridden! ' 

42 'It must have have value {}, but {} ' 

43 'was provided instead.'.format(kw, val, kwargs[kw]) 

44 ) 

45 kwargs.update(self.mandatory_input) 

46 

47 for kw, val in self.default_input.items(): 

48 if kw not in kwargs: 

49 kwargs[kw] = val 

50 

51 self.set(**kwargs) 

52 

53 self.process = process 

54 self.path = path 

55 

56 if txt is not None: 

57 self.txt = open(txt, 'a') 

58 else: 

59 self.txt = None 

60 self.print_log = print_log 

61 

62 if command is not None: 

63 self.command = command 

64 elif 'VASP_COMMAND' in cfg: 

65 self.command = cfg['VASP_COMMAND'] 

66 elif 'VASP_SCRIPT' in cfg: 

67 self.command = cfg['VASP_SCRIPT'] 

68 else: 

69 raise RuntimeError( 

70 'Please set either command in calculator' 

71 ' or VASP_COMMAND environment variable' 

72 ) 

73 

74 if isinstance(self.command, str): 

75 self.command = self.command.split() 

76 

77 self.atoms = None 

78 

79 def _stdin(self, text, ending='\n'): 

80 if self.txt is not None: 

81 self.txt.write(text + ending) 

82 if self.print_log: 

83 print(text, end=ending) 

84 self.process.stdin.write(text + ending) 

85 self.process.stdin.flush() 

86 

87 def _stdout(self, text): 

88 if self.txt is not None: 

89 self.txt.write(text) 

90 if self.print_log: 

91 print(text, end='') 

92 

93 def _run_vasp(self, atoms): 

94 if self.process is None: 

95 stopcar = os.path.join(self.path, 'STOPCAR') 

96 if os.path.isfile(stopcar): 

97 os.remove(stopcar) 

98 self._stdout('Writing VASP input files\n') 

99 self.initialize(atoms) 

100 self.write_input(atoms, directory=self.path) 

101 self._stdout('Starting VASP for initial step...\n') 

102 self.process = Popen( 

103 self.command, 

104 stdout=PIPE, 

105 stdin=PIPE, 

106 stderr=PIPE, 

107 cwd=self.path, 

108 universal_newlines=True, 

109 ) 

110 else: 

111 self._stdout('Inputting positions...\n') 

112 for atom in atoms.get_scaled_positions(): 

113 self._stdin(' '.join(map('{:19.16f}'.format, atom))) 

114 

115 while self.process.poll() is None: 

116 text = self.process.stdout.readline() 

117 self._stdout(text) 

118 if 'POSITIONS: reading from stdin' in text: 

119 return 

120 

121 # If we've reached this point, then VASP has exited without asking for 

122 # new positions, meaning it either exited without error unexpectedly, 

123 # or it exited with an error. Either way, we need to raise an error. 

124 

125 raise RuntimeError( 

126 'VASP exited unexpectedly with exit code {}'.format( 

127 self.process.poll() 

128 ) 

129 ) 

130 

131 def close(self): 

132 if self.process is None: 

133 return 

134 

135 self._stdout('Attemping to close VASP cleanly\n') 

136 with open(os.path.join(self.path, 'STOPCAR'), 'w') as stopcar: 

137 stopcar.write('LABORT = .TRUE.') 

138 

139 self._run_vasp(self.atoms) 

140 self._run_vasp(self.atoms) 

141 while self.process.poll() is None: 

142 time.sleep(1) 

143 self._stdout('VASP has been closed\n') 

144 self.process = None 

145 

146 def calculate( 

147 self, 

148 atoms=None, 

149 properties=None, 

150 system_changes=None, 

151 ): 

152 if system_changes is None: 

153 system_changes = ['positions', 'numbers', 'cell'] 

154 if properties is None: 

155 properties = ['energy'] 

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

157 

158 if not system_changes: 

159 return 

160 

161 if 'numbers' in system_changes: 

162 self.close() 

163 

164 self._run_vasp(atoms) 

165 

166 new = read(os.path.join(self.path, 'vasprun.xml'), index=-1) 

167 

168 self.results = { 

169 'free_energy': new.get_potential_energy(force_consistent=True), 

170 'energy': new.get_potential_energy(), 

171 'forces': new.get_forces()[self.resort], 

172 'stress': new.get_stress(), 

173 } 

174 

175 def __del__(self): 

176 self.close()