Ejemplo n.º 1
0
    def __init__(self, use_hardware=False, num_runs=1024, verbose=False,
                 user=None, password=None, device='ibmqx2'):
        """
        Initialize the Backend object.

        Args:
            use_hardware (bool): If True, the code is run on the IBM quantum
                chip (instead of using the IBM simulator)
            num_runs (int): Number of runs to collect statistics.
                (default is 1024)
            verbose (bool): If True, statistics are printed, in addition to
                the measurement result being registered (at the end of the
                circuit).
            user (string): IBM Quantum Experience user name
            password (string): IBM Quantum Experience password
            device (string): Device to use ('ibmqx2', 'ibmqx4', or 'ibmqx5')
                if use_hardware is set to True. Default is ibmqx2.
        """
        BasicEngine.__init__(self)
        self._reset()
        if use_hardware:
            self.device = device
        else:
            self.device = 'simulator'
        self._num_runs = num_runs
        self._verbose = verbose
        self._user = user
        self._password = password
        self._mapping = dict()
        self._inverse_mapping = dict()
        self._probabilities = dict()
        self.qasm = ""
Ejemplo n.º 2
0
    def __init__(self,
                 use_hardware=False,
                 num_runs=1024,
                 verbose=False,
                 user=None,
                 password=None):
        """
		Initialize the Backend object.
		
		Args:
			use_hardware (bool): If True, the code is run on the IBM quantum chip
				(instead of using the IBM simulator)
			num_runs (int): Number of runs to collect statistics. (default is 1024)
			verbose (bool): If True, statistics are printed, in addition to the
				measurement result being registered (at the end of the circuit).
			user (string): IBM Quantum Experience user name
			password (string): IBM Quantum Experience password
		"""
        BasicEngine.__init__(self)
        self._reset()
        if use_hardware:
            self._device = 'real'
        else:
            self._device = 'sim_trivial'
        self._num_runs = num_runs
        self._verbose = verbose
        self._user = user
        self._password = password
Ejemplo n.º 3
0
    def __init__(self, accept_input=False, default_measure=0):
        """
        Initialize a circuit drawing engine.

        The TikZ code generator uses a settings file (settings.json), which
        can be altered by the user. It contains gate widths, heights, offsets,
        etc.

        Args:
            accept_input (bool): If accept_input is true, the printer queries
                the user to input measurement results if the CircuitDrawer is
                the last engine. Otherwise, all measurements yield the result
                default_measure (0 or 1).
            default_measure (bool): Default value to use as measurement
                results if accept_input is False and there is no underlying
                backend to register real measurement results.
        """
        BasicEngine.__init__(self)
        self._accept_input = accept_input
        self._default_measure = default_measure
        self._qubit_lines = dict()
        self._free_lines = []
        self._map = dict()

        # Order in which qubit lines are drawn
        self._drawing_order = []
Ejemplo n.º 4
0
    def __init__(self,
                 decompositionRuleSet,
                 decomposition_chooser=lambda cmd, decomposition_list:
                 decomposition_list[0]):
        """
        Initialize an AutoReplacer.

        Args:
            decomposition_chooser (function): A function which, given the
                Command to decompose and a list of potential Decomposition
                objects, determines (and then returns) the 'best'
                decomposition.

        The default decomposition chooser simply returns the first list
        element, i.e., calling

        .. code-block:: python

            repl = AutoReplacer()

        Amounts to

        .. code-block:: python

            def decomposition_chooser(cmd, decomp_list):
                return decomp_list[0]
            repl = AutoReplacer(decomposition_chooser)
        """
        BasicEngine.__init__(self)
        self._decomp_chooser = decomposition_chooser
        self.decompositionRuleSet = decompositionRuleSet
