Instruction:
Write a Python 3 function for
running a Rabi oscillation experiment.

Response:
def rabi_oscillations(sampler: sim.Sampler,
                      qubit: devices.GridQubit,
                      max_angle: float = 2 * np.pi,
                      *,
                      repetitions: int = 1000,
                      num_points: int = 200) -> RabiResult:
    """Runs a Rabi oscillation experiment.

    Rotates a qubit around the x-axis of the Bloch sphere by a sequence of Rabi
    angles evenly spaced between 0 and max_angle. For each rotation, repeat
    the circuit a number of times and measure the average probability of the
    qubit being in the |1> state.

    Args:
        sampler: The quantum engine or simulator to run the circuits.
        qubit: The qubit under test.
        max_angle: The final Rabi angle in radians.
        repetitions: The number of repetitions of the circuit for each Rabi
            angle.
        num_points: The number of Rabi angles.

    Returns:
        A RabiResult object that stores and plots the result.
    """
    theta = sympy.Symbol('theta')
    circuit = circuits.Circuit.from_ops(ops.X(qubit) ** theta)
    circuit.append(ops.measure(qubit, key='z'))
    sweep = study.Linspace(key='theta', start=0.0, stop=max_angle / np.pi,
                           length=num_points)
    results = sampler.run_sweep(circuit, params=sweep, repetitions=repetitions)
    angles = np.linspace(0.0, max_angle, num_points)
    excited_state_probs = np.zeros(num_points)
    for i in range(num_points):
        excited_state_probs[i] = np.mean(results[i].measurements['z'])

    return RabiResult(angles, excited_state_probs)


Instruction:
Write a Python 3 function that can
generate a randomized benchmark of a single qubit.

Response:
def single_qubit_randomized_benchmarking(
        sampler: sim.Sampler,
        qubit: devices.GridQubit,
        use_xy_basis: bool = True,
        *,
        num_clifford_range: Sequence[int] = range(10, 100, 10),
        num_circuits: int = 20,
        repetitions: int = 1000) -> RandomizedBenchMarkResult:
    """Clifford-based randomized benchmarking (RB) of a single qubit.

    A total of num_circuits random circuits are generated, each of which
    contains a fixed number of single-qubit Clifford gates plus one
    additional Clifford that inverts the whole sequence and a measurement in
    the z-basis. Each circuit is repeated a number of times and the average
    |0> state population is determined from the measurement outcomes of all
    of the circuits.

    The above process is done for different circuit lengths specified by the
    integers in num_clifford_range. For example, an integer 10 means the
    random circuits will contain 10 Clifford gates each plus one inverting
    Clifford. The user may use the result to extract an average gate fidelity,
    by analyzing the change in the average |0> state population at different
    circuit lengths. For actual experiments, one should choose
    num_clifford_range such that a clear exponential decay is observed in the
    results.

    See Barends et al., Nature 508, 500 for details.

    Args:
        sampler: The quantum engine or simulator to run the circuits.
        qubit: The qubit under test.
        use_xy_basis: Determines if the Clifford gates are built with x and y
            rotations (True) or x and z rotations (False).
        num_clifford_range: The different numbers of Cliffords in the RB study.
        num_circuits: The number of random circuits generated for each
            number of Cliffords.
        repetitions: The number of repetitions of each circuit.

    Returns:
        A RandomizedBenchMarkResult object that stores and plots the result.
    """

    cliffords = _single_qubit_cliffords()
    c1 = cliffords.c1_in_xy if use_xy_basis else cliffords.c1_in_xz
    cfd_mats = np.array([_gate_seq_to_mats(gates) for gates in c1])

    gnd_probs = []
    for num_cfds in num_clifford_range:
        excited_probs_l = []
        for _ in range(num_circuits):
            circuit = _random_single_q_clifford(qubit, num_cfds, c1, cfd_mats)
            circuit.append(ops.measure(qubit, key='z'))
            results = sampler.run(circuit, repetitions=repetitions)
            excited_probs_l.append(np.mean(results.measurements['z']))
        gnd_probs.append(1.0 - np.mean(excited_probs_l))

    return RandomizedBenchMarkResult(num_clifford_range, gnd_probs)


Instruction:
Can you tell what is the following Python 3 function doing
def single_qubit_state_tomography(sampler: sim.Sampler,
                                  qubit: devices.GridQubit,
                                  circuit: circuits.Circuit,
                                  repetitions: int = 1000) -> TomographyResult:
    """Single-qubit state tomography.

    The density matrix of the output state of a circuit is measured by first
    doing projective measurements in the z-basis, which determine the
    diagonal elements of the matrix. A X/2 or Y/2 rotation is then added before
    the z-basis measurement, which determines the imaginary and real parts of
    the off-diagonal matrix elements, respectively.

    See Vandersypen and Chuang, Rev. Mod. Phys. 76, 1037 for details.

    Args:
        sampler: The quantum engine or simulator to run the circuits.
        qubit: The qubit under test.
        circuit: The circuit to execute on the qubit before tomography.
        repetitions: The number of measurements for each basis rotation.

    Returns:
        A TomographyResult object that stores and plots the density matrix.
    """
    circuit_z = circuit + circuits.Circuit.from_ops(ops.measure(qubit, key='z'))
    results = sampler.run(circuit_z, repetitions=repetitions)
    rho_11 = np.mean(results.measurements['z'])
    rho_00 = 1.0 - rho_11

    circuit_x = circuits.Circuit.from_ops(circuit, ops.X(qubit) ** 0.5,
                                          ops.measure(qubit, key='z'))
    results = sampler.run(circuit_x, repetitions=repetitions)
    rho_01_im = np.mean(results.measurements['z']) - 0.5

    circuit_y = circuits.Circuit.from_ops(circuit, ops.Y(qubit) ** -0.5,
                                          ops.measure(qubit, key='z'))
    results = sampler.run(circuit_y, repetitions=repetitions)
    rho_01_re = 0.5 - np.mean(results.measurements['z'])

    rho_01 = rho_01_re + 1j * rho_01_im
    rho_10 = np.conj(rho_01)

    rho = np.array([[rho_00, rho_01], [rho_10, rho_11]])

    return TomographyResult(rho)

Response: Single - qubit state tomography.


Instruction:
Write a Python 3 script to
generate a two - qubit Clifford gate.

Response:
def _two_qubit_clifford(q_0: devices.GridQubit, q_1: devices.GridQubit,
                        idx: int,
                        cliffords: Cliffords) -> Iterator[ops.OP_TREE]:
    """Generates a two-qubit Clifford gate.

    An integer (idx) from 0 to 11519 is used to generate a two-qubit Clifford
    gate which is constructed with single-qubit X and Y rotations and CZ gates.
    The decomposition of the Cliffords follow those described in the appendix
    of Barends et al., Nature 508, 500.

    The integer idx is first decomposed into idx_0 (which ranges from 0 to
    23), idx_1 (ranging from 0 to 23) and idx_2 (ranging from 0 to 19). idx_0
    and idx_1 determine the two single-qubit rotations which happen at the
    beginning of all two-qubit Clifford gates. idx_2 determines the
    subsequent gates in the following:

    a) If idx_2 = 0, do nothing so the Clifford is just two single-qubit
    Cliffords (total of 24*24 = 576 possibilities).

    b) If idx_2 = 1, perform a CZ, followed by -Y/2 on q_0 and Y/2 on q_1,
    followed by another CZ, followed by Y/2 on q_0 and -Y/2 on q_1, followed
    by one more CZ and finally a Y/2 on q_1. The Clifford is then a member of
    the SWAP-like class (total of 24*24 = 576 possibilities).

    c) If 2 <= idx_2 <= 10, perform a CZ followed by a member of the S_1
    group on q_0 and a member of the S_1^(Y/2) group on q_1. The Clifford is
    a member of the CNOT-like class (a total of 3*3*24*24 = 5184 possibilities).

    d) If 11 <= idx_2 <= 19, perform a CZ, followed by Y/2 on q_0 and -X/2 on
    q_1, followed by another CZ, and finally a member of the S_1^(Y/2) group on
    q_0 and a member of the S_1^(X/2) group on q_1. The Clifford is a member
    of the iSWAP-like class (a total of 3*3*24*24 = 5184 possibilities).

    Through the above process, all 11520 members of the two-qubit Clifford
    group may be generated.

    Args:
        q_0: The first qubit under test.
        q_1: The second qubit under test.
        idx: An integer from 0 to 11519.
        cliffords: A NamedTuple that contains single-qubit Cliffords from the
            C1, S1, S_1^(X/2) and S_1^(Y/2) groups.
    """
    c1 = cliffords.c1_in_xy
    s1 = cliffords.s1
    s1_x = cliffords.s1_x
    s1_y = cliffords.s1_y

    idx_0 = int(idx / 480)
    idx_1 = int((idx % 480) / 20)
    idx_2 = idx - idx_0 * 480 - idx_1 * 20
    yield _single_qubit_gates(c1[idx_0], q_0)
    yield _single_qubit_gates(c1[idx_1], q_1)
    if idx_2 == 1:
        yield ops.CZ(q_0, q_1)
        yield ops.Y(q_0) ** -0.5
        yield ops.Y(q_1) ** 0.5
        yield ops.CZ(q_0, q_1)
        yield ops.Y(q_0) ** 0.5
        yield ops.Y(q_1) ** -0.5
        yield ops.CZ(q_0, q_1)
        yield ops.Y(q_1) ** 0.5
    elif 2 <= idx_2 <= 10:
        yield ops.CZ(q_0, q_1)
        idx_3 = int((idx_2 - 2) / 3)
        idx_4 = (idx_2 - 2) % 3
        yield _single_qubit_gates(s1[idx_3], q_0)
        yield _single_qubit_gates(s1_y[idx_4], q_1)
    elif idx_2 >= 11:
        yield ops.CZ(q_0, q_1)
        yield ops.Y(q_0) ** 0.5
        yield ops.X(q_1) ** -0.5
        yield ops.CZ(q_0, q_1)
        idx_3 = int((idx_2 - 11) / 3)
        idx_4 = (idx_2 - 11) % 3
        yield _single_qubit_gates(s1_y[idx_3], q_0)
        yield _single_qubit_gates(s1_x[idx_4], q_1)


Instruction:
Create a Python 3 function for
returning a sequence of tuples with the first item being a Rabi angle and the second item being the corresponding excited state probability.

Response:
def data(self) -> Sequence[Tuple[float, float]]:
        """Returns a sequence of tuple pairs with the first item being a Rabi
        angle and the second item being the corresponding excited state
        probability.
        """
        return [(angle, prob) for angle, prob in zip(self._rabi_angles,
                                                     self._excited_state_probs)]


Instruction:
How would you explain what the following Python 3 function does
def plot(self, **plot_kwargs: Any) -> None:
        fig = plt.figure()
        plt.plot(self._rabi_angles, self._excited_state_probs, 'ro-',
                 figure=fig, **plot_kwargs)
        plt.xlabel(r"Rabi Angle (Radian)", figure=fig)
        plt.ylabel('Excited State Probability', figure=fig)
        fig.show()

