コード例 #1
0
ファイル: training_13.py プロジェクト: Holly-Jiang/k7m
def benchmark(depth, trail, parameters):

    if gdv_name == "TFL":
        folder = "BNTF"
        depth_string = "{:02}".format(depth)
        name_end = "TFL"
        if nr_qubits == 54:
            name_end = "QSE"

    elif gdv_name == "QSE":
        folder = "BSS"
        depth_string = "{:03}".format(depth)
        name_end = "QSE"

    # if nr_qubits==54:
    #     gdv_name = "QSE"

    qasm_file_name = "_private_benchmark/{}/{}QBT_{}CYC_{}_{}.qasm".format(
        folder, nr_qubits, depth_string, name_end, trail)

    solution_file_name = "_private_benchmark/meta/{}QBT_{}CYC_{}_{}_solution.csv".format(
        nr_qubits, depth_string, name_end, trail)

    # print("qiskit", depth)
    # input qasm file as circuit
    test_circuit = qiskit.QuantumCircuit.from_qasm_file(qasm_file_name)
    """
        Construct the optimal initial mapping
    """
    qiskit_layout_dict = dict()
    original_nodes = list()
    with open(solution_file_name, 'r') as csvfile:
        for original_node in csv.reader(csvfile, delimiter=','):
            original_nodes.append(literal_eval(original_node[0]))
    csvfile.close()
    # print(original_nodes)

    for i in range(len(original_nodes)):
        qiskit_layout_dict[test_circuit.qregs[0][i]] = original_nodes[i]
    # construct passes that use the optimal initial mapping and BasicSwap
    # however, no swapping gates should be ever necessary
    original_pm = PassManager()
    # print(original_nodes)
    qiskit_coupling_map = CouplingMap(
        couplinglist=connection_list[qubits[nr_qubits]])
    optimal_layout = Layout()
    optimal_layout.from_dict(qiskit_layout_dict)
    original_pm.append([
        SetLayout(optimal_layout),
        ApplyLayout(),
        BasicSwap(qiskit_coupling_map)
    ])
    map_original_circuit = original_pm.run(test_circuit)
    optimal_depth = map_original_circuit.depth()
    # print("optimal mapping: the circuit has", optimal_depth, "cycles")
    # print(map_original_circuit.draw(style="text"))
    # construct passes that use the DenseLayout+StochasticSwap without initial mapping
    """
       K7M 
    """
    gate_costs = {
        'id': 0,
        'u1': 0,
        'measure': 0,
        'reset': 0,
        'barrier': 0,
        'u2': 1,
        'u3': 1,
        'U': 1,
        "ok": 0,
        # update the costs
        "rev_cnot": 4 * 1 + 10,  # 4 u2/hadamard + 1 cnot
        "swap": 3 * 10 + 4,  # 4 u2/hadamard + 3 cnot
        'seed': 19
    }  # pass the seed through gate costs

    # parameters_string = str(parameters)

    # the number of qubits in the device
    parameters["nisq_qubits"] = qiskit_coupling_map.size()
    # Add the gate costs
    parameters["gate_costs"] = gate_costs
    # Should the initial mapping be chosen random?
    parameters["initial_map"] = K7MInitialMapping.HEURISTIC
    parameters["unidirectional_coupling"] = False
    parameters["dry_run"] = False

    k7mcomp = K7MCompiler(connection_list[qubits[nr_qubits]], parameters)

    execution_time = time.time()
    map_test_circuit, init_time, init_map = k7mcomp.run(test_circuit)
    execution_time = time.time() - execution_time

    if (map_test_circuit is None) and (init_map is None):
        # this happens when the execution was interrupted
        return optimal_depth, -1, execution_time, init_time, -1, -1

    # print(map_test_circuit.draw(output="text", fold=-1))
    # tmp_circuit = map_test_circuit.decompose()
    tmp_circuit = map_test_circuit
    # print(tmp_circuit.draw(output="text", fold=-1))
    # tmp_circuit = qiskit_to_tk(map_test_circuit)
    # Transform.RebaseToQiskit().DecomposeSWAPtoCX().apply(tmp_circuit)
    depth_result = tmp_circuit.depth()

    # print("k7m mapping: the circuit has", depth_result, "cycles")
    # print(map_test_circuit.draw(style="text"))
    # accumulate result
    # print("----")

    nr_t1 = noOfTranspositions(list(range(nr_qubits)), original_nodes,
                               nr_qubits)
    nr_t2 = noOfTranspositions(original_nodes, init_map, nr_qubits)

    return optimal_depth, depth_result, execution_time, init_time, nr_t1, nr_t2
