Skip to content

ising

Classical and transverse-field Ising model factory.

IsingModel dataclass

Bundled operators for a classical or transverse-field Ising Hamiltonian.

Qubits are labeled 0 .. num_qubits - 1. Couplings act on the edge set edges; single-site fields are on every qubit. Every ZZ edge and every single-site field is a LocalHamiltonian. A long-range edge, including the periodic wrap, names its two endpoints. Embedding that term puts identity on the sites in between.

Attributes:

  • full_hamiltonians (list[Hamiltonian]) –

    Hamiltonian terms in the full Hilbert space.

  • local_hamiltonians (list[LocalHamiltonian]) –

    One ZZ term per edge and one single-site field per qubit.

  • c_ops_full (list[Operator]) –

    Lindblad operators in the full space (empty; closed system).

  • c_ops_local (list[LocalOperator]) –

    Local Lindblad operators (empty; closed system).

  • psi0 (State) –

    Default initial state (all-|0⟩ classical, all-|+⟩ transverse).

  • e_ops (list[Operator]) –

    Per-site Z observables.

  • measurements (list[Measurement]) –

    Per-site Z expectations from shot counts, matching e_ops.

  • pauli_sum (PauliSum) –

    Full Hamiltonian as a sparse Pauli sum.

  • edges (list[tuple[int, int]]) –

    Resolved undirected interaction pairs (i, j) with i < j.

  • num_qubits (int) –

    Number of qubits.

  • J (float) –

    Coupling strength.

  • h (float) –

    Field strength.

  • field (FieldKind) –

    "classical" (Z field) or "transverse" (X field).

  • topology (TopologyKind) –

    "chain" or "custom" when edges was supplied.

  • boundary (BoundaryKind) –

    Boundary condition used for chain presets ("open" for custom).

Source code in shadowsim/models/ising.py
@dataclass(frozen=True)
class IsingModel:
    """Bundled operators for a classical or transverse-field Ising Hamiltonian.

    Qubits are labeled ``0 .. num_qubits - 1``. Couplings act on the edge set
    ``edges``; single-site fields are on every qubit. Every ZZ edge and every
    single-site field is a ``LocalHamiltonian``. A long-range edge, including
    the periodic wrap, names its two endpoints. Embedding that term puts
    identity on the sites in between.

    Attributes:
        full_hamiltonians: Hamiltonian terms in the full Hilbert space.
        local_hamiltonians: One ZZ term per edge and one single-site field per qubit.
        c_ops_full: Lindblad operators in the full space (empty; closed system).
        c_ops_local: Local Lindblad operators (empty; closed system).
        psi0: Default initial state (all-|0⟩ classical, all-|+⟩ transverse).
        e_ops: Per-site ``Z`` observables.
        measurements: Per-site ``Z`` expectations from shot counts, matching ``e_ops``.
        pauli_sum: Full Hamiltonian as a sparse Pauli sum.
        edges: Resolved undirected interaction pairs ``(i, j)`` with ``i < j``.
        num_qubits: Number of qubits.
        J: Coupling strength.
        h: Field strength.
        field: ``"classical"`` (Z field) or ``"transverse"`` (X field).
        topology: ``"chain"`` or ``"custom"`` when ``edges`` was supplied.
        boundary: Boundary condition used for chain presets (``"open"`` for custom).
    """

    full_hamiltonians: list[Hamiltonian]
    local_hamiltonians: list[LocalHamiltonian]
    c_ops_full: list[Operator]
    c_ops_local: list[LocalOperator]
    psi0: State
    e_ops: list[Operator]
    measurements: list[Measurement]
    pauli_sum: PauliSum
    edges: list[tuple[int, int]]
    num_qubits: int
    J: float
    h: float
    field: FieldKind
    topology: TopologyKind
    boundary: BoundaryKind

    @property
    def hamiltonian(self) -> Hamiltonian:
        """Return the combined full-space Hamiltonian."""
        return Hamiltonian(self.pauli_sum)

hamiltonian property

hamiltonian: Hamiltonian

Return the combined full-space Hamiltonian.

ising

ising(
    *,
    n_qubits: int,
    J: float = 1.0,
    h: float = 0.0,
    field: FieldKind = "transverse",
    topology: TopologyKind = _DEFAULT_TOPOLOGY,
    boundary: BoundaryKind = _DEFAULT_BOUNDARY,
    edges: Sequence[tuple[int, int]] | None = None,
) -> IsingModel

Build a classical or transverse-field Ising model.

Classical field

\(H = J \sum_{(i,j) \in E} Z_i Z_j + h \sum_i Z_i\)

Transverse field

\(H = J \sum_{(i,j) \in E} Z_i Z_j + h \sum_i X_i\)

Connectivity E comes from a 1D chain preset (topology="chain" with boundary="open" or "periodic") or from an explicit edges list.

Parameters:

  • n_qubits (int) –

    Number of qubits (at least 2).

  • J (float, default: 1.0 ) –

    ZZ coupling strength.

  • h (float, default: 0.0 ) –

    On-site field strength.

  • field (FieldKind, default: 'transverse' ) –

    "classical" for a Z field, "transverse" for an X field.

  • topology (TopologyKind, default: _DEFAULT_TOPOLOGY ) –

    Preset graph when edges is omitted (only "chain").

  • boundary (BoundaryKind, default: _DEFAULT_BOUNDARY ) –

    Chain boundary condition when edges is omitted.

  • edges (Sequence[tuple[int, int]] | None, default: None ) –

    Optional undirected interaction pairs. When set, overrides topology/boundary (which must remain at their defaults).

