Skip to content

Commit

Permalink
Close matplotlib figures after testing (#4810)
Browse files Browse the repository at this point in the history
Add test fixture that cleans up any open matplotlib figures and
plug it in the tests that open new figures.
Fix RuntimeWarning: More than 20 figures have been opened.
  • Loading branch information
pavoljuhas authored Jan 8, 2022
1 parent bbd965e commit 1634589
Show file tree
Hide file tree
Showing 13 changed files with 35 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
from cirq.experiments.cross_entropy_benchmarking import CrossEntropyPair, SpecklePurityPair


@pytest.mark.usefixtures('closefigures')
def test_cross_entropy_benchmarking():
# Check that the fidelities returned from a four-qubit XEB simulation are
# close to 1 (deviations from 1 is expected due to finite number of
Expand Down
1 change: 1 addition & 0 deletions cirq-core/cirq/experiments/qubit_characterizations_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ def test_two_qubit_state_tomography():
np.testing.assert_almost_equal(act_rho_yx, tar_rho_yx, decimal=1)


@pytest.mark.usefixtures('closefigures')
def test_tomography_plot_raises_for_incorrect_number_of_axes():
simulator = sim.Simulator()
qubit = GridQubit(0, 0)
Expand Down
3 changes: 3 additions & 0 deletions cirq-core/cirq/experiments/t1_decay_experiment_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def test_init_result():
assert result.data is data


@pytest.mark.usefixtures('closefigures')
def test_plot_does_not_raise_error():
class _TimeDependentDecay(cirq.NoiseModel):
def noisy_moment(self, moment, system_qubits):
Expand Down Expand Up @@ -167,6 +168,7 @@ def test_all_off_results():
)


