Skip to content

Add missing-raises-doc rule to the linter and subsequent refactor. #4345

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 16, 2021
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
10 changes: 8 additions & 2 deletions cirq-aqt/cirq_aqt/aqt_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,14 @@
gate_dict = {'X': cirq.X, 'Y': cirq.Y, 'Z': cirq.Z, 'MS': cirq.XX, 'R': cirq.PhasedXPowGate}


# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def get_op_string(op_obj: cirq.Operation) -> str:
"""Find the string representation for a given gate

Args:
op_obj: Gate object, one of: XXPowGate, XPowGate, YPowGate, ZPowGate,
PhasedXPowGate
PhasedXPowGate

Returns:
String representing the gate operations
Expand All @@ -58,8 +60,9 @@ def get_op_string(op_obj: cirq.Operation) -> str:
return op_str


# pylint: enable=missing-raises-doc
class AQTNoiseModel(cirq.NoiseModel):
"""A noise model for the AQT ion trap """
"""A noise model for the AQT ion trap"""

def __init__(self):
self.noise_op_dict = get_default_noise_dict()
Expand Down Expand Up @@ -190,6 +193,8 @@ def generate_circuit_from_list(self, json_string: str):
# Github issue: https://github.com/quantumlib/Cirq/issues/2199
self.circuit.append(cirq.measure(*[qubit for qubit in self.qubit_list], key='m'))

# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def simulate_samples(self, repetitions: int) -> cirq.Result:
"""Samples the circuit

Expand All @@ -210,6 +215,7 @@ def simulate_samples(self, repetitions: int) -> cirq.Result:
return result


# pylint: enable=missing-raises-doc
def get_aqt_device(num_qubits: int) -> Tuple[cirq.IonDevice, List[cirq.LineQubit]]:
"""Returns an AQT ion device

Expand Down
6 changes: 5 additions & 1 deletion cirq-aqt/cirq_aqt/aqt_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,14 @@ 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.Circuit,
param_resolver: cirq.ParamResolverOrSimilarType,
) -> str:
"""Generates the JSON string from a Circuit
"""Generates the JSON string from a Circuit.

The json format is defined as follows:

Expand Down Expand Up @@ -99,6 +101,7 @@ def _generate_json(
json_str = json.dumps(seq_list)
return json_str

# TODO(#3388) Add documentation for Raises.
def _send_json(
self,
*,
Expand Down Expand Up @@ -171,6 +174,7 @@ def _send_json(
measurements[i, j] = int(measurement_int_bin[j])
return measurements

# pylint: enable=missing-raises-doc
def run_sweep(
self, program: cirq.Circuit, params: cirq.Sweepable, repetitions: int = 1
) -> List[cirq.Result]:
Expand Down
22 changes: 12 additions & 10 deletions cirq-core/cirq/circuits/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -1814,6 +1814,8 @@ def zip(

zip.__doc__ = AbstractCircuit.zip.__doc__

# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def transform_qubits(
self,
qubit_map: Union[Dict['cirq.Qid', 'cirq.Qid'], Callable[['cirq.Qid'], 'cirq.Qid']],
Expand Down Expand Up @@ -1847,6 +1849,7 @@ def transform_qubits(
new_device=self.device if new_device is None else new_device, qubit_mapping=transform
)

# pylint: enable=missing-raises-doc
def _prev_moment_available(self, op: 'cirq.Operation', end_moment_index: int) -> Optional[int]:
last_available = end_moment_index
k = end_moment_index
Expand Down Expand Up @@ -2083,6 +2086,8 @@ def _insert_operations(
self._moments[moment_index].operations + tuple(new_ops)
)

# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def insert_at_frontier(
self, operations: 'cirq.OP_TREE', start: int, frontier: Dict['cirq.Qid', int] = None
) -> Dict['cirq.Qid', int]:
Expand Down Expand Up @@ -2116,6 +2121,7 @@ def insert_at_frontier(

return frontier

# pylint: enable=missing-raises-doc
def batch_remove(self, removals: Iterable[Tuple[int, 'cirq.Operation']]) -> None:
"""Removes several operations from a circuit.

