Beispiel #1
0
    def test_load_qasm_file(self):
        """Test load_qasm_file and get_circuit.

        If all is correct we should get the qasm file loaded in _qasm_file_path
        """
        q_circuit = load_qasm_file(self.qasm_file_path)
        qasm_string = q_circuit.qasm()
        self.log.info(qasm_string)
        expected_qasm_string = """\
OPENQASM 2.0;
include "qelib1.inc";
qreg a[4];
qreg b[4];
creg c[4];
creg d[4];
h a[0];
h a[1];
h a[2];
h a[3];
cx a[0],b[0];
cx a[1],b[1];
cx a[2],b[2];
cx a[3],b[3];
barrier a[0],a[1],a[2],a[3];
barrier b[0],b[1],b[2],b[3];
measure a[0] -> c[0];
measure a[1] -> c[1];
measure a[2] -> c[2];
measure a[3] -> c[3];
measure b[0] -> d[0];
measure b[1] -> d[1];
measure b[2] -> d[2];
measure b[3] -> d[3];
"""
        self.assertEqual(qasm_string, expected_qasm_string)
Beispiel #2
0
def probeMatrix(filename, nQubits, index, viewMatrix, compress):
    #Debug.debug(filename + " ; " + str(nQubits) + " ; " + str(index) + " ; " + str(viewMatrix), DebugLevel.Function)

    matrix1 = generateMatrix(filename, nQubits, index, compress)

    res = 0

    try:
        qc = load_qasm_file(filename)

        job_sim = execute(qc, "local_unitary_simulator")
        sim_result = job_sim.result()
        matrix2 = sim_result.get_unitary(qc)

        if (viewMatrix):
            print(Colors.ORANGE.value + "\nGenerated matrix\n" + str(matrix1) +
                  "\n" + Colors.ENDC.value)
            print(Colors.PURPLE.value + "\nSimulated matrix\n" + str(matrix2) +
                  "\n" + Colors.ENDC.value)

        if areEqual(matrix1, matrix2):
            print(Colors.GREEN.value + "\n EQUAL \n\n" + Colors.ENDC.value)
            res = 0
        elif areClose(matrix1, matrix2):
            print(Colors.BLUE.value + "\n CLOSE \n\n" + Colors.ENDC.value)
            res = 1
        else:
            print(Colors.RED.value + "\n ERROR \n\n" + Colors.ENDC.value)
            res = 2

    except QISKitError as ex:

        print("EXCEPCION Error = {}".format(ex))

    return res
    def executeQASM(self, filename):

        if (version.parse(__version__) > version.parse("0.5")
                and version.parse(__version__) < version.parse("0.6")):

            qc = load_qasm_file(filename)
            job_sim = execute(qc, "local_qasm_simulator")
            result = job_sim.result()
            return result._result

        elif (version.parse(__version__) > version.parse("0.6")):

            qc = load_qasm_file(filename)
            job_sim = execute(qc, Aer.get_backend("qasm_simulator"))
            result = job_sim.result()
            return result.get_counts()

        else:
            raise QiskitUnsupportedVersion(
                'Qiskit-terra version must be v0.5 or v0.6')
Beispiel #4
0
def main():
    parser = argparse.ArgumentParser()

    parser.add_argument('--file')

    args = vars(parser.parse_args())

    qc = load_qasm_file(args['file'])

    job_sim = execute(qc, "local_qasm_simulator")
    result = job_sim.result()

    print(json.dumps(result._result, indent=2, sort_keys=True))
    def executeQASM(self, filename):
        if (version.parse(__version__) >= version.parse("0.6")
                and (version.parse(__version__) < version.parse("0.7"))):

            qc = load_qasm_file(filename)
            job_sim = execute(qc, Aer.get_backend("qasm_simulator"))
            result = job_sim.result()
            return result.get_counts()

        elif (version.parse(__version__) >= version.parse("0.7")):
            qc = QuantumCircuit.from_qasm_file(filename)
            job_sim = execute(qc, Aer.get_backend("qasm_simulator"))
            result = job_sim.result()
            return result.get_counts()

        else:
            raise QiskitUnsupportedVersion(
                'Qiskit-terra version must be v0.6 or v0.7')
