Instruction:
Can you generate a brief explanation for the following Python 3 code
def _create_initial_solution(self) -> _STATE:

        def extract_sequences() -> List[List[GridQubit]]:
            """Creates list of sequcenes for initial state.

            Returns:
              List of lists of sequences constructed on the chip.
            """
            seqs = []
            prev = None
            seq = None
            for node in self._c:
                if prev is None:
                    seq = [node]
                else:
                    if node in self._c_adj[prev]:
                        # Expand current sequence.
                        seq.append(node)
                    else:
                        # Create new sequence, there is no connection between
                        # nodes.
                        seqs.append(seq)
                        seq = [node]
                prev = node
            if seq:
                seqs.append(seq)
            return seqs

        def assemble_edges() -> Set[EDGE]:
            """Creates list of edges for initial state.

            Returns:
              List of all possible edges.
            """
            nodes_set = set(self._c)
            edges = set()
            for n in self._c:
                if above(n) in nodes_set:
                    edges.add(self._normalize_edge((n, above(n))))
                if right_of(n) in nodes_set:
                    edges.add(self._normalize_edge((n, right_of(n))))
            return edges

        return extract_sequences(), assemble_edges()

Response: Creates an initial solution based on the chip description.


Instruction:
Here you have a function in Python 3, explain what it does
def _normalize_edge(self, edge: EDGE) -> EDGE:

        def lower(n: GridQubit, m: GridQubit) -> bool:
            return n.row < m.row or (n.row == m.row and n.col < m.col)

        n1, n2 = edge
        return (n1, n2) if lower(n1, n2) else (n2, n1)

Response: Normalizes an edge to be unique and return it.


Instruction:
Create a Python 3 function for
picking a random edge from the set of edges.

Response:
def _choose_random_edge(self, edges: Set[EDGE]) -> Optional[EDGE]:
        """Picks random edge from the set of edges.

        Args:
          edges: Set of edges to pick from.

        Returns:
          Random edge from the supplied set, or None for empty set.
        """
        if edges:
            index = self._rand.randint(len(edges))
            for e in edges:
                if not index:
                    return e
                index -= 1
        return None


Instruction:
Can you implement a function in Python 3 that
runs an annealing sequence search.

Response:
def place_line(self,
                   device: 'cirq.google.XmonDevice',
                   length: int) -> GridQubitLineTuple:
        """Runs line sequence search.

        Args:
            device: Chip description.
            length: Required line length.

        Returns:
            List of linear sequences on the chip found by simulated annealing
            method.
        """
        seqs = AnnealSequenceSearch(device, self.seed).search(self.trace_func)
        return GridQubitLineTuple.best_of(seqs, length)


Instruction:
Given the following Python 3 function, write the documentation
def _decompose_inside_control(self,
                                  target1: raw_types.Qid,
                                  control: raw_types.Qid,
                                  target2: raw_types.Qid
                                  ) -> op_tree.OP_TREE:
        """A decomposition assuming the control separates the targets.

        target1: ─@─X───────T──────@────────@─────────X───@─────X^-0.5─
                  │ │              │        │         │   │
        control: ─X─@─X─────@─T^-1─X─@─T────X─@─X^0.5─@─@─X─@──────────
                      │     │        │        │         │   │
        target2: ─────@─H─T─X─T──────X─T^-1───X─T^-1────X───X─H─S^-1───
        """
        a, b, c = target1, control, target2
        yield common_gates.CNOT(a, b)
        yield common_gates.CNOT(b, a)
        yield common_gates.CNOT(c, b)
        yield common_gates.H(c)
        yield common_gates.T(c)
        yield common_gates.CNOT(b, c)
        yield common_gates.T(a)
        yield common_gates.T(b)**-1
        yield common_gates.T(c)
        yield common_gates.CNOT(a, b)
        yield common_gates.CNOT(b, c)
        yield common_gates.T(b)
        yield common_gates.T(c)**-1
        yield common_gates.CNOT(a, b)
        yield common_gates.CNOT(b, c)
        yield pauli_gates.X(b)**0.5
        yield common_gates.T(c)**-1
        yield common_gates.CNOT(b, a)
        yield common_gates.CNOT(b, c)
        yield common_gates.CNOT(a, b)
        yield common_gates.CNOT(b, c)
        yield common_gates.H(c)
        yield common_gates.S(c)**-1
        yield pauli_gates.X(a)**-0.5

Response: A decomposition assuming the control separates the targets.


Instruction:
Explain what the following Python 3 code does
def _decompose_outside_control(self,
                                   control: raw_types.Qid,
                                   near_target: raw_types.Qid,
                                   far_target: raw_types.Qid
                                   ) -> op_tree.OP_TREE:
        """A decomposition assuming one of the targets is in the middle.

        control: ───T──────@────────@───@────────────@────────────────
                           │        │   │            │
           near: ─X─T──────X─@─T^-1─X─@─X────@─X^0.5─X─@─X^0.5────────
                  │          │        │      │         │
            far: ─@─Y^-0.5─T─X─T──────X─T^-1─X─T^-1────X─S─────X^-0.5─
        """
        a, b, c = control, near_target, far_target

        t = common_gates.T
        sweep_abc = [common_gates.CNOT(a, b),
                     common_gates.CNOT(b, c)]

        yield common_gates.CNOT(c, b)
        yield pauli_gates.Y(c)**-0.5
        yield t(a), t(b), t(c)
        yield sweep_abc
        yield t(b) ** -1, t(c)
        yield sweep_abc
        yield t(c) ** -1
        yield sweep_abc
        yield t(c) ** -1
        yield pauli_gates.X(b)**0.5
        yield sweep_abc
        yield common_gates.S(c)
        yield pauli_gates.X(b)**0.5
        yield pauli_gates.X(c)**-0.5

Response: A decomposition assuming one of the targets is in the middle.


Instruction:
Can you tell what is the following Python 3 function doing
def mixture(
    val: Any,
    default: Any = RaiseTypeErrorIfNotProvided) -> Sequence[Tuple[float, Any]]:
    """Return a sequence of tuples representing a probabilistic combination.

    A mixture is described by an iterable of tuples of the form

        (probability of object, object)

    The probability components of the tuples must sum to 1.0 and be between
    0 and 1 (inclusive).

    Args:
        val: The value whose mixture is being computed.
        default: A default value if val does not support mixture.

    Returns:
        An iterable of tuples of size 2. The first element of the tuple is a
        probability (between 0 and 1) and the second is the object that occurs
        with that probability in the mixture. The probabilities will sum to 1.0.
    """

    getter = getattr(val, '_mixture_', None)
    result = NotImplemented if getter is None else getter()

    if result is not NotImplemented:
        return result
    if default is not RaiseTypeErrorIfNotProvided:
        return default

    if getter is None:
        raise TypeError(
            "object of type '{}' has no _mixture_ method.".format(type(val)))

    raise TypeError("object of type '{}' does have a _mixture_ method, "
                    "but it returned NotImplemented.".format(type(val)))

Response: Returns a sequence of tuples representing a mixture of objects.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def has_mixture(val: Any) -> bool:
    getter = getattr(val, '_has_mixture_', None)
    result = NotImplemented if getter is None else getter()
    if result is not NotImplemented:
        return result

    # No _has_mixture_ function, use _mixture_ instead
    return mixture(val, None) is not None

Response: Returns whether the value has a mixture representation.


Instruction:
Given the following Python 3 function, write the documentation
def mixture_channel(
    val: Any,
    default: Any = RaiseTypeErrorIfNotProvided) -> Sequence[
    Tuple[float, np.ndarray]]:
    """Return a sequence of tuples for a channel that is a mixture of unitaries.

    In contrast to `mixture` this method falls back to `unitary` if `_mixture_`
    is not implemented.

    A mixture channel is described by an iterable of tuples of the form

        (probability of unitary, unitary)

    The probability components of the tuples must sum to 1.0 and be between
    0 and 1 (inclusive) and the `unitary` must be a unitary matrix.

    Args:
        val: The value whose mixture_channel is being computed.
        default: A default value if val does not support mixture.

    Returns:
        An iterable of tuples of size 2. The first element of the tuple is a
        probability (between 0 and 1) and the second is the unitary that occurs
        with that probability. The probabilities will sum to 1.0.
    """
    mixture_getter = getattr(val, '_mixture_', None)
    result = NotImplemented if mixture_getter is None else mixture_getter()
    if result is not NotImplemented:
        return result

    unitary_getter = getattr(val, '_unitary_', None)
    result = NotImplemented if unitary_getter is None else unitary_getter()
    if result is not NotImplemented:
        return ((1.0, result),)

    if default is not RaiseTypeErrorIfNotProvided:
        return default

    if mixture_getter is None and unitary_getter is None:
        raise TypeError(
            "object of type '{}' has no _mixture_ or _unitary_ method."
                .format(type(val)))

    raise TypeError("object of type '{}' does have a _mixture_ or _unitary_ "
                    "method, but it returned NotImplemented.".format(type(val)))

Response: Returns a sequence of tuples for a mixture of unitaries.


Instruction:
Write a Python 3 function for
returning whether the value has a mixture channel representation.

Response:
def has_mixture_channel(val: Any) -> bool:
    """Returns whether the value has a mixture channel representation.

    In contrast to `has_mixture` this method falls back to checking whether
    the value has a unitary representation via `has_channel`.

    Returns:
        If `val` has a `_has_mixture_` method and its result is not
        NotImplemented, that result is returned. Otherwise, if `val` has a
        `_has_unitary_` method and its results is not NotImplemented, that
        result is returned. Otherwise, if the value has a `_mixture_` method
        that is not a non-default value, True is returned. Returns False if none
        of these functions.
    """
    mixture_getter = getattr(val, '_has_mixture_', None)
    result = NotImplemented if mixture_getter is None else mixture_getter()
    if result is not NotImplemented:
        return result

    result = has_unitary(val)
    if result is not NotImplemented and result:
        return result

    # No _has_mixture_ or _has_unitary_ function, use _mixture_ instead.
    return mixture_channel(val, None) is not None


Instruction:
Write a Python 3 script for
validating that the mixture s tuple are valid probabilities.

Response:
def validate_mixture(supports_mixture: SupportsMixture):
    """Validates that the mixture's tuple are valid probabilities."""
    mixture_tuple = mixture(supports_mixture, None)
    if mixture_tuple is None:
        raise TypeError('{}_mixture did not have a _mixture_ method'.format(
            supports_mixture))

    def validate_probability(p, p_str):
        if p < 0:
            raise ValueError('{} was less than 0.'.format(p_str))
        elif p > 1:
            raise ValueError('{} was greater than 1.'.format(p_str))

    total = 0.0
    for p, val in mixture_tuple:
        validate_probability(p, '{}\'s probability'.format(str(val)))
        total += p
    if not np.isclose(total, 1.0):
        raise ValueError('Sum of probabilities of a mixture was not 1.0')