Response: Plots excited state probability vs the Rabi angle.


Instruction:
Can you write a function in Python 3 where it
returns a sequence of tuples with the first item being the number of Cliffords and the second item being the ground state probability.

Response:
def data(self) -> Sequence[Tuple[int, float]]:
        """Returns a sequence of tuple pairs with the first item being a
        number of Cliffords and the second item being the corresponding average
        ground state probability.
        """
        return [(num, prob) for num, prob in zip(self._num_cfds_seq,
                                                 self._gnd_state_probs)]


Instruction:
Can you implement a function in Python 3 that
plots the average ground state probability vs the number of cliffords in the RB study.

Response:
def plot(self, **plot_kwargs: Any) -> None:
        """Plots the average ground state probability vs the number of
        Cliffords in the RB study.

        Args:
            **plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot.
        """
        fig = plt.figure()
        plt.plot(self._num_cfds_seq, self._gnd_state_probs, 'ro-',
                 figure=fig, **plot_kwargs)
        plt.xlabel(r"Number of Cliffords", figure=fig)
        plt.ylabel('Ground State Probability', figure=fig)
        fig.show()


Instruction:
Can you tell what is the following Python 3 function doing
def reflection_matrix_pow(reflection_matrix: np.ndarray, exponent: float):

    # The eigenvalues are x and -x for some complex unit x. Determine x.
    squared_phase = np.dot(reflection_matrix[:, 0],
                           reflection_matrix[0, :])
    phase = complex(np.sqrt(squared_phase))

    # Extract +x and -x eigencomponents of the matrix.
    i = np.eye(reflection_matrix.shape[0]) * phase
    pos_part = (i + reflection_matrix) * 0.5
    neg_part = (i - reflection_matrix) * 0.5

    # Raise the matrix to a power by raising its eigencomponents to that power.
    pos_factor = phase**(exponent - 1)
    neg_factor = pos_factor * complex(-1)**exponent
    pos_part_raised = pos_factor * pos_part
    neg_part_raised = neg_part * neg_factor
    return pos_part_raised + neg_part_raised

Response: Raises a matrix with two opposing eigenvalues to a power.


Instruction:
How would you code a function in Python 3 to
return the phase of two numpy arrays that agree on the global phase of one entry.

Response:
def match_global_phase(a: np.ndarray,
                       b: np.ndarray
                       ) -> Tuple[np.ndarray, np.ndarray]:
    """Phases the given matrices so that they agree on the phase of one entry.

    To maximize precision, the position with the largest entry from one of the
    matrices is used when attempting to compute the phase difference between
    the two matrices.

    Args:
        a: A numpy array.
        b: Another numpy array.

    Returns:
        A tuple (a', b') where a' == b' implies a == b*exp(i t) for some t.
    """

    # Not much point when they have different shapes.
    if a.shape != b.shape:
        return a, b

    # Find the entry with the largest magnitude in one of the matrices.
    k = max(np.ndindex(*a.shape), key=lambda t: abs(b[t]))

    def dephase(v):
        r = np.real(v)
        i = np.imag(v)

        # Avoid introducing floating point error when axis-aligned.
        if i == 0:
            return -1 if r < 0 else 1
        if r == 0:
            return 1j if i < 0 else -1j

        return np.exp(-1j * np.arctan2(i, r))

    # Zero the phase at this entry in both matrices.
    return a * dephase(a[k]), b * dephase(b[k])


Instruction:
How would you explain what the following Python 3 function does
def targeted_left_multiply(left_matrix: np.ndarray,
                           right_target: np.ndarray,
                           target_axes: Sequence[int],
                           out: Optional[np.ndarray] = None
                           ) -> np.ndarray:
    """Left-multiplies the given axes of the target tensor by the given matrix.

    Note that the matrix must have a compatible tensor structure.

    For example, if you have an 6-qubit state vector `input_state` with shape
    (2, 2, 2, 2, 2, 2), and a 2-qubit unitary operation `op` with shape
    (2, 2, 2, 2), and you want to apply `op` to the 5'th and 3'rd qubits
    within `input_state`, then the output state vector is computed as follows:

        output_state = cirq.targeted_left_multiply(op, input_state, [5, 3])

    This method also works when the right hand side is a matrix instead of a
    vector. If a unitary circuit's matrix is `old_effect`, and you append
    a CNOT(q1, q4) operation onto the circuit, where the control q1 is the qubit
    at offset 1 and the target q4 is the qubit at offset 4, then the appended
    circuit's unitary matrix is computed as follows:

        new_effect = cirq.targeted_left_multiply(
            left_matrix=cirq.unitary(cirq.CNOT).reshape((2, 2, 2, 2)),
            right_target=old_effect,
            target_axes=[1, 4])

    Args:
        left_matrix: What to left-multiply the target tensor by.
        right_target: A tensor to carefully broadcast a left-multiply over.
        target_axes: Which axes of the target are being operated on.
        out: The buffer to store the results in. If not specified or None, a new
            buffer is used. Must have the same shape as right_target.

    Returns:
        The output tensor.
    """
    k = len(target_axes)
    d = len(right_target.shape)
    work_indices = tuple(range(k))
    data_indices = tuple(range(k, k + d))
    used_data_indices = tuple(data_indices[q] for q in target_axes)
    input_indices = work_indices + used_data_indices
    output_indices = list(data_indices)
    for w, t in zip(work_indices, target_axes):
        output_indices[t] = w

    all_indices = set(input_indices + data_indices + tuple(output_indices))

    return np.einsum(left_matrix, input_indices,
                     right_target, data_indices,
                     output_indices,
                     # We would prefer to omit 'optimize=' (it's faster),
                     # but this is a workaround for a bug in numpy:
                     #     https://github.com/numpy/numpy/issues/10926
                     optimize=len(all_indices) >= 26,
                     # And this is workaround for *another* bug!
                     # Supposed to be able to just say 'old=old'.
                     **({'out': out} if out is not None else {}))

Response: Left - multiplies the given axes of the target tensor by the given matrix.


Instruction:
Write a Python 3 script for
leaving - multiplies a matrix onto N slices.

Response:
def apply_matrix_to_slices(
        target: np.ndarray,
        matrix: np.ndarray,
        slices: List[_TSlice],
        *,
        out: Optional[np.ndarray] = None) -> np.ndarray:
    """Left-multiplies an NxN matrix onto N slices of a numpy array.

    Example:
        The 4x4 matrix of a fractional SWAP gate can be expressed as

           [ 1       ]
           [   X**t  ]
           [       1 ]

        Where X is the 2x2 Pauli X gate and t is the power of the swap with t=1
        being a full swap. X**t is a power of the Pauli X gate's matrix.
        Applying the fractional swap is equivalent to applying a fractional X
        within the inner 2x2 subspace; the rest of the matrix is identity. This
        can be expressed using `apply_matrix_to_slices` as follows:

            def fractional_swap(target):
                assert target.shape == (4,)
                return apply_matrix_to_slices(
                    target=target,
                    matrix=cirq.unitary(cirq.X**t),
                    slices=[1, 2]
                )

    Args:
        target: The input array with slices that need to be left-multiplied.
        matrix: The linear operation to apply to the subspace defined by the
            slices.
        slices: The parts of the tensor that correspond to the "vector entries"
            that the matrix should operate on. May be integers or complicated
            multi-dimensional slices into a tensor. The slices must refer to
            non-overlapping sections of the input all with the same shape.
        out: Where to write the output. If not specified, a new numpy array is
            created, with the same shape and dtype as the target, to store the
            output.

    Returns:
        The transformed array.
    """
    # Validate arguments.
    if out is target:
        raise ValueError("Can't write output over the input.")
    if matrix.shape != (len(slices), len(slices)):
        raise ValueError("matrix.shape != (len(slices), len(slices))")

    # Fill in default values and prepare space.
    if out is None:
        out = np.copy(target)
    else:
        out[...] = target[...]

    # Apply operation.
    for i, s_i in enumerate(slices):
        out[s_i] *= matrix[i, i]
        for j, s_j in enumerate(slices):
            if i != j:
                out[s_i] += target[s_j] * matrix[i, j]

    return out


Instruction:
How would you code a function in Python 3 to
take the partial trace of a given tensor.

Response:
def partial_trace(tensor: np.ndarray,
                  keep_indices: List[int]) -> np.ndarray:
    """Takes the partial trace of a given tensor.

    The input tensor must have shape `(d_0, ..., d_{k-1}, d_0, ..., d_{k-1})`.
    The trace is done over all indices that are not in keep_indices. The
    resulting tensor has shape `(d_{i_0}, ..., d_{i_r}, d_{i_0}, ..., d_{i_r})`
    where `i_j` is the `j`th element of `keep_indices`.

    Args:
        tensor: The tensor to sum over. This tensor must have a shape
            `(d_0, ..., d_{k-1}, d_0, ..., d_{k-1})`.
        keep_indices: Which indices to not sum over. These are only the indices
            of the first half of the tensors indices (i.e. all elements must
            be between `0` and `tensor.ndims / 2 - 1` inclusive).

    Raises:
        ValueError: if the tensor is not of the correct shape or the indices
            are not from the first half of valid indices for the tensor.
    """
    ndim = tensor.ndim // 2
    if not all(tensor.shape[i] == tensor.shape[i + ndim] for i in range(ndim)):
        raise ValueError('Tensors must have shape (d_0,...,d_{{k-1}},d_0,...,'
                         'd_{{k-1}}) but had shape ({}).'.format(tensor.shape))
    if not all(i < ndim for i in keep_indices):
        raise ValueError('keep_indices were {} but must be in first half, '
                         'i.e. have index less that {}.'.format(keep_indices,
                                                                ndim))
    keep_set = set(keep_indices)
    keep_map = dict(zip(keep_indices, sorted(keep_indices)))
    left_indices = [keep_map[i] if i in keep_set else i for i in range(ndim)]
    right_indices = [ndim + i if i in keep_set else i for i in left_indices]
    return np.einsum(tensor, left_indices + right_indices)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def mul(lhs: Any, rhs: Any, default: Any = RaiseTypeErrorIfNotProvided) -> Any:
    # Use left-hand-side's __mul__.
    left_mul = getattr(lhs, '__mul__', None)
    result = NotImplemented if left_mul is None else left_mul(rhs)

    # Fallback to right-hand-side's __rmul__.
    if result is NotImplemented:
        right_mul = getattr(rhs, '__rmul__', None)
        result = NotImplemented if right_mul is None else right_mul(lhs)

    # Don't build up factors of 1.0 vs sympy Symbols.
    if lhs == 1 and is_parameterized(rhs):
        result = rhs
    if rhs == 1 and is_parameterized(lhs):
        result = lhs
    if lhs == -1 and is_parameterized(rhs):
        result = -rhs
    if rhs == -1 and is_parameterized(lhs):
        result = -lhs

    # Output.
    if result is not NotImplemented:
        return result
    if default is not RaiseTypeErrorIfNotProvided:
        return default
    raise TypeError("unsupported operand type(s) for *: '{}' and '{}'".format(
        type(lhs), type(rhs)))

