def __init__(
            self,
            feature_dimension: int,
            depth: int = 2,
            entangler_map: Optional[List[List[int]]] = None,
            entanglement: str = 'full',
            data_map_func: Callable[[np.ndarray],
                                    float] = self_product) -> None:
        """Constructor.

        Args:
            feature_dimension: number of features
            depth: the number of repeated circuits, has a min. value of 1.
            entangler_map: 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: ['full', 'linear'], generate the qubit connectivity by predefined
                                topology
            data_map_func: a mapping function for data x
        """
        validate_min('depth', depth, 1)
        validate_in_set('entanglement', entanglement, {'full', 'linear'})
        super().__init__(feature_dimension,
                         depth,
                         entangler_map,
                         entanglement,
                         z_order=2,
                         data_map_func=data_map_func)
예제 #2
0
    def __init__(self, min_eigen_optimizer: MinimumEigenOptimizer, min_num_vars: int = 1,
                 min_num_vars_optimizer: Optional[OptimizationAlgorithm] = None,
                 penalty: Optional[float] = None) -> None:
        """ Initializes the recursive minimum eigen optimizer.

        This initializer takes a ``MinimumEigenOptimizer``, the parameters to specify until when to
        to apply the iterative scheme, and the optimizer to be applied once the threshold number of
        variables is reached.

        Args:
            min_eigen_optimizer: The eigen optimizer to use in every iteration.
            min_num_vars: The minimum number of variables to apply the recursive scheme. If this
                threshold is reached, the min_num_vars_optimizer is used.
            min_num_vars_optimizer: This optimizer is used after the recursive scheme for the
                problem with the remaining variables.
            penalty: The factor that is used to scale the penalty terms corresponding to linear
                equality constraints.

        TODO: add flag to store full history.

        Raises:
            QiskitOptimizationError: In case of invalid parameters (num_min_vars < 1).
        """

        validate_min('min_num_vars', min_num_vars, 1)

        self._min_eigen_optimizer = min_eigen_optimizer
        self._min_num_vars = min_num_vars
        if min_num_vars_optimizer:
            self._min_num_vars_optimizer = min_num_vars_optimizer
        else:
            self._min_num_vars_optimizer = MinimumEigenOptimizer(NumPyMinimumEigensolver())
        self._penalty = penalty
        self._qubo_converter = QuadraticProgramToQubo()
예제 #3
0
    def __init__(self,
                 num_eval_qubits: int,
                 a_factory: Optional[CircuitFactory] = None,
                 q_factory: Optional[CircuitFactory] = None,
                 i_objective: Optional[int] = None,
                 iqft: Optional[IQFT] = None) -> None:
        r"""Initializer.

        Args:
            num_eval_qubits: Number of evaluation qubits, has a min. value of 1.
            a_factory: The CircuitFactory subclass object representing the problem unitary.
            q_factory: The CircuitFactory subclass object representing an amplitude estimation
                sample (based on a_factory).
            i_objective: The index of the objective qubit, i.e. the qubit marking 'good' solutions
                with the state \|1> and 'bad' solutions with the state \|0>.
            iqft: the Inverse Quantum Fourier Transform component, defaults to using a standard IQFT
                when None
        """
        validate_min('num_eval_qubits', num_eval_qubits, 1)
        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,
              num_target_qubits: int,
              probabilities: Optional[Union[List[float], np.ndarray]] = None,
              low: float = 0,
              high: float = 1):
     r"""
     Args:
         num_target_qubits: Number of qubits it acts on,
             has a min. value of 1.
         probabilities: Probabilities for different states
         low: Lower bound, i.e., the value corresponding to \|0...0>
             (assuming an equidistant grid)
         high: Upper bound, i.e., the value corresponding to \|1...1>
             (assuming an equidistant grid)
     Raises:
         AquaError: num qubits and length of probabilities vector do not match
     """
     validate_min('num_target_qubits', num_target_qubits, 1)
     super().__init__(num_target_qubits)
     self._num_values = 2 ** self.num_target_qubits
     self._probabilities = np.array(probabilities)
     self._low = low
     self._high = high
     self._values = np.linspace(low, high, self.num_values)
     if probabilities is not None:
         if self.num_values != len(probabilities):
             raise AquaError('num qubits and length of probabilities vector do not match!')
