Coverage for ase/calculators/socketio.py: 86.78%
401 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 os
2import socket
3from contextlib import ExitStack, contextmanager
4from subprocess import PIPE, Popen
6import numpy as np
8import ase.units as units
9from ase.calculators.calculator import (
10 Calculator,
11 OldShellProfile,
12 PropertyNotImplementedError,
13 StandardProfile,
14 all_changes,
15)
16from ase.calculators.genericfileio import GenericFileIOCalculator
17from ase.parallel import world
18from ase.stress import full_3x3_to_voigt_6_stress
19from ase.utils import IOContext
22def actualunixsocketname(name):
23 return f'/tmp/ipi_{name}'
26class SocketClosed(OSError):
27 pass
30class IPIProtocol:
31 """Communication using IPI protocol."""
33 def __init__(self, socket, txt=None):
34 self.socket = socket
36 if txt is None:
38 def log(*args):
39 pass
40 else:
42 def log(*args):
43 print('Driver:', *args, file=txt)
44 txt.flush()
46 self.log = log
48 def sendmsg(self, msg):
49 self.log(' sendmsg', repr(msg))
50 # assert msg in self.statements, msg
51 msg = msg.encode('ascii').ljust(12)
52 self.socket.sendall(msg)
54 def _recvall(self, nbytes):
55 """Repeatedly read chunks until we have nbytes.
57 Normally we get all bytes in one read, but that is not guaranteed."""
58 remaining = nbytes
59 chunks = []
60 while remaining > 0:
61 chunk = self.socket.recv(remaining)
62 if len(chunk) == 0:
63 # (If socket is still open, recv returns at least one byte)
64 raise SocketClosed
65 chunks.append(chunk)
66 remaining -= len(chunk)
67 msg = b''.join(chunks)
68 assert len(msg) == nbytes and remaining == 0
69 return msg
71 def recvmsg(self):
72 msg = self._recvall(12)
73 if not msg:
74 raise SocketClosed
76 assert len(msg) == 12, msg
77 msg = msg.rstrip().decode('ascii')
78 # assert msg in self.responses, msg
79 self.log(' recvmsg', repr(msg))
80 return msg
82 def send(self, a, dtype):
83 buf = np.asarray(a, dtype).tobytes()
84 # self.log(' send {}'.format(np.array(a).ravel().tolist()))
85 self.log(f' send {len(buf)} bytes of {dtype}')
86 self.socket.sendall(buf)
88 def recv(self, shape, dtype):
89 a = np.empty(shape, dtype)
90 nbytes = np.dtype(dtype).itemsize * np.prod(shape)
91 buf = self._recvall(nbytes)
92 assert len(buf) == nbytes, (len(buf), nbytes)
93 self.log(f' recv {len(buf)} bytes of {dtype}')
94 # print(np.frombuffer(buf, dtype=dtype))
95 a.flat[:] = np.frombuffer(buf, dtype=dtype)
96 # self.log(' recv {}'.format(a.ravel().tolist()))
97 assert np.isfinite(a).all()
98 return a
100 def sendposdata(self, cell, icell, positions):
101 assert cell.size == 9
102 assert icell.size == 9
103 assert positions.size % 3 == 0
105 self.log(' sendposdata')
106 self.sendmsg('POSDATA')
107 self.send(cell.T / units.Bohr, np.float64)
108 self.send(icell.T * units.Bohr, np.float64)
109 self.send(len(positions), np.int32)
110 self.send(positions / units.Bohr, np.float64)
112 def recvposdata(self):
113 cell = self.recv((3, 3), np.float64).T.copy()
114 icell = self.recv((3, 3), np.float64).T.copy()
115 natoms = self.recv(1, np.int32)[0]
116 positions = self.recv((natoms, 3), np.float64)
117 return cell * units.Bohr, icell / units.Bohr, positions * units.Bohr
119 def sendrecv_force(self):
120 self.log(' sendrecv_force')
121 self.sendmsg('GETFORCE')
122 msg = self.recvmsg()
123 assert msg == 'FORCEREADY', msg
124 e = self.recv(1, np.float64)[0]
125 natoms = self.recv(1, np.int32)[0]
126 assert natoms >= 0
127 forces = self.recv((int(natoms), 3), np.float64)
128 virial = self.recv((3, 3), np.float64).T.copy()
129 nmorebytes = self.recv(1, np.int32)[0]
130 morebytes = self.recv(nmorebytes, np.byte)
131 return (
132 e * units.Ha,
133 (units.Ha / units.Bohr) * forces,
134 units.Ha * virial,
135 morebytes,
136 )
138 def sendforce(
139 self, energy, forces, virial, morebytes=np.zeros(1, dtype=np.byte)
140 ):
141 assert np.array([energy]).size == 1
142 assert forces.shape[1] == 3
143 assert virial.shape == (3, 3)
145 self.log(' sendforce')
146 self.sendmsg('FORCEREADY') # mind the units
147 self.send(np.array([energy / units.Ha]), np.float64)
148 natoms = len(forces)
149 self.send(np.array([natoms]), np.int32)
150 self.send(units.Bohr / units.Ha * forces, np.float64)
151 self.send(1.0 / units.Ha * virial.T, np.float64)
152 # We prefer to always send at least one byte due to trouble with
153 # empty messages. Reading a closed socket yields 0 bytes
154 # and thus can be confused with a 0-length bytestring.
155 self.send(np.array([len(morebytes)]), np.int32)
156 self.send(morebytes, np.byte)
158 def status(self):
159 self.log(' status')
160 self.sendmsg('STATUS')
161 msg = self.recvmsg()
162 return msg
164 def end(self):
165 self.log(' end')
166 self.sendmsg('EXIT')
168 def recvinit(self):
169 self.log(' recvinit')
170 bead_index = self.recv(1, np.int32)
171 nbytes = self.recv(1, np.int32)
172 initbytes = self.recv(nbytes, np.byte)
173 return bead_index, initbytes
175 def sendinit(self):
176 # XXX Not sure what this function is supposed to send.
177 # It 'works' with QE, but for now we try not to call it.
178 self.log(' sendinit')
179 self.sendmsg('INIT')
180 self.send(0, np.int32) # 'bead index' always zero for now
181 # We send one byte, which is zero, since things may not work
182 # with 0 bytes. Apparently implementations ignore the
183 # initialization string anyway.
184 self.send(1, np.int32)
185 self.send(np.zeros(1), np.byte) # initialization string
187 def calculate(self, positions, cell):
188 self.log('calculate')
189 msg = self.status()
190 # We don't know how NEEDINIT is supposed to work, but some codes
191 # seem to be okay if we skip it and send the positions instead.
192 if msg == 'NEEDINIT':
193 self.sendinit()
194 msg = self.status()
195 assert msg == 'READY', msg
196 icell = np.linalg.pinv(cell).transpose()
197 self.sendposdata(cell, icell, positions)
198 msg = self.status()
199 assert msg == 'HAVEDATA', msg
200 e, forces, virial, morebytes = self.sendrecv_force()
201 r = dict(energy=e, forces=forces, virial=virial, morebytes=morebytes)
202 return r
205@contextmanager
206def bind_unixsocket(socketfile):
207 assert socketfile.startswith('/tmp/ipi_'), socketfile
208 serversocket = socket.socket(socket.AF_UNIX)
209 try:
210 serversocket.bind(socketfile)
211 except OSError as err:
212 raise OSError(f'{err}: {socketfile!r}')
214 try:
215 with serversocket:
216 yield serversocket
217 finally:
218 os.unlink(socketfile)
221@contextmanager
222def bind_inetsocket(port):
223 serversocket = socket.socket(socket.AF_INET)
224 serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
225 serversocket.bind(('', port))
226 with serversocket:
227 yield serversocket
230class FileIOSocketClientLauncher:
231 def __init__(self, calc):
232 self.calc = calc
234 def __call__(self, atoms, properties=None, port=None, unixsocket=None):
235 assert self.calc is not None
236 cwd = self.calc.directory
238 profile = getattr(self.calc, 'profile', None)
239 if isinstance(self.calc, GenericFileIOCalculator):
240 # New GenericFileIOCalculator:
241 template = getattr(self.calc, 'template')
243 self.calc.write_inputfiles(atoms, properties)
244 if unixsocket is not None:
245 argv = template.socketio_argv(
246 profile, unixsocket=unixsocket, port=None
247 )
248 else:
249 argv = template.socketio_argv(
250 profile, unixsocket=None, port=port
251 )
253 if hasattr(self.calc.template, 'outputname'):
254 with ExitStack() as stack:
255 output_path = self.calc.template.outputname
256 fd_out = stack.enter_context(open(output_path, 'w'))
257 return Popen(argv, cwd=cwd, env=os.environ, stdout=fd_out)
259 return Popen(argv, cwd=cwd, env=os.environ)
260 else:
261 # Old FileIOCalculator:
262 self.calc.write_input(
263 atoms, properties=properties, system_changes=all_changes
264 )
266 if isinstance(profile, StandardProfile):
267 return profile.execute_nonblocking(self.calc)
269 if profile is None:
270 cmd = self.calc.command.replace('PREFIX', self.calc.prefix)
271 cmd = cmd.format(port=port, unixsocket=unixsocket)
272 elif isinstance(profile, OldShellProfile):
273 cmd = profile.command.replace('PREFIX', self.calc.prefix)
274 else:
275 raise TypeError(
276 f'Profile type {type(profile)} not supported for socketio'
277 )
279 return Popen(cmd, shell=True, cwd=cwd)
282class SocketServer(IOContext):
283 default_port = 31415
285 def __init__(
286 self, # launch_client=None,
287 port=None,
288 unixsocket=None,
289 timeout=None,
290 log=None,
291 ):
292 """Create server and listen for connections.
294 Parameters
295 ----------
297 client_command: Shell command to launch client process, or None
298 The process will be launched immediately, if given.
299 Else the user is expected to launch a client whose connection
300 the server will then accept at any time.
301 One calculate() is called, the server will block to wait
302 for the client.
303 port: integer or None
304 Port on which to listen for INET connections. Defaults
305 to 31415 if neither this nor unixsocket is specified.
306 unixsocket: string or None
307 Filename for unix socket.
308 timeout: float or None
309 timeout in seconds, or unlimited by default.
310 This parameter is passed to the Python socket object; see
311 documentation therof
312 log: file object or None
313 useful debug messages are written to this."""
315 if unixsocket is None and port is None:
316 port = self.default_port
317 elif unixsocket is not None and port is not None:
318 raise ValueError('Specify only one of unixsocket and port')
320 self.port = port
321 self.unixsocket = unixsocket
322 self.timeout = timeout
323 self._closed = False
325 if unixsocket is not None:
326 actualsocket = actualunixsocketname(unixsocket)
327 conn_name = f'UNIX-socket {actualsocket}'
328 socket_context = bind_unixsocket(actualsocket)
329 else:
330 conn_name = f'INET port {port}'
331 socket_context = bind_inetsocket(port)
333 self.serversocket = self.closelater(socket_context)
335 if log:
336 print(f'Accepting clients on {conn_name}', file=log)
338 self.serversocket.settimeout(timeout)
340 self.serversocket.listen(1)
342 self.log = log
344 self.proc = None
346 self.protocol = None
347 self.clientsocket = None
348 self.address = None
350 # if launch_client is not None:
351 # self.proc = launch_client(port=port, unixsocket=unixsocket)
353 def _accept(self):
354 """Wait for client and establish connection."""
355 # It should perhaps be possible for process to be launched by user
356 log = self.log
357 if log:
358 print('Awaiting client', file=self.log)
360 # If we launched the subprocess, the process may crash.
361 # We want to detect this, using loop with timeouts, and
362 # raise an error rather than blocking forever.
363 if self.proc is not None:
364 self.serversocket.settimeout(1.0)
366 while True:
367 try:
368 self.clientsocket, self.address = self.serversocket.accept()
369 self.closelater(self.clientsocket)
370 except TimeoutError:
371 if self.proc is not None:
372 status = self.proc.poll()
373 if status is not None:
374 raise OSError(
375 'Subprocess terminated unexpectedly'
376 ' with status {}'.format(status)
377 )
378 else:
379 break
381 self.serversocket.settimeout(self.timeout)
382 self.clientsocket.settimeout(self.timeout)
384 if log:
385 # For unix sockets, address is b''.
386 source = 'client' if self.address == b'' else self.address
387 print(f'Accepted connection from {source}', file=log)
389 self.protocol = IPIProtocol(self.clientsocket, txt=log)
391 def close(self):
392 if self._closed:
393 return
395 super().close()
397 if self.log:
398 print('Close socket server', file=self.log)
399 self._closed = True
401 # Proper way to close sockets?
402 # And indeed i-pi connections...
403 # if self.protocol is not None:
404 # self.protocol.end() # Send end-of-communication string
405 self.protocol = None
406 if self.proc is not None:
407 exitcode = self.proc.wait()
408 if exitcode != 0:
409 import warnings
411 # Quantum Espresso seems to always exit with status 128,
412 # even if successful.
413 # Should investigate at some point
414 warnings.warn(
415 'Subprocess exited with status {}'.format(exitcode)
416 )
417 # self.log('IPI server closed')
419 def calculate(self, atoms):
420 """Send geometry to client and return calculated things as dict.
422 This will block until client has established connection, then
423 wait for the client to finish the calculation."""
424 assert not self._closed
426 # If we have not established connection yet, we must block
427 # until the client catches up:
428 if self.protocol is None:
429 self._accept()
430 return self.protocol.calculate(atoms.positions, atoms.cell)
433class SocketClient:
434 def __init__(
435 self,
436 host='localhost',
437 port=None,
438 unixsocket=None,
439 timeout=None,
440 log=None,
441 comm=world,
442 ):
443 """Create client and connect to server.
445 Parameters
446 ----------
448 host: string
449 Hostname of server. Defaults to localhost
450 port: integer or None
451 Port to which to connect. By default 31415.
452 unixsocket: string or None
453 If specified, use corresponding UNIX socket.
454 See documentation of unixsocket for SocketIOCalculator.
455 timeout: float or None
456 See documentation of timeout for SocketIOCalculator.
457 log: file object or None
458 Log events to this file
459 comm: communicator or None
460 MPI communicator object. Defaults to ase.parallel.world.
461 When ASE runs in parallel, only the process with world.rank == 0
462 will communicate over the socket. The received information
463 will then be broadcast on the communicator. The SocketClient
464 must be created on all ranks of world, and will see the same
465 Atoms objects."""
466 # Only rank0 actually does the socket work.
467 # The other ranks only need to follow.
468 #
469 # Note: We actually refrain from assigning all the
470 # socket-related things except on master
471 self.comm = comm
473 if self.comm.rank == 0:
474 if unixsocket is not None:
475 sock = socket.socket(socket.AF_UNIX)
476 actualsocket = actualunixsocketname(unixsocket)
477 sock.connect(actualsocket)
478 else:
479 if port is None:
480 port = SocketServer.default_port
481 sock = socket.socket(socket.AF_INET)
482 sock.connect((host, port))
483 sock.settimeout(timeout)
484 self.host = host
485 self.port = port
486 self.unixsocket = unixsocket
488 self.protocol = IPIProtocol(sock, txt=log)
489 self.log = self.protocol.log
490 self.closed = False
492 self.bead_index = 0
493 self.bead_initbytes = b''
494 self.state = 'READY'
496 def close(self):
497 if not self.closed:
498 self.log('Close SocketClient')
499 self.closed = True
500 self.protocol.socket.close()
502 def calculate(self, atoms, use_stress):
503 # We should also broadcast the bead index, once we support doing
504 # multiple beads.
505 self.comm.broadcast(atoms.positions, 0)
506 self.comm.broadcast(np.ascontiguousarray(atoms.cell), 0)
508 energy = atoms.get_potential_energy()
509 forces = atoms.get_forces()
510 if use_stress:
511 stress = atoms.get_stress(voigt=False)
512 virial = -atoms.get_volume() * stress
513 else:
514 virial = np.zeros((3, 3))
515 return energy, forces, virial
517 def irun(self, atoms, use_stress=None):
518 if use_stress is None:
519 use_stress = any(atoms.pbc)
521 my_irun = self.irun_rank0 if self.comm.rank == 0 else self.irun_rankN
522 return my_irun(atoms, use_stress)
524 def irun_rankN(self, atoms, use_stress=True):
525 stop_criterion = np.zeros(1, bool)
526 while True:
527 self.comm.broadcast(stop_criterion, 0)
528 if stop_criterion[0]:
529 return
531 self.calculate(atoms, use_stress)
532 yield
534 def irun_rank0(self, atoms, use_stress=True):
535 # For every step we either calculate or quit. We need to
536 # tell other MPI processes (if this is MPI-parallel) whether they
537 # should calculate or quit.
538 try:
539 while True:
540 try:
541 msg = self.protocol.recvmsg()
542 except SocketClosed:
543 # Server closed the connection, but we want to
544 # exit gracefully anyway
545 msg = 'EXIT'
547 if msg == 'EXIT':
548 # Send stop signal to clients:
549 self.comm.broadcast(np.ones(1, bool), 0)
550 # (When otherwise exiting, things crashed and we should
551 # let MPI_ABORT take care of the mess instead of trying
552 # to synchronize the exit)
553 return
554 elif msg == 'STATUS':
555 self.protocol.sendmsg(self.state)
556 elif msg == 'POSDATA':
557 assert self.state == 'READY'
558 cell, _icell, positions = self.protocol.recvposdata()
559 atoms.cell[:] = cell
560 atoms.positions[:] = positions
562 # User may wish to do something with the atoms object now.
563 # Should we provide option to yield here?
564 #
565 # (In that case we should MPI-synchronize *before*
566 # whereas now we do it after.)
568 # Send signal for other ranks to proceed with calculation:
569 self.comm.broadcast(np.zeros(1, bool), 0)
570 energy, forces, virial = self.calculate(atoms, use_stress)
572 self.state = 'HAVEDATA'
573 yield
574 elif msg == 'GETFORCE':
575 assert self.state == 'HAVEDATA', self.state
576 self.protocol.sendforce(energy, forces, virial)
577 self.state = 'READY'
578 elif msg == 'INIT':
579 assert self.state == 'NEEDINIT'
580 bead_index, initbytes = self.protocol.recvinit()
581 self.bead_index = bead_index
582 self.bead_initbytes = initbytes
583 self.state = 'READY'
584 else:
585 raise KeyError('Bad message', msg)
586 finally:
587 self.close()
589 def run(self, atoms, use_stress=False):
590 for _ in self.irun(atoms, use_stress=use_stress):
591 pass
594class SocketIOCalculator(Calculator, IOContext):
595 implemented_properties = ['energy', 'free_energy', 'forces', 'stress']
596 supported_changes = {'positions', 'cell'}
598 def __init__(
599 self,
600 calc=None,
601 port=None,
602 unixsocket=None,
603 timeout=None,
604 log=None,
605 *,
606 launch_client=None,
607 comm=world,
608 ):
609 """Initialize socket I/O calculator.
611 This calculator launches a server which passes atomic
612 coordinates and unit cells to an external code via a socket,
613 and receives energy, forces, and stress in return.
615 ASE integrates this with the Quantum Espresso, FHI-aims and
616 Siesta calculators. This works with any external code that
617 supports running as a client over the i-PI protocol.
619 Parameters
620 ----------
622 calc: calculator or None
624 If calc is not None, a client process will be launched
625 using calc.command, and the input file will be generated
626 using ``calc.write_input()``. Otherwise only the server will
627 run, and it is up to the user to launch a compliant client
628 process.
630 port: integer
632 port number for socket. Should normally be between 1025
633 and 65535. Typical ports for are 31415 (default) or 3141.
635 unixsocket: str or None
637 if not None, ignore host and port, creating instead a
638 unix socket using this name prefixed with ``/tmp/ipi_``.
639 The socket is deleted when the calculator is closed.
641 timeout: float >= 0 or None
643 timeout for connection, by default infinite. See
644 documentation of Python sockets. For longer jobs it is
645 recommended to set a timeout in case of undetected
646 client-side failure.
648 log: file object or None (default)
650 logfile for communication over socket. For debugging or
651 the curious.
653 In order to correctly close the sockets, it is
654 recommended to use this class within a with-block:
656 >>> from ase.calculators.socketio import SocketIOCalculator
658 >>> with SocketIOCalculator(...) as calc: # doctest:+SKIP
659 ... atoms.calc = calc
660 ... atoms.get_forces()
661 ... atoms.rattle()
662 ... atoms.get_forces()
664 It is also possible to call calc.close() after
665 use. This is best done in a finally-block."""
667 Calculator.__init__(self)
669 if calc is not None:
670 if launch_client is not None:
671 raise ValueError('Cannot pass both calc and launch_client')
672 launch_client = FileIOSocketClientLauncher(calc)
673 self.launch_client = launch_client
674 self.timeout = timeout
675 self.server = None
677 self.log = self.openfile(file=log, comm=comm)
679 # We only hold these so we can pass them on to the server.
680 # They may both be None as stored here.
681 self._port = port
682 self._unixsocket = unixsocket
684 # If there is a calculator, we will launch in calculate() because
685 # we are responsible for executing the external process, too, and
686 # should do so before blocking. Without a calculator we want to
687 # block immediately:
688 if self.launch_client is None:
689 self.server = self.launch_server()
691 def todict(self):
692 d = {'type': 'calculator', 'name': 'socket-driver'}
693 # if self.calc is not None:
694 # d['calc'] = self.calc.todict()
695 return d
697 def launch_server(self):
698 return self.closelater(
699 SocketServer(
700 # launch_client=launch_client,
701 port=self._port,
702 unixsocket=self._unixsocket,
703 timeout=self.timeout,
704 log=self.log,
705 )
706 )
708 def calculate(
709 self, atoms=None, properties=None, system_changes=all_changes
710 ):
711 if properties is None:
712 properties = ['energy']
713 bad = [
714 change
715 for change in system_changes
716 if change not in self.supported_changes
717 ]
719 # First time calculate() is called, system_changes will be
720 # all_changes. After that, only positions and cell may change.
721 if self.atoms is not None and any(bad):
722 raise PropertyNotImplementedError(
723 'Cannot change {} through IPI protocol. '
724 'Please create new socket calculator.'.format(
725 bad if len(bad) > 1 else bad[0]
726 )
727 )
729 self.atoms = atoms.copy()
731 if self.server is None:
732 self.server = self.launch_server()
733 proc = self.launch_client(
734 atoms, properties, port=self._port, unixsocket=self._unixsocket
735 )
736 self.server.proc = proc # XXX nasty hack
738 results = self.server.calculate(atoms)
739 results['free_energy'] = results['energy']
740 virial = results.pop('virial')
741 if self.atoms.cell.rank == 3 and any(self.atoms.pbc):
742 vol = atoms.get_volume()
743 results['stress'] = -full_3x3_to_voigt_6_stress(virial) / vol
744 self.results.update(results)
746 def close(self):
747 self.server = None
748 super().close()
751class PySocketIOClient:
752 def __init__(self, calculator_factory):
753 self._calculator_factory = calculator_factory
755 def __call__(self, atoms, properties=None, port=None, unixsocket=None):
756 import pickle
757 import sys
759 # We pickle everything first, so we won't need to bother with the
760 # process as long as it succeeds.
761 transferbytes = pickle.dumps(
762 [
763 dict(unixsocket=unixsocket, port=port),
764 atoms.copy(),
765 self._calculator_factory,
766 ]
767 )
769 proc = Popen(
770 [sys.executable, '-m', 'ase.calculators.socketio'], stdin=PIPE
771 )
773 proc.stdin.write(transferbytes)
774 proc.stdin.close()
775 return proc
777 @staticmethod
778 def main():
779 import pickle
780 import sys
782 socketinfo, atoms, get_calculator = pickle.load(sys.stdin.buffer)
783 atoms.calc = get_calculator()
784 client = SocketClient(
785 host='localhost',
786 unixsocket=socketinfo.get('unixsocket'),
787 port=socketinfo.get('port'),
788 )
789 # XXX In principle we could avoid calculating stress until
790 # someone requests the stress, could we not?
791 # Which would make use_stress boolean unnecessary.
792 client.run(atoms, use_stress=True)
795if __name__ == '__main__':
796 PySocketIOClient.main()