def test_state_to_latex_for_large_sparse_statevector(self):
     """Test conversion of large sparse state vector"""
     sv = Statevector(np.eye(2 ** 15, 1))
     latex_representation = state_to_latex(sv)
     self.assertEqual(latex_representation, " |000000000000000\\rangle")
Esempio n. 2
0
def fidelity(vec1, vec2):
    sv1 = Statevector(vec1)
    sv2 = Statevector(vec2)
    return state_fidelity(sv1, sv2)
Esempio n. 3
0
if __name__ == '__main__':
    import numpy as np
    from qiskit import Aer
    from qiskit.aqua.algorithms.minimum_eigen_solvers import VQSD
    from qiskit.quantum_info.states import Statevector
    from qiskit.aqua.components.initial_states import Custom
    from qiskit.aqua.components.optimizers import COBYLA
    from qiskit.aqua.operators import MatrixOperator
    from qiskit.aqua.algorithms.eigen_solvers import NumPyEigensolver
    from qiskit.aqua.components.variational_forms import RY
    from qiskit.quantum_info import partial_trace

    num_ancillae = 1
    state_vector = np.sqrt(6/10) * Statevector.from_label('+1+') \
        + np.sqrt(4/10) * Statevector.from_label('-0-')
    initial_state = Custom(state_vector.num_qubits,
                           state_vector=state_vector.data)
    vqsd_obj = VQSD(initial_state,
                    q=.25,
                    num_ancillae=num_ancillae,
                    quantum_instance=Aer.get_backend("qasm_simulator"),
                    optimizer=COBYLA(),
                    var_form=RY(initial_state._num_qubits - num_ancillae,
                                depth=2))
    result = vqsd_obj.run(shots=1000)

    print("=== VQSD ===")
    print(result.eigenvalue)
    print(result.eigenstate)

    print("== Exact ===")
Esempio n. 4
0
    def _cost_evaluation(self, parameters):
        """
        Evaluate cost function at given parameters for the variational form.
        Args:
            parameters (numpy.ndarray): parameters for variational form.
        Returns:
            Union(float, list[float]): cost objective function value of each parameter.
        """
        num_parameter_sets = len(parameters) // self._var_form.num_parameters
        parameter_sets = np.split(parameters, num_parameter_sets)
        global_objs = []
        local_objs = []
        weighted_objs = []

        def _build_parameterized_circuits():
            if self._var_form.support_parameterized_circuit and \
                    self._parameterized_circuits is not None:
                parameterized_circuits = self.construct_circuit(
                    self._var_form_params,
                    statevector_mode=self._quantum_instance.is_statevector,
                    use_simulator_snapshot_mode=self._use_simulator_snapshot_mode)

                self._parameterized_circuits = \
                    self._quantum_instance.transpile(parameterized_circuits)

        _build_parameterized_circuits()
        circuits = []
        # binding parameters here since the circuits had been transpiled
        if self._parameterized_circuits is not None:
            for idx, parameter in enumerate(parameter_sets):
                curr_param = {self._var_form_params: parameter}
                for qc in self._parameterized_circuits:
                    tmp = qc.bind_parameters(curr_param)
                    tmp.name = str(idx) + '_' + tmp.name
                    circuits.append(tmp)
            to_be_simulated_circuits = circuits
        else:
            for idx, parameter in enumerate(parameter_sets):
                circuit = self.construct_circuit(
                    parameter,
                    statevector_mode=self._quantum_instance.is_statevector,
                    use_simulator_snapshot_mode=self._use_simulator_snapshot_mode,
                    circuit_name_prefix=str(idx))
                circuits.append(circuit)
            to_be_simulated_circuits = functools.reduce(lambda x, y:
                                                        x + y, circuits)

        start_time = time()
        result = self._quantum_instance.execute(to_be_simulated_circuits,
                                                self._parameterized_circuits
                                                is not None)

        for idx, _ in enumerate(parameter_sets):
            # Evaluate with result
            circuits = list(filter(lambda circ:
                                   circ.name.startswith('{}_'.format(idx)),
                                   to_be_simulated_circuits))

            # DIP test circuits
            dip_test_circuit = circuits[0]

            # PDIP circuits
            pdip_test_circuits = circuits[1:]

            # evaluate with results
            dip_test_counts = None
            pdip_test_counts = None
            if self._quantum_instance.is_statevector:
                np_state_vec = result.get_statevector(dip_test_circuit)
                dip_test_state_vec = Statevector(np_state_vec)
                dip_test_counts = dip_test_state_vec.probabilities_dict()
                pdip_test_counts = \
                    [Statevector(result.get_statevector(circ)).probabilities_dict()
                     for circ in pdip_test_circuits]
            else:
                dip_test_counts = result.get_counts(dip_test_circuit)
                pdip_test_counts = [result.get_counts(circ) for circ in
                                    pdip_test_circuits]

            obj_global = self._dip_test_post_process(dip_test_counts)
            obj_local = self._pdip_test_post_process(pdip_test_counts)
            obj_weigthed = self._q * obj_global + (1.0 - self._q) * obj_local
            end_time = time()

            global_objs.append(np.real(obj_global))
            local_objs.append(np.real(obj_local))
            weighted_objs.append(np.real(obj_weigthed))

            self._eval_count += 1
            if self._callback is not None:
                self._callback(self._eval_count, parameter_sets[idx],
                               np.real(obj_global), np.real(obj_local),
                               np.real(obj_weigthed))

            # If there is more than one parameter set then the calculation
            # of the evaluation time has to be done more carefully,
            # therefore we do not calculate it
            if len(parameter_sets) == 1:
                logger.info('Cost function evaluation %s '
                            'returned %s - %.5f (ms)',
                            self._eval_count,
                            np.real(obj_weigthed),
                            (end_time - start_time) * 1000)
            else:
                logger.info('Cost function evaluation %s returned %s',
                            self._eval_count,
                            np.real(obj_weigthed))
            return weighted_objs if len(weighted_objs) > 1 \
                                    else weighted_objs[0]
Esempio n. 5
0
 def test_getitem_except(self):
     """Test __getitem__ method raises exceptions."""
     for i in range(1, 4):
         state = Statevector(self.rand_vec(2**i))
         self.assertRaises(QiskitError, state.__getitem__, 2**i)
         self.assertRaises(QiskitError, state.__getitem__, -1)