microsoft/qdk

Public

mirrored from https://github.com/microsoft/qdkAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
copilot/replace-qsharp-with-qdk-python-tests

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

source/pip/qsharp/utils/_utils.py

50lines · modecode

1# Copyright (c) Microsoft Corporation.
2# Licensed under the MIT License.
3
4from .._qsharp import run
5from typing import List
6import math
7
8
9def dump_operation(operation: str, num_qubits: int) -> List[List[complex]]:
10 """
11 Returns a square matrix of complex numbers representing the operation performed.
12
13 :param operation: The operation to be performed, which must operate on a list of qubits.
14 :param num_qubits: The number of qubits to be used.
15
16 :return: The matrix representing the operation.
17 :rtype: List[List[complex]]
18 """
19 code = f"""{{
20 let op = {operation};
21 use (targets, extra) = (Qubit[{num_qubits}], Qubit[{num_qubits}]);
22 for i in 0..{num_qubits}-1 {{
23 H(targets[i]);
24 CNOT(targets[i], extra[i]);
25 }}
26 operation ApplyOp (op : (Qubit[] => Unit), targets : Qubit[]) : Unit {{ op(targets); }}
27 ApplyOp(op, targets);
28 Microsoft.Quantum.Diagnostics.DumpMachine();
29 ResetAll(targets + extra);
30 }}"""
31 result = run(code, shots=1, save_events=True)[0]
32 state = result["events"][-1].state_dump().get_dict()
33 num_entries = pow(2, num_qubits)
34 factor = math.sqrt(num_entries)
35 ndigits = 6
36 matrix = []
37 for i in range(num_entries):
38 matrix += [[]]
39 for j in range(num_entries):
40 entry = state.get(i * num_entries + j)
41 if entry is None:
42 matrix[i] += [complex(0, 0)]
43 else:
44 matrix[i] += [
45 complex(
46 round(factor * entry.real, ndigits),
47 round(factor * entry.imag, ndigits),
48 )
49 ]
50 return matrix
51