Exemplo n.º 1
0
 def __init__(self):
     BasicEngine.__init__(self)
     self._state = 0
     self._bit_positions = {}
Exemplo n.º 2
0
    def __init__(self, backend=None, engine_list=None, verbose=False):
        """
        Initialize the main compiler engine and all compiler engines.

        Sets 'next_engine'- and 'main_engine'-attributes of all compiler
        engines and adds the back-end as the last engine.

        Args:
            backend (BasicEngine): Backend to send the compiled circuit to.
            engine_list (list<BasicEngine>): List of engines / backends to use
                as compiler engines. Note: The engine list must not contain
                multiple mappers (instances of BasicMapperEngine).
                Default: projectq.setups.default.get_engine_list()
            verbose (bool): Either print full or compact error messages.
                            Default: False (i.e. compact error messages).

        Example:
            .. code-block:: python

                from projectq import MainEngine
                eng = MainEngine() # uses default engine_list and the Simulator

        Instead of the default `engine_list` one can use, e.g., one of the IBM
        setups which defines a custom `engine_list` useful for one of the IBM
        chips

        Example:
            .. code-block:: python

                import projectq.setups.ibm as ibm_setup
                from projectq import MainEngine
                eng = MainEngine(engine_list=ibm_setup.get_engine_list())
                # eng uses the default Simulator backend

        Alternatively, one can specify all compiler engines explicitly, e.g.,

        Example:
            .. code-block:: python

                from projectq.cengines import (TagRemover, AutoReplacer,
                                               LocalOptimizer,
                                               DecompositionRuleSet)
                from projectq.backends import Simulator
                from projectq import MainEngine
                rule_set = DecompositionRuleSet()
                engines = [AutoReplacer(rule_set), TagRemover(),
                           LocalOptimizer(3)]
                eng = MainEngine(Simulator(), engines)
        """
        BasicEngine.__init__(self)

        if backend is None:
            backend = Simulator()
        else:  # Test that backend is BasicEngine object
            if not isinstance(backend, BasicEngine):
                raise UnsupportedEngineError(
                    "\nYou supplied a backend which is not supported,\n"
                    "i.e. not an instance of BasicEngine.\n"
                    "Did you forget the brackets to create an instance?\n"
                    "E.g. MainEngine(backend=Simulator) instead of \n"
                    "     MainEngine(backend=Simulator())")
        # default engine_list is projectq.setups.default.get_engine_list()
        if engine_list is None:
            import projectq.setups.default
            engine_list = projectq.setups.default.get_engine_list()

        self.mapper = None
        if isinstance(engine_list, list):
            # Test that engine list elements are all BasicEngine objects
            for current_eng in engine_list:
                if not isinstance(current_eng, BasicEngine):
                    raise UnsupportedEngineError(
                        "\nYou supplied an unsupported engine in engine_list,"
                        "\ni.e. not an instance of BasicEngine.\n"
                        "Did you forget the brackets to create an instance?\n"
                        "E.g. MainEngine(engine_list=[AutoReplacer]) instead "
                        "of\n     MainEngine(engine_list=[AutoReplacer()])")
                if isinstance(current_eng, BasicMapperEngine):
                    if self.mapper is None:
                        self.mapper = current_eng
                    else:
                        raise UnsupportedEngineError(
                            "More than one mapper engine is not supported.")
        else:
            raise UnsupportedEngineError(
                "The provided list of engines is not a list!")
        engine_list = engine_list + [backend]
        self.backend = backend

        # Test that user did not supply twice the same engine instance
        num_different_engines = len(set([id(item) for item in engine_list]))
        if len(engine_list) != num_different_engines:
            raise UnsupportedEngineError(
                "\nError:\n You supplied twice the same engine as backend"
                " or item in engine_list. This doesn't work. Create two \n"
                " separate instances of a compiler engine if it is needed\n"
                " twice.\n")

        self._qubit_idx = int(0)
        for i in range(len(engine_list) - 1):
            engine_list[i].next_engine = engine_list[i + 1]
            engine_list[i].main_engine = self
        engine_list[-1].main_engine = self
        engine_list[-1].is_last_engine = True
        self.next_engine = engine_list[0]
        self.main_engine = self
        self.active_qubits = weakref.WeakSet()
        self._measurements = dict()
        self.dirty_qubits = set()
        self.verbose = verbose

        # In order to terminate an example code without eng.flush
        def atexit_function(weakref_main_eng):
            eng = weakref_main_eng()
            if eng is not None:
                if not hasattr(sys, "last_type"):
                    eng.flush(deallocate_qubits=True)
                # An exception causes the termination, don't send a flush and
                # make sure no qubits send deallocation gates anymore as this
                # might trigger additional exceptions
                else:
                    for qubit in eng.active_qubits:
                        qubit.id = -1

        self._delfun = atexit_function
        weakref_self = weakref.ref(self)
        atexit.register(self._delfun, weakref_self)
