Merge remote-tracking branch 'origin/release-4-6' into HEAD
[alexxy/gromacs.git] / src / gromacs / selection / poscalc.cpp
1 /*
2  *
3  *                This source code is part of
4  *
5  *                 G   R   O   M   A   C   S
6  *
7  *          GROningen MAchine for Chemical Simulations
8  *
9  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
10  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
11  * Copyright (c) 2001-2009, The GROMACS development team,
12  * check out http://www.gromacs.org for more information.
13
14  * This program is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU General Public License
16  * as published by the Free Software Foundation; either version 2
17  * of the License, or (at your option) any later version.
18  *
19  * If you want to redistribute modifications, please consider that
20  * scientific software is very special. Version control is crucial -
21  * bugs must be traceable. We will be happy to consider code for
22  * inclusion in the official distribution, but derived work must not
23  * be called official GROMACS. Details are found in the README & COPYING
24  * files - if they are missing, get the official version at www.gromacs.org.
25  *
26  * To help us fund GROMACS development, we humbly ask that you cite
27  * the papers on the package - you can find them in the top README file.
28  *
29  * For more info, check our website at http://www.gromacs.org
30  */
31 /*! \internal \file
32  * \brief
33  * Implements gmx::PositionCalculationCollection and functions in poscalc.h.
34  *
35  * \todo
36  * There is probably some room for optimization in the calculation of
37  * positions with bases.
38  * In particular, the current implementation may do a lot of unnecessary
39  * copying.
40  * The interface would need to be changed to make it possible to use the
41  * same output positions for several calculations.
42  *
43  * \todo
44  * The current algorithm for setting up base calculations could be improved
45  * in cases when there are calculations that cannot use a common base but
46  * still overlap partially (e.g., with three calculations A, B, and C
47  * such that A could use both B and C as a base, but B and C cannot use the
48  * same base).
49  * Setting up the bases in an optimal manner in every possible situation can
50  * be quite difficult unless several bases are allowed for one calculation,
51  * but better heuristics could probably be implemented.
52  * For best results, the setup should probably be postponed (at least
53  * partially) to gmx_ana_poscalc_init_eval().
54  *
55  * \author Teemu Murtola <teemu.murtola@cbr.su.se>
56  * \ingroup module_selection
57  */
58 #ifdef HAVE_CONFIG_H
59 #include <config.h>
60 #endif
61
62 #include <string.h>
63
64 #include "smalloc.h"
65 #include "typedefs.h"
66 #include "pbc.h"
67 #include "vec.h"
68
69 #include "gromacs/selection/centerofmass.h"
70 #include "gromacs/selection/indexutil.h"
71 #include "gromacs/selection/poscalc.h"
72 #include "gromacs/selection/position.h"
73 #include "gromacs/utility/exceptions.h"
74 #include "gromacs/utility/gmxassert.h"
75
76 namespace gmx
77 {
78
79 /*! \internal \brief
80  * Private implementation class for PositionCalculationCollection.
81  *
82  * \ingroup module_selection
83  */
84 class PositionCalculationCollection::Impl
85 {
86     public:
87         Impl();
88         ~Impl();
89
90         /*! \brief
91          * Inserts a position calculation structure into its collection.
92          *
93          * \param pc     Data structure to insert.
94          * \param before Data structure before which to insert
95          *   (NULL = insert at end).
96          *
97          * Inserts \p pc to its collection before \p before.
98          * If \p before is NULL, \p pc is appended to the list.
99          */
100         void insertCalculation(gmx_ana_poscalc_t *pc, gmx_ana_poscalc_t *before);
101         /*! \brief
102          * Removes a position calculation structure from its collection.
103          *
104          * \param pc    Data structure to remove.
105          *
106          * Removes \p pc from its collection.
107          */
108         void removeCalculation(gmx_ana_poscalc_t *pc);
109
110         /*! \copydoc PositionCalculationCollection::createCalculation()
111          *
112          * This method contains the actual implementation of the similarly
113          * named method in the parent class.
114          */
115         gmx_ana_poscalc_t *createCalculation(e_poscalc_t type, int flags);
116
117         /*! \brief
118          * Topology data.
119          *
120          * Can be NULL if none of the calculations require topology data or if
121          * setTopology() has not been called.
122          */
123         t_topology               *top_;
124         //! Pointer to the first data structure.
125         gmx_ana_poscalc_t        *first_;
126         //! Pointer to the last data structure.
127         gmx_ana_poscalc_t        *last_;
128         //! Whether the collection has been initialized for evaluation.
129         bool                      bInit_;
130 };
131
132 } // namespace gmx
133
134 /*! \internal \brief
135  * Data structure for position calculation.
136  */
137 struct gmx_ana_poscalc_t
138 {
139     /*! \brief
140      * Type of calculation.
141      *
142      * This field may differ from the type requested by the user, because
143      * it is changed internally to the most effective calculation.
144      * For example, if the user requests a COM calculation for residues
145      * consisting of single atoms, it is simply set to POS_ATOM.
146      * To provide a consistent interface to the user, the field \p itype
147      * should be used when information should be given out.
148      */
149     e_poscalc_t               type;
150     /*! \brief
151      * Flags for calculation options.
152      *
153      * See \ref poscalc_flags "documentation of the flags".
154      */
155     int                       flags;
156
157     /*! \brief
158      * Type for the created indices.
159      *
160      * This field always agrees with the type that the user requested, but
161      * may differ from \p type.
162      */
163     e_index_t                 itype;
164     /*! \brief
165      * Block data for the calculation.
166      */
167     t_blocka                  b;
168     /*! \brief
169      * Mapping from the blocks to the blocks of \p sbase.
170      *
171      * If \p sbase is NULL, this field is also.
172      */
173     int                      *baseid;
174     /*! \brief
175      * Maximum evaluation group.
176      */
177     gmx_ana_index_t           gmax;
178
179     /** Position storage for calculations that are used as a base. */
180     gmx_ana_pos_t            *p;
181
182     /** true if the positions have been evaluated for the current frame. */
183     bool                      bEval;
184     /*! \brief
185      * Base position data for this calculation.
186      *
187      * If not NULL, the centers required by this calculation have
188      * already been calculated in \p sbase.
189      * The structure pointed by \p sbase is always a static calculation.
190      */
191     struct gmx_ana_poscalc_t *sbase;
192     /** Next structure in the linked list of calculations. */
193     struct gmx_ana_poscalc_t *next;
194     /** Previous structure in the linked list of calculations. */
195     struct gmx_ana_poscalc_t *prev;
196     /** Number of references to this structure. */
197     int                       refcount;
198     /** Collection this calculation belongs to. */
199     gmx::PositionCalculationCollection::Impl *coll;
200 };
201
202 const char * const gmx::PositionCalculationCollection::typeEnumValues[] = {
203     "atom",
204     "res_com",       "res_cog",
205     "mol_com",       "mol_cog",
206     "whole_res_com", "whole_res_cog",
207     "whole_mol_com", "whole_mol_cog",
208     "part_res_com",  "part_res_cog",
209     "part_mol_com",  "part_mol_cog",
210     "dyn_res_com",   "dyn_res_cog",
211     "dyn_mol_com",   "dyn_mol_cog",
212     NULL,
213 };
214
215 /*! \brief
216  * Returns the partition type for a given position type.
217  *
218  * \param [in] type  \c e_poscalc_t value to convert.
219  * \returns    Corresponding \c e_indet_t.
220  */
221 static e_index_t
222 index_type_for_poscalc(e_poscalc_t type)
223 {
224     switch(type)
225     {
226         case POS_ATOM:    return INDEX_ATOM;
227         case POS_RES:     return INDEX_RES;
228         case POS_MOL:     return INDEX_MOL;
229         case POS_ALL:     return INDEX_ALL;
230         case POS_ALL_PBC: return INDEX_ALL;
231     }
232     return INDEX_UNKNOWN;
233 }
234
235 namespace gmx
236 {
237
238 // static
239 void
240 PositionCalculationCollection::typeFromEnum(const char *post,
241                                             e_poscalc_t *type, int *flags)
242 {
243     if (post[0] == 'a')
244     {
245         *type   = POS_ATOM;
246         *flags &= ~(POS_MASS | POS_COMPLMAX | POS_COMPLWHOLE);
247         return;
248     }
249
250     /* Process the prefix */
251     const char *ptr = post;
252     if (post[0] == 'w')
253     {
254         *flags &= ~POS_COMPLMAX;
255         *flags |= POS_COMPLWHOLE;
256         ptr = post + 6;
257     }
258     else if (post[0] == 'p')
259     {
260         *flags &= ~POS_COMPLWHOLE;
261         *flags |= POS_COMPLMAX;
262         ptr = post + 5;
263     }
264     else if (post[0] == 'd')
265     {
266         *flags &= ~(POS_COMPLMAX | POS_COMPLWHOLE);
267         ptr = post + 4;
268     }
269
270     if (ptr[0] == 'r')
271     {
272         *type = POS_RES;
273     }
274     else if (ptr[0] == 'm')
275     {
276         *type = POS_MOL;
277     }
278     else
279     {
280         GMX_THROW(InternalError("Unknown position calculation type"));
281     }
282     if (strlen(ptr) < 7)
283     {
284         GMX_THROW(InternalError("Unknown position calculation type"));
285     }
286     if (ptr[6] == 'm')
287     {
288         *flags |= POS_MASS;
289     }
290     else if (ptr[6] == 'g')
291     {
292         *flags &= ~POS_MASS;
293     }
294     else
295     {
296         GMX_THROW(InternalError("Unknown position calculation type"));
297     }
298 }
299
300 /********************************************************************
301  * PositionCalculationCollection::Impl
302  */
303
304 PositionCalculationCollection::Impl::Impl()
305     : top_(NULL), first_(NULL), last_(NULL), bInit_(false)
306 {
307 }
308
309 PositionCalculationCollection::Impl::~Impl()
310 {
311     // Loop backwards, because there can be internal references in that are
312     // correctly handled by this direction.
313     while (last_ != NULL)
314     {
315         GMX_ASSERT(last_->refcount == 1,
316                    "Dangling references to position calculations");
317         gmx_ana_poscalc_free(last_);
318     }
319 }
320
321 void
322 PositionCalculationCollection::Impl::insertCalculation(gmx_ana_poscalc_t *pc,
323                                                        gmx_ana_poscalc_t *before)
324 {
325     GMX_RELEASE_ASSERT(pc->coll == this, "Inconsistent collections");
326     if (before == NULL)
327     {
328         pc->next = NULL;
329         pc->prev = last_;
330         if (last_ != NULL)
331         {
332             last_->next = pc;
333         }
334         last_ = pc;
335     }
336     else
337     {
338         pc->prev     = before->prev;
339         pc->next     = before;
340         if (before->prev)
341         {
342             before->prev->next = pc;
343         }
344         before->prev = pc;
345     }
346     if (pc->prev == NULL)
347     {
348         first_ = pc;
349     }
350 }
351
352 void
353 PositionCalculationCollection::Impl::removeCalculation(gmx_ana_poscalc_t *pc)
354 {
355     GMX_RELEASE_ASSERT(pc->coll == this, "Inconsistent collections");
356     if (pc->prev != NULL)
357     {
358         pc->prev->next = pc->next;
359     }
360     else if (pc == first_)
361     {
362         first_ = pc->next;
363     }
364     if (pc->next != NULL)
365     {
366         pc->next->prev = pc->prev;
367     }
368     else if (pc == last_)
369     {
370         last_ = pc->prev;
371     }
372     pc->prev = pc->next = NULL;
373 }
374
375 gmx_ana_poscalc_t *
376 PositionCalculationCollection::Impl::createCalculation(e_poscalc_t type, int flags)
377 {
378     gmx_ana_poscalc_t *pc;
379
380     snew(pc, 1);
381     pc->type     = type;
382     pc->itype    = index_type_for_poscalc(type);
383     gmx_ana_poscalc_set_flags(pc, flags);
384     pc->refcount = 1;
385     pc->coll     = this;
386     insertCalculation(pc, NULL);
387     return pc;
388 }
389
390
391 /********************************************************************
392  * PositionCalculationCollection
393  */
394
395 PositionCalculationCollection::PositionCalculationCollection()
396     : impl_(new Impl)
397 {
398 }
399
400 PositionCalculationCollection::~PositionCalculationCollection()
401 {
402 }
403
404 void
405 PositionCalculationCollection::setTopology(t_topology *top)
406 {
407     impl_->top_ = top;
408 }
409
410 void
411 PositionCalculationCollection::printTree(FILE *fp) const
412 {
413     gmx_ana_poscalc_t *pc;
414     int                i, j;
415
416     fprintf(fp, "Position calculations:\n");
417     i  = 1;
418     pc = impl_->first_;
419     while (pc)
420     {
421         fprintf(fp, "%2d ", i);
422         switch (pc->type)
423         {
424             case POS_ATOM:    fprintf(fp, "ATOM");    break;
425             case POS_RES:     fprintf(fp, "RES");     break;
426             case POS_MOL:     fprintf(fp, "MOL");     break;
427             case POS_ALL:     fprintf(fp, "ALL");     break;
428             case POS_ALL_PBC: fprintf(fp, "ALL_PBC"); break;
429         }
430         if (pc->itype != index_type_for_poscalc(pc->type))
431         {
432             fprintf(fp, " (");
433             switch (pc->itype)
434             {
435                 case INDEX_UNKNOWN: fprintf(fp, "???");  break;
436                 case INDEX_ATOM:    fprintf(fp, "ATOM"); break;
437                 case INDEX_RES:     fprintf(fp, "RES");  break;
438                 case INDEX_MOL:     fprintf(fp, "MOL");  break;
439                 case INDEX_ALL:     fprintf(fp, "ALL");  break;
440             }
441             fprintf(fp, ")");
442         }
443         fprintf(fp, " flg=");
444         if (pc->flags & POS_MASS)
445         {
446             fprintf(fp, "M");
447         }
448         if (pc->flags & POS_DYNAMIC)
449         {
450             fprintf(fp, "D");
451         }
452         if (pc->flags & POS_MASKONLY)
453         {
454             fprintf(fp, "A");
455         }
456         if (pc->flags & POS_COMPLMAX)
457         {
458             fprintf(fp, "Cm");
459         }
460         if (pc->flags & POS_COMPLWHOLE)
461         {
462             fprintf(fp, "Cw");
463         }
464         if (!pc->flags)
465         {
466             fprintf(fp, "0");
467         }
468         fprintf(fp, " nr=%d nra=%d", pc->b.nr, pc->b.nra);
469         fprintf(fp, " refc=%d", pc->refcount);
470         fprintf(fp, "\n");
471         if (pc->gmax.nalloc_index > 0)
472         {
473             fprintf(fp, "   Group: ");
474             if (pc->gmax.isize > 20)
475             {
476                 fprintf(fp, " %d atoms", pc->gmax.isize);
477             }
478             else
479             {
480                 for (j = 0; j < pc->gmax.isize; ++j)
481                 {
482                     fprintf(fp, " %d", pc->gmax.index[j] + 1);
483                 }
484             }
485             fprintf(fp, "\n");
486         }
487         if (pc->b.nalloc_a > 0)
488         {
489             fprintf(fp, "   Atoms: ");
490             if (pc->b.nra > 20)
491             {
492                 fprintf(fp, " %d atoms", pc->b.nra);
493             }
494             else
495             {
496                 for (j = 0; j < pc->b.nra; ++j)
497                 {
498                     fprintf(fp, " %d", pc->b.a[j] + 1);
499                 }
500             }
501             fprintf(fp, "\n");
502         }
503         if (pc->b.nalloc_index > 0)
504         {
505             fprintf(fp, "   Blocks:");
506             if (pc->b.nr > 20)
507             {
508                 fprintf(fp, " %d pcs", pc->b.nr);
509             }
510             else
511             {
512                 for (j = 0; j <= pc->b.nr; ++j)
513                 {
514                     fprintf(fp, " %d", pc->b.index[j]);
515                 }
516             }
517             fprintf(fp, "\n");
518         }
519         if (pc->sbase)
520         {
521             gmx_ana_poscalc_t *base;
522
523             fprintf(fp, "   Base: ");
524             j = 1;
525             base = impl_->first_;
526             while (base && base != pc->sbase)
527             {
528                 ++j;
529                 base = base->next;
530             }
531             fprintf(fp, "%d", j);
532             if (pc->baseid && pc->b.nr <= 20)
533             {
534                 fprintf(fp, " id:");
535                 for (j = 0; j < pc->b.nr; ++j)
536                 {
537                     fprintf(fp, " %d", pc->baseid[j]+1);
538                 }
539             }
540             fprintf(fp, "\n");
541         }
542         ++i;
543         pc = pc->next;
544     }
545 }
546
547 gmx_ana_poscalc_t *
548 PositionCalculationCollection::createCalculation(e_poscalc_t type, int flags)
549 {
550     return impl_->createCalculation(type, flags);
551 }
552
553 gmx_ana_poscalc_t *
554 PositionCalculationCollection::createCalculationFromEnum(const char *post, int flags)
555 {
556     e_poscalc_t  type;
557     int cflags = flags;
558     typeFromEnum(post, &type, &cflags);
559     return impl_->createCalculation(type, cflags);
560 }
561
562 void PositionCalculationCollection::initEvaluation()
563 {
564     if (impl_->bInit_)
565     {
566         return;
567     }
568     gmx_ana_poscalc_t *pc = impl_->first_;
569     while (pc)
570     {
571         /* Initialize position storage for base calculations */
572         if (pc->p)
573         {
574             gmx_ana_poscalc_init_pos(pc, pc->p);
575         }
576         /* Construct the mapping of the base positions */
577         if (pc->sbase)
578         {
579             int                     bi, bj;
580
581             snew(pc->baseid, pc->b.nr);
582             for (bi = bj = 0; bi < pc->b.nr; ++bi, ++bj)
583             {
584                 while (pc->sbase->b.a[pc->sbase->b.index[bj]] != pc->b.a[pc->b.index[bi]])
585                 {
586                     ++bj;
587                 }
588                 pc->baseid[bi] = bj;
589             }
590         }
591         /* Free the block data for dynamic calculations */
592         if (pc->flags & POS_DYNAMIC)
593         {
594             if (pc->b.nalloc_index > 0)
595             {
596                 sfree(pc->b.index);
597                 pc->b.nalloc_index = 0;
598             }
599             if (pc->b.nalloc_a > 0)
600             {
601                 sfree(pc->b.a);
602                 pc->b.nalloc_a = 0;
603             }
604         }
605         pc = pc->next;
606     }
607     impl_->bInit_ = true;
608 }
609
610 void PositionCalculationCollection::initFrame()
611 {
612     if (!impl_->bInit_)
613     {
614         initEvaluation();
615     }
616     /* Clear the evaluation flags */
617     gmx_ana_poscalc_t *pc = impl_->first_;
618     while (pc)
619     {
620         pc->bEval = false;
621         pc = pc->next;
622     }
623 }
624
625 } // namespace gmx
626
627 /*! \brief
628  * Initializes position calculation using the maximum possible input index.
629  *
630  * \param[in,out] pc  Position calculation data structure.
631  * \param[in]     g   Maximum index group for the calculation.
632  * \param[in]     bBase Whether \p pc will be used as a base or not.
633  *
634  * \p bBase affects on how the \p pc->gmax field is initialized.
635  */
636 static void
637 set_poscalc_maxindex(gmx_ana_poscalc_t *pc, gmx_ana_index_t *g, bool bBase)
638 {
639     t_topology *top = pc->coll->top_;
640     gmx_ana_index_make_block(&pc->b, top, g, pc->itype, pc->flags & POS_COMPLWHOLE);
641     /* Set the type to POS_ATOM if the calculation in fact is such. */
642     if (pc->b.nr == pc->b.nra)
643     {
644         pc->type   = POS_ATOM; 
645         pc->flags &= ~(POS_MASS | POS_COMPLMAX | POS_COMPLWHOLE);
646     }
647     /* Set the POS_COMPLWHOLE flag if the calculation in fact always uses
648      * complete residues and molecules. */
649     if (!(pc->flags & POS_COMPLWHOLE)
650         && (!(pc->flags & POS_DYNAMIC) || (pc->flags & POS_COMPLMAX))
651         && (pc->type == POS_RES || pc->type == POS_MOL)
652         && gmx_ana_index_has_complete_elems(g, pc->itype, top))
653     {
654         pc->flags &= ~POS_COMPLMAX;
655         pc->flags |= POS_COMPLWHOLE;
656     }
657     /* Setup the gmax field */
658     if ((pc->flags & POS_COMPLWHOLE) && !bBase && pc->b.nra > g->isize)
659     {
660         gmx_ana_index_copy(&pc->gmax, g, true);
661         sfree(pc->gmax.name);
662         pc->gmax.name  = NULL;
663     }
664     else
665     {
666         gmx_ana_index_set(&pc->gmax, pc->b.nra, pc->b.a, NULL, 0);
667     }
668 }
669
670 /*! \brief
671  * Checks whether a position calculation should use a base at all.
672  *
673  * \param[in] pc   Position calculation data to check.
674  * \returns   true if \p pc can use a base and gets some benefit out of it,
675  *   false otherwise.
676  */
677 static bool
678 can_use_base(gmx_ana_poscalc_t *pc)
679 {
680     /* For atoms, it should be faster to do a simple copy, so don't use a
681      * base. */
682     if (pc->type == POS_ATOM)
683     {
684         return false;
685     }
686     /* For dynamic selections that do not use completion, it is not possible
687      * to use a base. */
688     if ((pc->type == POS_RES || pc->type == POS_MOL)
689         && (pc->flags & POS_DYNAMIC) && !(pc->flags & (POS_COMPLMAX | POS_COMPLWHOLE)))
690     {
691         return false;
692     }
693     /* Dynamic calculations for a single position cannot use a base. */
694     if ((pc->type == POS_ALL || pc->type == POS_ALL_PBC)
695         && (pc->flags & POS_DYNAMIC))
696     {
697         return false;
698     }
699     return true;
700 }
701
702 /*! \brief
703  * Checks whether two position calculations should use a common base.
704  *
705  * \param[in]     pc1 Calculation 1 to check for.
706  * \param[in]     pc2 Calculation 2 to check for.
707  * \param[in]     g1  Index group structure that contains the atoms from
708  *   \p pc1.
709  * \param[in,out] g   Working space, should have enough allocated memory to
710  *   contain the intersection of the atoms in \p pc1 and \p pc2.
711  * \returns   true if the two calculations should be merged to use a common
712  *   base, false otherwise.
713  */
714 static bool
715 should_merge(gmx_ana_poscalc_t *pc1, gmx_ana_poscalc_t *pc2,
716              gmx_ana_index_t *g1, gmx_ana_index_t *g)
717 {
718     gmx_ana_index_t  g2;
719
720     /* Do not merge calculations with different mass weighting. */
721     if ((pc1->flags & POS_MASS) != (pc2->flags & POS_MASS))
722     {
723         return false;
724     }
725     /* Avoid messing up complete calculations. */
726     if ((pc1->flags & POS_COMPLWHOLE) != (pc2->flags & POS_COMPLWHOLE))
727     {
728         return false;
729     }
730     /* Find the overlap between the calculations. */
731     gmx_ana_index_set(&g2, pc2->b.nra, pc2->b.a, NULL, 0);
732     gmx_ana_index_intersection(g, g1, &g2);
733     /* Do not merge if there is no overlap. */
734     if (g->isize == 0)
735     {
736         return false;
737     }
738     /* Full completion calculations always match if the type is correct. */
739     if ((pc1->flags & POS_COMPLWHOLE) && (pc2->flags & POS_COMPLWHOLE)
740         && pc1->type == pc2->type)
741     {
742         return true;
743     }
744     /* The calculations also match if the intersection consists of full
745      * blocks. */
746     if (gmx_ana_index_has_full_ablocks(g, &pc1->b)
747         && gmx_ana_index_has_full_ablocks(g, &pc2->b))
748     {
749         return true;
750     }
751     return false;
752 }
753
754 /*! \brief
755  * Creates a static base for position calculation.
756  *
757  * \param     pc  Data structure to copy.
758  * \returns   Pointer to a newly allocated base for \p pc.
759  *
760  * Creates and returns a deep copy of \p pc, but clears the
761  * \ref POS_DYNAMIC and \ref POS_MASKONLY flags.
762  * The newly created structure is set as the base (\c gmx_ana_poscalc_t::sbase)
763  * of \p pc and inserted in the collection before \p pc.
764  */
765 static gmx_ana_poscalc_t *
766 create_simple_base(gmx_ana_poscalc_t *pc)
767 {
768     gmx_ana_poscalc_t *base;
769     int                flags;
770
771     flags = pc->flags & ~(POS_DYNAMIC | POS_MASKONLY);
772     base = pc->coll->createCalculation(pc->type, flags);
773     set_poscalc_maxindex(base, &pc->gmax, true);
774
775     snew(base->p, 1);
776
777     pc->sbase = base;
778     pc->coll->removeCalculation(base);
779     pc->coll->insertCalculation(base, pc);
780
781     return base;
782 }
783
784 /*! \brief
785  * Merges a calculation into another calculation such that the new calculation
786  * can be used as a base.
787  *
788  * \param[in,out] base Base calculation to merge to.
789  * \param[in,out] pc   Position calculation to merge to \p base.
790  *
791  * After the call, \p base can be used as a base for \p pc (or any calculation
792  * that used it as a base).
793  * It is assumed that any overlap between \p base and \p pc is in complete
794  * blocks, i.e., that the merge is possible.
795  */
796 static void
797 merge_to_base(gmx_ana_poscalc_t *base, gmx_ana_poscalc_t *pc)
798 {
799     gmx_ana_index_t  gp, gb, g;
800     int              isize, bnr;
801     int              i, bi, bj, bo;
802
803     base->flags |= pc->flags & (POS_VELOCITIES | POS_FORCES);
804     gmx_ana_index_set(&gp, pc->b.nra, pc->b.a, NULL, 0);
805     gmx_ana_index_set(&gb, base->b.nra, base->b.a, NULL, 0);
806     isize = gmx_ana_index_difference_size(&gp, &gb);
807     if (isize > 0)
808     {
809         gmx_ana_index_clear(&g);
810         gmx_ana_index_reserve(&g, base->b.nra + isize);
811         /* Find the new blocks */
812         gmx_ana_index_difference(&g, &gp, &gb);
813         /* Count the blocks in g */
814         i = bi = bnr = 0;
815         while (i < g.isize)
816         {
817             while (pc->b.a[pc->b.index[bi]] != g.index[i])
818             {
819                 ++bi;
820             }
821             i += pc->b.index[bi+1] - pc->b.index[bi];
822             ++bnr;
823             ++bi;
824         }
825         /* Merge the atoms into a temporary structure */
826         gmx_ana_index_merge(&g, &gb, &g);
827         /* Merge the blocks */
828         srenew(base->b.index, base->b.nr + bnr + 1);
829         i  = g.isize - 1;
830         bi = base->b.nr - 1;
831         bj = pc->b.nr - 1;
832         bo = base->b.nr + bnr - 1;
833         base->b.index[bo+1] = i + 1;
834         while (bo >= 0)
835         {
836             if (bi < 0 || base->b.a[base->b.index[bi+1]-1] != g.index[i])
837             {
838                 i -= pc->b.index[bj+1] - pc->b.index[bj];
839                 --bj;
840             }
841             else
842             {
843                 if (bj >= 0 && pc->b.a[pc->b.index[bj+1]-1] == g.index[i])
844                 {
845                     --bj;
846                 }
847                 i -= base->b.index[bi+1] - base->b.index[bi];
848                 --bi;
849             }
850             base->b.index[bo] = i + 1;
851             --bo;
852         }
853         base->b.nr           += bnr;
854         base->b.nalloc_index += bnr;
855         sfree(base->b.a);
856         base->b.nra      = g.isize;
857         base->b.a        = g.index;
858         base->b.nalloc_a = g.isize;
859         /* Refresh the gmax field */
860         gmx_ana_index_set(&base->gmax, base->b.nra, base->b.a, NULL, 0);
861     }
862 }
863
864 /*! \brief
865  * Merges two bases into one.
866  *
867  * \param[in,out] tbase Base calculation to merge to.
868  * \param[in]     mbase Base calculation to merge to \p tbase.
869  *
870  * After the call, \p mbase has been freed and \p tbase is used as the base
871  * for all calculations that previously had \p mbase as their base.
872  * It is assumed that any overlap between \p tbase and \p mbase is in complete
873  * blocks, i.e., that the merge is possible.
874  */
875 static void
876 merge_bases(gmx_ana_poscalc_t *tbase, gmx_ana_poscalc_t *mbase)
877 {
878     gmx_ana_poscalc_t *pc;
879
880     merge_to_base(tbase, mbase);
881     mbase->coll->removeCalculation(mbase);
882     /* Set tbase as the base for all calculations that had mbase */
883     pc = tbase->coll->first_;
884     while (pc)
885     {
886         if (pc->sbase == mbase)
887         {
888             pc->sbase = tbase;
889             tbase->refcount++;
890         }
891         pc = pc->next;
892     }
893     /* Free mbase */
894     mbase->refcount = 0;
895     gmx_ana_poscalc_free(mbase);
896 }
897
898 /*! \brief
899  * Setups the static base calculation for a position calculation.
900  *
901  * \param[in,out] pc   Position calculation to setup the base for.
902  */
903 static void
904 setup_base(gmx_ana_poscalc_t *pc)
905 {
906     gmx_ana_poscalc_t *base, *pbase, *next;
907     gmx_ana_index_t    gp, g;
908
909     /* Exit immediately if pc should not have a base. */
910     if (!can_use_base(pc))
911     {
912         return;
913     }
914
915     gmx_ana_index_set(&gp, pc->b.nra, pc->b.a, NULL, 0);
916     gmx_ana_index_clear(&g);
917     gmx_ana_index_reserve(&g, pc->b.nra);
918     pbase = pc;
919     base = pc->coll->first_;
920     while (base)
921     {
922         /* Save the next calculation so that we can safely delete base */
923         next = base->next;
924         /* Skip pc, calculations that already have a base (we should match the
925          * base instead), as well as calculations that should not have a base.
926          * If the above conditions are met, check whether we should do a
927          * merge.
928          */
929         if (base != pc && !base->sbase && can_use_base(base)
930             && should_merge(pbase, base, &gp, &g))
931         {
932             /* Check whether this is the first base found */
933             if (pbase == pc)
934             {
935                 /* Create a real base if one is not present */
936                 if (!base->p)
937                 {
938                     pbase = create_simple_base(base);
939                 }
940                 else
941                 {
942                     pbase = base;
943                 }
944                 /* Make it a base for pc as well */
945                 merge_to_base(pbase, pc);
946                 pc->sbase = pbase;
947                 pbase->refcount++;
948             }
949             else /* This was not the first base */
950             {
951                 if (!base->p)
952                 {
953                     /* If it is not a real base, just make the new base as
954                      * the base for it as well. */
955                     merge_to_base(pbase, base);
956                     base->sbase = pbase;
957                     pbase->refcount++;
958                 }
959                 else
960                 {
961                     /* If base is a real base, merge it with the new base
962                      * and delete it. */
963                     merge_bases(pbase, base);
964                 }
965             }
966             gmx_ana_index_set(&gp, pbase->b.nra, pbase->b.a, NULL, 0);
967             gmx_ana_index_reserve(&g, pc->b.nra);
968         }
969         /* Proceed to the next unchecked calculation */
970         base = next;
971     }
972
973     gmx_ana_index_deinit(&g);
974
975     /* If no base was found, create one if one is required */
976     if (!pc->sbase && (pc->flags & POS_DYNAMIC)
977         && (pc->flags & (POS_COMPLMAX | POS_COMPLWHOLE)))
978     {
979         create_simple_base(pc);
980     }
981 }
982
983 /*!
984  * \param[in,out] pc    Position calculation data structure.
985  * \param[in]     flags New flags.
986  *
987  * \p flags are added to the old flags.
988  * If calculation type is \ref POS_ATOM, \ref POS_MASS is automatically
989  * cleared.
990  * If both \ref POS_DYNAMIC and \ref POS_MASKONLY are provided,
991  * \ref POS_DYNAMIC is cleared.
992  * If calculation type is not \ref POS_RES or \ref POS_MOL,
993  * \ref POS_COMPLMAX and \ref POS_COMPLWHOLE are automatically cleared.
994  */
995 void
996 gmx_ana_poscalc_set_flags(gmx_ana_poscalc_t *pc, int flags)
997 {
998     if (pc->type == POS_ATOM)
999     {
1000         flags &= ~POS_MASS;
1001     }
1002     if (flags & POS_MASKONLY)
1003     {
1004         flags &= ~POS_DYNAMIC;
1005     }
1006     if (pc->type != POS_RES && pc->type != POS_MOL)
1007     {
1008         flags &= ~(POS_COMPLMAX | POS_COMPLWHOLE);
1009     }
1010     pc->flags |= flags;
1011 }
1012
1013 /*!
1014  * \param[in,out] pc  Position calculation data structure.
1015  * \param[in]     g   Maximum index group for the calculation.
1016  *
1017  * Subsequent calls to gmx_ana_poscalc_update() should use only subsets of
1018  * \p g for evaluation.
1019  *
1020  * The topology should have been set for the collection of which \p pc is
1021  * a member.
1022  */
1023 void
1024 gmx_ana_poscalc_set_maxindex(gmx_ana_poscalc_t *pc, gmx_ana_index_t *g)
1025 {
1026     set_poscalc_maxindex(pc, g, false);
1027     setup_base(pc);
1028 }
1029
1030 /*!
1031  * \param[in]  pc  Position calculation data structure.
1032  * \param[out] p   Output positions.
1033  *
1034  * Calls to gmx_ana_poscalc_update() using \p pc should use only positions
1035  * initialized with this function.
1036  * The \c p->g pointer is initialized to point to an internal group that
1037  * contains the maximum index group set with gmx_ana_poscalc_set_maxindex().
1038  */
1039 void
1040 gmx_ana_poscalc_init_pos(gmx_ana_poscalc_t *pc, gmx_ana_pos_t *p)
1041 {
1042     gmx_ana_indexmap_init(&p->m, &pc->gmax, pc->coll->top_, pc->itype);
1043     /* Only do the static optimization when there is no completion */
1044     if (!(pc->flags & POS_DYNAMIC) && pc->b.nra == pc->gmax.isize)
1045     {
1046         gmx_ana_indexmap_set_static(&p->m, &pc->b);
1047     }
1048     gmx_ana_pos_reserve(p, p->m.nr, 0);
1049     if (pc->flags & POS_VELOCITIES)
1050     {
1051         gmx_ana_pos_reserve_velocities(p);
1052     }
1053     if (pc->flags & POS_FORCES)
1054     {
1055         gmx_ana_pos_reserve_forces(p);
1056     }
1057     gmx_ana_pos_set_nr(p, p->m.nr);
1058     gmx_ana_pos_set_evalgrp(p, &pc->gmax);
1059 }
1060
1061 /*!
1062  * \param  pc  Position calculation data to be freed.
1063  *
1064  * The \p pc pointer is invalid after the call.
1065  */
1066 void
1067 gmx_ana_poscalc_free(gmx_ana_poscalc_t *pc)
1068 {
1069     if (!pc)
1070     {
1071         return;
1072     }
1073
1074     pc->refcount--;
1075     if (pc->refcount > 0)
1076     {
1077         return;
1078     }
1079
1080     pc->coll->removeCalculation(pc);
1081     if (pc->b.nalloc_index > 0)
1082     {
1083         sfree(pc->b.index);
1084     }
1085     if (pc->b.nalloc_a > 0)
1086     {
1087         sfree(pc->b.a);
1088     }
1089     if (pc->flags & POS_COMPLWHOLE)
1090     {
1091         gmx_ana_index_deinit(&pc->gmax);
1092     }
1093     if (pc->p)
1094     {
1095         gmx_ana_pos_free(pc->p);
1096     }
1097     if (pc->sbase)
1098     {
1099         gmx_ana_poscalc_free(pc->sbase);
1100         sfree(pc->baseid);
1101     }
1102     sfree(pc);
1103 }
1104
1105 /*!
1106  * \param[in] pc  Position calculation data to query.
1107  * \returns   true if \p pc requires topology for initialization and/or
1108  *   evaluation, false otherwise.
1109  */
1110 bool
1111 gmx_ana_poscalc_requires_top(gmx_ana_poscalc_t *pc)
1112 {
1113     if ((pc->flags & POS_MASS) || pc->type == POS_RES || pc->type == POS_MOL)
1114     {
1115         return true;
1116     }
1117     return false;
1118 }
1119
1120 /*!
1121  * \param[in]     pc   Position calculation data.
1122  * \param[in,out] p    Output positions, initialized previously with
1123  *   gmx_ana_poscalc_init_pos() using \p pc.
1124  * \param[in]     g    Index group to use for the update.
1125  * \param[in]     fr   Current frame.
1126  * \param[in]     pbc  PBC data, or NULL if no PBC should be used.
1127  *
1128  * gmx_ana_poscalc_init_frame() should be called for each frame before calling
1129  * this function.
1130  */
1131 void
1132 gmx_ana_poscalc_update(gmx_ana_poscalc_t *pc, gmx_ana_pos_t *p,
1133                        gmx_ana_index_t *g, t_trxframe *fr, t_pbc *pbc)
1134 {
1135     int  i, bi, bj;
1136     
1137     if (pc->bEval == true && !(pc->flags & POS_MASKONLY))
1138     {
1139         return;
1140     }
1141     if (pc->sbase)
1142     {
1143         gmx_ana_poscalc_update(pc->sbase, NULL, NULL, fr, pbc);
1144     }
1145     if (!p)
1146     {
1147         p = pc->p;
1148     }
1149     if (!g)
1150     {
1151         g = &pc->gmax;
1152     }
1153     gmx_ana_pos_set_evalgrp(p, g);
1154
1155     /* Update the index map */
1156     if (pc->flags & POS_DYNAMIC)
1157     {
1158         gmx_ana_indexmap_update(&p->m, g, false);
1159         p->nr = p->m.nr;
1160     }
1161     else if (pc->flags & POS_MASKONLY)
1162     {
1163         gmx_ana_indexmap_update(&p->m, g, true);
1164         if (pc->bEval)
1165             return;
1166     }
1167     if (!(pc->flags & POS_DYNAMIC))
1168     {
1169         pc->bEval = true;
1170     }
1171
1172     /* Evaluate the positions */
1173     if (pc->sbase)
1174     {
1175         /* TODO: It might be faster to evaluate the positions within this
1176          * loop instead of in the beginning. */
1177         if (pc->flags & POS_DYNAMIC)
1178         {
1179             for (bi = 0; bi < p->nr; ++bi)
1180             {
1181                 bj = pc->baseid[p->m.refid[bi]];
1182                 copy_rvec(pc->sbase->p->x[bj], p->x[bi]);
1183             }
1184             if (p->v)
1185             {
1186                 for (bi = 0; bi < p->nr; ++bi)
1187                 {
1188                     bj = pc->baseid[p->m.refid[bi]];
1189                     copy_rvec(pc->sbase->p->v[bj], p->v[bi]);
1190                 }
1191             }
1192             if (p->f)
1193             {
1194                 for (bi = 0; bi < p->nr; ++bi)
1195                 {
1196                     bj = pc->baseid[p->m.refid[bi]];
1197                     copy_rvec(pc->sbase->p->f[bj], p->f[bi]);
1198                 }
1199             }
1200         }
1201         else
1202         {
1203             for (bi = 0; bi < p->nr; ++bi)
1204             {
1205                 bj = pc->baseid[bi];
1206                 copy_rvec(pc->sbase->p->x[bj], p->x[bi]);
1207             }
1208             if (p->v)
1209             {
1210                 for (bi = 0; bi < p->nr; ++bi)
1211                 {
1212                     bj = pc->baseid[bi];
1213                     copy_rvec(pc->sbase->p->v[bj], p->v[bi]);
1214                 }
1215             }
1216             if (p->f)
1217             {
1218                 for (bi = 0; bi < p->nr; ++bi)
1219                 {
1220                     bj = pc->baseid[bi];
1221                     copy_rvec(pc->sbase->p->f[bj], p->f[bi]);
1222                 }
1223             }
1224         }
1225     }
1226     else /* pc->sbase is NULL */
1227     {
1228         if (pc->flags & POS_DYNAMIC)
1229         {
1230             pc->b.nr    = p->m.mapb.nr;
1231             pc->b.index = p->m.mapb.index;
1232             pc->b.nra   = g->isize;
1233             pc->b.a     = g->index;
1234         }
1235         if (p->v && !fr->bV)
1236         {
1237             for (i = 0; i < pc->b.nra; ++i)
1238             {
1239                 clear_rvec(p->v[i]);
1240             }
1241         }
1242         if (p->f && !fr->bF)
1243         {
1244             for (i = 0; i < pc->b.nra; ++i)
1245             {
1246                 clear_rvec(p->f[i]);
1247             }
1248         }
1249         /* Here, we assume that the topology has been properly initialized,
1250          * and do not check the return values of gmx_calc_comg*(). */
1251         t_topology *top = pc->coll->top_;
1252         bool bMass = pc->flags & POS_MASS;
1253         switch (pc->type)
1254         {
1255         case POS_ATOM:
1256             for (i = 0; i < pc->b.nra; ++i)
1257             {
1258                 copy_rvec(fr->x[pc->b.a[i]], p->x[i]);
1259             }
1260             if (p->v && fr->bV)
1261             {
1262                 for (i = 0; i < pc->b.nra; ++i)
1263                 {
1264                     copy_rvec(fr->v[pc->b.a[i]], p->v[i]);
1265                 }
1266             }
1267             if (p->f && fr->bF)
1268             {
1269                 for (i = 0; i < pc->b.nra; ++i)
1270                 {
1271                     copy_rvec(fr->f[pc->b.a[i]], p->f[i]);
1272                 }
1273             }
1274             break;
1275         case POS_ALL:
1276             gmx_calc_comg(top, fr->x, pc->b.nra, pc->b.a, bMass, p->x[0]);
1277             if (p->v && fr->bV)
1278             {
1279                 gmx_calc_comg(top, fr->v, pc->b.nra, pc->b.a, bMass, p->v[0]);
1280             }
1281             if (p->f && fr->bF)
1282             {
1283                 gmx_calc_comg_f(top, fr->f, pc->b.nra, pc->b.a, bMass, p->f[0]);
1284             }
1285             break;
1286         case POS_ALL_PBC:
1287             gmx_calc_comg_pbc(top, fr->x, pbc, pc->b.nra, pc->b.a, bMass, p->x[0]);
1288             if (p->v && fr->bV)
1289             {
1290                 gmx_calc_comg(top, fr->v, pc->b.nra, pc->b.a, bMass, p->v[0]);
1291             }
1292             if (p->f && fr->bF)
1293             {
1294                 gmx_calc_comg_f(top, fr->f, pc->b.nra, pc->b.a, bMass, p->f[0]);
1295             }
1296             break;
1297         default:
1298             gmx_calc_comg_blocka(top, fr->x, &pc->b, bMass, p->x);
1299             if (p->v && fr->bV)
1300             {
1301                 gmx_calc_comg_blocka(top, fr->v, &pc->b, bMass, p->v);
1302             }
1303             if (p->f && fr->bF)
1304             {
1305                 gmx_calc_comg_blocka(top, fr->f, &pc->b, bMass, p->f);
1306             }
1307             break;
1308         }
1309     }
1310 }