Ejemplo n.º 5
0
	def __init__(self, gate_fusion=False, rnd_seed=None):
		"""
		Construct the C++/Python-simulator object and initialize it with a random
		seed.
		
		Args:
			gate_fusion (bool): If True, gates are cached and only executed once a
				certain gate-size has been reached (only has an effect for the c++
				simulator).
			rnd_seed (int): Random seed (uses random.randint(0, 1024) by default).
			
		Example of gate_fusion: Instead of applying a Hadamard gate to 5 qubits,
		the simulator calculates the kronecker product of the 1-qubit matrices and
		then applies 1 5-qubit gate. This increases operational intensity and
		keeps the simulator from having to iterate through the state vector
		multiple times. Depending on the system (and, especially, number of
		threads), this may or may not be beneficial.
		
		Note:
			If the C++ Simulator extension was not built or cannot be found, the
			Simulator defaults to a Python implementation of the kernels. While this
			is much slower, it is still good enough to run basic quantum algorithms.
			
			If you need to run large simulations, check out the tutorial in the docs
			which gives futher hints on how to build the C++ extension.
		"""
		if rnd_seed is None:
			rnd_seed = random.randint(0, 1024)
		BasicEngine.__init__(self)
		self._simulator = SimulatorBackend(rnd_seed)
		self._gate_fusion = gate_fusion
Ejemplo n.º 6
0
    def __init__(
        self,
        outfile=None,
        one_qubit_gate_map=None,
        two_qubit_gate_map=None,
        native_gates=None,
    ):
        BasicEngine.__init__(self)
        if native_gates is None:
            from qscout.v1.std import NATIVE_GATES

            native_gates = NATIVE_GATES
        self._circuit = CircuitBuilder(native_gates=native_gates)
        self._q = self._circuit.register("q", 0)
        self._block = UnscheduledBlockBuilder()
        self._circuit.expression.append(self._block.expression)
        self._block.gate("prepare_all")
        self.measure_accumulator = set()
        self.reset_accumulator = set()
        self.outfile = outfile
        if one_qubit_gate_map is None:
            self.one_qubit_gates = one_qubit_gates
        else:
            self.one_qubit_gates = one_qubit_gate_map
        if two_qubit_gate_map is None:
            self.two_qubit_gates = two_qubit_gates
        else:
            self.two_qubit_gates = two_qubit_gate_map
Ejemplo n.º 7
0
    def __init__(self, cluster_size, num_global):
        """
        Args:
            cluster_size (int): The maximum number of qubits in fused
                                multi-qubit gate
            num_global (int): Number of global qubits
        """
        BasicEngine.__init__(self)

        self._num_global = num_global
        self._max_cluster_size = cluster_size
        self._k_not_found = pow(2, 64) - 1

        self._swaps = 0
        self._swap_fraction = 0
        self._runs = 0
        self._gates = 0
        self._last_gates = 0

        self._locals = []
        self._globals = [self._k_not_found] * num_global
        self._cluster = set()

        self._is_diag_cluster = True
        self._is_empty_cluster = True
        self._nothing = True

        self._simulator = FakeSimulator()
        self._dealloc = False
Ejemplo n.º 8
0
    def __init__(
        self,
        num_runs: int = 1024,
        verbose: int = 0,
        quantum_inspire_api: Optional[QuantumInspireAPI] = None,
        backend_type: Optional[Union[Dict[str, Any], int,
                                     str]] = None) -> None:
        """
        Initialize the Backend object.

        Args:
            num_runs: Number of runs to collect statistics (default is 1024).
            verbose: Verbosity level, defaults to 0, which produces no extra output.
            quantum_inspire_api: Connection to QI platform, required parameter.
            backend_type: Backend to use for execution. When no backend_type is provided, the default backend will be
                          used.
        """
        BasicEngine.__init__(self)
        self._flushed: bool = False
        """ Because engines are meant to be 'single use' by the way ProjectQ is designed,
        any additional gates received after a FlushGate triggers an exception. """
        self._reset()
        self._num_runs: int = num_runs
        self._verbose: int = verbose
        self._cqasm: str = str()
        self._measured_states: Dict[int, float] = {}
        self._measured_ids: List[int] = []
        self._allocated_qubits: Set[int] = set()
        self._max_qubit_id: int = -1
        if not quantum_inspire_api:
            raise RuntimeError("Api is required")
        self.quantum_inspire_api: QuantumInspireAPI = quantum_inspire_api
        self.backend_type: Optional[Union[Dict[str, Any], int,
                                          str]] = backend_type