Response: Returns the product of two sets of elements.


Instruction:
How would you code a function in Python 3 to
determine if a matrix is approximately diagonal.

Response:
def is_diagonal(matrix: np.ndarray, *, atol: float = 1e-8) -> bool:
    """Determines if a matrix is a approximately diagonal.

    A matrix is diagonal if i!=j implies m[i,j]==0.

    Args:
        matrix: The matrix to check.
        atol: The per-matrix-entry absolute tolerance on equality.

    Returns:
        Whether the matrix is diagonal within the given tolerance.
    """
    matrix = np.copy(matrix)
    for i in range(min(matrix.shape)):
        matrix[i, i] = 0
    return tolerance.all_near_zero(matrix, atol=atol)


Instruction:
Can you generate the documentation for the following Python 3 function
def is_hermitian(
        matrix: np.ndarray,
        *,
        rtol: float = 1e-5,
        atol: float = 1e-8) -> bool:
    """Determines if a matrix is approximately Hermitian.

    A matrix is Hermitian if it's square and equal to its adjoint.

    Args:
        matrix: The matrix to check.
        rtol: The per-matrix-entry relative tolerance on equality.
        atol: The per-matrix-entry absolute tolerance on equality.

    Returns:
        Whether the matrix is Hermitian within the given tolerance.
    """
    return (matrix.shape[0] == matrix.shape[1] and
            np.allclose(matrix, np.conj(matrix.T), rtol=rtol, atol=atol))

Response: Determines if a matrix is approximately Hermitian.


Instruction:
Write a Python 3 function that can
determine if a matrix is approximately orthogonal.

Response:
def is_orthogonal(
        matrix: np.ndarray,
        *,
        rtol: float = 1e-5,
        atol: float = 1e-8) -> bool:
    """Determines if a matrix is approximately orthogonal.

    A matrix is orthogonal if it's square and real and its transpose is its
    inverse.

    Args:
        matrix: The matrix to check.
        rtol: The per-matrix-entry relative tolerance on equality.
        atol: The per-matrix-entry absolute tolerance on equality.

    Returns:
        Whether the matrix is orthogonal within the given tolerance.
    """
    return (matrix.shape[0] == matrix.shape[1] and
            np.all(np.imag(matrix) == 0) and
            np.allclose(matrix.dot(matrix.T), np.eye(matrix.shape[0]),
                        rtol=rtol,
                        atol=atol))


Instruction:
Can you tell what is the following Python 3 function doing
def is_special_orthogonal(
        matrix: np.ndarray,
        *,
        rtol: float = 1e-5,
        atol: float = 1e-8) -> bool:
    """Determines if a matrix is approximately special orthogonal.

    A matrix is special orthogonal if it is square and real and its transpose
    is its inverse and its determinant is one.

    Args:
        matrix: The matrix to check.
        rtol: The per-matrix-entry relative tolerance on equality.
        atol: The per-matrix-entry absolute tolerance on equality.

    Returns:
        Whether the matrix is special orthogonal within the given tolerance.
    """
    return (is_orthogonal(matrix, rtol=rtol, atol=atol) and
            (matrix.shape[0] == 0 or
             np.allclose(np.linalg.det(matrix), 1, rtol=rtol, atol=atol)))

Response: Determines if a matrix is approximately special orthogonal.


Instruction:
Explain what the following Python 3 code does
def is_unitary(
        matrix: np.ndarray,
        *,
        rtol: float = 1e-5,
        atol: float = 1e-8) -> bool:
    """Determines if a matrix is approximately unitary.

    A matrix is unitary if it's square and its adjoint is its inverse.

    Args:
        matrix: The matrix to check.
        rtol: The per-matrix-entry relative tolerance on equality.
        atol: The per-matrix-entry absolute tolerance on equality.

    Returns:
        Whether the matrix is unitary within the given tolerance.
    """
    return (matrix.shape[0] == matrix.shape[1] and
            np.allclose(matrix.dot(np.conj(matrix.T)), np.eye(matrix.shape[0]),
                        rtol=rtol,
                        atol=atol))

Response: Determines if a matrix is approximately unitary.


Instruction:
Can you generate the documentation for the following Python 3 function
def is_special_unitary(
        matrix: np.ndarray,
        *,
        rtol: float = 1e-5,
        atol: float = 1e-8) -> bool:
    """Determines if a matrix is approximately unitary with unit determinant.

    A matrix is special-unitary if it is square and its adjoint is its inverse
    and its determinant is one.

    Args:
        matrix: The matrix to check.
        rtol: The per-matrix-entry relative tolerance on equality.
        atol: The per-matrix-entry absolute tolerance on equality.
    Returns:
        Whether the matrix is unitary with unit determinant within the given
        tolerance.
    """
    return (is_unitary(matrix, rtol=rtol, atol=atol) and
            (matrix.shape[0] == 0 or
             np.allclose(np.linalg.det(matrix), 1, rtol=rtol, atol=atol)))

Response: Determines if a matrix is approximately unitary with unit determinant.


Instruction:
Write a Python 3 script for
determining if two matrices approximately commute.

Response:
def commutes(
        m1: np.ndarray,
        m2: np.ndarray,
        *,
        rtol: float = 1e-5,
        atol: float = 1e-8) -> bool:
    """Determines if two matrices approximately commute.

    Two matrices A and B commute if they are square and have the same size and
    AB = BA.

    Args:
        m1: One of the matrices.
        m2: The other matrix.
        rtol: The per-matrix-entry relative tolerance on equality.
        atol: The per-matrix-entry absolute tolerance on equality.

    Returns:
        Whether the two matrices have compatible sizes and a commutator equal
        to zero within tolerance.
  """
    return (m1.shape[0] == m1.shape[1] and
            m1.shape == m2.shape and
            np.allclose(m1.dot(m2), m2.dot(m1), rtol=rtol, atol=atol))


Instruction:
Can you create a Python 3 function that
determines if two arrays are all close to global phase.

Response:
def allclose_up_to_global_phase(
        a: np.ndarray,
        b: np.ndarray,
        *,
        rtol: float = 1.e-5,
        atol: float = 1.e-8,
        equal_nan: bool = False
) -> bool:
    """Determines if a ~= b * exp(i t) for some t.

    Args:
        a: A numpy array.
        b: Another numpy array.
        rtol: Relative error tolerance.
        atol: Absolute error tolerance.
        equal_nan: Whether or not NaN entries should be considered equal to
            other NaN entries.
    """

    a, b = transformations.match_global_phase(a, b)

    # Should now be equivalent.
    return np.allclose(a=a, b=b, rtol=rtol, atol=atol, equal_nan=equal_nan)


Instruction:
Can you create a Python 3 function that
returns an index corresponding to a desired subset of an np. ndarray.

Response:
def slice_for_qubits_equal_to(target_qubit_axes: Sequence[int],
                              little_endian_qureg_value: int,
                              *,  # Forces keyword args.
                              num_qubits: int = None
                              ) -> Tuple[Union[slice, int, 'ellipsis'], ...]:
    """Returns an index corresponding to a desired subset of an np.ndarray.

    It is assumed that the np.ndarray's shape is of the form (2, 2, 2, ..., 2).

    Example:

        ```python
        # A '4 qubit' tensor with values from 0 to 15.
        r = np.array(range(16)).reshape((2,) * 4)

        # We want to index into the subset where qubit #1 and qubit #3 are ON.
        s = cirq.slice_for_qubits_equal_to([1, 3], 0b11)
        print(s)
        # (slice(None, None, None), 1, slice(None, None, None), 1, Ellipsis)

        # Get that subset. It corresponds to numbers of the form 0b*1*1.
        # where here '*' indicates any possible value.
        print(r[s])
        # [[ 5  7]
        #  [13 15]]
        ```

    Args:
        target_qubit_axes: The qubits that are specified by the index bits. All
            other axes of the slice are unconstrained.
        little_endian_qureg_value: An integer whose bits specify what value is
            desired for of the target qubits. The integer is little endian
            w.r.t. the target quit axes, meaning the low bit of the integer
            determines the desired value of the first targeted qubit, and so
            forth with the k'th targeted qubit's value set to
            bool(qureg_value & (1 << k)).
        num_qubits: If specified the slices will extend all the way up to
            this number of qubits, otherwise if it is None, the final element
            return will be Ellipsis. Optional and defaults to using Ellipsis.

    Returns:
        An index object that will slice out a mutable view of the desired subset
        of a tensor.
    """
    n = num_qubits if num_qubits is not None else (
        max(target_qubit_axes) if target_qubit_axes else -1)
    result = [slice(None)] * (n + 2 * (
            num_qubits is None))  # type: List[Union[slice, int, ellipsis]]
    for k, axis in enumerate(target_qubit_axes):
        result[axis] = (little_endian_qureg_value >> k) & 1
    if num_qubits is None:
        result[-1] = Ellipsis
    return tuple(result)


Instruction:
Create a Python 3 function to
create a scheduled operation at a specific time.

Response:
def op_at_on(operation: ops.Operation,
                 time: Timestamp,
                 device: Device):
        """Creates a scheduled operation with a device-determined duration."""
        return ScheduledOperation(time,
                                  device.duration_of(operation),
                                  operation)


Instruction:
Here you have a function in Python 3, explain what it does
def num_qubits(self) -> Optional[int]:
        if not self:
            return None
        any_gate = next(iter(self))
        return any_gate.num_qubits()

Response: Returns the number of qubits in the domain if known None otherwise.


Instruction:
How would you implement a function in Python 3 that
reconstructs matrix of self using unitaries of underlying gates.

Response:
def matrix(self) -> np.ndarray:
        """Reconstructs matrix of self using unitaries of underlying gates.

        Raises:
            TypeError: if any of the gates in self does not provide a unitary.
        """
        num_qubits = self.num_qubits()
        if num_qubits is None:
            raise ValueError('Unknown number of qubits')
        num_dim = 2 ** num_qubits
        result = np.zeros((num_dim, num_dim), dtype=np.complex128)
        for gate, coefficient in self.items():
            result += protocols.unitary(gate) * coefficient
        return result


