示例#1
0
 def as_clifford(self):
     """
     If this circuit is composed entirely of Clifford operators, converts it
     to a :class:`qecc.Clifford` instance representing the action of the
     entire circuit. If the circuit is not entirely Clifford gates, this method
     raises a :obj:`RuntimeError`.
     """
     if not all(loc.is_clifford for loc in self):
         raise RuntimeError('All locations must be Clifford gates in order to represent a circuit as a Clifford operator.')
         
     nq = self.nq
     return reduce(mul, (loc.as_clifford(nq) for loc in reversed(self)), cc.eye_c(nq))
示例#2
0
    def as_clifford(self):
        """
        If this circuit is composed entirely of Clifford operators, converts it
        to a :class:`qecc.Clifford` instance representing the action of the
        entire circuit. If the circuit is not entirely Clifford gates, this method
        raises a :obj:`RuntimeError`.
        """
        if not all(loc.is_clifford for loc in self):
            raise RuntimeError(
                'All locations must be Clifford gates in order to represent a circuit as a Clifford operator.'
            )

        nq = self.nq
        return reduce(mul, (loc.as_clifford(nq) for loc in reversed(self)),
                      cc.eye_c(nq))
示例#3
0
 def as_clifford(self, nq):
     return cc.eye_c(nq)
示例#4
0
 def as_clifford(self, nq):
     return cc.eye_c(nq)
