Skip to content

Commit

Permalink
More lint documentation fixes. (#4641)
Browse files Browse the repository at this point in the history
Continuing the battle versus #3388
  • Loading branch information
dabacon authored Nov 9, 2021
1 parent 72f831d commit 1f0fc1d
Show file tree
Hide file tree
Showing 22 changed files with 257 additions and 310 deletions.
8 changes: 4 additions & 4 deletions cirq-core/cirq/contrib/acquaintance/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,6 @@ class GreedyExecutionStrategy(ExecutionStrategy):
qubits in any order are inserted.
"""

# TODO(#3388) Add documentation for Args.
# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-param-doc,missing-raises-doc
def __init__(
self, gates: LogicalGates, initial_mapping: LogicalMapping, device: 'cirq.Device' = None
) -> None:
Expand All @@ -142,6 +139,10 @@ def __init__(
Args:
gates: The gates to insert.
initial_mapping: The initial mapping of qubits to logical indices.
device: The device upon which to execute the strategy.
Raises:
NotImplementedError: If not all gates are of the same arity.
"""

if len(set(len(indices) for indices in gates)) > 1:
Expand All @@ -152,7 +153,6 @@ def __init__(
self._initial_mapping = initial_mapping.copy()
self._device = device or devices.UNCONSTRAINED_DEVICE

# pylint: enable=missing-param-doc,missing-raises-doc
@property
def initial_mapping(self) -> LogicalMapping:
return self._initial_mapping
Expand Down
20 changes: 8 additions & 12 deletions cirq-core/cirq/contrib/acquaintance/shift.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,18 @@
import cirq


# TODO(#3388) Add documentation for Args.
# pylint: disable=missing-param-doc
@value.value_equality
class CircularShiftGate(PermutationGate):
"""Performs a cyclical permutation of the qubits to the left by a specified
amount.
Args:
shift: how many positions to circularly left shift the qubits.
swap_gate: the gate to use when decomposing.
"""
"""Performs a cyclical permutation of the qubits to the left by a specified amount."""

def __init__(self, num_qubits: int, shift: int, swap_gate: 'cirq.Gate' = ops.SWAP) -> None:
"""Construct a circular shift gate.
Args:
num_qubits: The number of qubits to shift.
shift: The number of positions to circularly left shift the qubits.
swap_gate: The gate to use when decomposing.
"""
super(CircularShiftGate, self).__init__(num_qubits, swap_gate)
self.shift = shift

Expand Down Expand Up @@ -75,6 +74,3 @@ def permutation(self) -> Dict[int, int]:
shift = self.shift % self.num_qubits()
permuted_indices = itertools.chain(range(shift, self.num_qubits()), range(shift))
return {s: i for i, s in enumerate(permuted_indices)}


# pylint: enable=missing-param-doc
3 changes: 0 additions & 3 deletions cirq-core/cirq/contrib/acquaintance/strategies/complete.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,6 @@
import cirq


# TODO(#3388) Add summary line to docstring.
# TODO(#3388) Add documentation for Raises.
# pylint: disable=docstring-first-line-empty,missing-raises-doc
def complete_acquaintance_strategy(
qubit_order: Sequence['cirq.Qid'], acquaintance_size: int = 0, swap_gate: 'cirq.Gate' = ops.SWAP
) -> 'cirq.Circuit':
Expand Down
8 changes: 3 additions & 5 deletions cirq-core/cirq/contrib/qcircuit/qcircuit_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@
from cirq.contrib.qcircuit.qcircuit_diagram import circuit_to_latex_using_qcircuit


# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def circuit_to_pdf_using_qcircuit_via_tex(
circuit: circuits.Circuit,
filepath: str,
Expand All @@ -45,6 +43,9 @@ def circuit_to_pdf_using_qcircuit_via_tex(
default, latexmk is used with the '-pdfps' flag, which produces
intermediary dvi and ps files.
documentclass: The documentclass of the latex file.
Raises:
OSError, IOError: If cleanup fails.
"""
pdf_kwargs = {
'compiler': 'latexmk',
Expand All @@ -65,6 +66,3 @@ def circuit_to_pdf_using_qcircuit_via_tex(
except (OSError, IOError) as e:
if e.errno != errno.ENOENT:
raise


# pylint: enable=missing-raises-doc
23 changes: 11 additions & 12 deletions cirq-core/cirq/contrib/quimb/mps_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,6 @@ class MPSSimulator(
):
"""An efficient simulator for MPS circuits."""

# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def __init__(
self,
noise: 'cirq.NOISE_MODEL_LIKE' = None,
Expand All @@ -74,6 +72,9 @@ def __init__(
seed: The random seed to use for this simulator.
simulation_options: Numerical options for the simulation.
grouping: How to group qubits together, if None all are individual.
Raises:
ValueError: If the noise model is not unitary or a mixture.
"""
self.init = True
noise_model = devices.NoiseModel.from_noise_model_like(noise)
Expand All @@ -86,9 +87,6 @@ def __init__(
seed=seed,
)

# pylint: enable=missing-raises-doc
# TODO(#3388) Add documentation for Args.
# pylint: disable=missing-param-doc
def _create_partial_act_on_args(
self,
initial_state: Union[int, 'MPSState'],
Expand All @@ -103,6 +101,7 @@ def _create_partial_act_on_args(
qubits: Determines the canonical ordering of the qubits. This
is often used in specifying the initial state, i.e. the
ordering of the computational basis states.
logs: A mutable object that measurements are recorded into.
Returns:
MPSState args for simulating the Circuit.
Expand All @@ -119,7 +118,6 @@ def _create_partial_act_on_args(
log_of_measurement_results=logs,
)

# pylint: enable=missing-param-doc
def _create_step_result(
self,
sim_state: 'cirq.OperationTarget[MPSState]',
Expand Down Expand Up @@ -211,8 +209,6 @@ def _simulator_state(self):
class MPSState(ActOnArgs):
"""A state of the MPS simulation."""

# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def __init__(
self,
qubits: Sequence['cirq.Qid'],
Expand All @@ -234,6 +230,9 @@ def __init__(
initial_state: An integer representing the initial state.
log_of_measurement_results: A mutable object that measurements are
being recorded into.
Raises:
ValueError: If the grouping does not cover the qubits.
"""
super().__init__(prng, qubits, log_of_measurement_results)
qubit_map = self.qubit_map
Expand Down Expand Up @@ -272,7 +271,6 @@ def __init__(
self.simulation_options = simulation_options
self.estimated_gate_error_list: List[float] = []

# pylint: enable=missing-raises-doc
def i_str(self, i: int) -> str:
# Returns the index name for the i'th qid.
return self.format_i.format(i)
Expand Down Expand Up @@ -464,8 +462,6 @@ def estimation_stats(self):
"estimated_fidelity": estimated_fidelity,
}

# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def perform_measurement(
self, qubits: Sequence[ops.Qid], prng: np.random.RandomState, collapse_state_vector=True
) -> List[int]:
Expand All @@ -476,6 +472,10 @@ def perform_measurement(
prng: A random number generator, used to simulate measurements.
collapse_state_vector: A Boolean specifying whether we should mutate
the state after the measurement.
Raises:
ValueError: If the probabilities for the measurements differ too much from one for the
tolerance specified in simulation options.
"""
results: List[int] = []

Expand Down Expand Up @@ -515,7 +515,6 @@ def perform_measurement(

return results

# pylint: enable=missing-raises-doc
def _perform_measurement(self, qubits: Sequence['cirq.Qid']) -> List[int]:
"""Measures the axes specified by the simulator."""
return self.perform_measurement(qubits, self.prng)
Expand Down
14 changes: 7 additions & 7 deletions cirq-core/cirq/contrib/routing/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@
}


# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def route_circuit(
circuit: circuits.Circuit,
device_graph: nx.Graph,
Expand All @@ -41,11 +39,16 @@ def route_circuit(
Args:
circuit: The circuit to route.
device_graph: The device's graph, in which each vertex is a qubit and
each edge indicates the ability to do an operation on those qubits.
device_graph: The device's graph, in which each vertex is a qubit and each edge indicates
the ability to do an operation on those qubits.
algo_name: The name of a routing algorithm. Must be in ROUTERS.
router: The function that actually does the routing.
**kwargs: Arguments to pass to the routing algorithm.
Raises:
ValueError: If the circuit contains operations on more than two qubits, the number of
qubits in the circuit are more than those of the device, both `algo_name` and `router`
are specified, or no routing algorithm is specified.
"""

if any(protocols.num_qubits(op) > 2 for op in circuit.all_operations()):
Expand All @@ -61,6 +64,3 @@ def route_circuit(
elif router is None:
raise ValueError(f'No routing algorithm specified.')
return router(circuit, device_graph, **kwargs)


# pylint: enable=missing-raises-doc
8 changes: 2 additions & 6 deletions cirq-core/cirq/ion/ion_gates.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,17 +69,13 @@ def _from_json_dict_(cls, rads: float, **kwargs: Any) -> 'MSGate':
return cls(rads=rads)


# TODO(#3388) Add summary line to docstring.
# pylint: disable=docstring-first-line-empty
def ms(rads: float) -> MSGate:
"""
"""A helper to construct the `cirq.MSGate` for the given angle specified in radians.
Args:
rads: The rotation angle in radians.
Returns:
Mølmer–Sørensen gate rotating by the desired amount.
"""
return MSGate(rads=rads)


# pylint: enable=docstring-first-line-empty
13 changes: 9 additions & 4 deletions cirq-core/cirq/ops/matrix_gates.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,6 @@
class MatrixGate(raw_types.Gate):
"""A unitary qubit or qudit gate defined entirely by its matrix."""

# TODO(#3388) Add documentation for Args.
# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-param-doc,missing-raises-doc
def __init__(
self,
matrix: np.ndarray,
Expand All @@ -49,6 +46,15 @@ def __init__(
qid_shape: The shape of state tensor that the matrix applies to.
If not specified, this value is inferred by assuming that the
matrix is supposed to apply to qubits.
unitary_check_rtol: The relative tolerance for checking whether the supplied matrix
is unitary. See `cirq.is_unitary`.
unitary_check_atol: The absolute tolerance for checking whether the supplied matrix
is unitary. See `cirq.is_unitary`.
Raises:
ValueError: If the matrix is not a square numpy array, if the matrix does not match
the `qid_shape`, if `qid_shape` is not supplied and the matrix dimension is
not a power of 2, or if the matrix not unitary (to the supplied precisions).
"""
if len(matrix.shape) != 2 or matrix.shape[0] != matrix.shape[1]:
raise ValueError('`matrix` must be a square 2d numpy array.')
Expand Down Expand Up @@ -76,7 +82,6 @@ def __init__(
if not linalg.is_unitary(matrix, rtol=unitary_check_rtol, atol=unitary_check_atol):
raise ValueError(f'Not a unitary matrix: {self._matrix}')

# pylint: enable=missing-param-doc,missing-raises-doc
def _json_dict_(self) -> Dict[str, Any]:
return {
'cirq_type': self.__class__.__name__,
Expand Down
12 changes: 6 additions & 6 deletions cirq-core/cirq/ops/permutation_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,17 @@
class QubitPermutationGate(raw_types.Gate):
"""A qubit permutation gate specified by a permutation list."""

# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def __init__(self, permutation: Sequence[int]):
"""Inits QubitPermutationGate.
"""Create a `cirq.QubitPermutationGate`.
Args:
permutation: A shuffled sequence of integers from 0 to
len(permutation) - 1. The entry at offset `i` is the result
of permuting `i`.
Raises:
ValueError: If the supplied permutation is not valid (empty, repeated indices, indices
out of range).
"""
if not permutation:
raise ValueError(f"Invalid permutation (empty): {permutation}")
Expand All @@ -44,14 +46,12 @@ def __init__(self, permutation: Sequence[int]):
invalid_indices = [x for x in permutation if not 0 <= x < len(permutation)]
if len(invalid_indices) > 0:
raise ValueError(
f"All indices have to satisfy "
f"0 <= i < {len(permutation)}. "
f"All indices have to satisfy 0 <= i < {len(permutation)}.\n"
f"Invalid indices: {invalid_indices}"
)

self.permutation = tuple(permutation)

# pylint: enable=missing-raises-doc
def _value_equality_values_(self):
return self.permutation

Expand Down
14 changes: 7 additions & 7 deletions cirq-core/cirq/ops/qubit_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,6 @@ def __init__(
it is the x coordinate of the qubit).
"""

# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
@staticmethod
def explicit(
fixed_qubits: Iterable[raw_types.Qid], fallback: Optional['QubitOrder'] = None
Expand All @@ -67,6 +65,10 @@ def explicit(
Returns:
A Basis instance that forces the given qubits in the given order.
Raises:
ValueError: If a qubit appears twice in `fixed_qubits`, or there were is no fallback
specified but there are extra qubits.
"""
result = tuple(fixed_qubits)
if len(set(result)) < len(result):
Expand All @@ -82,7 +84,6 @@ def func(qubits):

return QubitOrder(func)

# pylint: enable=missing-raises-doc
@staticmethod
def sorted_by(key: Callable[[raw_types.Qid], Any]) -> 'QubitOrder':
"""A basis that orders qubits ascending based on a key function.
Expand All @@ -91,7 +92,6 @@ def sorted_by(key: Callable[[raw_types.Qid], Any]) -> 'QubitOrder':
key: A function that takes a qubit and returns a key value. The
basis will be ordered ascending according to these key values.
Returns:
A basis that orders qubits ascending based on a key function.
"""
Expand All @@ -111,8 +111,6 @@ def order_for(self, qubits: Iterable[raw_types.Qid]) -> Tuple[raw_types.Qid, ...
"""
return self._explicit_func(qubits)

# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
@staticmethod
def as_qubit_order(val: 'qubit_order_or_list.QubitOrderOrList') -> 'QubitOrder':
"""Converts a value into a basis.
Expand All @@ -122,14 +120,16 @@ def as_qubit_order(val: 'qubit_order_or_list.QubitOrderOrList') -> 'QubitOrder':
Returns:
The basis implied by the value.
Raises:
ValueError: If `val` is not an iterable or a `QubitOrder`.
"""
if isinstance(val, Iterable):
return QubitOrder.explicit(val)
if isinstance(val, QubitOrder):
return val
raise ValueError(f"Don't know how to interpret <{val}> as a Basis.")

# pylint: enable=missing-raises-doc
def map(
self,
internalize: Callable[[TExternalQubit], TInternalQubit],
Expand Down
Loading

0 comments on commit 1f0fc1d

Please sign in to comment.