Exemple #1
0
    def __init__(self,
                 operator,
                 var_form,
                 optimizer,
                 initial_point=None,
                 max_evals_grouped=1,
                 aux_operators=None,
                 callback=None,
                 auto_conversion=True):
        """

        Args:
            operator (BaseOperator): Qubit operator
            var_form (VariationalForm): parametrized variational form.
            optimizer (Optimizer): the classical optimization algorithm.
            initial_point (numpy.ndarray): optimizer initial point.
            max_evals_grouped (int): max number of evaluations performed simultaneously
            aux_operators (list[BaseOperator]): Auxiliary operators to be evaluated
                                                at each eigenvalue
            callback (Callable): a callback that can access the intermediate
                                 data during the optimization.
                                 Internally, four arguments are provided as follows
                                 the index of evaluation, parameters of variational form,
                                 evaluated mean, evaluated standard deviation.
            auto_conversion (bool): an automatic conversion for operator and aux_operators
                into the type which is most suitable for the backend.

                - for *non-Aer statevector simulator:*
                  :class:`~qiskit.aqua.operators.MatrixOperator`
                - for *Aer statevector simulator:*
                  :class:`~qiskit.aqua.operators.WeightedPauliOperator`
                - for *qasm simulator or real backend:*
                  :class:`~qiskit.aqua.operators.TPBGroupedWeightedPauliOperator`
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__(var_form=var_form,
                         optimizer=optimizer,
                         cost_fn=self._energy_evaluation,
                         initial_point=initial_point)
        self._use_simulator_snapshot_mode = None
        self._ret = None
        self._eval_time = None
        self._optimizer.set_max_evals_grouped(max_evals_grouped)
        self._callback = callback
        if initial_point is None:
            self._initial_point = var_form.preferred_init_points
        self._operator = operator
        self._eval_count = 0
        self._aux_operators = []
        if aux_operators is not None:
            aux_operators = \
                [aux_operators] if not isinstance(aux_operators, list) else aux_operators
            for aux_op in aux_operators:
                self._aux_operators.append(aux_op)
        self._auto_conversion = auto_conversion
        logger.info(self.print_settings())
        self._var_form_params = ParameterVector('θ',
                                                self._var_form.num_parameters)

        self._parameterized_circuits = None
Exemple #2
0
 def __init__(self, maxfun=1000, factr=10, iprint=-1, max_processes=None):
     r"""
     Args:
         maxfun (int): Maximum number of function evaluations.
         factr (float): The iteration stops when (f\^k - f\^{k+1})/max{\|f\^k\|,
                        \|f\^{k+1}|,1} <= factr * eps, where eps is the machine precision,
                        which is automatically generated by the code. Typical values for
                        factr are: 1e12 for low accuracy; 1e7 for moderate accuracy;
                        10.0 for extremely high accuracy. See Notes for relationship to ftol,
                        which is exposed (instead of factr) by the scipy.optimize.minimize
                        interface to L-BFGS-B.
         iprint (int): Controls the frequency of output. iprint < 0 means no output;
                       iprint = 0 print only one line at the last iteration; 0 < iprint < 99
                       print also f and \|proj g\| every iprint iterations; iprint = 99 print
                       details of every iteration except n-vectors; iprint = 100 print also the
                       changes of active set and final x; iprint > 100 print details of
                       every iteration including x and g.
         max_processes (int): maximum number of processes allowed.
     """
     validate(locals(), self._INPUT_SCHEMA)
     super().__init__()
     for k, v in locals().items():
         if k in self._OPTIONS:
             self._options[k] = v
     self._max_processes = max_processes
Exemple #3
0
    def __init__(self, operator, k=1, aux_operators=None):
        """Constructor.

        Args:
            operator (MatrixOperator): instance
            k (int): How many eigenvalues are to be computed
            aux_operators (list[MatrixOperator]): Auxiliary operators
                        to be evaluated at each eigenvalue
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()

        self._operator = op_converter.to_matrix_operator(operator)
        if aux_operators is None:
            self._aux_operators = []
        else:
            aux_operators = \
                [aux_operators] if not isinstance(aux_operators, list) else aux_operators
            self._aux_operators = \
                [op_converter.to_matrix_operator(aux_op) for aux_op in aux_operators]
        self._k = k
        if self._k > self._operator.matrix.shape[0]:
            self._k = self._operator.matrix.shape[0]
            logger.debug(
                "WARNING: Asked for %s eigenvalues but max possible is %s.", k,
                self._k)
        self._ret = {}
