Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pcvl 788 use post selected cnot as much as possible in converters #474

Draft
wants to merge 3 commits into
base: release/0.12.0
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 21 additions & 15 deletions perceval/converters/abstract_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from abc import ABC, abstractmethod

from perceval.components import Port, Circuit, Processor, Source, catalog
from perceval.utils import P, BasicState, Encoding, global_params
from perceval.utils import P, BasicState, Encoding, global_params, PostSelect, NoiseModel
from perceval.utils.algorithms.optimize import optimize
from perceval.utils.algorithms.norm import frobenius
import perceval.components.unitary_components as comp
Expand All @@ -52,8 +52,7 @@ class AGateConverter(ABC):
def __init__(self, backend_name: str = "SLOS", source: Source = Source()):
self._converted_processor = None
self._input_list = None # input state in list
self._cnot_idx = 0 # counter for CNOTS in circuit
self._source = source
self._noise_model = NoiseModel()
self._backend_name = backend_name

# Define function handler to create complex components
Expand Down Expand Up @@ -82,7 +81,7 @@ def _configure_processor(self, gate_circuit, **kwargs):

n_moi = n_qbits * 2 # In dual rail, number of modes of interest = 2 * number of qbits
self._input_list = [0] * n_moi
self._converted_processor = Processor(self._backend_name, n_moi, self._source)
self._converted_processor = Processor(self._backend_name, n_moi, noise=self._noise_model)
for i in range(n_qbits):
self._converted_processor.add_port(i * 2, Port(Encoding.DUAL_RAIL, qubit_names[i]))
self._input_list[i * 2] = 1
Expand Down Expand Up @@ -116,29 +115,34 @@ def _create_generic_1_qubit_gate(self, u) -> Circuit:
optimize(ins, u, frobenius, sign=-1)
return ins

def _create_2_qubit_gates_from_catalog(
self,
gate_name: str,
n_cnot,
c_idx,
c_data,
use_postselection,
parameter=None):
def _create_2_qubit_gates_from_catalog(self, gate_name: str, c_idx: int, c_data: int, use_postselection: bool):
r"""
List of Gates implemented:
CNOT - Heralded and post-processed
CZ - Heralded
CRz - Heralded and post-processed (uses two CNOTs)
SWAP
"""
# Save and clear current post-selection data from the converted processor before adding the next gate
if self._converted_processor._postselect is not None:
post_select_curr = self._converted_processor._postselect
else:
post_select_curr = PostSelect() # save empty if I need to merge incoming PostSelect to it
self._converted_processor.clear_postselection() # clear current post-selection

gate_name = gate_name.upper()
if gate_name in ["CNOT", "CX"]:
self._cnot_idx += 1
if use_postselection and self._cnot_idx == n_cnot:
if gate_name in ["CX:RALPH", "CX:KNILL"]:
if use_postselection and gate_name == "CX:RALPH":
cnot_processor = self.create_ppcnot_processor()
cnot_ps = cnot_processor._postselect

cnot_processor.clear_postselection() # clear after saving post select information
post_select_curr.merge(cnot_ps) # merge the incoming gate post-selection with the current
else:
cnot_processor = self.create_hcnot_processor()

self._converted_processor.add(_create_mode_map(c_idx, c_data), cnot_processor)

elif gate_name in ["CSIGN", "CZ"]:
# Controlled Z in myqlm is named CSIGN
cz_processor = self.create_hcz_processor()
Expand All @@ -157,4 +161,6 @@ def _create_2_qubit_gates_from_catalog(
else:
raise UnknownGateError(f"Gate not yet supported: {gate_name}")

# re-apply the cleared post-selection
self._converted_processor.set_postselection(post_select_curr)
return self._converted_processor
33 changes: 19 additions & 14 deletions perceval/converters/cqasm_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from perceval.components import Processor, Source, Circuit, BS, PS, PERM
from perceval.utils.converters import _label_cnots_in_gate_sequence
from perceval.utils.logging import get_logger, channel
from .abstract_converter import AGateConverter

Expand Down Expand Up @@ -66,7 +67,6 @@
"CNOT", "CZ"
}


def _cs(s: str) -> str:
r"""A shortcut to clean up the strings generated by the qASM parser"""
return s[2:-1]
Expand Down Expand Up @@ -96,7 +96,6 @@ def __init__(self, backend_name: str = "SLOS", source: Source = Source()):
import cqasm.v3x as cqasm

self._qubit_list = []
self._num_cnots = 0
self._use_postselection = False
self._cqasm = cqasm

Expand Down Expand Up @@ -124,7 +123,7 @@ def _operand_to_qubit_indices(self, operand):
else:
raise ConversionUnsupportedFeatureError(f"Cannot map variable { name } to a declared qubit")

def _convert_statement(self, statement):
def _get_gate_inf(self, statement):
gate_name = statement.name
num_operands = len(statement.operands)

Expand Down Expand Up @@ -155,6 +154,11 @@ def _convert_statement(self, statement):
raise ConversionUnsupportedFeatureError(
f"Gate { gate_name } has more than one control (n = { num_controls })")

return gate_name, controls, targets, parameter

def _convert_statement(self, statement, gate_index, optimized_gate_sequence):
gate_name, controls, targets, parameter = self._get_gate_inf(statement)

if not controls:
circuit_template = _CQASM_1_QUBIT_GATES.get(gate_name, None)
if not circuit_template:
Expand All @@ -170,13 +174,8 @@ def _convert_statement(self, statement):
raise ConversionUnsupportedFeatureError(
f"Unsupported 2-qubit gate { gate_name }")
for target in targets:
self._create_2_qubit_gates_from_catalog(
gate_name,
self._num_cnots,
controls[0] * 2,
target * 2,
self._use_postselection,
parameter=parameter)
self._create_2_qubit_gates_from_catalog(optimized_gate_sequence[gate_index], controls[0] * 2,
target * 2, self._use_postselection)