Returns:

  • IsingModel –

    An IsingModel with full/local Hamiltonians and default closed-system

  • IsingModel –

    simulation helpers.

Raises:

  • ValueError –

    On invalid size, field, topology, boundary, edges, or when both J and h are zero (no Hamiltonian terms).

Source code in shadowsim/models/ising.py
def ising(
    *,
    n_qubits: int,
    J: float = 1.0,
    h: float = 0.0,
    field: FieldKind = "transverse",
    topology: TopologyKind = _DEFAULT_TOPOLOGY,
    boundary: BoundaryKind = _DEFAULT_BOUNDARY,
    edges: Sequence[tuple[int, int]] | None = None,
) -> IsingModel:
    r"""Build a classical or transverse-field Ising model.

    **Classical field**

    \(H = J \sum_{(i,j) \in E} Z_i Z_j + h \sum_i Z_i\)

    **Transverse field**

    \(H = J \sum_{(i,j) \in E} Z_i Z_j + h \sum_i X_i\)

    Connectivity ``E`` comes from a 1D chain preset (``topology="chain"`` with
    ``boundary="open"`` or ``"periodic"``) or from an explicit ``edges`` list.

    Args:
        n_qubits: Number of qubits (at least 2).
        J: ZZ coupling strength.
        h: On-site field strength.
        field: ``"classical"`` for a Z field, ``"transverse"`` for an X field.
        topology: Preset graph when ``edges`` is omitted (only ``"chain"``).
        boundary: Chain boundary condition when ``edges`` is omitted.
        edges: Optional undirected interaction pairs. When set, overrides
            topology/boundary (which must remain at their defaults).

    Returns:
        An ``IsingModel`` with full/local Hamiltonians and default closed-system
        simulation helpers.

    Raises:
        ValueError: On invalid size, field, topology, boundary, edges, or when
            both ``J`` and ``h`` are zero (no Hamiltonian terms).
    """
    if not isinstance(n_qubits, int) or n_qubits < 2:
        raise ValueError(f"n_qubits must be an integer >= 2, got {n_qubits}")
    if field not in ("classical", "transverse"):
        raise ValueError(f"field must be 'classical' or 'transverse', got {field!r}")

    j_coup = float(J)
    h_field = float(h)
    if j_coup == 0.0 and h_field == 0.0:
        raise ValueError("J and h cannot both be zero")

    resolved_edges, resolved_topology, resolved_boundary = _resolve_edges(
        n_qubits=n_qubits,
        topology=topology,
        boundary=boundary,
        edges=edges,
    )

    field_pauli = "Z" if field == "classical" else "X"
    terms: dict[str, complex] = {}
    if j_coup != 0.0:
        for i, j in resolved_edges:
            label = _pauli_label(n_qubits, {i: "Z", j: "Z"})
            terms[label] = terms.get(label, 0.0) + j_coup
    if h_field != 0.0:
        for site in range(n_qubits):
            label = _pauli_label(n_qubits, {site: field_pauli})
            terms[label] = terms.get(label, 0.0) + h_field

    if not terms:
        raise ValueError("Ising Hamiltonian has no terms; provide edges with J != 0 or h != 0")

    pauli_sum = PauliSum(terms)

    local_hamiltonians: list[LocalHamiltonian] = []
    full_hamiltonians: list[Hamiltonian] = []

    zz_local = PauliString.from_string("ZZ").matrix()
    field_local = PauliString.from_string(field_pauli).matrix()

    if j_coup != 0.0:
        for i, j in resolved_edges:
            label = _pauli_label(n_qubits, {i: "Z", j: "Z"})
            full_hamiltonians.append(Hamiltonian(PauliSum({label: j_coup})))
            local_hamiltonians.append(LocalHamiltonian(j_coup * zz_local, [i, j]))

    if h_field != 0.0:
        for site in range(n_qubits):
            label = _pauli_label(n_qubits, {site: field_pauli})
            full_hamiltonians.append(Hamiltonian(PauliSum({label: h_field})))
            local_hamiltonians.append(LocalHamiltonian(h_field * field_local, [site]))

    if field == "classical":
        psi0_vec = np.zeros(2**n_qubits, dtype=np.complex128)
        psi0_vec[0] = 1.0
    else:
        plus = np.array([1.0, 1.0], dtype=np.complex128) / np.sqrt(2.0)
        psi0_vec = tensor([plus] * n_qubits)

    psi0 = State(psi0_vec, n_qubits)
    e_ops = [Operator(_pauli_label(n_qubits, {site: "Z"})) for site in range(n_qubits)]
    measurements = [
        Measurement((site,), '(counts["0"] - counts["1"]) / shots', f"expectation on {site}")
        for site in range(n_qubits)
    ]

    return IsingModel(
        full_hamiltonians=full_hamiltonians,
        local_hamiltonians=local_hamiltonians,
        c_ops_full=[],
        c_ops_local=[],
        psi0=psi0,
        e_ops=e_ops,
        measurements=measurements,
        pauli_sum=pauli_sum,
        edges=resolved_edges,
        num_qubits=n_qubits,
        J=j_coup,
        h=h_field,
        field=field,
        topology=resolved_topology,
        boundary=resolved_boundary,
    )