2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2014, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
39 * Implements functions of imd.h.
41 * Re-implementation of basic IMD functions from NAMD/VMD from scratch,
42 * see imdsocket.h for references to the IMD API.
44 * \author Martin Hoefling, Carsten Kutzner <ckutzne@gwdg.de>
55 #include "imdsocket.h"
59 #include "sighandler.h"
60 #include "gmx_ga2la.h"
62 #include "gromacs/mdlib/groupcoord.h"
63 #include "gromacs/fileio/confio.h"
64 #include "mtop_util.h"
66 #include "gromacs/timing/wallcycle.h"
70 #ifdef GMX_NATIVE_WINDOWS
76 /*! \brief How long shall we wait in seconds until we check for a connection again? */
79 /*! \brief How long shall we check for the IMD_GO? */
80 #define IMDCONNECTWAIT 2
82 /*! \brief IMD Header Size. */
84 /*! \brief IMD Protocol Version. */
87 /*! \brief Broadcast d to all nodes */
88 #define block_bc(cr, d) gmx_bcast(sizeof(d), &(d), (cr))
90 /*! \brief Broadcast nr elements of d to all nodes */
91 #define nblock_bc(cr, nr, d) gmx_bcast((nr)*sizeof((d)[0]), (d), (cr))
96 * IMD (interactive molecular dynamics) energy record.
98 * As in the original IMD implementation. Energies in kcal/mol.
99 * NOTE: We return the energies in GROMACS / SI units,
100 * so they also show up as SI in VMD.
105 gmx_int32_t tstep; /**< time step */
106 float T_abs; /**< absolute temperature */
107 float E_tot; /**< total energy */
108 float E_pot; /**< potential energy */
109 float E_vdw; /**< van der Waals energy */
110 float E_coul; /**< Coulomb interaction energy */
111 float E_bond; /**< bonds energy */
112 float E_angle; /**< angles energy */
113 float E_dihe; /**< dihedrals energy */
114 float E_impr; /**< improper dihedrals energy */
119 * \brief IMD (interactive molecular dynamics) communication structure.
121 * This structure defines the IMD communication message header & protocol version.
125 gmx_int32_t type; /**< Type of IMD message, see IMDType_t above */
126 gmx_int32_t length; /**< Length */
131 * \brief IMD (interactive molecular dynamics) main data structure.
133 * Contains private IMD data
135 typedef struct gmx_IMD
137 FILE *outf; /**< Output file for IMD data, mainly forces. */
139 int nat; /**< Number of atoms that can be pulled via IMD. */
140 int nat_loc; /**< Part of the atoms that are local. */
141 atom_id *ind; /**< Global indices of the IMD atoms. */
142 atom_id *ind_loc; /**< Local indices of the IMD atoms. */
143 int nalloc_loc; /**< Allocation size for ind_loc. */
144 rvec *xa; /**< Positions for all IMD atoms assembled on
146 ivec *xa_shifts; /**< Shifts for all IMD atoms, to make
147 molecule(s) whole. */
148 ivec *xa_eshifts; /**< Extra shifts since last DD step. */
149 rvec *xa_old; /**< Old positions for all IMD atoms on master. */
150 int *xa_ind; /**< Position of each local atom in the
153 int nstimd; /**< Global IMD frequency, known to all nodes. */
154 int nstimd_new; /**< New frequency from IMD client, master only. */
155 int nstimd_def; /**< Default IMD frequency when disconnected. */
157 int port; /**< Port to use for network socket. */
158 IMDSocket *socket; /**< The IMD socket on the master node. */
159 IMDSocket *clientsocket; /**< The IMD socket on the client. */
160 int length; /**< Length we got with last header. */
162 gmx_bool bWConnect; /**< Shall we block and wait for connection? */
163 gmx_bool bTerminated; /**< Set if MD is terminated. */
164 gmx_bool bTerminatable; /**< Set if MD can be terminated. */
165 gmx_bool bConnected; /**< Set if connection is present. */
166 gmx_bool bNewForces; /**< Set if we received new forces. */
167 gmx_bool bForceActivated; /**< Set if pulling from VMD is allowed. */
169 IMDEnergyBlock *energies; /**< Pointer to energies we send back. */
171 gmx_int32_t vmd_nforces; /**< Number of VMD forces. */
172 gmx_int32_t *vmd_f_ind; /**< VMD forces indices. */
173 float *vmd_forces; /**< The VMD forces flat in memory. */
174 int nforces; /**< Number of actual MD forces;
175 this gets communicated to the clients. */
176 atom_id *f_ind; /**< Force indices. */
177 rvec *f; /**< The IMD pulling forces. */
179 char *forcesendbuf; /**< Buffer for force sending. */
180 char *coordsendbuf; /**< Buffer for coordinate sending. */
181 char *energysendbuf; /**< Send buffer for energies. */
182 rvec *sendxbuf; /**< Buffer to make molecules whole before
185 t_block mols; /**< Molecules block in IMD group. */
187 /* The next block is used on the master node only to reduce the output
188 * without sacrificing information. If any of these values changes,
189 * we need to write output */
190 int old_nforces; /**< Old value for nforces. */
191 atom_id *old_f_ind; /**< Old values for force indices. */
192 rvec *old_forces; /**< Old values for IMD pulling forces. */
198 * \brief Enum for types of IMD messages.
200 * We use the same records as the NAMD/VMD IMD implementation.
202 typedef enum IMDType_t
204 IMD_DISCONNECT, /**< client disconnect */
205 IMD_ENERGIES, /**< energy data */
206 IMD_FCOORDS, /**< atomic coordinates */
207 IMD_GO, /**< start command for the simulation */
208 IMD_HANDSHAKE, /**< handshake to determine little/big endianness */
209 IMD_KILL, /**< terminates the simulation */
210 IMD_MDCOMM, /**< force data */
211 IMD_PAUSE, /**< pauses the simulation */
212 IMD_TRATE, /**< sets the IMD transmission and processing rate */
213 IMD_IOERROR, /**< I/O error */
214 IMD_NR /**< number of entries */
219 * \brief Names of the IMDType for error messages.
221 const char *eIMDType_names[IMD_NR + 1] = {
238 /*! \brief Fills the header with message and the length argument. */
239 static void fill_header(IMDHeader *header, IMDMessageType type, gmx_int32_t length)
241 /* We (ab-)use htonl network function for the correct endianness */
242 header->type = htonl((gmx_int32_t) type);
243 header->length = htonl(length);
247 /*! \brief Swaps the endianess of the header. */
248 static void swap_header(IMDHeader *header)
250 /* and vice versa... */
251 header->type = ntohl(header->type);
252 header->length = ntohl(header->length);
256 /*! \brief Reads multiple bytes from socket. */
257 static gmx_int32_t imd_read_multiple(IMDSocket *socket, char *datptr, gmx_int32_t toread)
259 gmx_int32_t leftcount, countread;
263 /* Try to read while we haven't reached toread */
264 while (leftcount != 0)
266 if ((countread = imdsock_read(socket, datptr, leftcount)) < 0)
268 /* interrupted function call, try again... */
273 /* this is an unexpected error, return what we got */
276 return toread - leftcount;
279 /* nothing read, finished */
281 else if (countread == 0)
285 leftcount -= countread;
289 /* return nr of bytes read */
290 return toread - leftcount;
294 /*! \brief Writes multiple bytes to socket in analogy to imd_read_multiple. */
295 static gmx_int32_t imd_write_multiple(IMDSocket *socket, const char *datptr, gmx_int32_t towrite)
297 gmx_int32_t leftcount, countwritten;
301 while (leftcount != 0)
303 if ((countwritten = imdsock_write(socket, datptr, leftcount)) <= 0)
311 return towrite - leftcount;
314 leftcount -= countwritten;
315 datptr += countwritten;
318 return towrite - leftcount;
322 /*! \brief Handshake with IMD client. */
323 static int imd_handshake(IMDSocket *socket)
328 fill_header(&header, IMD_HANDSHAKE, 1);
329 header.length = IMDVERSION; /* client wants unswapped version */
331 return (imd_write_multiple(socket, (char *) &header, HEADERSIZE) != HEADERSIZE);
335 /*! \brief Send energies using the energy block and the send buffer. */
336 static int imd_send_energies(IMDSocket *socket, const IMDEnergyBlock *energies, char *buffer)
341 recsize = HEADERSIZE + sizeof(IMDEnergyBlock);
342 fill_header((IMDHeader *) buffer, IMD_ENERGIES, 1);
343 memcpy(buffer + HEADERSIZE, energies, sizeof(IMDEnergyBlock));
345 return (imd_write_multiple(socket, buffer, recsize) != recsize);
349 /*! \brief Receive IMD header from socket, sets the length and returns the IMD message. */
350 static IMDMessageType imd_recv_header(IMDSocket *socket, gmx_int32_t *length)
355 if (imd_read_multiple(socket, (char *) &header, HEADERSIZE) != HEADERSIZE)
359 swap_header(&header);
360 *length = header.length;
362 return (IMDMessageType) header.type;
366 /*! \brief Receive force indices and forces.
368 * The number of forces was previously communicated via the header.
370 static int imd_recv_mdcomm(IMDSocket *socket, gmx_int32_t nforces, gmx_int32_t *forcendx, float *forces)
372 int retsize, retbytes;
375 /* reading indices */
376 retsize = sizeof(gmx_int32_t) * nforces;
377 retbytes = imd_read_multiple(socket, (char *) forcendx, retsize);
378 if (retbytes != retsize)
383 /* reading forces as float array */
384 retsize = 3 * sizeof(float) * nforces;
385 retbytes = imd_read_multiple(socket, (char *) forces, retsize);
386 if (retbytes != retsize)
396 /* GROMACS specific functions for the IMD implementation */
398 extern void write_IMDgroup_to_file(gmx_bool bIMD, t_inputrec *ir, t_state *state,
399 gmx_mtop_t *sys, int nfile, const t_filenm fnm[])
406 IMDatoms = gmx_mtop_global_atoms(sys);
407 write_sto_conf_indexed(opt2fn("-imd", nfile, fnm), "IMDgroup", &IMDatoms,
408 state->x, state->v, ir->ePBC, state->box, ir->imd->nat, ir->imd->ind);
413 extern void dd_make_local_IMD_atoms(gmx_bool bIMD, gmx_domdec_t *dd, t_IMD *imd)
416 t_gmx_IMD_setup *IMDsetup;
421 IMDsetup = imd->setup;
424 dd_make_local_group_indices(
425 ga2la, IMDsetup->nat, IMDsetup->ind, &IMDsetup->nat_loc,
426 &IMDsetup->ind_loc, &IMDsetup->nalloc_loc, IMDsetup->xa_ind);
432 /*! \brief Send positions from rvec.
434 * We need a separate send buffer and conversion to Angstrom.
436 static int imd_send_rvecs(IMDSocket *socket, int nat, rvec *x, char *buffer)
441 int tuplesize = 3 * sizeof(float);
444 /* Required size for the send buffer */
445 size = HEADERSIZE + 3 * sizeof(float) * nat;
448 fill_header((IMDHeader *) buffer, IMD_FCOORDS, (gmx_int32_t) nat);
449 for (i = 0; i < nat; i++)
451 sendx[0] = (float) x[i][0] * NM2A;
452 sendx[1] = (float) x[i][1] * NM2A;
453 sendx[2] = (float) x[i][2] * NM2A;
454 memcpy(buffer + HEADERSIZE + i * tuplesize, sendx, tuplesize);
457 return (imd_write_multiple(socket, buffer, size) != size);
461 /*! \brief Initializes the IMD private data. */
462 static t_gmx_IMD_setup* imd_create(int imdatoms, int nstimddef, int imdport)
464 t_gmx_IMD_setup *IMDsetup = NULL;
468 IMDsetup->nat = imdatoms;
469 IMDsetup->bTerminated = FALSE;
470 IMDsetup->bTerminatable = FALSE;
471 IMDsetup->bWConnect = FALSE;
472 IMDsetup->bConnected = FALSE;
473 IMDsetup->bForceActivated = FALSE;
474 IMDsetup->bNewForces = FALSE;
475 IMDsetup->bForceActivated = FALSE;
476 IMDsetup->nstimd = 1;
477 IMDsetup->nstimd_new = 1;
478 IMDsetup->nstimd_def = nstimddef;
482 fprintf(stderr, "%s You chose a port number < 1. Will automatically assign a free port.\n", IMDstr);
486 IMDsetup->port = imdport;
493 /*! \brief Prepare the socket on the MASTER. */
494 static void imd_prepare_master_socket(t_gmx_IMD_setup *IMDsetup)
499 #ifdef GMX_NATIVE_WINDOWS
500 /* Winsock requires separate initialization */
501 fprintf(stderr, "%s Initializing winsock.\n", IMDstr);
502 #ifdef GMX_HAVE_WINSOCK
503 if (imdsock_winsockinit())
505 gmx_fatal(FARGS, "%s Failed to initialize winsock.\n", IMDstr);
510 /* The rest is identical, first create and bind a socket and set to listen then. */
511 fprintf(stderr, "%s Setting up incoming socket.\n", IMDstr);
512 IMDsetup->socket = imdsock_create();
513 if (!IMDsetup->socket)
515 gmx_fatal(FARGS, "%s Failed to create socket.", IMDstr);
519 ret = imdsock_bind(IMDsetup->socket, IMDsetup->port);
522 gmx_fatal(FARGS, "%s binding socket to port %d failed with error %d.\n", IMDstr, IMDsetup->port, ret);
525 if (imd_sock_listen(IMDsetup->socket))
527 gmx_fatal(FARGS, "%s socket listen failed with error %d.\n", IMDstr, ret);
530 if (imdsock_getport(IMDsetup->socket, &IMDsetup->port))
532 gmx_fatal(FARGS, "%s Could not determine port number.\n", IMDstr, ret);
535 fprintf(stderr, "%s Listening for IMD connection on port %d.\n", IMDstr, IMDsetup->port);
539 /*! \brief Disconnect the client. */
540 static void imd_disconnect(t_gmx_IMD_setup *IMDsetup)
542 /* Write out any buffered pulling data */
543 fflush(IMDsetup->outf);
545 /* we first try to shut down the clientsocket */
546 imdsock_shutdown(IMDsetup->clientsocket);
547 if (!imdsock_destroy(IMDsetup->clientsocket))
549 fprintf(stderr, "%s Failed to destroy socket.\n", IMDstr);
552 /* then we reset the IMD step to its default, and reset the connection boolean */
553 IMDsetup->nstimd_new = IMDsetup->nstimd_def;
554 IMDsetup->clientsocket = NULL;
555 IMDsetup->bConnected = FALSE;
559 /*! \brief Prints an error message and disconnects the client.
561 * Does not terminate mdrun!
563 static void imd_fatal(t_gmx_IMD_setup *IMDsetup, const char *msg)
565 fprintf(stderr, "%s %s", IMDstr, msg);
566 imd_disconnect(IMDsetup);
567 fprintf(stderr, "%s disconnected.\n", IMDstr);
571 /*! \brief Check whether we got an incoming connection. */
572 static gmx_bool imd_tryconnect(t_gmx_IMD_setup *IMDsetup)
574 if (imdsock_tryread(IMDsetup->socket, 0, 0) > 0)
576 /* yes, we got something, accept on clientsocket */
577 IMDsetup->clientsocket = imdsock_accept(IMDsetup->socket);
578 if (!IMDsetup->clientsocket)
580 fprintf(stderr, "%s Accepting the connection on the socket failed.\n", IMDstr);
584 /* handshake with client */
585 if (imd_handshake(IMDsetup->clientsocket))
587 imd_fatal(IMDsetup, "Connection failed.\n");
591 fprintf(stderr, "%s Connection established, checking if I got IMD_GO orders.\n", IMDstr);
593 /* Check if we get the proper "GO" command from client. */
594 if (imdsock_tryread(IMDsetup->clientsocket, IMDCONNECTWAIT, 0) != 1 || imd_recv_header(IMDsetup->clientsocket, &(IMDsetup->length)) != IMD_GO)
596 imd_fatal(IMDsetup, "No IMD_GO order received. IMD connection failed.\n");
600 IMDsetup->bConnected = TRUE;
609 /*! \brief Wrap imd_tryconnect in order to make it blocking.
611 * Used when the simulation should wait for an incoming connection.
613 static void imd_blockconnect(t_gmx_IMD_setup *IMDsetup)
615 /* do not wait for connection, when e.g. ctrl+c is pressed and we will terminate anyways. */
616 if (!(int) gmx_get_stop_condition() == gmx_stop_cond_none)
621 fprintf(stderr, "%s Will wait until I have a connection and IMD_GO orders.\n", IMDstr);
623 /* while we have no clientsocket... 2nd part: we should still react on ctrl+c */
624 while ((!IMDsetup->clientsocket) && ((int) gmx_get_stop_condition() == gmx_stop_cond_none))
626 imd_tryconnect(IMDsetup);
627 #ifdef GMX_NATIVE_WINDOWS
628 /* for whatever reason, it is called Sleep on windows */
637 /*! \brief Make sure that our array holding the forces received via IMD is large enough. */
638 static void imd_prepare_vmd_Forces(t_gmx_IMD_setup *IMDsetup)
640 srenew((IMDsetup->vmd_f_ind), IMDsetup->vmd_nforces);
641 srenew((IMDsetup->vmd_forces), 3*IMDsetup->vmd_nforces);
645 /*! \brief Reads forces received via IMD. */
646 static void imd_read_vmd_Forces(t_gmx_IMD_setup *IMDsetup)
648 /* the length of the previously received header tells us the nr of forces we will receive */
649 IMDsetup->vmd_nforces = IMDsetup->length;
650 /* prepare the arrays */
651 imd_prepare_vmd_Forces(IMDsetup);
652 /* Now we read the forces... */
653 if (!(imd_recv_mdcomm(IMDsetup->clientsocket, IMDsetup->vmd_nforces, IMDsetup->vmd_f_ind, IMDsetup->vmd_forces)))
655 imd_fatal(IMDsetup, "Error while reading forces from remote. Disconnecting\n");
660 /*! \brief Prepares the MD force arrays. */
661 static void imd_prepare_MD_Forces(t_gmx_IMD_setup *IMDsetup)
663 srenew((IMDsetup->f_ind), IMDsetup->nforces);
664 srenew((IMDsetup->f ), IMDsetup->nforces);
668 /*! \brief Copy IMD forces to MD forces.
670 * Do conversion from Cal->Joule and from
671 * Angstrom -> nm and from a pointer array to arrays to 3*N array.
673 static void imd_copyto_MD_Forces(t_gmx_IMD_setup *IMDsetup)
676 real conversion = CAL2JOULE * NM2A;
679 for (i = 0; i < IMDsetup->nforces; i++)
681 /* Copy the indices, a copy is important because we may update the incoming forces
682 * whenever we receive new forces while the MD forces are only communicated upon
683 * IMD communication.*/
684 IMDsetup->f_ind[i] = IMDsetup->vmd_f_ind[i];
686 /* Convert to rvecs and do a proper unit conversion */
687 IMDsetup->f[i][0] = IMDsetup->vmd_forces[3*i ] * conversion;
688 IMDsetup->f[i][1] = IMDsetup->vmd_forces[3*i + 1] * conversion;
689 IMDsetup->f[i][2] = IMDsetup->vmd_forces[3*i + 2] * conversion;
694 /*! \brief Return TRUE if any of the forces or indices changed. */
695 static gmx_bool bForcesChanged(t_gmx_IMD_setup *IMDsetup)
700 /* First, check whether the number of pulled atoms changed */
701 if (IMDsetup->nforces != IMDsetup->old_nforces)
706 /* Second, check whether any of the involved atoms changed */
707 for (i = 0; i < IMDsetup->nforces; i++)
709 if (IMDsetup->f_ind[i] != IMDsetup->old_f_ind[i])
715 /* Third, check whether all forces are the same */
716 for (i = 0; i < IMDsetup->nforces; i++)
718 if (IMDsetup->f[i][XX] != IMDsetup->old_forces[i][XX])
722 if (IMDsetup->f[i][YY] != IMDsetup->old_forces[i][YY])
726 if (IMDsetup->f[i][ZZ] != IMDsetup->old_forces[i][ZZ])
732 /* All old and new forces are identical! */
737 /*! \brief Fill the old_f_ind and old_forces arrays with the new, old values. */
738 static void keep_old_values(t_gmx_IMD_setup *IMDsetup)
743 IMDsetup->old_nforces = IMDsetup->nforces;
745 for (i = 0; i < IMDsetup->nforces; i++)
747 IMDsetup->old_f_ind[i] = IMDsetup->f_ind[i];
748 copy_rvec(IMDsetup->f[i], IMDsetup->old_forces[i]);
753 /*! \brief Returns TRUE if any component of the two rvecs differs. */
754 static gmx_inline gmx_bool rvecs_differ(const rvec v1, const rvec v2)
759 for (i = 0; i < DIM; i++)
771 /*! \brief Write the applied pull forces to logfile.
773 * Call on master only!
775 static void output_imd_forces(t_inputrec *ir, double time)
777 t_gmx_IMD_setup *IMDsetup;
781 IMDsetup = ir->imd->setup;
783 if (bForcesChanged(IMDsetup))
785 /* Write time and total number of applied IMD forces */
786 fprintf(IMDsetup->outf, "%14.6e%6d", time, IMDsetup->nforces);
788 /* Write out the global atom indices of the pulled atoms and the forces itself,
789 * write out a force only if it has changed since the last output */
790 for (i = 0; i < IMDsetup->nforces; i++)
792 if (rvecs_differ(IMDsetup->f[i], IMDsetup->old_forces[i]))
794 fprintf(IMDsetup->outf, "%9d", IMDsetup->ind[IMDsetup->f_ind[i]] + 1);
795 fprintf(IMDsetup->outf, "%12.4e%12.4e%12.4e", IMDsetup->f[i][0], IMDsetup->f[i][1], IMDsetup->f[i][2]);
798 fprintf(IMDsetup->outf, "\n");
800 keep_old_values(IMDsetup);
805 /*! \brief Synchronize the nodes. */
806 static void imd_sync_nodes(t_inputrec *ir, t_commrec *cr, double t)
809 t_gmx_IMD_setup *IMDsetup;
813 IMDsetup = ir->imd->setup;
815 /* Notify the other nodes whether we are still connected. */
818 block_bc(cr, IMDsetup->bConnected);
821 /* ...if not connected, the job is done here. */
822 if (!IMDsetup->bConnected)
827 /* Let the other nodes know whether we got a new IMD synchronization frequency. */
830 block_bc(cr, IMDsetup->nstimd_new);
833 /* Now we all set the (new) nstimd communication time step */
834 IMDsetup->nstimd = IMDsetup->nstimd_new;
836 /* We're done if we don't allow pulling at all */
837 if (!(IMDsetup->bForceActivated))
842 /* OK, let's check if we have received forces which we need to communicate
843 * to the other nodes */
846 if (IMDsetup->bNewForces)
848 new_nforces = IMDsetup->vmd_nforces;
850 /* make the "new_forces" negative, when we did not receive new ones */
853 new_nforces = IMDsetup->vmd_nforces * -1;
857 /* make new_forces known to the clients */
860 block_bc(cr, new_nforces);
863 /* When new_natoms < 0 then we know that these are still the same forces
864 * so we don't communicate them, otherwise... */
865 if (new_nforces >= 0)
867 /* set local VMD and nforces */
868 IMDsetup->vmd_nforces = new_nforces;
869 IMDsetup->nforces = IMDsetup->vmd_nforces;
871 /* now everybody knows the number of forces in f_ind, so we can prepare
872 * the target arrays for indices and forces */
873 imd_prepare_MD_Forces(IMDsetup);
875 /* we first update the MD forces on the master by converting the VMD forces */
878 imd_copyto_MD_Forces(IMDsetup);
879 /* We also write out forces on every update, so that we know which
880 * forces are applied for every step */
883 output_imd_forces(ir, t);
887 /* In parallel mode we communicate the to-be-applied forces to the other nodes */
890 nblock_bc(cr, IMDsetup->nforces, IMDsetup->f_ind);
891 nblock_bc(cr, IMDsetup->nforces, IMDsetup->f );
894 /* done communicating the forces, reset bNewForces */
895 IMDsetup->bNewForces = FALSE;
900 /*! \brief Reads header from the client and decides what to do. */
901 static void imd_readcommand(t_gmx_IMD_setup *IMDsetup)
903 gmx_bool IMDpaused = FALSE;
904 IMDMessageType itype;
907 while (IMDsetup->clientsocket && (imdsock_tryread(IMDsetup->clientsocket, 0, 0) > 0 || IMDpaused))
909 itype = imd_recv_header(IMDsetup->clientsocket, &(IMDsetup->length));
910 /* let's see what we got: */
913 /* IMD asks us to terminate the simulation, check if the user allowed this */
915 if (IMDsetup->bTerminatable)
917 fprintf(stderr, " %s Terminating connection and running simulation (if supported by integrator).\n", IMDstr);
918 IMDsetup->bTerminated = TRUE;
919 IMDsetup->bWConnect = FALSE;
920 gmx_set_stop_condition(gmx_stop_cond_next);
924 fprintf(stderr, " %s Set -imdterm command line switch to allow mdrun termination from within IMD.\n", IMDstr);
929 /* the client doen't want to talk to us anymore */
931 fprintf(stderr, " %s Disconnecting client.\n", IMDstr);
932 imd_disconnect(IMDsetup);
935 /* we got new forces, read them and set bNewForces flag */
937 imd_read_vmd_Forces(IMDsetup);
938 IMDsetup->bNewForces = TRUE;
941 /* the client asks us to (un)pause the simulation. So we toggle the IMDpaused state */
945 fprintf(stderr, " %s Un-pause command received.\n", IMDstr);
950 fprintf(stderr, " %s Pause command received.\n", IMDstr);
956 /* the client sets a new transfer rate, if we get 0, we reset the rate
957 * to the default. VMD filters 0 however */
959 IMDsetup->nstimd_new = (IMDsetup->length > 0) ? IMDsetup->length : IMDsetup->nstimd_def;
960 fprintf(stderr, " %s Update frequency will be set to %d.\n", IMDstr, IMDsetup->nstimd_new);
963 /* Catch all rule for the remaining IMD types which we don't expect */
965 fprintf(stderr, " %s Received unexpected %s.\n", IMDstr, ENUM_NAME((int)itype, IMD_NR, eIMDType_names));
966 imd_fatal(IMDsetup, "Terminating connection\n");
973 /*! \brief Open IMD output file and write header information.
975 * Call on master only.
977 static FILE *open_imd_out(
979 t_gmx_IMD_setup *IMDsetup,
987 /* Open log file of applied IMD forces if requested */
990 /* If we append to an existing file, all the header information is already there */
991 if (Flags & MD_APPENDFILES)
993 fp = gmx_fio_fopen(fn, "a+");
997 fp = gmx_fio_fopen(fn, "w+");
998 if (IMDsetup->nat == nat_total)
1000 fprintf(fp, "# Note that you can select an IMD index group in the .mdp file if a subset of the atoms suffices.\n");
1003 xvgr_header(fp, "IMD Pull Forces", "Time (ps)", "# of Forces / Atom IDs / Forces (kJ/mol)", exvggtNONE, oenv);
1005 fprintf(fp, "# Can display and manipulate %d (of a total of %d) atoms via IMD.\n", IMDsetup->nat, nat_total);
1006 fprintf(fp, "# column 1 : time (ps)\n");
1007 fprintf(fp, "# column 2 : total number of atoms feeling an IMD pulling force at that time\n");
1008 fprintf(fp, "# cols. 3.-6 : global atom number of pulled atom, x-force, y-force, z-force (kJ/mol)\n");
1009 fprintf(fp, "# then follow : atom-ID, f[x], f[y], f[z] for more atoms in case the force on multiple atoms is changed simultaneously.\n");
1010 fprintf(fp, "# Note that the force on any atom is always equal to the last value for that atom-ID found in the data.\n");
1014 /* To reduce the output file size we remember the old values and output only
1015 * when something changed */
1016 snew(IMDsetup->old_f_ind, IMDsetup->nat); /* One can never pull on more atoms */
1017 snew(IMDsetup->old_forces, IMDsetup->nat);
1022 fprintf(stdout, "%s For a log of the IMD pull forces explicitly specify '-if' on the command line.\n"
1023 "%s (Not possible with energy minimization.)\n", IMDstr, IMDstr);
1030 extern void IMD_finalize(gmx_bool bIMD, t_IMD *imd)
1034 if (imd->setup->outf)
1036 gmx_fio_fclose(imd->setup->outf);
1043 /*! \brief Creates the molecule start-end position array of molecules in the IMD group. */
1044 static void init_imd_prepare_mols_in_imdgroup(t_gmx_IMD_setup *IMDsetup, gmx_mtop_t *top_global)
1047 int gstart, gend, count;
1048 t_block gmols, lmols;
1052 gmols = top_global->mols;
1053 nat = IMDsetup->nat;
1054 ind = IMDsetup->ind;
1058 /* check whether index is sorted */
1059 for (i = 0; i < nat-1; i++)
1061 if (ind[i] > ind[i+1])
1063 gmx_fatal(FARGS, "%s IMD index is not sorted. This is currently not supported.\n", IMDstr);
1067 snew(lmols.index, gmols.nr+1);
1070 for (i = 0; i < gmols.nr; i++)
1072 gstart = gmols.index[i];
1073 gend = gmols.index[i+1];
1075 for (ii = 0; ii < nat; ii++)
1077 if ((ind[ii] >= gstart) && (ind[ii] < gend))
1084 lmols.index[lmols.nr+1] = lmols.index[lmols.nr]+count;
1088 srenew(lmols.index, lmols.nr+1);
1089 lmols.nalloc_index = lmols.nr+1;
1090 IMDsetup->mols = lmols;
1094 /*! \brief Copied and modified from groupcoord.c shift_positions_group(). */
1095 static void shift_positions(
1097 rvec x[], /* The positions [0..nr] */
1098 ivec is, /* The shift [0..nr] */
1099 int nr) /* The number of positions */
1103 /* Loop over the group's atoms */
1106 for (i = 0; i < nr; i++)
1112 x[i][XX] = x[i][XX]-tx*box[XX][XX]-ty*box[YY][XX]-tz*box[ZZ][XX];
1113 x[i][YY] = x[i][YY]-ty*box[YY][YY]-tz*box[ZZ][YY];
1114 x[i][ZZ] = x[i][ZZ]-tz*box[ZZ][ZZ];
1119 for (i = 0; i < nr; i++)
1125 x[i][XX] = x[i][XX]-tx*box[XX][XX];
1126 x[i][YY] = x[i][YY]-ty*box[YY][YY];
1127 x[i][ZZ] = x[i][ZZ]-tz*box[ZZ][ZZ];
1133 /*! \brief Removes shifts of molecules diffused outside of the box. */
1134 static void imd_remove_molshifts(t_gmx_IMD_setup *IMDsetup, matrix box)
1137 ivec largest, smallest, shift;
1141 mols = IMDsetup->mols;
1143 /* for each molecule also present in IMD group */
1144 for (i = 0; i < mols.nr; i++)
1146 /* first we determine the minimum and maximum shifts for each molecule */
1148 clear_ivec(largest);
1149 clear_ivec(smallest);
1152 copy_ivec(IMDsetup->xa_shifts[mols.index[i]], largest);
1153 copy_ivec(IMDsetup->xa_shifts[mols.index[i]], smallest);
1155 for (ii = mols.index[i]+1; ii < mols.index[i+1]; ii++)
1157 if (IMDsetup->xa_shifts[ii][XX] > largest[XX])
1159 largest[XX] = IMDsetup->xa_shifts[ii][XX];
1161 if (IMDsetup->xa_shifts[ii][XX] < smallest[XX])
1163 smallest[XX] = IMDsetup->xa_shifts[ii][XX];
1166 if (IMDsetup->xa_shifts[ii][YY] > largest[YY])
1168 largest[YY] = IMDsetup->xa_shifts[ii][YY];
1170 if (IMDsetup->xa_shifts[ii][YY] < smallest[YY])
1172 smallest[YY] = IMDsetup->xa_shifts[ii][YY];
1175 if (IMDsetup->xa_shifts[ii][ZZ] > largest[ZZ])
1177 largest[ZZ] = IMDsetup->xa_shifts[ii][ZZ];
1179 if (IMDsetup->xa_shifts[ii][ZZ] < smallest[ZZ])
1181 smallest[ZZ] = IMDsetup->xa_shifts[ii][ZZ];
1186 /* check if we what we can subtract/add to the positions
1187 * to put them back into the central box */
1188 if (smallest[XX] > 0)
1190 shift[XX] = smallest[XX];
1192 if (smallest[YY] > 0)
1194 shift[YY] = smallest[YY];
1196 if (smallest[ZZ] > 0)
1198 shift[ZZ] = smallest[ZZ];
1201 if (largest[XX] < 0)
1203 shift[XX] = largest[XX];
1205 if (largest[YY] < 0)
1207 shift[YY] = largest[YY];
1209 if (largest[ZZ] < 0)
1211 shift[ZZ] = largest[ZZ];
1214 /* is there a shift at all? */
1215 if ((shift[XX]) || (shift[YY]) || (shift[ZZ]))
1217 molsize = mols.index[i+1]-mols.index[i];
1218 /* shift the positions */
1219 shift_positions(box, &(IMDsetup->xa[mols.index[i]]), shift, molsize);
1226 /*! \brief Initialize arrays used to assemble the positions from the other nodes. */
1227 static void init_imd_prepare_for_x_assembly(t_commrec *cr, rvec x[], t_gmx_IMD_setup *IMDsetup)
1232 snew(IMDsetup->xa, IMDsetup->nat);
1233 snew(IMDsetup->xa_ind, IMDsetup->nat);
1234 snew(IMDsetup->xa_shifts, IMDsetup->nat);
1235 snew(IMDsetup->xa_eshifts, IMDsetup->nat);
1236 snew(IMDsetup->xa_old, IMDsetup->nat);
1238 /* Save the original (whole) set of positions such that later the
1239 * molecule can always be made whole again */
1242 for (i = 0; i < IMDsetup->nat; i++)
1244 ii = IMDsetup->ind[i];
1245 copy_rvec(x[ii], IMDsetup->xa_old[i]);
1251 IMDsetup->nat_loc = IMDsetup->nat;
1252 IMDsetup->ind_loc = IMDsetup->ind;
1254 /* xa_ind[i] needs to be set to i for serial runs */
1255 for (i = 0; i < IMDsetup->nat; i++)
1257 IMDsetup->xa_ind[i] = i;
1261 /* Communicate initial coordinates xa_old to all processes */
1265 gmx_bcast(IMDsetup->nat * sizeof(IMDsetup->xa_old[0]), IMDsetup->xa_old, cr);
1272 /*! \brief Check for non-working integrator / parallel options. */
1273 static void imd_check_integrator_parallel(t_inputrec *ir, t_commrec *cr)
1277 if (((ir->eI) == eiSteep) || ((ir->eI) == eiCG) || ((ir->eI) == eiLBFGS) || ((ir->eI) == eiNM))
1279 gmx_fatal(FARGS, "%s Energy minimization via steep, CG, lbfgs and nm in parallel is currently not supported by IMD.\n", IMDstr);
1286 extern void init_IMD(
1289 gmx_mtop_t *top_global,
1294 const t_filenm fnm[],
1297 unsigned long Flags)
1301 t_gmx_IMD_setup *IMDsetup;
1302 gmx_int32_t bufxsize;
1303 gmx_bool bIMD = FALSE;
1306 /* We will allow IMD sessions only if explicitly enabled in the .tpr file */
1307 if (FALSE == ir->bIMD)
1312 /* It seems we have a .tpr file that defines an IMD group and thus allows IMD sessions.
1313 * Check whether we can actually provide the IMD functionality for this setting: */
1316 /* Check whether IMD was enabled by one of the command line switches: */
1317 if ((Flags & MD_IMDWAIT) || (Flags & MD_IMDTERM) || (Flags & MD_IMDPULL))
1319 /* Multiple simulations or replica exchange */
1322 fprintf(stderr, "%s Cannot use IMD for multiple simulations or replica exchange.\n", IMDstr);
1324 /* OK, IMD seems to be allowed and turned on... */
1327 fprintf(stderr, "%s Enabled. This simulation will accept incoming IMD connections.\n", IMDstr);
1333 fprintf(stderr, "%s None of the -imd switches was used.\n"
1334 "%s This run will not accept incoming IMD connections\n", IMDstr, IMDstr);
1336 } /* end master only */
1338 /* Disable IMD if not all the needed functionality is there! */
1339 #if defined(GMX_NATIVE_WINDOWS) && !defined(GMX_HAVE_WINSOCK)
1341 fprintf(stderr, "Disabling IMD because the winsock library was not found at compile time.\n");
1344 /* Let the other nodes know whether we want IMD */
1349 /* ... and update our local inputrec accordingly. */
1352 /*... if not we are done.*/
1359 /* check if we're using a sane integrator / parallel combination */
1360 imd_check_integrator_parallel(ir, cr);
1364 *****************************************************
1365 * From here on we assume that IMD is turned on *
1366 *****************************************************
1370 nat_total = top_global->natoms;
1372 /* Initialize IMD setup structure. If we read in a pre-IMD .tpr file, imd->nat
1373 * will be zero. For those cases we transfer _all_ atomic positions */
1374 ir->imd->setup = imd_create(ir->imd->nat > 0 ? ir->imd->nat : nat_total,
1375 defnstimd, imdport);
1376 IMDsetup = ir->imd->setup;
1378 /* We might need to open an output file for IMD forces data */
1381 IMDsetup->outf = open_imd_out(opt2fn("-if", nfile, fnm), ir->imd->setup, nat_total, oenv, Flags);
1384 /* Make sure that we operate with a valid atom index array for the IMD atoms */
1385 if (ir->imd->nat > 0)
1387 /* Point to the user-supplied array of atom numbers */
1388 IMDsetup->ind = ir->imd->ind;
1392 /* Make a dummy (ind[i] = i) array of all atoms */
1393 snew(IMDsetup->ind, nat_total);
1394 for (i = 0; i < nat_total; i++)
1396 IMDsetup->ind[i] = i;
1400 /* read environment on master and prepare socket for incoming connections */
1403 /* we allocate memory for our IMD energy structure */
1404 gmx_int32_t recsize = HEADERSIZE + sizeof(IMDEnergyBlock);
1405 snew(IMDsetup->energysendbuf, recsize);
1407 /* Shall we wait for a connection? */
1408 if (Flags & MD_IMDWAIT)
1410 IMDsetup->bWConnect = TRUE;
1411 fprintf(stderr, "%s Pausing simulation while no IMD connection present (-imdwait).\n", IMDstr);
1414 /* Will the IMD clients be able to terminate the simulation? */
1415 if (Flags & MD_IMDTERM)
1417 IMDsetup->bTerminatable = TRUE;
1418 fprintf(stderr, "%s Allow termination of the simulation from IMD client (-imdterm).\n", IMDstr);
1421 /* Is pulling from IMD client allowed? */
1422 if (Flags & MD_IMDPULL)
1424 IMDsetup->bForceActivated = TRUE;
1425 fprintf(stderr, "%s Pulling from IMD remote is enabled (-imdpull).\n", IMDstr);
1428 /* Initialize send buffers with constant size */
1429 snew(IMDsetup->sendxbuf, IMDsetup->nat);
1430 snew(IMDsetup->energies, 1);
1431 bufxsize = HEADERSIZE + 3 * sizeof(float) * IMDsetup->nat;
1432 snew(IMDsetup->coordsendbuf, bufxsize);
1435 /* do we allow interactive pulling? If so let the other nodes know. */
1438 block_bc(cr, IMDsetup->bForceActivated);
1441 /* setup the listening socket on master process */
1444 fprintf(fplog, "%s Setting port for connection requests to %d.\n", IMDstr, IMDsetup->port);
1445 fprintf(stderr, "%s Turning on IMD - port for incoming requests is %d.\n", IMDstr, IMDsetup->port);
1446 imd_prepare_master_socket(IMDsetup);
1447 /* Wait until we have a connection if specified before */
1448 if (IMDsetup->bWConnect)
1450 imd_blockconnect(IMDsetup);
1454 fprintf(stderr, "%s -imdwait not set, starting simulation.\n", IMDstr);
1457 /* Let the other nodes know whether we are connected */
1458 imd_sync_nodes(ir, cr, 0);
1460 /* Initialize arrays used to assemble the positions from the other nodes */
1461 init_imd_prepare_for_x_assembly(cr, x, IMDsetup);
1463 /* Initialize molecule blocks to make them whole later...*/
1466 init_imd_prepare_mols_in_imdgroup(IMDsetup, top_global);
1469 gmx_incons("init_IMD: this GROMACS version was not compiled with IMD support!");
1474 extern gmx_bool do_IMD(
1483 gmx_wallcycle_t wcycle)
1485 gmx_bool imdstep = FALSE;
1486 t_gmx_IMD_setup *IMDsetup;
1496 wallcycle_start(wcycle, ewcIMD);
1498 IMDsetup = ir->imd->setup;
1500 /* read command from client and check if new incoming connection */
1503 /* If not already connected, check for new connections */
1504 if (!IMDsetup->clientsocket)
1506 if (IMDsetup->bWConnect)
1508 imd_blockconnect(IMDsetup);
1512 imd_tryconnect(IMDsetup);
1516 /* Let's see if we have new IMD messages for us */
1517 if (IMDsetup->clientsocket)
1519 imd_readcommand(IMDsetup);
1523 /* is this an IMD communication step? */
1524 imdstep = do_per_step(step, IMDsetup->nstimd);
1526 /* OK so this is an IMD step ... */
1529 /* First we sync all nodes to let everybody know whether we are connected to VMD */
1530 imd_sync_nodes(ir, cr, t);
1533 /* If a client is connected, we collect the positions
1534 * and put molecules back into the box before transfer */
1535 if ((imdstep && IMDsetup->bConnected)
1536 || bNS) /* independent of imdstep, we communicate positions at each NS step */
1538 /* Transfer the IMD positions to the master node. Every node contributes
1539 * its local positions x and stores them in the assembled xa array. */
1540 communicate_group_positions(cr, IMDsetup->xa, IMDsetup->xa_shifts, IMDsetup->xa_eshifts,
1541 TRUE, x, IMDsetup->nat, IMDsetup->nat_loc,
1542 IMDsetup->ind_loc, IMDsetup->xa_ind, IMDsetup->xa_old, box);
1544 /* If connected and master -> remove shifts */
1545 if ((imdstep && IMDsetup->bConnected) && MASTER(cr))
1547 imd_remove_molshifts(IMDsetup, box);
1551 wallcycle_stop(wcycle, ewcIMD);
1553 gmx_incons("do_IMD called without IMD support!");
1560 extern void IMD_fill_energy_record(gmx_bool bIMD, t_IMD *imd, gmx_enerdata_t *enerd,
1561 gmx_int64_t step, gmx_bool bHaveNewEnergies)
1563 IMDEnergyBlock *ene;
1570 IMDsetup = imd->setup;
1572 if (IMDsetup->clientsocket)
1574 ene = IMDsetup->energies;
1578 /* In MPI-parallel simulations the energies are not accessible a at every time step.
1579 * We update them if we have new values, otherwise, the energy values from the
1580 * last global communication step are still on display in the viewer. */
1581 if (bHaveNewEnergies)
1583 ene->T_abs = (float) enerd->term[F_TEMP ];
1584 ene->E_pot = (float) enerd->term[F_EPOT ];
1585 ene->E_tot = (float) enerd->term[F_ETOT ];
1586 ene->E_bond = (float) enerd->term[F_BONDS ];
1587 ene->E_angle = (float) enerd->term[F_ANGLES ];
1588 ene->E_dihe = (float) enerd->term[F_PDIHS ];
1589 ene->E_impr = (float) enerd->term[F_IDIHS ];
1590 ene->E_vdw = (float) enerd->term[F_LJ ];
1591 ene->E_coul = (float) (enerd->term[F_COUL_SR] + enerd->term[F_COUL_LR]);
1595 gmx_incons("IMD_fill_energy_record called without IMD support.");
1601 extern void IMD_send_positions(t_IMD *imd)
1607 IMDsetup = imd->setup;
1609 if (IMDsetup->clientsocket)
1612 if (imd_send_energies(IMDsetup->clientsocket, IMDsetup->energies, IMDsetup->energysendbuf))
1614 imd_fatal(IMDsetup, "Error sending updated energies. Disconnecting client.\n");
1617 if (imd_send_rvecs(IMDsetup->clientsocket, IMDsetup->nat, IMDsetup->xa, IMDsetup->coordsendbuf))
1619 imd_fatal(IMDsetup, "Error sending updated positions. Disconnecting client.\n");
1623 gmx_incons("IMD_send_positions called without IMD support.");
1628 extern void IMD_prep_energies_send_positions(gmx_bool bIMD, gmx_bool bIMDstep,
1629 t_IMD *imd, gmx_enerdata_t *enerd,
1630 gmx_int64_t step, gmx_bool bHaveNewEnergies,
1631 gmx_wallcycle_t wcycle)
1636 wallcycle_start(wcycle, ewcIMD);
1638 /* Update time step for IMD and prepare IMD energy record if we have new energies. */
1639 IMD_fill_energy_record(TRUE, imd, enerd, step, bHaveNewEnergies);
1643 /* Send positions and energies to VMD client via IMD */
1644 IMD_send_positions(imd);
1647 wallcycle_stop(wcycle, ewcIMD);
1649 gmx_incons("IMD_prep_energies_send_positions called without IMD support.");
1655 extern int IMD_get_step(t_gmx_IMD IMDsetup)
1657 return IMDsetup->nstimd;
1661 extern void IMD_apply_forces(gmx_bool bIMD, t_IMD *imd, t_commrec *cr, rvec *f,
1662 gmx_wallcycle_t wcycle)
1666 t_gmx_IMD_setup *IMDsetup;
1672 wallcycle_start(wcycle, ewcIMD);
1674 IMDsetup = imd->setup;
1676 /* Are forces allowed at all? If not we're done */
1677 if (!IMDsetup->bForceActivated)
1682 for (i = 0; i < IMDsetup->nforces; i++)
1684 /* j are the indices in the "System group".*/
1685 j = IMDsetup->ind[IMDsetup->f_ind[i]];
1687 /* check if this is a local atom and find out locndx */
1688 if (PAR(cr) && ga2la_get_home(cr->dd->ga2la, j, &locndx))
1693 rvec_inc(f[j], IMDsetup->f[i]);
1696 wallcycle_start(wcycle, ewcIMD);
1698 gmx_incons("IMD_apply_forces called without IMD support.");