Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def __init__(self):
BasicEngine.__init__(self)
self._l = [[]]
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 = dict() # dict of lists containing operations for each qubit
self._m = m # wait for m gates before sending on
def is_available(self, cmd):
"""
Specialized implementation of is_available: Returns True if the
CircuitDrawer is the last engine (since it can print any command).
Args:
cmd (Command): Command for which to check availability (all
Commands can be printed).
Returns:
availability (bool): True, unless the next engine cannot handle
the Command (if there is a next engine).
"""
try:
return BasicEngine.is_available(self, cmd)
except LastEngineException:
return True
R,
Measure,
FlushGate,
Allocate,
Deallocate,
BasicMathGate,
TimeEvolution)
from projectq.types import WeakQubitRef
try:
from ._cppsim import Simulator as SimulatorBackend
except ImportError:
from ._pysim import Simulator as SimulatorBackend
class Simulator(BasicEngine):
"""
Simulator is a compiler engine which simulates a quantum computer using
C++-based kernels.
OpenMP is enabled and the number of threads can be controlled using the
OMP_NUM_THREADS environment variable, i.e.
.. code-block:: bash
export OMP_NUM_THREADS=4 # use 4 threads
export OMP_PROC_BIND=spread # bind threads to processors by spreading
"""
def __init__(self, gate_fusion=False, rnd_seed=None):
"""
Construct the C++/Python-simulator object and initialize it with a
random seed.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Contains a compiler engine to add mapping information
"""
from projectq.cengines import BasicEngine
from projectq.meta import QubitPlacementTag
from projectq.ops import Allocate
class ManualMapper(BasicEngine):
"""
Manual Mapper which adds QubitPlacementTags to Allocate gate commands
according to a user-specified mapping.
Attributes:
map (function): The function which maps a given qubit id to its
location. It gets set when initializing the mapper.
"""
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
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
The InstructionFilter can be used to further specify which gates to
replace/keep.
"""
from projectq.cengines import (BasicEngine,
ForwarderEngine,
CommandModifier)
from projectq.ops import (FlushGate,
get_inverse)
class NoGateDecompositionError(Exception):
pass
class InstructionFilter(BasicEngine):
"""
The InstructionFilter is a compiler engine which changes the behavior of
is_available according to a filter function. All commands are passed to
this function, which then returns whether this command can be executed
(True) or needs replacement (False).
"""
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).
"""
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.
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, optional 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._clear: bool = True
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
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 '
"""
if self._compute:
for cmd in command_list:
if cmd.gate == Allocate:
self._allocated_qubit_ids.add(cmd.qubits[0][0].id)
elif cmd.gate == Deallocate:
self._deallocated_qubit_ids.add(cmd.qubits[0][0].id)
self._l.append(deepcopy(cmd))
tags = cmd.tags
tags.append(ComputeTag())
self.send(command_list)
else:
self.send(command_list)
class UncomputeEngine(BasicEngine):
"""
Adds Uncompute-tags to all commands.
"""
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()
def receive(self, command_list):
"""
Receive commands and add an UncomputeTag to their tags.