Instruction:
How would you implement a function in Python 3 that
returns the numpy array with the given handle.

Response:
def _get_array(self, handle: int) -> np.ndarray:
        """Returns 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.

        Returns:
          The numpy ndarray with the handle given from _create_array.
        """
        tup = self._arrays[handle]
        assert tup is not None
        c_arr, shape = tup
        with warnings.catch_warnings():
            warnings.simplefilter('ignore', RuntimeWarning)
            result = np.ctypeslib.as_array(c_arr)
        result.shape = shape
        return result


Instruction:
Create a Python 3 function to
write QASM output to a file specified by path.

Response:
def save(self, path: Union[str, bytes, int]) -> None:
        """Write QASM output to a file specified by path."""
        with open(path, 'w') as f:
            def write(s: str) -> None:
                f.write(s)
            self._write_qasm(write)


Instruction:
Create a Python 3 function to
rectify the acquaintance strategy of the given circuit.

Response:
def rectify_acquaintance_strategy(
        circuit: circuits.Circuit,
        acquaint_first: bool=True
        ) -> None:
    """Splits moments so that they contain either only acquaintance gates
    or only permutation gates. Orders resulting moments so that the first one
    is of the same type as the previous one.

    Args:
        circuit: The acquaintance strategy to rectify.
        acquaint_first: Whether to make acquaintance moment first in when
        splitting the first mixed moment.
    """

    if not is_acquaintance_strategy(circuit):
        raise TypeError('not is_acquaintance_strategy(circuit)')

    rectified_moments = []
    for moment in circuit:
        gate_type_to_ops = collections.defaultdict(list
                ) # type: Dict[bool, List[ops.GateOperation]]
        for op in moment.operations:
            gate_type_to_ops[isinstance(op.gate, AcquaintanceOpportunityGate)
                    ].append(op)
        if len(gate_type_to_ops) == 1:
            rectified_moments.append(moment)
            continue
        for acquaint_first in sorted(gate_type_to_ops.keys(),
                                     reverse=acquaint_first):
            rectified_moments.append(
                    ops.Moment(gate_type_to_ops[acquaint_first]))
    circuit._moments = rectified_moments


Instruction:
Given the following Python 3 function, write the documentation
def replace_acquaintance_with_swap_network(
        circuit: circuits.Circuit,
        qubit_order: Sequence[ops.Qid],
        acquaintance_size: Optional[int] = 0,
        swap_gate: ops.Gate = ops.SWAP
        ) -> bool:
    """
    Replace every moment containing acquaintance gates (after
    rectification) with a generalized swap network, with the partition
    given by the acquaintance gates in that moment (and singletons for the
    free qubits). Accounts for reversing effect of swap networks.

    Args:
        circuit: The acquaintance strategy.
        qubit_order: The qubits, in order, on which the replacing swap network
            gate acts on.
        acquaintance_size: The acquaintance size of the new swap network gate.
        swap_gate: The gate used to swap logical indices.

    Returns: Whether or not the overall effect of the inserted swap network
        gates is to reverse the order of the qubits, i.e. the parity of the
        number of swap network gates inserted.

    Raises:
        TypeError: circuit is not an acquaintance strategy.
    """

    if not is_acquaintance_strategy(circuit):
        raise TypeError('not is_acquaintance_strategy(circuit)')

    rectify_acquaintance_strategy(circuit)
    reflected = False
    reverse_map = {q: r for q, r in zip(qubit_order, reversed(qubit_order))}
    for moment_index, moment in enumerate(circuit):
        if reflected:
            moment = moment.transform_qubits(reverse_map.__getitem__)
        if all(isinstance(op.gate, AcquaintanceOpportunityGate)
                for op in moment.operations):
            swap_network_gate = SwapNetworkGate.from_operations(
                    qubit_order, moment.operations,
                    acquaintance_size, swap_gate)
            swap_network_op = swap_network_gate(*qubit_order)
            moment = ops.Moment([swap_network_op])
            reflected = not reflected
        circuit._moments[moment_index] = moment
    return reflected

Response: Replaces all acquaintance gates in the given circuit with a generalized swap network.


Instruction:
Can you write a function in Python 3 where it
checks if a gate is a native ion gate.

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

    Args:
        gate: Input gate.

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


Instruction:
Make a summary of the following Python 3 code
def convert_one(self, op: ops.Operation) -> ops.OP_TREE:

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

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

Response: Convert a single operation into an ion trap native gates.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def diagonalize_real_symmetric_matrix(
        matrix: np.ndarray,
        *,
        rtol: float = 1e-5,
        atol: float = 1e-8) -> np.ndarray:
    """Returns an orthogonal matrix that diagonalizes the given matrix.

    Args:
        matrix: A real symmetric matrix to diagonalize.
        rtol: float = 1e-5,
        atol: float = 1e-8

    Returns:
        An orthogonal matrix P such that P.T @ matrix @ P is diagonal.

    Raises:
        ValueError: Matrix isn't real symmetric.
    """

    # TODO: Determine if thresholds should be passed into is_hermitian
    if np.any(np.imag(matrix) != 0) or not predicates.is_hermitian(matrix):
        raise ValueError('Input must be real and symmetric.')

    _, result = np.linalg.eigh(matrix)

    return result

Response: Returns an orthogonal matrix that diagonalizes the given matrix.


Instruction:
Write a Python 3 script for
splitting a range into approximate equivalence classes.

Response:
def _contiguous_groups(
        length: int,
        comparator: Callable[[int, int], bool]
) -> List[Tuple[int, int]]:
    """Splits range(length) into approximate equivalence classes.

    Args:
        length: The length of the range to split.
        comparator: Determines if two indices have approximately equal items.

    Returns:
        A list of (inclusive_start, exclusive_end) range endpoints. Each
        corresponds to a run of approximately-equivalent items.
    """
    result = []
    start = 0
    while start < length:
        past = start + 1
        while past < length and comparator(start, past):
            past += 1
        result.append((start, past))
        start = past
    return result


Instruction:
Can you generate the documentation for the following Python 3 function
def diagonalize_real_symmetric_and_sorted_diagonal_matrices(
        symmetric_matrix: np.ndarray,
        diagonal_matrix: np.ndarray,
        *,
        rtol: float = 1e-5,
        atol: float = 1e-8,
        check_preconditions: bool = True) -> np.ndarray:
    """Returns an orthogonal matrix that diagonalizes both given matrices.

    The given matrices must commute.
    Guarantees that the sorted diagonal matrix is not permuted by the
    diagonalization (except for nearly-equal values).

    Args:
        symmetric_matrix: A real symmetric matrix.
        diagonal_matrix: A real diagonal matrix with entries along the diagonal
            sorted into descending order.
        rtol: Relative numeric error threshold.
        atol: Absolute numeric error threshold.
        check_preconditions: If set, verifies that the input matrices commute
            and are respectively symmetric and diagonal descending.

    Returns:
        An orthogonal matrix P such that P.T @ symmetric_matrix @ P is diagonal
        and P.T @ diagonal_matrix @ P = diagonal_matrix (up to tolerance).

    Raises:
        ValueError: Matrices don't meet preconditions (e.g. not symmetric).
    """

    # Verify preconditions.
    if check_preconditions:
        if (np.any(np.imag(symmetric_matrix)) or
                not predicates.is_hermitian(symmetric_matrix,
                                            rtol=rtol,
                                            atol=atol)):
            raise ValueError('symmetric_matrix must be real symmetric.')
        if (not predicates.is_diagonal(diagonal_matrix, atol=atol) or
                np.any(np.imag(diagonal_matrix)) or
                np.any(diagonal_matrix[:-1, :-1] < diagonal_matrix[1:, 1:])):
            raise ValueError(
                'diagonal_matrix must be real diagonal descending.')
        if not predicates.commutes(diagonal_matrix,
                                   symmetric_matrix,
                                   rtol=rtol,
                                   atol=atol):
            raise ValueError('Given matrices must commute.')

    def similar_singular(i, j):
        return np.allclose(diagonal_matrix[i, i],
                            diagonal_matrix[j, j], rtol=rtol)

    # Because the symmetric matrix commutes with the diagonal singulars matrix,
    # the symmetric matrix should be block-diagonal with a block boundary
    # wherever the singular values happen change. So we can use the singular
    # values to extract blocks that can be independently diagonalized.
    ranges = _contiguous_groups(diagonal_matrix.shape[0], similar_singular)

    # Build the overall diagonalization by diagonalizing each block.
    p = np.zeros(symmetric_matrix.shape, dtype=np.float64)
    for start, end in ranges:
        block = symmetric_matrix[start:end, start:end]
        p[start:end, start:end] = diagonalize_real_symmetric_matrix(
            block, rtol=rtol, atol=atol)

    return p

Response: Returns an orthogonal matrix that diagonalizes both given matrices.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def bidiagonalize_real_matrix_pair_with_symmetric_products(
        mat1: np.ndarray,
        mat2: np.ndarray,
        *,
        rtol: float = 1e-5,
        atol: float = 1e-8,
        check_preconditions: bool = True) -> Tuple[np.ndarray, np.ndarray]:
    """Finds orthogonal matrices that diagonalize both mat1 and mat2.

    Requires mat1 and mat2 to be real.
    Requires mat1.T @ mat2 to be symmetric.
    Requires mat1 @ mat2.T to be symmetric.

    Args:
        mat1: One of the real matrices.
        mat2: The other real matrix.
        rtol: Relative numeric error threshold.
        atol: Absolute numeric error threshold.
        check_preconditions: If set, verifies that the inputs are real, and that
            mat1.T @ mat2 and mat1 @ mat2.T are both symmetric. Defaults to set.

    Returns:
        A tuple (L, R) of two orthogonal matrices, such that both L @ mat1 @ R
        and L @ mat2 @ R are diagonal matrices.

    Raises:
        ValueError: Matrices don't meet preconditions (e.g. not real).
    """

    if check_preconditions:
        if np.any(np.imag(mat1) != 0):
            raise ValueError('mat1 must be real.')
        if np.any(np.imag(mat2) != 0):
            raise ValueError('mat2 must be real.')
        if not predicates.is_hermitian(mat1.dot(mat2.T), rtol=rtol, atol=atol):
            raise ValueError('mat1 @ mat2.T must be symmetric.')
        if not predicates.is_hermitian(mat1.T.dot(mat2), rtol=rtol, atol=atol):
            raise ValueError('mat1.T @ mat2 must be symmetric.')

    # Use SVD to bi-diagonalize the first matrix.
    base_left, base_diag, base_right = _svd_handling_empty(np.real(mat1))
    base_diag = np.diag(base_diag)

    # Determine where we switch between diagonalization-fixup strategies.
    dim = base_diag.shape[0]
    rank = dim
    while rank > 0 and tolerance.all_near_zero(base_diag[rank - 1, rank - 1],
                                               atol=atol):
        rank -= 1
    base_diag = base_diag[:rank, :rank]

    # Try diagonalizing the second matrix with the same factors as the first.
    semi_corrected = base_left.T.dot(np.real(mat2)).dot(base_right.T)

    # Fix up the part of the second matrix's diagonalization that's matched
    # against non-zero diagonal entries in the first matrix's diagonalization
    # by performing simultaneous diagonalization.
    overlap = semi_corrected[:rank, :rank]
    overlap_adjust = diagonalize_real_symmetric_and_sorted_diagonal_matrices(
        overlap,
        base_diag,
        rtol=rtol,
        atol=atol,
        check_preconditions=check_preconditions)

    # Fix up the part of the second matrix's diagonalization that's matched
    # against zeros in the first matrix's diagonalization by performing an SVD.
    extra = semi_corrected[rank:, rank:]
    extra_left_adjust, _, extra_right_adjust = _svd_handling_empty(extra)

    # Merge the fixup factors into the initial diagonalization.
    left_adjust = combinators.block_diag(overlap_adjust, extra_left_adjust)
    right_adjust = combinators.block_diag(overlap_adjust.T,
                                          extra_right_adjust)
    left = left_adjust.T.dot(base_left.T)
    right = base_right.T.dot(right_adjust.T)

    return left, right

