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