Exemple #4
0
    def __init__(self,
                 maxiter=100,
                 disp=False,
                 ftol=1e-06,
                 tol=None,
                 eps=1.4901161193847656e-08):
        """
        Constructor.

        For details, please refer to
        https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html.

        Args:
            maxiter (int): Maximum number of iterations.
            disp (bool): Set to True to print convergence messages.
            ftol (float): Precision goal for the value of f in the stopping criterion.
            tol (float or None): Tolerance for termination.
            eps (float): Step size used for numerical approximation of the Jacobian.
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()
        for k, v in locals().items():
            if k in self._OPTIONS:
                self._options[k] = v
        self._tol = tol
Exemple #5
0
    def __init__(self, num_qubits, low=None, high=None, mu=None, sigma=None):
        """
        Circuit Factory to build a circuit that represents a multivariate normal distribution.

        Args:
            num_qubits (Union(list, numpy.ndarray)): representing number of qubits per dimension
            low (Union(list, numpy.ndarray)): representing lower bounds per dimension
            high (Union(list, numpy.ndarray)): representing upper bounds per dimension
            mu (Union(list, numpy.ndarray)): representing expected values
            sigma (Union(list, numpy.ndarray)): representing co-variance matrix
        """
        validate(locals(), self._INPUT_SCHEMA)

        if not isinstance(sigma, np.ndarray):
            sigma = np.asarray(sigma)

        dimension = len(num_qubits)

        if mu is None:
            mu = np.zeros(dimension)
        if sigma is None:
            sigma = np.eye(dimension)
        if low is None:
            low = -np.ones(dimension)
        if high is None:
            high = np.ones(dimension)

        self.mu = mu
        self.sigma = sigma
        probs = self._compute_probabilities([], num_qubits, low, high)
        probs = np.asarray(probs) / np.sum(probs)
        super().__init__(num_qubits, probs, low, high)
Exemple #6
0
    def __init__(self,
                 maxiter=1000,
                 eta=3.0,
                 tol=1e-6,
                 disp=False,
                 momentum=0.25):
        """
        Constructor.

        Performs Analytical Quantum Gradient Descent (AQGD).

        Args:
            maxiter (int): Maximum number of iterations, each iteration evaluation gradient.
            eta (float): The coefficient of the gradient update. Increasing this value
                         results in larger step sizes: param = previous_param - eta * deriv
            tol (float): The convergence criteria that must be reached before stopping.
                         Optimization stops when: absolute(loss - previous_loss) < tol
            disp (bool): Set to true to display convergence messages.
            momentum (float): Bias towards the previous gradient momentum in current update.
                              Must be within the bounds: [0,1)

        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()

        self._eta = eta
        self._maxiter = maxiter
        self._tol = tol if tol is not None else 1e-6
        self._disp = disp
        self._momentum_coeff = momentum
        self._previous_loss = None
    def __init__(self,
                 maxfun=1000,
                 maxiter=15000,
                 factr=10,
                 iprint=-1,
                 epsilon=1e-08):
        r"""

        Uses scipy.optimize.fmin_l_bfgs_b
        https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fmin_l_bfgs_b.html

        Args:
            maxfun (int): Maximum number of function evaluations.
            maxiter (int): Maximum number of iterations.
            factr (float): The iteration stops when (f\^k - f\^{k+1})/max{\|f\^k\|,
                           \|f\^{k+1}\|,1} <= factr * eps, where eps is the machine precision,
                           which is automatically generated by the code. Typical values for
                           factr are: 1e12 for low accuracy; 1e7 for moderate accuracy;
                           10.0 for extremely high accuracy. See Notes for relationship to ftol,
                           which is exposed (instead of factr) by the scipy.optimize.minimize
                           interface to L-BFGS-B.
            iprint (int): Controls the frequency of output. iprint < 0 means no output;
                          iprint = 0 print only one line at the last iteration; 0 < iprint < 99
                          print also f and \|proj g\| every iprint iterations; iprint = 99 print
                          details of every iteration except n-vectors; iprint = 100 print also the
                          changes of active set and final x; iprint > 100 print details of
                          every iteration including x and g.
            epsilon (float): Step size used when approx_grad is True, for numerically
                             calculating the gradient
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()
        for k, v in locals().items():
            if k in self._OPTIONS:
                self._options[k] = v
Exemple #8
0
    def __init__(self, N=15, a=2):
        """
        Constructor.

        Args:
            N (int): The integer to be factored.
            a (int): A random integer a that satisfies a < N and gcd(a, N) = 1
         Raises:
            AquaError: invalid input
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()
        self._n = None
        self._up_qreg = None
        self._down_qreg = None
        self._aux_qreg = None

        # check the input integer
        if N < 1 or N % 2 == 0:
            raise AquaError('The input needs to be an odd integer greater than 1.')

        self._N = N

        if a >= N or math.gcd(a, self._N) != 1:
            raise AquaError('The integer a needs to satisfy a < N and gcd(a, N) = 1.')

        self._a = a

        self._ret = {'factors': []}

        # check if the input integer is a power
        tf, b, p = is_power(N, return_decomposition=True)
        if tf:
            logger.info('The input integer is a power: %s=%s^%s.', N, b, p)
            self._ret['factors'].append(b)
