Instruction:
Can you implement a function in Python 3 that
returns a unitary matrix describing the given value.

Response:
def unitary(val: Any,
            default: TDefault = RaiseTypeErrorIfNotProvided
            ) -> Union[np.ndarray, TDefault]:
    """Returns a unitary matrix describing the given value.

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

    Returns:
        If `val` has a _unitary_ method and its result is not NotImplemented,
        that result is returned. Otherwise, if `val` is a cirq.Gate or
        cirq.Operation, decomposition will be attempted and the resulting
        unitary is returned if unitaries exist for all operations of the
        decompostion. If the result is still NotImplemented and a default value
        was specified, the default value is returned.

    Raises:
        TypeError: `val` doesn't have a _unitary_ method (or that method
            returned NotImplemented) and also no default value was specified.
    """
    from cirq import Gate, Operation  # HACK: Avoids circular dependencies.

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

    # Fallback to decomposition for gates and operations
    if isinstance(val, (Gate, Operation)):
        decomposed_unitary = _decompose_and_get_unitary(val)
        if decomposed_unitary is not None:
            return decomposed_unitary

    if default is not RaiseTypeErrorIfNotProvided:
        return default

    if getter is None:
        raise TypeError("object of type '{}' "
                        "has no _unitary_ method.".format(type(val)))
    raise TypeError("object of type '{}' does have a _unitary_ method, "
                    "but it returned NotImplemented.".format(type(val)))


Instruction:
Make a summary of the following Python 3 code
def has_unitary(val: Any) -> bool:
    from cirq.protocols.decompose import (decompose_once,
                                          decompose_once_with_qubits)
    # HACK: Avoids circular dependencies.
    from cirq import Gate, Operation, LineQubit

    getter = getattr(val, '_has_unitary_', None)
    result = NotImplemented if getter is None else getter()
    if result is not NotImplemented:
        return result

    # Fallback to explicit _unitary_
    unitary_getter = getattr(val, '_unitary_', None)
    if unitary_getter is not None and unitary_getter() is not NotImplemented:
        return True

    # Fallback to decomposition for gates and operations
    if isinstance(val, Gate):
        # Since gates don't know about qubits, we need to create some
        decomposed_val = decompose_once_with_qubits(val,
            LineQubit.range(val.num_qubits()),
            default=None)
        if decomposed_val is not None:
            return all(has_unitary(v) for v in decomposed_val)
    elif isinstance(val, Operation):
        decomposed_val = decompose_once(val, default=None)
        if decomposed_val is not None:
            return all(has_unitary(v) for v in decomposed_val)

    # Finally, fallback to full unitary method, including decomposition
    return unitary(val, None) is not None

Response: Returns whether the value has a unitary matrix representation.


Instruction:
Can you generate the documentation for the following Python 3 function
def _decompose_and_get_unitary(val: Union['cirq.Operation', 'cirq.Gate']
                               ) -> np.ndarray:
    """Try to decompose a cirq.Operation or cirq.Gate, and return its unitary
    if it exists.

    Returns:
        If `val` can be decomposed into unitaries, calculate the resulting
        unitary and return it. If it doesn't exist, None is returned.
    """
    from cirq.protocols.apply_unitary import apply_unitary, ApplyUnitaryArgs
    from cirq.protocols.decompose import (decompose_once,
                                          decompose_once_with_qubits)
    from cirq import Gate, LineQubit, Operation

    if isinstance(val, Operation):
        qubits = val.qubits
        decomposed_val = decompose_once(val, default=None)
    elif isinstance(val, Gate):
        # Since gates don't know about qubits, we need to create some
        qubits = tuple(LineQubit.range(val.num_qubits()))
        decomposed_val = decompose_once_with_qubits(val,
                                                    qubits,
                                                    default=None)

    if decomposed_val is not None:
        # Calculate the resulting unitary (if it exists)
        n = len(qubits)
        state = np.eye(1 << n, dtype=np.complex128)
        state.shape = (2,) * (2 * n)
        buffer = np.zeros(state.shape, dtype=np.complex128)
        qubit_map = {q: i for i, q in enumerate(qubits)}
        result = state
        for op in decomposed_val:
            indices = [qubit_map[q] for q in op.qubits]
            result = apply_unitary(
                unitary_value=op,
                args=ApplyUnitaryArgs(state, buffer, indices),
                default=None)
            if result is None:
                return None
            if result is buffer:
                buffer = state
            state = result
        if result is not None:
            return result.reshape((1 << n, 1 << n))

Response: Decomposes a cirq. Operation or cirq. Gate and returns its unitary if it exists.


Instruction:
Write a Python 3 script for
checking if the user has write permission.

Response:
def check_collaborator_has_write(repo: GithubRepository, username: str
                                 ) -> Optional[CannotAutomergeError]:
    """
    References:
        https://developer.github.com/v3/issues/events/#list-events-for-an-issue
    """
    url = ("https://api.github.com/repos/{}/{}/collaborators/{}/permission"
           "?access_token={}".format(repo.organization,
                                     repo.name,
                                     username,
                                     repo.access_token))

    response = requests.get(url)

    if response.status_code != 200:
        raise RuntimeError(
            'Collaborator check failed. Code: {}. Content: {}.'.format(
                response.status_code, response.content))

    payload = json.JSONDecoder().decode(response.content.decode())
    if payload['permission'] not in ['admin', 'write']:
        return CannotAutomergeError(
            'Only collaborators with write permission can use automerge.')

    return None


Instruction:
Can you tell what is the following Python 3 function doing
def check_auto_merge_labeler(repo: GithubRepository, pull_id: int
                             ) -> Optional[CannotAutomergeError]:
    """
    References:
        https://developer.github.com/v3/issues/events/#list-events-for-an-issue
    """
    url = ("https://api.github.com/repos/{}/{}/issues/{}/events"
           "?access_token={}".format(repo.organization,
                                     repo.name,
                                     pull_id,
                                     repo.access_token))

    response = requests.get(url)

    if response.status_code != 200:
        raise RuntimeError(
            'Event check failed. Code: {}. Content: {}.'.format(
                response.status_code, response.content))

    payload = json.JSONDecoder().decode(response.content.decode())
    relevant = [event
                for event in payload
                if event['event'] == 'labeled' and
                event['label']['name'] in AUTO_MERGE_LABELS]
    if not relevant:
        return CannotAutomergeError('"automerge" label was never added.')

    return check_collaborator_has_write(repo, relevant[-1]['actor']['login'])

Response: Check if a labeler is relevant to a new issue.


Instruction:
Explain what the following Python 3 code does
def add_comment(repo: GithubRepository, pull_id: int, text: str) -> None:
    url = ("https://api.github.com/repos/{}/{}/issues/{}/comments"
           "?access_token={}".format(repo.organization,
                                     repo.name,
                                     pull_id,
                                     repo.access_token))
    data = {
        'body': text
    }
    response = requests.post(url, json=data)

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

Response: Adds a comment to a node.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def edit_comment(repo: GithubRepository, text: str, comment_id: int) -> None:
    url = ("https://api.github.com/repos/{}/{}/issues/comments/{}"
           "?access_token={}".format(repo.organization,
                                     repo.name,
                                     comment_id,
                                     repo.access_token))
    data = {
        'body': text
    }
    response = requests.patch(url, json=data)

    if response.status_code != 200:
        raise RuntimeError('Edit comment failed. Code: {}. Content: {}.'.format(
            response.status_code, response.content))

Response: Edit a comment in a node.


Instruction:
Explain what the following Python 3 code does
def classify_pr_synced_state(pr: PullRequestDetails) -> Optional[bool]:
    state = pr.payload['mergeable_state'].lower()
    classification = {
        'behind': False,
        'clean': True,
    }
    return classification.get(state, None)

Response: Classifies the state of a single pull request.


Instruction:
Can you write a function in Python 3 where it
gets the status of a pull request.

Response:
def get_pr_review_status(pr: PullRequestDetails) -> Any:
    """
    References:
        https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request
    """
    url = ("https://api.github.com/repos/{}/{}/pulls/{}/reviews"
           "?access_token={}".format(pr.repo.organization,
                                     pr.repo.name,
                                     pr.pull_id,
                                     pr.repo.access_token))
    response = requests.get(url)

    if response.status_code != 200:
        raise RuntimeError(
            'Get review failed. Code: {}. Content: {}.'.format(
                response.status_code, response.content))

    return json.JSONDecoder().decode(response.content.decode())


Instruction:
Write a Python 3 script for
getting check - runs for a specific pull request.

Response:
def get_pr_checks(pr: PullRequestDetails) -> Dict[str, Any]:
    """
    References:
        https://developer.github.com/v3/checks/runs/#list-check-runs-for-a-specific-ref
    """
    url = ("https://api.github.com/repos/{}/{}/commits/{}/check-runs"
           "?access_token={}".format(pr.repo.organization,
                                     pr.repo.name,
                                     pr.branch_sha,
                                     pr.repo.access_token))
    response = requests.get(
        url,
        headers={'Accept': 'application/vnd.github.antiope-preview+json'})

    if response.status_code != 200:
        raise RuntimeError(
            'Get check-runs failed. Code: {}. Content: {}.'.format(
                response.status_code, response.content))

    return json.JSONDecoder().decode(response.content.decode())


Instruction:
Can you generate the documentation for the following Python 3 function
def get_repo_ref(repo: GithubRepository, ref: str) -> Dict[str, Any]:

    url = ("https://api.github.com/repos/{}/{}/git/refs/{}"
           "?access_token={}".format(repo.organization,
                                     repo.name,
                                     ref,
                                     repo.access_token))
    response = requests.get(url)
    if response.status_code != 200:
        raise RuntimeError(
            'Refs get failed. Code: {}. Content: {}.'.format(
                response.status_code, response.content))
    payload = json.JSONDecoder().decode(response.content.decode())
    return payload

Response: Get a single reference from a repository.


Instruction:
Write a Python 3 function that can
list the comments on an issue on a GitHub repository.

