Skip to content

Commit

Permalink
ENH: Add MersenneTwisterRandomVariateGenerator::ResetNextSeed()
Browse files Browse the repository at this point in the history
Allows generating a reproducible sequence of pseudo-random numbers.
  • Loading branch information
N-Dekker committed Oct 2, 2023
1 parent 75b9967 commit 2119f76
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,11 @@ class ITKCommon_EXPORT MersenneTwisterRandomVariateGenerator : public RandomVari
static Pointer
GetInstance();

/** Resets the internal data that is used to calculate the next seed. (Does not reset the initial seed.) Allows
* generating a reproducible sequence of pseudo-random numbers. */
static void
ResetNextSeed();

/** Length of state vector */
static constexpr IntegerType StateVectorLength = 624;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,16 @@ MersenneTwisterRandomVariateGenerator::GetInstance()
return m_PimplGlobals->m_StaticInstance;
}


void
MersenneTwisterRandomVariateGenerator::ResetNextSeed()
{
itkInitGlobalsMacro(PimplGlobals);
const std::lock_guard<std::recursive_mutex> lockGuard(m_PimplGlobals->m_StaticInstanceLock);
m_PimplGlobals->m_StaticDiffer = 0;
}


MersenneTwisterRandomVariateGenerator::MersenneTwisterRandomVariateGenerator()
{
SetSeed(121212);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,18 @@ TEST(MersenneTwisterRandomVariateGenerator, GetIntegerVariateReturnsSameAsStdMt1
EXPECT_EQ(generator->GetIntegerVariate(), stdMt19937());
}
}


TEST(MersenneTwisterRandomVariateGenerator, ResetNextSeed)
{
using GeneratorType = itk::Statistics::MersenneTwisterRandomVariateGenerator;

const auto globalGenerator = GeneratorType::GetInstance();
ASSERT_NE(globalGenerator, nullptr);

GeneratorType::ResetNextSeed();
const auto nextSeed = globalGenerator->GetNextSeed();

GeneratorType::ResetNextSeed();
EXPECT_EQ(globalGenerator->GetNextSeed(), nextSeed);
}

0 comments on commit 2119f76

Please sign in to comment.