Response: This function returns the orthogonalized matrix that diagonalize both mat1 and mat2 and returns the first orthogonal matrix that is symmetric.


Instruction:
Can you create a Python 3 function that
finds orthogonal matrices L, R such that L @ matrix @ R is diagonal. Args: mat: A unitary matrix. rtol: Relative numeric error threshold. atol: Absolute numeric error threshold. check_preconditions: If set, verifies that the input is a unitary matrix (to the given tolerances). Defaults to set. Returns: A triplet (L, d, R) such that L @ mat @ R = diag(d). Both L and R will be orthogonal matrices with determinant equal to 1. Raises: ValueError: Matrices don't meet preconditions (e.g. not real).

Response:
def bidiagonalize_unitary_with_special_orthogonals(
        mat: np.ndarray,
        *,
        rtol: float = 1e-5,
        atol: float = 1e-8,
        check_preconditions: bool = True
) -> Tuple[np.ndarray, np.array, np.ndarray]:
    """Finds orthogonal matrices L, R such that L @ matrix @ R is diagonal.

    Args:
        mat: A unitary matrix.
        rtol: Relative numeric error threshold.
        atol: Absolute numeric error threshold.
        check_preconditions: If set, verifies that the input is a unitary matrix
            (to the given tolerances). Defaults to set.

    Returns:
        A triplet (L, d, R) such that L @ mat @ R = diag(d). Both L and R will
        be orthogonal matrices with determinant equal to 1.

    Raises:
        ValueError: Matrices don't meet preconditions (e.g. not real).
    """

    if check_preconditions:
        if not predicates.is_unitary(mat, rtol=rtol, atol=atol):
            raise ValueError('matrix must be unitary.')

    # Note: Because mat is unitary, setting A = real(mat) and B = imag(mat)
    # guarantees that both A @ B.T and A.T @ B are Hermitian.
    left, right = bidiagonalize_real_matrix_pair_with_symmetric_products(
        np.real(mat),
        np.imag(mat),
        rtol=rtol,
        atol=atol,
        check_preconditions=check_preconditions)

    # Convert to special orthogonal w/o breaking diagonalization.
    if np.linalg.det(left) < 0:
        left[0, :] *= -1
    if np.linalg.det(right) < 0:
        right[:, 0] *= -1

    diag = combinators.dot(left, mat, right)

    return left, np.diag(diag), right


Instruction:
Can you generate the documentation for the following Python 3 function
def asymmetric_depolarize(
    p_x: float, p_y: float, p_z: float
) -> AsymmetricDepolarizingChannel:
    r"""Returns a AsymmetricDepolarizingChannel with given parameter.

    This channel evolves a density matrix via

        $$
        \rho \rightarrow (1 - p_x - p_y - p_z) \rho
                + p_x X \rho X + p_y Y \rho Y + p_z Z \rho Z
        $$

    Args:
        p_x: The probability that a Pauli X and no other gate occurs.
        p_y: The probability that a Pauli Y and no other gate occurs.
        p_z: The probability that a Pauli Z and no other gate occurs.

    Raises:
        ValueError: if the args or the sum of the args are not probabilities.
    """
    return AsymmetricDepolarizingChannel(p_x, p_y, p_z)

Response: r Returns an AsymmetricDepolarizingChannel with given parameter.


Instruction:
Can you implement a function in Python 3 that
queries the scheduled operations by time and qubit.

Response:
def query(
            self,
            *,  # Forces keyword args.
            time: Timestamp,
            duration: Union[Duration, timedelta] = Duration(),
            qubits: Iterable[Qid] = None,
            include_query_end_time=False,
            include_op_end_times=False) -> List[ScheduledOperation]:
        """Finds operations by time and qubit.

        Args:
            time: Operations must end after this time to be returned.
            duration: Operations must start by time+duration to be
                returned.
            qubits: If specified, only operations touching one of the included
                qubits will be returned.
            include_query_end_time: Determines if the query interval includes
                its end time. Defaults to no.
            include_op_end_times: Determines if the scheduled operation
                intervals include their end times or not. Defaults to no.

        Returns:
            A list of scheduled operations meeting the specified conditions.
        """
        duration = Duration.create(duration)
        earliest_time = time - self._max_duration
        end_time = time + duration
        qubits = None if qubits is None else frozenset(qubits)

        def overlaps_interval(op):
            if not include_op_end_times and op.time + op.duration == time:
                return False
            if not include_query_end_time and op.time == end_time:
                return False
            return op.time + op.duration >= time and op.time <= end_time

        def overlaps_qubits(op):
            if qubits is None:
                return True
            return not qubits.isdisjoint(op.operation.qubits)

        potential_matches = self.scheduled_operations.irange_key(earliest_time,
                                                                 end_time)
        return [op
                for op in potential_matches
                if overlaps_interval(op) and overlaps_qubits(op)]


Instruction:
Write a Python 3 function that can
find operations happening at the same time as the given operation.

Response:
def operations_happening_at_same_time_as(
        self, scheduled_operation: ScheduledOperation
    ) -> List[ScheduledOperation]:
        """Finds operations happening at the same time as the given operation.

        Args:
            scheduled_operation: The operation specifying the time to query.

        Returns:
            Scheduled operations that overlap with the given operation.
        """
        overlaps = self.query(
            time=scheduled_operation.time,
            duration=scheduled_operation.duration)
        return [e for e in overlaps if e != scheduled_operation]


Instruction:
Explain what the following Python 3 code does
def include(self, scheduled_operation: ScheduledOperation):
        collisions = self.query(time=scheduled_operation.time,
                                duration=scheduled_operation.duration,
                                qubits=scheduled_operation.operation.qubits)
        if collisions:
            raise ValueError('Operation {} has collisions: {}'.format(
                scheduled_operation.operation, collisions))
        self.scheduled_operations.add(scheduled_operation)
        self._max_duration = max(self._max_duration,
                                 scheduled_operation.duration)

Response: Adds a scheduled operation to the schedule.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def exclude(self, scheduled_operation: ScheduledOperation) -> bool:
        try:
            self.scheduled_operations.remove(scheduled_operation)
            return True
        except ValueError:
            return False

Response: Removes a scheduled operation from the schedule if present.


Instruction:
Explain what the following Python 3 code does
def to_circuit(self) -> Circuit:
        circuit = Circuit(device=self.device)
        time = None  # type: Optional[Timestamp]
        for so in self.scheduled_operations:
            if so.time != time:
                circuit.append(so.operation,
                               strategy=InsertStrategy.NEW_THEN_INLINE)
                time = so.time
            else:
                circuit.append(so.operation,
                               strategy=InsertStrategy.INLINE)
        return circuit

Response: Convert the schedule to a circuit.


Instruction:
Write a Python 3 script for
acquainting each of the qubits with another set of qubits with another set of qubits.

Response:
def acquaint_insides(swap_gate: ops.Gate,
                     acquaintance_gate: ops.Operation,
                     qubits: Sequence[ops.Qid],
                     before: bool,
                     layers: Layers,
                     mapping: Dict[ops.Qid, int]
                     ) -> None:
    """Acquaints each of the qubits with another set specified by an
    acquaintance gate.

    Args:
        qubits: The list of qubits of which half are individually acquainted
            with another list of qubits.
        layers: The layers to put gates into.
        acquaintance_gate: The acquaintance gate that acquaints the end qubit
            with another list of qubits.
        before: Whether the acquainting is done before the shift.
        swap_gate: The gate used to swap logical indices.
        mapping: The mapping from qubits to logical indices. Used to keep track
            of the effect of inside-acquainting swaps.
    """

    max_reach = _get_max_reach(len(qubits), round_up=before)
    reaches = itertools.chain(range(1, max_reach + 1),
                    range(max_reach, -1, -1))
    offsets = (0, 1) * max_reach
    swap_gate = SwapPermutationGate(swap_gate)
    ops = []
    for offset, reach in zip(offsets, reaches):
        if offset == before:
            ops.append(acquaintance_gate)
        for dr in range(offset, reach, 2):
            ops.append(swap_gate(*qubits[dr:dr + 2]))
    intrastitial_layer = getattr(layers, 'pre' if before else 'post')
    intrastitial_layer += ops

    # add interstitial gate
    interstitial_layer = getattr(layers,
            ('prior' if before else 'posterior') + '_interstitial')
    interstitial_layer.append(acquaintance_gate)

    # update mapping
    reached_qubits = qubits[:max_reach + 1]
    positions = list(mapping[q] for q in reached_qubits)
    mapping.update(zip(reached_qubits, reversed(positions)))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def acquaint_and_shift(parts: Tuple[List[ops.Qid], List[ops.Qid]],
                       layers: Layers,
                       acquaintance_size: Optional[int],
                       swap_gate: ops.Gate,
                       mapping: Dict[ops.Qid, int]):
    """Acquaints and shifts a pair of lists of qubits. The first part is
    acquainted with every qubit individually in the second part, and vice
    versa. Operations are grouped into several layers:
        * prior_interstitial: The first layer of acquaintance gates.
        * prior: The combination of acquaintance gates and swaps that acquaints
            the inner halves.
        * intra: The shift gate.
        * post: The combination of acquaintance gates and swaps that acquaints
            the outer halves.
        * posterior_interstitial: The last layer of acquaintance gates.

    Args:
        parts: The two lists of qubits to acquaint.
        layers: The layers to put gates into.
        acquaintance_size: The number of qubits to acquaint at a time. If None,
            after each pair of parts is shifted the union thereof is
            acquainted.
        swap_gate: The gate used to swap logical indices.
        mapping: The mapping from qubits to logical indices. Used to keep track
            of the effect of inside-acquainting swaps.
    """
    left_part, right_part = parts
    left_size, right_size = len(left_part), len(right_part)
    assert not (set(left_part) & set(right_part))
    qubits = left_part + right_part
    shift = CircularShiftGate(len(qubits),
                              left_size,
                              swap_gate=swap_gate)(
                                      *qubits)
    if acquaintance_size is None:
        layers.intra.append(shift)
        layers.post.append(acquaint(*qubits))
        shift.gate.update_mapping(mapping, qubits)
    elif max(left_size, right_size) != acquaintance_size - 1:
        layers.intra.append(shift)
        shift.gate.update_mapping(mapping, qubits)
    elif acquaintance_size == 2:
        layers.prior_interstitial.append(acquaint(*qubits))
        layers.intra.append(shift)
        shift.gate.update_mapping(mapping, qubits)
    else:
        # before
        if left_size == acquaintance_size - 1:
            # right part
            pre_acquaintance_gate = acquaint(*qubits[:acquaintance_size])
            acquaint_insides(
                    swap_gate=swap_gate,
                    acquaintance_gate=pre_acquaintance_gate,
                    qubits=right_part,
                    before=True,
                    layers=layers,
                    mapping=mapping)

        if right_size == acquaintance_size - 1:
            # left part
            pre_acquaintance_gate = acquaint(*qubits[-acquaintance_size:])
            acquaint_insides(
                    swap_gate=swap_gate,
                    acquaintance_gate=pre_acquaintance_gate,
                    qubits=left_part[::-1],
                    before=True,
                    layers=layers,
                    mapping=mapping)

        layers.intra.append(shift)
        shift.gate.update_mapping(mapping, qubits)

        # after
        if ((left_size == acquaintance_size - 1) and
            (right_size > 1)):
            # right part
            post_acquaintance_gate = acquaint(*qubits[-acquaintance_size:])

            new_left_part = qubits[right_size - 1::-1]
            acquaint_insides(
                    swap_gate=swap_gate,
                    acquaintance_gate=post_acquaintance_gate,
                    qubits=new_left_part,
                    before=False,
                    layers=layers,
                    mapping=mapping)

        if ((right_size == acquaintance_size - 1) and
            (left_size > 1)):
            # left part

            post_acquaintance_gate = acquaint(*qubits[:acquaintance_size])
            acquaint_insides(
                    swap_gate=swap_gate,
                    acquaintance_gate=post_acquaintance_gate,
                    qubits=qubits[right_size:],
                    before=False,
                    layers=layers,
                    mapping=mapping)