Response:
def list_pr_comments(repo: GithubRepository, pull_id: int
                     ) -> List[Dict[str, Any]]:
    """
    References:
        https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue
    """
    url = ("https://api.github.com/repos/{}/{}/issues/{}/comments"
           "?access_token={}".format(repo.organization,
                                     repo.name,
                                     pull_id,
                                     repo.access_token))
    response = requests.get(url)
    if response.status_code != 200:
        raise RuntimeError(
            'Comments get failed. Code: {}. Content: {}.'.format(
                response.status_code, response.content))
    payload = json.JSONDecoder().decode(response.content.decode())
    return payload


Instruction:
Create a Python 3 function for
deleting a single comment from a branch.

Response:
def delete_comment(repo: GithubRepository, comment_id: int) -> None:
    """
    References:
        https://developer.github.com/v3/issues/comments/#delete-a-comment
    """
    url = ("https://api.github.com/repos/{}/{}/issues/comments/{}"
           "?access_token={}".format(repo.organization,
                                     repo.name,
                                     comment_id,
                                     repo.access_token))
    response = requests.delete(url)
    if response.status_code != 204:
        raise RuntimeError(
            'Comment delete failed. Code: {}. Content: {}.'.format(
                response.status_code, response.content))


Instruction:
Write a Python 3 function that can
try to merge the branch with the master branch.

Response:
def attempt_sync_with_master(pr: PullRequestDetails
                             ) -> Union[bool, CannotAutomergeError]:
    """
    References:
        https://developer.github.com/v3/repos/merging/#perform-a-merge
    """
    master_sha = get_master_sha(pr.repo)
    remote = pr.remote_repo
    url = ("https://api.github.com/repos/{}/{}/merges"
           "?access_token={}".format(remote.organization,
                                     remote.name,
                                     remote.access_token))
    data = {
        'base': pr.branch_name,
        'head': master_sha,
        'commit_message': 'Update branch (automerge)'.format(pr.branch_name)
    }
    response = requests.post(url, json=data)

    if response.status_code == 201:
        # Merge succeeded.
        log('Synced #{} ({!r}) with master.'.format(pr.pull_id, pr.title))
        return True

    if response.status_code == 204:
        # Already merged.
        return False

    if response.status_code == 409:
        # Merge conflict.
        return CannotAutomergeError("There's a merge conflict.")

    if response.status_code == 403:
        # Permission denied.
        return CannotAutomergeError(
            "Spurious failure. Github API requires me to be an admin on the "
            "fork repository to merge master into the PR branch. Hit "
            "'Update Branch' for me before trying again.")

    raise RuntimeError('Sync with master failed for unknown reason. '
                       'Code: {}. Content: {}.'.format(response.status_code,
                                                       response.content))


Instruction:
Write a Python 3 function for
attempting to merge a single branch into a single branch.

Response:
def attempt_squash_merge(pr: PullRequestDetails
                         ) -> Union[bool, CannotAutomergeError]:
    """
    References:
        https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
    """
    url = ("https://api.github.com/repos/{}/{}/pulls/{}/merge"
           "?access_token={}".format(pr.repo.organization,
                                     pr.repo.name,
                                     pr.pull_id,
                                     pr.repo.access_token))
    data = {
        'commit_title': '{} (#{})'.format(pr.title, pr.pull_id),
        'commit_message': pr.body,
        'sha': pr.branch_sha,
        'merge_method': 'squash'
    }
    response = requests.put(url, json=data)

    if response.status_code == 200:
        # Merge succeeded.
        log('Merged PR#{} ({!r}):\n{}\n'.format(
            pr.pull_id,
            pr.title,
            indent(pr.body)))
        return True

    if response.status_code == 405:
        return CannotAutomergeError("Pull Request is not mergeable.")

    if response.status_code == 409:
        # Need to sync.
        return False

    raise RuntimeError('Merge failed. Code: {}. Content: {}.'.format(
        response.status_code, response.content))


Instruction:
Write a Python 3 script to
delete a single branch from the remote repository.

Response:
def auto_delete_pr_branch(pr: PullRequestDetails) -> bool:
    """
    References:
        https://developer.github.com/v3/git/refs/#delete-a-reference
    """

    open_pulls = list_open_pull_requests(pr.repo, base_branch=pr.branch_name)
    if any(open_pulls):
        log('Not deleting branch {!r}. It is used elsewhere.'.format(
            pr.branch_name))
        return False

    remote = pr.remote_repo
    if pr.is_on_fork():
        log('Not deleting branch {!r}. It belongs to a fork ({}/{}).'.format(
            pr.branch_name,
            pr.remote_repo.organization,
            pr.remote_repo.name))
        return False

    url = ("https://api.github.com/repos/{}/{}/git/refs/heads/{}"
           "?access_token={}".format(remote.organization,
                                     remote.name,
                                     pr.branch_name,
                                     remote.access_token))
    response = requests.delete(url)

    if response.status_code == 204:
        # Delete succeeded.
        log('Deleted branch {!r}.'.format(pr.branch_name))
        return True

    log('Delete failed. Code: {}. Content: {}.'.format(
        response.status_code, response.content))
    return False


Instruction:
Write a Python 3 function for
adding labels to an issue.

Response:
def add_labels_to_pr(repo: GithubRepository,
                     pull_id: int,
                     *labels: str,
                     override_token: str = None) -> None:
    """
    References:
        https://developer.github.com/v3/issues/labels/#add-labels-to-an-issue
    """
    url = ("https://api.github.com/repos/{}/{}/issues/{}/labels"
           "?access_token={}".format(repo.organization,
                                     repo.name,
                                     pull_id,
                                     override_token or repo.access_token))
    response = requests.post(url, json=list(labels))

    if response.status_code != 200:
        raise RuntimeError(
            'Add labels failed. Code: {}. Content: {}.'.format(
                response.status_code, response.content))


Instruction:
Here you have a function in Python 3, explain what it does
def remove_label_from_pr(repo: GithubRepository,
                         pull_id: int,
                         label: str) -> bool:
    """
    References:
        https://developer.github.com/v3/issues/labels/#remove-a-label-from-an-issue
    """
    url = ("https://api.github.com/repos/{}/{}/issues/{}/labels/{}"
           "?access_token={}".format(repo.organization,
                                     repo.name,
                                     pull_id,
                                     label,
                                     repo.access_token))
    response = requests.delete(url)

    if response.status_code == 404:
        payload = json.JSONDecoder().decode(response.content.decode())
        if payload['message'] == 'Label does not exist':
            return False

    if response.status_code == 200:
        # Removed the label.
        return True

    raise RuntimeError(
        'Label remove failed. Code: {}. Content: {}.'.format(
            response.status_code, response.content))

Response: Removes a label from a pull request.


Instruction:
Given the following Python 3 function, write the documentation
def drop_temporary(pr: PullRequestDetails,
                   problem: Optional[CannotAutomergeError],
                   prev_seen_times: Dict[int, datetime.datetime],
                   next_seen_times: Dict[int, datetime.datetime],
                   ) -> Optional[CannotAutomergeError]:
    """Filters out problems that may be temporary."""

    if problem is not None and problem.may_be_temporary:
        since = prev_seen_times.get(pr.pull_id, datetime.datetime.utcnow())
        if is_recent_date(since):
            next_seen_times[pr.pull_id] = since
            return None

    return problem

Response: Filter out problems that may be temporary.


Instruction:
Make a summary of the following Python 3 code
def from_github(repo: GithubRepository,
                    pull_id: int) -> 'PullRequestDetails':
        """
        References:
            https://developer.github.com/v3/pulls/#get-a-single-pull-request
        """
        url = ("https://api.github.com/repos/{}/{}/pulls/{}"
               "?access_token={}".format(repo.organization,
                                         repo.name,
                                         pull_id,
                                         repo.access_token))

        response = requests.get(url)

        if response.status_code != 200:
            raise RuntimeError(
                'Pull check failed. Code: {}. Content: {}.'.format(
                    response.status_code, response.content))

        payload = json.JSONDecoder().decode(response.content.decode())
        return PullRequestDetails(payload, repo)

Response: Returns a PullRequestDetails object from a github repository and pull_id.


Instruction:
Write a Python 3 function that can
return a Mølmer–Sørensen gate rotating by the desired amount.

Response:
def MS(rads: float) -> ops.XXPowGate:
    """The Mølmer–Sørensen gate, a native two-qubit operation in ion traps.

    A rotation around the XX axis in the two-qubit bloch sphere.

    The gate implements the following unitary:

        exp(-i t XX) = [ cos(t)   0        0       -isin(t)]
                       [ 0        cos(t)  -isin(t)  0      ]
                       [ 0       -isin(t)  cos(t)   0      ]
                       [-isin(t)  0        0        cos(t) ]

    Args:
        rads: The rotation angle in radians.

    Returns:
        Mølmer–Sørensen gate rotating by the desired amount.
    """
    return ops.XXPowGate(exponent=rads*2/np.pi, global_shift=-0.5)


Instruction:
Create a Python 3 function to
calculate probability and draws if solution should be accepted.

Response:
def _accept(random_sample: float, cost_diff: float,
            temp: float) -> Tuple[bool, float]:
    """Calculates probability and draws if solution should be accepted.

    Based on exp(-Delta*E/T) formula.

    Args:
        random_sample: Uniformly distributed random number in the range [0, 1).
        cost_diff: Cost difference between new and previous solutions.
        temp: Current temperature.

    Returns:
        Tuple of boolean and float, with boolean equal to True if solution is
        accepted, and False otherwise. The float value is acceptance
        probability.
    """
    exponent = -cost_diff / temp
    if exponent >= 0.0:
        return True, 1.0
    else:
        probability = math.exp(exponent)
    return probability > random_sample, probability


Instruction:
Can you create a Python 3 function that
minimizes the current annealing candidate.