예제 #5
0
    def __init__(self, num_eval_qubits: int,
                 a_factory: Optional[CircuitFactory] = None,
                 i_objective: Optional[int] = None,
                 q_factory: Optional[CircuitFactory] = None,
                 iqft: Optional[IQFT] = None) -> None:
        """

        Args:
            num_eval_qubits: number of evaluation qubits, has a min. value of 1.
            a_factory: the CircuitFactory subclass object representing
                                        the problem unitary
            i_objective: i objective
            q_factory: the CircuitFactory subclass object representing an
                                        amplitude estimation sample (based on a_factory)
            iqft: the Inverse Quantum Fourier Transform component,
                         defaults to using a standard iqft when None
        """
        validate_min('num_eval_qubits', num_eval_qubits, 1)
        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 = {}
예제 #6
0
    def __init__(self,
                 num_qubits: int,
                 var_form: QuantumCircuit,
                 params: Union[List[float], np.ndarray],
                 low: float = 0,
                 high: float = 1) -> None:
        """
        Args:
            num_qubits: Number of qubits
            var_form: Variational form
            params: Parameters for variational form
            low: Lower bound
            high: Upper bound
        """
        validate_min('num_qubits', num_qubits, 1)
        self._num_qubits = num_qubits
        self._var_form = var_form

        # fix the order of the parameters in the circuit
        self._var_form_params = sorted(self._var_form.parameters,
                                       key=lambda p: p.name)

        self.params = params
        if isinstance(num_qubits, int):
            probabilities = np.zeros(2**num_qubits)
        elif isinstance(num_qubits, float):
            probabilities = np.zeros(2**int(num_qubits))
        else:
            probabilities = np.zeros(2**sum(num_qubits))
        super().__init__(num_qubits, probabilities, low, high)
예제 #7
0
    def __init__(self,
                 operator: BaseOperator,
                 k: int = 1,
                 aux_operators: Optional[List[BaseOperator]] = None) -> None:
        """Constructor.

        Args:
            operator: instance
            k: How many eigenvalues are to be computed, has a min. value of 1.
            aux_operators: Auxiliary operators
                        to be evaluated at each eigenvalue
        """
        validate_min('k', k, 1)
        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 = {}
예제 #8
0
    def __init__(
        self,
        operator: LegacyBaseOperator,
        var_form_base: VariationalForm,
        optimizer: Optimizer,
        initial_point: Optional[np.ndarray] = None,
        excitation_pool: Optional[List[WeightedPauliOperator]] = None,
        threshold: float = 1e-5,
        delta: float = 1,
        max_iterations: Optional[int] = None,
        max_evals_grouped: int = 1,
        aux_operators: Optional[List[LegacyBaseOperator]] = None,
        quantum_instance: Optional[Union[QuantumInstance, Backend,
                                         BaseBackend]] = None
    ) -> None:
        """
        Args:
            operator: Qubit operator
            var_form_base: base parameterized variational form
            optimizer: the classical optimizer algorithm
            initial_point: optimizer initial point
            excitation_pool: list of excitation operators
            threshold: absolute threshold value for gradients, has a min. value of 1e-15.
            delta: finite difference step size for gradient computation,
                    has a min. value of 1e-5.
            max_iterations: maximum number of macro iterations of the VQEAdapt algorithm.
            max_evals_grouped: max number of evaluations performed simultaneously
            aux_operators: Auxiliary operators to be evaluated at each eigenvalue
            quantum_instance: Quantum Instance or Backend

        Raises:
            ValueError: if var_form_base is not an instance of UCCSD.
            See also: qiskit/chemistry/components/variational_forms/uccsd_adapt.py
        """
        validate_min('threshold', threshold, 1e-15)
        validate_min('delta', delta, 1e-5)
        super().__init__(var_form=var_form_base,
                         optimizer=optimizer,
                         initial_point=initial_point,
                         quantum_instance=quantum_instance)
        self._ret = None  # type: Dict
        self._optimizer.set_max_evals_grouped(max_evals_grouped)
        if initial_point is None:
            self._initial_point = var_form_base.preferred_init_points
        self._operator = operator
        if not isinstance(var_form_base, UCCSD):
            raise ValueError("var_form_base has to be an instance of UCCSD.")
        self._var_form_base = var_form_base
        self._var_form_base.manage_hopping_operators()
        self._excitation_pool = self._var_form_base.excitation_pool \
            if excitation_pool is None else excitation_pool
        self._threshold = threshold
        self._delta = delta
        self._max_iterations = max_iterations
        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)
