Beispiel #1
0
def test_graph_conversions():
    igraph = ig.Graph.Star(6)
    g = Graph.from_igraph(igraph)
    assert g.n_nodes == igraph.vcount()
    assert g.edges() == igraph.get_edgelist()
    assert all(c == 0 for c in g._edge_colors)

    nxg = nx.star_graph(5)
    g = Graph.from_networkx(nxg)
    assert g.n_nodes == igraph.vcount()
    assert g.edges() == igraph.get_edgelist()
    assert all(c == 0 for c in g._edge_colors)

    igraph = ig.Graph()
    igraph.add_vertices(3)
    igraph.add_edges(
        [(0, 1), (1, 2)],
        attributes={
            "color": ["red", "blue"],
        },
    )
    with pytest.raises(ValueError, match="not all colors are integers"):
        _ = Graph.from_igraph(igraph)

    igraph = ig.Graph()
    igraph.add_vertices(3)
    igraph.add_edges(
        [(0, 1), (1, 2)],
        attributes={
            "color": [0, 1],
        },
    )
    g = Graph.from_igraph(igraph)
    assert g.edges(color=0) == [(0, 1)]
    assert g.edges(color=1) == [(1, 2)]
Beispiel #2
0
def test_edge_color_accessor():
    edges = [(0, 1, 0), (0, 3, 1), (1, 2, 1), (2, 3, 0)]
    g = Graph(edges=edges)

    assert edges == sorted(g.edges(return_color=True))

    g = Hypercube(4, 1)

    assert [(i, j, 0) for (i, j, _) in edges] == sorted(g.edges(return_color=True))
Beispiel #3
0
def test_is_bipartite():
    for i in range(1, 10):
        for j in range(1, i * i):
            x = nx.dense_gnm_random_graph(i, j)
            y = Graph.from_networkx(x)
            if len(x) == len(
                set((i for (i, j) in x.edges())) | set((j for (i, j) in x.edges()))
            ):
                assert y.is_bipartite() == nx.is_bipartite(x)
Beispiel #4
0
    def copy(self, *, dtype: Optional[DType] = None):
        if dtype is None:
            dtype = self.dtype

        graph = Graph(edges=[list(edge) for edge in self.edges])
        return Ising(hilbert=self.hilbert,
                     graph=graph,
                     J=self.J,
                     h=self.h,
                     dtype=dtype)
Beispiel #5
0
 def copy(self):
     graph = Graph(edges=[list(edge) for edge in self.edges])
     return BoseHubbard(
         hilbert=self.hilbert,
         graph=graph,
         J=self.J,
         U=self.U,
         V=self.V,
         mu=self.mu,
         dtype=self.dtype,
     )
Beispiel #6
0
def test_is_connected():
    for i in range(5, 10):
        for j in range(i + 1, i * i):
            x = nx.dense_gnm_random_graph(i, j)
            y = Graph.from_networkx(x)

            if len(x) == len(
                set((i for (i, j) in x.edges)) | set((j for (i, j) in x.edges))
            ):
                assert y.is_connected() == nx.is_connected(x)
            else:
                assert not nx.is_connected(x)
Beispiel #7
0
    Lattice,
    Edgeless,
    Triangular,
    Honeycomb,
    Kagome,
)
from netket.graph import _lattice
from netket.utils import group

from .. import common

pytestmark = common.skipif_mpi