Instruction:
Can you generate the documentation for the following Python 3 function
def box_draw_character(first: Optional[BoxDrawCharacterSet],
                       second: BoxDrawCharacterSet,
                       *,
                       top: int = 0,
                       bottom: int = 0,
                       left: int = 0,
                       right: int = 0) -> Optional[str]:
    """Finds a box drawing character based on its connectivity.

    For example:

        box_draw_character(
            NORMAL_BOX_CHARS,
            BOLD_BOX_CHARS,
            top=-1,
            right=+1)

    evaluates to '┕', which has a normal upward leg and bold rightward leg.

    Args:
        first: The character set to use for legs set to -1. If set to None,
            defaults to the same thing as the second character set.
        second: The character set to use for legs set to +1.
        top: Whether the upward leg should be present.
        bottom: Whether the bottom leg should be present.
        left: Whether the left leg should be present.
        right: Whether the right leg should be present.

    Returns:
        A box drawing character approximating the desired properties, or None
        if all legs are set to 0.
    """
    if first is None:
        first = second
    sign = +1
    combo = None

    # Known combinations.
    if first is NORMAL_BOX_CHARS and second is BOLD_BOX_CHARS:
        combo = NORMAL_THEN_BOLD_MIXED_BOX_CHARS
    if first is BOLD_BOX_CHARS and second is NORMAL_BOX_CHARS:
        combo = NORMAL_THEN_BOLD_MIXED_BOX_CHARS
        sign = -1

    if combo is None:
        choice = second if +1 in [top, bottom, left, right] else first
        return choice.char(top=bool(top),
                           bottom=bool(bottom),
                           left=bool(left),
                           right=bool(right))

    return combo.char(top=top * sign,
                      bottom=bottom * sign,
                      left=left * sign,
                      right=right * sign)

Response: Finds a box drawing character based on its connectivity.


Instruction:
Write a Python 3 function for
returning an application of this gate to the given qubits.

Response:
def on(self,
           *qubits: raw_types.Qid) -> 'SingleQubitPauliStringGateOperation':
        """Returns an application of this gate to the given qubits.

        Args:
            *qubits: The collection of qubits to potentially apply the gate to.
        """
        if len(qubits) != 1:
            raise ValueError(
                'Expected a single qubit, got <{!r}>.'.format(qubits))
        from cirq.ops.pauli_string import SingleQubitPauliStringGateOperation
        return SingleQubitPauliStringGateOperation(self, qubits[0])


Instruction:
Can you generate the documentation for the following Python 3 function
def decompose(
    val: TValue,
    *,
    intercepting_decomposer: Callable[['cirq.Operation'],
                                      Union[None,
                                            NotImplementedType,
                                            'cirq.OP_TREE']] = None,
    fallback_decomposer: Callable[['cirq.Operation'],
                                  Union[None,
                                        NotImplementedType,
                                        'cirq.OP_TREE']] = None,
    keep: Callable[['cirq.Operation'], bool] = None,
    on_stuck_raise: Union[None,
                          Exception,
                          Callable[['cirq.Operation'],
                                   Union[None, Exception]]]
    = _value_error_describing_bad_operation
) -> List['cirq.Operation']:
    """Recursively decomposes a value into `cirq.Operation`s meeting a criteria.

    Args:
        val: The value to decompose into operations.
        intercepting_decomposer: An optional method that is called before the
            default decomposer (the value's `_decompose_` method). If
            `intercepting_decomposer` is specified and returns a result that
            isn't `NotImplemented` or `None`, that result is used. Otherwise the
            decomposition falls back to the default decomposer.

            Note that `val` will be passed into `intercepting_decomposer`, even
            if `val` isn't a `cirq.Operation`.
        fallback_decomposer: An optional decomposition that used after the
            `intercepting_decomposer` and the default decomposer (the value's
            `_decompose_` method) both fail.
        keep: A predicate that determines if the initial operation or
            intermediate decomposed operations should be kept or else need to be
            decomposed further. If `keep` isn't specified, it defaults to "value
            can't be decomposed anymore".
        on_stuck_raise: If there is an operation that can't be decomposed and
            also can't be kept, `on_stuck_raise` is used to determine what error
            to raise. `on_stuck_raise` can either directly be an `Exception`, or
            a method that takes the problematic operation and returns an
            `Exception`. If `on_stuck_raise` is set to `None` or a method that
            returns `None`, undecomposable operations are simply silently kept.
            `on_stuck_raise` defaults to a `ValueError` describing the unwanted
            undecomposable operation.

    Returns:
        A list of operations that the given value was decomposed into. If
        `on_stuck_raise` isn't set to None, all operations in the list will
        satisfy the predicate specified by `keep`.

    Raises:
        TypeError:
            `val` isn't a `cirq.Operation` and can't be decomposed even once.
            (So it's not possible to return a list of operations.)

        ValueError:
            Default type of error raised if there's an undecomposable operation
            that doesn't satisfy the given `keep` predicate.

        TError:
            Custom type of error raised if there's an undecomposable operation
            that doesn't satisfy the given `keep` predicate.
    """
    from cirq import ops  # HACK: Avoids circular dependencies.

    if (on_stuck_raise is not _value_error_describing_bad_operation and
            keep is None):
        raise ValueError(
            "Must specify 'keep' if specifying 'on_stuck_raise', because it's "
            "not possible to get stuck if you don't have a criteria on what's "
            "acceptable to keep.")

    decomposers = [d
                   for d in [intercepting_decomposer,
                             _default_decomposer,
                             fallback_decomposer]
                   if d]

    def decomposer(op):
        for d in decomposers:
            r = d(op)
            if r is not NotImplemented and r is not None:
                return r
        return NotImplemented

    output = []
    queue = [val]  # type: List[Any]
    while queue:
        item = queue.pop(0)

        if isinstance(item, ops.Operation) and keep is not None and keep(item):
            output.append(item)
            continue

        decomposed = decomposer(item)
        if decomposed is not NotImplemented and decomposed is not None:
            queue[:0] = ops.flatten_op_tree(decomposed)
            continue

        if (not isinstance(item, ops.Operation) and
                isinstance(item, collections.Iterable)):
            queue[:0] = ops.flatten_op_tree(item)
            continue

        if keep is not None and on_stuck_raise is not None:
            if isinstance(on_stuck_raise, Exception):
                raise on_stuck_raise
            elif callable(on_stuck_raise):
                error = on_stuck_raise(item)
                if error is not None:
                    raise error

        output.append(item)

    return output

Response: Recursively decompose a value into a list of cirq. Operation objects.


Instruction:
Can you tell what is the following Python 3 function doing
def decompose_once(val: Any,
                   default=RaiseTypeErrorIfNotProvided,
                   **kwargs):
    """Decomposes a value into operations, if possible.

    This method decomposes the value exactly once, instead of decomposing it
    and then continuing to decomposing the decomposed operations recursively
    until some criteria is met (which is what `cirq.decompose` does).

    Args:
        val: The value to call `_decompose_` on, if possible.
        default: A default result to use if the value doesn't have a
            `_decompose_` method or that method returns `NotImplemented` or
            `None`. If not specified, undecomposable values cause a `TypeError`.
        kwargs: Arguments to forward into the `_decompose_` method of `val`.
            For example, this is used to tell gates what qubits they are being
            applied to.

    Returns:
        The result of `val._decompose_(**kwargs)`, if `val` has a `_decompose_`
        method and it didn't return `NotImplemented` or `None`. Otherwise
        `default` is returned, if it was specified. Otherwise an error is
        raised.

    TypeError:
        `val` didn't have a `_decompose_` method (or that method returned
        `NotImplemented` or `None`) and `default` wasn't set.
    """
    method = getattr(val, '_decompose_', None)
    decomposed = NotImplemented if method is None else method(**kwargs)

    if decomposed is not NotImplemented and decomposed is not None:
        from cirq import ops  # HACK: Avoids circular dependencies.
        return list(ops.flatten_op_tree(decomposed))

    if default is not RaiseTypeErrorIfNotProvided:
        return default
    if method is None:
        raise TypeError("object of type '{}' "
                        "has no _decompose_ method.".format(type(val)))
    raise TypeError("object of type '{}' does have a _decompose_ method, "
                    "but it returned NotImplemented or None.".format(type(val)))

Response: Decomposes a value into operations recursively returning a list of the result of decomposing it.


Instruction:
Explain what the following Python 3 code does
def decompose_once_with_qubits(val: Any,
                               qubits: Iterable['cirq.Qid'],
                               default=RaiseTypeErrorIfNotProvided):
    """Decomposes a value into operations on the given qubits.

    This method is used when decomposing gates, which don't know which qubits
    they are being applied to unless told. It decomposes the gate exactly once,
    instead of decomposing it and then continuing to decomposing the decomposed
    operations recursively until some criteria is met.

    Args:
        val: The value to call `._decompose_(qubits=qubits)` on, if possible.
        qubits: The value to pass into the named `qubits` parameter of
            `val._decompose_`.
        default: A default result to use if the value doesn't have a
            `_decompose_` method or that method returns `NotImplemented` or
            `None`. If not specified, undecomposable values cause a `TypeError`.

    Returns:
        The result of `val._decompose_(qubits=qubits)`, if `val` has a
        `_decompose_` method and it didn't return `NotImplemented` or `None`.
        Otherwise `default` is returned, if it was specified. Otherwise an error
        is raised.

    TypeError:
        `val` didn't have a `_decompose_` method (or that method returned
        `NotImplemented` or `None`) and `default` wasn't set.
    """
    return decompose_once(val, default, qubits=tuple(qubits))

Response: Decomposes a value into operations on the given qubits.


Instruction:
Write a Python 3 script to
return an explicit basis set that forces the given qubits in the given order.

Response:
def explicit(fixed_qubits: Iterable[raw_types.Qid],
                 fallback: Optional['QubitOrder']=None) -> 'QubitOrder':
        """A basis that contains exactly the given qubits in the given order.

        Args:
            fixed_qubits: The qubits in basis order.
            fallback: A fallback order to use for extra qubits not in the
                fixed_qubits list. Extra qubits will always come after the
                fixed_qubits, but will be ordered based on the fallback. If no
                fallback is specified, a ValueError is raised when extra qubits
                are specified.

        Returns:
            A Basis instance that forces the given qubits in the given order.
        """
        result = tuple(fixed_qubits)
        if len(set(result)) < len(result):
            raise ValueError(
                'Qubits appear in fixed_order twice: {}.'.format(result))

        def func(qubits):
            remaining = set(qubits) - set(fixed_qubits)
            if not remaining:
                return result
            if not fallback:
                raise ValueError(
                    'Unexpected extra qubits: {}.'.format(remaining))
            return result + fallback.order_for(remaining)

        return QubitOrder(func)


Instruction:
Explain what the following Python 3 code does
def order_for(self, qubits: Iterable[raw_types.Qid]
                  ) -> Tuple[raw_types.Qid, ...]:
        """Returns a qubit tuple ordered corresponding to the basis.

        Args:
            qubits: Qubits that should be included in the basis. (Additional
                qubits may be added into the output by the basis.)

        Returns:
            A tuple of qubits in the same order that their single-qubit
            matrices would be passed into `np.kron` when producing a matrix for
            the entire system.
        """
        return self._explicit_func(qubits)

Response: Returns a qubit tuple ordered corresponding to the basis.