Exemple #9
0
    def __init__(self, operator, num_orbitals, num_particles, qubit_mapping='parity',
                 two_qubit_reduction=True, active_occupied=None, active_unoccupied=None,
                 is_eom_matrix_symmetric=True, se_list=None, de_list=None,
                 z2_symmetries=None, untapered_op=None, aux_operators=None):
        """
        Args:
            operator (BaseOperator): qubit operator
            num_orbitals (int):  total number of spin orbitals
            num_particles (Union(list, int)): number of particles, if it is a list,
                                        the first number is alpha and the second
                                        number if beta.
            qubit_mapping (str): qubit mapping type
            two_qubit_reduction (bool): two qubit reduction is applied or not
            active_occupied (list): list of occupied orbitals to include, indices are
                                    0 to n where n is num particles // 2
            active_unoccupied (list): list of unoccupied orbitals to include, indices are
                                    0 to m where m is (num_orbitals - num particles) // 2
            is_eom_matrix_symmetric (bool): is EoM matrix symmetric
            se_list (list[list]): single excitation list, overwrite the setting in active space
            de_list (list[list]): double excitation list, overwrite the setting in active space
            z2_symmetries (Z2Symmetries): represent the Z2 symmetries
            untapered_op (BaseOperator): if the operator is tapered, we need untapered operator
                                         to build element of EoM matrix
            aux_operators (list[BaseOperator]): Auxiliary operators to be evaluated at
                                                each eigenvalue
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__(operator, 1, aux_operators)

        self.qeom = QEquationOfMotion(operator, num_orbitals, num_particles, qubit_mapping,
                                      two_qubit_reduction, active_occupied, active_unoccupied,
                                      is_eom_matrix_symmetric, se_list, de_list,
                                      z2_symmetries, untapered_op)
Exemple #10
0
    def __init__(self,
                 operator,
                 state_in,
                 iqft,
                 num_time_slices=1,
                 num_ancillae=1,
                 expansion_mode='trotter',
                 expansion_order=1,
                 shallow_circuit_concat=False):
        """

        Args:
            operator (BaseOperator): the hamiltonian Operator object
            state_in (InitialState): the InitialState component
                representing the initial quantum state
            iqft (IQFT): the Inverse Quantum Fourier Transform component
            num_time_slices (int): the number of time slices
            num_ancillae (int): the number of ancillary qubits to use for the measurement
            expansion_mode (str): the expansion mode (trotter|suzuki)
            expansion_order (int): the suzuki expansion order
            shallow_circuit_concat (bool): indicate whether to use shallow
                (cheap) mode for circuit concatenation
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()
        self._operator = op_converter.to_weighted_pauli_operator(
            operator.copy())
        self._num_ancillae = num_ancillae
        self._ret = {}

        self._ret['translation'] = sum(
            [abs(p[0]) for p in self._operator.reorder_paulis()])
        self._ret['stretch'] = 0.5 / self._ret['translation']

        # translate the operator
        self._operator.simplify()
        translation_op = WeightedPauliOperator([[
            self._ret['translation'],
            Pauli(np.zeros(self._operator.num_qubits),
                  np.zeros(self._operator.num_qubits))
        ]])
        translation_op.simplify()
        self._operator += translation_op
        self._pauli_list = self._operator.reorder_paulis()

        # stretch the operator
        for p in self._pauli_list:
            p[0] = p[0] * self._ret['stretch']

        self._phase_estimation_circuit = PhaseEstimationCircuit(
            operator=self._operator,
            state_in=state_in,
            iqft=iqft,
            num_time_slices=num_time_slices,
            num_ancillae=num_ancillae,
            expansion_mode=expansion_mode,
            expansion_order=expansion_order,
            shallow_circuit_concat=shallow_circuit_concat,
            pauli_list=self._pauli_list)
        self._binary_fractions = [1 / 2**p for p in range(1, num_ancillae + 1)]
