4946a3092e8f8ab618e1cb96ecffac4b7cced6d7
[alexxy/gromacs.git] / src / gromacs / random / threefry.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2015,2016,2017,2018,2019, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35
36 /*! \file
37  * \brief Implementation of the 2x64 ThreeFry random engine
38  *
39  * \author Erik Lindahl <erik.lindahl@gmail.com>
40  * \inpublicapi
41  * \ingroup module_random
42  */
43
44 #ifndef GMX_RANDOM_THREEFRY_H
45 #define GMX_RANDOM_THREEFRY_H
46
47 #include <array>
48 #include <limits>
49
50 #include "gromacs/math/functions.h"
51 #include "gromacs/random/seed.h"
52 #include "gromacs/utility/classhelpers.h"
53 #include "gromacs/utility/exceptions.h"
54
55 /*
56  * The GROMACS implementation of the ThreeFry random engine has been
57  * heavily inspired by the versions proposed to Boost by:
58  *
59  * John Salmon, Copyright 2010-2014 by D. E. Shaw Research
60  * https://github.com/DEShawResearch/Random123-Boost
61  *
62  * Thijs van den Berg, Copyright (c) 2014 M.A. (Thijs) van den Berg
63  * https://github.com/sitmo/threefry
64  *
65  * Both of them are covered by the Boost Software License:
66  *
67  * Boost Software License - Version 1.0 - August 17th, 2003
68  *
69  * Permission is hereby granted, free of charge, to any person or organization
70  * obtaining a copy of the software and accompanying documentation covered by
71  * this license (the "Software") to use, reproduce, display, distribute,
72  * execute, and transmit the Software, and to prepare derivative works of the
73  * Software, and to permit third-parties to whom the Software is furnished to
74  * do so, all subject to the following:
75  *
76  * The copyright notices in the Software and this entire statement, including
77  * the above license grant, this restriction and the following disclaimer,
78  * must be included in all copies of the Software, in whole or in part, and
79  * all derivative works of the Software, unless such copies or derivative
80  * works are solely in the form of machine-executable object code generated by
81  * a source language processor.
82  *
83  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
84  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
85  * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
86  * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
87  * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
88  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
89  * DEALINGS IN THE SOFTWARE.
90  */
91
92 namespace gmx
93 {
94
95 namespace internal
96 {
97 // Variable-bitfield counters used to increment internal counters as
98 // part of std::arrays.
99
100 struct highBitCounter
101 {
102     /*! \brief Clear highBits higest bits of ctr, return false if they were non-zero.
103      *
104      *  This function clears the space required for the internal counters,
105      *  and returns true if they were correctly zero when calling, false otherwise.
106      *
107      *  \tparam        UIntType  Integer type to use for each word in counter
108      *  \tparam        words     Number of UIntType words in counter
109      *  \tparam        highBits  Number of bits to check. The template parameter makes it
110      *                           possible to optimize this extensively at compile time.
111      *  \param         ctr       Reference to counter to check and clear.
112      */
113     template<class UIntType, std::size_t words, unsigned int highBits>
114     static bool checkAndClear(std::array<UIntType, words>* ctr)
115     {
116         const std::size_t bitsPerWord = std::numeric_limits<UIntType>::digits;
117         const std::size_t bitsTotal   = bitsPerWord * words;
118
119         static_assert(highBits <= bitsTotal, "High bits do not fit in counter.");
120
121         const std::size_t lastWordIdx       = (bitsTotal - highBits) / bitsPerWord;
122         const std::size_t lastWordLowBitIdx = (bitsTotal - highBits) % bitsPerWord;
123         const UIntType    lastWordOne       = static_cast<UIntType>(1) << lastWordLowBitIdx;
124         const UIntType    mask              = lastWordOne - 1;
125
126         bool isClear = true;
127
128         for (unsigned int i = words - 1; i > lastWordIdx; --i)
129         {
130             if ((*ctr)[i])
131             {
132                 isClear   = false;
133                 (*ctr)[i] = 0;
134             }
135         }
136         if (highBits > 0 && (*ctr)[lastWordIdx] >= lastWordOne)
137         {
138             isClear = false;
139             (*ctr)[lastWordIdx] &= mask;
140         }
141         return isClear;
142     }
143
144     /*! \brief Increment the internal counter in highBits by one
145      *
146      *  \tparam         UIntType  Integer type to use for each word in counter
147      *  \tparam         words     Number of UIntType words in counter
148      *  \tparam         highBits  Number of bits reserved for the internal counter.
149      *  \param          ctr       Reference to the counter value to increment.
150      *
151      *  \throws InternalError if internal counter space is exhausted.
152      *
153      *  This routine will work across the word boundaries for any number
154      *  of internal counter bits that fits in the total counter.
155      */
156     template<class UIntType, std::size_t words, unsigned int highBits>
157     static void increment(std::array<UIntType, words>* ctr)
158     {
159         const std::size_t bitsPerWord = std::numeric_limits<UIntType>::digits;
160         const std::size_t bitsTotal   = bitsPerWord * words;
161
162         static_assert(highBits <= bitsTotal, "High bits do not fit in counter.");
163
164         const std::size_t lastWordIdx       = (bitsTotal - highBits) / bitsPerWord;
165         const std::size_t lastWordLowBitIdx = (bitsTotal - highBits) % bitsPerWord;
166         const UIntType    lastWordOne       = static_cast<UIntType>(1) << lastWordLowBitIdx;
167
168         // For algorithm & efficiency reasons we need to store the internal counter in
169         // the same array as the user-provided counter, so we use the higest bits, possibly
170         // crossing several words.
171         //
172         // To have the computer help us with the dirty carry arithmetics we store the bits
173         // in the internal counter part in normal fashion, but the internal counter words in
174         // reverse order; the highest word of the total counter array (words-1) is thus
175         // the least significant part of the internal counter (if it spans several words).
176         //
177         // The incrementation works as follows:
178         //
179         // 0) If the index of the least significant internal counter word is larger
180         //    than words-1, there was never any space.
181         // 1) If the internal counter spans more than one word, we must have one or
182         //    more internal counter words that correspond entirely to the this counter.
183         //    Start with the least significant one (words-1) and increment it.
184         //    If the new value is not zero we did not loop around (no carry), so everything
185         //    is good, and we are done - return!
186         //    If the new value is zero, we need to move the carry result to the next word,
187         //    so we just continue the loop until we have gone through all words that
188         //    are internal-counter-only.
189         // 2) After the loop, there is stuff remaining to add, and by definition there
190         //    is some internal counter space in the next word, but the question
191         //    is if we have exhausted it. We already created a constant that corresponds
192         //    to the bit that represents '1' for the internal counter part of this word.
193         //    When we add this constant it will not affect the user-counter-part at all,
194         //    and if we exhaust the internal counter space the high bits will cause the entire
195         //    word to wrap around, and the result will be smaller than the bit we added.
196         //    If this happens we throw, otherwise we're done.
197         //
198         // Since all constants will be evaluated at compile time, this entire routine
199         // will usually be reduced to simply incrementing a word by a constant, and throwing
200         // if the result is smaller than the constant.
201
202         if (lastWordIdx >= words)
203         {
204             GMX_THROW(InternalError(
205                     "Cannot increment random engine defined with 0 internal counter bits."));
206         }
207
208         for (unsigned int i = words - 1; i > lastWordIdx; --i)
209         {
210             (*ctr)[i]++;
211             if ((*ctr)[i])
212             {
213                 return; // No carry means we are done
214             }
215         }
216         (*ctr)[lastWordIdx] += lastWordOne;
217         if ((*ctr)[lastWordIdx] < lastWordOne)
218         {
219             GMX_THROW(InternalError("Random engine stream ran out of internal counter space."));
220         }
221     }
222
223     /*! \brief Increment the internal counter in highBits by a value.
224      *
225      *  \tparam        UIntType  Integer type to use for each word in counter
226      *  \tparam        words     Number of UIntType words in counter
227      *  \tparam        highBits  Number of bits reserved for the internal counter.
228      *  \param         ctr       Reference to the counter to increment.
229      *  \param         addend    Value to add to internal.
230      *
231      *  \throws InternalError if internal counter space is exhausted.
232      *
233      *  This routine will work across the word boundaries for any number
234      *  of internal counter bits that fits in the total counter.
235      */
236     template<class UIntType, std::size_t words, unsigned int highBits>
237     static void increment(std::array<UIntType, words>* ctr, UIntType addend)
238     {
239         const std::size_t bitsPerWord = std::numeric_limits<UIntType>::digits;
240         const std::size_t bitsTotal   = bitsPerWord * words;
241
242         static_assert(highBits <= bitsTotal, "High bits do not fit in counter.");
243
244         const std::size_t lastWordIdx       = (bitsTotal - highBits) / bitsPerWord;
245         const std::size_t lastWordLowBitIdx = (bitsTotal - highBits) % bitsPerWord;
246         const UIntType    lastWordOne       = static_cast<UIntType>(1) << lastWordLowBitIdx;
247         const UIntType    lastWordMaxVal    = (~static_cast<UIntType>(0)) >> lastWordLowBitIdx;
248
249         if (lastWordIdx >= words)
250         {
251             GMX_THROW(InternalError(
252                     "Cannot increment random engine defined with 0 internal counter bits."));
253         }
254
255         for (unsigned int i = words - 1; i > lastWordIdx; --i)
256         {
257             (*ctr)[i] += addend;
258             addend = ((*ctr)[i] < addend); // 1 is the carry!
259             if (addend == 0)
260             {
261                 return;
262             }
263         }
264
265         if (addend > lastWordMaxVal)
266         {
267             GMX_THROW(InternalError("Random engine stream ran out of internal counter space."));
268         }
269         addend *= lastWordOne;
270
271         (*ctr)[lastWordIdx] += addend;
272
273         if ((*ctr)[lastWordIdx] < addend)
274         {
275             GMX_THROW(InternalError("Random engine stream ran out of internal counter space."));
276         }
277     }
278 };
279 } // namespace internal
280
281 /*! \brief General implementation class for ThreeFry counter-based random engines.
282  *
283  *  This class is used to implement several different ThreeFry2x64 random engines
284  *  differing in the number of rounds executed in and the number of bits reserved
285  *  for the internal counter. It is compatible with C++11 random engines, and
286  *  can be used e.g. with all random distributions from the standard library.
287  *
288  *  ThreeFry is a counter-based rather than state-based random engine. This
289  *  means that we seed it with a "key", after which we can get the
290  *  N:th random number in a sequence (specified by a counter) directly. This
291  *  means we are guaranteed the same sequence of numbers even when running in
292  *  parallel if using e.g. step and atom index as counters.
293  *
294  *  However, it is also useful to be able to use it as a normal random engine,
295  *  for instance if you need more than 2 64-bit random values for a specific
296  *  counter value, not to mention where you just need good normal random numbers.
297  *  To achieve this, this implementation uses John Salmon's idea of reserving
298  *  a couple of the highest bits in the user-provided counter for an internal
299  *  counter. For instance, if reserving 3 bits, this means you get a stream of
300  *  8 iterations (each with 2 random values) after every restart. If you call
301  *  the engine after these bits have been exhausted, it will throw an
302  *  exception to make sure you don't get overlapping streams by mistake.
303  *  Reserving 3 bits also means you can only use 64-3=61 bits of the highest
304  *  word when restarting (i.e., setting) the counters.
305  *
306  *  This version also supports using internalCounterBits=0. In this case the
307  *  random engine will be able to return a single counter round, i.e. 2 64-bit
308  *  values for ThreeFry2x64, after which an exception is thrown. In this case no
309  *  high bits are reserved, which means the class implements the raw ThreeFry2x64
310  *  random function.
311  *
312  *  \tparam rounds  The number of encryption iterations used when generating.
313  *                  This can in principle be any value, but 20 rounds has been
314  *                  shown to pass all BigCrush random tests, and with 13 rounds
315  *                  only one fails. This is a very stringent test, and the
316  *                  standard Mersenne Twister engine fails two, so 13 rounds
317  *                  should be a perfectly fine balance in most cases.
318  *  \tparam internalCounterBits
319  *                  Number of high bits in the user-provided counter reserved
320  *                  for the internal counter. The number of values the engine
321  *                  can return after each restart will be
322  *                  words*2^internalCounterBits.
323  */
324 template<unsigned int rounds, unsigned int internalCounterBits>
325 class ThreeFry2x64General
326 {
327     // While this class will formally work with any value for rounds, there is
328     // no reason to go lower than 13, and this might help catch some typos.
329     // If we find a reason to use lower values in the future, or if you simply
330     // want to test, this assert can safely be removed.
331     static_assert(rounds >= 13,
332                   "You should not use less than 13 encryption rounds for ThreeFry2x64.");
333
334 public:
335     // result_type must be lower case to be compatible with C++11 standard library
336
337     /*! \brief Integer type for output. */
338     typedef uint64_t result_type;
339     /*! \brief Use array for counter & key states so it is allocated on the stack */
340     typedef std::array<result_type, 2> counter_type;
341
342 private:
343     /*! \brief Rotate value left by specified number of bits
344      *
345      *  \param i    Value to rotate (result_type, which should be 64-bit).
346      *  \param bits Number of bits to rotate i.
347      *
348      *  \return Input value rotated 'bits' left.
349      */
350     result_type rotLeft(result_type i, unsigned int bits)
351     {
352         return (i << bits) | (i >> (std::numeric_limits<result_type>::digits - bits));
353     }
354
355     /*! \brief Perform encryption step for ThreeFry2x64 algorithm
356      *
357      *  It performs the encryption step of the standard ThreeFish symmetric-key
358      *  tweakable block cipher, which is the core of the ThreeFry random
359      *  engine. The number of encryption rounds is specified by the class
360      *  template parameter 'rounds'.
361      *
362      *  \param key   Reference to key value
363      *  \param ctr   Counter value to use
364      *
365      *  \return Newly encrypted 2x64 block, according to the class template parameters.
366      */
367     counter_type generateBlock(const counter_type& key, const counter_type& ctr)
368     {
369         const unsigned int rotations[] = { 16, 42, 12, 31, 16, 32, 24, 21 };
370         counter_type       x           = ctr;
371
372         result_type ks[3] = { 0x0, 0x0, 0x1bd11bdaa9fc1a22 };
373
374         // This is actually a pretty simple routine that merely executes the
375         // for-block specified further down 'rounds' times. However, both
376         // clang and gcc have problems unrolling and replacing rotations[r%8]
377         // with constants, so we unroll the first 20 iterations manually.
378
379         if (rounds > 0)
380         {
381             ks[0] = key[0];
382             ks[2] ^= key[0];
383             x[0]  = x[0] + key[0];
384             ks[1] = key[1];
385             ks[2] ^= key[1];
386             x[1] = x[1] + key[1];
387             x[0] += x[1];
388             x[1] = rotLeft(x[1], 16);
389             x[1] ^= x[0];
390         }
391         if (rounds > 1)
392         {
393             x[0] += x[1];
394             x[1] = rotLeft(x[1], 42);
395             x[1] ^= x[0];
396         }
397         if (rounds > 2)
398         {
399             x[0] += x[1];
400             x[1] = rotLeft(x[1], 12);
401             x[1] ^= x[0];
402         }
403         if (rounds > 3)
404         {
405             x[0] += x[1];
406             x[1] = rotLeft(x[1], 31);
407             x[1] ^= x[0];
408             x[0] += ks[1];
409             x[1] += ks[2] + 1;
410         }
411         if (rounds > 4)
412         {
413             x[0] += x[1];
414             x[1] = rotLeft(x[1], 16);
415             x[1] ^= x[0];
416         }
417         if (rounds > 5)
418         {
419             x[0] += x[1];
420             x[1] = rotLeft(x[1], 32);
421             x[1] ^= x[0];
422         }
423         if (rounds > 6)
424         {
425             x[0] += x[1];
426             x[1] = rotLeft(x[1], 24);
427             x[1] ^= x[0];
428         }
429         if (rounds > 7)
430         {
431             x[0] += x[1];
432             x[1] = rotLeft(x[1], 21);
433             x[1] ^= x[0];
434             x[0] += ks[2];
435             x[1] += ks[0] + 2;
436         }
437         if (rounds > 8)
438         {
439             x[0] += x[1];
440             x[1] = rotLeft(x[1], 16);
441             x[1] ^= x[0];
442         }
443         if (rounds > 9)
444         {
445             x[0] += x[1];
446             x[1] = rotLeft(x[1], 42);
447             x[1] ^= x[0];
448         }
449         if (rounds > 10)
450         {
451             x[0] += x[1];
452             x[1] = rotLeft(x[1], 12);
453             x[1] ^= x[0];
454         }
455         if (rounds > 11)
456         {
457             x[0] += x[1];
458             x[1] = rotLeft(x[1], 31);
459             x[1] ^= x[0];
460             x[0] += ks[0];
461             x[1] += ks[1] + 3;
462         }
463         if (rounds > 12)
464         {
465             x[0] += x[1];
466             x[1] = rotLeft(x[1], 16);
467             x[1] ^= x[0];
468         }
469         if (rounds > 13)
470         {
471             x[0] += x[1];
472             x[1] = rotLeft(x[1], 32);
473             x[1] ^= x[0];
474         }
475         if (rounds > 14)
476         {
477             x[0] += x[1];
478             x[1] = rotLeft(x[1], 24);
479             x[1] ^= x[0];
480         }
481         if (rounds > 15)
482         {
483             x[0] += x[1];
484             x[1] = rotLeft(x[1], 21);
485             x[1] ^= x[0];
486             x[0] += ks[1];
487             x[1] += ks[2] + 4;
488         }
489         if (rounds > 16)
490         {
491             x[0] += x[1];
492             x[1] = rotLeft(x[1], 16);
493             x[1] ^= x[0];
494         }
495         if (rounds > 17)
496         {
497             x[0] += x[1];
498             x[1] = rotLeft(x[1], 42);
499             x[1] ^= x[0];
500         }
501         if (rounds > 18)
502         {
503             x[0] += x[1];
504             x[1] = rotLeft(x[1], 12);
505             x[1] ^= x[0];
506         }
507         if (rounds > 19)
508         {
509             x[0] += x[1];
510             x[1] = rotLeft(x[1], 31);
511             x[1] ^= x[0];
512             x[0] += ks[2];
513             x[1] += ks[0] + 5;
514         }
515
516         for (unsigned int r = 20; r < rounds; r++)
517         {
518             x[0] += x[1];
519             x[1] = rotLeft(x[1], rotations[r % 8]);
520             x[1] ^= x[0];
521             if (((r + 1) & 3) == 0)
522             {
523                 unsigned int r4 = (r + 1) >> 2;
524                 x[0] += ks[r4 % 3];
525                 x[1] += ks[(r4 + 1) % 3] + r4;
526             }
527         }
528         return x;
529     }
530
531 public:
532     //! \brief Smallest value that can be returned from random engine.
533 #if !defined(_MSC_VER)
534     static constexpr
535 #else
536     // Avoid constexpr bug in MSVC 2015, note that max() below does work
537     static
538 #endif
539             result_type
540             min()
541     {
542         return std::numeric_limits<result_type>::min();
543     }
544
545     //! \brief Largest value that can be returned from random engine.
546     static constexpr result_type max() { return std::numeric_limits<result_type>::max(); }
547
548     /*! \brief Construct random engine with 2x64 key values
549      *
550      *  This constructor takes two values, and should only be used with
551      *  the 2x64 implementations.
552      *
553      *  \param key0   Random seed in the form of a 64-bit unsigned value.
554      *  \param domain Random domain. This is used to guarantee that different
555      *                applications of a random engine inside the code get different
556      *                streams of random numbers, without requiring the user
557      *                to provide lots of random seeds. Pick a value from the
558      *                RandomDomain class, or RandomDomain::Other if it is
559      *                not important. In the latter case you might want to use
560      *                \ref gmx::DefaultRandomEngine instead.
561      *
562      *  \note The random domain is really another 64-bit seed value.
563      *
564      *  \throws InternalError if the high bits needed to encode the number of counter
565      *          bits are nonzero.
566      */
567     //NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
568     ThreeFry2x64General(uint64_t key0 = 0, RandomDomain domain = RandomDomain::Other)
569     {
570         seed(key0, domain);
571     }
572
573     /*! \brief Construct random engine from 2x64-bit unsigned integers
574      *
575      *  This constructor assigns the raw 128 bit key data from unsigned integers.
576      *  It is meant for the case when you want full control over the key,
577      *  for instance to compare with reference values of the ThreeFry
578      *  function during testing.
579      *
580      *  \param key0   First word of key/random seed.
581      *  \param key1   Second word of key/random seed.
582      *
583      *  \throws InternalError if the high bits needed to encode the number of counter
584      *          bits are nonzero. To test arbitrary values, use 0 internal counter bits.
585      */
586     //NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
587     ThreeFry2x64General(uint64_t key0, uint64_t key1) { seed(key0, key1); }
588
589     /*! \brief Seed 2x64 random engine with two 64-bit key values
590      *
591      *  \param key0   First word of random seed, in the form of 64-bit unsigned values.
592      *  \param domain Random domain. This is used to guarantee that different
593      *                applications of a random engine inside the code get different
594      *                streams of random numbers, without requiring the user
595      *                to provide lots of random seeds. Pick a value from the
596      *                RandomDomain class, or RandomDomain::Other if it is
597      *                not important. In the latter case you might want to use
598      *                \ref gmx::DefaultRandomEngine instead.
599      *
600      *  \note The random domain is really another 64-bit seed value.
601      *
602      *  Re-initialized the seed similar to the counter constructor.
603      *  Same rules apply: The highest few bits of the last word are
604      *  reserved to encode the number of internal counter bits, but
605      *  to save the user the trouble of making sure these are zero
606      *  when using e.g. a random device, we just ignore them.
607      */
608     void seed(uint64_t key0 = 0, RandomDomain domain = RandomDomain::Other)
609     {
610         seed(key0, static_cast<uint64_t>(domain));
611     }
612
613     /*! \brief Seed random engine from 2x64-bit unsigned integers
614      *
615      *  This assigns the raw 128 bit key data from unsigned integers.
616      *  It is meant for the case when you want full control over the key,
617      *  for instance to compare with reference values of the ThreeFry
618      *  function during testing.
619      *
620      *  \param key0   First word of key/random seed.
621      *  \param key1   Second word of key/random seed.
622      *
623      *  \throws InternalError if the high bits needed to encode the number of counter
624      *          bits are nonzero. To test arbitrary values, use 0 internal counter bits.
625      */
626     void seed(uint64_t key0, uint64_t key1)
627     {
628         const unsigned int internalCounterBitsBits =
629                 (internalCounterBits > 0) ? (StaticLog2<internalCounterBits>::value + 1) : 0;
630
631         key_ = { { key0, key1 } };
632
633         if (internalCounterBits > 0)
634         {
635             internal::highBitCounter::checkAndClear<result_type, 2, internalCounterBitsBits>(&key_);
636             internal::highBitCounter::increment<result_type, 2, internalCounterBitsBits>(
637                     &key_, internalCounterBits - 1);
638         }
639         restart(0, 0);
640     }
641
642     /*! \brief Restart 2x64 random engine counter from 2 64-bit values
643      *
644      *  \param ctr0 First word of new counter, in the form of 64-bit unsigned values.
645      *  \param ctr1 Second word of new counter
646      *
647      * Restarting the engine with a new counter is extremely fast with ThreeFry64,
648      * and basically just consists of storing the counter value, so you should
649      * use this liberally in your innermost loops to restart the engine with
650      * e.g. the current step and atom index as counter values.
651      *
652      * \throws InternalError if any of the highest bits that are reserved
653      *         for the internal part of the counter are set. The number of
654      *         reserved bits is to the last template parameter to the class.
655      */
656     void restart(uint64_t ctr0 = 0, uint64_t ctr1 = 0)
657     {
658
659         counter_ = { { ctr0, ctr1 } };
660         if (!internal::highBitCounter::checkAndClear<result_type, 2, internalCounterBits>(&counter_))
661         {
662             GMX_THROW(InternalError(
663                     "High bits of counter are reserved for the internal stream counter."));
664         }
665         block_ = generateBlock(key_, counter_);
666         index_ = 0;
667     }
668
669     /*! \brief Generate the next random number
670      *
671      *  This will return the next stored 64-bit value if one is available,
672      *  and otherwise generate a new block, update the internal counters, and
673      *  return the first value while storing the others.
674      *
675      *  \throws InternalError if the internal counter space is exhausted.
676      */
677     result_type operator()()
678     {
679         if (index_ >= c_resultsPerCounter_)
680         {
681             internal::highBitCounter::increment<result_type, 2, internalCounterBits>(&counter_);
682             block_ = generateBlock(key_, counter_);
683             index_ = 0;
684         }
685         return block_[index_++];
686     }
687
688     /*! \brief Skip next n random numbers
689      *
690      *  Moves the internal random stream for the give key/counter value
691      *  n positions forward. The count is based on the number of random values
692      *  returned, such that skipping 5 values gives exactly the same result as
693      *  drawing 5 values that are ignored.
694      *
695      *  \param n Number of values to jump forward.
696      *
697      *  \throws InternalError if the internal counter space is exhausted.
698      */
699     void discard(uint64_t n)
700     {
701         index_ += n % c_resultsPerCounter_;
702         n /= c_resultsPerCounter_;
703
704         if (index_ > c_resultsPerCounter_)
705         {
706             index_ -= c_resultsPerCounter_;
707             n++;
708         }
709
710         // Make sure the state is the same as if we came to this counter and
711         // index by natural generation.
712         if (index_ == 0 && n > 0)
713         {
714             index_ = c_resultsPerCounter_;
715             n--;
716         }
717         internal::highBitCounter::increment<result_type, 2, internalCounterBits>(&counter_, n);
718         block_ = generateBlock(key_, counter_);
719     }
720
721     /*! \brief Return true if two ThreeFry2x64 engines are identical
722      *
723      * \param  x    Instance to compare with.
724      *
725      * This routine should return true if the two engines will generate
726      * identical random streams when drawing.
727      */
728     bool operator==(const ThreeFry2x64General<rounds, internalCounterBits>& x) const
729     {
730         // block_ is uniquely specified by key_ and counter_.
731         return (key_ == x.key_ && counter_ == x.counter_ && index_ == x.index_);
732     }
733
734     /*! \brief Return true of two ThreeFry2x64 engines are not identical
735      *
736      * \param  x    Instance to compare with.
737      *
738      * This routine should return true if the two engines will generate
739      * different random streams when drawing.
740      */
741     bool operator!=(const ThreeFry2x64General<rounds, internalCounterBits>& x) const
742     {
743         return !operator==(x);
744     }
745
746 private:
747     /*! \brief Number of results returned for each invocation of the block generation */
748     static const unsigned int c_resultsPerCounter_ =
749             static_cast<unsigned int>(sizeof(counter_type) / sizeof(result_type));
750
751     /*! \brief ThreeFry2x64 key, i.e. the random seed for this stream.
752      *
753      *  The highest few bits of the key are replaced to encode the value of
754      *  internalCounterBits, in order to make all streams unique.
755      */
756     counter_type key_;
757
758     /*! \brief ThreeFry2x64 total counter.
759      *
760      *  The highest internalCounterBits are reserved for an internal counter
761      *  so that the combination of a key and counter provides a stream that
762      *  returns 2*2^internalCounterBits (ThreeFry2x64) random 64-bit values before
763      *  the internal counter space is exhausted and an exception is thrown.
764      */
765     counter_type counter_;
766     /*! \brief The present block encrypted from values of key and counter. */
767     counter_type block_;
768     /*! \brief Index of the next value in block_ to return from random engine */
769     unsigned int index_;
770
771     GMX_DISALLOW_COPY_AND_ASSIGN(ThreeFry2x64General);
772 };
773
774
775 /*! \brief ThreeFry2x64 random engine with 20 iteractions.
776  *
777  *  \tparam internalCounterBits, default 64.
778  *
779  *  This class provides very high quality random numbers that pass all
780  *  BigCrush tests, it works with two 64-bit values each for keys and
781  *  counters, and is most  efficient when we only need a few random values
782  *  before restarting the counters with new values.
783  */
784 template<unsigned int internalCounterBits = 64>
785 class ThreeFry2x64 : public ThreeFry2x64General<20, internalCounterBits>
786 {
787 public:
788     /*! \brief Construct ThreeFry random engine with 2x64 key values, 20 rounds.
789      *
790      *  \param key0   Random seed in the form of a 64-bit unsigned value.
791      *  \param domain Random domain. This is used to guarantee that different
792      *                applications of a random engine inside the code get different
793      *                streams of random numbers, without requiring the user
794      *                to provide lots of random seeds. Pick a value from the
795      *                RandomDomain class, or RandomDomain::Other if it is
796      *                not important. In the latter case you might want to use
797      *                \ref gmx::DefaultRandomEngine instead.
798      *
799      *  \note The random domain is really another 64-bit seed value.
800      *
801      *  \throws InternalError if the high bits needed to encode the number of counter
802      *          bits are nonzero.
803      */
804     ThreeFry2x64(uint64_t key0 = 0, RandomDomain domain = RandomDomain::Other) :
805         ThreeFry2x64General<20, internalCounterBits>(key0, domain)
806     {
807     }
808
809     /*! \brief Construct random engine from 2x64-bit unsigned integers, 20 rounds
810      *
811      *  This constructor assigns the raw 128 bit key data from unsigned integers.
812      *  It is meant for the case when you want full control over the key,
813      *  for instance to compare with reference values of the ThreeFry
814      *  function during testing.
815      *
816      *  \param key0   First word of key/random seed.
817      *  \param key1   Second word of key/random seed.
818      *
819      *  \throws InternalError if the high bits needed to encode the number of counter
820      *          bits are nonzero. To test arbitrary values, use 0 internal counter bits.
821      */
822     ThreeFry2x64(uint64_t key0, uint64_t key1) :
823         ThreeFry2x64General<20, internalCounterBits>(key0, key1)
824     {
825     }
826 };
827
828 /*! \brief ThreeFry2x64 random engine with 13 iteractions.
829  *
830  *  \tparam internalCounterBits, default 64.
831  *
832  *  This class provides relatively high quality random numbers that only
833  *  fail one BigCrush test, and it is a bit faster than the 20-round version.
834  *  It works with two 64-bit values each for keys and counters, and is most
835  *  efficient when we only need a few random values before restarting
836  *  the counters with new values.
837  */
838 template<unsigned int internalCounterBits = 64>
839 class ThreeFry2x64Fast : public ThreeFry2x64General<13, internalCounterBits>
840 {
841 public:
842     /*! \brief Construct ThreeFry random engine with 2x64 key values, 13 rounds.
843      *
844      *  \param key0   Random seed in the form of a 64-bit unsigned value.
845      *  \param domain Random domain. This is used to guarantee that different
846      *                applications of a random engine inside the code get different
847      *                streams of random numbers, without requiring the user
848      *                to provide lots of random seeds. Pick a value from the
849      *                RandomDomain class, or RandomDomain::Other if it is
850      *                not important. In the latter case you might want to use
851      *                \ref gmx::DefaultRandomEngine instead.
852      *
853      *  \note The random domain is really another 64-bit seed value.
854      *
855      *  \throws InternalError if the high bits needed to encode the number of counter
856      *          bits are nonzero.
857      */
858     ThreeFry2x64Fast(uint64_t key0 = 0, RandomDomain domain = RandomDomain::Other) :
859         ThreeFry2x64General<13, internalCounterBits>(key0, domain)
860     {
861     }
862
863     /*! \brief Construct ThreeFry random engine from 2x64-bit unsigned integers, 13 rounds.
864      *
865      *  This constructor assigns the raw 128 bit key data from unsigned integers.
866      *  It is meant for the case when you want full control over the key,
867      *  for instance to compare with reference values of the ThreeFry
868      *  function during testing.
869      *
870      *  \param key0   First word of key/random seed.
871      *  \param key1   Second word of key/random seed.
872      *
873      *  \throws InternalError if the high bits needed to encode the number of counter
874      *          bits are nonzero. To test arbitrary values, use 0 internal counter bits.
875      */
876     ThreeFry2x64Fast(uint64_t key0, uint64_t key1) :
877         ThreeFry2x64General<13, internalCounterBits>(key0, key1)
878     {
879     }
880 };
881
882
883 /*! \brief Default fast and accurate random engine in Gromacs
884  *
885  *  This engine will return 2*2^64 random results using the default
886  *  gmx::RandomDomain::Other stream, and can be initialized with a single
887  *  seed argument without having to remember empty template angle brackets.
888  */
889 typedef ThreeFry2x64Fast<> DefaultRandomEngine;
890
891 } // namespace gmx
892
893 #endif // GMX_RANDOM_THREEFRY_H