Response:
def anneal_minimize(
        initial: T,
        cost_func: Callable[[T], float],
        move_func: Callable[[T], T],
        random_sample: Callable[[], float],
        temp_initial: float = 1.0e-2,
        temp_final: float = 1e-6,
        cooling_factor: float = 0.99,
        repeat: int = 100,
        trace_func: Callable[
            [T, float, float, float, bool], None] = None) -> T:
    """Minimize solution using Simulated Annealing meta-heuristic.

    Args:
        initial: Initial solution of type T to the problem.
        cost_func: Callable which takes current solution of type T, evaluates it
            and returns float with the cost estimate. The better solution is,
            the lower resulting value should be; negative values are allowed.
        move_func: Callable which takes current solution of type T and returns a
            new solution candidate of type T which is random iteration over
            input solution. The input solution, which is argument to this
            callback should not be mutated.
        random_sample: Callable which gives uniformly sampled random value from
            the [0, 1) interval on each call.
        temp_initial: Optional initial temperature for simulated annealing
            optimization. Scale of this value is cost_func-dependent.
        temp_final: Optional final temperature for simulated annealing
            optimization, where search should be stopped. Scale of this value is
            cost_func-dependent.
        cooling_factor: Optional factor to be applied to the current temperature
            and give the new temperature, this must be strictly greater than 0
            and strictly lower than 1.
        repeat: Optional number of iterations to perform at each given
            temperature.
        trace_func: Optional callback for tracing simulated annealing progress.
            This is going to be called at each algorithm step for the arguments:
            solution candidate (T), current temperature (float), candidate cost
            (float), probability of accepting candidate (float), and acceptance
            decision (boolean).

    Returns:
        The best solution found.

    Raises:
        ValueError: When supplied arguments are invalid.
    """

    if not 0.0 < cooling_factor < 1.0:
        raise ValueError("Cooling factor must be within (0, 1) range")

    temp = temp_initial
    sol = initial
    sol_cost = cost_func(initial)
    best = sol
    best_cost = sol_cost

    if trace_func:
        trace_func(sol, temp, sol_cost, 1.0, True)

    while temp > temp_final:
        for _ in range(0, repeat):
            # Find a new solution candidate and evaluate its cost.
            cand = move_func(sol)
            cand_cost = cost_func(cand)

            # Store the best solution, regardless if it is accepted or not.
            if best_cost > cand_cost:
                best = cand
                best_cost = cand_cost

            accepted, probability = _accept(random_sample(),
                                            cand_cost - sol_cost,
                                            temp)
            if accepted:
                sol = cand
                sol_cost = cand_cost

            if trace_func:
                trace_func(cand, temp, cand_cost, probability, accepted)

        temp *= cooling_factor

    return best


Instruction:
Explain what the following Python 3 code does
def op_gate_of_type(op: raw_types.Operation,
                    gate_type: Type[TV]) -> Optional[TV]:
    """Returns the gate of given type, if the op has that gate otherwise None.
    """
    if isinstance(op, GateOperation) and isinstance(op.gate, gate_type):
        return op.gate
    return None

Response: Returns the gate of given type if the op has that gate otherwise None.


Instruction:
Write a Python 3 function that can
take a sequence of qubit pairs and returns a sequence in which every pair is at distance two.