Response: Acquaints and shifts a pair of parts into a single set of layers.


Instruction:
Here you have a function in Python 3, explain what it does
def circuit_to_pdf_using_qcircuit_via_tex(circuit: circuits.Circuit,
                                          filepath: str,
                                          pdf_kwargs=None,
                                          qcircuit_kwargs=None,
                                          clean_ext=('dvi', 'ps'),
                                          documentclass='article'):
    """Compiles the QCircuit-based latex diagram of the given circuit.

    Args:
        circuit: The circuit to produce a pdf of.
        filepath: Where to output the pdf.
        pdf_kwargs: The arguments to pass to generate_pdf.
        qcircuit_kwargs: The arguments to pass to
            circuit_to_latex_using_qcircuit.
        clean_ext: The file extensions to clean up after compilation. By
            default, latexmk is used with the '-pdfps' flag, which produces
            intermediary dvi and ps files.
        documentclass: The documentclass of the latex file.
    """
    pdf_kwargs = {'compiler': 'latexmk', 'compiler_args': ['-pdfps'],
                  **({} if pdf_kwargs is None else pdf_kwargs)}
    qcircuit_kwargs = {} if qcircuit_kwargs is None else qcircuit_kwargs
    tex = circuit_to_latex_using_qcircuit(circuit, **qcircuit_kwargs)
    doc = Document(documentclass=documentclass, document_options='dvips')
    doc.packages.append(Package('amsmath'))
    doc.packages.append(Package('qcircuit'))
    doc.append(NoEscape(tex))
    doc.generate_pdf(filepath, **pdf_kwargs)
    for ext in clean_ext:
        try:
            os.remove(filepath + '.' + ext)
        except (OSError, IOError) as e:
            if e.errno != errno.ENOENT:
                raise

Response: Compiles the QCircuit - based latex diagram of the given circuit and outputs a PDF of the result.


Instruction:
How would you explain what the following Python 3 function does
def deconstruct_single_qubit_matrix_into_angles(
        mat: np.ndarray) -> Tuple[float, float, float]:
    """Breaks down a 2x2 unitary into more useful ZYZ angle parameters.

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

    Returns:
        A tuple containing the amount to phase around Z, then rotate around Y,
        then phase around Z (all in radians).
    """
    # Anti-cancel left-vs-right phase along top row.
    right_phase = cmath.phase(mat[0, 1] * np.conj(mat[0, 0])) + math.pi
    mat = np.dot(mat, _phase_matrix(-right_phase))

    # Cancel top-vs-bottom phase along left column.
    bottom_phase = cmath.phase(mat[1, 0] * np.conj(mat[0, 0]))
    mat = np.dot(_phase_matrix(-bottom_phase), mat)

    # Lined up for a rotation. Clear the off-diagonal cells with one.
    rotation = math.atan2(abs(mat[1, 0]), abs(mat[0, 0]))
    mat = np.dot(_rotation_matrix(-rotation), mat)

    # Cancel top-left-vs-bottom-right phase.
    diagonal_phase = cmath.phase(mat[1, 1] * np.conj(mat[0, 0]))

    # Note: Ignoring global phase.
    return right_phase + diagonal_phase, rotation * 2, bottom_phase

Response: Breaks down a 2x2 unitary matrix into more useful ZYZ angle parameters.


Instruction:
How would you explain what the following Python 3 function does
def _group_similar(items: List[T],
                   comparer: Callable[[T, T], bool]) -> List[List[T]]:
    """Combines similar items into groups.

  Args:
    items: The list of items to group.
    comparer: Determines if two items are similar.

  Returns:
    A list of groups of items.
  """
    groups = []  # type: List[List[T]]
    used = set()  # type: Set[int]
    for i in range(len(items)):
        if i not in used:
            group = [items[i]]
            for j in range(i + 1, len(items)):
                if j not in used and comparer(items[i], items[j]):
                    used.add(j)
                    group.append(items[j])
            groups.append(group)
    return groups

Response: Combines similar items into groups.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _perp_eigendecompose(matrix: np.ndarray,
                         rtol: float = 1e-5,
                         atol: float = 1e-8,
                         ) -> Tuple[np.array, List[np.ndarray]]:
    """An eigendecomposition that ensures eigenvectors are perpendicular.

    numpy.linalg.eig doesn't guarantee that eigenvectors from the same
    eigenspace will be perpendicular. This method uses Gram-Schmidt to recover
    a perpendicular set. It further checks that all eigenvectors are
    perpendicular and raises an ArithmeticError otherwise.

    Args:
        matrix: The matrix to decompose.
        rtol: Relative threshold for determining whether eigenvalues are from
              the same eigenspace and whether eigenvectors are perpendicular.
        atol: Absolute threshold for determining whether eigenvalues are from
              the same eigenspace and whether eigenvectors are perpendicular.

    Returns:
        The eigenvalues and column eigenvectors. The i'th eigenvalue is
        associated with the i'th column eigenvector.

    Raises:
        ArithmeticError: Failed to find perpendicular eigenvectors.
    """
    vals, cols = np.linalg.eig(matrix)
    vecs = [cols[:, i] for i in range(len(cols))]

    # Convert list of row arrays to list of column arrays.
    for i in range(len(vecs)):
        vecs[i] = np.reshape(vecs[i], (len(vecs[i]), vecs[i].ndim))

    # Group by similar eigenvalue.
    n = len(vecs)
    groups = _group_similar(
        list(range(n)),
        lambda k1, k2: np.allclose(vals[k1], vals[k2], rtol=rtol))

    # Remove overlap between eigenvectors with the same eigenvalue.
    for g in groups:
        q, _ = np.linalg.qr(np.hstack([vecs[i] for i in g]))
        for i in range(len(g)):
            vecs[g[i]] = q[:, i]

    return vals, vecs

Response: Decomposes a matrix of the ith column eigenvectors into a perpendicular set of ith eigenvalues.


Instruction:
How would you explain what the following Python 3 function does
def map_eigenvalues(
        matrix: np.ndarray,
        func: Callable[[complex], complex],
        *,
        rtol: float = 1e-5,
        atol: float = 1e-8) -> np.ndarray:
    """Applies a function to the eigenvalues of a matrix.

    Given M = sum_k a_k |v_k><v_k|, returns f(M) = sum_k f(a_k) |v_k><v_k|.

    Args:
        matrix: The matrix to modify with the function.
        func: The function to apply to the eigenvalues of the matrix.
        rtol: Relative threshold used when separating eigenspaces.
        atol: Absolute threshold used when separating eigenspaces.

    Returns:
        The transformed matrix.
    """
    vals, vecs = _perp_eigendecompose(matrix,
                                      rtol=rtol,
                                      atol=atol)
    pieces = [np.outer(vec, np.conj(vec.T)) for vec in vecs]
    out_vals = np.vectorize(func)(vals.astype(complex))

    total = np.zeros(shape=matrix.shape)
    for piece, val in zip(pieces, out_vals):
        total = np.add(total, piece * val)
    return total

Response: Applies a function to the eigenvalues of a matrix.


Instruction:
Given the following Python 3 function, write the documentation
def kron_factor_4x4_to_2x2s(
        matrix: np.ndarray,
) -> Tuple[complex, np.ndarray, np.ndarray]:
    """Splits a 4x4 matrix U = kron(A, B) into A, B, and a global factor.

    Requires the matrix to be the kronecker product of two 2x2 unitaries.
    Requires the matrix to have a non-zero determinant.
    Giving an incorrect matrix will cause garbage output.

    Args:
        matrix: The 4x4 unitary matrix to factor.

    Returns:
        A scalar factor and a pair of 2x2 unit-determinant matrices. The
        kronecker product of all three is equal to the given matrix.

    Raises:
        ValueError:
            The given matrix can't be tensor-factored into 2x2 pieces.
    """

    # Use the entry with the largest magnitude as a reference point.
    a, b = max(
        ((i, j) for i in range(4) for j in range(4)),
        key=lambda t: abs(matrix[t]))

    # Extract sub-factors touching the reference cell.
    f1 = np.zeros((2, 2), dtype=np.complex128)
    f2 = np.zeros((2, 2), dtype=np.complex128)
    for i in range(2):
        for j in range(2):
            f1[(a >> 1) ^ i, (b >> 1) ^ j] = matrix[a ^ (i << 1), b ^ (j << 1)]
            f2[(a & 1) ^ i, (b & 1) ^ j] = matrix[a ^ i, b ^ j]

    # Rescale factors to have unit determinants.
    f1 /= (np.sqrt(np.linalg.det(f1)) or 1)
    f2 /= (np.sqrt(np.linalg.det(f2)) or 1)

    # Determine global phase.
    g = matrix[a, b] / (f1[a >> 1, b >> 1] * f2[a & 1, b & 1])
    if np.real(g) < 0:
        f1 *= -1
        g = -g

    return g, f1, f2