예제 #9
0
 def __init__(self,
              maxfun: int = 1000,
              factr: float = 10,
              iprint: int = -1,
              max_processes: Optional[int] = None) -> None:
     r"""
     Args:
         maxfun: Maximum number of function evaluations.
         factr : 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: 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: maximum number of processes allowed, has a min. value of 1 if not None.
     """
     if max_processes:
         validate_min('max_processes', max_processes, 1)
     super().__init__()
     for k, v in list(locals().items()):
         if k in self._OPTIONS:
             self._options[k] = v
     self._max_processes = max_processes
    def __init__(self,
                 num_target_qubits: int,
                 mu: float = 0,
                 sigma: float = 1,
                 low: float = 0,
                 high: float = 1) -> None:
        r"""
        Univariate lognormal distribution

        Args:
            num_target_qubits: number of qubits it acts on,
                has a min. value of 1.
            mu: expected value of considered normal distribution
            sigma: standard deviation of considered normal distribution
            low: lower bound, i.e., the value corresponding to \|0...0>
                         (assuming an equidistant grid)
            high: upper bound, i.e., the value corresponding to \|1...1>
                          (assuming an equidistant grid)
        """
        validate_min('num_target_qubits', num_target_qubits, 1)
        probabilities, _ = UnivariateDistribution.\
            pdf_to_probabilities(
                lambda x: lognorm.pdf(x, s=sigma, scale=np.exp(mu)),
                low, high, 2 ** num_target_qubits)
        super().__init__(num_target_qubits, probabilities, low, high)
예제 #11
0
    def __init__(
        self,
        operator: Optional[Union[OperatorBase, LegacyBaseOperator]] = None,
        k: int = 1,
        aux_operators: Optional[List[Optional[Union[
            OperatorBase, LegacyBaseOperator]]]] = None
    ) -> None:
        """
        Args:
            operator: Operator instance. If None is supplied it must be provided later before
                run() is called. Allowing None here permits the algorithm to be configured
                and used later when operator is available, say creating an instance an letting
                application stack use this algorithm with an operator it creates.
            k: How many eigenvalues are to be computed, has a min. value of 1.
            aux_operators: Auxiliary operators to be evaluated at each eigenvalue
        """
        validate_min('k', k, 1)
        super().__init__()

        self._operator = None
        self._aux_operators = None
        self._in_k = k
        self._k = k

        self.operator = operator
        self.aux_operators = aux_operators

        self._ret = {}  # type: Dict[str, Any]
    def __init__(
        self,
        transformation: FermionicTransformation,
        solver: MinimumEigensolverFactory,
        threshold: float = 1e-5,
        delta: float = 1,
        max_iterations: Optional[int] = None,
    ) -> None:
        """
        Args:
            transformation: a fermionic driver to operator transformation strategy.
            solver: a factory for the VQE solver employing a UCCSD variational form.
            threshold: the energy convergence threshold. It has a minimum value of 1e-15.
            delta: the finite difference step size for the gradient computation. It has a minimum
                value of 1e-5.
            max_iterations: the maximum number of iterations of the AdaptVQE algorithm.
        """
        validate_min('threshold', threshold, 1e-15)
        validate_min('delta', delta, 1e-5)

        super().__init__(transformation, solver)

        self._threshold = threshold
        self._delta = delta
        self._max_iterations = max_iterations
예제 #13
0
    def __init__(
        self,
        operator: Union[OperatorBase, LegacyBaseOperator] = None,
        optimizer: Optimizer = None,
        p: int = 1,
        initial_state: Optional[InitialState] = None,
        mixer: Union[OperatorBase, LegacyBaseOperator] = None,
        initial_point: Optional[np.ndarray] = None,
        max_evals_grouped: int = 1,
        aux_operators: Optional[List[Optional[Union[
            OperatorBase, LegacyBaseOperator]]]] = None,
        callback: Optional[Callable[[int, np.ndarray, float, float],
                                    None]] = None,
        quantum_instance: Optional[Union[QuantumInstance, BaseBackend]] = None
    ) -> None:
        """
        Args:
            operator: Qubit operator
            optimizer: A classical optimizer.
            p: the integer parameter p as specified in https://arxiv.org/abs/1411.4028,
                Has a minimum valid value of 1.
            initial_state: An optional initial state to prepend the QAOA circuit with
            mixer: the mixer Hamiltonian to evolve with. Allows support of optimizations in
                constrained subspaces as per https://arxiv.org/abs/1709.03489
            initial_point: An optional initial point (i.e. initial parameter values)
                for the optimizer. If ``None`` then it will simply compute a random one.
            max_evals_grouped: Max number of evaluations performed simultaneously. Signals the
                given optimizer that more than one set of parameters can be supplied so that
                potentially the expectation values can be computed in parallel. Typically this is
                possible when a finite difference gradient is used by the optimizer such that
                multiple points to compute the gradient can be passed and if computed in parallel
                improve overall execution time.
            aux_operators: Optional list of auxiliary operators to be evaluated with the eigenstate
                of the minimum eigenvalue main result and their expectation values returned.
                For instance in chemistry these can be dipole operators, total particle count
                operators so we can get values for these at the ground state.
            callback: a callback that can access the intermediate data during the optimization.
                Four parameter values are passed to the callback as follows during each evaluation
                by the optimizer for its current set of parameters as it works towards the minimum.
                These are: the evaluation count, the optimizer parameters for the
                variational form, the evaluated mean and the evaluated standard deviation.
            quantum_instance: Quantum Instance or Backend
        """
        validate_min('p', p, 1)

        self._p = p
        self._mixer_operator = mixer.to_opflow() if isinstance(
            mixer, LegacyBaseOperator) else mixer
        self._initial_state = initial_state

        # VQE will use the operator setter, during its constructor, which is overridden below and
        # will cause the var form to be built
        super().__init__(operator,
                         None,
                         optimizer,
                         initial_point=initial_point,
                         max_evals_grouped=max_evals_grouped,
                         callback=callback,
                         quantum_instance=quantum_instance,
                         aux_operators=aux_operators)
예제 #14
0
    def __init__(
            self,
            feature_dimension: int,
            depth: int = 2,
            data_map_func: Callable[[np.ndarray],
                                    float] = self_product) -> None:
        """
        Args:
            feature_dimension: The number of features
            depth: The number of repeated circuits. Defaults to 2, has a minimum value of 1.
            data_map_func: A mapping function for data x which can be supplied to override the
                default mapping from :meth:`self_product`.
        """
        warnings.warn(
            'The qiskit.aqua.components.feature_maps.FirstOrderExpansion object is '
            'deprecated as of 0.7.0 and will be removed no sooner than 3 months after '
            'the release. You should use qiskit.circuit.library.ZFeatureMap instead.',
            DeprecationWarning,
            stacklevel=2)

        validate_min('depth', depth, 1)
        super().__init__(feature_dimension,
                         depth,
                         z_order=1,
                         data_map_func=data_map_func)
예제 #15
0
 def __init__(self,
              max_trials: int = 1000,
              save_steps: int = 1,
              last_avg: int = 1,
              c0: float = _C0,
              c1: float = 0.1,
              c2: float = 0.602,
              c3: float = 0.101,
              c4: float = 0,
              skip_calibration: float = False) -> None:
     """
     Args:
         max_trials: Maximum number of iterations to perform.
         save_steps: Save intermediate info every save_steps step. It has a min. value of 1.
         last_avg: Averaged parameters over the last_avg iterations.
             If last_avg = 1, only the last iteration is considered. It has a min. value of 1.
         c0: The initial a. Step size to update parameters.
         c1: The initial c. The step size used to approximate gradient.
         c2: The alpha in the paper, and it is used to adjust a (c0) at each iteration.
         c3: The gamma in the paper, and it is used to adjust c (c1) at each iteration.
         c4: The parameter used to control a as well.
         skip_calibration: Skip calibration and use provided c(s) as is.
     """
     validate_min('save_steps', save_steps, 1)
     validate_min('last_avg', last_avg, 1)
     super().__init__()
     for k, v in locals().items():
         if k in self._OPTIONS:
             self._options[k] = v
     self._max_trials = max_trials
     self._parameters = np.array([c0, c1, c2, c3, c4])
     self._skip_calibration = skip_calibration
예제 #16
0
 def __init__(self,
              operator: WeightedPauliOperator,
              timelimit: int = 600,
              thread: int = 1,
              display: int = 2) -> None:
     """
     Args:
         operator: The Ising Hamiltonian as an Operator
         timelimit: A time limit in seconds for the execution
         thread: The number of threads that CPLEX uses. Setting this 0 lets CPLEX decide the
             number of threads to allocate, but this may not be ideal for small problems for
             which the default of 1 is more suitable.
         display: Decides what CPLEX reports to the screen and records in a log during
             mixed integer optimization. This value must be between 0 and 5 where the
             amount of information displayed increases with increasing values of this parameter.
     """
     validate_min('timelimit', timelimit, 1)
     validate_min('thread', thread, 0)
     validate_range('display', display, 0, 5)
     super().__init__()
     self._ins = IsingInstance()
     self._ins.parse(operator.to_dict()['paulis'])
     self._timelimit = timelimit
     self._thread = thread
     self._display = display
     self._sol = None