def qasm_compile(input, device):
    name = device["name"]

    qc = load_qasm_file(f"input/{input}.qasm")
    dag = DAGCircuit.fromQuantumCircuit(qc)

    try:
        r = transpiler.transpile(dag, coupling_map=device["topology"])
        qasm = r.qasm()
        volume, depth = r.property_summary()["size"], r.property_summary(
        )["depth"]
    except:
        qasm = ""
        volume, depth = 0, 0

    with open(f"output/{input}_{name}.qasm", "w") as f:
        f.write(qasm)
    with open(f"output/{input}_{name}.json", "w") as f:
        f.write(json.dumps({'volume': volume, 'depth': depth}))
    def test_load_qasm_file(self):
        """Test load_qasm_file and get_circuit.

        If all is correct we should get the qasm file loaded in QASM_FILE_PATH

        Previously:
            Libraries:
                from qiskit.wrapper import load_qasm_file
        """
        q_circuit = load_qasm_file(self.QASM_FILE_PATH)
        qasm_string = q_circuit.qasm()
        self.log.info(qasm_string)
        expected_qasm_string = """\
OPENQASM 2.0;
include "qelib1.inc";
qreg a[4];
qreg b[4];
creg c[4];
creg d[4];
h a[0];
h a[1];
h a[2];
h a[3];
cx a[0],b[0];
cx a[1],b[1];
cx a[2],b[2];
cx a[3],b[3];
barrier a[0],a[1],a[2],a[3];
barrier b[0],b[1],b[2],b[3];
measure a[0] -> c[0];
measure a[1] -> c[1];
measure a[2] -> c[2];
measure a[3] -> c[3];
measure b[0] -> d[0];
measure b[1] -> d[1];
measure b[2] -> d[2];
measure b[3] -> d[3];
"""
        self.assertEqual(qasm_string, expected_qasm_string)
    def test_load_qasm_file(self):
        """Test load_qasm_file and get_circuit.

        If all is correct we should get the qasm file loaded in QASM_FILE_PATH

        Previously:
            Libraries:
                from qiskit.wrapper import load_qasm_file
        """
        q_circuit = load_qasm_file(self.QASM_FILE_PATH)
        qasm_string = q_circuit.qasm()
        self.log.info(qasm_string)
        expected_qasm_string = """\
OPENQASM 2.0;
include "qelib1.inc";
qreg a[4];
qreg b[4];
creg c[4];
creg d[4];
h a[0];
h a[1];
h a[2];
h a[3];
cx a[0],b[0];
cx a[1],b[1];
cx a[2],b[2];
cx a[3],b[3];
barrier a[0],a[1],a[2],a[3];
barrier b[0],b[1],b[2],b[3];
measure a[0] -> c[0];
measure a[1] -> c[1];
measure a[2] -> c[2];
measure a[3] -> c[3];
measure b[0] -> d[0];
measure b[1] -> d[1];
measure b[2] -> d[2];
measure b[3] -> d[3];
"""
        self.assertEqual(qasm_string, expected_qasm_string)
Beispiel #9
0
"""
Example on how to use: load_qasm_file
If you want to use your local cloned repository intead of the one installed via pypi,
you have to run like this:
    examples/python$ PYTHONPATH=$PYTHONPATH:../.. python load_qasm.py
"""
from qiskit.wrapper import load_qasm_file
from qiskit import QISKitError, available_backends, execute
try:
    qc = load_qasm_file("../qasm/entangled_registers.qasm")

    # See a list of available local simulators
    print("Local backends: ", available_backends({'local': True}))

    # Compile and run the Quantum circuit on a local simulator backend
    job_sim = execute(qc, "local_qasm_simulator")
    sim_result = job_sim.result()

    # Show the results
    print("simulation: ", sim_result)
    print(sim_result.get_counts(qc))

except QISKitError as ex:
    print('There was an internal QISKit error. Error = {}'.format(ex))

    print ("load_qasm_matrix <fileName> <number of shots> ->\n" +
        " load the qassembler code in fileName and execute in the real quantum computer IBM-Q of 5 qubits from IBM\n" +
        " OPTIONAL use an exact number of shots in the computer (1024 default)")
    quit()

try:

    if len(sys.argv) > 2:
        shots = sys.argv[2]
    else:
        shots = 1024

    QX_TOKEN = APItoken
    QX_URL = config['url']

    register(QX_TOKEN, QX_URL)

    print('\033[93m' + "\nConnecting with Quantum Computer... It could take a moment\n" + '\033[0m')

    qc = load_qasm_file(sys.argv[1])

    job_exp = execute(qc, 'ibmqx4', shots=shots, max_credits=10)
    sim_result = job_exp.result()
    realValues = sim_result.get_counts(qc)

    print(realValues)

except QISKitError as ex:
    print ("EXCEPCION Error = {}".format(ex))
    
