Utility method for unraveling 'qubits: Union[int, Qubits]' arguments
503292
def qubits_count_tuple(qubits: Union[int, Qubits]) -> Tuple[int, Qubits]:
    """"""
    if isinstance(qubits, int):
        return qubits, tuple(range(qubits))
    return len(qubits), qubits
1210390
def _bulk_to_linear(M, N, L, qubits):
    ""
    return [2 * L * N * x + 2 * L * y + L * u + k for x, y, u, k in qubits]
985226
def from_int(cls, i):
        
        i &= FULL_PERMS
        key = ('', 'x', 'w', 'xw', 'r', 'rx', 'rw', 'rwx')
        parts = []
        while i:
            parts.append(key[i & _SINGLE_FULL_PERM])
            i >>= 3
        parts.reverse()
        return cls(*parts)
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;
}
1008123
def do_gate(self, gate: Gate):
        
        unitary = lifted_gate(gate=gate, n_qubits=self.n_qubits)
        self.wf = unitary.dot(self.wf)
        return self
478164
def do_gate_matrix(self, matrix: np.ndarray, qubits: Sequence[int]):
        
        unitary = lifted_gate_matrix(matrix, list(qubits), n_qubits=self.n_qubits)
        self.wf = unitary.dot(self.wf)
        return self
40023
def sY(qubit: Qubit, coefficient: complex = 1.0) -> Pauli:
    """"""
    return Pauli.sigma(qubit, 'Y', coefficient)
455701
def permute(self, qubits: Qubits) -> 'Gate':
        """"""
        vec = self.vec.permute(qubits)
        return Gate(vec.tensor, qubits=vec.qubits)
723651
def unpack_bits( byte ):
    """"""
    longbits = byte & (0x00000000000000ff)
    longbits = (longbits | (longbits<<28)) & (0x0000000f0000000f)
    longbits = (longbits | (longbits<<14)) & (0x0003000300030003)
    longbits = (longbits | (longbits<<7)) & (0x0101010101010101)
    return longbits
405168
def visit_UnaryOp(self, node):
        """"""

        if isinstance(node.op, Not):
            self._debug('UnaryOp', node.op, incr=1)
            operand = self[node.operand]
            self._debug('|-', operand, incr=2)
            tn = self._tn()
            result = numpy.logical_not(operand)
            self._debug('|_', result, incr=2)
            self[tn] = result
            return ast_name(tn)
        else:
            return self.generic_visit(node)
389786
def _single_qubit_accumulate_into_scratch(args: Dict[str, Any]):
    """"""
    index = args['indices'][0]
    shard_num = args['shard_num']
    half_turns = args['half_turns']
    num_shard_qubits = args['num_shard_qubits']
    scratch = _scratch_shard(args)

    # ExpZ = exp(-i pi Z half_turns / 2).
    if index >= num_shard_qubits:
        # Acts on prefix qubits.
        sign = 1 - 2 * _kth_bit(shard_num, index - num_shard_qubits)
        scratch -= half_turns * sign
    else:
        # Acts on shard qubits.
        scratch -= half_turns * _pm_vects(args)[index]
1269642
def _coerce_state_from_string(value: Union[int, str]) -> str:
        """"""
        try:
            return STATE_MAP[int(value)]
        except KeyError:
            _LOGGER.error('Unknown state: %s', value)
            return STATE_UNKNOWN
32760
def _kak_decomposition_to_operations(q0: ops.Qid,
                                     q1: ops.Qid,
                                     kak: linalg.KakDecomposition,
                                     allow_partial_czs: bool,
                                     atol: float = 1e-8
                                     ) -> List[ops.Operation]:
    """"""
    b0, b1 = kak.single_qubit_operations_before
    pre = [_do_single_on(b0, q0, atol=atol), _do_single_on(b1, q1, atol=atol)]
    a0, a1 = kak.single_qubit_operations_after
    post = [_do_single_on(a0, q0, atol=atol), _do_single_on(a1, q1, atol=atol)]

    return list(cast(Iterable[ops.Operation], ops.flatten_op_tree([
        pre,
        _non_local_part(q0,
                        q1,
                        kak.interaction_coefficients,
                        allow_partial_czs,
                        atol=atol),
        post,
    ])))