예제 #17
0
 def __init__(self, num_qubits: int) -> None:
     """
     Args:
         num_qubits: The number of qubits
     """
     validate_min('num_qubits', num_qubits, 1)
     super().__init__(num_qubits, degree=0)
예제 #18
0
    def __init__(
        self,
        num_eval_qubits: int,
        a_factory: Optional[CircuitFactory] = None,
        q_factory: Optional[CircuitFactory] = None,
        i_objective: Optional[int] = None,
        iqft: Optional[QuantumCircuit] = None,
        quantum_instance: Optional[Union[QuantumInstance, BaseBackend]] = None
    ) -> None:
        r"""
        Args:
            num_eval_qubits: Number of evaluation qubits, has a min. value of 1.
            a_factory: The CircuitFactory subclass object representing the problem unitary.
            q_factory: The CircuitFactory subclass object representing an amplitude estimation
                sample (based on a_factory).
            i_objective: The index of the objective qubit, i.e. the qubit marking 'good' solutions
                with the state \|1> and 'bad' solutions with the state \|0>.
            iqft: The Inverse Quantum Fourier Transform component, defaults to using a standard IQFT
                when None
            quantum_instance: Quantum Instance or Backend
        """
        validate_min('num_eval_qubits', num_eval_qubits, 1)
        super().__init__(a_factory, q_factory, i_objective, quantum_instance)

        # get parameters
        self._m = num_eval_qubits
        self._M = 2**num_eval_qubits
        self._iqft = iqft or QFT(self._m).inverse()
        self._circuit = None
        self._ret = {}  # type: Dict[str, Any]
예제 #19
0
 def __init__(self,
              feature_dimension: int,
              depth: int = 2,
              entangler_map: Optional[List[List[int]]] = None,
              entanglement: str = 'full',
              data_map_func: Callable[[np.ndarray], float] = self_product) -> None:
     """
     Args:
         feature_dimension: The number of features
         depth: The number of repeated circuits. Defaults to 2, has a minimum value of 1.
         entangler_map: Describes the connectivity of qubits, each list in the overall list
             describes [source, target]. Defaults to ``None`` where the map is created as per
             *entanglement* parameter.
             Note that the order in the list is the order of applying the two-qubit gate.
         entanglement: ('full' | 'linear'), generate the qubit connectivity by a predefined
             topology. Defaults to full which connects every qubit to each other. Linear
             connects each qubit to the next.
         data_map_func: A mapping function for data x which can be supplied to override the
             default mapping from :meth:`self_product`.
     """
     warnings.warn('The qiskit.aqua.components.feature_maps.SecondOrderExpansion object is '
                   'deprecated as of 0.7.0 and will be removed no sooner than 3 months after '
                   'the release. You should use qiskit.circuit.library.ZZFeatureMap instead.',
                   DeprecationWarning, stacklevel=2)
     validate_min('depth', depth, 1)
     validate_in_set('entanglement', entanglement, {'full', 'linear'})
     super().__init__(feature_dimension, depth, entangler_map, entanglement,
                      z_order=2, data_map_func=data_map_func)
예제 #20
0
 def __init__(self, num_qubits: int) -> None:
     """
     Args:
         num_qubits: Number of qubits, has a minimum value of 1.
     """
     super().__init__()
     validate_min('num_qubits', num_qubits, 1)
     self._num_qubits = num_qubits
예제 #21
0
 def __init__(self,
              num_qubits: int,
              degree: int = 0) -> None:
     validate_min('num_qubits', num_qubits, 1)
     validate_min('degree', degree, 0)
     super().__init__()
     self._num_qubits = num_qubits
     self._degree = degree
