Esempio 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)
Esempio n. 2
0
    def setUp(self):
        self.random_seed = 10598
        self.training_data = {
            'A': np.asarray([[2.95309709, 2.51327412],
                             [3.14159265, 4.08407045]]),
            'B': np.asarray([[4.08407045, 2.26194671],
                             [4.46106157, 2.38761042]])
        }
        self.testing_data = {
            'A': np.asarray([[3.83274304, 2.45044227]]),
            'B': np.asarray([[3.89557489, 0.31415927]])
        }

        self.ref_kernel_matrix_training = np.asarray(
            [[1., 0.8388671875, 0.1142578125, 0.3564453125],
             [0.8388671875, 1., 0.1044921875, 0.427734375],
             [0.1142578125, 0.1044921875, 1., 0.66015625],
             [0.3564453125, 0.427734375, 0.66015625, 1.]])

        self.ref_kernel_matrix_testing = np.asarray(
            [[0.1357421875, 0.166015625, 0.4580078125, 0.140625],
             [0.3076171875, 0.3623046875, 0.0166015625, 0.150390625]])

        self.ref_support_vectors = np.asarray([[2.95309709, 2.51327412],
                                               [3.14159265, 4.08407045],
                                               [4.08407045, 2.26194671],
                                               [4.46106157, 2.38761042]])

        self.svm_input = get_input_instance('SVMInput')
        self.svm_input.training_dataset = self.training_data
        self.svm_input.test_dataset = self.testing_data
Esempio n. 3
0
def get_algorithm_ck(params, algo_input=None, json_output=False):
    """
    Retrieve algorithm as named in params, using params and algo_input as input data
    and returning a result dictionary
    Args:
        params (dict): Dictionary of params for algo and dependent objects
        algo_input(algorithminput): Main input data for algorithm. Optional, an algo may run entirely from params
        json_output(bool): False for regular python dictionary return, True for json conversion
    Returns:
        Result dictionary containing result of algorithm computation
    """
    _discover_on_demand()

    inputparser = InputParser(params)
    inputparser.parse()
    inputparser.validate_merge_defaults()
    logger.debug('Algorithm Input: {}'.format(json.dumps(inputparser.get_sections(), sort_keys=True, indent=4)))

    algo_name = inputparser.get_section_property(InputParser.ALGORITHM, InputParser.NAME)
    if algo_name is None:
        raise AlgorithmError('Missing algorithm name')

    if algo_name not in local_algorithms():
        raise AlgorithmError('Algorithm "{0}" missing in local algorithms'.format(algo_name))

    backend_cfg = None
    backend = inputparser.get_section_property(InputParser.BACKEND, InputParser.NAME)
    if backend is not None:
        backend_cfg = {k: v for k, v in inputparser.get_section(InputParser.BACKEND).items() if k != 'name'}
        backend_cfg['backend'] = backend

    algorithm = get_algorithm_instance(algo_name)
    algorithm.random_seed = inputparser.get_section_property(InputParser.PROBLEM, 'random_seed')
    if backend_cfg is not None:
        algorithm.setup_quantum_backend(**backend_cfg)

    algo_params = copy.deepcopy(inputparser.get_sections())

    if algo_input is None:
        input_name = inputparser.get_section_property('input', InputParser.NAME)
        if input_name is not None:
            algo_input = get_input_instance(input_name)
            input_params = copy.deepcopy(inputparser.get_section_properties('input'))
            del input_params[InputParser.NAME]
            convert_json_to_dict(input_params)
            algo_input.from_params(input_params)

    algorithm.init_params(algo_params, algo_input)

    return algorithm
Esempio n. 4
0
 def setUp(self):
     np.random.seed(50)
     pauli_dict = {
         'paulis': [{
             "coeff": {
                 "imag": 0.0,
                 "real": -1.052373245772859
             },
             "label": "II"
         }, {
             "coeff": {
                 "imag": 0.0,
                 "real": 0.39793742484318045
             },
             "label": "ZI"
         }, {
             "coeff": {
                 "imag": 0.0,
                 "real": -0.39793742484318045
             },
             "label": "IZ"
         }, {
             "coeff": {
                 "imag": 0.0,
                 "real": -0.01128010425623538
             },
             "label": "ZZ"
         }, {
             "coeff": {
                 "imag": 0.0,
                 "real": 0.18093119978423156
             },
             "label": "XX"
         }]
     }
     qubitOp = Operator.load_from_dict(pauli_dict)
     self.algo_input = get_input_instance('EnergyInput')
     self.algo_input.qubit_op = qubitOp
Esempio n. 5
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)
Esempio n. 6
0
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================

from qiskit_acqua import Operator, run_algorithm
from qiskit_acqua.input import get_input_instance

pauli_dict = {
    'paulis': [{"coeff": {"imag": 0.0, "real": -1.052373245772859},
                "label": "II"},
               {"coeff": {"imag": 0.0, "real": 0.39793742484318045},
                "label": "ZI"},
               {"coeff": {"imag": 0.0, "real": -0.39793742484318045},
                "label": "ZZ"},
               {"coeff": {"imag": 0.0, "real": 0.18093119978423156},
                "label": "XX"}
               ]
}
algo_input = get_input_instance('EnergyInput')
algo_input.qubit_op = Operator.load_from_dict(pauli_dict)
params = {
    'algorithm': {'name': 'VQE'},
    'optimizer': {'name': 'SPSA'},
    'variational_form': {'name': 'RY', 'depth': 5},
    'backend': {'name': 'local_qasm_simulator'}
}
result = run_algorithm(params, algo_input)
print(result['energy'])
Esempio n. 7
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()