graphs = [
    # star and tree
    Graph.from_igraph(ig.Graph.Star(5)),
    Graph.from_igraph(ig.Graph.Tree(n=3, children=2)),
    # Grid graphs
    Hypercube(length=10, n_dim=1, pbc=True),
    Hypercube(length=4, n_dim=2, pbc=True),
    Hypercube(length=5, n_dim=1, pbc=False),
    Grid([2, 2], pbc=False),
    Grid([4, 2], pbc=[True, False]),
    # lattice graphs
    Lattice(
        basis_vectors=[[1.0, 0.0], [1.0 / 2.0, math.sqrt(3) / 2.0]],
        extent=[3, 3],
        pbc=[False, False],
        site_offsets=[[0, 0]],
    ),
    Lattice(
Beispiel #8
0
 def copy(self):
     graph = Graph(edges=[list(edge) for edge in self.edges])
     return Ising(hilbert=self.hilbert, graph=graph, J=self.J, h=self.h)
Beispiel #9
0
    def __init__(
        self,
        hilbert: AbstractHilbert,
        graph: AbstractGraph,
        J: Union[float, Sequence[float]] = 1.0,
        sign_rule=None,
        *,
        acting_on_subspace: Union[List[int], int] = None,
    ):
        """
        Constructs an Heisenberg operator given a hilbert space and a graph providing the
        connectivity of the lattice.

        Args:
            hilbert: Hilbert space the operator acts on.
            graph: The graph upon which this hamiltonian is defined.
            J: The strength of the coupling. Default is 1.
               Can pass a sequence of coupling strengths with coloured graphs:
               edges of colour n will have coupling strength J[n]
            sign_rule: If True, Marshal's sign rule will be used. On a bipartite
                lattice, this corresponds to a basis change flipping the Sz direction
                at every odd site of the lattice. For non-bipartite lattices, the
                sign rule cannot be applied. Defaults to True if the lattice is
                bipartite, False otherwise.
                If a sequence of coupling strengths is passed, defaults to False
                and a matching sequence of sign_rule must be specified to override it
            acting_on_subspace: Specifies the mapping between nodes of the graph and
                Hilbert space sites, so that graph node :code:`i ∈ [0, ..., graph.n_nodes - 1]`,
                corresponds to :code:`acting_on_subspace[i] ∈ [0, ..., hilbert.n_sites]`.
                Must be a list of length `graph.n_nodes`. Passing a single integer :code:`start`
                is equivalent to :code:`[start, ..., start + graph.n_nodes - 1]`.

        Examples:
         Constructs a ``Heisenberg`` operator for a 1D system.

            >>> import netket as nk
            >>> g = nk.graph.Hypercube(length=20, n_dim=1, pbc=True)
            >>> hi = nk.hilbert.Spin(s=0.5, total_sz=0, N=g.n_nodes)
            >>> op = nk.operator.Heisenberg(hilbert=hi, graph=g)
            >>> print(op)
            Heisenberg(J=1.0, sign_rule=True; dim=20)
        """
        if isinstance(J, Sequence):
            # check that the number of Js matches the number of colours
            assert len(J) == max(graph.edge_colors) + 1

            if sign_rule is None:
                sign_rule = [False] * len(J)
            else:
                assert len(sign_rule) == len(J)
                for i in range(len(J)):
                    subgraph = Graph(edges=graph.edges(filter_color=i))
                    if sign_rule[i] and not subgraph.is_bipartite():
                        raise ValueError(
                            "sign_rule=True specified for a non-bipartite lattice"
                        )
        else:
            if sign_rule is None:
                sign_rule = graph.is_bipartite()
            elif sign_rule and not graph.is_bipartite():
                raise ValueError(
                    "sign_rule=True specified for a non-bipartite lattice")

        self._J = J
        self._sign_rule = sign_rule

        sz_sz = np.array([
            [1, 0, 0, 0],
            [0, -1, 0, 0],
            [0, 0, -1, 0],
            [0, 0, 0, 1],
        ])
        exchange = np.array([
            [0, 0, 0, 0],
            [0, 0, 2, 0],
            [0, 2, 0, 0],
            [0, 0, 0, 0],
        ])

        if isinstance(J, Sequence):
            bond_ops = [
                J[i] * (sz_sz - exchange if sign_rule[i] else sz_sz + exchange)
                for i in range(len(J))
            ]
            bond_ops_colors = list(range(len(J)))
        else:
            bond_ops = [
                J * (sz_sz - exchange if sign_rule else sz_sz + exchange)
            ]
            bond_ops_colors = []

        super().__init__(
            hilbert,
            graph,
            bond_ops=bond_ops,
            bond_ops_colors=bond_ops_colors,
            acting_on_subspace=acting_on_subspace,
        )