Ejemplo n.º 1
0
def main():
    sample_Total, training_input, test_input, class_labels = \
        ad_hoc_data(training_size=20, test_size=10, n=2,  # 2 is the dimension of each data point
                    gap=0.3, PLOT_DATA=False)

    total_array, label_to_labelclass = get_points(test_input, class_labels)

    params = {
        'problem': {
            'name': 'svm_classification'
        },
        'backend': {
            'name': 'local_qasm_simulator',
            'shots': 1024
        },
        'algorithm': {
            'name': 'SVM_QKernel',
            'print_info': True
        }
    }

    algo_input = get_input_instance('SVMInput')
    algo_input.training_dataset = training_input
    algo_input.test_dataset = test_input
    algo_input.datapoints = total_array
    result = run_algorithm(params, algo_input)
    print(result)
Ejemplo n.º 2
0
 def test_ee_via_run_algorithm(self):
     params = {'algorithm': {'name': 'ExactEigensolver'}}
     result = run_algorithm(params, self.algo_input)
     self.assertAlmostEqual(result['energy'], -1.85727503)
     np.testing.assert_array_almost_equal(result['energies'], [-1.85727503])
     np.testing.assert_array_almost_equal(result['eigvals'],
                                          [-1.85727503 + 0j])
Ejemplo n.º 3
0
    def test_svm_qkernel_via_run_algorithm(self):

        params = {
            'problem': {
                'name': 'svm_classification',
                'random_seed': self.random_seed
            },
            'algorithm': {
                'name': 'SVM_QKernel'
            },
            'backend': {
                'name': 'local_qasm_simulator',
                'shots': 1024
            }
        }
        result = run_algorithm(params, self.svm_input)

        np.testing.assert_array_almost_equal(result['kernel_matrix_training'],
                                             self.ref_kernel_matrix_training,
                                             decimal=4)
        np.testing.assert_array_almost_equal(result['kernel_matrix_testing'],
                                             self.ref_kernel_matrix_testing,
                                             decimal=4)

        self.assertEqual(len(result['svm']['support_vectors']), 4)
        np.testing.assert_array_almost_equal(result['svm']['support_vectors'],
                                             self.ref_support_vectors,
                                             decimal=4)

        self.assertEqual(result['test_success_ratio'], 0.5)
    def run(self, input, output=None):
        if input is None:
            raise ACQUAChemistryError("Missing input.")

        self._parser = InputParser(input)
        self._parser.parse()
        driver_return = self._run_driver_from_parser(self._parser, False)
        if driver_return[0] == ACQUAChemistry._DRIVER_RUN_TO_HDF5:
            logger.info('No further process.')
            return {'printable': [driver_return[1]]}

        data = run_algorithm(driver_return[1], driver_return[2], True)
        if not isinstance(data, dict):
            raise ACQUAChemistryError(
                "Algorithm run result should be a dictionary")

        if logger.isEnabledFor(logging.DEBUG):
            logger.debug('Algorithm returned: {}'.format(
                json.dumps(data, indent=4)))

        convert_json_to_dict(data)
        lines, result = self._format_result(data)
        logger.info('Processing complete. Final result available')
        result['printable'] = lines

        if output is not None:
            with open(output, 'w') as f:
                for line in lines:
                    print(line, file=f)

        return result
Ejemplo n.º 5
0
 def test_ee_via_run_algorithm_k4(self):
     params = {'algorithm': {'name': 'ExactEigensolver', 'k': 4}}
     result = run_algorithm(params, self.algo_input)
     self.assertAlmostEqual(result['energy'], -1.85727503)
     self.assertEqual(len(result['eigvals']), 4)
     self.assertEqual(len(result['eigvecs']), 4)
     np.testing.assert_array_almost_equal(
         result['energies'],
         [-1.85727503, -1.24458455, -0.88272215, -0.22491125])
Ejemplo n.º 6
0
    def test_run_algorithm(self):
        filepath = self._get_resource_path('ExactEigensolver.json')
        params = None
        with open(filepath) as json_file:
            params = json.load(json_file)

        dict_ret = None
        try:
            dict_ret = run_algorithm(params, None, False)
        except Exception as e:
            self.fail(str(e))

        self.assertIsInstance(dict_ret, dict)
    def run_algorithm_from_json(self, params, output=None):
        ret = run_algorithm(params, None, True)
        if not isinstance(ret, dict):
            raise ACQUAChemistryError(
                "Algorithm run result should be a dictionary")

        logger.debug('Algorithm returned: {}'.format(json.dumps(ret,
                                                                indent=4)))
        convert_json_to_dict(ret)
        print('Output:')
        if isinstance(ret, dict):
            for k, v in ret.items():
                print("'{}': {}".format(k, v))
        else:
            print(ret)

        return ret
    def test_end2end_H2(self, name, optimizer, backend, mode, shots):

        optimizer_params = {'name': optimizer}
        if optimizer == 'COBYLA':
            optimizer_params['maxiter'] = 1000
        elif optimizer == 'SPSA':
            optimizer_params['max_trials'] = 2000
            optimizer_params['save_steps'] = 25

        algo_params = {'problem': {'name': 'energy'},
                    'backend': {'name': backend, 'shots': shots},
                    'algorithm': {'name': 'VQE'},
                    'optimizer': optimizer_params,
                    'variational_form': {'name': 'RYRZ', 'depth': 5, 'entanglement': 'full'}
                    }

        results = run_algorithm(algo_params, self.algo_input)
        self.assertAlmostEqual(results['energy'], self.reference_energy)