Beispiel #11
0
def probeMatrix(filename, nQubits, rowReverse, index, viewMatrix, compress, shots):
    #Debug.debug(filename + " ; " + str(nQubits) + " ; " + str(index) + " ; " + str(viewMatrix), DebugLevel.Function)

    matrix = generateMatrix(filename, nQubits, rowReverse, index, compress)

    if (viewMatrix):
        print(Colors.BLUE.value + "\nGenerated matrix\n" + str(matrix) + "\n" + Colors.ENDC.value)

    try:

        qc = load_qasm_file(filename)

        job_sim = execute(qc, "local_unitary_simulator")
        sim_result = job_sim.result()
        matrix2 = sim_result.get_unitary(qc)
        
        

        expectedValues = {}

        for i in range(2**nQubits):
            if nQubits == 2:
                st = "{0:{fill}2b}".format(i, fill=0)
            elif nQubits == 3:
                st = "{0:{fill}3b}".format(i, fill=0)
            else:
                st = "{0:{fill}5b}".format(i, fill=0)
            expectedValues[st] = np.absolute(matrix[i,0])**2


        print(Colors.PURPLE.value + "\n EXPECTED VALUES \n" + str(expectedValues) + "\n\n" + Colors.ENDC.value)

        # send the circuit to the simulator
        qc = load_qasm_file(filename)

        job_sim = execute(qc, "local_qasm_simulator", shots=shots)
        sim_result = job_sim.result()
        simuValues = sim_result.get_counts(qc)
        
        print(Colors.RED.value + "\n SIMULATED VALUES \n" + str(simuValues) + "\n\n" +  Colors.ENDC.value)


        #######################################
        # send the circuit to the real computer

        # Set your API Token.
        # You can get it from https://quantumexperience.ng.bluemix.net/qx/account,
        # looking for "Personal Access Token" section.
        QX_TOKEN = APItoken
        QX_URL = config['url']

        print(Colors.ORANGE.value + "\nConnecting with Quantum Computer... It could take a moment\n\n" +  Colors.ENDC.value)

        # Authenticate with the IBM Q API in order to use online devices.
        # You need the API Token and the QX URL.
        register(QX_TOKEN, QX_URL)

        qc = load_qasm_file(filename)

        job_exp = execute(qc, 'ibmqx4', shots=shots, max_credits=10)
        sim_result = job_exp.result()
        realValues = sim_result.get_counts(qc)

        # Compile and run the Quantum Program on a real device backend
                
        print(Colors.GREEN.value + "\n REAL VALUES \n" + str(realValues) + "\n\n" +  Colors.ENDC.value)

        keys = []
        expectedValuesArray = []
        simuValuesArray = []
        realValuesArray = []
        for i in range(2**nQubits):
            if nQubits == 2:
                st = "{0:{fill}2b}".format(i, fill=0)
            elif nQubits == 3:
                st = "{0:{fill}3b}".format(i, fill=0)
            else:
                st = "{0:{fill}5b}".format(i, fill=0)
            keys.append(st)
            
            if st in expectedValues.keys():
                expectedValuesArray.append(expectedValues[st]*shots)
            else:
                expectedValuesArray.append(0)

            if st in simuValues.keys():
                simuValuesArray.append(simuValues[st])
            else:
                simuValuesArray.append(0)

            if st in realValues.keys():
                realValuesArray.append(realValues[st])
            else:
                realValuesArray.append(0)

        _keys = np.arange(len(keys))

        ax = plt.subplot(111)
        b1 = ax.bar(_keys-0.1, expectedValuesArray,width=0.1,color='b',align='center')
        b2 = ax.bar(_keys, realValuesArray,width=0.1,color='g',align='center')
        b3 = ax.bar(_keys+0.1, simuValuesArray,width=0.1,color='y',align='center')

        ax.legend((b1[0], b2[0], b3[0]), ('Expected results', 'Real results', 'Simulated results'))

        ax.set_ylabel('Counts of computer solutions')
        ax.set_xlabel('Qubit values')

        plt.xticks(_keys, keys) # set labels manually

        plt.show()

    except QISKitError as ex:

        print ("EXCEPCION Error = {}".format(ex))
Beispiel #12
0
"""
Example on how to use: load_qasm_file

"""
from qiskit.wrapper import load_qasm_file
from qiskit import QISKitError, execute, Aer

try:
    qc = load_qasm_file("examples/qasm/entangled_registers.qasm")

    # See a list of available local simulators
    print("Aer backends: ", Aer.backends())
    sim_backend = Aer.get_backend('qasm_simulator')


    # Compile and run the Quantum circuit on a local simulator backend
    job_sim = execute(qc, sim_backend)
    sim_result = job_sim.result()

    # Show the results
    print("simulation: ", sim_result)
    print(sim_result.get_counts(qc))

except QISKitError as ex:
    print('There was an internal Qiskit error. Error = {}'.format(ex))