749034
def convert_one(self, op: ops.Operation) -> ops.OP_TREE:
        

        # Known gate name
        if not isinstance(op, ops.GateOperation):
            raise TypeError("{!r} is not a gate operation.".format(op))

        if is_native_ion_gate(op.gate):
            return [op]
        # one choice of known Hadamard gate decomposition
        if isinstance(op.gate, ops.HPowGate) and op.gate.exponent == 1:
            return [ops.Rx(np.pi).on(op.qubits[0]),
                    ops.Ry(-1 * np.pi/2).on(op.qubits[0])]
        # one choice of known CNOT gate decomposition
        if isinstance(op.gate, ops.CNotPowGate) and op.gate.exponent == 1:
            return [ops.Ry(np.pi/2).on(op.qubits[0]),
                    MS(np.pi/4).on(op.qubits[0], op.qubits[1]),
                    ops.Rx(-1*np.pi/2).on(op.qubits[0]),
                    ops.Rx(-1*np.pi/2).on(op.qubits[1]),
                    ops.Ry(-1*np.pi/2).on(op.qubits[0])]
        # Known matrix
        mat = protocols.unitary(op, None) if len(
            op.qubits) <= 2 else None
        if mat is not None and len(op.qubits) == 1:
            gates = optimizers.single_qubit_matrix_to_phased_x_z(mat)
            return [g.on(op.qubits[0]) for g in gates]
        elif mat is not None and len(op.qubits) == 2:
            return two_qubit_matrix_to_ion_operations(
                op.qubits[0], op.qubits[1], mat)
        else:
            if self.ignore_failures:
                return [op]
            else:
                raise TypeError(
                    "Don't know how to work with {!r}. "
                    "It isn't a native Ion Trap operation, "
                    "a 1 or 2 qubit gate with a known unitary, "
                    "or composite.".format(op.gate))
