Skip to content

Commit ecd7bda

Browse files
N-Dekkerdzenanz
authored andcommitted
ENH: Add MersenneTwisterRandomVariateGenerator::ResetNextSeed()
Allows generating a reproducible sequence of pseudo-random numbers.
1 parent 427972e commit ecd7bda

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

Modules/Core/Common/include/itkMersenneTwisterRandomVariateGenerator.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,11 @@ class ITKCommon_EXPORT MersenneTwisterRandomVariateGenerator : public RandomVari
160160
static Pointer
161161
GetInstance();
162162

163+
/** Resets the internal data that is used to calculate the next seed. (Does not reset the initial seed.) Allows
164+
* generating a reproducible sequence of pseudo-random numbers. */
165+
static void
166+
ResetNextSeed();
167+
163168
/** Length of state vector */
164169
static constexpr IntegerType StateVectorLength = 624;
165170

Modules/Core/Common/src/itkMersenneTwisterRandomVariateGenerator.cxx

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,16 @@ MersenneTwisterRandomVariateGenerator::GetInstance()
8181
return m_PimplGlobals->m_StaticInstance;
8282
}
8383

84+
85+
void
86+
MersenneTwisterRandomVariateGenerator::ResetNextSeed()
87+
{
88+
itkInitGlobalsMacro(PimplGlobals);
89+
const std::lock_guard<std::recursive_mutex> lockGuard(m_PimplGlobals->m_StaticInstanceLock);
90+
m_PimplGlobals->m_StaticDiffer = 0;
91+
}
92+
93+
8494
MersenneTwisterRandomVariateGenerator::MersenneTwisterRandomVariateGenerator()
8595
{
8696
SetSeed(121212);

Modules/Core/Common/test/itkMersenneTwisterRandomVariateGeneratorGTest.cxx

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,18 @@ TEST(MersenneTwisterRandomVariateGenerator, GetIntegerVariateReturnsSameAsStdMt1
5959
EXPECT_EQ(generator->GetIntegerVariate(), stdMt19937());
6060
}
6161
}
62+
63+
64+
TEST(MersenneTwisterRandomVariateGenerator, ResetNextSeed)
65+
{
66+
using GeneratorType = itk::Statistics::MersenneTwisterRandomVariateGenerator;
67+
68+
const auto globalGenerator = GeneratorType::GetInstance();
69+
ASSERT_NE(globalGenerator, nullptr);
70+
71+
GeneratorType::ResetNextSeed();
72+
const auto nextSeed = globalGenerator->GetNextSeed();
73+
74+
GeneratorType::ResetNextSeed();
75+
EXPECT_EQ(globalGenerator->GetNextSeed(), nextSeed);
76+
}

0 commit comments

Comments
 (0)