Ejemplo n.º 9
0
    def __init__(self,
                 process_func=_dummy_process,
                 qubit_id_mapping_redux=True):
        """
        Initialize the OpenQASMEngine object.

        Args:
            process_func (function): Function to be called periodically to
                process a qiskit.QuantumCircuit. This happens anytime a
                FlushGate gets processed by the engine.
                This function should accept a single argument:
                qiskit.QuantumCircuit.
            qubit_id_mapping_redux (bool): If True, try to allocate new Qubit
                                           IDs to the next available qreg/creg
                                           (if any), otherwise create a new
                                           qreg/creg.
                                           If False, simply create a new
                                           qreg/creg for each new Qubit ID

        Example:
            .. code-block:: python

                from projectq.cengines import MainEngine, OpenQASMEngine

                backend = OpenQASMEngine()
                eng = MainEngine(backend=backend)
                # do something ...
                eng.flush()
                qc = backend.circuit # get the corresponding Qiskit circuit

        If you have a ProjectQ program with multiple measurements (followed by
        `eng.flush()`) the OpenQASMEngine can automatically generate a list of
        circuits:

        Example:
            .. code-block:: python

                from projectq.cengines import MainEngine, OpenQASMEngine

                qc_list = []
                def process(qc):
                    qc_list.append(qc)

                backend = OpenQASMEngine(process_func=process)
                eng = MainEngine(backend=backend)
                # do something ...
                eng.flush()
                # do something ...
                eng.flush()
                qc_list # contains a list of successive circuits
        """
        BasicEngine.__init__(self)
        self._was_flushed = False
        self._openqasm_circuit = QuantumCircuit()
        self._process_func = process_func
        self._qreg_dict = dict()
        self._creg_dict = dict()
        self._qubit_id_mapping_redux = qubit_id_mapping_redux
        self._reg_index = 0
        self._available_indices = []
Ejemplo n.º 10
0
    def __init__(self) -> None:
        """
        Initialize the tketBackendEngine.

        Initializes local Circuit to an empty Circuit.
        """
        BasicEngine.__init__(self)
        self._circuit = Circuit()
Ejemplo n.º 11
0
 def __init__(self):
     """
     Initialize a UncomputeEngine.
     """
     BasicEngine.__init__(self)
     # Save all qubit ids from qubits which are created or destroyed.
     self._allocated_qubit_ids = set()
     self._deallocated_qubit_ids = set()
Ejemplo n.º 12
0
 def __init__(self, total_err_prob=0.01):
     BasicEngine.__init__(self)
     self._distEngine = DistillationEngine()
     self._command_buffer = []
     self._Tgate_count = 0
     self._logical_qubit_count = 0
     self._total_err_prob = total_err_prob
     self._remap = dict()
    def __init__(self, output="instructions"):
        BasicEngine.__init__(self)

        self._output = output
        self._command_buffer = []
        # self._Tgate_count = 0
        self._logical_qubit_count = 0
        self._remap = dict()
Ejemplo n.º 14
0
    def __init__(self):
        """
        Initialize an IBM CNOT Mapper compiler engine.

        Resets the mapping.
        """
        BasicEngine.__init__(self)
        self._reset()
Ejemplo n.º 15
0
 def __init__(self, permutation_rule):
     """
     Initialize the Permutation Base Engine.
     To use the permutation engine please use a derived class.
     """
     BasicEngine.__init__(self)
     self._dllist = DoubleLinkedList(
     )  # dict of lists containing operations for each qubit
     self._perm = permutation_rule(self._dllist)