Response: Splits a 4x4 matrix U into A B and a pair of 2x2 unitaries.


Instruction:
How would you explain what the following Python 3 function does
def so4_to_magic_su2s(
        mat: np.ndarray,
        *,
        rtol: float = 1e-5,
        atol: float = 1e-8,
        check_preconditions: bool = True
) -> Tuple[np.ndarray, np.ndarray]:
    """Finds 2x2 special-unitaries A, B where mat = Mag.H @ kron(A, B) @ Mag.

    Mag is the magic basis matrix:

        1  0  0  i
        0  i  1  0
        0  i -1  0     (times sqrt(0.5) to normalize)
        1  0  0 -i

    Args:
        mat: A real 4x4 orthogonal matrix.
        rtol: Per-matrix-entry relative tolerance on equality.
        atol: Per-matrix-entry absolute tolerance on equality.
        check_preconditions: When set, the code verifies that the given
            matrix is from SO(4). Defaults to set.

    Returns:
        A pair (A, B) of matrices in SU(2) such that Mag.H @ kron(A, B) @ Mag
        is approximately equal to the given matrix.

    Raises:
        ValueError: Bad matrix.
        """
    if check_preconditions:
        if mat.shape != (4, 4) or not predicates.is_special_orthogonal(
                mat, atol=atol, rtol=rtol):
            raise ValueError('mat must be 4x4 special orthogonal.')

    ab = combinators.dot(MAGIC, mat, MAGIC_CONJ_T)
    _, a, b = kron_factor_4x4_to_2x2s(ab)

    return a, b

Response: This function converts a 4x4 orthogonal matrix to a 2x2 special - unitaries matrix.


Instruction:
Can you generate the documentation for the following Python 3 function
def kak_canonicalize_vector(x: float, y: float, z: float) -> KakDecomposition:

    phase = [complex(1)]  # Accumulated global phase.
    left = [np.eye(2)] * 2  # Per-qubit left factors.
    right = [np.eye(2)] * 2  # Per-qubit right factors.
    v = [x, y, z]  # Remaining XX/YY/ZZ interaction vector.

    # These special-unitary matrices flip the X, Y, and Z axes respectively.
    flippers = [
        np.array([[0, 1], [1, 0]]) * 1j,
        np.array([[0, -1j], [1j, 0]]) * 1j,
        np.array([[1, 0], [0, -1]]) * 1j
    ]

    # Each of these special-unitary matrices swaps two the roles of two axes.
    # The matrix at index k swaps the *other two* axes (e.g. swappers[1] is a
    # Hadamard operation that swaps X and Z).
    swappers = [
        np.array([[1, -1j], [1j, -1]]) * 1j * np.sqrt(0.5),
        np.array([[1, 1], [1, -1]]) * 1j * np.sqrt(0.5),
        np.array([[0, 1 - 1j], [1 + 1j, 0]]) * 1j * np.sqrt(0.5)
    ]

    # Shifting strength by ½π is equivalent to local ops (e.g. exp(i½π XX)∝XX).
    def shift(k, step):
        v[k] += step * np.pi / 2
        phase[0] *= 1j ** step
        right[0] = combinators.dot(flippers[k] ** (step % 4), right[0])
        right[1] = combinators.dot(flippers[k] ** (step % 4), right[1])

    # Two negations is equivalent to temporarily flipping along the other axis.
    def negate(k1, k2):
        v[k1] *= -1
        v[k2] *= -1
        phase[0] *= -1
        s = flippers[3 - k1 - k2]  # The other axis' flipper.
        left[1] = combinators.dot(left[1], s)
        right[1] = combinators.dot(s, right[1])

    # Swapping components is equivalent to temporarily swapping the two axes.
    def swap(k1, k2):
        v[k1], v[k2] = v[k2], v[k1]
        s = swappers[3 - k1 - k2]  # The other axis' swapper.
        left[0] = combinators.dot(left[0], s)
        left[1] = combinators.dot(left[1], s)
        right[0] = combinators.dot(s, right[0])
        right[1] = combinators.dot(s, right[1])

    # Shifts an axis strength into the range (-π/4, π/4].
    def canonical_shift(k):
        while v[k] <= -np.pi / 4:
            shift(k, +1)
        while v[k] > np.pi / 4:
            shift(k, -1)

    # Sorts axis strengths into descending order by absolute magnitude.
    def sort():
        if abs(v[0]) < abs(v[1]):
            swap(0, 1)
        if abs(v[1]) < abs(v[2]):
            swap(1, 2)
        if abs(v[0]) < abs(v[1]):
            swap(0, 1)

    # Get all strengths to (-¼π, ¼π] in descending order by absolute magnitude.
    canonical_shift(0)
    canonical_shift(1)
    canonical_shift(2)
    sort()

    # Move all negativity into z.
    if v[0] < 0:
        negate(0, 2)
    if v[1] < 0:
        negate(1, 2)
    canonical_shift(2)

    return KakDecomposition(
        global_phase=phase[0],
        single_qubit_operations_after=(left[1], left[0]),
        interaction_coefficients=(v[0], v[1], v[2]),
        single_qubit_operations_before=(right[1], right[0]))

Response: Canonicalizes an XX Y Z interaction by swap - negation and shift - ing axes.


Instruction:
Create a Python 3 function to
decompose a 2 - qubit unitary into 1 - qubit ops and XX YZ interactions.

Response:
def kak_decomposition(
        mat: np.ndarray,
        rtol: float = 1e-5,
        atol: float = 1e-8) -> KakDecomposition:
    """Decomposes a 2-qubit unitary into 1-qubit ops and XX/YY/ZZ interactions.

    Args:
        mat: The 4x4 unitary matrix to decompose.
        rtol: Per-matrix-entry relative tolerance on equality.
        atol: Per-matrix-entry absolute tolerance on equality.

    Returns:
        A `cirq.KakDecomposition` canonicalized such that the interaction
        coefficients x, y, z satisfy:

            0 ≤ abs(z) ≤ y ≤ x ≤ π/4
            z ≠ -π/4

    Raises:
        ValueError: Bad matrix.
        ArithmeticError: Failed to perform the decomposition.

    References:
        'An Introduction to Cartan's KAK Decomposition for QC Programmers'
        https://arxiv.org/abs/quant-ph/0507171
    """
    magic = np.array([[1, 0, 0, 1j],
                      [0, 1j, 1, 0],
                      [0, 1j, -1, 0],
                      [1, 0, 0, -1j]]) * np.sqrt(0.5)
    gamma = np.array([[1, 1, 1, 1],
                      [1, 1, -1, -1],
                      [-1, 1, -1, 1],
                      [1, -1, -1, 1]]) * 0.25

    # Diagonalize in magic basis.
    left, d, right = diagonalize.bidiagonalize_unitary_with_special_orthogonals(
        combinators.dot(np.conj(magic.T), mat, magic),
        atol=atol,
        rtol=rtol,
        check_preconditions=False)

    # Recover pieces.
    a1, a0 = so4_to_magic_su2s(left.T,
                               atol=atol,
                               rtol=rtol,
                               check_preconditions=False)
    b1, b0 = so4_to_magic_su2s(right.T,
                               atol=atol,
                               rtol=rtol,
                               check_preconditions=False)
    w, x, y, z = gamma.dot(np.vstack(np.angle(d))).flatten()
    g = np.exp(1j * w)

    # Canonicalize.
    inner_cannon = kak_canonicalize_vector(x, y, z)

    b1 = np.dot(inner_cannon.single_qubit_operations_before[0], b1)
    b0 = np.dot(inner_cannon.single_qubit_operations_before[1], b0)
    a1 = np.dot(a1, inner_cannon.single_qubit_operations_after[0])
    a0 = np.dot(a0, inner_cannon.single_qubit_operations_after[1])
    return KakDecomposition(
        interaction_coefficients=inner_cannon.interaction_coefficients,
        global_phase=g * inner_cannon.global_phase,
        single_qubit_operations_before=(b1, b0),
        single_qubit_operations_after=(a1, a0))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def update_mapping(mapping: Dict[ops.Qid, LogicalIndex],
                   operations: ops.OP_TREE
                   ) -> None:
    """Updates a mapping (in place) from qubits to logical indices according to
    a set of permutation gates. Any gates other than permutation gates are
    ignored.

    Args:
        mapping: The mapping to update.
        operations: The operations to update according to.
    """
    for op in ops.flatten_op_tree(operations):
        if (isinstance(op, ops.GateOperation) and
            isinstance(op.gate, PermutationGate)):
            op.gate.update_mapping(mapping, op.qubits)

Response: Updates a mapping from qubits to logical indices according to the given operations.


Instruction:
Create a Python 3 function for
updating a mapping from qubits to logical indices.

Response:
def update_mapping(self, mapping: Dict[ops.Qid, LogicalIndex],
                       keys: Sequence[ops.Qid]
                       ) -> None:
        """Updates a mapping (in place) from qubits to logical indices.

        Args:
            mapping: The mapping to update.
            keys: The qubits acted on by the gate.
        """
        permutation = self.permutation()
        indices = tuple(permutation.keys())
        new_keys = [keys[permutation[i]] for i in indices]
        old_elements = [mapping[keys[i]] for i in indices]
        mapping.update(zip(new_keys, old_elements))


Instruction:
Create a Python 3 function for
adding text to the given location.

Response:
def write(self,
              x: int,
              y: int,
              text: str,
              transposed_text: 'Optional[str]' = None):
        """Adds text to the given location.

        Args:
            x: The column in which to write the text.
            y: The row in which to write the text.
            text: The text to write at location (x, y).
            transposed_text: Optional text to write instead, if the text
                diagram is transposed.
        """
        entry = self.entries.get((x, y), _DiagramText('', ''))
        self.entries[(x, y)] = _DiagramText(
            entry.text + text,
            entry.transposed_text + (transposed_text if transposed_text
                                     else text))


Instruction:
Here you have a function in Python 3, explain what it does
def content_present(self, x: int, y: int) -> bool:

        # Text?
        if (x, y) in self.entries:
            return True

        # Vertical line?
        if any(v.x == x and v.y1 < y < v.y2 for v in self.vertical_lines):
            return True

        # Horizontal line?
        if any(line_y == y and x1 < x < x2
               for line_y, x1, x2, _ in self.horizontal_lines):
            return True

        return False

