Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement the RNGScope class for RAII-based RNG control. #4

Merged
merged 1 commit into from
Jul 18, 2024

Conversation

LTLA
Copy link
Contributor

@LTLA LTLA commented Jul 15, 2024

Inspired by the Rcpp class of the same name. Usage is demonstrated in examples/ex_rng_scope.cpp; it enables people to easily set the seed for reproducible execution of various RNG-dependent igraph functions. For example:

{
     ig::RNGScope scope(1000); // sets PCG32 with seed 1000.
     // do something with igraph functions that might use the RNG.
} // previous RNG is restored upon exiting the scope.

Multiple RNGScopes can be safely nested within each other's lifetimes, so users don't have to worry about whether they are interfering with an igraph RNG defined elsewhere if they want reproducible execution of their own code.

void foo() {
    ig::RNGScope scope1(2000, &igraph_rng_mt19937); // sets MT with seed 2000
    // do something with igraph functions that might use the RNG.
}

int main() {
    ig::RNGScope scope2; // uses PCG32 with the default seed
    // do something with igraph functions that might use the RNG

    foo(); // uses 'scope1' internally but sets it back to 'scope2' on exit.

    // do more things with the 'scope2' RNG.
    return 0;
}

{
ig::RNGScope filled(1000);
std::cout << "New RNG scope:" << std::endl;
std::cout << " Draw from [0, 100]: " << igraph_rng_get_integer(igraph_rng_default(), 0, 100) << std::endl;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you please use RNG_INTEGER and the similar macros in all places in the example?

@szhorvat
Copy link
Member

szhorvat commented Jul 18, 2024

I am not sure I'm 100% happy with the details of this yet, but everything's in flux at the moment anyway. I'll comment more when I get the chance. I'm merging now in the interest of progress and testability. Polishing is possible later.

@szhorvat szhorvat merged commit 0a64adf into igraph:main Jul 18, 2024
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants