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>
54 #ifdef GMX_NATIVE_WINDOWS
61 #include "imdsocket.h"
64 #include "sighandler.h"
65 #include "gmx_ga2la.h"
66 #include "gromacs/mdlib/groupcoord.h"
67 #include "gromacs/fileio/confio.h"
68 #include "gromacs/topology/mtop_util.h"
70 #include "gromacs/timing/wallcycle.h"
72 #include "gromacs/fileio/xvgr.h"
73 #include "gromacs/math/vec.h"
74 #include "gromacs/pbcutil/pbc.h"
75 #include "gromacs/utility/fatalerror.h"
76 #include "gromacs/utility/smalloc.h"
78 /*! \brief How long shall we wait in seconds until we check for a connection again? */
81 /*! \brief How long shall we check for the IMD_GO? */
82 #define IMDCONNECTWAIT 2
84 /*! \brief IMD Header Size. */
86 /*! \brief IMD Protocol Version. */
89 /*! \brief Broadcast d to all nodes */
90 #define block_bc(cr, d) gmx_bcast(sizeof(d), &(d), (cr))
92 /*! \brief Broadcast nr elements of d to all nodes */
93 #define nblock_bc(cr, nr, d) gmx_bcast((nr)*sizeof((d)[0]), (d), (cr))
98 * IMD (interactive molecular dynamics) energy record.
100 * As in the original IMD implementation. Energies in kcal/mol.
101 * NOTE: We return the energies in GROMACS / SI units,
102 * so they also show up as SI in VMD.
107 gmx_int32_t tstep; /**< time step */
108 float T_abs; /**< absolute temperature */
109 float E_tot; /**< total energy */
110 float E_pot; /**< potential energy */
111 float E_vdw; /**< van der Waals energy */
112 float E_coul; /**< Coulomb interaction energy */
113 float E_bond; /**< bonds energy */
114 float E_angle; /**< angles energy */
115 float E_dihe; /**< dihedrals energy */
116 float E_impr; /**< improper dihedrals energy */
121 * \brief IMD (interactive molecular dynamics) communication structure.
123 * This structure defines the IMD communication message header & protocol version.
127 gmx_int32_t type; /**< Type of IMD message, see IMDType_t above */
128 gmx_int32_t length; /**< Length */
133 * \brief IMD (interactive molecular dynamics) main data structure.
135 * Contains private IMD data
137 typedef struct gmx_IMD
139 FILE *outf; /**< Output file for IMD data, mainly forces. */
141 int nat; /**< Number of atoms that can be pulled via IMD. */
142 int nat_loc; /**< Part of the atoms that are local. */
143 atom_id *ind; /**< Global indices of the IMD atoms. */
144 atom_id *ind_loc; /**< Local indices of the IMD atoms. */
145 int nalloc_loc; /**< Allocation size for ind_loc. */
146 rvec *xa; /**< Positions for all IMD atoms assembled on
148 ivec *xa_shifts; /**< Shifts for all IMD atoms, to make
149 molecule(s) whole. */
150 ivec *xa_eshifts; /**< Extra shifts since last DD step. */
151 rvec *xa_old; /**< Old positions for all IMD atoms on master. */
152 int *xa_ind; /**< Position of each local atom in the
155 int nstimd; /**< Global IMD frequency, known to all nodes. */
156 int nstimd_new; /**< New frequency from IMD client, master only. */
157 int nstimd_def; /**< Default IMD frequency when disconnected. */
159 int port; /**< Port to use for network socket. */
160 IMDSocket *socket; /**< The IMD socket on the master node. */
161 IMDSocket *clientsocket; /**< The IMD socket on the client. */
162 int length; /**< Length we got with last header. */
164 gmx_bool bWConnect; /**< Shall we block and wait for connection? */
165 gmx_bool bTerminated; /**< Set if MD is terminated. */
166 gmx_bool bTerminatable; /**< Set if MD can be terminated. */
167 gmx_bool bConnected; /**< Set if connection is present. */
168 gmx_bool bNewForces; /**< Set if we received new forces. */
169 gmx_bool bForceActivated; /**< Set if pulling from VMD is allowed. */
171 IMDEnergyBlock *energies; /**< Pointer to energies we send back. */
173 gmx_int32_t vmd_nforces; /**< Number of VMD forces. */
174 gmx_int32_t *vmd_f_ind; /**< VMD forces indices. */
175 float *vmd_forces; /**< The VMD forces flat in memory. */
176 int nforces; /**< Number of actual MD forces;
177 this gets communicated to the clients. */
178 atom_id *f_ind; /**< Force indices. */
179 rvec *f; /**< The IMD pulling forces. */
181 char *forcesendbuf; /**< Buffer for force sending. */
182 char *coordsendbuf; /**< Buffer for coordinate sending. */
183 char *energysendbuf; /**< Send buffer for energies. */
184 rvec *sendxbuf; /**< Buffer to make molecules whole before
187 t_block mols; /**< Molecules block in IMD group. */
189 /* The next block is used on the master node only to reduce the output
190 * without sacrificing information. If any of these values changes,
191 * we need to write output */
192 int old_nforces; /**< Old value for nforces. */
193 atom_id *old_f_ind; /**< Old values for force indices. */
194 rvec *old_forces; /**< Old values for IMD pulling forces. */
200 * \brief Enum for types of IMD messages.
202 * We use the same records as the NAMD/VMD IMD implementation.
204 typedef enum IMDType_t
206 IMD_DISCONNECT, /**< client disconnect */
207 IMD_ENERGIES, /**< energy data */
208 IMD_FCOORDS, /**< atomic coordinates */
209 IMD_GO, /**< start command for the simulation */
210 IMD_HANDSHAKE, /**< handshake to determine little/big endianness */
211 IMD_KILL, /**< terminates the simulation */
212 IMD_MDCOMM, /**< force data */
213 IMD_PAUSE, /**< pauses the simulation */
214 IMD_TRATE, /**< sets the IMD transmission and processing rate */
215 IMD_IOERROR, /**< I/O error */
216 IMD_NR /**< number of entries */
221 * \brief Names of the IMDType for error messages.
223 const char *eIMDType_names[IMD_NR + 1] = {
240 /*! \brief Fills the header with message and the length argument. */
241 static void fill_header(IMDHeader *header, IMDMessageType type, gmx_int32_t length)
243 /* We (ab-)use htonl network function for the correct endianness */
244 header->type = htonl((gmx_int32_t) type);
245 header->length = htonl(length);
249 /*! \brief Swaps the endianess of the header. */
250 static void swap_header(IMDHeader *header)
252 /* and vice versa... */
253 header->type = ntohl(header->type);
254 header->length = ntohl(header->length);
258 /*! \brief Reads multiple bytes from socket. */
259 static gmx_int32_t imd_read_multiple(IMDSocket *socket, char *datptr, gmx_int32_t toread)
261 gmx_int32_t leftcount, countread;
265 /* Try to read while we haven't reached toread */
266 while (leftcount != 0)
268 if ((countread = imdsock_read(socket, datptr, leftcount)) < 0)
270 /* interrupted function call, try again... */
275 /* this is an unexpected error, return what we got */
278 return toread - leftcount;
281 /* nothing read, finished */
283 else if (countread == 0)
287 leftcount -= countread;
291 /* return nr of bytes read */
292 return toread - leftcount;
296 /*! \brief Writes multiple bytes to socket in analogy to imd_read_multiple. */
297 static gmx_int32_t imd_write_multiple(IMDSocket *socket, const char *datptr, gmx_int32_t towrite)
299 gmx_int32_t leftcount, countwritten;
303 while (leftcount != 0)
305 if ((countwritten = imdsock_write(socket, datptr, leftcount)) <= 0)
313 return towrite - leftcount;
316 leftcount -= countwritten;
317 datptr += countwritten;
320 return towrite - leftcount;
324 /*! \brief Handshake with IMD client. */
325 static int imd_handshake(IMDSocket *socket)
330 fill_header(&header, IMD_HANDSHAKE, 1);
331 header.length = IMDVERSION; /* client wants unswapped version */
333 return (imd_write_multiple(socket, (char *) &header, HEADERSIZE) != HEADERSIZE);
337 /*! \brief Send energies using the energy block and the send buffer. */
338 static int imd_send_energies(IMDSocket *socket, const IMDEnergyBlock *energies, char *buffer)
343 recsize = HEADERSIZE + sizeof(IMDEnergyBlock);
344 fill_header((IMDHeader *) buffer, IMD_ENERGIES, 1);
345 memcpy(buffer + HEADERSIZE, energies, sizeof(IMDEnergyBlock));
347 return (imd_write_multiple(socket, buffer, recsize) != recsize);
351 /*! \brief Receive IMD header from socket, sets the length and returns the IMD message. */
352 static IMDMessageType imd_recv_header(IMDSocket *socket, gmx_int32_t *length)
357 if (imd_read_multiple(socket, (char *) &header, HEADERSIZE) != HEADERSIZE)
361 swap_header(&header);
362 *length = header.length;
364 return (IMDMessageType) header.type;
368 /*! \brief Receive force indices and forces.
370 * The number of forces was previously communicated via the header.
372 static int imd_recv_mdcomm(IMDSocket *socket, gmx_int32_t nforces, gmx_int32_t *forcendx, float *forces)
374 int retsize, retbytes;
377 /* reading indices */
378 retsize = sizeof(gmx_int32_t) * nforces;
379 retbytes = imd_read_multiple(socket, (char *) forcendx, retsize);
380 if (retbytes != retsize)
385 /* reading forces as float array */
386 retsize = 3 * sizeof(float) * nforces;
387 retbytes = imd_read_multiple(socket, (char *) forces, retsize);
388 if (retbytes != retsize)
398 /* GROMACS specific functions for the IMD implementation */
400 extern void write_IMDgroup_to_file(gmx_bool bIMD, t_inputrec *ir, t_state *state,
401 gmx_mtop_t *sys, int nfile, const t_filenm fnm[])
408 IMDatoms = gmx_mtop_global_atoms(sys);
409 write_sto_conf_indexed(opt2fn("-imd", nfile, fnm), "IMDgroup", &IMDatoms,
410 state->x, state->v, ir->ePBC, state->box, ir->imd->nat, ir->imd->ind);
415 extern void dd_make_local_IMD_atoms(gmx_bool bIMD, gmx_domdec_t *dd, t_IMD *imd)
418 t_gmx_IMD_setup *IMDsetup;
423 IMDsetup = imd->setup;
426 dd_make_local_group_indices(
427 ga2la, IMDsetup->nat, IMDsetup->ind, &IMDsetup->nat_loc,
428 &IMDsetup->ind_loc, &IMDsetup->nalloc_loc, IMDsetup->xa_ind);
434 /*! \brief Send positions from rvec.
436 * We need a separate send buffer and conversion to Angstrom.
438 static int imd_send_rvecs(IMDSocket *socket, int nat, rvec *x, char *buffer)
443 int tuplesize = 3 * sizeof(float);
446 /* Required size for the send buffer */
447 size = HEADERSIZE + 3 * sizeof(float) * nat;
450 fill_header((IMDHeader *) buffer, IMD_FCOORDS, (gmx_int32_t) nat);
451 for (i = 0; i < nat; i++)
453 sendx[0] = (float) x[i][0] * NM2A;
454 sendx[1] = (float) x[i][1] * NM2A;
455 sendx[2] = (float) x[i][2] * NM2A;
456 memcpy(buffer + HEADERSIZE + i * tuplesize, sendx, tuplesize);
459 return (imd_write_multiple(socket, buffer, size) != size);
463 /*! \brief Initializes the IMD private data. */
464 static t_gmx_IMD_setup* imd_create(int imdatoms, int nstimddef, int imdport)
466 t_gmx_IMD_setup *IMDsetup = NULL;
470 IMDsetup->nat = imdatoms;
471 IMDsetup->bTerminated = FALSE;
472 IMDsetup->bTerminatable = FALSE;
473 IMDsetup->bWConnect = FALSE;
474 IMDsetup->bConnected = FALSE;
475 IMDsetup->bForceActivated = FALSE;
476 IMDsetup->bNewForces = FALSE;
477 IMDsetup->bForceActivated = FALSE;
478 IMDsetup->nstimd = 1;
479 IMDsetup->nstimd_new = 1;
480 IMDsetup->nstimd_def = nstimddef;
484 fprintf(stderr, "%s You chose a port number < 1. Will automatically assign a free port.\n", IMDstr);
488 IMDsetup->port = imdport;
495 /*! \brief Prepare the socket on the MASTER. */
496 static void imd_prepare_master_socket(t_gmx_IMD_setup *IMDsetup)
501 #ifdef GMX_NATIVE_WINDOWS
502 /* Winsock requires separate initialization */
503 fprintf(stderr, "%s Initializing winsock.\n", IMDstr);
504 #ifdef GMX_HAVE_WINSOCK
505 if (imdsock_winsockinit())
507 gmx_fatal(FARGS, "%s Failed to initialize winsock.\n", IMDstr);
512 /* The rest is identical, first create and bind a socket and set to listen then. */
513 fprintf(stderr, "%s Setting up incoming socket.\n", IMDstr);
514 IMDsetup->socket = imdsock_create();
515 if (!IMDsetup->socket)
517 gmx_fatal(FARGS, "%s Failed to create socket.", IMDstr);
521 ret = imdsock_bind(IMDsetup->socket, IMDsetup->port);
524 gmx_fatal(FARGS, "%s binding socket to port %d failed with error %d.\n", IMDstr, IMDsetup->port, ret);
527 if (imd_sock_listen(IMDsetup->socket))
529 gmx_fatal(FARGS, "%s socket listen failed with error %d.\n", IMDstr, ret);
532 if (imdsock_getport(IMDsetup->socket, &IMDsetup->port))
534 gmx_fatal(FARGS, "%s Could not determine port number.\n", IMDstr, ret);
537 fprintf(stderr, "%s Listening for IMD connection on port %d.\n", IMDstr, IMDsetup->port);
541 /*! \brief Disconnect the client. */
542 static void imd_disconnect(t_gmx_IMD_setup *IMDsetup)
544 /* Write out any buffered pulling data */
545 fflush(IMDsetup->outf);
547 /* we first try to shut down the clientsocket */
548 imdsock_shutdown(IMDsetup->clientsocket);
549 if (!imdsock_destroy(IMDsetup->clientsocket))
551 fprintf(stderr, "%s Failed to destroy socket.\n", IMDstr);
554 /* then we reset the IMD step to its default, and reset the connection boolean */
555 IMDsetup->nstimd_new = IMDsetup->nstimd_def;
556 IMDsetup->clientsocket = NULL;
557 IMDsetup->bConnected = FALSE;
561 /*! \brief Prints an error message and disconnects the client.
563 * Does not terminate mdrun!
565 static void imd_fatal(t_gmx_IMD_setup *IMDsetup, const char *msg)
567 fprintf(stderr, "%s %s", IMDstr, msg);
568 imd_disconnect(IMDsetup);
569 fprintf(stderr, "%s disconnected.\n", IMDstr);
573 /*! \brief Check whether we got an incoming connection. */
574 static gmx_bool imd_tryconnect(t_gmx_IMD_setup *IMDsetup)
576 if (imdsock_tryread(IMDsetup->socket, 0, 0) > 0)
578 /* yes, we got something, accept on clientsocket */
579 IMDsetup->clientsocket = imdsock_accept(IMDsetup->socket);
580 if (!IMDsetup->clientsocket)
582 fprintf(stderr, "%s Accepting the connection on the socket failed.\n", IMDstr);
586 /* handshake with client */
587 if (imd_handshake(IMDsetup->clientsocket))
589 imd_fatal(IMDsetup, "Connection failed.\n");
593 fprintf(stderr, "%s Connection established, checking if I got IMD_GO orders.\n", IMDstr);
595 /* Check if we get the proper "GO" command from client. */
596 if (imdsock_tryread(IMDsetup->clientsocket, IMDCONNECTWAIT, 0) != 1 || imd_recv_header(IMDsetup->clientsocket, &(IMDsetup->length)) != IMD_GO)
598 imd_fatal(IMDsetup, "No IMD_GO order received. IMD connection failed.\n");
602 IMDsetup->bConnected = TRUE;
611 /*! \brief Wrap imd_tryconnect in order to make it blocking.
613 * Used when the simulation should wait for an incoming connection.
615 static void imd_blockconnect(t_gmx_IMD_setup *IMDsetup)
617 /* do not wait for connection, when e.g. ctrl+c is pressed and we will terminate anyways. */
618 if (!(int) gmx_get_stop_condition() == gmx_stop_cond_none)
623 fprintf(stderr, "%s Will wait until I have a connection and IMD_GO orders.\n", IMDstr);
625 /* while we have no clientsocket... 2nd part: we should still react on ctrl+c */
626 while ((!IMDsetup->clientsocket) && ((int) gmx_get_stop_condition() == gmx_stop_cond_none))
628 imd_tryconnect(IMDsetup);
629 #ifdef GMX_NATIVE_WINDOWS
630 /* for whatever reason, it is called Sleep on windows */
639 /*! \brief Make sure that our array holding the forces received via IMD is large enough. */
640 static void imd_prepare_vmd_Forces(t_gmx_IMD_setup *IMDsetup)
642 srenew((IMDsetup->vmd_f_ind), IMDsetup->vmd_nforces);
643 srenew((IMDsetup->vmd_forces), 3*IMDsetup->vmd_nforces);
647 /*! \brief Reads forces received via IMD. */
648 static void imd_read_vmd_Forces(t_gmx_IMD_setup *IMDsetup)
650 /* the length of the previously received header tells us the nr of forces we will receive */
651 IMDsetup->vmd_nforces = IMDsetup->length;
652 /* prepare the arrays */
653 imd_prepare_vmd_Forces(IMDsetup);
654 /* Now we read the forces... */
655 if (!(imd_recv_mdcomm(IMDsetup->clientsocket, IMDsetup->vmd_nforces, IMDsetup->vmd_f_ind, IMDsetup->vmd_forces)))
657 imd_fatal(IMDsetup, "Error while reading forces from remote. Disconnecting\n");
662 /*! \brief Prepares the MD force arrays. */
663 static void imd_prepare_MD_Forces(t_gmx_IMD_setup *IMDsetup)
665 srenew((IMDsetup->f_ind), IMDsetup->nforces);
666 srenew((IMDsetup->f ), IMDsetup->nforces);
670 /*! \brief Copy IMD forces to MD forces.
672 * Do conversion from Cal->Joule and from
673 * Angstrom -> nm and from a pointer array to arrays to 3*N array.
675 static void imd_copyto_MD_Forces(t_gmx_IMD_setup *IMDsetup)
678 real conversion = CAL2JOULE * NM2A;
681 for (i = 0; i < IMDsetup->nforces; i++)
683 /* Copy the indices, a copy is important because we may update the incoming forces
684 * whenever we receive new forces while the MD forces are only communicated upon
685 * IMD communication.*/
686 IMDsetup->f_ind[i] = IMDsetup->vmd_f_ind[i];
688 /* Convert to rvecs and do a proper unit conversion */
689 IMDsetup->f[i][0] = IMDsetup->vmd_forces[3*i ] * conversion;
690 IMDsetup->f[i][1] = IMDsetup->vmd_forces[3*i + 1] * conversion;
691 IMDsetup->f[i][2] = IMDsetup->vmd_forces[3*i + 2] * conversion;
696 /*! \brief Return TRUE if any of the forces or indices changed. */
697 static gmx_bool bForcesChanged(t_gmx_IMD_setup *IMDsetup)
702 /* First, check whether the number of pulled atoms changed */
703 if (IMDsetup->nforces != IMDsetup->old_nforces)
708 /* Second, check whether any of the involved atoms changed */
709 for (i = 0; i < IMDsetup->nforces; i++)
711 if (IMDsetup->f_ind[i] != IMDsetup->old_f_ind[i])
717 /* Third, check whether all forces are the same */
718 for (i = 0; i < IMDsetup->nforces; i++)
720 if (IMDsetup->f[i][XX] != IMDsetup->old_forces[i][XX])
724 if (IMDsetup->f[i][YY] != IMDsetup->old_forces[i][YY])
728 if (IMDsetup->f[i][ZZ] != IMDsetup->old_forces[i][ZZ])
734 /* All old and new forces are identical! */
739 /*! \brief Fill the old_f_ind and old_forces arrays with the new, old values. */
740 static void keep_old_values(t_gmx_IMD_setup *IMDsetup)
745 IMDsetup->old_nforces = IMDsetup->nforces;
747 for (i = 0; i < IMDsetup->nforces; i++)
749 IMDsetup->old_f_ind[i] = IMDsetup->f_ind[i];
750 copy_rvec(IMDsetup->f[i], IMDsetup->old_forces[i]);
755 /*! \brief Returns TRUE if any component of the two rvecs differs. */
756 static gmx_inline gmx_bool rvecs_differ(const rvec v1, const rvec v2)
761 for (i = 0; i < DIM; i++)
773 /*! \brief Write the applied pull forces to logfile.
775 * Call on master only!
777 static void output_imd_forces(t_inputrec *ir, double time)
779 t_gmx_IMD_setup *IMDsetup;
783 IMDsetup = ir->imd->setup;
785 if (bForcesChanged(IMDsetup))
787 /* Write time and total number of applied IMD forces */
788 fprintf(IMDsetup->outf, "%14.6e%6d", time, IMDsetup->nforces);
790 /* Write out the global atom indices of the pulled atoms and the forces itself,
791 * write out a force only if it has changed since the last output */
792 for (i = 0; i < IMDsetup->nforces; i++)
794 if (rvecs_differ(IMDsetup->f[i], IMDsetup->old_forces[i]))
796 fprintf(IMDsetup->outf, "%9d", IMDsetup->ind[IMDsetup->f_ind[i]] + 1);
797 fprintf(IMDsetup->outf, "%12.4e%12.4e%12.4e", IMDsetup->f[i][0], IMDsetup->f[i][1], IMDsetup->f[i][2]);
800 fprintf(IMDsetup->outf, "\n");
802 keep_old_values(IMDsetup);
807 /*! \brief Synchronize the nodes. */
808 static void imd_sync_nodes(t_inputrec *ir, t_commrec *cr, double t)
811 t_gmx_IMD_setup *IMDsetup;
815 IMDsetup = ir->imd->setup;
817 /* Notify the other nodes whether we are still connected. */
820 block_bc(cr, IMDsetup->bConnected);
823 /* ...if not connected, the job is done here. */
824 if (!IMDsetup->bConnected)
829 /* Let the other nodes know whether we got a new IMD synchronization frequency. */
832 block_bc(cr, IMDsetup->nstimd_new);
835 /* Now we all set the (new) nstimd communication time step */
836 IMDsetup->nstimd = IMDsetup->nstimd_new;
838 /* We're done if we don't allow pulling at all */
839 if (!(IMDsetup->bForceActivated))
844 /* OK, let's check if we have received forces which we need to communicate
845 * to the other nodes */
848 if (IMDsetup->bNewForces)
850 new_nforces = IMDsetup->vmd_nforces;
852 /* make the "new_forces" negative, when we did not receive new ones */
855 new_nforces = IMDsetup->vmd_nforces * -1;
859 /* make new_forces known to the clients */
862 block_bc(cr, new_nforces);
865 /* When new_natoms < 0 then we know that these are still the same forces
866 * so we don't communicate them, otherwise... */
867 if (new_nforces >= 0)
869 /* set local VMD and nforces */
870 IMDsetup->vmd_nforces = new_nforces;
871 IMDsetup->nforces = IMDsetup->vmd_nforces;
873 /* now everybody knows the number of forces in f_ind, so we can prepare
874 * the target arrays for indices and forces */
875 imd_prepare_MD_Forces(IMDsetup);
877 /* we first update the MD forces on the master by converting the VMD forces */
880 imd_copyto_MD_Forces(IMDsetup);
881 /* We also write out forces on every update, so that we know which
882 * forces are applied for every step */
885 output_imd_forces(ir, t);
889 /* In parallel mode we communicate the to-be-applied forces to the other nodes */
892 nblock_bc(cr, IMDsetup->nforces, IMDsetup->f_ind);
893 nblock_bc(cr, IMDsetup->nforces, IMDsetup->f );
896 /* done communicating the forces, reset bNewForces */
897 IMDsetup->bNewForces = FALSE;
902 /*! \brief Reads header from the client and decides what to do. */
903 static void imd_readcommand(t_gmx_IMD_setup *IMDsetup)
905 gmx_bool IMDpaused = FALSE;
906 IMDMessageType itype;
909 while (IMDsetup->clientsocket && (imdsock_tryread(IMDsetup->clientsocket, 0, 0) > 0 || IMDpaused))
911 itype = imd_recv_header(IMDsetup->clientsocket, &(IMDsetup->length));
912 /* let's see what we got: */
915 /* IMD asks us to terminate the simulation, check if the user allowed this */
917 if (IMDsetup->bTerminatable)
919 fprintf(stderr, " %s Terminating connection and running simulation (if supported by integrator).\n", IMDstr);
920 IMDsetup->bTerminated = TRUE;
921 IMDsetup->bWConnect = FALSE;
922 gmx_set_stop_condition(gmx_stop_cond_next);
926 fprintf(stderr, " %s Set -imdterm command line switch to allow mdrun termination from within IMD.\n", IMDstr);
931 /* the client doen't want to talk to us anymore */
933 fprintf(stderr, " %s Disconnecting client.\n", IMDstr);
934 imd_disconnect(IMDsetup);
937 /* we got new forces, read them and set bNewForces flag */
939 imd_read_vmd_Forces(IMDsetup);
940 IMDsetup->bNewForces = TRUE;
943 /* the client asks us to (un)pause the simulation. So we toggle the IMDpaused state */
947 fprintf(stderr, " %s Un-pause command received.\n", IMDstr);
952 fprintf(stderr, " %s Pause command received.\n", IMDstr);
958 /* the client sets a new transfer rate, if we get 0, we reset the rate
959 * to the default. VMD filters 0 however */
961 IMDsetup->nstimd_new = (IMDsetup->length > 0) ? IMDsetup->length : IMDsetup->nstimd_def;
962 fprintf(stderr, " %s Update frequency will be set to %d.\n", IMDstr, IMDsetup->nstimd_new);
965 /* Catch all rule for the remaining IMD types which we don't expect */
967 fprintf(stderr, " %s Received unexpected %s.\n", IMDstr, ENUM_NAME((int)itype, IMD_NR, eIMDType_names));
968 imd_fatal(IMDsetup, "Terminating connection\n");
975 /*! \brief Open IMD output file and write header information.
977 * Call on master only.
979 static FILE *open_imd_out(
981 t_gmx_IMD_setup *IMDsetup,
989 /* Open log file of applied IMD forces if requested */
992 /* If we append to an existing file, all the header information is already there */
993 if (Flags & MD_APPENDFILES)
995 fp = gmx_fio_fopen(fn, "a+");
999 fp = gmx_fio_fopen(fn, "w+");
1000 if (IMDsetup->nat == nat_total)
1002 fprintf(fp, "# Note that you can select an IMD index group in the .mdp file if a subset of the atoms suffices.\n");
1005 xvgr_header(fp, "IMD Pull Forces", "Time (ps)", "# of Forces / Atom IDs / Forces (kJ/mol)", exvggtNONE, oenv);
1007 fprintf(fp, "# Can display and manipulate %d (of a total of %d) atoms via IMD.\n", IMDsetup->nat, nat_total);
1008 fprintf(fp, "# column 1 : time (ps)\n");
1009 fprintf(fp, "# column 2 : total number of atoms feeling an IMD pulling force at that time\n");
1010 fprintf(fp, "# cols. 3.-6 : global atom number of pulled atom, x-force, y-force, z-force (kJ/mol)\n");
1011 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");
1012 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");
1016 /* To reduce the output file size we remember the old values and output only
1017 * when something changed */
1018 snew(IMDsetup->old_f_ind, IMDsetup->nat); /* One can never pull on more atoms */
1019 snew(IMDsetup->old_forces, IMDsetup->nat);
1024 fprintf(stdout, "%s For a log of the IMD pull forces explicitly specify '-if' on the command line.\n"
1025 "%s (Not possible with energy minimization.)\n", IMDstr, IMDstr);
1032 extern void IMD_finalize(gmx_bool bIMD, t_IMD *imd)
1036 if (imd->setup->outf)
1038 gmx_fio_fclose(imd->setup->outf);
1045 /*! \brief Creates the molecule start-end position array of molecules in the IMD group. */
1046 static void init_imd_prepare_mols_in_imdgroup(t_gmx_IMD_setup *IMDsetup, gmx_mtop_t *top_global)
1049 int gstart, gend, count;
1050 t_block gmols, lmols;
1054 gmols = top_global->mols;
1055 nat = IMDsetup->nat;
1056 ind = IMDsetup->ind;
1060 /* check whether index is sorted */
1061 for (i = 0; i < nat-1; i++)
1063 if (ind[i] > ind[i+1])
1065 gmx_fatal(FARGS, "%s IMD index is not sorted. This is currently not supported.\n", IMDstr);
1069 snew(lmols.index, gmols.nr+1);
1072 for (i = 0; i < gmols.nr; i++)
1074 gstart = gmols.index[i];
1075 gend = gmols.index[i+1];
1077 for (ii = 0; ii < nat; ii++)
1079 if ((ind[ii] >= gstart) && (ind[ii] < gend))
1086 lmols.index[lmols.nr+1] = lmols.index[lmols.nr]+count;
1090 srenew(lmols.index, lmols.nr+1);
1091 lmols.nalloc_index = lmols.nr+1;
1092 IMDsetup->mols = lmols;
1096 /*! \brief Copied and modified from groupcoord.c shift_positions_group(). */
1097 static void shift_positions(
1099 rvec x[], /* The positions [0..nr] */
1100 ivec is, /* The shift [0..nr] */
1101 int nr) /* The number of positions */
1105 /* Loop over the group's atoms */
1108 for (i = 0; i < nr; i++)
1114 x[i][XX] = x[i][XX]-tx*box[XX][XX]-ty*box[YY][XX]-tz*box[ZZ][XX];
1115 x[i][YY] = x[i][YY]-ty*box[YY][YY]-tz*box[ZZ][YY];
1116 x[i][ZZ] = x[i][ZZ]-tz*box[ZZ][ZZ];
1121 for (i = 0; i < nr; i++)
1127 x[i][XX] = x[i][XX]-tx*box[XX][XX];
1128 x[i][YY] = x[i][YY]-ty*box[YY][YY];
1129 x[i][ZZ] = x[i][ZZ]-tz*box[ZZ][ZZ];
1135 /*! \brief Removes shifts of molecules diffused outside of the box. */
1136 static void imd_remove_molshifts(t_gmx_IMD_setup *IMDsetup, matrix box)
1139 ivec largest, smallest, shift;
1143 mols = IMDsetup->mols;
1145 /* for each molecule also present in IMD group */
1146 for (i = 0; i < mols.nr; i++)
1148 /* first we determine the minimum and maximum shifts for each molecule */
1150 clear_ivec(largest);
1151 clear_ivec(smallest);
1154 copy_ivec(IMDsetup->xa_shifts[mols.index[i]], largest);
1155 copy_ivec(IMDsetup->xa_shifts[mols.index[i]], smallest);
1157 for (ii = mols.index[i]+1; ii < mols.index[i+1]; ii++)
1159 if (IMDsetup->xa_shifts[ii][XX] > largest[XX])
1161 largest[XX] = IMDsetup->xa_shifts[ii][XX];
1163 if (IMDsetup->xa_shifts[ii][XX] < smallest[XX])
1165 smallest[XX] = IMDsetup->xa_shifts[ii][XX];
1168 if (IMDsetup->xa_shifts[ii][YY] > largest[YY])
1170 largest[YY] = IMDsetup->xa_shifts[ii][YY];
1172 if (IMDsetup->xa_shifts[ii][YY] < smallest[YY])
1174 smallest[YY] = IMDsetup->xa_shifts[ii][YY];
1177 if (IMDsetup->xa_shifts[ii][ZZ] > largest[ZZ])
1179 largest[ZZ] = IMDsetup->xa_shifts[ii][ZZ];
1181 if (IMDsetup->xa_shifts[ii][ZZ] < smallest[ZZ])
1183 smallest[ZZ] = IMDsetup->xa_shifts[ii][ZZ];
1188 /* check if we what we can subtract/add to the positions
1189 * to put them back into the central box */
1190 if (smallest[XX] > 0)
1192 shift[XX] = smallest[XX];
1194 if (smallest[YY] > 0)
1196 shift[YY] = smallest[YY];
1198 if (smallest[ZZ] > 0)
1200 shift[ZZ] = smallest[ZZ];
1203 if (largest[XX] < 0)
1205 shift[XX] = largest[XX];
1207 if (largest[YY] < 0)
1209 shift[YY] = largest[YY];
1211 if (largest[ZZ] < 0)
1213 shift[ZZ] = largest[ZZ];
1216 /* is there a shift at all? */
1217 if ((shift[XX]) || (shift[YY]) || (shift[ZZ]))
1219 molsize = mols.index[i+1]-mols.index[i];
1220 /* shift the positions */
1221 shift_positions(box, &(IMDsetup->xa[mols.index[i]]), shift, molsize);
1228 /*! \brief Initialize arrays used to assemble the positions from the other nodes. */
1229 static void init_imd_prepare_for_x_assembly(t_commrec *cr, rvec x[], t_gmx_IMD_setup *IMDsetup)
1234 snew(IMDsetup->xa, IMDsetup->nat);
1235 snew(IMDsetup->xa_ind, IMDsetup->nat);
1236 snew(IMDsetup->xa_shifts, IMDsetup->nat);
1237 snew(IMDsetup->xa_eshifts, IMDsetup->nat);
1238 snew(IMDsetup->xa_old, IMDsetup->nat);
1240 /* Save the original (whole) set of positions such that later the
1241 * molecule can always be made whole again */
1244 for (i = 0; i < IMDsetup->nat; i++)
1246 ii = IMDsetup->ind[i];
1247 copy_rvec(x[ii], IMDsetup->xa_old[i]);
1253 IMDsetup->nat_loc = IMDsetup->nat;
1254 IMDsetup->ind_loc = IMDsetup->ind;
1256 /* xa_ind[i] needs to be set to i for serial runs */
1257 for (i = 0; i < IMDsetup->nat; i++)
1259 IMDsetup->xa_ind[i] = i;
1263 /* Communicate initial coordinates xa_old to all processes */
1267 gmx_bcast(IMDsetup->nat * sizeof(IMDsetup->xa_old[0]), IMDsetup->xa_old, cr);
1274 /*! \brief Check for non-working integrator / parallel options. */
1275 static void imd_check_integrator_parallel(t_inputrec *ir, t_commrec *cr)
1279 if (((ir->eI) == eiSteep) || ((ir->eI) == eiCG) || ((ir->eI) == eiLBFGS) || ((ir->eI) == eiNM))
1281 gmx_fatal(FARGS, "%s Energy minimization via steep, CG, lbfgs and nm in parallel is currently not supported by IMD.\n", IMDstr);
1288 extern void init_IMD(
1291 gmx_mtop_t *top_global,
1296 const t_filenm fnm[],
1299 unsigned long Flags)
1303 t_gmx_IMD_setup *IMDsetup;
1304 gmx_int32_t bufxsize;
1305 gmx_bool bIMD = FALSE;
1308 /* We will allow IMD sessions only if explicitly enabled in the .tpr file */
1309 if (FALSE == ir->bIMD)
1314 /* It seems we have a .tpr file that defines an IMD group and thus allows IMD sessions.
1315 * Check whether we can actually provide the IMD functionality for this setting: */
1318 /* Check whether IMD was enabled by one of the command line switches: */
1319 if ((Flags & MD_IMDWAIT) || (Flags & MD_IMDTERM) || (Flags & MD_IMDPULL))
1321 /* Multiple simulations or replica exchange */
1324 fprintf(stderr, "%s Cannot use IMD for multiple simulations or replica exchange.\n", IMDstr);
1326 /* OK, IMD seems to be allowed and turned on... */
1329 fprintf(stderr, "%s Enabled. This simulation will accept incoming IMD connections.\n", IMDstr);
1335 fprintf(stderr, "%s None of the -imd switches was used.\n"
1336 "%s This run will not accept incoming IMD connections\n", IMDstr, IMDstr);
1338 } /* end master only */
1340 /* Disable IMD if not all the needed functionality is there! */
1341 #if defined(GMX_NATIVE_WINDOWS) && !defined(GMX_HAVE_WINSOCK)
1343 fprintf(stderr, "Disabling IMD because the winsock library was not found at compile time.\n");
1346 /* Let the other nodes know whether we want IMD */
1351 /* ... and update our local inputrec accordingly. */
1354 /*... if not we are done.*/
1361 /* check if we're using a sane integrator / parallel combination */
1362 imd_check_integrator_parallel(ir, cr);
1366 *****************************************************
1367 * From here on we assume that IMD is turned on *
1368 *****************************************************
1372 nat_total = top_global->natoms;
1374 /* Initialize IMD setup structure. If we read in a pre-IMD .tpr file, imd->nat
1375 * will be zero. For those cases we transfer _all_ atomic positions */
1376 ir->imd->setup = imd_create(ir->imd->nat > 0 ? ir->imd->nat : nat_total,
1377 defnstimd, imdport);
1378 IMDsetup = ir->imd->setup;
1380 /* We might need to open an output file for IMD forces data */
1383 IMDsetup->outf = open_imd_out(opt2fn("-if", nfile, fnm), ir->imd->setup, nat_total, oenv, Flags);
1386 /* Make sure that we operate with a valid atom index array for the IMD atoms */
1387 if (ir->imd->nat > 0)
1389 /* Point to the user-supplied array of atom numbers */
1390 IMDsetup->ind = ir->imd->ind;
1394 /* Make a dummy (ind[i] = i) array of all atoms */
1395 snew(IMDsetup->ind, nat_total);
1396 for (i = 0; i < nat_total; i++)
1398 IMDsetup->ind[i] = i;
1402 /* read environment on master and prepare socket for incoming connections */
1405 /* we allocate memory for our IMD energy structure */
1406 gmx_int32_t recsize = HEADERSIZE + sizeof(IMDEnergyBlock);
1407 snew(IMDsetup->energysendbuf, recsize);
1409 /* Shall we wait for a connection? */
1410 if (Flags & MD_IMDWAIT)
1412 IMDsetup->bWConnect = TRUE;
1413 fprintf(stderr, "%s Pausing simulation while no IMD connection present (-imdwait).\n", IMDstr);
1416 /* Will the IMD clients be able to terminate the simulation? */
1417 if (Flags & MD_IMDTERM)
1419 IMDsetup->bTerminatable = TRUE;
1420 fprintf(stderr, "%s Allow termination of the simulation from IMD client (-imdterm).\n", IMDstr);
1423 /* Is pulling from IMD client allowed? */
1424 if (Flags & MD_IMDPULL)
1426 IMDsetup->bForceActivated = TRUE;
1427 fprintf(stderr, "%s Pulling from IMD remote is enabled (-imdpull).\n", IMDstr);
1430 /* Initialize send buffers with constant size */
1431 snew(IMDsetup->sendxbuf, IMDsetup->nat);
1432 snew(IMDsetup->energies, 1);
1433 bufxsize = HEADERSIZE + 3 * sizeof(float) * IMDsetup->nat;
1434 snew(IMDsetup->coordsendbuf, bufxsize);
1437 /* do we allow interactive pulling? If so let the other nodes know. */
1440 block_bc(cr, IMDsetup->bForceActivated);
1443 /* setup the listening socket on master process */
1446 fprintf(fplog, "%s Setting port for connection requests to %d.\n", IMDstr, IMDsetup->port);
1447 fprintf(stderr, "%s Turning on IMD - port for incoming requests is %d.\n", IMDstr, IMDsetup->port);
1448 imd_prepare_master_socket(IMDsetup);
1449 /* Wait until we have a connection if specified before */
1450 if (IMDsetup->bWConnect)
1452 imd_blockconnect(IMDsetup);
1456 fprintf(stderr, "%s -imdwait not set, starting simulation.\n", IMDstr);
1459 /* Let the other nodes know whether we are connected */
1460 imd_sync_nodes(ir, cr, 0);
1462 /* Initialize arrays used to assemble the positions from the other nodes */
1463 init_imd_prepare_for_x_assembly(cr, x, IMDsetup);
1465 /* Initialize molecule blocks to make them whole later...*/
1468 init_imd_prepare_mols_in_imdgroup(IMDsetup, top_global);
1471 gmx_incons("init_IMD: this GROMACS version was not compiled with IMD support!");
1476 extern gmx_bool do_IMD(
1485 gmx_wallcycle_t wcycle)
1487 gmx_bool imdstep = FALSE;
1488 t_gmx_IMD_setup *IMDsetup;
1498 wallcycle_start(wcycle, ewcIMD);
1500 IMDsetup = ir->imd->setup;
1502 /* read command from client and check if new incoming connection */
1505 /* If not already connected, check for new connections */
1506 if (!IMDsetup->clientsocket)
1508 if (IMDsetup->bWConnect)
1510 imd_blockconnect(IMDsetup);
1514 imd_tryconnect(IMDsetup);
1518 /* Let's see if we have new IMD messages for us */
1519 if (IMDsetup->clientsocket)
1521 imd_readcommand(IMDsetup);
1525 /* is this an IMD communication step? */
1526 imdstep = do_per_step(step, IMDsetup->nstimd);
1528 /* OK so this is an IMD step ... */
1531 /* First we sync all nodes to let everybody know whether we are connected to VMD */
1532 imd_sync_nodes(ir, cr, t);
1535 /* If a client is connected, we collect the positions
1536 * and put molecules back into the box before transfer */
1537 if ((imdstep && IMDsetup->bConnected)
1538 || bNS) /* independent of imdstep, we communicate positions at each NS step */
1540 /* Transfer the IMD positions to the master node. Every node contributes
1541 * its local positions x and stores them in the assembled xa array. */
1542 communicate_group_positions(cr, IMDsetup->xa, IMDsetup->xa_shifts, IMDsetup->xa_eshifts,
1543 TRUE, x, IMDsetup->nat, IMDsetup->nat_loc,
1544 IMDsetup->ind_loc, IMDsetup->xa_ind, IMDsetup->xa_old, box);
1546 /* If connected and master -> remove shifts */
1547 if ((imdstep && IMDsetup->bConnected) && MASTER(cr))
1549 imd_remove_molshifts(IMDsetup, box);
1553 wallcycle_stop(wcycle, ewcIMD);
1555 gmx_incons("do_IMD called without IMD support!");
1562 extern void IMD_fill_energy_record(gmx_bool bIMD, t_IMD *imd, gmx_enerdata_t *enerd,
1563 gmx_int64_t step, gmx_bool bHaveNewEnergies)
1565 IMDEnergyBlock *ene;
1572 IMDsetup = imd->setup;
1574 if (IMDsetup->clientsocket)
1576 ene = IMDsetup->energies;
1580 /* In MPI-parallel simulations the energies are not accessible a at every time step.
1581 * We update them if we have new values, otherwise, the energy values from the
1582 * last global communication step are still on display in the viewer. */
1583 if (bHaveNewEnergies)
1585 ene->T_abs = (float) enerd->term[F_TEMP ];
1586 ene->E_pot = (float) enerd->term[F_EPOT ];
1587 ene->E_tot = (float) enerd->term[F_ETOT ];
1588 ene->E_bond = (float) enerd->term[F_BONDS ];
1589 ene->E_angle = (float) enerd->term[F_ANGLES ];
1590 ene->E_dihe = (float) enerd->term[F_PDIHS ];
1591 ene->E_impr = (float) enerd->term[F_IDIHS ];
1592 ene->E_vdw = (float) enerd->term[F_LJ ];
1593 ene->E_coul = (float) (enerd->term[F_COUL_SR] + enerd->term[F_COUL_LR]);
1597 gmx_incons("IMD_fill_energy_record called without IMD support.");
1603 extern void IMD_send_positions(t_IMD *imd)
1609 IMDsetup = imd->setup;
1611 if (IMDsetup->clientsocket)
1614 if (imd_send_energies(IMDsetup->clientsocket, IMDsetup->energies, IMDsetup->energysendbuf))
1616 imd_fatal(IMDsetup, "Error sending updated energies. Disconnecting client.\n");
1619 if (imd_send_rvecs(IMDsetup->clientsocket, IMDsetup->nat, IMDsetup->xa, IMDsetup->coordsendbuf))
1621 imd_fatal(IMDsetup, "Error sending updated positions. Disconnecting client.\n");
1625 gmx_incons("IMD_send_positions called without IMD support.");
1630 extern void IMD_prep_energies_send_positions(gmx_bool bIMD, gmx_bool bIMDstep,
1631 t_IMD *imd, gmx_enerdata_t *enerd,
1632 gmx_int64_t step, gmx_bool bHaveNewEnergies,
1633 gmx_wallcycle_t wcycle)
1638 wallcycle_start(wcycle, ewcIMD);
1640 /* Update time step for IMD and prepare IMD energy record if we have new energies. */
1641 IMD_fill_energy_record(TRUE, imd, enerd, step, bHaveNewEnergies);
1645 /* Send positions and energies to VMD client via IMD */
1646 IMD_send_positions(imd);
1649 wallcycle_stop(wcycle, ewcIMD);
1651 gmx_incons("IMD_prep_energies_send_positions called without IMD support.");
1657 extern int IMD_get_step(t_gmx_IMD IMDsetup)
1659 return IMDsetup->nstimd;
1663 extern void IMD_apply_forces(gmx_bool bIMD, t_IMD *imd, t_commrec *cr, rvec *f,
1664 gmx_wallcycle_t wcycle)
1668 t_gmx_IMD_setup *IMDsetup;
1674 wallcycle_start(wcycle, ewcIMD);
1676 IMDsetup = imd->setup;
1678 /* Are forces allowed at all? If not we're done */
1679 if (!IMDsetup->bForceActivated)
1684 for (i = 0; i < IMDsetup->nforces; i++)
1686 /* j are the indices in the "System group".*/
1687 j = IMDsetup->ind[IMDsetup->f_ind[i]];
1689 /* check if this is a local atom and find out locndx */
1690 if (PAR(cr) && ga2la_get_home(cr->dd->ga2la, j, &locndx))
1695 rvec_inc(f[j], IMDsetup->f[i]);
1698 wallcycle_start(wcycle, ewcIMD);
1700 gmx_incons("IMD_apply_forces called without IMD support.");