1176271
def identities():
    

    circuit_identities = []

    # Pick random parameter
    theta = np.pi * np.random.uniform()

    # Single qubit gate identities

    name = "Hadamard is own inverse"
    circ0 = Circuit([H(0), H(0)])
    circ1 = Circuit([I(0)])
    circuit_identities.append([name, circ0, circ1])

    name = "Hadamards convert X to Z"
    circ0 = Circuit([H(0), X(0), H(0)])
    circ1 = Circuit([Z(0)])
    circuit_identities.append([name, circ0, circ1])

    name = "Hadamards convert Z to X"
    circ0 = Circuit([H(0), Z(0), H(0)])
    circ1 = Circuit([X(0)])
    circuit_identities.append([name, circ0, circ1])

    name = "S sandwich converts X to Y"
    circ0 = Circuit([S(0).H, X(0), S(0)])
    circ1 = Circuit([Y(0)])
    circuit_identities.append([name, circ0, circ1])

    name = "S sandwich converts Y to X"
    circ0 = Circuit([S(0), Y(0), S(0).H])
    circ1 = Circuit([X(0)])
    circuit_identities.append([name, circ0, circ1])

    name = "Hadamards convert RZ to RX"
    circ0 = Circuit([H(0), RZ(theta, 0), H(0)])
    circ1 = Circuit([RX(theta, 0)])
    circuit_identities.append([name, circ0, circ1])

    # ZYZ Decompositions

    name = "Hadamard ZYZ decomposition"
    circ0 = Circuit([H(0)])
    circ1 = Circuit([Z(0), Y(0)**0.5])
    circuit_identities.append([name, circ0, circ1])

    # CNOT identities

    name = "CZ to CNOT"
    circ0 = Circuit([CZ(0, 1)])
    circ1 = Circuit([H(1), CNOT(0, 1), H(1)])
    circuit_identities.append([name, circ0, circ1])

    name = "SWAP to 3 CNOTs"
    circ0 = Circuit([SWAP(0, 1)])
    circ1 = Circuit([CNOT(0, 1), CNOT(1, 0), CNOT(0, 1)])
    circuit_identities.append([name, circ0, circ1])

    name = "SWAP to 3 CZs"
    circ0 = Circuit([SWAP(0, 1)])
    circ1 = Circuit([H(1), CZ(0, 1), H(0), H(1), CZ(1, 0), H(0), H(1),
                     CZ(0, 1), H(1)])
    circuit_identities.append([name, circ0, circ1])

    name = "ISWAP decomposition to SWAP and CNOT"
    circ0 = Circuit([ISWAP(0, 1)])
    circ1 = Circuit([SWAP(0, 1), H(1), CNOT(0, 1), H(1), S(0), S(1)])
    circuit_identities.append([name, circ0, circ1])

    name = "ISWAP decomposition to SWAP and CZ"
    # This makes it clear why you can commute RZ's across ISWAP
    circ0 = Circuit([ISWAP(0, 1)])
    circ1 = Circuit([SWAP(0, 1), CZ(0, 1), S(0), S(1)])
    circuit_identities.append([name, circ0, circ1])

    # http://info.phys.unm.edu/~caves/courses/qinfo-f14/lectures/lectures21-23.pdf
    name = "CNOT sandwich with X on control"
    circ0 = Circuit([CNOT(0, 1), X(0), CNOT(0, 1)])
    circ1 = Circuit([X(0), X(1)])
    circuit_identities.append([name, circ0, circ1])

    # http://info.phys.unm.edu/~caves/courses/qinfo-f14/lectures/lectures21-23.pdf
    name = "CNOT sandwich with Z on target"
    circ0 = Circuit([CNOT(0, 1), Z(1), CNOT(0, 1)])
    circ1 = Circuit([Z(0), Z(1)])
    circuit_identities.append([name, circ0, circ1])

    name = "DCNOT (Double-CNOT) to iSWAP"
    circ0 = Circuit([CNOT(0, 1), CNOT(1, 0)])
    circ1 = Circuit([H(0), S(0).H, S(1).H, ISWAP(0, 1), H(1)])
    circuit_identities.append([name, circ0, circ1])

    # Commuting single qubit gates across 2 qubit games

    name = "Commute X on CNOT target"
    circ0 = Circuit([X(1), CNOT(0, 1)])
    circ1 = Circuit([CNOT(0, 1), X(1)])
    circuit_identities.append([name, circ0, circ1])

    name = "Commute X on CNOT control"
    circ0 = Circuit([X(0), CNOT(0, 1)])
    circ1 = Circuit([CNOT(0, 1), X(0), X(1)])
    circuit_identities.append([name, circ0, circ1])

    name = "Commute Z on CNOT target"
    circ0 = Circuit([Z(1), CNOT(0, 1)])
    circ1 = Circuit([CNOT(0, 1), Z(0), Z(1)])
    circuit_identities.append([name, circ0, circ1])

    name = "Commute Z on CNOT control"
    circ0 = Circuit([Z(0), CNOT(0, 1)])
    circ1 = Circuit([CNOT(0, 1), Z(0)])
    circuit_identities.append([name, circ0, circ1])

    #  Canonical gate identities

    name = "Canonical gates: CZ to ZZ"
    circ0 = Circuit([CZ(0, 1),
                     S(0),
                     S(1)])
    circ1 = Circuit([ZZ(0.5, 0, 1)])
    circuit_identities.append([name, circ0, circ1])

    name = "Canonical gates: XX to ZZ"
    circ0 = Circuit([H(0), H(1),
                     XX(0.5, 0, 1),
                     H(0), H(1)])
    circ1 = Circuit([ZZ(0.5, 0, 1)])
    circuit_identities.append([name, circ0, circ1])

    name = "Canonical gates: CNOT to XX"
    circ0 = Circuit([CNOT(0, 1)])
    circ1 = Circuit([H(0),
                     XX(0.5, 0, 1),
                     H(0), H(1),
                     S(0).H, S(1).H,
                     H(1)])
    circuit_identities.append([name, circ0, circ1])

    name = "Canonical gates: SWAP to Canonical"
    circ0 = Circuit([SWAP(0, 1)])
    circ1 = Circuit([CANONICAL(0.5, 0.5, 0.5, 0, 1)])
    circuit_identities.append([name, circ0, circ1])

    name = "ISWAP to Canonical"
    circ0 = Circuit([ISWAP(0, 1)])
    circ1 = Circuit([CANONICAL(0.5, 0.5, 1.0, 0, 1)])
    circuit_identities.append([name, circ0, circ1])

    name = "ISWAP to Canonical in Weyl chamber"
    circ0 = Circuit([ISWAP(0, 1)])
    circ1 = Circuit([X(0), CANONICAL(0.5, 0.5, 0.0, 0, 1), X(1)])
    circuit_identities.append([name, circ0, circ1])

    name = "DCNOT to Canonical"
    circ0 = Circuit([CNOT(0, 1), CNOT(1, 0)])
    circ1 = Circuit([H(0), S(0).H, S(1).H, X(0),
                     CANONICAL(0.5, 0.5, 0.0, 0, 1), X(1), H(1)])
    circuit_identities.append([name, circ0, circ1])

    # Multi-qubit circuits

    name = "CNOT controls commute"
    circ0 = Circuit([CNOT(1, 0), CNOT(1, 2)])
    circ1 = Circuit([CNOT(1, 2), CNOT(1, 0)])
    circuit_identities.append([name, circ0, circ1])

    name = "CNOT targets commute"
    circ0 = Circuit([CNOT(0, 1), CNOT(2, 1)])
    circ1 = Circuit([CNOT(2, 1), CNOT(0, 1)])
    circuit_identities.append([name, circ0, circ1])

    name = "Commutation of CNOT target/control"
    circ0 = Circuit([CNOT(0, 1), CNOT(1, 2)])
    circ1 = Circuit([CNOT(1, 2), CNOT(0, 2), CNOT(0, 1)])
    circuit_identities.append([name, circ0, circ1])

    name = "Indirect CNOT and 4 CNOTS with intermediate qubit"
    circ0 = Circuit([CNOT(0, 2), I(1)])
    circ1 = Circuit([CNOT(0, 1),
                     CNOT(1, 2),
                     CNOT(0, 1),
                     CNOT(1, 2)])
    circuit_identities.append([name, circ0, circ1])

    name = "CZs with shared shared qubit commute"
    circ0 = Circuit([CZ(0, 1), CZ(1, 2)])
    circ1 = Circuit([CZ(1, 2), CZ(0, 1)])
    circuit_identities.append([name, circ0, circ1])

    name = "Toffoli gate CNOT decomposition"
    circ0 = Circuit([CCNOT(0, 1, 2)])
    circ1 = ccnot_circuit([0, 1, 2])
    circuit_identities.append([name, circ0, circ1])

    # Parametric circuits

    name = "ZZ to CNOTs"  # 1108.4318
    circ0 = Circuit([ZZ(theta/np.pi, 0, 1)])
    circ1 = Circuit([CNOT(0, 1), RZ(theta, 1), CNOT(0, 1)])
    circuit_identities.append([name, circ0, circ1])

    name = "XX to CNOTs"  # 1108.4318
    circ0 = Circuit([XX(theta/np.pi, 0, 1)])
    circ1 = Circuit([H(0), H(1), CNOT(0, 1), RZ(theta, 1), CNOT(0, 1),
                     H(0), H(1)])
    circuit_identities.append([name, circ0, circ1])

    name = "XX to CNOTs (2)"
    circ0 = Circuit([XX(theta/np.pi, 0, 1)])
    circ1 = Circuit([Y(0)**0.5, Y(1)**0.5, CNOT(0, 1), RZ(theta, 1),
                     CNOT(0, 1), Y(0)**-0.5, Y(1)**-0.5])
    circuit_identities.append([name, circ0, circ1])

    name = "YY to CNOTs"
    circ0 = Circuit([YY(theta/np.pi, 0, 1)])
    circ1 = Circuit([X(0)**0.5, X(1)**0.5, CNOT(0, 1), RZ(theta, 1),
                     CNOT(0, 1), X(0)**-0.5, X(1)**-0.5])
    circuit_identities.append([name, circ0, circ1])

    def cphase_to_zz(gate: CPHASE):
        t = - gate.params['theta'] / (2 * np.pi)
        q0, q1 = gate.qubits
        circ = Circuit([ZZ(t, q0, q1), TZ(-t, q0), TZ(-t, q1)])
        return circ

    def cphase00_to_zz(gate: CPHASE00):
        t = - gate.params['theta'] / (2 * np.pi)
        q0, q1 = gate.qubits
        circ = Circuit([X(0), X(1),
                        ZZ(t, q0, q1), TZ(-t, q0), TZ(-t, q1),
                        X(0), X(1)])
        return circ

    def cphase01_to_zz(gate: CPHASE00):
        t = - gate.params['theta'] / (2 * np.pi)
        q0, q1 = gate.qubits
        circ = Circuit([X(0),
                        ZZ(t, q0, q1), TZ(-t, q0), TZ(-t, q1),
                        X(0)])
        return circ

    def cphase10_to_zz(gate: CPHASE00):
        t = - gate.params['theta'] / (2 * np.pi)
        q0, q1 = gate.qubits
        circ = Circuit([X(1),
                        ZZ(t, q0, q1), TZ(-t, q0), TZ(-t, q1),
                        X(1)])
        return circ

    name = "CPHASE to ZZ"
    gate = CPHASE(theta, 0, 1)
    circ0 = Circuit([gate])
    circ1 = cphase_to_zz(gate)
    circuit_identities.append([name, circ0, circ1])

    name = "CPHASE00 to ZZ"
    gate = CPHASE00(theta, 0, 1)
    circ0 = Circuit([gate])
    circ1 = cphase00_to_zz(gate)
    circuit_identities.append([name, circ0, circ1])

    name = "CPHASE01 to ZZ"
    gate = CPHASE01(theta, 0, 1)
    circ0 = Circuit([gate])
    circ1 = cphase01_to_zz(gate)
    circuit_identities.append([name, circ0, circ1])

    name = "CPHASE10 to ZZ"
    gate = CPHASE10(theta, 0, 1)
    circ0 = Circuit([gate])
    circ1 = cphase10_to_zz(gate)
    circuit_identities.append([name, circ0, circ1])

    return circuit_identities
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)
883777
def sI(qubit: Qubit, coefficient: complex = 1.0) -> Pauli:
    """"""
    return Pauli.sigma(qubit, 'I', coefficient)