Hi, there
is there any way we could set up a seed for community_leiden? thanks
seems kwds does not support any other argument except resolution_parameter
Hi, there
is there any way we could set up a seed for community_leiden? thanks
seems kwds does not support any other argument except resolution_parameter
igraph uses Python’s built-in random
module for all random number generation. You can simply set a seed using random.seed()
directly before the community_leiden()
call.
If you don’t want to affect any other functions by setting a seed, you can save and restore the random state. I’m not very good with Python, but here’s something I cobbled together with some AI help using contextmanager:
from contextlib import contextmanager
import random
@contextmanager
def local_random(seed=None):
"""Temporarily set the random state, restoring it afterwards."""
state = random.getstate()
if seed is not None:
random.seed(seed)
try:
yield
finally:
random.setstate(state)
This allows you to run a function in a local random context, without affecting the random state, and optionally seed that local context. You will need to use
with local_random(seed=123):
g.community_leiden()
@tamas Is there anything similar to this that is built into Python? If not, why don’t we provide something similar to this local_random
as part of python-igraph? It would satisfy a common demand.
BTW this is modelled on Mathematica’s BlockRandom
, which I use frequently.
I couldn’t believe that there’s nothing like this built into Python’s random
module or NumPy but apparently there isn’t. It’s weird, but probably there are reasons for that:
async
functions where you could in theory have two or more of these context managers running in parallel such that they exit not exactly in the reverse order.I think that if you need reproducible results from igraph, a better approach would be to set igraph’s RNG to a local instance with an interface identical to the random
module, but I don’t mind adding such a function to igraph itself. It’s just that it really has nothing to do with igraph - it really belongs to Python’s standard library, either in the contextlib
module or in the random
module.
We have two reasonable options:
What do you prefer?
Just add it to the community detection tutorial. Thanks!
@Bea_Marton, can you please incorporate it, and use it in the example that shows the stochasticity of some methods?