/
mutation_utils.py
121 lines (98 loc) · 4.78 KB
/
mutation_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import collections
from typing import cast, Dict, List, Optional, Sequence, Union, TYPE_CHECKING
from cirq import circuits, ops, optimizers
from cirq.contrib.acquaintance.gates import SwapNetworkGate, AcquaintanceOpportunityGate
from cirq.contrib.acquaintance.devices import is_acquaintance_strategy, get_acquaintance_size
from cirq.contrib.acquaintance.permutation import PermutationGate
if TYPE_CHECKING:
import cirq
STRATEGY_GATE = Union[AcquaintanceOpportunityGate, PermutationGate]
def rectify_acquaintance_strategy(circuit: 'cirq.Circuit', acquaint_first: bool = True) -> None:
"""Splits moments so that they contain either only acquaintance gates
or only permutation gates. Orders resulting moments so that the first one
is of the same type as the previous one.
Args:
circuit: The acquaintance strategy to rectify.
acquaint_first: Whether to make acquaintance moment first in when
splitting the first mixed moment.
"""
if not is_acquaintance_strategy(circuit):
raise TypeError('not is_acquaintance_strategy(circuit)')
rectified_moments = []
for moment in circuit:
gate_type_to_ops: Dict[bool, List[ops.GateOperation]] = collections.defaultdict(list)
for op in moment.operations:
gate_op = cast(ops.GateOperation, op)
is_acquaintance = isinstance(gate_op.gate, AcquaintanceOpportunityGate)
gate_type_to_ops[is_acquaintance].append(gate_op)
if len(gate_type_to_ops) == 1:
rectified_moments.append(moment)
continue
for acquaint_first in sorted(gate_type_to_ops.keys(), reverse=acquaint_first):
rectified_moments.append(ops.Moment(gate_type_to_ops[acquaint_first]))
circuit._moments = rectified_moments
# TODO(#3388) Add summary line to docstring.
# pylint: disable=docstring-first-line-empty
def replace_acquaintance_with_swap_network(
circuit: 'cirq.Circuit',
qubit_order: Sequence['cirq.Qid'],
acquaintance_size: Optional[int] = 0,
swap_gate: 'cirq.Gate' = ops.SWAP,
) -> bool:
"""
Replace every moment containing acquaintance gates (after
rectification) with a generalized swap network, with the partition
given by the acquaintance gates in that moment (and singletons for the
free qubits). Accounts for reversing effect of swap networks.
Args:
circuit: The acquaintance strategy.
qubit_order: The qubits, in order, on which the replacing swap network
gate acts on.
acquaintance_size: The acquaintance size of the new swap network gate.
swap_gate: The gate used to swap logical indices.
Returns: Whether or not the overall effect of the inserted swap network
gates is to reverse the order of the qubits, i.e. the parity of the
number of swap network gates inserted.
Raises:
TypeError: circuit is not an acquaintance strategy.
"""
if not is_acquaintance_strategy(circuit):
raise TypeError('not is_acquaintance_strategy(circuit)')
rectify_acquaintance_strategy(circuit)
reflected = False
reverse_map = {q: r for q, r in zip(qubit_order, reversed(qubit_order))}
for moment_index, moment in enumerate(circuit):
if reflected:
moment = moment.transform_qubits(reverse_map.__getitem__)
if all(isinstance(op.gate, AcquaintanceOpportunityGate) for op in moment.operations):
swap_network_gate = SwapNetworkGate.from_operations(
qubit_order, moment.operations, acquaintance_size, swap_gate
)
swap_network_op = swap_network_gate(*qubit_order)
moment = ops.Moment([swap_network_op])
reflected = not reflected
circuit._moments[moment_index] = moment
return reflected
# pylint: enable=docstring-first-line-empty
class ExposeAcquaintanceGates(optimizers.ExpandComposite):
"""Decomposes any permutation gates that provide acquaintance opportunities
in order to make them explicit."""
def __init__(self):
circuits.PointOptimizer.__init__(self)
self.no_decomp = lambda op: (
not get_acquaintance_size(op) or isinstance(op.gate, AcquaintanceOpportunityGate)
)
expose_acquaintance_gates = ExposeAcquaintanceGates()