diff --git a/cirq-core/cirq/contrib/graph_device/graph_device.py b/cirq-core/cirq/contrib/graph_device/graph_device.py index cf1029efb6c..a6ad463227c 100644 --- a/cirq-core/cirq/contrib/graph_device/graph_device.py +++ b/cirq-core/cirq/contrib/graph_device/graph_device.py @@ -120,8 +120,6 @@ class UndirectedGraphDevice(devices.Device): * duration_of does not check that operation is valid. """ - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def __init__( self, device_graph: Optional[UndirectedHypergraph] = None, @@ -136,6 +134,9 @@ def __init__( crosstalk_graph: An undirected hypergraph whose vertices are edges of device_graph and whose edges give simultaneity constraints thereon. + + Raises: + TypeError: If the crosstalk graph is not a valid crosstalk graph. """ if device_graph is None: @@ -150,7 +151,6 @@ def __init__( self.device_graph = device_graph self.crosstalk_graph = crosstalk_graph - # pylint: enable=missing-raises-doc @property def qubits(self) -> Tuple['cirq.Qid', ...]: return cast(Tuple['cirq.Qid', ...], tuple(sorted(self.device_graph.vertices))) diff --git a/cirq-core/cirq/contrib/quimb/density_matrix.py b/cirq-core/cirq/contrib/quimb/density_matrix.py index eed902785fd..05acff4aa15 100644 --- a/cirq-core/cirq/contrib/quimb/density_matrix.py +++ b/cirq-core/cirq/contrib/quimb/density_matrix.py @@ -75,8 +75,6 @@ def _add_to_positions( positions[(f'i{mi}b', _qpos_tag(qubits))] = (mi * x_scale, y_scale * qy + yb_offset) -# TODO(#3388) Add documentation for Raises. -# pylint: disable=missing-raises-doc def circuit_to_density_matrix_tensors( circuit: cirq.Circuit, qubits: Optional[Sequence[cirq.Qid]] = None ) -> Tuple[List[qtn.Tensor], Dict['cirq.Qid', int], Dict[Tuple[str, str], Tuple[float, float]]]: @@ -103,6 +101,9 @@ def circuit_to_density_matrix_tensors( positions: A positions dictionary suitable for passing to tn.graph()'s `fix` argument to draw the resulting tensor network similar to a quantum circuit. + + Raises: + ValueError: If an op is encountered that cannot be converted. """ if qubits is None: # coverage: ignore @@ -195,7 +196,6 @@ def _positions(_mi, _these_qubits): return tensors, qubit_frontier, positions -# pylint: enable=missing-raises-doc def tensor_density_matrix( circuit: cirq.Circuit, qubits: Optional[List[cirq.Qid]] = None ) -> np.ndarray: diff --git a/cirq-core/cirq/experiments/google_v2_supremacy_circuit.py b/cirq-core/cirq/experiments/google_v2_supremacy_circuit.py index 2147ef751c3..8e55807476f 100644 --- a/cirq-core/cirq/experiments/google_v2_supremacy_circuit.py +++ b/cirq-core/cirq/experiments/google_v2_supremacy_circuit.py @@ -176,12 +176,11 @@ def _add_cz_layer(layer_index: int, circuit: circuits.Circuit) -> int: return layer_index -# TODO(#3388) Add summary line to docstring. -# pylint: disable=docstring-first-line-empty def _make_cz_layer( qubits: Iterable[devices.GridQubit], layer_index: int ) -> Iterable[ops.Operation]: - """ + """Make the CZ layer gate. + Each layer index corresponds to a shift/transpose of this CZ pattern: ●───● ● ● ●───● ● ● . . . @@ -235,6 +234,3 @@ def _make_cz_layer( continue # No CZ along this edge for this layer. yield ops.common_gates.CZ(q, q2) - - -# pylint: enable=docstring-first-line-empty diff --git a/cirq-core/cirq/experiments/t1_decay_experiment.py b/cirq-core/cirq/experiments/t1_decay_experiment.py index 4c785539f9c..dd13dbd2b9a 100644 --- a/cirq-core/cirq/experiments/t1_decay_experiment.py +++ b/cirq-core/cirq/experiments/t1_decay_experiment.py @@ -31,8 +31,6 @@ optimize = _import.LazyLoader("optimize", globals(), "scipy.optimize") -# TODO(#3388) Add documentation for Raises. -# pylint: disable=missing-raises-doc def t1_decay( sampler: 'cirq.Sampler', *, @@ -58,6 +56,10 @@ def t1_decay( Returns: A T1DecayResult object that stores and can plot the data. + + Raises: + ValueError: If the supplied parameters are not valid: negative repetitions, + max delay less than min, or min delay less than 0. """ min_delay_dur = value.Duration(min_delay) max_delay_dur = value.Duration(max_delay) @@ -96,7 +98,6 @@ def t1_decay( return T1DecayResult(tab) -# pylint: enable=missing-raises-doc class T1DecayResult: """Results from a Rabi oscillation experiment.""" diff --git a/cirq-core/cirq/linalg/decompositions.py b/cirq-core/cirq/linalg/decompositions.py index 52f5032d025..d9d3250eff8 100644 --- a/cirq-core/cirq/linalg/decompositions.py +++ b/cirq-core/cirq/linalg/decompositions.py @@ -876,8 +876,6 @@ def kak_decomposition( ) -# TODO(#3388) Add documentation for Raises. -# pylint: disable=missing-raises-doc def kak_vector( unitary: Union[Iterable[np.ndarray], np.ndarray], *, @@ -930,6 +928,9 @@ def kak_vector( the same as the input shape, except the two unitary matrix axes are replaced by the kak vector axis (i.e. the output has shape `unitary.shape[:-2] + (3,)`). + + Raises: + ValueError: If `atol` is negative or if the unitary has the wrong shape. """ unitary = np.asarray(unitary) if len(unitary) == 0: @@ -979,7 +980,6 @@ def kak_vector( return _canonicalize_kak_vector(k_vec, atol) -# pylint: enable=missing-raises-doc def _canonicalize_kak_vector(k_vec: np.ndarray, atol: float) -> np.ndarray: r"""Map a KAK vector into its Weyl chamber equivalent vector. @@ -1027,9 +1027,6 @@ def _canonicalize_kak_vector(k_vec: np.ndarray, atol: float) -> np.ndarray: return k_vec -# TODO(#3388) Add documentation for Args. -# TODO(#3388) Add documentation for Raises. -# pylint: disable=missing-param-doc,missing-raises-doc def num_cnots_required(u: np.ndarray, atol: float = 1e-8) -> int: """Returns the min number of CNOT/CZ gates required by a two-qubit unitary. @@ -1038,10 +1035,14 @@ def num_cnots_required(u: np.ndarray, atol: float = 1e-8) -> int: Controlled-Not Gates”. https://arxiv.org/abs/quant-ph/0308045 Args: - u: a two-qubit unitary + u: A two-qubit unitary. + atol: The absolute tolerance used to make this judgement. Returns: - the number of CNOT or CZ gates required to implement the unitary + The number of CNOT or CZ gates required to implement the unitary. + + Raises: + ValueError: If the shape of `u` is not 4 by 4. """ if u.shape != (4, 4): raise ValueError(f"Expected unitary of shape (4,4), instead got {u.shape}") @@ -1061,7 +1062,6 @@ def num_cnots_required(u: np.ndarray, atol: float = 1e-8) -> int: return 3 -# pylint: enable=missing-param-doc,missing-raises-doc def _gamma(u: np.ndarray) -> np.ndarray: """Gamma function to convert u to the magic basis. diff --git a/cirq-core/cirq/ops/controlled_gate.py b/cirq-core/cirq/ops/controlled_gate.py index ed16d8207b1..5a9337e673e 100644 --- a/cirq-core/cirq/ops/controlled_gate.py +++ b/cirq-core/cirq/ops/controlled_gate.py @@ -29,8 +29,6 @@ class ControlledGate(raw_types.Gate): This object is typically created via `gate.controlled()`. """ - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def __init__( self, sub_gate: 'cirq.Gate', @@ -54,6 +52,10 @@ def __init__( expected dimension of each control qid. Defaults to `(2,) * num_controls`. Specify this argument when using qudits. + Raises: + ValueError: If the `control_values` or `control_qid_shape` does not + match with `num_conrols`, or if the `control_values` are out of + bounds. """ if num_controls is None: if control_values is not None: @@ -94,7 +96,6 @@ def __init__( else: self.sub_gate = sub_gate - # pylint: enable=missing-raises-doc def num_controls(self) -> int: return len(self.control_qid_shape) diff --git a/cirq-core/cirq/ops/dense_pauli_string.py b/cirq-core/cirq/ops/dense_pauli_string.py index 5c1526bc306..6a700fc0924 100644 --- a/cirq-core/cirq/ops/dense_pauli_string.py +++ b/cirq-core/cirq/ops/dense_pauli_string.py @@ -109,14 +109,13 @@ def _value_equality_values_(self): # Would cause approx_eq to false positive when atol > 1. return self.coefficient, tuple(PAULI_CHARS[p] for p in self.pauli_mask) - # TODO(#3388) Add documentation for Args. - # pylint: disable=missing-param-doc @classmethod def one_hot(cls: Type[TCls], *, index: int, length: int, pauli: 'cirq.PAULI_GATE_LIKE') -> TCls: """Creates a dense pauli string with only one non-identity Pauli. Args: index: The index of the Pauli that is not an identity. + length: The total length of the string to create. pauli: The pauli gate to put at the hot index. Can be set to either a string ('X', 'Y', 'Z', 'I'), a cirq gate (`cirq.X`, `cirq.Y`, `cirq.Z`, or `cirq.I`), or an integer (0=I, 1=X, 2=Y, @@ -127,7 +126,6 @@ def one_hot(cls: Type[TCls], *, index: int, length: int, pauli: 'cirq.PAULI_GATE concrete_cls = cast(Callable, DensePauliString if cls is BaseDensePauliString else cls) return concrete_cls(pauli_mask=mask) - # pylint: enable=missing-param-doc @classmethod def eye(cls: Type[TCls], length: int) -> TCls: """Creates a dense pauli string containing only identity gates. @@ -283,8 +281,6 @@ def __abs__(self): def on(self, *qubits) -> 'cirq.PauliString': return self.sparse(qubits) - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def sparse(self, qubits: Optional[Sequence['cirq.Qid']] = None) -> 'cirq.PauliString': """A `cirq.PauliString` version of this dense pauli string. @@ -295,6 +291,10 @@ def sparse(self, qubits: Optional[Sequence['cirq.Qid']] = None) -> 'cirq.PauliSt Returns: A `cirq.PauliString` with the non-identity operations from this dense pauli string applied to appropriate qubits. + + Raises: + ValueError: If the number of qubits supplied does not match that of + this instance. """ if qubits is None: from cirq import devices @@ -309,7 +309,6 @@ def sparse(self, qubits: Optional[Sequence['cirq.Qid']] = None) -> 'cirq.PauliSt qubit_pauli_map={q: PAULI_GATES[p] for q, p in zip(qubits, self.pauli_mask) if p}, ) - # pylint: enable=missing-raises-doc def __str__(self) -> str: if self.coefficient == 1: coef = '+' diff --git a/cirq-core/cirq/ops/pauli_gates.py b/cirq-core/cirq/ops/pauli_gates.py index 581dd473ca6..0750f584ecf 100644 --- a/cirq-core/cirq/ops/pauli_gates.py +++ b/cirq-core/cirq/ops/pauli_gates.py @@ -84,13 +84,14 @@ def __lt__(self, other): return NotImplemented return (other._index - self._index) % 3 == 1 - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def on(self, *qubits: 'cirq.Qid') -> 'SingleQubitPauliStringGateOperation': """Returns an application of this gate to the given qubits. Args: *qubits: The collection of qubits to potentially apply the gate to. + + Raises: + ValueError: If more than one qubit is acted upon. """ if len(qubits) != 1: raise ValueError(f'Expected a single qubit, got <{qubits!r}>.') @@ -98,7 +99,6 @@ def on(self, *qubits: 'cirq.Qid') -> 'SingleQubitPauliStringGateOperation': return SingleQubitPauliStringGateOperation(self, qubits[0]) - # pylint: enable=missing-raises-doc @property def _canonical_exponent(self): """Overrides EigenGate._canonical_exponent in subclasses.""" diff --git a/cirq-core/cirq/ops/pauli_string_phasor.py b/cirq-core/cirq/ops/pauli_string_phasor.py index 4266df4d87b..7b27a83942e 100644 --- a/cirq-core/cirq/ops/pauli_string_phasor.py +++ b/cirq-core/cirq/ops/pauli_string_phasor.py @@ -40,8 +40,6 @@ class PauliStringPhasor(pauli_string_raw_types.PauliStringGateOperation): their amplitude multiplied by e^(i pi exponent_pos). """ - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def __init__( self, pauli_string: ps.PauliString, @@ -58,6 +56,10 @@ def __init__( in the form of the t in (-1)**t = exp(i pi t). exponent_pos: How much to phase vectors in the positive eigenspace, in the form of the t in (-1)**t = exp(i pi t). + + Raises: + ValueError: If the given pauli string does not have eignevalues +1 + or -1. """ if pauli_string.coefficient == -1: pauli_string = -pauli_string @@ -73,7 +75,6 @@ def __init__( self.exponent_neg = value.canonicalize_half_turns(exponent_neg) self.exponent_pos = value.canonicalize_half_turns(exponent_pos) - # pylint: enable=missing-raises-doc @property def exponent_relative(self) -> Union[int, float, sympy.Basic]: return value.canonicalize_half_turns(self.exponent_neg - self.exponent_pos) diff --git a/cirq-core/cirq/optimizers/two_qubit_decompositions.py b/cirq-core/cirq/optimizers/two_qubit_decompositions.py index d58676dcd06..9f65bf4c86c 100644 --- a/cirq-core/cirq/optimizers/two_qubit_decompositions.py +++ b/cirq-core/cirq/optimizers/two_qubit_decompositions.py @@ -199,19 +199,17 @@ def _kak_decomposition_to_operations( ) -# TODO(#3388) Add documentation for Args. -# pylint: disable=missing-param-doc def _is_trivial_angle(rad: float, atol: float) -> bool: """Tests if a circuit for an operator exp(i*rad*XX) (or YY, or ZZ) can be performed with a whole CZ. Args: rad: The angle in radians, assumed to be in the range [-pi/4, pi/4] + atol: The absolute tolerance with which to make this judgement. """ return abs(rad) < atol or abs(abs(rad) - np.pi / 4) < atol -# pylint: enable=missing-param-doc def _parity_interaction( q0: 'cirq.Qid', q1: 'cirq.Qid', rads: float, atol: float, gate: Optional[ops.Gate] = None ): diff --git a/cirq-core/cirq/protocols/act_on_protocol.py b/cirq-core/cirq/protocols/act_on_protocol.py index 06f4ccd00f2..54edd8a76a2 100644 --- a/cirq-core/cirq/protocols/act_on_protocol.py +++ b/cirq-core/cirq/protocols/act_on_protocol.py @@ -88,8 +88,6 @@ def _act_on_( """ -# TODO(#3388) Add documentation for Raises. -# pylint: disable=missing-raises-doc def act_on( action: Union['cirq.Operation', 'cirq.Gate'], args: 'cirq.OperationTarget', @@ -125,6 +123,10 @@ def act_on( Nothing. Results are communicated by editing `args`. Raises: + ValueError: If called on an operation and supplied qubits, if not called + on an operation and no qubits are supplied, or if `_act_on_` or + `_act_on_fallback_` returned something other than `True` or + `NotImplemented`. TypeError: Failed to act `action` on `args`. """ is_op = isinstance(action, ops.Operation) @@ -166,6 +168,3 @@ def act_on( f"Action type: {type(action)}\n" f"Action repr: {action!r}\n" ) - - -# pylint: enable=missing-raises-doc diff --git a/cirq-core/cirq/protocols/approximate_equality_protocol.py b/cirq-core/cirq/protocols/approximate_equality_protocol.py index b9c4203e91f..3d67d75b36a 100644 --- a/cirq-core/cirq/protocols/approximate_equality_protocol.py +++ b/cirq-core/cirq/protocols/approximate_equality_protocol.py @@ -47,8 +47,6 @@ def _approx_eq_(self, other: Any, *, atol: Union[int, float]) -> bool: """ -# TODO(#3388) Add documentation for Raises. -# pylint: disable=missing-raises-doc def approx_eq(val: Any, other: Any, *, atol: Union[int, float] = 1e-8) -> bool: """Approximately compares two objects. @@ -72,6 +70,10 @@ def approx_eq(val: Any, other: Any, *, atol: Union[int, float] = 1e-8) -> bool: Returns: True if objects are approximately equal, False otherwise. + + Raises: + AttributeError: If there is insufficient information to determine whether + the objects are approximately equal. """ # Check if val defines approximate equality via _approx_eq_. This takes @@ -118,7 +120,6 @@ def approx_eq(val: Any, other: Any, *, atol: Union[int, float] = 1e-8) -> bool: return val == other -# pylint: enable=missing-raises-doc def _approx_eq_iterables(val: Iterable, other: Iterable, *, atol: Union[int, float]) -> bool: """Iterates over arguments and calls approx_eq recursively. diff --git a/cirq-core/cirq/protocols/mixture_protocol.py b/cirq-core/cirq/protocols/mixture_protocol.py index 05adeff5796..64da3478747 100644 --- a/cirq-core/cirq/protocols/mixture_protocol.py +++ b/cirq-core/cirq/protocols/mixture_protocol.py @@ -60,8 +60,6 @@ def _has_mixture_(self) -> bool: """ -# TODO(#3388) Add documentation for Raises. -# pylint: disable=missing-raises-doc def mixture( val: Any, default: Any = RaiseTypeErrorIfNotProvided ) -> Sequence[Tuple[float, np.ndarray]]: @@ -82,6 +80,10 @@ def mixture( An iterable of tuples of size 2. The first element of the tuple is a probability (between 0 and 1) and the second is the object that occurs with that probability in the mixture. The probabilities will sum to 1.0. + + Raises: + TypeError: If `val` has no `_mixture_` or `_unitary_` mehod, or if it + does and this method returned `NotImplemented`. """ mixture_getter = getattr(val, '_mixture_', None) @@ -106,7 +108,6 @@ def mixture( ) -# pylint: enable=missing-raises-doc def has_mixture(val: Any, *, allow_decompose: bool = True) -> bool: """Returns whether the value has a mixture representation. diff --git a/cirq-core/cirq/sim/act_on_args.py b/cirq-core/cirq/sim/act_on_args.py index d3dc9416103..870eaf3b9c5 100644 --- a/cirq-core/cirq/sim/act_on_args.py +++ b/cirq-core/cirq/sim/act_on_args.py @@ -73,8 +73,6 @@ def _set_qubits(self, qubits: Sequence['cirq.Qid']): self._qubits = tuple(qubits) self.qubit_map = {q: i for i, q in enumerate(self.qubits)} - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def measure(self, qubits: Sequence['cirq.Qid'], key: str, invert_mask: Sequence[bool]): """Adds a measurement result to the log. @@ -84,6 +82,9 @@ def measure(self, qubits: Sequence['cirq.Qid'], key: str, invert_mask: Sequence[ that operations should only store results under keys they have declared in a `_measurement_key_names_` method. invert_mask: The invert mask for the measurement. + + Raises: + ValueError: If a measurement key has already been logged to a key. """ bits = self._perform_measurement(qubits) corrected = [bit ^ (bit < 2 and mask) for bit, mask in zip(bits, invert_mask)] @@ -91,7 +92,6 @@ def measure(self, qubits: Sequence['cirq.Qid'], key: str, invert_mask: Sequence[ raise ValueError(f"Measurement already logged to key {key!r}") self._log_of_measurement_results[key] = corrected - # pylint: enable=missing-raises-doc def get_axes(self, qubits: Sequence['cirq.Qid']) -> List[int]: return [self.qubit_map[q] for q in qubits] diff --git a/cirq-core/cirq/sim/clifford/clifford_simulator.py b/cirq-core/cirq/sim/clifford/clifford_simulator.py index babefa6b5be..dafed64ec61 100644 --- a/cirq-core/cirq/sim/clifford/clifford_simulator.py +++ b/cirq-core/cirq/sim/clifford/clifford_simulator.py @@ -64,8 +64,6 @@ def is_supported_operation(op: 'cirq.Operation') -> bool: # TODO: support more general Pauli measurements return protocols.has_stabilizer_effect(op) - # TODO(#3388) Add documentation for Args. - # pylint: disable=missing-param-doc def _create_partial_act_on_args( self, initial_state: Union[int, clifford.ActOnStabilizerCHFormArgs], @@ -80,6 +78,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 log of the results of measurement that is added to. Returns: ActOnStabilizerChFormArgs for the circuit. @@ -97,7 +96,6 @@ def _create_partial_act_on_args( qubits=qubits, ) - # pylint: enable=missing-param-doc def _create_step_result( self, sim_state: 'cirq.OperationTarget[clifford.ActOnStabilizerCHFormArgs]', diff --git a/cirq-core/cirq/sim/density_matrix_simulator.py b/cirq-core/cirq/sim/density_matrix_simulator.py index 67c87b24e03..ffcd69af42e 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator.py +++ b/cirq-core/cirq/sim/density_matrix_simulator.py @@ -116,8 +116,6 @@ class DensityMatrixSimulator( # step_result.density_matrix() """ - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def __init__( self, *, @@ -141,23 +139,27 @@ def __init__( unentangled qubit sets independently and merging those states at the end. - Example: - >>> (q0,) = cirq.LineQubit.range(1) - >>> circuit = cirq.Circuit(cirq.H(q0), cirq.measure(q0)) + Raises: + ValueError: If the supplied dtype is not `np.complex64` or + `np.complex128`. - Default case (ignore_measurement_results = False): - >>> simulator = cirq.DensityMatrixSimulator() - >>> result = simulator.run(circuit) + Example: + >>> (q0,) = cirq.LineQubit.range(1) + >>> circuit = cirq.Circuit(cirq.H(q0), cirq.measure(q0)) + + Default case (ignore_measurement_results = False): + >>> simulator = cirq.DensityMatrixSimulator() + >>> result = simulator.run(circuit) - The measurement result will be strictly one of 0 or 1. + The measurement result will be strictly one of 0 or 1. - In the other case: - >>> simulator = cirq.DensityMatrixSimulator( - ... ignore_measurement_results = True) + In the other case: + >>> simulator = cirq.DensityMatrixSimulator( + ... ignore_measurement_results = True) - will raise a `ValueError` exception if you call `simulator.run` - when `ignore_measurement_results` has been set to True - (for more see https://github.com/quantumlib/Cirq/issues/2777). + Will raise a `ValueError` exception if you call `simulator.run` + when `ignore_measurement_results` has been set to True + (for more see https://github.com/quantumlib/Cirq/issues/2777). """ super().__init__( dtype=dtype, @@ -169,9 +171,6 @@ def __init__( if dtype not in {np.complex64, np.complex128}: raise ValueError(f'dtype must be complex64 or complex128, was {dtype}') - # 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[np.ndarray, 'cirq.STATE_VECTOR_LIKE', 'cirq.ActOnDensityMatrixArgs'], @@ -186,6 +185,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: The log of measurement results that is added into. Returns: ActOnDensityMatrixArgs for the circuit. @@ -210,7 +210,6 @@ def _create_partial_act_on_args( log_of_measurement_results=logs, ) - # pylint: enable=missing-param-doc def _can_be_in_run_prefix(self, val: Any): return not protocols.is_measurement(val) diff --git a/cirq-core/cirq/sim/simulator.py b/cirq-core/cirq/sim/simulator.py index b038d2a77e2..25e0dd6f891 100644 --- a/cirq-core/cirq/sim/simulator.py +++ b/cirq-core/cirq/sim/simulator.py @@ -76,8 +76,6 @@ def run_sweep( ) -> List[study.Result]: return list(self.run_sweep_iter(program, params, repetitions)) - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def run_sweep_iter( self, program: 'cirq.AbstractCircuit', @@ -97,6 +95,9 @@ def run_sweep_iter( Returns: Result list for this run; one for each possible parameter resolver. + + Raises: + ValueError: If the circuit has no measurements. """ if not program.has_measurements(): raise ValueError("Circuit has no measurements to sample.") @@ -116,7 +117,6 @@ def run_sweep_iter( params=param_resolver, measurements=measurements ) - # pylint: enable=missing-raises-doc @abc.abstractmethod def _run( self, @@ -642,8 +642,6 @@ def _create_act_on_args( The `OperationTarget` for this simulator. """ - # TODO(#3388) Add documentation for Args. - # pylint: disable=missing-param-doc @abc.abstractmethod def _core_iterator( self, @@ -660,12 +658,13 @@ def _core_iterator( sim_state: The initial args for the simulation. The form of this state depends on the simulation implementation. See documentation of the implementing class for details. + all_measurements_are_terminal: Whether all measurements in + the circuit are terminal. Yields: StepResults from simulating a Moment of the Circuit. """ - # pylint: enable=missing-param-doc @abc.abstractmethod def _create_simulator_trial_result( self, @@ -824,8 +823,6 @@ class SimulationTrialResult: measurement gate.) """ - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def __init__( self, params: study.ParamResolver, @@ -847,6 +844,10 @@ def __init__( for cases when calculating simulator state may be expensive and unneeded. If this is provided, then final_simulator_state should not be, and vice versa. + + Raises: + ValueError: If `final_step_result` and `final_simulator_state` are both + None or both not None. """ if [final_step_result, final_simulator_state].count(None) != 1: raise ValueError( @@ -857,7 +858,6 @@ def __init__( self._final_step_result = final_step_result self._final_simulator_state_cache = final_simulator_state - # pylint: enable=missing-raises-doc @property def _final_simulator_state(self): if self._final_simulator_state_cache is None: diff --git a/cirq-core/cirq/value/duration.py b/cirq-core/cirq/value/duration.py index eaa3d2af6c6..03b0da9c541 100644 --- a/cirq-core/cirq/value/duration.py +++ b/cirq-core/cirq/value/duration.py @@ -44,8 +44,6 @@ class Duration: """A time delta that supports symbols and picosecond accuracy.""" - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def __init__( self, value: DURATION_LIKE = None, @@ -67,6 +65,9 @@ def __init__( micros: A number of microseconds to add to the time delta. millis: A number of milliseconds to add to the time delta. + Raises: + TypeError: If the given value is not of a `cirq.DURATION_LIKE` type. + Examples: >>> print(cirq.Duration(nanos=100)) 100 ns @@ -86,7 +87,6 @@ def __init__( picos + nanos * 1000 + micros * 1000_000 + millis * 1000_000_000 ) - # pylint: enable=missing-raises-doc def _is_parameterized_(self) -> bool: return protocols.is_parameterized(self._picos) diff --git a/cirq-core/cirq/value/value_equality_attr.py b/cirq-core/cirq/value/value_equality_attr.py index 723b4a8a3c7..837c235475c 100644 --- a/cirq-core/cirq/value/value_equality_attr.py +++ b/cirq-core/cirq/value/value_equality_attr.py @@ -133,8 +133,6 @@ def value_equality( pass -# TODO(#3388) Add documentation for Raises. -# pylint: disable=missing-raises-doc def value_equality( cls: type = None, *, @@ -184,6 +182,13 @@ class return the existing class' type. approximate: When set, the decorated class will be enhanced with `_approx_eq_` implementation and thus start to support the `SupportsApproximateEquality` protocol. + + Raises: + TypeError: If the class decorated does not implement the required + `_value_equality_values` method or, if `manual_cls` is True, + the class does not implement `_value_equality_values_cls_`. + ValueError: If both `distinct_child_types` and `manual_cls` are + specified. """ # If keyword arguments were specified, python invokes the decorator method @@ -231,4 +236,4 @@ class return the existing class' type. return cls -# pylint: enable=function-redefined,missing-raises-doc +# pylint: enable=function-redefined diff --git a/cirq-google/cirq_google/engine/engine_client.py b/cirq-google/cirq_google/engine/engine_client.py index 7e0ac00296e..30decbec4ef 100644 --- a/cirq-google/cirq_google/engine/engine_client.py +++ b/cirq-google/cirq_google/engine/engine_client.py @@ -299,8 +299,6 @@ def delete_program(self, project_id: str, program_id: str, delete_jobs: bool = F ) ) - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def create_job( self, project_id: str, @@ -325,7 +323,10 @@ def create_job( labels: Optional set of labels to set on the job. Returns: - Tuple of created job id and job + Tuple of created job id and job. + + Raises: + ValueError: If the priority is not betwen 0 and 1000. """ # Check program to run and program parameters. if priority and not 0 <= priority < 1000: @@ -358,7 +359,6 @@ def create_job( ) return _ids_from_job_name(job.name)[2], job - # pylint: enable=missing-raises-doc def list_jobs( self, project_id: str, @@ -680,8 +680,6 @@ def get_calibration( ) ) - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def get_current_calibration( self, project_id: str, processor_id: str ) -> Optional[qtypes.QuantumCalibration]: @@ -693,6 +691,9 @@ def get_current_calibration( Returns: The quantum calibration or None if there is no current calibration. + + Raises: + EngineException: If the request for calibration fails. """ try: return self._make_request( @@ -705,7 +706,6 @@ def get_current_calibration( return None raise - # pylint: enable=missing-raises-doc def create_reservation( self, project_id: str, @@ -779,15 +779,16 @@ def delete_reservation(self, project_id: str, processor_id: str, reservation_id: name = _reservation_name_from_ids(project_id, processor_id, reservation_id) return self._make_request(lambda: self.grpc_client.delete_quantum_reservation(name=name)) - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def get_reservation(self, project_id: str, processor_id: str, reservation_id: str): """Gets a quantum reservation from the engine. Args: project_id: A project_id of the parent Google Cloud Project. processor_id: The processor unique identifier. - reservation_id: Unique ID of the reservation in the parent project, + reservation_id: Unique ID of the reservation in the parent project. + + Raises: + EngineException: If the request to get the reservation failed. """ try: name = _reservation_name_from_ids(project_id, processor_id, reservation_id) @@ -797,7 +798,6 @@ def get_reservation(self, project_id: str, processor_id: str, reservation_id: st return None raise - # pylint: enable=missing-raises-doc def list_reservations( self, project_id: str, processor_id: str, filter_str: str = '' ) -> List[qtypes.QuantumReservation]: @@ -957,14 +957,15 @@ def _ids_from_calibration_name(calibration_name: str) -> Tuple[str, str, int]: return parts[1], parts[3], int(parts[5]) -# TODO(#3388) Add documentation for Raises. -# pylint: disable=missing-raises-doc def _date_or_time_to_filter_expr(param_name: str, param: Union[datetime.datetime, datetime.date]): """Formats datetime or date to filter expressions. Args: - param_name: the name of the filter parameter (for error messaging) - param: the value of the paramter + param_name: The name of the filter parameter (for error messaging). + param: The value of the parameter. + + Raises: + ValueError: If the supplied param is not a datetime or date. """ if isinstance(param, datetime.datetime): return f"{int(param.timestamp())}" @@ -976,6 +977,3 @@ def _date_or_time_to_filter_expr(param_name: str, param: Union[datetime.datetime f"type {type(param)}. Supported types: datetime.datetime and" f"datetime.date" ) - - -# pylint: enable=missing-raises-doc diff --git a/cirq-google/cirq_google/engine/engine_program.py b/cirq-google/cirq_google/engine/engine_program.py index fc9a71bf5bf..bb595f4fe56 100644 --- a/cirq-google/cirq_google/engine/engine_program.py +++ b/cirq-google/cirq_google/engine/engine_program.py @@ -62,8 +62,6 @@ def __init__( self._program = _program self.result_type = result_type - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def run_sweep( self, job_id: Optional[str] = None, @@ -94,6 +92,9 @@ def run_sweep( Returns: An EngineJob. If this is iterated over it returns a list of TrialResults, one for each parameter sweep. + + Raises: + ValueError: If called on a program that is a batch of programs. """ import cirq_google.engine.engine as engine_base @@ -117,7 +118,6 @@ def run_sweep( self.project_id, self.program_id, created_job_id, self.context, job ) - # pylint: enable=missing-raises-doc def run_batch( self, job_id: Optional[str] = None, @@ -204,8 +204,6 @@ def run_batch( result_type=ResultType.Batch, ) - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def run_calibration( self, job_id: Optional[str] = None, @@ -233,7 +231,10 @@ def run_calibration( labels: Optional set of labels to set on the job. Returns: - An EngineJob. Results can be accessed with calibration_results(). + An EngineJob. Results can be accessed with calibration_results(). + + Raises: + ValueError: If no processors are specified. """ import cirq_google.engine.engine as engine_base @@ -266,7 +267,6 @@ def run_calibration( result_type=ResultType.Batch, ) - # pylint: enable=missing-raises-doc def run( self, job_id: Optional[str] = None, diff --git a/cirq-google/cirq_google/experimental/noise_models/noise_models.py b/cirq-google/cirq_google/experimental/noise_models/noise_models.py index 902b8eb7fb8..d63e135d963 100644 --- a/cirq-google/cirq_google/experimental/noise_models/noise_models.py +++ b/cirq-google/cirq_google/experimental/noise_models/noise_models.py @@ -93,8 +93,6 @@ def noisy_moment(self, moment: cirq.Moment, system_qubits: Sequence[cirq.Qid]) - return moments -# TODO(#3388) Add documentation for Raises. -# pylint: disable=missing-raises-doc def simple_noise_from_calibration_metrics( calibration: engine.Calibration, depol_noise: bool = False, @@ -119,6 +117,10 @@ def simple_noise_from_calibration_metrics( Returns: A PerQubitDepolarizingWithDampedReadoutNoiseModel with error probabilities generated from the provided calibration data. + Raises: + NotImplementedError: If `damping_noise` is True, as this is not yet + supported. + ValueError: If none of the noises is set to True. """ if not any([depol_noise, damping_noise, readout_decay_noise, readout_error_noise]): raise ValueError('At least one error type must be specified.') @@ -157,6 +159,3 @@ def simple_noise_from_calibration_metrics( return PerQubitDepolarizingWithDampedReadoutNoiseModel( depol_probs=depol_probs, decay_probs=readout_decay_probs, bitflip_probs=readout_error_probs ) - - -# pylint: enable=missing-raises-doc diff --git a/cirq-ionq/cirq_ionq/job.py b/cirq-ionq/cirq_ionq/job.py index fa1785b7ca8..b93924d5b07 100644 --- a/cirq-ionq/cirq_ionq/job.py +++ b/cirq-ionq/cirq_ionq/job.py @@ -169,8 +169,6 @@ def measurement_dict(self) -> Dict[str, Sequence[int]]: measurement_dict[key] = [int(t) for t in value.split(',')] return measurement_dict - # TODO(#3388) Add documentation for Raises. - # pylint: disable=missing-raises-doc def results( self, timeout_seconds: int = 7200, polling_seconds: int = 1 ) -> Union[results.QPUResult, results.SimulatorResult]: @@ -187,6 +185,9 @@ def results( Raises: IonQUnsuccessfulJob: If the job has failed, been canceled, or deleted. IonQException: If unable to get the results from the API. + RuntimeError: If the job reported that it had failed on the server, or + the job had an unknown status. + TimeoutError: If the job timed out at the server. """ time_waited_seconds = 0 while time_waited_seconds < timeout_seconds: @@ -228,7 +229,6 @@ def results( repetitions=self.repetitions(), ) - # pylint: enable=missing-raises-doc def cancel(self): """Cancel the given job.