Response: Determines if a line or printed text is at the given location.


Instruction:
How would you implement a function in Python 3 that
adds a horizontal or vertical line from x1 y1 to x2 y2.

Response:
def grid_line(self, x1: int, y1: int, x2: int, y2: int,
                  emphasize: bool = False):
        """Adds a vertical or horizontal line from (x1, y1) to (x2, y2).

        Horizontal line is selected on equality in the second coordinate and
        vertical line is selected on equality in the first coordinate.

        Raises:
            ValueError: If line is neither horizontal nor vertical.
        """
        if x1 == x2:
            self.vertical_line(x1, y1, y2, emphasize)
        elif y1 == y2:
            self.horizontal_line(y1, x1, x2, emphasize)
        else:
            raise ValueError("Line is neither horizontal nor vertical")


Instruction:
Make a summary of the following Python 3 code
def vertical_line(self,
                      x: Union[int, float],
                      y1: Union[int, float],
                      y2: Union[int, float],
                      emphasize: bool = False
                      ) -> None:
        """Adds a line from (x, y1) to (x, y2)."""
        y1, y2 = sorted([y1, y2])
        self.vertical_lines.append(_VerticalLine(x, y1, y2, emphasize))

Response: Adds a vertical line from x y1 y2 to x y2.


Instruction:
Write a Python 3 script to
add a horizontal line to the log.

Response:
def horizontal_line(self,
                        y: Union[int, float],
                        x1: Union[int, float],
                        x2: Union[int, float],
                        emphasize: bool = False
                        ) -> None:
        """Adds a line from (x1, y) to (x2, y)."""
        x1, x2 = sorted([x1, x2])
        self.horizontal_lines.append(_HorizontalLine(y, x1, x2, emphasize))


Instruction:
Can you tell what is the following Python 3 function doing
def transpose(self) -> 'TextDiagramDrawer':
        out = TextDiagramDrawer()
        out.entries = {(y, x): _DiagramText(v.transposed_text, v.text)
                       for (x, y), v in self.entries.items()}
        out.vertical_lines = [_VerticalLine(*e)
                              for e in self.horizontal_lines]
        out.horizontal_lines = [_HorizontalLine(*e)
                                for e in self.vertical_lines]
        out.vertical_padding = self.horizontal_padding.copy()
        out.horizontal_padding = self.vertical_padding.copy()
        return out

Response: Returns the same diagram but mirrored across its diagonal.


Instruction:
Can you tell what is the following Python 3 function doing
def width(self) -> int:
        max_x = -1.0
        for x, _ in self.entries.keys():
            max_x = max(max_x, x)
        for v in self.vertical_lines:
            max_x = max(max_x, v.x)
        for h in self.horizontal_lines:
            max_x = max(max_x, h.x1, h.x2)
        return 1 + int(max_x)

Response: Determines how many entry columns are in the diagram.


Instruction:
How would you implement a function in Python 3 that
determines how many entry rows are in the diagram.

Response:
def height(self) -> int:
        """Determines how many entry rows are in the diagram."""
        max_y = -1.0
        for _, y in self.entries.keys():
            max_y = max(max_y, y)
        for h in self.horizontal_lines:
            max_y = max(max_y, h.y)
        for v in self.vertical_lines:
            max_y = max(max_y, v.y1, v.y2)
        return 1 + int(max_y)


Instruction:
Implement a Python 3 function for
changing the padding after the given column.

Response:
def force_horizontal_padding_after(
            self, index: int, padding: Union[int, float]) -> None:
        """Change the padding after the given column."""
        self.horizontal_padding[index] = padding


Instruction:
Given the following Python 3 function, write the documentation
def force_vertical_padding_after(
            self, index: int, padding: Union[int, float]) -> None:
        """Change the padding after the given row."""
        self.vertical_padding[index] = padding

Response: Change the padding after the given row.


Instruction:
Given the following Python 3 function, write the documentation
def insert_empty_columns(self, x: int, amount: int = 1) -> None:
        def transform_columns(
                column: Union[int, float],
                row: Union[int, float]
        ) -> Tuple[Union[int, float], Union[int, float]]:
            return column + (amount if column >= x else 0), row
        self._transform_coordinates(transform_columns)

Response: Insert a number of columns after the given column.


Instruction:
How would you explain what the following Python 3 function does
def insert_empty_rows(self, y: int, amount: int = 1) -> None:
        def transform_rows(
                column: Union[int, float],
                row: Union[int, float]
        ) -> Tuple[Union[int, float], Union[int, float]]:
            return column, row + (amount if row >= y else 0)
        self._transform_coordinates(transform_rows)

Response: Insert a number of rows after the given row.


Instruction:
Write a Python 3 script to
output text containing the diagram.

Response:
def render(self,
               horizontal_spacing: int = 1,
               vertical_spacing: int = 1,
               crossing_char: str = None,
               use_unicode_characters: bool = True) -> str:
        """Outputs text containing the diagram."""

        block_diagram = BlockDiagramDrawer()

        w = self.width()
        h = self.height()

        # Communicate padding into block diagram.
        for x in range(0, w - 1):
            block_diagram.set_col_min_width(
                x*2 + 1,
                # Horizontal separation looks narrow, so partials round up.
                int(np.ceil(self.horizontal_padding.get(x, horizontal_spacing)))
            )
            block_diagram.set_col_min_width(x*2, 1)
        for y in range(0, h - 1):
            block_diagram.set_row_min_height(
                y*2 + 1,
                # Vertical separation looks wide, so partials round down.
                int(np.floor(self.vertical_padding.get(y, vertical_spacing)))
            )
            block_diagram.set_row_min_height(y*2, 1)

        # Draw vertical lines.
        for x_b, y1_b, y2_b, emphasize in self.vertical_lines:
            x = int(x_b * 2)
            y1, y2 = int(min(y1_b, y2_b) * 2), int(max(y1_b, y2_b) * 2)
            charset = pick_charset(use_unicode_characters, emphasize)

            # Caps.
            block_diagram.mutable_block(x, y1).draw_curve(
                charset, bottom=True)
            block_diagram.mutable_block(x, y2).draw_curve(
                charset, top=True)

            # Span.
            for y in range(y1 + 1, y2):
                block_diagram.mutable_block(x, y).draw_curve(
                    charset, top=True, bottom=True)

        # Draw horizontal lines.
        for y_b, x1_b, x2_b, emphasize in self.horizontal_lines:
            y = int(y_b * 2)
            x1, x2 = int(min(x1_b, x2_b) * 2), int(max(x1_b, x2_b) * 2)
            charset = pick_charset(use_unicode_characters, emphasize)

            # Caps.
            block_diagram.mutable_block(x1, y).draw_curve(
                charset, right=True)
            block_diagram.mutable_block(x2, y).draw_curve(
                charset, left=True)

            # Span.
            for x in range(x1 + 1, x2):
                block_diagram.mutable_block(x, y).draw_curve(
                    charset, left=True, right=True, crossing_char=crossing_char)

        # Place entries.
        for (x, y), v in self.entries.items():
            x *= 2
            y *= 2
            block_diagram.mutable_block(x, y).content = v.text

        return block_diagram.render()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def all_near_zero(a: Union[float, complex, Iterable[float], np.ndarray],
                  *,
                  atol: float = 1e-8) -> bool:
    """Checks if the tensor's elements are all near zero.

    Args:
        a: Tensor of elements that could all be near zero.
        atol: Absolute tolerance.
    """
    return np.all(np.less_equal(np.abs(a), atol))

Response: Checks if the tensor s elements are all near zero.


Instruction:
Write a Python 3 script to
check if the elements of a tensor are all near zero.

Response:
def all_near_zero_mod(a: Union[float, complex, Iterable[float], np.ndarray],
                      period: float,
                      *,
                      atol: float = 1e-8) -> bool:
    """Checks if the tensor's elements are all near multiples of the period.

    Args:
        a: Tensor of elements that could all be near multiples of the period.
        period: The period, e.g. 2 pi when working in radians.
        atol: Absolute tolerance.
    """
    b = (np.asarray(a) + period / 2) % period - period / 2
    return np.all(np.less_equal(np.abs(b), atol))


Instruction:
Can you generate the documentation for the following Python 3 function
def _git_fetch_for_comparison(remote: str,
                              actual_branch: str,
                              compare_branch: str,
                              verbose: bool) -> prepared_env.PreparedEnv:
    """Fetches two branches including their common ancestor.

    Limits the depth of the fetch to avoid unnecessary work. Scales up the
    depth exponentially and tries again when the initial guess is not deep
    enough.

    Args:
        remote: The location of the remote repository, in a format that the
            git command will understand.
        actual_branch: A remote branch or ref to fetch,
        compare_branch: Another remote branch or ref to fetch,
        verbose: When set, more progress output is produced.

    Returns:
        A ComparableCommits containing the commit id of the actual branch and
        a the id of a commit to compare against (e.g. for when doing incremental
        checks).
    """
    actual_id = ''
    base_id = ''
    for depth in [10, 100, 1000, None]:
        depth_str = '' if depth is None else '--depth={}'.format(depth)

        shell_tools.run_cmd(
            'git',
            'fetch',
            None if verbose else '--quiet',
            remote,
            actual_branch,
            depth_str,
            log_run_to_stderr=verbose)
        actual_id = shell_tools.output_of('git', 'rev-parse', 'FETCH_HEAD')

        shell_tools.run_cmd('git',
                            'fetch',
                            None if verbose else '--quiet',
                            remote,
                            compare_branch,
                            depth_str,
                            log_run_to_stderr=verbose)
        base_id = shell_tools.output_of('git', 'rev-parse', 'FETCH_HEAD')

        try:
            base_id = shell_tools.output_of(
                'git',
                'merge-base',
                actual_id,
                base_id)
            break
        except subprocess.CalledProcessError:
            # No common ancestor. We need to dig deeper.
            pass

    return prepared_env.PreparedEnv(None, actual_id, base_id, None, None)

Response: Fetches two branches including their common ancestor and returns the actual branch and base branch.