Exemple #11
0
    def __init__(self,
                 maxiter=None,
                 maxfev=1000,
                 disp=False,
                 xtol=0.0001,
                 tol=None):
        """
        Constructor.

        For details, please refer to
        https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html.

        Args:
            maxiter (int): Maximum allowed number of iterations. If both maxiter and maxfev
                           are set, minimization will stop at the first reached.
            maxfev (int): Maximum allowed number of function evaluations. If both maxiter and
                          maxfev are set, minimization will stop at the first reached.
            disp (bool): Set to True to print convergence messages.
            xtol (float): Relative error in solution xopt acceptable for convergence.
            tol (float or None): Tolerance for termination.
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()
        for k, v in locals().items():
            if k in self._OPTIONS:
                self._options[k] = v
        self._tol = tol
Exemple #12
0
    def __init__(self,
                 num_eval_qubits,
                 a_factory=None,
                 i_objective=None,
                 q_factory=None,
                 iqft=None):
        """

        Args:
            num_eval_qubits (int): number of evaluation qubits
            a_factory (CircuitFactory): the CircuitFactory subclass object representing
                                        the problem unitary
            i_objective (int): i objective
            q_factory (CircuitFactory): the CircuitFactory subclass object representing an
                                        amplitude estimation sample (based on a_factory)
            iqft (IQFT): the Inverse Quantum Fourier Transform component,
                         defaults to using a standard iqft when None
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__(a_factory, q_factory, i_objective)

        # get parameters
        self._m = num_eval_qubits
        self._M = 2**num_eval_qubits

        if iqft is None:
            iqft = Standard(self._m)

        self._iqft = iqft
        self._circuit = None
        self._ret = {}
    def __init__(self,
                 feature_dimension,
                 depth=2,
                 entangler_map=None,
                 entanglement='full',
                 data_map_func=self_product):
        """Constructor.

        Args:
            feature_dimension (int): number of features
            depth (int): the number of repeated circuits
            entangler_map (list[list]): describe the connectivity of qubits, each list describes
                                        [source, target], or None for full entanglement.
                                        Note that the order is the list is the order of
                                        applying the two-qubit gate.
            entanglement (str): ['full', 'linear'], generate the qubit connectivity by predefined
                                topology
            data_map_func (Callable): a mapping function for data x
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__(feature_dimension,
                         depth,
                         entangler_map,
                         entanglement,
                         z_order=2,
                         data_map_func=data_map_func)
Exemple #14
0
    def __init__(self, oracle):
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()

        self._oracle = oracle
        self._circuit = None
        self._ret = {}
Exemple #15
0
    def __init__(self,
                 matrix=None,
                 vector=None,
                 truncate_powerdim=False,
                 truncate_hermitian=False,
                 eigs=None,
                 init_state=None,
                 reciprocal=None,
                 num_q=0,
                 num_a=0,
                 orig_size=None):
        """
        Constructor.

        Args:
            matrix (np.array): the input matrix of linear system of equations
            vector (np.array): the input vector of linear system of equations
            truncate_powerdim (bool): flag indicating expansion to 2**n matrix to be truncated
            truncate_hermitian (bool): flag indicating expansion to hermitian matrix to be truncated
            eigs (Eigenvalues): the eigenvalue estimation instance
            init_state (InitialState): the initial quantum state preparation
            reciprocal (Reciprocal): the eigenvalue reciprocal and controlled rotation instance
            num_q (int): number of qubits required for the matrix Operator instance
            num_a (int): number of ancillary qubits for Eigenvalues instance
            orig_size (int): The original dimension of the problem (if truncate_powerdim)
        Raises:
            ValueError: invalid input
        """
        super().__init__()
        validate(locals(), self._INPUT_SCHEMA)
        if matrix.shape[0] != matrix.shape[1]:
            raise ValueError("Input matrix must be square!")
        if matrix.shape[0] != len(vector):
            raise ValueError("Input vector dimension does not match input "
                             "matrix dimension!")
        if not np.allclose(matrix, matrix.conj().T):
            raise ValueError("Input matrix must be hermitian!")
        if np.log2(matrix.shape[0]) % 1 != 0:
            raise ValueError("Input matrix dimension must be 2**n!")
        if truncate_powerdim and orig_size is None:
            raise ValueError("Truncation to {} dimensions is not "
                             "possible!".format(orig_size))

        self._matrix = matrix
        self._vector = vector
        self._truncate_powerdim = truncate_powerdim
        self._truncate_hermitian = truncate_hermitian
        self._eigs = eigs
        self._init_state = init_state
        self._reciprocal = reciprocal
        self._num_q = num_q
        self._num_a = num_a
        self._circuit = None
        self._io_register = None
        self._eigenvalue_register = None
        self._ancilla_register = None
        self._success_bit = None
        self._original_dimension = orig_size
        self._ret = {}
    def __init__(self,
                 uncertainty_model,
                 strike_price,
                 c_approx,
                 i_state=None,
                 i_compare=None,
                 i_objective=None):
        """
        Constructor.

        Args:
            uncertainty_model (UnivariateDistribution): uncertainty model for spot price
            strike_price (float): strike price of the European option
            c_approx (float): approximation factor for linear payoff
            i_state (Optional(Union(list, numpy.ndarray))): indices of qubits
                                                            representing the uncertainty
            i_compare (Optional(int)): index of qubit for comparing spot price to strike price
                            (enabling payoff or not)
            i_objective (Optional(int)): index of qubit for objective function
        """
        super().__init__(uncertainty_model.num_target_qubits + 2)

        self._uncertainty_model = uncertainty_model
        self._strike_price = strike_price
        self._c_approx = c_approx

        if i_state is None:
            i_state = list(range(uncertainty_model.num_target_qubits))
        self.i_state = i_state
        if i_compare is None:
            i_compare = uncertainty_model.num_target_qubits
        self.i_compare = i_compare
        if i_objective is None:
            i_objective = uncertainty_model.num_target_qubits + 1
        self.i_objective = i_objective

        validate(locals(), self._INPUT_SCHEMA)

        # map strike price to {0, ..., 2^n-1}
        lb = uncertainty_model.low
        ub = uncertainty_model.high
        self._mapped_strike_price = int(
            np.round((strike_price - lb) / (ub - lb) *
                     (uncertainty_model.num_values - 1)))

        # create comparator
        self._comparator = FixedValueComparator(
            uncertainty_model.num_target_qubits, self._mapped_strike_price)

        self.offset_angle_zero = np.pi / 4 * (1 - self._c_approx)
        if self._mapped_strike_price < uncertainty_model.num_values - 1:
            self.offset_angle = -1 * np.pi / 2 * self._c_approx * self._mapped_strike_price / \
                        (uncertainty_model.num_values - self._mapped_strike_price - 1)
            self.slope_angle = np.pi / 2 * self._c_approx / \
                (uncertainty_model.num_values - self._mapped_strike_price - 1)
        else:
            self.offset_angle = 0
            self.slope_angle = 0
Exemple #17
0
    def __init__(self,
                 num_qubits,
                 state="zero",
                 state_vector=None,
                 circuit=None):
        """Constructor.

        Args:
            num_qubits (int): number of qubits
            state (str): `zero`, `uniform` or `random`
            state_vector (numpy.ndarray): customized vector
            circuit (QuantumCircuit): the actual custom circuit for the desired initial state
        Raises:
            AquaError: invalid input
        """
        # pylint: disable=comparison-with-callable
        loc = locals().copy()
        # since state_vector is a numpy array of complex numbers which aren't json valid,
        # remove it from validation
        del loc['state_vector']
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()
        self._num_qubits = num_qubits
        self._state = state
        size = np.power(2, self._num_qubits)
        self._circuit = None
        if circuit is not None:
            if circuit.width() != num_qubits:
                logger.warning('The specified num_qubits and '
                               'the provided custom circuit do not match.')
            self._circuit = convert_to_basis_gates(circuit)
            if state_vector is not None:
                self._state = None
                self._state_vector = None
                logger.warning(
                    'The provided state_vector is ignored in favor of '
                    'the provided custom circuit.')
        else:
            if state_vector is None:
                if self._state == 'zero':
                    self._state_vector = np.array([1.0] + [0.0] * (size - 1))
                elif self._state == 'uniform':
                    self._state_vector = np.array([1.0 / np.sqrt(size)] * size)
                elif self._state == 'random':
                    self._state_vector = normalize_vector(
                        aqua_globals.random.rand(size))
                else:
                    raise AquaError('Unknown state {}'.format(self._state))
            else:
                if len(state_vector) != np.power(2, self._num_qubits):
                    raise AquaError(
                        'The state vector length {} is incompatible with '
                        'the number of qubits {}'.format(
                            len(state_vector), self._num_qubits))
                self._state_vector = normalize_vector(state_vector)
                self._state = None
Exemple #18
0
 def __init__(self, estimator_cls, params=None, code_size=4):
     validate(locals(), self._INPUT_SCHEMA)
     super().__init__()
     self.estimator_cls = estimator_cls
     self.params = params if params is not None else []
     self.code_size = code_size
     self.rand = aqua_globals.random
     self.estimators = None
     self.classes = None
     self.codebook = None
Exemple #19
0
    def __init__(self, feature_dimension=2):
        """Constructor.

        Args:
            feature_dimension (int): The feature dimension
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()
        self._feature_dimension = feature_dimension
        self._num_qubits = next_power_of_2_base(feature_dimension)