Exemplo n.º 3
0
    def __init__(self,
                 allow_classical_instructions=True,
                 allow_all=False,
                 allow_arithmetic=False,
                 allow_toffoli=False,
                 allow_nots_with_many_controls=False,
                 allow_single_qubit_gates=False,
                 allow_single_qubit_gates_with_controls=False,
                 allow_classes=(),
                 allow_custom_predicate=lambda cmd: False,
                 ban_classes=(),
                 ban_custom_predicate=lambda cmd: False):
        """
        Constructs a LimitedCapabilityEngine that accepts commands based on
        the given criteria arguments.

        Note that a command is accepted if it meets *none* of the ban criteria
        and *any* of the allow criteria.

        Args:
            allow_classical_instructions (bool):
                Enabled by default. Marks classical instruction commands like
                'Allocate', 'Flush', etc as available.

            allow_all (bool):
                Defaults to allowing all commands.
                Any ban criteria will override this default.

            allow_arithmetic (bool):
                Allows gates with the BasicMathGate type.

            allow_toffoli (bool):
                Allows NOT gates with at most 2 controls.

            allow_nots_with_many_controls (bool):
                Allows NOT gates with arbitrarily many controls.

            allow_single_qubit_gates (bool):
                Allows gates that affect only a single qubit
                (counting controls).

            allow_single_qubit_gates_with_controls (bool):
                Allows gates that target only a single qubit.

            allow_classes (list[type]):
                Allows any gates matching the given class.

            allow_custom_predicate (function(Command) : bool):
                Allows any gates that cause the given function to return True.

            ban_classes (list[type]):
                Bans any gates matching the given class.

            ban_custom_predicate (function(Command) : bool):
                Bans gates that cause the given function to return True.
        """
        BasicEngine.__init__(self)
        self.allow_arithmetic = allow_arithmetic
        self.allow_all = allow_all
        self.allow_nots_with_many_controls = allow_nots_with_many_controls
        self.allow_single_qubit_gates = allow_single_qubit_gates
        self.allow_single_qubit_gates_with_controls = (
            allow_single_qubit_gates_with_controls)
        self.allow_toffoli = allow_toffoli
        self.allow_classical_instructions = allow_classical_instructions
        self.allowed_classes = tuple(allow_classes)
        self.allow_custom_predicate = allow_custom_predicate
        self.ban_classes = tuple(ban_classes)
        self.ban_custom_predicate = ban_custom_predicate
Exemplo n.º 4
0
 def __init__(self):
     BasicEngine.__init__(self)
     self._commands = []
     self._allocated_qubit_ids = set()
     self._deallocated_qubit_ids = set()