コード例 #2
0
ファイル: run_benchmark.py プロジェクト: lmsasu/k7m
def benchmark(depth, trail, varying_param):

    # qasm_file_name = "_private_benchmark/BNTF/16QBT_{:02}CYC_{}_{}.qasm".format(
    #     depth, gdv_name, trail)
    #
    # solution_file_name = "_private_benchmark/meta/16QBT_{:02}CYC_{}_{}_solution.csv".format(
    #     depth, gdv_name, trail)

    if gdv_name == "TFL":
        folder = "BNTF"
        depth_string = "{:02}".format(depth)
        name_end = "TFL"
        if nr_qubits == 54:
            name_end = "QSE"

    elif gdv_name == "QSE":
        folder = "BSS"
        depth_string = "{:03}".format(depth)
        name_end = "QSE"

    # if nr_qubits==54:
    #     gdv_name = "QSE"

    qasm_file_name = "_private_benchmark/{}/{}QBT_{}CYC_{}_{}.qasm".format(
        folder, nr_qubits, depth_string, name_end, trail)

    solution_file_name = "_private_benchmark/meta/{}QBT_{}CYC_{}_{}_solution.csv".format(
        nr_qubits, depth_string, name_end, trail)

    # print("qiskit", depth)
    # input qasm file as circuit
    test_circuit = qiskit.QuantumCircuit.from_qasm_file(qasm_file_name)
    """
        Construct the optimal initial mapping
    """
    qiskit_layout_dict = dict()
    original_nodes = list()
    with open(solution_file_name, 'r') as csvfile:
        for original_node in csv.reader(csvfile, delimiter=','):
            original_nodes.append(literal_eval(original_node[0]))
    csvfile.close()
    print(original_nodes)

    for i in range(len(original_nodes)):
        qiskit_layout_dict[test_circuit.qregs[0][i]] = original_nodes[i]
    # construct passes that use the optimal initial mapping and BasicSwap
    # however, no swapping gates should be ever necessary
    original_pm = PassManager()
    # print(original_nodes)
    qiskit_coupling_map = CouplingMap(
        couplinglist=connection_list[qubits[nr_qubits]])
    optimal_layout = Layout()
    optimal_layout.from_dict(qiskit_layout_dict)
    original_pm.append([
        SetLayout(optimal_layout),
        ApplyLayout(),
        BasicSwap(qiskit_coupling_map)
    ])
    map_original_circuit = original_pm.run(test_circuit)
    optimal_depth = map_original_circuit.depth()
    print("optimal mapping: the circuit has", optimal_depth, "cycles")
    # print(map_original_circuit.draw(style="text"))
    # construct passes that use the DenseLayout+StochasticSwap without initial mapping
    """
       K7M 
    """
    gate_costs = {
        'id': 0,
        'u1': 0,
        'measure': 0,
        'reset': 0,
        'barrier': 0,
        'u2': 1,
        'u3': 1,
        'U': 1,
        "ok": 0,
        # update the costs
        "rev_cnot": 4 * 1 + 10,  # 4 u2/hadamard + 1 cnot
        "swap": 3 * 10 + 4,  # 4 u2/hadamard + 3 cnot
        'seed': 19
    }  # pass the seed through gate costs

    parameters = {
        # maximum depth of the search tree
        # after this depth, the leafs are evaluated
        # and only the path with minimum cost is kept in the tree
        # thus, the tree is pruned
        "max_depth": test_circuit.n_qubits // 2,
        # "max_depth": test_circuit.n_qubits/4,

        # maximum number of children of a node
        # "max_children": qiskit_coupling_map.size(),
        "max_children": 2,

        # the first number_of_qubits * this factor the search maximises the cost
        # afterwards it minimises it
        "opt_max_t_min": False,
        "qubit_increase_factor": 3,
        "option_skip_cx": False,
        "penalty_skip_cx": 20,
        "opt_div_by_act": False,

        # later changes in the mapping should not affect
        # the initial mapping of the circuit
        "opt_att": True,
        # b \in [0, 10]
        "att_b": -10,
        # c \in [0, 1]
        "att_c": 1,
        "div_dist": 2,
        "cx": 0.01
    }

    parameters_string = str(parameters)

    # the number of qubits in the device
    parameters["nisq_qubits"] = qiskit_coupling_map.size()
    # Add the gate costs
    parameters["gate_costs"] = gate_costs
    # Should the initial mapping be chosen random?
    parameters["initial_map"] = K7MInitialMapping.HEURISTIC
    parameters["unidirectional_coupling"] = False
    parameters["dry_run"] = False

    k7mcomp = K7MCompiler(connection_list[qubits[nr_qubits]], parameters)

    execution_time = time.time()
    map_test_circuit, init_time = k7mcomp.run(test_circuit)
    execution_time = time.time() - execution_time

    # print(map_test_circuit.draw(output="text", fold=-1))
    # tmp_circuit = map_test_circuit.decompose()
    tmp_circuit = map_test_circuit
    # print(tmp_circuit.draw(output="text", fold=-1))
    # tmp_circuit = qiskit_to_tk(map_test_circuit)
    # Transform.RebaseToQiskit().DecomposeSWAPtoCX().apply(tmp_circuit)
    depth_result = tmp_circuit.depth()

    print("k7m mapping: the circuit has", depth_result, "cycles")
    # print(map_test_circuit.draw(style="text"))
    # accumulate result
    print("----")

    file_op_type = "a"
    global first_run
    if first_run:
        file_op_type = "w"
    first_run = False

    with open(
            "_private_data/BNTF/_{}_{}_{}.csv".format(name_end,
                                                      qubits[nr_qubits],
                                                      parameters_string),
            file_op_type) as csvFile:
        writer = csv.writer(csvFile)
        writer.writerow(
            [trail, "k7m", optimal_depth, depth_result, execution_time])

    return optimal_depth, depth_result, execution_time, init_time
