How to use the qiskit.aqua.AquaError function in qiskit

To help you get started, we’ve selected a few qiskit examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Qiskit / qiskit-aqua / qiskit / aqua / components / oracles / logical_expression_oracle.py View on Github external
def _dimacs_cnf_to_expression(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'
        ]

        if not lines[0][:6] == 'p cnf ':
            raise AquaError('Unrecognized dimacs cnf header {}.'.format(lines[0]))

        def create_var(cnf_tok):
            return ('~v' + cnf_tok[1:]) if cnf_tok[0] == '-' else ('v' + cnf_tok)

        clauses = []
        for line in lines[1:]:
            toks = line.split()
            if not toks[-1] == '0':
                raise AquaError('Unrecognized dimacs line {}.'.format(line))

            clauses.append('({})'.format(' | '.join(
                [create_var(t) for t in toks[:-1]]
            )))
        return ' & '.join(clauses)
github Qiskit / qiskit-aqua / qiskit / aqua / operators / common.py View on Github external
use_basis_gates (bool, optional): boolean flag for indicating only using basis
                                          gates when building circuit.
        shallow_slicing (bool, optional): boolean flag for indicating using shallow
                                          qc.data reference repetition for slicing
        barrier (bool, optional): whether or not add barrier for every slice

    Returns:
        Instruction: The Instruction corresponding to specified evolution.

    Raises:
        AquaError: power must be an integer and greater or equal to 1
        ValueError: Unrecognized pauli
    """

    if not isinstance(power, (int, np.int)) or power < 1:
        raise AquaError("power must be an integer and greater or equal to 1.")

    state_registers = QuantumRegister(pauli_list[0][1].numberofqubits)
    if controlled:
        inst_name = 'Controlled-Evolution^{}'.format(power)
        ancillary_registers = QuantumRegister(1)
        qc_slice = QuantumCircuit(state_registers, ancillary_registers, name=inst_name)
    else:
        inst_name = 'Evolution^{}'.format(power)
        qc_slice = QuantumCircuit(state_registers, name=inst_name)

    # for each pauli [IXYZ]+, record the list of qubit pairs needing CX's
    cnot_qubit_pairs = [None] * len(pauli_list)
    # for each pauli [IXYZ]+, record the highest index of the nontrivial pauli gate (X,Y, or Z)
    top_xyz_pauli_indices = [-1] * len(pauli_list)

    for pauli_idx, pauli in enumerate(reversed(pauli_list)):
github Qiskit / qiskit-aqua / qiskit / aqua / operators / weighted_pauli_operator.py View on Github external
Raises:
            AquaError: if Operator is empty
            AquaError: Can not find quantum register with `q` as the name and do not provide
                       quantum register explicitly
            AquaError: The provided qr is not in the wave_function
        """
        if self.is_empty():
            raise AquaError("Operator is empty, check the operator.")
        # pylint: disable=import-outside-toplevel
        from qiskit.aqua.utils.run_circuits import find_regs_by_name

        if qr is None:
            qr = find_regs_by_name(wave_function, 'q')
            if qr is None:
                raise AquaError("Either providing the quantum register (qr) explicitly"
                                "or used `q` as the name in the input circuit.")
        else:
            if not wave_function.has_register(qr):
                raise AquaError("The provided QuantumRegister (qr) is not in the circuit.")

        n_qubits = self.num_qubits
        instructions = self.evaluation_instruction(statevector_mode, use_simulator_snapshot_mode)
        circuits = []
        if use_simulator_snapshot_mode:
            circuit = wave_function.copy(name=circuit_name_prefix + 'snapshot_mode')
            # Add expectation value snapshot instruction
            instr = instructions.get('expval_snapshot', None)
            if instr is not None:
                circuit.append(instr, qr)
            circuits.append(circuit)
        elif statevector_mode:
github Qiskit / qiskit-aqua / qiskit / aqua / circuits / boolean_logical_circuits.py View on Github external
self._ast = ast
            self._num_clauses = 0
            self._max_clause_size = 0
        else:
            if ast_depth == 1:
                if self._depth == 1:
                    self._num_clauses = 1
                    self._max_clause_size = len(ast) - 1
                    self._ast = ast
                else:  # depth == 2:
                    if ast[0] == 'and':
                        op = 'or'
                    elif ast[0] == 'or':
                        op = 'and'
                    else:
                        raise AquaError('Unexpected expression root operator {}.'.format(ast[0]))
                    self._num_clauses = len(ast) - 1
                    self._max_clause_size = 1
                    self._ast = (ast[0], *[(op, l) for l in ast[1:]])

            else:  # self._depth == 2
                self._num_clauses = len(ast) - 1
                self._max_clause_size = max([len(l) - 1 for l in ast[1:]])
                self._ast = ast

        self._variable_register = None
        self._clause_register = None
        self._output_register = None
        self._ancillary_register = None