Exemplo n.º 5
0
    def __init__(self, backend=None, engine_list=None):
        """
        Initialize the main compiler engine and all compiler engines.

        Sets 'next_engine'- and 'main_engine'-attributes of all compiler
        engines and adds the back-end as the last engine.

        Args:
            backend (BasicEngine): Backend to send the circuit to.
            engine_list (list<BasicEngine>): List of engines / backends to use
                as compiler engines.

        Example:
            .. code-block:: python

                from projectq import MainEngine
                eng = MainEngine() # uses default setup and the Simulator

        Alternatively, one can specify all compiler engines explicitly, e.g.,

        Example:
            .. code-block:: python

                from projectq.cengines import TagRemover,AutoReplacer,LocalOptimizer,DecompositionRuleSet
                from projectq.backends import Simulator
                from projectq import MainEngine
                rule_set = DecompositionRuleSet()
                engines = [AutoReplacer(rule_set), TagRemover(), LocalOptimizer(3)]
                eng = MainEngine(Simulator(), engines)
        """
        BasicEngine.__init__(self)

        if backend is None:
            backend = Simulator()
        else:  # Test that backend is BasicEngine object
            if not isinstance(backend, BasicEngine):
                raise UnsupportedEngineError(
                    "\nYou supplied a backend which is not supported,\n"
                    "i.e. not an instance of BasicEngine.\n"
                    "Did you forget the brackets to create an instance?\n"
                    "E.g. MainEngine(backend=Simulator) instead of \n"
                    "     MainEngine(backend=Simulator())")
        if engine_list is None:
            try:
                engine_list = projectq.default_engines()
            except AttributeError:
                from projectq.setups.default import default_engines
                engine_list = default_engines()
        else:  # Test that engine list elements are all BasicEngine objects
            if not isinstance(engine_list, list):
                raise UnsupportedEngineError(
                    "\n The engine_list argument is not a list!\n")
            for current_eng in engine_list:
                if not isinstance(current_eng, BasicEngine):
                    raise UnsupportedEngineError(
                        "\nYou supplied an unsupported engine in engine_list,"
                        "\ni.e. not an instance of BasicEngine.\n"
                        "Did you forget the brackets to create an instance?\n"
                        "E.g. MainEngine(engine_list=[AutoReplacer]) instead "
                        "of\n     MainEngine(engine_list=[AutoReplacer()])")

        engine_list = engine_list + [backend]
        self.backend = backend

        # Test that user did not supply twice the same engine instance
        num_different_engines = len(set([id(item) for item in engine_list]))
        if len(engine_list) != num_different_engines:
            raise UnsupportedEngineError(
                "\n Error:\n You supplied twice the same engine as backend" +
                " or item in engine_list. This doesn't work. Create two \n" +
                " separate instances of a compiler engine if it is needed\n" +
                " twice.\n")

        self._qubit_idx = int(0)
        for i in range(len(engine_list) - 1):
            engine_list[i].next_engine = engine_list[i + 1]
            engine_list[i].main_engine = self
        engine_list[-1].main_engine = self
        engine_list[-1].is_last_engine = True
        self.next_engine = engine_list[0]
        self.main_engine = self
        self.active_qubits = weakref.WeakSet()
        self._measurements = dict()
        self.dirty_qubits = set()

        # In order to terminate an example code without eng.flush or Measure
        self._delfun = lambda x: x.flush(deallocate_qubits=True)
        atexit.register(self._delfun, self)
Exemplo n.º 6
0
 def __init__(self):
     BasicEngine.__init__(self)
     self._current_mapping = None
Exemplo n.º 7
0
 def __init__(self) -> None:
     BasicEngine.__init__(self)
     self._circuit = Circuit()
     self._qubit_dictionary: dict = dict()
 def __init__(self, rules):
     BasicEngine.__init__(self)
     self.rules = tuple(rules) + (InverseControlMergeRule(), )
     self._last_command = None
Exemplo n.º 9
0
 def __init__(self):
     BasicEngine.__init__(self)
     self._circuit = Circuit()
     self._qubit_dictionary = dict()
Exemplo n.º 10
0
 def __init__(self):
     BasicEngine.__init__(self)
     self.current_mapping = dict()
Exemplo n.º 11
0
 def __init__(self):
     BasicEngine.__init__(self)
     self._l = [[]]
	def __init__(self):
		BasicEngine.__init__(self)
		self.commands = []
 def __init__(self):
     BasicEngine.__init__(self)
     self._states = np.array([0], np.int32)
Exemplo n.º 14
0
    def __init__(self, *args, **kwargs):
        BasicEngine.__init__(self, *args, **kwargs)

        self._reset()