Skip to content

Commit

Permalink
Even more documentation lint (#4662)
Browse files Browse the repository at this point in the history
The vacuum marches on.
  • Loading branch information
dabacon authored Nov 11, 2021
1 parent ca05b0e commit dcaacd6
Show file tree
Hide file tree
Showing 10 changed files with 46 additions and 53 deletions.
6 changes: 3 additions & 3 deletions cirq-core/cirq/contrib/routing/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,6 @@ 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 All @@ -73,6 +71,9 @@ def is_valid_routing(
`operator.eq`.
can_reorder: A predicate that determines if two operations may be
reordered.
Raises:
ValueError: If equals operator or can_reorder throws a ValueError.
"""
circuit_dag = circuits.CircuitDag.from_circuit(circuit, can_reorder=can_reorder)
logical_operations = swap_network.get_logical_operations()
Expand All @@ -84,7 +85,6 @@ 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
25 changes: 16 additions & 9 deletions cirq-core/cirq/experiments/t2_decay_experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ class ExperimentType(enum.Enum):
_T2_COLUMNS = ['delay_ns', 0, 1]


# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def t2_decay(
sampler: 'cirq.Sampler',
*,
Expand Down Expand Up @@ -123,8 +121,14 @@ def t2_decay(
from min_delay to max_delay with linear steps.
num_pulses: For CPMG, a list of the number of pulses to use.
If multiple pulses are specified, each will be swept on.
Returns:
A T2DecayResult object that stores and can plot the data.
Raises:
ValueError: If invalid parameters are specified, negative repetitions, max
less than min durations, negative min delays, or an unsupported experiment
configuraiton.
"""
min_delay_dur = value.Duration(min_delay)
max_delay_dur = value.Duration(max_delay)
Expand Down Expand Up @@ -220,7 +224,6 @@ def t2_decay(
return T2DecayResult(x_basis_tabulation, y_basis_tabulation)


# pylint: enable=missing-raises-doc
def _create_tabulation(measurements: pd.DataFrame) -> pd.DataFrame:
"""Returns a sum of 0 and 1 results per index from a list of measurements."""
if 'num_pulses' in measurements.columns:
Expand Down Expand Up @@ -280,15 +283,17 @@ class T2DecayResult:
the data to calculate estimated T2 phase decay times.
"""

# TODO(#3388) Add documentation for Args.
# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-param-doc,missing-raises-doc
def __init__(self, x_basis_data: pd.DataFrame, y_basis_data: pd.DataFrame):
"""Inits T2DecayResult.
Args:
data: A data frame with three columns:
delay_ns, false_count, true_count.
x_basis_data: Data frame in x basis with three columns: delay_ns,
false_count, and true_count.
y_basis_data: Data frame in y basis with three columns: delay_ns,
false_count, and true_count.
Raises:
ValueError: If the supplied data does not have the proper columns.
"""
x_cols = list(x_basis_data.columns)
y_cols = list(y_basis_data.columns)
Expand All @@ -307,14 +312,16 @@ def __init__(self, x_basis_data: pd.DataFrame, y_basis_data: pd.DataFrame):
self._expectation_pauli_x = self._expectation(x_basis_data)
self._expectation_pauli_y = self._expectation(y_basis_data)

# pylint: enable=missing-param-doc,missing-raises-doc
def _expectation(self, data: pd.DataFrame) -> pd.DataFrame:
"""Calculates the expected value of the Pauli operator.
Assuming that the data is measured in the Pauli basis of the operator,
then the expectation of the Pauli operator would be +1 if the
measurement is all ones and -1 if the measurement is all zeros.
Args:
data: measurement data to compute the expecation for.
Returns:
Data frame with columns 'delay_ns', 'num_pulses' and 'value'
The num_pulses column will only exist if multiple pulses
Expand Down
7 changes: 1 addition & 6 deletions cirq-core/cirq/ion/ion_decomposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.

# TODO(#3388) Add summary line to docstring.
# pylint: disable=docstring-first-line-empty
"""
Utility methods related to optimizing quantum circuits
using native iontrap operations.
"""Utility methods related to optimizing quantum circuits using native iontrap operations.
Gate compilation methods implemented here are following the paper below:
'Basic circuit compilation techniques for an ion-trap quantum machine'
arXiv:1603.07678
"""
# pylint: enable=docstring-first-line-empty

from typing import Iterable, List, Optional, cast, Tuple, TYPE_CHECKING

Expand Down
6 changes: 3 additions & 3 deletions cirq-core/cirq/study/sweepable.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,6 @@ def to_sweeps(sweepable: Sweepable) -> List[Sweep]:
raise TypeError(f'Unrecognized sweepable type: {type(sweepable)}.\nsweepable: {sweepable}')


# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def to_sweep(
sweep_or_resolver_list: Union[
'Sweep', ParamResolverOrSimilarType, Iterable[ParamResolverOrSimilarType]
Expand All @@ -88,6 +86,9 @@ def to_sweep(
Returns:
A sweep equal to or containing the argument.
Raises:
TypeError: If an unsupport type was supplied.
"""
if isinstance(sweep_or_resolver_list, Sweep):
return sweep_or_resolver_list
Expand All @@ -100,7 +101,6 @@ def to_sweep(
raise TypeError(f'Unexpected sweep-like value: {sweep_or_resolver_list}')


# pylint: enable=missing-raises-doc
def _resolver_to_sweep(resolver: ParamResolver) -> Sweep:
params = resolver.param_dict
if not params:
Expand Down
5 changes: 3 additions & 2 deletions cirq-core/cirq/testing/logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
from typing import ContextManager, List, Optional


# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def assert_logs(
*matches: str,
count: Optional[int] = 1,
Expand Down Expand Up @@ -59,6 +57,9 @@ def assert_logs(
A ContextManager that can be entered into which captures the logs
for code executed within the entered context. This ContextManager
checks that the asserts for the logs are true on exit.
Raises:
ValueError: If `min_level` is greater than `max_level`.
"""
if min_level > max_level:
raise ValueError("min_level should be less than or equal to max_level")
Expand Down
6 changes: 3 additions & 3 deletions cirq-core/cirq/value/angle.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@
from cirq.value import type_alias


# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def chosen_angle_to_half_turns(
half_turns: Optional[type_alias.TParamVal] = None,
rads: Optional[float] = None,
Expand All @@ -39,6 +37,9 @@ def chosen_angle_to_half_turns(
Returns:
A number of half turns.
Raises:
ValueError: If more than one of `half_turn`, `rads`, or `degs` is given.
"""

if len([1 for e in [half_turns, rads, degs] if e is not None]) > 1:
Expand All @@ -56,7 +57,6 @@ def chosen_angle_to_half_turns(
return default


# pylint: enable=missing-raises-doc
def chosen_angle_to_canonical_half_turns(
half_turns: Optional[type_alias.TParamVal] = None,
rads: Optional[float] = None,
Expand Down
24 changes: 10 additions & 14 deletions cirq-core/cirq/work/observable_measurement_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,6 @@ def _setting_to_z_observable(setting: InitObsSetting):
)


# TODO(#3388) Add documentation for Args.
# pylint: disable=missing-param-doc
class BitstringAccumulator:
"""A mutable container of bitstrings and associated metadata populated
during a `measure_observables` run.
Expand Down Expand Up @@ -189,15 +187,15 @@ class BitstringAccumulator:
for the settings in `simul_settings`.
qubit_to_index: A mapping from qubits to contiguous indices starting
from zero. This allows us to store bitstrings as a 2d numpy array.
bitstrings: The bitstrings to record.
chunksizes: This class accumulates bitstrings from potentially several
"chunked" processor runs. Each chunk has a certain number of
repetitions, recorded in this array. This theoretically
allows you to re-split up the bitstring array should the need
arise. The total number of repetitions is the sum of this 1d array.
timestamps: We record a timestamp for each request/chunk. This
1d array will have the same length as `chunksizes`.
readout_calibration:
The result of `calibrate_readout_error`. When requesting
readout_calibration: The result of `calibrate_readout_error`. When requesting
means and variances, if this is not `None`, we will use the
calibrated value to correct the requested quantity. This is a
`BitstringAccumulator` containing the results of measuring Z
Expand Down Expand Up @@ -399,8 +397,6 @@ def __str__(self):
s += '\n'.join(' ' + self.summary_string(setting) for setting in self._simul_settings)
return s

# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def covariance(self, *, atol=1e-8) -> np.ndarray:
"""Compute the covariance matrix for the estimators of all settings.
Expand All @@ -410,6 +406,9 @@ def covariance(self, *, atol=1e-8) -> np.ndarray:
Args:
atol: The absolute tolerance for asserting coefficients are real.
Raises:
ValueError: If there are no measurements.
"""
if len(self.bitstrings) == 0:
raise ValueError("No measurements")
Expand All @@ -434,7 +433,6 @@ def covariance(self, *, atol=1e-8) -> np.ndarray:
cov = np.cov(all_obs_vals, ddof=1) / all_obs_vals.shape[1]
return cov

# pylint: enable=missing-raises-doc
def _validate_setting(self, setting: InitObsSetting, what: str):
mws = _max_weight_state([self.max_setting.init_state, setting.init_state])
mwo = _max_weight_observable([self.max_setting.observable, setting.observable])
Expand All @@ -444,8 +442,6 @@ def _validate_setting(self, setting: InitObsSetting, what: str):
f"with this BitstringAccumulator's meas_spec."
)

# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def variance(self, setting: InitObsSetting, *, atol: float = 1e-8):
"""Compute the variance of the estimators of the given setting.
Expand All @@ -459,8 +455,11 @@ def variance(self, setting: InitObsSetting, *, atol: float = 1e-8):
for `np.var`.
Args:
setting: The setting
setting: The initial state and observable.
atol: The absolute tolerance for asserting coefficients are real.
Raises:
ValueError: If there were no measurements.
"""
if len(self.bitstrings) == 0:
raise ValueError("No measurements")
Expand Down Expand Up @@ -491,7 +490,6 @@ def variance(self, setting: InitObsSetting, *, atol: float = 1e-8):

return var

# pylint: enable=missing-raises-doc
def stderr(self, setting: InitObsSetting, *, atol: float = 1e-8):
"""The standard error of the estimators for `setting`."""
return np.sqrt(self.variance(setting, atol=atol))
Expand Down Expand Up @@ -520,12 +518,10 @@ def mean(self, setting: InitObsSetting, *, atol: float = 1e-8):
return mean


# pylint: enable=missing-param-doc
def flatten_grouped_results(
grouped_results: List[BitstringAccumulator],
) -> List[ObservableMeasuredResult]:
"""Flatten results from a collection of BitstringAccumulators into a list
of ObservableMeasuredResult.
"""Flatten a collection of BitstringAccumulators into a list of ObservableMeasuredResult.
Raw results are contained in BitstringAccumulator which contains
structure related to how the observables were measured (i.e. their
Expand Down
6 changes: 3 additions & 3 deletions cirq-google/cirq_google/api/v2/sweeps.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@
from cirq_google.api.v2 import run_context_pb2


# TODO(#3388) Add documentation for Raises.
# pylint: disable=missing-raises-doc
def sweep_to_proto(
sweep: cirq.Sweep,
*,
Expand All @@ -34,6 +32,9 @@ def sweep_to_proto(
Returns:
Populated sweep protobuf message.
Raises:
ValueError: If the conversion cannot be completed successfully.
"""
if out is None:
out = run_context_pb2.Sweep()
Expand Down Expand Up @@ -70,7 +71,6 @@ def sweep_to_proto(
return out


# pylint: enable=missing-raises-doc
def sweep_from_proto(msg: run_context_pb2.Sweep) -> cirq.Sweep:
"""Creates a Sweep from a v2 protobuf message."""
which = msg.WhichOneof('sweep')
Expand Down
8 changes: 2 additions & 6 deletions cirq-pasqal/cirq_pasqal/pasqal_sampler_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,11 @@ def test_pasqal_circuit_init():
assert moment1 == moment2


# TODO(#3388) Add summary line to docstring.
# pylint: disable=docstring-first-line-empty
@patch('cirq_pasqal.pasqal_sampler.requests.get')
@patch('cirq_pasqal.pasqal_sampler.requests.post')
def test_run_sweep(mock_post, mock_get):
"""
"""Test running a sweep.
Encodes a random binary number in the qubits, sweeps between odd and even
without noise and checks if the results match.
"""
Expand Down Expand Up @@ -103,6 +102,3 @@ def test_run_sweep(mock_post, mock_get):
assert cirq.read_json(json_text=submitted_json) == ex_circuit_odd
assert mock_post.call_count == 2
assert data[1] == ex_circuit_odd


# pylint: enable=docstring-first-line-empty
6 changes: 2 additions & 4 deletions examples/bell_inequality.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# pylint: disable=wrong-or-nonexistent-copyright-notice
# TODO(#3388) Add summary line to docstring.
# pylint: disable=docstring-first-line-empty
"""
"""An example demonstrating Bell's theorem.
Bell's theorem or inequality proves that entanglement based
observations can't be reproduced with any local realist theory [1].
Expand Down Expand Up @@ -56,7 +55,6 @@
11111_11111_11___11111_111_111_11_111111111_1111111_111_1111111111111111111
Win rate: 84.0%
"""
# pylint: enable=docstring-first-line-empty

import numpy as np

Expand Down

0 comments on commit dcaacd6

Please sign in to comment.