Ejemplo n.º 16
0
    def __init__(self,
                 num_runs: int = 1024,
                 verbose: int = 0,
                 quantum_inspire_api: Optional[QuantumInspireAPI] = None,
                 backend_type: Optional[Union[int, str]] = None) -> None:
        """
        Initialize the Backend object.

        :param num_runs: Number of runs to collect statistics (default is 1024).
        :param verbose: Verbosity level, defaults to 0, which produces no extra output.
        :param quantum_inspire_api: Connection to QI platform, optional parameter.
        :param backend_type: Backend to use for execution.
            When no backend_type is provided, the default backend will be used.

        :raises AuthenticationError: When an authentication error occurs.
        """
        BasicEngine.__init__(self)
        self._flushed: bool = False
        """ Because engines are meant to be 'single use' by the way ProjectQ is designed,
        any additional gates received after a FlushGate triggers an exception. """
        self._clear: bool = True
        self._qasm: str = ""
        self._reset()
        self._verbose: int = verbose
        self._cqasm: str = str()
        self._measured_states: Dict[int, float] = {}
        self._measured_ids: List[int] = []
        self._allocation_map: List[Tuple[int, int]] = []
        self._max_qubit_id: int = -1
        self._quantum_inspire_result: Dict[str, Any] = {}
        if quantum_inspire_api is None:
            try:
                quantum_inspire_api = QuantumInspireAPI()
            except AuthenticationError as ex:
                raise AuthenticationError(
                    'Make sure you have saved your token credentials on disk or '
                    'provide a QuantumInspireAPI instance as parameter to QIBackend'
                ) from ex
        self._quantum_inspire_api: QuantumInspireAPI = quantum_inspire_api
        self._backend_type: Dict[
            str,
            Any] = self._quantum_inspire_api.get_backend_type(backend_type)
        if num_runs < 1 or num_runs > self._backend_type['max_number_of_shots']:
            raise ProjectQBackendError(
                f'Invalid number of runs (num_runs={num_runs})')
        self._num_runs: int = num_runs
        self._full_state_projection = not self._backend_type[
            "is_hardware_backend"]
        self._is_simulation_backend = not self._backend_type[
            "is_hardware_backend"]
        self._max_number_of_qubits: int = self._backend_type[
            "number_of_qubits"]
        self._one_qubit_gates: Tuple[Any, ...] = self._get_one_qubit_gates()
        self._two_qubit_gates: Tuple[Any, ...] = self._get_two_qubit_gates()
        self._three_qubit_gates: Tuple[Any,
                                       ...] = self._get_three_qubit_gates()
Ejemplo n.º 17
0
    def __init__(self, qubits):
        """
		Initialize the control engine.

		Args:
			qubits (list of Qubit objects): qubits conditional on which the following
			operations are executed.
		"""
        BasicEngine.__init__(self)
        self._qubits = qubits
Ejemplo n.º 18
0
    def __init__(self, p, noise_model=None):
        """
        Initialize NoiseEngine object
        """

        self.p = p  # Delete this later

        noise_model = deepcopy(noise_model)
        BasicEngine.__init__(self)
        self.noise_model = deepcopy(noise_model)
 def __init__(self,
              decomposition_rule_set,
              decomposition_chooser=lambda cmd, decomposition_list:
              decomposition_list[0],
              merge_rules=()):
     BasicEngine.__init__(self)
     self._cached_results = dict()
     self.decomposition_rule_set = decomposition_rule_set
     self.decomposition_chooser = decomposition_chooser
     self.merge_rules = merge_rules
Ejemplo n.º 20
0
    def __init__(self):
        """
        Initialize a resource counter engine.

        Sets all statistics to zero.
        """
        BasicEngine.__init__(self)
        self.gate_counts = dict()
        self._active_qubits = 0
        self.max_width = 0
Ejemplo n.º 21
0
    def __init__(self, m=5):
        """
        Initialize a LocalOptimizer object.

        Args:
            m (int): Number of gates to cache per qubit, before sending on the
                first gate.
        """
        BasicEngine.__init__(self)
        self._l = [[]]  # list of lists containing operations for each qubit
        self._m = m  # wait for m gates before sending on
Ejemplo n.º 22
0
    def __init__(self, save_commands=False):
        """
        Initialize DummyEngine

        Args:
            save_commands (default = False): If True, commands are saved in
                                             self.received_commands.
        """
        BasicEngine.__init__(self)
        self.save_commands = save_commands
        self.received_commands = []
Ejemplo n.º 23
0
    def __init__(self, map_fun=lambda x: x):
        """
        Initialize the mapper to a given mapping. If no mapping function is
        provided, the qubit id is used as the location.

        Args:
            map_fun (function): Function which, given the qubit id, returns
                an integer describing the physical location.
        """
        BasicEngine.__init__(self)
        self.map = map_fun
