Teleport a qubit from start to end using an ancilla qubit
437980
def teleport(start_index, end_index, ancilla_index):
    
    program = make_bell_pair(end_index, ancilla_index)

    ro = program.declare('ro', memory_size=3)

    # do the teleportation
    program.inst(CNOT(start_index, ancilla_index))
    program.inst(H(start_index))

    # measure the results and store them in classical registers [0] and [1]
    program.measure(start_index, ro[0])
    program.measure(ancilla_index, ro[1])

    program.if_then(ro[1], X(2))
    program.if_then(ro[0], Z(2))

    program.measure(end_index, ro[2])

    print(program)
    return program
319836
def bit_reversal(qubits: List[int]) -> Program:
    
    p = Program()
    n = len(qubits)
    for i in range(int(n / 2)):
        p.inst(SWAP(qubits[i], qubits[-i - 1]))
    return p
721077
function bitop(operation, destkey /* key1, keyN, req */) {
  var keys = slice.call(arguments, 2)
    , req = typeof keys[keys.length - 1] === 'object' ? keys.pop() : null
    , buffers = []
    , plen
    , ind
    , len = 0
    , out
    , buf
    , byte
    , i
    , j
    , v;

  // unary operation, ensure keys length is one
  if(operation === BITOP.NOT) {
    keys = keys.slice(0, 1);
  }

  for(i = 0;i < keys.length;i++) {
    v = this.getKey(keys[i], req);
    if(v === undefined) {
      buffers.push(EMPTY);
    }else if(typeof v === 'number') {
      buffers.push(new Buffer([v]));
    }else if(typeof v === 'string') {
      buffers.push(new Buffer(v));
    /* istanbul ignore else: not testing unsupported types */
    }else if(Buffer.isBuffer(v)) {
      buffers.push(v);
    }

    // last buffer added, used to get longest buffer length
    buf = buffers[buffers.length - 1];

    // previous length so we can get index of longest buffer
    plen = len;

    // calculate longest buffer length
    len = Math.max(len, buf.length);

    // find index of longest buffer
    if(len > plen) {
      ind = buffers.length - 1;
    }
  }

  // use the longest one as the start buffer
  // and copy so as not to modify the original
  // key data if it was already a buffer
  buf = buffers.splice(ind, 1)[0];
  out = new Buffer(buf);

  // give us something for the outer loop to
  // iterate over
  if(operation === BITOP.NOT) {
    buffers.push(out);
  }

  for(i = 0;i < buffers.length;i++) {
    buf = buffers[i];
    for(j = 0;j < out.length;j++) {
      if(operation === BITOP.NOT) {
        out[j] = ~out[j];
        continue;
      }
      byte = j < buf.length ? buf[j] : 0;
      switch(operation) {
        case BITOP.AND:
          out[j] &= byte;
          break;
        case BITOP.OR:
          out[j] |= byte;
          break;
        case BITOP.XOR:
          out[j] ^= byte;
          break;
      }
    }
  }

  if(len) this.setKey(destkey, out, undefined, undefined, undefined, req);
  return len;
}
1071793
def main(self, spin, data):
        
        data  = data.decode(self.encoding)
        field = re.match(RFC_REG, data)
        
        if not field:
            return
    
        prefix  = self.extract_prefix(field.group('prefix'))
        command = field.group('command').upper()
        args    = self.extract_args(field.group('arguments'))
        spawn(spin, command, *(prefix + args))
579100
def default_rotations(*qubits):
    
    for gates in cartesian_product(TOMOGRAPHY_GATES.keys(), repeat=len(qubits)):
        tomography_program = Program()
        for qubit, gate in izip(qubits, gates):
            tomography_program.inst(gate(qubit))
        yield tomography_program
