Skip to content

Commit c536026

Browse files
wshankscoruscating
andauthored
Address several warnings raised during tests (#1351)
This change rolls together several small changes to avoid warnings generated when running the tests. Here is a summary of the changes: * Update use of `datetime.utcnow()` deprecated in Python 3.12 * Concatenate pandas dataframes more carefully to avoid `FutureWarning` when concatenating an empty dataframe (see pandas-dev/pandas#52532). * Adjust plotter tests to avoid warnings + Use supported options rather than arbitrary options to avoid unexpected option warning + Catch expected warning when passing an untrained discriminator to `IQPlotter` * Move the setting of the axis scale earlier in the logic of `MplDrawer.format_canvas`. `format_canvas` queries the limits of each `axes` object and uses those values. When no data set on a set of axes (an odd edge case), the default values depend on the scale (because the minimum for linear is 0 but for log is 0.1), so the scale needs to be set first. * Remove transpile options from `FineDragCal` (`_transpiled_circuits` for `BaseCalibrationExperiment` warns about and ignores transpile options) * Replace `isinstance` checks with `pulse_type` checks for calibration tests checking pulse shape * Replace `qiskit.Aer` usage with `qiskit_aer` * Set tolerance on cvxpy test to larger value, close to the tolerance achieved in practice. The routine was maxing out its iterations without achieving tolerance but still producing a close enough result for the test to pass. Increasing the tolerance avoids the max iterations warning and makes the test faster. * Rename `TestLibrary` to `MutableTestLibrary`. The class name starting with `Test*` causes pytest to warn about the class looking like a class holding test cases. pytest is not the main way we run the tests but it still seems best to avoid confusion between test case classes and test helper classes. * Catch warnings about insufficient trials in `QuantumVolume` tests using small numbers of trials. * Catch user and deprecation warnings about calibration saving and loading to csv files. * Convert existing calibration saving and loading tests from json to csv, leaving basic coverage of csv saving. A bug was found with json saving, resulting in one test being marked as an expected failure. * Set data on the `ExperimentData` for `TestFramework.test_run_analysis_experiment_data_pickle_roundtrip` to avoid a warning about an empty experiment data object. Other cases of this warning were addressed in 729014b but this test case was added afterward in a6c9e53. In order to avoid warnings creeping in in the future, this change also makes any warnings emitted by qiskit-experiments code be treated as exceptions by the tests (with an exception for `ScatterTable` methods for which it is planned to remove the deprecation). Any expected warnings in tests can be handled by using `assertWarns` or `warnings.catch_warnings`. As all the changes relate to tests (except the `FineDragCal` one which is a non-functional change to avoid a warning), no release note was added. --------- Co-authored-by: Helena Zhang <[email protected]>
1 parent bf980b4 commit c536026

File tree

15 files changed

+214
-119
lines changed

15 files changed

+214
-119
lines changed

qiskit_experiments/library/calibration/fine_drag_cal.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,6 @@ def __init__(
6666
auto_update=auto_update,
6767
)
6868

69-
self.set_transpile_options(basis_gates=["sx", schedule_name, "rz"])
70-
7169
@classmethod
7270
def _default_experiment_options(cls) -> Options:
7371
"""Default experiment options.

qiskit_experiments/test/fake_service.py

Lines changed: 60 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -111,33 +111,38 @@ def create_experiment(
111111
# backend - the query methods `experiment` and `experiments` are supposed to return an
112112
# an instantiated backend object, and not only the backend name. We assume that the fake
113113
# service works with the fake backend (class FakeBackend).
114-
self.exps = pd.concat(
114+
row = pd.DataFrame(
115115
[
116-
self.exps,
117-
pd.DataFrame(
118-
[
119-
{
120-
"experiment_type": experiment_type,
121-
"experiment_id": experiment_id,
122-
"parent_id": parent_id,
123-
"backend_name": backend_name,
124-
"metadata": metadata,
125-
"job_ids": job_ids,
126-
"tags": tags,
127-
"notes": notes,
128-
"share_level": kwargs.get("share_level", None),
129-
"device_components": [],
130-
"start_datetime": datetime(2022, 1, 1)
131-
+ timedelta(hours=len(self.exps)),
132-
"figure_names": [],
133-
"backend": FakeBackend(backend_name=backend_name),
134-
}
135-
],
136-
columns=self.exps.columns,
137-
),
116+
{
117+
"experiment_type": experiment_type,
118+
"experiment_id": experiment_id,
119+
"parent_id": parent_id,
120+
"backend_name": backend_name,
121+
"metadata": metadata,
122+
"job_ids": job_ids,
123+
"tags": tags,
124+
"notes": notes,
125+
"share_level": kwargs.get("share_level", None),
126+
"device_components": [],
127+
"start_datetime": datetime(2022, 1, 1) + timedelta(hours=len(self.exps)),
128+
"figure_names": [],
129+
"backend": FakeBackend(backend_name=backend_name),
130+
}
138131
],
139-
ignore_index=True,
132+
columns=self.exps.columns,
140133
)
134+
if len(self.exps) > 0:
135+
self.exps = pd.concat(
136+
[
137+
self.exps,
138+
row,
139+
],
140+
ignore_index=True,
141+
)
142+
else:
143+
# Avoid the FutureWarning on concatenating empty DataFrames
144+
# introduced in https://github.com/pandas-dev/pandas/pull/52532
145+
self.exps = row
141146

142147
return experiment_id
143148

@@ -293,35 +298,39 @@ def create_analysis_result(
293298
# `IBMExperimentService.create_analysis_result`. Since `DbExperimentData` does not set it
294299
# via kwargs (as it does with chisq), the user cannot control the time and the service
295300
# alone decides about it. Here we've chosen to set the start date of the experiment.
296-
self.results = pd.concat(
301+
row = pd.DataFrame(
297302
[
298-
self.results,
299-
pd.DataFrame(
300-
[
301-
{
302-
"result_data": result_data,
303-
"result_id": result_id,
304-
"result_type": result_type,
305-
"device_components": device_components,
306-
"experiment_id": experiment_id,
307-
"quality": quality,
308-
"verified": verified,
309-
"tags": tags,
310-
"backend_name": self.exps.loc[self.exps.experiment_id == experiment_id]
311-
.iloc[0]
312-
.backend_name,
313-
"chisq": kwargs.get("chisq", None),
314-
"creation_datetime": self.exps.loc[
315-
self.exps.experiment_id == experiment_id
316-
]
317-
.iloc[0]
318-
.start_datetime,
319-
}
320-
]
321-
),
322-
],
323-
ignore_index=True,
303+
{
304+
"result_data": result_data,
305+
"result_id": result_id,
306+
"result_type": result_type,
307+
"device_components": device_components,
308+
"experiment_id": experiment_id,
309+
"quality": quality,
310+
"verified": verified,
311+
"tags": tags,
312+
"backend_name": self.exps.loc[self.exps.experiment_id == experiment_id]
313+
.iloc[0]
314+
.backend_name,
315+
"chisq": kwargs.get("chisq", None),
316+
"creation_datetime": self.exps.loc[self.exps.experiment_id == experiment_id]
317+
.iloc[0]
318+
.start_datetime,
319+
}
320+
]
324321
)
322+
if len(self.results) > 0:
323+
self.results = pd.concat(
324+
[
325+
self.results,
326+
row,
327+
],
328+
ignore_index=True,
329+
)
330+
else:
331+
# Avoid the FutureWarning on concatenating empty DataFrames
332+
# introduced in https://github.com/pandas-dev/pandas/pull/52532
333+
self.results = row
325334

326335
# a helper method for updating the experiment's device components, see usage below
327336
def add_new_components(expcomps):

qiskit_experiments/test/pulse_backend.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ def __init__(
9696
None,
9797
name="PulseBackendV2",
9898
description="A PulseBackend simulator",
99-
online_date=datetime.datetime.utcnow(),
99+
online_date=datetime.datetime.now(datetime.timezone.utc),
100100
backend_version="0.0.1",
101101
)
102102

qiskit_experiments/visualization/drawers/mpl_drawer.py

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,31 @@ def format_canvas(self):
147147
else:
148148
all_axes = [self._axis]
149149

150+
# Set axes scale. This needs to be done before anything tries to work with
151+
# the axis limits because if no limits or data are set explicitly the
152+
# default limits depend on the scale method (for example, the minimum
153+
# value is 0 for linear scaling but not for log scaling).
154+
def signed_sqrt(x):
155+
return np.sign(x) * np.sqrt(abs(x))
156+
157+
def signed_square(x):
158+
return np.sign(x) * x**2
159+
160+
for ax_type in ("x", "y"):
161+
for sub_ax in all_axes:
162+
scale = self.figure_options.get(f"{ax_type}scale")
163+
if ax_type == "x":
164+
mpl_setscale = sub_ax.set_xscale
165+
else:
166+
mpl_setscale = sub_ax.set_yscale
167+
168+
# Apply non linear axis spacing
169+
if scale is not None:
170+
if scale == "quadratic":
171+
mpl_setscale("function", functions=(signed_square, signed_sqrt))
172+
else:
173+
mpl_setscale(scale)
174+
150175
# Get axis formatter from drawing options
151176
formatter_opts = {}
152177
for ax_type in ("x", "y"):
@@ -181,12 +206,6 @@ def format_canvas(self):
181206
"max_ax_vals": max_vals,
182207
}
183208

184-
def signed_sqrt(x):
185-
return np.sign(x) * np.sqrt(abs(x))
186-
187-
def signed_square(x):
188-
return np.sign(x) * x**2
189-
190209
for i, sub_ax in enumerate(all_axes):
191210
# Add data labels if there are multiple labels registered per sub_ax.
192211
_, labels = sub_ax.get_legend_handles_labels()
@@ -197,18 +216,15 @@ def signed_square(x):
197216
limit = formatter_opts[ax_type]["limit"][i]
198217
unit = formatter_opts[ax_type]["unit"][i]
199218
unit_scale = formatter_opts[ax_type]["unit_scale"][i]
200-
scale = self.figure_options.get(f"{ax_type}scale")
201219
min_ax_vals = formatter_opts[ax_type]["min_ax_vals"]
202220
max_ax_vals = formatter_opts[ax_type]["max_ax_vals"]
203221
share_axis = self.figure_options.get(f"share{ax_type}")
204222

205223
if ax_type == "x":
206-
mpl_setscale = sub_ax.set_xscale
207224
mpl_axis_obj = getattr(sub_ax, "xaxis")
208225
mpl_setlimit = sub_ax.set_xlim
209226
mpl_share = sub_ax.sharex
210227
else:
211-
mpl_setscale = sub_ax.set_yscale
212228
mpl_axis_obj = getattr(sub_ax, "yaxis")
213229
mpl_setlimit = sub_ax.set_ylim
214230
mpl_share = sub_ax.sharey
@@ -219,13 +235,6 @@ def signed_square(x):
219235
else:
220236
limit = min_ax_vals[i], max_ax_vals[i]
221237

222-
# Apply non linear axis spacing
223-
if scale is not None:
224-
if scale == "quadratic":
225-
mpl_setscale("function", functions=(signed_square, signed_sqrt))
226-
else:
227-
mpl_setscale(scale)
228-
229238
# Create formatter for axis tick label notation
230239
if unit and unit_scale:
231240
# If value is specified, automatically scale axis magnitude

test/base.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,26 @@ def setUpClass(cls):
9999
super().setUpClass()
100100

101101
warnings.filterwarnings("error", category=DeprecationWarning)
102+
# Tests should not generate any warnings unless testing those
103+
# warnings. In that case, the test should catch the warning
104+
# assertWarns or warnings.catch_warnings.
105+
warnings.filterwarnings("error", module="qiskit_experiments")
106+
# Ideally, changes introducing pending deprecations should include
107+
# alternative code paths and not need to generate warnings in the
108+
# tests but until this exception is necessary until the use of the
109+
# deprecated ScatterTable methods are removed.
110+
warnings.filterwarnings(
111+
"default",
112+
module="qiskit_experiments",
113+
message=".*Curve data uses dataframe representation.*",
114+
category=PendingDeprecationWarning,
115+
)
116+
warnings.filterwarnings(
117+
"default",
118+
module="qiskit_experiments",
119+
message=".*The curve data representation is replaced with dataframe format.*",
120+
category=PendingDeprecationWarning,
121+
)
102122

103123
# Some functionality may be deprecated in Qiskit Experiments. If
104124
# the deprecation warnings aren't filtered, the tests will fail as

0 commit comments

Comments
 (0)