Instruction:
Explain what the following Python 3 code does
def fetch_github_pull_request(destination_directory: str,
                              repository: github_repository.GithubRepository,
                              pull_request_number: int,
                              verbose: bool
                              ) -> prepared_env.PreparedEnv:
    """Uses content from github to create a dir for testing and comparisons.

    Args:
        destination_directory: The location to fetch the contents into.
        repository: The github repository that the commit lives under.
        pull_request_number: The id of the pull request to clone. If None, then
            the master branch is cloned instead.
        verbose: When set, more progress output is produced.

    Returns:
        Commit ids corresponding to content to test/compare.
    """

    branch = 'pull/{}/head'.format(pull_request_number)
    os.chdir(destination_directory)
    print('chdir', destination_directory, file=sys.stderr)

    shell_tools.run_cmd(
        'git',
        'init',
        None if verbose else '--quiet',
        out=sys.stderr)
    result = _git_fetch_for_comparison(remote=repository.as_remote(),
                                       actual_branch=branch,
                                       compare_branch='master',
                                       verbose=verbose)
    shell_tools.run_cmd(
        'git',
        'branch',
        None if verbose else '--quiet',
        'compare_commit',
        result.compare_commit_id,
        log_run_to_stderr=verbose)
    shell_tools.run_cmd(
        'git',
        'checkout',
        None if verbose else '--quiet',
        '-b',
        'actual_commit',
        result.actual_commit_id,
        log_run_to_stderr=verbose)
    return prepared_env.PreparedEnv(
        github_repo=repository,
        actual_commit_id=result.actual_commit_id,
        compare_commit_id=result.compare_commit_id,
        destination_directory=destination_directory,
        virtual_env_path=None)

Response: Uses content from github to create a dir for testing and comparison.


Instruction:
Explain what the following Python 3 code does
def fetch_local_files(destination_directory: str,
                      verbose: bool) -> prepared_env.PreparedEnv:
    """Uses local files to create a directory for testing and comparisons.

    Args:
        destination_directory: The directory where the copied files should go.
        verbose: When set, more progress output is produced.

    Returns:
        Commit ids corresponding to content to test/compare.
    """
    staging_dir = destination_directory + '-staging'
    try:
        shutil.copytree(get_repo_root(), staging_dir)
        os.chdir(staging_dir)
        if verbose:
            print('chdir', staging_dir, file=sys.stderr)

        shell_tools.run_cmd(
            'git',
            'add',
            '--all',
            out=sys.stderr,
            log_run_to_stderr=verbose)

        shell_tools.run_cmd(
            'git',
            'commit',
            '-m', 'working changes',
            '--allow-empty',
            '--no-gpg-sign',
            None if verbose else '--quiet',
            out=sys.stderr,
            log_run_to_stderr=verbose)

        cur_commit = shell_tools.output_of('git', 'rev-parse', 'HEAD')

        os.chdir(destination_directory)
        if verbose:
            print('chdir', destination_directory, file=sys.stderr)
        shell_tools.run_cmd('git',
                            'init',
                            None if verbose else '--quiet',
                            out=sys.stderr,
                            log_run_to_stderr=verbose)
        result = _git_fetch_for_comparison(staging_dir,
                                           cur_commit,
                                           'master',
                                           verbose=verbose)
    finally:
        shutil.rmtree(staging_dir, ignore_errors=True)

    shell_tools.run_cmd(
        'git',
        'branch',
        None if verbose else '--quiet',
        'compare_commit',
        result.compare_commit_id,
        log_run_to_stderr=verbose)
    shell_tools.run_cmd(
        'git',
        'checkout',
        None if verbose else '--quiet',
        '-b',
        'actual_commit',
        result.actual_commit_id,
        log_run_to_stderr=verbose)
    return prepared_env.PreparedEnv(
        github_repo=None,
        actual_commit_id=result.actual_commit_id,
        compare_commit_id=result.compare_commit_id,
        destination_directory=destination_directory,
        virtual_env_path=None)

Response: Uses local files to create a directory for testing and comparison.


Instruction:
How would you explain what the following Python 3 function does
def circuit_to_tensorflow_runnable(
        circuit: circuits.Circuit,
        initial_state: Union[int, np.ndarray] = 0,
        ) -> ComputeFuncAndFeedDict:
    """Returns a compute function and feed_dict for a `cirq.Circuit`'s output.

    `result.compute()` will return a `tensorflow.Tensor` with
    `tensorflow.placeholder` objects to be filled in by `result.feed_dict`, at
    which point it will evaluate to the output state vector of the circuit.

    You can apply further operations to the tensor returned by
    `result.compute`. This allows, for example, for the final result to be
    a small amount of computed data (e.g. an expectation value) instead of the
    gigantic raw state vector.

    The tensor returned by `result.compute` is intended to run efficiently
    on cloud TPUs. It will have dtype complex64 and a shape of (2**n,) where n
    is the number of qubits.

    Examples:
        To simulate the circuit with tensorflow in a normal session, forward
        this method's output into `tensorflow.Session.run` as follows:

            import tensorflow as tf
            r = circuit_to_tensorflow_runnable(...)
            with tf.Session() as session:
                output = session.run(r.compute(), feed_dict=r.feed_dict)
            print(output)

        Note that you can use the returned tensor in further computations. For
        example, to compute the chance of the system ending up in the first 128
        computational basis states you can use `tf.norm(tensor[:128], 2)`:

            import tensorflow as tf
            r = circuit_to_tensorflow_runnable(...)
            expectation = lambda: tf.norm(r.compute()[:128], 2)
            with tf.Session() as session:
                output = session.run(expectation, feed_dict=r.feed_dict)
            print(output)

        For documentation on running against cloud TPUs, see

            https://cloud.google.com/tpu/docs/quickstart#run_example

        Generally speaking, from within a cloud instance, you use
        `tf.contrib.tpu.rewrite` to convert the tensor into a TPU compatible
        form, initialize the TPU system, then run the rewritten tensor:

            import tensorflow as tf
            TPU_TARGET = ???????
            r = circuit_to_tensorflow_runnable(...YOUR_CIRCUIT...)
            rewritten_for_tpu = tf.contrib.tpu.rewrite(r.compute)

            with tf.Session(target=TPU_TARGET) as session:
                session.run(tf.contrib.tpu.initialize_system())
                output = session.run(rewritten_for_tpu, feed_dict=r.feed_dict)
            print(output)

    Args:
        circuit: The circuit to apply to `initial_state` to produce an output
            state vector.
        initial_state: The input into the circuit. If this is an integer, it
            indicates that the input state is a computational basis state where
            the k'th qubit is set by the k'th bit of the integer. If this is
            a numpy array, it should directly encode a normalized wavefunction.

    Returns:
        A ComputeFuncAndFeedDict, which is a named tuple whose first element is
        a function that returns a Tensor representing the output state vector
        that results from applying the given circuit to the given, and whose
        second element is a feed_dict containing important parameters describing
        that tensor.
    """
    if not circuit.are_all_measurements_terminal():
        raise ValueError('not circuit.are_all_measurements_terminal()')

    t = _TensorCircuit(circuit, initial_state)
    return ComputeFuncAndFeedDict(t.compute, t.feed_dict)

Response: Returns a compute function and feed_dict for a single circuit.


Instruction:
Here you have a function in Python 3, explain what it does
def _circuit_as_layers(circuit: circuits.Circuit,
                       grouping: _QubitGrouping) -> List[_TransformsThenCzs]:
    """Transforms a circuit into a series of GroupMatrix+CZ layers.

    Args:
        circuit: The circuit to transform.
        grouping: How the circuit's qubits are combined into groups.

    Returns:
        A list of layers. Each layer has a matrix to apply to each group of
        qubits, and a list of CZs to apply to pairs of qubits crossing
        between groups.
    """
    frontier = {q: 0 for q in circuit.all_qubits()}

    layers = []
    while True:
        # Pull within-group operations into per-group matrices.
        any_group_matrices = False
        group_matrices = []
        for g in grouping.groups:
            # Scan for reachable operations contained within the group qubits.
            start_frontier = {q: frontier[q] for q in g}
            end_frontier = circuit.reachable_frontier_from(start_frontier)
            mergeable_ops = circuit.findall_operations_between(start_frontier,
                                                               end_frontier)

            # Advance frontier.
            for q, v in end_frontier.items():
                frontier[q] = v

            # Fold reachable operations into a single group matrix.
            group_matrix = np.eye(1 << len(g)).reshape((2, 2) * len(g))
            if mergeable_ops:
                any_group_matrices = True
            for _, op in mergeable_ops:
                group_matrix = linalg.targeted_left_multiply(
                    left_matrix=protocols.unitary(op).reshape(
                        (2, 2) * len(op.qubits)),
                    right_target=group_matrix,
                    target_axes=[grouping.loc(q)[1] for q in op.qubits])
            group_matrices.append(np.transpose(group_matrix.reshape(
                1 << len(g), 1 << len(g))))

        # Scan for reachable CZ operations between groups.
        end_frontier = circuit.reachable_frontier_from(
            frontier,
            is_blocker=lambda op: grouping.all_in_same_group(*op.qubits))
        cz_ops = circuit.findall_operations_between(frontier, end_frontier)

        # Advance frontier.
        frontier = end_frontier

        # List out qubit index pairs for each CZ.
        cz_indices = []
        for _, cz in cz_ops:
            a, b = cz.qubits
            assert cz == ops.CZ(a, b)
            cz_indices.append((grouping.ind(a), grouping.ind(b)))

        # Combine group and CZ operations into a simulation layer.
        if not any_group_matrices and not cz_indices:
            break
        layer = _TransformsThenCzs(group_matrices=group_matrices,
                                   cz_indices=cz_indices)
        layers.append(layer)

    # We should have processed the whole circuit.
    assert frontier == {q: len(circuit) for q in circuit.all_qubits()}

    return layers

Response: Transforms a circuit into a series of GroupMatrix + CZs.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _deref(tensor: tf.Tensor, index: tf.Tensor) -> tf.Tensor:
    assert tensor.shape[0] > 0
    return _deref_helper(lambda i: tensor[i, ...],
                         index,
                         0,
                         tensor.shape[0] - 1)

Response: Equivalent to tensor [ index... ].


Instruction:
How would you explain what the following Python 3 function does
def _multi_deref(tensors: List[tf.Tensor], index: tf.Tensor) -> List[tf.Tensor]:
    assert tensors
    assert tensors[0].shape[0] > 0
    return _deref_helper(lambda i: [tensor[i, ...] for tensor in tensors],
                         index,
                         0,
                         tensors[0].shape[0] - 1)

Response: Equivalent to _deref for multi - tensor.


Instruction:
Write a Python 3 function for
running the given circuit or schedule and returns the first result.

Response:
def run(
            self,
            program: Union[circuits.Circuit, schedules.Schedule],
            param_resolver: 'study.ParamResolverOrSimilarType' = None,
            repetitions: int = 1,
    ) -> study.TrialResult:
        """Samples from the given Circuit or Schedule.

        Args:
            program: The circuit or schedule to simulate.
            param_resolver: Parameters to run with the program.
            repetitions: The number of repetitions to simulate.

        Returns:
            TrialResult for a run.
        """
        return self.run_sweep(program, study.ParamResolver(param_resolver),
                              repetitions)[0]