Ejemplo n.º 24
0
    def __init__(self, tags=[ComputeTag, UncomputeTag]):
        """
		Construct the TagRemover.
		
		Args:
			tags: A list of meta tag classes (e.g., [ComputeTag, UncomputeTag])
				denoting the tags to remove
		"""
        BasicEngine.__init__(self)
        assert isinstance(tags, list)
        self._tags = tags
    def __init__(self, connectivity):
        """
        Initialize the engine.

        Args:
            connectivity (set): Set of tuples (c, t) where if (c, t) is an
                element of the set means that a CNOT can be performed between
                the physical ids (c, t) with c being the control and t being
                the target qubit.
        """
        BasicEngine.__init__(self)
        self.connectivity = connectivity
Ejemplo n.º 26
0
 def __init__(self,
              supremacy_circuit=False,
              num_splits=10**6,
              cluster_size=4):
     BasicEngine.__init__(self)
     self._cmd_list = []
     self._was_scheduling = False
     self._init = False
     self._supremacy_circuit = supremacy_circuit
     self.NUM_SPLITS = num_splits
     self.CLUSTER_SIZE = cluster_size
     self._deallocations_cache = []
Ejemplo n.º 27
0
    def __init__(self, filterfun):
        """
        Initializer: The provided filterfun returns True for all commands
        which do not need replacement and False for commands that do.

        Args:
            filterfun (function): Filter function which returns True for
                available commands, and False otherwise. filterfun will be
                called as filterfun(self, cmd).
        """
        BasicEngine.__init__(self)
        self._filterfun = filterfun
Ejemplo n.º 28
0
    def __init__(self):
        """
        Initialize a resource counter engine.

        Sets all statistics to zero.
        """
        BasicEngine.__init__(self)
        self.gate_counts = {}
        self.gate_class_counts = {}
        self._active_qubits = 0
        self.max_width = 0
        # key: qubit id, depth of this qubit
        self._depth_of_qubit = dict()
        self._previous_max_depth = 0
Ejemplo n.º 29
0
    def __init__(self,
                 use_hardware=False,
                 num_runs=100,
                 verbose=False,
                 token='',
                 device='simulator',
                 num_retries=3000,
                 interval=1,
                 retrieve_execution=None):
        """
        Initialize the Backend object.

        Args:
            use_hardware (bool): If True, the code is run on the AQT quantum
                chip (instead of using the AQT simulator)
            num_runs (int): Number of runs to collect statistics.
                (default is 100, max is usually around 200)
            verbose (bool): If True, statistics are printed, in addition to
                the measurement result being registered (at the end of the
                circuit).
            token (str): AQT user API token.
            device (str): name of the AQT device to use. simulator By default
            num_retries (int): Number of times to retry to obtain
                results from the AQT API. (default is 3000)
            interval (float, int): Number of seconds between successive
                attempts to obtain results from the AQT API.
                (default is 1)
            retrieve_execution (int): Job ID to retrieve instead of re-
                running the circuit (e.g., if previous run timed out).
        """
        BasicEngine.__init__(self)
        self._reset()
        if use_hardware:
            self.device = device
        else:
            self.device = 'simulator'
        self._clear = True
        self._num_runs = num_runs
        self._verbose = verbose
        self._token = token
        self._num_retries = num_retries
        self._interval = interval
        self._probabilities = dict()
        self._circuit = []
        self._mapper = []
        self._measured_ids = []
        self._allocated_qubits = set()
        self._retrieve_execution = retrieve_execution
Ejemplo n.º 30
0
 def __init__(self, accept_input=False, default_measure=0):
     """
     Initialize a circuit drawing engine(mpl)
     Args:
         accept_input (bool): If accept_input is true, the printer queries
             the user to input measurement results if the CircuitDrawerMPL
             is the last engine. Otherwise, all measurements yield the
             result default_measure (0 or 1).
         default_measure (bool): Default value to use as measurement
             results if accept_input is False and there is no underlying
             backend to register real measurement results.
     """
     BasicEngine.__init__(self)
     self._accept_input = accept_input
     self._default_measure = default_measure
     self._map = dict()
     self._qubit_lines = {}