def test_create_py_random_state(): pyrs = random.Random assert isinstance(create_py_random_state(1), pyrs) assert isinstance(create_py_random_state(None), pyrs) assert isinstance(create_py_random_state(pyrs(1)), pyrs) pytest.raises(ValueError, create_py_random_state, 'a') np = pytest.importorskip('numpy') rs = np.random.RandomState nprs = PythonRandomInterface assert isinstance(create_py_random_state(np.random), nprs) assert isinstance(create_py_random_state(rs(1)), nprs) # test default rng input assert isinstance(PythonRandomInterface(), nprs)
def _random_state(func, *args, **kwargs): # Parse the decorator arguments. try: random_state_arg = args[random_state_index] except TypeError as e: raise nx.NetworkXError("random_state_index must be an integer") from e except IndexError as e: raise nx.NetworkXError("random_state_index is incorrect") from e # Create a numpy.random.RandomState instance random_state = create_py_random_state(random_state_arg) # args is a tuple, so we must convert to list before modifying it. new_args = list(args) new_args[random_state_index] = random_state return func(*new_args, **kwargs)
def _random_state(func, *args, **kwargs): # Parse the decorator arguments. try: random_state_arg = args[random_state_index] except TypeError: raise nx.NetworkXError("random_state_index must be an integer") except IndexError: raise nx.NetworkXError("random_state_index is incorrect") # Create a numpy.random.RandomState instance random_state = create_py_random_state(random_state_arg) # args is a tuple, so we must convert to list before modifying it. new_args = list(args) new_args[random_state_index] = random_state return func(*new_args, **kwargs)
def random_ordered_tree(n, seed=None, directed=False): """ Creates a random ordered tree Parameters ---------- n : int A positive integer representing the number of nodes in the tree. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. directed : bool if the edges are one-way Returns ------- networkx.OrderedDiGraph | networkx.OrderedGraph Example ------- >>> import networkx as nx >>> assert len(random_ordered_tree(n=1, seed=0).nodes) == 1 >>> assert len(random_ordered_tree(n=2, seed=0).nodes) == 2 >>> assert len(random_ordered_tree(n=3, seed=0).nodes) == 3 >>> otree = random_ordered_tree(n=5, seed=3, directed=True) >>> print(forest_str(otree)) ╙── 0 └─╼ 1 └─╼ 4 ├─╼ 2 └─╼ 3 """ from networkx.utils import create_py_random_state rng = create_py_random_state(seed) # Create a random undirected tree create_using = nx.OrderedDiGraph if directed else nx.OrderedGraph otree = random_tree(n, seed=rng, create_using=create_using) return otree
def random_balanced_sequence(n, seed=None, item_type="chr", container_type="auto", open_to_close=None): r""" Creates a random balanced sequence for testing / benchmarks Parameters ---------- n : int A positive integer representing the number of nodes in the tree. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. open_to_close : dict | None if specified, updates existing open_to_close with tokens from this sequence. item_type: str the type of sequence returned (see `item_type` in :func:`tree_to_seq` for details) can also be "paren", which is a special case that returns a nested set of parenthesis. container_type : str Determines the container_type type. Can be "auto", "list", "tuple", or "str". If "auto" tries to choose the best given the input data. Returns ------- Tuple[(str | Tuple), Dict[str, str]] The first item is the sequence itself the second item is the open_to_close mappings. Example ------- >>> # Demo the various sequence encodings that we might use >>> seq, open_to_close = random_balanced_sequence(4, seed=1, item_type="chr") >>> print("seq = {!r}".format(seq)) seq = '\x00\x02\x04\x05\x03\x06\x07\x01' >>> seq, open_to_close = random_balanced_sequence(4, seed=1, item_type="number") >>> print("seq = {!r}".format(seq)) seq = (1, 2, 3, -3, -2, 4, -4, -1) >>> seq, open_to_close = random_balanced_sequence(10, seed=1, item_type="paren") >>> print("seq = {!r}".format(seq)) seq = '([[{{[]{[]}}{}()}]])' """ from torch_liberator._nx_ext_v2.tree_embedding import tree_to_seq from torch_liberator._nx_ext_v2.utils import random_ordered_tree from networkx.utils import create_py_random_state # Create a random otree and then convert it to a balanced sequence rng = create_py_random_state(seed) if open_to_close is None: open_to_close = {} # To create a random balanced sequences we simply create a random ordered # tree and convert it to a sequence tree = random_ordered_tree(n, seed=rng, directed=True) if item_type == "paren": # special case pool = "[{(" for node in tree.nodes: tree.nodes[node]["label"] = rng.choice(pool) open_to_close.update({"[": "]", "{": "}", "(": ")"}) seq, open_to_close, *_ = tree_to_seq( tree, open_to_close=open_to_close, item_type="label", container_type=container_type, ) else: seq, open_to_close, *_ = tree_to_seq( tree, open_to_close=open_to_close, item_type=item_type, container_type=container_type, ) return seq, open_to_close