499504
def _convert_local_operator_to_qutip(expr, full_space, mapping):
    """"""
    n = full_space.dimension
    if full_space != expr.space:
        all_spaces = full_space.local_factors
        own_space_index = all_spaces.index(expr.space)
        return qutip.tensor(
            *([qutip.qeye(s.dimension)
               for s in all_spaces[:own_space_index]] +
              [convert_to_qutip(expr, expr.space, mapping=mapping), ] +
              [qutip.qeye(s.dimension)
               for s in all_spaces[own_space_index + 1:]])
        )
    if isinstance(expr, Create):
        return qutip.create(n)
    elif isinstance(expr, Jz):
        return qutip.jmat((expr.space.dimension-1)/2., "z")
    elif isinstance(expr, Jplus):
        return qutip.jmat((expr.space.dimension-1)/2., "+")
    elif isinstance(expr, Jminus):
        return qutip.jmat((expr.space.dimension-1)/2., "-")
    elif isinstance(expr, Destroy):
        return qutip.destroy(n)
    elif isinstance(expr, Phase):
        arg = complex(expr.operands[1]) * arange(n)
        d = np_cos(arg) + 1j * np_sin(arg)
        return qutip.Qobj(np_diag(d))
    elif isinstance(expr, Displace):
        alpha = expr.operands[1]
        return qutip.displace(n, alpha)
    elif isinstance(expr, Squeeze):
        eta = expr.operands[1]
        return qutip.displace(n, eta)
    elif isinstance(expr, LocalSigma):
        j = expr.j
        k = expr.k
        if isinstance(j, str):
            j = expr.space.basis_labels.index(j)
        if isinstance(k, str):
            k = expr.space.basis_labels.index(k)
        ket = qutip.basis(n, j)
        bra = qutip.basis(n, k).dag()
        return ket * bra
    else:
        raise ValueError("Cannot convert '%s' of type %s"
                         % (str(expr), type(expr)))
1259628
def ghz_state(qubits: Union[int, Qubits]) -> State:
    """"""
    N, qubits = qubits_count_tuple(qubits)
    ket = np.zeros(shape=[2] * N)
    ket[(0, ) * N] = 1 / sqrt(2)
    ket[(1, ) * N] = 1 / sqrt(2)
    return State(ket, qubits)
189406
def _time_dependent_to_qutip(
        op, full_space=None, time_symbol=symbols("t", real=True),
        convert_as='pyfunc'):
    """"""
    if full_space is None:
        full_space = op.space
    if time_symbol in op.free_symbols:
        op = op.expand()
        if isinstance(op, OperatorPlus):
            result = []
            for o in op.operands:
                if time_symbol not in o.free_symbols:
                    if len(result) == 0:
                        result.append(convert_to_qutip(o,
                                                       full_space=full_space))
                    else:
                        result[0] += convert_to_qutip(o, full_space=full_space)
            for o in op.operands:
                if time_symbol in o.free_symbols:
                    result.append(_time_dependent_to_qutip(o, full_space,
                                  time_symbol, convert_as))
            return result
        elif (
                isinstance(op, ScalarTimesOperator) and
                isinstance(op.coeff, ScalarValue)):
            if convert_as == 'pyfunc':
                func_no_args = lambdify(time_symbol, op.coeff.val)
                if {time_symbol, } == op.coeff.free_symbols:
                    def func(t, args):
                        # args are ignored for increased efficiency, since we
                        # know there are no free symbols except t
                        return func_no_args(t)
                else:
                    def func(t, args):
                        return func_no_args(t).subs(args)
                coeff = func
            elif convert_as == 'str':
                # a bit of a hack to replace imaginary unit
                # TODO: we can probably use one of the sympy code generation
                # routines, or lambdify with 'numexpr' to implement this in a
                # more robust way
                coeff = re.sub("I", "(1.0j)", str(op.coeff.val))
            else:
                raise ValueError(("Invalid value '%s' for `convert_as`, must "
                                  "be one of 'str', 'pyfunc'") % convert_as)
            return [convert_to_qutip(op.term, full_space), coeff]
        else:
            raise ValueError("op cannot be expressed in qutip. It must have "
                             "the structure op = sum_i f_i(t) * op_i")
    else:
        return convert_to_qutip(op, full_space=full_space)
