def test_basic_capture(self): dump_plus = qsharp.compile(""" open Microsoft.Quantum.Diagnostics; operation DumpPlus() : Unit { use qs = Qubit[2]; within { H(qs[0]); H(qs[1]); } apply { DumpMachine(); } } """) with qsharp.capture_diagnostics(as_qobj=False) as captured: dump_plus.simulate() assert 1 == len(captured) expected = """ { "diagnostic_kind": "state-vector", "qubit_ids": [0, 1], "n_qubits": 2, "amplitudes": [{"Real": 0.5000000000000001, "Imaginary": 0.0, "Magnitude": 0.5000000000000001, "Phase": 0.0}, {"Real": 0.5000000000000001, "Imaginary": 0.0, "Magnitude": 0.5000000000000001, "Phase": 0.0}, {"Real": 0.5000000000000001, "Imaginary": 0.0, "Magnitude": 0.5000000000000001, "Phase": 0.0}, {"Real": 0.5000000000000001, "Imaginary": 0.0, "Magnitude": 0.5000000000000001, "Phase": 0.0}] } """ del captured[0]['div_id'] assert json.dumps(json.loads(expected)) == json.dumps(captured[0])
def _test_workspace_with_providers_after_connection(): with pytest.raises(AzureError) as exception_info: qsharp.azure.target() assert exception_info.value.error_name == "NoTarget" targets = qsharp.azure.connect() for target in targets: active_target = qsharp.azure.target(target.id) assert isinstance(active_target, AzureTarget) assert active_target == target # Submit a snippet operation without parameters op = qsharp.compile(""" operation HelloQ() : Result { Message($"Hello from quantum world!"); return Zero; } """) job = qsharp.azure.submit(op) assert isinstance(job, AzureJob) retrieved_job = qsharp.azure.status(job.id) assert isinstance(retrieved_job, AzureJob) assert job.id == retrieved_job.id # Submit a job with the "jobParams" parameter job2 = qsharp.azure.submit(op, jobParams={ "key1": "value1", "key2": "value2" }) assert isinstance(job2, AzureJob)
def test_capture_experimental_diagnostics_as_qobj(self): dump_plus = qsharp.compile(""" open Microsoft.Quantum.Diagnostics; operation DumpPlus() : Unit { use qs = Qubit[2]; within { H(qs[0]); H(qs[1]); } apply { DumpMachine(); } } """) qsharp.experimental.set_noise_model_by_name('ideal') qsharp.config['experimental.simulators.nQubits'] = 2 qsharp.config['experimental.simulators.representation'] = 'mixed' with qsharp.capture_diagnostics(as_qobj=True) as captured: dump_plus.simulate_noise() assert 1 == len(captured) assert abs(1.0 - captured[0].tr()) <= 1e-8 import qutip as qt expected = qt.Qobj([[1], [1], [1], [1]], dims=[[2, 2], [1, 1]]).unit() expected = expected * expected.dag() assert (expected - captured[0]).norm() <= 1e-8
def test_chemistry_compile(): """ Verifies that that adding packages and compile works """ qsharp.packages.add("microsoft.quantum.chemistry") op = qsharp.compile(""" open Microsoft.Quantum.Chemistry.JordanWigner; /// # Summary /// We can now use Canon's phase estimation algorithms to /// learn the ground state energy using the above simulation. operation TrotterEstimateEnergy (qSharpData: JordanWignerEncodingData, nBitsPrecision : Int, trotterStepSize : Double) : (Double, Double) { let (nSpinOrbitals, data, statePrepData, energyShift) = qSharpData!; // Order of integrator let trotterOrder = 1; let (nQubits, (rescaleFactor, oracle)) = TrotterStepOracle(qSharpData, trotterStepSize, trotterOrder); // Prepare ProductState let statePrep = PrepareTrialState(statePrepData, _); let phaseEstAlgorithm = RobustPhaseEstimation(nBitsPrecision, _, _); let estPhase = EstimateEnergy(nQubits, statePrep, oracle, phaseEstAlgorithm); let estEnergy = estPhase * rescaleFactor + energyShift; return (estPhase, estEnergy); } """) assert op._name == "TrotterEstimateEnergy"
def generate_code(self, num_measurements: int = 1) -> QSharpCallable: validate_type(num_measurements, int) qsharp_code: str = """ open Microsoft.Quantum.Intrinsic; open Microsoft.Quantum.Measurement; open Microsoft.Quantum.Arrays; open Microsoft.Quantum.Math; operation Program():String[]{{ use q = Qubit[{num_qubits}]; mutable value = ConstantArray({num_measurements},""); mutable res = ""; for i in IndexRange(value) {{ {gates} set value w/= i <- res; set res = ""; }} ResetAll(q); return value; }} """ return compile( qsharp_code.format( num_qubits=self.num_qubits, num_measurements=num_measurements, gates=self._gates, ))
def qsharp(magic_args, cell, local_ns=None): """Compiles a Q# snippet, exposing its operations and functions to the current local scope.""" callables = qs.compile(cell) if isinstance(callables, qs.QSharpCallable): local_ns[callables._name] = callables else: for qs_callable in callables: local_ns[qs_callable._name] = qs_callable
def post_apply(self): #pragma no cover """Compile the Q# program""" for e in self.obs_queue: self.measure += "set resultArray w/= {wires[0]} <- ".format(wires=e.wires) self.measure += self._observable_map[e.name].format(p=e.parameters, wires=e.wires) self.measure += " " self._source_code = PROGRAM.format(wires=self.num_wires, operations=self.prog, measurements=self.measure) self.qs = qsharp.compile(self._source_code)
def test_toffoli_simulate(): foo = qsharp.compile(""" open Microsoft.Quantum.Measurement; operation Foo() : Result { using (q = Qubit()) { X(q); return MResetZ(q); } } """) assert foo.toffoli_simulate() == 1
def test_simple_compile(): """ Verifies that compile works """ op = qsharp.compile(""" operation HelloQ() : Result { Message($"Hello from quantum world!"); return One; } """) r = op.simulate() assert r == qsharp.Result.One
def post_apply(self): #pragma no cover """Compile the Q# program""" for e in self.obs_queue: # translate operation wire labels to the device's wire labels device_wires = self.map_wires(e.wires) self.measure += "set resultArray w/= {wires[0]} <- ".format( wires=device_wires.tolist()) self.measure += self._observable_map[e.name].format( wires=device_wires.tolist()) self.measure += " " self._source_code = PROGRAM.format(wires=self.num_wires, operations=self.prog, measurements=self.measure) self.qs = qsharp.compile(self._source_code)
def dump_qsharp_unitary(op_code, qubits_count): """Returns unitary matrix which is implemented by Q# operation. It applies given operation on every possible state vector (using Q# simulator) and retrieves state in which operation moves those vectors. These states are columns of unitary matrix implemented by the operation. args: op_code - Q# code for operation, which must be called "Op". qubits_count - number of qubits on which operation acts. return: np.array - unitary matrix implemented by given operation. """ dump_op = qsharp.compile(DUMP_CODE + op_code)[0] result = [] for basis_vector in range(2**qubits_count): bits = [(basis_vector >> i) % 2 == 1 for i in range(qubits_count)] dump_op.simulate(bits=bits, dump_file=DUMP_FILE) result.append(read_machine_state()) os.remove(DUMP_FILE) return np.array(result).T
def test_multi_compile(): """ Verifies that compile works """ ops = qsharp.compile(""" operation HelloQ() : Result { Message($"Hello from quantum world!"); return One; } operation Hello2() : Result { Message($"Will call hello."); return HelloQ(); } """) assert "Hello2" == ops[0]._name assert "HelloQ" == ops[1]._name r = ops[1].simulate() assert r == qsharp.Result.One
def test_capture_diagnostics_as_qobj(self): dump_plus = qsharp.compile(""" open Microsoft.Quantum.Diagnostics; operation DumpPlus() : Unit { use qs = Qubit[2]; within { H(qs[0]); H(qs[1]); } apply { DumpMachine(); } } """) with qsharp.capture_diagnostics(as_qobj=True) as captured: dump_plus.simulate() assert 1 == len(captured) assert abs(1.0 - captured[0].norm()) <= 1e-8 import qutip as qt expected = qt.Qobj([[1], [1], [1], [1]], dims=[[2, 2], [1, 1]]).unit() assert (expected - captured[0]).norm() <= 1e-8
import qsharp from qsharp.serialization import map_tuples qsharp.packages.add("microsoft.quantum.chemistry") # For now, it is better if you compile the entry-point operation from Python (instead of using a .qs file): TrotterEstimateEnergy = qsharp.compile(""" open Microsoft.Quantum.Chemistry.JordanWigner; operation TrotterEstimateEnergy (qSharpData: JordanWignerEncodingData, nBitsPrecision : Int, trotterStepSize : Double) : (Double, Double) { let (nSpinOrbitals, data, statePrepData, energyShift) = qSharpData!; // Order of integrator let trotterOrder = 1; let (nQubits, (rescaleFactor, oracle)) = TrotterStepOracle(qSharpData, trotterStepSize, trotterOrder); // Prepare ProductState let statePrep = PrepareTrialState(statePrepData, _); let phaseEstAlgorithm = RobustPhaseEstimation(nBitsPrecision, _, _); let estPhase = EstimateEnergy(nQubits, statePrep, oracle, phaseEstAlgorithm); let estEnergy = estPhase * rescaleFactor + energyShift; return (estPhase, estEnergy); } """) qsharp.packages.add("microsoft.quantum.chemistry.jupyter") filename = "broombridge_v0.2.yaml" ## Load fermion Hamiltonian from Broombridge file.
import qsharp ## Compile the program directly teleport = qsharp.compile(""" open Microsoft.Quantum.Intrinsic; open Microsoft.Quantum.Canon; open Microsoft.Quantum.Measurement; operation TeleportClassicalMessage (message : Bool) : Bool { using ((msg, target) = (Qubit(), Qubit())) { if (message) { X(msg); } using (register = Qubit()) { H(register); CNOT(register, target); CNOT(msg, register); H(msg); if (MResetZ(msg) == One) { Z(target); } if (IsResultOne(MResetZ(register))) { X(target); } } return MResetZ(target) == One; } } """) assert teleport.simulate(message=True) assert not teleport.simulate(message=False)
import xquantum as xq import qsharp import math with open('{0}/qdk/qdk.qs'.format(xq.__path__[0]), 'r') as file: qdk = qsharp.compile(''.join(file.readlines()[1:-1])) CircuitParameterDerivative = qdk[4] Classify = qdk[5] # from Cazzella.Quantum.CrossQuantum import Classify, CircuitParameterDerivative def testModel(engine, circuitModel, hyperParams, params, normalizedFeatureSet): rotationSet = _encodeFeatureRotationSet(normalizedFeatureSet) return [ _classifiedLableProbability(engine, circuitModel, hyperParams, params, r) for r in rotationSet ] def classifiedLableProbability(engine, circuitModel, hyperParams, parameters, normalizedFeatures): rotations = _encodeFeatureRotations(normalizedFeatures) return _classifiedLableProbability(engine, circuitModel, hyperParams, parameters, rotations) def circuitDerivativeByParams(engine, circuitModel, hyperParams, parameters, normalizedFeatures): rotations = _encodeFeatureRotations(normalizedFeatures)
#!/bin/env python # -*- coding: utf-8 -*- ## # qsharp-interop.py: Demo showing how Q# code can be run from a Python host. ## # Copyright (c) Sarah Kaiser and Chris Granade. # Code sample from the book "Learn Quantum Computing with Python and Q#" by # Sarah Kaiser and Chris Granade, published by Manning Publications Co. # Book ISBN 9781617296130. # Code licensed under the MIT License. ## import qsharp prepare_qubit = qsharp.compile(""" // <2> open Microsoft.Quantum.Diagnostics; // <3> operation PrepareQubit(): Unit { // <4> using (qubit = Qubit()) { DumpMachine(); } } """) if __name__ == "__main__": prepare_qubit.simulate()