Instruction:
Create a Python 3 function to
compute the display states for the given base - class and returns the result.

Response:
def compute_displays(
        self,
        program: Union[circuits.Circuit, schedules.Schedule],
        param_resolver: study.ParamResolver = study.ParamResolver({}),
        qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
        initial_state: Union[int, np.ndarray] = 0,
    ) -> study.ComputeDisplaysResult:
        """Computes displays in the supplied Circuit or Schedule.

        Args:
            program: The circuit or schedule to simulate.
            param_resolver: Parameters to run with the program.
            qubit_order: Determines the canonical ordering of the qubits used
                to define the order of amplitudes in the wave function.
            initial_state: If an int, the state is set to the computational
                basis state corresponding to this state. Otherwise  if this
                is a np.ndarray it is the full initial state. In this case it
                must be the correct size, be normalized (an L2 norm of 1), and
                be safely castable to an appropriate dtype for the simulator.

        Returns:
            ComputeDisplaysResult for the simulation.
        """
        return self.compute_displays_sweep(
            program, [param_resolver], qubit_order, initial_state)[0]


Instruction:
Write a Python 3 function that can
accumulate single qubit phase gates into the scratch shards.

Response:
def _single_qubit_accumulate_into_scratch(args: Dict[str, Any]):
    """Accumulates single qubit phase gates into the scratch shards."""
    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]


Instruction:
How would you explain what the following Python 3 function does
def _one_projector(args: Dict[str, Any], index: int) -> Union[int, np.ndarray]:
    num_shard_qubits = args['num_shard_qubits']
    shard_num = args['shard_num']
    if index >= num_shard_qubits:
        return _kth_bit(shard_num, index - num_shard_qubits)
    return _zero_one_vects(args)[index]

Response: Returns a projector onto the |1 > subspace of the index - th qubit.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _two_qubit_accumulate_into_scratch(args: Dict[str, Any]):
    index0, index1 = args['indices']
    half_turns = args['half_turns']
    scratch = _scratch_shard(args)

    projector = _one_projector(args, index0) * _one_projector(args, index1)
    # Exp11 = exp(-i pi |11><11| half_turns), but we accumulate phases as
    # pi / 2.
    scratch += 2 * half_turns * projector

Response: Accumulates two qubit phase gates into the scratch shards.


Instruction:
Can you tell what is the following Python 3 function doing
def _apply_scratch_as_phase(args: Dict[str, Any]):
    state = _state_shard(args)
    state *= np.exp(I_PI_OVER_2 * _scratch_shard(args))

Response: Takes scratch shards and applies them as exponentiated phase to state.


Instruction:
Write a Python 3 script to
apply a W gate when the gate acts only within a shard.

Response:
def _w_within_shard(args: Dict[str, Any]):
    """Applies a W gate when the gate acts only within a shard."""
    index = args['index']
    half_turns = args['half_turns']
    axis_half_turns = args['axis_half_turns']
    state = _state_shard(args)
    pm_vect = _pm_vects(args)[index]
    num_shard_qubits = args['num_shard_qubits']
    shard_size = 2 ** num_shard_qubits

    reshape_tuple = (2 ** (num_shard_qubits - 1 - index), 2, 2 ** index)
    perm_state = np.reshape(
        np.reshape(state, reshape_tuple)[:, ::-1, :], shard_size)
    cos = np.cos(-0.5 * np.pi * half_turns)
    sin = np.sin(-0.5 * np.pi * half_turns)

    cos_axis = np.cos(np.pi * axis_half_turns)
    sin_axis = np.sin(np.pi * axis_half_turns)

    new_state = cos * state + 1j * sin * perm_state * (
        cos_axis - 1j * sin_axis * pm_vect)
    np.copyto(state, new_state)


Instruction:
How would you explain what the following Python 3 function does
def _w_between_shards(args: Dict[str, Any]):
    shard_num = args['shard_num']
    state = _state_shard(args)
    num_shard_qubits = args['num_shard_qubits']
    index = args['index']
    half_turns = args['half_turns']

    axis_half_turns = args['axis_half_turns']

    perm_index = shard_num ^ (1 << (index - num_shard_qubits))
    perm_state = mem_manager.SharedMemManager.get_array(
        args['state_handle']).view(np.complex64)[perm_index]

    cos = np.cos(-0.5 * np.pi * half_turns)
    sin = np.sin(-0.5 * np.pi * half_turns)

    cos_axis = np.cos(np.pi * axis_half_turns)
    sin_axis = np.sin(np.pi * axis_half_turns)

    scratch = _scratch_shard(args)
    z_op = (1 - 2 * _kth_bit(shard_num, index - num_shard_qubits))
    np.copyto(scratch, state * cos + 1j * sin * perm_state *
              (cos_axis - 1j * sin_axis * z_op))

Response: Applies a W gate when the gate acts between shards.


Instruction:
Here you have a function in Python 3, explain what it does
def _copy_scratch_to_state(args: Dict[str, Any]):
    np.copyto(_state_shard(args), _scratch_shard(args))

Response: Copes scratch shards to state shards.


Instruction:
Given the following Python 3 function, write the documentation
def _one_prob_per_shard(args: Dict[str, Any]) -> float:
    index = args['index']

    state = _state_shard(args) * _one_projector(args, index)
    norm = np.linalg.norm(state)
    return norm * norm

Response: Returns the probability of getting a one measurement on a state shard.


Instruction:
Given the following Python 3 function, write the documentation
def _norm_squared(args: Dict[str, Any]) -> float:
    state = _state_shard(args)
    return np.sum(np.abs(state) ** 2)

Response: Returns the norm for each state shard.


Instruction:
Create a Python 3 function to
project state shards onto the appropriate post measurement state.

Response:
def _collapse_state(args: Dict[str, Any]):
    """Projects state shards onto the appropriate post measurement state.

    This function makes no assumptions about the interpretation of quantum
    theory.

    Args:
        args: The args from shard_num_args.
    """
    index = args['index']
    result = args['result']
    prob_one = args['prob_one']

    state = _state_shard(args)
    normalization = np.sqrt(prob_one if result else 1 - prob_one)
    state *= (_one_projector(args, index) * result +
              (1 - _one_projector(args, index)) * (1 - result))
    state /= normalization


Instruction:
Here you have a function in Python 3, explain what it does
def init_z_vects(self):
        shard_size = 2 ** self._num_shard_qubits

        a, b = np.indices((shard_size, self._num_shard_qubits))
        a >>= b
        a &= 1
        zero_one_vects = np.ascontiguousarray(a.transpose())
        zero_one_vects_handle = mem_manager.SharedMemManager.create_array(
            zero_one_vects)
        self._shared_mem_dict['zero_one_vects_handle'] = zero_one_vects_handle

        pm_vects = 1 - 2 * zero_one_vects
        pm_vects_handle = mem_manager.SharedMemManager.create_array(pm_vects)
        self._shared_mem_dict['pm_vects_handle'] = pm_vects_handle

Response: Initializes the bitwise vectors which are precomputed in shared memory.


Instruction:
Write a Python 3 script to
initialize a scratch pad equal in size to the wavefunction.

Response:
def _init_scratch(self):
        """Initializes a scratch pad equal in size to the wavefunction."""
        scratch = np.zeros((self._num_shards, self._shard_size),
                           dtype=np.complex64)
        scratch_handle = mem_manager.SharedMemManager.create_array(
            scratch.view(dtype=np.float32))
        self._shared_mem_dict['scratch_handle'] = scratch_handle


Instruction:
Create a Python 3 function to
initialize a the shard wavefunction and sets the initial state.

Response:
def _init_state(self, initial_state: Union[int, np.ndarray]):
        """Initializes a the shard wavefunction and sets the initial state."""
        state = np.reshape(
            sim.to_valid_state_vector(initial_state, self._num_qubits),
            (self._num_shards, self._shard_size))
        state_handle = mem_manager.SharedMemManager.create_array(
            state.view(dtype=np.float32))
        self._shared_mem_dict['state_handle'] = state_handle


Instruction:
Can you write a function in Python 3 where it
simulates a set of phases on the xmon architecture.

Response:
def simulate_phases(self, phase_map: Dict[Tuple[int, ...], float]):
        """Simulate a set of phase gates on the xmon architecture.

        Args:
            phase_map: A map from a tuple of indices to a value, one for each
                phase gate being simulated. If the tuple key has one index, then
                this is a Z phase gate on the index-th qubit with a rotation
                angle of pi times the value of the map. If the tuple key has two
                indices, then this is a |11> phasing gate, acting on the qubits
                at the two indices, and a rotation angle of pi times the value
                of the map.
        """
        self._pool.map(_clear_scratch, self._shard_num_args())
        # Iterate over the map of phase data.
        for indices, half_turns in phase_map.items():
            args = self._shard_num_args(
                {'indices': indices, 'half_turns': half_turns})
            if len(indices) == 1:
                self._pool.map(_single_qubit_accumulate_into_scratch, args)
            elif len(indices) == 2:
                self._pool.map(_two_qubit_accumulate_into_scratch, args)
        # Exponentiate the phases and add them into the state.
        self._pool.map(_apply_scratch_as_phase, self._shard_num_args())


Instruction:
How would you code a function in Python 3 to
simulate a single qubit rotation gate about a X + b Y.

Response:
def simulate_w(self,
                   index: int,
                   half_turns: float,
                   axis_half_turns: float):
        """Simulate a single qubit rotation gate about a X + b Y.

        The gate simulated is U = exp(-i pi/2 W half_turns)
            where W = cos(pi axis_half_turns) X + sin(pi axis_half_turns) Y

        Args:
          index: The qubit to act on.
          half_turns: The amount of the overall rotation, see the formula
              above.
          axis_half_turns: The angle between the pauli X and Y operators,
              see the formula above.
        """
        args = self._shard_num_args({
            'index': index,
            'half_turns': half_turns,
            'axis_half_turns': axis_half_turns
        })
        if index >= self._num_shard_qubits:
            # W gate spans shards.
            self._pool.map(_clear_scratch, args)
            self._pool.map(_w_between_shards, args)
            self._pool.map(_copy_scratch_to_state, args)
        else:
            # W gate is within a shard.
            self._pool.map(_w_within_shard, args)

        # Normalize after every w.
        norm_squared = np.sum(self._pool.map(_norm_squared, args))
        args = self._shard_num_args({
            'norm_squared': norm_squared
        })
        self._pool.map(_renorm, args)


Instruction:
Create a Python 3 function for
simulating a single qubit measurement in the computational basis.

Response:
def simulate_measurement(self, index: int) -> bool:
        """Simulates a single qubit measurement in the computational basis.

        Args:
            index: Which qubit is measured.

        Returns:
            True iff the measurement result corresponds to the |1> state.
        """
        args = self._shard_num_args({'index': index})
        prob_one = np.sum(self._pool.map(_one_prob_per_shard, args))
        result = bool(np.random.random() <= prob_one)

        args = self._shard_num_args({
            'index': index,
            'result': result,
            'prob_one': prob_one
        })
        self._pool.map(_collapse_state, args)
        return result