示例#5
0
class Location(object):
    """
    Represents a gate, wait, measurement or preparation location in a
    circuit.
    
    Note that currently, only gate locations are implemented.
    
    :param kind: The kind of location to be created. Each kind is an
        abbreviation drawn from ``Location.KIND_NAMES``, or is the index in
        ``Location.KIND_NAMES`` corresponding to the desired location kind.
    :type kind: int or str
    :param qubits: Indicies of the qubits on which this location acts.
    :type qubits: tuple of ints.
    """

    ## PRIVATE CLASS CONSTANTS ##
    _CLIFFORD_GATE_KINDS = [
        'I', 'X', 'Y', 'Z', 'H', 'R_pi4', 'CNOT', 'CZ', 'SWAP'
    ]

    _CLIFFORD_GATE_FUNCS = {
        'I': lambda nq, idx: cc.eye_c(nq),
        'X': lambda nq, idx: pc.elem_gen(nq, idx, 'X').as_clifford(),
        'Y': lambda nq, idx: pc.elem_gen(nq, idx, 'Y').as_clifford(),
        'Z': lambda nq, idx: pc.elem_gen(nq, idx, 'Z').as_clifford(),
        'H': cc.hadamard,
        'R_pi4': cc.phase,
        'CNOT': cc.cnot,
        'CZ': cc.cz,
        'SWAP': cc.swap
    }

    _QCVIEWER_NAMES = {
        'I': 'I',  # This one is implemented by a gate definition
        # included by Circuit.as_qcviewer().
        'X': 'X',
        'Y': 'Y',
        'Z': 'Z',
        'H': 'H',
        'R_pi4': 'P',
        'CNOT': 'tof',
        'CZ': 'Z',
        'SWAP': 'swap'
    }

    ## PUBLIC CLASS CONSTANTS ##

    #: Names of the kinds of locations used by QuaEC.
    KIND_NAMES = sum([_CLIFFORD_GATE_KINDS], [])

    ## INITIALIZER ##

    def __init__(self, kind, *qubits):
        if isinstance(kind, int):
            self._kind = kind
        elif isinstance(kind, str):
            self._kind = self.KIND_NAMES.index(kind)
        else:
            raise TypeError("Location kind must be an int or str.")

        #if not all(isinstance(q, int) for q in qubits):
        #    raise TypeError('Qubit indices must be integers. Got {} instead, which is of type {}.'.format(
        #        *(iter((q, type(q)) for q in qubits if not isinstance(q, int)).next())
        #    ))

        try:
            self._qubits = tuple(map(int, qubits))
        except TypeError as e:
            raise TypeError('Qubit integers must be int-like.')
        self._is_clifford = bool(self.kind in self._CLIFFORD_GATE_KINDS)

    ## REPRESENTATION METHODS ##

    def __str__(self):
        return "    {:<4}    {}".format(self.kind,
                                        ' '.join(map(str, self.qubits)))

    def __repr__(self):
        return "<{} Location on qubits {}>".format(self.kind, self.qubits)

    def __hash__(self):
        return hash((self._kind, ) + self.qubits)

    ## IMPORT METHODS ##

    @staticmethod
    def from_quasm(source):
        """
        Returns a :class:`qecc.Location` initialized from a QuASM-formatted line.
        
        :type str source: A line of QuASM code specifying a location.
        :rtype: :class:`qecc.Location`
        :returns: The location represented by the given QuASM source.
        """
        parts = source.split()
        return Location(parts[0], *map(int, parts[1:]))

    ## PROPERTIES ##

    @property
    def kind(self):
        """
        Returns a string defining which kind of location this instance
        represents. Guaranteed to be a string that is an element of
        ``Location.KIND_NAMES``.
        """
        return self.KIND_NAMES[self._kind]

    @property
    def qubits(self):
        """
        Returns a tuple of ints describing which qubits this location acts upon.
        """
        return self._qubits

    @property
    def nq(self):
        """
        Returns the number of qubits in the smallest circuit that can contain
        this location without relabeling qubits. For a :class:`qecc.Location`
        ``loc``, this property is defined as ``1 + max(loc.nq)``.
        """
        return 1 + max(self.qubits)

    @property
    def is_clifford(self):
        """
        Returns ``True`` if and only if this location represents a gate drawn
        from the Clifford group.
        """
        return self._is_clifford

    @property
    def wt(self):
        """
        Returns the number of qubits on which this location acts.
        """
        return len(self.qubits)

    ## SIMULATION METHODS ##

    def as_clifford(self, nq=None):
        """
        If this location represents a Clifford gate, returns the action of that
        gate. Otherwise, a :obj:`RuntimeError` is raised.
        
        :param int nq: Specifies how many qubits to represent this location as
            acting upon. If not specified, defaults to the value of the ``nq``
            property.
        :rtype: :class:`qecc.Clifford`
        """
        if not self.is_clifford:
            raise RuntimeError("Location must be a Clifford gate.")
        else:
            if nq is None:
                nq = self.nq
            elif nq < self.nq:
                raise ValueError(
                    'nq must be greater than or equal to the nq property.')

            return self._CLIFFORD_GATE_FUNCS[self.kind](nq, *self.qubits)

    ## EXPORT METHODS ##

    def as_qcviewer(self, qubit_names=None):
        """
        Returns a representation of this location in a format suitable for
        inclusion in a QCViewer file. 
            
        :param qubit_names: If specified, the given aliases will be used for the
            qubits involved in this location when exporting to QCViewer.
            Defaults to "q1", "q2", etc.
        :rtype: str
        
        Note that the identity (or "wait") location requires the following to be
        added to QCViewer's ``gateLib``::
        
            NAME wait
            DRAWNAME "1"
            SYMBOL I
            1 , 0
            0 , 1
        """
        # FIXME: link to QCViewer in the docstring here.
        return '    {gatename}    {gatespec}\n'.format(
            gatename=self._QCVIEWER_NAMES[self.kind],
            gatespec=qubits_str(self.qubits, qubit_names),
        )

    ## OTHER METHODS ##

    def relabel_qubits(self, relabel_dict):
        """
        Returns a new location related to this one by a relabeling of the
        qubits. The relabelings are to be indicated by a dictionary that
        specifies what each qubit index is to be mapped to.
        
        >>> import qecc as q
        >>> loc = q.Location('CNOT', 0, 1)
        >>> print loc
            CNOT    0 1
        >>> print loc.relabel_qubits({1: 2})
            CNOT    0 2
            
        :param dict relabel_dict: If `i` is a key of `relabel_dict`, then qubit
            `i` will be replaced by `relabel_dict[i]` in the returned location.
        :rtype: :class:`qecc.Location`
        :returns: A new location with the qubits relabeled as 
            specified by `relabel_dict`.
        """
        return Location(
            self.kind,
            *tuple(relabel_dict[i] if i in relabel_dict else i
                   for i in self.qubits))