def _non_adjacent_filter(self, cmd, qubit_graph, flip=False):
    """A ProjectQ filter to identify when swaps are needed on a graph

    This flags any gates that act on two non-adjacent qubits with respect to
    the qubit_graph that has been given

    Args:
        self(Dummy): Dummy parameter to meet function specification.
        cmd(projectq.command): Command to be checked for decomposition into
            additional swap gates.
        qubit_graph(Graph): Graph object specifying connectivity of
            qubits. The values of the nodes of this graph are unique qubit ids.
        flip(Bool): Flip for switching if identifying a gate is in this class
            by true or false.  Designed to meet the specification of ProjectQ
            InstructionFilter and DecompositionRule with one function.

    Returns:
        bool: When flip is False, this returns True when a 2 qubit command
            acts on non-adjacent qubits or when it acts only on a single qubit.
            This is reversed when flip is used.

    """
    if qubit_graph is None:
        return True ^ flip

    total_qubits = (cmd.control_qubits +
                    [item for qureg in cmd.qubits for item in qureg])

    # Check for non-connected gate on 2 qubits
    if ((len(total_qubits) == 1) or
            (len(total_qubits) == 2 and
             qubit_graph.is_adjacent(
                 qubit_graph.find_index(total_qubits[0].id),
                 qubit_graph.find_index(total_qubits[1].id)))):
        return True ^ flip
    return False ^ flip