Instruction:
Can you generate the documentation for the following Python 3 function
def as_qubit_order(val: 'qubit_order_or_list.QubitOrderOrList'
                       ) -> 'QubitOrder':
        """Converts a value into a basis.

        Args:
            val: An iterable or a basis.

        Returns:
            The basis implied by the value.
        """
        if isinstance(val, collections.Iterable):
            return QubitOrder.explicit(val)
        if isinstance(val, QubitOrder):
            return val
        raise ValueError(
            "Don't know how to interpret <{}> as a Basis.".format(val))

Response: Converts a value into a basis set.


Instruction:
How would you code a function in Python 3 to
transform the Basis so that it applies to the internal and external qubits.

Response:
def map(self,
            internalize: Callable[[TExternalQubit], TInternalQubit],
            externalize: Callable[[TInternalQubit], TExternalQubit]
            ) -> 'QubitOrder':
        """Transforms the Basis so that it applies to wrapped qubits.

        Args:
            externalize: Converts an internal qubit understood by the underlying
                basis into an external qubit understood by the caller.
            internalize: Converts an external qubit understood by the caller
                into an internal qubit understood by the underlying basis.

        Returns:
            A basis that transforms qubits understood by the caller into qubits
            understood by an underlying basis, uses that to order the qubits,
            then wraps the ordered qubits back up for the caller.
        """

        def func(qubits):
            unwrapped_qubits = [internalize(q) for q in qubits]
            unwrapped_result = self.order_for(unwrapped_qubits)
            return tuple(externalize(q) for q in unwrapped_result)

        return QubitOrder(func)


Instruction:
Can you tell what is the following Python 3 function doing
def range(*args, prefix: str):
        return [NamedQubit(prefix + str(i)) for i in range(*args)]

Response: Returns a range of NamedQubits.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def channel(val: Any,
            default: Any = RaiseTypeErrorIfNotProvided
            ) -> Union[Tuple[np.ndarray], Sequence[TDefault]]:
    r"""Returns a list of matrices describing the channel for the given value.

    These matrices are the terms in the operator sum representation of
    a quantum channel. If the returned matrices are {A_0,A_1,..., A_{r-1}},
    then this describes the channel:
        \rho \rightarrow \sum_{k=0}^{r-1} A_0 \rho A_0^\dagger
    These matrices are required to satisfy the trace preserving condition
        \sum_{k=0}^{r-1} A_i^\dagger A_i = I
    where I is the identity matrix. The matrices A_i are sometimes called
    Krauss or noise operators.

    Args:
        val: The value to describe by a channel.
        default: Determines the fallback behavior when `val` doesn't have
            a channel. If `default` is not set, a TypeError is raised. If
            default is set to a value, that value is returned.

    Returns:
        If `val` has a `_channel_` method and its result is not NotImplemented,
        that result is returned. Otherwise, if `val` has a `_mixture_` method
        and its results is not NotImplement a tuple made up of channel
        corresponding to that mixture being a probabilistic mixture of unitaries
        is returned.  Otherwise, if `val` has a `_unitary_` method and
        its result is not NotImplemented a tuple made up of that result is
        returned. Otherwise, if a default value was specified, the default
        value is returned.

    Raises:
        TypeError: `val` doesn't have a _channel_ or _unitary_ method (or that
            method returned NotImplemented) and also no default value was
            specified.
    """
    channel_getter = getattr(val, '_channel_', None)
    channel_result = (
        NotImplemented if channel_getter is None else channel_getter())
    if channel_result is not NotImplemented:
        return tuple(channel_result)

    mixture_getter = getattr(val, '_mixture_', None)
    mixture_result = (
        NotImplemented if mixture_getter is None else mixture_getter())
    if mixture_result is not NotImplemented:
        return tuple(np.sqrt(p) * u for p, u in mixture_result)

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

    if default is not RaiseTypeErrorIfNotProvided:
        return default

    if (channel_getter is None and unitary_getter is None
            and mixture_getter is None):
        raise TypeError("object of type '{}' has no _channel_ or _mixture_ or "
                        "_unitary_ method.".format(type(val)))
    raise TypeError("object of type '{}' does have a _channel_, _mixture_ or "
                "_unitary_ method, but it returned NotImplemented."
                .format(type(val)))

Response: r Returns a list of matrices describing the channel for the given value.


Instruction:
Here you have a function in Python 3, explain what it does
def has_channel(val: Any) -> bool:
    channel_getter = getattr(val, '_has_channel_', None)
    result = NotImplemented if channel_getter is None else channel_getter()

    if result is not NotImplemented:
        return result

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

    # No has methods, use `_channel_` or delegates instead.
    return channel(val, None) is not None

Response: Returns whether the value has a channel representation.


Instruction:
Explain what the following Python 3 code does
def two_qubit_matrix_to_operations(q0: ops.Qid,
                                   q1: ops.Qid,
                                   mat: np.ndarray,
                                   allow_partial_czs: bool,
                                   atol: float = 1e-8,
                                   clean_operations: bool = True,
                                   ) -> List[ops.Operation]:
    """Decomposes a two-qubit operation into Z/XY/CZ gates.

    Args:
        q0: The first qubit being operated on.
        q1: The other qubit being operated on.
        mat: Defines the operation to apply to the pair of qubits.
        allow_partial_czs: Enables the use of Partial-CZ gates.
        atol: A limit on the amount of absolute error introduced by the
            construction.
        clean_operations: Enables optimizing resulting operation list by
            merging operations and ejecting phased Paulis and Z operations.

    Returns:
        A list of operations implementing the matrix.
    """
    kak = linalg.kak_decomposition(mat, atol=atol)
    operations = _kak_decomposition_to_operations(
        q0, q1, kak, allow_partial_czs, atol=atol)
    if clean_operations:
        return _cleanup_operations(operations)
    else:
        return operations

Response: Decomposes a two - qubit operation into Z and XY gates.


Instruction:
Can you create a Python 3 function that
returns a list of operations that are part of the decomposition.

Response:
def _kak_decomposition_to_operations(q0: ops.Qid,
                                     q1: ops.Qid,
                                     kak: linalg.KakDecomposition,
                                     allow_partial_czs: bool,
                                     atol: float = 1e-8
                                     ) -> List[ops.Operation]:
    """Assumes that the decomposition is canonical."""
    b0, b1 = kak.single_qubit_operations_before
    pre = [_do_single_on(b0, q0, atol=atol), _do_single_on(b1, q1, atol=atol)]
    a0, a1 = kak.single_qubit_operations_after
    post = [_do_single_on(a0, q0, atol=atol), _do_single_on(a1, q1, atol=atol)]

    return list(cast(Iterable[ops.Operation], ops.flatten_op_tree([
        pre,
        _non_local_part(q0,
                        q1,
                        kak.interaction_coefficients,
                        allow_partial_czs,
                        atol=atol),
        post,
    ])))


Instruction:
Write a Python 3 script to
test if a circuit for an operator expi * rad is trivial.

Response:
def _is_trivial_angle(rad: float, atol: float) -> bool:
    """Tests if a circuit for an operator exp(i*rad*XX) (or YY, or ZZ) can
    be performed with a whole CZ.

    Args:
        rad: The angle in radians, assumed to be in the range [-pi/4, pi/4]
    """
    return abs(rad) < atol or abs(abs(rad) - np.pi / 4) < atol


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _parity_interaction(q0: ops.Qid,
                        q1: ops.Qid,
                        rads: float,
                        atol: float,
                        gate: Optional[ops.Gate] = None):
    """Yields a ZZ interaction framed by the given operation."""
    if abs(rads) < atol:
        return

    h = rads * -2 / np.pi
    if gate is not None:
        g = cast(ops.Gate, gate)
        yield g.on(q0), g.on(q1)

    # If rads is ±pi/4 radians within tolerance, single full-CZ suffices.
    if _is_trivial_angle(rads, atol):
        yield ops.CZ.on(q0, q1)
    else:
        yield ops.CZ(q0, q1) ** (-2 * h)

    yield ops.Z(q0)**h
    yield ops.Z(q1)**h
    if gate is not None:
        g = protocols.inverse(gate)
        yield g.on(q0), g.on(q1)

Response: Yields a ZZ interaction framed by the given operation.


Instruction:
Can you tell what is the following Python 3 function doing
def _non_local_part(q0: ops.Qid,
                    q1: ops.Qid,
                    interaction_coefficients: Tuple[float, float, float],
                    allow_partial_czs: bool,
                    atol: float = 1e-8):
    """Yields non-local operation of KAK decomposition."""

    x, y, z = interaction_coefficients

    if (allow_partial_czs or
        all(_is_trivial_angle(e, atol) for e in [x, y, z])):
        return [
            _parity_interaction(q0, q1, x, atol, ops.Y**-0.5),
            _parity_interaction(q0, q1, y, atol, ops.X**0.5),
            _parity_interaction(q0, q1, z, atol)
        ]

    if abs(z) >= atol:
        return _xx_yy_zz_interaction_via_full_czs(q0, q1, x, y, z)

    if y >= atol:
        return _xx_yy_interaction_via_full_czs(q0, q1, x, y)

    return _xx_interaction_via_full_czs(q0, q1, x)

Response: Yields non - local part of the KAK decomposition.


Instruction:
Explain what the following Python 3 code does
def _run(
        self,
        circuit: circuits.Circuit,
        param_resolver: study.ParamResolver,
        repetitions: int) -> Dict[str, List[np.ndarray]]:
        """See definition in `cirq.SimulatesSamples`."""
        param_resolver = param_resolver or study.ParamResolver({})
        resolved_circuit = protocols.resolve_parameters(circuit, param_resolver)
        def measure_or_mixture(op):
            return protocols.is_measurement(op) or protocols.has_mixture(op)
        if circuit.are_all_matches_terminal(measure_or_mixture):
            return self._run_sweep_sample(resolved_circuit, repetitions)
        else:
            return self._run_sweep_repeat(resolved_circuit, repetitions)

Response: Runs the simulation for the given set of resources.


Instruction:
Can you write a function in Python 3 where it
simulates an operation that has a unitary.

Response:
def _simulate_unitary(self, op: ops.Operation, data: _StateAndBuffer,
            indices: List[int]) -> None:
        """Simulate an op that has a unitary."""
        result = protocols.apply_unitary(
                op,
                args=protocols.ApplyUnitaryArgs(
                        data.state,
                        data.buffer,
                        indices))
        if result is data.buffer:
            data.buffer = data.state
        data.state = result


Instruction:
Can you tell what is the following Python 3 function doing
def _simulate_measurement(self, op: ops.Operation, data: _StateAndBuffer,
            indices: List[int], measurements: Dict[str, List[bool]],
            num_qubits: int) -> None:
        """Simulate an op that is a measurement in the computataional basis."""
        meas = ops.op_gate_of_type(op, ops.MeasurementGate)
        # TODO: support measurement outside computational basis.
        if meas:
            invert_mask = meas.invert_mask or num_qubits * (False,)
            # Measure updates inline.
            bits, _ = wave_function.measure_state_vector(data.state,
                                                         indices,
                                                         data.state)
            corrected = [bit ^ mask for bit, mask in
                         zip(bits, invert_mask)]
            key = protocols.measurement_key(meas)
            measurements[key].extend(corrected)