Ejemplo n.º 9
0
def run(currentTest):
    params = {
        'problem': {
            'name': 'search'
        },
        'algorithm': {
            'name': 'Grover'
        },
        'oracle': {
            'name': 'SAT',
            'cnf': currentTest
        },
        'backend': {
            'name': 'local_qasm_simulator'
        }
    }

    result = run_algorithm(params)
    print(result['result'])
Ejemplo n.º 10
0
def runGrover(r=rules):
    params = {
        'problem': {
            'name': 'search'
        },
        'algorithm': {
            'name': 'Grover'
        },
        'oracle': {
            'name': 'SAT',
            'cnf': r
        },
        'backend': {
            'name': 'local_qasm_simulator'
        }
    }

    print("Starting Grover search")
    result = run_algorithm(params)
    print(result['result'])
    return result['result']
Ejemplo n.º 11
0
def main():
    parser = argparse.ArgumentParser(
        description='QISKit ACQUA Command Line Tool')
    parser.add_argument('input',
                        metavar='input',
                        help='Algorithm JSON input file')
    parser.add_argument('-jo',
                        metavar='output',
                        help='Algorithm JSON output file name',
                        required=False)

    args = parser.parse_args()

    preferences = Preferences()
    if preferences.get_logging_config() is None:
        logging_config = build_logging_config(['qiskit_acqua'], logging.INFO)
        preferences.set_logging_config(logging_config)
        preferences.save()

    set_logger_config(preferences.get_logging_config())

    params = None
    with open(args.input) as json_file:
        params = json.load(json_file)

    ret = run_algorithm(params, None, True)

    if args.jo is not None:
        with open(args.jo, 'w') as f:
            print('{}'.format(ret), file=f)
    else:
        convert_json_to_dict(ret)
        print(
            '\n\n--------------------------------- R E S U L T ------------------------------------\n'
        )
        if isinstance(ret, dict):
            for k, v in ret.items():
                print("'{}': {}".format(k, v))
        else:
            print(ret)
Ejemplo n.º 12
0
from qiskit_acqua.input import get_input_instance
from qiskit_acqua import run_algorithm



sample_Total, training_input, test_input, class_labels = \
Wine(training_size=40, test_size=10, n=2, # 2 is the dimension of each data point
            PLOT_DATA=False)
total_array, label_to_labelclass = get_points(test_input, class_labels)

params = {
    'problem': {
        'name': 'svm_classification'
    },
    'backend': {
        'name': 'local_qasm_simulator',
        'shots': 1000
    },
    'algorithm': {
        'name': 'QuantumSVM_OneAgainstRest',
        'print_info': True
    }
}

algo_input = get_input_instance('SVMInput')
algo_input.training_dataset = training_input
algo_input.test_dataset = test_input
algo_input.datapoints = total_array
result = run_algorithm(params, algo_input)
print(result)
Ejemplo n.º 13
0
        'name': 'search'
    },
    'algorithm': {
        'name': 'Grover'
    },
    'oracle': {
        'name': 'SAT',
        'cnf': risk_sat
    },
    'backend': {
        'name': 'local_qasm_simulator'
    }
}

start = time.time()
result = run_algorithm(params)
end = time.time()

print('job took {} seconds'.format(end - start))
answer = result['result']
print("{} or {}".format(answer, convert(answer)))

# classical version search
arr = np.zeros(NUM_ITEMS)
db = [int(num) for num in arr]
db[location] = 1
start = time.time()
for i, val in enumerate(db):
    if val == 1:
        print(i)
        break
Ejemplo n.º 14
0
def maxCut(graph=None, n=5):

    G = graph

    # if Graph isn't provided, create a sample one
    if G is None:
        G = makeGraph(num=n)

    # colour every node red and show the starting graph
    colors = ['r' for _ in G.nodes()]
    pos = nx.spring_layout(G)
    default_axes = plt.axes(frameon=True)
    nx.draw_networkx(G,
                     node_color=colors,
                     node_size=600,
                     alpha=.8,
                     ax=default_axes,
                     pos=pos)
    plt.show()

    # Computing the weight matrix from the graph and display it
    w = np.zeros([n, n])
    for i in range(n):
        for j in range(n):
            temp = G.get_edge_data(i, j, default=0)
            if temp != 0:
                w[i, j] = temp['weight']
    print(w)

    # Map to Ising problem
    qubitOp, offset = maxcut.get_maxcut_qubitops(w)
    algo_input = get_input_instance('EnergyInput')
    algo_input.qubit_op = qubitOp

    algorithm_cfg = {'name': 'VQE', 'operator_mode': 'grouped_paulis'}

    optimizer_cfg = {'name': 'SPSA', 'max_trials': 300}

    var_form_cfg = {'name': 'RY', 'depth': 5, 'entanglement': 'linear'}

    params = {
        'problem': {
            'name': 'ising',
            'random_seed': 10598
        },
        'algorithm': algorithm_cfg,
        'optimizer': optimizer_cfg,
        'variational_form': var_form_cfg,
        'backend': {
            'name': 'local_qasm_simulator',
            'shots': 100
        }
    }

    # run the algorithm and print the results
    result = run_algorithm(params, algo_input)
    x = maxcut.sample_most_likely(len(w), result['eigvecs'][0])
    print('energy:', result['energy'])
    print('time:', result['eval_time'])
    print('maxcut objective:', result['energy'] + offset)
    print('solution:', maxcut.get_graph_solution(x))
    print('solution objective:', maxcut.maxcut_value(x, w))
    plot_histogram(result['eigvecs'][0])

    # colour the nodes that don't recieve a freebie red, else blue
    colors = [
        'r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)
    ]
    nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos)
    plt.show()