Ejemplo n.º 1
0
    def star_decoder(self, for_enc=None, as_dict=False):
        r"""
        Returns a tuple of a decoding Clifford and a :class:`qecc.PauliList`
        specifying the recovery operation to perform as a function of the result
        of a :math:`Z^{\otimes{n - k}}` measurement on the ancilla register.
        
        For syndromes corresponding to errors of weight greater than the distance,
        the relevant element of the recovery list will be set to
        :obj:`qecc.Unspecified`.
        
        :param for_enc: If not ``None``, specifies to use a given Clifford
            operator as the encoder, instead of the first element yielded by
            :meth:`encoding_cliffords`.
        :param bool as_dict: If ``True``, returns a dictionary from recovery
            operators to syndromes that indicate that recovery.
        """
        def error_to_pauli(error):
            if error == p.I.as_clifford():
                return "I"
            if error == p.X.as_clifford():
                return "X"
            if error == p.Y.as_clifford():
                return "Y"
            if error == p.Z.as_clifford():
                return "Z"

        if for_enc is None:
            encoder = next(self.encoding_cliffords())
        else:
            encoder = for_enc
        decoder = encoder.inv()

        errors = pc.PauliList(p.eye_p(self.nq)) + pc.PauliList(
            p.paulis_by_weight(self.nq, self.n_correctable))

        syndrome_dict = defaultdict(lambda: Unspecified)
        syndrome_meas = [
            p.elem_gen(self.nq, idx, 'Z')
            for idx in range(self.nq_logical, self.nq)
        ]

        for error in errors:
            effective_gate = decoder * error.as_clifford() * encoder
            # FIXME: the following line emulates measurement until we have a real
            #        measurement simulation method.
            syndrome = tuple(
                [effective_gate(meas).ph / 2 for meas in syndrome_meas])

            recovery = "".join([
                # FIXME: the following is a broken hack to get the phases on the logical qubit register.
                error_to_pauli(
                    c.Clifford([effective_gate.xout[idx][idx]],
                               [effective_gate.zout[idx][idx]]))
                for idx in range(self.nq_logical)
            ])

            # For degenerate codes, the syndromes can collide, so long as we
            # correct the same way for each.
            if syndrome in syndrome_dict and syndrome_dict[
                    syndrome] != recovery:
                raise RuntimeError(
                    'Syndrome {} has collided.'.format(syndrome))

            syndrome_dict[syndrome] = recovery

        if as_dict:
            outdict = dict()
            keyfn = lambda syndrome_recovery: syndrome_recovery[1]
            data = sorted(list(syndrome_dict.items()), key=keyfn)
            for recovery, syndrome_group in it.groupby(data, keyfn):
                outdict[recovery] = [syn[0] for syn in syndrome_group]

            return decoder, outdict

        else:
            recovery_list = pc.PauliList(
                syndrome_dict[syndrome]
                for syndrome in it.product(list(range(2)),
                                           repeat=self.n_constraints))

            return decoder, recovery_list
Ejemplo n.º 2
0
 def star_decoder(self, for_enc=None, as_dict=False):
     r"""
     Returns a tuple of a decoding Clifford and a :class:`qecc.PauliList`
     specifying the recovery operation to perform as a function of the result
     of a :math:`Z^{\otimes{n - k}}` measurement on the ancilla register.
     
     For syndromes corresponding to errors of weight greater than the distance,
     the relevant element of the recovery list will be set to
     :obj:`qecc.Unspecified`.
     
     :param for_enc: If not ``None``, specifies to use a given Clifford
         operator as the encoder, instead of the first element yielded by
         :meth:`encoding_cliffords`.
     :param bool as_dict: If ``True``, returns a dictionary from recovery
         operators to syndromes that indicate that recovery.
     """
     def error_to_pauli(error):
         if error == p.I.as_clifford():
             return "I"
         if error == p.X.as_clifford():
             return "X"
         if error == p.Y.as_clifford():
             return "Y"
         if error == p.Z.as_clifford():
             return "Z"
     
     if for_enc is None:
         encoder = self.encoding_cliffords().next()
     else:
         encoder = for_enc
     decoder = encoder.inv()
     
     errors = pc.PauliList(p.eye_p(self.nq)) + pc.PauliList(p.paulis_by_weight(self.nq, self.n_correctable))
     
     syndrome_dict = defaultdict(lambda: Unspecified)
     syndrome_meas = [p.elem_gen(self.nq, idx, 'Z') for idx in range(self.nq_logical, self.nq)]
             
     for error in errors:
         effective_gate = decoder * error.as_clifford() * encoder
         # FIXME: the following line emulates measurement until we have a real
         #        measurement simulation method.
         syndrome = tuple([effective_gate(meas).ph / 2 for meas in syndrome_meas])
         
         recovery = "".join([
             # FIXME: the following is a broken hack to get the phases on the logical qubit register.
             error_to_pauli(c.Clifford([effective_gate.xout[idx][idx]], [effective_gate.zout[idx][idx]]))
             for idx in range(self.nq_logical)
         ])
         
         # For degenerate codes, the syndromes can collide, so long as we
         # correct the same way for each.
         if syndrome in syndrome_dict and syndrome_dict[syndrome] != recovery:
             raise RuntimeError('Syndrome {} has collided.'.format(syndrome))
             
         syndrome_dict[syndrome] = recovery
     
     if as_dict:
         outdict = dict()
         keyfn = lambda (syndrome, recovery): recovery
         data = sorted(syndrome_dict.items(), key=keyfn)
         for recovery, syndrome_group in it.groupby(data, keyfn):
             outdict[recovery] = [syn[0] for syn in syndrome_group]
         
         return decoder, outdict
         
     else:
         recovery_list = pc.PauliList(syndrome_dict[syndrome] for syndrome in it.product(range(2), repeat=self.n_constraints))
         
         return decoder, recovery_list
Ejemplo n.º 3
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))