Response: Simulate an operation that is a measurement in the computataional basis.


Instruction:
Make a summary of the following Python 3 code
def _simulate_mixture(self, op: ops.Operation, data: _StateAndBuffer,
            indices: List[int]) -> None:
        """Simulate an op that is a mixtures of unitaries."""
        probs, unitaries = zip(*protocols.mixture(op))
        # We work around numpy barfing on choosing from a list of
        # numpy arrays (which is not `one-dimensional`) by selecting
        # the index of the unitary.
        index = np.random.choice(range(len(unitaries)), p=probs)
        shape = (2,) * (2 * len(indices))
        unitary = unitaries[index].astype(self._dtype).reshape(shape)
        result = linalg.targeted_left_multiply(unitary, data.state, indices,
                                               out=data.buffer)
        data.buffer = data.state
        data.state = result

Response: Simulate an op that is a mixtures of unitaries.


Instruction:
How would you explain what the following Python 3 function does
def cubic_acquaintance_strategy(
        qubits: Iterable[ops.Qid],
        swap_gate: ops.Gate=ops.SWAP
        ) -> circuits.Circuit:
    """Acquaints every triple of qubits.

    Exploits the fact that in a simple linear swap network every pair of
    logical qubits that starts at distance two remains so (except temporarily
    near the edge), and that every third one `goes through` the pair at some
    point in the network. The strategy then iterates through a series of
    mappings in which qubits i and i + k are placed at distance two, for k = 1
    through n / 2. Linear swap networks are used in between to effect the
    permutation.
    """

    qubits = tuple(qubits)
    n_qubits = len(qubits)

    swap_gate = SwapPermutationGate(swap_gate)

    moments = []
    index_order = tuple(range(n_qubits))
    max_separation = max(((n_qubits - 1) // 2) + 1, 2)
    for separation in range(1, max_separation):
        stepped_indices_concatenated = tuple(itertools.chain(*(
                range(offset, n_qubits, separation)
                for offset in range(separation))))
        new_index_order = skip_and_wrap_around(stepped_indices_concatenated)
        permutation = {i: new_index_order.index(j)
            for i, j in enumerate(index_order)}
        permutation_gate = LinearPermutationGate(
                n_qubits, permutation, swap_gate)
        moments.append(ops.Moment([permutation_gate(*qubits)]))
        for i in range(n_qubits + 1):
            for offset in range(3):
                moment = ops.Moment(acquaint(*qubits[j:j+3])
                        for j in range(offset, n_qubits - 2, 3))
                moments.append(moment)
            if i < n_qubits:
                moment = ops.Moment(swap_gate(*qubits[j:j+2])
                        for j in range(i % 2, n_qubits - 1, 2))
                moments.append(moment)
        index_order = new_index_order[::-1]
    return circuits.Circuit(moments, device=UnconstrainedAcquaintanceDevice)

Response: A cubic acquaintance strategy for a set of logical qubits.


Instruction:
Create a Python 3 function to
parse ASCIIart device layout into info about qubits and connectivity.

Response:
def _parse_device(s: str) -> Tuple[List[GridQubit], Dict[str, Set[GridQubit]]]:
    """Parse ASCIIart device layout into info about qubits and connectivity.

    Args:
        s: String representing the qubit layout. Each line represents a row,
            and each character in the row is a qubit, or a blank site if the
            character is a hyphen '-'. Different letters for the qubit specify
            which measurement line that qubit is connected to, e.g. all 'A'
            qubits share a measurement line. Leading and trailing spaces on
            each line are ignored.

    Returns:
        A list of qubits and a dict mapping measurement line name to the qubits
        on that measurement line.
    """
    lines = s.strip().split('\n')
    qubits = []  # type: List[GridQubit]
    measurement_lines = {}  # type: Dict[str, Set[GridQubit]]
    for row, line in enumerate(lines):
        for col, c in enumerate(line.strip()):
            if c != '-':
                qubit = GridQubit(row, col)
                qubits.append(qubit)
                measurement_line = measurement_lines.setdefault(c, set())
                measurement_line.add(qubit)
    return qubits, measurement_lines


Instruction:
Write a Python 3 function that can
iterate over arguments and calls approx_eq recursively.

Response:
def _approx_eq_iterables(val: Any, other: Any, *,
                         atol: Union[int, float]) -> bool:
    """Iterates over arguments and calls approx_eq recursively.

    Types of `val` and `other` does not necessarily needs to match each other.
    They just need to be iterable of the same length and have the same
    structure, approx_eq() will be called on each consecutive element of `val`
    and `other`.

    Args:
        val: Source for approximate comparison.
        other: Target for approximate comparison.
        atol: The minimum absolute tolerance. See np.isclose() documentation for
              details.

    Returns:
        True if objects are approximately equal, False otherwise. Returns
        NotImplemented when approximate equality is not implemented for given
        types.
    """

    def get_iter(iterable):
        try:
            return iter(iterable)
        except TypeError:
            return None

    val_it = get_iter(val)
    other_it = get_iter(other)

    if val_it is not None and other_it is not None:
        while True:
            try:
                val_next = next(val_it)
            except StopIteration:
                try:
                    next(other_it)
                    return False
                except StopIteration:
                    return True

            try:
                other_next = next(other_it)
            except StopIteration:
                return False

            result = approx_eq(val_next, other_next, atol=atol)
            if result is not True:
                return result

    return NotImplemented


Instruction:
Create a Python 3 function to
complete an acquaintance strategy for a set of qubits.

Response:
def complete_acquaintance_strategy(qubit_order: Sequence[ops.Qid],
                                   acquaintance_size: int=0,
                                   ) -> circuits.Circuit:
    """
    Returns an acquaintance strategy capable of executing a gate corresponding
    to any set of at most acquaintance_size qubits.

    Args:
        qubit_order: The qubits on which the strategy should be defined.
        acquaintance_size: The maximum number of qubits to be acted on by
        an operation.

    Returns:
        An circuit capable of implementing any set of k-local
        operation.
    """
    if acquaintance_size < 0:
        raise ValueError('acquaintance_size must be non-negative.')
    elif acquaintance_size == 0:
        return circuits.Circuit(device=UnconstrainedAcquaintanceDevice)

    if acquaintance_size > len(qubit_order):
        return circuits.Circuit(device=UnconstrainedAcquaintanceDevice)
    if acquaintance_size == len(qubit_order):
        return circuits.Circuit.from_ops(
                acquaint(*qubit_order), device=UnconstrainedAcquaintanceDevice)

    strategy = circuits.Circuit.from_ops(
            (acquaint(q) for q in qubit_order),
            device=UnconstrainedAcquaintanceDevice)
    for size_to_acquaint in range(2, acquaintance_size + 1):
        expose_acquaintance_gates(strategy)
        replace_acquaintance_with_swap_network(
                strategy, qubit_order, size_to_acquaint)
    return strategy


Instruction:
Create a Python 3 function to
add the specified number of input and output qubits.

Response:
def set_io_qubits(qubit_count):
    """Add the specified number of input and output qubits."""
    input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
    output_qubit = cirq.GridQubit(qubit_count, 0)
    return (input_qubits, output_qubit)


Instruction:
Write a Python 3 script to
implement function f = 1 if x == x

Response:
def make_oracle(input_qubits, output_qubit, x_bits):
    """Implement function {f(x) = 1 if x==x', f(x) = 0 if x!= x'}."""
    # Make oracle.
    # for (1, 1) it's just a Toffoli gate
    # otherwise negate the zero-bits.
    yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit)
    yield(cirq.TOFFOLI(input_qubits[0], input_qubits[1], output_qubit))
    yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def make_grover_circuit(input_qubits, output_qubit, oracle):
    # For 2 input qubits, that means using Grover operator only once.
    c = cirq.Circuit()

    # Initialize qubits.
    c.append([
        cirq.X(output_qubit),
        cirq.H(output_qubit),
        cirq.H.on_each(*input_qubits),
    ])

    # Query oracle.
    c.append(oracle)

    # Construct Grover operator.
    c.append(cirq.H.on_each(*input_qubits))
    c.append(cirq.X.on_each(*input_qubits))
    c.append(cirq.H.on(input_qubits[1]))
    c.append(cirq.CNOT(input_qubits[0], input_qubits[1]))
    c.append(cirq.H.on(input_qubits[1]))
    c.append(cirq.X.on_each(*input_qubits))
    c.append(cirq.H.on_each(*input_qubits))

    # Measure the result.
    c.append(cirq.measure(*input_qubits, key='result'))

    return c

Response: Construct a Grover circuit.


Instruction:
Implement a function in Python 3 to
iterate through relevant python files within the given directory and returns an iterable of all python files that are not generated by the user.

Response:
def get_unhidden_ungenerated_python_files(directory: str) -> Iterable[str]:
    """Iterates through relevant python files within the given directory.

    Args:
        directory: The top-level directory to explore.

    Yields:
        File paths.
    """
    for dirpath, dirnames, filenames in os.walk(directory, topdown=True):
        if os.path.split(dirpath)[-1].startswith('.'):
            dirnames.clear()
            continue

        for filename in filenames:
            if filename.endswith('.py') and not filename.endswith('_pb2.py'):
                yield os.path.join(dirpath, filename)


Instruction:
Given the following Python 3 function, write the documentation
def create_virtual_env(venv_path: str,
                       requirements_paths: Iterable[str],
                       python_path: str,
                       verbose: bool) -> None:
    """Creates a new virtual environment and then installs dependencies.

    Args:
        venv_path: Where to put the virtual environment's state.
        requirements_paths: Location of requirements files to -r install.
        python_path: The python binary to use.
        verbose: When set, more progress output is produced.
    """
    shell_tools.run_cmd('virtualenv',
                        None if verbose else '--quiet',
                        '-p',
                        python_path,
                        venv_path,
                        out=sys.stderr)
    pip_path = os.path.join(venv_path, 'bin', 'pip')
    for req_path in requirements_paths:
        shell_tools.run_cmd(pip_path,
                            'install',
                            None if verbose else '--quiet',
                            '-r',
                            req_path,
                            out=sys.stderr)

Response: Creates a new virtual environment and installs dependencies.


Instruction:
Can you generate the documentation for the following Python 3 function
def derive_temporary_python2_environment(
        destination_directory: str,
        python3_environment: PreparedEnv,
        verbose: bool,
        env_name: str = '.test_virtualenv_py2',
        python_path: str = "/usr/bin/python2.7") -> PreparedEnv:
    """Creates a python 2.7 environment starting from a prepared python 3 one.

    Args:
        destination_directory: Where to put the python 2 environment.
        python3_environment: The prepared environment to start from.
        verbose: When set, more progress output is produced.
        env_name: The name to use for the virtualenv directory.
        python_path: The python binary to use.

    Returns:
        A description of the environment that was prepared.
    """

    shutil.rmtree(destination_directory)
    input_directory = cast(str, python3_environment.destination_directory)
    os.chdir(input_directory)
    conversion_script_path = os.path.join(
        input_directory,
        'dev_tools',
        'python2.7-generate.sh')
    shell_tools.run_cmd('bash',
                        conversion_script_path,
                        destination_directory,
                        input_directory,
                        python3_environment.virtual_env_path,
                        out=sys.stderr)
    os.chdir(destination_directory)

    # Create virtual environment.
    env_path = os.path.join(destination_directory, env_name)
    # (These files are output by dev_tools/python2.7-generate.sh.)
    req_path = os.path.join(destination_directory, 'requirements.txt')
    dev_req_path = os.path.join(destination_directory,
                                'pip-list-test-tools.txt')
    contrib_req_path = os.path.join(destination_directory,
                                    'cirq',
                                    'contrib',
                                    'contrib-requirements.txt')
    req_paths = [req_path, dev_req_path, contrib_req_path]
    create_virtual_env(venv_path=env_path,
                       python_path=python_path,
                       requirements_paths=req_paths,
                       verbose=verbose)

    return PreparedEnv(github_repo=python3_environment.repository,
                       actual_commit_id=python3_environment.actual_commit_id,
                       compare_commit_id=python3_environment.compare_commit_id,
                       destination_directory=destination_directory,
                       virtual_env_path=env_path)

Response: Derives a temporary python 2. 7 environment from a prepared python 3 one.


Instruction:
Can you tell what is the following Python 3 function doing
def run_estimate(unknown_gate, qnum, repetitions):

    qubits = [None] * qnum
    for i in range(len(qubits)):
        qubits[i] = cirq.GridQubit(0, i)
    ancilla = cirq.GridQubit(0, len(qubits))

    circuit = cirq.Circuit.from_ops(
        cirq.H.on_each(*qubits),
        [cirq.ControlledGate(unknown_gate**(2**i)).on(qubits[qnum-i-1], ancilla)
         for i in range(qnum)],
        QftInverse(qnum)(*qubits),
        cirq.measure(*qubits, key='phase'))
    simulator = cirq.Simulator()
    result = simulator.run(circuit, repetitions=repetitions)
    return result

Response: Runs the phase estimator circuit and execute simulations.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def experiment(qnum, repetitions=100):

    def example_gate(phi):
        """An example unitary 1-qubit gate U with an eigen vector |0> and an
        eigen value exp(2*Pi*i*phi)
        """

        gate = cirq.SingleQubitMatrixGate(
            matrix=np.array([[np.exp(2*np.pi*1.0j*phi), 0], [0, 1]]))
        return gate

    print('Estimation with {}qubits.'.format(qnum))
    print('Actual, Estimation (Raw binary)')
    errors = []
    fold_func = lambda ms: ''.join(np.flip(ms, 0).astype(int).astype(str))
    for phi in np.arange(0, 1, 0.1):
        result = run_estimate(example_gate(phi), qnum, repetitions)
        hist = result.histogram(key='phase', fold_func=fold_func)
        estimate_bin = hist.most_common(1)[0][0]
        estimate = (sum([float(s)*0.5**(order+1)
                         for order, s in enumerate(estimate_bin)]))
        print('{:0.4f}, {:0.4f} ({})'.format(phi, estimate, estimate_bin))
        errors.append((phi-estimate)**2)
    print('RMS Error: {:0.4f}\n'.format(np.sqrt(sum(errors)/len(errors))))

Response:
Execute the phase estimator cirquit with multiple settings and
    show results.


Instruction:
Make a summary of the following Python 3 code
def _decompose_(self, qubits):

        qubits = list(qubits)
        while len(qubits) > 0:
            q_head = qubits.pop(0)
            yield cirq.H(q_head)
            for i, qubit in enumerate(qubits):
                yield (cirq.CZ**(-1/2.0**(i+1)))(qubit, q_head)

Response: A generator that yields the quantum circuit.


Instruction:
Implement a Python 3 function for
searching for linear sequence of qubits on a device.

Response:
def line_on_device(
        device: 'cirq.google.XmonDevice',
        length: int,
        method: LinePlacementStrategy = greedy.GreedySequenceSearchStrategy()
) -> GridQubitLineTuple:
    """Searches for linear sequence of qubits on device.

    Args:
        device: Google Xmon device instance.
        length: Desired number of qubits making up the line.
        method: Line placement method. Defaults to
                cirq.greedy.GreedySequenceSearchMethod.

    Returns:
        Line sequences search results.
    """
    return method.place_line(device, length)


Instruction:
Write a Python 3 script for
returning the value ** factor of the given value.

Response:
def pow(val: Any,
        exponent: Any,
        default: Any = RaiseTypeErrorIfNotProvided) -> Any:
    """Returns `val**factor` of the given value, if defined.

    Values define an extrapolation by defining a __pow__(self, exponent) method.
    Note that the method may return NotImplemented to indicate a particular
    extrapolation can't be done.

    Args:
        val: The value or iterable of values to invert.
        exponent: The extrapolation factor. For example, if this is 0.5 and val
            is a gate then the caller is asking for a square root of the gate.
        default: Determines the fallback behavior when `val` doesn't have
            an extrapolation defined. If `default` is not set and that occurs,
            a TypeError is raised instead.

    Returns:
        If `val` has a __pow__ method that returns something besides
        NotImplemented, that result is returned. Otherwise, if a default value
        was specified, the default value is returned.

    Raises:
        TypeError: `val` doesn't have a __pow__ method (or that method returned
            NotImplemented) and no `default` value was specified.
    """
    raiser = getattr(val, '__pow__', None)
    result = NotImplemented if raiser is None else raiser(exponent)
    if result is not NotImplemented:
        return result

    if default is not RaiseTypeErrorIfNotProvided:
        return default
    if raiser is None:
        raise TypeError("object of type '{}' "
                        "has no __pow__ method.".format(type(val)))
    raise TypeError("object of type '{}' does have a __pow__ method, "
                    "but it returned NotImplemented.".format(type(val)))


Instruction:
Make a summary of the following Python 3 code
def sample(program: Union[circuits.Circuit, schedules.Schedule],
           *,
           noise: devices.NoiseModel = devices.NO_NOISE,
           param_resolver: Optional[study.ParamResolver] = None,
           repetitions: int = 1,
           dtype: Type[np.number] = np.complex64) -> study.TrialResult:
    """Simulates sampling from the given circuit or schedule.

    Args:
        program: The circuit or schedule to sample from.
        noise: Noise model to use while running the simulation.
        param_resolver: Parameters to run with the program.
        repetitions: The number of samples to take.
        dtype: The `numpy.dtype` used by the simulation. Typically one of
            `numpy.complex64` or `numpy.complex128`.
            Favors speed over precision by default, i.e. uses `numpy.complex64`.
    """

    # State vector simulation is much faster, but only works if no randomness.
    if noise == devices.NO_NOISE and protocols.has_unitary(program):
        return sparse_simulator.Simulator(dtype=dtype).run(
            program=program,
            param_resolver=param_resolver,
            repetitions=repetitions)

    return density_matrix_simulator.DensityMatrixSimulator(
        dtype=dtype, noise=noise).run(program=program,
                                      param_resolver=param_resolver,
                                      repetitions=repetitions)

Response: Simulates sampling from the given circuit or schedule.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def sample_sweep(program: Union[circuits.Circuit, schedules.Schedule],
                 params: study.Sweepable,
                 *,
                 noise: devices.NoiseModel = devices.NO_NOISE,
                 repetitions: int = 1,
                 dtype: Type[np.number] = np.complex64
                ) -> List[study.TrialResult]:
    """Runs the supplied Circuit or Schedule, mimicking quantum hardware.

    In contrast to run, this allows for sweeping over different parameter
    values.

    Args:
        program: The circuit or schedule to simulate.
        params: Parameters to run with the program.
        noise: Noise model to use while running the simulation.
        repetitions: The number of repetitions to simulate, per set of
            parameter values.
        dtype: The `numpy.dtype` used by the simulation. Typically one of
            `numpy.complex64` or `numpy.complex128`.
            Favors speed over precision by default, i.e. uses `numpy.complex64`.

    Returns:
        TrialResult list for this run; one for each possible parameter
        resolver.
    """
    circuit = (program if isinstance(program, circuits.Circuit)
               else program.to_circuit())
    param_resolvers = study.to_resolvers(params)

    trial_results = []  # type: List[study.TrialResult]
    for param_resolver in param_resolvers:
        measurements = sample(circuit,
                              noise=noise,
                              param_resolver=param_resolver,
                              repetitions=repetitions,
                              dtype=dtype)
        trial_results.append(measurements)
    return trial_results

Response: Runs the supplied Circuit or Schedule and returns a list of trial results.


Instruction:
Can you generate the documentation for the following Python 3 function
def moment_by_moment_schedule(device: Device, circuit: Circuit):
    schedule = Schedule(device)
    t = Timestamp()
    for moment in circuit:
        if not moment.operations:
            continue
        for op in moment.operations:
            scheduled_op = ScheduledOperation.op_at_on(op, t, device)
            # Raises a ValueError describing the problem if this cannot be
            # scheduled.
            schedule.include(scheduled_operation=scheduled_op)
            # Raises ValueError at first sign of a device conflict.
            device.validate_scheduled_operation(schedule, scheduled_op)
        # Increment time for next moment by max of ops during this moment.
        max_duration = max(device.duration_of(op) for op in moment.operations)
        t += max_duration
    return schedule

Response: Returns a schedule aligned with the moment structure of the circuit.


Instruction:
Given the following Python 3 function, write the documentation
def min_height(self) -> int:
        return max(
            len(self.content.split('\n')) if self.content else 0,
            # Only vertical lines can cross 0 height blocks.
            int(any([self.left, self.right]))
        )

Response: Minimum height necessary to render the block s contents.


Instruction:
Create a Python 3 function to
draw lines in the box using the given character set.

Response:
def draw_curve(self,
                   grid_characters: BoxDrawCharacterSet,
                   *,
                   top: bool = False,
                   left: bool = False,
                   right: bool = False,
                   bottom: bool = False,
                   crossing_char: Optional[str] = None):
        """Draws lines in the box using the given character set.

        Supports merging the new lines with the lines from a previous call to
        draw_curve, including when they have different character sets (assuming
        there exist characters merging the two).

        Args:
            grid_characters: The character set to draw the curve with.
            top: Draw topward leg?
            left: Draw leftward leg?
            right: Draw rightward leg?
            bottom: Draw downward leg?
            crossing_char: Overrides the all-legs-present character. Useful for
                ascii diagrams, where the + doesn't always look the clearest.
        """
        if not any([top, left, right, bottom]):
            return

        # Remember which legs are new, old, or missing.
        sign_top = +1 if top else -1 if self.top else 0
        sign_bottom = +1 if bottom else -1 if self.bottom else 0
        sign_left = +1 if left else -1 if self.left else 0
        sign_right = +1 if right else -1 if self.right else 0

        # Add new segments.
        if top:
            self.top = grid_characters.top_bottom
        if bottom:
            self.bottom = grid_characters.top_bottom
        if left:
            self.left = grid_characters.left_right
        if right:
            self.right = grid_characters.left_right

        # Fill center.
        if not all([crossing_char,
                    self.top, self.bottom, self.left, self.right]):
            crossing_char = box_draw_character(
                self._prev_curve_grid_chars,
                grid_characters,
                top=sign_top,
                bottom=sign_bottom,
                left=sign_left,
                right=sign_right)
        self.center = crossing_char or ''

        self._prev_curve_grid_chars = grid_characters


Instruction:
Can you create a Python 3 function that
returns a list of text lines representing the block s contents.

Response:
def render(self, width: int, height: int) -> List[str]:
        """Returns a list of text lines representing the block's contents.

        Args:
            width: The width of the output text. Must be at least as large as
                the block's minimum width.
            height: The height of the output text. Must be at least as large as
                the block's minimum height.

        Returns:
            Text pre-split into lines.
        """
        if width == 0 or height == 0:
            return [''] * height

        out_chars = [[' '] * width for _ in range(height)]

        mid_x = int((width - 1) * self.horizontal_alignment)
        mid_y = (height - 1) // 2

        # Horizontal line legs.
        if self.left:
            out_chars[mid_y][:mid_x + 1] = self.left * (mid_x + 1)
        if self.right:
            out_chars[mid_y][mid_x:] = self.right * (width - mid_x)

        # Vertical line legs.
        if self.top:
            for y in range(mid_y + 1):
                out_chars[y][mid_x] = self.top
        if self.bottom:
            for y in range(mid_y, height):
                out_chars[y][mid_x] = self.bottom

        # Central content.
        mid = self.content or self.center
        if self.content or self.center:
            content_lines = mid.split('\n')
            y = mid_y - (len(content_lines) - 1) // 2
            for dy, content_line in enumerate(content_lines):
                s = int((len(content_line) - 1) * self.horizontal_alignment)
                x = mid_x - s
                for dx, c in enumerate(content_line):
                    out_chars[y + dy][x + dx] = c

        return [''.join(line) for line in out_chars]


Instruction:
How would you code a function in Python 3 to
return the mutable block at the given position.

Response:
def mutable_block(self, x: int, y: int) -> Block:
        """Returns the block at (x, y) so it can be edited."""
        if x < 0 or y < 0:
            raise IndexError('x < 0 or y < 0')
        return self._blocks[(x, y)]


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_col_min_width(self, x: int, min_width: int):
        if x < 0:
            raise IndexError('x < 0')
        self._min_widths[x] = min_width

Response: Sets a minimum width for blocks in the column with coordinate x.


Instruction:
Implement a function in Python 3 to
set a minimum height for blocks in the row with coordinate y.

Response:
def set_row_min_height(self, y: int, min_height: int):
        """Sets a minimum height for blocks in the row with coordinate y."""
        if y < 0:
            raise IndexError('y < 0')
        self._min_heights[y] = min_height


Instruction:
Can you generate the documentation for the following Python 3 function
def render(self,
               *,
               block_span_x: Optional[int] = None,
               block_span_y: Optional[int] = None,
               min_block_width: int = 0,
               min_block_height: int = 0) -> str:
        """Outputs text containing the diagram.

        Args:
            block_span_x: The width of the diagram in blocks. Set to None to
                default to using the smallest width that would include all
                accessed blocks and columns with a specified minimum width.
            block_span_y: The height of the diagram in blocks. Set to None to
                default to using the smallest height that would include all
                accessed blocks and rows with a specified minimum height.
            min_block_width: A global minimum width for all blocks.
            min_block_height: A global minimum height for all blocks.

        Returns:
            The diagram as a string.
        """

        # Determine desired size of diagram in blocks.
        if block_span_x is None:
            block_span_x = 1 + max(
                max(x for x, _ in self._blocks.keys()),
                max(self._min_widths.keys()),
            )
        if block_span_y is None:
            block_span_y = 1 + max(
                max(y for _, y in self._blocks.keys()),
                max(self._min_heights.keys()),
            )

        # Method for accessing blocks without creating new entries.
        empty = Block()
        def block(x: int, y: int) -> Block:
            return self._blocks.get((x, y), empty)

        # Determine the width of every column and the height of every row.
        widths = {
            x: max(
                max(block(x, y).min_width() for y in range(block_span_y)),
                self._min_widths.get(x, 0),
                min_block_width,
            )
            for x in range(block_span_x)
        }
        heights = {
            y: max(
                max(block(x, y).min_height() for x in range(block_span_x)),
                self._min_heights.get(y, 0),
                min_block_height,
            )
            for y in range(block_span_y)
        }

        # Get the individually rendered blocks.
        block_renders = {
            (x, y): block(x, y).render(widths[x], heights[y])
            for x in range(block_span_x)
            for y in range(block_span_y)
        }

        # Paste together all of the rows of rendered block content.
        out_lines = []  # type: List[str]
        for y in range(block_span_y):
            for by in range(heights[y]):
                out_line_chunks = []  # type: List[str]
                for x in range(block_span_x):
                    out_line_chunks.extend(block_renders[x, y][by])
                out_lines.append(''.join(out_line_chunks).rstrip())

        # Then paste together the rows.
        return '\n'.join(out_lines)

Response:
Outputs text containing the diagram.

        Args:
            block_span_x: The width of the diagram in blocks. Set to None to
                default to using the smallest width that would include all
                accessed blocks and columns with a specified minimum width.
            block_span_y: The height of the diagram in blocks. Set to None to
                default to using the smallest height that would include all
                accessed blocks and rows with a specified minimum height.
            min_block_width: A global minimum width for all blocks.
            min_block_height: A global minimum height for all blocks.

        Returns:
            The diagram as a string.


Instruction:
Create a Python 3 function to
demonstrate Quantum Fourier transform.

Response:
def main():
    """Demonstrates Quantum Fourier transform.
    """
    # Create circuit
    qft_circuit = generate_2x2_grid_qft_circuit()
    print('Circuit:')
    print(qft_circuit)
    # Simulate and collect final_state
    simulator = cirq.Simulator()
    result = simulator.simulate(qft_circuit)
    print()
    print('FinalState')
    print(np.around(result.final_state, 3))


Instruction:
Make a summary of the following Python 3 code
def map_qubits(self: TSelf_PauliStringGateOperation,
                   qubit_map: Dict[raw_types.Qid, raw_types.Qid]
                  ) -> TSelf_PauliStringGateOperation:
        """Return an equivalent operation on new qubits with its Pauli string
        mapped to new qubits.

        new_pauli_string = self.pauli_string.map_qubits(qubit_map)
        """

Response:
Return an equivalent operation on new qubits with its Pauli string
        mapped to new qubits.


Instruction:
Create a Python 3 function for
reporting the status of the current branch to github.

Response:
def report_status_to_github(self,
                                state: str,
                                description: str,
                                context: str,
                                target_url: Optional[str] = None):
        """Sets a commit status indicator on github.

        If not running from a pull request (i.e. repository is None), then this
        just prints to stderr.

        Args:
            state: The state of the status indicator.
                Must be 'error', 'failure', 'pending', or 'success'.
            description: A summary of why the state is what it is,
                e.g. '5 lint errors' or 'tests passed!'.
            context: The name of the status indicator, e.g. 'pytest' or 'lint'.
            target_url: Optional location where additional details about the
                status can be found, e.g. an online test results page.

        Raises:
            ValueError: Not one of the allowed states.
            IOError: The HTTP post request failed, or the response didn't have
                a 201 code indicating success in the expected way.
        """
        if state not in ['error', 'failure', 'pending', 'success']:
            raise ValueError('Unrecognized state: {!r}'.format(state))

        if self.repository is None or self.repository.access_token is None:
            return

        print(repr(('report_status',
                    context,
                    state,
                    description,
                    target_url)), file=sys.stderr)

        payload = {
            'state': state,
            'description': description,
            'context': context,
        }
        if target_url is not None:
            payload['target_url'] = target_url

        url = (
            "https://api.github.com/repos/{}/{}/statuses/{}?access_token={}"
            .format(self.repository.organization,
                    self.repository.name,
                    self.actual_commit_id,
                    self.repository.access_token))

        response = requests.post(url, json=payload)

        if response.status_code != 201:
            raise IOError('Request failed. Code: {}. Content: {}.'.format(
                response.status_code, response.content))


Instruction:
Write a Python 3 script for
getting the files changed on one git branch vs another.

Response:
def get_changed_files(self) -> List[str]:
        """Get the files changed on one git branch vs another.

        Returns:
            List[str]: File paths of changed files, relative to the git repo
                root.
        """
        out = shell_tools.output_of(
            'git',
            'diff',
            '--name-only',
            self.compare_commit_id,
            self.actual_commit_id,
            '--',
            cwd=self.destination_directory)
        return [e for e in out.split('\n') if e.strip()]


Instruction:
Can you create a Python 3 function that
creates a Duration from datetime. timedelta.

Response:
def create(cls, duration: Union['Duration', timedelta]) -> 'Duration':
        """Creates a Duration from datetime.timedelta if necessary"""
        if isinstance(duration, cls):
            return duration
        elif isinstance(duration, timedelta):
            duration_in_picos = duration.total_seconds() * 10**12
            return cls(picos=duration_in_picos)
        else:
            raise TypeError(
                'Only datetime.timedelta and cirq.Duration are supported.')


Instruction:
Given the following Python 3 function, write the documentation
def _create_array(self, arr: np.ndarray) -> int:
        if not isinstance(arr, np.ndarray):
            raise ValueError('Array is not a numpy ndarray.')
        try:
            c_arr = np.ctypeslib.as_ctypes(arr)
        except (KeyError, NotImplementedError):
            raise ValueError(
                'Array has unsupported dtype {}.'.format(arr.dtype))

        # pylint: disable=protected-access
        raw_arr = RawArray(c_arr._type_, c_arr)

        with self._lock:
            if self._count >= len(self._arrays):
                self._arrays += len(self._arrays) * [None]

            self._get_next_free()

            # Note storing the shape is a workaround for an issue encountered
            # when upgrading to numpy 1.15.
            # See https://github.com/numpy/numpy/issues/11636
            self._arrays[self._current] = (raw_arr, arr.shape)

            self._count += 1

        return self._current

Response: Creates a RawArray from the given numpy array.


Instruction:
How would you implement a function in Python 3 that
frees the memory for the given array with the given handle.

Response:
def _free_array(self, handle: int):
        """Frees the memory for the array with the given handle.

        Args:
          handle: The handle of the array whose memory should be freed. This
            handle must come from the _create_array method.
        """
        with self._lock:
            if self._arrays[handle] is not None:
                self._arrays[handle] = None
                self._count -= 1