code: """ Test cases for .hist method """
  
  import numpy as np
  import pytest
  
  import pandas.util._test_decorators as td
  
  from pandas import DataFrame, Index, Series, to_datetime
  import pandas._testing as tm
  from pandas.tests.plotting.common import TestPlotBase, _check_plot_works
  
  pytestmark = pytest.mark.slow
  
  
  @td.skip_if_no_mpl
  class TestSeriesPlots(TestPlotBase):
      def setup_method(self, method):
          TestPlotBase.setup_method(self, method)
          import matplotlib as mpl
  
          mpl.rcdefaults()
  
          self.ts = tm.makeTimeSeries()
          self.ts.name = "ts"
  
      def test_hist_legacy(self):
          _check_plot_works(self.ts.hist)
          _check_plot_works(self.ts.hist, grid=False)
          _check_plot_works(self.ts.hist, figsize=(8, 10))
          # _check_plot_works adds an ax so catch warning. see GH #13188
          with tm.assert_produces_warning(UserWarning):
              _check_plot_works(self.ts.hist, by=self.ts.index.month)
          with tm.assert_produces_warning(UserWarning):
              _check_plot_works(self.ts.hist, by=self.ts.index.month, bins=5)
  
          fig, ax = self.plt.subplots(1, 1)
          _check_plot_works(self.ts.hist, ax=ax)
          _check_plot_works(self.ts.hist, ax=ax, figure=fig)
          _check_plot_works(self.ts.hist, figure=fig)
          tm.close()
  
          fig, (ax1, ax2) = self.plt.subplots(1, 2)
          _check_plot_works(self.ts.hist, figure=fig, ax=ax1)
          _check_plot_works(self.ts.hist, figure=fig, ax=ax2)
  
          with pytest.raises(ValueError):
              self.ts.hist(by=self.ts.index, figure=fig)
  
      def test_hist_bins_legacy(self):
          df = DataFrame(np.random.randn(10, 2))
          ax = df.hist(bins=2)[0][0]
          assert len(ax.patches) == 2
  
      def test_hist_layout(self):
          df = self.hist_df
          with pytest.raises(ValueError):
              df.height.hist(layout=(1, 1))
  
          with pytest.raises(ValueError):
              df.height.hist(layout=[1, 1])
  
      def test_hist_layout_with_by(self):
          df = self.hist_df
  
          # _check_plot_works adds an `ax` kwarg to the method call
          # so we get a warning about an axis being cleared, even
          # though we don't explicing pass one, see GH #13188
          with tm.assert_produces_warning(UserWarning):
              axes = _check_plot_works(df.height.hist, by=df.gender, layout=(2, 1))
          self._check_axes_shape(axes, axes_num=2, layout=(2, 1))
  
          with tm.assert_produces_warning(UserWarning):
              axes = _check_plot_works(df.height.hist, by=df.gender, layout=(3, -1))
          self._check_axes_shape(axes, axes_num=2, layout=(3, 1))
  
          with tm.assert_produces_warning(UserWarning):
              axes = _check_plot_works(df.height.hist, by=df.category, layout=(4, 1))
          self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
  
          with tm.assert_produces_warning(UserWarning):
              axes = _check_plot_works(df.height.hist, by=df.category, layout=(2, -1))
          self._check_axes_shape(axes, axes_num=4, layout=(2, 2))
  
          with tm.assert_produces_warning(UserWarning):
              axes = _check_plot_works(df.height.hist, by=df.category, layout=(3, -1))
          self._check_axes_shape(axes, axes_num=4, layout=(3, 2))
  
          with tm.assert_produces_warning(UserWarning):
              axes = _check_plot_works(df.height.hist, by=df.category, layout=(-1, 4))
          self._check_axes_shape(axes, axes_num=4, layout=(1, 4))
  
          with tm.assert_produces_warning(UserWarning):
              axes = _check_plot_works(df.height.hist, by=df.classroom, layout=(2, 2))
          self._check_axes_shape(axes, axes_num=3, layout=(2, 2))
  
          axes = df.height.hist(by=df.category, layout=(4, 2), figsize=(12, 7))
          self._check_axes_shape(axes, axes_num=4, layout=(4, 2), figsize=(12, 7))
  
      def test_hist_no_overlap(self):
          from matplotlib.pyplot import gcf, subplot
  
          x = Series(np.random.randn(2))
          y = Series(np.random.randn(2))
          subplot(121)
          x.hist()
          subplot(122)
          y.hist()
          fig = gcf()
          axes = fig.axes
          assert len(axes) == 2
  
      def test_hist_by_no_extra_plots(self):
          df = self.hist_df
          axes = df.height.hist(by=df.gender)  # noqa
          assert len(self.plt.get_fignums()) == 1
  
      def test_plot_fails_when_ax_differs_from_figure(self):
          from pylab import figure
  
          fig1 = figure()
          fig2 = figure()
          ax1 = fig1.add_subplot(111)
          with pytest.raises(AssertionError):
              self.ts.hist(ax=ax1, figure=fig2)
  
      @pytest.mark.parametrize(
          "histtype, expected",
          [
              ("bar", True),
              ("barstacked", True),
              ("step", False),
              ("stepfilled", True),
          ],
      )
      def test_histtype_argument(self, histtype, expected):
          # GH23992 Verify functioning of histtype argument
          ser = Series(np.random.randint(1, 10))
          ax = ser.hist(histtype=histtype)
          self._check_patches_all_filled(ax, filled=expected)
  
      @pytest.mark.parametrize(
          "by, expected_axes_num, expected_layout", [(None, 1, (1, 1)), ("b", 2, (1, 2))]
      )
      def test_hist_with_legend(self, by, expected_axes_num, expected_layout):
          # GH 6279 - Series histogram can have a legend
          index = 15 * ["1"] + 15 * ["2"]
          s = Series(np.random.randn(30), index=index, name="a")
          s.index.name = "b"
  
          # Use default_axes=True when plotting method generate subplots itself
          axes = _check_plot_works(s.hist, default_axes=True, legend=True, by=by)
          self._check_axes_shape(axes, axes_num=expected_axes_num, layout=expected_layout)
          self._check_legend_labels(axes, "a")
  
      @pytest.mark.parametrize("by", [None, "b"])
      def test_hist_with_legend_raises(self, by):
          # GH 6279 - Series histogram with legend and label raises
          index = 15 * ["1"] + 15 * ["2"]
          s = Series(np.random.randn(30), index=index, name="a")
          s.index.name = "b"
  
          with pytest.raises(ValueError, match="Cannot use both legend and label"):
              s.hist(legend=True, by=by, label="c")
  
  
  @td.skip_if_no_mpl
  class TestDataFramePlots(TestPlotBase):
      def test_hist_df_legacy(self):
          from matplotlib.patches import Rectangle
  
          with tm.assert_produces_warning(UserWarning):
              _check_plot_works(self.hist_df.hist)
  
          # make sure layout is handled
          df = DataFrame(np.random.randn(100, 2))
          df[2] = to_datetime(
              np.random.randint(
                  self.start_date_to_int64,
                  self.end_date_to_int64,
                  size=100,
                  dtype=np.int64,
              )
          )
          with tm.assert_produces_warning(UserWarning):
              axes = _check_plot_works(df.hist, grid=False)
          self._check_axes_shape(axes, axes_num=3, layout=(2, 2))
          assert not axes[1, 1].get_visible()
  
          _check_plot_works(df[[2]].hist)
          df = DataFrame(np.random.randn(100, 1))
          _check_plot_works(df.hist)
  
          # make sure layout is handled
          df = DataFrame(np.random.randn(100, 5))
          df[5] = to_datetime(
              np.random.randint(
                  self.start_date_to_int64,
                  self.end_date_to_int64,
                  size=100,
                  dtype=np.int64,
              )
          )
          with tm.assert_produces_warning(UserWarning):
              axes = _check_plot_works(df.hist, layout=(4, 2))
          self._check_axes_shape(axes, axes_num=6, layout=(4, 2))
  
          # make sure sharex, sharey is handled
          with tm.assert_produces_warning(UserWarning):
              _check_plot_works(df.hist, sharex=True, sharey=True)
  
          # handle figsize arg
          with tm.assert_produces_warning(UserWarning):
              _check_plot_works(df.hist, figsize=(8, 10))
  
          # check bins argument
          with tm.assert_produces_warning(UserWarning):
              _check_plot_works(df.hist, bins=5)
  
          # make sure xlabelsize and xrot are handled
          ser = df[0]
          xf, yf = 20, 18
          xrot, yrot = 30, 40
          axes = ser.hist(xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot)
          self._check_ticks_props(
              axes, xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot
          )
  
          xf, yf = 20, 18
          xrot, yrot = 30, 40
          axes = df.hist(xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot)
          self._check_ticks_props(
              axes, xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot
          )
  
          tm.close()
  
          ax = ser.hist(cumulative=True, bins=4, density=True)
          # height of last bin (index 5) must be 1.0
          rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
          tm.assert_almost_equal(rects[-1].get_height(), 1.0)
  
          tm.close()
          ax = ser.hist(log=True)
          # scale of y must be 'log'
          self._check_ax_scales(ax, yaxis="log")
  
          tm.close()
  
          # propagate attr exception from matplotlib.Axes.hist
          with pytest.raises(AttributeError):
              ser.hist(foo="bar")
  
      def test_hist_non_numerical_or_datetime_raises(self):
          # gh-10444, GH32590
          df = DataFrame(
              {
                  "a": np.random.rand(10),
                  "b": np.random.randint(0, 10, 10),
                  "c": to_datetime(
                      np.random.randint(
                          1582800000000000000, 1583500000000000000, 10, dtype=np.int64
                      )
                  ),
                  "d": to_datetime(
                      np.random.randint(
                          1582800000000000000, 1583500000000000000, 10, dtype=np.int64
                      ),
                      utc=True,
                  ),
              }
          )
          df_o = df.astype(object)
  
          msg = "hist method requires numerical or datetime columns, nothing to plot."
          with pytest.raises(ValueError, match=msg):
              df_o.hist()
  
      def test_hist_layout(self):
          df = DataFrame(np.random.randn(100, 2))
          df[2] = to_datetime(
              np.random.randint(
                  self.start_date_to_int64,
                  self.end_date_to_int64,
                  size=100,
                  dtype=np.int64,
              )
          )
  
          layout_to_expected_size = (
              {"layout": None, "expected_size": (2, 2)},  # default is 2x2
              {"layout": (2, 2), "expected_size": (2, 2)},
              {"layout": (4, 1), "expected_size": (4, 1)},
              {"layout": (1, 4), "expected_size": (1, 4)},
              {"layout": (3, 3), "expected_size": (3, 3)},
              {"layout": (-1, 4), "expected_size": (1, 4)},
              {"layout": (4, -1), "expected_size": (4, 1)},
              {"layout": (-1, 2), "expected_size": (2, 2)},
              {"layout": (2, -1), "expected_size": (2, 2)},
          )
  
          for layout_test in layout_to_expected_size:
              axes = df.hist(layout=layout_test["layout"])
              expected = layout_test["expected_size"]
              self._check_axes_shape(axes, axes_num=3, layout=expected)
  
          # layout too small for all 4 plots
          with pytest.raises(ValueError):
              df.hist(layout=(1, 1))
  
          # invalid format for layout
          with pytest.raises(ValueError):
              df.hist(layout=(1,))
          with pytest.raises(ValueError):
              df.hist(layout=(-1, -1))
  
      # GH 9351
      def test_tight_layout(self):
          df = DataFrame(np.random.randn(100, 2))
          df[2] = to_datetime(
              np.random.randint(
                  self.start_date_to_int64,
                  self.end_date_to_int64,
                  size=100,
                  dtype=np.int64,
              )
          )
          # Use default_axes=True when plotting method generate subplots itself
          _check_plot_works(df.hist, default_axes=True)
          self.plt.tight_layout()
  
          tm.close()
  
      def test_hist_subplot_xrot(self):
          # GH 30288
          df = DataFrame(
              {
                  "length": [1.5, 0.5, 1.2, 0.9, 3],
                  "animal": ["pig", "rabbit", "pig", "pig", "rabbit"],
              }
          )
          # Use default_axes=True when plotting method generate subplots itself
          axes = _check_plot_works(
              df.hist,
              default_axes=True,
              filterwarnings="always",
              column="length",
              by="animal",
              bins=5,
              xrot=0,
          )
          self._check_ticks_props(axes, xrot=0)
  
      @pytest.mark.parametrize(
          "column, expected",
          [
              (None, ["width", "length", "height"]),
              (["length", "width", "height"], ["length", "width", "height"]),
          ],
      )
      def test_hist_column_order_unchanged(self, column, expected):
          # GH29235
  
          df = DataFrame(
              {
                  "width": [0.7, 0.2, 0.15, 0.2, 1.1],
                  "length": [1.5, 0.5, 1.2, 0.9, 3],
                  "height": [3, 0.5, 3.4, 2, 1],
              },
              index=["pig", "rabbit", "duck", "chicken", "horse"],
          )
  
          # Use default_axes=True when plotting method generate subplots itself
          axes = _check_plot_works(
              df.hist,
              default_axes=True,
              column=column,
              layout=(1, 3),
          )
          result = [axes[0, i].get_title() for i in range(3)]
          assert result == expected
  
      @pytest.mark.parametrize(
          "histtype, expected",
          [
              ("bar", True),
              ("barstacked", True),
              ("step", False),
              ("stepfilled", True),
          ],
      )
      def test_histtype_argument(self, histtype, expected):
          # GH23992 Verify functioning of histtype argument
          df = DataFrame(np.random.randint(1, 10, size=(100, 2)), columns=["a", "b"])
          ax = df.hist(histtype=histtype)
          self._check_patches_all_filled(ax, filled=expected)
  
      @pytest.mark.parametrize("by", [None, "c"])
      @pytest.mark.parametrize("column", [None, "b"])
      def test_hist_with_legend(self, by, column):
          # GH 6279 - DataFrame histogram can have a legend
          expected_axes_num = 1 if by is None and column is not None else 2
          expected_layout = (1, expected_axes_num)
          expected_labels = column or ["a", "b"]
          if by is not None:
              expected_labels = [expected_labels] * 2
  
          index = Index(15 * ["1"] + 15 * ["2"], name="c")
          df = DataFrame(np.random.randn(30, 2), index=index, columns=["a", "b"])
  
          # Use default_axes=True when plotting method generate subplots itself
          axes = _check_plot_works(
              df.hist,
              default_axes=True,
              legend=True,
              by=by,
              column=column,
          )
  
          self._check_axes_shape(axes, axes_num=expected_axes_num, layout=expected_layout)
          if by is None and column is None:
              axes = axes[0]
          for expected_label, ax in zip(expected_labels, axes):
              self._check_legend_labels(ax, expected_label)
  
      @pytest.mark.parametrize("by", [None, "c"])
      @pytest.mark.parametrize("column", [None, "b"])
      def test_hist_with_legend_raises(self, by, column):
          # GH 6279 - DataFrame histogram with legend and label raises
          index = Index(15 * ["1"] + 15 * ["2"], name="c")
          df = DataFrame(np.random.randn(30, 2), index=index, columns=["a", "b"])
  
          with pytest.raises(ValueError, match="Cannot use both legend and label"):
              df.hist(legend=True, by=by, column=column, label="d")
  
  
  @td.skip_if_no_mpl
  class TestDataFrameGroupByPlots(TestPlotBase):
      def test_grouped_hist_legacy(self):
          from matplotlib.patches import Rectangle
  
          from pandas.plotting._matplotlib.hist import _grouped_hist
  
          df = DataFrame(np.random.randn(500, 1), columns=["A"])
          df["B"] = to_datetime(
              np.random.randint(
                  self.start_date_to_int64,
                  self.end_date_to_int64,
                  size=500,
                  dtype=np.int64,
              )
          )
          df["C"] = np.random.randint(0, 4, 500)
          df["D"] = ["X"] * 500
  
          axes = _grouped_hist(df.A, by=df.C)
          self._check_axes_shape(axes, axes_num=4, layout=(2, 2))
  
          tm.close()
          axes = df.hist(by=df.C)
          self._check_axes_shape(axes, axes_num=4, layout=(2, 2))
  
          tm.close()
          # group by a key with single value
          axes = df.hist(by="D", rot=30)
          self._check_axes_shape(axes, axes_num=1, layout=(1, 1))
          self._check_ticks_props(axes, xrot=30)
  
          tm.close()
          # make sure kwargs to hist are handled
          xf, yf = 20, 18
          xrot, yrot = 30, 40
  
          axes = _grouped_hist(
              df.A,
              by=df.C,
              cumulative=True,
              bins=4,
              xlabelsize=xf,
              xrot=xrot,
              ylabelsize=yf,
              yrot=yrot,
              density=True,
          )
          # height of last bin (index 5) must be 1.0
          for ax in axes.ravel():
              rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
              height = rects[-1].get_height()
              tm.assert_almost_equal(height, 1.0)
          self._check_ticks_props(
              axes, xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot
          )
  
          tm.close()
          axes = _grouped_hist(df.A, by=df.C, log=True)
          # scale of y must be 'log'
          self._check_ax_scales(axes, yaxis="log")
  
          tm.close()
          # propagate attr exception from matplotlib.Axes.hist
          with pytest.raises(AttributeError):
              _grouped_hist(df.A, by=df.C, foo="bar")
  
          msg = "Specify figure size by tuple instead"
          with pytest.raises(ValueError, match=msg):
              df.hist(by="C", figsize="default")
  
      def test_grouped_hist_legacy2(self):
          n = 10
          weight = Series(np.random.normal(166, 20, size=n))
          height = Series(np.random.normal(60, 10, size=n))
          with tm.RNGContext(42):
              gender_int = np.random.choice([0, 1], size=n)
          df_int = DataFrame({"height": height, "weight": weight, "gender": gender_int})
          gb = df_int.groupby("gender")
          axes = gb.hist()
          assert len(axes) == 2
          assert len(self.plt.get_fignums()) == 2
          tm.close()
  
      def test_grouped_hist_layout(self):
          df = self.hist_df
          msg = "Layout of 1x1 must be larger than required size 2"
          with pytest.raises(ValueError, match=msg):
              df.hist(column="weight", by=df.gender, layout=(1, 1))
  
          msg = "Layout of 1x3 must be larger than required size 4"
          with pytest.raises(ValueError, match=msg):
              df.hist(column="height", by=df.category, layout=(1, 3))
  
          msg = "At least one dimension of layout must be positive"
          with pytest.raises(ValueError, match=msg):
              df.hist(column="height", by=df.category, layout=(-1, -1))
  
          with tm.assert_produces_warning(UserWarning):
              axes = _check_plot_works(
                  df.hist, column="height", by=df.gender, layout=(2, 1)
              )
          self._check_axes_shape(axes, axes_num=2, layout=(2, 1))
  
          with tm.assert_produces_warning(UserWarning):
              axes = _check_plot_works(
                  df.hist, column="height", by=df.gender, layout=(2, -1)
              )
          self._check_axes_shape(axes, axes_num=2, layout=(2, 1))
  
          axes = df.hist(column="height", by=df.category, layout=(4, 1))
          self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
  
          axes = df.hist(column="height", by=df.category, layout=(-1, 1))
          self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
  
          axes = df.hist(column="height", by=df.category, layout=(4, 2), figsize=(12, 8))
          self._check_axes_shape(axes, axes_num=4, layout=(4, 2), figsize=(12, 8))
          tm.close()
  
          # GH 6769
          with tm.assert_produces_warning(UserWarning):
              axes = _check_plot_works(
                  df.hist, column="height", by="classroom", layout=(2, 2)
              )
          self._check_axes_shape(axes, axes_num=3, layout=(2, 2))
  
          # without column
          with tm.assert_produces_warning(UserWarning):
              axes = _check_plot_works(df.hist, by="classroom")
          self._check_axes_shape(axes, axes_num=3, layout=(2, 2))
  
          axes = df.hist(by="gender", layout=(3, 5))
          self._check_axes_shape(axes, axes_num=2, layout=(3, 5))
  
          axes = df.hist(column=["height", "weight", "category"])
          self._check_axes_shape(axes, axes_num=3, layout=(2, 2))
  
      def test_grouped_hist_multiple_axes(self):
          # GH 6970, GH 7069
          df = self.hist_df
  
          fig, axes = self.plt.subplots(2, 3)
          returned = df.hist(column=["height", "weight", "category"], ax=axes[0])
          self._check_axes_shape(returned, axes_num=3, layout=(1, 3))
          tm.assert_numpy_array_equal(returned, axes[0])
          assert returned[0].figure is fig
          returned = df.hist(by="classroom", ax=axes[1])
          self._check_axes_shape(returned, axes_num=3, layout=(1, 3))
          tm.assert_numpy_array_equal(returned, axes[1])
          assert returned[0].figure is fig
  
          with pytest.raises(ValueError):
              fig, axes = self.plt.subplots(2, 3)
              # pass different number of axes from required
              axes = df.hist(column="height", ax=axes)
  
      def test_axis_share_x(self):
          df = self.hist_df
          # GH4089
          ax1, ax2 = df.hist(column="height", by=df.gender, sharex=True)
  
          # share x
          assert ax1._shared_x_axes.joined(ax1, ax2)
          assert ax2._shared_x_axes.joined(ax1, ax2)
  
          # don't share y
          assert not ax1._shared_y_axes.joined(ax1, ax2)
          assert not ax2._shared_y_axes.joined(ax1, ax2)
  
      def test_axis_share_y(self):
          df = self.hist_df
          ax1, ax2 = df.hist(column="height", by=df.gender, sharey=True)
  
          # share y
          assert ax1._shared_y_axes.joined(ax1, ax2)
          assert ax2._shared_y_axes.joined(ax1, ax2)
  
          # don't share x
          assert not ax1._shared_x_axes.joined(ax1, ax2)
          assert not ax2._shared_x_axes.joined(ax1, ax2)
  
      def test_axis_share_xy(self):
          df = self.hist_df
          ax1, ax2 = df.hist(column="height", by=df.gender, sharex=True, sharey=True)
  
          # share both x and y
          assert ax1._shared_x_axes.joined(ax1, ax2)
          assert ax2._shared_x_axes.joined(ax1, ax2)
  
          assert ax1._shared_y_axes.joined(ax1, ax2)
          assert ax2._shared_y_axes.joined(ax1, ax2)
  
      @pytest.mark.parametrize(
          "histtype, expected",
          [
              ("bar", True),
              ("barstacked", True),
              ("step", False),
              ("stepfilled", True),
          ],
      )
      def test_histtype_argument(self, histtype, expected):
          # GH23992 Verify functioning of histtype argument
          df = DataFrame(np.random.randint(1, 10, size=(100, 2)), columns=["a", "b"])
          ax = df.hist(by="a", histtype=histtype)
          self._check_patches_all_filled(ax, filled=expected)
   from statsmodels.compat.pandas import assert_frame_equal, make_dataframe
  
  from datetime import datetime
  import numpy as np
  from numpy.testing import (assert_almost_equal, assert_equal, assert_allclose,
                             assert_raises, assert_)
  from numpy import array, column_stack
  
  from statsmodels.tsa.filters._utils import pandas_wrapper
  from statsmodels.datasets import macrodata
  from pandas import DataFrame, date_range, concat
  from statsmodels.tsa.filters.api import (bkfilter, hpfilter, cffilter,
                                           convolution_filter, recursive_filter)
  
  
  def test_bking1d():
      # Test Baxter King band-pass filter. Results are taken from Stata
      bking_results = array([
          7.320813, 2.886914, -6.818976, -13.49436,
          -13.27936, -9.405913, -5.691091, -5.133076, -7.273468,
          -9.243364, -8.482916, -4.447764, 2.406559, 10.68433,
          19.46414, 28.09749, 34.11066, 33.48468, 24.64598, 9.952399,
          -4.265528, -12.59471, -13.46714, -9.049501, -3.011248,
          .5655082, 2.897976, 7.406077, 14.67959, 18.651, 13.05891,
          -2.945415, -24.08659, -41.86147, -48.68383, -43.32689,
          -31.66654, -20.38356, -13.76411, -9.978693, -3.7704, 10.27108,
          31.02847, 51.87613, 66.93117, 73.51951, 73.4053, 69.17468,
          59.8543, 38.23899, -.2604809, -49.0107, -91.1128, -112.1574,
          -108.3227, -86.51453, -59.91258, -40.01185, -29.70265,
          -22.76396, -13.08037, 1.913622, 20.44045, 37.32873, 46.79802,
          51.95937, 59.67393, 70.50803, 81.27311, 83.53191, 67.72536,
          33.78039, -6.509092, -37.31579, -46.05207, -29.81496, 1.416417,
          28.31503,
          32.90134, 8.949259, -35.41895, -84.65775, -124.4288, -144.6036,
          -140.2204, -109.2624, -53.6901, 15.07415, 74.44268, 104.0403,
          101.0725, 76.58291, 49.27925, 36.15751, 36.48799, 37.60897,
          27.75998, 4.216643, -23.20579, -39.33292, -36.6134, -20.90161,
          -4.143123, 5.48432, 9.270075, 13.69573, 22.16675, 33.01987,
          41.93186, 47.12222, 48.62164, 47.30701, 40.20537, 22.37898,
          -7.133002, -43.3339, -78.51229, -101.3684, -105.2179,
          -90.97147,
          -68.30824, -48.10113, -35.60709, -31.15775, -31.82346,
          -32.49278, -28.22499, -14.42852, 10.1827, 36.64189, 49.43468,
          38.75517, 6.447761, -33.15883, -62.60446, -72.87829, -66.54629,
          -52.61205, -38.06676, -26.19963, -16.51492, -7.007577,
          .6125674,
          7.866972, 14.8123, 22.52388, 30.65265, 39.47801, 49.05027,
          59.02925,
          72.88999, 95.08865, 125.8983, 154.4283, 160.7638, 130.6092,
          67.84406, -7.070272, -68.08128, -99.39944, -104.911,
          -100.2372, -98.11596, -104.2051, -114.0125, -113.3475,
          -92.98669, -51.91707, -.7313812, 43.22938, 64.62762, 64.07226,
          59.35707, 67.06026, 91.87247, 124.4591, 151.2402, 163.0648,
          154.6432])
      X = macrodata.load_pandas().data['realinv'].values
      Y = bkfilter(X, 6, 32, 12)
      assert_almost_equal(Y, bking_results, 4)
  
  
  def test_bking2d():
      # Test Baxter-King band-pass filter with 2d input
      bking_results = array([
          [7.320813, -.0374475], [2.886914, -.0430094],
          [-6.818976, -.053456], [-13.49436, -.0620739], [-13.27936, -.0626929],
          [-9.405913, -.0603022], [-5.691091, -.0630016], [-5.133076, -.0832268],
          [-7.273468, -.1186448], [-9.243364, -.1619868], [-8.482916, -.2116604],
          [-4.447764, -.2670747], [2.406559, -.3209931], [10.68433, -.3583075],
          [19.46414, -.3626742], [28.09749, -.3294618], [34.11066, -.2773388],
          [33.48468, -.2436127], [24.64598, -.2605531], [9.952399, -.3305166],
          [-4.265528, -.4275561], [-12.59471, -.5076068], [-13.46714, -.537573],
          [-9.049501, -.5205845], [-3.011248, -.481673], [.5655082, -.4403994],
          [2.897976, -.4039957], [7.406077, -.3537394], [14.67959, -.2687359],
          [18.651, -.1459743], [13.05891, .0014926], [-2.945415, .1424277],
          [-24.08659, .2451936], [-41.86147, .288541], [-48.68383, .2727282],
          [-43.32689, .1959127], [-31.66654, .0644874], [-20.38356, -.1158372],
          [-13.76411, -.3518627], [-9.978693, -.6557535], [-3.7704, -1.003754],
          [10.27108, -1.341632], [31.02847, -1.614486], [51.87613, -1.779089],
          [66.93117, -1.807459], [73.51951, -1.679688], [73.4053, -1.401012],
          [69.17468, -.9954996], [59.8543, -.511261], [38.23899, -.0146745],
          [-.2604809, .4261311], [-49.0107, .7452514], [-91.1128, .8879492],
          [-112.1574, .8282748], [-108.3227, .5851508], [-86.51453, .2351699],
          [-59.91258, -.1208998], [-40.01185, -.4297895], [-29.70265, -.6821963],
          [-22.76396, -.9234254], [-13.08037, -1.217539], [1.913622, -1.57367],
          [20.44045, -1.927008], [37.32873, -2.229565], [46.79802, -2.463154],
          [51.95937, -2.614697], [59.67393, -2.681357], [70.50803, -2.609654],
          [81.27311, -2.301618], [83.53191, -1.720974], [67.72536, -.9837123],
          [33.78039, -.2261613], [-6.509092, .4546985], [-37.31579, 1.005751],
          [-46.05207, 1.457224], [-29.81496, 1.870815], [1.416417, 2.263313],
          [28.31503, 2.599906], [32.90134, 2.812282], [8.949259, 2.83358],
          [-35.41895, 2.632667], [-84.65775, 2.201077], [-124.4288, 1.598951],
          [-144.6036, .9504762], [-140.2204, .4187932], [-109.2624, .1646726],
          [-53.6901, .2034265], [15.07415, .398165], [74.44268, .5427476],
          [104.0403, .5454975], [101.0725, .4723354], [76.58291, .4626823],
          [49.27925, .5840143], [36.15751, .7187981], [36.48799, .6058422],
          [37.60897, .1221227], [27.75998, -.5891272], [4.216643, -1.249841],
          [-23.20579, -1.594972], [-39.33292, -1.545968], [-36.6134, -1.275494],
          [-20.90161, -1.035783], [-4.143123, -.9971732], [5.48432, -1.154264],
          [9.270075, -1.29987], [13.69573, -1.240559], [22.16675, -.9662656],
          [33.01987, -.6420301], [41.93186, -.4698712], [47.12222, -.4527797],
          [48.62164, -.4407153], [47.30701, -.2416076], [40.20537, .2317583],
          [22.37898, .8710276], [-7.133002, 1.426177], [-43.3339, 1.652785],
          [-78.51229, 1.488021], [-101.3684, 1.072096], [-105.2179, .6496446],
          [-90.97147, .4193682], [-68.30824, .41847], [-48.10113, .5253419],
          [-35.60709, .595076], [-31.15775, .5509905], [-31.82346, .3755519],
          [-32.49278, .1297979], [-28.22499, -.0916165], [-14.42852, -.2531037],
          [10.1827, -.3220784], [36.64189, -.2660561], [49.43468, -.1358522],
          [38.75517, -.0279508], [6.447761, .0168735], [-33.15883, .0315687],
          [-62.60446, .0819507], [-72.87829, .2274033], [-66.54629, .4641401],
          [-52.61205, .7211093], [-38.06676, .907773], [-26.19963, .9387103],
          [-16.51492, .7940786], [-7.007577, .5026631], [.6125674, .1224996],
          [7.866972, -.2714422], [14.8123, -.6273921], [22.52388, -.9124271],
          [30.65265, -1.108861], [39.47801, -1.199206], [49.05027, -1.19908],
          [59.02925, -1.139046], [72.88999, -.9775021], [95.08865, -.6592603],
          [125.8983, -.1609712], [154.4283, .4796201], [160.7638, 1.100565],
          [130.6092, 1.447148], [67.84406, 1.359608], [-7.070272, .8931825],
          [-68.08128, .2619787], [-99.39944, -.252208], [-104.911, -.4703874],
          [-100.2372, -.4430657], [-98.11596, -.390683], [-104.2051, -.5647846],
          [-114.0125, -.9397582], [-113.3475, -1.341633], [-92.98669, -1.567337],
          [-51.91707, -1.504943], [-.7313812, -1.30576], [43.22938, -1.17151],
          [64.62762, -1.136151], [64.07226, -1.050555], [59.35707, -.7308369],
          [67.06026, -.1766731], [91.87247, .3898467], [124.4591, .8135461],
          [151.2402, .9644226], [163.0648, .6865934], [154.6432, .0115685]])
  
      mdata = macrodata.load_pandas()
      X = mdata.data[['realinv', 'cpi']].values.astype(float)
      Y = bkfilter(X, 6, 32, 12)
      assert_almost_equal(Y, bking_results, 4)
  
  
  def test_hpfilter():
      # Test Hodrick-Prescott Filter. Results taken from Stata.
      hpfilt_res = array([
          [3.951191484487844718e+01, 2.670837085155121713e+03],
          [8.008853245681075350e+01, 2.698712467543189177e+03],
          [4.887545512195401898e+01, 2.726612544878045810e+03],
          [3.059193256079834100e+01, 2.754612067439201837e+03],
          [6.488266733421960453e+01, 2.782816332665780465e+03],
          [2.304024204546703913e+01, 2.811349757954532834e+03],
          [-1.355312369487364776e+00, 2.840377312369487299e+03],
          [-6.746236512580753697e+01, 2.870078365125807522e+03],
          [-8.136743836853429457e+01, 2.900631438368534418e+03],
          [-6.016789026443257171e+01, 2.932172890264432681e+03],
          [-4.636922433138215638e+01, 2.964788224331382025e+03],
          [-2.069533915570400495e+01, 2.998525339155703932e+03],
          [-2.162152558595607843e+00, 3.033403152558595593e+03],
          [-4.718647774311648391e+00, 3.069427647774311481e+03],
          [-1.355645669169007306e+01, 3.106603456691690099e+03],
          [-4.436926204475639679e+01, 3.144932262044756499e+03],
          [-4.332027378211660107e+01, 3.184407273782116590e+03],
          [-4.454697106352068658e+01, 3.224993971063520803e+03],
          [-2.629875787765286077e+01, 3.266630757877652741e+03],
          [-4.426119635629265758e+01, 3.309228196356292756e+03],
          [-1.443441190762496262e+01, 3.352680411907625057e+03],
          [-2.026686669186437939e+01, 3.396853866691864368e+03],
          [-1.913700136208899494e+01, 3.441606001362089046e+03],
          [-5.482458977940950717e+01, 3.486781589779409387e+03],
          [-1.596244517937793717e+01, 3.532213445179378141e+03],
          [-1.374011542874541192e+01, 3.577700115428745448e+03],
          [1.325482813403914406e+01, 3.623030171865960710e+03],
          [5.603040174253828809e+01, 3.667983598257461836e+03],
          [1.030743373627105939e+02, 3.712348662637289181e+03],
          [7.217534795943993231e+01, 3.755948652040559864e+03],
          [5.462972503693208637e+01, 3.798671274963067845e+03],
          [4.407065050666142270e+01, 3.840449349493338559e+03],
          [3.749016270204992907e+01, 3.881249837297949853e+03],
          [-1.511244199923112319e+00, 3.921067244199923152e+03],
          [-9.093507374079763395e+00, 3.959919507374079785e+03],
          [-1.685361946760258434e+01, 3.997823619467602384e+03],
          [2.822211031434289907e+01, 4.034790889685657021e+03],
          [6.117590627896424849e+01, 4.070822093721035344e+03],
          [5.433135391434370831e+01, 4.105935646085656117e+03],
          [3.810480376716623141e+01, 4.140188196232833434e+03],
          [7.042964928802848590e+01, 4.173670350711971878e+03],
          [4.996346842507591646e+01, 4.206496531574924120e+03],
          [4.455282059571254649e+01, 4.238825179404287155e+03],
          [-7.584961950576143863e+00, 4.270845961950576566e+03],
          [-4.620339247697120300e+01, 4.302776392476971523e+03],
          [-7.054024364552969928e+01, 4.334829243645529459e+03],
          [-6.492941099801464588e+01, 4.367188410998014660e+03],
          [-1.433567024239555394e+02, 4.399993702423955256e+03],
          [-5.932834493089012540e+01, 4.433344344930889747e+03],
          [-6.842096758743628016e+01, 4.467249967587436004e+03],
          [-6.774011924654860195e+01, 4.501683119246548813e+03],
          [-9.030958565658056614e+01, 4.536573585656580690e+03],
          [-4.603981499136807543e+01, 4.571808814991368308e+03],
          [2.588118806672991923e+01, 4.607219811933269739e+03],
          [3.489419371912299539e+01, 4.642608806280876706e+03],
          [7.675179642495095322e+01, 4.677794203575049323e+03],
          [1.635497817724171910e+02, 4.712616218227582976e+03],
          [1.856079654765617306e+02, 4.746963034523438182e+03],
          [1.254269446392718237e+02, 4.780825055360728584e+03],
          [1.387413113837174024e+02, 4.814308688616282780e+03],
          [6.201826599282230745e+01, 4.847598734007177882e+03],
          [4.122129542972197669e+01, 4.880966704570278125e+03],
          [-4.120287475842360436e+01, 4.914722874758424041e+03],
          [-9.486328233441963675e+01, 4.949203282334419782e+03],
          [-1.894232132641573116e+02, 4.984718213264157384e+03],
          [-1.895766639620087517e+02, 5.021518663962008759e+03],
          [-1.464092413342650616e+02, 5.059737241334265491e+03],
          [-1.218770668721217589e+02, 5.099388066872122181e+03],
          [-4.973075629078175552e+01, 5.140393756290781312e+03],
          [-5.365375213897277717e+01, 5.182600752138972894e+03],
          [-7.175241524251214287e+01, 5.225824415242512259e+03],
          [-7.834757283225462743e+01, 5.269846572832254424e+03],
          [-6.264220687943907251e+01, 5.314404206879438789e+03],
          [-3.054332122210325906e+00, 5.359185332122210639e+03],
          [4.808218808024685131e+01, 5.403838811919753425e+03],
          [2.781399326736391231e+00, 5.448011600673263274e+03],
          [-2.197570415173231595e+01, 5.491380704151732061e+03],
          [1.509441335012807031e+02, 5.533624866498719712e+03],
          [1.658909029574851957e+02, 5.574409097042514986e+03],
          [2.027292548049981633e+02, 5.613492745195001589e+03],
          [1.752101578176061594e+02, 5.650738842182393455e+03],
          [1.452808749847536092e+02, 5.686137125015246056e+03],
          [1.535481629475025329e+02, 5.719786837052497503e+03],
          [1.376169777998875361e+02, 5.751878022200112355e+03],
          [1.257703080340770612e+02, 5.782696691965922582e+03],
          [-2.524186846895645431e+01, 5.812614868468956047e+03],
          [-6.546618027042404719e+01, 5.842083180270424236e+03],
          [1.192352023580315290e+01, 5.871536479764196883e+03],
          [1.043482970188742911e+02, 5.901368702981125352e+03],
          [2.581376184768396342e+01, 5.931981238152316109e+03],
          [6.634330880534071184e+01, 5.963840691194659485e+03],
          [-4.236780162594641297e+01, 5.997429801625946311e+03],
          [-1.759397735321817891e+02, 6.033272773532181418e+03],
          [-1.827933311233055065e+02, 6.071867331123305121e+03],
          [-2.472312362505917918e+02, 6.113601236250591683e+03],
          [-2.877470049336488955e+02, 6.158748004933649099e+03],
          [-2.634066336693540507e+02, 6.207426633669354487e+03],
          [-1.819572770763625158e+02, 6.259576277076362203e+03],
          [-1.175034606274621183e+02, 6.314971460627461965e+03],
          [-4.769898649718379602e+01, 6.373272986497183410e+03],
          [1.419578280287896632e+01, 6.434068217197121157e+03],
          [6.267929662760798237e+01, 6.496914703372392069e+03],
          [6.196413196753746888e+01, 6.561378868032462378e+03],
          [5.019769125317907310e+01, 6.627066308746821051e+03],
          [4.665364933213822951e+01, 6.693621350667861407e+03],
          [3.662430749527266016e+01, 6.760719692504727391e+03],
          [7.545680850246480986e+01, 6.828066191497535328e+03],
          [6.052940492147536133e+01, 6.895388595078524304e+03],
          [6.029518881462354329e+01, 6.962461811185376064e+03],
          [2.187042136652689805e+01, 7.029098578633473153e+03],
          [2.380067926824722235e+01, 7.095149320731752596e+03],
          [-7.119129802169481991e+00, 7.160478129802169860e+03],
          [-3.194497359120850888e+01, 7.224963973591208742e+03],
          [-1.897137038934124575e+01, 7.288481370389341464e+03],
          [-1.832687287845146784e+01, 7.350884872878451461e+03],
          [4.600482336597542599e+01, 7.412017176634024509e+03],
          [2.489047706403016491e+01, 7.471709522935970199e+03],
          [6.305909392127250612e+01, 7.529821906078727807e+03],
          [4.585212309498183458e+01, 7.586229876905018500e+03],
          [9.314260180878318351e+01, 7.640848398191216802e+03],
          [1.129819097095369216e+02, 7.693621090290463144e+03],
          [1.204662123176703972e+02, 7.744549787682329224e+03],
          [1.336860614601246198e+02, 7.793706938539875409e+03],
          [1.034567175813735957e+02, 7.841240282418626521e+03],
          [1.403118873372050075e+02, 7.887381112662795204e+03],
          [1.271726169351004501e+02, 7.932425383064899506e+03],
          [8.271925765282139764e+01, 7.976756742347178260e+03],
          [-3.197432211752584408e+01, 8.020838322117525422e+03],
          [-1.150209535194062482e+02, 8.065184953519406008e+03],
          [-1.064694837456772802e+02, 8.110291483745677397e+03],
          [-1.190428718925368230e+02, 8.156580871892536379e+03],
          [-1.353635336292991269e+02, 8.204409533629299403e+03],
          [-9.644348283027102298e+01, 8.254059482830271008e+03],
          [-6.143413116116607853e+01, 8.305728131161165948e+03],
          [-3.019161311097923317e+01, 8.359552613110980019e+03],
          [1.384333163552582846e+00, 8.415631666836447039e+03],
          [-4.156016073666614830e+01, 8.474045160736666730e+03],
          [-4.843882841860977351e+01, 8.534873828418609264e+03],
          [-6.706442838867042155e+01, 8.598172428388670596e+03],
          [-2.019644488579979225e+01, 8.663965444885800025e+03],
          [-4.316446881084630149e+00, 8.732235446881084499e+03],
          [4.435061943264736328e+01, 8.802952380567352520e+03],
          [2.820550564155564643e+01, 8.876083494358445023e+03],
          [5.155624419490777655e+01, 8.951623755805092514e+03],
          [-4.318760899315748247e+00, 9.029585760899315574e+03],
          [-6.534632828542271454e+01, 9.110014328285422380e+03],
          [-7.226757738268497633e+01, 9.192951577382684263e+03],
          [-9.412378615444868046e+01, 9.278398786154448317e+03],
          [-1.191240653288368776e+02, 9.366312065328836979e+03],
          [-4.953669826751865912e+01, 9.456588698267518339e+03],
          [-6.017251579067487910e+01, 9.549051515790675694e+03],
          [-5.103438828313483100e+01, 9.643492388283135369e+03],
          [-7.343057830678117170e+01, 9.739665578306781754e+03],
          [-2.774245193054957781e+01, 9.837293451930549054e+03],
          [-3.380481112519191811e+00, 9.936052481112519672e+03],
          [-2.672779877794346248e+01, 1.003560179877794326e+04],
          [-3.217342505148371856e+01, 1.013559842505148299e+04],
          [-4.140567518359966925e+01, 1.023568267518359971e+04],
          [-6.687756033938057953e+00, 1.033547475603393832e+04],
          [7.300600408459467872e+01, 1.043456899591540605e+04],
          [6.862345670680042531e+01, 1.053255554329319966e+04],
          [5.497882461487461114e+01, 1.062907017538512628e+04],
          [9.612244093055960548e+01, 1.072379155906944106e+04],
          [1.978212770103891671e+02, 1.081643272298961165e+04],
          [1.362772276848754700e+02, 1.090676677231512440e+04],
          [2.637635494867263333e+02, 1.099469045051327339e+04],
          [1.876813256815166824e+02, 1.108018567431848351e+04],
          [1.711447873158413131e+02, 1.116339921268415856e+04],
          [5.257586460826678376e+01, 1.124459513539173349e+04],
          [4.710652228531762375e+01, 1.132414447771468258e+04],
          [-6.237613484241046535e+01, 1.140245113484241119e+04],
          [-9.982044354035315337e+01, 1.147994844354035376e+04],
          [-7.916275548997509759e+01, 1.155703075548997549e+04],
          [-9.526003459472303803e+01, 1.163403003459472347e+04],
          [-1.147987680369169539e+02, 1.171122876803691724e+04],
          [-1.900259054765901965e+02, 1.178884990547659072e+04],
          [-2.212256473439556430e+02, 1.186704464734395515e+04],
          [-2.071394278781845060e+02, 1.194584542787818464e+04],
          [-8.968541528904825100e+01, 1.202514641528904758e+04],
          [-6.189531564415665343e+01, 1.210471231564415575e+04],
          [-5.662878162551714922e+01, 1.218425178162551674e+04],
          [-4.961678134413705266e+01, 1.226343478134413635e+04],
          [-3.836288992144181975e+01, 1.234189588992144127e+04],
          [-8.956671991456460091e+00, 1.241923867199145570e+04],
          [3.907028461866866564e+01, 1.249504271538133071e+04],
          [1.865299000184495526e+01, 1.256888200999815490e+04],
          [4.279803532226833340e+01, 1.264035496467773191e+04],
          [3.962735362631610769e+01, 1.270907164637368442e+04],
          [1.412691291877854383e+02, 1.277466887081221466e+04],
          [1.256537791844366438e+02, 1.283680822081556289e+04],
          [7.067642758858892194e+01, 1.289523957241141034e+04],
          [1.108876647603192396e+02, 1.294979133523968085e+04],
          [9.956490829291760747e+01, 1.300033609170708223e+04],
          [1.571612709880937473e+02, 1.304681572901190702e+04],
          [2.318746375812715996e+02, 1.308923436241872878e+04],
          [2.635546670125277160e+02, 1.312769433298747208e+04],
          [2.044220965739259555e+02, 1.316244290342607383e+04],
          [2.213739418903714977e+02, 1.319389205810962812e+04],
          [1.020184547767112235e+02, 1.322258154522328914e+04],
          [-1.072694716663390864e+02, 1.324918947166633916e+04],
          [-3.490477058718843182e+02, 1.327445770587188417e+04],
          [-3.975570728533530200e+02, 1.329906107285335383e+04],
          [-3.331152428080622485e+02, 1.332345624280806260e+04]])
      dta = macrodata.load_pandas().data['realgdp'].values
      res = column_stack((hpfilter(dta, 1600)))
      assert_almost_equal(res, hpfilt_res, 6)
  
  
  def test_cfitz_filter():
      # Test Christiano-Fitzgerald Filter. Results taken from R.
      # NOTE: The Stata mata code and the matlab code it's based on are wrong.
      cfilt_res = array([
          [0.712599537179426, 0.439563468233128],
          [1.06824041304411, 0.352886666575907],
          [1.19422467791128, 0.257297004260607],
          [0.970845473140327, 0.114504692143872],
          [0.467026976628563, -0.070734782329146],
          [-0.089153511514031, -0.238609685132605],
          [-0.452339254128573, -0.32376584042956],
          [-0.513231214461187, -0.314288554228112],
          [-0.352372578720063, -0.258815055101336],
          [-0.160282602521333, -0.215076844089567],
          [-0.0918782593827686, -0.194120745417214],
          [-0.168083823205437, -0.158327420072693],
          [-0.291595204965808, -0.0742727139742986],
          [-0.348638756841307, 0.037008291163602],
          [-0.304328040874631, 0.108196527328748],
          [-0.215933150969686, 0.0869231107437175],
          [-0.165632621390694, -0.0130556619786275],
          [-0.182326839507151, -0.126570926191824],
          [-0.223737786804725, -0.205535321806185],
          [-0.228939291453403, -0.269110078201836],
          [-0.185518327227038, -0.375976507132174],
          [-0.143900152461529, -0.53760115656157],
          [-0.162749541550174, -0.660065018626038],
          [-0.236263634756884, -0.588542352053736],
          [-0.275785854309211, -0.236867929421996],
          [-0.173666515108109, 0.303436335579219],
          [0.0963135720251639, 0.779772338801993],
          [0.427070069032285, 0.929108075350647],
          [0.629034743259998, 0.658330841002647],
          [0.557941248993624, 0.118500049361018],
          [0.227866624051603, -0.385048321099911],
          [-0.179878859883227, -0.582223992561493],
          [-0.428263000051965, -0.394053702908091],
          [-0.381640684645912, 0.0445437406977307],
          [-0.0942745548364887, 0.493997792757968],
          [0.238132391504895, 0.764519811304315],
          [0.431293754256291, 0.814755206427316],
          [0.455010435813661, 0.745567043101108],
          [0.452800768971269, 0.709401694610443],
          [0.615754619329312, 0.798293251119636],
          [1.00256335412457, 0.975856845059388],
          [1.44841039351691, 1.09097252730799],
          [1.64651971120370, 0.967823457118036],
          [1.35534532901802, 0.522397724737059],
          [0.580492790312048, -0.16941343361609],
          [-0.410746188031773, -0.90760401289056],
          [-1.26148406066881, -1.49592867122591],
          [-1.75784179124566, -1.87404167409849],
          [-1.94478553960064, -2.14586210891112],
          [-2.03751202708559, -2.465855239868],
          [-2.20376059354166, -2.86294187189049],
          [-2.39722338315852, -3.15004697654831],
          [-2.38032366161537, -3.01390466643222],
          [-1.91798022532025, -2.23395210271226],
          [-0.982318490353716, -0.861346053067472],
          [0.199047030343412, 0.790266582335616],
          [1.28582776574786, 2.33731327460104],
          [2.03565905376430, 3.54085486821911],
          [2.41201557412526, 4.36519456268955],
          [2.52011070482927, 4.84810517685452],
          [2.45618479815452, 4.92906708807477],
          [2.22272146945388, 4.42591058990048],
          [1.78307567169034, 3.20962906108388],
          [1.18234431860844, 1.42568060336985],
          [0.590069172333348, -0.461896808688991],
          [0.19662302949837, -1.89020992539465],
          [0.048307034171166, -2.53490571941987],
          [-0.0141956981899000, -2.50020338531674],
          [-0.230505187108187, -2.20625973569823],
          [-0.700947410386801, -2.06643697511048],
          [-1.27085123163060, -2.21536883679783],
          [-1.64082547897928, -2.49016921117735],
          [-1.62286182971254, -2.63948740221362],
          [-1.31609762181362, -2.54685250637904],
          [-1.03085567704873, -2.27157435428923],
          [-1.01100120380112, -1.90404507430561],
          [-1.19823958399826, -1.4123209792214],
          [-1.26398933608383, -0.654000086153317],
          [-0.904710628949692, 0.447960016248203],
          [-0.151340093679588, 1.73970411237156],
          [0.592926881165989, 2.85741581650685],
          [0.851660587507523, 3.4410446351716],
          [0.480324393352127, 3.36870271362297],
          [-0.165153230782417, 2.82003806696544],
          [-0.459235919375844, 2.12858991660866],
          [0.0271158842479935, 1.55840980891556],
          [1.18759188180671, 1.17980298478623],
          [2.43238266962309, 0.904011534980672],
          [3.08277213720132, 0.595286911949837],
          [2.79953663720953, 0.148014782859571],
          [1.73694442845833, -0.496297332023011],
          [0.357638079951977, -1.33108149877570],
          [-0.891418825216945, -2.22650083183366],
          [-1.77646467793627, -2.89359299718574],
          [-2.24614790863088, -2.97921619243347],
          [-2.29048879096607, -2.30003092779280],
          [-1.87929656465888, -1.05298381273274],
          [-1.04510101454788, 0.215837488618531],
          [0.00413338508394524, 0.937866257924888],
          [0.906870625251025, 0.92664365343019],
          [1.33869057593416, 0.518564571494679],
          [1.22659678454440, 0.288096869652890],
          [0.79380139656044, 0.541053084632774],
          [0.38029431865832, 1.01905199983437],
          [0.183929413600038, 1.10529586616777],
          [0.140045425897033, 0.393618564826736],
          [0.0337313182352219, -0.86431819007665],
          [-0.269208622829813, -1.85638085246792],
          [-0.687276639992166, -1.82275359004533],
          [-1.00161592325614, -0.692695765071617],
          [-1.06320089194036, 0.803577361347341],
          [-0.927152307196776, 1.67366338751788],
          [-0.786802101366614, 1.42564362251793],
          [-0.772970884572502, 0.426446388877964],
          [-0.81275662801789, -0.437721213831647],
          [-0.686831250382476, -0.504255468075149],
          [-0.237936463020255, 0.148656301898438],
          [0.459631879129522, 0.832925905720478],
          [1.12717379822508, 0.889455302576383],
          [1.48640453200855, 0.268042676202216],
          [1.46515245776211, -0.446505038539178],
          [1.22993484959115, -0.563868578181134],
          [1.0272100765927, 0.0996849952196907],
          [0.979191212438404, 1.05053652824665],
          [1.00733490030391, 1.51658415000556],
          [0.932192535457706, 1.06262774912638],
          [0.643374300839414, -0.0865180803476065],
          [0.186885168954461, -1.24799408923277],
          [-0.290842337365465, -1.80035611156538],
          [-0.669446735516495, -1.58847333561510],
          [-0.928915624595538, -0.932116966867929],
          [-1.11758635926997, -0.307879396807850],
          [-1.26832454569756, -0.00856199983957032],
          [-1.35755577149251, -0.0303537516690989],
          [-1.34244112665546, -0.196807620887435],
          [-1.22227976023299, -0.342062643495923],
          [-1.04601473486818, -0.390474392372016],
          [-0.85158508717846, -0.322164402093596],
          [-0.605033439160543, -0.126930141915954],
          [-0.218304303942818, 0.179551077808122],
          [0.352173017779006, 0.512327303000081],
          [1.01389600097229, 0.733397490572755],
          [1.55149778750607, 0.748740387440165],
          [1.75499674757591, 0.601759717901009],
          [1.56636057468633, 0.457705308377562],
          [1.12239792537274, 0.470849913286519],
          [0.655802600286141, 0.646142040378738],
          [0.335285115340180, 0.824103600255079],
          [0.173454596506888, 0.808068498175582],
          [0.0666753011315252, 0.521488214487996],
          [-0.0842367474816212, 0.0583493276173476],
          [-0.285604762631464, -0.405958418332253],
          [-0.465735422869919, -0.747800086512926],
          [-0.563586691231348, -0.94982272350799],
          [-0.598110322024572, -1.04736894794361],
          [-0.65216025756061, -1.04858365218822],
          [-0.789663117801624, -0.924145633093637],
          [-0.984704045337959, -0.670740724179446],
          [-1.12449565589348, -0.359476803003931],
          [-1.07878318723543, -0.092290938944355],
          [-0.775555435407062, 0.102132527529259],
          [-0.231610677329856, 0.314409560305622],
          [0.463192794235131, 0.663523546243286],
          [1.17416973448423, 1.13156902460931],
          [1.74112278814906, 1.48967153067024],
          [2.00320855757084, 1.42571085941843],
          [1.8529912317336, 0.802460519079555],
          [1.30747261947211, -0.169219078629572],
          [0.540237070403222, -1.01621539672694],
          [-0.177136817092375, -1.3130784867977],
          [-0.611981468823591, -0.982477824460773],
          [-0.700240028737747, -0.344919609255406],
          [-0.572396497740112, 0.125083535035390],
          [-0.450934466600975, 0.142553112732280],
          [-0.494020014254326, -0.211429053871656],
          [-0.701707589094918, -0.599602868825992],
          [-0.94721339346157, -0.710669870591623],
          [-1.09297139748946, -0.47846194092245],
          [-1.08850658866583, -0.082258450179988],
          [-0.976082880696692, 0.235758921309309],
          [-0.81885695346771, 0.365298185204303],
          [-0.63165529525553, 0.384725179378064],
          [-0.37983149226421, 0.460240196164378],
          [-0.0375551354277652, 0.68580913832794],
          [0.361996927427804, 0.984470835955107],
          [0.739920615366072, 1.13195975020298],
          [1.03583478061534, 0.88812510421667],
          [1.25614938962160, 0.172561520611839],
          [1.45295030231799, -0.804979390544485],
          [1.64887158748426, -1.55662011197859],
          [1.78022721495313, -1.52921975346218],
          [1.71945683859668, -0.462240366424548],
          [1.36728880239190, 1.31213774341268],
          [0.740173894315912, 2.88362740582926],
          [-0.0205364331835904, 3.20319080963167],
          [-0.725643970956428, 1.75222466531151],
          [-1.23900506689782, -0.998432917440275],
          [-1.52651897508678, -3.72752870885448],
          [-1.62857516631435, -5.00551707196292],
          [-1.59657420180451, -4.18499132634584],
          [-1.45489013276495, -1.81759097305637],
          [-1.21309542313047, 0.722029457352468]])
      dta = macrodata.load_pandas().data[['tbilrate', 'infl']].values[1:]
      cyc, trend = cffilter(dta)
      assert_almost_equal(cyc, cfilt_res, 8)
      # do 1d
      cyc, trend = cffilter(dta[:, 1])
      assert_almost_equal(cyc, cfilt_res[:, 1], 8)
  
  
  def test_bking_pandas():
      # 1d
      dta = macrodata.load_pandas().data
      index = date_range(start='1959-01-01', end='2009-10-01', freq='Q')
      dta.index = index
      filtered = bkfilter(dta["infl"])
      nd_filtered = bkfilter(dta['infl'].values)
      assert_equal(filtered.values, nd_filtered)
      assert_equal(filtered.index[0], datetime(1962, 3, 31))
      assert_equal(filtered.index[-1], datetime(2006, 9, 30))
      assert_equal(filtered.name, "infl_cycle")
  
      # 2d
      filtered = bkfilter(dta[["infl", "unemp"]])
      nd_filtered = bkfilter(dta[['infl', 'unemp']].values)
      assert_equal(filtered.values, nd_filtered)
      assert_equal(filtered.index[0], datetime(1962, 3, 31))
      assert_equal(filtered.index[-1], datetime(2006, 9, 30))
      assert_equal(filtered.columns.values, ["infl_cycle", "unemp_cycle"])
  
  
  def test_cfitz_pandas():
      # 1d
      dta = macrodata.load_pandas().data
      index = date_range(start='1959-01-01', end='2009-10-01', freq='Q')
      dta.index = index
      cycle, trend = cffilter(dta["infl"])
      ndcycle, ndtrend = cffilter(dta['infl'].values)
      assert_allclose(cycle.values, ndcycle, rtol=1e-14)
      assert_equal(cycle.index[0], datetime(1959, 3, 31))
      assert_equal(cycle.index[-1], datetime(2009, 9, 30))
      assert_equal(cycle.name, "infl_cycle")
  
      # 2d
      cycle, trend = cffilter(dta[["infl", "unemp"]])
      ndcycle, ndtrend = cffilter(dta[['infl', 'unemp']].values)
      assert_allclose(cycle.values, ndcycle, rtol=1e-14)
      assert_equal(cycle.index[0], datetime(1959, 3, 31))
      assert_equal(cycle.index[-1], datetime(2009, 9, 30))
      assert_equal(cycle.columns.values, ["infl_cycle", "unemp_cycle"])
  
  
  def test_hpfilter_pandas():
      dta = macrodata.load_pandas().data
      index = date_range(start='1959-01-01', end='2009-10-01', freq='Q')
      dta.index = index
      cycle, trend = hpfilter(dta["realgdp"])
      ndcycle, ndtrend = hpfilter(dta['realgdp'].values)
      assert_equal(cycle.values, ndcycle)
      assert_equal(cycle.index[0], datetime(1959, 3, 31))
      assert_equal(cycle.index[-1], datetime(2009, 9, 30))
      assert_equal(cycle.name, "realgdp_cycle")
  
  
  class TestFilters(object):
      @classmethod
      def setup_class(cls):
          # even
          data = [-50, 175, 149, 214, 247, 237, 225, 329, 729, 809,
                  530, 489, 540, 457, 195, 176, 337, 239, 128, 102,
                  232, 429, 3, 98, 43, -141, -77, -13, 125, 361, -45, 184]
          cls.data = DataFrame(data, date_range(start='1/1/1951',
                                                periods=len(data),
                                                freq='Q'))
          data[9] = np.nan
          cls.datana = DataFrame(data, date_range(start='1/1/1951',
                                                  periods=len(data),
                                                  freq='Q'))
          from .results import filter_results
          cls.expected = filter_results
  
      def test_convolution(self):
          x = self.data.values.squeeze()
          res = convolution_filter(x, [.75, .25])
          expected = self.expected.conv2
          np.testing.assert_almost_equal(res, expected)
  
          res = convolution_filter(x, [.75, .25], nsides=1)
          expected = self.expected.conv1
          np.testing.assert_almost_equal(res, expected)
  
          x = self.datana.values.squeeze()
          res = convolution_filter(x, [.75, .25])
          expected = self.expected.conv2_na
          np.testing.assert_almost_equal(res, expected)
  
          res = convolution_filter(x, [.75, .25], nsides=1)
          expected = self.expected.conv1_na
          np.testing.assert_almost_equal(res, expected)
  
      def test_convolution2d(self):
          x = self.data.values
          res = convolution_filter(x, [[.75], [.25]])
          expected = self.expected.conv2
          np.testing.assert_almost_equal(res, expected[:, None])
          res = convolution_filter(np.c_[x, x], [[.75, .75], [.25, .25]])
          np.testing.assert_almost_equal(res, np.c_[expected, expected])
  
          res = convolution_filter(x, [[.75], [.25]], nsides=1)
          expected = self.expected.conv1
          np.testing.assert_almost_equal(res, expected[:, None])
  
          x = self.datana.values
          res = convolution_filter(x, [[.75], [.25]])
          expected = self.expected.conv2_na
          np.testing.assert_almost_equal(res, expected[:, None])
  
          res = convolution_filter(x, [[.75], [.25]], nsides=1)
          expected = self.expected.conv1_na
          np.testing.assert_almost_equal(res, expected[:, None])
  
      def test_recursive(self):
          x = self.data.values.squeeze()
          res = recursive_filter(x, [.75, .25])
          expected = self.expected.recurse
          np.testing.assert_almost_equal(res, expected)
  
          res = recursive_filter(x, [.75, .25], init=[150, 100])
          expected = self.expected.recurse_init
          np.testing.assert_almost_equal(res, expected)
  
          x = self.datana.values.squeeze()
          res = recursive_filter(x, [.75, .25])
          expected = self.expected.recurse_na
          np.testing.assert_almost_equal(res, expected)
  
          res = recursive_filter(x, [.75, .25], init=[150, 100])
          expected = self.expected.recurse_init_na
          np.testing.assert_almost_equal(res, expected)
  
          assert_raises(ValueError, recursive_filter, x,
                        [.75, .25, .5], [150, 100])
  
      def test_pandas(self):
          start = datetime(1951, 3, 31)
          end = datetime(1958, 12, 31)
          x = self.data[0]
          res = convolution_filter(x, [.75, .25])
          assert_(res.index[0] == start)
          assert_(res.index[-1] == end)
  
          res = convolution_filter(x, [.75, .25], nsides=1)
          assert_(res.index[0] == start)
          # with no nan-padding q1 if not
          assert_(res.index[-1] == end)
  
          res = recursive_filter(x, [.75, .25])
          assert_(res.index[0] == start)
          assert_(res.index[-1] == end)
  
          x = self.datana
          res = recursive_filter(x, [.75, .25])
          assert_(res.index[0] == start)
          assert_(res.index[-1] == end)
  
      def test_pandas2d(self):
          start = datetime(1951, 3, 31)
          end = datetime(1958, 12, 31)
          x = concat((self.data[0], self.data[0]), axis=1)
          res = convolution_filter(x, [[.75, .75], [.25, .25]])
          assert_(res.index[0] == start)
          assert_(res.index[-1] == end)
  
      def test_odd_length_filter(self):
          start = datetime(1951, 3, 31)
          end = datetime(1958, 12, 31)
          x = self.data[0]
          res = convolution_filter(x, [.75, .5, .3, .2, .1])
          expected = self.expected.conv2_odd
          np.testing.assert_almost_equal(res.values.squeeze(), expected)
          np.testing.assert_(res.index[0] == start)
          np.testing.assert_(res.index[-1] == end)
  
          res = convolution_filter(x, [.75, .5, .3, .2, .1], nsides=1)
          expected = self.expected.conv1_odd
          np.testing.assert_almost_equal(res.values.squeeze(), expected)
          np.testing.assert_(res.index[0] == start)
          np.testing.assert_(res.index[-1] == end)
          # with no NAs
  
          # not a stable filter
          res = recursive_filter(x, [.75, .5, .3, .2, .1], init=[150, 100,
                                                                 125, 135,
                                                                 145])
          expected = self.expected.recurse_odd
          # only have 12 characters in R and this blows up and gets big
          np.testing.assert_almost_equal(res.values.squeeze(), expected, 4)
          np.testing.assert_(res.index[0] == start)
          np.testing.assert_(res.index[-1] == end)
  
  
  def dummy_func(x):
      return x
  
  
  def dummy_func_array(x):
      return x.values
  
  
  def dummy_func_pandas_columns(x):
      return x.values
  
  
  def dummy_func_pandas_series(x):
      return x['A']
  
  
  def test_pandas_freq_decorator():
      x = make_dataframe()
      # in x, get a function back that returns an x with the same columns
      func = pandas_wrapper(dummy_func)
  
      np.testing.assert_equal(func(x.values), x)
  
      func = pandas_wrapper(dummy_func_array)
      assert_frame_equal(func(x), x)
  
      expected = x.rename(columns=dict(zip('ABCD', 'EFGH')))
      func = pandas_wrapper(dummy_func_array, names=list('EFGH'))
      assert_frame_equal(func(x), expected)
   from warnings import warn
  
  import numpy as np
  from mizani.palettes import rescale_pal
  
  from ..doctools import document
  from ..exceptions import PlotnineWarning
  from ..utils import alias
  from .scale import scale_discrete, scale_continuous
  
  
  @document
  class scale_stroke_continuous(scale_continuous):
      """
      Continuous Stroke Scale
  
      Parameters
      ----------
      range : array_like
          Range ([Minimum, Maximum]) of output stroke values.
          Should be between 0 and 1. Default is ``(1, 6)``
      {superclass_parameters}
      """
      _aesthetics = ['stroke']
  
      def __init__(self, range=(1, 6), **kwargs):
          self.palette = rescale_pal(range)
          scale_continuous.__init__(self, **kwargs)
  
  
  @document
  class scale_stroke_ordinal(scale_discrete):
      """
      Discrete Stroke Scale
  
      Parameters
      ----------
      range : array_like
          Range ([Minimum, Maximum]) of output stroke values.
          Should be between 0 and 1. Default is ``(1, 6)``
      {superclass_parameters}
      """
      _aesthetics = ['stroke']
  
      def __init__(self, range=(1, 6), **kwargs):
          def palette(n):
              return np.linspace(range[0], range[1], n)
  
          self.palette = palette
          scale_discrete.__init__(self, **kwargs)
  
  
  @document
  class scale_stroke_discrete(scale_stroke_ordinal):
      """
      Discrete Stroke Scale
  
      Parameters
      ----------
      {superclass_parameters}
      """
      _aesthetics = ['stroke']
  
      def __init__(self, **kwargs):
          warn(
              "Using stroke for a ordinal variable is not advised.",
              PlotnineWarning
          )
          super().__init__(self, **kwargs)
  
  
  alias('scale_stroke', scale_stroke_continuous)
   #!/usr/bin/env python
  """Tests for the linalg.isolve.gcrotmk module
  """
  
  from numpy.testing import (assert_, assert_allclose, assert_equal,
                             suppress_warnings)
  
  import numpy as np
  from numpy import zeros, array, allclose
  from scipy.linalg import norm
  from scipy.sparse import csr_matrix, eye, rand
  
  from scipy.sparse.linalg.interface import LinearOperator
  from scipy.sparse.linalg import splu
  from scipy.sparse.linalg.isolve import gcrotmk, gmres
  
  
  Am = csr_matrix(array([[-2,1,0,0,0,9],
                         [1,-2,1,0,5,0],
                         [0,1,-2,1,0,0],
                         [0,0,1,-2,1,0],
                         [0,3,0,1,-2,1],
                         [1,0,0,0,1,-2]]))
  b = array([1,2,3,4,5,6])
  count = [0]
  
  
  def matvec(v):
      count[0] += 1
      return Am*v
  
  
  A = LinearOperator(matvec=matvec, shape=Am.shape, dtype=Am.dtype)
  
  
  def do_solve(**kw):
      count[0] = 0
      with suppress_warnings() as sup:
          sup.filter(DeprecationWarning, ".*called without specifying.*")
          x0, flag = gcrotmk(A, b, x0=zeros(A.shape[0]), tol=1e-14, **kw)
      count_0 = count[0]
      assert_(allclose(A*x0, b, rtol=1e-12, atol=1e-12), norm(A*x0-b))
      return x0, count_0
  
  
  class TestGCROTMK(object):
      def test_preconditioner(self):
          # Check that preconditioning works
          pc = splu(Am.tocsc())
          M = LinearOperator(matvec=pc.solve, shape=A.shape, dtype=A.dtype)
  
          x0, count_0 = do_solve()
          x1, count_1 = do_solve(M=M)
  
          assert_equal(count_1, 3)
          assert_(count_1 < count_0/2)
          assert_(allclose(x1, x0, rtol=1e-14))
  
      def test_arnoldi(self):
          np.random.seed(1)
  
          A = eye(2000) + rand(2000, 2000, density=5e-4)
          b = np.random.rand(2000)
  
          # The inner arnoldi should be equivalent to gmres
          with suppress_warnings() as sup:
              sup.filter(DeprecationWarning, ".*called without specifying.*")
              x0, flag0 = gcrotmk(A, b, x0=zeros(A.shape[0]), m=15, k=0, maxiter=1)
              x1, flag1 = gmres(A, b, x0=zeros(A.shape[0]), restart=15, maxiter=1)
  
          assert_equal(flag0, 1)
          assert_equal(flag1, 1)
          assert np.linalg.norm(A.dot(x0) - b) > 1e-3
  
          assert_allclose(x0, x1)
  
      def test_cornercase(self):
          np.random.seed(1234)
  
          # Rounding error may prevent convergence with tol=0 --- ensure
          # that the return values in this case are correct, and no
          # exceptions are raised
  
          for n in [3, 5, 10, 100]:
              A = 2*eye(n)
  
              with suppress_warnings() as sup:
                  sup.filter(DeprecationWarning, ".*called without specifying.*")
                  b = np.ones(n)
                  x, info = gcrotmk(A, b, maxiter=10)
                  assert_equal(info, 0)
                  assert_allclose(A.dot(x) - b, 0, atol=1e-14)
  
                  x, info = gcrotmk(A, b, tol=0, maxiter=10)
                  if info == 0:
                      assert_allclose(A.dot(x) - b, 0, atol=1e-14)
  
                  b = np.random.rand(n)
                  x, info = gcrotmk(A, b, maxiter=10)
                  assert_equal(info, 0)
                  assert_allclose(A.dot(x) - b, 0, atol=1e-14)
  
                  x, info = gcrotmk(A, b, tol=0, maxiter=10)
                  if info == 0:
                      assert_allclose(A.dot(x) - b, 0, atol=1e-14)
  
      def test_nans(self):
          A = eye(3, format='lil')
          A[1,1] = np.nan
          b = np.ones(3)
  
          with suppress_warnings() as sup:
              sup.filter(DeprecationWarning, ".*called without specifying.*")
              x, info = gcrotmk(A, b, tol=0, maxiter=10)
              assert_equal(info, 1)
  
      def test_truncate(self):
          np.random.seed(1234)
          A = np.random.rand(30, 30) + np.eye(30)
          b = np.random.rand(30)
  
          for truncate in ['oldest', 'smallest']:
              with suppress_warnings() as sup:
                  sup.filter(DeprecationWarning, ".*called without specifying.*")
                  x, info = gcrotmk(A, b, m=10, k=10, truncate=truncate, tol=1e-4,
                                    maxiter=200)
              assert_equal(info, 0)
              assert_allclose(A.dot(x) - b, 0, atol=1e-3)
  
      def test_CU(self):
          for discard_C in (True, False):
              # Check that C,U behave as expected
              CU = []
              x0, count_0 = do_solve(CU=CU, discard_C=discard_C)
              assert_(len(CU) > 0)
              assert_(len(CU) <= 6)
  
              if discard_C:
                  for c, u in CU:
                      assert_(c is None)
  
              # should converge immediately
              x1, count_1 = do_solve(CU=CU, discard_C=discard_C)
              if discard_C:
                  assert_equal(count_1, 2 + len(CU))
              else:
                  assert_equal(count_1, 3)
              assert_(count_1 <= count_0/2)
              assert_allclose(x1, x0, atol=1e-14)
  
      def test_denormals(self):
          # Check that no warnings are emitted if the matrix contains
          # numbers for which 1/x has no float representation, and that
          # the solver behaves properly.
          A = np.array([[1, 2], [3, 4]], dtype=float)
          A *= 100 * np.nextafter(0, 1)
  
          b = np.array([1, 1])
  
          with suppress_warnings() as sup:
              sup.filter(DeprecationWarning, ".*called without specifying.*")
              xp, info = gcrotmk(A, b)
  
          if info == 0:
              assert_allclose(A.dot(xp), b)
   """Test functions for the sparse.linalg.interface module
  """
  
  from functools import partial
  from itertools import product
  import operator
  import pytest
  from pytest import raises as assert_raises, warns
  from numpy.testing import assert_, assert_equal
  
  import numpy as np
  import scipy.sparse as sparse
  
  from scipy.sparse.linalg import interface
  from scipy.sparse.sputils import matrix
  
  
  class TestLinearOperator(object):
      def setup_method(self):
          self.A = np.array([[1,2,3],
                             [4,5,6]])
          self.B = np.array([[1,2],
                             [3,4],
                             [5,6]])
          self.C = np.array([[1,2],
                             [3,4]])
  
      def test_matvec(self):
          def get_matvecs(A):
              return [{
                          'shape': A.shape,
                          'matvec': lambda x: np.dot(A, x).reshape(A.shape[0]),
                          'rmatvec': lambda x: np.dot(A.T.conj(),
                                                      x).reshape(A.shape[1])
                      },
                      {
                          'shape': A.shape,
                          'matvec': lambda x: np.dot(A, x),
                          'rmatvec': lambda x: np.dot(A.T.conj(), x),
                          'rmatmat': lambda x: np.dot(A.T.conj(), x),
                          'matmat': lambda x: np.dot(A, x)
                      }]
  
          for matvecs in get_matvecs(self.A):
              A = interface.LinearOperator(**matvecs)
  
              assert_(A.args == ())
  
              assert_equal(A.matvec(np.array([1,2,3])), [14,32])
              assert_equal(A.matvec(np.array([[1],[2],[3]])), [[14],[32]])
              assert_equal(A * np.array([1,2,3]), [14,32])
              assert_equal(A * np.array([[1],[2],[3]]), [[14],[32]])
              assert_equal(A.dot(np.array([1,2,3])), [14,32])
              assert_equal(A.dot(np.array([[1],[2],[3]])), [[14],[32]])
  
              assert_equal(A.matvec(matrix([[1],[2],[3]])), [[14],[32]])
              assert_equal(A * matrix([[1],[2],[3]]), [[14],[32]])
              assert_equal(A.dot(matrix([[1],[2],[3]])), [[14],[32]])
  
              assert_equal((2*A)*[1,1,1], [12,30])
              assert_equal((2 * A).rmatvec([1, 1]), [10, 14, 18])
              assert_equal((2*A).H.matvec([1,1]), [10, 14, 18])
              assert_equal((2*A)*[[1],[1],[1]], [[12],[30]])
              assert_equal((2 * A).matmat([[1], [1], [1]]), [[12], [30]])
              assert_equal((A*2)*[1,1,1], [12,30])
              assert_equal((A*2)*[[1],[1],[1]], [[12],[30]])
              assert_equal((2j*A)*[1,1,1], [12j,30j])
              assert_equal((A+A)*[1,1,1], [12, 30])
              assert_equal((A + A).rmatvec([1, 1]), [10, 14, 18])
              assert_equal((A+A).H.matvec([1,1]), [10, 14, 18])
              assert_equal((A+A)*[[1],[1],[1]], [[12], [30]])
              assert_equal((A+A).matmat([[1],[1],[1]]), [[12], [30]])
              assert_equal((-A)*[1,1,1], [-6,-15])
              assert_equal((-A)*[[1],[1],[1]], [[-6],[-15]])
              assert_equal((A-A)*[1,1,1], [0,0])
              assert_equal((A - A) * [[1], [1], [1]], [[0], [0]])
  
              X = np.array([[1, 2], [3, 4]])
              # A_asarray = np.array([[1, 2, 3], [4, 5, 6]])
              assert_equal((2 * A).rmatmat(X), np.dot((2 * self.A).T, X))
              assert_equal((A * 2).rmatmat(X), np.dot((self.A * 2).T, X))
              assert_equal((2j * A).rmatmat(X),
                           np.dot((2j * self.A).T.conj(), X))
              assert_equal((A * 2j).rmatmat(X),
                           np.dot((self.A * 2j).T.conj(), X))
              assert_equal((A + A).rmatmat(X),
                           np.dot((self.A + self.A).T, X))
              assert_equal((A + 2j * A).rmatmat(X),
                           np.dot((self.A + 2j * self.A).T.conj(), X))
              assert_equal((-A).rmatmat(X), np.dot((-self.A).T, X))
              assert_equal((A - A).rmatmat(X),
                           np.dot((self.A - self.A).T, X))
              assert_equal((2j * A).rmatmat(2j * X),
                           np.dot((2j * self.A).T.conj(), 2j * X))
  
              z = A+A
              assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] is A)
              z = 2*A
              assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] == 2)
  
              assert_(isinstance(A.matvec([1, 2, 3]), np.ndarray))
              assert_(isinstance(A.matvec(np.array([[1],[2],[3]])), np.ndarray))
              assert_(isinstance(A * np.array([1,2,3]), np.ndarray))
              assert_(isinstance(A * np.array([[1],[2],[3]]), np.ndarray))
              assert_(isinstance(A.dot(np.array([1,2,3])), np.ndarray))
              assert_(isinstance(A.dot(np.array([[1],[2],[3]])), np.ndarray))
  
              assert_(isinstance(A.matvec(matrix([[1],[2],[3]])), np.ndarray))
              assert_(isinstance(A * matrix([[1],[2],[3]]), np.ndarray))
              assert_(isinstance(A.dot(matrix([[1],[2],[3]])), np.ndarray))
  
              assert_(isinstance(2*A, interface._ScaledLinearOperator))
              assert_(isinstance(2j*A, interface._ScaledLinearOperator))
              assert_(isinstance(A+A, interface._SumLinearOperator))
              assert_(isinstance(-A, interface._ScaledLinearOperator))
              assert_(isinstance(A-A, interface._SumLinearOperator))
  
              assert_((2j*A).dtype == np.complex_)
  
              assert_raises(ValueError, A.matvec, np.array([1,2]))
              assert_raises(ValueError, A.matvec, np.array([1,2,3,4]))
              assert_raises(ValueError, A.matvec, np.array([[1],[2]]))
              assert_raises(ValueError, A.matvec, np.array([[1],[2],[3],[4]]))
  
              assert_raises(ValueError, lambda: A*A)
              assert_raises(ValueError, lambda: A**2)
  
          for matvecsA, matvecsB in product(get_matvecs(self.A),
                                            get_matvecs(self.B)):
              A = interface.LinearOperator(**matvecsA)
              B = interface.LinearOperator(**matvecsB)
              # AtimesB = np.array([[22, 28], [49, 64]])
              AtimesB = self.A.dot(self.B)
              X = np.array([[1, 2], [3, 4]])
  
              assert_equal((A * B).rmatmat(X), np.dot((AtimesB).T, X))
              assert_equal((2j * A * B).rmatmat(X),
                           np.dot((2j * AtimesB).T.conj(), X))
  
              assert_equal((A*B)*[1,1], [50,113])
              assert_equal((A*B)*[[1],[1]], [[50],[113]])
              assert_equal((A*B).matmat([[1],[1]]), [[50],[113]])
  
              assert_equal((A * B).rmatvec([1, 1]), [71, 92])
              assert_equal((A * B).H.matvec([1, 1]), [71, 92])
  
              assert_(isinstance(A*B, interface._ProductLinearOperator))
  
              assert_raises(ValueError, lambda: A+B)
              assert_raises(ValueError, lambda: A**2)
  
              z = A*B
              assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] is B)
  
          for matvecsC in get_matvecs(self.C):
              C = interface.LinearOperator(**matvecsC)
              X = np.array([[1, 2], [3, 4]])
  
              assert_equal(C.rmatmat(X), np.dot((self.C).T, X))
              assert_equal((C**2).rmatmat(X),
                           np.dot((np.dot(self.C, self.C)).T, X))
  
              assert_equal((C**2)*[1,1], [17,37])
              assert_equal((C**2).rmatvec([1, 1]), [22, 32])
              assert_equal((C**2).H.matvec([1, 1]), [22, 32])
              assert_equal((C**2).matmat([[1],[1]]), [[17],[37]])
  
              assert_(isinstance(C**2, interface._PowerLinearOperator))
  
      def test_matmul(self):
          D = {'shape': self.A.shape,
               'matvec': lambda x: np.dot(self.A, x).reshape(self.A.shape[0]),
               'rmatvec': lambda x: np.dot(self.A.T.conj(),
                                           x).reshape(self.A.shape[1]),
               'rmatmat': lambda x: np.dot(self.A.T.conj(), x),
               'matmat': lambda x: np.dot(self.A, x)}
          A = interface.LinearOperator(**D)
          B = np.array([[1, 2, 3],
                        [4, 5, 6],
                        [7, 8, 9]])
          b = B[0]
  
          assert_equal(operator.matmul(A, b), A * b)
          assert_equal(operator.matmul(A, B), A * B)
          assert_raises(ValueError, operator.matmul, A, 2)
          assert_raises(ValueError, operator.matmul, 2, A)
  
  
  class TestAsLinearOperator(object):
      def setup_method(self):
          self.cases = []
  
          def make_cases(original, dtype):
              cases = []
  
              cases.append((matrix(original, dtype=dtype), original))
              cases.append((np.array(original, dtype=dtype), original))
              cases.append((sparse.csr_matrix(original, dtype=dtype), original))
  
              # Test default implementations of _adjoint and _rmatvec, which
              # refer to each other.
              def mv(x, dtype):
                  y = original.dot(x)
                  if len(x.shape) == 2:
                      y = y.reshape(-1, 1)
                  return y
  
              def rmv(x, dtype):
                  return original.T.conj().dot(x)
  
              class BaseMatlike(interface.LinearOperator):
                  args = ()
  
                  def __init__(self, dtype):
                      self.dtype = np.dtype(dtype)
                      self.shape = original.shape
  
                  def _matvec(self, x):
                      return mv(x, self.dtype)
  
              class HasRmatvec(BaseMatlike):
                  args = ()
  
                  def _rmatvec(self,x):
                      return rmv(x, self.dtype)
  
              class HasAdjoint(BaseMatlike):
                  args = ()
  
                  def _adjoint(self):
                      shape = self.shape[1], self.shape[0]
                      matvec = partial(rmv, dtype=self.dtype)
                      rmatvec = partial(mv, dtype=self.dtype)
                      return interface.LinearOperator(matvec=matvec,
                                                      rmatvec=rmatvec,
                                                      dtype=self.dtype,
                                                      shape=shape)
  
              class HasRmatmat(HasRmatvec):
                  def _matmat(self, x):
                      return original.dot(x)
  
                  def _rmatmat(self, x):
                      return original.T.conj().dot(x)
  
              cases.append((HasRmatvec(dtype), original))
              cases.append((HasAdjoint(dtype), original))
              cases.append((HasRmatmat(dtype), original))
              return cases
  
          original = np.array([[1,2,3], [4,5,6]])
          self.cases += make_cases(original, np.int32)
          self.cases += make_cases(original, np.float32)
          self.cases += make_cases(original, np.float64)
          self.cases += [(interface.aslinearoperator(M).T, A.T)
                         for M, A in make_cases(original.T, np.float64)]
          self.cases += [(interface.aslinearoperator(M).H, A.T.conj())
                         for M, A in make_cases(original.T, np.float64)]
  
          original = np.array([[1, 2j, 3j], [4j, 5j, 6]])
          self.cases += make_cases(original, np.complex_)
          self.cases += [(interface.aslinearoperator(M).T, A.T)
                         for M, A in make_cases(original.T, np.complex_)]
          self.cases += [(interface.aslinearoperator(M).H, A.T.conj())
                         for M, A in make_cases(original.T, np.complex_)]
  
      def test_basic(self):
  
          for M, A_array in self.cases:
              A = interface.aslinearoperator(M)
              M,N = A.shape
  
              xs = [np.array([1, 2, 3]),
                    np.array([[1], [2], [3]])]
              ys = [np.array([1, 2]), np.array([[1], [2]])]
  
              if A.dtype == np.complex_:
                  xs += [np.array([1, 2j, 3j]),
                         np.array([[1], [2j], [3j]])]
                  ys += [np.array([1, 2j]), np.array([[1], [2j]])]
  
              x2 = np.array([[1, 4], [2, 5], [3, 6]])
  
              for x in xs:
                  assert_equal(A.matvec(x), A_array.dot(x))
                  assert_equal(A * x, A_array.dot(x))
  
              assert_equal(A.matmat(x2), A_array.dot(x2))
              assert_equal(A * x2, A_array.dot(x2))
  
              for y in ys:
                  assert_equal(A.rmatvec(y), A_array.T.conj().dot(y))
                  assert_equal(A.T.matvec(y), A_array.T.dot(y))
                  assert_equal(A.H.matvec(y), A_array.T.conj().dot(y))
  
              for y in ys:
                  if y.ndim < 2:
                      continue
                  assert_equal(A.rmatmat(y), A_array.T.conj().dot(y))
                  assert_equal(A.T.matmat(y), A_array.T.dot(y))
                  assert_equal(A.H.matmat(y), A_array.T.conj().dot(y))
  
              if hasattr(M,'dtype'):
                  assert_equal(A.dtype, M.dtype)
  
              assert_(hasattr(A, 'args'))
  
      def test_dot(self):
  
          for M, A_array in self.cases:
              A = interface.aslinearoperator(M)
              M,N = A.shape
  
              x0 = np.array([1, 2, 3])
              x1 = np.array([[1], [2], [3]])
              x2 = np.array([[1, 4], [2, 5], [3, 6]])
  
              assert_equal(A.dot(x0), A_array.dot(x0))
              assert_equal(A.dot(x1), A_array.dot(x1))
              assert_equal(A.dot(x2), A_array.dot(x2))
  
  
  def test_repr():
      A = interface.LinearOperator(shape=(1, 1), matvec=lambda x: 1)
      repr_A = repr(A)
      assert_('unspecified dtype' not in repr_A, repr_A)
  
  
  def test_identity():
      ident = interface.IdentityOperator((3, 3))
      assert_equal(ident * [1, 2, 3], [1, 2, 3])
      assert_equal(ident.dot(np.arange(9).reshape(3, 3)).ravel(), np.arange(9))
  
      assert_raises(ValueError, ident.matvec, [1, 2, 3, 4])
  
  
  def test_attributes():
      A = interface.aslinearoperator(np.arange(16).reshape(4, 4))
  
      def always_four_ones(x):
          x = np.asarray(x)
          assert_(x.shape == (3,) or x.shape == (3, 1))
          return np.ones(4)
  
      B = interface.LinearOperator(shape=(4, 3), matvec=always_four_ones)
  
      for op in [A, B, A * B, A.H, A + A, B + B, A**4]:
          assert_(hasattr(op, "dtype"))
          assert_(hasattr(op, "shape"))
          assert_(hasattr(op, "_matvec"))
  
  def matvec(x):
      """ Needed for test_pickle as local functions are not pickleable """
      return np.zeros(3)
  
  def test_pickle():
      import pickle
  
      for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
          A = interface.LinearOperator((3, 3), matvec)
          s = pickle.dumps(A, protocol=protocol)
          B = pickle.loads(s)
  
          for k in A.__dict__:
              assert_equal(getattr(A, k), getattr(B, k))
  
  def test_inheritance():
      class Empty(interface.LinearOperator):
          pass
  
      with warns(RuntimeWarning, match="should implement at least"):
          assert_raises(TypeError, Empty)
  
      class Identity(interface.LinearOperator):
          def __init__(self, n):
              super(Identity, self).__init__(dtype=None, shape=(n, n))
  
          def _matvec(self, x):
              return x
  
      id3 = Identity(3)
      assert_equal(id3.matvec([1, 2, 3]), [1, 2, 3])
      assert_raises(NotImplementedError, id3.rmatvec, [4, 5, 6])
  
      class MatmatOnly(interface.LinearOperator):
          def __init__(self, A):
              super(MatmatOnly, self).__init__(A.dtype, A.shape)
              self.A = A
  
          def _matmat(self, x):
              return self.A.dot(x)
  
      mm = MatmatOnly(np.random.randn(5, 3))
      assert_equal(mm.matvec(np.random.randn(3)).shape, (5,))
  
  def test_dtypes_of_operator_sum():
      # gh-6078
  
      mat_complex = np.random.rand(2,2) + 1j * np.random.rand(2,2)
      mat_real = np.random.rand(2,2)
  
      complex_operator = interface.aslinearoperator(mat_complex)
      real_operator = interface.aslinearoperator(mat_real)
  
      sum_complex = complex_operator + complex_operator
      sum_real = real_operator + real_operator
  
      assert_equal(sum_real.dtype, np.float64)
      assert_equal(sum_complex.dtype, np.complex128)
  
  def test_no_double_init():
      call_count = [0]
  
      def matvec(v):
          call_count[0] += 1
          return v
  
      # It should call matvec exactly once (in order to determine the
      # operator dtype)
      interface.LinearOperator((2, 2), matvec=matvec)
      assert_equal(call_count[0], 1)
  
  def test_adjoint_conjugate():
      X = np.array([[1j]])
      A = interface.aslinearoperator(X)
  
      B = 1j * A
      Y = 1j * X
  
      v = np.array([1])
  
      assert_equal(B.dot(v), Y.dot(v))
      assert_equal(B.H.dot(v), Y.T.conj().dot(v))
  
  def test_ndim():
      X = np.array([[1]])
      A = interface.aslinearoperator(X)
      assert_equal(A.ndim, 2)
  
  def test_transpose_noconjugate():
      X = np.array([[1j]])
      A = interface.aslinearoperator(X)
  
      B = 1j * A
      Y = 1j * X
  
      v = np.array([1])
  
      assert_equal(B.dot(v), Y.dot(v))
      assert_equal(B.T.dot(v), Y.T.dot(v))
   # -*- coding: utf-8 -*-
  """
  Created on Thu Aug  3 21:08:49 2017
  
  Author: Josef Perktold
  """
  
  import numpy as np
  from numpy.testing import assert_allclose
  from statsmodels.discrete.discrete_model import (Poisson, NegativeBinomial,
                                                   NegativeBinomialP)
  from statsmodels.tools.tools import add_constant
  
  import statsmodels.discrete.tests.results.results_count_margins as res_stata
  
  # load data into module namespace
  from statsmodels.datasets.cpunish import load
  cpunish_data = load(as_pandas=False)
  cpunish_data.exog[:,3] = np.log(cpunish_data.exog[:,3])
  exog = add_constant(cpunish_data.exog, prepend=False)
  endog = cpunish_data.endog - 1 # avoid zero-truncation
  exog /= np.round(exog.max(0), 3)
  
  class CheckMarginMixin(object):
      rtol_fac = 1
  
      def test_margins_table(self):
          res1 = self.res1
          sl = self.res1_slice
          rf = self.rtol_fac
          assert_allclose(self.margeff.margeff, self.res1.params[sl], rtol=1e-5 * rf)
          assert_allclose(self.margeff.margeff_se, self.res1.bse[sl], rtol=1e-6 * rf)
          assert_allclose(self.margeff.pvalues, self.res1.pvalues[sl], rtol=5e-6 * rf)
          assert_allclose(self.margeff.conf_int(), res1.margins_table[sl, 4:6],
                          rtol=1e-6 * rf)
  
  
  class TestPoissonMargin(CheckMarginMixin):
  
      @classmethod
      def setup_class(cls):
          # here we do not need to check convergence from default start_params
          start_params = [14.1709, 0.7085, -3.4548, -0.539, 3.2368,  -7.9299,
                          -5.0529]
          mod_poi = Poisson(endog, exog)
          res_poi = mod_poi.fit(start_params=start_params)
          #res_poi = mod_poi.fit(maxiter=100)
          marge_poi = res_poi.get_margeff()
          cls.res = res_poi
          cls.margeff = marge_poi
  
          cls.rtol_fac = 1
          cls.res1_slice = slice(None, None, None)
          cls.res1 = res_stata.results_poisson_margins_cont
  
  
  class TestPoissonMarginDummy(CheckMarginMixin):
  
      @classmethod
      def setup_class(cls):
          # here we do not need to check convergence from default start_params
          start_params = [14.1709, 0.7085, -3.4548, -0.539, 3.2368,  -7.9299,
                          -5.0529]
          mod_poi = Poisson(endog, exog)
          res_poi = mod_poi.fit(start_params=start_params)
          marge_poi = res_poi.get_margeff(dummy=True)
          cls.res = res_poi
          cls.margeff = marge_poi
  
          cls.res1_slice = [0, 1, 2, 3, 5, 6]
          cls.res1 = res_stata.results_poisson_margins_dummy
  
  
  class TestNegBinMargin(CheckMarginMixin):
  
      @classmethod
      def setup_class(cls):
          # here we do not need to check convergence from default start_params
          start_params = [13.1996, 0.8582, -2.8005, -1.5031, 2.3849, -8.5552,
                          -2.88, 1.14]
          mod = NegativeBinomial(endog, exog)
          res = mod.fit(start_params=start_params, method='nm', maxiter=2000)
          marge = res.get_margeff()
          cls.res = res
          cls.margeff = marge
  
          cls.res1_slice = slice(None, None, None)
          cls.res1 = res_stata.results_negbin_margins_cont
          cls.rtol_fac = 5e1
          # negbin has lower agreement with Stata in this case
  
  
  class TestNegBinMarginDummy(CheckMarginMixin):
  
      @classmethod
      def setup_class(cls):
          # here we do not need to check convergence from default start_params
          start_params = [13.1996, 0.8582, -2.8005, -1.5031, 2.3849, -8.5552,
                          -2.88, 1.14]
          mod = NegativeBinomial(endog, exog)
          res = mod.fit(start_params=start_params, method='nm', maxiter=2000)
          marge = res.get_margeff(dummy=True)
          cls.res = res
          cls.margeff = marge
  
          cls.res1_slice = cls.res1_slice = [0, 1, 2, 3, 5, 6]
          cls.res1 = res_stata.results_negbin_margins_dummy
          cls.rtol_fac = 5e1
  
  
  class TestNegBinPMargin(CheckMarginMixin):
      # this is the same as the nb2 version above for NB-P, p=2
  
      @classmethod
      def setup_class(cls):
          # here we do not need to check convergence from default start_params
          start_params = [13.1996, 0.8582, -2.8005, -1.5031, 2.3849, -8.5552,
                          -2.88, 1.14]
          mod = NegativeBinomialP(endog, exog)   # checks also that default p=2
          res = mod.fit(start_params=start_params, method='nm', maxiter=2000)
          marge = res.get_margeff()
          cls.res = res
          cls.margeff = marge
  
          cls.res1_slice = slice(None, None, None)
          cls.res1 = res_stata.results_negbin_margins_cont
          cls.rtol_fac = 5e1
          # negbin has lower agreement with Stata in this case
   from typing import List
  
  from pandas._typing import FilePathOrBuffer, Scalar, StorageOptions
  from pandas.compat._optional import import_optional_dependency
  
  from pandas.io.excel._base import BaseExcelReader
  
  
  class PyxlsbReader(BaseExcelReader):
      def __init__(
          self,
          filepath_or_buffer: FilePathOrBuffer,
          storage_options: StorageOptions = None,
      ):
          """
          Reader using pyxlsb engine.
  
          Parameters
          ----------
          filepath_or_buffer : str, path object, or Workbook
              Object to be parsed.
          storage_options : dict, optional
              passed to fsspec for appropriate URLs (see ``_get_filepath_or_buffer``)
          """
          import_optional_dependency("pyxlsb")
          # This will call load_workbook on the filepath or buffer
          # And set the result to the book-attribute
          super().__init__(filepath_or_buffer, storage_options=storage_options)
  
      @property
      def _workbook_class(self):
          from pyxlsb import Workbook
  
          return Workbook
  
      def load_workbook(self, filepath_or_buffer: FilePathOrBuffer):
          from pyxlsb import open_workbook
  
          # TODO: hack in buffer capability
          # This might need some modifications to the Pyxlsb library
          # Actual work for opening it is in xlsbpackage.py, line 20-ish
  
          return open_workbook(filepath_or_buffer)
  
      @property
      def sheet_names(self) -> List[str]:
          return self.book.sheets
  
      def get_sheet_by_name(self, name: str):
          self.raise_if_bad_sheet_by_name(name)
          return self.book.get_sheet(name)
  
      def get_sheet_by_index(self, index: int):
          self.raise_if_bad_sheet_by_index(index)
          # pyxlsb sheets are indexed from 1 onwards
          # There's a fix for this in the source, but the pypi package doesn't have it
          return self.book.get_sheet(index + 1)
  
      def _convert_cell(self, cell, convert_float: bool) -> Scalar:
          # TODO: there is no way to distinguish between floats and datetimes in pyxlsb
          # This means that there is no way to read datetime types from an xlsb file yet
          if cell.v is None:
              return ""  # Prevents non-named columns from not showing up as Unnamed: i
          if isinstance(cell.v, float) and convert_float:
              val = int(cell.v)
              if val == cell.v:
                  return val
              else:
                  return float(cell.v)
  
          return cell.v
  
      def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]:
          return [
              [self._convert_cell(c, convert_float) for c in r]
              for r in sheet.rows(sparse=False)
          ]
   import numpy as np
  
  import matplotlib as mpl
  from matplotlib.testing.decorators import image_comparison
  import matplotlib.pyplot as plt
  from mpl_toolkits.axes_grid1 import ImageGrid
  
  
  # The original version of this test relied on mpl_toolkits's slightly different
  # colorbar implementation; moving to matplotlib's own colorbar implementation
  # caused the small image comparison error.
  @image_comparison(['imagegrid_cbar_mode.png'],
                    remove_text=True, style='mpl20', tol=0.3)
  def test_imagegrid_cbar_mode_edge():
      # Remove this line when this test image is regenerated.
      plt.rcParams['pcolormesh.snap'] = False
  
      X, Y = np.meshgrid(np.linspace(0, 6, 30), np.linspace(0, 6, 30))
      arr = np.sin(X) * np.cos(Y) + 1j*(np.sin(3*Y) * np.cos(Y/2.))
  
      fig = plt.figure(figsize=(18, 9))
  
      positions = (241, 242, 243, 244, 245, 246, 247, 248)
      directions = ['row']*4 + ['column']*4
      cbar_locations = ['left', 'right', 'top', 'bottom']*2
  
      for position, direction, location in zip(
              positions, directions, cbar_locations):
          grid = ImageGrid(fig, position,
                           nrows_ncols=(2, 2),
                           direction=direction,
                           cbar_location=location,
                           cbar_size='20%',
                           cbar_mode='edge')
          ax1, ax2, ax3, ax4, = grid
  
          ax1.imshow(arr.real, cmap='nipy_spectral')
          ax2.imshow(arr.imag, cmap='hot')
          ax3.imshow(np.abs(arr), cmap='jet')
          ax4.imshow(np.arctan2(arr.imag, arr.real), cmap='hsv')
  
          # In each row/column, the "first" colorbars must be overwritten by the
          # "second" ones.  To achieve this, clear out the axes first.
          for ax in grid:
              ax.cax.cla()
              cb = ax.cax.colorbar(
                  ax.images[0],
                  ticks=mpl.ticker.MaxNLocator(5))  # old default locator.
  
  
  def test_imagegrid():
      fig = plt.figure()
      grid = ImageGrid(fig, 111, nrows_ncols=(1, 1))
      ax = grid[0]
      im = ax.imshow([[1, 2]], norm=mpl.colors.LogNorm())
      cb = ax.cax.colorbar(im)
      assert isinstance(cb.locator, mpl.colorbar._ColorbarLogLocator)
  