コード例 #3
0
ファイル: run_benchmark.py プロジェクト: Holly-Jiang/k7m
def benchmark(depth, trail, varying_param):

    # qasm_file_name = "_private_benchmark/BNTF/16QBT_{:02}CYC_{}_{}.qasm".format(
    #     depth, gdv_name, trail)
    #
    # solution_file_name = "_private_benchmark/meta/16QBT_{:02}CYC_{}_{}_solution.csv".format(
    #     depth, gdv_name, trail)

    if gdv_name == "TFL":
        folder = "BNTF"
        depth_string = "{:02}".format(depth)
        name_end = "TFL"
        if nr_qubits == 54:
            name_end = "QSE"

    elif gdv_name == "QSE":
        folder = "BSS"
        depth_string = "{:03}".format(depth)
        name_end = "QSE"

    # if nr_qubits==54:
    #     gdv_name = "QSE"

    qasm_file_name = "_private_benchmark/{}/{}QBT_{}CYC_{}_{}.qasm".format(
        folder, nr_qubits, depth_string, name_end, trail)

    solution_file_name = "_private_benchmark/meta/{}QBT_{}CYC_{}_{}_solution.csv".format(
        nr_qubits, depth_string, name_end, trail)

    # print("qiskit", depth)
    # input qasm file as circuit
    test_circuit = qiskit.QuantumCircuit.from_qasm_file(qasm_file_name)


    """
        Construct the optimal initial mapping
    """
    qiskit_layout_dict = dict()
    original_nodes = list()
    with open(solution_file_name, 'r') as csvfile:
        for original_node in csv.reader(csvfile, delimiter=','):
            original_nodes.append(literal_eval(original_node[0]))
    csvfile.close()
    print(original_nodes)

    for i in range(len(original_nodes)):
        qiskit_layout_dict[test_circuit.qregs[0][i]] = original_nodes[i]
    # construct passes that use the optimal initial mapping and BasicSwap
    # however, no swapping gates should be ever necessary
    original_pm = PassManager()
    # print(original_nodes)
    qiskit_coupling_map = CouplingMap(couplinglist=connection_list[qubits[nr_qubits]])
    optimal_layout = Layout()
    optimal_layout.from_dict(qiskit_layout_dict)
    original_pm.append([SetLayout(optimal_layout),
                        ApplyLayout(),
                        BasicSwap(qiskit_coupling_map)])
    map_original_circuit = original_pm.run(test_circuit)
    optimal_depth = map_original_circuit.depth()
    print("optimal mapping: the circuit has", optimal_depth, "cycles")
    # print(map_original_circuit.draw(style="text"))
    # construct passes that use the DenseLayout+StochasticSwap without initial mapping


    """
       K7M 
    """
    gate_costs = {'id': 0, 'u1': 0, 'measure': 0,
                  'reset': 0, 'barrier': 0,
                  'u2': 1, 'u3': 1, 'U': 1,

                  "ok": 0,
                  # update the costs
                  "rev_cnot": 4 * 1 + 10,  # 4 u2/hadamard + 1 cnot
                  "swap": 3 * 10 + 4,  # 4 u2/hadamard + 3 cnot

                  'seed': 19}  # pass the seed through gate costs

    """
    20 secunde
    4.093154 :: attr_b=5.00,attr_c=0.61,edge_cost=0.20,max_breadth=4,max_depth=9,movement_factor=2
    
    5 secunde
    4.138454 :: attr_b=17.30,attr_c=0.25,edge_cost=0.20,max_breadth=3,max_depth=9,movement_factor=4
    
    0.5 secunde
    4.322774 :: attr_b=8.00,attr_c=0.02,edge_cost=0.20,max_breadth=2,max_depth=9,movement_factor=2
    
    0.05 secunde
    4.464655 :: attr_b=3.50,attr_c=0.31,edge_cost=0.90,max_breadth=2,max_depth=6,movement_factor=6
    
    # Lucian
    2.424873 for [-w9 -d9 -b1.50 -c0.32 -e0.80 -m10]
    """

    parameters = {
        "att_b": 15,
        "att_c": 0,

        "cx": 0.8,

        "max_children": 2,
        "max_depth": 9,

        "div_dist": 10,

        # UNUSED
        "opt_att": True,
        "opt_max_t_min": False,
        "qubit_increase_factor": 3,
        "option_skip_cx": False,
        "penalty_skip_cx": 20,
        "opt_div_by_act": False,

        "TIME_LIMIT": 600  # seconds
    }

    parameters_string = str(parameters)

    # the number of qubits in the device
    parameters["nisq_qubits"] = qiskit_coupling_map.size()
    # Add the gate costs
    parameters["gate_costs"] = gate_costs
    # Should the initial mapping be chosen random?
    parameters["initial_map"] = K7MInitialMapping.HEURISTIC
    parameters["unidirectional_coupling"]=False
    parameters["dry_run"] = False

    k7mcomp = K7MCompiler(connection_list[qubits[nr_qubits]], parameters)

    execution_time = time.time()
    map_test_circuit, init_time, init_map = k7mcomp.run(test_circuit)
    execution_time = time.time() - execution_time

    if (map_test_circuit is None) and (init_map is None):
        # this happens when the execution was interrupted
        # Will not write to file of results. So the averages are not affected
        # by the interrupted experiments
        return optimal_depth, -1, execution_time, init_time, -1, -1

    depth_result = map_test_circuit.depth()

    print("k7m mapping: the circuit has", depth_result, "cycles")
    # print(map_test_circuit.draw(style="text"))
    # accumulate result
    print("----")

    file_op_type = "a"
    global first_run
    if first_run:
        file_op_type = "w"
    first_run = False

    with open(
            "_private_data/BNTF/_{}_{}.csv".format(name_end,
                                                   qubits[nr_qubits],
                                                   ),
            file_op_type) as csvFile:
        writer = csv.writer(csvFile)
        writer.writerow([trail, "k7m", optimal_depth, depth_result, execution_time])

    return optimal_depth, depth_result, execution_time, init_time