예제 #22
0
파일: ryrz.py 프로젝트: sergey55568/quantum
    def __init__(self,
                 num_qubits: int,
                 depth: int = 3,
                 entangler_map: Optional[List[List[int]]] = None,
                 entanglement: str = 'full',
                 initial_state: Optional[InitialState] = None,
                 entanglement_gate: str = 'cz',
                 skip_unentangled_qubits: bool = False) -> None:
        """
        Args:
            num_qubits: Number of qubits, has a minimum value of 1.
            depth: Number of rotation layers, has a minimum value of 1.
            entangler_map: Describe the connectivity of qubits, each list pair describes
                [source, target], or None for as defined by `entanglement`.
                Note that the order is the list is the order of applying the two-qubit gate.
            entanglement: ('full' | 'linear') overridden by 'entangler_map` if its
                provided. 'full' is all-to-all entanglement, 'linear' is nearest-neighbor.
            initial_state: An initial state object
            entanglement_gate: ('cz' | 'cx')
            skip_unentangled_qubits: Skip the qubits not in the entangler_map
        """
        warnings.warn(
            'The qiskit.aqua.components.variational_forms.RYRZ object is deprecated as '
            'of 0.7.0 and will be removed no sooner than 3 months after the release. You '
            'should use qiskit.circuit.library.EfficientSU2 (uses CX entangling) or '
            'qiskit.circuit.library.TwoLocal instead.',
            DeprecationWarning,
            stacklevel=2)

        validate_min('num_qubits', num_qubits, 1)
        validate_min('depth', depth, 1)
        validate_in_set('entanglement', entanglement, {'full', 'linear'})
        validate_in_set('entanglement_gate', entanglement_gate, {'cz', 'cx'})
        super().__init__()
        self._num_qubits = num_qubits
        self._depth = depth
        if entangler_map is None:
            self._entangler_map = VariationalForm.get_entangler_map(
                entanglement, num_qubits)
        else:
            self._entangler_map = VariationalForm.validate_entangler_map(
                entangler_map, num_qubits)
        # determine the entangled qubits
        all_qubits = []
        for src, targ in self._entangler_map:
            all_qubits.extend([src, targ])
        self._entangled_qubits = sorted(list(set(all_qubits)))
        self._initial_state = initial_state
        self._entanglement_gate = entanglement_gate
        self._skip_unentangled_qubits = skip_unentangled_qubits

        # for the first layer
        self._num_parameters = len(self._entangled_qubits) * 2 if self._skip_unentangled_qubits \
            else self._num_qubits * 2
        # for repeated block
        self._num_parameters += len(self._entangled_qubits) * depth * 2
        self._bounds = [(-np.pi, np.pi)] * self._num_parameters
        self._support_parameterized_circuit = True
