Avoid crash with empty reference for 'same as' selection
[alexxy/gromacs.git] / src / gromacs / selection / tests / selectioncollection.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2010,2011,2012,2013,2014,2015, 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 /*! \internal \file
36  * \brief
37  * Tests selection parsing and compilation.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_selection
41  */
42 #include <gtest/gtest.h>
43
44 #include "gromacs/options/basicoptions.h"
45 #include "gromacs/options/options.h"
46 #include "gromacs/selection/indexutil.h"
47 #include "gromacs/selection/selectioncollection.h"
48 #include "gromacs/selection/selection.h"
49 #include "gromacs/utility/arrayref.h"
50 #include "gromacs/utility/exceptions.h"
51 #include "gromacs/utility/flags.h"
52 #include "gromacs/utility/gmxregex.h"
53 #include "gromacs/utility/stringutil.h"
54
55 #include "testutils/refdata.h"
56 #include "testutils/testasserts.h"
57 #include "testutils/testfilemanager.h"
58 #include "testutils/testoptions.h"
59
60 #include "toputils.h"
61
62 namespace
63 {
64
65 /********************************************************************
66  * Test fixture for selection testing
67  */
68
69 class SelectionCollectionTest : public ::testing::Test
70 {
71     public:
72         static int               s_debugLevel;
73
74         SelectionCollectionTest();
75         ~SelectionCollectionTest();
76
77         void setAtomCount(int natoms)
78         {
79             ASSERT_NO_THROW_GMX(sc_.setTopology(NULL, natoms));
80         }
81         void loadTopology(const char *filename);
82         void setTopology();
83         void loadIndexGroups(const char *filename);
84
85         gmx::test::TopologyManager  topManager_;
86         gmx::SelectionCollection    sc_;
87         gmx::SelectionList          sel_;
88         t_topology                 *top_;
89         t_trxframe                 *frame_;
90         gmx_ana_indexgrps_t        *grps_;
91 };
92
93 int SelectionCollectionTest::s_debugLevel = 0;
94
95 // \cond/\endcond do not seem to work here with Doxygen 1.8.5 parser.
96 #ifndef DOXYGEN
97 GMX_TEST_OPTIONS(SelectionCollectionTestOptions, options)
98 {
99     options->addOption(gmx::IntegerOption("seldebug")
100                            .store(&SelectionCollectionTest::s_debugLevel)
101                            .description("Set selection debug level"));
102 }
103 #endif
104
105 SelectionCollectionTest::SelectionCollectionTest()
106     : top_(NULL), frame_(NULL), grps_(NULL)
107 {
108     topManager_.requestFrame();
109     sc_.setDebugLevel(s_debugLevel);
110     sc_.setReferencePosType("atom");
111     sc_.setOutputPosType("atom");
112 }
113
114 SelectionCollectionTest::~SelectionCollectionTest()
115 {
116     if (grps_ != NULL)
117     {
118         gmx_ana_indexgrps_free(grps_);
119     }
120 }
121
122 void
123 SelectionCollectionTest::loadTopology(const char *filename)
124 {
125     topManager_.loadTopology(filename);
126     setTopology();
127 }
128
129 void
130 SelectionCollectionTest::setTopology()
131 {
132     top_   = topManager_.topology();
133     frame_ = topManager_.frame();
134
135     ASSERT_NO_THROW_GMX(sc_.setTopology(top_, -1));
136 }
137
138 void
139 SelectionCollectionTest::loadIndexGroups(const char *filename)
140 {
141     GMX_RELEASE_ASSERT(grps_ == NULL,
142                        "External groups can only be loaded once");
143     std::string fullpath =
144         gmx::test::TestFileManager::getInputFilePath(filename);
145     gmx_ana_indexgrps_init(&grps_, NULL, fullpath.c_str());
146     sc_.setIndexGroups(grps_);
147 }
148
149
150 /********************************************************************
151  * Test fixture for selection testing with reference data
152  */
153
154 class SelectionCollectionDataTest : public SelectionCollectionTest
155 {
156     public:
157         enum TestFlag
158         {
159             efTestEvaluation            = 1<<0,
160             efTestPositionAtoms         = 1<<1,
161             efTestPositionCoordinates   = 1<<2,
162             efTestPositionMapping       = 1<<3,
163             efTestPositionMasses        = 1<<4,
164             efTestPositionCharges       = 1<<5,
165             efTestSelectionNames        = 1<<6,
166             efDontTestCompiledAtoms     = 1<<8
167         };
168         typedef gmx::FlagsTemplate<TestFlag> TestFlags;
169
170         SelectionCollectionDataTest()
171             : checker_(data_.rootChecker()), count_(0), framenr_(0)
172         {
173         }
174
175         void setFlags(TestFlags flags) { flags_ = flags; }
176
177         void runParser(const gmx::ConstArrayRef<const char *> &selections);
178         void runCompiler();
179         void runEvaluate();
180         void runEvaluateFinal();
181
182         void runTest(int                                     natoms,
183                      const gmx::ConstArrayRef<const char *> &selections);
184         void runTest(const char                             *filename,
185                      const gmx::ConstArrayRef<const char *> &selections);
186
187     private:
188         static void checkSelection(gmx::test::TestReferenceChecker *checker,
189                                    const gmx::Selection &sel, TestFlags flags);
190
191         void checkCompiled();
192
193         gmx::test::TestReferenceData    data_;
194         gmx::test::TestReferenceChecker checker_;
195         size_t                          count_;
196         int                             framenr_;
197         TestFlags                       flags_;
198 };
199
200
201 void
202 SelectionCollectionDataTest::checkSelection(
203         gmx::test::TestReferenceChecker *checker,
204         const gmx::Selection &sel, TestFlags flags)
205 {
206     using gmx::test::TestReferenceChecker;
207
208     {
209         gmx::ConstArrayRef<int> atoms = sel.atomIndices();
210         checker->checkSequence(atoms.begin(), atoms.end(), "Atoms");
211     }
212     if (flags.test(efTestPositionAtoms)
213         || flags.test(efTestPositionCoordinates)
214         || flags.test(efTestPositionMapping)
215         || flags.test(efTestPositionMasses)
216         || flags.test(efTestPositionCharges))
217     {
218         TestReferenceChecker compound(
219                 checker->checkSequenceCompound("Positions", sel.posCount()));
220         for (int i = 0; i < sel.posCount(); ++i)
221         {
222             TestReferenceChecker          poscompound(compound.checkCompound("Position", NULL));
223             const gmx::SelectionPosition &p = sel.position(i);
224             if (flags.test(efTestPositionAtoms))
225             {
226                 gmx::ConstArrayRef<int> atoms = p.atomIndices();
227                 poscompound.checkSequence(atoms.begin(), atoms.end(), "Atoms");
228             }
229             if (flags.test(efTestPositionCoordinates))
230             {
231                 poscompound.checkVector(p.x(), "Coordinates");
232             }
233             if (flags.test(efTestPositionMapping))
234             {
235                 poscompound.checkInteger(p.refId(), "RefId");
236                 poscompound.checkInteger(p.mappedId(), "MappedId");
237             }
238             if (flags.test(efTestPositionMasses))
239             {
240                 poscompound.checkReal(p.mass(), "Mass");
241             }
242             if (flags.test(efTestPositionCharges))
243             {
244                 poscompound.checkReal(p.charge(), "Charge");
245             }
246         }
247     }
248 }
249
250
251 void
252 SelectionCollectionDataTest::runParser(
253         const gmx::ConstArrayRef<const char *> &selections)
254 {
255     using gmx::test::TestReferenceChecker;
256
257     TestReferenceChecker compound(checker_.checkCompound("ParsedSelections", "Parsed"));
258     size_t               varcount = 0;
259     count_ = 0;
260     for (size_t i = 0; i < selections.size(); ++i)
261     {
262         SCOPED_TRACE(std::string("Parsing selection \"")
263                      + selections[i] + "\"");
264         gmx::SelectionList result;
265         ASSERT_NO_THROW_GMX(result = sc_.parseFromString(selections[i]));
266         sel_.insert(sel_.end(), result.begin(), result.end());
267         if (sel_.size() == count_)
268         {
269             std::string          id = gmx::formatString("Variable%d", static_cast<int>(varcount + 1));
270             TestReferenceChecker varcompound(
271                     compound.checkCompound("ParsedVariable", id.c_str()));
272             varcompound.checkString(selections[i], "Input");
273             ++varcount;
274         }
275         else
276         {
277             std::string          id = gmx::formatString("Selection%d", static_cast<int>(count_ + 1));
278             TestReferenceChecker selcompound(
279                     compound.checkCompound("ParsedSelection", id.c_str()));
280             selcompound.checkString(selections[i], "Input");
281             if (flags_.test(efTestSelectionNames))
282             {
283                 selcompound.checkString(sel_[count_].name(), "Name");
284             }
285             selcompound.checkString(sel_[count_].selectionText(), "Text");
286             selcompound.checkBoolean(sel_[count_].isDynamic(), "Dynamic");
287             ++count_;
288         }
289     }
290 }
291
292
293 void
294 SelectionCollectionDataTest::runCompiler()
295 {
296     ASSERT_NO_THROW_GMX(sc_.compile());
297     ASSERT_EQ(count_, sel_.size());
298     checkCompiled();
299 }
300
301
302 void
303 SelectionCollectionDataTest::checkCompiled()
304 {
305     using gmx::test::TestReferenceChecker;
306     const TestFlags      mask = ~TestFlags(efTestPositionCoordinates);
307
308     TestReferenceChecker compound(checker_.checkCompound("CompiledSelections", "Compiled"));
309     for (size_t i = 0; i < count_; ++i)
310     {
311         SCOPED_TRACE(std::string("Checking selection \"") +
312                      sel_[i].selectionText() + "\"");
313         std::string          id = gmx::formatString("Selection%d", static_cast<int>(i + 1));
314         TestReferenceChecker selcompound(
315                 compound.checkCompound("Selection", id.c_str()));
316         if (flags_.test(efTestSelectionNames))
317         {
318             selcompound.checkString(sel_[i].name(), "Name");
319         }
320         if (!flags_.test(efDontTestCompiledAtoms))
321         {
322             checkSelection(&selcompound, sel_[i], flags_ & mask);
323         }
324     }
325 }
326
327
328 void
329 SelectionCollectionDataTest::runEvaluate()
330 {
331     using gmx::test::TestReferenceChecker;
332
333     ++framenr_;
334     ASSERT_NO_THROW_GMX(sc_.evaluate(frame_, NULL));
335     std::string          frame = gmx::formatString("Frame%d", framenr_);
336     TestReferenceChecker compound(
337             checker_.checkCompound("EvaluatedSelections", frame.c_str()));
338     for (size_t i = 0; i < count_; ++i)
339     {
340         SCOPED_TRACE(std::string("Checking selection \"") +
341                      sel_[i].selectionText() + "\"");
342         std::string          id = gmx::formatString("Selection%d", static_cast<int>(i + 1));
343         TestReferenceChecker selcompound(
344                 compound.checkCompound("Selection", id.c_str()));
345         checkSelection(&selcompound, sel_[i], flags_);
346     }
347 }
348
349
350 void
351 SelectionCollectionDataTest::runEvaluateFinal()
352 {
353     ASSERT_NO_THROW_GMX(sc_.evaluateFinal(framenr_));
354     checkCompiled();
355 }
356
357
358 void
359 SelectionCollectionDataTest::runTest(
360         int natoms, const gmx::ConstArrayRef<const char *> &selections)
361 {
362     ASSERT_NO_FATAL_FAILURE(runParser(selections));
363     ASSERT_NO_FATAL_FAILURE(setAtomCount(natoms));
364     ASSERT_NO_FATAL_FAILURE(runCompiler());
365 }
366
367
368 void
369 SelectionCollectionDataTest::runTest(
370         const char *filename, const gmx::ConstArrayRef<const char *> &selections)
371 {
372     ASSERT_NO_FATAL_FAILURE(runParser(selections));
373     ASSERT_NO_FATAL_FAILURE(loadTopology(filename));
374     ASSERT_NO_FATAL_FAILURE(runCompiler());
375     if (flags_.test(efTestEvaluation))
376     {
377         ASSERT_NO_FATAL_FAILURE(runEvaluate());
378         ASSERT_NO_FATAL_FAILURE(runEvaluateFinal());
379     }
380 }
381
382
383 /********************************************************************
384  * Tests for SelectionCollection functionality without reference data
385  */
386
387 TEST_F(SelectionCollectionTest, HandlesNoSelections)
388 {
389     EXPECT_FALSE(sc_.requiresTopology());
390     EXPECT_NO_THROW_GMX(sc_.compile());
391 }
392
393 TEST_F(SelectionCollectionTest, HandlesVelocityAndForceRequests)
394 {
395     ASSERT_NO_THROW_GMX(sel_ = sc_.parseFromString("atomnr 1 to 10; none"));
396     ASSERT_NO_FATAL_FAILURE(setAtomCount(10));
397     ASSERT_EQ(2U, sel_.size());
398     ASSERT_NO_THROW_GMX(sel_[0].setEvaluateVelocities(true));
399     ASSERT_NO_THROW_GMX(sel_[1].setEvaluateVelocities(true));
400     ASSERT_NO_THROW_GMX(sel_[0].setEvaluateForces(true));
401     ASSERT_NO_THROW_GMX(sel_[1].setEvaluateForces(true));
402     ASSERT_NO_THROW_GMX(sc_.compile());
403     EXPECT_TRUE(sel_[0].hasVelocities());
404     EXPECT_TRUE(sel_[1].hasVelocities());
405     EXPECT_TRUE(sel_[0].hasForces());
406     EXPECT_TRUE(sel_[1].hasForces());
407 }
408
409 TEST_F(SelectionCollectionTest, ParsesSelectionsFromFile)
410 {
411     ASSERT_NO_THROW_GMX(sel_ = sc_.parseFromFile(
412                                     gmx::test::TestFileManager::getInputFilePath("selfile.dat")));
413     // These should match the contents of selfile.dat
414     ASSERT_EQ(2U, sel_.size());
415     EXPECT_STREQ("resname RA RB", sel_[0].selectionText());
416     EXPECT_STREQ("resname RB RC", sel_[1].selectionText());
417 }
418
419 TEST_F(SelectionCollectionTest, HandlesAtypicalWhitespace)
420 {
421     ASSERT_NO_THROW_GMX(sel_ = sc_.parseFromString("atomnr\n1\r\nto\t10;\vatomnr 3\f to 14\r"));
422     ASSERT_EQ(2U, sel_.size());
423     EXPECT_STREQ("atomnr 1 to 10", sel_[0].selectionText());
424     // TODO: Get rid of the trailing whitespace.
425     EXPECT_STREQ("atomnr 3 to 14 ", sel_[1].selectionText());
426 }
427
428 TEST_F(SelectionCollectionTest, HandlesInvalidRegularExpressions)
429 {
430     ASSERT_NO_FATAL_FAILURE(loadTopology("simple.gro"));
431     EXPECT_THROW_GMX({
432                          sc_.parseFromString("resname ~ \"R[A\"");
433                          sc_.compile();
434                      }, gmx::InvalidInputError);
435 }
436
437 TEST_F(SelectionCollectionTest, HandlesUnsupportedRegularExpressions)
438 {
439     if (!gmx::Regex::isSupported())
440     {
441         ASSERT_NO_FATAL_FAILURE(loadTopology("simple.gro"));
442         EXPECT_THROW_GMX({
443                              sc_.parseFromString("resname \"R[AD]\"");
444                              sc_.compile();
445                          }, gmx::InvalidInputError);
446     }
447 }
448
449 TEST_F(SelectionCollectionTest, HandlesMissingMethodParamValue)
450 {
451     EXPECT_THROW_GMX(sc_.parseFromString("mindist from atomnr 1 cutoff"),
452                      gmx::InvalidInputError);
453 }
454
455 TEST_F(SelectionCollectionTest, HandlesMissingMethodParamValue2)
456 {
457     EXPECT_THROW_GMX(sc_.parseFromString("within 1 of"),
458                      gmx::InvalidInputError);
459 }
460
461 TEST_F(SelectionCollectionTest, HandlesMissingMethodParamValue3)
462 {
463     EXPECT_THROW_GMX(sc_.parseFromString("within of atomnr 1"),
464                      gmx::InvalidInputError);
465 }
466
467 // TODO: Tests for more parser errors
468
469 TEST_F(SelectionCollectionTest, HandlesUnknownGroupReferenceParser1)
470 {
471     ASSERT_NO_THROW_GMX(sc_.setIndexGroups(NULL));
472     EXPECT_THROW_GMX(sc_.parseFromString("group \"foo\""), gmx::InconsistentInputError);
473     EXPECT_THROW_GMX(sc_.parseFromString("4"), gmx::InconsistentInputError);
474 }
475
476 TEST_F(SelectionCollectionTest, HandlesUnknownGroupReferenceParser2)
477 {
478     ASSERT_NO_THROW_GMX(loadIndexGroups("simple.ndx"));
479     EXPECT_THROW_GMX(sc_.parseFromString("group \"foo\""), gmx::InconsistentInputError);
480     EXPECT_THROW_GMX(sc_.parseFromString("4"), gmx::InconsistentInputError);
481 }
482
483 TEST_F(SelectionCollectionTest, HandlesUnknownGroupReferenceDelayed1)
484 {
485     ASSERT_NO_THROW_GMX(sc_.parseFromString("group \"foo\""));
486     ASSERT_NO_FATAL_FAILURE(setAtomCount(10));
487     EXPECT_THROW_GMX(sc_.setIndexGroups(NULL), gmx::InconsistentInputError);
488     EXPECT_THROW_GMX(sc_.compile(), gmx::APIError);
489 }
490
491 TEST_F(SelectionCollectionTest, HandlesUnknownGroupReferenceDelayed2)
492 {
493     ASSERT_NO_THROW_GMX(sc_.parseFromString("group 4; group \"foo\""));
494     ASSERT_NO_FATAL_FAILURE(setAtomCount(10));
495     EXPECT_THROW_GMX(loadIndexGroups("simple.ndx"), gmx::InconsistentInputError);
496     EXPECT_THROW_GMX(sc_.compile(), gmx::APIError);
497 }
498
499 TEST_F(SelectionCollectionTest, HandlesUnsortedGroupReference)
500 {
501     ASSERT_NO_THROW_GMX(loadIndexGroups("simple.ndx"));
502     EXPECT_THROW_GMX(sc_.parseFromString("atomnr 1 to 3 and group \"GrpUnsorted\""),
503                      gmx::InconsistentInputError);
504     EXPECT_THROW_GMX(sc_.parseFromString("group 2 or atomnr 2 to 5"),
505                      gmx::InconsistentInputError);
506     EXPECT_THROW_GMX(sc_.parseFromString("within 1 of group 2"),
507                      gmx::InconsistentInputError);
508 }
509
510 TEST_F(SelectionCollectionTest, HandlesUnsortedGroupReferenceDelayed)
511 {
512     ASSERT_NO_THROW_GMX(sc_.parseFromString("atomnr 1 to 3 and group \"GrpUnsorted\""));
513     ASSERT_NO_THROW_GMX(sc_.parseFromString("atomnr 1 to 3 and group 2"));
514     EXPECT_THROW_GMX(loadIndexGroups("simple.ndx"), gmx::InconsistentInputError);
515     // TODO: Add a separate check in the selection compiler for a safer API
516     // (makes sense in the future if the compiler needs the information for
517     // other purposes as well).
518     // EXPECT_THROW_GMX(sc_.compile(), gmx::APIError);
519 }
520
521 TEST_F(SelectionCollectionTest, RecoversFromMissingMoleculeInfo)
522 {
523     ASSERT_NO_THROW_GMX(sc_.parseFromString("molindex 1 to 5"));
524     ASSERT_NO_FATAL_FAILURE(loadTopology("simple.gro"));
525     EXPECT_THROW_GMX(sc_.compile(), gmx::InconsistentInputError);
526 }
527
528 TEST_F(SelectionCollectionTest, RecoversFromMissingAtomTypes)
529 {
530     ASSERT_NO_THROW_GMX(sc_.parseFromString("type CA"));
531     ASSERT_NO_FATAL_FAILURE(loadTopology("simple.gro"));
532     EXPECT_THROW_GMX(sc_.compile(), gmx::InconsistentInputError);
533 }
534
535 TEST_F(SelectionCollectionTest, RecoversFromMissingPDBInfo)
536 {
537     ASSERT_NO_THROW_GMX(sc_.parseFromString("altloc A"));
538     ASSERT_NO_FATAL_FAILURE(loadTopology("simple.gro"));
539     EXPECT_THROW_GMX(sc_.compile(), gmx::InconsistentInputError);
540 }
541
542 TEST_F(SelectionCollectionTest, RecoversFromInvalidPermutation)
543 {
544     ASSERT_NO_THROW_GMX(sc_.parseFromString("all permute 1 1"));
545     ASSERT_NO_FATAL_FAILURE(setAtomCount(10));
546     EXPECT_THROW_GMX(sc_.compile(), gmx::InvalidInputError);
547 }
548
549 TEST_F(SelectionCollectionTest, RecoversFromInvalidPermutation2)
550 {
551     ASSERT_NO_THROW_GMX(sc_.parseFromString("all permute 3 2 1"));
552     ASSERT_NO_FATAL_FAILURE(setAtomCount(10));
553     EXPECT_THROW_GMX(sc_.compile(), gmx::InconsistentInputError);
554 }
555
556 TEST_F(SelectionCollectionTest, RecoversFromInvalidPermutation3)
557 {
558     ASSERT_NO_THROW_GMX(sc_.parseFromString("x < 1.5 permute 3 2 1"));
559     ASSERT_NO_FATAL_FAILURE(loadTopology("simple.gro"));
560     ASSERT_NO_THROW_GMX(sc_.compile());
561     EXPECT_THROW_GMX(sc_.evaluate(frame_, NULL), gmx::InconsistentInputError);
562 }
563
564 // TODO: Tests for evaluation errors
565
566
567 /********************************************************************
568  * Tests for selection keywords
569  */
570
571 TEST_F(SelectionCollectionDataTest, HandlesAllNone)
572 {
573     static const char * const selections[] = {
574         "all",
575         "none"
576     };
577     runTest(10, selections);
578 }
579
580 TEST_F(SelectionCollectionDataTest, HandlesAtomnr)
581 {
582     static const char * const selections[] = {
583         "atomnr 1 to 3 6 to 8",
584         "atomnr 4 2 5 to 7",
585         "atomnr <= 5"
586     };
587     runTest(10, selections);
588 }
589
590 TEST_F(SelectionCollectionDataTest, HandlesResnr)
591 {
592     static const char * const selections[] = {
593         "resnr 1 2 5",
594         "resid 4 to 3"
595     };
596     runTest("simple.gro", selections);
597 }
598
599 TEST_F(SelectionCollectionDataTest, HandlesResIndex)
600 {
601     static const char * const selections[] = {
602         "resindex 1 4",
603         "residue 1 3"
604     };
605     runTest("simple.pdb", selections);
606 }
607
608 TEST_F(SelectionCollectionDataTest, HandlesMolIndex)
609 {
610     static const char * const selections[] = {
611         "molindex 1 4",
612         "molecule 2 3 5"
613     };
614     ASSERT_NO_FATAL_FAILURE(runParser(selections));
615     ASSERT_NO_FATAL_FAILURE(loadTopology("simple.gro"));
616     topManager_.initUniformMolecules(3);
617     ASSERT_NO_FATAL_FAILURE(runCompiler());
618 }
619
620 TEST_F(SelectionCollectionDataTest, HandlesAtomname)
621 {
622     static const char * const selections[] = {
623         "name CB",
624         "atomname S1 S2"
625     };
626     runTest("simple.gro", selections);
627 }
628
629 TEST_F(SelectionCollectionDataTest, HandlesPdbAtomname)
630 {
631     static const char * const selections[] = {
632         "name HG21",
633         "name 1HG2",
634         "pdbname HG21 CB",
635         "pdbatomname 1HG2"
636     };
637     runTest("simple.pdb", selections);
638 }
639
640
641 TEST_F(SelectionCollectionDataTest, HandlesAtomtype)
642 {
643     static const char * const selections[] = {
644         "atomtype CA"
645     };
646     ASSERT_NO_FATAL_FAILURE(runParser(selections));
647     ASSERT_NO_FATAL_FAILURE(loadTopology("simple.gro"));
648     const char *const types[] = { "CA", "SA", "SB" };
649     topManager_.initAtomTypes(types);
650     ASSERT_NO_FATAL_FAILURE(runCompiler());
651 }
652
653 TEST_F(SelectionCollectionDataTest, HandlesChain)
654 {
655     static const char * const selections[] = {
656         "chain A",
657         "chain B"
658     };
659     runTest("simple.pdb", selections);
660 }
661
662 TEST_F(SelectionCollectionDataTest, HandlesMass)
663 {
664     static const char * const selections[] = {
665         "mass > 5"
666     };
667     ASSERT_NO_FATAL_FAILURE(runParser(selections));
668     ASSERT_NO_FATAL_FAILURE(loadTopology("simple.gro"));
669     for (int i = 0; i < top_->atoms.nr; ++i)
670     {
671         top_->atoms.atom[i].m = 1.0 + i;
672     }
673     ASSERT_NO_FATAL_FAILURE(runCompiler());
674 }
675
676 TEST_F(SelectionCollectionDataTest, HandlesCharge)
677 {
678     static const char * const selections[] = {
679         "charge < 0.5"
680     };
681     ASSERT_NO_FATAL_FAILURE(runParser(selections));
682     ASSERT_NO_FATAL_FAILURE(loadTopology("simple.gro"));
683     for (int i = 0; i < top_->atoms.nr; ++i)
684     {
685         top_->atoms.atom[i].q = i / 10.0;
686     }
687     ASSERT_NO_FATAL_FAILURE(runCompiler());
688 }
689
690 TEST_F(SelectionCollectionDataTest, HandlesAltLoc)
691 {
692     static const char * const selections[] = {
693         "altloc \" \"",
694         "altloc A"
695     };
696     runTest("simple.pdb", selections);
697 }
698
699 TEST_F(SelectionCollectionDataTest, HandlesInsertCode)
700 {
701     static const char * const selections[] = {
702         "insertcode \" \"",
703         "insertcode A"
704     };
705     runTest("simple.pdb", selections);
706 }
707
708 TEST_F(SelectionCollectionDataTest, HandlesOccupancy)
709 {
710     static const char * const selections[] = {
711         "occupancy 1",
712         "occupancy < .5"
713     };
714     runTest("simple.pdb", selections);
715 }
716
717 TEST_F(SelectionCollectionDataTest, HandlesBeta)
718 {
719     static const char * const selections[] = {
720         "beta 0",
721         "beta >= 0.3"
722     };
723     runTest("simple.pdb", selections);
724 }
725
726 TEST_F(SelectionCollectionDataTest, HandlesResname)
727 {
728     static const char * const selections[] = {
729         "resname RA",
730         "resname RB RC"
731     };
732     runTest("simple.gro", selections);
733 }
734
735 TEST_F(SelectionCollectionDataTest, HandlesCoordinateKeywords)
736 {
737     static const char * const selections[] = {
738         "x < 3",
739         "y >= 3",
740         "x {-1 to 2}"
741     };
742     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates);
743     runTest("simple.gro", selections);
744 }
745
746
747 TEST_F(SelectionCollectionDataTest, HandlesSameResidue)
748 {
749     static const char * const selections[] = {
750         "same residue as atomnr 1 4 12"
751     };
752     runTest("simple.gro", selections);
753 }
754
755
756 TEST_F(SelectionCollectionDataTest, HandlesSameResidueName)
757 {
758     static const char * const selections[] = {
759         "same resname as atomnr 1 14"
760     };
761     runTest("simple.gro", selections);
762 }
763
764
765 TEST_F(SelectionCollectionDataTest, HandlesPositionKeywords)
766 {
767     static const char * const selections[] = {
768         "cog of resnr 1 3",
769         "res_cog of name CB and resnr 1 3",
770         "whole_res_cog of name CB and resnr 1 3",
771         "part_res_cog of x < 3",
772         "dyn_res_cog of x < 3"
773     };
774     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates
775              | efTestPositionAtoms);
776     runTest("simple.gro", selections);
777 }
778
779
780 TEST_F(SelectionCollectionDataTest, HandlesDistanceKeyword)
781 {
782     static const char * const selections[] = {
783         "distance from cog of resnr 1 < 2"
784     };
785     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates);
786     runTest("simple.gro", selections);
787 }
788
789
790 TEST_F(SelectionCollectionDataTest, HandlesMinDistanceKeyword)
791 {
792     static const char * const selections[] = {
793         "mindistance from resnr 1 < 2"
794     };
795     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates);
796     runTest("simple.gro", selections);
797 }
798
799
800 TEST_F(SelectionCollectionDataTest, HandlesWithinKeyword)
801 {
802     static const char * const selections[] = {
803         "within 1 of resnr 2"
804     };
805     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates);
806     runTest("simple.gro", selections);
807 }
808
809
810 TEST_F(SelectionCollectionDataTest, HandlesInSolidAngleKeyword)
811 {
812     // Both of these should evaluate to empty on a correct implementation.
813     static const char * const selections[] = {
814         "resname TP and not insolidangle center cog of resname C span resname R cutoff 20",
815         "resname TN and insolidangle center cog of resname C span resname R cutoff 20"
816     };
817     setFlags(TestFlags() | efDontTestCompiledAtoms | efTestEvaluation);
818     runTest("sphere.gro", selections);
819 }
820
821
822 TEST_F(SelectionCollectionDataTest, HandlesPermuteModifier)
823 {
824     static const char * const selections[] = {
825         "all permute 3 1 2",
826         "res_cog of resnr 1 to 4 permute 2 1",
827         "name CB S1 and res_cog x < 3 permute 2 1"
828     };
829     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates
830              | efTestPositionAtoms | efTestPositionMapping);
831     runTest("simple.gro", selections);
832 }
833
834
835 TEST_F(SelectionCollectionDataTest, HandlesPlusModifier)
836 {
837     static const char * const selections[] = {
838         "name S2 plus name S1",
839         "res_cog of resnr 2 plus res_cog of resnr 1 plus res_cog of resnr 3",
840         "name S1 and y < 3 plus res_cog of x < 2.5"
841     };
842     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates
843              | efTestPositionAtoms | efTestPositionMapping);
844     runTest("simple.gro", selections);
845 }
846
847
848 TEST_F(SelectionCollectionDataTest, HandlesMergeModifier)
849 {
850     static const char * const selections[] = {
851         "name S2 merge name S1",
852         "resnr 1 2 and name S2 merge resnr 1 2 and name S1 merge res_cog of resnr 1 2",
853         "name S1 and x < 2.5 merge res_cog of x < 2.5"
854     };
855     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates
856              | efTestPositionAtoms | efTestPositionMapping);
857     runTest("simple.gro", selections);
858 }
859
860
861 /********************************************************************
862  * Tests for generic selection evaluation
863  */
864
865 TEST_F(SelectionCollectionDataTest, ComputesMassesAndCharges)
866 {
867     static const char * const selections[] = {
868         "name CB",
869         "y > 2",
870         "res_cog of y > 2"
871     };
872     setFlags(TestFlags() | efTestEvaluation | efTestPositionAtoms
873              | efTestPositionMasses | efTestPositionCharges);
874     ASSERT_NO_FATAL_FAILURE(runParser(selections));
875     ASSERT_NO_FATAL_FAILURE(loadTopology("simple.gro"));
876     for (int i = 0; i < top_->atoms.nr; ++i)
877     {
878         top_->atoms.atom[i].m =   1.0 + i / 100.0;
879         top_->atoms.atom[i].q = -(1.0 + i / 100.0);
880     }
881     ASSERT_NO_FATAL_FAILURE(runCompiler());
882     ASSERT_NO_FATAL_FAILURE(runEvaluate());
883     ASSERT_NO_FATAL_FAILURE(runEvaluateFinal());
884 }
885
886 TEST_F(SelectionCollectionDataTest, ComputesMassesAndChargesWithoutTopology)
887 {
888     static const char * const selections[] = {
889         "atomnr 1 to 3 8 to 9",
890         "y > 2",
891         "cog of (y > 2)"
892     };
893     setFlags(TestFlags() | efTestPositionAtoms
894              | efTestPositionMasses | efTestPositionCharges);
895     runTest(10, selections);
896 }
897
898
899 /********************************************************************
900  * Tests for selection syntactic constructs
901  */
902
903 TEST_F(SelectionCollectionDataTest, HandlesSelectionNames)
904 {
905     static const char * const selections[] = {
906         "\"GroupSelection\" group \"GrpA\"",
907         "\"DynamicSelection\" x < 5",
908         "y < 3"
909     };
910     setFlags(TestFlags() | efTestSelectionNames);
911     ASSERT_NO_THROW_GMX(loadIndexGroups("simple.ndx"));
912     runTest(10, selections);
913 }
914
915 TEST_F(SelectionCollectionDataTest, HandlesIndexGroupsInSelections)
916 {
917     static const char * const selections[] = {
918         "group \"GrpA\"",
919         "GrpB",
920         "1",
921         "group \"GrpB\" and resname RB"
922     };
923     setFlags(TestFlags() | efTestSelectionNames);
924     ASSERT_NO_THROW_GMX(loadIndexGroups("simple.ndx"));
925     runTest("simple.gro", selections);
926 }
927
928 TEST_F(SelectionCollectionDataTest, HandlesIndexGroupsInSelectionsDelayed)
929 {
930     static const char * const selections[] = {
931         "group \"GrpA\"",
932         "GrpB",
933         "1",
934         "group \"GrpB\" and resname RB"
935     };
936     setFlags(TestFlags() | efTestSelectionNames);
937     ASSERT_NO_FATAL_FAILURE(runParser(selections));
938     ASSERT_NO_FATAL_FAILURE(loadTopology("simple.gro"));
939     ASSERT_NO_THROW_GMX(loadIndexGroups("simple.ndx"));
940     ASSERT_NO_FATAL_FAILURE(runCompiler());
941 }
942
943 TEST_F(SelectionCollectionDataTest, HandlesUnsortedIndexGroupsInSelections)
944 {
945     static const char * const selections[] = {
946         "foo = group \"GrpUnsorted\"",
947         "group \"GrpUnsorted\"",
948         "GrpUnsorted",
949         "2",
950         "res_cog of group \"GrpUnsorted\"",
951         "group \"GrpUnsorted\" permute 2 1",
952         "foo"
953     };
954     setFlags(TestFlags() | efTestPositionAtoms | efTestPositionMapping
955              | efTestSelectionNames);
956     ASSERT_NO_THROW_GMX(loadIndexGroups("simple.ndx"));
957     runTest("simple.gro", selections);
958 }
959
960 TEST_F(SelectionCollectionDataTest, HandlesUnsortedIndexGroupsInSelectionsDelayed)
961 {
962     static const char * const selections[] = {
963         "foo = group \"GrpUnsorted\"",
964         "group \"GrpUnsorted\"",
965         "GrpUnsorted",
966         "2",
967         "res_cog of group \"GrpUnsorted\"",
968         "group \"GrpUnsorted\" permute 2 1",
969         "foo"
970     };
971     ASSERT_NO_FATAL_FAILURE(runParser(selections));
972     ASSERT_NO_FATAL_FAILURE(loadTopology("simple.gro"));
973     ASSERT_NO_THROW_GMX(loadIndexGroups("simple.ndx"));
974     ASSERT_NO_FATAL_FAILURE(runCompiler());
975 }
976
977 TEST_F(SelectionCollectionDataTest, HandlesConstantPositions)
978 {
979     static const char * const selections[] = {
980         "[1, -2, 3.5]"
981     };
982     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates);
983     runTest("simple.gro", selections);
984 }
985
986
987 TEST_F(SelectionCollectionDataTest, HandlesWithinConstantPositions)
988 {
989     static const char * const selections[] = {
990         "within 1 of [2, 1, 0]"
991     };
992     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates);
993     runTest("simple.gro", selections);
994 }
995
996
997 TEST_F(SelectionCollectionDataTest, HandlesOverlappingIntegerRanges)
998 {
999     static const char * const selections[] = {
1000         "atomnr 2 to 4 5 to 8",
1001         "atomnr 2 to 5 4 to 7"
1002     };
1003     ASSERT_NO_FATAL_FAILURE(runTest(10, selections));
1004 }
1005
1006
1007 TEST_F(SelectionCollectionDataTest, HandlesOverlappingRealRanges)
1008 {
1009     static const char * const selections[] = {
1010         "charge {-0.35 to -0.05 0.25 to 0.75}",
1011         "charge {0.05 to -0.3 -0.05 to 0.55}"
1012     };
1013     ASSERT_NO_FATAL_FAILURE(runParser(selections));
1014     ASSERT_NO_FATAL_FAILURE(loadTopology("simple.gro"));
1015     for (int i = 0; i < top_->atoms.nr; ++i)
1016     {
1017         top_->atoms.atom[i].q = i / 10.0 - 0.5;
1018     }
1019     ASSERT_NO_FATAL_FAILURE(runCompiler());
1020 }
1021
1022
1023 TEST_F(SelectionCollectionDataTest, HandlesForcedStringMatchingMode)
1024 {
1025     static const char * const selections[] = {
1026         "name = S1 \"C?\"",
1027         "name ? S1 \"C?\""
1028     };
1029     runTest("simple.gro", selections);
1030 }
1031
1032
1033 TEST_F(SelectionCollectionDataTest, HandlesWildcardMatching)
1034 {
1035     static const char * const selections[] = {
1036         "name \"S?\"",
1037         "name ? \"S?\""
1038     };
1039     runTest("simple.gro", selections);
1040 }
1041
1042
1043 TEST_F(SelectionCollectionDataTest, HandlesRegexMatching)
1044 {
1045     static const char * const selections[] = {
1046         "resname \"R[BD]\"",
1047         "resname ~ \"R[BD]\""
1048     };
1049     if (gmx::Regex::isSupported())
1050     {
1051         runTest("simple.gro", selections);
1052     }
1053 }
1054
1055
1056 TEST_F(SelectionCollectionDataTest, HandlesBasicBoolean)
1057 {
1058     static const char * const selections[] = {
1059         "atomnr 1 to 5 and atomnr 2 to 7",
1060         "atomnr 1 to 5 or not atomnr 3 to 8",
1061         "not not atomnr 1 to 5 and atomnr 2 to 6 and not not atomnr 3 to 7",
1062         "atomnr 1 to 5 and (atomnr 2 to 7 and atomnr 3 to 6)",
1063         "x < 5 and atomnr 1 to 5 and y < 3 and atomnr 2 to 4"
1064     };
1065     runTest(10, selections);
1066 }
1067
1068
1069 TEST_F(SelectionCollectionDataTest, HandlesDynamicAtomValuedParameters)
1070 {
1071     static const char * const selections[] = {
1072         "same residue as (atomnr 3 5 13 or y > 5)",
1073         "(resnr 1 3 5 or x > 10) and same residue as (atomnr 3 5 13 or z > 5)"
1074     };
1075     setFlags(TestFlags() | efTestEvaluation);
1076     runTest("simple.gro", selections);
1077 }
1078
1079
1080 TEST_F(SelectionCollectionDataTest, HandlesEmptySelectionWithUnevaluatedExpressions)
1081 {
1082     static const char * const selections[] = {
1083         "none and x > 2",
1084         "none and same resname as resnr 2"
1085     };
1086     runTest("simple.gro", selections);
1087 }
1088
1089
1090 TEST_F(SelectionCollectionDataTest, HandlesEmptyReferenceForSame)
1091 {
1092     static const char * const selections[] = {
1093         "same residue as none",
1094         "same resname as none"
1095     };
1096     runTest("simple.gro", selections);
1097 }
1098
1099
1100 TEST_F(SelectionCollectionDataTest, HandlesNumericComparisons)
1101 {
1102     static const char * const selections[] = {
1103         "x > 2",
1104         "2 < x",
1105         "y > resnr",
1106         "resnr < 2.5",
1107         "2.5 > resnr"
1108     };
1109     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates);
1110     runTest("simple.gro", selections);
1111 }
1112
1113
1114 TEST_F(SelectionCollectionDataTest, HandlesArithmeticExpressions)
1115 {
1116     static const char * const selections[] = {
1117         "x+1 > 3",
1118         "(y-1)^2 <= 1",
1119         "x+--1 > 3",
1120         "-x+-1 < -3"
1121     };
1122     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates);
1123     runTest("simple.gro", selections);
1124 }
1125
1126
1127 TEST_F(SelectionCollectionDataTest, HandlesNumericVariables)
1128 {
1129     static const char * const selections[] = {
1130         "value = x + y",
1131         "value <= 4",
1132         "index = resnr",
1133         "index < 3"
1134     };
1135     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates);
1136     runTest("simple.gro", selections);
1137 }
1138
1139
1140 TEST_F(SelectionCollectionDataTest, HandlesComplexNumericVariables)
1141 {
1142     static const char * const selections[] = {
1143         "value = x + y",
1144         "resname RA and value <= 4",
1145         "resname RA RB and x < 3 and value <= 4",
1146         "index = atomnr",
1147         "resname RA and index < 3",
1148         "resname RB and y < 3 and index < 6"
1149     };
1150     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates);
1151     runTest("simple.gro", selections);
1152 }
1153
1154
1155 TEST_F(SelectionCollectionDataTest, HandlesPositionVariables)
1156 {
1157     static const char * const selections[] = {
1158         "foo = res_cog of resname RA",
1159         "foo",
1160         "within 1 of foo",
1161         "bar = cog of resname RA",
1162         "bar",
1163         "within 1 of bar"
1164     };
1165     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates);
1166     runTest("simple.gro", selections);
1167 }
1168
1169
1170 TEST_F(SelectionCollectionDataTest, HandlesConstantPositionInVariable)
1171 {
1172     static const char * const selections[] = {
1173         "constpos = [1.0, 2.5, 0.5]",
1174         "constpos",
1175         "within 2 of constpos"
1176     };
1177     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates
1178              | efTestPositionAtoms);
1179     runTest("simple.gro", selections);
1180 }
1181
1182
1183 TEST_F(SelectionCollectionDataTest, HandlesNumericConstantsInVariables)
1184 {
1185     static const char * const selections[] = {
1186         "constint = 4",
1187         "constreal1 = 0.5",
1188         "constreal2 = 2.7",
1189         "resnr < constint",
1190         "x + constreal1 < constreal2"
1191     };
1192     setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates);
1193     runTest("simple.gro", selections);
1194 }
1195
1196
1197 /********************************************************************
1198  * Tests for complex boolean syntax
1199  */
1200
1201 TEST_F(SelectionCollectionDataTest, HandlesBooleanStaticAnalysis)
1202 {
1203     static const char * const selections[] = {
1204         "atomnr 1 to 5 and atomnr 2 to 7 and x < 2",
1205         "atomnr 1 to 5 and (atomnr 4 to 7 or x < 2)",
1206         "atomnr 1 to 5 and y < 3 and (atomnr 4 to 7 or x < 2)",
1207         "atomnr 1 to 5 and not (atomnr 4 to 7 or x < 2)",
1208         "atomnr 1 to 5 or (atomnr 4 to 6 and (atomnr 5 to 7 or x < 2))"
1209     };
1210     runTest(10, selections);
1211 }
1212
1213
1214 TEST_F(SelectionCollectionDataTest, HandlesBooleanStaticAnalysisWithVariables)
1215 {
1216     static const char * const selections[] = {
1217         "foo = atomnr 4 to 7 or x < 2",
1218         "atomnr 1 to 4 and foo",
1219         "atomnr 2 to 6 and y < 3 and foo",
1220         "atomnr 6 to 10 and not foo"
1221     };
1222     runTest(10, selections);
1223 }
1224
1225
1226 TEST_F(SelectionCollectionDataTest, HandlesBooleanStaticAnalysisWithMoreVariables)
1227 {
1228     static const char * const selections[] = {
1229         "foo = atomnr 4 to 7",
1230         "bar = foo and x < 2",
1231         "bar2 = foo and y < 2",
1232         "atomnr 1 to 4 and bar",
1233         "atomnr 2 to 6 and y < 3 and bar2",
1234         "atomnr 6 to 10 and not foo"
1235     };
1236     runTest(10, selections);
1237 }
1238
1239
1240 /********************************************************************
1241  * Tests for complex subexpression cases
1242  *
1243  * These tests use some knowledge of the implementation to trigger different
1244  * paths in the code.
1245  */
1246
1247 TEST_F(SelectionCollectionDataTest, HandlesUnusedVariables)
1248 {
1249     static const char * const selections[] = {
1250         "unused1 = atomnr 1 to 3",
1251         "foo = atomnr 4 to 7",
1252         "atomnr 1 to 6 and foo",
1253         "unused2 = atomnr 3 to 5"
1254     };
1255     runTest(10, selections);
1256 }
1257
1258
1259 TEST_F(SelectionCollectionDataTest, HandlesVariablesWithStaticEvaluationGroups)
1260 {
1261     static const char * const selections[] = {
1262         "foo = atomnr 4 to 7 and x < 2",
1263         "atomnr 1 to 5 and foo",
1264         "atomnr 3 to 7 and foo"
1265     };
1266     runTest(10, selections);
1267 }
1268
1269
1270 TEST_F(SelectionCollectionDataTest, HandlesVariablesWithMixedEvaluationGroups)
1271 {
1272     static const char * const selections[] = {
1273         "foo = atomnr 4 to 7 and x < 2",
1274         "atomnr 1 to 6 and foo",
1275         "within 1 of foo",
1276         "foo"
1277     };
1278     runTest(10, selections);
1279 }
1280
1281
1282 TEST_F(SelectionCollectionDataTest, HandlesVariablesWithMixedEvaluationGroups2)
1283 {
1284     static const char * const selections[] = {
1285         "foo = atomnr 1 to 8 and x < 10",
1286         "atomnr 1 to 5 and y < 10 and foo",
1287         "foo"
1288     };
1289     setFlags(TestFlags() | efTestEvaluation);
1290     runTest("simple.gro", selections);
1291 }
1292
1293
1294 } // namespace