From 3c0ca4b6b2734009589ff2b94778622f6b7391da Mon Sep 17 00:00:00 2001 From: Dave Bacon Date: Thu, 11 Nov 2021 08:01:37 +0000 Subject: [PATCH] More documentation fixes (#4654) What do you do every night? Fix more documentation lint errors pinky. --- cirq-aqt/cirq_aqt/aqt_sampler.py | 16 +++++++------ .../cirq/contrib/acquaintance/permutation.py | 10 +++----- .../cirq/contrib/paulistring/separate.py | 10 ++++---- cirq-core/cirq/interop/quirk/cells/testing.py | 8 ++----- cirq-core/cirq/ion/convert_to_ion_gates.py | 10 ++++---- cirq-core/cirq/ops/moment.py | 18 +++++++------- cirq-core/cirq/sim/sparse_simulator_test.py | 6 ++--- .../cirq/testing/equivalent_repr_eval.py | 12 ++++------ .../optimizers/convert_to_sqrt_iswap.py | 24 +++++++++---------- .../serialization/op_deserializer.py | 14 +++++------ cirq-pasqal/cirq_pasqal/pasqal_noise_model.py | 9 ++++--- cirq-web/cirq_web/circuits/circuit.py | 7 +++--- 12 files changed, 64 insertions(+), 80 deletions(-) diff --git a/cirq-aqt/cirq_aqt/aqt_sampler.py b/cirq-aqt/cirq_aqt/aqt_sampler.py index 8fbd8ebc94b..c05ccb7fad8 100644 --- a/cirq-aqt/cirq_aqt/aqt_sampler.py +++ b/cirq-aqt/cirq_aqt/aqt_sampler.py @@ -50,8 +50,6 @@ def __init__(self, remote_host: str, access_token: str): self.remote_host = remote_host self.access_token = access_token - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def _generate_json( self, circuit: cirq.AbstractCircuit, @@ -71,11 +69,14 @@ def _generate_json( qubits: list of qubits where the operation acts on. Args: - circuit: Circuit to be run - param_resolver: Param resolver for the + circuit: Circuit to be run. + param_resolver: Param resolver for resolving parameters in circuit. Returns: - json formatted string of the sequence + json formatted string of the sequence. + + Raises: + RuntimeError: If the circuit is empty. """ seq_list: List[ @@ -101,7 +102,6 @@ def _generate_json( json_str = json.dumps(seq_list) return json_str - # TODO(#3388) Add documentation for Raises. def _send_json( self, *, @@ -128,6 +128,9 @@ def _send_json( Returns: Measurement results as an array of boolean. + + Raises: + RuntimeError: If there was an unexpected response from the server. """ header = {"Ocp-Apim-Subscription-Key": self.access_token, "SDK": "cirq"} response = put( @@ -174,7 +177,6 @@ def _send_json( measurements[i, j] = int(measurement_int_bin[j]) return measurements - # pylint: enable=missing-raises-doc def run_sweep( self, program: cirq.AbstractCircuit, params: cirq.Sweepable, repetitions: int = 1 ) -> List[cirq.Result]: diff --git a/cirq-core/cirq/contrib/acquaintance/permutation.py b/cirq-core/cirq/contrib/acquaintance/permutation.py index eaf6a5b2871..fc95761d8d1 100644 --- a/cirq-core/cirq/contrib/acquaintance/permutation.py +++ b/cirq-core/cirq/contrib/acquaintance/permutation.py @@ -40,14 +40,13 @@ LogicalMapping = Dict[LogicalMappingKey, LogicalIndex] -# TODO(#3388) Add documentation for Args. -# pylint: disable=missing-param-doc class PermutationGate(ops.Gate, metaclass=abc.ABCMeta): """A permutation gate indicates a change in the mapping from qubits to logical indices. Args: - swap_gate: the gate that swaps the indices mapped to by a pair of + num_qubits: The number of qubits the gate should act on. + swap_gate: The gate that swaps the indices mapped to by a pair of qubits (e.g. SWAP or fermionic swap). """ @@ -108,7 +107,6 @@ def _circuit_diagram_info_( return wire_symbols -# pylint: enable=missing-param-doc class MappingDisplayGate(ops.Gate): """Displays the indices mapped to a set of wires.""" @@ -188,14 +186,13 @@ class LinearPermutationGate(PermutationGate): """A permutation gate that decomposes a given permutation using a linear sorting network.""" - # TODO(#3388) Add documentation for Args. - # pylint: disable=missing-param-doc def __init__( self, num_qubits: int, permutation: Dict[int, int], swap_gate: 'cirq.Gate' = ops.SWAP ) -> None: """Initializes a linear permutation gate. Args: + num_qubits: The number of qubits to permute. permutation: The permutation effected by the gate. swap_gate: The swap gate used in decompositions. """ @@ -203,7 +200,6 @@ def __init__( PermutationGate.validate_permutation(permutation, num_qubits) self._permutation = permutation - # pylint: enable=missing-param-doc def permutation(self) -> Dict[int, int]: return self._permutation diff --git a/cirq-core/cirq/contrib/paulistring/separate.py b/cirq-core/cirq/contrib/paulistring/separate.py index bdaac30d3c1..f1ddfeaa5d3 100644 --- a/cirq-core/cirq/contrib/paulistring/separate.py +++ b/cirq-core/cirq/contrib/paulistring/separate.py @@ -19,20 +19,20 @@ from cirq.contrib.paulistring.convert_gate_set import converted_gate_set -# TODO(#3388) Add documentation for Args. -# pylint: disable=missing-param-doc def convert_and_separate_circuit( circuit: circuits.Circuit, leave_cliffords: bool = True, atol: float = 1e-8, ) -> Tuple[circuits.Circuit, circuits.Circuit]: - """Converts any circuit into two circuits where (circuit_left+circuit_right) - is equivalent to the given circuit. + """Converts a circuit into two, one made of PauliStringPhasor and the other Clifford gates. Args: circuit: Any Circuit that cirq.google.optimized_for_xmon() supports. All gates should either provide a decomposition or have a known one or two qubit unitary matrix. + leave_cliffords: If set, single qubit rotations in the Clifford group + are not converted to SingleQubitCliffordGates. + atol: The absolute tolerance for the conversion. Returns: (circuit_left, circuit_right) @@ -43,12 +43,12 @@ def convert_and_separate_circuit( SingleQubitCliffordGate and PauliInteractionGate gates. It also contains MeasurementGates if the given circuit contains measurements. + """ circuit = converted_gate_set(circuit, no_clifford_gates=not leave_cliffords, atol=atol) return pauli_string_half(circuit), regular_half(circuit) -# pylint: enable=missing-param-doc def regular_half(circuit: circuits.Circuit) -> circuits.Circuit: """Return only the Clifford part of a circuit. See convert_and_separate_circuit(). diff --git a/cirq-core/cirq/interop/quirk/cells/testing.py b/cirq-core/cirq/interop/quirk/cells/testing.py index 51183f944ab..e9dad1e6b4f 100644 --- a/cirq-core/cirq/interop/quirk/cells/testing.py +++ b/cirq-core/cirq/interop/quirk/cells/testing.py @@ -20,8 +20,6 @@ from cirq import quirk_url_to_circuit -# TODO(#3388) Add summary line to docstring. -# pylint: disable=docstring-first-line-empty def assert_url_to_circuit_returns( json_text: str, circuit: 'cirq.Circuit' = None, @@ -31,7 +29,8 @@ def assert_url_to_circuit_returns( output_amplitudes_from_quirk: Optional[List[Dict[str, float]]] = None, maps: Optional[Dict[int, int]] = None, ): - """ + """Assert that `quirk_url_to_circuit` functions correctly. + Args: json_text: The part of the quirk URL after "#circuit=". circuit: The optional expected circuit. If specified and not @@ -80,6 +79,3 @@ def assert_url_to_circuit_returns( if maps: cirq.testing.assert_equivalent_computational_basis_map(maps, parsed) - - -# pylint: enable=docstring-first-line-empty diff --git a/cirq-core/cirq/ion/convert_to_ion_gates.py b/cirq-core/cirq/ion/convert_to_ion_gates.py index f9b838a97ed..f3e5708337d 100644 --- a/cirq-core/cirq/ion/convert_to_ion_gates.py +++ b/cirq-core/cirq/ion/convert_to_ion_gates.py @@ -32,16 +32,17 @@ def __init__(self, ignore_failures: bool = False) -> None: self.ignore_failures = ignore_failures self.gateset = ion_device.get_ion_gateset() - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def convert_one(self, op: ops.Operation) -> ops.OP_TREE: """Convert a single (one- or two-qubit) operation into ion trap native gates. Args: - op: gate operation to be converted + op: The gate operation to be converted. Returns: - the desired operation implemented with ion trap gates + The desired operations implemented with ion trap gates. + + Raises: + TypeError: If the operation cannot be converted. """ # Known gate name @@ -80,7 +81,6 @@ def convert_one(self, op: ops.Operation) -> ops.OP_TREE: "or composite.".format(op.gate) ) - # pylint: enable=missing-raises-doc def convert_circuit(self, circuit: circuits.Circuit) -> circuits.Circuit: new_circuit = circuits.Circuit() for moment in circuit: diff --git a/cirq-core/cirq/ops/moment.py b/cirq-core/cirq/ops/moment.py index b88c4854a47..ab4c1bdf6bf 100644 --- a/cirq-core/cirq/ops/moment.py +++ b/cirq-core/cirq/ops/moment.py @@ -137,8 +137,6 @@ def operation_at(self, qubit: raw_types.Qid) -> Optional['cirq.Operation']: else: return None - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def with_operation(self, operation: 'cirq.Operation') -> 'cirq.Moment': """Returns an equal moment, but with the given op added. @@ -147,6 +145,9 @@ def with_operation(self, operation: 'cirq.Operation') -> 'cirq.Moment': Returns: The new moment. + + Raises: + ValueError: If the operation given overlaps a current operation in the moment. """ if any(q in self._qubits for q in operation.qubits): raise ValueError(f'Overlapping operations: {operation}') @@ -161,7 +162,6 @@ def with_operation(self, operation: 'cirq.Operation') -> 'cirq.Moment': return m - # TODO(#3388) Add documentation for Raises. def with_operations(self, *contents: 'cirq.OP_TREE') -> 'cirq.Moment': """Returns a new moment with the given contents added. @@ -170,6 +170,9 @@ def with_operations(self, *contents: 'cirq.OP_TREE') -> 'cirq.Moment': Returns: The new moment. + + Raises: + ValueError: If the contents given overlaps a current operation in the moment. """ from cirq.ops import op_tree @@ -192,7 +195,6 @@ def with_operations(self, *contents: 'cirq.OP_TREE') -> 'cirq.Moment': return m - # pylint: enable=missing-raises-doc def without_operations_touching(self, qubits: Iterable['cirq.Qid']) -> 'cirq.Moment': """Returns an equal moment, but without ops on the given qubits. @@ -375,8 +377,6 @@ def __getitem__(self, key): ops_to_keep.append(self._qubit_to_op[q]) return Moment(frozenset(ops_to_keep)) - # TODO(#3388) Add summary line to docstring. - # pylint: disable=docstring-first-line-empty def to_text_diagram( self: 'cirq.Moment', *, @@ -385,8 +385,9 @@ def to_text_diagram( use_unicode_characters: bool = True, precision: Optional[int] = None, include_tags: bool = True, - ): - """ + ) -> str: + """Create a text diagram for the moment. + Args: xy_breakdown_func: A function to split qubits/qudits into x and y components. For example, the default breakdown turns @@ -469,7 +470,6 @@ def cleanup_key(key: Any) -> Any: return diagram.render() - # pylint: enable=docstring-first-line-empty def _commutes_( self, other: Any, *, atol: Union[int, float] = 1e-8 ) -> Union[bool, NotImplementedType]: diff --git a/cirq-core/cirq/sim/sparse_simulator_test.py b/cirq-core/cirq/sim/sparse_simulator_test.py index 4372f6ac1c2..7414fdfbadc 100644 --- a/cirq-core/cirq/sim/sparse_simulator_test.py +++ b/cirq-core/cirq/sim/sparse_simulator_test.py @@ -1174,10 +1174,9 @@ def test_random_seed_mixture_deterministic(): ) -# TODO(#3388) Add summary line to docstring. -# pylint: disable=docstring-first-line-empty def test_entangled_reset_does_not_break_randomness(): - """ + """Test for bad assumptions on caching the wave function on general channels. + A previous version of cirq made the mistake of assuming that it was okay to cache the wavefunction produced by general channels on unrelated qubits before repeatedly sampling measurements. This test checks for that mistake. @@ -1194,7 +1193,6 @@ def test_entangled_reset_does_not_break_randomness(): assert 10 <= counts[1] <= 90 -# pylint: enable=docstring-first-line-empty def test_overlapping_measurements_at_end(): a, b = cirq.LineQubit.range(2) circuit = cirq.Circuit( diff --git a/cirq-core/cirq/testing/equivalent_repr_eval.py b/cirq-core/cirq/testing/equivalent_repr_eval.py index d514f0eee9f..b1e13fc3021 100644 --- a/cirq-core/cirq/testing/equivalent_repr_eval.py +++ b/cirq-core/cirq/testing/equivalent_repr_eval.py @@ -15,8 +15,6 @@ from typing import Any, Dict, Optional -# TODO(#3388) Add documentation for Raises. -# pylint: disable=missing-raises-doc def assert_equivalent_repr( value: Any, *, @@ -37,10 +35,11 @@ def assert_equivalent_repr( evaluating the repr. local_vals: Pre-defined values that should be in the local scope when evaluating the repr. + + Raises: + AssertionError: If the assertion fails, or eval(repr(value)) raises an error. """ - # pylint: disable=unused-variable - __tracebackhide__ = True - # pylint: enable=unused-variable + __tracebackhide__ = True # pylint: disable=unused-variable global_vals = global_vals or {} local_vals = local_vals or {} @@ -99,6 +98,3 @@ def assert_equivalent_repr( "{!r}.XXX must be equivalent to ({!r}).XXX, " "but it wasn't.".format(type(value), value, value) ) - - -# pylint: enable=missing-raises-doc diff --git a/cirq-google/cirq_google/optimizers/convert_to_sqrt_iswap.py b/cirq-google/cirq_google/optimizers/convert_to_sqrt_iswap.py index be9c52f72fb..58353d3ba06 100644 --- a/cirq-google/cirq_google/optimizers/convert_to_sqrt_iswap.py +++ b/cirq-google/cirq_google/optimizers/convert_to_sqrt_iswap.py @@ -51,12 +51,10 @@ def __init__(self, ignore_failures=False) -> None: super().__init__() self.ignore_failures = ignore_failures - # TODO(#3388) Add summary line to docstring. - # pylint: disable=docstring-first-line-empty def _convert_one(self, op: cirq.Operation) -> cirq.OP_TREE: - """ - Decomposer intercept: Let cirq decompose one-qubit gates, - intercept on 2-qubit gates if they are known gates. + """The main conversion method. + + Let Cirq decompose one-qubit gates, intercept on 2-qubit gates if they are known gates. """ if isinstance(op, cirq.GlobalPhaseOperation): return [] @@ -82,7 +80,6 @@ def _convert_one(self, op: cirq.Operation) -> cirq.OP_TREE: return NotImplemented - # pylint: enable=docstring-first-line-empty def _on_stuck_raise(self, bad): return TypeError( f"Don't know how to work with {bad}. " @@ -265,11 +262,10 @@ def iswap_to_sqrt_iswap(a, b, turns): yield cirq.Z(b) ** -0.25 -# TODO(#3388) Add documentation for Args. -# pylint: disable=missing-param-doc def swap_to_sqrt_iswap(a, b, turns): - """Implement the evolution of the hopping term using two sqrt_iswap gates - and single-qubit operations. Output unitary: + """Implement the evolution of a hopping term using two sqrt_iswap gates and single qubit gates. + + Output unitary: [[1, 0, 0, 0], [0, g·c, -i·g·s, 0], [0, -i·g·s, g·c, 0], @@ -279,8 +275,11 @@ def swap_to_sqrt_iswap(a, b, turns): Args: a: the first qubit b: the second qubit - theta: The rotational angle that specifies the gate, where - c = cos(π·t/2), s = sin(π·t/2), g = exp(i·π·t/2). + turns: The rotational angle that specifies the gate, where + c = cos(π·t/2), s = sin(π·t/2), g = exp(i·π·t/2). + + Yields: + A `cirq.OP_TREE` representing the decomposition. """ if not isinstance(turns, sympy.Basic) and _near_mod_n(turns, 1.0, 2): # Decomposition for cirq.SWAP @@ -308,7 +307,6 @@ def swap_to_sqrt_iswap(a, b, turns): yield cirq.CZ.on(a, b) ** (-turns) -# pylint: enable=missing-param-doc def fsim_gate(a, b, theta, phi): """FSimGate has a default decomposition in cirq to XXPowGate and YYPowGate, which is an awkward decomposition for this gate set. diff --git a/cirq-google/cirq_google/serialization/op_deserializer.py b/cirq-google/cirq_google/serialization/op_deserializer.py index 6ed77a59d96..e9690a5fbef 100644 --- a/cirq-google/cirq_google/serialization/op_deserializer.py +++ b/cirq-google/cirq_google/serialization/op_deserializer.py @@ -146,8 +146,6 @@ def __init__( def serialized_id(self): return self._serialized_gate_id - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def from_proto( self, proto: v2.program_pb2.Operation, @@ -168,6 +166,10 @@ def from_proto( Returns: The deserialized GateOperation represented by `proto`. + + Raises: + ValueError: If the proto references a missing constants table, or a required arg is + missing. """ qubits = [v2.qubit_from_proto_id(q.id) for q in proto.qubits] args = self._args_from_proto(proto, arg_function_language=arg_function_language) @@ -191,7 +193,6 @@ def from_proto( op = op.with_tags(CalibrationTag(proto.token_value)) return op - # pylint: enable=missing-raises-doc def _args_from_proto( self, proto: v2.program_pb2.Operation, *, arg_function_language: str ) -> Dict[str, arg_func_langs.ARG_LIKE]: @@ -228,8 +229,6 @@ class CircuitOpDeserializer(OpDeserializer): def serialized_id(self): return 'circuit' - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def from_proto( self, proto: v2.program_pb2.CircuitOperation, @@ -251,6 +250,9 @@ def from_proto( Returns: The deserialized CircuitOperation represented by `proto`. + + Raises: + ValueError: If the circuit operatio proto cannot be deserialied because it is malformed. """ if constants is None or deserialized_constants is None: raise ValueError( @@ -322,5 +324,3 @@ def from_proto( arg_map, # type: ignore rep_ids, ) - - # pylint: enable=missing-raises-doc diff --git a/cirq-pasqal/cirq_pasqal/pasqal_noise_model.py b/cirq-pasqal/cirq_pasqal/pasqal_noise_model.py index 82d4bc0e23f..425bafd9b4a 100644 --- a/cirq-pasqal/cirq_pasqal/pasqal_noise_model.py +++ b/cirq-pasqal/cirq_pasqal/pasqal_noise_model.py @@ -65,16 +65,17 @@ def noisy_moment( noise_list.append(noise_op.on(qubit)) return list(moment) + noise_list - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def get_op_string(self, cirq_op: cirq.ops.Operation) -> str: """Find the string representation for a given operation. Args: - cirq_op: one cirq operation. + cirq_op: A cirq operation. Returns: String representing the gate operations. + + Raises: + ValueError: If the operations gate is not supported. """ if not self.device.is_pasqal_device_op(cirq_op) or isinstance( cirq_op.gate, cirq.ops.MeasurementGate @@ -82,5 +83,3 @@ def get_op_string(self, cirq_op: cirq.ops.Operation) -> str: raise ValueError('Got unknown operation:', cirq_op) return str(cirq_op.gate) - - # pylint: enable=missing-raises-doc diff --git a/cirq-web/cirq_web/circuits/circuit.py b/cirq-web/cirq_web/circuits/circuit.py index 8b4e22f3dc3..e610253d5a0 100644 --- a/cirq-web/cirq_web/circuits/circuit.py +++ b/cirq-web/cirq_web/circuits/circuit.py @@ -25,8 +25,6 @@ class Circuit3D(widget.Widget): """Takes cirq.Circuit objects and displays them in 3D.""" - # TODO(#3388) Add documentation for Args. - # pylint: disable=missing-param-doc def __init__( self, circuit: cirq.Circuit, @@ -36,14 +34,15 @@ def __init__( """Initializes a Circuit instance. Args: - circuit: The cirq.Circuit to be represented in 3D. + circuit: The `cirq.Circuit` to be represented in 3D. + resolvers: The symbol resolve for how to show symbols in 3D. + padding_factor: The distance between meshes. """ super().__init__() self.circuit = circuit self._resolvers = resolvers self.padding_factor = padding_factor - # pylint: enable=missing-param-doc def get_client_code(self) -> str: # Remove hyphens from the id so that we can use # it as the variable name in TS.