예제 #23
0
 def __init__(self,
              num_qubits: int,
              state: str = 'zero',
              state_vector: Optional[Union[np.ndarray, StateFn]] = None,
              circuit: Optional[QuantumCircuit] = None) -> None:
     """
     Args:
         num_qubits: Number of qubits, has a minimum value of 1.
         state: Use a predefined state of ('zero' | 'uniform' | 'random')
         state_vector: An optional vector of ``complex`` or ``float`` representing the state as
             a probability distribution which will be normalized to a total probability of 1
             when initializing the qubits. The length of the vector must be :math:`2^q`, where
             :math:`q` is the *num_qubits* value. When provided takes precedence over *state*.
         circuit: A quantum circuit for the desired initial state. When provided takes
             precedence over both *state_vector* and *state*.
     Raises:
         AquaError: invalid input
     """
     validate_min('num_qubits', num_qubits, 1)
     validate_in_set('state', state, {'zero', 'uniform', 'random'})
     super().__init__()
     self._num_qubits = num_qubits
     self._state = state
     size = np.power(2, self._num_qubits)
     self._circuit = None
     if isinstance(state_vector, StateFn):
         state_vector = state_vector.to_matrix()
     # pylint: disable=comparison-with-callable
     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.random(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
예제 #24
0
 def __init__(self, feature_dimension: int = 2) -> None:
     """
     Args:
         feature_dimension: The feature dimension, has a minimum value of 1.
     """
     validate_min('feature_dimension', feature_dimension, 1)
     super().__init__()
     self._feature_dimension = feature_dimension
     self._num_qubits = next_power_of_2_base(feature_dimension)
예제 #25
0
파일: grover.py 프로젝트: AW-AlanWu/PuGua
def _check_deprecated_args(init_state, mct_mode, rotation_counts, lam,
                           num_iterations):
    """Check the deprecated args, can be removed 3 months after 0.8.0."""

    # init_state has been renamed to state_preparation
    if init_state is not None:
        warnings.warn(
            'The init_state argument is deprecated as of 0.8.0, and will be removed '
            'no earlier than 3 months after the release date. You should use the '
            'state_preparation argument instead and pass a QuantumCircuit or '
            'Statevector instead of an InitialState.',
            DeprecationWarning,
            stacklevel=3)

    if mct_mode is not None:
        validate_in_set(
            'mct_mode', mct_mode,
            {'basic', 'basic-dirty-ancilla', 'advanced', 'noancilla'})
        warnings.warn(
            'The mct_mode argument is deprecated as of 0.8.0, and will be removed no '
            'earlier than 3 months after the release date. If you want to use a '
            'special MCX mode you should use the GroverOperator in '
            'qiskit.circuit.library directly and pass it to the grover_operator '
            'keyword argument.',
            DeprecationWarning,
            stacklevel=3)

    if rotation_counts is not None:
        warnings.warn(
            'The rotation_counts argument is deprecated as of 0.8.0, and will be '
            'removed no earlier than 3 months after the release date. '
            'If you want to use the incremental mode with the rotation_counts '
            'argument or you should use the iterations argument instead and pass '
            'a list of integers',
            DeprecationWarning,
            stacklevel=3)

    if lam is not None:
        warnings.warn(
            'The lam argument is deprecated as of 0.8.0, and will be '
            'removed no earlier than 3 months after the release date. '
            'If you want to use the incremental mode with the lam argument, '
            'you should use the iterations argument instead and pass '
            'a list of integers calculated with the lam argument.',
            DeprecationWarning,
            stacklevel=3)

    if num_iterations is not None:
        validate_min('num_iterations', num_iterations, 1)
        warnings.warn(
            'The num_iterations argument is deprecated as of 0.8.0, and will be '
            'removed no earlier than 3 months after the release date. '
            'If you want to use the num_iterations argument '
            'you should use the iterations argument instead and pass an integer '
            'for the number of iterations.',
            DeprecationWarning,
            stacklevel=3)
예제 #26
0
    def __init__(
        self,
        N: int = 15,
        a: int = 2,
        quantum_instance: Optional[Union[QuantumInstance, BaseBackend,
                                         Backend]] = None
    ) -> None:
        """
        Args:
            N: The integer to be factored, has a min. value of 3.
            a: Any integer that satisfies 1 < a < N and gcd(a, N) = 1.
            quantum_instance: Quantum Instance or Backend

         Raises:
            ValueError: Invalid input
        """
        warn_package('aqua.algorithms.factorizers',
                     'qiskit.algorithms.factorizers', 'qiskit-terra')
        validate_min('N', N, 3)
        validate_min('a', a, 2)
        super().__init__(quantum_instance)
        self._n = None  # type: Optional[int]
        self._up_qreg = None
        self._down_qreg = None  # type: Optional[QuantumRegister]
        self._aux_qreg = None  # type: Optional[QuantumRegister]

        # check the input integer
        if N < 1 or N % 2 == 0:
            raise ValueError(
                '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 ValueError(
                'The integer a needs to satisfy a < N and gcd(a, N) = 1.')

        self._a = a

        self._ret = AlgorithmResult({
            "factors": [],
            "total_counts": 0,
            "successful_counts": 0
        })

        # 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)

        self._qft = QFT(do_swaps=False).to_instruction()
        self._iqft = self._qft.inverse()

        self._phi_add_N = None  # type: Optional[Gate]
        self._iphi_add_N = None
예제 #27
0
    def __init__(self,
                 atom: Union[str,
                             List[str]] = 'H 0.0 0.0 0.0; H 0.0 0.0 0.735',
                 unit: UnitsType = UnitsType.ANGSTROM,
                 charge: int = 0,
                 spin: int = 0,
                 basis: str = 'sto3g',
                 hf_method: HFMethodType = HFMethodType.RHF,
                 conv_tol: float = 1e-9,
                 max_cycle: int = 50,
                 init_guess: InitialGuess = InitialGuess.MINAO,
                 max_memory: Optional[int] = None) -> None:
        """
        Initializer

        Args:
            atom: atom list or string separated by semicolons or line breaks
            unit: angstrom or bohr
            charge: charge
            spin: spin
            basis: basis set
            hf_method: Hartree-Fock Method type
            conv_tol: Convergence tolerance see PySCF docs and pyscf/scf/hf.py
            max_cycle: Max convergence cycles see PySCF docs and pyscf/scf/hf.py,
                       has a min. value of 1.
            init_guess: See PySCF pyscf/scf/hf.py init_guess_by_minao/1e/atom methods
            max_memory: 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_min('max_cycle', max_cycle, 1)
        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
예제 #28
0
    def __init__(self,
                 oracle: Oracle,
                 init_state: Optional[InitialState] = None,
                 incremental: bool = False,
                 num_iterations: int = 1,
                 mct_mode: str = 'basic') -> None:
        """
        Constructor.

        Args:
            oracle: the oracle component
            init_state: the initial quantum state preparation
            incremental: boolean flag for whether to use incremental search mode or not
            num_iterations: the number of iterations to use for amplitude amplification,
                            has a min. value of 1.
            mct_mode: mct mode
        Raises:
            AquaError: evaluate_classically() missing from the input oracle
        """
        validate_min('num_iterations', num_iterations, 1)
        validate_in_set(
            'mct_mode', mct_mode,
            {'basic', 'basic-dirty-ancilla', 'advanced', 'noancilla'})
        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
        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
예제 #29
0
    def __init__(self,
                 operator: BaseOperator,
                 optimizer: Optimizer,
                 p: int = 1,
                 initial_state: Optional[InitialState] = None,
                 mixer: Optional[BaseOperator] = None,
                 initial_point: Optional[np.ndarray] = None,
                 max_evals_grouped: int = 1,
                 aux_operators: Optional[List[BaseOperator]] = None,
                 callback: Optional[Callable[[int, np.ndarray, float, float],
                                             None]] = None,
                 auto_conversion: bool = True) -> None:
        """
        Args:
            operator: Qubit operator
            optimizer: The classical optimizer to use.
            p: the integer parameter p as specified in https://arxiv.org/abs/1411.4028,
                has a min. value of 1.
            initial_state: the initial state to prepend the QAOA circuit with
            mixer: the mixer Hamiltonian to evolve with. Allows support of
                   optimizations in constrained subspaces
                   as per https://arxiv.org/abs/1709.03489
            optimizer: the classical optimization algorithm.
            initial_point: optimizer initial point.
            max_evals_grouped: max number of evaluations to be performed simultaneously.
            aux_operators: aux operators
            callback: 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: 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_min('p', p, 1)
        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)