apis: pandas._testing.assert_numpy_array_equal pandas.tests.plotting.common.TestPlotBase.setup_method matplotlib.pyplot.gcf pandas._testing.assert_produces_warning numpy.random.choice pandas._testing.close pandas._testing.assert_almost_equal numpy.random.rand pandas.tests.plotting.common._check_plot_works pandas._testing.RNGContext pandas.Index matplotlib.rcdefaults pandas.plotting._matplotlib.hist._grouped_hist pandas._testing.makeTimeSeries pandas.DataFrame numpy.random.randn matplotlib.pyplot.subplot numpy.random.normal numpy.random.randint
apis: numpy.testing.assert_almost_equal numpy.testing.assert_raises pandas.date_range numpy.testing.assert_equal pandas.concat numpy.testing.assert_allclose numpy.array numpy.testing.assert_
apis: numpy.linspace
apis: numpy.allclose numpy.ones numpy.eye scipy.linalg.norm numpy.zeros numpy.testing.assert_equal scipy.sparse.rand numpy.random.seed scipy.sparse.eye numpy.nextafter scipy.sparse.linalg.isolve.gcrotmk numpy.random.rand numpy.testing.assert_allclose numpy.array numpy.testing.suppress_warnings scipy.sparse.linalg.interface.LinearOperator numpy.testing.assert_
apis: numpy.ones numpy.zeros numpy.testing.assert_equal scipy.sparse.linalg.interface.IdentityOperator numpy.dtype numpy.random.randn numpy.asarray scipy.sparse.csr_matrix numpy.arange scipy.sparse.linalg.interface.aslinearoperator numpy.random.rand scipy.sparse.sputils.matrix numpy.array numpy.dot scipy.sparse.linalg.interface.LinearOperator numpy.testing.assert_
apis: numpy.log numpy.testing.assert_allclose
apis: pandas.compat._optional.import_optional_dependency
apis: matplotlib.ticker.MaxNLocator numpy.arctan2 matplotlib.pyplot.figure numpy.abs numpy.cos matplotlib.testing.decorators.image_comparison matplotlib.colors.LogNorm numpy.sin numpy.linspace