コード例 #4
0
def twospin_df(J, Bx, dB, Bz_max, dt_steps, dt_steps_bool, gamma, skip,
               provider, backend, pq1, pq2):
    count_list = []
    calibrated_count_list = []
    tarray, Bzarray, dt_or_steps, _ = adiabaticramp(J, Bx, dB, Bz_max,
                                                    dt_steps, dt_steps_bool,
                                                    gamma)

    if dt_steps_bool == 'dt':
        dt = dt_steps
    else:
        dt = dt_or_steps

    thetaarray, _ = theta(Bzarray, dt)

    # Calibration Matrix
    meas_calibs, state_labels = complete_meas_cal(qubit_list=[0, 1],
                                                  qr=QuantumRegister(2),
                                                  circlabel='2spin')
    cal_results = execute(meas_calibs,
                          backend=provider.get_backend(backend),
                          shots=1000).result()
    meas_calibs, state_labels = complete_meas_cal(qubit_list=[0, 1],
                                                  qr=QuantumRegister(2),
                                                  circlabel='2spin')
    meas_fitter = CompleteMeasFitter(cal_results,
                                     state_labels,
                                     circlabel='2spin')
    meas_fitter.plot_calibration()

    qmap = Layout()

    i = 0
    while (i < len(thetaarray)):
        print('Bz = %f' % (Bzarray[i]))
        qr = QuantumRegister(2, 'qr')
        cr = ClassicalRegister(2, 'cr')
        circ = QuantumCircuit(qr, cr)
        qmap.from_dict(input_dict={qr[0]: pq1, qr[1]: pq2})
        circ.initialize([0, 0, 0, 1], [0, 1])

        twospin_instruction(circ, J, Bx, thetaarray[:i + 1], dt)
        circ.measure([0, 1], [0, 1])

        result = execute(circ, provider.get_backend(backend),
                         shots=5000).result()
        counts = result.get_counts()
        counts['Time'] = tarray[i]
        counts['Bz'] = Bzarray[i]
        count_list.append(counts)
        with open("count_list.txt", "w") as output:
            output.write(str(count_list))

        mitigated_counts = meas_fitter.filter.apply(result).get_counts()
        mitigated_counts['Time'] = tarray[i]
        mitigated_counts['Bz'] = Bzarray[i]
        calibrated_count_list.append(mitigated_counts)
        with open("calibrated_count_list.txt", "w") as output:
            output.write(str(calibrated_count_list))

        i = i + 1 + skip

    # Creating dataframe
    df = pd.DataFrame(count_list)
    time_col = df.pop('Time')
    df.insert(0, 'Time', time_col)
    df['Exact'] = exactm(J, Bx, Bzarray, dt)
    df['Interaction'] = interactionm(J, Bx, thetaarray, dt)

    calibrated_df = pd.DataFrame(calibrated_count_list)
    time_col = df.pop('Time')
    df.insert(0, 'Time', time_col)

    if '00' not in df:
        df['00'] = 0
    if '01' not in df:
        df['01'] = 0
    if '10' not in df:
        df['10'] = 0
    if '11' not in df:
        df['11'] = 0
    df = df.fillna(0)

    if '00' not in calibrated_df:
        calibrated_df['00'] = 0
    if '01' not in calibrated_df:
        calibrated_df['01'] = 0
    if '10' not in calibrated_df:
        calibrated_df['10'] = 0
    if '11' not in calibrated_df:
        calibrated_df['11'] = 0
    calibrated_df = calibrated_df.fillna(0)

    # Calculating mz
    total = df['00'] + df['01'] + df['10'] + df['11']
    df['mz'] = -(df['00'] / total - df['11'] / total)
    calibrated_df['mz'] = -(df['00'] / total - df['11'] / total)

    # Creating Files
    if dt_steps_bool == 'dt':
        df.to_csv(
            'J={:.3f} Bx={:.3f} dB={:.3f} BzMax={:.3f} dt={:.3f} gamma={:.3f}.csv'
            .format(J, Bx, dB, Bz_max, dt_steps, gamma))
        calibrated_df.to_csv(
            'Calibrated J={:.3f} Bx={:.3f} dB={:.3f} BzMax={:.3f} dt={:.3f} gamma={:.3f}.csv'
            .format(J, Bx, dB, Bz_max, dt_steps, gamma))
    else:
        df.to_csv(
            'J={:.3f} Bx={:.3f} dB={:.3f} BzMax={:.3f} BzSteps={:.3f} gamma={:.3f}.csv'
            .format(J, Bx, dB, Bz_max, dt_steps, gamma))
        calibrated_df.to_csv(
            'Calibrated J={:.3f} Bx={:.3f} dB={:.3f} BzMax={:.3f} BzSteps={:.3f} gamma={:.3f}.csv'
            .format(J, Bx, dB, Bz_max, dt_steps, gamma))

    return df, dt_or_steps, thetaarray