code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def receive(self, command_list):
"""
Receive a list of commands.
Receive a command list and, for each command, stores it until completion. Upon flush, send the data to the
IBM QE API.
Args:
command_list: List of commands to execute
"""
for cmd in com... |
Receive a list of commands.
Receive a command list and, for each command, stores it until completion. Upon flush, send the data to the
IBM QE API.
Args:
command_list: List of commands to execute
| receive | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ibm/_ibm.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm.py | Apache-2.0 |
def __init__(self, **kwargs):
"""Initialize a session with the IBM QE's APIs."""
super().__init__(**kwargs)
self.backends = {}
self.timeout = 5.0 | Initialize a session with the IBM QE's APIs. | __init__ | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ibm/_ibm_http_client.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py | Apache-2.0 |
def get_list_devices(self, verbose=False):
"""
Get the list of available IBM backends with their properties.
Args:
verbose (bool): print the returned dictionary if True
Returns:
(dict) backends dictionary by name device, containing the qubit size 'nq', the coupl... |
Get the list of available IBM backends with their properties.
Args:
verbose (bool): print the returned dictionary if True
Returns:
(dict) backends dictionary by name device, containing the qubit size 'nq', the coupling map 'coupling_map'
as well as ... | get_list_devices | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ibm/_ibm_http_client.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py | Apache-2.0 |
def can_run_experiment(self, info, device):
"""
Check if the device is big enough to run the code.
Args:
info (dict): dictionary sent by the backend containing the code to run
device (str): name of the ibm device to use
Returns:
(tuple): (bool) True ... |
Check if the device is big enough to run the code.
Args:
info (dict): dictionary sent by the backend containing the code to run
device (str): name of the ibm device to use
Returns:
(tuple): (bool) True if device is big enough, False otherwise
... | can_run_experiment | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ibm/_ibm_http_client.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py | Apache-2.0 |
def authenticate(self, token=None):
"""
Authenticate with IBM's Web API.
Args:
token (str): IBM quantum experience user API token.
"""
if token is None:
token = getpass.getpass(prompt="IBM QE token > ")
if len(token) == 0:
raise Except... |
Authenticate with IBM's Web API.
Args:
token (str): IBM quantum experience user API token.
| authenticate | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ibm/_ibm_http_client.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py | Apache-2.0 |
def run(self, info, device): # pylint: disable=too-many-locals
"""
Run the quantum code to the IBMQ machine.
Update since September 2020: only protocol available is what they call 'object storage' where a job request
via the POST method gets in return a url link to which send the json ... |
Run the quantum code to the IBMQ machine.
Update since September 2020: only protocol available is what they call 'object storage' where a job request
via the POST method gets in return a url link to which send the json data. A final http validates the data
communication.
Args:... | run | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ibm/_ibm_http_client.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py | Apache-2.0 |
def show_devices(token=None, verbose=False):
"""
Access the list of available devices and their properties (ex: for setup configuration).
Args:
token (str): IBM quantum experience user API token.
verbose (bool): If True, additional information is printed
Returns:
(list) list of... |
Access the list of available devices and their properties (ex: for setup configuration).
Args:
token (str): IBM quantum experience user API token.
verbose (bool): If True, additional information is printed
Returns:
(list) list of available devices and their properties
| show_devices | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ibm/_ibm_http_client.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py | Apache-2.0 |
def retrieve(device, token, jobid, num_retries=3000, interval=1, verbose=False): # pylint: disable=too-many-arguments
"""
Retrieve a previously run job by its ID.
Args:
device (str): Device on which the code was run / is running.
token (str): IBM quantum experience user API token.
... |
Retrieve a previously run job by its ID.
Args:
device (str): Device on which the code was run / is running.
token (str): IBM quantum experience user API token.
jobid (str): Id of the job to retrieve
Returns:
(dict) result form the IBMQ server
| retrieve | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ibm/_ibm_http_client.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py | Apache-2.0 |
def send(
info,
device='ibmq_qasm_simulator',
token=None,
shots=None,
num_retries=3000,
interval=1,
verbose=False,
): # pylint: disable=too-many-arguments
"""
Send QASM through the IBM API and runs the quantum circuit.
Args:
info(dict): Contains representation of the ci... |
Send QASM through the IBM API and runs the quantum circuit.
Args:
info(dict): Contains representation of the circuit to run.
device (str): name of the ibm device. Simulator chosen by default
token (str): IBM quantum experience user API token.
shots (int): Number of runs of the ... | send | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ibm/_ibm_http_client.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ibm/_ibm_http_client.py | Apache-2.0 |
def _store(self, cmd):
"""Interpret the ProjectQ command as a circuit instruction and store it.
Args:
cmd (Command): A command to process.
Raises:
InvalidCommandError: If the command can not be interpreted.
MidCircuitMeasurementError: If this command would r... | Interpret the ProjectQ command as a circuit instruction and store it.
Args:
cmd (Command): A command to process.
Raises:
InvalidCommandError: If the command can not be interpreted.
MidCircuitMeasurementError: If this command would result in a
mid-cir... | _store | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq.py | Apache-2.0 |
def __init__(self, verbose=False):
"""Initialize an session with IonQ's APIs."""
super().__init__()
self.backends = {}
self.timeout = 5.0
self.token = None
self._verbose = verbose | Initialize an session with IonQ's APIs. | __init__ | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_http_client.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_http_client.py | Apache-2.0 |
def update_devices_list(self):
"""Update the list of devices this backend can support."""
self.authenticate(self.token)
req = super().get(urljoin(_API_URL, 'backends'))
req.raise_for_status()
r_json = req.json()
# Legacy backends, kept for backward compatibility.
... | Update the list of devices this backend can support. | update_devices_list | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_http_client.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_http_client.py | Apache-2.0 |
def can_run_experiment(self, info, device):
"""
Determine whether or not the desired device has enough allocatable qubits to run something.
This returns a three-element tuple with whether or not the experiment
can be run, the max number of qubits possible, and the number of qubits
... |
Determine whether or not the desired device has enough allocatable qubits to run something.
This returns a three-element tuple with whether or not the experiment
can be run, the max number of qubits possible, and the number of qubits
needed to run this experiment.
Args:
... | can_run_experiment | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_http_client.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_http_client.py | Apache-2.0 |
def authenticate(self, token=None):
"""Set an Authorization header for this session.
If no token is provided, an prompt will appear to ask for one.
Args:
token (str): IonQ user API token.
"""
if token is None:
token = getpass.getpass(prompt='IonQ apiKey ... | Set an Authorization header for this session.
If no token is provided, an prompt will appear to ask for one.
Args:
token (str): IonQ user API token.
| authenticate | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_http_client.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_http_client.py | Apache-2.0 |
def get_result(self, device, execution_id, num_retries=3000, interval=1):
"""
Given a backend and ID, fetch the results for this job's execution.
The return dictionary should have at least:
* ``nq`` (int): Number of qubits for this job.
* ``output_probs`` (dict): Map of... |
Given a backend and ID, fetch the results for this job's execution.
The return dictionary should have at least:
* ``nq`` (int): Number of qubits for this job.
* ``output_probs`` (dict): Map of integer states to probability values.
Args:
device (str): The d... | get_result | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_http_client.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_http_client.py | Apache-2.0 |
def receive(self, command_list):
"""
Receive a list of commands.
Args:
command_list (list<Command>): List of commands to receive.
"""
for cmd in command_list:
if isinstance(cmd.gate, FlushGate):
self._reset()
self.send([cmd... |
Receive a list of commands.
Args:
command_list (list<Command>): List of commands to receive.
| receive | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_mapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_mapper.py | Apache-2.0 |
def test_ionq_backend_init():
"""Test initialized backend has an empty circuit"""
backend = _ionq.IonQBackend(verbose=True, use_hardware=True)
assert hasattr(backend, '_circuit')
circuit = getattr(backend, '_circuit')
assert isinstance(circuit, list)
assert len(circuit) == 0 | Test initialized backend has an empty circuit | test_ionq_backend_init | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_test.py | Apache-2.0 |
def test_ionq_empty_circuit():
"""Test that empty circuits are still flushable."""
backend = _ionq.IonQBackend(verbose=True)
eng = MainEngine(backend=backend)
eng.flush() | Test that empty circuits are still flushable. | test_ionq_empty_circuit | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_test.py | Apache-2.0 |
def test_ionq_no_circuit_executed():
"""Test that one can't retrieve probabilities if no circuit was run."""
backend = _ionq.IonQBackend(verbose=True)
eng = MainEngine(backend=backend)
# no circuit has been executed -> raises exception
with pytest.raises(RuntimeError):
backend.get_probabilit... | Test that one can't retrieve probabilities if no circuit was run. | test_ionq_no_circuit_executed | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_test.py | Apache-2.0 |
def test_ionq_get_probability(monkeypatch, mapper_factory):
"""Test a shortcut for getting a specific state's probability"""
def mock_retrieve(*args, **kwargs):
return {
'nq': 3,
'shots': 10,
'output_probs': {'3': 0.4, '0': 0.6},
'meas_mapped': [0, 1],
... | Test a shortcut for getting a specific state's probability | test_ionq_get_probability | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_test.py | Apache-2.0 |
def test_ionq_invalid_command():
"""Test that this backend raises out with invalid commands."""
# Ph gate is not a valid gate
qb = WeakQubitRef(None, 1)
cmd = Command(None, gate=Ph(math.pi), qubits=[(qb,)])
backend = _ionq.IonQBackend(verbose=True)
with pytest.raises(InvalidCommandError):
... | Test that this backend raises out with invalid commands. | test_ionq_invalid_command | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_test.py | Apache-2.0 |
def test_ionq_sent_error(monkeypatch, mapper_factory):
"""Test that errors on "send" will raise back out."""
# patch send
type_error = TypeError()
mock_send = mock.MagicMock(side_effect=type_error)
monkeypatch.setattr(_ionq_http_client, "send", mock_send)
backend = _ionq.IonQBackend()
eng =... | Test that errors on "send" will raise back out. | test_ionq_sent_error | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_test.py | Apache-2.0 |
def test_ionq_send_nonetype_response_error(monkeypatch, mapper_factory):
"""Test that no return value from "send" will raise a runtime error."""
# patch send
mock_send = mock.MagicMock(return_value=None)
monkeypatch.setattr(_ionq_http_client, "send", mock_send)
backend = _ionq.IonQBackend()
eng... | Test that no return value from "send" will raise a runtime error. | test_ionq_send_nonetype_response_error | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_test.py | Apache-2.0 |
def test_ionq_retrieve(monkeypatch, mapper_factory):
"""Test that initializing a backend with a jobid will fetch that job's results to use as its own"""
def mock_retrieve(*args, **kwargs):
return {
'nq': 3,
'shots': 10,
'output_probs': {'3': 0.4, '0': 0.6},
... | Test that initializing a backend with a jobid will fetch that job's results to use as its own | test_ionq_retrieve | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_test.py | Apache-2.0 |
def test_ionq_backend_functional_test(monkeypatch, mapper_factory):
"""Test that the backend can handle a valid circuit with valid results."""
expected = {
'nq': 3,
'shots': 10,
'meas_mapped': [1, 2],
'meas_qubit_ids': [1, 2],
'circuit': [
{'gate': 'ry', 'rota... | Test that the backend can handle a valid circuit with valid results. | test_ionq_backend_functional_test | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_test.py | Apache-2.0 |
def test_ionq_backend_functional_aliases_test(monkeypatch, mapper_factory):
"""Test that sub-classed or aliased gates are handled correctly."""
# using alias gates, for coverage
expected = {
'nq': 4,
'shots': 10,
'meas_mapped': [2, 3],
'meas_qubit_ids': [2, 3],
'circu... | Test that sub-classed or aliased gates are handled correctly. | test_ionq_backend_functional_aliases_test | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_test.py | Apache-2.0 |
def test_ionq_no_midcircuit_measurement(monkeypatch, mapper_factory):
"""Test that attempts to measure mid-circuit raise exceptions."""
def mock_send(*args, **kwargs):
return {
'nq': 1,
'shots': 10,
'output_probs': {'0': 0.4, '1': 0.6},
}
monkeypatch.set... | Test that attempts to measure mid-circuit raise exceptions. | test_ionq_no_midcircuit_measurement | python | ProjectQ-Framework/ProjectQ | projectq/backends/_ionq/_ionq_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_ionq/_ionq_test.py | Apache-2.0 |
def _convert_logical_to_mapped_qubit(self, qubit):
"""
Convert a qubit from a logical to a mapped qubit if there is a mapper.
Args:
qubit (projectq.types.Qubit): Logical quantum bit
"""
mapper = self.main_engine.mapper
if mapper is not None:
if qu... |
Convert a qubit from a logical to a mapped qubit if there is a mapper.
Args:
qubit (projectq.types.Qubit): Logical quantum bit
| _convert_logical_to_mapped_qubit | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_classical_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_classical_simulator.py | Apache-2.0 |
def _write_mapped_bit(self, mapped_qubit, value):
"""
Write a mapped bit value.
For internal use only. Does not change logical to mapped qubits.
"""
pos = self._bit_positions[mapped_qubit.id]
if value:
self._state |= 1 << pos
else:
self._s... |
Write a mapped bit value.
For internal use only. Does not change logical to mapped qubits.
| _write_mapped_bit | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_classical_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_classical_simulator.py | Apache-2.0 |
def _mask(self, qureg):
"""
Return a mask, to compare against the state, with bits from the register set to 1 and other bits set to 0.
Args:
qureg (projectq.types.Qureg): The bits whose positions should be set.
Returns:
int: The mask.
"""
mask = ... |
Return a mask, to compare against the state, with bits from the register set to 1 and other bits set to 0.
Args:
qureg (projectq.types.Qureg): The bits whose positions should be set.
Returns:
int: The mask.
| _mask | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_classical_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_classical_simulator.py | Apache-2.0 |
def read_register(self, qureg):
"""
Read a group of bits as a little-endian integer.
Note:
If there is a mapper present in the compiler, this function automatically converts from logical qubits to
mapped qubits for the qureg argument.
Args:
qureg (pr... |
Read a group of bits as a little-endian integer.
Note:
If there is a mapper present in the compiler, this function automatically converts from logical qubits to
mapped qubits for the qureg argument.
Args:
qureg (projectq.types.Qureg):
The gr... | read_register | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_classical_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_classical_simulator.py | Apache-2.0 |
def _read_mapped_register(self, mapped_qureg):
"""
Read a value to some mapped quantum register.
For internal use only. Does not change logical to mapped qubits.
"""
mask = 0
for i, qubit in enumerate(mapped_qureg):
mask |= self._read_mapped_bit(qubit) << i
... |
Read a value to some mapped quantum register.
For internal use only. Does not change logical to mapped qubits.
| _read_mapped_register | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_classical_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_classical_simulator.py | Apache-2.0 |
def write_register(self, qureg, value):
"""
Set a group of bits to store a little-endian integer value.
Note:
If there is a mapper present in the compiler, this function automatically converts from logical qubits to
mapped qubits for the qureg argument.
Args:
... |
Set a group of bits to store a little-endian integer value.
Note:
If there is a mapper present in the compiler, this function automatically converts from logical qubits to
mapped qubits for the qureg argument.
Args:
qureg (projectq.types.Qureg): The bits to... | write_register | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_classical_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_classical_simulator.py | Apache-2.0 |
def _write_mapped_register(self, mapped_qureg, value):
"""
Write a value to some mapped quantum register.
For internal use only. Does not change logical to mapped qubits.
"""
if value < 0 or value >= 1 << len(mapped_qureg):
raise ValueError("Value won't fit in regist... |
Write a value to some mapped quantum register.
For internal use only. Does not change logical to mapped qubits.
| _write_mapped_register | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_classical_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_classical_simulator.py | Apache-2.0 |
def is_available(self, cmd):
"""Test whether a Command is supported by a compiler engine."""
return (
cmd.gate == Measure
or cmd.gate == Allocate
or cmd.gate == Deallocate
or isinstance(cmd.gate, (BasicMathGate, FlushGate, XGate))
) | Test whether a Command is supported by a compiler engine. | is_available | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_classical_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_classical_simulator.py | Apache-2.0 |
def receive(self, command_list):
"""
Receive a list of commands.
This implementation simply forwards all commands to the next engine.
"""
for cmd in command_list:
self._handle(cmd)
if not self.is_last_engine:
self.send(command_list) |
Receive a list of commands.
This implementation simply forwards all commands to the next engine.
| receive | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_classical_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_classical_simulator.py | Apache-2.0 |
def __init__(self, rnd_seed, *args, **kwargs): # pylint: disable=unused-argument
"""
Initialize the simulator.
Args:
rnd_seed (int): Seed to initialize the random number generator.
args: Dummy argument to allow an interface identical to the c++ simulator.
kw... |
Initialize the simulator.
Args:
rnd_seed (int): Seed to initialize the random number generator.
args: Dummy argument to allow an interface identical to the c++ simulator.
kwargs: Same as args.
| __init__ | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def allocate_qubit(self, qubit_id):
"""
Allocate a qubit.
Args:
qubit_id (int): ID of the qubit which is being allocated.
"""
self._map[qubit_id] = self._num_qubits
self._num_qubits += 1
self._state.resize(1 << self._num_qubits, refcheck=_USE_REFCHECK... |
Allocate a qubit.
Args:
qubit_id (int): ID of the qubit which is being allocated.
| allocate_qubit | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def get_classical_value(self, qubit_id, tol=1.0e-10):
"""
Return the classical value of a classical bit (i.e., a qubit which has been measured / uncomputed).
Args:
qubit_it (int): ID of the qubit of which to get the classical value.
tol (float): Tolerance for numerical e... |
Return the classical value of a classical bit (i.e., a qubit which has been measured / uncomputed).
Args:
qubit_it (int): ID of the qubit of which to get the classical value.
tol (float): Tolerance for numerical errors when determining whether the qubit is indeed classical.
... | get_classical_value | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def deallocate_qubit(self, qubit_id):
"""
Deallocate a qubit (if it has been measured / uncomputed).
Args:
qubit_id (int): ID of the qubit to deallocate.
Raises:
RuntimeError: If the qubit is in a superposition, i.e., has not been measured / uncomputed.
... |
Deallocate a qubit (if it has been measured / uncomputed).
Args:
qubit_id (int): ID of the qubit to deallocate.
Raises:
RuntimeError: If the qubit is in a superposition, i.e., has not been measured / uncomputed.
| deallocate_qubit | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def _get_control_mask(self, ctrlids):
"""
Get control mask from list of control qubit IDs.
Returns:
A mask which represents the control qubits in binary.
"""
mask = 0
for ctrlid in ctrlids:
ctrlpos = self._map[ctrlid]
mask |= 1 << ctrl... |
Get control mask from list of control qubit IDs.
Returns:
A mask which represents the control qubits in binary.
| _get_control_mask | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def emulate_math(self, func, qubit_ids, ctrlqubit_ids): # pylint: disable=too-many-locals
"""
Emulate a math function (e.g., BasicMathGate).
Args:
func (function): Function executing the operation to emulate.
qubit_ids (list<list<int>>): List of lists of qubit IDs to wh... |
Emulate a math function (e.g., BasicMathGate).
Args:
func (function): Function executing the operation to emulate.
qubit_ids (list<list<int>>): List of lists of qubit IDs to which the gate is being applied. Every gate is
applied to a tuple of quantum registers, ... | emulate_math | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def get_expectation_value(self, terms_dict, ids):
"""
Return the expectation value of a qubit operator w.r.t. qubit ids.
Args:
terms_dict (dict): Operator dictionary (see QubitOperator.terms)
ids (list[int]): List of qubit ids upon which the operator acts.
Retur... |
Return the expectation value of a qubit operator w.r.t. qubit ids.
Args:
terms_dict (dict): Operator dictionary (see QubitOperator.terms)
ids (list[int]): List of qubit ids upon which the operator acts.
Returns:
Expectation value
| get_expectation_value | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def apply_qubit_operator(self, terms_dict, ids):
"""
Apply a (possibly non-unitary) qubit operator to qubits.
Args:
terms_dict (dict): Operator dictionary (see QubitOperator.terms)
ids (list[int]): List of qubit ids upon which the operator acts.
"""
new_s... |
Apply a (possibly non-unitary) qubit operator to qubits.
Args:
terms_dict (dict): Operator dictionary (see QubitOperator.terms)
ids (list[int]): List of qubit ids upon which the operator acts.
| apply_qubit_operator | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def get_probability(self, bit_string, ids):
"""
Return the probability of the outcome `bit_string` when measuring the qubits given by the list of ids.
Args:
bit_string (list[bool|int]): Measurement outcome.
ids (list[int]): List of qubit ids determining the ordering.
... |
Return the probability of the outcome `bit_string` when measuring the qubits given by the list of ids.
Args:
bit_string (list[bool|int]): Measurement outcome.
ids (list[int]): List of qubit ids determining the ordering.
Returns:
Probability of measuring the... | get_probability | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def get_amplitude(self, bit_string, ids):
"""
Return the probability amplitude of the supplied `bit_string`.
The ordering is given by the list of qubit ids.
Args:
bit_string (list[bool|int]): Computational basis state
ids (list[int]): List of qubit ids determini... |
Return the probability amplitude of the supplied `bit_string`.
The ordering is given by the list of qubit ids.
Args:
bit_string (list[bool|int]): Computational basis state
ids (list[int]): List of qubit ids determining the ordering. Must contain all allocated qubits.
... | get_amplitude | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def emulate_time_evolution(self, terms_dict, time, ids, ctrlids): # pylint: disable=too-many-locals
"""
Apply exp(-i*time*H) to the wave function, i.e., evolves under the Hamiltonian H for a given time.
The terms in the Hamiltonian are not required to commute.
This function computes t... |
Apply exp(-i*time*H) to the wave function, i.e., evolves under the Hamiltonian H for a given time.
The terms in the Hamiltonian are not required to commute.
This function computes the action of the matrix exponential using ideas from Al-Mohy and Higham, 2011.
TODO: Implement better es... | emulate_time_evolution | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def apply_controlled_gate(self, matrix, ids, ctrlids):
"""
Apply the k-qubit gate matrix m to the qubits with indices ids, using ctrlids as control qubits.
Args:
matrix (list[list]): 2^k x 2^k complex matrix describing the k-qubit gate.
ids (list): A list containing the ... |
Apply the k-qubit gate matrix m to the qubits with indices ids, using ctrlids as control qubits.
Args:
matrix (list[list]): 2^k x 2^k complex matrix describing the k-qubit gate.
ids (list): A list containing the qubit IDs to which to apply the gate.
ctrlids (list): ... | apply_controlled_gate | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def _single_qubit_gate(self, matrix, pos, mask):
"""
Apply the single qubit gate matrix m to the qubit at position `pos` using `mask` to identify control qubits.
Args:
matrix (list[list]): 2x2 complex matrix describing the single-qubit gate.
pos (int): Bit-position of th... |
Apply the single qubit gate matrix m to the qubit at position `pos` using `mask` to identify control qubits.
Args:
matrix (list[list]): 2x2 complex matrix describing the single-qubit gate.
pos (int): Bit-position of the qubit.
mask (int): Bit-mask where set bits ind... | _single_qubit_gate | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def _multi_qubit_gate(self, matrix, pos, mask): # pylint: disable=too-many-locals
"""
Apply the k-qubit gate matrix m to the qubits at `pos` using `mask` to identify control qubits.
Args:
matrix (list[list]): 2^k x 2^k complex matrix describing the k-qubit gate.
pos (li... |
Apply the k-qubit gate matrix m to the qubits at `pos` using `mask` to identify control qubits.
Args:
matrix (list[list]): 2^k x 2^k complex matrix describing the k-qubit gate.
pos (list[int]): List of bit-positions of the qubits.
mask (int): Bit-mask where set bits... | _multi_qubit_gate | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def set_wavefunction(self, wavefunction, ordering):
"""
Set wavefunction and qubit ordering.
Args:
wavefunction (list[complex]): Array of complex amplitudes describing the wavefunction (must be normalized).
ordering (list): List of ids describing the new ordering of qubi... |
Set wavefunction and qubit ordering.
Args:
wavefunction (list[complex]): Array of complex amplitudes describing the wavefunction (must be normalized).
ordering (list): List of ids describing the new ordering of qubits (i.e., the ordering of the provided
wavefunc... | set_wavefunction | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def collapse_wavefunction(self, ids, values):
"""
Collapse a quantum register onto a classical basis state.
Args:
ids (list[int]): Qubit IDs to collapse.
values (list[bool]): Measurement outcome for each of the qubit IDs in `ids`.
Raises:
RuntimeErro... |
Collapse a quantum register onto a classical basis state.
Args:
ids (list[int]): Qubit IDs to collapse.
values (list[bool]): Measurement outcome for each of the qubit IDs in `ids`.
Raises:
RuntimeError: If probability of outcome is ~0 or unknown qubits are ... | collapse_wavefunction | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def run(self):
"""
Provide a dummy implementation for running a quantum circuit.
Only defined to provide the same interface as the c++ simulator.
""" |
Provide a dummy implementation for running a quantum circuit.
Only defined to provide the same interface as the c++ simulator.
| run | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.0 |
def _apply_term(self, term, ids, ctrlids=None):
"""
Apply a QubitOperator term to the state vector.
(Helper function for time evolution & expectation)
Args:
term: One term of QubitOperator.terms
ids (list[int]): Term index to Qubit ID mapping
ctrlids... |
Apply a QubitOperator term to the state vector.
(Helper function for time evolution & expectation)
Args:
term: One term of QubitOperator.terms
ids (list[int]): Term index to Qubit ID mapping
ctrlids (list[int]): Control qubit IDs
| _apply_term | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_pysim.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_pysim.py | Apache-2.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 effe... |
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 see... | __init__ | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_simulator.py | Apache-2.0 |
def is_available(self, cmd):
"""
Test whether a Command is supported by a compiler engine.
Specialized implementation of is_available: The simulator can deal with all arbitrarily-controlled gates which
provide a gate-matrix (via gate.matrix) and acts on 5 or less qubits (not counting th... |
Test whether a Command is supported by a compiler engine.
Specialized implementation of is_available: The simulator can deal with all arbitrarily-controlled gates which
provide a gate-matrix (via gate.matrix) and acts on 5 or less qubits (not counting the control qubits).
Args:
... | is_available | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_simulator.py | Apache-2.0 |
def _convert_logical_to_mapped_qureg(self, qureg):
"""
Convert a qureg from logical to mapped qubits if there is a mapper.
Args:
qureg (list[Qubit],Qureg): Logical quantum bits
"""
mapper = self.main_engine.mapper
if mapper is not None:
mapped_qur... |
Convert a qureg from logical to mapped qubits if there is a mapper.
Args:
qureg (list[Qubit],Qureg): Logical quantum bits
| _convert_logical_to_mapped_qureg | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_simulator.py | Apache-2.0 |
def get_expectation_value(self, qubit_operator, qureg):
"""
Return the expectation value of a qubit operator.
Get the expectation value of qubit_operator w.r.t. the current wave
function represented by the supplied quantum register.
Args:
qubit_operator (projectq.op... |
Return the expectation value of a qubit operator.
Get the expectation value of qubit_operator w.r.t. the current wave
function represented by the supplied quantum register.
Args:
qubit_operator (projectq.ops.QubitOperator): Operator to measure.
qureg (list[Qubi... | get_expectation_value | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_simulator.py | Apache-2.0 |
def apply_qubit_operator(self, qubit_operator, qureg):
"""
Apply a (possibly non-unitary) qubit_operator to the current wave function represented by a quantum register.
Args:
qubit_operator (projectq.ops.QubitOperator): Operator to apply.
qureg (list[Qubit],Qureg): Quant... |
Apply a (possibly non-unitary) qubit_operator to the current wave function represented by a quantum register.
Args:
qubit_operator (projectq.ops.QubitOperator): Operator to apply.
qureg (list[Qubit],Qureg): Quantum bits to which to apply the operator.
Raises:
... | apply_qubit_operator | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_simulator.py | Apache-2.0 |
def get_probability(self, bit_string, qureg):
"""
Return the probability of the outcome `bit_string` when measuring the quantum register `qureg`.
Args:
bit_string (list[bool|int]|string[0|1]): Measurement outcome.
qureg (Qureg|list[Qubit]): Quantum register.
Ret... |
Return the probability of the outcome `bit_string` when measuring the quantum register `qureg`.
Args:
bit_string (list[bool|int]|string[0|1]): Measurement outcome.
qureg (Qureg|list[Qubit]): Quantum register.
Returns:
Probability of measuring the provided b... | get_probability | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_simulator.py | Apache-2.0 |
def get_amplitude(self, bit_string, qureg):
"""
Return the probability amplitude of the supplied `bit_string`.
The ordering is given by the quantum register `qureg`, which must
contain all allocated qubits.
Args:
bit_string (list[bool|int]|string[0|1]): Computationa... |
Return the probability amplitude of the supplied `bit_string`.
The ordering is given by the quantum register `qureg`, which must
contain all allocated qubits.
Args:
bit_string (list[bool|int]|string[0|1]): Computational basis state
qureg (Qureg|list[Qubit]): Qu... | get_amplitude | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_simulator.py | Apache-2.0 |
def set_wavefunction(self, wavefunction, qureg):
"""
Set the wavefunction and the qubit ordering of the simulator.
The simulator will adopt the ordering of qureg (instead of reordering
the wavefunction).
Args:
wavefunction (list[complex]): Array of complex amplitude... |
Set the wavefunction and the qubit ordering of the simulator.
The simulator will adopt the ordering of qureg (instead of reordering
the wavefunction).
Args:
wavefunction (list[complex]): Array of complex amplitudes
describing the wavefunction (must be norma... | set_wavefunction | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_simulator.py | Apache-2.0 |
def collapse_wavefunction(self, qureg, values):
"""
Collapse a quantum register onto a classical basis state.
Args:
qureg (Qureg|list[Qubit]): Qubits to collapse.
values (list[bool|int]|string[0|1]): Measurement outcome for each
... |
Collapse a quantum register onto a classical basis state.
Args:
qureg (Qureg|list[Qubit]): Qubits to collapse.
values (list[bool|int]|string[0|1]): Measurement outcome for each
of the qubits in `qureg`.
Raises:
... | collapse_wavefunction | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_simulator.py | Apache-2.0 |
def _handle(self, cmd): # pylint: disable=too-many-branches,too-many-locals,too-many-statements
"""
Handle all commands.
i.e., call the member functions of the C++- simulator object corresponding to measurement, allocation/
deallocation, and (controlled) single-qubit gate.
Arg... |
Handle all commands.
i.e., call the member functions of the C++- simulator object corresponding to measurement, allocation/
deallocation, and (controlled) single-qubit gate.
Args:
cmd (Command): Command to handle.
Raises:
Exception: If a non-single-qub... | _handle | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_simulator.py | Apache-2.0 |
def receive(self, command_list):
"""
Receive a list of commands.
Receive a list of commands from the previous engine and handle them (simulate them classically) prior to
sending them on to the next engine.
Args:
command_list (list<Command>): List of commands to exec... |
Receive a list of commands.
Receive a list of commands from the previous engine and handle them (simulate them classically) prior to
sending them on to the next engine.
Args:
command_list (list<Command>): List of commands to execute on the simulator.
| receive | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_simulator.py | Apache-2.0 |
def test_simulator_set_wavefunction_always_complex(sim):
"""Checks that wavefunction is always complex"""
eng = MainEngine(sim)
qubit = eng.allocate_qubit()
eng.flush()
wf = [1.0, 0]
eng.backend.set_wavefunction(wf, qubit)
Y | qubit
eng.flush()
assert eng.backend.get_amplitude('1', q... | Checks that wavefunction is always complex | test_simulator_set_wavefunction_always_complex | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_simulator_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_simulator_test.py | Apache-2.0 |
def mapper(request):
"""Add a mapper which changes qubit ids by adding 1."""
if request.param == "mapper":
class TrivialMapper(BasicMapperEngine):
def __init__(self):
super().__init__()
self.current_mapping = {}
def receive(self, command_list):
... | Add a mapper which changes qubit ids by adding 1. | mapper | python | ProjectQ-Framework/ProjectQ | projectq/backends/_sim/_simulator_test_fixtures.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_sim/_simulator_test_fixtures.py | Apache-2.0 |
def _send_cmd_with_mapped_ids(self, cmd):
"""
Send this Command using the mapped qubit ids of self.current_mapping.
If it is a Measurement gate, then it adds a LogicalQubitID tag.
Args:
cmd: Command object with logical qubit ids.
"""
new_cmd = deepcopy(cmd)
... |
Send this Command using the mapped qubit ids of self.current_mapping.
If it is a Measurement gate, then it adds a LogicalQubitID tag.
Args:
cmd: Command object with logical qubit ids.
| _send_cmd_with_mapped_ids | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_basicmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_basicmapper.py | Apache-2.0 |
def __init__(self):
"""
Initialize the basic engine.
Initializes local variables such as _next_engine, _main_engine, etc. to None.
"""
self.main_engine = None
self.next_engine = None
self.is_last_engine = False |
Initialize the basic engine.
Initializes local variables such as _next_engine, _main_engine, etc. to None.
| __init__ | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_basics.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_basics.py | Apache-2.0 |
def is_available(self, cmd):
"""
Test whether a Command is supported by a compiler engine.
Default implementation of is_available: Ask the next engine whether a command is available, i.e., whether it can
be executed by the next engine(s).
Args:
cmd (Command): Comman... |
Test whether a Command is supported by a compiler engine.
Default implementation of is_available: Ask the next engine whether a command is available, i.e., whether it can
be executed by the next engine(s).
Args:
cmd (Command): Command for which to check availability.
... | is_available | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_basics.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_basics.py | Apache-2.0 |
def allocate_qubit(self, dirty=False):
"""
Return a new qubit as a list containing 1 qubit object (quantum register of size 1).
Allocates a new qubit by getting a (new) qubit id from the MainEngine, creating the qubit object, and then
sending an AllocateQubit command down the pipeline. ... |
Return a new qubit as a list containing 1 qubit object (quantum register of size 1).
Allocates a new qubit by getting a (new) qubit id from the MainEngine, creating the qubit object, and then
sending an AllocateQubit command down the pipeline. If dirty=True, the fresh qubit can be replaced by ... | allocate_qubit | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_basics.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_basics.py | Apache-2.0 |
def deallocate_qubit(self, qubit):
"""
Deallocate a qubit (and sends the deallocation command down the pipeline).
If the qubit was allocated as a dirty qubit, add DirtyQubitTag() to Deallocate command.
Args:
qubit (BasicQubit): Qubit to deallocate.
Raises:
... |
Deallocate a qubit (and sends the deallocation command down the pipeline).
If the qubit was allocated as a dirty qubit, add DirtyQubitTag() to Deallocate command.
Args:
qubit (BasicQubit): Qubit to deallocate.
Raises:
ValueError: Qubit already deallocated. Call... | deallocate_qubit | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_basics.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_basics.py | Apache-2.0 |
def is_meta_tag_supported(self, meta_tag):
"""
Check if there is a compiler engine handling the meta tag.
Args:
engine: First engine to check (then iteratively calls getNextEngine)
meta_tag: Meta tag class for which to check support
Returns:
supporte... |
Check if there is a compiler engine handling the meta tag.
Args:
engine: First engine to check (then iteratively calls getNextEngine)
meta_tag: Meta tag class for which to check support
Returns:
supported (bool): True if one of the further compiler engines ... | is_meta_tag_supported | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_basics.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_basics.py | Apache-2.0 |
def __init__(self, engine, cmd_mod_fun=None):
"""
Initialize a ForwarderEngine.
Args:
engine (BasicEngine): Engine to forward all commands to.
cmd_mod_fun (function): Function which is called before sending a command. Each command cmd is replaced by
the c... |
Initialize a ForwarderEngine.
Args:
engine (BasicEngine): Engine to forward all commands to.
cmd_mod_fun (function): Function which is called before sending a command. Each command cmd is replaced by
the command it returns when getting called with cmd.
| __init__ | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_basics.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_basics.py | Apache-2.0 |
def __init__(self, cmd_mod_fun):
"""
Initialize the CommandModifier.
Args:
cmd_mod_fun (function): Function which, given a command cmd, returns the command it should send instead.
Example:
.. code-block:: python
def cmd_mod_fun(cmd):
... |
Initialize the CommandModifier.
Args:
cmd_mod_fun (function): Function which, given a command cmd, returns the command it should send instead.
Example:
.. code-block:: python
def cmd_mod_fun(cmd):
cmd.tags += [MyOwnTag()]
... | __init__ | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_cmdmodifier.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_cmdmodifier.py | Apache-2.0 |
def __init__(self, connections=None):
"""
Initialize an IBM 5-qubit mapper compiler engine.
Resets the mapping.
"""
super().__init__()
self.current_mapping = {}
self._reset()
self._cmds = []
self._interactions = {}
if connections is None:... |
Initialize an IBM 5-qubit mapper compiler engine.
Resets the mapping.
| __init__ | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_ibm5qubitmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_ibm5qubitmapper.py | Apache-2.0 |
def _reset(self):
"""Reset the mapping parameters so the next circuit can be mapped."""
self._cmds = []
self._interactions = {} | Reset the mapping parameters so the next circuit can be mapped. | _reset | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_ibm5qubitmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_ibm5qubitmapper.py | Apache-2.0 |
def _determine_cost(self, mapping):
"""
Determine the cost of the circuit with the given mapping.
Args:
mapping (dict): Dictionary with key, value pairs where keys are logical qubit ids and the corresponding
value is the physical location on the IBM Q chip.
R... |
Determine the cost of the circuit with the given mapping.
Args:
mapping (dict): Dictionary with key, value pairs where keys are logical qubit ids and the corresponding
value is the physical location on the IBM Q chip.
Returns:
Cost measure taking into ac... | _determine_cost | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_ibm5qubitmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_ibm5qubitmapper.py | Apache-2.0 |
def _run(self):
"""
Run all stored gates.
Raises:
Exception:
If the mapping to the IBM backend cannot be performed or if the mapping was already determined but
more CNOTs get sent down the pipeline.
"""
if len(self.current_mapping) > 0... |
Run all stored gates.
Raises:
Exception:
If the mapping to the IBM backend cannot be performed or if the mapping was already determined but
more CNOTs get sent down the pipeline.
| _run | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_ibm5qubitmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_ibm5qubitmapper.py | Apache-2.0 |
def _store(self, cmd):
"""
Store a command and handle CNOTs.
Args:
cmd (Command): A command to store
"""
if not cmd.gate == FlushGate():
target = cmd.qubits[0][0].id
if _is_cnot(cmd):
# CNOT encountered
ctrl = cmd.control_q... |
Store a command and handle CNOTs.
Args:
cmd (Command): A command to store
| _store | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_ibm5qubitmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_ibm5qubitmapper.py | Apache-2.0 |
def receive(self, command_list):
"""
Receive a list of commands.
Receive a command list and, for each command, stores it until completion.
Args:
command_list (list of Command objects): list of commands to
receive.
Raises:
Exception: If m... |
Receive a list of commands.
Receive a command list and, for each command, stores it until completion.
Args:
command_list (list of Command objects): list of commands to
receive.
Raises:
Exception: If mapping the CNOT gates to 1 qubit would requi... | receive | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_ibm5qubitmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_ibm5qubitmapper.py | Apache-2.0 |
def return_swap_depth(swaps):
"""
Return the circuit depth to execute these swaps.
Args:
swaps(list of tuples): Each tuple contains two integers representing the two IDs of the qubits involved in the
Swap operation
Returns:
Circuit depth to execute these s... |
Return the circuit depth to execute these swaps.
Args:
swaps(list of tuples): Each tuple contains two integers representing the two IDs of the qubits involved in the
Swap operation
Returns:
Circuit depth to execute these swaps.
| return_swap_depth | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_linearmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_linearmapper.py | Apache-2.0 |
def __init__(self, num_qubits, cyclic=False, storage=1000):
"""
Initialize a LinearMapper compiler engine.
Args:
num_qubits(int): Number of physical qubits in the linear chain
cyclic(bool): If 1D chain is a cycle. Default is False.
storage(int): Number of gat... |
Initialize a LinearMapper compiler engine.
Args:
num_qubits(int): Number of physical qubits in the linear chain
cyclic(bool): If 1D chain is a cycle. Default is False.
storage(int): Number of gates to temporarily store, default is 1000
| __init__ | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_linearmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_linearmapper.py | Apache-2.0 |
def is_available(self, cmd):
"""Only allows 1 or two qubit gates."""
num_qubits = 0
for qureg in cmd.all_qubits:
num_qubits += len(qureg)
return num_qubits <= 2 | Only allows 1 or two qubit gates. | is_available | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_linearmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_linearmapper.py | Apache-2.0 |
def return_new_mapping(num_qubits, cyclic, currently_allocated_ids, stored_commands, current_mapping):
"""
Build a mapping of qubits to a linear chain.
It goes through stored_commands and tries to find a mapping to apply these gates on a first come first served
basis. More complicated ... |
Build a mapping of qubits to a linear chain.
It goes through stored_commands and tries to find a mapping to apply these gates on a first come first served
basis. More complicated scheme could try to optimize to apply as many gates as possible between the Swaps.
Args:
num_... | return_new_mapping | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_linearmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_linearmapper.py | Apache-2.0 |
def _process_two_qubit_gate( # pylint: disable=too-many-arguments,too-many-branches,too-many-statements
num_qubits, cyclic, qubit0, qubit1, active_qubits, segments, neighbour_ids
):
"""
Process a two qubit gate.
It either removes the two qubits from active_qubits if the gate is not... |
Process a two qubit gate.
It either removes the two qubits from active_qubits if the gate is not possible or updates the segments such
that the gate is possible.
Args:
num_qubits (int): Total number of qubits in the chain
cyclic (bool): If linear chain is a cyc... | _process_two_qubit_gate | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_linearmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_linearmapper.py | Apache-2.0 |
def _return_new_mapping_from_segments( # pylint: disable=too-many-locals,too-many-branches
num_qubits, segments, allocated_qubits, current_mapping
):
"""
Combine the individual segments into a new mapping.
It tries to minimize the number of swaps to go from the old mapping in self.... |
Combine the individual segments into a new mapping.
It tries to minimize the number of swaps to go from the old mapping in self.current_mapping to the new mapping
which it returns. The strategy is to map a segment to the same region where most of the qubits are
already. Note that this ... | _return_new_mapping_from_segments | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_linearmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_linearmapper.py | Apache-2.0 |
def _odd_even_transposition_sort_swaps(self, old_mapping, new_mapping):
"""
Return the swap operation for an odd-even transposition sort.
See https://en.wikipedia.org/wiki/Odd-even_sort for more info.
Args:
old_mapping: dict: keys are logical ids and values are mapped qubit... |
Return the swap operation for an odd-even transposition sort.
See https://en.wikipedia.org/wiki/Odd-even_sort for more info.
Args:
old_mapping: dict: keys are logical ids and values are mapped qubit ids
new_mapping: dict: keys are logical ids and values are mapped qubi... | _odd_even_transposition_sort_swaps | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_linearmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_linearmapper.py | Apache-2.0 |
def _send_possible_commands(self): # pylint: disable=too-many-branches
"""
Send the stored commands possible without changing the mapping.
Note: self.current_mapping must exist already
"""
active_ids = deepcopy(self._currently_allocated_ids)
for logical_id in self.curre... |
Send the stored commands possible without changing the mapping.
Note: self.current_mapping must exist already
| _send_possible_commands | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_linearmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_linearmapper.py | Apache-2.0 |
def _run(self): # pylint: disable=too-many-locals,too-many-branches
"""
Create a new mapping and executes possible gates.
It first allocates all 0, ..., self.num_qubits-1 mapped qubit ids, if they are not already used because we
might need them all for the swaps. Then it creates a new ... |
Create a new mapping and executes possible gates.
It first allocates all 0, ..., self.num_qubits-1 mapped qubit ids, if they are not already used because we
might need them all for the swaps. Then it creates a new map, swaps all the qubits to the new map, executes
all possible gates, a... | _run | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_linearmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_linearmapper.py | Apache-2.0 |
def receive(self, command_list):
"""
Receive a list of commands.
Receive a command list and, for each command, stores it until we do a mapping (FlushGate or Cache of stored
commands is full).
Args:
command_list (list of Command objects): list of commands to receive.... |
Receive a list of commands.
Receive a command list and, for each command, stores it until we do a mapping (FlushGate or Cache of stored
commands is full).
Args:
command_list (list of Command objects): list of commands to receive.
| receive | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_linearmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_linearmapper.py | Apache-2.0 |
def __init__( # pylint: disable=too-many-statements,too-many-branches
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-... |
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 (l... | __init__ | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_main.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_main.py | Apache-2.0 |
def __del__(self):
"""
Destroy the main engine.
Flushes the entire circuit down the pipeline, clearing all temporary buffers (in, e.g., optimizers).
"""
if not hasattr(sys, "last_type"):
self.flush(deallocate_qubits=True)
try:
atexit.unregister(se... |
Destroy the main engine.
Flushes the entire circuit down the pipeline, clearing all temporary buffers (in, e.g., optimizers).
| __del__ | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_main.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_main.py | Apache-2.0 |
def get_measurement_result(self, qubit):
"""
Return the classical value of a measured qubit, given that an engine registered this result previously.
See also setMeasurementResult.
Args:
qubit (BasicQubit): Qubit of which to get the measurement result.
Example:
... |
Return the classical value of a measured qubit, given that an engine registered this result previously.
See also setMeasurementResult.
Args:
qubit (BasicQubit): Qubit of which to get the measurement result.
Example:
.. code-block:: python
from... | get_measurement_result | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_main.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_main.py | Apache-2.0 |
def get_new_qubit_id(self):
"""
Return a unique qubit id to be used for the next qubit allocation.
Returns:
new_qubit_id (int): New unique qubit id.
"""
self._qubit_idx += 1
return self._qubit_idx - 1 |
Return a unique qubit id to be used for the next qubit allocation.
Returns:
new_qubit_id (int): New unique qubit id.
| get_new_qubit_id | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_main.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_main.py | Apache-2.0 |
def send(self, command_list):
"""
Forward the list of commands to the next engine in the pipeline.
It also shortens exception stack traces if self.verbose is False.
"""
try:
self.next_engine.receive(command_list)
except Exception as err: # pylint: disable=br... |
Forward the list of commands to the next engine in the pipeline.
It also shortens exception stack traces if self.verbose is False.
| send | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_main.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_main.py | Apache-2.0 |
def flush(self, deallocate_qubits=False):
"""
Flush the entire circuit down the pipeline, clearing potential buffers (of, e.g., optimizers).
Args:
deallocate_qubits (bool): If True, deallocates all qubits that are still alive (invalidating references to
them by setti... |
Flush the entire circuit down the pipeline, clearing potential buffers (of, e.g., optimizers).
Args:
deallocate_qubits (bool): If True, deallocates all qubits that are still alive (invalidating references to
them by setting their id to -1).
| flush | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_main.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_main.py | Apache-2.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
... |
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 (must be constant).
| __init__ | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_manualmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_manualmapper.py | Apache-2.0 |
def receive(self, command_list):
"""
Receives a command list and passes it to the next engine, adding qubit placement tags to allocate gates.
Args:
command_list (list of Command objects): list of commands to receive.
"""
for cmd in command_list:
ids = [qb... |
Receives a command list and passes it to the next engine, adding qubit placement tags to allocate gates.
Args:
command_list (list of Command objects): list of commands to receive.
| receive | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_manualmapper.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_manualmapper.py | Apache-2.0 |
def __init__(self, cache_size=5, m=None): # pylint: disable=invalid-name
"""
Initialize a LocalOptimizer object.
Args:
cache_size (int): Number of gates to cache per qubit, before sending on the first gate.
"""
super().__init__()
self._l = {} # dict of list... |
Initialize a LocalOptimizer object.
Args:
cache_size (int): Number of gates to cache per qubit, before sending on the first gate.
| __init__ | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_optimize.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_optimize.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.