def test_callable_input(self, graph):
        """Tests if function returns the correct output given a custom method set by the user"""
        objective_return = (0, [0])

        def custom_method(*args, **kwargs):
            """Mockup of custom-method function fed to ``find_dense``"""
            return objective_return

        result = resize.resize_subgraphs(
            subgraphs=[[0, 1]], graph=graph, target=4, resize_options={"method": custom_method}
        )

        assert result == objective_return
    def test_valid_input(self, graph, monkeypatch, methods):
        """Tests if function returns the correct output under normal conditions. The resizing
        method is here monkey patched to return a known result."""
        objective_return = (0, [0])

        def custom_method(*args, **kwargs):
            """Mockup of custom-method function fed to ``resize_subgraphs``"""
            return objective_return

        with monkeypatch.context() as m:
            m.setattr(resize, "METHOD_DICT", {methods: custom_method})

            result = resize.resize_subgraphs(
                subgraphs=[[0, 1]], graph=graph, target=4, resize_options={"method": methods}
            )

        assert result == objective_return
def test_resize_subgraphs_integration(graph, target, methods):
    """Test if function returns resized subgraphs of the correct form given an input list of
    variable sized subgraphs specified by ``subgraphs``. The output should be a list of ``len(
    10)``, each element containing itself a list corresponding to a subgraph that should be of
    ``len(target)``. Each element in the subraph list should correspond to a node of the input
    graph. Note that graph nodes are numbered in this test as [0, 1, 4, 9, ...] (i.e., squares of
    the usual list) as a simple mapping to explore that the resized subgraph returned is still a
    valid subgraph."""
    graph = nx.relabel_nodes(graph, lambda x: x ** 2)
    graph_nodes = set(graph.nodes)
    s_relabeled = [(np.array(s) ** 2).tolist() for s in subgraphs]
    resized = resize.resize_subgraphs(
        subgraphs=s_relabeled, graph=graph, target=target, resize_options={"method": methods}
    )
    resized = np.array(resized)
    dims = resized.shape
    assert len(dims) == 2
    assert dims[0] == len(s_relabeled)
    assert dims[1] == target
    assert all(set(sample).issubset(graph_nodes) for sample in resized)
Пример #4
0
def random_search(
    graph: nx.Graph, nodes: int, iterations: int = 1, options: Optional[dict] = None
) -> Tuple[float, list]:
    """Random search algorithm for finding dense subgraphs of a given size.

    The algorithm proceeds by sampling subgraphs according to the
    :func:`~strawberryfields.apps.graph.sample.sample_subgraphs`. The resultant subgraphs
    are resized using :func:`~strawberryfields.apps.graph.resize.resize_subgraphs` to
    be of size ``nodes``. The densest subgraph is then selected among all the resultant
    subgraphs. Specified``options`` must be of the form given in :func:`find_dense`.

    Args:
        graph (nx.Graph): the input graph
        nodes (int): the size of desired dense subgraph
        iterations (int): number of iterations to use in algorithm
        options (dict[str, dict[str, Any]]): dict-of-dicts specifying options in different parts
            of heuristic search algorithm; defaults to :const:`OPTIONS_DEFAULTS`

    Returns:
        tuple[float, list]: the density and list of nodes corresponding to the densest subgraph
        found
    """
    options = {**OPTIONS_DEFAULTS, **(options or {})}

    samples = sample.sample_subgraphs(
        graph=graph,
        nodes=nodes,
        samples=iterations,
        sample_options=options["sample"],
        backend_options=options["backend"],
    )

    samples = resize.resize_subgraphs(
        subgraphs=samples, graph=graph, target=nodes, resize_options=options["resize"]
    )

    density_and_samples = [(nx.density(graph.subgraph(s)), s) for s in samples]

    return max(density_and_samples)
 def test_target_big(self, graph):
     """Test if function raises a ``ValueError`` when a too large number is given for
     ``target`` """
     with pytest.raises(ValueError, match="target must be greater than two and less than"):
         resize.resize_subgraphs(subgraphs=[[0, 1]], graph=graph, target=5)
 def test_target_wrong_type(self, graph):
     """Test if function raises a ``TypeError`` when incorrect type given for ``target`` """
     with pytest.raises(TypeError, match="target must be an integer"):
         resize.resize_subgraphs(subgraphs=[[0, 1]], graph=graph, target=[])