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