Eliminate mdlib/mdrun.h
[alexxy/gromacs.git] / src / gromacs / imd / imd.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2014,2015,2016,2017,2018,2019, 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.
8  *
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.
13  *
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.
18  *
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.
23  *
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.
31  *
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.
34  */
35
36 /*! \internal \file
37  *
38  * \brief
39  * Implements functions of imd.h.
40  *
41  * Re-implementation of basic IMD functions from NAMD/VMD from scratch,
42  * see imdsocket.h for references to the IMD API.
43  *
44  * \author Martin Hoefling, Carsten Kutzner <ckutzne@gwdg.de>
45  *
46  * \ingroup module_imd
47  */
48 #include "gmxpre.h"
49
50 #include "imd.h"
51
52 #include "config.h"
53
54 #include <cerrno>
55 #include <cstring>
56
57 #if GMX_NATIVE_WINDOWS
58 #include <windows.h>
59 #else
60 #include <unistd.h>
61 #endif
62
63 #include "gromacs/commandline/filenm.h"
64 #include "gromacs/domdec/domdec_struct.h"
65 #include "gromacs/domdec/ga2la.h"
66 #include "gromacs/fileio/confio.h"
67 #include "gromacs/fileio/gmxfio.h"
68 #include "gromacs/fileio/xvgr.h"
69 #include "gromacs/gmxlib/network.h"
70 #include "gromacs/imd/imdsocket.h"
71 #include "gromacs/math/units.h"
72 #include "gromacs/math/vec.h"
73 #include "gromacs/mdlib/broadcaststructs.h"
74 #include "gromacs/mdlib/groupcoord.h"
75 #include "gromacs/mdlib/sighandler.h"
76 #include "gromacs/mdlib/sim_util.h"
77 #include "gromacs/mdtypes/enerdata.h"
78 #include "gromacs/mdtypes/inputrec.h"
79 #include "gromacs/mdtypes/md_enums.h"
80 #include "gromacs/mdtypes/mdrunoptions.h"
81 #include "gromacs/mdtypes/state.h"
82 #include "gromacs/pbcutil/pbc.h"
83 #include "gromacs/timing/wallcycle.h"
84 #include "gromacs/topology/mtop_util.h"
85 #include "gromacs/topology/topology.h"
86 #include "gromacs/utility/fatalerror.h"
87 #include "gromacs/utility/smalloc.h"
88
89 /*! \brief How long shall we wait in seconds until we check for a connection again? */
90 #define IMDLOOPWAIT 1
91
92 /*! \brief How long shall we check for the IMD_GO? */
93 #define IMDCONNECTWAIT 2
94
95 /*! \brief IMD Header Size. */
96 #define HEADERSIZE 8
97 /*! \brief IMD Protocol Version. */
98 #define IMDVERSION 2
99
100
101 /*! \internal
102  * \brief
103  * IMD (interactive molecular dynamics) energy record.
104  *
105  * As in the original IMD implementation. Energies in kcal/mol.
106  * NOTE: We return the energies in GROMACS / SI units,
107  * so they also show up as SI in VMD.
108  *
109  */
110 typedef struct
111 {
112     int32_t     tstep;   /**< time step                                     */
113     float       T_abs;   /**< absolute temperature                          */
114     float       E_tot;   /**< total energy                                  */
115     float       E_pot;   /**< potential energy                              */
116     float       E_vdw;   /**< van der Waals energy                          */
117     float       E_coul;  /**< Coulomb interaction energy                    */
118     float       E_bond;  /**< bonds energy                                  */
119     float       E_angle; /**< angles energy                                 */
120     float       E_dihe;  /**< dihedrals energy                              */
121     float       E_impr;  /**< improper dihedrals energy                     */
122 } IMDEnergyBlock;
123
124
125 /*! \internal
126  * \brief IMD (interactive molecular dynamics) communication structure.
127  *
128  * This structure defines the IMD communication message header & protocol version.
129  */
130 typedef struct
131 {
132     int32_t type;      /**< Type of IMD message, see IMDType_t above      */
133     int32_t length;    /**< Length                                        */
134 } IMDHeader;
135
136
137 /*! \internal
138  * \brief IMD (interactive molecular dynamics) main data structure.
139  *
140  * Contains private IMD data
141  */
142 typedef struct t_gmx_IMD
143 {
144     FILE      *outf;                 /**< Output file for IMD data, mainly forces.    */
145
146     int        nat;                  /**< Number of atoms that can be pulled via IMD. */
147     int        nat_loc;              /**< Part of the atoms that are local.           */
148     int       *ind;                  /**< Global indices of the IMD atoms.            */
149     int       *ind_loc;              /**< Local indices of the IMD atoms.             */
150     int        nalloc_loc;           /**< Allocation size for ind_loc.                */
151     rvec      *xa;                   /**< Positions for all IMD atoms assembled on
152                                           the master node.                            */
153     ivec      *xa_shifts;            /**< Shifts for all IMD atoms, to make
154                                           molecule(s) whole.                          */
155     ivec      *xa_eshifts;           /**< Extra shifts since last DD step.            */
156     rvec      *xa_old;               /**< Old positions for all IMD atoms on master.  */
157     int       *xa_ind;               /**< Position of each local atom in the
158                                           collective array.                           */
159
160     int             nstimd;          /**< Global IMD frequency, known to all nodes.   */
161     int             nstimd_new;      /**< New frequency from IMD client, master only. */
162     int             nstimd_def;      /**< Default IMD frequency when disconnected.    */
163
164     int             port;            /**< Port to use for network socket.             */
165     IMDSocket      *socket;          /**< The IMD socket on the master node.          */
166     IMDSocket      *clientsocket;    /**< The IMD socket on the client.               */
167     int             length;          /**< Length we got with last header.             */
168
169     gmx_bool        bWConnect;       /**< Shall we block and wait for connection?     */
170     gmx_bool        bTerminated;     /**< Set if MD is terminated.                    */
171     gmx_bool        bTerminatable;   /**< Set if MD can be terminated.                */
172     gmx_bool        bConnected;      /**< Set if connection is present.               */
173     gmx_bool        bNewForces;      /**< Set if we received new forces.              */
174     gmx_bool        bForceActivated; /**< Set if pulling from VMD is allowed.         */
175
176     IMDEnergyBlock *energies;        /**< Pointer to energies we send back.           */
177
178     int32_t         vmd_nforces;     /**< Number of VMD forces.                       */
179     int32_t        *vmd_f_ind;       /**< VMD forces indices.                         */
180     float          *vmd_forces;      /**< The VMD forces flat in memory.              */
181     int             nforces;         /**< Number of actual MD forces;
182                                           this gets communicated to the clients.      */
183     int            *f_ind;           /**< Force indices.                              */
184     rvec           *f;               /**< The IMD pulling forces.                     */
185
186     char           *forcesendbuf;    /**< Buffer for force sending.                   */
187     char           *coordsendbuf;    /**< Buffer for coordinate sending.              */
188     char           *energysendbuf;   /**< Send buffer for energies.                   */
189     rvec           *sendxbuf;        /**< Buffer to make molecules whole before
190                                           sending.                                    */
191
192     t_block         mols;            /**< Molecules block in IMD group.               */
193
194     /* The next block is used on the master node only to reduce the output
195      * without sacrificing information. If any of these values changes,
196      * we need to write output */
197     int       old_nforces;       /**< Old value for nforces.                      */
198     int      *old_f_ind;         /**< Old values for force indices.               */
199     rvec     *old_forces;        /**< Old values for IMD pulling forces.          */
200
201 } t_gmx_IMD_setup;
202
203
204 /*! \internal
205  * \brief Enum for types of IMD messages.
206  *
207  * We use the same records as the NAMD/VMD IMD implementation.
208  */
209 typedef enum IMDType_t
210 {
211     IMD_DISCONNECT,      /**< client disconnect                               */
212     IMD_ENERGIES,        /**< energy data                                     */
213     IMD_FCOORDS,         /**< atomic coordinates                              */
214     IMD_GO,              /**< start command for the simulation                */
215     IMD_HANDSHAKE,       /**< handshake to determine little/big endianness    */
216     IMD_KILL,            /**< terminates the simulation                       */
217     IMD_MDCOMM,          /**< force data                                      */
218     IMD_PAUSE,           /**< pauses the simulation                           */
219     IMD_TRATE,           /**< sets the IMD transmission and processing rate   */
220     IMD_IOERROR,         /**< I/O error                                       */
221     IMD_NR               /**< number of entries                               */
222 } IMDMessageType;
223
224
225 /*! \internal
226  * \brief Names of the IMDType for error messages.
227  */
228 static const char *eIMDType_names[IMD_NR + 1] = {
229     "IMD_DISCONNECT",
230     "IMD_ENERGIES",
231     "IMD_FCOORDS",
232     "IMD_GO",
233     "IMD_HANDSHAKE",
234     "IMD_KILL",
235     "IMD_MDCOMM",
236     "IMD_PAUSE",
237     "IMD_TRATE",
238     "IMD_IOERROR",
239     nullptr
240 };
241
242
243 #ifdef GMX_IMD
244
245
246 /*! \brief Fills the header with message and the length argument. */
247 static void fill_header(IMDHeader *header, IMDMessageType type, int32_t length)
248 {
249     /* We (ab-)use htonl network function for the correct endianness */
250     header->type   = htonl(static_cast<int32_t>(type));
251     header->length = htonl(length);
252 }
253
254
255 /*! \brief Swaps the endianess of the header. */
256 static void swap_header(IMDHeader *header)
257 {
258     /* and vice versa... */
259     header->type   = ntohl(header->type);
260     header->length = ntohl(header->length);
261 }
262
263
264 /*! \brief Reads multiple bytes from socket. */
265 static int32_t imd_read_multiple(IMDSocket *socket, char *datptr, int32_t toread)
266 {
267     int32_t leftcount, countread;
268
269
270     leftcount = toread;
271     /* Try to read while we haven't reached toread */
272     while (leftcount != 0)
273     {
274         if ((countread = imdsock_read(socket, datptr, leftcount)) < 0)
275         {
276             /* interrupted function call, try again... */
277             if (errno == EINTR)
278             {
279                 countread = 0;
280             }
281             /* this is an unexpected error, return what we got */
282             else
283             {
284                 return toread - leftcount;
285             }
286
287             /* nothing read, finished */
288         }
289         else if (countread == 0)
290         {
291             break;
292         }
293         leftcount -= countread;
294         datptr    += countread;
295     } /* end while */
296
297     /* return nr of bytes read */
298     return toread - leftcount;
299 }
300
301
302 /*! \brief Writes multiple bytes to socket in analogy to imd_read_multiple. */
303 static int32_t imd_write_multiple(IMDSocket *socket, const char *datptr, int32_t towrite)
304 {
305     int32_t leftcount, countwritten;
306
307
308     leftcount = towrite;
309     while (leftcount != 0)
310     {
311         if ((countwritten = imdsock_write(socket, datptr, leftcount)) <= 0)
312         {
313             if (errno == EINTR)
314             {
315                 countwritten = 0;
316             }
317             else
318             {
319                 return towrite - leftcount;
320             }
321         }
322         leftcount -= countwritten;
323         datptr    += countwritten;
324     } /* end while */
325
326     return towrite - leftcount;
327 }
328
329
330 /*! \brief Handshake with IMD client. */
331 static int imd_handshake(IMDSocket *socket)
332 {
333     IMDHeader header;
334
335
336     fill_header(&header, IMD_HANDSHAKE, 1);
337     header.length = IMDVERSION; /* client wants unswapped version */
338
339     return static_cast<int>(imd_write_multiple(socket, reinterpret_cast<char *>(&header), HEADERSIZE) != HEADERSIZE);
340 }
341
342
343 /*! \brief Send energies using the energy block and the send buffer. */
344 static int imd_send_energies(IMDSocket *socket, const IMDEnergyBlock *energies, char *buffer)
345 {
346     int32_t recsize;
347
348
349     recsize = HEADERSIZE + sizeof(IMDEnergyBlock);
350     fill_header(reinterpret_cast<IMDHeader *>(buffer), IMD_ENERGIES, 1);
351     memcpy(buffer + HEADERSIZE, energies, sizeof(IMDEnergyBlock));
352
353     return static_cast<int>(imd_write_multiple(socket, buffer, recsize) != recsize);
354 }
355
356
357 /*! \brief Receive IMD header from socket, sets the length and returns the IMD message. */
358 static IMDMessageType imd_recv_header(IMDSocket *socket, int32_t *length)
359 {
360     IMDHeader header;
361
362
363     if (imd_read_multiple(socket, reinterpret_cast<char *>(&header), HEADERSIZE) != HEADERSIZE)
364     {
365         return IMD_IOERROR;
366     }
367     swap_header(&header);
368     *length = header.length;
369
370     return static_cast<IMDMessageType>(header.type);
371 }
372
373
374 /*! \brief Receive force indices and forces.
375  *
376  * The number of forces was previously communicated via the header.
377  */
378 static int imd_recv_mdcomm(IMDSocket *socket, int32_t nforces, int32_t *forcendx, float *forces)
379 {
380     int retsize, retbytes;
381
382
383     /* reading indices */
384     retsize  = sizeof(int32_t) * nforces;
385     retbytes = imd_read_multiple(socket, reinterpret_cast<char *>(forcendx), retsize);
386     if (retbytes != retsize)
387     {
388         return FALSE;
389     }
390
391     /* reading forces as float array */
392     retsize  = 3 * sizeof(float) * nforces;
393     retbytes = imd_read_multiple(socket, reinterpret_cast<char *>(forces), retsize);
394     if (retbytes != retsize)
395     {
396         return FALSE;
397     }
398
399     return TRUE;
400 }
401
402 #endif
403
404 /* GROMACS specific functions for the IMD implementation */
405 void write_IMDgroup_to_file(gmx_bool bIMD, t_inputrec *ir, const t_state *state,
406                             const gmx_mtop_t *sys, int nfile, const t_filenm fnm[])
407 {
408     t_atoms IMDatoms;
409
410
411     if (bIMD)
412     {
413         IMDatoms = gmx_mtop_global_atoms(sys);
414         write_sto_conf_indexed(opt2fn("-imd", nfile, fnm), "IMDgroup", &IMDatoms,
415                                state->x.rvec_array(), state->v.rvec_array(), ir->ePBC, state->box, ir->imd->nat, ir->imd->ind);
416     }
417 }
418
419
420 void dd_make_local_IMD_atoms(gmx_bool bIMD, const gmx_domdec_t *dd, t_IMD *imd)
421 {
422     const gmx_ga2la_t *ga2la;
423     t_gmx_IMD_setup   *IMDsetup;
424
425     if (bIMD)
426     {
427         IMDsetup = imd->setup;
428         ga2la    = dd->ga2la;
429
430         dd_make_local_group_indices(
431                 ga2la, IMDsetup->nat, IMDsetup->ind, &IMDsetup->nat_loc,
432                 &IMDsetup->ind_loc, &IMDsetup->nalloc_loc, IMDsetup->xa_ind);
433     }
434 }
435
436
437 #ifdef GMX_IMD
438 /*! \brief Send positions from rvec.
439  *
440  * We need a separate send buffer and conversion to Angstrom.
441  */
442 static int imd_send_rvecs(IMDSocket *socket, int nat, rvec *x, char *buffer)
443 {
444     int32_t     size;
445     int         i;
446     float       sendx[3];
447     int         tuplesize = 3 * sizeof(float);
448
449
450     /* Required size for the send buffer */
451     size = HEADERSIZE + 3 * sizeof(float) * nat;
452
453     /* Prepare header */
454     fill_header(reinterpret_cast<IMDHeader *>(buffer), IMD_FCOORDS, static_cast<int32_t>(nat));
455     for (i = 0; i < nat; i++)
456     {
457         sendx[0] = static_cast<float>(x[i][0]) * NM2A;
458         sendx[1] = static_cast<float>(x[i][1]) * NM2A;
459         sendx[2] = static_cast<float>(x[i][2]) * NM2A;
460         memcpy(buffer + HEADERSIZE + i * tuplesize, sendx, tuplesize);
461     }
462
463     return static_cast<int>(imd_write_multiple(socket, buffer, size) != size);
464 }
465
466
467 /*! \brief Initializes the IMD private data. */
468 static t_gmx_IMD_setup* imd_create(int imdatoms, int nstimddef, int imdport)
469 {
470     t_gmx_IMD_setup *IMDsetup = nullptr;
471
472
473     snew(IMDsetup, 1);
474     IMDsetup->nat             = imdatoms;
475     IMDsetup->bTerminated     = FALSE;
476     IMDsetup->bTerminatable   = FALSE;
477     IMDsetup->bWConnect       = FALSE;
478     IMDsetup->bConnected      = FALSE;
479     IMDsetup->bForceActivated = FALSE;
480     IMDsetup->bNewForces      = FALSE;
481     IMDsetup->bForceActivated = FALSE;
482     IMDsetup->nstimd          = 1;
483     IMDsetup->nstimd_new      = 1;
484     IMDsetup->nstimd_def      = nstimddef;
485     if (imdport < 1)
486     {
487         IMDsetup->port        = 0;
488         fprintf(stderr, "%s You chose a port number < 1. Will automatically assign a free port.\n", IMDstr);
489     }
490     else
491     {
492         IMDsetup->port        = imdport;
493     }
494
495     return IMDsetup;
496 }
497
498
499 /*! \brief Prepare the socket on the MASTER. */
500 static void imd_prepare_master_socket(t_gmx_IMD_setup *IMDsetup)
501 {
502     int ret;
503
504
505 #if GMX_NATIVE_WINDOWS
506     /* Winsock requires separate initialization */
507     fprintf(stderr, "%s Initializing winsock.\n", IMDstr);
508 #ifdef GMX_HAVE_WINSOCK
509     if (imdsock_winsockinit())
510     {
511         gmx_fatal(FARGS, "%s Failed to initialize winsock.\n", IMDstr);
512     }
513 #endif
514 #endif
515
516     /* The rest is identical, first create and bind a socket and set to listen then. */
517     fprintf(stderr, "%s Setting up incoming socket.\n", IMDstr);
518     IMDsetup->socket = imdsock_create();
519     if (!IMDsetup->socket)
520     {
521         gmx_fatal(FARGS, "%s Failed to create socket.", IMDstr);
522     }
523
524     /* Bind to port */
525     ret = imdsock_bind(IMDsetup->socket, IMDsetup->port);
526     if (ret)
527     {
528         gmx_fatal(FARGS, "%s binding socket to port %d failed with error %d.\n", IMDstr, IMDsetup->port, ret);
529     }
530
531     if (imd_sock_listen(IMDsetup->socket))
532     {
533         gmx_fatal(FARGS, "%s socket listen failed with error %d.\n", IMDstr, ret);
534     }
535
536     if (imdsock_getport(IMDsetup->socket, &IMDsetup->port))
537     {
538         gmx_fatal(FARGS, "%s Could not determine port number.\n", IMDstr);
539     }
540
541     fprintf(stderr, "%s Listening for IMD connection on port %d.\n", IMDstr, IMDsetup->port);
542 }
543
544
545 /*! \brief Disconnect the client. */
546 static void imd_disconnect(t_gmx_IMD_setup *IMDsetup)
547 {
548     /* Write out any buffered pulling data */
549     fflush(IMDsetup->outf);
550
551     /* we first try to shut down the clientsocket */
552     imdsock_shutdown(IMDsetup->clientsocket);
553     if (!imdsock_destroy(IMDsetup->clientsocket))
554     {
555         fprintf(stderr, "%s Failed to destroy socket.\n", IMDstr);
556     }
557
558     /* then we reset the IMD step to its default, and reset the connection boolean */
559     IMDsetup->nstimd_new   = IMDsetup->nstimd_def;
560     IMDsetup->clientsocket = nullptr;
561     IMDsetup->bConnected   = FALSE;
562 }
563
564
565 /*! \brief Prints an error message and disconnects the client.
566  *
567  *  Does not terminate mdrun!
568  */
569 static void imd_fatal(t_gmx_IMD_setup *IMDsetup, const char *msg)
570 {
571     fprintf(stderr, "%s %s", IMDstr, msg);
572     imd_disconnect(IMDsetup);
573     fprintf(stderr, "%s disconnected.\n", IMDstr);
574 }
575
576
577 /*! \brief Check whether we got an incoming connection. */
578 static gmx_bool imd_tryconnect(t_gmx_IMD_setup *IMDsetup)
579 {
580     if (imdsock_tryread(IMDsetup->socket, 0, 0) > 0)
581     {
582         /* yes, we got something, accept on clientsocket */
583         IMDsetup->clientsocket = imdsock_accept(IMDsetup->socket);
584         if (!IMDsetup->clientsocket)
585         {
586             fprintf(stderr, "%s Accepting the connection on the socket failed.\n", IMDstr);
587             return FALSE;
588         }
589
590         /* handshake with client */
591         if (imd_handshake(IMDsetup->clientsocket))
592         {
593             imd_fatal(IMDsetup, "Connection failed.\n");
594             return FALSE;
595         }
596
597         fprintf(stderr, "%s Connection established, checking if I got IMD_GO orders.\n", IMDstr);
598
599         /* Check if we get the proper "GO" command from client. */
600         if (imdsock_tryread(IMDsetup->clientsocket, IMDCONNECTWAIT, 0) != 1 || imd_recv_header(IMDsetup->clientsocket, &(IMDsetup->length)) != IMD_GO)
601         {
602             imd_fatal(IMDsetup, "No IMD_GO order received. IMD connection failed.\n");
603         }
604
605         /* IMD connected */
606         IMDsetup->bConnected = TRUE;
607
608         return TRUE;
609     }
610
611     return FALSE;
612 }
613
614
615 /*! \brief Wrap imd_tryconnect in order to make it blocking.
616  *
617  * Used when the simulation should wait for an incoming connection.
618  */
619 static void imd_blockconnect(t_gmx_IMD_setup *IMDsetup)
620 {
621     /* do not wait for connection, when e.g. ctrl+c is pressed and we will terminate anyways. */
622     if (!(static_cast<int>(gmx_get_stop_condition()) == gmx_stop_cond_none))
623     {
624         return;
625     }
626
627     fprintf(stderr, "%s Will wait until I have a connection and IMD_GO orders.\n", IMDstr);
628
629     /* while we have no clientsocket... 2nd part: we should still react on ctrl+c */
630     while ((!IMDsetup->clientsocket) && (static_cast<int>(gmx_get_stop_condition()) == gmx_stop_cond_none))
631     {
632         imd_tryconnect(IMDsetup);
633 #if GMX_NATIVE_WINDOWS
634         /* for whatever reason, it is called Sleep on windows */
635         Sleep(IMDLOOPWAIT);
636 #else
637         sleep(IMDLOOPWAIT);
638 #endif
639     }
640 }
641
642
643 /*! \brief Make sure that our array holding the forces received via IMD is large enough. */
644 static void imd_prepare_vmd_Forces(t_gmx_IMD_setup *IMDsetup)
645 {
646     srenew((IMDsetup->vmd_f_ind), IMDsetup->vmd_nforces);
647     srenew((IMDsetup->vmd_forces), 3*IMDsetup->vmd_nforces);
648 }
649
650
651 /*! \brief Reads forces received via IMD. */
652 static void imd_read_vmd_Forces(t_gmx_IMD_setup *IMDsetup)
653 {
654     /* the length of the previously received header tells us the nr of forces we will receive */
655     IMDsetup->vmd_nforces = IMDsetup->length;
656     /* prepare the arrays */
657     imd_prepare_vmd_Forces(IMDsetup);
658     /* Now we read the forces... */
659     if (!(imd_recv_mdcomm(IMDsetup->clientsocket, IMDsetup->vmd_nforces, IMDsetup->vmd_f_ind, IMDsetup->vmd_forces)))
660     {
661         imd_fatal(IMDsetup, "Error while reading forces from remote. Disconnecting\n");
662     }
663 }
664
665
666 /*! \brief Prepares the MD force arrays. */
667 static void imd_prepare_MD_Forces(t_gmx_IMD_setup *IMDsetup)
668 {
669     srenew((IMDsetup->f_ind), IMDsetup->nforces);
670     srenew((IMDsetup->f    ), IMDsetup->nforces);
671 }
672
673
674 /*! \brief Copy IMD forces to MD forces.
675  *
676  * Do conversion from Cal->Joule and from
677  * Angstrom -> nm and from a pointer array to arrays to 3*N array.
678  */
679 static void imd_copyto_MD_Forces(t_gmx_IMD_setup *IMDsetup)
680 {
681     int  i;
682     real conversion = CAL2JOULE * NM2A;
683
684
685     for (i = 0; i < IMDsetup->nforces; i++)
686     {
687         /* Copy the indices, a copy is important because we may update the incoming forces
688          * whenever we receive new forces while the MD forces are only communicated upon
689          * IMD communication.*/
690         IMDsetup->f_ind[i] = IMDsetup->vmd_f_ind[i];
691
692         /* Convert to rvecs and do a proper unit conversion */
693         IMDsetup->f[i][0] = IMDsetup->vmd_forces[3*i    ] * conversion;
694         IMDsetup->f[i][1] = IMDsetup->vmd_forces[3*i + 1] * conversion;
695         IMDsetup->f[i][2] = IMDsetup->vmd_forces[3*i + 2] * conversion;
696     }
697 }
698
699
700 /*! \brief Return TRUE if any of the forces or indices changed. */
701 static gmx_bool bForcesChanged(t_gmx_IMD_setup *IMDsetup)
702 {
703     int i;
704
705
706     /* First, check whether the number of pulled atoms changed */
707     if (IMDsetup->nforces != IMDsetup->old_nforces)
708     {
709         return TRUE;
710     }
711
712     /* Second, check whether any of the involved atoms changed */
713     for (i = 0; i < IMDsetup->nforces; i++)
714     {
715         if (IMDsetup->f_ind[i] != IMDsetup->old_f_ind[i])
716         {
717             return TRUE;
718         }
719     }
720
721     /* Third, check whether all forces are the same */
722     for (i = 0; i < IMDsetup->nforces; i++)
723     {
724         if (IMDsetup->f[i][XX] != IMDsetup->old_forces[i][XX])
725         {
726             return TRUE;
727         }
728         if (IMDsetup->f[i][YY] != IMDsetup->old_forces[i][YY])
729         {
730             return TRUE;
731         }
732         if (IMDsetup->f[i][ZZ] != IMDsetup->old_forces[i][ZZ])
733         {
734             return TRUE;
735         }
736     }
737
738     /* All old and new forces are identical! */
739     return FALSE;
740 }
741
742
743 /*! \brief Fill the old_f_ind and old_forces arrays with the new, old values. */
744 static void keep_old_values(t_gmx_IMD_setup *IMDsetup)
745 {
746     int i;
747
748
749     IMDsetup->old_nforces = IMDsetup->nforces;
750
751     for (i = 0; i < IMDsetup->nforces; i++)
752     {
753         IMDsetup->old_f_ind[i] = IMDsetup->f_ind[i];
754         copy_rvec(IMDsetup->f[i], IMDsetup->old_forces[i]);
755     }
756 }
757
758
759 /*! \brief Returns TRUE if any component of the two rvecs differs. */
760 static inline gmx_bool rvecs_differ(const rvec v1, const rvec v2)
761 {
762     int i;
763
764
765     for (i = 0; i < DIM; i++)
766     {
767         if (v1[i] != v2[i])
768         {
769             return TRUE;
770         }
771     }
772
773     return FALSE;
774 }
775
776
777 /*! \brief Write the applied pull forces to logfile.
778  *
779  * Call on master only!
780  */
781 static void output_imd_forces(t_inputrec *ir, double time)
782 {
783     t_gmx_IMD_setup *IMDsetup;
784     int              i;
785
786
787     IMDsetup = ir->imd->setup;
788
789     if (bForcesChanged(IMDsetup))
790     {
791         /* Write time and total number of applied IMD forces */
792         fprintf(IMDsetup->outf, "%14.6e%6d", time, IMDsetup->nforces);
793
794         /* Write out the global atom indices of the pulled atoms and the forces itself,
795          * write out a force only if it has changed since the last output */
796         for (i = 0; i < IMDsetup->nforces; i++)
797         {
798             if (rvecs_differ(IMDsetup->f[i], IMDsetup->old_forces[i]))
799             {
800                 fprintf(IMDsetup->outf, "%9d", IMDsetup->ind[IMDsetup->f_ind[i]] + 1);
801                 fprintf(IMDsetup->outf, "%12.4e%12.4e%12.4e", IMDsetup->f[i][0], IMDsetup->f[i][1], IMDsetup->f[i][2]);
802             }
803         }
804         fprintf(IMDsetup->outf, "\n");
805
806         keep_old_values(IMDsetup);
807     }
808 }
809
810
811 /*! \brief Synchronize the nodes. */
812 static void imd_sync_nodes(t_inputrec *ir, const t_commrec *cr, double t)
813 {
814     int              new_nforces = 0;
815     t_gmx_IMD_setup *IMDsetup;
816
817
818     IMDsetup = ir->imd->setup;
819
820     /* Notify the other nodes whether we are still connected. */
821     if (PAR(cr))
822     {
823         block_bc(cr, IMDsetup->bConnected);
824     }
825
826     /* ...if not connected, the job is done here. */
827     if (!IMDsetup->bConnected)
828     {
829         return;
830     }
831
832     /* Let the other nodes know whether we got a new IMD synchronization frequency. */
833     if (PAR(cr))
834     {
835         block_bc(cr, IMDsetup->nstimd_new);
836     }
837
838     /* Now we all set the (new) nstimd communication time step */
839     IMDsetup->nstimd = IMDsetup->nstimd_new;
840
841     /* We're done if we don't allow pulling at all */
842     if (!(IMDsetup->bForceActivated))
843     {
844         return;
845     }
846
847     /* OK, let's check if we have received forces which we need to communicate
848      * to the other nodes */
849     if (MASTER(cr))
850     {
851         if (IMDsetup->bNewForces)
852         {
853             new_nforces = IMDsetup->vmd_nforces;
854         }
855         /* make the "new_forces" negative, when we did not receive new ones */
856         else
857         {
858             new_nforces = IMDsetup->vmd_nforces * -1;
859         }
860     }
861
862     /* make new_forces known to the clients */
863     if (PAR(cr))
864     {
865         block_bc(cr, new_nforces);
866     }
867
868     /* When new_natoms < 0 then we know that these are still the same forces
869      * so we don't communicate them, otherwise... */
870     if (new_nforces >= 0)
871     {
872         /* set local VMD and nforces */
873         IMDsetup->vmd_nforces = new_nforces;
874         IMDsetup->nforces     = IMDsetup->vmd_nforces;
875
876         /* now everybody knows the number of forces in f_ind, so we can prepare
877          * the target arrays for indices and forces */
878         imd_prepare_MD_Forces(IMDsetup);
879
880         /* we first update the MD forces on the master by converting the VMD forces */
881         if (MASTER(cr))
882         {
883             imd_copyto_MD_Forces(IMDsetup);
884             /* We also write out forces on every update, so that we know which
885              * forces are applied for every step */
886             if (IMDsetup->outf)
887             {
888                 output_imd_forces(ir, t);
889             }
890         }
891
892         /* In parallel mode we communicate the to-be-applied forces to the other nodes */
893         if (PAR(cr))
894         {
895             nblock_bc(cr, IMDsetup->nforces, IMDsetup->f_ind);
896             nblock_bc(cr, IMDsetup->nforces, IMDsetup->f    );
897         }
898
899         /* done communicating the forces, reset bNewForces */
900         IMDsetup->bNewForces = FALSE;
901     }
902 }
903
904
905 /*! \brief Reads header from the client and decides what to do. */
906 static void imd_readcommand(t_gmx_IMD_setup *IMDsetup)
907 {
908     gmx_bool       IMDpaused = FALSE;
909     IMDMessageType itype;
910
911
912     while (IMDsetup->clientsocket && (imdsock_tryread(IMDsetup->clientsocket, 0, 0) > 0 || IMDpaused))
913     {
914         itype = imd_recv_header(IMDsetup->clientsocket, &(IMDsetup->length));
915         /* let's see what we got: */
916         switch (itype)
917         {
918             /* IMD asks us to terminate the simulation, check if the user allowed this */
919             case IMD_KILL:
920                 if (IMDsetup->bTerminatable)
921                 {
922                     fprintf(stderr, " %s Terminating connection and running simulation (if supported by integrator).\n", IMDstr);
923                     IMDsetup->bTerminated = TRUE;
924                     IMDsetup->bWConnect   = FALSE;
925                     gmx_set_stop_condition(gmx_stop_cond_next);
926                 }
927                 else
928                 {
929                     fprintf(stderr, " %s Set -imdterm command line switch to allow mdrun termination from within IMD.\n", IMDstr);
930                 }
931
932                 break;
933
934             /* the client doen't want to talk to us anymore */
935             case IMD_DISCONNECT:
936                 fprintf(stderr, " %s Disconnecting client.\n", IMDstr);
937                 imd_disconnect(IMDsetup);
938                 break;
939
940             /* we got new forces, read them and set bNewForces flag */
941             case IMD_MDCOMM:
942                 imd_read_vmd_Forces(IMDsetup);
943                 IMDsetup->bNewForces = TRUE;
944                 break;
945
946             /* the client asks us to (un)pause the simulation. So we toggle the IMDpaused state */
947             case IMD_PAUSE:
948                 if (IMDpaused)
949                 {
950                     fprintf(stderr, " %s Un-pause command received.\n", IMDstr);
951                     IMDpaused = FALSE;
952                 }
953                 else
954                 {
955                     fprintf(stderr, " %s Pause command received.\n", IMDstr);
956                     IMDpaused = TRUE;
957                 }
958
959                 break;
960
961             /* the client sets a new transfer rate, if we get 0, we reset the rate
962              * to the default. VMD filters 0 however */
963             case IMD_TRATE:
964                 IMDsetup->nstimd_new = (IMDsetup->length > 0) ? IMDsetup->length : IMDsetup->nstimd_def;
965                 fprintf(stderr, " %s Update frequency will be set to %d.\n", IMDstr, IMDsetup->nstimd_new);
966                 break;
967
968             /* Catch all rule for the remaining IMD types which we don't expect */
969             default:
970                 fprintf(stderr, " %s Received unexpected %s.\n", IMDstr, enum_name(static_cast<int>(itype), IMD_NR, eIMDType_names));
971                 imd_fatal(IMDsetup, "Terminating connection\n");
972                 break;
973         } /* end switch */
974     }     /* end while  */
975 }
976
977
978 /*! \brief Open IMD output file and write header information.
979  *
980  * Call on master only.
981  */
982 static FILE *open_imd_out(const char                     *fn,
983                           t_gmx_IMD_setup                *IMDsetup,
984                           int                             nat_total,
985                           const gmx_output_env_t         *oenv,
986                           const gmx::ContinuationOptions &continuationOptions)
987 {
988     FILE       *fp;
989
990
991     /* Open log file of applied IMD forces if requested */
992     if (fn && oenv)
993     {
994         /* If we append to an existing file, all the header information is already there */
995         if (continuationOptions.appendFiles)
996         {
997             fp = gmx_fio_fopen(fn, "a+");
998         }
999         else
1000         {
1001             fp = gmx_fio_fopen(fn, "w+");
1002             if (IMDsetup->nat == nat_total)
1003             {
1004                 fprintf(fp, "# Note that you can select an IMD index group in the .mdp file if a subset of the atoms suffices.\n");
1005             }
1006
1007             xvgr_header(fp, "IMD Pull Forces", "Time (ps)", "# of Forces / Atom IDs / Forces (kJ/mol)", exvggtNONE, oenv);
1008
1009             fprintf(fp, "# Can display and manipulate %d (of a total of %d) atoms via IMD.\n", IMDsetup->nat, nat_total);
1010             fprintf(fp, "# column 1    : time (ps)\n");
1011             fprintf(fp, "# column 2    : total number of atoms feeling an IMD pulling force at that time\n");
1012             fprintf(fp, "# cols. 3.-6  : global atom number of pulled atom, x-force, y-force, z-force (kJ/mol)\n");
1013             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");
1014             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");
1015             fflush(fp);
1016         }
1017
1018         /* To reduce the output file size we remember the old values and output only
1019          * when something changed */
1020         snew(IMDsetup->old_f_ind, IMDsetup->nat);  /* One can never pull on more atoms */
1021         snew(IMDsetup->old_forces, IMDsetup->nat);
1022
1023         return fp;
1024     }
1025
1026     fprintf(stdout, "%s For a log of the IMD pull forces explicitly specify '-if' on the command line.\n"
1027             "%s (Not possible with energy minimization.)\n", IMDstr, IMDstr);
1028
1029     return nullptr;
1030 }
1031 #endif
1032
1033
1034 void IMD_finalize(gmx_bool bIMD, t_IMD *imd)
1035 {
1036     if (bIMD)
1037     {
1038         if (imd->setup->outf)
1039         {
1040             gmx_fio_fclose(imd->setup->outf);
1041         }
1042     }
1043 }
1044
1045
1046 #ifdef GMX_IMD
1047 /*! \brief Creates the molecule start-end position array of molecules in the IMD group. */
1048 static void init_imd_prepare_mols_in_imdgroup(t_gmx_IMD_setup *IMDsetup, const gmx_mtop_t *top_global)
1049 {
1050     int      i, ii;
1051     t_block  lmols;
1052     int      nat;
1053     int     *ind;
1054
1055     nat   = IMDsetup->nat;
1056     ind   = IMDsetup->ind;
1057
1058     lmols.nr = 0;
1059
1060     /* check whether index is sorted */
1061     for (i = 0; i < nat-1; i++)
1062     {
1063         if (ind[i] > ind[i+1])
1064         {
1065             gmx_fatal(FARGS, "%s IMD index is not sorted. This is currently not supported.\n", IMDstr);
1066         }
1067     }
1068
1069     gmx::RangePartitioning gmols = gmx_mtop_molecules(*top_global);
1070     snew(lmols.index, gmols.numBlocks() + 1);
1071     lmols.index[0] = 0;
1072
1073     for (i = 0; i < gmols.numBlocks(); i++)
1074     {
1075         auto mol   = gmols.block(i);
1076         int  count = 0;
1077         for (ii = 0; ii < nat; ii++)
1078         {
1079             if (mol.inRange(ind[ii]))
1080             {
1081                 count += 1;
1082             }
1083         }
1084         if (count > 0)
1085         {
1086             lmols.index[lmols.nr+1] = lmols.index[lmols.nr]+count;
1087             lmols.nr               += 1;
1088         }
1089     }
1090     srenew(lmols.index, lmols.nr+1);
1091     lmols.nalloc_index = lmols.nr+1;
1092     IMDsetup->mols     = lmols;
1093 }
1094
1095
1096 /*! \brief Copied and modified from groupcoord.c shift_positions_group(). */
1097 static void shift_positions(
1098         const matrix box,
1099         rvec         x[], /* The positions [0..nr] */
1100         const ivec   is,  /* The shift [0..nr] */
1101         int          nr)  /* The number of positions */
1102 {
1103     int      i, tx, ty, tz;
1104
1105     /* Loop over the group's atoms */
1106     if (TRICLINIC(box))
1107     {
1108         for (i = 0; i < nr; i++)
1109         {
1110             tx = is[XX];
1111             ty = is[YY];
1112             tz = is[ZZ];
1113
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];
1117         }
1118     }
1119     else
1120     {
1121         for (i = 0; i < nr; i++)
1122         {
1123             tx = is[XX];
1124             ty = is[YY];
1125             tz = is[ZZ];
1126
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];
1130         }
1131     }
1132 }
1133
1134
1135 /*! \brief Removes shifts of molecules diffused outside of the box. */
1136 static void imd_remove_molshifts(t_gmx_IMD_setup *IMDsetup, const matrix box)
1137 {
1138     int     i, ii, molsize;
1139     ivec    largest, smallest, shift;
1140     t_block mols;
1141
1142
1143     mols = IMDsetup->mols;
1144
1145     /* for each molecule also present in IMD group */
1146     for (i = 0; i < mols.nr; i++)
1147     {
1148         /* first we determine the minimum and maximum shifts for each molecule */
1149
1150         clear_ivec(largest);
1151         clear_ivec(smallest);
1152         clear_ivec(shift);
1153
1154         copy_ivec(IMDsetup->xa_shifts[mols.index[i]], largest);
1155         copy_ivec(IMDsetup->xa_shifts[mols.index[i]], smallest);
1156
1157         for (ii = mols.index[i]+1; ii < mols.index[i+1]; ii++)
1158         {
1159             if (IMDsetup->xa_shifts[ii][XX] > largest[XX])
1160             {
1161                 largest[XX]  = IMDsetup->xa_shifts[ii][XX];
1162             }
1163             if (IMDsetup->xa_shifts[ii][XX] < smallest[XX])
1164             {
1165                 smallest[XX] = IMDsetup->xa_shifts[ii][XX];
1166             }
1167
1168             if (IMDsetup->xa_shifts[ii][YY] > largest[YY])
1169             {
1170                 largest[YY]  = IMDsetup->xa_shifts[ii][YY];
1171             }
1172             if (IMDsetup->xa_shifts[ii][YY] < smallest[YY])
1173             {
1174                 smallest[YY] = IMDsetup->xa_shifts[ii][YY];
1175             }
1176
1177             if (IMDsetup->xa_shifts[ii][ZZ] > largest[ZZ])
1178             {
1179                 largest[ZZ]  = IMDsetup->xa_shifts[ii][ZZ];
1180             }
1181             if (IMDsetup->xa_shifts[ii][ZZ] < smallest[ZZ])
1182             {
1183                 smallest[ZZ] = IMDsetup->xa_shifts[ii][ZZ];
1184             }
1185
1186         }
1187
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)
1191         {
1192             shift[XX] = smallest[XX];
1193         }
1194         if (smallest[YY] > 0)
1195         {
1196             shift[YY] = smallest[YY];
1197         }
1198         if (smallest[ZZ] > 0)
1199         {
1200             shift[ZZ] = smallest[ZZ];
1201         }
1202
1203         if (largest[XX] < 0)
1204         {
1205             shift[XX] = largest[XX];
1206         }
1207         if (largest[YY] < 0)
1208         {
1209             shift[YY] = largest[YY];
1210         }
1211         if (largest[ZZ] < 0)
1212         {
1213             shift[ZZ] = largest[ZZ];
1214         }
1215
1216         /* is there a shift at all? */
1217         if ((shift[XX]) || (shift[YY]) || (shift[ZZ]))
1218         {
1219             molsize = mols.index[i+1]-mols.index[i];
1220             /* shift the positions */
1221             shift_positions(box, &(IMDsetup->xa[mols.index[i]]), shift, molsize);
1222         }
1223
1224     }
1225 }
1226
1227
1228 /*! \brief Initialize arrays used to assemble the positions from the other nodes. */
1229 static void init_imd_prepare_for_x_assembly(const t_commrec *cr, const rvec x[], t_gmx_IMD_setup *IMDsetup)
1230 {
1231     int i, ii;
1232
1233
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);
1239
1240     /* Save the original (whole) set of positions such that later the
1241      * molecule can always be made whole again */
1242     if (MASTER(cr))
1243     {
1244         for (i = 0; i < IMDsetup->nat; i++)
1245         {
1246             ii = IMDsetup->ind[i];
1247             copy_rvec(x[ii], IMDsetup->xa_old[i]);
1248         }
1249     }
1250
1251     if (!PAR(cr))
1252     {
1253         IMDsetup->nat_loc = IMDsetup->nat;
1254         IMDsetup->ind_loc = IMDsetup->ind;
1255
1256         /* xa_ind[i] needs to be set to i for serial runs */
1257         for (i = 0; i < IMDsetup->nat; i++)
1258         {
1259             IMDsetup->xa_ind[i] = i;
1260         }
1261     }
1262
1263     /* Communicate initial coordinates xa_old to all processes */
1264 #if GMX_MPI
1265     if (PAR(cr))
1266     {
1267         gmx_bcast(IMDsetup->nat * sizeof(IMDsetup->xa_old[0]), IMDsetup->xa_old, cr);
1268     }
1269 #endif
1270 }
1271 #endif
1272
1273
1274 /*! \brief Check for non-working integrator / parallel options. */
1275 static void imd_check_integrator_parallel(t_inputrec *ir, const t_commrec *cr)
1276 {
1277     if (PAR(cr))
1278     {
1279         if (((ir->eI) == eiSteep) || ((ir->eI) == eiCG) || ((ir->eI) == eiLBFGS) || ((ir->eI) == eiNM))
1280         {
1281             gmx_fatal(FARGS, "%s Energy minimization via steep, CG, lbfgs and nm in parallel is currently not supported by IMD.\n", IMDstr);
1282         }
1283     }
1284 }
1285
1286 void init_IMD(t_inputrec              *ir,
1287               const t_commrec         *cr,
1288               const gmx_multisim_t    *ms,
1289               const gmx_mtop_t        *top_global,
1290               FILE                    *fplog,
1291               int                      defnstimd,
1292               const rvec               x[],
1293               int                      nfile,
1294               const t_filenm           fnm[],
1295               const gmx_output_env_t  *oenv,
1296               const gmx::MdrunOptions &mdrunOptions)
1297 {
1298     int              i;
1299     int              nat_total;
1300     t_gmx_IMD_setup *IMDsetup;
1301     int32_t          bufxsize;
1302     gmx_bool         bIMD = FALSE;
1303
1304
1305     /* We will allow IMD sessions only if explicitly enabled in the .tpr file */
1306     if (!ir->bIMD)
1307     {
1308         return;
1309     }
1310     // TODO many of these error conditions were we can't do what the
1311     // user asked for should be handled with a fatal error, not just a
1312     // warning.
1313
1314     const auto &options = mdrunOptions.imdOptions;
1315
1316     /* It seems we have a .tpr file that defines an IMD group and thus allows IMD sessions.
1317      * Check whether we can actually provide the IMD functionality for this setting: */
1318     if (MASTER(cr))
1319     {
1320         /* Check whether IMD was enabled by one of the command line switches: */
1321         if (options.wait || options.terminatable || options.pull)
1322         {
1323             /* Multiple simulations or replica exchange */
1324             if (isMultiSim(ms))
1325             {
1326                 fprintf(stderr, "%s Cannot use IMD for multiple simulations or replica exchange.\n", IMDstr);
1327             }
1328             /* OK, IMD seems to be allowed and turned on... */
1329             else
1330             {
1331                 fprintf(stderr, "%s Enabled. This simulation will accept incoming IMD connections.\n", IMDstr);
1332                 bIMD = TRUE;
1333             }
1334         }
1335         else
1336         {
1337             fprintf(stderr, "%s None of the -imd switches was used.\n"
1338                     "%s This run will not accept incoming IMD connections\n", IMDstr, IMDstr);
1339         }
1340     } /* end master only */
1341
1342     /* Disable IMD if not all the needed functionality is there! */
1343 #if GMX_NATIVE_WINDOWS && !defined(GMX_HAVE_WINSOCK)
1344     bIMD = FALSE;
1345     fprintf(stderr, "Disabling IMD because the winsock library was not found at compile time.\n");
1346 #endif
1347
1348     /* Let the other nodes know whether we want IMD */
1349     if (PAR(cr))
1350     {
1351         block_bc(cr, bIMD);
1352     }
1353     /* ... and update our local inputrec accordingly. */
1354     ir->bIMD = bIMD;
1355
1356     /*... if not we are done.*/
1357     if (!ir->bIMD)
1358     {
1359         return;
1360     }
1361
1362
1363     /* check if we're using a sane integrator / parallel combination */
1364     imd_check_integrator_parallel(ir, cr);
1365
1366
1367     /*
1368      *****************************************************
1369      * From here on we assume that IMD is turned on      *
1370      *****************************************************
1371      */
1372
1373 #ifdef GMX_IMD
1374     nat_total = top_global->natoms;
1375
1376     /* Initialize IMD setup structure. If we read in a pre-IMD .tpr file, imd->nat
1377      * will be zero. For those cases we transfer _all_ atomic positions */
1378     ir->imd->setup = imd_create(ir->imd->nat > 0 ? ir->imd->nat : nat_total,
1379                                 defnstimd, options.port);
1380     IMDsetup       = ir->imd->setup;
1381
1382     /* We might need to open an output file for IMD forces data */
1383     if (MASTER(cr))
1384     {
1385         IMDsetup->outf = open_imd_out(opt2fn("-if", nfile, fnm), ir->imd->setup, nat_total, oenv, mdrunOptions.continuationOptions);
1386     }
1387
1388     /* Make sure that we operate with a valid atom index array for the IMD atoms */
1389     if (ir->imd->nat > 0)
1390     {
1391         /* Point to the user-supplied array of atom numbers */
1392         IMDsetup->ind = ir->imd->ind;
1393     }
1394     else
1395     {
1396         /* Make a dummy (ind[i] = i) array of all atoms */
1397         snew(IMDsetup->ind, nat_total);
1398         for (i = 0; i < nat_total; i++)
1399         {
1400             IMDsetup->ind[i] = i;
1401         }
1402     }
1403
1404     /* read environment on master and prepare socket for incoming connections */
1405     if (MASTER(cr))
1406     {
1407         /* we allocate memory for our IMD energy structure */
1408         int32_t recsize = HEADERSIZE + sizeof(IMDEnergyBlock);
1409         snew(IMDsetup->energysendbuf, recsize);
1410
1411         /* Shall we wait for a connection? */
1412         if (options.wait)
1413         {
1414             IMDsetup->bWConnect = TRUE;
1415             fprintf(stderr, "%s Pausing simulation while no IMD connection present (-imdwait).\n", IMDstr);
1416         }
1417
1418         /* Will the IMD clients be able to terminate the simulation? */
1419         if (options.terminatable)
1420         {
1421             IMDsetup->bTerminatable = TRUE;
1422             fprintf(stderr, "%s Allow termination of the simulation from IMD client (-imdterm).\n", IMDstr);
1423         }
1424
1425         /* Is pulling from IMD client allowed? */
1426         if (options.pull)
1427         {
1428             IMDsetup->bForceActivated = TRUE;
1429             fprintf(stderr, "%s Pulling from IMD remote is enabled (-imdpull).\n", IMDstr);
1430         }
1431
1432         /* Initialize send buffers with constant size */
1433         snew(IMDsetup->sendxbuf, IMDsetup->nat);
1434         snew(IMDsetup->energies, 1);
1435         bufxsize = HEADERSIZE + 3 * sizeof(float) * IMDsetup->nat;
1436         snew(IMDsetup->coordsendbuf, bufxsize);
1437     }
1438
1439     /* do we allow interactive pulling? If so let the other nodes know. */
1440     if (PAR(cr))
1441     {
1442         block_bc(cr, IMDsetup->bForceActivated);
1443     }
1444
1445     /* setup the listening socket on master process */
1446     if (MASTER(cr))
1447     {
1448         fprintf(fplog, "%s Setting port for connection requests to %d.\n", IMDstr, IMDsetup->port);
1449         fprintf(stderr, "%s Turning on IMD - port for incoming requests is %d.\n", IMDstr, IMDsetup->port);
1450         imd_prepare_master_socket(IMDsetup);
1451         /* Wait until we have a connection if specified before */
1452         if (IMDsetup->bWConnect)
1453         {
1454             imd_blockconnect(IMDsetup);
1455         }
1456         else
1457         {
1458             fprintf(stderr, "%s -imdwait not set, starting simulation.\n", IMDstr);
1459         }
1460     }
1461     /* Let the other nodes know whether we are connected */
1462     imd_sync_nodes(ir, cr, 0);
1463
1464     /* Initialize arrays used to assemble the positions from the other nodes */
1465     init_imd_prepare_for_x_assembly(cr, x, IMDsetup);
1466
1467     /* Initialize molecule blocks to make them whole later...*/
1468     if (MASTER(cr))
1469     {
1470         init_imd_prepare_mols_in_imdgroup(IMDsetup, top_global);
1471     }
1472 #else
1473     gmx_incons("init_IMD: this GROMACS version was not compiled with IMD support!");
1474 #endif
1475 }
1476
1477
1478 gmx_bool do_IMD(gmx_bool         bIMD,
1479                 int64_t          step,
1480                 const t_commrec *cr,
1481                 gmx_bool         bNS,
1482                 const matrix     box,
1483                 const rvec       x[],
1484                 t_inputrec      *ir,
1485                 double           t,
1486                 gmx_wallcycle   *wcycle)
1487 {
1488     gmx_bool         imdstep = FALSE;
1489     t_gmx_IMD_setup *IMDsetup;
1490
1491
1492     /* IMD at all? */
1493     if (!bIMD)
1494     {
1495         return FALSE;
1496     }
1497
1498 #ifdef GMX_IMD
1499     wallcycle_start(wcycle, ewcIMD);
1500
1501     IMDsetup = ir->imd->setup;
1502
1503     /* read command from client and check if new incoming connection */
1504     if (MASTER(cr))
1505     {
1506         /* If not already connected, check for new connections */
1507         if (!IMDsetup->clientsocket)
1508         {
1509             if (IMDsetup->bWConnect)
1510             {
1511                 imd_blockconnect(IMDsetup);
1512             }
1513             else
1514             {
1515                 imd_tryconnect(IMDsetup);
1516             }
1517         }
1518
1519         /* Let's see if we have new IMD messages for us */
1520         if (IMDsetup->clientsocket)
1521         {
1522             imd_readcommand(IMDsetup);
1523         }
1524     }
1525
1526     /* is this an IMD communication step? */
1527     imdstep = do_per_step(step, IMDsetup->nstimd);
1528
1529     /* OK so this is an IMD step ... */
1530     if (imdstep)
1531     {
1532         /* First we sync all nodes to let everybody know whether we are connected to VMD */
1533         imd_sync_nodes(ir, cr, t);
1534     }
1535
1536     /* If a client is connected, we collect the positions
1537      * and put molecules back into the box before transfer */
1538     if ((imdstep && IMDsetup->bConnected)
1539         || bNS)            /* independent of imdstep, we communicate positions at each NS step */
1540     {
1541         /* Transfer the IMD positions to the master node. Every node contributes
1542          * its local positions x and stores them in the assembled xa array. */
1543         communicate_group_positions(cr, IMDsetup->xa, IMDsetup->xa_shifts, IMDsetup->xa_eshifts,
1544                                     TRUE, x, IMDsetup->nat, IMDsetup->nat_loc,
1545                                     IMDsetup->ind_loc, IMDsetup->xa_ind, IMDsetup->xa_old, box);
1546
1547         /* If connected and master -> remove shifts */
1548         if ((imdstep && IMDsetup->bConnected) && MASTER(cr))
1549         {
1550             imd_remove_molshifts(IMDsetup, box);
1551         }
1552     }
1553
1554     wallcycle_stop(wcycle, ewcIMD);
1555 #else
1556     gmx_incons("do_IMD called without IMD support!");
1557 #endif
1558
1559     return imdstep;
1560 }
1561
1562
1563 void IMD_fill_energy_record(gmx_bool bIMD, t_IMD *imd, const gmx_enerdata_t *enerd,
1564                             int64_t step, gmx_bool bHaveNewEnergies)
1565 {
1566     IMDEnergyBlock *ene;
1567     t_gmx_IMD      *IMDsetup;
1568
1569
1570     if (bIMD)
1571     {
1572 #ifdef GMX_IMD
1573         IMDsetup = imd->setup;
1574
1575         if (IMDsetup->clientsocket)
1576         {
1577             ene = IMDsetup->energies;
1578
1579             ene->tstep = step;
1580
1581             /* In MPI-parallel simulations the energies are not accessible a at every time step.
1582              * We update them if we have new values, otherwise, the energy values from the
1583              * last global communication step are still on display in the viewer. */
1584             if (bHaveNewEnergies)
1585             {
1586                 ene->T_abs   = static_cast<float>(enerd->term[F_TEMP   ]);
1587                 ene->E_pot   = static_cast<float>(enerd->term[F_EPOT   ]);
1588                 ene->E_tot   = static_cast<float>(enerd->term[F_ETOT   ]);
1589                 ene->E_bond  = static_cast<float>(enerd->term[F_BONDS  ]);
1590                 ene->E_angle = static_cast<float>(enerd->term[F_ANGLES ]);
1591                 ene->E_dihe  = static_cast<float>(enerd->term[F_PDIHS  ]);
1592                 ene->E_impr  = static_cast<float>(enerd->term[F_IDIHS  ]);
1593                 ene->E_vdw   = static_cast<float>(enerd->term[F_LJ     ]);
1594                 ene->E_coul  = static_cast<float>(enerd->term[F_COUL_SR]);
1595             }
1596         }
1597 #else
1598         gmx_incons("IMD_fill_energy_record called without IMD support.");
1599 #endif
1600     }
1601 }
1602
1603
1604 void IMD_send_positions(t_IMD *imd)
1605 {
1606 #ifdef GMX_IMD
1607     t_gmx_IMD *IMDsetup;
1608
1609
1610     IMDsetup = imd->setup;
1611
1612     if (IMDsetup->clientsocket)
1613     {
1614
1615         if (imd_send_energies(IMDsetup->clientsocket, IMDsetup->energies, IMDsetup->energysendbuf))
1616         {
1617             imd_fatal(IMDsetup, "Error sending updated energies. Disconnecting client.\n");
1618         }
1619
1620         if (imd_send_rvecs(IMDsetup->clientsocket, IMDsetup->nat, IMDsetup->xa, IMDsetup->coordsendbuf))
1621         {
1622             imd_fatal(IMDsetup, "Error sending updated positions. Disconnecting client.\n");
1623         }
1624     }
1625 #else
1626     gmx_incons("IMD_send_positions called without IMD support.");
1627 #endif
1628 }
1629
1630
1631 void IMD_prep_energies_send_positions(gmx_bool bIMD, gmx_bool bIMDstep,
1632                                       t_IMD *imd, const gmx_enerdata_t *enerd,
1633                                       int64_t step, gmx_bool bHaveNewEnergies,
1634                                       gmx_wallcycle *wcycle)
1635 {
1636     if (bIMD)
1637     {
1638 #ifdef GMX_IMD
1639         wallcycle_start(wcycle, ewcIMD);
1640
1641         /* Update time step for IMD and prepare IMD energy record if we have new energies. */
1642         IMD_fill_energy_record(TRUE, imd, enerd, step, bHaveNewEnergies);
1643
1644         if (bIMDstep)
1645         {
1646             /* Send positions and energies to VMD client via IMD */
1647             IMD_send_positions(imd);
1648         }
1649
1650         wallcycle_stop(wcycle, ewcIMD);
1651 #else
1652         gmx_incons("IMD_prep_energies_send_positions called without IMD support.");
1653 #endif
1654     }
1655 }
1656
1657 int IMD_get_step(t_gmx_IMD *IMDsetup)
1658 {
1659     return IMDsetup->nstimd;
1660 }
1661
1662
1663 void IMD_apply_forces(gmx_bool bIMD, t_IMD *imd, const t_commrec *cr, rvec *f,
1664                       gmx_wallcycle *wcycle)
1665 {
1666     int              i, j;
1667     t_gmx_IMD_setup *IMDsetup;
1668
1669
1670     if (bIMD)
1671     {
1672 #ifdef GMX_IMD
1673         wallcycle_start(wcycle, ewcIMD);
1674
1675         IMDsetup = imd->setup;
1676
1677         /* Are forces allowed at all? If not we're done */
1678         if (!IMDsetup->bForceActivated)
1679         {
1680             return;
1681         }
1682
1683         for (i = 0; i < IMDsetup->nforces; i++)
1684         {
1685             /* j are the indices in the "System group".*/
1686             j = IMDsetup->ind[IMDsetup->f_ind[i]];
1687
1688             /* check if this is a local atom and find out locndx */
1689             const int *locndx;
1690             if (PAR(cr) && (locndx = cr->dd->ga2la->findHome(j)))
1691             {
1692                 j = *locndx;
1693             }
1694
1695             rvec_inc(f[j], IMDsetup->f[i]);
1696         }
1697
1698         wallcycle_start(wcycle, ewcIMD);
1699 #else
1700         gmx_incons("IMD_apply_forces called without IMD support.");
1701 #endif
1702     }
1703 }