Expand All @@ -2125,11 +2131,9 @@ def batch_remove(self, removals: Iterable[Tuple[int, 'cirq.Operation']]) -> None
listed operations must actually be present or the edit will
fail (without making any changes to the circuit).

ValueError:
One of the operations to delete wasn't present to start with.

IndexError:
Deleted from a moment that doesn't exist.
Raises:
ValueError: One of the operations to delete wasn't present to start with.
IndexError: Deleted from a moment that doesn't exist.
"""
copy = self.copy()
for i, op in removals:
Expand All @@ -2152,11 +2156,9 @@ def batch_replace(
operations must actually be present or the edit will fail
(without making any changes to the circuit).

ValueError:
One of the operations to replace wasn't present to start with.

IndexError:
Replaced in a moment that doesn't exist.
Raises:
ValueError: One of the operations to replace wasn't present to start with.
IndexError: Replaced in a moment that doesn't exist.
"""
copy = self.copy()
for i, op, new_op in replacements:
Expand Down
3 changes: 3 additions & 0 deletions cirq-core/cirq/contrib/acquaintance/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ class GreedyExecutionStrategy(ExecutionStrategy):
qubits in any order are inserted.
"""

# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def __init__(
self, gates: LogicalGates, initial_mapping: LogicalMapping, device: 'cirq.Device' = None
) -> None:
Expand All @@ -149,6 +151,7 @@ def __init__(
self._initial_mapping = initial_mapping.copy()
self._device = device or devices.UNCONSTRAINED_DEVICE

# pylint: enable=missing-raises-doc
@property
def initial_mapping(self) -> LogicalMapping:
return self._initial_mapping
Expand Down
3 changes: 3 additions & 0 deletions cirq-core/cirq/contrib/acquaintance/mutation_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
STRATEGY_GATE = Union[AcquaintanceOpportunityGate, PermutationGate]


# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
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
Expand Down Expand Up @@ -57,6 +59,7 @@ def rectify_acquaintance_strategy(circuit: 'cirq.Circuit', acquaint_first: bool
circuit._moments = rectified_moments


# pylint: enable=missing-raises-doc
# TODO(#3388) Add summary line to docstring.
# pylint: disable=docstring-first-line-empty
def replace_acquaintance_with_swap_network(
Expand Down
5 changes: 3 additions & 2 deletions cirq-core/cirq/contrib/acquaintance/strategies/complete.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@


# TODO(#3388) Add summary line to docstring.
# pylint: disable=docstring-first-line-empty
# 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 Expand Up @@ -65,4 +66,4 @@ def complete_acquaintance_strategy(
return strategy


# pylint: enable=docstring-first-line-empty
# pylint: enable=docstring-first-line-empty,missing-raises-doc
3 changes: 3 additions & 0 deletions cirq-core/cirq/contrib/graph_device/graph_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ 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,
Expand Down Expand Up @@ -148,6 +150,7 @@ 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)))
Expand Down
5 changes: 5 additions & 0 deletions cirq-core/cirq/contrib/qcircuit/qcircuit_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
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 Down Expand Up @@ -63,3 +65,6 @@ def circuit_to_pdf_using_qcircuit_via_tex(
except (OSError, IOError) as e:
if e.errno != errno.ENOENT:
raise


# pylint: enable=missing-raises-doc
3 changes: 3 additions & 0 deletions cirq-core/cirq/contrib/quimb/density_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ 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.LineQubit]] = None
) -> Tuple[List[qtn.Tensor], Dict['cirq.Qid', int], Dict[Tuple[str, str], Tuple[float, float]]]:
Expand Down Expand Up @@ -186,6 +188,7 @@ def _positions(mi, qubits):
return tensors, qubit_frontier, positions


# pylint: enable=missing-raises-doc
def tensor_density_matrix(
circuit: cirq.Circuit, qubits: Optional[List[cirq.LineQubit]] = None
) -> np.ndarray:
Expand Down
9 changes: 9 additions & 0 deletions cirq-core/cirq/contrib/quimb/mps_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ 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 @@ -85,6 +87,7 @@ def __init__(
seed=seed,
)

# pylint: enable=missing-raises-doc
def _create_partial_act_on_args(
self,
initial_state: Union[int, 'MPSState'],
Expand Down Expand Up @@ -206,6 +209,8 @@ def _simulator_state(self):
class MPSState(ActOnArgs):
"""A state of the MPS simulation."""

# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
@deprecated_parameter(
deadline='v0.13',
fix='No longer needed. `protocols.act_on` infers axes.',
Expand Down Expand Up @@ -274,6 +279,7 @@ 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,6 +470,8 @@ 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 Down Expand Up @@ -513,6 +521,7 @@ 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
3 changes: 3 additions & 0 deletions cirq-core/cirq/contrib/quimb/state_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ def _get_quimb_version():
QUIMB_VERSION = _get_quimb_version()


# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def circuit_to_tensors(
circuit: cirq.Circuit,
qubits: Optional[Sequence[cirq.Qid]] = None,
Expand Down Expand Up @@ -84,6 +86,7 @@ def circuit_to_tensors(
return tensors, qubit_frontier, positions


# pylint: enable=missing-raises-doc
def tensor_state_vector(
circuit: cirq.Circuit, qubits: Optional[Sequence[cirq.Qid]] = None
) -> np.ndarray:
Expand Down
9 changes: 7 additions & 2 deletions cirq-core/cirq/contrib/routing/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
}


# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def route_circuit(
circuit: circuits.Circuit,
device_graph: nx.Graph,
Expand All @@ -35,15 +37,15 @@ def route_circuit(
) -> SwapNetwork:
"""Routes a circuit on a given device.

