Bulk change to const ref for mtop
[alexxy/gromacs.git] / src / gromacs / topology / mtop_util.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2008,2009,2010, The GROMACS development team.
5  * Copyright (c) 2012,2013,2014,2015,2016 The GROMACS development team.
6  * Copyright (c) 2017,2018,2019,2020,2021, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 #include "gmxpre.h"
38
39 #include "mtop_util.h"
40
41 #include <climits>
42 #include <cstddef>
43 #include <cstdio>
44 #include <cstdlib>
45 #include <cstring>
46
47 #include "gromacs/math/vectypes.h"
48 #include "gromacs/topology/atoms.h"
49 #include "gromacs/topology/block.h"
50 #include "gromacs/topology/exclusionblocks.h"
51 #include "gromacs/topology/idef.h"
52 #include "gromacs/topology/ifunc.h"
53 #include "gromacs/topology/topology.h"
54 #include "gromacs/topology/topsort.h"
55 #include "gromacs/utility/arrayref.h"
56 #include "gromacs/utility/fatalerror.h"
57 #include "gromacs/utility/real.h"
58 #include "gromacs/utility/smalloc.h"
59
60 void gmx_mtop_count_atomtypes(const gmx_mtop_t& mtop, int state, int typecount[])
61 {
62     for (int i = 0; i < mtop.ffparams.atnr; ++i)
63     {
64         typecount[i] = 0;
65     }
66     for (const gmx_molblock_t& molb : mtop.molblock)
67     {
68         const t_atoms& atoms = mtop.moltype[molb.type].atoms;
69         for (int i = 0; i < atoms.nr; ++i)
70         {
71             const int tpi = (state == 0) ? atoms.atom[i].type : atoms.atom[i].typeB;
72             typecount[tpi] += molb.nmol;
73         }
74     }
75 }
76
77 int gmx_mtop_num_molecules(const gmx_mtop_t& mtop)
78 {
79     int numMolecules = 0;
80     for (const gmx_molblock_t& molb : mtop.molblock)
81     {
82         numMolecules += molb.nmol;
83     }
84     return numMolecules;
85 }
86
87 int gmx_mtop_nres(const gmx_mtop_t& mtop)
88 {
89     int nres = 0;
90     for (const gmx_molblock_t& molb : mtop.molblock)
91     {
92         nres += molb.nmol * mtop.moltype[molb.type].atoms.nres;
93     }
94     return nres;
95 }
96
97 AtomIterator::AtomIterator(const gmx_mtop_t& mtop, int globalAtomNumber) :
98     mtop_(&mtop),
99     mblock_(0),
100     atoms_(&mtop.moltype[mtop.molblock[0].type].atoms),
101     currentMolecule_(0),
102     highestResidueNumber_(mtop.maxResNumberNotRenumbered()),
103     localAtomNumber_(0),
104     globalAtomNumber_(globalAtomNumber)
105 {
106     GMX_ASSERT(globalAtomNumber == 0 || globalAtomNumber == mtop.natoms,
107                "Starting at other atoms not implemented yet");
108 }
109
110 AtomIterator& AtomIterator::operator++()
111 {
112     localAtomNumber_++;
113     globalAtomNumber_++;
114
115     if (localAtomNumber_ >= atoms_->nr)
116     {
117         if (atoms_->nres <= mtop_->maxResiduesPerMoleculeToTriggerRenumber())
118         {
119             /* Single residue molecule, increase the count with one */
120             highestResidueNumber_ += atoms_->nres;
121         }
122         currentMolecule_++;
123         localAtomNumber_ = 0;
124         if (currentMolecule_ >= mtop_->molblock[mblock_].nmol)
125         {
126             mblock_++;
127             if (mblock_ >= mtop_->molblock.size())
128             {
129                 return *this;
130             }
131             atoms_           = &mtop_->moltype[mtop_->molblock[mblock_].type].atoms;
132             currentMolecule_ = 0;
133         }
134     }
135     return *this;
136 }
137
138 bool AtomIterator::operator==(const AtomIterator& o) const
139 {
140     return mtop_ == o.mtop_ && globalAtomNumber_ == o.globalAtomNumber_;
141 }
142
143 const t_atom& AtomProxy::atom() const
144 {
145     return it_->atoms_->atom[it_->localAtomNumber_];
146 }
147
148 int AtomProxy::globalAtomNumber() const
149 {
150     return it_->globalAtomNumber_;
151 }
152
153 const char* AtomProxy::atomName() const
154 {
155     return *(it_->atoms_->atomname[it_->localAtomNumber_]);
156 }
157
158 const char* AtomProxy::residueName() const
159 {
160     int residueIndexInMolecule = it_->atoms_->atom[it_->localAtomNumber_].resind;
161     return *(it_->atoms_->resinfo[residueIndexInMolecule].name);
162 }
163
164 int AtomProxy::residueNumber() const
165 {
166     int residueIndexInMolecule = it_->atoms_->atom[it_->localAtomNumber_].resind;
167     if (it_->atoms_->nres <= it_->mtop_->maxResiduesPerMoleculeToTriggerRenumber())
168     {
169         return it_->highestResidueNumber_ + 1 + residueIndexInMolecule;
170     }
171     else
172     {
173         return it_->atoms_->resinfo[residueIndexInMolecule].nr;
174     }
175 }
176
177 const gmx_moltype_t& AtomProxy::moleculeType() const
178 {
179     return it_->mtop_->moltype[it_->mtop_->molblock[it_->mblock_].type];
180 }
181
182 int AtomProxy::atomNumberInMol() const
183 {
184     return it_->localAtomNumber_;
185 }
186
187 struct gmx_mtop_atomloop_block
188 {
189     const gmx_mtop_t* mtop;
190     size_t            mblock;
191     const t_atoms*    atoms;
192     int               at_local;
193 };
194
195 gmx_mtop_atomloop_block_t gmx_mtop_atomloop_block_init(const gmx_mtop_t& mtop)
196 {
197     struct gmx_mtop_atomloop_block* aloop = nullptr;
198
199     snew(aloop, 1);
200
201     aloop->mtop     = &mtop;
202     aloop->mblock   = 0;
203     aloop->atoms    = &mtop.moltype[mtop.molblock[aloop->mblock].type].atoms;
204     aloop->at_local = -1;
205
206     return aloop;
207 }
208
209 static void gmx_mtop_atomloop_block_destroy(gmx_mtop_atomloop_block_t aloop)
210 {
211     sfree(aloop);
212 }
213
214 gmx_bool gmx_mtop_atomloop_block_next(gmx_mtop_atomloop_block_t aloop, const t_atom** atom, int* nmol)
215 {
216     if (aloop == nullptr)
217     {
218         gmx_incons("gmx_mtop_atomloop_all_next called without calling gmx_mtop_atomloop_all_init");
219     }
220
221     aloop->at_local++;
222
223     if (aloop->at_local >= aloop->atoms->nr)
224     {
225         aloop->mblock++;
226         if (aloop->mblock >= aloop->mtop->molblock.size())
227         {
228             gmx_mtop_atomloop_block_destroy(aloop);
229             return FALSE;
230         }
231         aloop->atoms    = &aloop->mtop->moltype[aloop->mtop->molblock[aloop->mblock].type].atoms;
232         aloop->at_local = 0;
233     }
234
235     *atom = &aloop->atoms->atom[aloop->at_local];
236     *nmol = aloop->mtop->molblock[aloop->mblock].nmol;
237
238     return TRUE;
239 }
240
241 typedef struct gmx_mtop_ilistloop
242 {
243     const gmx_mtop_t* mtop;
244     int               mblock;
245 } t_gmx_mtop_ilist;
246
247 gmx_mtop_ilistloop_t gmx_mtop_ilistloop_init(const gmx_mtop_t& mtop)
248 {
249     struct gmx_mtop_ilistloop* iloop = nullptr;
250
251     snew(iloop, 1);
252
253     iloop->mtop   = &mtop;
254     iloop->mblock = -1;
255
256     return iloop;
257 }
258
259 static void gmx_mtop_ilistloop_destroy(gmx_mtop_ilistloop_t iloop)
260 {
261     sfree(iloop);
262 }
263
264 const InteractionLists* gmx_mtop_ilistloop_next(gmx_mtop_ilistloop_t iloop, int* nmol)
265 {
266     if (iloop == nullptr)
267     {
268         gmx_incons("gmx_mtop_ilistloop_next called without calling gmx_mtop_ilistloop_init");
269     }
270
271     iloop->mblock++;
272     if (iloop->mblock >= gmx::ssize(iloop->mtop->molblock))
273     {
274         if (iloop->mblock == gmx::ssize(iloop->mtop->molblock) && iloop->mtop->bIntermolecularInteractions)
275         {
276             *nmol = 1;
277             return iloop->mtop->intermolecular_ilist.get();
278         }
279
280         gmx_mtop_ilistloop_destroy(iloop);
281         return nullptr;
282     }
283
284     *nmol = iloop->mtop->molblock[iloop->mblock].nmol;
285
286     return &iloop->mtop->moltype[iloop->mtop->molblock[iloop->mblock].type].ilist;
287 }
288 typedef struct gmx_mtop_ilistloop_all
289 {
290     const gmx_mtop_t* mtop;
291     size_t            mblock;
292     int               mol;
293     int               a_offset;
294 } t_gmx_mtop_ilist_all;
295
296 int gmx_mtop_ftype_count(const gmx_mtop_t& mtop, int ftype)
297 {
298     int nmol = 0;
299     int n    = 0;
300
301     gmx_mtop_ilistloop_t iloop = gmx_mtop_ilistloop_init(mtop);
302     while (const InteractionLists* il = gmx_mtop_ilistloop_next(iloop, &nmol))
303     {
304         n += nmol * (*il)[ftype].size() / (1 + NRAL(ftype));
305     }
306
307     if (mtop.bIntermolecularInteractions)
308     {
309         n += (*mtop.intermolecular_ilist)[ftype].size() / (1 + NRAL(ftype));
310     }
311
312     return n;
313 }
314
315 int gmx_mtop_interaction_count(const gmx_mtop_t& mtop, const int unsigned if_flags)
316 {
317     int n = 0;
318
319     gmx_mtop_ilistloop_t iloop = gmx_mtop_ilistloop_init(mtop);
320     int                  nmol  = 0;
321     while (const InteractionLists* il = gmx_mtop_ilistloop_next(iloop, &nmol))
322     {
323         for (int ftype = 0; ftype < F_NRE; ftype++)
324         {
325             if ((interaction_function[ftype].flags & if_flags) == if_flags)
326             {
327                 n += nmol * (*il)[ftype].size() / (1 + NRAL(ftype));
328             }
329         }
330     }
331
332     if (mtop.bIntermolecularInteractions)
333     {
334         for (int ftype = 0; ftype < F_NRE; ftype++)
335         {
336             if ((interaction_function[ftype].flags & if_flags) == if_flags)
337             {
338                 n += (*mtop.intermolecular_ilist)[ftype].size() / (1 + NRAL(ftype));
339             }
340         }
341     }
342
343     return n;
344 }
345
346 gmx::EnumerationArray<ParticleType, int> gmx_mtop_particletype_count(const gmx_mtop_t& mtop)
347 {
348     gmx::EnumerationArray<ParticleType, int> count = { { 0 } };
349
350     for (const auto& molblock : mtop.molblock)
351     {
352         const t_atoms& atoms = mtop.moltype[molblock.type].atoms;
353         for (int a = 0; a < atoms.nr; a++)
354         {
355             count[atoms.atom[a].ptype] += molblock.nmol;
356         }
357     }
358
359     return count;
360 }
361
362 static void atomcat(t_atoms* dest, const t_atoms* src, int copies, int maxres_renum, int* maxresnr)
363 {
364     int i = 0, j = 0, l = 0, size = 0;
365     int srcnr  = src->nr;
366     int destnr = dest->nr;
367
368     if (dest->nr == 0)
369     {
370         dest->haveMass    = src->haveMass;
371         dest->haveType    = src->haveType;
372         dest->haveCharge  = src->haveCharge;
373         dest->haveBState  = src->haveBState;
374         dest->havePdbInfo = src->havePdbInfo;
375     }
376     else
377     {
378         dest->haveMass    = dest->haveMass && src->haveMass;
379         dest->haveType    = dest->haveType && src->haveType;
380         dest->haveCharge  = dest->haveCharge && src->haveCharge;
381         dest->haveBState  = dest->haveBState && src->haveBState;
382         dest->havePdbInfo = dest->havePdbInfo && src->havePdbInfo;
383     }
384
385     if (srcnr)
386     {
387         size = destnr + copies * srcnr;
388         srenew(dest->atom, size);
389         srenew(dest->atomname, size);
390         if (dest->haveType)
391         {
392             srenew(dest->atomtype, size);
393             if (dest->haveBState)
394             {
395                 srenew(dest->atomtypeB, size);
396             }
397         }
398         if (dest->havePdbInfo)
399         {
400             srenew(dest->pdbinfo, size);
401         }
402     }
403     if (src->nres)
404     {
405         size = dest->nres + copies * src->nres;
406         srenew(dest->resinfo, size);
407     }
408
409     /* residue information */
410     for (l = dest->nres, j = 0; (j < copies); j++, l += src->nres)
411     {
412         memcpy(reinterpret_cast<char*>(&(dest->resinfo[l])),
413                reinterpret_cast<char*>(&(src->resinfo[0])),
414                static_cast<size_t>(src->nres * sizeof(src->resinfo[0])));
415     }
416
417     for (l = destnr, j = 0; (j < copies); j++, l += srcnr)
418     {
419         memcpy(reinterpret_cast<char*>(&(dest->atom[l])),
420                reinterpret_cast<char*>(&(src->atom[0])),
421                static_cast<size_t>(srcnr * sizeof(src->atom[0])));
422         memcpy(reinterpret_cast<char*>(&(dest->atomname[l])),
423                reinterpret_cast<char*>(&(src->atomname[0])),
424                static_cast<size_t>(srcnr * sizeof(src->atomname[0])));
425         if (dest->haveType)
426         {
427             memcpy(reinterpret_cast<char*>(&(dest->atomtype[l])),
428                    reinterpret_cast<char*>(&(src->atomtype[0])),
429                    static_cast<size_t>(srcnr * sizeof(src->atomtype[0])));
430             if (dest->haveBState)
431             {
432                 memcpy(reinterpret_cast<char*>(&(dest->atomtypeB[l])),
433                        reinterpret_cast<char*>(&(src->atomtypeB[0])),
434                        static_cast<size_t>(srcnr * sizeof(src->atomtypeB[0])));
435             }
436         }
437         if (dest->havePdbInfo)
438         {
439             memcpy(reinterpret_cast<char*>(&(dest->pdbinfo[l])),
440                    reinterpret_cast<char*>(&(src->pdbinfo[0])),
441                    static_cast<size_t>(srcnr * sizeof(src->pdbinfo[0])));
442         }
443     }
444
445     /* Increment residue indices */
446     for (l = destnr, j = 0; (j < copies); j++)
447     {
448         for (i = 0; (i < srcnr); i++, l++)
449         {
450             dest->atom[l].resind = dest->nres + j * src->nres + src->atom[i].resind;
451         }
452     }
453
454     if (src->nres <= maxres_renum)
455     {
456         /* Single residue molecule, continue counting residues */
457         for (j = 0; (j < copies); j++)
458         {
459             for (l = 0; l < src->nres; l++)
460             {
461                 (*maxresnr)++;
462                 dest->resinfo[dest->nres + j * src->nres + l].nr = *maxresnr;
463             }
464         }
465     }
466
467     dest->nres += copies * src->nres;
468     dest->nr += copies * src->nr;
469 }
470
471 t_atoms gmx_mtop_global_atoms(const gmx_mtop_t& mtop)
472 {
473     t_atoms atoms;
474
475     init_t_atoms(&atoms, 0, FALSE);
476
477     int maxresnr = mtop.maxResNumberNotRenumbered();
478     for (const gmx_molblock_t& molb : mtop.molblock)
479     {
480         atomcat(&atoms,
481                 &mtop.moltype[molb.type].atoms,
482                 molb.nmol,
483                 mtop.maxResiduesPerMoleculeToTriggerRenumber(),
484                 &maxresnr);
485     }
486
487     return atoms;
488 }
489
490 /*
491  * The cat routines below are old code from src/kernel/topcat.c
492  */
493
494 static void ilistcat(int ftype, InteractionList* dest, const InteractionList& src, int copies, int dnum, int snum)
495 {
496     const int nral = NRAL(ftype);
497
498     size_t destIndex = dest->iatoms.size();
499     dest->iatoms.resize(dest->iatoms.size() + copies * src.size());
500
501     for (int c = 0; c < copies; c++)
502     {
503         for (int i = 0; i < src.size();)
504         {
505             dest->iatoms[destIndex++] = src.iatoms[i++];
506             for (int a = 0; a < nral; a++)
507             {
508                 dest->iatoms[destIndex++] = dnum + src.iatoms[i++];
509             }
510         }
511         dnum += snum;
512     }
513 }
514
515 static void ilistcat(int ftype, t_ilist* dest, const InteractionList& src, int copies, int dnum, int snum)
516 {
517     const int nral = NRAL(ftype);
518
519     dest->nalloc = dest->nr + copies * src.size();
520     srenew(dest->iatoms, dest->nalloc);
521
522     for (int c = 0; c < copies; c++)
523     {
524         for (int i = 0; i < src.size();)
525         {
526             dest->iatoms[dest->nr++] = src.iatoms[i++];
527             for (int a = 0; a < nral; a++)
528             {
529                 dest->iatoms[dest->nr++] = dnum + src.iatoms[i++];
530             }
531         }
532         dnum += snum;
533     }
534 }
535
536 static const t_iparams& getIparams(const InteractionDefinitions& idef, const int index)
537 {
538     return idef.iparams[index];
539 }
540
541 static const t_iparams& getIparams(const t_idef& idef, const int index)
542 {
543     return idef.iparams[index];
544 }
545
546 static void resizeIParams(std::vector<t_iparams>* iparams, const int newSize)
547 {
548     iparams->resize(newSize);
549 }
550
551 static void resizeIParams(t_iparams** iparams, const int newSize)
552 {
553     srenew(*iparams, newSize);
554 }
555
556 template<typename IdefType>
557 static void set_posres_params(IdefType* idef, const gmx_molblock_t* molb, int i0, int a_offset)
558 {
559     auto* il = &idef->il[F_POSRES];
560     int   i1 = il->size() / 2;
561     resizeIParams(&idef->iparams_posres, i1);
562     for (int i = i0; i < i1; i++)
563     {
564         t_iparams* ip = &idef->iparams_posres[i];
565         /* Copy the force constants */
566         *ip        = getIparams(*idef, il->iatoms[i * 2]);
567         int a_molb = il->iatoms[i * 2 + 1] - a_offset;
568         if (molb->posres_xA.empty())
569         {
570             gmx_incons("Position restraint coordinates are missing");
571         }
572         ip->posres.pos0A[XX] = molb->posres_xA[a_molb][XX];
573         ip->posres.pos0A[YY] = molb->posres_xA[a_molb][YY];
574         ip->posres.pos0A[ZZ] = molb->posres_xA[a_molb][ZZ];
575         if (!molb->posres_xB.empty())
576         {
577             ip->posres.pos0B[XX] = molb->posres_xB[a_molb][XX];
578             ip->posres.pos0B[YY] = molb->posres_xB[a_molb][YY];
579             ip->posres.pos0B[ZZ] = molb->posres_xB[a_molb][ZZ];
580         }
581         else
582         {
583             ip->posres.pos0B[XX] = ip->posres.pos0A[XX];
584             ip->posres.pos0B[YY] = ip->posres.pos0A[YY];
585             ip->posres.pos0B[ZZ] = ip->posres.pos0A[ZZ];
586         }
587         /* Set the parameter index for idef->iparams_posre */
588         il->iatoms[i * 2] = i;
589     }
590 }
591
592 template<typename IdefType>
593 static void set_fbposres_params(IdefType* idef, const gmx_molblock_t* molb, int i0, int a_offset)
594 {
595     auto* il = &idef->il[F_FBPOSRES];
596     int   i1 = il->size() / 2;
597     resizeIParams(&idef->iparams_fbposres, i1);
598     for (int i = i0; i < i1; i++)
599     {
600         t_iparams* ip = &idef->iparams_fbposres[i];
601         /* Copy the force constants */
602         *ip        = getIparams(*idef, il->iatoms[i * 2]);
603         int a_molb = il->iatoms[i * 2 + 1] - a_offset;
604         if (molb->posres_xA.empty())
605         {
606             gmx_incons("Position restraint coordinates are missing");
607         }
608         /* Take flat-bottom posres reference from normal position restraints */
609         ip->fbposres.pos0[XX] = molb->posres_xA[a_molb][XX];
610         ip->fbposres.pos0[YY] = molb->posres_xA[a_molb][YY];
611         ip->fbposres.pos0[ZZ] = molb->posres_xA[a_molb][ZZ];
612         /* Note: no B-type for flat-bottom posres */
613
614         /* Set the parameter index for idef->iparams_posre */
615         il->iatoms[i * 2] = i;
616     }
617 }
618
619 /*! \brief Copy parameters to idef structure from mtop.
620  *
621  * Makes a deep copy of the force field parameters data structure from a gmx_mtop_t.
622  * Used to initialize legacy topology types.
623  *
624  * \param[in] mtop Reference to input mtop.
625  * \param[in] idef Pointer to idef to populate.
626  */
627 static void copyFFParametersFromMtop(const gmx_mtop_t& mtop, t_idef* idef)
628 {
629     const gmx_ffparams_t* ffp = &mtop.ffparams;
630
631     idef->ntypes = ffp->numTypes();
632     idef->atnr   = ffp->atnr;
633     /* we can no longer copy the pointers to the mtop members,
634      * because they will become invalid as soon as mtop gets free'd.
635      * We also need to make sure to only operate on valid data!
636      */
637
638     if (!ffp->functype.empty())
639     {
640         snew(idef->functype, ffp->functype.size());
641         std::copy(ffp->functype.data(), ffp->functype.data() + ffp->functype.size(), idef->functype);
642     }
643     else
644     {
645         idef->functype = nullptr;
646     }
647     if (!ffp->iparams.empty())
648     {
649         snew(idef->iparams, ffp->iparams.size());
650         std::copy(ffp->iparams.data(), ffp->iparams.data() + ffp->iparams.size(), idef->iparams);
651     }
652     else
653     {
654         idef->iparams = nullptr;
655     }
656     idef->iparams_posres   = nullptr;
657     idef->iparams_fbposres = nullptr;
658     idef->fudgeQQ          = ffp->fudgeQQ;
659     idef->ilsort           = ilsortUNKNOWN;
660 }
661
662 /*! \brief Copy idef structure from mtop.
663  *
664  * Makes a deep copy of an idef data structure from a gmx_mtop_t.
665  * Used to initialize legacy topology types.
666  *
667  * \param[in] mtop Reference to input mtop.
668  * \param[in] idef Pointer to idef to populate.
669  * \param[in] mergeConstr Decide if constraints will be merged.
670  */
671 template<typename IdefType>
672 static void copyIListsFromMtop(const gmx_mtop_t& mtop, IdefType* idef, bool mergeConstr)
673 {
674     int natoms = 0;
675     for (const gmx_molblock_t& molb : mtop.molblock)
676     {
677         const gmx_moltype_t& molt = mtop.moltype[molb.type];
678
679         int srcnr  = molt.atoms.nr;
680         int destnr = natoms;
681
682         int nposre_old   = idef->il[F_POSRES].size();
683         int nfbposre_old = idef->il[F_FBPOSRES].size();
684         for (int ftype = 0; ftype < F_NRE; ftype++)
685         {
686             if (mergeConstr && ftype == F_CONSTR && !molt.ilist[F_CONSTRNC].empty())
687             {
688                 /* Merge all constrains into one ilist.
689                  * This simplifies the constraint code.
690                  */
691                 for (int mol = 0; mol < molb.nmol; mol++)
692                 {
693                     ilistcat(ftype, &idef->il[F_CONSTR], molt.ilist[F_CONSTR], 1, destnr + mol * srcnr, srcnr);
694                     ilistcat(ftype, &idef->il[F_CONSTR], molt.ilist[F_CONSTRNC], 1, destnr + mol * srcnr, srcnr);
695                 }
696             }
697             else if (!(mergeConstr && ftype == F_CONSTRNC))
698             {
699                 ilistcat(ftype, &idef->il[ftype], molt.ilist[ftype], molb.nmol, destnr, srcnr);
700             }
701         }
702         if (idef->il[F_POSRES].size() > nposre_old)
703         {
704             /* Executing this line line stops gmxdump -sys working
705              * correctly. I'm not aware there's an elegant fix. */
706             set_posres_params(idef, &molb, nposre_old / 2, natoms);
707         }
708         if (idef->il[F_FBPOSRES].size() > nfbposre_old)
709         {
710             set_fbposres_params(idef, &molb, nfbposre_old / 2, natoms);
711         }
712
713         natoms += molb.nmol * srcnr;
714     }
715
716     if (mtop.bIntermolecularInteractions)
717     {
718         for (int ftype = 0; ftype < F_NRE; ftype++)
719         {
720             ilistcat(ftype, &idef->il[ftype], (*mtop.intermolecular_ilist)[ftype], 1, 0, mtop.natoms);
721         }
722     }
723
724     // We have not (yet) sorted free-energy interactions to the end of the ilists
725     idef->ilsort = ilsortNO_FE;
726 }
727
728 /*! \brief Copy atomtypes from mtop
729  *
730  * Makes a deep copy of t_atomtypes from gmx_mtop_t.
731  * Used to initialize legacy topology types.
732  *
733  * \param[in] mtop Reference to input mtop.
734  * \param[in] atomtypes Pointer to atomtypes to populate.
735  */
736 static void copyAtomtypesFromMtop(const gmx_mtop_t& mtop, t_atomtypes* atomtypes)
737 {
738     atomtypes->nr = mtop.atomtypes.nr;
739     if (mtop.atomtypes.atomnumber)
740     {
741         snew(atomtypes->atomnumber, mtop.atomtypes.nr);
742         std::copy(mtop.atomtypes.atomnumber,
743                   mtop.atomtypes.atomnumber + mtop.atomtypes.nr,
744                   atomtypes->atomnumber);
745     }
746     else
747     {
748         atomtypes->atomnumber = nullptr;
749     }
750 }
751
752 /*! \brief Generate a single list of lists of exclusions for the whole system
753  *
754  * \param[in] mtop  Reference to input mtop.
755  */
756 static gmx::ListOfLists<int> globalExclusionLists(const gmx_mtop_t& mtop)
757 {
758     gmx::ListOfLists<int> excls;
759
760     int atomIndex = 0;
761     for (const gmx_molblock_t& molb : mtop.molblock)
762     {
763         const gmx_moltype_t& molt = mtop.moltype[molb.type];
764
765         for (int mol = 0; mol < molb.nmol; mol++)
766         {
767             excls.appendListOfLists(molt.excls, atomIndex);
768
769             atomIndex += molt.atoms.nr;
770         }
771     }
772
773     return excls;
774 }
775
776 /*! \brief Updates inter-molecular exclusion lists
777  *
778  * This function updates inter-molecular exclusions to exclude all
779  * non-bonded interactions between a given list of atoms
780  *
781  * \param[inout]    excls   existing exclusions in local topology
782  * \param[in]       ids     list of global IDs of atoms
783  */
784 static void addMimicExclusions(gmx::ListOfLists<int>* excls, const gmx::ArrayRef<const int> ids)
785 {
786     t_blocka inter_excl{};
787     init_blocka(&inter_excl);
788     size_t n_q = ids.size();
789
790     inter_excl.nr  = excls->ssize();
791     inter_excl.nra = n_q * n_q;
792
793     size_t total_nra = n_q * n_q;
794
795     snew(inter_excl.index, excls->ssize() + 1);
796     snew(inter_excl.a, total_nra);
797
798     for (int i = 0; i < inter_excl.nr; ++i)
799     {
800         inter_excl.index[i] = 0;
801     }
802
803     /* Here we loop over the list of QM atom ids
804      *  and create exclusions between all of them resulting in
805      *  n_q * n_q sized exclusion list
806      */
807     int prev_index = 0;
808     for (int k = 0; k < inter_excl.nr; ++k)
809     {
810         inter_excl.index[k] = prev_index;
811         for (long i = 0; i < ids.ssize(); i++)
812         {
813             if (k != ids[i])
814             {
815                 continue;
816             }
817             size_t index             = n_q * i;
818             inter_excl.index[ids[i]] = index;
819             prev_index               = index + n_q;
820             for (size_t j = 0; j < n_q; ++j)
821             {
822                 inter_excl.a[n_q * i + j] = ids[j];
823             }
824         }
825     }
826     inter_excl.index[ids[n_q - 1] + 1] = n_q * n_q;
827
828     inter_excl.index[inter_excl.nr] = n_q * n_q;
829
830     std::vector<gmx::ExclusionBlock> qmexcl2(excls->size());
831     gmx::blockaToExclusionBlocks(&inter_excl, qmexcl2);
832
833     // Merge the created exclusion list with the existing one
834     gmx::mergeExclusions(excls, qmexcl2);
835 }
836
837 static void sortFreeEnergyInteractionsAtEnd(const gmx_mtop_t& mtop, InteractionDefinitions* idef)
838 {
839     std::vector<real> qA(mtop.natoms);
840     std::vector<real> qB(mtop.natoms);
841     for (const AtomProxy atomP : AtomRange(mtop))
842     {
843         const t_atom& local = atomP.atom();
844         int           index = atomP.globalAtomNumber();
845         qA[index]           = local.q;
846         qB[index]           = local.qB;
847     }
848     gmx_sort_ilist_fe(idef, qA.data(), qB.data());
849 }
850
851 static void gen_local_top(const gmx_mtop_t& mtop,
852                           bool              freeEnergyInteractionsAtEnd,
853                           bool              bMergeConstr,
854                           gmx_localtop_t*   top)
855 {
856     copyIListsFromMtop(mtop, &top->idef, bMergeConstr);
857     if (freeEnergyInteractionsAtEnd)
858     {
859         sortFreeEnergyInteractionsAtEnd(mtop, &top->idef);
860     }
861     top->excls = globalExclusionLists(mtop);
862     if (!mtop.intermolecularExclusionGroup.empty())
863     {
864         addMimicExclusions(&top->excls, mtop.intermolecularExclusionGroup);
865     }
866 }
867
868 void gmx_mtop_generate_local_top(const gmx_mtop_t& mtop, gmx_localtop_t* top, bool freeEnergyInteractionsAtEnd)
869 {
870     gen_local_top(mtop, freeEnergyInteractionsAtEnd, true, top);
871 }
872
873 /*! \brief Fills an array with molecule begin/end atom indices
874  *
875  * \param[in]  mtop   The global topology
876  * \param[out] index  Array of size nr. of molecules + 1 to be filled with molecule begin/end indices
877  */
878 static void fillMoleculeIndices(const gmx_mtop_t& mtop, gmx::ArrayRef<int> index)
879 {
880     int globalAtomIndex   = 0;
881     int globalMolIndex    = 0;
882     index[globalMolIndex] = globalAtomIndex;
883     for (const gmx_molblock_t& molb : mtop.molblock)
884     {
885         int numAtomsPerMolecule = mtop.moltype[molb.type].atoms.nr;
886         for (int mol = 0; mol < molb.nmol; mol++)
887         {
888             globalAtomIndex += numAtomsPerMolecule;
889             globalMolIndex += 1;
890             index[globalMolIndex] = globalAtomIndex;
891         }
892     }
893 }
894
895 gmx::RangePartitioning gmx_mtop_molecules(const gmx_mtop_t& mtop)
896 {
897     gmx::RangePartitioning mols;
898
899     for (const gmx_molblock_t& molb : mtop.molblock)
900     {
901         int numAtomsPerMolecule = mtop.moltype[molb.type].atoms.nr;
902         for (int mol = 0; mol < molb.nmol; mol++)
903         {
904             mols.appendBlock(numAtomsPerMolecule);
905         }
906     }
907
908     return mols;
909 }
910
911 std::vector<gmx::Range<int>> atomRangeOfEachResidue(const gmx_moltype_t& moltype)
912 {
913     std::vector<gmx::Range<int>> atomRanges;
914     int                          currentResidueNumber = moltype.atoms.atom[0].resind;
915     int                          startAtom            = 0;
916     // Go through all atoms in a molecule to store first and last atoms in each residue.
917     for (int i = 0; i < moltype.atoms.nr; i++)
918     {
919         int residueOfThisAtom = moltype.atoms.atom[i].resind;
920         if (residueOfThisAtom != currentResidueNumber)
921         {
922             // This atom belongs to the next residue, so record the range for the previous residue,
923             // remembering that end points to one place past the last atom.
924             int endAtom = i;
925             atomRanges.emplace_back(startAtom, endAtom);
926             // Prepare for the current residue
927             startAtom            = endAtom;
928             currentResidueNumber = residueOfThisAtom;
929         }
930     }
931     // special treatment for last residue in this molecule.
932     atomRanges.emplace_back(startAtom, moltype.atoms.nr);
933
934     return atomRanges;
935 }
936
937 /*! \brief Creates and returns a deprecated t_block struct with molecule indices
938  *
939  * \param[in] mtop  The global topology
940  */
941 static t_block gmx_mtop_molecules_t_block(const gmx_mtop_t& mtop)
942 {
943     t_block mols;
944
945     mols.nr           = gmx_mtop_num_molecules(mtop);
946     mols.nalloc_index = mols.nr + 1;
947     snew(mols.index, mols.nalloc_index);
948
949     fillMoleculeIndices(mtop, gmx::arrayRefFromArray(mols.index, mols.nr + 1));
950
951     return mols;
952 }
953
954 static void gen_t_topology(const gmx_mtop_t& mtop, bool bMergeConstr, t_topology* top)
955 {
956     copyAtomtypesFromMtop(mtop, &top->atomtypes);
957     for (int ftype = 0; ftype < F_NRE; ftype++)
958     {
959         top->idef.il[ftype].nr     = 0;
960         top->idef.il[ftype].nalloc = 0;
961         top->idef.il[ftype].iatoms = nullptr;
962     }
963     copyFFParametersFromMtop(mtop, &top->idef);
964     copyIListsFromMtop(mtop, &top->idef, bMergeConstr);
965
966     top->name                        = mtop.name;
967     top->atoms                       = gmx_mtop_global_atoms(mtop);
968     top->mols                        = gmx_mtop_molecules_t_block(mtop);
969     top->bIntermolecularInteractions = mtop.bIntermolecularInteractions;
970     top->symtab                      = mtop.symtab;
971 }
972
973 t_topology gmx_mtop_t_to_t_topology(gmx_mtop_t* mtop, bool freeMTop)
974 {
975     t_topology top;
976
977     gen_t_topology(*mtop, false, &top);
978
979     if (freeMTop)
980     {
981         // Clear pointers and counts, such that the pointers copied to top
982         // keep pointing to valid data after destroying mtop.
983         mtop->symtab.symbuf = nullptr;
984         mtop->symtab.nr     = 0;
985     }
986     return top;
987 }
988
989 std::vector<int> get_atom_index(const gmx_mtop_t& mtop)
990 {
991
992     std::vector<int> atom_index;
993     for (const AtomProxy atomP : AtomRange(mtop))
994     {
995         const t_atom& local = atomP.atom();
996         int           index = atomP.globalAtomNumber();
997         if (local.ptype == ParticleType::Atom)
998         {
999             atom_index.push_back(index);
1000         }
1001     }
1002     return atom_index;
1003 }
1004
1005 void convertAtomsToMtop(t_symtab* symtab, char** name, t_atoms* atoms, gmx_mtop_t* mtop)
1006 {
1007     mtop->symtab = *symtab;
1008
1009     mtop->name = name;
1010
1011     mtop->moltype.clear();
1012     mtop->moltype.resize(1);
1013     mtop->moltype.back().atoms = *atoms;
1014
1015     mtop->molblock.resize(1);
1016     mtop->molblock[0].type = 0;
1017     mtop->molblock[0].nmol = 1;
1018
1019     mtop->bIntermolecularInteractions = FALSE;
1020
1021     mtop->natoms = atoms->nr;
1022
1023     mtop->haveMoleculeIndices = false;
1024
1025     mtop->finalize();
1026 }
1027
1028 bool haveFepPerturbedNBInteractions(const gmx_mtop_t& mtop)
1029 {
1030     for (const gmx_moltype_t& molt : mtop.moltype)
1031     {
1032         for (int a = 0; a < molt.atoms.nr; a++)
1033         {
1034             if (PERTURBED(molt.atoms.atom[a]))
1035             {
1036                 return true;
1037             }
1038         }
1039     }
1040
1041     return false;
1042 }
1043
1044 bool haveFepPerturbedMasses(const gmx_mtop_t& mtop)
1045 {
1046     for (const gmx_moltype_t& molt : mtop.moltype)
1047     {
1048         for (int a = 0; a < molt.atoms.nr; a++)
1049         {
1050             const t_atom& atom = molt.atoms.atom[a];
1051             if (atom.m != atom.mB)
1052             {
1053                 return true;
1054             }
1055         }
1056     }
1057
1058     return false;
1059 }
1060
1061 bool havePerturbedConstraints(const gmx_mtop_t& mtop)
1062 {
1063     // This code assumes that all perturbed constraints parameters are actually used
1064     const auto& ffparams = mtop.ffparams;
1065
1066     for (gmx::index i = 0; i < gmx::ssize(ffparams.functype); i++)
1067     {
1068         if (ffparams.functype[i] == F_CONSTR || ffparams.functype[i] == F_CONSTRNC)
1069         {
1070             const auto& iparams = ffparams.iparams[i];
1071             if (iparams.constr.dA != iparams.constr.dB)
1072             {
1073                 return true;
1074             }
1075         }
1076     }
1077
1078     return false;
1079 }