예제 #30
0
    def __init__(self,
                 atoms: Union[str, List[str]] =
                 'H 0.0 0.0 0.0; H 0.0 0.0 0.735',
                 units: UnitsType = UnitsType.ANGSTROM,
                 charge: int = 0,
                 multiplicity: int = 1,
                 basis: BasisType = BasisType.BSTO3G,
                 hf_method: HFMethodType = HFMethodType.RHF,
                 tol: float = 1e-8,
                 maxiters: int = 100,
                 molecule: Optional[Molecule] = None) -> None:
        """
        Args:
            atoms: Atoms list or string separated by semicolons or line breaks. Each element in the
                list is an atom followed by position e.g. `H 0.0 0.0 0.5`. The preceding example
                shows the `XYZ` format for position but `Z-Matrix` format is supported too here.
            units: Angstrom or Bohr
            charge: Charge on the molecule
            multiplicity: Spin multiplicity (2S+1)
            basis: Basis set; sto3g, 6-31g or 6-31g**
            hf_method: Hartree-Fock Method type
            tol: Convergence tolerance see pyquante2.scf hamiltonians and iterators
            maxiters: Convergence max iterations see pyquante2.scf hamiltonians and iterators,
                has a min. value of 1.
            molecule: A driver independent Molecule definition instance may be provided. When
                a molecule is supplied the `atoms`, `units`, `charge` and `multiplicity` parameters
                are all ignored as the Molecule instance now defines these instead. The Molecule
                object is read when the driver is run and converted to the driver dependent
                configuration for the computation. This allows, for example, the Molecule geometry
                to be updated to compute different points.

        Raises:
            QiskitChemistryError: Invalid Input
        """
        validate_min('maxiters', maxiters, 1)
        self._check_valid()
        if not isinstance(atoms, str) and not isinstance(atoms, list):
            raise QiskitChemistryError("Invalid atom input for PYQUANTE Driver '{}'".format(atoms))

        if isinstance(atoms, list):
            atoms = ';'.join(atoms)
        elif isinstance(atoms, str):
            atoms = atoms.replace('\n', ';')

        super().__init__(molecule=molecule,
                         basis=basis.value,
                         hf_method=hf_method.value,
                         supports_molecule=True)
        self._atoms = atoms
        self._units = units.value
        self._charge = charge
        self._multiplicity = multiplicity
        self._tol = tol
        self._maxiters = maxiters