Instruction:
How would you implement a function in Python 3 that
samples from measurements in the computational basis.

Response:
def sample_measurements(
            self,
            indices: List[int],
            repetitions: int=1) -> List[List[bool]]:
        """Samples from measurements in the computational basis.

        Note that this does not collapse the wave function.

        Args:
            indices: Which qubits are measured.

        Returns:
            Measurement results with True corresponding to the |1> state.
            The outer list is for repetitions, and the inner corresponds to
            measurements ordered by the input indices.

        Raises:
            ValueError if repetitions is less than one.
        """
        # Stepper uses little endian while sample_state uses big endian.
        reversed_indices = [self._num_qubits - 1 - index for index in indices]
        return sim.sample_state_vector(self._current_state(), reversed_indices,
                                       repetitions)


Instruction:
How would you implement a function in Python 3 that
decomposes the Fermionic SWAP gate into two single - qubit gates and one iSWAP gate.

Response:
def fswap(p, q):
    """Decompose the Fermionic SWAP gate into two single-qubit gates and
    one iSWAP gate.

    Args:
        p: the id of the first qubit
        q: the id of the second qubit
    """

    yield cirq.ISWAP(q, p), cirq.Z(p) ** 1.5
    yield cirq.Z(q) ** 1.5


Instruction:
Can you tell what is the following Python 3 function doing
def bogoliubov_trans(p, q, theta):

    # The iSWAP gate corresponds to evolve under the Hamiltonian XX+YY for
    # time -pi/4.
    expo = -4 * theta / np.pi

    yield cirq.X(p)
    yield cirq.S(p)
    yield cirq.ISWAP(p, q)**expo
    yield cirq.S(p) ** 1.5
    yield cirq.X(p)

Response: A generator that yields the 2 - mode Bogoliubov transformation.


Instruction:
How would you explain what the following Python 3 function does
def fermi_fourier_trans_2(p, q):

    yield cirq.Z(p)**1.5
    yield cirq.ISWAP(q, p)**0.5
    yield cirq.Z(p)**1.5

Response: A 2 - mode fermionic Fourier transformation.


Instruction:
Can you tell what is the following Python 3 function doing
def fermi_fourier_trans_inverse_4(qubits):

    yield fswap(qubits[1], qubits[2]),
    yield fermi_fourier_trans_2(qubits[0], qubits[1])
    yield fermi_fourier_trans_2(qubits[2], qubits[3])
    yield fswap(qubits[1], qubits[2])
    yield fermi_fourier_trans_2(qubits[0], qubits[1])
    yield cirq.S(qubits[2])
    yield fermi_fourier_trans_2(qubits[2], qubits[3])
    yield fswap(qubits[1], qubits[2])

Response: A fermionic Fourier transformation on 4 qubits.


Instruction:
Can you tell what is the following Python 3 function doing
def fermi_fourier_trans_inverse_conjugate_4(qubits):

    yield fswap(qubits[1], qubits[2]),
    yield fermi_fourier_trans_2(qubits[0], qubits[1])
    yield fermi_fourier_trans_2(qubits[2], qubits[3])
    yield fswap(qubits[1], qubits[2])
    yield fermi_fourier_trans_2(qubits[0], qubits[1])
    yield cirq.S(qubits[2]) ** 3
    yield fermi_fourier_trans_2(qubits[2], qubits[3])
    yield fswap(qubits[1], qubits[2])

Response: This function implements the inverse conjugate of the Fourier transform.


Instruction:
Write a Python 3 script to
generate the parameters for the BCS ground state i. e. the delta and bog_theta of the Bogoliubov transformation.

