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