@pytest.mark.usefixtures('closefigures')
def test_curve_fit_plot_works():
good_fit = cirq.experiments.T1DecayResult(
data=pd.DataFrame(
Expand All @@ -184,6 +186,7 @@ def test_curve_fit_plot_works():
good_fit.plot(include_fit=True)


@pytest.mark.usefixtures('closefigures')
def test_curve_fit_plot_warning():
bad_fit = cirq.experiments.T1DecayResult(
data=pd.DataFrame(
Expand Down
1 change: 1 addition & 0 deletions cirq-core/cirq/experiments/t2_decay_experiment_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ def test_init_t2_decay_result():
cirq.experiments.T2DecayResult(x_data, bad_data)


@pytest.mark.usefixtures('closefigures')
def test_plot_does_not_raise_error():
class _TimeDependentDecay(cirq.NoiseModel):
def noisy_moment(self, moment, system_qubits):
Expand Down
2 changes: 2 additions & 0 deletions cirq-core/cirq/linalg/decompositions_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ def test_kak_vector_empty():
assert len(cirq.kak_vector([])) == 0


@pytest.mark.usefixtures('closefigures')
def test_kak_plot_empty():
cirq.scatter_plot_normalized_kak_interaction_coefficients([])

Expand Down Expand Up @@ -553,6 +554,7 @@ def test_axis_angle_init():
cirq.AxisAngleDecomposition(angle=1, axis=(0, 0.5, 0), global_phase=1)


@pytest.mark.usefixtures('closefigures')
def test_scatter_plot_normalized_kak_interaction_coefficients():
a, b = cirq.LineQubit.range(2)
data = [
Expand Down
4 changes: 4 additions & 0 deletions cirq-core/cirq/vis/density_matrix_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from cirq.vis.density_matrix import _plot_element_of_density_matrix


@pytest.mark.usefixtures('closefigures')
@pytest.mark.parametrize('show_text', [True, False])
@pytest.mark.parametrize('size', [2, 4, 8, 16])
def test_density_matrix_plotter(size, show_text):
Expand All @@ -47,6 +48,7 @@ def test_density_matrix_plotter(size, show_text):
)


@pytest.mark.usefixtures('closefigures')
@pytest.mark.parametrize('show_text', [True, False])
@pytest.mark.parametrize('size', [2, 4, 8, 16])
def test_density_matrix_circle_rectangle_sizes(size, show_text):
Expand Down Expand Up @@ -89,6 +91,7 @@ def test_density_matrix_circle_rectangle_sizes(size, show_text):
)


@pytest.mark.usefixtures('closefigures')
@pytest.mark.parametrize('show_text', [True, False])
@pytest.mark.parametrize('size', [2, 4, 8, 16])
def test_density_matrix_sizes_upper_bounds(size, show_text):
Expand All @@ -112,6 +115,7 @@ def test_density_matrix_sizes_upper_bounds(size, show_text):
assert max_radius * 2 <= 1.0, "Some circle is exceeding out of it's cell size"


@pytest.mark.usefixtures('closefigures')
@pytest.mark.parametrize('show_rect', [True, False])
@pytest.mark.parametrize('value', [0.0, 1.0, 0.5 + 0.3j, 0.2 + 0.1j, 0.5 + 0.5j])
def test_density_element_plot(value, show_rect):
Expand Down
1 change: 1 addition & 0 deletions cirq-core/cirq/vis/heatmap_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,7 @@ def test_colorbar(ax, position, size, pad):
plt.close(fig2)


@pytest.mark.usefixtures('closefigures')
def test_plot_updates_local_config():
value_map_2d = {
(grid_qubit.GridQubit(3, 2), grid_qubit.GridQubit(4, 2)): 0.004619111460557768,
Expand Down
2 changes: 2 additions & 0 deletions cirq-core/cirq/vis/histogram_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from cirq.vis import integrated_histogram


@pytest.mark.usefixtures('closefigures')
@pytest.mark.parametrize('data', [range(10), {f'key_{i}': i for i in range(10)}])
def test_integrated_histogram(data):
ax = integrated_histogram(
Expand All @@ -39,6 +40,7 @@ def test_integrated_histogram(data):
assert line.get_color() == 'r'


@pytest.mark.usefixtures('closefigures')
def test_multiple_plots():
_, ax = plt.subplots(1, 1)
n = 53
Expand Down
3 changes: 3 additions & 0 deletions cirq-core/cirq/vis/state_histogram_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import numpy as np
from matplotlib import pyplot as plt
import matplotlib as mpl
import pytest

import cirq
from cirq.devices import GridQubit
Expand Down Expand Up @@ -64,6 +65,7 @@ def test_get_state_histogram_multi_2():
np.testing.assert_equal(values_to_plot, expected_values)


@pytest.mark.usefixtures('closefigures')
def test_plot_state_histogram_result():
qubits = cirq.LineQubit.range(4)
c = cirq.Circuit(
Expand All @@ -80,6 +82,7 @@ def test_plot_state_histogram_result():
assert str(r1) == str(r2)


@pytest.mark.usefixtures('closefigures')
def test_plot_state_histogram_collection():
qubits = cirq.LineQubit.range(4)
c = cirq.Circuit(
Expand Down
2 changes: 2 additions & 0 deletions cirq-google/cirq_google/engine/calibration_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ def test_calibration_heatmap():
cg.Calibration(multi_qubit_data).heatmap('multi_value')


@pytest.mark.usefixtures('closefigures')
def test_calibration_plot_histograms():
calibration = cg.Calibration(_CALIBRATION_DATA)
_, ax = mpl.pyplot.subplots(1, 1)
Expand All @@ -208,6 +209,7 @@ def test_calibration_plot_histograms():
cg.Calibration(multi_qubit_data).plot_histograms('multi_value')


@pytest.mark.usefixtures('closefigures')
def test_calibration_plot():
calibration = cg.Calibration(_CALIBRATION_DATA)
_, axs = calibration.plot('two_qubit_xeb')
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
# pylint: disable=wrong-or-nonexistent-copyright-notice
from matplotlib import pyplot as plt
import pytest

from cirq_google.optimizers.two_qubit_gates import example


@pytest.mark.usefixtures('closefigures')
def test_gate_compilation_example():
plt.switch_backend('agg')
example.main(samples=10, max_infidelity=0.3)
10 changes: 10 additions & 0 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
import os
import random

import pytest

# allow CI execution of isolated_packages_test.py without numpy
try:
import numpy
Expand Down Expand Up @@ -47,6 +49,14 @@ def pytest_addoption(parser):
)


@pytest.fixture
def closefigures():
import matplotlib.pyplot as plt

yield
plt.close('all')


# skip seeding for unset or empty CIRQ_TESTING_RANDOM_SEED
if numpy is not None and os.environ.get('CIRQ_TESTING_RANDOM_SEED'):
rngseed = int(os.environ['CIRQ_TESTING_RANDOM_SEED'])
Expand Down
3 changes: 3 additions & 0 deletions examples/examples_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ def test_example_runs_phase_estimator():
examples.phase_estimator.main(qnums=(2,), repetitions=2)


@pytest.mark.usefixtures('closefigures')
def test_example_heatmaps():
pytest.importorskip("cirq_google")
plt.switch_backend('agg')
Expand All @@ -114,6 +115,7 @@ def test_example_runs_hhl():
examples.hhl.main()


@pytest.mark.usefixtures('closefigures')
def test_example_runs_qubit_characterizations():
examples.qubit_characterizations_example.main(
minimum_cliffords=2, maximum_cliffords=6, cliffords_step=2
Expand All @@ -124,6 +126,7 @@ def test_example_swap_networks():
examples.swap_networks.main()


@pytest.mark.usefixtures('closefigures')
def test_example_cross_entropy_benchmarking():
examples.cross_entropy_benchmarking_example.main(
repetitions=10, num_circuits=2, cycles=[2, 3, 4]
Expand Down

0 comments on commit 1634589

Please sign in to comment.