def convert(self, ast, use_postselection: bool = True) -> Processor:
r"""Convert a cQASM quantum program into a `Processor`.
Expand All @@ -193,16 +192,22 @@ def convert(self, ast, use_postselection: bool = True) -> Processor:
get_logger().info(f"Convert cqasm.ast ({len(self._qubit_list)} qubits, {len(ast.block.statements)} operations) to processor",
channel.general)
self._collect_qubit_list(ast)
self._num_cnots = sum(
(s.name == "CNOT") + 2 * (s.name in ["CR", "CRk"])
for s in ast.block.statements)
self._use_postselection = use_postselection

qubit_names = [
f'{ q }[{ i }]' if i >= 0 else q for (q, i) in self._qubit_list]
self._configure_processor(ast, qubit_names=qubit_names)

# for gate sequence to optimize cnots
gate_sequence = []
for statement in ast.block.statements:
self._convert_statement(statement)
gate_name, controls, targets, parameter = self._get_gate_inf(statement)
gate_sequence.append([gate_name, controls + targets])

optimized_gate_sequence = _label_cnots_in_gate_sequence(gate_sequence)

for gate_index, statement in enumerate(ast.block.statements):
self._convert_statement(statement, gate_index, optimized_gate_sequence)
self.apply_input_state()
return self._converted_processor

Expand Down
22 changes: 15 additions & 7 deletions perceval/converters/myqlm_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,19 @@

from perceval.components import Circuit, Processor, Source, BS, PS
from perceval.utils.logging import get_logger, channel
from perceval.utils.converters import _label_cnots_in_gate_sequence
from .abstract_converter import AGateConverter


def _get_gate_sequence(myqlm_circ) -> list:
# returns a nested list of gate names with corresponding qubit positions from a myqlm circuit
gate_info = []
for gate_instruction in myqlm_circ.iterate_simple():
gate_info.append([gate_instruction[0], gate_instruction[2]])

return gate_info


class MyQLMConverter(AGateConverter):
r"""myQLM quantum circuit to perceval circuit converter.

Expand Down Expand Up @@ -60,7 +70,10 @@ def convert(self, qlmc, use_postselection: bool = True) -> Processor:
# this nested import fixes automatic class reference generation

get_logger().info(f"Convert myQLM circuit ({qlmc.nbqbits} qubits) to processor", channel.general)
n_cnot = qlmc.count("CNOT") # count the number of CNOT gates in circuit - needed to find the num. heralds

gate_sequence = _get_gate_sequence(qlmc)
optimized_gate_sequence = _label_cnots_in_gate_sequence(gate_sequence)

self._configure_processor(qlmc) # empty processor with ports initialized

for i, instruction in enumerate(qlmc.iterate_simple()):
Expand Down Expand Up @@ -94,12 +107,7 @@ def convert(self, qlmc, use_postselection: bool = True) -> Processor:
raise ValueError(f"Gates with number of Qbits higher than 2 not implemented")
c_idx = instruction_qbit[0] * 2
c_data = instruction_qbit[1] * 2
self._create_2_qubit_gates_from_catalog(
instruction_name,
n_cnot,
c_idx,
c_data,
use_postselection)
self._create_2_qubit_gates_from_catalog(optimized_gate_sequence[i], c_idx, c_data, use_postselection)

self.apply_input_state()
return self._converted_processor
28 changes: 17 additions & 11 deletions perceval/converters/qiskit_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,19 @@

from perceval.components import Processor, Source
from perceval.utils.logging import get_logger, channel
from perceval.utils.converters import _label_cnots_in_gate_sequence
from .abstract_converter import AGateConverter
from .circuit_to_graph_converter import gates_and_qubits

def _get_gate_sequence(qisk_circ) -> list:
# returns a nested list of gate names with corresponding qubit positions
gate_names, qubit_pos = gates_and_qubits(qisk_circ) # from qiskit circuit

gate_info = []
for index, elem in enumerate(gate_names):
gate_info.append([gate_names[index], qubit_pos[index]])

return gate_info


class QiskitConverter(AGateConverter):
Expand Down Expand Up @@ -58,15 +70,13 @@ def convert(self, qc, use_postselection: bool = True) -> Processor:
get_logger().info(f"Convert qiskit.QuantumCircuit ({qc.num_qubits} qubits, {len(qc.data)} operations) to processor",
channel.general)

n_cnot = 0 # count the number of CNOT gates in circuit - needed to find the num. heralds
for instruction in qc.data:
if instruction[0].name == "cx":
n_cnot += 1
gate_sequence = _get_gate_sequence(qc)
optimized_gate_sequence = _label_cnots_in_gate_sequence(gate_sequence)

qubit_names = qc.qregs[0].name
self._configure_processor(qc, qname=qubit_names) # empty processor with ports initialized

for instruction in qc.data:
for gate_index, instruction in enumerate(qc.data):
# barrier has no effect
if isinstance(instruction[0], qiskit.circuit.barrier.Barrier):
continue
Expand All @@ -84,11 +94,7 @@ def convert(self, qc, use_postselection: bool = True) -> Processor:
raise NotImplementedError("2+ Qubit gates not implemented")
c_idx = qc.find_bit(instruction[1][0])[0] * 2
c_data = qc.find_bit(instruction[1][1])[0] * 2
self._create_2_qubit_gates_from_catalog(
instruction[0].name,
n_cnot,
c_idx,
c_data,
use_postselection)
self._create_2_qubit_gates_from_catalog(optimized_gate_sequence[gate_index], c_idx, c_data,
use_postselection)
self.apply_input_state()
return self._converted_processor
Loading