Exemple #20
0
 def __init__(self, max_evals=1000):  # pylint: disable=unused-argument
     """
     Args:
         max_evals (int): Maximum allowed number of function evaluations.
     """
     validate(locals(), self._INPUT_SCHEMA)
     check_nlopt_valid('CRS')
     super().__init__()
     for k, v in locals().items():
         if k in self._OPTIONS:
             self._options[k] = v
Exemple #21
0
    def __init__(self,
                 maxiter=10000,
                 tol=1e-6,
                 lr=1e-3,
                 beta_1=0.9,
                 beta_2=0.99,
                 noise_factor=1e-8,
                 eps=1e-10,
                 amsgrad=False,
                 snapshot_dir=None):
        """
        Args:
            maxiter (int): Maximum number of iterations
            tol (float): Tolerance for termination
            lr (float): Value >= 0, Learning rate.
            beta_1 (float): Value in range 0 to 1, Generally close to 1.
            beta_2 (float): Value in range 0 to 1, Generally close to 1.
            noise_factor (float): Value >= 0, Noise factor
            eps (float): Value >=0, Epsilon to be used for finite differences if no analytic
                gradient method is given.
            amsgrad (bool): True to use AMSGRAD, False if not
            snapshot_dir (Optional(str)): If not None save the optimizer's parameter
                after every step to the given directory
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()
        for k, v in locals().items():
            if k in self._OPTIONS:
                self._options[k] = v
        self._maxiter = maxiter
        self._snapshot_dir = snapshot_dir
        self._tol = tol
        self._lr = lr
        self._beta_1 = beta_1
        self._beta_2 = beta_2
        self._noise_factor = noise_factor
        self._eps = eps
        self._amsgrad = amsgrad
        self._t = 0  # time steps
        self._m = np.zeros(1)
        self._v = np.zeros(1)
        if self._amsgrad:
            self._v_eff = np.zeros(1)

        if self._snapshot_dir:

            with open(os.path.join(self._snapshot_dir, 'adam_params.csv'),
                      mode='w') as csv_file:
                if self._amsgrad:
                    fieldnames = ['v', 'v_eff', 'm', 't']
                else:
                    fieldnames = ['v', 'm', 't']
                writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
                writer.writeheader()
    def __init__(self, matrix=None, vector=None):
        """Constructor.

        Args:
            matrix (array): the input matrix of linear system of equations
            vector (array): the input vector of linear system of equations
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()
        self._matrix = matrix
        self._vector = vector
        self._ret = {}
    def __init__(self, num_qubits, num_orbitals, num_particles,
                 qubit_mapping='parity', two_qubit_reduction=True, sq_list=None):
        """Constructor.

        Args:
            num_qubits (int): number of qubits
            num_orbitals (int): number of spin orbitals
            num_particles (Union(list, int)): number of particles, if it is a list, the first number
                                      is alpha and the second number if beta.
            qubit_mapping (str): mapping type for qubit operator
            two_qubit_reduction (bool): flag indicating whether or not two qubit is reduced
            sq_list (list[int]): position of the single-qubit operators that
                                anticommute with the cliffords

        Raises:
            ValueError: wrong setting in num_particles and num_orbitals.
            ValueError: wrong setting for computed num_qubits and supplied num_qubits.
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()
        self._sq_list = sq_list
        self._qubit_tapering = bool(self._sq_list)
        self._qubit_mapping = qubit_mapping.lower()
        self._two_qubit_reduction = two_qubit_reduction
        if self._qubit_mapping != 'parity':
            if self._two_qubit_reduction:
                logger.warning("two_qubit_reduction only works with parity qubit mapping "
                               "but you have %s. We switch two_qubit_reduction "
                               "to False.", self._qubit_mapping)
                self._two_qubit_reduction = False

        self._num_orbitals = num_orbitals
        if isinstance(num_particles, list):
            self._num_alpha = num_particles[0]
            self._num_beta = num_particles[1]
        else:
            logger.info("We assume that the number of alphas and betas are the same.")
            self._num_alpha = num_particles // 2
            self._num_beta = num_particles // 2

        self._num_particles = self._num_alpha + self._num_beta

        if self._num_particles > self._num_orbitals:
            raise ValueError("# of particles must be less than or equal to # of orbitals.")

        self._num_qubits = num_orbitals - 2 if self._two_qubit_reduction else self._num_orbitals
        self._num_qubits = self._num_qubits \
            if not self._qubit_tapering else self._num_qubits - len(sq_list)
        if self._num_qubits != num_qubits:
            raise ValueError("Computed num qubits {} does not match "
                             "actual {}".format(self._num_qubits, num_qubits))

        self._bitstr = None
    def __init__(self,
                 atom,
                 unit=UnitsType.ANGSTROM,
                 charge=0,
                 spin=0,
                 basis='sto3g',
                 hf_method=HFMethodType.RHF,
                 conv_tol=1e-9,
                 max_cycle=50,
                 init_guess=InitialGuess.MINAO,
                 max_memory=None):
        """
        Initializer
        Args:
            atom (str or list): atom list or string separated by semicolons or line breaks
            unit (UnitsType): angstrom or bohr
            charge (int): charge
            spin (int): spin
            basis (str): basis set
            hf_method (HFMethodType): Hartree-Fock Method type
            conv_tol (float): Convergence tolerance see PySCF docs and pyscf/scf/hf.py
            max_cycle (int): Max convergence cycles see PySCF docs and pyscf/scf/hf.py
            init_guess (InitialGuess): See PySCF pyscf/scf/hf.py init_guess_by_minao/1e/atom methods
            max_memory (int): maximum memory
        Raises:
            QiskitChemistryError: Invalid Input
        """
        self._check_valid()
        if not isinstance(atom, list) and not isinstance(atom, str):
            raise QiskitChemistryError(
                "Invalid atom input for PYSCF Driver '{}'".format(atom))

        if isinstance(atom, list):
            atom = ';'.join(atom)
        else:
            atom = atom.replace('\n', ';')

        unit = unit.value
        hf_method = hf_method.value
        init_guess = init_guess.value
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()
        self._atom = atom
        self._unit = unit
        self._charge = charge
        self._spin = spin
        self._basis = basis
        self._hf_method = hf_method
        self._conv_tol = conv_tol
        self._max_cycle = max_cycle
        self._init_guess = init_guess
        self._max_memory = max_memory
Exemple #25
0
    def __init__(self,
                 oracle,
                 init_state=None,
                 incremental=False,
                 num_iterations=1,
                 mct_mode='basic'):
        """
        Constructor.

        Args:
            oracle (Oracle): the oracle component
            init_state (InitialState): the initial quantum state preparation
            incremental (bool): boolean flag for whether to use incremental search mode or not
            num_iterations (int): the number of iterations to use for amplitude amplification
            mct_mode (str): mct mode
        Raises:
            AquaError: evaluate_classically() missing from the input oracle
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()

        if not callable(getattr(oracle, "evaluate_classically", None)):
            raise AquaError(
                'Missing the evaluate_classically() method from the provided oracle instance.'
            )

        self._oracle = oracle
        self._mct_mode = mct_mode
        self._init_state = \
            init_state if init_state else Custom(len(oracle.variable_register), state='uniform')
        self._init_state_circuit = \
            self._init_state.construct_circuit(mode='circuit', register=oracle.variable_register)
        self._init_state_circuit_inverse = self._init_state_circuit.inverse()

        self._diffusion_circuit = self._construct_diffusion_circuit()
        self._max_num_iterations = np.ceil(2**(len(oracle.variable_register) /
                                               2))
        self._incremental = incremental
        self._num_iterations = num_iterations if not incremental else 1
        validate(locals(), self._INPUT_SCHEMA)
        if incremental:
            logger.debug(
                'Incremental mode specified, ignoring "num_iterations".')
        else:
            if num_iterations > self._max_num_iterations:
                logger.warning(
                    'The specified value %s for "num_iterations" '
                    'might be too high.', num_iterations)
        self._ret = {}
        self._qc_aa_iteration = None
        self._qc_amplitude_amplification = None
        self._qc_measurement = None
    def __init__(self, feature_dimension, depth=2, data_map_func=self_product):
        """Constructor.

        Args:
            feature_dimension (int): number of features
            depth (int): the number of repeated circuits
            data_map_func (Callable): a mapping function for data x
        """
        validate(locals(), self._INPUT_SCHEMA)
        super().__init__(feature_dimension,
                         depth,
                         z_order=1,
                         data_map_func=data_map_func)