Response:
def bcs_parameters(n_site, n_fermi, u, t) :
    """Generate the parameters for the BCS ground state, i.e., the
    superconducting gap and the rotational angles in the Bogoliubov
    transformation.

     Args:
        n_site: the number of sites in the Hubbard model
        n_fermi: the number of fermions
        u: the interaction strength
        t: the tunneling strength

    Returns:
        float delta, List[float] bog_theta
    """

    # The wave numbers satisfy the periodic boundary condition.
    wave_num = np.linspace(0, 1, n_site, endpoint=False)
    # The hopping energy as a function of wave numbers
    hop_erg = -2 * t * np.cos(2 * np.pi * wave_num)
    # Finding the Fermi energy
    fermi_erg = hop_erg[n_fermi // 2]
    # Set the Fermi energy to zero
    hop_erg = hop_erg - fermi_erg

    def _bcs_gap(x):
        """Defines the self-consistent equation for the BCS wavefunction.

        Args:
            x: the superconducting gap
        """

        s = 0.
        for i in range(n_site):
            s += 1. / np.sqrt(hop_erg[i] ** 2 + x ** 2)
        return 1 + s * u / (2 * n_site)

    # Superconducting gap
    delta = scipy.optimize.bisect(_bcs_gap, 0.01, 10000. * abs(u))
    # The amplitude of the double excitation state
    bcs_v = np.sqrt(0.5 * (1 - hop_erg / np.sqrt(hop_erg ** 2 + delta ** 2)))
    # The rotational angle in the Bogoliubov transformation.
    bog_theta = np.arcsin(bcs_v)

    return delta, bog_theta


Instruction:
How would you code a function in Python 3 to
calculate the bloch vector of a qubit.

Response:
def bloch_vector_from_state_vector(state: Sequence, index: int) -> np.ndarray:
    """Returns the bloch vector of a qubit.

    Calculates the bloch vector of the qubit at index
    in the wavefunction given by state, assuming state follows
    the standard Kronecker convention of numpy.kron.

    Args:
        state: A sequence representing a wave function in which
            the ordering mapping to qubits follows the standard Kronecker
            convention of numpy.kron.
        index: index of qubit who's bloch vector we want to find.
            follows the standard Kronecker convention of numpy.kron.

    Returns:
        A length 3 numpy array representing the qubit's bloch vector.

    Raises:
        ValueError: if the size of state is not a power of 2.
        ValueError: if the size of the state represents more than 25 qubits.
        IndexError: if index is out of range for the number of qubits
            corresponding to the state.
    """
    rho = density_matrix_from_state_vector(state, [index])
    v = np.zeros(3, dtype=np.float32)
    v[0] = 2*np.real(rho[0][1])
    v[1] = 2*np.imag(rho[1][0])
    v[2] = np.real(rho[0][0] - rho[1][1])

    return v


Instruction:
Here you have a function in Python 3, explain what it does
def dirac_notation(state: Sequence, decimals: int=2) -> str:
    perm_list = ["".join(seq) for seq in itertools.product(
        "01", repeat=int(len(state)).bit_length() - 1)]
    components = []
    ket = "|{}⟩"
    for x in range(len(perm_list)):
        format_str = "({:." + str(decimals) + "g})"
        # Python 2 rounds imaginary numbers to 0, so need to round separately.
        val = (round(state[x].real, decimals)
               + 1j * round(state[x].imag, decimals))
        if round(val.real, decimals) == 0 and round(val.imag, decimals) != 0:
            val = val.imag
            format_str = "{:." + str(decimals) + "g}j"
        elif round(val.imag, decimals) == 0 and round(val.real, decimals) != 0:
            val = val.real
            format_str = "{:." + str(decimals) + "g}"
        if val != 0:
            if round(state[x], decimals) == 1:
                components.append(ket.format(perm_list[x]))
            else:
                components.append((format_str + ket).format(val, perm_list[x]))
    if not components:
        return '0'

    return ' + '.join(components).replace(' + -', ' - ')

Response: Returns the wavefunction as a string in Dirac notation.


Instruction:
Implement a Python 3 function for
verifying the state_rep is valid and converts it to ndarray form.

Response:
def to_valid_state_vector(state_rep: Union[int, np.ndarray],
                          num_qubits: int,
                          dtype: Type[np.number] = np.complex64) -> np.ndarray:
    """Verifies the state_rep is valid and converts it to ndarray form.

    This method is used to support passing in an integer representing a
    computational basis state or a full wave function as a representation of
    a state.

    Args:
        state_rep: If an int, the state returned is the state corresponding to
            a computational basis state. If an numpy array this is the full
            wave function. Both of these are validated for the given number
            of qubits, and the state must be properly normalized and of the
            appropriate dtype.
        num_qubits: The number of qubits for the state. The state_rep must be
            valid for this number of qubits.
        dtype: The numpy dtype of the state, will be used when creating the
            state for a computational basis state, or validated against if
            state_rep is a numpy array.

    Returns:
        A numpy ndarray corresponding to the state on the given number of
        qubits.

    Raises:
        ValueError if the state is not valid.
    """
    if isinstance(state_rep, np.ndarray):
        if len(state_rep) != 2 ** num_qubits:
            raise ValueError(
                'initial state was of size {} '
                'but expected state for {} qubits'.format(
                    len(state_rep), num_qubits))
        state = state_rep
    elif isinstance(state_rep, int):
        if state_rep < 0:
            raise ValueError('initial_state must be positive')
        elif state_rep >= 2 ** num_qubits:
            raise ValueError(
                'initial state was {} but expected state for {} qubits'.format(
                    state_rep, num_qubits))
        else:
            state = np.zeros(2 ** num_qubits, dtype=dtype)
            state[state_rep] = 1.0
    else:
        raise TypeError('initial_state was not of type int or ndarray')
    validate_normalized_state(state, num_qubits, dtype)
    return state


Instruction:
Explain what the following Python 3 code does
def validate_normalized_state(state: np.ndarray,
                              num_qubits: int,
                              dtype: Type[np.number] = np.complex64) -> None:
    """Validates that the given state is a valid wave function."""
    if state.size != 1 << num_qubits:
        raise ValueError(
            'State has incorrect size. Expected {} but was {}.'.format(
                1 << num_qubits, state.size))
    if state.dtype != dtype:
        raise ValueError(
            'State has invalid dtype. Expected {} but was {}'.format(
                dtype, state.dtype))
    norm = np.sum(np.abs(state) ** 2)
    if not np.isclose(norm, 1):
        raise ValueError('State is not normalized instead had norm %s' % norm)

Response: Validates that the given state is a valid wave function.


Instruction:
Can you create a Python 3 function that
samples repeatedly from measurements in the computational basis.

Response:
def sample_state_vector(state: np.ndarray,
                        indices: List[int],
                        repetitions: int=1) -> np.ndarray:
    """Samples repeatedly from measurements in the computational basis.

    Note that this does not modify the passed in state.

    Args:
        state: The multi-qubit wavefunction to be sampled. This is an array of
            2 to the power of the number of qubit complex numbers, and so
            state must be of size ``2**integer``.  The state can be a vector of
            size ``2**integer`` or a tensor of shape ``(2, 2, ..., 2)``.
        indices: Which qubits are measured. The state is assumed to be supplied
            in big endian order. That is the xth index of v, when expressed as
            a bitstring, has its largest values in the 0th index.
        repetitions: The number of times to sample the state.

    Returns:
        Measurement results with True corresponding to the ``|1⟩`` state.
        The outer list is for repetitions, and the inner corresponds to
        measurements ordered by the supplied qubits. These lists
        are wrapped as an numpy ndarray.

    Raises:
        ValueError: ``repetitions`` is less than one or size of ``state`` is not
            a power of 2.
        IndexError: An index from ``indices`` is out of range, given the number
            of qubits corresponding to the state.
    """
    if repetitions < 0:
        raise ValueError('Number of repetitions cannot be negative. Was {}'
                         .format(repetitions))
    num_qubits = _validate_num_qubits(state)
    _validate_indices(num_qubits, indices)

    if repetitions == 0 or len(indices) == 0:
        return np.zeros(shape=(repetitions, len(indices)))

    # Calculate the measurement probabilities.
    probs = _probs(state, indices, num_qubits)

    # We now have the probability vector, correctly ordered, so sample over
    # it. Note that we us ints here, since numpy's choice does not allow for
    # choosing from a list of tuples or list of lists.
    result = np.random.choice(len(probs), size=repetitions, p=probs)
    # Convert to bools and rearrange to match repetition being the outer list.
    return np.transpose([(1 & (result >> i)).astype(np.bool) for i in
                         range(len(indices))])


Instruction:
Can you write a function in Python 3 where it
returns the probabilities for a measurement on the given indices.

Response:
def _probs(state: np.ndarray, indices: List[int],
           num_qubits: int) -> List[float]:
    """Returns the probabilities for a measurement on the given indices."""
    # Tensor of squared amplitudes, shaped a rank [2, 2, .., 2] tensor.
    tensor = np.reshape(state, [2] * num_qubits)

    # Calculate the probabilities for measuring the particular results.
    probs = [
        np.linalg.norm(
                tensor[linalg.slice_for_qubits_equal_to(indices, b)]) ** 2
        for b in range(2 ** len(indices))]

    # To deal with rounding issues, ensure that the probabilities sum to 1.
    probs /= sum(probs) # type: ignore
    return probs


Instruction:
How would you implement a function in Python 3 that
validates that state s size is a power of 2 returning number of qubits.

Response:
def _validate_num_qubits(state: np.ndarray) -> int:
    """Validates that state's size is a power of 2, returning number of qubits.
    """
    size = state.size
    if size & (size - 1):
        raise ValueError('state.size ({}) is not a power of two.'.format(size))
    return size.bit_length() - 1


Instruction:
How would you code a function in Python 3 to
validate that the indices have values within range of num_qubits.

Response:
def _validate_indices(num_qubits: int, indices: List[int]) -> None:
    """Validates that the indices have values within range of num_qubits."""
    if any(index < 0 for index in indices):
        raise IndexError('Negative index in indices: {}'.format(indices))
    if any(index >= num_qubits for index in indices):
        raise IndexError('Out of range indices, must be less than number of '
                         'qubits but was {}'.format(indices))


Instruction:
Can you tell what is the following Python 3 function doing
def density_matrix_of(self, qubits: List[ops.Qid] = None) -> np.ndarray:
        return density_matrix_from_state_vector(
            self.state_vector(),
            [self.qubit_map[q] for q in qubits] if qubits is not None else None
        )

Response: Returns the density matrix of the state.


Instruction:
Implement a function in Python 3 to
return the bloch vector of a given qubit in the state given by self. state_vector.

Response:
def bloch_vector_of(self, qubit: ops.Qid) -> np.ndarray:
        """Returns the bloch vector of a qubit in the state.

        Calculates the bloch vector of the given qubit
        in the state given by self.state_vector(), given that
        self.state_vector() follows the standard Kronecker convention of
        numpy.kron.

        Args:
            qubit: qubit who's bloch vector we want to find.

        Returns:
            A length 3 numpy array representing the qubit's bloch vector.

        Raises:
            ValueError: if the size of the state represents more than 25 qubits.
            IndexError: if index is out of range for the number of qubits
                corresponding to the state.
        """
        return bloch_vector_from_state_vector(self.state_vector(),
                                              self.qubit_map[qubit])


Instruction:
Can you tell what is the following Python 3 function doing
def get_acquaintance_size(obj: Union[circuits.Circuit, ops.Operation]) -> int:
    if isinstance(obj, circuits.Circuit):
        if not is_acquaintance_strategy(obj):
            raise TypeError('not is_acquaintance_strategy(circuit)')
        return max(tuple(get_acquaintance_size(op)
                         for op in obj.all_operations()) or (0,))
    if not isinstance(obj, ops.Operation):
        raise TypeError('not isinstance(obj, (Circuit, Operation))')
    if not isinstance(obj, ops.GateOperation):
        return 0
    if isinstance(obj.gate, AcquaintanceOpportunityGate):
        return len(obj.qubits)
    if isinstance(obj.gate, BipartiteSwapNetworkGate):
        return 2
    if isinstance(obj.gate, ShiftSwapNetworkGate):
        return obj.gate.acquaintance_size()
    if isinstance(obj.gate, SwapNetworkGate):
        if obj.gate.acquaintance_size is None:
            return sum(sorted(obj.gate.part_lens)[-2:])
        if (obj.gate.acquaintance_size - 1) in obj.gate.part_lens:
            return obj.gate.acquaintance_size
    sizer = getattr(obj.gate, '_acquaintance_size_', None)
    return 0 if sizer is None else sizer(len(obj.qubits))

Response: Returns the number of qubits to be acquainted with each other.


Instruction:
Given the following Python 3 function, write the documentation
def get_or_search(self) -> List[GridQubit]:
        if not self._sequence:
            self._sequence = self._find_sequence()
        return self._sequence

Response: Starts the search or gives previously calculated sequence.


Instruction:
Explain what the following Python 3 code does
def _find_sequence(self) -> List[GridQubit]:
        # Run the first pass and drop starting qubit from the found sequence.
        tail = self._sequence_search(self._start, [])
        tail.pop(0)

        # Run the second pass and keep the starting qubit.
        head = self._sequence_search(self._start, tail)
        head.reverse()

        return self._expand_sequence(head + tail)

Response: Searches for a sequence starting at a given qubit.


Instruction:
How would you explain what the following Python 3 function does
def _sequence_search(self, start: GridQubit,
                         current: List[GridQubit]) -> List[GridQubit]:
        """Search for the continuous linear sequence from the given qubit.

        This method is called twice for the same starting qubit, so that
        sequences that begin and end on this qubit are searched for.

        Args:
            start: The first qubit, where search should be trigerred from.
            current: Previously found linear sequence, which qubits are
                     forbidden to use during the search.

        Returns:
            Continuous linear sequence that begins with the starting qubit and
            does not contain any qubits from the current list.
        """
        used = set(current)
        seq = []
        n = start  # type: Optional[GridQubit]
        while n is not None:
            # Append qubit n to the sequence and mark it is as visited.
            seq.append(n)
            used.add(n)
            # Advance search to the next qubit.
            n = self._choose_next_qubit(n, used)
        return seq

Response: Search for the continuous linear sequence from the given qubit.


Instruction:
How would you explain what the following Python 3 function does
def _find_path_between(self, p: GridQubit, q: GridQubit,
                           used: Set[GridQubit]) -> Optional[List[GridQubit]]:
        """Searches for continuous sequence between two qubits.

        This method runs two BFS algorithms in parallel (alternating variable s
        in each iteration); the first one starting from qubit p, and the second
        one starting from qubit q. If at some point a qubit reachable from p is
        found to be on the set of qubits already reached from q (or vice versa),
        the search is stopped and new path returned.

        Args:
            p: The first qubit, start of the sequence.
            q: The second qubit, end of the sequence.
            used: Set of forbidden qubits which cannot appear on the sequence.

        Returns:
            Continues sequence of qubits with new path between p and q, or None
            if no path was found.
        """

        def assemble_path(n: GridQubit, parent: Dict[GridQubit, GridQubit]):
            path = [n]
            while n in parent:
                n = parent[n]
                path.append(n)
            return path

        other = {p: q, q: p}
        parents = {p: dict(), q: dict()} \
            # type: Dict[GridQubit, Dict[GridQubit, GridQubit]]
        visited = {p: set(), q: set()}  # type: Dict[GridQubit, Set[GridQubit]]

        queue = collections.deque([(p, p), (q, q)])

        # Run two BFSs simultaneously.
        while queue:
            n, s = queue.popleft()
            for n_adj in self._c_adj[n]:
                if n_adj in visited[other[s]]:
                    # Connection has been found, construct the path and return.
                    path_s = assemble_path(n, parents[s])[-2::-1]
                    path_other = assemble_path(n_adj, parents[other[s]])[:-1]
                    path = path_s + path_other
                    if s == q:
                        path.reverse()
                    return path
                elif n_adj not in used and n_adj not in visited[s]:
                    # Append n_adj to the end of queue of qubit s.
                    queue.append((n_adj, s))
                    visited[s].add(n_adj)
                    parents[s][n_adj] = n

        return None

Response: Searches for continuous sequence between two qubits.


Instruction:
Here you have a function in Python 3, explain what it does
def _collect_unused(self, start: GridQubit,
                        used: Set[GridQubit]) -> Set[GridQubit]:
        """Lists all the qubits that are reachable from given qubit.

        Args:
            start: The first qubit for which connectivity should be calculated.
                   Might be a member of used set.
            used: Already used qubits, which cannot be used during the
                  collection.

        Returns:
            Set of qubits that are reachable from starting qubit without
            traversing any of the used qubits.
        """

        def collect(n: GridQubit, visited: Set[GridQubit]):
            visited.add(n)
            for m in self._c_adj[n]:
                if m not in used and m not in visited:
                    collect(m, visited)

        visited = set()  # type: Set[GridQubit]
        collect(start, visited)
        return visited

Response: Returns a list of all the qubits that are reachable from start and which are not used during the collection.


Instruction:
Can you implement a function in Python 3 that
runs line sequence search.

Response:
def place_line(self,
                   device: 'cirq.google.XmonDevice',
                   length: int) -> GridQubitLineTuple:
        """Runs line sequence search.

        Args:
            device: Chip description.
            length: Required line length.

        Returns:
            Linear sequences found on the chip.

        Raises:
            ValueError: If search algorithm passed on initialization is not
                        recognized.
        """

        if not device.qubits:
            return GridQubitLineTuple()

        start = min(device.qubits)  # type: GridQubit
        sequences = []  # type: List[LineSequence]
        greedy_search = {
            'minimal_connectivity': [
                _PickFewestNeighbors(device, start),
            ],
            'largest_area': [
                _PickLargestArea(device, start),
            ],
            'best': [
                _PickFewestNeighbors(device, start),
                _PickLargestArea(device, start),
            ]
        }  # type: Dict[str, List[GreedySequenceSearch]]

        algos = greedy_search.get(self.algorithm)
        if algos is None:
            raise ValueError(
                "Unknown greedy search algorithm %s" % self.algorithm)

        for algorithm in algos:
            sequences.append(algorithm.get_or_search())

        return GridQubitLineTuple.best_of(sequences, length)


Instruction:
Create a Python 3 function to
return a maximum on the trace distance between this effect s input and output.

Response:
def trace_distance_bound(val: Any) -> float:
    """Returns a maximum on the trace distance between this effect's input
    and output.  This method makes use of the effect's `_trace_distance_bound_`
    method to determine the maximum bound on the trace difference between
    before and after the effect.

    Args:
        val: The effect of which the bound should be calculated

    Returns:
        If `val` has a _trace_distance_bound_ method and its result is not
        NotImplemented, that result is returned. Otherwise, 1 is returned.
        Result is capped at a maximum of 1, even if the underlying function
        produces a result greater than 1.

    """
    getter = getattr(val, '_trace_distance_bound_', None)
    result = NotImplemented if getter is None else getter()

    if result is not NotImplemented and result < 1.0:
        return result
    return 1.0


Instruction:
Can you write a function in Python 3 where it
determines if the moment has operations touching the given qubits.

Response:
def operates_on(self, qubits: Iterable[raw_types.Qid]) -> bool:
        """Determines if the moment has operations touching the given qubits.

        Args:
            qubits: The qubits that may or may not be touched by operations.

        Returns:
            Whether this moment has operations involving the qubits.
        """
        return any(q in qubits for q in self.qubits)


Instruction:
Explain what the following Python 3 code does
def without_operations_touching(self, qubits: Iterable[raw_types.Qid]):
        qubits = frozenset(qubits)
        if not self.operates_on(qubits):
            return self
        return Moment(
            operation for operation in self.operations
            if qubits.isdisjoint(frozenset(operation.qubits)))

Response: Returns an equal moment but without operations on the given qubits.


Instruction:
Here you have a function in Python 3, explain what it does
def _approx_eq_(self, other: Any, atol: Union[int, float]) -> bool:
        if not isinstance(other, type(self)):
            return NotImplemented
        return approx_eq(self.operations, other.operations, atol=atol)

Response: See cirq. protocols. SupportsApproximateEquality.


Instruction:
Can you write a function in Python 3 where it
returns true only if the operations have qubits in common.

Response:
def _disjoint_qubits(op1: ops.Operation, op2: ops.Operation) -> bool:
    """Returns true only if the operations have qubits in common."""
    return not set(op1.qubits) & set(op2.qubits)


Instruction:
Can you create a Python 3 function that
describes how to change operations near the given location.

Response:
def optimization_at(self,
                        circuit: Circuit,
                        index: int,
                        op: ops.Operation
                        ) -> Optional[PointOptimizationSummary]:
        """Describes how to change operations near the given location.

        For example, this method could realize that the given operation is an
        X gate and that in the very next moment there is a Z gate. It would
        indicate that they should be combined into a Y gate by returning
        PointOptimizationSummary(clear_span=2,
                                 clear_qubits=op.qubits,
                                 new_operations=cirq.Y(op.qubits[0]))

        Args:
            circuit: The circuit to improve.
            index: The index of the moment with the operation to focus on.
            op: The operation to focus improvements upon.

        Returns:
            A description of the optimization to perform, or else None if no
            change should be made.
        """


Instruction:
Can you write a function in Python 3 where it
converts a schedule into an iterable of proto dictionaries.

Response:
def schedule_to_proto_dicts(schedule: Schedule) -> Iterable[Dict]:
    """Convert a schedule into an iterable of proto dictionaries.

    Args:
        schedule: The schedule to convert to a proto dict. Must contain only
            gates that can be cast to xmon gates.

    Yields:
        A proto dictionary corresponding to an Operation proto.
    """
    last_time_picos = None  # type: Optional[int]
    for so in schedule.scheduled_operations:
        op = gate_to_proto_dict(
            cast(ops.GateOperation, so.operation).gate,
            so.operation.qubits)
        time_picos = so.time.raw_picos()
        if last_time_picos is None:
            op['incremental_delay_picoseconds'] = time_picos
        else:
            op['incremental_delay_picoseconds'] = time_picos - last_time_picos
        last_time_picos = time_picos
        yield op


Instruction:
Can you generate the documentation for the following Python 3 function
def schedule_from_proto_dicts(
        device: 'xmon_device.XmonDevice',
        ops: Iterable[Dict],
) -> Schedule:
    """Convert proto dictionaries into a Schedule for the given device."""
    scheduled_ops = []
    last_time_picos = 0
    for op in ops:
        delay_picos = 0
        if 'incremental_delay_picoseconds' in op:
            delay_picos = op['incremental_delay_picoseconds']
        time_picos = last_time_picos + delay_picos
        last_time_picos = time_picos
        xmon_op = xmon_op_from_proto_dict(op)
        scheduled_ops.append(ScheduledOperation.op_at_on(
            operation=xmon_op,
            time=Timestamp(picos=time_picos),
            device=device,
        ))
    return Schedule(device, scheduled_ops)

Response: Convert a list of proto dictionaries into a Schedule object.


Instruction:
Given the following Python 3 function, write the documentation
def pack_results(measurements: Sequence[Tuple[str, np.ndarray]]) -> bytes:
    if not measurements:
        return b''

    shapes = [(key, np.shape(data)) for key, data in measurements]
    if not all(len(shape) == 2 for _, shape in shapes):
        raise ValueError("Expected 2-D data: shapes={}".format(shapes))

    reps = shapes[0][1][0]
    if not all(shape[0] == reps for _, shape in shapes):
        raise ValueError(
            "Expected same reps for all keys: shapes={}".format(shapes))

    bits = np.hstack([np.asarray(data, dtype=bool) for _, data in measurements])
    bits = bits.reshape(-1)

    # Pad length to multiple of 8 if needed.
    remainder = len(bits) % 8
    if remainder:
        bits = np.pad(bits, (0, 8 - remainder), 'constant')

    # Pack in little-endian bit order.
    bits = bits.reshape((-1, 8))[:, ::-1]
    byte_arr = np.packbits(bits, axis=1).reshape(-1)

    return byte_arr.tobytes()

Response: Pack measurement results into a byte string.


Instruction:
Can you write a function in Python 3 where it
unpacks data from a bitstring into individual measurement results.

Response:
def unpack_results(
        data: bytes,
        repetitions: int,
        key_sizes: Sequence[Tuple[str, int]]
) -> Dict[str, np.ndarray]:
    """Unpack data from a bitstring into individual measurement results.

    Args:
        data: Packed measurement results, in the form <rep0><rep1>...
            where each repetition is <key0_0>..<key0_{size0-1}><key1_0>...
            with bits packed in little-endian order in each byte.
        repetitions: number of repetitions.
        key_sizes: Keys and sizes of the measurements in the data.

    Returns:
        Dict mapping measurement key to a 2D array of boolean results. Each
        array has shape (repetitions, size) with size for that measurement.
    """
    bits_per_rep = sum(size for _, size in key_sizes)
    total_bits = repetitions * bits_per_rep

    byte_arr = np.frombuffer(data, dtype='uint8').reshape((len(data), 1))
    bits = np.unpackbits(byte_arr, axis=1)[:, ::-1].reshape(-1).astype(bool)
    bits = bits[:total_bits].reshape((repetitions, bits_per_rep))

    results = {}
    ofs = 0
    for key, size in key_sizes:
        results[key] = bits[:, ofs:ofs + size]
        ofs += size

    return results


Instruction:
Given the following Python 3 function, write the documentation
def is_native_xmon_op(op: ops.Operation) -> bool:
    return (isinstance(op, ops.GateOperation) and
            is_native_xmon_gate(op.gate))

Response: Checks if the operation is a native xmon gate.


Instruction:
Write a Python 3 function for
checking if a gate is a native xmon gate.

Response:
def is_native_xmon_gate(gate: ops.Gate) -> bool:
    """Check if a gate is a native xmon gate.

    Args:
        gate: Input gate.

    Returns:
        True if the gate is native to the xmon, false otherwise.
    """
    return isinstance(gate, (ops.CZPowGate,
                             ops.MeasurementGate,
                             ops.PhasedXPowGate,
                             ops.XPowGate,
                             ops.YPowGate,
                             ops.ZPowGate))


Instruction:
Can you generate the documentation for the following Python 3 function
def xmon_op_from_proto_dict(proto_dict: Dict) -> ops.Operation:

    def raise_missing_fields(gate_name: str):
        raise ValueError(
            '{} missing required fields: {}'.format(gate_name, proto_dict))
    param = _parameterized_value_from_proto_dict
    qubit = devices.GridQubit.from_proto_dict
    if 'exp_w' in proto_dict:
        exp_w = proto_dict['exp_w']
        if ('half_turns' not in exp_w or 'axis_half_turns' not in exp_w
                or 'target' not in exp_w):
            raise_missing_fields('ExpW')
        return ops.PhasedXPowGate(
            exponent=param(exp_w['half_turns']),
            phase_exponent=param(exp_w['axis_half_turns']),
        ).on(qubit(exp_w['target']))
    elif 'exp_z' in proto_dict:
        exp_z = proto_dict['exp_z']
        if 'half_turns' not in exp_z or 'target' not in exp_z:
            raise_missing_fields('ExpZ')
        return ops.Z(qubit(exp_z['target']))**param(exp_z['half_turns'])
    elif 'exp_11' in proto_dict:
        exp_11 = proto_dict['exp_11']
        if ('half_turns' not in exp_11 or 'target1' not in exp_11
                or 'target2' not in exp_11):
            raise_missing_fields('Exp11')
        return ops.CZ(qubit(exp_11['target1']),
                      qubit(exp_11['target2']))**param(exp_11['half_turns'])
    elif 'measurement' in proto_dict:
        meas = proto_dict['measurement']
        invert_mask = cast(Tuple[Any, ...], ())
        if 'invert_mask' in meas:
            invert_mask = tuple(json.loads(x) for x in meas['invert_mask'])
        if 'key' not in meas or 'targets' not in meas:
            raise_missing_fields('Measurement')
        return ops.MeasurementGate(
            num_qubits=len(meas['targets']),
            key=meas['key'],
            invert_mask=invert_mask
        ).on(*[qubit(q) for q in meas['targets']])
    else:
        raise ValueError('invalid operation: {}'.format(proto_dict))

Response: Convert the dictionary representation of a single operation into an XMon operation.


Instruction:
How would you code a function in Python 3 to
remove terms with coefficients of absolute value atol or less.

Response:
def clean(self: 'TSelf', *, atol: float=1e-9) -> 'TSelf':
        """Remove terms with coefficients of absolute value atol or less."""
        negligible = [v for v, c in self._terms.items() if abs(c) <= atol]
        for v in negligible:
            del self._terms[v]
        return self


Instruction:
Write a Python 3 function for
checking whether two linear combinations are approximately equal.

Response:
def _approx_eq_(self, other: Any, atol: float) -> bool:
        """Checks whether two linear combinations are approximately equal."""
        if not isinstance(other, LinearDict):
            return NotImplemented

        all_vs = set(self.keys()) | set(other.keys())
        return all(abs(self[v] - other[v]) < atol for v in all_vs)


Instruction:
Given the following Python 3 function, write the documentation
def enqueue(self, priority: int, item: TItem) -> bool:
        if self._drop_set is not None:
            if (priority, item) in self._drop_set:
                return False
            self._drop_set.add((priority, item))

        # First enqueue initializes self._offset.
        if not self._buckets:
            self._buckets.append([item])
            self._offset = priority
            self._len = 1
            return True

        # Where is the bucket this item is supposed to go into?
        i = priority - self._offset

        # Extend bucket list backwards if needed.
        if i < 0:
            self._buckets[:0] = [[] for _ in range(-i)]
            self._offset = priority
            i = 0

        # Extend bucket list forwards if needed.
        while i >= len(self._buckets):
            self._buckets.append([])

        # Finish by adding item to the intended bucket's list.
        self._buckets[i].append(item)
        self._len += 1
        return True

Response: Enqueue an item into the priority queue.


Instruction:
Implement a function in Python 3 to
remove and returns an item from the priority queue.

Response:
def dequeue(self) -> Tuple[int, TItem]:
        """Removes and returns an item from the priority queue.

        Returns:
            A tuple whose first element is the priority of the dequeued item
            and whose second element is the dequeued item.

        Raises:
            ValueError:
                The queue is empty.
        """
        if self._len == 0:
            raise ValueError('BucketPriorityQueue is empty.')

        # Drop empty buckets at the front of the queue.
        while self._buckets and not self._buckets[0]:
            self._buckets.pop(0)
            self._offset += 1

        # Pull item out of the front bucket.
        item = self._buckets[0].pop(0)
        priority = self._offset
        self._len -= 1
        if self._drop_set is not None:
            self._drop_set.remove((priority, item))

        # Note: do not eagerly clear out empty buckets after pulling the item!
        # Doing so increases the worst case complexity of "monotonic" use from
        # O(N+P) to O(N*P).

        return priority, item


Instruction:
Create a Python 3 function to
run the supplied Circuit or Schedule via Quantum Engine.

Response:
def run(
            self,
            *,  # Force keyword args.
            program: Union[circuits.Circuit, Schedule],
            job_config: Optional[JobConfig] = None,
            param_resolver: ParamResolver = ParamResolver({}),
            repetitions: int = 1,
            priority: int = 50,
            processor_ids: Sequence[str] = ('xmonsim',)) -> TrialResult:
        """Runs the supplied Circuit or Schedule via Quantum Engine.

        Args:
            program: The Circuit or Schedule to execute. If a circuit is
                provided, a moment by moment schedule will be used.
            job_config: Configures the names of programs and jobs.
            param_resolver: Parameters to run with the program.
            repetitions: The number of repetitions to simulate.
            priority: The priority to run at, 0-100.
            processor_ids: The engine processors to run against.

        Returns:
            A single TrialResult for this run.
        """
        return list(
            self.run_sweep(program=program,
                           job_config=job_config,
                           params=[param_resolver],
                           repetitions=repetitions,
                           priority=priority,
                           processor_ids=processor_ids))[0]


Instruction:
Make a summary of the following Python 3 code
def run_sweep(
            self,
            *,  # Force keyword args.
            program: Union[circuits.Circuit, Schedule],
            job_config: Optional[JobConfig] = None,
            params: Sweepable = None,
            repetitions: int = 1,
            priority: int = 500,
            processor_ids: Sequence[str] = ('xmonsim',)) -> 'EngineJob':
        """Runs the supplied Circuit or Schedule via Quantum Engine.

        In contrast to run, this runs across multiple parameter sweeps, and
        does not block until a result is returned.

        Args:
            program: The Circuit or Schedule to execute. If a circuit is
                provided, a moment by moment schedule will be used.
            job_config: Configures the names of programs and jobs.
            params: Parameters to run with the program.
            repetitions: The number of circuit repetitions to run.
            priority: The priority to run at, 0-100.
            processor_ids: The engine processors to run against.

        Returns:
            An EngineJob. If this is iterated over it returns a list of
            TrialResults, one for each parameter sweep.
        """

        job_config = self.implied_job_config(job_config)
        schedule = self.program_as_schedule(program)

        # Check program to run and program parameters.
        if not 0 <= priority < 1000:
            raise ValueError('priority must be between 0 and 1000')

        schedule.device.validate_schedule(schedule)

        # Create program.
        sweeps = _sweepable_to_sweeps(params or ParamResolver({}))
        program_dict = {}  # type: Dict[str, Any]

        program_dict['parameter_sweeps'] = [
            sweep_to_proto_dict(sweep, repetitions) for
            sweep in sweeps]
        program_dict['operations'] = [op for op in
                                      schedule_to_proto_dicts(schedule)]
        code = {
            '@type': 'type.googleapis.com/cirq.api.google.v1.Program'}
        code.update(program_dict)
        request = {
            'name': 'projects/%s/programs/%s' % (job_config.project_id,
                                                 job_config.program_id,),
            'gcs_code_location': {'uri': job_config.gcs_program},
            'code': code,
        }
        response = self.service.projects().programs().create(
            parent='projects/%s' % job_config.project_id,
            body=request).execute()

        # Create job.
        request = {
            'name': '%s/jobs/%s' % (response['name'], job_config.job_id),
            'output_config': {
                'gcs_results_location': {
                    'uri': job_config.gcs_results
                }
            },
            'scheduling_config': {
                'priority': priority,
                'processor_selector': {
                    'processor_names': [
                        'projects/%s/processors/%s' %
                        (job_config.project_id, processor_id)
                        for processor_id in processor_ids
                    ]
                }
            },
        }
        response = self.service.projects().programs().jobs().create(
            parent=response['name'], body=request).execute()

        return EngineJob(job_config, response, self)

Response: Runs a single parameter sweep.


Instruction:
Can you implement a function in Python 3 that
returns the previously created quantum program.

Response:
def get_program(self, program_resource_name: str) -> Dict:
        """Returns the previously created quantum program.

        Params:
            program_resource_name: A string of the form
                `projects/project_id/programs/program_id`.

        Returns:
            A dictionary containing the metadata and the program.
        """
        return self.service.projects().programs().get(
            name=program_resource_name).execute()


Instruction:
Can you create a Python 3 function that
returns the metadata about a previously created job.

Response:
def get_job(self, job_resource_name: str) -> Dict:
        """Returns metadata about a previously created job.

        See get_job_result if you want the results of the job and not just
        metadata about the job.

        Params:
            job_resource_name: A string of the form
                `projects/project_id/programs/program_id/jobs/job_id`.

        Returns:
            A dictionary containing the metadata.
        """
        return self.service.projects().programs().jobs().get(
            name=job_resource_name).execute()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_job_results(self, job_resource_name: str) -> List[TrialResult]:
        response = self.service.projects().programs().jobs().getResult(
            parent=job_resource_name).execute()
        trial_results = []
        for sweep_result in response['result']['sweepResults']:
            sweep_repetitions = sweep_result['repetitions']
            key_sizes = [(m['key'], len(m['qubits']))
                         for m in sweep_result['measurementKeys']]
            for result in sweep_result['parameterizedResults']:
                data = base64.standard_b64decode(result['measurementResults'])
                measurements = unpack_results(data, sweep_repetitions,
                                              key_sizes)

                trial_results.append(TrialResult(
                    params=ParamResolver(
                        result.get('params', {}).get('assignments', {})),
                    repetitions=sweep_repetitions,
                    measurements=measurements))
        return trial_results

Response: Returns the actual results of a completed job.


Instruction:
Can you implement a function in Python 3 that
cancels the given job.

Response:
def cancel_job(self, job_resource_name: str):
        """Cancels the given job.

        See also the cancel method on EngineJob.

        Params:
            job_resource_name: A string of the form
                `projects/project_id/programs/program_id/jobs/job_id`.
        """
        self.service.projects().programs().jobs().cancel(
            name=job_resource_name, body={}).execute()


Instruction:
Here you have a function in Python 3, explain what it does
def results(self) -> List[TrialResult]:
        if not self._results:
            job = self._update_job()
            for _ in range(1000):
                if job['executionStatus']['state'] in TERMINAL_STATES:
                    break
                time.sleep(0.5)
                job = self._update_job()
            if job['executionStatus']['state'] != 'SUCCESS':
                raise RuntimeError(
                    'Job %s did not succeed. It is in state %s.' % (
                        job['name'], job['executionStatus']['state']))
            self._results = self._engine.get_job_results(
                self.job_resource_name)
        return self._results

Response: Returns the job results blocking until the job is complete.


Instruction:
Here you have a function in Python 3, explain what it does
def flatten_op_tree(root: OP_TREE,
                    preserve_moments: bool = False
                    ) -> Iterable[Union[Operation, Moment]]:
    """Performs an in-order iteration of the operations (leaves) in an OP_TREE.

    Args:
        root: The operation or tree of operations to iterate.
        preserve_moments: Whether to yield Moments intact instead of
            flattening them

    Yields:
        Operations from the tree.

    Raises:
        TypeError: root isn't a valid OP_TREE.
    """
    if (isinstance(root, Operation)
            or preserve_moments and isinstance(root, Moment)):
        yield root
        return

    if isinstance(root, collections.Iterable):
        for subtree in root:
            for item in flatten_op_tree(subtree, preserve_moments):
                yield item
        return

    raise TypeError('Not a collections.Iterable or an Operation: {} {}'.format(
        type(root), root))

Response: Returns an in - order iteration of the operations in an OP_TREE.


Instruction:
How would you explain what the following Python 3 function does
def transform_op_tree(
        root: OP_TREE,
        op_transformation: Callable[[Operation], OP_TREE]=lambda e: e,
        iter_transformation: Callable[[Iterable[OP_TREE]], OP_TREE]=lambda e: e,
        preserve_moments: bool = False
) -> OP_TREE:
    """Maps transformation functions onto the nodes of an OP_TREE.

    Args:
        root: The operation or tree of operations to transform.
        op_transformation: How to transform the operations (i.e. leaves).
        iter_transformation: How to transform the iterables (i.e. internal
            nodes).
        preserve_moments: Whether to leave Moments alone. If True, the
            transformation functions will not be applied to Moments or the
            operations within them.

    Returns:
        A transformed operation tree.

    Raises:
        TypeError: root isn't a valid OP_TREE.
    """
    if isinstance(root, Operation):
        return op_transformation(root)

    if preserve_moments and isinstance(root, Moment):
        return root

    if isinstance(root, collections.Iterable):
        return iter_transformation(
            transform_op_tree(subtree,
                              op_transformation,
                              iter_transformation,
                              preserve_moments)
            for subtree in root)

    raise TypeError(
        'Not a collections.Iterable or an Operation: {}'.format(root))

Response: Transforms an OP_TREE into a single element - wise tree of internalCOOKIE entries.


Instruction:
How would you explain what the following Python 3 function does
def circuit_to_quirk_url(circuit: circuits.Circuit,
                         prefer_unknown_gate_to_failure: bool=False,
                         escape_url=True) -> str:
    """Returns a Quirk URL for the given circuit.

    Args:
        circuit: The circuit to open in Quirk.
        prefer_unknown_gate_to_failure: If not set, gates that fail to convert
            will cause this function to raise an error. If set, a URL
            containing bad gates will be generated. (Quirk will open the URL,
            and replace the bad gates with parse errors, but still get the rest
            of the circuit.)
        escape_url: If set, the generated URL will have special characters such
            as quotes escaped using %. This makes it possible to paste the URL
            into forums and the command line and etc and have it properly
            parse. If not set, the generated URL will be more compact and human
            readable (and can still be pasted directly into a browser's address
            bar).

    Returns:

    """
    circuit = circuit.copy()
    linearize_circuit_qubits(circuit)

    cols = []  # Type: List[List[Any]]
    for moment in circuit:
        can_merges = []
        for op in moment.operations:
            for col, can_merge in _to_quirk_cols(
                    op,
                    prefer_unknown_gate_to_failure):
                if can_merge:
                    can_merges.append(col)
                else:
                    cols.append(col)
        if can_merges:
            merged_col = [1] * max(len(e) for e in can_merges)
            for col in can_merges:
                for i in range(len(col)):
                    if col[i] != 1:
                        merged_col[i] = col[i]
            cols.append(merged_col)

    circuit_json = json.JSONEncoder(ensure_ascii=False,
                                    separators=(',', ':'),
                                    sort_keys=True).encode({'cols': cols})
    if escape_url:
        suffix = urllib.parse.quote(circuit_json)
    else:
        suffix = circuit_json
    return 'http://algassert.com/quirk#circuit={}'.format(suffix)

Response: Converts a circuit into a Quirk URL.


Instruction:
Can you create a Python 3 function that
determines if two qubits are adjacent qubits.

Response:
def is_adjacent(self, other: ops.Qid) -> bool:
        """Determines if two qubits are adjacent qubits."""
        return (isinstance(other, GridQubit) and
                abs(self.row - other.row) + abs(self.col - other.col) == 1)


Instruction:
Write a Python 3 script for
creating a GridQubit object from a protobuf dictionary.

Response:
def from_proto_dict(proto_dict: Dict) -> 'GridQubit':
        """Proto dict must have 'row' and 'col' keys."""
        if 'row' not in proto_dict or 'col' not in proto_dict:
            raise ValueError(
                'Proto dict does not contain row or col: {}'.format(proto_dict))
        return GridQubit(row=proto_dict['row'], col=proto_dict['col'])


Instruction:
Implement a function in Python 3 to
get the logical operations to apply to qubits.

Response:
def get_operations(self,
                       indices: Sequence[LogicalIndex],
                       qubits: Sequence[ops.Qid]
                       ) -> ops.OP_TREE:
        """Gets the logical operations to apply to qubits."""


Instruction:
Explain what the following Python 3 code does
def merge_single_qubit_gates_into_phased_x_z(
        circuit: circuits.Circuit,
        atol: float = 1e-8) -> None:
    """Canonicalizes runs of single-qubit rotations in a circuit.

    Specifically, any run of non-parameterized circuits will be replaced by an
    optional PhasedX operation followed by an optional Z operation.

    Args:
        circuit: The circuit to rewrite. This value is mutated in-place.
        atol: Absolute tolerance to angle error. Larger values allow more
            negligible gates to be dropped, smaller values increase accuracy.
    """

    def synth(qubit: ops.Qid, matrix: np.ndarray) -> List[ops.Operation]:
        out_gates = decompositions.single_qubit_matrix_to_phased_x_z(
            matrix, atol)
        return [gate(qubit) for gate in out_gates]

    MergeSingleQubitGates(synthesizer=synth).optimize_circuit(circuit)

Response: This function merges single - qubit gates into a single - qubit molecular x - z - gate.


Instruction:
Write a Python 3 function that can
wrap the given string with terminal color codes.

Response:
def highlight(text: str, color_code: int, bold: bool=False) -> str:
    """Wraps the given string with terminal color codes.

    Args:
        text: The content to highlight.
        color_code: The color to highlight with, e.g. 'shelltools.RED'.
        bold: Whether to bold the content in addition to coloring.

    Returns:
        The highlighted string.
    """
    return '{}\033[{}m{}\033[0m'.format(
        '\033[1m' if bold else '',
        color_code,
        text,)


Instruction:
Write a Python 3 script to
print and captures output from the given asynchronous iterable.

Response:
async def _async_forward(async_chunks: collections.AsyncIterable,
                         out: Optional[Union[TeeCapture, IO[str]]]
                         ) -> Optional[str]:
    """Prints/captures output from the given asynchronous iterable.

    Args:
        async_chunks: An asynchronous source of bytes or str.
        out: Where to put the chunks.

    Returns:
        The complete captured output, or else None if the out argument wasn't a
        TeeCapture instance.
    """
    capture = isinstance(out, TeeCapture)
    out_pipe = out.out_pipe if isinstance(out, TeeCapture) else out

    chunks = [] if capture else None  # type: Optional[List[str]]
    async for chunk in async_chunks:
        if not isinstance(chunk, str):
            chunk = chunk.decode()
        if out_pipe:
            print(chunk, file=out_pipe, end='')
        if chunks is not None:
            chunks.append(chunk)

    return ''.join(chunks) if chunks is not None else None


Instruction:
Make a summary of the following Python 3 code
async def _async_wait_for_process(
        future_process: Any,
        out: Optional[Union[TeeCapture, IO[str]]] = sys.stdout,
        err: Optional[Union[TeeCapture, IO[str]]] = sys.stderr
) -> CommandOutput:
    """Awaits the creation and completion of an asynchronous process.

    Args:
        future_process: The eventually created process.
        out: Where to write stuff emitted by the process' stdout.
        err: Where to write stuff emitted by the process' stderr.

    Returns:
        A (captured output, captured error output, return code) triplet.
    """
    process = await future_process
    future_output = _async_forward(process.stdout, out)
    future_err_output = _async_forward(process.stderr, err)
    output, err_output = await asyncio.gather(future_output, future_err_output)
    await process.wait()

    return CommandOutput(output, err_output, process.returncode)

Response: A wrapper around asyncio. Popen that waits for the process to finish.


Instruction:
How would you explain what the following Python 3 function does
def run_cmd(*cmd: Optional[str],
            out: Optional[Union[TeeCapture, IO[str]]] = sys.stdout,
            err: Optional[Union[TeeCapture, IO[str]]] = sys.stderr,
            raise_on_fail: bool = True,
            log_run_to_stderr: bool = True,
            abbreviate_non_option_arguments: bool = False,
            **kwargs
            ) -> CommandOutput:
    """Invokes a subprocess and waits for it to finish.

    Args:
        cmd: Components of the command to execute, e.g. ["echo", "dog"].
        out: Where to write the process' stdout. Defaults to sys.stdout. Can be
            anything accepted by print's 'file' parameter, or None if the
            output should be dropped, or a TeeCapture instance. If a TeeCapture
            instance is given, the first element of the returned tuple will be
            the captured output.
        err: Where to write the process' stderr. Defaults to sys.stderr. Can be
            anything accepted by print's 'file' parameter, or None if the
            output should be dropped, or a TeeCapture instance. If a TeeCapture
            instance is given, the second element of the returned tuple will be
            the captured error output.
        raise_on_fail: If the process returns a non-zero error code
            and this flag is set, a CalledProcessError will be raised.
            Otherwise the return code is the third element of the returned
            tuple.
        log_run_to_stderr: Determines whether the fact that this shell command
            was executed is logged to sys.stderr or not.
        abbreviate_non_option_arguments: When logging to stderr, this cuts off
            the potentially-huge tail of the command listing off e.g. hundreds
            of file paths. No effect if log_run_to_stderr is not set.

        **kwargs: Extra arguments for asyncio.create_subprocess_shell, such as
            a cwd (current working directory) argument.

    Returns:
        A (captured output, captured error output, return code) triplet. The
        captured outputs will be None if the out or err parameters were not set
        to an instance of TeeCapture.

    Raises:
         subprocess.CalledProcessError: The process returned a non-zero error
            code and raise_on_fail was set.
    """
    kept_cmd = tuple(cast(str, e) for e in cmd if e is not None)
    if log_run_to_stderr:
        cmd_desc = kept_cmd
        if abbreviate_non_option_arguments:
            cmd_desc = abbreviate_command_arguments_after_switches(cmd_desc)
        print('run:', cmd_desc, file=sys.stderr)
    result = asyncio.get_event_loop().run_until_complete(
        _async_wait_for_process(
            asyncio.create_subprocess_exec(
                *kept_cmd,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                **kwargs),
            out,
            err))
    if raise_on_fail and result[2]:
        raise subprocess.CalledProcessError(result[2], kept_cmd)
    return result

Response: Invokes a subprocess and waits for it to finish.


Instruction:
Can you generate the documentation for the following Python 3 function
def run_shell(cmd: str,
              out: Optional[Union[TeeCapture, IO[str]]] = sys.stdout,
              err: Optional[Union[TeeCapture, IO[str]]] = sys.stderr,
              raise_on_fail: bool = True,
              log_run_to_stderr: bool = True,
              **kwargs
              ) -> CommandOutput:
    """Invokes a shell command and waits for it to finish.

    Args:
        cmd: The command line string to execute, e.g. "echo dog | cat > file".
        out: Where to write the process' stdout. Defaults to sys.stdout. Can be
            anything accepted by print's 'file' parameter, or None if the
            output should be dropped, or a TeeCapture instance. If a TeeCapture
            instance is given, the first element of the returned tuple will be
            the captured output.
        err: Where to write the process' stderr. Defaults to sys.stderr. Can be
            anything accepted by print's 'file' parameter, or None if the
            output should be dropped, or a TeeCapture instance. If a TeeCapture
            instance is given, the second element of the returned tuple will be
            the captured error output.
        raise_on_fail: If the process returns a non-zero error code
            and this flag is set, a CalledProcessError will be raised.
            Otherwise the return code is the third element of the returned
            tuple.
        log_run_to_stderr: Determines whether the fact that this shell command
            was executed is logged to sys.stderr or not.
        **kwargs: Extra arguments for asyncio.create_subprocess_shell, such as
            a cwd (current working directory) argument.

    Returns:
        A (captured output, captured error output, return code) triplet. The
        captured outputs will be None if the out or err parameters were not set
        to an instance of TeeCapture.

    Raises:
         subprocess.CalledProcessError: The process returned a non-zero error
            code and raise_on_fail was set.
    """
    if log_run_to_stderr:
        print('shell:', cmd, file=sys.stderr)
    result = asyncio.get_event_loop().run_until_complete(
        _async_wait_for_process(
            asyncio.create_subprocess_shell(
                cmd,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                **kwargs),
            out,
            err))
    if raise_on_fail and result[2]:
        raise subprocess.CalledProcessError(result[2], cmd)
    return result

Response: Invokes a shell command and waits for it to finish.


Instruction:
Here you have a function in Python 3, explain what it does
def output_of(*cmd: Optional[str], **kwargs) -> str:
    result = cast(str, run_cmd(*cmd,
                               log_run_to_stderr=False,
                               out=TeeCapture(),
                               **kwargs).out)

    # Strip final newline.
    if result.endswith('\n'):
        result = result[:-1]

    return result

Response: Invokes a subprocess and returns its output as a string.


Instruction:
Here you have a function in Python 3, explain what it does
def chosen_angle_to_half_turns(
        half_turns: Optional[Union[sympy.Basic, float]] = None,
        rads: Optional[float] = None,
        degs: Optional[float] = None,
        default: float = 1.0,
) -> Union[sympy.Basic, float]:
    """Returns a half_turns value based on the given arguments.

    At most one of half_turns, rads, degs must be specified. If none are
    specified, the output defaults to half_turns=1.

    Args:
        half_turns: The number of half turns to rotate by.
        rads: The number of radians to rotate by.
        degs: The number of degrees to rotate by
        default: The half turns angle to use if nothing else is specified.

    Returns:
        A number of half turns.
    """

    if len([1 for e in [half_turns, rads, degs] if e is not None]) > 1:
        raise ValueError('Redundant angle specification. '
                         'Use ONE of half_turns, rads, or degs.')

    if rads is not None:
        return rads / np.pi

    if degs is not None:
        return degs / 180

    if half_turns is not None:
        return half_turns

    return default

Response: Returns a half_turns value based on the given arguments.


Instruction:
Can you generate the documentation for the following Python 3 function
def chosen_angle_to_canonical_half_turns(
        half_turns: Optional[Union[sympy.Basic, float]] = None,
        rads: Optional[float] = None,
        degs: Optional[float] = None,
        default: float = 1.0,
) -> Union[sympy.Basic, float]:
    """Returns a canonicalized half_turns based on the given arguments.

    At most one of half_turns, rads, degs must be specified. If none are
    specified, the output defaults to half_turns=1.

    Args:
        half_turns: The number of half turns to rotate by.
        rads: The number of radians to rotate by.
        degs: The number of degrees to rotate by
        default: The half turns angle to use if nothing else is specified.

    Returns:
        A number of half turns.
    """
    return canonicalize_half_turns(
            chosen_angle_to_half_turns(
                half_turns=half_turns,
                rads=rads,
                degs=degs,
                default=default))

Response: Returns a canonicalized half_turns based on the given arguments.


Instruction:
Make a summary of the following Python 3 code
def canonicalize_half_turns(
        half_turns: Union[sympy.Basic, float]
) -> Union[sympy.Basic, float]:
    """Wraps the input into the range (-1, +1]."""
    if isinstance(half_turns, sympy.Basic):
        return half_turns
    half_turns %= 2
    if half_turns > 1:
        half_turns -= 2
    return half_turns

Response: Wraps the input into the range - 1 - 1.


Instruction:
Create a Python 3 function to
implement a single - qubit operation with few rotations.

Response:
def single_qubit_matrix_to_pauli_rotations(
        mat: np.ndarray, atol: float = 0
) -> List[Tuple[ops.Pauli, float]]:
    """Implements a single-qubit operation with few rotations.

    Args:
        mat: The 2x2 unitary matrix of the operation to implement.
        atol: A limit on the amount of absolute error introduced by the
            construction.

    Returns:
        A list of (Pauli, half_turns) tuples that, when applied in order,
        perform the desired operation.
    """

    def is_clifford_rotation(half_turns):
        return near_zero_mod(half_turns, 0.5, atol=atol)

    def to_quarter_turns(half_turns):
        return round(2 * half_turns) % 4

    def is_quarter_turn(half_turns):
        return (is_clifford_rotation(half_turns) and
                to_quarter_turns(half_turns) % 2 == 1)

    def is_half_turn(half_turns):
        return (is_clifford_rotation(half_turns) and
                to_quarter_turns(half_turns) == 2)

    def is_no_turn(half_turns):
        return (is_clifford_rotation(half_turns) and
                to_quarter_turns(half_turns) == 0)

    # Decompose matrix
    z_rad_before, y_rad, z_rad_after = (
        linalg.deconstruct_single_qubit_matrix_into_angles(mat))
    z_ht_before = z_rad_before / np.pi - 0.5
    m_ht = y_rad / np.pi
    m_pauli = ops.pauli_gates.X  # type: ops.pauli_gates.Pauli
    z_ht_after = z_rad_after / np.pi + 0.5

    # Clean up angles
    if is_clifford_rotation(z_ht_before):
        if ((is_quarter_turn(z_ht_before) or is_quarter_turn(z_ht_after)) ^
            (is_half_turn(m_ht) and is_no_turn(z_ht_before-z_ht_after))):
            z_ht_before += 0.5
            z_ht_after -= 0.5
            m_pauli = ops.pauli_gates.Y
        if is_half_turn(z_ht_before) or is_half_turn(z_ht_after):
            z_ht_before -= 1
            z_ht_after += 1
            m_ht = -m_ht
    if is_no_turn(m_ht):
        z_ht_before += z_ht_after
        z_ht_after = 0
    elif is_half_turn(m_ht):
        z_ht_after -= z_ht_before
        z_ht_before = 0

    # Generate operations
    rotation_list = [
        (ops.pauli_gates.Z, z_ht_before),
        (m_pauli, m_ht),
        (ops.pauli_gates.Z, z_ht_after)]
    return [(pauli, ht) for pauli, ht in rotation_list if not is_no_turn(ht)]


Instruction:
Here you have a function in Python 3, explain what it does
def single_qubit_matrix_to_gates(
        mat: np.ndarray, tolerance: float = 0
) -> List[ops.SingleQubitGate]:
    """Implements a single-qubit operation with few gates.

    Args:
        mat: The 2x2 unitary matrix of the operation to implement.
        tolerance: A limit on the amount of error introduced by the
            construction.

    Returns:
        A list of gates that, when applied in order, perform the desired
            operation.
    """
    rotations = single_qubit_matrix_to_pauli_rotations(mat, tolerance)
    return [cast(ops.SingleQubitGate, pauli)**ht for pauli, ht in rotations]

Response: Implements a single - qubit operation with few gates.


Instruction:
Make a summary of the following Python 3 code
def single_qubit_op_to_framed_phase_form(
        mat: np.ndarray) -> Tuple[np.ndarray, complex, complex]:
    """Decomposes a 2x2 unitary M into U^-1 * diag(1, r) * U * diag(g, g).

    U translates the rotation axis of M to the Z axis.
    g fixes a global phase factor difference caused by the translation.
    r's phase is the amount of rotation around M's rotation axis.

    This decomposition can be used to decompose controlled single-qubit
    rotations into controlled-Z operations bordered by single-qubit operations.

    Args:
      mat:  The qubit operation as a 2x2 unitary matrix.

    Returns:
        A 2x2 unitary U, the complex relative phase factor r, and the complex
        global phase factor g. Applying M is equivalent (up to global phase) to
        applying U, rotating around the Z axis to apply r, then un-applying U.
        When M is controlled, the control must be rotated around the Z axis to
        apply g.
    """
    vals, vecs = np.linalg.eig(mat)
    u = np.conj(vecs).T
    r = vals[1] / vals[0]
    g = vals[0]
    return u, r, g

Response: Decomposes a 2x2 unitary M into a 2x2 complex relative phase factor r and complex global phase factor g.


Instruction:
Here you have a function in Python 3, explain what it does
def _deconstruct_single_qubit_matrix_into_gate_turns(
        mat: np.ndarray) -> Tuple[float, float, float]:
    """Breaks down a 2x2 unitary into gate parameters.

    Args:
        mat: The 2x2 unitary matrix to break down.

    Returns:
       A tuple containing the amount to rotate around an XY axis, the phase of
       that axis, and the amount to phase around Z. All results will be in
       fractions of a whole turn, with values canonicalized into the range
       [-0.5, 0.5).
    """
    pre_phase, rotation, post_phase = (
        linalg.deconstruct_single_qubit_matrix_into_angles(mat))

    # Figure out parameters of the actual gates we will do.
    tau = 2 * np.pi
    xy_turn = rotation / tau
    xy_phase_turn = 0.25 - pre_phase / tau
    total_z_turn = (post_phase + pre_phase) / tau

    # Normalize turns into the range [-0.5, 0.5).
    return (_signed_mod_1(xy_turn), _signed_mod_1(xy_phase_turn),
            _signed_mod_1(total_z_turn))

Response: Breaks down a 2x2 unitary matrix into gate parameters.


Instruction:
Explain what the following Python 3 code does
def single_qubit_matrix_to_phased_x_z(
        mat: np.ndarray,
        atol: float = 0
) -> List[ops.SingleQubitGate]:
    """Implements a single-qubit operation with a PhasedX and Z gate.

    If one of the gates isn't needed, it will be omitted.

    Args:
        mat: The 2x2 unitary matrix of the operation to implement.
        atol: A limit on the amount of error introduced by the
            construction.

    Returns:
        A list of gates that, when applied in order, perform the desired
            operation.
    """

    xy_turn, xy_phase_turn, total_z_turn = (
        _deconstruct_single_qubit_matrix_into_gate_turns(mat))

    # Build the intended operation out of non-negligible XY and Z rotations.
    result = [
        ops.PhasedXPowGate(exponent=2 * xy_turn,
                           phase_exponent=2 * xy_phase_turn),
        ops.Z**(2 * total_z_turn)
    ]
    result = [
        g for g in result
        if protocols.trace_distance_bound(g) > atol
    ]

    # Special case: XY half-turns can absorb Z rotations.
    if len(result) == 2 and abs(xy_turn) >= 0.5 - atol:
        return [
            ops.PhasedXPowGate(phase_exponent=2 * xy_phase_turn + total_z_turn)
        ]

    return result

Response: Implements a single - qubit operation with a PhasedX and Z gate.