Response:
def qubit_pairs_to_qubit_order(
    qubit_pairs: Sequence[Sequence[ops.Qid]]
    ) -> List[ops.Qid]:
    """Takes a sequence of qubit pairs and returns a sequence in which every
    pair is at distance two.

    Specifically, given pairs (1a, 1b), (2a, 2b), etc. returns
    (1a, 2a, 1b, 2b, 3a, 4a, 3b, 4b, ...).
    """

    if set(len(qubit_pair) for qubit_pair in qubit_pairs) != set((2,)):
        raise ValueError(
            'set(len(qubit_pair) for qubit_pair in qubit_pairs) != '
            'set((2,))')
    n_pairs = len(qubit_pairs)
    qubits = [] # type: List[ops.Qid]
    for i in range(0, 2 * (n_pairs // 2), 2):
        qubits += [qubit_pairs[i][0], qubit_pairs[i + 1][0],
                   qubit_pairs[i][1], qubit_pairs[i + 1][1]]
    if n_pairs % 2:
        qubits += list(qubit_pairs[-1])
    return qubits


Instruction:
Make a summary of the following Python 3 code
def quartic_paired_acquaintance_strategy(
    qubit_pairs: Iterable[Tuple[ops.Qid, ops.Qid]]
    ) -> Tuple[circuits.Circuit, Sequence[ops.Qid]]:
    """Acquaintance strategy for pairs of pairs.

    Implements UpCCGSD ansatz from arXiv:1810.02327.
    """

    qubit_pairs = tuple(
            cast(Tuple[ops.Qid, ops.Qid], tuple(qubit_pair))
            for qubit_pair in qubit_pairs)
    qubits = qubit_pairs_to_qubit_order(qubit_pairs)
    n_qubits = len(qubits)
    swap_network = SwapNetworkGate((1,) * n_qubits, 2)(*qubits)
    strategy = circuits.Circuit.from_ops(swap_network,
            device=UnconstrainedAcquaintanceDevice)
    expose_acquaintance_gates(strategy)
    for i in reversed(range(0, n_qubits, 2)):
        moment = ops.Moment([acquaint(*qubits[j: j + 4])
                             for j in range(i % 4, n_qubits - 3, 4)])
        strategy.insert(2 * i, moment)
    return strategy, qubits

Response: Acquaintance strategy for pairs of pairs.


Instruction:
Can you tell what is the following Python 3 function doing
def circuit_diagram_info(val: Any,
                         args: Optional[CircuitDiagramInfoArgs] = None,
                         default=RaiseTypeErrorIfNotProvided):
    """Requests information on drawing an operation in a circuit diagram.

    Calls _circuit_diagram_info_ on `val`. If `val` doesn't have
    _circuit_diagram_info_, or it returns NotImplemented, that indicates that
    diagram information is not available.

    Args:
        val: The operation or gate that will need to be drawn.
        args: A CircuitDiagramInfoArgs describing the desired drawing style.
        default: A default result to return if the value doesn't have circuit
            diagram information. If not specified, a TypeError is raised
            instead.

    Returns:
        If `val` has no _circuit_diagram_info_ method or it returns
        NotImplemented, then `default` is returned (or a TypeError is
        raised if no `default` is specified).

        Otherwise, the value returned by _circuit_diagram_info_ is returned.

    Raises:
        TypeError:
            `val` doesn't have circuit diagram information and `default` was
            not specified.
    """

    # Attempt.
    if args is None:
        args = CircuitDiagramInfoArgs.UNINFORMED_DEFAULT
    getter = getattr(val, '_circuit_diagram_info_', None)
    result = NotImplemented if getter is None else getter(args)

    # Success?
    if isinstance(result, str):
        return CircuitDiagramInfo(wire_symbols=(result,))
    if isinstance(result, collections.Iterable):
        return CircuitDiagramInfo(wire_symbols=tuple(result))
    if result is not NotImplemented:
        return result

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

Response: Returns a CircuitDiagramInfo object that can be used to draw an operation in a circuit diagram.


Instruction:
Create a Python 3 function for
returning the Pauli expansion of val in the Pauli basis.

Response:
def pauli_expansion(
    val: Any,
    *,
    default: Union[value.LinearDict[str], TDefault]
        = RaiseTypeErrorIfNotProvided,
    atol: float = 1e-9
) -> Union[value.LinearDict[str], TDefault]:
    """Returns coefficients of the expansion of val in the Pauli basis.

    Args:
        val: The value whose Pauli expansion is to returned.
        default: Determines what happens when `val` does not have methods that
            allow Pauli expansion to be obtained (see below). If set, the value
            is returned in that case. Otherwise, TypeError is raised.
        atol: Ignore coefficients whose absolute value is smaller than this.

    Returns:
        If `val` has a _pauli_expansion_ method, then its result is returned.
        Otherwise, if `val` has a small unitary then that unitary is expanded
        in the Pauli basis and coefficients are returned. Otherwise, if default
        is set to None or other value then default is returned. Otherwise,
        TypeError is raised.

    Raises:
        TypeError if `val` has none of the methods necessary to obtain its Pauli
        expansion and no default value has been provided.
    """
    method = getattr(val, '_pauli_expansion_', None)
    expansion = NotImplemented if method is None else method()

    if expansion is not NotImplemented:
        return expansion.clean(atol=atol)

    matrix = unitary(val, default=None)
    if matrix is None:
        if default is RaiseTypeErrorIfNotProvided:
            raise TypeError('No Pauli expansion for object {} of type {}'
                    .format(val, type(val)))
        return default

    num_qubits = matrix.shape[0].bit_length() - 1
    basis = operator_spaces.kron_bases(operator_spaces.PAULI_BASIS,
                                       repeat=num_qubits)

    expansion = operator_spaces.expand_matrix_in_orthogonal_basis(matrix, basis)
    return expansion.clean(atol=atol)


Instruction:
Can you implement a function in Python 3 that
sees definition in `cirq.SimulatesSamples`.

Response:
def _run(self, circuit: circuits.Circuit,
             param_resolver: study.ParamResolver,
             repetitions: int) -> Dict[str, np.ndarray]:
        """See definition in `cirq.SimulatesSamples`."""
        param_resolver = param_resolver or study.ParamResolver({})
        resolved_circuit = protocols.resolve_parameters(circuit,
                                                        param_resolver)

        if circuit.are_all_measurements_terminal():
            return self._run_sweep_sample(resolved_circuit, repetitions)
        else:
            return self._run_sweep_repeat(resolved_circuit, repetitions)


Instruction:
Write a Python 3 function that can
return an iterator over the state of the simulation.

Response:
def _simulator_iterator(self, circuit: circuits.Circuit,
                            param_resolver: study.ParamResolver,
                            qubit_order: ops.QubitOrderOrList,
                            initial_state: Union[int, np.ndarray]) -> Iterator:
        """See definition in `cirq.SimulatesIntermediateState`.

        If the initial state is an int, the state is set to the computational
        basis state corresponding to this state. Otherwise  if the initial
        state is a np.ndarray it is the full initial state, either a pure state
        or the full density matrix.  If it is the pure state it must be the
        correct size, be normalized (an L2 norm of 1), and be safely castable
        to an appropriate dtype for the simulator.  If it is a mixed state
        it must be correctly sized and positive semidefinite with trace one.
        """
        param_resolver = param_resolver or study.ParamResolver({})
        resolved_circuit = protocols.resolve_parameters(circuit, param_resolver)
        actual_initial_state = 0 if initial_state is None else initial_state
        return self._base_iterator(resolved_circuit,
                                   qubit_order,
                                   actual_initial_state)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def compute_displays_sweep(
        self,
        program: Union[circuits.Circuit, schedules.Schedule],
        params: Optional[study.Sweepable] = None,
        qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
        initial_state: Union[int, np.ndarray] = 0,
    ) -> List[study.ComputeDisplaysResult]:
        """Computes displays in the supplied Circuit or Schedule.

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

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

        Returns:
            List of ComputeDisplaysResults for this run, one for each
            possible parameter resolver.
        """
        circuit = (program if isinstance(program, circuits.Circuit)
                   else program.to_circuit())
        param_resolvers = study.to_resolvers(params or study.ParamResolver({}))
        qubit_order = ops.QubitOrder.as_qubit_order(qubit_order)
        qubits = qubit_order.order_for(circuit.all_qubits())

        compute_displays_results = []  # type: List[study.ComputeDisplaysResult]
        for param_resolver in param_resolvers:
            display_values = {}  # type: Dict[Hashable, Any]

            # Compute the displays in the first Moment
            moment = circuit[0]
            matrix = density_matrix_utils.to_valid_density_matrix(
                initial_state, num_qubits=len(qubits), dtype=self._dtype)
            qubit_map = {q: i for i, q in enumerate(qubits)}
            _enter_moment_display_values_into_dictionary(
                display_values, moment, matrix, qubit_order, qubit_map)

            # Compute the displays in the rest of the Moments
            all_step_results = self.simulate_moment_steps(
                circuit,
                param_resolver,
                qubit_order,
                initial_state)
            for step_result, moment in zip(all_step_results, circuit[1:]):
                _enter_moment_display_values_into_dictionary(
                    display_values,
                    moment,
                    step_result.density_matrix(),
                    qubit_order,
                    step_result._qubit_map)

            compute_displays_results.append(study.ComputeDisplaysResult(
                params=param_resolver,
                display_values=display_values))

        return compute_displays_results

Response: Computes the displays in the supplied circuit or schedule.


Instruction:
Implement a Python 3 function for
setting the density matrix to a new density matrix.

Response:
def set_density_matrix(self, density_matrix_repr: Union[int, np.ndarray]):
        """Set the density matrix to a new density matrix.

        Args:
            density_matrix_repr: If this is an int, the density matrix is set to
            the computational basis state corresponding to this state. Otherwise
            if this is a np.ndarray it is the full state, either a pure state
            or the full density matrix.  If it is the pure state it must be the
            correct size, be normalized (an L2 norm of 1), and be safely
            castable to an appropriate dtype for the simulator.  If it is a
            mixed state it must be correctly sized and positive semidefinite
            with trace one.
        """
        density_matrix = density_matrix_utils.to_valid_density_matrix(
            density_matrix_repr, len(self._qubit_map), self._dtype)
        density_matrix = np.reshape(density_matrix,
                                    self.simulator_state().density_matrix.shape)
        np.copyto(dst=self.simulator_state().density_matrix, src=density_matrix)


Instruction:
Here you have a function in Python 3, explain what it does
def density_matrix(self):
        size = 2 ** len(self._qubit_map)
        return np.reshape(self._density_matrix, (size, size))

Response: Returns the density matrix at this step in the simulation.


Instruction:
Create a Python 3 function for
creating tensor product of bases.

Response:
def kron_bases(*bases: Dict[str, np.ndarray],
               repeat: int = 1) -> Dict[str, np.ndarray]:
    """Creates tensor product of bases."""
    product_basis = {'': 1}
    for basis in bases * repeat:
        product_basis = {
            name1 + name2: np.kron(matrix1, matrix2)
            for name1, matrix1 in product_basis.items()
            for name2, matrix2 in basis.items()
        }
    return product_basis


Instruction:
Implement a Python 3 function for
computing Hilbert - Schmidt inner product of two matrices. Linear in second argument.

Response:
def hilbert_schmidt_inner_product(m1: np.ndarray, m2: np.ndarray) -> complex:
    """Computes Hilbert-Schmidt inner product of two matrices.

    Linear in second argument.
    """
    return np.einsum('ij,ij', m1.conj(), m2)


Instruction:
Here you have a function in Python 3, explain what it does
def expand_matrix_in_orthogonal_basis(
        m: np.ndarray,
        basis: Dict[str, np.ndarray],
) -> value.LinearDict[str]:
    """Computes coefficients of expansion of m in basis.

    We require that basis be orthogonal w.r.t. the Hilbert-Schmidt inner
    product. We do not require that basis be orthonormal. Note that Pauli
    basis (I, X, Y, Z) is orthogonal, but not orthonormal.
    """
    return value.LinearDict({
        name: (hilbert_schmidt_inner_product(b, m) /
               hilbert_schmidt_inner_product(b, b))
        for name, b in basis.items()
    })

Response: Computes coefficients of expansion of m in basis.


Instruction:
Write a Python 3 function for
computing linear combination of basis vectors with given coefficients.

Response:
def matrix_from_basis_coefficients(expansion: value.LinearDict[str],
                                   basis: Dict[str, np.ndarray]) -> np.ndarray:
    """Computes linear combination of basis vectors with given coefficients."""
    some_element = next(iter(basis.values()))
    result = np.zeros_like(some_element, dtype=np.complex128)
    for name, coefficient in expansion.items():
        result += coefficient * basis[name]
    return result


Instruction:
Can you generate the documentation for the following Python 3 function
def converted_gate_set(circuit: circuits.Circuit,
                       no_clifford_gates: bool = False,
                       atol: float = 1e-8,
                       ) -> circuits.Circuit:
    """Returns a new, equivalent circuit using the gate set
    {SingleQubitCliffordGate,
    CZ/PauliInteractionGate, PauliStringPhasor}.
    """
    conv_circuit = circuits.Circuit(circuit)
    optimizers.ConvertToCzAndSingleGates().optimize_circuit(conv_circuit)
    optimizers.MergeSingleQubitGates().optimize_circuit(conv_circuit)
    ConvertToPauliStringPhasors(ignore_failures=True,
                                keep_clifford=not no_clifford_gates,
                                atol=atol,
                                ).optimize_circuit(conv_circuit)
    optimizers.DropEmptyMoments().optimize_circuit(conv_circuit)
    return conv_circuit

Response:
Converts a circuit using the gate set
    CZ and PauliStringPhasor.


Instruction:
Can you implement a function in Python 3 that
returns a new circuit with optimized operations applied to the given xmon gate set.

Response:
def optimized_for_xmon(
        circuit: circuits.Circuit,
        new_device: Optional[xmon_device.XmonDevice] = None,
        qubit_map: Callable[[ops.Qid], devices.GridQubit] =
            lambda e: cast(devices.GridQubit, e),
        allow_partial_czs: bool = False,
) -> circuits.Circuit:
    """Optimizes a circuit with XmonDevice in mind.

    Starts by converting the circuit's operations to the xmon gate set, then
    begins merging interactions and rotations, ejecting pi-rotations and phasing
    operations, dropping unnecessary operations, and pushing operations earlier.

    Args:
        circuit: The circuit to optimize.
        new_device: The device the optimized circuit should be targeted at. If
            set to None, the circuit's current device is used.
        qubit_map: Transforms the qubits (e.g. so that they are GridQubits).
        allow_partial_czs: If true, the optimized circuit may contain partial CZ
            gates.  Otherwise all partial CZ gates will be converted to full CZ
            gates.  At worst, two CZ gates will be put in place of each partial
            CZ from the input.

    Returns:
        The optimized circuit.
    """
    copy = circuit.copy()
    opts = _OPTIMIZERS_PART_CZ if allow_partial_czs else _OPTIMIZERS
    for optimizer in opts:
        optimizer(copy)

    return circuits.Circuit.from_ops(
        (op.transform_qubits(qubit_map) for op in copy.all_operations()),
        strategy=circuits.InsertStrategy.EARLIEST,
        device=new_device or copy.device)


Instruction:
Implement a Python 3 function for
applying a channel effect to the target tensor.

Response:
def apply_channel(val: Any,
        args: ApplyChannelArgs,
        default: TDefault = RaiseTypeErrorIfNotProvided
) -> Union[np.ndarray, TDefault]:
    """High performance evolution under a channel evolution.

    If `val` defines an `_apply_channel_` method, that method will be
    used to apply `val`'s channel effect to the target tensor. Otherwise, if
    `val` defines an `_apply_unitary_` method, that method will be used to
    apply `val`s channel effect to the target tensor.  Otherwise, if `val`
    returns a non-default channel with `cirq.channel`, that channel will be
    applied using a generic method.  If none of these cases apply, an
    exception is raised or the specified default value is returned.

    Args:
        val: The value with a channel to apply to the target.
        args: A mutable `cirq.ApplyChannelArgs` object describing the target
            tensor, available workspace, and left and right axes to operate on.
            The attributes of this object will be mutated as part of computing
            the result.
        default: What should be returned if `val` doesn't have a channel. If
            not specified, a TypeError is raised instead of returning a default
            value.

    Returns:
        If the receiving object is not able to apply a channel,
        the specified default value is returned (or a TypeError is raised). If
        this occurs, then `target_tensor` should not have been mutated.

        If the receiving object was able to work inline, directly
        mutating `target_tensor` it will return `target_tensor`. The caller is
        responsible for checking if the result is `target_tensor`.

        If the receiving object wrote its output over `out_buffer`, the
        result will be `out_buffer`. The caller is responsible for
        checking if the result is `out_buffer` (and e.g. swapping
        the buffer for the target tensor before the next call).

        Note that it is an error for the return object to be either of the
        auxiliary buffers, and the method will raise an AssertionError if
        this contract is violated.

        The receiving object may also write its output over a new buffer
        that it created, in which case that new array is returned.

    Raises:
        TypeError: `val` doesn't have a channel and `default` wasn't specified.
        AssertionError: if the
    """
    # Check if the specialized method is present.
    func = getattr(val, '_apply_channel_', None)
    if func is not None:
        result = func(args)
        if result is not NotImplemented and result is not None:
            def err_str(buf_num_str):
                return (
                    "Object of type '{}' returned a result object equal to "
                    "auxiliary_buffer{}. This type violates the contract "
                    "that appears in apply_unitary's documentation.".format(
                        type(val), buf_num_str))
            assert result is not args.auxiliary_buffer0, err_str('0')
            assert result is not args.auxiliary_buffer1, err_str('1')
            return result

    # Possibly use `apply_unitary`.
    result = _apply_unitary(val, args)
    if result is not None:
        return result

    # Fallback to using the object's `_channel_` matrices.
    krauss = channel(val, None)
    if krauss is not None:
        return _apply_krauss(krauss, args)

    # Don't know how to apply channel. Fallback to specified default behavior.
    if default is not RaiseTypeErrorIfNotProvided:
        return default
    raise TypeError(
            "object of type '{}' has no _apply_channel_, _apply_unitary_, "
            "_unitary_, or _channel_ methods (or they returned None or "
            "NotImplemented).".format(type(val)))


Instruction:
How would you explain what the following Python 3 function does
def _apply_unitary(val: Any, args: 'ApplyChannelArgs') -> Optional[np.ndarray]:
    left_args = ApplyUnitaryArgs(target_tensor=args.target_tensor,
                                 available_buffer=args.auxiliary_buffer0,
                                 axes=args.left_axes)
    left_result = apply_unitary(val, left_args, None)
    if left_result is None:
        return None
    right_args = ApplyUnitaryArgs(
            target_tensor=np.conjugate(left_result),
            available_buffer=args.out_buffer,
            axes=args.right_axes)
    right_result = apply_unitary(val, right_args)
    np.conjugate(right_result, out=right_result)
    return right_result

Response: Attempt to use apply_unitary and return the result.


Instruction:
Can you generate the documentation for the following Python 3 function
def _apply_krauss(krauss: Union[Tuple[np.ndarray], Sequence[Any]],
        args: 'ApplyChannelArgs') -> np.ndarray:
    """Directly apply the kraus operators to the target tensor."""
    # Initialize output.
    args.out_buffer[:] = 0
    # Stash initial state into buffer0.
    np.copyto(dst=args.auxiliary_buffer0, src=args.target_tensor)

    # Special case for single-qubit operations.
    if krauss[0].shape == (2, 2):
        return _apply_krauss_single_qubit(krauss, args)
    # Fallback to np.einsum for the general case.
    return _apply_krauss_multi_qubit(krauss, args)

Response: Directly apply the kraus operators to the target tensor.


Instruction:
Can you implement a function in Python 3 that
uses slicing to apply single qubit channel.

Response:
def _apply_krauss_single_qubit(krauss: Union[Tuple[Any], Sequence[Any]],
        args: 'ApplyChannelArgs') -> np.ndarray:
    """Use slicing to apply single qubit channel."""
    zero_left = linalg.slice_for_qubits_equal_to(args.left_axes, 0)
    one_left = linalg.slice_for_qubits_equal_to(args.left_axes, 1)
    zero_right = linalg.slice_for_qubits_equal_to(args.right_axes, 0)
    one_right = linalg.slice_for_qubits_equal_to(args.right_axes, 1)
    for krauss_op in krauss:
        np.copyto(dst=args.target_tensor,
                  src=args.auxiliary_buffer0)
        linalg.apply_matrix_to_slices(
                args.target_tensor,
                krauss_op,
                [zero_left, one_left],
                out=args.auxiliary_buffer1)
        # No need to transpose as we are acting on the tensor
        # representation of matrix, so transpose is done for us.
        linalg.apply_matrix_to_slices(
                args.auxiliary_buffer1,
                np.conjugate(krauss_op),
                [zero_right, one_right],
                out=args.target_tensor)
        args.out_buffer += args.target_tensor
    return args.out_buffer


Instruction:
Write a Python 3 script for
using numpy s einsum to apply a multi - qubit channel.

Response:
def _apply_krauss_multi_qubit(krauss: Union[Tuple[Any], Sequence[Any]],
        args: 'ApplyChannelArgs') -> np.ndarray:
    """Use numpy's einsum to apply a multi-qubit channel."""
    for krauss_op in krauss:
        np.copyto(dst=args.target_tensor, src=args.auxiliary_buffer0)
        krauss_tensor = np.reshape(
                krauss_op.astype(args.target_tensor.dtype),
                (2,) * len(args.left_axes) * 2)
        linalg.targeted_left_multiply(
                krauss_tensor,
                args.target_tensor,
                args.left_axes,
                out=args.auxiliary_buffer1)
        # No need to transpose as we are acting on the tensor
        # representation of matrix, so transpose is done for us.
        linalg.targeted_left_multiply(
                np.conjugate(krauss_tensor),
                args.auxiliary_buffer1,
                args.right_axes,
                out=args.target_tensor)
        args.out_buffer += args.target_tensor
    return args.out_buffer


Instruction:
How would you code a function in Python 3 to
convert any circuit into two circuits where the left and right gates are equivalent to the given circuit.

Response:
def convert_and_separate_circuit(circuit: circuits.Circuit,
                                 leave_cliffords: bool = True,
                                 atol: float = 1e-8,
                                 ) -> Tuple[circuits.Circuit, circuits.Circuit]:
    """Converts any circuit into two circuits where (circuit_left+circuit_right)
    is equivalent to the given circuit.

    Args:
        circuit: Any Circuit that cirq.google.optimized_for_xmon() supports.
            All gates should either provide a decomposition or have a known one
            or two qubit unitary matrix.

    Returns:
        (circuit_left, circuit_right)

        circuit_left contains only PauliStringPhasor operations.

        circuit_right is a Clifford circuit which contains only
        SingleQubitCliffordGate and PauliInteractionGate gates.
        It also contains MeasurementGates if the
        given circuit contains measurements.
    """
    circuit = converted_gate_set(circuit,
                                 no_clifford_gates=not leave_cliffords,
                                 atol=atol)
    return pauli_string_half(circuit), regular_half(circuit)


Instruction:
Explain what the following Python 3 code does
def regular_half(circuit: circuits.Circuit) -> circuits.Circuit:
    return circuits.Circuit(
        ops.Moment(op
                   for op in moment.operations
                   if not isinstance(op, ops.PauliStringPhasor))
        for moment in circuit)

Response: Return only the Clifford part of a circuit.


Instruction:
How would you code a function in Python 3 to
return only the non - Clifford part of a circuit.

Response:
def pauli_string_half(circuit: circuits.Circuit) -> circuits.Circuit:
    """Return only the non-Clifford part of a circuit.  See
    convert_and_separate_circuit().

    Args:
        circuit: A Circuit with the gate set {SingleQubitCliffordGate,
            PauliInteractionGate, PauliStringPhasor}.

    Returns:
        A Circuit with only PauliStringPhasor operations.
    """
    return circuits.Circuit.from_ops(
            _pull_non_clifford_before(circuit),
            strategy=circuits.InsertStrategy.EARLIEST)


Instruction:
Write a Python 3 function that can
verify the density matrix_rep is valid and converts it to ndarray form.

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

    This method is used to support passing a matrix, a vector (wave function),
    or a computational basis state as a representation of a state.

    Args:
        density_matrix_rep: If an numpy array, if it is of rank 2 (a matrix),
            then this is the density matrix. If it is a numpy array of rank 1
            (a vector) then this is a wave function. If this is an int,
            then this is the computation basis state.
        num_qubits: The number of qubits for the density matrix. The
            density_matrix_rep must be valid for this number of qubits.
        dtype: The numpy dtype of the density matrix, will be used when creating
            the state for a computational basis state (int), or validated
            against if density_matrix_rep is a numpy array.

    Returns:
        A numpy matrix corresponding to the density matrix on the given number
        of qubits.

    Raises:
        ValueError if the density_matrix_rep is not valid.
    """
    if (isinstance(density_matrix_rep, np.ndarray)
        and density_matrix_rep.ndim == 2):
        if density_matrix_rep.shape != (2 ** num_qubits, 2 ** num_qubits):
            raise ValueError(
                'Density matrix was not square and of size 2 ** num_qubit, '
                'instead was {}'.format(density_matrix_rep.shape))
        if not np.allclose(density_matrix_rep,
                           np.transpose(np.conj(density_matrix_rep))):
            raise ValueError('The density matrix is not hermitian.')
        if not np.isclose(np.trace(density_matrix_rep), 1.0):
            raise ValueError(
                'Density matrix did not have trace 1 but instead {}'.format(
                    np.trace(density_matrix_rep)))
        if density_matrix_rep.dtype != dtype:
            raise ValueError(
                'Density matrix had dtype {} but expected {}'.format(
                    density_matrix_rep.dtype, dtype))
        if not np.all(np.linalg.eigvalsh(density_matrix_rep) > -1e-8):
            raise ValueError('The density matrix is not positive semidefinite.')
        return density_matrix_rep

    state_vector = wave_function.to_valid_state_vector(density_matrix_rep,
                                                       num_qubits, dtype)
    return np.outer(state_vector, np.conj(state_vector))


Instruction:
Create a Python 3 function to
perform a measurement of the density matrix in the computational basis.

Response:
def measure_density_matrix(
    density_matrix: np.ndarray,
    indices: List[int],
    out: np.ndarray = None) -> Tuple[List[bool], np.ndarray]:
    """Performs a measurement of the density matrix in the computational basis.

    This does not modify `density_matrix` unless the optional `out` is
    `density_matrix`.

    Args:
        density_matrix: The density matrix to be measured. This matrix is
            assumed to be positive semidefinite and trace one. The matrix is
            assumed to be of shape (2 ** integer, 2 ** integer) or
            (2, 2, ..., 2).
        indices: Which qubits are measured. The matrix is assumed to be supplied
            in big endian order. That is the xth index of v, when expressed as
            a bitstring, has the largest values in the 0th index.
        out: An optional place to store the result. If `out` is the same as
            the `density_matrix` parameter, then `density_matrix` will be
            modified inline. If `out` is not None, then the result is put into
            `out`.  If `out` is None a new value will be allocated. In all of
            these cases `out` will be the same as the returned ndarray of the
            method. The shape and dtype of `out` will match that of
            `density_matrix` if `out` is None, otherwise it will match the
            shape and dtype of `out`.

    Returns:
        A tuple of a list and an numpy array. The list is an array of booleans
        corresponding to the measurement values (ordered by the indices). The
        numpy array is the post measurement matrix. This matrix has the same
        shape and dtype as the input matrix.

    Raises:
        ValueError if the dimension of the matrix is not compatible with a
            matrix of n qubits.
        IndexError if the indices are out of range for the number of qubits
            corresponding to the density matrix.
    """
    num_qubits = _validate_num_qubits(density_matrix)
    _validate_indices(num_qubits, indices)

    if len(indices) == 0:
        if out is None:
            out = np.copy(density_matrix)
        elif out is not density_matrix:
            np.copyto(dst=out, src=density_matrix)
        return ([], out)
        # Final else: if out is matrix then matrix will be modified in place.

    # Cache initial shape.
    initial_shape = density_matrix.shape

    # Calculate the measurement probabilities and then make the measurement.
    probs = _probs(density_matrix, indices, num_qubits)
    result = np.random.choice(len(probs), p=probs)
    measurement_bits = [(1 & (result >> i)) for i in range(len(indices))]

    # Calculate the slice for the measurement result.
    result_slice = linalg.slice_for_qubits_equal_to(indices, result,
                                                    num_qubits=num_qubits)
    # Create a mask which is False for only the slice.
    mask = np.ones([2] * 2 * num_qubits, dtype=bool)
    # Remove ellipses from last element of
    mask[result_slice * 2] = False

    if out is None:
        out = np.copy(density_matrix)
    elif out is not density_matrix:
        np.copyto(dst=out, src=density_matrix)
    # Final else: if out is matrix then matrix will be modified in place.

    # Potentially reshape to tensor, and then set masked values to 0.
    out.shape = [2] * num_qubits * 2
    out[mask] = 0

    # Restore original shape (if necessary) and renormalize.
    out.shape = initial_shape
    out /= probs[result]

    return measurement_bits, out


Instruction:
How would you implement a function in Python 3 that
returns the probabilities for a measurement on the given indices.

Response:
def _probs(density_matrix: np.ndarray, indices: List[int],
    num_qubits: int) -> List[float]:
    """Returns the probabilities for a measurement on the given indices."""
    # Only diagonal elements matter.
    all_probs = np.diagonal(
        np.reshape(density_matrix, (2 ** num_qubits, 2 ** num_qubits)))
    # Shape into a tensor
    tensor = np.reshape(all_probs, [2] * num_qubits)

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

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


Instruction:
Given the following Python 3 function, write the documentation
def _validate_num_qubits(density_matrix: np.ndarray) -> int:
    shape = density_matrix.shape
    half_index = len(shape) // 2
    row_size = np.prod(shape[:half_index]) if len(shape) != 0 else 0
    col_size = np.prod(shape[half_index:]) if len(shape) != 0 else 0
    if row_size != col_size:
        raise ValueError(
            'Matrix was not square. Shape was {}'.format(shape))
    if row_size & (row_size - 1):
        raise ValueError(
            'Matrix could not be shaped into a square matrix with dimensions '
            'not a power of two. Shape was {}'.format(shape)
        )
    if len(shape) > 2 and not np.allclose(shape, 2):
        raise ValueError(
            'Matrix is a tensor of rank greater than 2, but had dimensions '
            'that are not powers of two. Shape was {}'.format(shape)
        )
    return int(row_size).bit_length() - 1

Response: Validates that matrix s shape is a valid shape for qubits.


Instruction:
Can you generate the documentation for the following Python 3 function
def _apply_unitary_circuit(circuit: Circuit,
                           state: np.ndarray,
                           qubits: Tuple[ops.Qid, ...],
                           dtype: Type[np.number]) -> np.ndarray:
    """Applies a circuit's unitary effect to the given vector or matrix.

    This method assumes that the caller wants to ignore measurements.

    Args:
        circuit: The circuit to simulate. All operations must have a known
            matrix or decompositions leading to known matrices. Measurements
            are allowed to be in the circuit, but they will be ignored.
        state: The initial state tensor (i.e. superposition or unitary matrix).
            This is what will be left-multiplied by the circuit's effective
            unitary. If this is a state vector, it must have shape
            (2,) * num_qubits. If it is a unitary matrix it should have shape
            (2,) * (2*num_qubits).
        qubits: The qubits in the state tensor. Determines which axes operations
            apply to. An operation targeting the k'th qubit in this list will
            operate on the k'th axis of the state tensor.
        dtype: The numpy dtype to use for applying the unitary. Must be a
            complex dtype.

    Returns:
        The left-multiplied state tensor.
    """
    qubit_map = {q: i for i, q in enumerate(qubits)}
    buffer = np.zeros(state.shape, dtype=dtype)

    def on_stuck(bad_op):
        return TypeError(
            'Operation without a known matrix or decomposition: {!r}'.format(
                bad_op))

    unitary_ops = protocols.decompose(
        circuit.all_operations(),
        keep=protocols.has_unitary,
        intercepting_decomposer=_decompose_measurement_inversions,
        on_stuck_raise=on_stuck)

    for op in unitary_ops:
        indices = [qubit_map[q] for q in op.qubits]
        result = protocols.apply_unitary(
            unitary_value=op,
            args=protocols.ApplyUnitaryArgs(state, buffer, indices))
        if result is buffer:
            buffer = state
        state = result
    return state

Response: Applies a circuit s unitary effect to the given vector or matrix.


Instruction:
Write a Python 3 function that can
group runs of items that are identical according to a keying function.

Response:
def _group_until_different(items: Iterable[TIn],
                           key: Callable[[TIn], TKey],
                           value=lambda e: e):
    """Groups runs of items that are identical according to a keying function.

    Args:
        items: The items to group.
        key: If two adjacent items produce the same output from this function,
            they will be grouped.
        value: Maps each item into a value to put in the group. Defaults to the
            item itself.

    Examples:
        _group_until_different(range(11), key=is_prime) yields
            (False, [0, 1])
            (True, [2, 3])
            (False, [4])
            (True, [5])
            (False, [6])
            (True, [7])
            (False, [8, 9, 10])

    Yields:
        Tuples containing the group key and item values.
    """
    return ((k, [value(i) for i in v]) for (k, v) in groupby(items, key))


Instruction:
Can you generate the documentation for the following Python 3 function
def from_ops(*operations: ops.OP_TREE,
                 strategy: InsertStrategy = InsertStrategy.EARLIEST,
                 device: devices.Device = devices.UnconstrainedDevice
                 ) -> 'Circuit':
        """Creates an empty circuit and appends the given operations.

        Args:
            operations: The operations to append to the new circuit.
            strategy: How to append the operations.
            device: Hardware that the circuit should be able to run on.

        Returns:
            The constructed circuit containing the operations.
        """
        result = Circuit(device=device)
        result.append(operations, strategy)
        return result

Response: Creates a new circuit with the given operations.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _approx_eq_(self, other: Any, atol: Union[int, float]) -> bool:
        if not isinstance(other, type(self)):
            return NotImplemented
        return cirq.protocols.approx_eq(
            self._moments,
            other._moments,
            atol=atol
        ) and self._device == other._device

Response: See cirq. protocols. SupportsApproximateEquality.


Instruction:
Given the following Python 3 function, write the documentation
def with_device(
            self,
            new_device: devices.Device,
            qubit_mapping: Callable[[ops.Qid], ops.Qid] = lambda e: e,
    ) -> 'Circuit':
        """Maps the current circuit onto a new device, and validates.

        Args:
            new_device: The new device that the circuit should be on.
            qubit_mapping: How to translate qubits from the old device into
                qubits on the new device.

        Returns:
            The translated circuit.
        """
        return Circuit(
            moments=[ops.Moment(operation.transform_qubits(qubit_mapping)
                            for operation in moment.operations)
                     for moment in self._moments],
            device=new_device
        )

Response: Returns a new circuit with the current circuit mapped onto a new device.


Instruction:
Can you generate the documentation for the following Python 3 function
def _repr_pretty_(self, p: Any, cycle: bool) -> None:
        if cycle:
            # There should never be a cycle.  This is just in case.
            p.text('Circuit(...)')
        else:
            p.text(self.to_text_diagram())

Response: Print ASCII diagram in Jupyter.


Instruction:
How would you explain what the following Python 3 function does
def next_moment_operating_on(self,
                                 qubits: Iterable[ops.Qid],
                                 start_moment_index: int = 0,
                                 max_distance: int = None) -> Optional[int]:
        """Finds the index of the next moment that touches the given qubits.

        Args:
            qubits: We're looking for operations affecting any of these qubits.
            start_moment_index: The starting point of the search.
            max_distance: The number of moments (starting from the start index
                and moving forward) to check. Defaults to no limit.

        Returns:
            None if there is no matching moment, otherwise the index of the
            earliest matching moment.

        Raises:
          ValueError: negative max_distance.
        """
        max_circuit_distance = len(self._moments) - start_moment_index
        if max_distance is None:
            max_distance = max_circuit_distance
        elif max_distance < 0:
            raise ValueError('Negative max_distance: {}'.format(max_distance))
        else:
            max_distance = min(max_distance, max_circuit_distance)

        return self._first_moment_operating_on(
            qubits,
            range(start_moment_index, start_moment_index + max_distance))

Response: Finds the index of the next moment that touches the given qubits.


Instruction:
Can you generate the documentation for the following Python 3 function
def next_moments_operating_on(self,
                                  qubits: Iterable[ops.Qid],
                                  start_moment_index: int = 0
                                  ) -> Dict[ops.Qid, int]:
        """Finds the index of the next moment that touches each qubit.

        Args:
            qubits: The qubits to find the next moments acting on.
            start_moment_index: The starting point of the search.

        Returns:
            The index of the next moment that touches each qubit. If there
            is no such moment, the next moment is specified as the number of
            moments in the circuit. Equivalently, can be characterized as one
            plus the index of the last moment after start_moment_index
            (inclusive) that does *not* act on a given qubit.
        """
        next_moments = {}
        for q in qubits:
            next_moment = self.next_moment_operating_on(
                [q], start_moment_index)
            next_moments[q] = (len(self._moments) if next_moment is None else
                               next_moment)
        return next_moments

Response: Finds the index of the next moments that act on a given qubit.


Instruction:
Implement a function in Python 3 to
find the index of the previous matching moment that touches the given qubits.

Response:
def prev_moment_operating_on(
            self,
            qubits: Sequence[ops.Qid],
            end_moment_index: Optional[int] = None,
            max_distance: Optional[int] = None) -> Optional[int]:
        """Finds the index of the next moment that touches the given qubits.

        Args:
            qubits: We're looking for operations affecting any of these qubits.
            end_moment_index: The moment index just after the starting point of
                the reverse search. Defaults to the length of the list of
                moments.
            max_distance: The number of moments (starting just before from the
                end index and moving backward) to check. Defaults to no limit.

        Returns:
            None if there is no matching moment, otherwise the index of the
            latest matching moment.

        Raises:
            ValueError: negative max_distance.
        """
        if end_moment_index is None:
            end_moment_index = len(self._moments)

        if max_distance is None:
            max_distance = len(self._moments)
        elif max_distance < 0:
            raise ValueError('Negative max_distance: {}'.format(max_distance))
        else:
            max_distance = min(end_moment_index, max_distance)

        # Don't bother searching indices past the end of the list.
        if end_moment_index > len(self._moments):
            d = end_moment_index - len(self._moments)
            end_moment_index -= d
            max_distance -= d
        if max_distance <= 0:
            return None

        return self._first_moment_operating_on(qubits,
                                               (end_moment_index - k - 1
                                                for k in range(max_distance)))


Instruction:
How would you code a function in Python 3 to
determine how far can be reached into a given start frontier.

Response:
def reachable_frontier_from(
            self,
            start_frontier: Dict[ops.Qid, int],
            *,
            is_blocker: Callable[[ops.Operation], bool] = lambda op: False
    ) -> Dict[ops.Qid, int]:
        """Determines how far can be reached into a circuit under certain rules.

        The location L = (qubit, moment_index) is *reachable* if and only if:

            a) L is one of the items in `start_frontier`.

            OR

            b) There is no operation at L and prev(L) = (qubit, moment_index-1)
                is reachable and L is within the bounds of the circuit.

            OR

            c) There is an operation P covering L and, for every location
                M = (q', moment_index) that P covers, the location
                prev(M) = (q', moment_index-1) is reachable. Also, P must not be
                classified as a blocker by the given `is_blocker` argument.

        In other words, the reachable region extends forward through time along
        each qubit until it hits a blocked operation or an operation that
        crosses into the set of not-involved-at-the-moment qubits.

        For each qubit q in `start_frontier`, the reachable locations will
        correspond to a contiguous range starting at start_frontier[q] and
        ending just before some index end_q. The result of this method is a
        dictionary, and that dictionary maps each qubit q to its end_q.

        Examples:

            If start_frontier is {
                cirq.LineQubit(0): 6,
                cirq.LineQubit(1): 2,
                cirq.LineQubit(2): 2,
            } then the reachable wire locations in the following circuit are
            highlighted with '█' characters:

                0   1   2   3   4   5   6   7   8   9   10  11  12  13
            0: ───H───@─────────────────█████████████████████─@───H───
                      │                                       │
            1: ───────@─██H███@██████████████████████─@───H───@───────
                              │                       │
            2: ─────────██████@███H██─@───────@───H───@───────────────
                                      │       │
            3: ───────────────────────@───H───@───────────────────────

            And the computed end_frontier is {
                cirq.LineQubit(0): 11,
                cirq.LineQubit(1): 9,
                cirq.LineQubit(2): 6,
            }

            Note that the frontier indices (shown above the circuit) are
            best thought of (and shown) as happening *between* moment indices.

            If we specify a blocker as follows:

                is_blocker=lambda: op == cirq.CZ(cirq.LineQubit(1),
                                                 cirq.LineQubit(2))

            and use this start_frontier:

                {
                    cirq.LineQubit(0): 0,
                    cirq.LineQubit(1): 0,
                    cirq.LineQubit(2): 0,
                    cirq.LineQubit(3): 0,
                }

            Then this is the reachable area:

                0   1   2   3   4   5   6   7   8   9   10  11  12  13
            0: ─██H███@██████████████████████████████████████─@───H───
                      │                                       │
            1: ─██████@███H██─@───────────────────────@───H───@───────
                              │                       │
            2: ─█████████████─@───H───@───────@───H───@───────────────
                                      │       │
            3: ─█████████████████████─@───H───@───────────────────────

            and the computed end_frontier is:

                {
                    cirq.LineQubit(0): 11,
                    cirq.LineQubit(1): 3,
                    cirq.LineQubit(2): 3,
                    cirq.LineQubit(3): 5,
                }

        Args:
            start_frontier: A starting set of reachable locations.
            is_blocker: A predicate that determines if operations block
                reachability. Any location covered by an operation that causes
                `is_blocker` to return True is considered to be an unreachable
                location.

        Returns:
            An end_frontier dictionary, containing an end index for each qubit q
            mapped to a start index by the given `start_frontier` dictionary.

            To determine if a location (q, i) was reachable, you can use
            this expression:

                q in start_frontier and start_frontier[q] <= i < end_frontier[q]

            where i is the moment index, q is the qubit, and end_frontier is the
            result of this method.
        """
        active = set()  # type: Set[ops.Qid]
        end_frontier = {}
        queue = BucketPriorityQueue[ops.Operation](drop_duplicate_entries=True)

        def enqueue_next(qubit: ops.Qid, moment: int) -> None:
            next_moment = self.next_moment_operating_on([qubit], moment)
            if next_moment is None:
                end_frontier[qubit] = max(len(self), start_frontier[qubit])
                if qubit in active:
                    active.remove(qubit)
            else:
                next_op = self.operation_at(qubit, next_moment)
                assert next_op is not None
                queue.enqueue(next_moment, next_op)

        for start_qubit, start_moment in start_frontier.items():
            enqueue_next(start_qubit, start_moment)

        while queue:
            cur_moment, cur_op = queue.dequeue()
            for q in cur_op.qubits:
                if (q in start_frontier and
                        cur_moment >= start_frontier[q] and
                        q not in end_frontier):
                    active.add(q)

            continue_past = (
                cur_op is not None and
                active.issuperset(cur_op.qubits) and
                not is_blocker(cur_op)
            )
            if continue_past:
                for q in cur_op.qubits:
                    enqueue_next(q, cur_moment + 1)
            else:
                for q in cur_op.qubits:
                    if q in active:
                        end_frontier[q] = cur_moment
                        active.remove(q)

        return end_frontier


Instruction:
Implement a Python 3 function for
finding operations between two given frontiers.

Response:
def findall_operations_between(self,
                                   start_frontier: Dict[ops.Qid, int],
                                   end_frontier: Dict[ops.Qid, int],
                                   omit_crossing_operations: bool = False
                                   ) -> List[Tuple[int, ops.Operation]]:
        """Finds operations between the two given frontiers.

        If a qubit is in `start_frontier` but not `end_frontier`, its end index
        defaults to the end of the circuit. If a qubit is in `end_frontier` but
        not `start_frontier`, its start index defaults to the start of the
        circuit. Operations on qubits not mentioned in either frontier are not
        included in the results.

        Args:
            start_frontier: Just before where to start searching for operations,
                for each qubit of interest. Start frontier indices are
                inclusive.
            end_frontier: Just before where to stop searching for operations,
                for each qubit of interest. End frontier indices are exclusive.
            omit_crossing_operations: Determines whether or not operations that
                cross from a location between the two frontiers to a location
                outside the two frontiers are included or excluded. (Operations
                completely inside are always included, and operations completely
                outside are always excluded.)

        Returns:
            A list of tuples. Each tuple describes an operation found between
            the two frontiers. The first item of each tuple is the index of the
            moment containing the operation, and the second item is the
            operation itself. The list is sorted so that the moment index
            increases monotonically.
        """
        result = BucketPriorityQueue[ops.Operation](
            drop_duplicate_entries=True)

        involved_qubits = set(start_frontier.keys()) | set(end_frontier.keys())
        # Note: only sorted to ensure a deterministic result ordering.
        for q in sorted(involved_qubits):
            for i in range(start_frontier.get(q, 0),
                           end_frontier.get(q, len(self))):
                op = self.operation_at(q, i)
                if op is None:
                    continue
                if (omit_crossing_operations and
                        not involved_qubits.issuperset(op.qubits)):
                    continue
                result.enqueue(i, op)

        return list(result)


Instruction:
Can you tell what is the following Python 3 function doing
def findall_operations_until_blocked(
            self,
            start_frontier: Dict[ops.Qid, int],
            is_blocker: Callable[[ops.Operation], bool] = lambda op: False
    ) -> List[Tuple[int, ops.Operation]]:
        """
        Finds all operations until a blocking operation is hit.  This returns
        a list of all operations from the starting frontier until a blocking
        operation is encountered.  An operation is part of the list if
        it is involves a qubit in the start_frontier dictionary, comes after
        the moment listed in that dictionary, and before any blocking
        operationi that involve that qubit.  Operations are only considered
        to blocking the qubits that they operate on, so a blocking operation
        that does not operate on any qubit in the starting frontier is not
        actually considered blocking.  See `reachable_frontier_from` for a more
        in depth example of reachable states.

        Args:
            start_frontier: A starting set of reachable locations.
            is_blocker: A predicate that determines if operations block
                reachability. Any location covered by an operation that causes
                `is_blocker` to return True is considered to be an unreachable
                location.

        Returns:
            A list of tuples. Each tuple describes an operation found between
            the start frontier and a blocking operation. The first item of
            each tuple is the index of the moment containing the operation,
            and the second item is the operation itself.
        """
        op_list = []
        max_index = len(self._moments)
        for qubit in start_frontier:
            current_index = start_frontier[qubit]
            if current_index < 0:
                current_index = 0
            while current_index < max_index:
                if self[current_index].operates_on_single_qubit(qubit):
                    next_op = self.operation_at(qubit, current_index)
                    if next_op is not None:
                        if is_blocker(next_op):
                            break
                        op_list.append((current_index,next_op))
                current_index+=1
        return op_list

Response: This function finds all operations until a blocking operation is hit.


Instruction:
Write a Python 3 function for
finding the operation on a qubit within a moment.

Response:
def operation_at(self,
                     qubit: ops.Qid,
                     moment_index: int) -> Optional[ops.Operation]:
        """Finds the operation on a qubit within a moment, if any.

        Args:
            qubit: The qubit to check for an operation on.
            moment_index: The index of the moment to check for an operation
                within. Allowed to be beyond the end of the circuit.

        Returns:
            None if there is no operation on the qubit at the given moment, or
            else the operation.
        """
        if not 0 <= moment_index < len(self._moments):
            return None
        for op in self._moments[moment_index].operations:
            if qubit in op.qubits:
                return op
        return None


Instruction:
Write a Python 3 function for
finding the locations of all operations that satisfy a given condition.

Response:
def findall_operations(self, predicate: Callable[[ops.Operation], bool]
                           ) -> Iterable[Tuple[int, ops.Operation]]:
        """Find the locations of all operations that satisfy a given condition.

        This returns an iterator of (index, operation) tuples where each
        operation satisfies op_cond(operation) is truthy. The indices are
        in order of the moments and then order of the ops within that moment.

        Args:
            predicate: A method that takes an Operation and returns a Truthy
                value indicating the operation meets the find condition.

        Returns:
            An iterator (index, operation)'s that satisfy the op_condition.
        """
        for index, moment in enumerate(self._moments):
            for op in moment.operations:
                if predicate(op):
                    yield index, op


Instruction:
Create a Python 3 function to
find the locations of all gate operations of a given type.

Response:
def findall_operations_with_gate_type(
            self,
            gate_type: Type[T_DESIRED_GATE_TYPE]
    ) -> Iterable[Tuple[int,
                        ops.GateOperation,
                        T_DESIRED_GATE_TYPE]]:
        """Find the locations of all gate operations of a given type.

        Args:
            gate_type: The type of gate to find, e.g. XPowGate or
                MeasurementGate.

        Returns:
            An iterator (index, operation, gate)'s for operations with the given
            gate type.
        """
        result = self.findall_operations(lambda operation: bool(
            ops.op_gate_of_type(operation, gate_type)))
        for index, op in result:
            gate_op = cast(ops.GateOperation, op)
            yield index, gate_op, cast(T_DESIRED_GATE_TYPE, gate_op.gate)


Instruction:
Can you tell what is the following Python 3 function doing
def are_all_matches_terminal(self,
            predicate: Callable[[ops.Operation], bool]):
        """Check whether all of the ops that satisfy a predicate are terminal.

        Args:
            predicate: A predicate on ops.Operations which is being checked.

        Returns:
            Whether or not all `Operation` s in a circuit that satisfy the
            given predicate are terminal.
        """
        return all(
            self.next_moment_operating_on(op.qubits, i + 1) is None for
            (i, op) in self.findall_operations(predicate)
        )

Response: Returns True if all of the operations in a circuit that satisfy a predicate are terminal.


Instruction:
Write a Python 3 function that can
determine and prepares where an insertion should occur at the specified splitter index.

Response:
def _pick_or_create_inserted_op_moment_index(
            self, splitter_index: int, op: ops.Operation,
            strategy: InsertStrategy) -> int:
        """Determines and prepares where an insertion will occur.

        Args:
            splitter_index: The index to insert at.
            op: The operation that will be inserted.
            strategy: The insertion strategy.

        Returns:
            The index of the (possibly new) moment where the insertion should
                occur.

        Raises:
            ValueError: Unrecognized append strategy.
        """

        if (strategy is InsertStrategy.NEW or
                strategy is InsertStrategy.NEW_THEN_INLINE):
            self._moments.insert(splitter_index, ops.Moment())
            return splitter_index

        if strategy is InsertStrategy.INLINE:
            if (0 <= splitter_index - 1 < len(self._moments) and
                    self._can_add_op_at(splitter_index - 1, op)):
                return splitter_index - 1

            return self._pick_or_create_inserted_op_moment_index(
                splitter_index, op, InsertStrategy.NEW)

        if strategy is InsertStrategy.EARLIEST:
            if self._can_add_op_at(splitter_index, op):
                p = self._prev_moment_available(op, splitter_index)
                return p or 0

            return self._pick_or_create_inserted_op_moment_index(
                splitter_index, op, InsertStrategy.INLINE)

        raise ValueError('Unrecognized append strategy: {}'.format(strategy))


Instruction:
Create a Python 3 function for
inserting operations into the circuit.

Response:
def insert(
            self,
            index: int,
            moment_or_operation_tree: Union[ops.Moment, ops.OP_TREE],
            strategy: InsertStrategy = InsertStrategy.EARLIEST) -> int:
        """ Inserts operations into the circuit.
            Operations are inserted into the moment specified by the index and
            'InsertStrategy'.
            Moments within the operation tree are inserted intact.

        Args:
            index: The index to insert all of the operations at.
            moment_or_operation_tree: The moment or operation tree to insert.
            strategy: How to pick/create the moment to put operations into.

        Returns:
            The insertion index that will place operations just after the
            operations that were inserted by this method.

        Raises:
            ValueError: Bad insertion strategy.
        """
        moments_and_operations = list(ops.flatten_op_tree(
            ops.transform_op_tree(moment_or_operation_tree,
                                  self._device.decompose_operation,
                                  preserve_moments=True),
            preserve_moments=True))

        for moment_or_op in moments_and_operations:
            if isinstance(moment_or_op, ops.Moment):
                self._device.validate_moment(cast(ops.Moment, moment_or_op))
            else:
                self._device.validate_operation(
                    cast(ops.Operation, moment_or_op))

        # limit index to 0..len(self._moments), also deal with indices smaller 0
        k = max(min(index if index >= 0 else len(self._moments) + index,
                    len(self._moments)), 0)
        for moment_or_op in moments_and_operations:
            if isinstance(moment_or_op, ops.Moment):
                self._moments.insert(k, moment_or_op)
                k += 1
            else:
                p = self._pick_or_create_inserted_op_moment_index(
                    k, moment_or_op, strategy)
                while p >= len(self._moments):
                    self._moments.append(ops.Moment())
                self._moments[p] = self._moments[p].with_operation(moment_or_op)
                self._device.validate_moment(self._moments[p])
                k = max(k, p + 1)
                if strategy is InsertStrategy.NEW_THEN_INLINE:
                    strategy = InsertStrategy.INLINE
        return k


Instruction:
Given the following Python 3 function, write the documentation
def insert_into_range(self,
                          operations: ops.OP_TREE,
                          start: int,
                          end: int) -> int:
        """Writes operations inline into an area of the circuit.

        Args:
            start: The start of the range (inclusive) to write the
                given operations into.
            end: The end of the range (exclusive) to write the given
                operations into. If there are still operations remaining,
                new moments are created to fit them.
            operations: An operation or tree of operations to insert.

        Returns:
            An insertion index that will place operations after the operations
            that were inserted by this method.

        Raises:
            IndexError: Bad inline_start and/or inline_end.
        """
        if not 0 <= start <= end <= len(self):
            raise IndexError('Bad insert indices: [{}, {})'.format(
                start, end))

        operations = list(ops.flatten_op_tree(operations))
        for op in operations:
            self._device.validate_operation(op)

        i = start
        op_index = 0
        while op_index < len(operations):
            op = operations[op_index]
            while i < end and not self._device.can_add_operation_into_moment(
                    op, self._moments[i]):
                i += 1
            if i >= end:
                break
            self._moments[i] = self._moments[i].with_operation(op)
            op_index += 1

        if op_index >= len(operations):
            return end

        return self.insert(end, operations[op_index:])

Response: Inserts operations inline into an area of the circuit.


Instruction:
Given the following Python 3 function, write the documentation
def _pick_inserted_ops_moment_indices(operations: Sequence[ops.Operation],
                                          start: int = 0,
                                          frontier: Dict[ops.Qid,
                                                         int] = None
                                          ) -> Tuple[Sequence[int],
                                                     Dict[ops.Qid, int]]:
        """Greedily assigns operations to moments.

        Args:
            operations: The operations to assign to moments.
            start: The first moment to consider assignment to.
            frontier: The first moment to which an operation acting on a qubit
                can be assigned. Updated in place as operations are assigned.

        Returns:
            The frontier giving the index of the moment after the last one to
            which an operation that acts on each qubit is assigned. If a
            frontier was specified as an argument, this is the same object.
        """
        if frontier is None:
            frontier = defaultdict(lambda: 0)
        moment_indices = []
        for op in operations:
            op_start = max(start, max(frontier[q] for q in op.qubits))
            moment_indices.append(op_start)
            for q in op.qubits:
                frontier[q] = max(frontier[q], op_start + 1)

        return moment_indices, frontier

Response: Greedily assigns operations to moments.


Instruction:
Write a Python 3 script to
insert moments to separate two frontiers.

Response:
def _push_frontier(self,
                       early_frontier: Dict[ops.Qid, int],
                       late_frontier: Dict[ops.Qid, int],
                       update_qubits: Iterable[ops.Qid] = None
                       ) -> Tuple[int, int]:
        """Inserts moments to separate two frontiers.

        After insertion n_new moments, the following holds:
           for q in late_frontier:
               early_frontier[q] <= late_frontier[q] + n_new
           for q in update_qubits:
               early_frontier[q] the identifies the same moment as before
                   (but whose index may have changed if this moment is after
                   those inserted).

        Args:
            early_frontier: The earlier frontier. For qubits not in the later
                frontier, this is updated to account for the newly inserted
                moments.
            late_frontier: The later frontier. This is not modified.
            update_qubits: The qubits for which to update early_frontier to
                account for the newly inserted moments.

        Returns:
            (index at which new moments were inserted, how many new moments
            were inserted) if new moments were indeed inserted. (0, 0)
            otherwise.
        """
        if update_qubits is None:
            update_qubits = set(early_frontier).difference(late_frontier)
        n_new_moments = (max(early_frontier.get(q, 0) - late_frontier[q]
                             for q in late_frontier)
                         if late_frontier else 0)
        if n_new_moments > 0:
            insert_index = min(late_frontier.values())
            self._moments[insert_index:insert_index] = (
                [ops.Moment()] * n_new_moments)
            for q in update_qubits:
                if early_frontier.get(q, 0) > insert_index:
                    early_frontier[q] += n_new_moments
            return insert_index, n_new_moments
        return (0, 0)