Exemple #27
0
    def __init__(self,
                 training_dataset,
                 test_dataset=None,
                 datapoints=None,
                 gamma=None,
                 multiclass_extension=None):
        # pylint: disable=line-too-long
        """

        Args:
            training_dataset (dict, optional): training dataset.
            test_dataset (dict, optional): testing dataset.
            datapoints (numpy.ndarray, optional): prediction dataset.
            gamma (int, optional): Used as input for sklearn rbf_kernel internally. See
                `sklearn.metrics.pairwise.rbf_kernel
                <https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.rbf_kernel.html>`_
                for more information about gamma.
            multiclass_extension (MultiExtension, optional): if number of classes > 2 then
                a multiclass scheme is needed.

        Raises:
            AquaError: If using binary classifier where num classes >= 3
        """

        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()
        if training_dataset is None:
            raise AquaError('Training dataset must be provided.')

        is_multiclass = get_num_classes(training_dataset) > 2
        if is_multiclass:
            if multiclass_extension is None:
                raise AquaError('Dataset has more than two classes. '
                                'A multiclass extension must be provided.')
        else:
            if multiclass_extension is not None:
                logger.warning(
                    "Dataset has just two classes. Supplied multiclass "
                    "extension will be ignored")

        if multiclass_extension is None:
            svm_instance = _SVM_Classical_Binary(training_dataset,
                                                 test_dataset, datapoints,
                                                 gamma)
        else:
            svm_instance = _SVM_Classical_Multiclass(training_dataset,
                                                     test_dataset, datapoints,
                                                     gamma,
                                                     multiclass_extension)

        self.instance = svm_instance