Exactly one of algo_name and router must be specified.

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.
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.

Exactly one of algo_name and router must be specified.
"""

if any(protocols.num_qubits(op) > 2 for op in circuit.all_operations()):
Expand All @@ -59,3 +61,6 @@ 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
3 changes: 3 additions & 0 deletions cirq-core/cirq/contrib/routing/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ def ops_are_consistent_with_device_graph(
return True


# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def is_valid_routing(
circuit: circuits.Circuit,
swap_network: SwapNetwork,
Expand Down Expand Up @@ -82,6 +84,7 @@ def is_valid_routing(
raise


# pylint: enable=missing-raises-doc
def get_circuit_connectivity(circuit: 'cirq.Circuit') -> nx.Graph:
"""Return a graph of all 2q interactions in a circuit.

Expand Down
3 changes: 3 additions & 0 deletions cirq-core/cirq/devices/noise_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ class NoiseModel(metaclass=value.ABCMetaImplementAnyOneOf):
dynamically rewrite the program they are simulating.
"""

# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
@classmethod
def from_noise_model_like(cls, noise: 'cirq.NOISE_MODEL_LIKE') -> 'cirq.NoiseModel':
"""Transforms an object into a noise model if umambiguously possible.
Expand Down Expand Up @@ -72,6 +74,7 @@ def from_noise_model_like(cls, noise: 'cirq.NOISE_MODEL_LIKE') -> 'cirq.NoiseMod
'or a single qubit gate). Got {!r}'.format(noise)
)

# pylint: enable=missing-raises-doc
def is_virtual_moment(self, moment: 'cirq.Moment') -> bool:
"""Returns true iff the given moment is non-empty and all of its
operations are virtual.
Expand Down
3 changes: 3 additions & 0 deletions cirq-core/cirq/experiments/cross_entropy_benchmarking.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,8 @@ def depolarizing_model(self) -> CrossEntropyDepolarizingModel:
spam_depolarization=params[0], cycle_depolarization=params[1], covariance=covariance
)

# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def purity_depolarizing_model(self) -> CrossEntropyDepolarizingModel:
"""Fit a depolarizing error model for a cycle to purity data.

Expand Down Expand Up @@ -193,6 +195,7 @@ def purity_depolarizing_model(self) -> CrossEntropyDepolarizingModel:
spam_depolarization=params[0], cycle_depolarization=params[1], covariance=covariance
)

# pylint: enable=missing-raises-doc
@classmethod
def _from_json_dict_(cls, data, repetitions, **kwargs):
purity_data = kwargs.get('purity_data', None)
Expand Down
Loading