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 get_probability(self, state, qureg):
"""Shortcut to get a specific state's probability.
Args:
state (str): A state in bit-string format.
qureg (Qureg): A ProjectQ Qureg object.
Returns:
float: The probability for the provided state.
"""
if len(state) != len(qureg):
raise ValueError('Desired state and register must be the same length!')
probs = self.get_probabilities(qureg)
return probs[state] | Shortcut to get a specific state's probability.
Args:
state (str): A state in bit-string format.
qureg (Qureg): A ProjectQ Qureg object.
Returns:
float: The probability for the provided state.
| get_probability | 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 get_probabilities(self, qureg):
"""
Given the provided qubit register, determine the probability of each possible outcome.
Note:
This method should only be called *after* a circuit has been run and its results are available.
Args:
qureg (Qureg): A ProjectQ Qureg object.
Returns:
dict: A dict mapping of states -> probability.
"""
if len(self._probabilities) == 0:
raise RuntimeError("Please, run the circuit first!")
probability_dict = {}
for state, probability in self._probabilities.items():
mapped_state = ['0'] * len(qureg)
for i, qubit in enumerate(qureg):
try:
meas_idx = self._measured_ids.index(qubit.id)
except ValueError:
continue
mapped_state[i] = state[meas_idx]
mapped_state = "".join(mapped_state)
probability_dict[mapped_state] = probability_dict.get(mapped_state, 0) + probability
return probability_dict |
Given the provided qubit register, determine the probability of each possible outcome.
Note:
This method should only be called *after* a circuit has been run and its results are available.
Args:
qureg (Qureg): A ProjectQ Qureg object.
Returns:
dict: A dict mapping of states -> probability.
| get_probabilities | 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 _run(self): # pylint: disable=too-many-locals
"""Run the circuit this object has built during engine execution."""
# Nothing to do with an empty circuit.
if len(self._circuit) == 0:
return
if self._retrieve_execution is None:
qubit_mapping = self.main_engine.mapper.current_mapping
measured_ids = self._measured_ids[:]
info = {
'circuit': self._circuit,
'nq': len(qubit_mapping.keys()),
'shots': self._num_runs,
'meas_mapped': [qubit_mapping[qubit_id] for qubit_id in measured_ids],
'meas_qubit_ids': measured_ids,
}
res = http_client.send(
info,
device=self.device,
token=self._token,
num_retries=self._num_retries,
interval=self._interval,
verbose=self._verbose,
)
if res is None:
raise RuntimeError('Failed to submit job to the server!')
else:
res = http_client.retrieve(
device=self.device,
token=self._token,
jobid=self._retrieve_execution,
num_retries=self._num_retries,
interval=self._interval,
verbose=self._verbose,
)
if res is None:
raise RuntimeError(f"Failed to retrieve job with id: '{self._retrieve_execution}'!")
self._measured_ids = measured_ids = res['meas_qubit_ids']
# Determine random outcome from probable states.
random_outcome = random.random()
p_sum = 0.0
measured = ""
star = ""
num_measured = len(measured_ids)
probable_outcomes = res['output_probs']
states = probable_outcomes.keys()
self._probabilities = {}
for idx, state_int in enumerate(states):
state = _rearrange_result(int(state_int), num_measured)
probability = probable_outcomes[state_int]
p_sum += probability
if p_sum >= random_outcome and measured == "" or (idx == len(states) - 1):
measured = state
star = "*"
self._probabilities[state] = probability
if self._verbose and probability > 0: # pragma: no cover
print(f"{state} with p = {probability}{star}")
# Register measurement results
for idx, qubit_id in enumerate(measured_ids):
result = int(measured[idx])
qubit_ref = WeakQubitRef(self.main_engine, qubit_id)
self.main_engine.set_measurement_result(qubit_ref, result) | Run the circuit this object has built during engine execution. | _run | 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.
self.backends = {
'ionq_simulator': {
'nq': 29,
'target': 'simulator',
},
'ionq_qpu': {
'nq': 11,
'target': 'qpu',
},
}
for backend in r_json:
self.backends[backend["backend"]] = {"nq": backend["qubits"], "target": backend["backend"]}
if self._verbose: # pragma: no cover
print('- List of IonQ devices available:')
print(self.backends) | 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
needed to run this experiment.
Args:
info (dict): A dict containing number of shots, qubits, and
a circuit.
device (str): An IonQ device name.
Returns:
tuple(bool, int, int): Whether the operation can be run, max
number of qubits the device supports, and number of qubits
required for the experiment.
"""
nb_qubit_max = self.backends[device]['nq']
nb_qubit_needed = info['nq']
return nb_qubit_needed <= nb_qubit_max, nb_qubit_max, nb_qubit_needed |
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:
info (dict): A dict containing number of shots, qubits, and
a circuit.
device (str): An IonQ device name.
Returns:
tuple(bool, int, int): Whether the operation can be run, max
number of qubits the device supports, and number of qubits
required for the experiment.
| 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 > ')
if not token:
raise RuntimeError('An authentication token is required!')
self.headers.update({'Authorization': f'apiKey {token}'})
self.token = token | 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 integer states to probability values.
Args:
device (str): The device used to run this job.
execution_id (str): An IonQ Job ID.
num_retries (int, optional): Number of times to retry the fetch
before raising a timeout error. Defaults to 3000.
interval (int, optional): Number of seconds to wait between retries.
Defaults to 1.
Raises:
Exception: If the process receives a kill signal before completion.
Exception: If the job is in an unknown processing state.
DeviceOfflineError: If the provided device is not online.
RequestTimeoutError: If we were unable to retrieve the job results
after ``num_retries`` attempts.
Returns:
dict: A dict of job data for an engine to consume.
"""
if self._verbose: # pragma: no cover
print(f"Waiting for results. [Job ID: {execution_id}]")
original_sigint_handler = signal.getsignal(signal.SIGINT)
def _handle_sigint_during_get_result(*_): # pragma: no cover
raise Exception(f"Interrupted. The ID of your submitted job is {execution_id}.")
signal.signal(signal.SIGINT, _handle_sigint_during_get_result)
try:
for retries in range(num_retries):
req = super().get(urljoin(_JOB_API_URL, execution_id))
req.raise_for_status()
r_json = req.json()
status = r_json['status']
# Check if job is completed.
if status == 'completed':
meas_mapped = r_json['registers']['meas_mapped']
meas_qubit_ids = json.loads(r_json['metadata']['meas_qubit_ids'])
output_probs = r_json['data']['registers']['meas_mapped']
return {
'nq': r_json['qubits'],
'output_probs': output_probs,
'meas_mapped': meas_mapped,
'meas_qubit_ids': meas_qubit_ids,
}
# Otherwise, make sure it is in a known healthy state.
if status not in ('ready', 'running', 'submitted'):
# TODO: Add comprehensive API error processing here.
raise Exception(f"Error while running the code: {status}.")
# Sleep, then check availability before trying again.
time.sleep(interval)
if self.is_online(device) and retries % 60 == 0:
self.update_devices_list()
if not self.is_online(device): # pragma: no cover
raise DeviceOfflineError(
f"Device went offline. The ID of your submitted job is {execution_id}."
)
finally:
if original_sigint_handler is not None:
signal.signal(signal.SIGINT, original_sigint_handler)
raise RequestTimeoutError(f"Timeout. The ID of your submitted job is {execution_id}.") |
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 device used to run this job.
execution_id (str): An IonQ Job ID.
num_retries (int, optional): Number of times to retry the fetch
before raising a timeout error. Defaults to 3000.
interval (int, optional): Number of seconds to wait between retries.
Defaults to 1.
Raises:
Exception: If the process receives a kill signal before completion.
Exception: If the job is in an unknown processing state.
DeviceOfflineError: If the provided device is not online.
RequestTimeoutError: If we were unable to retrieve the job results
after ``num_retries`` attempts.
Returns:
dict: A dict of job data for an engine to consume.
| 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])
else:
self._process_cmd(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_probabilities([])
eng.flush() | 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],
'meas_qubit_ids': [1, 2],
}
monkeypatch.setattr(_ionq_http_client, "retrieve", mock_retrieve)
backend = _ionq.IonQBackend(
retrieve_execution="a3877d18-314f-46c9-86e7-316bc4dbe968",
verbose=True,
)
eng = MainEngine(backend=backend, engine_list=[mapper_factory()])
unused_qubit = eng.allocate_qubit() # noqa: F841
qureg = eng.allocate_qureg(2)
# entangle the qureg
Ry(math.pi / 2) | qureg[0]
Rx(math.pi / 2) | qureg[0]
Rx(math.pi / 2) | qureg[0]
Ry(math.pi / 2) | qureg[0]
Rxx(math.pi / 2) | (qureg[0], qureg[1])
Rx(7 * math.pi / 2) | qureg[0]
Ry(7 * math.pi / 2) | qureg[0]
Rx(7 * math.pi / 2) | qureg[1]
# measure; should be all-0 or all-1
All(Measure) | qureg
# run the circuit
eng.flush()
assert eng.backend.get_probability('11', qureg) == pytest.approx(0.4)
assert eng.backend.get_probability('00', qureg) == pytest.approx(0.6)
with pytest.raises(ValueError) as excinfo:
eng.backend.get_probability('111', qureg)
assert str(excinfo.value) == 'Desired state and register must be the same length!' | 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_get_probabilities(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': {'1': 0.4, '0': 0.6},
'meas_mapped': [1],
'meas_qubit_ids': [1],
}
monkeypatch.setattr(_ionq_http_client, "retrieve", mock_retrieve)
backend = _ionq.IonQBackend(
retrieve_execution="a3877d18-314f-46c9-86e7-316bc4dbe968",
verbose=True,
)
eng = MainEngine(backend=backend, engine_list=[mapper_factory()])
qureg = eng.allocate_qureg(2)
q0, q1 = qureg
H | q0
CNOT | (q0, q1)
Measure | q1
# run the circuit
eng.flush()
assert eng.backend.get_probability('01', qureg) == pytest.approx(0.4)
assert eng.backend.get_probability('00', qureg) == pytest.approx(0.6)
assert eng.backend.get_probability('1', [qureg[1]]) == pytest.approx(0.4)
assert eng.backend.get_probability('0', [qureg[1]]) == pytest.approx(0.6) | Test a shortcut for getting a specific state's probability | test_ionq_get_probabilities | 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):
backend.receive([cmd]) | 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 = MainEngine(
backend=backend,
engine_list=[mapper_factory()],
verbose=True,
)
qubit = eng.allocate_qubit()
Rx(0.5) | qubit
with pytest.raises(Exception) as excinfo:
qubit[0].__del__()
eng.flush()
# verbose=True on the engine re-raises errors instead of compacting them.
assert type_error is excinfo.value
# atexit sends another FlushGate, therefore we remove the backend:
dummy = DummyEngine()
dummy.is_last_engine = True
eng.next_engine = dummy | 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 = MainEngine(
backend=backend,
engine_list=[mapper_factory()],
verbose=True,
)
qubit = eng.allocate_qubit()
Rx(0.5) | qubit
with pytest.raises(RuntimeError) as excinfo:
eng.flush()
# verbose=True on the engine re-raises errors instead of compacting them.
assert str(excinfo.value) == "Failed to submit job to the server!"
# atexit sends another FlushGate, therefore we remove the backend:
dummy = DummyEngine()
dummy.is_last_engine = True
eng.next_engine = dummy | 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},
'meas_mapped': [0, 1],
'meas_qubit_ids': [1, 2],
}
monkeypatch.setattr(_ionq_http_client, "retrieve", mock_retrieve)
backend = _ionq.IonQBackend(
retrieve_execution="a3877d18-314f-46c9-86e7-316bc4dbe968",
verbose=True,
)
eng = MainEngine(backend=backend, engine_list=[mapper_factory()])
unused_qubit = eng.allocate_qubit()
qureg = eng.allocate_qureg(2)
# entangle the qureg
Ry(math.pi / 2) | qureg[0]
Rx(math.pi / 2) | qureg[0]
Rx(math.pi / 2) | qureg[0]
Ry(math.pi / 2) | qureg[0]
Rxx(math.pi / 2) | (qureg[0], qureg[1])
Rx(7 * math.pi / 2) | qureg[0]
Ry(7 * math.pi / 2) | qureg[0]
Rx(7 * math.pi / 2) | qureg[1]
del unused_qubit
# measure; should be all-0 or all-1
All(Measure) | qureg
# run the circuit
eng.flush()
prob_dict = eng.backend.get_probabilities([qureg[0], qureg[1]])
assert prob_dict['11'] == pytest.approx(0.4)
assert prob_dict['00'] == pytest.approx(0.6)
# Unknown qubit
invalid_qubit = [WeakQubitRef(eng, 10)]
probs = eng.backend.get_probabilities(invalid_qubit)
assert {'0': 1} == probs | 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_retrieve_nonetype_response_error(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 None
monkeypatch.setattr(_ionq_http_client, "retrieve", mock_retrieve)
backend = _ionq.IonQBackend(
retrieve_execution="a3877d18-314f-46c9-86e7-316bc4dbe968",
verbose=True,
)
eng = MainEngine(
backend=backend,
engine_list=[mapper_factory()],
verbose=True,
)
unused_qubit = eng.allocate_qubit()
qureg = eng.allocate_qureg(2)
# entangle the qureg
Ry(math.pi / 2) | qureg[0]
Rx(math.pi / 2) | qureg[0]
Rx(math.pi / 2) | qureg[0]
Ry(math.pi / 2) | qureg[0]
Rxx(math.pi / 2) | (qureg[0], qureg[1])
Rx(7 * math.pi / 2) | qureg[0]
Ry(7 * math.pi / 2) | qureg[0]
Rx(7 * math.pi / 2) | qureg[1]
del unused_qubit
# measure; should be all-0 or all-1
All(Measure) | qureg
# run the circuit
with pytest.raises(RuntimeError) as excinfo:
eng.flush()
exc = excinfo.value
expected_err = "Failed to retrieve job with id: 'a3877d18-314f-46c9-86e7-316bc4dbe968'!"
assert str(exc) == expected_err | Test that initializing a backend with a jobid will fetch that job's results to use as its own | test_ionq_retrieve_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_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', 'rotation': 0.5, 'targets': [1]},
{'gate': 'rx', 'rotation': 0.5, 'targets': [1]},
{'gate': 'rx', 'rotation': 0.5, 'targets': [1]},
{'gate': 'ry', 'rotation': 0.5, 'targets': [1]},
{'gate': 'xx', 'rotation': 0.5, 'targets': [1, 2]},
{'gate': 'rx', 'rotation': 3.5, 'targets': [1]},
{'gate': 'ry', 'rotation': 3.5, 'targets': [1]},
{'gate': 'rx', 'rotation': 3.5, 'targets': [2]},
],
}
def mock_send(*args, **kwargs):
assert args[0] == expected
return {
'nq': 3,
'shots': 10,
'output_probs': {'3': 0.4, '0': 0.6},
'meas_mapped': [1, 2],
'meas_qubit_ids': [1, 2],
}
monkeypatch.setattr(_ionq_http_client, "send", mock_send)
backend = _ionq.IonQBackend(verbose=True, num_runs=10)
eng = MainEngine(
backend=backend,
engine_list=[mapper_factory()],
verbose=True,
)
unused_qubit = eng.allocate_qubit() # noqa: F841
qureg = eng.allocate_qureg(2)
# entangle the qureg
Ry(0.5) | qureg[0]
Rx(0.5) | qureg[0]
Rx(0.5) | qureg[0]
Ry(0.5) | qureg[0]
Rxx(0.5) | (qureg[0], qureg[1])
Rx(3.5) | qureg[0]
Ry(3.5) | qureg[0]
Rx(3.5) | qureg[1]
All(Barrier) | qureg
# measure; should be all-0 or all-1
All(Measure) | qureg
# run the circuit
eng.flush()
prob_dict = eng.backend.get_probabilities([qureg[0], qureg[1]])
assert prob_dict['11'] == pytest.approx(0.4)
assert prob_dict['00'] == pytest.approx(0.6) | 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],
'circuit': [
{'gate': 'x', 'targets': [0]},
{'gate': 'x', 'targets': [1]},
{'controls': [0], 'gate': 'x', 'targets': [2]},
{'controls': [1], 'gate': 'x', 'targets': [2]},
{'controls': [0, 1], 'gate': 'x', 'targets': [3]},
{'gate': 's', 'targets': [2]},
{'gate': 'si', 'targets': [3]},
],
}
def mock_send(*args, **kwargs):
assert args[0] == expected
return {
'nq': 4,
'shots': 10,
'output_probs': {'1': 0.9},
'meas_mapped': [2, 3],
}
monkeypatch.setattr(_ionq_http_client, "send", mock_send)
backend = _ionq.IonQBackend(verbose=True, num_runs=10)
eng = MainEngine(
backend=backend,
engine_list=[mapper_factory(9)],
verbose=True,
)
# Do some stuff with a circuit. Get weird with it.
circuit = eng.allocate_qureg(4)
qubit1, qubit2, qubit3, qubit4 = circuit
All(X) | [qubit1, qubit2]
CNOT | (qubit1, qubit3)
CNOT | (qubit2, qubit3)
Toffoli | (qubit1, qubit2, qubit4)
Barrier | circuit
S | qubit3
Sdag | qubit4
All(Measure) | [qubit3, qubit4]
# run the circuit
eng.flush()
prob_dict = eng.backend.get_probabilities([qubit3, qubit4])
assert prob_dict['10'] == pytest.approx(0.9) | 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.setattr(_ionq_http_client, "send", mock_send)
# Create a backend to use with an engine.
backend = _ionq.IonQBackend(verbose=True, num_runs=10)
eng = MainEngine(
backend=backend,
engine_list=[mapper_factory()],
verbose=True,
)
qubit = eng.allocate_qubit()
X | qubit
Measure | qubit
with pytest.raises(MidCircuitMeasurementError):
X | qubit
# atexit sends another FlushGate, therefore we remove the backend:
dummy = DummyEngine()
dummy.is_last_engine = True
eng.active_qubits = []
eng.next_engine = dummy | 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 qubit.id not in mapper.current_mapping:
raise RuntimeError("Unknown qubit id. Please make sure you have called eng.flush().")
return WeakQubitRef(qubit.engine, mapper.current_mapping[qubit.id])
return qubit |
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._state &= ~(1 << pos) |
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 = 0
for qb in qureg:
mask |= 1 << self._bit_positions[qb.id]
return 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 (projectq.types.Qureg):
The group of bits to read, in little-endian order.
Returns:
int: Little-endian register value.
"""
new_qureg = []
for qubit in qureg:
new_qureg.append(self._convert_logical_to_mapped_qubit(qubit))
return self._read_mapped_register(new_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 (projectq.types.Qureg):
The group of bits to read, in little-endian order.
Returns:
int: Little-endian register value.
| 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
return mask |
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:
qureg (projectq.types.Qureg): The bits to write, in little-endian order.
value (int): The integer value to store. Must fit in the register.
"""
new_qureg = []
for qubit in qureg:
new_qureg.append(self._convert_logical_to_mapped_qubit(qubit))
self._write_mapped_register(new_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:
qureg (projectq.types.Qureg): The bits to write, in little-endian order.
value (int): The integer value to store. Must fit in the register.
| 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 register.")
for i, mapped_qubit in enumerate(mapped_qureg):
self._write_mapped_bit(mapped_qubit, (value >> i) & 1) |
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.
kwargs: Same as args.
"""
random.seed(rnd_seed)
self._state = _np.ones(1, dtype=_np.complex128)
self._map = {}
self._num_qubits = 0
print("(Note: This is the (slow) Python simulator.)") |
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 measure_qubits(self, ids):
"""
Measure the qubits with IDs ids and return a list of measurement outcomes (True/False).
Args:
ids (list<int>): List of qubit IDs to measure.
Returns:
List of measurement results (containing either True or False).
"""
random_outcome = random.random()
val = 0.0
i_picked = 0
while val < random_outcome and i_picked < len(self._state):
val += _np.abs(self._state[i_picked]) ** 2
i_picked += 1
i_picked -= 1
pos = [self._map[ID] for ID in ids]
res = [False] * len(pos)
mask = 0
val = 0
for i, _pos in enumerate(pos):
res[i] = ((i_picked >> _pos) & 1) == 1
mask |= 1 << _pos
val |= (res[i] & 1) << _pos
nrm = 0.0
for i, _state in enumerate(self._state):
if (mask & i) != val:
self._state[i] = 0.0
else:
nrm += _np.abs(_state) ** 2
self._state *= 1.0 / _np.sqrt(nrm)
return res |
Measure the qubits with IDs ids and return a list of measurement outcomes (True/False).
Args:
ids (list<int>): List of qubit IDs to measure.
Returns:
List of measurement results (containing either True or False).
| measure_qubits | 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 errors when determining whether the qubit is indeed classical.
Raises:
RuntimeError: If the qubit is in a superposition, i.e., has not been measured / uncomputed.
"""
pos = self._map[qubit_id]
state_up = state_down = False
for i in range(0, len(self._state), (1 << (pos + 1))):
for j in range(0, (1 << pos)):
if _np.abs(self._state[i + j]) > tol:
state_up = True
if _np.abs(self._state[i + j + (1 << pos)]) > tol:
state_down = True
if state_up and state_down:
raise RuntimeError(
"Qubit has not been measured / "
"uncomputed. Cannot access its "
"classical value and/or deallocate a "
"qubit in superposition!"
)
return state_down |
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.
Raises:
RuntimeError: If the qubit is in a superposition, i.e., has not been measured / uncomputed.
| 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.
"""
pos = self._map[qubit_id]
classical_value = self.get_classical_value(qubit_id)
newstate = _np.zeros((1 << (self._num_qubits - 1)), dtype=_np.complex128)
k = 0
for i in range((1 << pos) * int(classical_value), len(self._state), (1 << (pos + 1))):
newstate[k : k + (1 << pos)] = self._state[i : i + (1 << pos)] # noqa: E203
k += 1 << pos
newmap = {}
for key, value in self._map.items():
if value > pos:
newmap[key] = value - 1
elif key != qubit_id:
newmap[key] = value
self._map = newmap
self._state = newstate
self._num_qubits -= 1 |
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 << ctrlpos
return mask |
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 which the gate is being applied. Every gate is
applied to a tuple of quantum registers, which corresponds to this 'list of lists'.
ctrlqubit_ids (list<int>): List of control qubit ids.
"""
mask = self._get_control_mask(ctrlqubit_ids)
# determine qubit locations from their IDs
qb_locs = []
for qureg in qubit_ids:
qb_locs.append([])
for qubit_id in qureg:
qb_locs[-1].append(self._map[qubit_id])
newstate = _np.zeros_like(self._state)
for i, state in enumerate(self._state):
if (mask & i) == mask:
arg_list = [0] * len(qb_locs)
for qr_i, qr_loc in enumerate(qb_locs):
for qb_i, qb_loc in enumerate(qr_loc):
arg_list[qr_i] |= ((i >> qb_loc) & 1) << qb_i
res = func(arg_list)
new_i = i
for qr_i, qr_loc in enumerate(qb_locs):
for qb_i, qb_loc in enumerate(qr_loc):
if not ((new_i >> qb_loc) & 1) == ((res[qr_i] >> qb_i) & 1):
new_i ^= 1 << qb_loc
newstate[new_i] = state
else:
newstate[i] = state
self._state = newstate |
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, which corresponds to this 'list of lists'.
ctrlqubit_ids (list<int>): List of control qubit ids.
| 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.
Returns:
Expectation value
"""
expectation = 0.0
current_state = _np.copy(self._state)
for term, coefficient in terms_dict:
self._apply_term(term, ids)
delta = coefficient * _np.vdot(current_state, self._state).real
expectation += delta
self._state = _np.copy(current_state)
return expectation |
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_state = _np.zeros_like(self._state)
current_state = _np.copy(self._state)
for term, coefficient in terms_dict:
self._apply_term(term, ids)
self._state *= coefficient
new_state += self._state
self._state = _np.copy(current_state)
self._state = new_state |
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.
Returns:
Probability of measuring the provided bit string.
Raises:
RuntimeError if an unknown qubit id was provided.
"""
for qubit_id in ids:
if qubit_id not in self._map:
raise RuntimeError("get_probability(): Unknown qubit id. Please make sure you have called eng.flush().")
mask = 0
bit_str = 0
for i, qubit_id in enumerate(ids):
mask |= 1 << self._map[qubit_id]
bit_str |= bit_string[i] << self._map[qubit_id]
probability = 0.0
for i, state in enumerate(self._state):
if (i & mask) == bit_str:
probability += state.real**2 + state.imag**2
return probability |
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 provided bit string.
Raises:
RuntimeError if an unknown qubit id was provided.
| 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 determining the ordering. Must contain all allocated qubits.
Returns:
Probability amplitude of the provided bit string.
Raises:
RuntimeError if the second argument is not a permutation of all allocated qubits.
"""
if not set(ids) == set(self._map):
raise RuntimeError(
"The second argument to get_amplitude() must be a permutation of all allocated qubits. "
"Please make sure you have called eng.flush()."
)
index = 0
for i, qubit_id in enumerate(ids):
index |= bit_string[i] << self._map[qubit_id]
return self._state[index] |
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.
Returns:
Probability amplitude of the provided bit string.
Raises:
RuntimeError if the second argument is not a permutation of 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 the action of the matrix exponential using ideas from Al-Mohy and Higham, 2011.
TODO: Implement better estimates for s.
Args:
terms_dict (dict): Operator dictionary (see QubitOperator.terms) defining the Hamiltonian.
time (scalar): Time to evolve for
ids (list): A list of qubit IDs to which to apply the evolution.
ctrlids (list): A list of control qubit IDs.
"""
# Determine the (normalized) trace, which is nonzero only for identity terms:
trace = sum(c for (t, c) in terms_dict if len(t) == 0)
terms_dict = [(t, c) for (t, c) in terms_dict if len(t) > 0]
op_nrm = abs(time) * sum(abs(c) for (_, c) in terms_dict)
# rescale the operator by s:
scale = int(op_nrm + 1.0)
correction = _np.exp(-1j * time * trace / float(scale))
output_state = _np.copy(self._state)
mask = self._get_control_mask(ctrlids)
for _ in range(scale):
j = 0
nrm_change = 1.0
while nrm_change > 1.0e-12:
coeff = (-time * 1j) / float(scale * (j + 1))
current_state = _np.copy(self._state)
update = 0j
for term, tcoeff in terms_dict:
self._apply_term(term, ids)
self._state *= tcoeff
update += self._state
self._state = _np.copy(current_state)
update *= coeff
self._state = update
for k, _update in enumerate(update):
if (k & mask) == mask:
output_state[k] += _update
nrm_change = _np.linalg.norm(update)
j += 1
for k in range(len(update)):
if (k & mask) == mask:
output_state[k] *= correction
self._state = _np.copy(output_state) |
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 estimates for s.
Args:
terms_dict (dict): Operator dictionary (see QubitOperator.terms) defining the Hamiltonian.
time (scalar): Time to evolve for
ids (list): A list of qubit IDs to which to apply the evolution.
ctrlids (list): A list of control qubit IDs.
| 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 qubit IDs to which to apply the gate.
ctrlids (list): A list of control qubit IDs (i.e., the gate is only applied where these qubits are 1).
"""
mask = self._get_control_mask(ctrlids)
if len(matrix) == 2:
pos = self._map[ids[0]]
self._single_qubit_gate(matrix, pos, mask)
else:
pos = [self._map[ID] for ID in ids]
self._multi_qubit_gate(matrix, pos, mask) |
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): A list of control qubit IDs (i.e., the gate is only applied where these qubits are 1).
| 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 the qubit.
mask (int): Bit-mask where set bits indicate control qubits.
"""
def kernel(u, d, m): # pylint: disable=invalid-name
return u * m[0][0] + d * m[0][1], u * m[1][0] + d * m[1][1]
for i in range(0, len(self._state), (1 << (pos + 1))):
for j in range(1 << pos):
if ((i + j) & mask) == mask:
id1 = i + j
id2 = id1 + (1 << pos)
self._state[id1], self._state[id2] = kernel(self._state[id1], self._state[id2], matrix) |
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 indicate control qubits.
| _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 (list[int]): List of bit-positions of the qubits.
mask (int): Bit-mask where set bits indicate control qubits.
"""
# follows the description in https://arxiv.org/abs/1704.01127
inactive = [p for p in range(len(self._map)) if p not in pos]
matrix = _np.matrix(matrix)
subvec = _np.zeros(1 << len(pos), dtype=complex)
subvec_idx = [0] * len(subvec)
for k in range(1 << len(inactive)):
# determine base index (state of inactive qubits)
base = 0
for i, _inactive in enumerate(inactive):
base |= ((k >> i) & 1) << _inactive
# check the control mask
if mask != (base & mask):
continue
# now gather all elements involved in mat-vec mul
for j in range(len(subvec_idx)): # pylint: disable=consider-using-enumerate
offset = 0
for i, _pos in enumerate(pos):
offset |= ((j >> i) & 1) << _pos
subvec_idx[j] = base | offset
subvec[j] = self._state[subvec_idx[j]]
# perform mat-vec mul
self._state[subvec_idx] = matrix.dot(subvec) |
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 indicate control qubits.
| _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 qubits (i.e., the ordering of the provided
wavefunction).
"""
# wavefunction contains 2^n values for n qubits
if len(wavefunction) != (1 << len(ordering)): # pragma: no cover
raise ValueError('The wavefunction must contain 2^n elements!')
# all qubits must have been allocated before
if not all(qubit_id in self._map for qubit_id in ordering) or len(self._map) != len(ordering):
raise RuntimeError(
"set_wavefunction(): Invalid mapping provided. Please make sure all qubits have been "
"allocated previously (call eng.flush())."
)
self._state = _np.array(wavefunction, dtype=_np.complex128)
self._map = {ordering[i]: i for i in range(len(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 qubits (i.e., the ordering of the provided
wavefunction).
| 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:
RuntimeError: If probability of outcome is ~0 or unknown qubits are provided.
"""
if len(ids) != len(values):
raise ValueError('The number of ids and values do not match!')
# all qubits must have been allocated before
if not all(Id in self._map for Id in ids):
raise RuntimeError(
"collapse_wavefunction(): Unknown qubit id(s) provided. Try calling eng.flush() before "
"invoking this function."
)
mask = 0
val = 0
for i, qubit_id in enumerate(ids):
pos = self._map[qubit_id]
mask |= 1 << pos
val |= int(values[i]) << pos
nrm = 0.0
for i, state in enumerate(self._state):
if (mask & i) == val:
nrm += _np.abs(state) ** 2
if nrm < 1.0e-12:
raise RuntimeError("collapse_wavefunction(): Invalid collapse! Probability is ~0.")
inv_nrm = 1.0 / _np.sqrt(nrm)
for i in range(len(self._state)): # pylint: disable=consider-using-enumerate
if (mask & i) != val:
self._state[i] = 0.0
else:
self._state[i] *= inv_nrm |
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 provided.
| 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 (list[int]): Control qubit IDs
"""
X = [[0.0, 1.0], [1.0, 0.0]]
Y = [[0.0, -1j], [1j, 0.0]]
Z = [[1.0, 0.0], [0.0, -1.0]]
gates = [X, Y, Z]
if not ctrlids:
ctrlids = []
for local_op in term:
qb_id = ids[local_op[0]]
self.apply_controlled_gate(gates[ord(local_op[1]) - ord('X')], [qb_id], 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 effect for the c++ simulator).
rnd_seed (int): Random seed (uses random.randint(0, 4294967295) 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 gate matrices and then applies one 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 further hints on how
to build the C++ extension.
"""
if rnd_seed is None:
rnd_seed = random.randint(0, 4294967295)
super().__init__()
self._simulator = SimulatorBackend(rnd_seed)
self._gate_fusion = gate_fusion |
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, 4294967295) 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 gate matrices and then applies one 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 further hints on how
to build the C++ extension.
| __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 the control qubits).
Args:
cmd (Command): Command for which to check availability (single- qubit gate, arbitrary controls)
Returns:
True if it can be simulated and False otherwise.
"""
if has_negative_control(cmd):
return False
if (
cmd.gate == Measure
or cmd.gate == Allocate
or cmd.gate == Deallocate
or isinstance(cmd.gate, (BasicMathGate, TimeEvolution))
):
return True
try:
matrix = cmd.gate.matrix
# Allow up to 5-qubit gates
if len(matrix) > 2**5:
return False
return True
except AttributeError:
return False |
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:
cmd (Command): Command for which to check availability (single- qubit gate, arbitrary controls)
Returns:
True if it can be simulated and False otherwise.
| 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_qureg = []
for qubit in qureg:
if qubit.id not in mapper.current_mapping:
raise RuntimeError("Unknown qubit id. Please make sure you have called eng.flush().")
new_qubit = WeakQubitRef(qubit.engine, mapper.current_mapping[qubit.id])
mapped_qureg.append(new_qubit)
return mapped_qureg
return qureg |
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.ops.QubitOperator): Operator to measure.
qureg (list[Qubit],Qureg): Quantum bits to measure.
Returns:
Expectation value
Note:
Make sure all previous commands (especially allocations) have passed through the compilation chain (call
main_engine.flush() to make sure).
Note:
If there is a mapper present in the compiler, this function automatically converts from logical qubits to
mapped qubits for the qureg argument.
Raises:
Exception: If `qubit_operator` acts on more qubits than present in the `qureg` argument.
"""
qureg = self._convert_logical_to_mapped_qureg(qureg)
num_qubits = len(qureg)
for term, _ in qubit_operator.terms.items():
if not term == () and term[-1][0] >= num_qubits:
raise Exception("qubit_operator acts on more qubits than contained in the qureg.")
operator = [(list(term), coeff) for (term, coeff) in qubit_operator.terms.items()]
return self._simulator.get_expectation_value(operator, [qb.id for qb in 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.ops.QubitOperator): Operator to measure.
qureg (list[Qubit],Qureg): Quantum bits to measure.
Returns:
Expectation value
Note:
Make sure all previous commands (especially allocations) have passed through the compilation chain (call
main_engine.flush() to make sure).
Note:
If there is a mapper present in the compiler, this function automatically converts from logical qubits to
mapped qubits for the qureg argument.
Raises:
Exception: If `qubit_operator` acts on more qubits than present in the `qureg` argument.
| 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): Quantum bits to which to apply the operator.
Raises:
Exception: If `qubit_operator` acts on more qubits than present in
the `qureg` argument.
Warning:
This function allows applying non-unitary gates and it will not re-normalize the wave function! It is for
numerical experiments only and should not be used for other purposes.
Note:
Make sure all previous commands (especially allocations) have passed through the compilation chain (call
main_engine.flush() to make sure).
Note:
If there is a mapper present in the compiler, this function automatically converts from logical qubits to
mapped qubits for the qureg argument.
"""
qureg = self._convert_logical_to_mapped_qureg(qureg)
num_qubits = len(qureg)
for term, _ in qubit_operator.terms.items():
if not term == () and term[-1][0] >= num_qubits:
raise Exception("qubit_operator acts on more qubits than contained in the qureg.")
operator = [(list(term), coeff) for (term, coeff) in qubit_operator.terms.items()]
return self._simulator.apply_qubit_operator(operator, [qb.id for qb in 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): Quantum bits to which to apply the operator.
Raises:
Exception: If `qubit_operator` acts on more qubits than present in
the `qureg` argument.
Warning:
This function allows applying non-unitary gates and it will not re-normalize the wave function! It is for
numerical experiments only and should not be used for other purposes.
Note:
Make sure all previous commands (especially allocations) have passed through the compilation chain (call
main_engine.flush() to make sure).
Note:
If there is a mapper present in the compiler, this function automatically converts from logical qubits to
mapped qubits for the qureg argument.
| 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.
Returns:
Probability of measuring the provided bit string.
Note:
Make sure all previous commands (especially allocations) have passed through the compilation chain (call
main_engine.flush() to make sure).
Note:
If there is a mapper present in the compiler, this function automatically converts from logical qubits to
mapped qubits for the qureg argument.
"""
qureg = self._convert_logical_to_mapped_qureg(qureg)
bit_string = [bool(int(b)) for b in bit_string]
return self._simulator.get_probability(bit_string, [qb.id for qb in 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.
Returns:
Probability of measuring the provided bit string.
Note:
Make sure all previous commands (especially allocations) have passed through the compilation chain (call
main_engine.flush() to make sure).
Note:
If there is a mapper present in the compiler, this function automatically converts from logical qubits to
mapped qubits for the qureg argument.
| 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]): Computational basis state
qureg (Qureg|list[Qubit]): Quantum register determining the ordering. Must contain all allocated qubits.
Returns:
Probability amplitude of the provided bit string.
Note:
Make sure all previous commands (especially allocations) have passed through the compilation chain (call
main_engine.flush() to make sure).
Note:
If there is a mapper present in the compiler, this function automatically converts from logical qubits to
mapped qubits for the qureg argument.
"""
qureg = self._convert_logical_to_mapped_qureg(qureg)
bit_string = [bool(int(b)) for b in bit_string]
return self._simulator.get_amplitude(bit_string, [qb.id for qb in 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]): Computational basis state
qureg (Qureg|list[Qubit]): Quantum register determining the ordering. Must contain all allocated qubits.
Returns:
Probability amplitude of the provided bit string.
Note:
Make sure all previous commands (especially allocations) have passed through the compilation chain (call
main_engine.flush() to make sure).
Note:
If there is a mapper present in the compiler, this function automatically converts from logical qubits to
mapped qubits for the qureg argument.
| 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 amplitudes
describing the wavefunction (must be normalized).
qureg (Qureg|list[Qubit]): Quantum register determining the
ordering. Must contain all allocated qubits.
Note:
Make sure all previous commands (especially allocations) have
passed through the compilation chain (call main_engine.flush() to
make sure).
Note:
If there is a mapper present in the compiler, this function
automatically converts from logical qubits to mapped qubits for
the qureg argument.
"""
qureg = self._convert_logical_to_mapped_qureg(qureg)
self._simulator.set_wavefunction(wavefunction, [qb.id for qb in 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 amplitudes
describing the wavefunction (must be normalized).
qureg (Qureg|list[Qubit]): Quantum register determining the
ordering. Must contain all allocated qubits.
Note:
Make sure all previous commands (especially allocations) have
passed through the compilation chain (call main_engine.flush() to
make sure).
Note:
If there is a mapper present in the compiler, this function
automatically converts from logical qubits to mapped qubits for
the qureg argument.
| 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
of the qubits in `qureg`.
Raises:
RuntimeError: If an outcome has probability (approximately) 0 or
if unknown qubits are provided (see note).
Note:
Make sure all previous commands have passed through the
compilation chain (call main_engine.flush() to make sure).
Note:
If there is a mapper present in the compiler, this function
automatically converts from logical qubits to mapped qubits for
the qureg argument.
"""
qureg = self._convert_logical_to_mapped_qureg(qureg)
return self._simulator.collapse_wavefunction([qb.id for qb in qureg], [bool(int(v)) for v in 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
of the qubits in `qureg`.
Raises:
RuntimeError: If an outcome has probability (approximately) 0 or
if unknown qubits are provided (see note).
Note:
Make sure all previous commands have passed through the
compilation chain (call main_engine.flush() to make sure).
Note:
If there is a mapper present in the compiler, this function
automatically converts from logical qubits to mapped qubits for
the qureg argument.
| 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.
Args:
cmd (Command): Command to handle.
Raises:
Exception: If a non-single-qubit gate needs to be processed (which should never happen due to
is_available).
"""
if cmd.gate == Measure:
if get_control_count(cmd) != 0:
raise ValueError('Cannot have control qubits with a measurement gate!')
ids = [qb.id for qr in cmd.qubits for qb in qr]
out = self._simulator.measure_qubits(ids)
i = 0
for qureg in cmd.qubits:
for qb in qureg:
# Check if a mapper assigned a different logical id
logical_id_tag = None
for tag in cmd.tags:
if isinstance(tag, LogicalQubitIDTag):
logical_id_tag = tag
if logical_id_tag is not None:
qb = WeakQubitRef(qb.engine, logical_id_tag.logical_qubit_id)
self.main_engine.set_measurement_result(qb, out[i])
i += 1
elif cmd.gate == Allocate:
qubit_id = cmd.qubits[0][0].id
self._simulator.allocate_qubit(qubit_id)
elif cmd.gate == Deallocate:
qubit_id = cmd.qubits[0][0].id
self._simulator.deallocate_qubit(qubit_id)
elif isinstance(cmd.gate, BasicMathGate):
# improve performance by using C++ code for some commomn gates
from projectq.libs.math import ( # pylint: disable=import-outside-toplevel
AddConstant,
AddConstantModN,
MultiplyByConstantModN,
)
qubitids = []
for qureg in cmd.qubits:
qubitids.append([])
for qb in qureg:
qubitids[-1].append(qb.id)
if FALLBACK_TO_PYSIM:
math_fun = cmd.gate.get_math_function(cmd.qubits)
self._simulator.emulate_math(math_fun, qubitids, [qb.id for qb in cmd.control_qubits])
else:
# individual code for different standard gates to make it faster!
if isinstance(cmd.gate, AddConstant):
self._simulator.emulate_math_addConstant(cmd.gate.a, qubitids, [qb.id for qb in cmd.control_qubits])
elif isinstance(cmd.gate, AddConstantModN):
self._simulator.emulate_math_addConstantModN(
cmd.gate.a,
cmd.gate.N,
qubitids,
[qb.id for qb in cmd.control_qubits],
)
elif isinstance(cmd.gate, MultiplyByConstantModN):
self._simulator.emulate_math_multiplyByConstantModN(
cmd.gate.a,
cmd.gate.N,
qubitids,
[qb.id for qb in cmd.control_qubits],
)
else:
math_fun = cmd.gate.get_math_function(cmd.qubits)
self._simulator.emulate_math(math_fun, qubitids, [qb.id for qb in cmd.control_qubits])
elif isinstance(cmd.gate, TimeEvolution):
op = [(list(term), coeff) for (term, coeff) in cmd.gate.hamiltonian.terms.items()]
time = cmd.gate.time
qubitids = [qb.id for qb in cmd.qubits[0]]
ctrlids = [qb.id for qb in cmd.control_qubits]
self._simulator.emulate_time_evolution(op, time, qubitids, ctrlids)
elif len(cmd.gate.matrix) <= 2**5:
matrix = cmd.gate.matrix
ids = [qb.id for qureg in cmd.qubits for qb in qureg]
if not 2 ** len(ids) == len(cmd.gate.matrix):
raise Exception(
f"Simulator: Error applying {str(cmd.gate)} gate: {int(math.log(len(cmd.gate.matrix), 2))}-qubit"
f" gate applied to {len(ids)} qubits."
)
self._simulator.apply_controlled_gate(matrix.tolist(), ids, [qb.id for qb in cmd.control_qubits])
if not self._gate_fusion:
self._simulator.run()
else:
raise Exception(
"This simulator only supports controlled k-qubit gates with k < 6!\nPlease add an auto-replacer"
" engine to your list of compiler engines."
) |
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-qubit gate needs to be processed (which should never happen due to
is_available).
| _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 execute on the simulator.
"""
for cmd in command_list:
if not cmd.gate == FlushGate():
self._handle(cmd)
else:
self._simulator.run() # flush gate --> run all saved gates
if not self.is_last_engine:
self.send([cmd]) |
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 mapper(request):
"""
Adds 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):
for cmd in command_list:
for qureg in cmd.all_qubits:
for qubit in qureg:
if qubit.id == -1:
continue
elif qubit.id not in self.current_mapping:
previous_map = self.current_mapping
previous_map[qubit.id] = qubit.id + 1
self.current_mapping = previous_map
self._send_cmd_with_mapped_ids(cmd)
return TrivialMapper()
if request.param == "no_mapper":
return None |
Adds a mapper which changes qubit ids by adding 1
| mapper | 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 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', qubit) == pytest.approx(1j) | 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):
for cmd in command_list:
for qureg in cmd.all_qubits:
for qubit in qureg:
if qubit.id == -1:
continue
elif qubit.id not in self.current_mapping:
previous_map = self.current_mapping
previous_map[qubit.id] = qubit.id + 1
self.current_mapping = previous_map
self._send_cmd_with_mapped_ids(cmd)
return TrivialMapper()
if request.param == "no_mapper":
return None | 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)
qubits = new_cmd.qubits
for qureg in qubits:
for qubit in qureg:
if qubit.id != -1:
qubit.id = self.current_mapping[qubit.id]
control_qubits = new_cmd.control_qubits
for qubit in control_qubits:
qubit.id = self.current_mapping[qubit.id]
if isinstance(new_cmd.gate, MeasureGate):
# Add LogicalQubitIDTag to MeasureGate
def add_logical_id(command, old_tags=deepcopy(cmd.tags)):
command.tags = old_tags + [LogicalQubitIDTag(cmd.qubits[0][0].id)]
return command
tagger_eng = CommandModifier(add_logical_id)
insert_engine(self, tagger_eng)
self.send([new_cmd])
drop_engine_after(self)
else:
self.send([new_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): Command for which to check availability.
Returns:
True if the command can be executed.
Raises:
LastEngineException: If is_last_engine is True but is_available is not implemented.
"""
if not self.is_last_engine:
return self.next_engine.is_available(cmd)
raise LastEngineException(self) |
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.
Returns:
True if the command can be executed.
Raises:
LastEngineException: If is_last_engine is True but is_available is not implemented.
| 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. If dirty=True, the fresh qubit can be replaced by a
pre-allocated one (in an unknown, dirty, initial state). Dirty qubits must be returned to their initial states
before they are deallocated / freed.
All allocated qubits are added to the MainEngine's set of active qubits as weak references. This allows proper
clean-up at the end of the Python program (using atexit), deallocating all qubits which are still alive. Qubit
ids of dirty qubits are registered in MainEngine's dirty_qubits set.
Args:
dirty (bool): If True, indicates that the allocated qubit may be
dirty (i.e., in an arbitrary initial state).
Returns:
Qureg of length 1, where the first entry is the allocated qubit.
"""
new_id = self.main_engine.get_new_qubit_id()
qb = Qureg([Qubit(self, new_id)])
cmd = Command(self, Allocate, (qb,))
if dirty:
from projectq.meta import ( # pylint: disable=import-outside-toplevel
DirtyQubitTag,
)
if self.is_meta_tag_supported(DirtyQubitTag):
cmd.tags += [DirtyQubitTag()]
self.main_engine.dirty_qubits.add(qb[0].id)
self.main_engine.active_qubits.add(qb[0])
self.send([cmd])
return qb |
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 a
pre-allocated one (in an unknown, dirty, initial state). Dirty qubits must be returned to their initial states
before they are deallocated / freed.
All allocated qubits are added to the MainEngine's set of active qubits as weak references. This allows proper
clean-up at the end of the Python program (using atexit), deallocating all qubits which are still alive. Qubit
ids of dirty qubits are registered in MainEngine's dirty_qubits set.
Args:
dirty (bool): If True, indicates that the allocated qubit may be
dirty (i.e., in an arbitrary initial state).
Returns:
Qureg of length 1, where the first entry is the allocated qubit.
| 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:
ValueError: Qubit already deallocated. Caller likely has a bug.
"""
if qubit.id == -1:
raise ValueError("Already deallocated.")
from projectq.meta import ( # pylint: disable=import-outside-toplevel
DirtyQubitTag,
)
is_dirty = qubit.id in self.main_engine.dirty_qubits
self.send(
[
Command(
self,
Deallocate,
([WeakQubitRef(engine=qubit.engine, idx=qubit.id)],),
tags=[DirtyQubitTag()] if is_dirty else [],
)
]
)
# Mark qubit as deallocated
qubit.id = -1 |
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. Caller likely has a bug.
| 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:
supported (bool): True if one of the further compiler engines is a meta tag handler, i.e.,
engine.is_meta_tag_handler(meta_tag) returns True.
"""
engine = self
while engine is not None:
try:
if engine.is_meta_tag_handler(meta_tag):
return True
except AttributeError:
pass
engine = engine.next_engine
return False |
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 a meta tag handler, i.e.,
engine.is_meta_tag_handler(meta_tag) returns True.
| 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 command it returns when getting called with cmd.
"""
super().__init__()
self.main_engine = engine.main_engine
self.next_engine = engine
if cmd_mod_fun is None:
def cmd_mod_fun(cmd):
return cmd
self._cmd_mod_fun = cmd_mod_fun |
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):
cmd.tags += [MyOwnTag()]
compiler_engine = CommandModifier(cmd_mod_fun)
...
"""
super().__init__()
self._cmd_mod_fun = 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):
cmd.tags += [MyOwnTag()]
compiler_engine = CommandModifier(cmd_mod_fun)
...
| __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:
# general connectivity easier for testing functions
self.connections = {
(0, 1),
(1, 0),
(1, 2),
(1, 3),
(1, 4),
(2, 1),
(2, 3),
(2, 4),
(3, 1),
(3, 4),
(4, 3),
}
else:
self.connections = connections |
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.
Returns:
Cost measure taking into account CNOT directionality or None if the circuit cannot be executed given the
mapping.
"""
cost = 0
for tpl, interaction in self._interactions.items():
ctrl_id = tpl[0]
target_id = tpl[1]
ctrl_pos = mapping[ctrl_id]
target_pos = mapping[target_id]
if not (ctrl_pos, target_pos) in self.connections:
if (target_pos, ctrl_pos) in self.connections:
cost += interaction
else:
return None
return cost |
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 account CNOT directionality or None if the circuit cannot be executed given the
mapping.
| _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 and max(self.current_mapping.values()) > 4:
raise RuntimeError(
"Too many qubits allocated. The IBM Q "
"device supports at most 5 qubits and no "
"intermediate measurements / "
"reallocations."
)
if len(self._interactions) > 0:
logical_ids = list(self.current_mapping)
best_mapping = self.current_mapping
best_cost = None
for physical_ids in itertools.permutations(list(range(5)), len(logical_ids)):
mapping = {logical_ids[i]: physical_ids[i] for i in range(len(logical_ids))}
new_cost = self._determine_cost(mapping)
if new_cost is not None:
if best_cost is None or new_cost < best_cost:
best_cost = new_cost
best_mapping = mapping
if best_cost is None:
raise RuntimeError("Circuit cannot be mapped without using Swaps. Mapping failed.")
self._interactions = {}
self.current_mapping = best_mapping
for cmd in self._cmds:
self._send_cmd_with_mapped_ids(cmd)
self._cmds = [] |
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_qubits[0].id
if not (ctrl, target) in self._interactions:
self._interactions[(ctrl, target)] = 0
self._interactions[(ctrl, target)] += 1
elif cmd.gate == Allocate:
if target not in self.current_mapping:
new_max = 0
if len(self.current_mapping) > 0:
new_max = max(self.current_mapping.values()) + 1
self._current_mapping[target] = new_max
self._cmds.append(cmd) |
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 mapping the CNOT gates to 1 qubit would require Swaps. The current version only supports
remapping of CNOT gates without performing any Swaps due to the large costs associated with Swapping
given the CNOT constraints.
"""
for cmd in command_list:
self._store(cmd)
if isinstance(cmd.gate, FlushGate):
self._run()
self._reset() |
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 require Swaps. The current version only supports
remapping of CNOT gates without performing any Swaps due to the large costs associated with Swapping
given the CNOT constraints.
| 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 swaps.
"""
depth_of_qubits = {}
for qb0_id, qb1_id in swaps:
if qb0_id not in depth_of_qubits:
depth_of_qubits[qb0_id] = 0
if qb1_id not in depth_of_qubits:
depth_of_qubits[qb1_id] = 0
max_depth = max(depth_of_qubits[qb0_id], depth_of_qubits[qb1_id])
depth_of_qubits[qb0_id] = max_depth + 1
depth_of_qubits[qb1_id] = max_depth + 1
return max(list(depth_of_qubits.values()) + [0]) |
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 gates to temporarily store, default is 1000
"""
super().__init__()
self.num_qubits = num_qubits
self.cyclic = cyclic
self.storage = storage
# Storing commands
self._stored_commands = []
# Logical qubit ids for which the Allocate gate has already been
# processed and sent to the next engine but which are not yet
# deallocated:
self._currently_allocated_ids = set()
# Statistics:
self.num_mappings = 0
self.depth_of_swaps = {}
self.num_of_swaps_per_mapping = {} |
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 scheme could try to optimize to apply as many gates as possible between the Swaps.
Args:
num_qubits(int): Total number of qubits in the linear chain
cyclic(bool): If linear chain is a cycle.
currently_allocated_ids(set of int): Logical qubit ids for which the Allocate gate has already been
processed and sent to the next engine but which are not yet
deallocated and hence need to be included in the new mapping.
stored_commands(list of Command objects): Future commands which should be applied next.
current_mapping: A current mapping as a dict. key is logical qubit id, value is placement id. If there are
different possible maps, this current mapping is used to minimize the swaps to go to the
new mapping by a heuristic.
Returns: A new mapping as a dict. key is logical qubit id,
value is placement id
"""
# allocated_qubits is used as this mapper currently does not reassign
# a qubit placement to a new qubit if the previous qubit at that
# location has been deallocated. This is done after the next swaps.
allocated_qubits = deepcopy(currently_allocated_ids)
active_qubits = deepcopy(currently_allocated_ids)
# Segments contains a list of segments. A segment is a list of
# neighbouring qubit ids
segments = []
# neighbour_ids only used to speedup the lookup process if qubits
# are already connected. key: qubit_id, value: set of neighbour ids
neighbour_ids = {}
for qubit_id in active_qubits:
neighbour_ids[qubit_id] = set()
for cmd in stored_commands:
if len(allocated_qubits) == num_qubits and len(active_qubits) == 0:
break
qubit_ids = []
for qureg in cmd.all_qubits:
for qubit in qureg:
qubit_ids.append(qubit.id)
if len(qubit_ids) > 2 or len(qubit_ids) == 0:
raise Exception(f"Invalid command (number of qubits): {str(cmd)}")
if isinstance(cmd.gate, AllocateQubitGate):
qubit_id = cmd.qubits[0][0].id
if len(allocated_qubits) < num_qubits:
allocated_qubits.add(qubit_id)
active_qubits.add(qubit_id)
neighbour_ids[qubit_id] = set()
elif isinstance(cmd.gate, DeallocateQubitGate):
qubit_id = cmd.qubits[0][0].id
if qubit_id in active_qubits:
active_qubits.remove(qubit_id)
# Do not remove from allocated_qubits as this would
# allow the mapper to add a new qubit to this location
# before the next swaps which is currently not supported
elif len(qubit_ids) == 1:
continue
# Process a two qubit gate:
else:
LinearMapper._process_two_qubit_gate(
num_qubits=num_qubits,
cyclic=cyclic,
qubit0=qubit_ids[0],
qubit1=qubit_ids[1],
active_qubits=active_qubits,
segments=segments,
neighbour_ids=neighbour_ids,
)
return LinearMapper._return_new_mapping_from_segments(
num_qubits=num_qubits,
segments=segments,
allocated_qubits=allocated_qubits,
current_mapping=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 scheme could try to optimize to apply as many gates as possible between the Swaps.
Args:
num_qubits(int): Total number of qubits in the linear chain
cyclic(bool): If linear chain is a cycle.
currently_allocated_ids(set of int): Logical qubit ids for which the Allocate gate has already been
processed and sent to the next engine but which are not yet
deallocated and hence need to be included in the new mapping.
stored_commands(list of Command objects): Future commands which should be applied next.
current_mapping: A current mapping as a dict. key is logical qubit id, value is placement id. If there are
different possible maps, this current mapping is used to minimize the swaps to go to the
new mapping by a heuristic.
Returns: A new mapping as a dict. key is logical qubit id,
value is placement id
| 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 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 cycle
qubit0 (int): qubit.id of one of the qubits
qubit1 (int): qubit.id of the other qubit
active_qubits (set): contains all qubit ids which for which gates can be applied in this cycle before the
swaps
segments: List of segments. A segment is a list of neighbouring qubits.
neighbour_ids (dict): Key: qubit.id Value: qubit.id of neighbours
"""
# already connected
if qubit1 in neighbour_ids and qubit0 in neighbour_ids[qubit1]:
return
# at least one qubit is not an active qubit:
if qubit0 not in active_qubits or qubit1 not in active_qubits:
active_qubits.discard(qubit0)
active_qubits.discard(qubit1)
# at least one qubit is in the inside of a segment:
elif len(neighbour_ids[qubit0]) > 1 or len(neighbour_ids[qubit1]) > 1:
active_qubits.discard(qubit0)
active_qubits.discard(qubit1)
# qubits are both active and either not yet in a segment or at
# the end of segment:
else:
segment_index_qb0 = None
qb0_is_left_end = None
segment_index_qb1 = None
qb1_is_left_end = None
for index, segment in enumerate(segments):
if qubit0 == segment[0]:
segment_index_qb0 = index
qb0_is_left_end = True
elif qubit0 == segment[-1]:
segment_index_qb0 = index
qb0_is_left_end = False
if qubit1 == segment[0]:
segment_index_qb1 = index
qb1_is_left_end = True
elif qubit1 == segment[-1]:
segment_index_qb1 = index
qb1_is_left_end = False
# Both qubits are not yet assigned to a segment:
if segment_index_qb0 is None and segment_index_qb1 is None:
segments.append([qubit0, qubit1])
neighbour_ids[qubit0].add(qubit1)
neighbour_ids[qubit1].add(qubit0)
# if qubits are in the same segment, then the gate is not
# possible. Note that if self.cyclic==True, we have
# added that connection already to neighbour_ids and wouldn't be
# in this branch.
elif segment_index_qb0 == segment_index_qb1:
active_qubits.remove(qubit0)
active_qubits.remove(qubit1)
# qubit0 not yet assigned to a segment:
elif segment_index_qb0 is None:
if qb1_is_left_end:
segments[segment_index_qb1].insert(0, qubit0)
else:
segments[segment_index_qb1].append(qubit0)
neighbour_ids[qubit0].add(qubit1)
neighbour_ids[qubit1].add(qubit0)
if cyclic and len(segments[0]) == num_qubits:
neighbour_ids[segments[0][0]].add(segments[0][-1])
neighbour_ids[segments[0][-1]].add(segments[0][0])
# qubit1 not yet assigned to a segment:
elif segment_index_qb1 is None:
if qb0_is_left_end:
segments[segment_index_qb0].insert(0, qubit1)
else:
segments[segment_index_qb0].append(qubit1)
neighbour_ids[qubit0].add(qubit1)
neighbour_ids[qubit1].add(qubit0)
if cyclic and len(segments[0]) == num_qubits:
neighbour_ids[segments[0][0]].add(segments[0][-1])
neighbour_ids[segments[0][-1]].add(segments[0][0])
# both qubits are at the end of different segments -> combine them
else:
if not qb0_is_left_end and qb1_is_left_end:
segments[segment_index_qb0].extend(segments[segment_index_qb1])
segments.pop(segment_index_qb1)
elif not qb0_is_left_end and not qb1_is_left_end:
segments[segment_index_qb0].extend(reversed(segments[segment_index_qb1]))
segments.pop(segment_index_qb1)
elif qb0_is_left_end and qb1_is_left_end:
segments[segment_index_qb0].reverse()
segments[segment_index_qb0].extend(segments[segment_index_qb1])
segments.pop(segment_index_qb1)
else:
segments[segment_index_qb1].extend(segments[segment_index_qb0])
segments.pop(segment_index_qb0)
# Add new neighbour ids and make sure to check cyclic
neighbour_ids[qubit0].add(qubit1)
neighbour_ids[qubit1].add(qubit0)
if cyclic and len(segments[0]) == num_qubits:
neighbour_ids[segments[0][0]].add(segments[0][-1])
neighbour_ids[segments[0][-1]].add(segments[0][0])
return |
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 cycle
qubit0 (int): qubit.id of one of the qubits
qubit1 (int): qubit.id of the other qubit
active_qubits (set): contains all qubit ids which for which gates can be applied in this cycle before the
swaps
segments: List of segments. A segment is a list of neighbouring qubits.
neighbour_ids (dict): Key: qubit.id Value: qubit.id of neighbours
| _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.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 is not a global optimal strategy but helps if currently the qubits can be divided into
independent groups without interactions between the groups.
Args:
num_qubits (int): Total number of qubits in the linear chain
segments: List of segments. A segment is a list of qubit ids which should be nearest neighbour in the new
map. Individual qubits are in allocated_qubits but not in any segment
allocated_qubits: A set of all qubit ids which need to be present in the new map
current_mapping: A current mapping as a dict. key is logical qubit id, value is placement id. If there are
different possible maps, this current mapping is used to minimize the swaps to go to the
new mapping by a heuristic.
Returns:
A new mapping as a dict. key is logical qubit id,
value is placement id
"""
remaining_segments = deepcopy(segments)
individual_qubits = deepcopy(allocated_qubits)
num_unused_qubits = num_qubits - len(allocated_qubits)
# Create a segment out of individual qubits and add to segments
for segment in segments:
for qubit_id in segment:
individual_qubits.remove(qubit_id)
for individual_qubit_id in individual_qubits:
remaining_segments.append([individual_qubit_id])
previous_chain = [None] * num_qubits
if current_mapping:
for key, value in current_mapping.items():
previous_chain[value] = key
# Note: previous_chain potentially has some None elements
new_chain = [None] * num_qubits
current_position_to_fill = 0
while len(remaining_segments):
best_segment = None
best_padding = num_qubits
highest_overlap_fraction = 0
for segment in remaining_segments:
for padding in range(num_unused_qubits + 1):
idx0 = current_position_to_fill + padding
idx1 = idx0 + len(segment)
previous_chain_ids = set(previous_chain[idx0:idx1])
previous_chain_ids.discard(None)
segment_ids = set(segment)
segment_ids.discard(None)
overlap = len(previous_chain_ids.intersection(segment_ids)) + previous_chain[idx0:idx1].count(None)
if overlap == 0:
overlap_fraction = 0
elif overlap == len(segment):
overlap_fraction = 1
else:
overlap_fraction = overlap / float(len(segment))
if (
(overlap_fraction == 1 and padding < best_padding)
or overlap_fraction > highest_overlap_fraction
or highest_overlap_fraction == 0
):
best_segment = segment
best_padding = padding
highest_overlap_fraction = overlap_fraction
# Add best segment and padding to new_chain
new_chain[
current_position_to_fill
+ best_padding : current_position_to_fill # noqa: E203
+ best_padding
+ len(best_segment)
] = best_segment
remaining_segments.remove(best_segment)
current_position_to_fill += best_padding + len(best_segment)
num_unused_qubits -= best_padding
# Create mapping
new_mapping = {}
for pos, logical_id in enumerate(new_chain):
if logical_id is not None:
new_mapping[logical_id] = pos
return new_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.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 is not a global optimal strategy but helps if currently the qubits can be divided into
independent groups without interactions between the groups.
Args:
num_qubits (int): Total number of qubits in the linear chain
segments: List of segments. A segment is a list of qubit ids which should be nearest neighbour in the new
map. Individual qubits are in allocated_qubits but not in any segment
allocated_qubits: A set of all qubit ids which need to be present in the new map
current_mapping: A current mapping as a dict. key is logical qubit id, value is placement id. If there are
different possible maps, this current mapping is used to minimize the swaps to go to the
new mapping by a heuristic.
Returns:
A new mapping as a dict. key is logical qubit id,
value is placement id
| _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 ids
new_mapping: dict: keys are logical ids and values are mapped qubit ids
Returns:
List of tuples. Each tuple is a swap operation which needs to be applied. Tuple contains the two
MappedQubit ids for the Swap.
"""
final_positions = [None] * self.num_qubits
# move qubits which are in both mappings
for logical_id in old_mapping:
if logical_id in new_mapping:
final_positions[old_mapping[logical_id]] = new_mapping[logical_id]
# exchange all remaining None with the not yet used mapped ids
used_mapped_ids = set(final_positions)
used_mapped_ids.discard(None)
all_ids = set(range(self.num_qubits))
not_used_mapped_ids = list(all_ids.difference(used_mapped_ids))
not_used_mapped_ids = sorted(not_used_mapped_ids, reverse=True)
for i, pos in enumerate(final_positions):
if pos is None:
final_positions[i] = not_used_mapped_ids.pop()
if len(not_used_mapped_ids) > 0: # pragma: no cover
raise RuntimeError('Internal compiler error: len(not_used_mapped_ids) > 0')
# Start sorting:
swap_operations = []
finished_sorting = False
while not finished_sorting:
finished_sorting = True
for i in range(1, len(final_positions) - 1, 2):
if final_positions[i] > final_positions[i + 1]:
swap_operations.append((i, i + 1))
tmp = final_positions[i]
final_positions[i] = final_positions[i + 1]
final_positions[i + 1] = tmp
finished_sorting = False
for i in range(0, len(final_positions) - 1, 2):
if final_positions[i] > final_positions[i + 1]:
swap_operations.append((i, i + 1))
tmp = final_positions[i]
final_positions[i] = final_positions[i + 1]
final_positions[i + 1] = tmp
finished_sorting = False
return swap_operations |
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 qubit ids
Returns:
List of tuples. Each tuple is a swap operation which needs to be applied. Tuple contains the two
MappedQubit ids for the Swap.
| _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.current_mapping:
active_ids.add(logical_id)
new_stored_commands = []
for i, cmd in enumerate(self._stored_commands):
if len(active_ids) == 0:
new_stored_commands += self._stored_commands[i:]
break
if isinstance(cmd.gate, AllocateQubitGate):
if cmd.qubits[0][0].id in self.current_mapping:
self._currently_allocated_ids.add(cmd.qubits[0][0].id)
qb = WeakQubitRef(engine=self, idx=self.current_mapping[cmd.qubits[0][0].id])
new_cmd = Command(
engine=self,
gate=AllocateQubitGate(),
qubits=([qb],),
tags=[LogicalQubitIDTag(cmd.qubits[0][0].id)],
)
self.send([new_cmd])
else:
new_stored_commands.append(cmd)
elif isinstance(cmd.gate, DeallocateQubitGate):
if cmd.qubits[0][0].id in active_ids:
qb = WeakQubitRef(engine=self, idx=self.current_mapping[cmd.qubits[0][0].id])
new_cmd = Command(
engine=self,
gate=DeallocateQubitGate(),
qubits=([qb],),
tags=[LogicalQubitIDTag(cmd.qubits[0][0].id)],
)
self._currently_allocated_ids.remove(cmd.qubits[0][0].id)
active_ids.remove(cmd.qubits[0][0].id)
self._current_mapping.pop(cmd.qubits[0][0].id)
self.send([new_cmd])
else:
new_stored_commands.append(cmd)
else:
send_gate = True
mapped_ids = set()
for qureg in cmd.all_qubits:
for qubit in qureg:
if qubit.id not in active_ids:
send_gate = False
break
mapped_ids.add(self.current_mapping[qubit.id])
# Check that mapped ids are nearest neighbour
if len(mapped_ids) == 2:
mapped_ids = list(mapped_ids)
diff = abs(mapped_ids[0] - mapped_ids[1])
if self.cyclic:
if diff not in (1, self.num_qubits - 1):
send_gate = False
else:
if diff != 1:
send_gate = False
if send_gate:
self._send_cmd_with_mapped_ids(cmd)
else:
for qureg in cmd.all_qubits:
for qubit in qureg:
active_ids.discard(qubit.id)
new_stored_commands.append(cmd)
self._stored_commands = new_stored_commands |
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 map, swaps all the qubits to the new map, executes
all possible gates, and finally deallocates mapped qubit ids which don't store any information.
"""
num_of_stored_commands_before = len(self._stored_commands)
if not self.current_mapping:
self.current_mapping = {}
else:
self._send_possible_commands()
if len(self._stored_commands) == 0:
return
new_mapping = self.return_new_mapping(
self.num_qubits,
self.cyclic,
self._currently_allocated_ids,
self._stored_commands,
self.current_mapping,
)
swaps = self._odd_even_transposition_sort_swaps(old_mapping=self.current_mapping, new_mapping=new_mapping)
if swaps: # first mapping requires no swaps
# Allocate all mapped qubit ids (which are not already allocated,
# i.e., contained in self._currently_allocated_ids)
mapped_ids_used = set()
for logical_id in self._currently_allocated_ids:
mapped_ids_used.add(self.current_mapping[logical_id])
not_allocated_ids = set(range(self.num_qubits)).difference(mapped_ids_used)
for mapped_id in not_allocated_ids:
qb = WeakQubitRef(engine=self, idx=mapped_id)
cmd = Command(engine=self, gate=Allocate, qubits=([qb],))
self.send([cmd])
# Send swap operations to arrive at new_mapping:
for qubit_id0, qubit_id1 in swaps:
qb0 = WeakQubitRef(engine=self, idx=qubit_id0)
qb1 = WeakQubitRef(engine=self, idx=qubit_id1)
cmd = Command(engine=self, gate=Swap, qubits=([qb0], [qb1]))
self.send([cmd])
# Register statistics:
self.num_mappings += 1
depth = return_swap_depth(swaps)
if depth not in self.depth_of_swaps:
self.depth_of_swaps[depth] = 1
else:
self.depth_of_swaps[depth] += 1
if len(swaps) not in self.num_of_swaps_per_mapping:
self.num_of_swaps_per_mapping[len(swaps)] = 1
else:
self.num_of_swaps_per_mapping[len(swaps)] += 1
# Deallocate all previously mapped ids which we only needed for the
# swaps:
mapped_ids_used = set()
for logical_id in self._currently_allocated_ids:
mapped_ids_used.add(new_mapping[logical_id])
not_needed_anymore = set(range(self.num_qubits)).difference(mapped_ids_used)
for mapped_id in not_needed_anymore:
qb = WeakQubitRef(engine=self, idx=mapped_id)
cmd = Command(engine=self, gate=Deallocate, qubits=([qb],))
self.send([cmd])
# Change to new map:
self.current_mapping = new_mapping
# Send possible gates:
self._send_possible_commands()
# Check that mapper actually made progress
if len(self._stored_commands) == num_of_stored_commands_before:
raise RuntimeError(
"Mapper is potentially in an infinite loop. It is likely that the algorithm requires too many"
"qubits. Increase the number of qubits for this mapper."
) |
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, and finally deallocates mapped qubit ids which don't store any information.
| _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.
"""
for cmd in command_list:
if isinstance(cmd.gate, FlushGate):
while self._stored_commands:
self._run()
self.send([cmd])
else:
self._stored_commands.append(cmd)
# Storage is full: Create new map and send some gates away:
if len(self._stored_commands) >= self.storage:
self._run() |
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-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)
"""
super().__init__()
self.active_qubits = weakref.WeakSet()
self._measurements = {}
self.dirty_qubits = set()
self.verbose = verbose
self.main_engine = self
self.n_engines_max = _N_ENGINES_THRESHOLD
if backend is None:
backend = Simulator()
else: # Test that backend is BasicEngine object
if not isinstance(backend, BasicEngine):
self.next_engine = _ErrorEngine()
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())"
)
self.backend = backend
# default engine_list is projectq.setups.default.get_engine_list()
if engine_list is None:
import projectq.setups.default # pylint: disable=import-outside-toplevel
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):
self.next_engine = _ErrorEngine()
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:
self.next_engine = _ErrorEngine()
raise UnsupportedEngineError("More than one mapper engine is not supported.")
else:
self.next_engine = _ErrorEngine()
raise UnsupportedEngineError("The provided list of engines is not a list!")
engine_list = engine_list + [backend]
# Test that user did not supply twice the same engine instance
num_different_engines = len({id(item) for item in engine_list})
if len(engine_list) != num_different_engines:
self.next_engine = _ErrorEngine()
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.n_engines = len(engine_list)
if self.n_engines > self.n_engines_max:
raise ValueError('Too many compiler engines added to the MainEngine!')
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]
# 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) |
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)
| __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(self._delfun) # only available in Python3
except AttributeError: # pragma: no cover
pass |
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:
.. code-block:: python
from projectq.ops import H, Measure
from projectq import MainEngine
eng = MainEngine()
qubit = eng.allocate_qubit() # quantum register of size 1
H | qubit
Measure | qubit
eng.get_measurement_result(qubit[0]) == int(qubit)
"""
if qubit.id in self._measurements:
return self._measurements[qubit.id]
raise NotYetMeasuredError(
"\nError: Can't access measurement result for qubit #" + str(qubit.id) + ". The problem may be:\n\t"
"1. Your code lacks a measurement statement\n\t"
"2. You have not yet called engine.flush() to force execution of your code\n\t"
"3. The "
"underlying backend failed to register the measurement result\n"
) |
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 projectq.ops import H, Measure
from projectq import MainEngine
eng = MainEngine()
qubit = eng.allocate_qubit() # quantum register of size 1
H | qubit
Measure | qubit
eng.get_measurement_result(qubit[0]) == int(qubit)
| 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=broad-except
if self.verbose:
raise
exc_type, exc_value, _ = sys.exc_info()
# try:
last_line = traceback.format_exc().splitlines()
compact_exception = exc_type(
str(exc_value) + '\n raised in:\n' + repr(last_line[-3]) + "\n" + repr(last_line[-2])
)
compact_exception.__cause__ = None
raise compact_exception from err # use verbose=True for more info |
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 setting their id to -1).
"""
if deallocate_qubits:
while [qb for qb in self.active_qubits if qb is not None]:
qb = self.active_qubits.pop() # noqa: F841
qb.__del__() # pylint: disable=unnecessary-dunder-call
self.receive([Command(self, FlushGate(), ([WeakQubitRef(self, -1)],))]) |
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
location (must be constant).
"""
super().__init__()
self.map = map_fun
self.current_mapping = {} |
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.id for qr in cmd.qubits for qb in qr]
ids += [qb.id for qb in cmd.control_qubits]
for qubit_id in ids:
if qubit_id not in self.current_mapping:
self._current_mapping[qubit_id] = self.map(qubit_id)
self._send_cmd_with_mapped_ids(cmd) |
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 lists containing operations for each qubit
if m:
warnings.warn(
'Pending breaking API change: LocalOptimizer(m=5) will be dropped in a future version in favor of '
'LinearMapper(cache_size=5)',
DeprecationWarning,
)
cache_size = m
self._cache_size = cache_size # wait for m gates before sending on |
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 |
def _send_qubit_pipeline(self, idx, n_gates):
"""Send n gate operations of the qubit with index idx to the next engine."""
il = self._l[idx] # pylint: disable=invalid-name
for i in range(min(n_gates, len(il))): # loop over first n operations
# send all gates before n-qubit gate for other qubits involved
# --> recursively call send_helper
other_involved_qubits = [qb for qreg in il[i].all_qubits for qb in qreg if qb.id != idx]
for qb in other_involved_qubits:
qubit_id = qb.id
try:
gateloc = 0
# find location of this gate within its list
while self._l[qubit_id][gateloc] != il[i]:
gateloc += 1
gateloc = self._optimize(qubit_id, gateloc)
# flush the gates before the n-qubit gate
self._send_qubit_pipeline(qubit_id, gateloc)
# delete the n-qubit gate, we're taking care of it
# and don't want the other qubit to do so
self._l[qubit_id] = self._l[qubit_id][1:]
except IndexError: # pragma: no cover
print("Invalid qubit pipeline encountered (in the process of shutting down?).")
# all qubits that need to be flushed have been flushed
# --> send on the n-qubit gate
self.send([il[i]])
# n operations have been sent on --> resize our gate list
self._l[idx] = self._l[idx][n_gates:] | Send n gate operations of the qubit with index idx to the next engine. | _send_qubit_pipeline | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_optimize.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_optimize.py | Apache-2.0 |
def _get_gate_indices(self, idx, i, qubit_ids):
"""
Return all indices of a command.
Each index corresponding to the command's index in one of the qubits' command lists.
Args:
idx (int): qubit index
i (int): command position in qubit idx's command list
IDs (list<int>): IDs of all qubits involved in the command
"""
N = len(qubit_ids)
# 1-qubit gate: only gate at index i in list #idx is involved
if N == 1:
return [i]
# When the same gate appears multiple time, we need to make sure not to
# match earlier instances of the gate applied to the same qubits. So we
# count how many there are, and skip over them when looking in the
# other lists.
cmd = self._l[idx][i]
num_identical_to_skip = sum(1 for prev_cmd in self._l[idx][:i] if prev_cmd == cmd)
indices = []
for qubit_id in qubit_ids:
identical_indices = [i for i, c in enumerate(self._l[qubit_id]) if c == cmd]
indices.append(identical_indices[num_identical_to_skip])
return indices |
Return all indices of a command.
Each index corresponding to the command's index in one of the qubits' command lists.
Args:
idx (int): qubit index
i (int): command position in qubit idx's command list
IDs (list<int>): IDs of all qubits involved in the command
| _get_gate_indices | python | ProjectQ-Framework/ProjectQ | projectq/cengines/_optimize.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/cengines/_optimize.py | Apache-2.0 |
def _optimize(self, idx, lim=None):
"""
Gate cancellation routine.
Try to remove identity gates using the is_identity function, then merge or even cancel successive gates using
the get_merged and get_inverse functions of the gate (see, e.g., BasicRotationGate).
It does so for all qubit command lists.
"""
# loop over all qubit indices
i = 0
limit = len(self._l[idx])
if lim is not None:
limit = lim
while i < limit - 1:
# can be dropped if the gate is equivalent to an identity gate
if self._l[idx][i].is_identity():
# determine index of this gate on all qubits
qubitids = [qb.id for sublist in self._l[idx][i].all_qubits for qb in sublist]
gid = self._get_gate_indices(idx, i, qubitids)
for j, qubit_id in enumerate(qubitids):
new_list = (
self._l[qubit_id][0 : gid[j]] + self._l[qubit_id][gid[j] + 1 :] # noqa: E203 # noqa: E203
)
self._l[qubitids[j]] = new_list # pylint: disable=undefined-loop-variable
i = 0
limit -= 1
continue
# can be dropped if two in a row are self-inverses
inv = self._l[idx][i].get_inverse()
if inv == self._l[idx][i + 1]:
# determine index of this gate on all qubits
qubitids = [qb.id for sublist in self._l[idx][i].all_qubits for qb in sublist]
gid = self._get_gate_indices(idx, i, qubitids)
# check that there are no other gates between this and its
# inverse on any of the other qubits involved
erase = True
for j, qubit_id in enumerate(qubitids):
erase *= inv == self._l[qubit_id][gid[j] + 1]
# drop these two gates if possible and goto next iteration
if erase:
for j, qubit_id in enumerate(qubitids):
new_list = (
self._l[qubit_id][0 : gid[j]] + self._l[qubit_id][gid[j] + 2 :] # noqa: E203 # noqa: E203
)
self._l[qubit_id] = new_list
i = 0
limit -= 2
continue
# gates are not each other's inverses --> check if they're
# mergeable
try:
merged_command = self._l[idx][i].get_merged(self._l[idx][i + 1])
# determine index of this gate on all qubits
qubitids = [qb.id for sublist in self._l[idx][i].all_qubits for qb in sublist]
gid = self._get_gate_indices(idx, i, qubitids)
merge = True
for j, qubit_id in enumerate(qubitids):
merged = self._l[qubit_id][gid[j]].get_merged(self._l[qubit_id][gid[j] + 1])
merge *= merged == merged_command
if merge:
for j, qubit_id in enumerate(qubitids):
self._l[qubit_id][gid[j]] = merged_command
new_list = (
self._l[qubit_id][0 : gid[j] + 1] # noqa: E203
+ self._l[qubit_id][gid[j] + 2 :] # noqa: E203
)
self._l[qubit_id] = new_list
i = 0
limit -= 1
continue
except NotMergeable:
pass # can't merge these two commands.
i += 1 # next iteration: look at next gate
return limit |
Gate cancellation routine.
Try to remove identity gates using the is_identity function, then merge or even cancel successive gates using
the get_merged and get_inverse functions of the gate (see, e.g., BasicRotationGate).
It does so for all qubit command lists.
| _optimize | 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.