github Qiskit / qiskit-aqua / qiskit / aqua / circuits / boolean_logical_circuits.py View on Github external
def __init__(self, ast, num_vars=None):
        """
        Constructor.

        Args:
            ast (tuple): The logic expression as an Abstract Syntax Tree (AST) tuple
            num_vars (int): Number of boolean variables
        """

        ast_depth = BooleanLogicNormalForm._get_ast_depth(ast)

        if ast_depth > 2:
            raise AquaError('Expressions of depth greater than 2 are not supported.')
        self._depth = ast_depth
        inferred_num_vars = BooleanLogicNormalForm._get_ast_num_vars(ast)
        if num_vars is None:
            self._num_variables = inferred_num_vars
        else:
            if inferred_num_vars > num_vars:
                raise AquaError('{} variables present, but only {} specified.'.format(inferred_num_vars, num_vars))
            self._num_variables = num_vars

        if ast_depth == 0:
            self._ast = ast
            self._num_clauses = 0
            self._max_clause_size = 0
        else:
            if ast_depth == 1:
                if self._depth == 1:
github Qiskit / qiskit-aqua / qiskit / aqua / parser / json_schema.py View on Github external
def format_property_name(property_name):
        """ format property name """
        if property_name is None:
            property_name = ''
        property_name = property_name.strip()
        if not property_name:
            raise AquaError("Empty property name.")

        return property_name
github Qiskit / qiskit-aqua / qiskit / aqua / circuits / gates / multi_control_rotation_gates.py View on Github external
"""

    # check controls
    if isinstance(q_controls, QuantumRegister):
        control_qubits = [qb for qb in q_controls]
    elif isinstance(q_controls, list):
        control_qubits = q_controls
    else:
        raise AquaError(
            'The mcrz gate needs a list of qubits or a quantum register for controls.')

    # check target
    if isinstance(q_target, Qubit):
        target_qubit = q_target
    else:
        raise AquaError('The mcrz gate needs a single qubit as target.')

    all_qubits = control_qubits + [target_qubit]

    self._check_qargs(all_qubits)
    self._check_dups(all_qubits)

    n_c = len(control_qubits)
    if n_c == 1:  # cu3
        apply_cu3(self, 0, 0, lam, control_qubits[0],
                  target_qubit, use_basis_gates=use_basis_gates)
    else:
        lam_step = lam * (1 / (2 ** (n_c - 1)))
        _apply_mcu3_graycode(self, 0, 0, lam_step, control_qubits,
                             target_qubit, use_basis_gates=use_basis_gates)
github Qiskit / qiskit-aqua / qiskit / aqua / input / linear_system_input.py View on Github external
def load_vec_from_list(vec):
        def depth(x): return isinstance(x, list) and max(map(depth, x))+1
        if depth(vec) == 2:
            return np.array(vec[0])+1j*np.array(vec[1])
        elif depth(vec) == 1:
            return np.array(vec)
        else:
            raise AquaError("Vector list must be depth 2 or 3")
github Qiskit / qiskit-aqua / qiskit / aqua / components / oracles / truth_table_oracle.py View on Github external
diff_mask = terms[cur_term][0] ^ terms[next_term][0]
                                dc_mask = diff_mask | terms[cur_term][1]
                                implicant_mask = terms[cur_term][0] & terms[next_term][0]
                            else:
                                continue
                        else:
                            raise AquaError('Unexpected type: {}.'.format(type(cur_term)))
                        if bin(diff_mask).count('1') == 1:
                            prime_dict[cur_term] = False
                            prime_dict[next_term] = False
                            if isinstance(cur_term, int):
                                cur_implicant = (cur_term, next_term)
                            elif isinstance(cur_term, tuple):
                                cur_implicant = tuple(sorted((*cur_term, *next_term)))
                            else:
                                raise AquaError('Unexpected type: {}.'.format(type(cur_term)))
                            new_implicants[cur_implicant] = (
                                implicant_mask,
                                dc_mask
                            )
                            num1s = bin(implicant_mask).count('1')
                            if num1s not in new_num1s_dict:
                                new_num1s_dict[num1s] = [cur_implicant]
                            else:
                                if cur_implicant not in new_num1s_dict[num1s]:
                                    new_num1s_dict[num1s].append(cur_implicant)
            cur_num1s += 1
        return new_implicants, new_num1s_dict, prime_dict
github Qiskit / qiskit-aqua / qiskit / aqua / input / qgan_input.py View on Github external
def from_params(cls, params):
        if 'data' not in params:
            raise AquaError("Training data not given.")
        if 'bounds' not in params:
            raise AquaError("Data bounds not given.")
        data = params['data']
        bounds = params['bounds']
        return cls(data, bounds)