Instruction:
How would you explain what the following Python 3 function does
def run_sweep(
            self,
            program: Union[circuits.Circuit, schedules.Schedule],
            params: study.Sweepable,
            repetitions: int = 1,
    ) -> List[study.TrialResult]:
        """Samples from the given Circuit or Schedule.

        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.
            repetitions: The number of repetitions to simulate.

        Returns:
            TrialResult list for this run; one for each possible parameter
            resolver.
        """

Response: Runs the sweeping procedure over the given parameter set.


Instruction:
How would you explain what the following Python 3 function does
def measure(*qubits: raw_types.Qid,
            key: Optional[str] = None,
            invert_mask: Tuple[bool, ...] = ()
            ) -> gate_operation.GateOperation:
    """Returns a single MeasurementGate applied to all the given qubits.

    The qubits are measured in the computational basis.

    Args:
        *qubits: The qubits that the measurement gate should measure.
        key: The string key of the measurement. If this is None, it defaults
            to a comma-separated list of the target qubits' str values.
        invert_mask: A list of Truthy or Falsey values indicating whether
            the corresponding qubits should be flipped. None indicates no
            inverting should be done.

    Returns:
        An operation targeting the given qubits with a measurement.

    Raises:
        ValueError if the qubits are not instances of Qid.
    """
    for qubit in qubits:
        if isinstance(qubit, np.ndarray):
            raise ValueError(
                    'measure() was called a numpy ndarray. Perhaps you meant '
                    'to call measure_state_vector on numpy array?'
            )
        elif not isinstance(qubit, raw_types.Qid):
            raise ValueError(
                    'measure() was called with type different than Qid.')

    if key is None:
        key = _default_measurement_key(qubits)
    return MeasurementGate(len(qubits), key, invert_mask).on(*qubits)

Response: Returns a MeasurementGate applied to all the given qubits.


Instruction:
Write a Python 3 function for
returning a list of operations individually measuring the given qubits.

Response:
def measure_each(*qubits: raw_types.Qid,
                 key_func: Callable[[raw_types.Qid], str] = str
                 ) -> List[gate_operation.GateOperation]:
    """Returns a list of operations individually measuring the given qubits.

    The qubits are measured in the computational basis.

    Args:
        *qubits: The qubits to measure.
        key_func: Determines the key of the measurements of each qubit. Takes
            the qubit and returns the key for that qubit. Defaults to str.

    Returns:
        A list of operations individually measuring the given qubits.
    """
    return [MeasurementGate(1, key_func(q)).on(q) for q in qubits]


Instruction:
Can you generate a brief explanation for the following Python 3 code
def Rx(rads: Union[float, sympy.Basic]) -> XPowGate:
    pi = sympy.pi if protocols.is_parameterized(rads) else np.pi
    return XPowGate(exponent=rads / pi, global_shift=-0.5)

Response: Returns a gate with the matrix e^ - i X rads / 2.


Instruction:
Can you create a Python 3 function that
returns a gate with the matrix e^Y rads / 2.

Response:
def Ry(rads: Union[float, sympy.Basic]) -> YPowGate:
    """Returns a gate with the matrix e^{-i Y rads / 2}."""
    pi = sympy.pi if protocols.is_parameterized(rads) else np.pi
    return YPowGate(exponent=rads / pi, global_shift=-0.5)


Instruction:
Given the following Python 3 function, write the documentation
def Rz(rads: Union[float, sympy.Basic]) -> ZPowGate:
    pi = sympy.pi if protocols.is_parameterized(rads) else np.pi
    return ZPowGate(exponent=rads / pi, global_shift=-0.5)

Response: Returns a ZPowGate with the matrix e^ - i Z rads.


Instruction:
How would you explain what the following Python 3 function does
def _decompose_(self, qubits):
        a, b = qubits
        yield CNOT(a, b)
        yield CNOT(b, a) ** self._exponent
        yield CNOT(a, b)

Response: Decomposes the set of qubits into a set of unique entries.


Instruction:
Here you have a function in Python 3, explain what it does
def validate_args(self, qubits: Sequence[Qid]) -> None:
        if len(qubits) == 0:
            raise ValueError(
                "Applied a gate to an empty set of qubits. Gate: {}".format(
                    repr(self)))

        if len(qubits) != self.num_qubits():
            raise ValueError(
                'Wrong number of qubits for <{!r}>. '
                'Expected {} qubits but got <{!r}>.'.format(
                    self,
                    self.num_qubits(),
                    qubits))

        if any([not isinstance(qubit, Qid)
                for qubit in qubits]):
            raise ValueError(
                    'Gate was called with type different than Qid.')

Response: Checks if this gate can be applied to the given qubits.