301230
def map_gate(gate: Gate, args: Sequence[Qubits]) -> Circuit:
    
    circ = Circuit()

    for qubits in args:
        circ += gate.relabel(qubits)

    return circ
1097303
def reversal_circuit(qubits: Qubits) -> Circuit:
    """"""
    N = len(qubits)
    circ = Circuit()
    for n in range(N // 2):
        circ += SWAP(qubits[n], qubits[N-1-n])
    return circ
251579
def quartic_paired_acquaintance_strategy(
    qubit_pairs: Iterable[Tuple[ops.Qid, ops.Qid]]
    ) -> Tuple[circuits.Circuit, Sequence[ops.Qid]]:
    

    qubit_pairs = tuple(
            cast(Tuple[ops.Qid, ops.Qid], tuple(qubit_pair))
            for qubit_pair in qubit_pairs)
    qubits = qubit_pairs_to_qubit_order(qubit_pairs)
    n_qubits = len(qubits)
    swap_network = SwapNetworkGate((1,) * n_qubits, 2)(*qubits)
    strategy = circuits.Circuit.from_ops(swap_network,
            device=UnconstrainedAcquaintanceDevice)
    expose_acquaintance_gates(strategy)
    for i in reversed(range(0, n_qubits, 2)):
        moment = ops.Moment([acquaint(*qubits[j: j + 4])
                             for j in range(i % 4, n_qubits - 3, 4)])
        strategy.insert(2 * i, moment)
    return strategy, qubits
96984
def set_io_qubits(qubit_count):
    """"""
    input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
    output_qubit = cirq.GridQubit(qubit_count, 0)
    return (input_qubits, output_qubit)
955503
def default_channel_ops(nqubits):
    
    for gates in cartesian_product(TOMOGRAPHY_GATES.values(), repeat=nqubits):
        yield qt.tensor(*gates)
1141481
def operates_on(self, qubits: Iterable[raw_types.Qid]) -> bool:
        
        return any(q in qubits for q in self.qubits)
1308555
def plot(self, qubit_subset=None):
        
        import matplotlib.pyplot as plt
        prob_dict = self.get_outcome_probs()
        if qubit_subset:
            sub_dict = {}
            qubit_num = len(self)
            for i in qubit_subset:
                if i > (2**qubit_num - 1):
                    raise IndexError("Index {} too large for {} qubits.".format(i, qubit_num))
                else:
                    sub_dict[get_bitstring_from_index(i, qubit_num)] = prob_dict[get_bitstring_from_index(i, qubit_num)]
            prob_dict = sub_dict
        plt.bar(range(len(prob_dict)), prob_dict.values(), align='center', color='#6CAFB7')
        plt.xticks(range(len(prob_dict)), prob_dict.keys())
        plt.show()
472885
def qubit_pairs(args, length):
    """"""
    if not isinstance(args, tuple):
        raise ValueError("Control and target qubits pair(s) are required.")
    if len(args) != 2:
        raise ValueError("Control and target qubits pair(s) are required.")
    controls = list(slicing(args[0], length))
    targets = list(slicing(args[1], length))
    if len(controls) != len(targets):
        raise ValueError("The number of control qubits and target qubits are must be same.")
    for c, z in zip(controls, targets):
        if c == z:
            raise ValueError("Control qubit and target qubit are must be different.")
    return zip(controls, targets)
1347339
def on(self,
           *qubits: raw_types.Qid) -> 'SingleQubitPauliStringGateOperation':
        
        if len(qubits) != 1:
            raise ValueError(
                'Expected a single qubit, got <{!r}>.'.format(qubits))
        from cirq.ops.pauli_string import SingleQubitPauliStringGateOperation
        return SingleQubitPauliStringGateOperation(self, qubits[0])