def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance Args: params: parameters dictionary algo_input: Input instance """ if algo_input is not None: raise AquaError("Input instance not supported.") ae_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) num_eval_qubits = ae_params.get('num_eval_qubits') # Set up uncertainty model and problem uncertainty_model_params = params.get( Pluggable.SECTION_KEY_UNCERTAINTY_MODEL) uncertainty_model_params['num_target_qubits'] = num_eval_qubits uncertainty_model = get_pluggable_class( PluggableType.UNCERTAINTY_MODEL, uncertainty_model_params['name']).init_params(params) uncertainty_problem_params = params.get( Pluggable.SECTION_KEY_UNCERTAINTY_PROBLEM) uncertainty_problem_params['uncertainty_model'] = uncertainty_model uncertainty_problem = get_pluggable_class( PluggableType.UNCERTAINTY_PROBLEM, uncertainty_problem_params['name']).init_params(params) # Set up iqft, we need to add num qubits to params which is our num_ancillae bits here iqft_params = params.get(Pluggable.SECTION_KEY_IQFT) iqft_params['num_qubits'] = num_eval_qubits iqft = get_pluggable_class(PluggableType.IQFT, iqft_params['name']).init_params(params) return cls(num_eval_qubits, uncertainty_problem, q_factory=None, iqft=iqft)
def __init__(self, expression=None, optimization='off', mct_mode='basic'): """ Constructor. Args: expression (str): The string of the desired logical expression. It could be either in the DIMACS CNF format, or a general boolean logical expression, such as 'a ^ b' and 'v[0] & (~v[1] | v[2])' optimization (str): The mode of optimization to use for minimizing the circuit. Currently, besides no optimization ('off'), Aqua also supports an 'espresso' mode <https://en.wikipedia.org/wiki/Espresso_heuristic_logic_minimizer> mct_mode (str): The mode to use for building Multiple-Control Toffoli. """ self.validate(locals()) super().__init__() self._mct_mode = mct_mode self._optimization = optimization from pyeda.boolalg.expr import ast2expr, expr from pyeda.parsing.dimacs import parse_cnf if expression is None: raw_expr = expr(None) else: try: raw_expr = expr(expression) except: try: raw_expr = ast2expr( parse_cnf(expression.strip(), varname='v')) except: raise AquaError( 'Failed to parse the input expression: {}.'.format( expression)) self._expr = raw_expr self._process_expr() self.construct_circuit()
def _build_single_hopping_operator(index, num_particles, num_orbitals, qubit_mapping, two_qubit_reduction, z2_symmetries): h_1 = np.zeros((num_orbitals, num_orbitals), dtype=complex) h_2 = np.zeros( (num_orbitals, num_orbitals, num_orbitals, num_orbitals), dtype=complex) if len(index) == 2: i, j = index h_1[i, j] = 4.0 elif len(index) == 4: i, j, k, m = index h_2[i, j, k, m] = 16.0 fer_op = FermionicOperator(h_1, h_2) qubit_op = fer_op.mapping(qubit_mapping) if two_qubit_reduction: qubit_op = Z2Symmetries.two_qubit_reduction( qubit_op, num_particles) commutativities = [] if not z2_symmetries.is_empty(): for symmetry in z2_symmetries.symmetries: symmetry_op = WeightedPauliOperator(paulis=[[1.0, symmetry]]) commuting = qubit_op.commute_with(symmetry_op) anticommuting = qubit_op.anticommute_with(symmetry_op) if commuting != anticommuting: # only one of them is True if commuting: commutativities.append(True) elif anticommuting: commutativities.append(False) else: raise AquaError( "Symmetry {} is nor commute neither anti-commute " "to exciting operator.".format(symmetry.to_label())) return qubit_op, commutativities
def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance Args: params (dict): parameters dictionary algo_input (EnergyInput): EnergyInput instance """ if algo_input is None: raise AquaError("EnergyInput instance is required.") operator = algo_input.qubit_op qaoa_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) operator_mode = qaoa_params.get('operator_mode') p = qaoa_params.get('p') initial_point = qaoa_params.get('initial_point') batch_mode = qaoa_params.get('batch_mode') init_state_params = params.get(Pluggable.SECTION_KEY_INITIAL_STATE) init_state_params['num_qubits'] = operator.num_qubits init_state = get_pluggable_class( PluggableType.INITIAL_STATE, init_state_params['name']).init_params(params) # Set up optimizer opt_params = params.get(Pluggable.SECTION_KEY_OPTIMIZER) optimizer = get_pluggable_class(PluggableType.OPTIMIZER, opt_params['name']).init_params(params) return cls(operator, optimizer, p=p, initial_state=init_state, operator_mode=operator_mode, initial_point=initial_point, batch_mode=batch_mode, aux_operators=algo_input.aux_ops)
def construct_circuit( self, parameter: Union[List[float], List[Parameter], np.ndarray] ) -> OperatorBase: r""" Generate the ansatz circuit and expectation value measurement, and return their runnable composition. Args: parameter: Parameters for the ansatz circuit. Returns: The Operator equalling the measurement of the ansatz :class:`StateFn` by the Observable's expectation :class:`StateFn`. Raises: AquaError: If no operator has been provided. """ if self.operator is None: raise AquaError("The operator was never provided.") # ensure operator and varform are compatible self._check_operator_varform() if isinstance(self.var_form, QuantumCircuit): param_dict = dict(zip(self._var_form_params, parameter)) # type: Dict wave_function = self.var_form.assign_parameters(param_dict) else: wave_function = self.var_form.construct_circuit(parameter) # If ExpectationValue was never created, create one now. if not self.expectation: self._try_set_expectation_value_from_factory() observable_meas = self.expectation.convert( StateFn(self.operator, is_measurement=True)) ansatz_circuit_op = CircuitStateFn(wave_function) return observable_meas.compose(ansatz_circuit_op).reduce()
def _construct_grover_operator(oracle, state_preparation, mct_mode): # check the type of state_preparation if isinstance(state_preparation, InitialState): warnings.warn( 'Passing an InitialState component is deprecated as of 0.8.0, and ' 'will be removed no earlier than 3 months after the release date. ' 'You should pass a QuantumCircuit instead.', DeprecationWarning, stacklevel=3) if isinstance(oracle, Oracle): state_preparation = state_preparation.construct_circuit( mode='circuit', register=oracle.variable_register) else: raise TypeError( 'If init_state is of type InitialState, oracle must be of type ' 'Oracle') elif not (isinstance(state_preparation, QuantumCircuit) or state_preparation is None): raise TypeError('Unsupported type "{}" of state_preparation'.format( type(state_preparation))) # check to oracle type and if necessary convert the deprecated Oracle component to # a circuit reflection_qubits = None if isinstance(oracle, Oracle): if not callable(getattr(oracle, "evaluate_classically", None)): raise AquaError('Missing the evaluate_classically() method \ from the provided oracle instance.') oracle, reflection_qubits = _oracle_component_to_circuit(oracle) elif not isinstance(oracle, (QuantumCircuit, Statevector)): raise TypeError('Unsupported type "{}" of oracle'.format(type(oracle))) grover_operator = GroverOperator(oracle=oracle, state_preparation=state_preparation, reflection_qubits=reflection_qubits, mcx_mode=mct_mode) return grover_operator
def __init__(self, state_vector): """Constructor. Args: state_vector (numpy.ndarray): vector representation of the desired quantum state Raises: AquaError: invalid input """ warnings.warn( 'The StateVectorCircuit class is deprecated as of Qiskit Aqua 0.9.0 and will ' 'be removed no earlier than 3 months after the release. If you need to ' 'initialize a circuit, use the QuantumCircuit.initialize or ' 'QuantumCircuit.isometry methods. For a parameterized initialization, try ' 'the qiskit.ml.circuit.library.RawFeatureVector class.', DeprecationWarning, stacklevel=2) if not is_power_of_2(len(state_vector)): raise AquaError( 'The length of the input state vector needs to be a power of 2.' ) self._num_qubits = log2(len(state_vector)) self._state_vector = normalize_vector(state_vector)
def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance Args: params: parameters dictionary algo_input: input instance """ if algo_input is not None: raise AquaError("Unexpected Input instance.") grover_params = params.get(QuantumAlgorithm.SECTION_KEY_ALGORITHM) incremental = grover_params.get(Grover.PROP_INCREMENTAL) num_iterations = grover_params.get(Grover.PROP_NUM_ITERATIONS) mct_mode = grover_params.get(Grover.PROP_MCT_MODE) oracle_params = params.get(QuantumAlgorithm.SECTION_KEY_ORACLE) oracle = get_pluggable_class( PluggableType.ORACLE, oracle_params['name']).init_params(oracle_params) return cls(oracle, incremental=incremental, num_iterations=num_iterations, mct_mode=mct_mode)
def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance Args: params: parameters dictionary algo_input: Input instance """ if algo_input is not None: raise AquaError("Input instance not supported.") ae_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) log_max_evals = ae_params.get('log_max_evals') # Set up uncertainty problem. The params can include an uncertainty model # type dependent on the uncertainty problem and is this its responsibility # to create for itself from the complete params set that is passed to it. uncertainty_problem_params = params.get( Pluggable.SECTION_KEY_UNCERTAINTY_PROBLEM) uncertainty_problem = get_pluggable_class( PluggableType.UNCERTAINTY_PROBLEM, uncertainty_problem_params['name']).init_params(params) return cls(log_max_evals, uncertainty_problem, q_factory=None)
def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance. Args: params: parameters dictionary algo_input: EnergyInput instance """ if algo_input is None: raise AquaError("EnergyInput instance is required.") operator = algo_input.qubit_op evolution_fidelity_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) expansion_order = evolution_fidelity_params.get(EvolutionFidelity.PROP_EXPANSION_ORDER) # Set up initial state, we need to add computed num qubits to params initial_state_params = params.get(Pluggable.SECTION_KEY_INITIAL_STATE) initial_state_params['num_qubits'] = operator.num_qubits initial_state = get_pluggable_class(PluggableType.INITIAL_STATE, initial_state_params['name']).init_params(params) return cls(operator, initial_state, expansion_order)
def run(self, quantum_instance: Optional[Union[QuantumInstance, BaseBackend]] = None, **kwargs) -> Dict: """Execute the algorithm with selected backend. Args: quantum_instance: the experimental setting. kwargs (dict): kwargs Returns: dict: results of an algorithm. Raises: AquaError: If a quantum instance or backend has not been provided """ if quantum_instance is None and self.quantum_instance is None: raise AquaError("Quantum device or backend " "is needed since you are running quantum algorithm.") if isinstance(quantum_instance, BaseBackend): self.set_backend(quantum_instance, **kwargs) else: if quantum_instance is not None: self.quantum_instance = quantum_instance return self._run()
def register_pluggable(cls): """ Registers a pluggable class Args: cls (Pluggable): Pluggable class. Returns: str: pluggable name Raises: AquaError: Class doesn't derive from known pluggable """ _discover_on_demand() pluggable_type = None for p_type, c in _get_pluggables_types_dict().items(): if issubclass(cls, c): pluggable_type = p_type break if pluggable_type is None: raise AquaError( 'Could not register class {} is not subclass of any known pluggable' .format(cls)) return _register_pluggable(pluggable_type, cls)
def __init__(self, N=15): """ Constructor. Args: N (int): The integer to be factored. """ self.validate(locals()) super().__init__() # 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 self._ret = {'factors': []} # check if the input integer is a power tf, b, p = is_power(N, return_decomposition=True) if tf: logger.warning(f'The input integer is a power: {N}={b}^{p}.') self._ret['factors'].append(b)
def confidence_interval(self, alpha, kind='fisher'): """ Proxy calling the correct method to compute the confidence interval, according to the value of `kind` """ # check if AE did run already if 'estimation' not in self._ret.keys(): raise AquaError('Call run() first!') # if statevector simulator the estimate is exact if self._quantum_instance.is_statevector: return 2 * [self._ret['estimation']] if kind in ['likelihood_ratio', 'lr']: return self._likelihood_ratio_ci(alpha) if kind in ['fisher', 'fi']: return self._fisher_ci(alpha, observed=False) if kind in ['observed_fisher', 'observed_information', 'oi']: return self._fisher_ci(alpha, observed=True) raise NotImplementedError('CI `{}` is not implemented.'.format(kind))
def dimacs_cnf_to_cnf_ast(dimacs): lines = [ ll for ll in [l.strip().lower() for l in dimacs.strip().split('\n')] if len(ll) > 0 and not ll[0] == 'c' ] # for line_partition in partition_lines(lines[1:], partitions): clauses = [] for line in lines[1:]: toks = line.split() if not toks[-1] == '0': raise AquaError('Unrecognized dimacs line {}.'.format(line)) else: clauses.append([int(t) for t in toks[:-1]]) clause_asts = [] for clause in clauses: ast_lit_nodes = [('lit', literal) for literal in clause] ast_clause_node = ('or', *ast_lit_nodes) clause_asts.append(ast_clause_node) cnf_ast = ('and', *clause_asts) return cnf_ast
def get_optimal_vector(self): # pylint: disable=import-outside-toplevel from qiskit.aqua.utils.run_circuits import find_regs_by_name if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal vector before running the " "algorithm to find optimal params.") qc = self.get_optimal_circuit() if self._quantum_instance.is_statevector: ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_statevector(qc) else: c = ClassicalRegister(qc.width(), name='c') q = find_regs_by_name(qc, 'q') qc.add_register(c) qc.barrier(q) qc.measure(q, c) tmp_cache = self._quantum_instance.circuit_cache self._quantum_instance._circuit_cache = None ret = self._quantum_instance.execute(qc) self._quantum_instance._circuit_cache = tmp_cache self._ret['min_vector'] = ret.get_counts(qc) return self._ret['min_vector']
def _do_checks(flags, qr_variables, qb_target, qr_ancillae, circuit): # check flags if flags is None: flags = [1 for i in range(len(qr_variables))] else: if len(flags) > len(qr_variables): raise AquaError('`flags` cannot be longer than `qr_variables`.') # check variables # TODO: improve the check if isinstance(qr_variables, QuantumRegister) or isinstance(qr_variables, list): variable_qubits = [qb for qb, i in zip(qr_variables, flags) if not i == 0] else: raise ValueError('A QuantumRegister or list of qubits is expected for variables.') # check target if isinstance(qb_target, tuple): target_qubit = qb_target else: raise ValueError('A single qubit is expected for the target.') # check ancilla if qr_ancillae is None: ancillary_qubits = [] elif isinstance(qr_ancillae, QuantumRegister): ancillary_qubits = [qb for qb in qr_ancillae] elif isinstance(qr_ancillae, list): ancillary_qubits = qr_ancillae else: raise ValueError('An optional list of qubits or a QuantumRegister is expected for ancillae.') all_qubits = variable_qubits + [target_qubit] + ancillary_qubits circuit._check_qargs(all_qubits) circuit._check_dups(all_qubits) return flags
def _add_or_sub(self, other, operation, copy=True): """ Add two operators either extend (in-place) or combine (copy) them. The addition performs optimized combination of two operators. If `other` has identical basis, the coefficient are combined rather than appended. Args: other (WeightedPauliOperator): to-be-combined operator operation (callable or str): add or sub callable from operator copy (bool): working on a copy or self Returns: WeightedPauliOperator: operator Raises: AquaError: two operators have different number of qubits. """ if not self.is_empty() and not other.is_empty(): if self.num_qubits != other.num_qubits: raise AquaError("Can not add/sub two operators with different number of qubits.") ret_op = self.copy() if copy else self for pauli in other.paulis: pauli_label = pauli[1].to_label() idx = ret_op._paulis_table.get(pauli_label, None) if idx is not None: ret_op._paulis[idx][0] = operation(ret_op._paulis[idx][0], pauli[0]) else: new_pauli = deepcopy(pauli) ret_op._paulis_table[pauli_label] = len(ret_op._paulis) ret_op._basis.append((new_pauli[1], [len(ret_op._paulis)])) new_pauli[0] = operation(0.0, pauli[0]) ret_op._paulis.append(new_pauli) return ret_op
def construct_circuit(self, parameter, backend=None, use_simulator_operator_mode=False, statevector_mode=None, circuit_name_prefix=''): """Generate the circuits. Args: parameter (numpy.ndarray): parameters for variational form. backend (qiskit.BaseBackend, optional): backend object. use_simulator_operator_mode (bool, optional): is backend from AerProvider, if True and mode is paulis, single circuit is generated. statevector_mode (bool, optional): indicate which type of simulator are going to use. circuit_name_prefix (str, optional): a prefix of circuit name Returns: [QuantumCircuit]: the generated circuits with Hamiltonian. """ if backend is not None: warnings.warn( "backend option is deprecated and it will be removed after 0.6, " "Use `statevector_mode` instead", DeprecationWarning) statevector_mode = is_statevector_backend(backend) else: if statevector_mode is None: raise AquaError( "Either backend or statevector_mode need to be provided.") wave_function = self._var_form.construct_circuit(parameter) circuits = self._operator.construct_evaluation_circuit( use_simulator_operator_mode=use_simulator_operator_mode, wave_function=wave_function, statevector_mode=statevector_mode, circuit_name_prefix=circuit_name_prefix) return circuits
def evaluation_instruction(self, statevector_mode, use_simulator_operator_mode=False): """ Args: statevector_mode (bool): will it be run on statevector simulator or not use_simulator_operator_mode (bool): will it use qiskit aer simulator operator mode Returns: dict: Pauli-instruction pair. Raises: AquaError: if Operator is empty """ if self.is_empty(): raise AquaError("Operator is empty, check the operator.") instructions = {} qr = QuantumRegister(self.num_qubits) qc = QuantumCircuit(qr) if statevector_mode and not use_simulator_operator_mode: for _, pauli in self._paulis: tmp_qc = qc.copy(name="Pauli " + pauli.to_label()) if np.all(np.logical_not(pauli.z)) and np.all(np.logical_not(pauli.x)): # all I continue # This explicit barrier is needed for statevector simulator since Qiskit-terra # will remove global phase at default compilation level but the results here # rely on global phase. tmp_qc.barrier([x for x in range(self.num_qubits)]) tmp_qc.append(pauli, [x for x in range(self.num_qubits)]) instructions[pauli.to_label()] = tmp_qc.to_instruction() else: cr = ClassicalRegister(self.num_qubits) qc.add_register(cr) for basis, _ in self._basis: tmp_qc = qc.copy(name="Pauli " + basis.to_label()) tmp_qc = pauli_measurement(tmp_qc, basis, qr, cr, barrier=True) instructions[basis.to_label()] = tmp_qc.to_instruction() return instructions
def __init__(self, epsilon, alpha, ci_method='beta', min_ratio=2, a_factory=None, q_factory=None, i_objective=None): """ The output of the algorithm is an estimate for the amplitude `a`, that with at least probability 1 - alpha has an error of epsilon. The number of A operator calls scales linearly in 1/epsilon (up to a logarithmic factor). Args: epsilon (float): target precision for estimation target `a` alpha (float): confidence level, the target probability is 1 - alpha ci_method (str): statistical method used to estimate the confidence intervals in each iteration, can be 'chernoff' for the Chernoff intervals or 'beta' for the Clopper-Pearson intervals (default) min_ratio (float): minimal q-ratio (K_{i+1} / K_i) for FindNextK a_factory (CircuitFactory): the A operator, specifying the QAE problem q_factory (CircuitFactory): the Q operator (Grover operator), constructed from the A operator i_objective (int): index of the objective qubit, that marks the 'good/bad' states Raises: AquaError: if the method to compute the confidence intervals is not supported """ validate(locals(), self._INPUT_SCHEMA) super().__init__(a_factory, q_factory, i_objective) # store parameters self._epsilon = epsilon self._alpha = alpha self._min_ratio = min_ratio if ci_method in ['chernoff', 'beta']: self._ci_method = ci_method else: raise AquaError('invalid method to compute confidence intervals') # results dictionary self._ret = {}
def construct_kernel_matrix(self, x1_vec, x2_vec=None, quantum_instance=None): """ Construct kernel matrix, if x2_vec is None, self-innerproduct is conducted. Notes: When using `statevector_simulator`, we only build the circuits for Psi(x1)|0> rather than Psi(x2)^dagger Psi(x1)|0>, and then we perform the inner product classically. That is, for `statevector_simulator`, the total number of circuits will be O(N) rather than O(N^2) for `qasm_simulator`. Args: x1_vec (numpy.ndarray): data points, 2-D array, N1xD, where N1 is the number of data, D is the feature dimension x2_vec (numpy.ndarray): data points, 2-D array, N2xD, where N2 is the number of data, D is the feature dimension quantum_instance (QuantumInstance): quantum backend with all settings Returns: numpy.ndarray: 2-D matrix, N1xN2 Raises: AquaError: Quantum instance is not present. """ self._quantum_instance = self._quantum_instance \ if quantum_instance is None else quantum_instance if self._quantum_instance is None: raise AquaError( "Either setup quantum instance or provide it in the parameter." ) return QSVM.get_kernel_matrix(self._quantum_instance, self.feature_map, x1_vec, x2_vec)
def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance. Args: params (dict): parameters dictionary algo_input (EnergyInput): EnergyInput instance Returns: VQE: vqe object Raises: AquaError: invalid input """ if algo_input is None: raise AquaError("EnergyInput instance is required.") operator = algo_input.qubit_op vqe_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) initial_point = vqe_params.get('initial_point') max_evals_grouped = vqe_params.get('max_evals_grouped') # Set up variational form, we need to add computed num qubits # Pass all parameters so that Variational Form can create its dependents var_form_params = params.get(Pluggable.SECTION_KEY_VAR_FORM) var_form_params['num_qubits'] = operator.num_qubits var_form = get_pluggable_class(PluggableType.VARIATIONAL_FORM, var_form_params['name']).init_params(params) # Set up optimizer opt_params = params.get(Pluggable.SECTION_KEY_OPTIMIZER) optimizer = get_pluggable_class(PluggableType.OPTIMIZER, opt_params['name']).init_params(params) return cls(operator, var_form, optimizer, initial_point=initial_point, max_evals_grouped=max_evals_grouped, aux_operators=algo_input.aux_ops)
def test(self, data, labels, quantum_instance=None): """ Test the svm. Args: data (numpy.ndarray): NxD array, where N is the number of data, D is the feature dimension. labels (numpy.ndarray): Nx1 array, where N is the number of data quantum_instance (QuantumInstance): quantum backend with all setting Returns: float: accuracy Raises: AquaError: Quantum instance is not present. """ self._quantum_instance = self._quantum_instance \ if quantum_instance is None else quantum_instance if self._quantum_instance is None: raise AquaError( "Either setup quantum instance or provide it in the parameter." ) return self.instance.test(data, labels)
def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True): """Construct the circuit. Args: mode (str): 'matrix' or 'circuit' qubits (QuantumRegister or qubits): register or qubits to build the circuit on. circuit (QuantumCircuit): circuit for construction. do_swaps (bool): include the swaps. Returns: The matrix or circuit depending on the specified mode. """ if mode == 'circuit': return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps) elif mode == 'matrix': return self._build_matrix() else: raise AquaError('Unrecognized mode: {}.'.format(mode))
def init_params(cls, params, algo_input): """ Initialize qGAN via parameters dictionary and algorithm input instance. Args: params: parameters dictionary algo_input: Input instance Returns: QGAN: qgan object """ if algo_input is None: raise AquaError("Input instance not supported.") qgan_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) num_qubits = qgan_params.get('num_qubits') batch_size = qgan_params.get('batch_size') num_epochs = qgan_params.get('num_epochs') seed = qgan_params.get('seed') tol_rel_ent = qgan_params.get('tol_rel_ent') snapshot_dir = qgan_params.get('snapshot_dir') discriminator_params = params.get( Pluggable.SECTION_KEY_DISCRIMINATIVE_NETWORK) generator_params = params.get(Pluggable.SECTION_KEY_GENERATIVE_NETWORK) generator_params['num_qubits'] = num_qubits discriminator = get_pluggable_class( PluggableType.DISCRIMINATIVE_NETWORK, discriminator_params['name']).init_params(params) generator = get_pluggable_class( PluggableType.GENERATIVE_NETWORK, generator_params['name']).init_params(params) return cls(algo_input.data, algo_input.bounds, num_qubits, batch_size, num_epochs, seed, discriminator, generator, tol_rel_ent, snapshot_dir)
def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance Args: params: parameters dictionary algo_input: LinearSystemInput instance """ if algo_input is None: raise AquaError("LinearSystemInput instance is required.") matrix = algo_input.matrix vector = algo_input.vector if not isinstance(matrix, np.ndarray): matrix = np.asarray(matrix) if not isinstance(vector, np.ndarray): vector = np.asarray(vector) if matrix.shape[0] != len(vector): raise ValueError("Input vector dimension does not match input " "matrix dimension!") if matrix.shape[0] != matrix.shape[1]: raise ValueError("Input matrix must be square!") return cls(matrix, vector)
def construct_circuit(self, mode='circuit', register=None): """ Construct the statevector of desired initial state. Args: mode (string): `vector` or `circuit`. The `vector` mode produces the vector. While the `circuit` constructs the quantum circuit corresponding that vector. register (QuantumRegister): qubits for circuit construction. Returns: QuantumCircuit or numpy.ndarray: statevector. Raises: RuntimeError: invalid input for mode AquaError: when mode is not 'vector' or 'circuit'. """ if mode == 'vector': raise RuntimeError('Initial state based on variational ' 'form does not support vector mode.') if mode == 'circuit': return self._var_form.construct_circuit(self._var_form_params, q=register) else: raise AquaError('Mode should be either "vector" or "circuit"')
def __init__(self, num_target_qubits, probabilities=None, low=0, high=1): """ Abstract univariate distribution class Args: num_target_qubits (int): number of qubits it acts on probabilities (Union(list, numpy.ndarray)): probabilities for different states 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) Raises: AquaError: 'num qubits and length of probabilities vector do not match """ 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!' )
def __init__( self, primitive: Union[OperatorBase] = None, alpha: float = 1.0, coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> None: """ Args: primitive: The ``OperatorBase`` which defines the diagonal operator measurement. coeff: A coefficient by which to multiply the state function alpha: A real-valued parameter between 0 and 1 which specifies the fraction of observed samples to include when computing the objective value. alpha = 1 corresponds to a standard observable expectation value. alpha = 0 corresponds to only using the single sample with the lowest energy. alpha = 0.5 corresponds to ranking each observation by lowest energy and using the best Raises: ValueError: TODO remove that this raises an error ValueError: If alpha is not in [0, 1]. AquaError: If the primitive is not diagonal. """ if primitive is None: raise ValueError if not 0 <= alpha <= 1: raise ValueError('The parameter alpha must be in [0, 1].') self._alpha = alpha if not _check_is_diagonal(primitive): raise AquaError( 'Input operator to CVaRMeasurement must be diagonal, but is not:', str(primitive)) super().__init__(primitive, coeff=coeff, is_measurement=True)