Instruction:
Can you write a function in Python 3 where it
returns an application of this gate to the given qubits.

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

        Args:
            *qubits: The collection of qubits to potentially apply the gate to.
        """
        # Avoids circular import.
        from cirq.ops import gate_operation
        return gate_operation.GateOperation(self, list(qubits))


Instruction:
Create a Python 3 function for
returning a controlled version of this gate.

Response:
def controlled_by(self, *control_qubits: Qid) -> 'Gate':
        """Returns a controlled version of this gate.

        Args:
            control_qubits: Optional qubits to control the gate by.
        """
        # Avoids circular import.
        from cirq.ops import ControlledGate
        return ControlledGate(self, control_qubits,
                              len(control_qubits) if control_qubits is not None
                                                  else 1)


Instruction:
How would you code a function in Python 3 to
return the same operation but with different qubits.

Response:
def transform_qubits(self: TSelf_Operation,
                         func: Callable[[Qid], Qid]) -> TSelf_Operation:
        """Returns the same operation, but with different qubits.

        Args:
            func: The function to use to turn each current qubit into a desired
                new qubit.

        Returns:
            The receiving operation but with qubits transformed by the given
                function.
        """
        return self.with_qubits(*(func(q) for q in self.qubits))


Instruction:
Can you generate the documentation for the following Python 3 function
def controlled_by(self, *control_qubits: Qid) -> 'Operation':
        # Avoids circular import.
        from cirq.ops import ControlledOperation
        if control_qubits is None or len(control_qubits) is 0:
            raise ValueError(
                "Can't get controlled operation without control qubit. Op: {}"
                .format(repr(self)))
        else:
            return ControlledOperation(control_qubits, self)

Response: Returns a controlled version of this operation.


Instruction:
Can you generate the documentation for the following Python 3 function
def perform_check(self,
                      env: env_tools.PreparedEnv,
                      verbose: bool) -> Tuple[bool, str]:
        """Evaluates the status check and returns a pass/fail with message.

        Args:
            env: Describes a prepared python 3 environment in which to run.
            verbose: When set, more progress output is produced.

        Returns:
            A tuple containing a pass/fail boolean and then a details message.
        """

Response: Evaluates the status check and returns a pass or fail with a details message.


Instruction:
Can you tell what is the following Python 3 function doing
def run(self,
            env: env_tools.PreparedEnv,
            verbose: bool,
            previous_failures: Set['Check']) -> CheckResult:
        """Evaluates this check.

        Args:
            env: The prepared python environment to run the check in.
            verbose: When set, more progress output is produced.
            previous_failures: Checks that have already run and failed.

        Returns:
            A CheckResult instance.
        """

        # Skip if a dependency failed.
        if previous_failures.intersection(self.dependencies):
            print(shell_tools.highlight(
                'Skipped ' + self.command_line_switch(),
                shell_tools.YELLOW))
            return CheckResult(
                self, False, 'Skipped due to dependency failing.', None)

        print(shell_tools.highlight(
            'Running ' + self.command_line_switch(),
            shell_tools.GREEN))
        try:
            success, message = self.perform_check(env, verbose=verbose)
            result = CheckResult(self, success, message, None)
        except Exception as ex:
            result = CheckResult(self, False, 'Unexpected error.', ex)

        print(shell_tools.highlight(
            'Finished ' + self.command_line_switch(),
            shell_tools.GREEN if result.success else shell_tools.RED))
        if verbose:
            print(result)

        return result

Response: Runs the check in the given python environment.


Instruction:
Can you generate the documentation for the following Python 3 function
def pick_env_and_run_and_report(self,
                                    env: env_tools.PreparedEnv,
                                    env_py2: Optional[env_tools.PreparedEnv],
                                    verbose: bool,
                                    previous_failures: Set['Check']
                                    ) -> CheckResult:
        """Evaluates this check in python 3 or 2.7, and reports to github.

        If the prepared environments are not linked to a github repository,
        with a known access token, reporting to github is skipped.

        Args:
            env: A prepared python 3 environment.
            env_py2: A prepared python 2.7 environment.
            verbose: When set, more progress output is produced.
            previous_failures: Checks that have already run and failed.

        Returns:
            A CheckResult instance.
        """
        env.report_status_to_github('pending', 'Running...', self.context())
        chosen_env = cast(env_tools.PreparedEnv,
                          env_py2 if self.needs_python2_env() else env)
        os.chdir(cast(str, chosen_env.destination_directory))

        result = self.run(chosen_env, verbose, previous_failures)

        if result.unexpected_error is not None:
            env.report_status_to_github('error',
                                        'Unexpected error.',
                                        self.context())
        else:
            env.report_status_to_github(
                'success' if result.success else 'failure',
                result.message,
                self.context())

        return result

Response: Selects the environment and runs it and reports the result to github.


Instruction:
Can you tell what is the following Python 3 function doing
def to_resolvers(sweepable: Sweepable) -> List[ParamResolver]:
    if isinstance(sweepable, ParamResolver):
        return [sweepable]
    elif isinstance(sweepable, Sweep):
        return list(sweepable)
    elif isinstance(sweepable, collections.Iterable):
        iterable = cast(collections.Iterable, sweepable)
        return list(iterable) if isinstance(next(iter(iterable)),
                                            ParamResolver) else sum(
            [list(s) for s in iterable], [])
    raise TypeError('Unexpected Sweepable type.')

Response: Convert a Sweepable to a list of ParamResolvers.


Instruction:
Can you implement a function in Python 3 that
returns whether the object is parameterized with any unresolved Symbols.

Response:
def is_parameterized(val: Any) -> bool:
    """Returns whether the object is parameterized with any Symbols.

    A value is parameterized when it has an `_is_parameterized_` method and
    that method returns a truthy value, or if the value is an instance of
    sympy.Basic.

    Returns:
        True if the gate has any unresolved Symbols
        and False otherwise. If no implementation of the magic
        method above exists or if that method returns NotImplemented,
        this will default to False.
    """
    if isinstance(val, sympy.Basic):
        return True

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

    if result is not NotImplemented:
        return result
    else:
        return False


Instruction:
Explain what the following Python 3 code does
def resolve_parameters(
        val: Any,
        param_resolver: 'cirq.ParamResolverOrSimilarType') -> Any:
    """Resolves symbol parameters in the effect using the param resolver.

    This function will use the `_resolve_parameters_` magic method
    of `val` to resolve any Symbols with concrete values from the given
    parameter resolver.

    Args:
        val: The object to resolve (e.g. the gate, operation, etc)
        param_resolver: the object to use for resolving all symbols

    Returns:
        a gate or operation of the same type, but with all Symbols
        replaced with floats according to the given ParamResolver.
        If `val` has no `_resolve_parameters_` method or if it returns
        NotImplemented, `val` itself is returned.
    """
    if not param_resolver:
        return val

    # Ensure its a dictionary wrapped in a ParamResolver.
    from cirq import ParamResolver  # HACK: break cycle.
    param_resolver = ParamResolver(param_resolver)
    if isinstance(val, sympy.Basic):
        return param_resolver.value_of(val)

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

    if result is not NotImplemented:
        return result
    else:
        return val

Response: Resolves symbol parameters in the effect using the given ParamResolver.


Instruction:
Here you have a function in Python 3, explain what it does
def circuit_to_latex_using_qcircuit(
        circuit: circuits.Circuit,
        qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT) -> str:
    """Returns a QCircuit-based latex diagram of the given circuit.

    Args:
        circuit: The circuit to represent in latex.
        qubit_order: Determines the order of qubit wires in the diagram.

    Returns:
        Latex code for the diagram.
    """
    diagram = circuit.to_text_diagram_drawer(
        qubit_namer=qcircuit_qubit_namer,
        qubit_order=qubit_order,
        get_circuit_diagram_info=get_qcircuit_diagram_info)
    return _render(diagram)

Response: Returns a LaTeX code for the given circuit.


Instruction:
Explain what the following Python 3 code does
def kron(*matrices: np.ndarray) -> np.ndarray:
    product = np.eye(1)
    for m in matrices:
        product = np.kron(product, m)
    return np.array(product)

Response: Computes the kronecker product of a sequence of matrices.


Instruction:
How would you implement a function in Python 3 that
computes the kronecker product of a sequence of matrices and controls.

Response:
def kron_with_controls(*matrices: np.ndarray) -> np.ndarray:
    """Computes the kronecker product of a sequence of matrices and controls.

    Use linalg.CONTROL_TAG to represent controls. Any entry of the output
    matrix corresponding to a situation where the control is not satisfied will
    be overwritten by identity matrix elements.

    The control logic works by imbuing NaN with the meaning "failed to meet one
    or more controls". The normal kronecker product then spreads the per-item
    NaNs to all the entries in the product that need to be replaced by identity
    matrix elements. This method rewrites those NaNs. Thus CONTROL_TAG can be
    the matrix [[NaN, 0], [0, 1]] or equivalently [[NaN, NaN], [NaN, 1]].

    Because this method re-interprets NaNs as control-failed elements, it won't
    propagate error-indicating NaNs from its input to its output in the way
    you'd otherwise expect.

    Args:
        *matrices: The matrices and controls to combine with the kronecker
            product.

    Returns:
        The resulting matrix.
    """

    product = kron(*matrices)

    # The NaN from CONTROL_TAG spreads to everywhere identity belongs.
    for i in range(product.shape[0]):
        for j in range(product.shape[1]):
            if np.isnan(product[i, j]):
                product[i, j] = 1 if i == j else 0

    return product


Instruction:
Can you implement a function in Python 3 that
computes the dot/matrix product of a sequence of values. A *args version of np.linalg.multi_dot. Args: *values: The values to combine with the dot/matrix product. Returns: The resulting value or matrix.

Response:
def dot(*values: Union[float, complex, np.ndarray]
        ) -> Union[float, complex, np.ndarray]:
    """Computes the dot/matrix product of a sequence of values.

    A *args version of np.linalg.multi_dot.

    Args:
        *values: The values to combine with the dot/matrix product.

    Returns:
        The resulting value or matrix.
    """
    if len(values) == 1:
        if isinstance(values[0], np.ndarray):
            return np.array(values[0])
        return values[0]
    return np.linalg.multi_dot(values)


Instruction:
Make a summary of the following Python 3 code
def block_diag(*blocks: np.ndarray) -> np.ndarray:
    for b in blocks:
        if b.shape[0] != b.shape[1]:
            raise ValueError('Blocks must be square.')

    if not blocks:
        return np.zeros((0, 0), dtype=np.complex128)

    n = sum(b.shape[0] for b in blocks)
    dtype = functools.reduce(_merge_dtypes, (b.dtype for b in blocks))

    result = np.zeros(shape=(n, n), dtype=dtype)
    i = 0
    for b in blocks:
        j = i + b.shape[0]
        result[i:j, i:j] = b
        i = j

    return result

Response: Concatenates blocks into a block diagonal matrix.


Instruction:
Create a Python 3 function to
find the first index of a target item within a list of lists.

Response:
def index_2d(seqs: List[List[Any]], target: Any) -> Tuple[int, int]:
    """Finds the first index of a target item within a list of lists.

    Args:
        seqs: The list of lists to search.
        target: The item to find.

    Raises:
        ValueError: Item is not present.
    """
    for i in range(len(seqs)):
        for j in range(len(seqs[i])):
            if seqs[i][j] == target:
                return i, j
    raise ValueError('Item not present.')


Instruction:
Write a Python 3 script to
issue new linear sequence search.

Response:
def search(
            self,
            trace_func: Callable[
                [List[LineSequence], float, float, float, bool],
                None] = None) -> List[LineSequence]:
        """Issues new linear sequence search.

        Each call to this method starts new search.

        Args:
          trace_func: Optional callable which will be called for each simulated
            annealing step with arguments: solution candidate (list of linear
            sequences on the chip), current temperature (float), candidate cost
            (float), probability of accepting candidate (float), and acceptance
            decision (boolean).

        Returns:
          List of linear sequences on the chip found by this method.
        """

        def search_trace(state: _STATE, temp: float,
                         cost: float, probability: float, accepted: bool):
            if trace_func:
                trace_seqs, _ = state
                trace_func(trace_seqs, temp, cost, probability, accepted)

        seqs, _ = optimization.anneal_minimize(
            self._create_initial_solution(),
            self._quadratic_sum_cost,
            self._force_edges_active_move,
            self._rand.random_sample,
            trace_func=search_trace)
        return seqs


Instruction:
Can you generate the documentation for the following Python 3 function
def _quadratic_sum_cost(self, state: _STATE) -> float:
        cost = 0.0
        total_len = float(len(self._c))
        seqs, _ = state
        for seq in seqs:
            cost += (len(seq) / total_len) ** 2
        return -cost

Response: Function that sums squares of lengths of sequences.


Instruction:
Create a Python 3 function to
move function which repeats _force_edge_active_move a few times.

Response:
def _force_edges_active_move(self, state: _STATE) -> _STATE:
        """Move function which repeats _force_edge_active_move a few times.

        Args:
          state: Search state, not mutated.

        Returns:
          New search state which consists of incremental changes of the
          original state.
        """
        for _ in range(self._rand.randint(1, 4)):
            state = self._force_edge_active_move(state)
        return state


Instruction:
Here you have a function in Python 3, explain what it does
def _force_edge_active_move(self, state: _STATE) -> _STATE:
        seqs, edges = state
        unused_edges = edges.copy()

        # List edges which do not belong to any linear sequence.
        for seq in seqs:
            for i in range(1, len(seq)):
                unused_edges.remove(self._normalize_edge((seq[i - 1], seq[i])))

        edge = self._choose_random_edge(unused_edges)
        if not edge:
            return seqs, edges

        return (
            self._force_edge_active(seqs,
                                    edge,
                                    lambda: bool(self._rand.randint(2))),
            edges)

Response: Move which forces a random edge to appear on some sequence.


Instruction:
How would you explain what the following Python 3 function does
def _force_edge_active(self, seqs: List[List[GridQubit]], edge: EDGE,
                           sample_bool: Callable[[], bool]
                           ) -> List[List[GridQubit]]:
        """Move which forces given edge to appear on some sequence.

        Args:
          seqs: List of linear sequences covering chip.
          edge: Edge to be activated.
          sample_bool: Callable returning random bool.

        Returns:
          New list of linear sequences with given edge on some of the
          sequences.
        """

        n0, n1 = edge

        # Make a copy of original sequences.
        seqs = list(seqs)

        # Localize edge nodes within current solution.
        i0, j0 = index_2d(seqs, n0)
        i1, j1 = index_2d(seqs, n1)
        s0 = seqs[i0]
        s1 = seqs[i1]

        # Handle case when nodes belong to different linear sequences,
        # separately from the case where they belong to a single linear
        # sequence.
        if i0 != i1:

            # Split s0 and s1 in two parts: s0 in parts before n0, and after n0
            # (without n0); s1 in parts before n1, and after n1 (without n1).
            part = [s0[:j0], s0[j0 + 1:]], [s1[:j1], s1[j1 + 1:]]

            # Remove both sequences from original list.
            del seqs[max(i0, i1)]
            del seqs[min(i0, i1)]

            # Choose part of s0 which will be attached to n0, and make sure it
            # can be attached in the end.
            c0 = 0 if not part[0][1] else 1 if not part[0][
                0] else sample_bool()
            if c0:
                part[0][c0].reverse()

            # Choose part of s1 which will be attached to n1, and make sure it
            # can be attached in the beginning.
            c1 = 0 if not part[1][1] else 1 if not part[1][
                0] else sample_bool()
            if not c1:
                part[1][c1].reverse()

            # Append newly formed sequence from the chosen parts and new edge.
            seqs.append(part[0][c0] + [n0, n1] + part[1][c1])

            # Append the left-overs to the solution, if they exist.
            other = [1, 0]
            seqs.append(part[0][other[c0]])
            seqs.append(part[1][other[c1]])
        else:
            # Swap nodes so that n0 always preceeds n1 on sequence.
            if j0 > j1:
                j0, j1 = j1, j0
                n0, n1 = n1, n0

            # Split sequence in three parts, without nodes n0 an n1 present:
            # head might end with n0, inner might begin with n0 and end with
            # n1, tail might begin with n1.
            head = s0[:j0]
            inner = s0[j0 + 1:j1]
            tail = s0[j1 + 1:]

            # Remove original sequence from sequences list.
            del seqs[i0]

            # Either append edge to inner section, or attach it between head
            # and tail.
            if sample_bool():
                # Append edge either before or after inner section.
                if sample_bool():
                    seqs.append(inner + [n1, n0] + head[::-1])
                    seqs.append(tail)
                else:
                    seqs.append(tail[::-1] + [n1, n0] + inner)
                    seqs.append(head)
            else:
                # Form a new sequence from head, tail, and new edge.
                seqs.append(head + [n0, n1] + tail)
                seqs.append(inner)

        return [e for e in seqs if e]

Response: Move which forces given edge to appear on some of the linear sequences.