Skip to content
Merged
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
1 change: 0 additions & 1 deletion cirq-core/cirq/contrib/acquaintance/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
from cirq.contrib.acquaintance.executor import (
AcquaintanceOperation,
GreedyExecutionStrategy,
StrategyExecutor,
StrategyExecutorTransformer,
)

Expand Down
47 changes: 4 additions & 43 deletions cirq-core/cirq/contrib/acquaintance/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import abc
from collections import defaultdict

from cirq import circuits, devices, ops, protocols, transformers, _compat
from cirq import circuits, devices, ops, protocols, transformers

from cirq.contrib.acquaintance.gates import AcquaintanceOpportunityGate
from cirq.contrib.acquaintance.permutation import (
Expand All @@ -34,10 +34,10 @@


class ExecutionStrategy(metaclass=abc.ABCMeta):
"""Tells StrategyExecutor how to execute an acquaintance strategy.
"""Tells `StrategyExecutorTransormer` how to execute an acquaintance strategy.

An execution strategy tells StrategyExecutor how to execute an
acquaintance strategy, i.e. what gates to implement at the available
An execution strategy tells `StrategyExecutorTransformer` how to execute
an acquaintance strategy, i.e. what gates to implement at the available
acquaintance opportunities."""

keep_acquaintance = False
Expand Down Expand Up @@ -78,45 +78,6 @@ def __call__(self, *args, **kwargs):
return strategy.mapping


@_compat.deprecated_class(
deadline='v1.0', fix='Use cirq.contrib.acquaintance.StrategyExecutorTransformer'
)
class StrategyExecutor(circuits.PointOptimizer):
"""Executes an acquaintance strategy."""

def __init__(self, execution_strategy: ExecutionStrategy) -> None:
super().__init__()
self.execution_strategy = execution_strategy
self.mapping = execution_strategy.initial_mapping.copy()

def __call__(self, strategy: 'cirq.Circuit'):
expose_acquaintance_gates(strategy)
super().optimize_circuit(strategy)
return self.mapping.copy()

def optimization_at(
self, circuit: 'cirq.Circuit', index: int, op: 'cirq.Operation'
) -> Optional['cirq.PointOptimizationSummary']:
if isinstance(op.gate, AcquaintanceOpportunityGate):
logical_indices = tuple(self.mapping[q] for q in op.qubits)
logical_operations = self.execution_strategy.get_operations(logical_indices, op.qubits)
clear_span = int(not self.execution_strategy.keep_acquaintance)

return circuits.PointOptimizationSummary(
clear_span=clear_span, clear_qubits=op.qubits, new_operations=logical_operations
)

if isinstance(op, ops.GateOperation) and isinstance(op.gate, PermutationGate):
op.gate.update_mapping(self.mapping, op.qubits)
return None

raise TypeError(
'Can only execute a strategy consisting of gates that '
'are instances of AcquaintanceOpportunityGate or '
'PermutationGate.'
)


@transformers.transformer
class StrategyExecutorTransformer:
"""Executes an acquaintance strategy."""
Expand Down
27 changes: 5 additions & 22 deletions cirq-core/cirq/contrib/acquaintance/executor_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,7 @@ def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs):
return self._wire_symbols


@pytest.mark.parametrize(
'StrategyType, is_deprecated',
[[cca.StrategyExecutor, True], [cca.StrategyExecutorTransformer, False]],
)
def test_executor_explicit(StrategyType, is_deprecated):
def test_executor_explicit():
num_qubits = 8
qubits = cirq.LineQubit.range(num_qubits)
circuit = cca.complete_acquaintance_strategy(qubits, 2)
Expand All @@ -53,19 +49,9 @@ def test_executor_explicit(StrategyType, is_deprecated):
initial_mapping = {q: i for i, q in enumerate(sorted(qubits))}
execution_strategy = cca.GreedyExecutionStrategy(gates, initial_mapping)

if is_deprecated:
with cirq.testing.assert_deprecated(
"Use cirq.contrib.acquaintance.StrategyExecutorTransformer", deadline='v1.0'
):
executor = StrategyType(execution_strategy)
with pytest.raises(TypeError):
op = cirq.X(qubits[0])
bad_strategy = cirq.Circuit(op)
executor.optimization_at(bad_strategy, 0, op)
else:
with pytest.raises(ValueError):
executor = StrategyType(None)
executor = StrategyType(execution_strategy)
with pytest.raises(ValueError):
executor = cca.StrategyExecutorTransformer(None)
executor = cca.StrategyExecutorTransformer(execution_strategy)

with pytest.raises(NotImplementedError):
bad_gates = {(0,): ExampleGate(['0']), (0, 1): ExampleGate(['0', '1'])}
Expand All @@ -75,10 +61,7 @@ def test_executor_explicit(StrategyType, is_deprecated):
bad_strategy = cirq.Circuit(cirq.X(qubits[0]))
executor(bad_strategy)

if is_deprecated:
executor(circuit)
else:
circuit = executor(circuit)
circuit = executor(circuit)
expected_text_diagram = """
0: ───0───1───╲0╱─────────────────1───3───╲0╱─────────────────3───5───╲0╱─────────────────5───7───╲0╱─────────────────
│ │ │ │ │ │ │ │ │ │ │ │
Expand Down
16 changes: 6 additions & 10 deletions cirq-core/cirq/contrib/paulistring/recombine_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
# 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 pytest

import cirq
from cirq.contrib.paulistring import (
Expand All @@ -28,7 +27,6 @@ def _assert_no_multi_qubit_pauli_strings(circuit: cirq.Circuit) -> None:


def test_move_non_clifford_into_clifford():
cg = pytest.importorskip("cirq_google")
q0, q1, q2 = cirq.LineQubit.range(3)
c_orig = cirq.testing.nonoptimal_toffoli_circuit(q0, q1, q2)

Expand All @@ -43,11 +41,9 @@ def test_move_non_clifford_into_clifford():
_assert_no_multi_qubit_pauli_strings(c_recombined1)
_assert_no_multi_qubit_pauli_strings(c_recombined2)

with cirq.testing.assert_deprecated(
'Use cirq.optimize_for_target_gateset', deadline='v0.16', count=None
):
baseline_len = len(cg.optimized_for_xmon(c_orig))
opt_len1 = len(cg.optimized_for_xmon(c_recombined1))
opt_len2 = len(cg.optimized_for_xmon(c_recombined2))
assert opt_len1 <= baseline_len
assert opt_len2 <= baseline_len
gateset = cirq.CZTargetGateset()
baseline_len = len(cirq.optimize_for_target_gateset(c_orig, gateset=gateset))
opt_len1 = len(cirq.optimize_for_target_gateset(c_recombined1, gateset=gateset))
opt_len2 = len(cirq.optimize_for_target_gateset(c_recombined2, gateset=gateset))
assert opt_len1 <= baseline_len
assert opt_len2 <= baseline_len
6 changes: 1 addition & 5 deletions cirq-core/cirq/contrib/quimb/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,7 @@
circuit_to_density_matrix_tensors,
)

from cirq.contrib.quimb.grid_circuits import (
simplify_expectation_value_circuit,
MergeNQubitGates,
get_grid_moments,
)
from cirq.contrib.quimb.grid_circuits import simplify_expectation_value_circuit, get_grid_moments

from cirq.contrib.quimb.mps_simulator import (
MPSOptions,
Expand Down
48 changes: 15 additions & 33 deletions cirq-core/cirq/contrib/quimb/grid_circuits.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
# pylint: disable=wrong-or-nonexistent-copyright-notice
from typing import Optional, Iterator
# Copyright 2022 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.

from typing import Iterator
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

odd that you have to add this!

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, not sure why it was missing before, but I figured we should add it while I was here.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the copyright or the import? The import was indeed there


import networkx as nx

Expand Down Expand Up @@ -89,37 +102,6 @@ def _interaction(
)


@cirq._compat.deprecated_class(deadline='v0.16', fix="Use cirq.merge_k_qubit_unitaries")
class MergeNQubitGates(cirq.PointOptimizer):
"""Optimizes runs of adjacent unitary n-qubit operations."""

def __init__(self, *, n_qubits: int):
super().__init__()
self.n_qubits = n_qubits

def optimization_at(
self, circuit: cirq.Circuit, index: int, op: cirq.Operation
) -> Optional[cirq.PointOptimizationSummary]:
if len(op.qubits) != self.n_qubits:
return None

frontier = {q: index for q in op.qubits}
op_list = circuit.findall_operations_until_blocked(
frontier, is_blocker=lambda next_op: next_op.qubits != op.qubits
)
if len(op_list) <= 1:
return None
operations = [op for idx, op in op_list]
indices = [idx for idx, op in op_list]
matrix = cirq.linalg.dot(*(cirq.unitary(op) for op in operations[::-1]))

return cirq.PointOptimizationSummary(
clear_span=max(indices) + 1 - index,
clear_qubits=op.qubits,
new_operations=[cirq.MatrixGate(matrix).on(*op.qubits)],
)


def simplify_expectation_value_circuit(circuit_sand: cirq.Circuit):
"""For low weight operators on low-degree circuits, we can simplify
the circuit representation of an expectation value.
Expand Down
9 changes: 5 additions & 4 deletions cirq-core/cirq/contrib/quimb/mps_simulator_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,15 +469,16 @@ def test_state_copy():


def test_simulation_state_initializer():
expected_classical_data = cirq.ClassicalDataDictionaryStore(
_records={cirq.MeasurementKey('test'): [(4,)]}
)
s = ccq.mps_simulator.MPSState(
qubits=(cirq.LineQubit(0),),
prng=np.random.RandomState(0),
classical_data=cirq.ClassicalDataDictionaryStore(
_records={cirq.MeasurementKey('test'): [(4,)]}
),
classical_data=expected_classical_data,
)
assert s.qubits == (cirq.LineQubit(0),)
assert s.log_of_measurement_results == {'test': [4]}
assert s.classical_data == expected_classical_data


def test_act_on_gate():
Expand Down