Exemple #28
0
    def __init__(self,
                 operator,
                 optimizer,
                 p=1,
                 initial_state=None,
                 mixer=None,
                 initial_point=None,
                 max_evals_grouped=1,
                 aux_operators=None,
                 callback=None,
                 auto_conversion=True):
        """
        Args:
            operator (BaseOperator): Qubit operator
            p (int): the integer parameter p as specified in https://arxiv.org/abs/1411.4028
            initial_state (InitialState): the initial state to prepend the QAOA circuit with
            mixer (BaseOperator): the mixer Hamiltonian to evolve with. Allows support of
                                  optimizations in constrained subspaces
                                  as per https://arxiv.org/abs/1709.03489
            optimizer (Optimizer): the classical optimization algorithm.
            initial_point (numpy.ndarray): optimizer initial point.
            max_evals_grouped (int): max number of evaluations to be performed simultaneously.
            aux_operators (list): aux operators
            callback (Callable): a callback that can access the intermediate
                                 data during the optimization.
                                 Internally, four arguments are provided as follows
                                 the index of evaluation, parameters of variational form,
                                 evaluated mean, evaluated standard deviation.
            auto_conversion (bool): an automatic conversion for operator and aux_operators
                into the type which is most suitable for the backend.

                - for *non-Aer statevector simulator:*
                  :class:`~qiskit.aqua.operators.MatrixOperator`
                - for *Aer statevector simulator:*
                  :class:`~qiskit.aqua.operators.WeightedPauliOperator`
                - for *qasm simulator or real backend:*
                  :class:`~qiskit.aqua.operators.TPBGroupedWeightedPauliOperator`
        """
        validate(locals(), self._INPUT_SCHEMA)
        var_form = QAOAVarForm(operator.copy(),
                               p,
                               initial_state=initial_state,
                               mixer_operator=mixer)
        super().__init__(operator,
                         var_form,
                         optimizer,
                         initial_point=initial_point,
                         max_evals_grouped=max_evals_grouped,
                         aux_operators=aux_operators,
                         callback=callback,
                         auto_conversion=auto_conversion)
    def __init__(self, bitmaps, optimization=False, mct_mode='basic'):
        """
        Constructor for Truth Table-based Oracle

        Args:
            bitmaps (Union(str, [str])): A single binary string or a list of binary strings
                representing the desired single- and multi-value truth table.
            optimization (bool): Boolean flag for attempting circuit optimization.
                When set, the Quine-McCluskey algorithm is used to compute the prime
                implicants of the truth table,
                and then its exact cover is computed to try to reduce the circuit.
            mct_mode (str): The mode to use when constructing multiple-control Toffoli.
        Raises:
            AquaError: invalid input
        """
        if isinstance(bitmaps, str):
            bitmaps = [bitmaps]

        validate(locals(), self._INPUT_SCHEMA)
        super().__init__()

        self._mct_mode = mct_mode.strip().lower()
        self._optimization = optimization

        self._bitmaps = bitmaps

        # check that the input bitmaps length is a power of 2
        if not is_power_of_2(len(bitmaps[0])):
            raise AquaError('Length of any bitmap must be a power of 2.')
        for bitmap in bitmaps[1:]:
            if not len(bitmap) == len(bitmaps[0]):
                raise AquaError('Length of all bitmaps must be the same.')
        self._nbits = int(math.log(len(bitmaps[0]), 2))
        self._num_outputs = len(bitmaps)

        self._lit_to_var = None
        self._var_to_lit = None

        esop_exprs = []
        for bitmap in bitmaps:
            esop_expr = self._get_esop_ast(bitmap)
            esop_exprs.append(esop_expr)

        self._esops = [
            ESOP(esop_expr, num_vars=self._nbits) for esop_expr in esop_exprs
        ] if esop_exprs else None

        self.construct_circuit()
Exemple #30
0
 def __init__(self, num_target_qubits, mu=0, sigma=1, low=-1, high=1):
     r"""
     Args:
         num_target_qubits (int): number of qubits it acts on
         mu (float): expected value of considered normal distribution
         sigma (float): standard deviation of considered normal distribution
         low (float): lower bound, i.e., the value corresponding to \|0...0>
                      (assuming an equidistant grid)
         high (float): upper bound, i.e., the value corresponding to \|1...1>
                       (assuming an equidistant grid)
     """
     validate(locals(), self._INPUT_SCHEMA)
     probabilities, _ = UnivariateDistribution.\
         pdf_to_probabilities(
             lambda x: norm.pdf(x, mu, sigma), low, high, 2 ** num_target_qubits)
     super().__init__(num_target_qubits, probabilities, low, high)