Exemple #1
0
def test_context_with_badparam():
    original_value = 'gray'
    other_value = 'blue'
    d = OrderedDict([(PARAM, original_value), ('badparam', None)])
    with style.context({PARAM: other_value}):
        assert mpl.rcParams[PARAM] == other_value
        x = style.context([d])
        assert_raises(KeyError, x.__enter__)
        assert mpl.rcParams[PARAM] == other_value
Exemple #2
0
def test_context_with_badparam():
    original_value = 'gray'
    other_value = 'blue'
    d = OrderedDict([(PARAM, original_value), ('badparam', None)])
    with style.context({PARAM: other_value}):
        assert mpl.rcParams[PARAM] == other_value
        x = style.context([d])
        assert_raises(KeyError, x.__enter__)
        assert mpl.rcParams[PARAM] == other_value
Exemple #3
0
def test_context_with_badparam():
    original_value = 'gray'
    other_value = 'blue'
    with style.context({PARAM: other_value}):
        assert mpl.rcParams[PARAM] == other_value
        x = style.context({PARAM: original_value, 'badparam': None})
        with pytest.raises(KeyError):
            with x:
                pass
        assert mpl.rcParams[PARAM] == other_value
Exemple #4
0
def test_context_with_badparam():
    if sys.version_info[:2] >= (2, 7):
        from collections import OrderedDict
    else:
        m = "Test can only be run in Python >= 2.7 as it requires OrderedDict"
        raise SkipTest(m)

    original_value = 'gray'
    other_value = 'blue'
    d = OrderedDict([(PARAM, original_value), ('badparam', None)])
    with style.context({PARAM: other_value}):
        assert mpl.rcParams[PARAM] == other_value
        x = style.context([d])
        assert_raises(KeyError, x.__enter__)
        assert mpl.rcParams[PARAM] == other_value
Exemple #5
0
def test_skewt_gridspec():
    'Test using SkewT on a sub-plot'
    with style.context(test_style):
        fig = make_figure(figsize=(9, 9))
        gs = GridSpec(1, 2)
        hide_tick_labels(SkewT(fig, subplot=gs[0, 1]).ax)
        return fig
Exemple #6
0
def test_skewt_gridspec():
    'Test using SkewT on a sub-plot'
    with style.context(test_style):
        fig = make_figure(figsize=(9, 9))
        gs = GridSpec(1, 2)
        hide_tick_labels(SkewT(fig, subplot=gs[0, 1]).ax)
        return fig
Exemple #7
0
def generate_fig4():

    with style.context("ggplot"):

        v_data = read_data("data/imitation data/v/")

        x = [i.g_accuracy for i in v_data]
        y = [i.win_rate for i in v_data]

        fig = Figure()
        canvas = FigureCanvas(fig)
        ax = fig.add_subplot(1, 1, 1)
        ax.plot(x, y, ".")
        ax.set_xlabel("Accuracy")
        ax.set_ylabel("Win Rate")
        ax.set_title(
            "Win Rate as a function of Accuracy\n(sample size=2000000, sampled from games)"
        )
        common.save_next_fig(PART_NUM, fig)

        x = [i.epoch for i in v_data]
        y1 = [i.g_accuracy for i in v_data]
        y2 = [i.win_rate for i in v_data]

        fig = Figure()
        canvas = FigureCanvas(fig)
        ax = fig.add_axes((0.1, 0.1, 0.8, 0.8))
        ax.plot(x, y1, ".", label="Accuracy")
        ax.plot(x, y2, ".", label="Win Rate")
        ax.set_xlabel("Epoch")
        ax.legend()
        ax.set_title(
            "Win Rate and Accuracy as a function of Epoch\n(sample size=2000000, sampled from games)"
        )
        common.save_next_fig(PART_NUM, fig)

        t_data = read_data("data/imitation data/t/")
        a_data = read_data("data/imitation data/a/")

        fig = Figure()
        canvas = FigureCanvas(fig)
        ax = fig.add_subplot(1, 1, 1)

        x = [i.epoch for i in v_data]
        y = [i.win_rate for i in v_data]
        ax.plot(x, y, ".", label="Vanilla")

        x = [i.epoch for i in t_data]
        y = [i.win_rate for i in t_data]
        ax.plot(x, y, ".", label="Decomposed")

        x = [i.epoch for i in a_data]
        y = [i.win_rate for i in a_data]
        ax.plot(x, y, ".", label="Uniform Sampling")

        ax.set_xlabel("Epoch")
        ax.set_ylabel("Win Rate")
        ax.legend()
        ax.set_title("Comparison of Different Settings\n(sample size=2000000)")
        common.save_next_fig(PART_NUM, fig)
Exemple #8
0
def test_context():
    mpl.rcParams[PARAM] = 'gray'
    with temp_style('test', DUMMY_SETTINGS):
        with style.context('test'):
            assert mpl.rcParams[PARAM] == VALUE
    # Check that this value is reset after the exiting the context.
    assert mpl.rcParams[PARAM] == 'gray'
def test_stationlayout_api():
    'Test the StationPlot api'
    setup_font()
    with style.context(test_style):
        fig = make_figure(figsize=(9, 9))

        # testing data
        x = np.array([1, 5])
        y = np.array([2, 4])
        data = dict()
        data['temp'] = np.array([32., 212.]) * units.degF
        data['u'] = np.array([2, 0]) * units.knots
        data['v'] = np.array([0, 5]) * units.knots
        data['stid'] = ['KDEN', 'KSHV']
        data['cover'] = [3, 8]

        # Set up the layout
        layout = StationPlotLayout()
        layout.add_barb('u', 'v', units='knots')
        layout.add_value('NW', 'temp', fmt='0.1f', units=units.degC, color='darkred')
        layout.add_symbol('C', 'cover', sky_cover, color='magenta')
        layout.add_text((0, 2), 'stid', color='darkgrey')
        layout.add_value('NE', 'dewpt', color='green')  # This should be ignored

        # Make the plot
        sp = StationPlot(fig.add_subplot(1, 1, 1), x, y, fontsize=12)
        layout.plot(sp, data)

        sp.ax.set_xlim(0, 6)
        sp.ax.set_ylim(0, 6)
        hide_tick_labels(sp.ax)

        return fig
Exemple #10
0
def test_context_with_dict():
    original_value = 'gray'
    other_value = 'blue'
    mpl.rcParams[PARAM] = original_value
    with style.context({PARAM: other_value}):
        assert mpl.rcParams[PARAM] == other_value
    assert mpl.rcParams[PARAM] == original_value
Exemple #11
0
def test_nws_layout():
    'Test metpy\'s NWS layout for station plots'
    setup_font()
    with style.context(test_style):
        fig = make_figure(figsize=(3, 3))

        # testing data
        x = np.array([1])
        y = np.array([2])
        data = dict()
        data['air_temperature'] = np.array([77]) * units.degF
        data['dew_point_temperature'] = np.array([71]) * units.degF
        data['air_pressure_at_sea_level'] = np.array([999.8]) * units('mbar')
        data['eastward_wind'] = np.array([15.]) * units.knots
        data['northward_wind'] = np.array([15.]) * units.knots
        data['cloud_coverage'] = [7]
        data['present_weather'] = [80]
        data['high_cloud_type'] = [1]
        data['medium_cloud_type'] = [3]
        data['low_cloud_type'] = [2]
        data['visibility_in_air'] = np.array([5.]) * units.mile
        data['tendency_of_air_pressure'] = np.array([-0.3]) * units('mbar')
        data['tendency_of_air_pressure_symbol'] = [8]

        # Make the plot
        sp = StationPlot(fig.add_subplot(1, 1, 1), x, y, fontsize=12, spacing=16)
        nws_layout.plot(sp, data)

        sp.ax.set_xlim(0, 3)
        sp.ax.set_ylim(0, 3)
        hide_tick_labels(sp.ax)

        return fig
Exemple #12
0
def test_simple_layout():
    'Test metpy\'s simple layout for station plots'
    setup_font()
    with style.context(test_style):
        fig = make_figure(figsize=(9, 9))

        # testing data
        x = np.array([1, 5])
        y = np.array([2, 4])
        data = dict()
        data['air_temperature'] = np.array([32., 212.]) * units.degF
        data['dew_point_temperature'] = np.array([28., 80.]) * units.degF
        data['air_pressure_at_sea_level'] = np.array([29.92, 28.00]) * units.inHg
        data['eastward_wind'] = np.array([2, 0]) * units.knots
        data['northward_wind'] = np.array([0, 5]) * units.knots
        data['cloud_coverage'] = [3, 8]
        data['present_weather'] = [65, 75]
        data['unused'] = [1, 2]

        # Make the plot
        sp = StationPlot(fig.add_subplot(1, 1, 1), x, y, fontsize=12)
        simple_layout.plot(sp, data)

        sp.ax.set_xlim(0, 6)
        sp.ax.set_ylim(0, 6)
        hide_tick_labels(sp.ax)

        return fig
Exemple #13
0
def test_stationlayout_api():
    """Test the StationPlot API."""
    setup_font()
    with style.context(test_style):
        fig = make_figure(figsize=(9, 9))

        # testing data
        x = np.array([1, 5])
        y = np.array([2, 4])
        data = dict()
        data['temp'] = np.array([32., 212.]) * units.degF
        data['u'] = np.array([2, 0]) * units.knots
        data['v'] = np.array([0, 5]) * units.knots
        data['stid'] = ['KDEN', 'KSHV']
        data['cover'] = [3, 8]

        # Set up the layout
        layout = StationPlotLayout()
        layout.add_barb('u', 'v', units='knots')
        layout.add_value('NW', 'temp', fmt='0.1f', units=units.degC, color='darkred')
        layout.add_symbol('C', 'cover', sky_cover, color='magenta')
        layout.add_text((0, 2), 'stid', color='darkgrey')
        layout.add_value('NE', 'dewpt', color='green')  # This should be ignored

        # Make the plot
        sp = StationPlot(fig.add_subplot(1, 1, 1), x, y, fontsize=12)
        layout.plot(sp, data)

        sp.ax.set_xlim(0, 6)
        sp.ax.set_ylim(0, 6)
        hide_tick_labels(sp.ax)

        return fig
Exemple #14
0
 def run(self):
     scan_loader = self._make_scan_loader()
     gpsms = self._load_spectrum_matches()
     if not os.path.exists(self.output_path):
         os.makedirs(self.output_path)
     n = len(gpsms)
     self.log("%d Spectrum Matches" % (n,))
     for i, gpsm in enumerate(gpsms):
         scan = scan_loader.get_scan_by_id(gpsm.scan.scan_id)
         gpep = gpsm.structure.convert()
         if i % 10 == 0:
             self.log("... %0.2f%%: %s @ %s" % (((i + 1) / float(n) * 100.0), gpep, scan.id))
         with style.context(self._mpl_style):
             fig = figure()
             grid = plt.GridSpec(nrows=5, ncols=1)
             ax1 = fig.add_subplot(grid[1, 0])
             ax2 = fig.add_subplot(grid[2:, 0])
             ax3 = fig.add_subplot(grid[0, 0])
             match = CoverageWeightedBinomialModelTree.evaluate(scan, gpep)
             ax3.text(0, 0.5, (
                 str(match.target) + '\n' + scan.id +
                 '\nscore=%0.3f    q value=%0.3g' % (gpsm.score, gpsm.q_value)), va='center')
             ax3.axis('off')
             match.plot(ax=ax2)
             glycopeptide_match_logo(match, ax=ax1)
             fname = format_filename("%s_%s.pdf" % (scan.id, gpep))
             path = os.path.join(self.output_path, fname)
             abspath = os.path.abspath(path)
             if len(abspath) > 259 and platform.system().lower() == 'windows':
                 abspath = '\\\\?\\' + abspath
             fig.savefig(abspath, bbox_inches='tight')
             plt.close(fig)
Exemple #15
0
    def __init__(self,
                 image_path,
                 image_name,
                 reltol=1,
                 adjust_tolerance=True,
                 plt_close_all_enter=True,
                 plt_close_all_exit=True,
                 style=None,
                 *args,
                 **kwargs):
        self.suffix = "." + image_name.split(".")[-1]
        super(ImageComparison, self).__init__(suffix=self.suffix,
                                              *args,
                                              **kwargs)
        self.image_name = image_name
        self.baseline_image = os.path.join(image_path, image_name)
        self.keep_output = "OBSPY_KEEP_IMAGES" in os.environ
        self.keep_only_failed = "OBSPY_KEEP_ONLY_FAILED_IMAGES" in os.environ
        self.output_path = os.path.join(image_path, "testrun")
        self.diff_filename = "-failed-diff.".join(self.name.rsplit(".", 1))
        self.tol = reltol * 3.0
        self.plt_close_all_enter = plt_close_all_enter
        self.plt_close_all_exit = plt_close_all_exit

        if (MATPLOTLIB_VERSION < [1, 4, 0]
                or (MATPLOTLIB_VERSION[:2] == [1, 4] and style is None)):
            # No good style support.
            self.style = None
        else:
            import matplotlib.style as mstyle
            self.style = mstyle.context(style or 'classic')

        # Adjust the tolerance based on the matplotlib version. This works
        # well enough and otherwise testing is just a pain.
        #
        # The test images were generated with matplotlib tag 291091c6eb267
        # which is after https://github.com/matplotlib/matplotlib/issues/7905
        # has been fixed.
        #
        # Thus test images should accurate for matplotlib >= 2.0.1 anf
        # fairly accurate for matplotlib 1.5.x.
        if adjust_tolerance:
            # Really old versions.
            if MATPLOTLIB_VERSION < [1, 3, 0]:
                self.tol *= 30
            # 1.3 + 1.4 have slightly different text positioning mostly.
            elif [1, 3, 0] <= MATPLOTLIB_VERSION < [1, 5, 0]:
                self.tol *= 15
            # A few plots with mpl 1.5 have ticks and axis slightl shifted.
            # This is especially true for ticks with exponential numbers.
            # Thus the tolerance also has to be a bit higher here.
            elif [1, 5, 0] <= MATPLOTLIB_VERSION < [2, 0, 0]:
                self.tol *= 5.0
            # Matplotlib 2.0.0 has a bug with the tick placement. This is
            # fixed in 2.0.1 but the tolerance for 2.0.0 has to be much
            # higher. 10 is an empiric value. The tick placement potentially
            # influences the axis locations and then the misfit is really
            # quite high.
            elif [2, 0, 0] <= MATPLOTLIB_VERSION < [2, 0, 1]:
                self.tol *= 10
Exemple #16
0
def base_plot(df, part, cut=30, xlabel="Number of Episodes", jump=5):
    data = df.data[:cut]
    label = df.label
    with style.context("ggplot"):
        fig = Figure()
        canvas = FigureCanvas(fig)
        ax1 = fig.add_subplot(1, 1, 1)
        ax2 = ax1.twiny()
        
        ax1.plot([i.episodes for i in data], [i.win_rate for i in data], "-o")
        
        ax1.set_ylim(0., 1.1)
        ax1.set_xlim(0, data[-1].episodes + data[0].episodes)
        ax2.set_xlim(0, data[-1].episodes + data[0].episodes)
        
        ax1.set_xticks([i.episodes for i in data[::jump]])
        ax1.set_xticklabels(["{:.1e}".format(i.episodes) for i in data[::jump]])
        ax2.set_xticks([i.episodes for i in data[::jump]])
        ax2.set_xticklabels(["{:.1e}".format(i.time) for i in data[::jump]])
        
        fig.suptitle("Win Rate of {}".format(label))
        fig.subplots_adjust(top=0.8)
        ax1.set_xlabel(xlabel)
        ax1.set_ylabel("Win Rate")
        ax2.set_xlabel("Time (seconds)")
        p = Path("figures/part{}/".format(part))
        p.mkdir(parents=True, exist_ok=True)
        fig.savefig(str(p / "plot_{}.png".format(df.name)))
Exemple #17
0
def test_simple_layout():
    """Test metpy's simple layout for station plots."""
    setup_font()
    with style.context(test_style):
        fig = make_figure(figsize=(9, 9))

        # testing data
        x = np.array([1, 5])
        y = np.array([2, 4])
        data = dict()
        data['air_temperature'] = np.array([32., 212.]) * units.degF
        data['dew_point_temperature'] = np.array([28., 80.]) * units.degF
        data['air_pressure_at_sea_level'] = np.array([29.92, 28.00]) * units.inHg
        data['eastward_wind'] = np.array([2, 0]) * units.knots
        data['northward_wind'] = np.array([0, 5]) * units.knots
        data['cloud_coverage'] = [3, 8]
        data['present_weather'] = [65, 75]
        data['unused'] = [1, 2]

        # Make the plot
        sp = StationPlot(fig.add_subplot(1, 1, 1), x, y, fontsize=12)
        simple_layout.plot(sp, data)

        sp.ax.set_xlim(0, 6)
        sp.ax.set_ylim(0, 6)
        hide_tick_labels(sp.ax)

        return fig
Exemple #18
0
def test_nws_layout():
    """Test metpy's NWS layout for station plots."""
    setup_font()
    with style.context(test_style):
        fig = make_figure(figsize=(3, 3))

        # testing data
        x = np.array([1])
        y = np.array([2])
        data = dict()
        data['air_temperature'] = np.array([77]) * units.degF
        data['dew_point_temperature'] = np.array([71]) * units.degF
        data['air_pressure_at_sea_level'] = np.array([999.8]) * units('mbar')
        data['eastward_wind'] = np.array([15.]) * units.knots
        data['northward_wind'] = np.array([15.]) * units.knots
        data['cloud_coverage'] = [7]
        data['present_weather'] = [80]
        data['high_cloud_type'] = [1]
        data['medium_cloud_type'] = [3]
        data['low_cloud_type'] = [2]
        data['visibility_in_air'] = np.array([5.]) * units.mile
        data['tendency_of_air_pressure'] = np.array([-0.3]) * units('mbar')
        data['tendency_of_air_pressure_symbol'] = [8]

        # Make the plot
        sp = StationPlot(fig.add_subplot(1, 1, 1), x, y, fontsize=12, spacing=16)
        nws_layout.plot(sp, data)

        sp.ax.set_xlim(0, 3)
        sp.ax.set_ylim(0, 3)
        hide_tick_labels(sp.ax)

        return fig
Exemple #19
0
def test_use_url(tmpdir):
    path = Path(tmpdir, 'file')
    path.write_text('axes.facecolor: adeade')
    with temp_style('test', DUMMY_SETTINGS):
        url = ('file:' + ('///' if sys.platform == 'win32' else '') +
               path.resolve().as_posix())
        with style.context(url):
            assert mpl.rcParams['axes.facecolor'] == "#adeade"
Exemple #20
0
def test_single_path(tmpdir):
    mpl.rcParams[PARAM] = 'gray'
    temp_file = f'text.{STYLE_EXTENSION}'
    path = Path(tmpdir, temp_file)
    path.write_text(f'{PARAM} : {VALUE}')
    with style.context(path):
        assert mpl.rcParams[PARAM] == VALUE
    assert mpl.rcParams[PARAM] == 'gray'
Exemple #21
0
def test_use_url(tmpdir):
    path = Path(tmpdir, 'file')
    path.write_text('axes.facecolor: adeade')
    with temp_style('test', DUMMY_SETTINGS):
        url = ('file:'
               + ('///' if sys.platform == 'win32' else '')
               + path.resolve().as_posix())
        with style.context(url):
            assert mpl.rcParams['axes.facecolor'] == "#adeade"
Exemple #22
0
def test_context_with_dict_after_namedstyle():
    # Test dict after style name where dict modifies the same parameter.
    original_value = 'gray'
    other_value = 'blue'
    mpl.rcParams[PARAM] = original_value
    with temp_style('test', DUMMY_SETTINGS):
        with style.context(['test', {PARAM: other_value}]):
            assert mpl.rcParams[PARAM] == other_value
    assert mpl.rcParams[PARAM] == original_value
Exemple #23
0
def test_alias(equiv_styles):
    rc_dicts = []
    for sty in equiv_styles:
        with style.context(sty):
            rc_dicts.append(dict(mpl.rcParams))

    rc_base = rc_dicts[0]
    for nm, rc in zip(equiv_styles[1:], rc_dicts[1:]):
        assert rc_base == rc
Exemple #24
0
    def __init__(self, image_path, image_name, reltol=1,
                 adjust_tolerance=True, plt_close_all_enter=True,
                 plt_close_all_exit=True, style=None, no_uploads=False, *args,
                 **kwargs):
        self.suffix = "." + image_name.split(".")[-1]
        super(ImageComparison, self).__init__(suffix=self.suffix, *args,
                                              **kwargs)
        self.image_name = image_name
        self.baseline_image = os.path.join(image_path, image_name)
        self.keep_output = "OBSPY_KEEP_IMAGES" in os.environ
        self.keep_only_failed = "OBSPY_KEEP_ONLY_FAILED_IMAGES" in os.environ
        self.output_path = os.path.join(image_path, "testrun")
        self.diff_filename = "-failed-diff.".join(self.name.rsplit(".", 1))
        self.tol = reltol * 3.0
        self.plt_close_all_enter = plt_close_all_enter
        self.plt_close_all_exit = plt_close_all_exit
        self.no_uploads = no_uploads

        if (MATPLOTLIB_VERSION < [1, 4, 0] or
                (MATPLOTLIB_VERSION[:2] == [1, 4] and style is None)):
            # No good style support.
            self.style = None
        else:
            import matplotlib.style as mstyle
            self.style = mstyle.context(style or 'classic')

        # Adjust the tolerance based on the matplotlib version. This works
        # well enough and otherwise testing is just a pain.
        #
        # The test images were generated with matplotlib tag 291091c6eb267
        # which is after https://github.com/matplotlib/matplotlib/issues/7905
        # has been fixed.
        #
        # Thus test images should accurate for matplotlib >= 2.0.1 anf
        # fairly accurate for matplotlib 1.5.x.
        if adjust_tolerance:
            # Really old versions.
            if MATPLOTLIB_VERSION < [1, 3, 0]:
                self.tol *= 30
            # 1.3 + 1.4 have slightly different text positioning mostly.
            elif [1, 3, 0] <= MATPLOTLIB_VERSION < [1, 5, 0]:
                self.tol *= 15
            # A few plots with mpl 1.5 have ticks and axis slightl shifted.
            # This is especially true for ticks with exponential numbers.
            # Thus the tolerance also has to be a bit higher here.
            elif [1, 5, 0] <= MATPLOTLIB_VERSION < [2, 0, 0]:
                self.tol *= 5.0
            # Matplotlib 2.0.0 has a bug with the tick placement. This is
            # fixed in 2.0.1 but the tolerance for 2.0.0 has to be much
            # higher. 10 is an empiric value. The tick placement potentially
            # influences the axis locations and then the misfit is really
            # quite high.
            elif [2, 0, 0] <= MATPLOTLIB_VERSION < [2, 0, 1]:
                self.tol *= 10
Exemple #25
0
def test_hodograph_api():
    'Basic test of Hodograph API'
    with style.context(test_style):
        fig = make_figure(figsize=(9, 9))
        ax = fig.add_subplot(1, 1, 1)
        hodo = Hodograph(ax, component_range=60)
        hodo.add_grid(increment=5, color='k')
        hodo.plot([1, 10], [1, 10], color='red')
        hodo.plot_colormapped(np.array([1, 3, 5, 10]), np.array([2, 4, 6, 11]),
                              np.array([0.1, 0.3, 0.5, 0.9]), cmap='Greys')
        hide_tick_labels(ax)
        return fig
Exemple #26
0
def test_hodograph_units():
    'Test passing unit-ed quantities to Hodograph'
    with style.context(test_style):
        fig = make_figure(figsize=(9, 9))
        ax = fig.add_subplot(1, 1, 1)
        hodo = Hodograph(ax)
        u = np.arange(10) * units.kt
        v = np.arange(10) * units.kt
        hodo.plot(u, v)
        hodo.plot_colormapped(u, v, np.sqrt(u * u + v * v), cmap='Greys')
        hide_tick_labels(ax)
        return fig
Exemple #27
0
def test_hodograph_api():
    'Basic test of Hodograph API'
    with style.context(test_style):
        fig = make_figure(figsize=(9, 9))
        ax = fig.add_subplot(1, 1, 1)
        hodo = Hodograph(ax, component_range=60)
        hodo.add_grid(increment=5, color='k')
        hodo.plot([1, 10], [1, 10], color='red')
        hodo.plot_colormapped(np.array([1, 3, 5, 10]), np.array([2, 4, 6, 11]),
                              np.array([0.1, 0.3, 0.5, 0.9]), cmap='Greys')
        hide_tick_labels(ax)
        return fig
Exemple #28
0
def test_hodograph_units():
    'Test passing unit-ed quantities to Hodograph'
    with style.context(test_style):
        fig = make_figure(figsize=(9, 9))
        ax = fig.add_subplot(1, 1, 1)
        hodo = Hodograph(ax)
        u = np.arange(10) * units.kt
        v = np.arange(10) * units.kt
        hodo.plot(u, v)
        hodo.plot_colormapped(u, v, np.sqrt(u * u + v * v), cmap='Greys')
        hide_tick_labels(ax)
        return fig
Exemple #29
0
def test_multi_color_hatch():
    fig, ax = plt.subplots()

    rects = ax.bar(range(5), range(1, 6))
    for i, rect in enumerate(rects):
        rect.set_facecolor('none')
        rect.set_edgecolor('C{}'.format(i))
        rect.set_hatch('/')

    for i in range(5):
        with mstyle.context({'hatch.color': 'C{}'.format(i)}):
            r = Rectangle((i - .8 / 2, 5), .8, 1, hatch='//', fc='none')
        ax.add_patch(r)
Exemple #30
0
def test_multi_color_hatch():
    fig, ax = plt.subplots()

    rects = ax.bar(range(5), range(1, 6))
    for i, rect in enumerate(rects):
        rect.set_facecolor('none')
        rect.set_edgecolor('C{}'.format(i))
        rect.set_hatch('/')

    for i in range(5):
        with mstyle.context({'hatch.color': 'C{}'.format(i)}):
            r = Rectangle((i-.8/2, 5), .8, 1, hatch='//', fc='none')
        ax.add_patch(r)
Exemple #31
0
    def _makedos(self,
                 ax,
                 dos_plotter,
                 dos_options,
                 dos_label=None,
                 plot_legend=True):
        """This is basically the same as the SDOSPlotter get_plot function."""

        # don't use first 4 colours; these are the band structure line colours
        cycle = cycler("color",
                       rcParams["axes.prop_cycle"].by_key()["color"][4:])
        with context({"axes.prop_cycle": cycle}):
            plot_data = dos_plotter.dos_plot_data(**dos_options)

        mask = plot_data["mask"]
        energies = plot_data["energies"][mask]
        lines = plot_data["lines"]
        spins = [Spin.up] if len(
            lines[0][0]["dens"]) == 1 else [Spin.up, Spin.down]

        # disable y ticks for DOS panel
        ax.tick_params(axis="y", which="both", right=False)

        for line_set in plot_data["lines"]:
            for line, spin in it.product(line_set, spins):
                if spin == Spin.up:
                    label = line["label"]
                    densities = line["dens"][spin][mask]
                else:
                    label = ""
                    densities = -line["dens"][spin][mask]
                ax.fill_betweenx(
                    energies,
                    densities,
                    0,
                    lw=0,
                    facecolor=line["colour"],
                    alpha=line["alpha"],
                )
                ax.plot(densities, energies, label=label, color=line["colour"])

            # x and y axis reversed versus normal dos plotting
            ax.set_ylim(dos_options["xmin"], dos_options["xmax"])
            ax.set_xlim(plot_data["ymin"], plot_data["ymax"])

            if dos_label is not None:
                ax.set_xlabel(dos_label)

        ax.set_xticklabels([])
        if plot_legend:
            ax.legend(loc=2, frameon=False, ncol=1, bbox_to_anchor=(1.0, 1.0))
Exemple #32
0
def context(style='light', after_reset=False):
    """Context manager for using plot styles temporarily.

    This context manager supports the two pyfar styles ``light`` and ``dark``.
    It is a wrapper for ``matplotlib.pyplot.style.context()``.

    Parameters
    ----------
    style : str, dict, Path or list
        A style specification. Valid options are:

        +------+-------------------------------------------------------------+
        | str  | The name of a style or a path/URL to a style file. For a    |
        |      | list of available style names, see                          |
        |      | ``matplotlib.style.available``.                             |
        +------+-------------------------------------------------------------+
        | dict | Dictionary with valid key/value pairs for                   |
        |      | ``matplotlib.rcParams``.                                    |
        +------+-------------------------------------------------------------+
        | Path | A path-like object which is a path to a style file.         |
        +------+-------------------------------------------------------------+
        | list | A list of style specifiers (str, Path or dict) applied from |
        |      | first to last in the list.                                  |
        +------+-------------------------------------------------------------+

    after_reset : bool
        If ``True``, apply style after resetting settings to their defaults;
        otherwise, apply style on top of the current settings.

    See also
    --------
    pyfar.plot.plotstyle

    Examples
    --------

    Generate customizable subplots with the default pyfar plot style

    >>> import pyfar as pf
    >>> import matplotlib.pyplot as plt
    >>> with pf.plot.context():
    >>>     fig, ax = plt.subplots(2, 1)
    >>>     pf.plot.time(pf.Signal([0, 1, 0, -1], 44100), ax=ax[0])
    """

    # get pyfar plotstyle if desired
    style = plotstyle(style)

    # apply plot style
    with mpl_style.context(style):
        yield
Exemple #33
0
def test_context_with_union_of_dict_and_namedstyle():
    # Test dict after style name where dict modifies the a different parameter.
    original_value = 'gray'
    other_param = 'text.usetex'
    other_value = True
    d = {other_param: other_value}
    mpl.rcParams[PARAM] = original_value
    mpl.rcParams[other_param] = (not other_value)
    with temp_style('test', DUMMY_SETTINGS):
        with style.context(['test', d]):
            assert mpl.rcParams[PARAM] == VALUE
            assert mpl.rcParams[other_param] == other_value
    assert mpl.rcParams[PARAM] == original_value
    assert mpl.rcParams[other_param] == (not other_value)
Exemple #34
0
    def __init__(self,
                 image_path,
                 image_name,
                 reltol=1,
                 adjust_tolerance=True,
                 plt_close_all_enter=True,
                 plt_close_all_exit=True,
                 style=None,
                 no_uploads=False,
                 *args,
                 **kwargs):
        self.suffix = "." + image_name.split(".")[-1]
        super(ImageComparison, self).__init__(suffix=self.suffix,
                                              *args,
                                              **kwargs)
        self.image_name = image_name
        self.baseline_image = os.path.join(image_path, image_name)
        self.keep_output = "OBSPY_KEEP_IMAGES" in os.environ
        self.keep_only_failed = "OBSPY_KEEP_ONLY_FAILED_IMAGES" in os.environ
        self.output_path = os.path.join(image_path, "testrun")
        self.diff_filename = "-failed-diff.".join(self.name.rsplit(".", 1))
        self.tol = reltol * 3.0
        self.plt_close_all_enter = plt_close_all_enter
        self.plt_close_all_exit = plt_close_all_exit
        self.no_uploads = no_uploads

        import matplotlib.style as mstyle
        self.style = mstyle.context(style or 'classic')

        # Adjust the tolerance based on the matplotlib version. This works
        # well enough and otherwise testing is just a pain.
        #
        # The test images were generated with matplotlib tag 291091c6eb267
        # which is after https://github.com/matplotlib/matplotlib/issues/7905
        # has been fixed.
        #
        # Thus test images should accurate for matplotlib >= 2.0.1.
        if adjust_tolerance:
            # Adjusts tolerance depending on the freetype version.
            # XXX: Should eventually be handled differently!
            try:
                from matplotlib import ft2font
            except ImportError:
                pass
            else:
                if hasattr(ft2font, "__freetype_version__"):
                    if (LooseVersion(ft2font.__freetype_version__) >=
                            LooseVersion("2.8.0")):
                        self.tol *= 10
Exemple #35
0
        def savefig_latex():
            style_path = pt(
                __file__).parent / "matplolib_styles/styles/science.mplstyle"
            with style.context([f"{style_path}"]):
                self.fig2, self.ax2 = plt.subplots()
                for i, line in enumerate(self.ax.lines):

                    x = line.get_xdata()
                    y = line.get_ydata()
                    lg = line.get_label().replace("_", "\_")

                    if lg.endswith("felix"): ls = f"C{i}."
                    elif lg.startswith("Binned"): ls = "k."
                    else: ls = f"C{i}-"

                    if lg == "Averaged" or lg.startswith("Fitted"):
                        self.ax2.plot(x, y, "k-", label=lg, zorder=100)
                    else:
                        self.ax2.plot(x, y, ls, ms=2, label=lg)

                self.ax2.grid()
                self.ax2.set(xlim=self.ax.get_xlim())
                legend = self.ax2.legend(bbox_to_anchor=[1, 1],
                                         fontsize=self.xlabelSz.get())
                legend.set_visible(self.plotLegend.get())

                # Setting title
                self.ax2.set_title(self.plotTitle.get().replace("_", "\_"),
                                   fontsize=self.titleSz.get())

                # Setting X and Y label
                if self.plotYscale.get(): scale = "log"
                else: scale = "linear"
                self.ax2.set(yscale=scale)
                self.ax2.set(ylabel=self.plotYlabel.get().replace("%", "\%"),
                             xlabel=self.plotXlabel.get())

                # Xlabel and Ylabel fontsize
                self.ax2.xaxis.label.set_size(self.xlabelSz.get())
                self.ax2.yaxis.label.set_size(self.ylabelSz.get())
                self.ax2.tick_params(axis='x',
                                     which='major',
                                     labelsize=self.xlabelSz.get())
                self.ax2.tick_params(axis='y',
                                     which='major',
                                     labelsize=self.ylabelSz.get())

                self.fig2.savefig(save_filename, dpi=self.dpi_value.get() * 6)
Exemple #36
0
def test_skewt_api():
    'Test the SkewT api'
    with style.context(test_style):
        fig = make_figure(figsize=(9, 9))
        skew = SkewT(fig)

        # Plot the data using normal plotting functions, in this case using
        # log scaling in Y, as dictated by the typical meteorological plot
        p = np.linspace(1000, 100, 10)
        t = np.linspace(20, -20, 10)
        u = np.linspace(-10, 10, 10)
        skew.plot(p, t, 'r')
        skew.plot_barbs(p, u, u)

        # Add the relevant special lines
        skew.plot_dry_adiabats()
        skew.plot_moist_adiabats()
        skew.plot_mixing_lines()
        hide_tick_labels(skew.ax)

        return fig
def save_plots(stylesheet, image_ext=IMAGE_EXT, base_dir=None):
    """Save plots for a given stylessheet.

    Each script in the plot-scripts directory is run with the given
    stylesheet and saved to a subdirectory in `base_dir`.
    """
    base_dir = base_dir or disk.images_dir
    style_dir = pth.join(base_dir, base_filename(stylesheet))

    with style.context(stylesheet):
        # Create directory after trying to load style so we don't create an
        # empty directory if the stylesheet isn't valid.
        if not pth.exists(style_dir):
            os.makedirs(style_dir)

        for script in disk.iter_plot_scripts():
            image_name = base_filename(script) + image_ext
            with open(script) as f:
                exec(compile(f.read(), script, 'exec'), {})
            plt.savefig(pth.join(style_dir, image_name))
            plt.close('all')
def save_plots(stylesheet, image_ext=IMAGE_EXT, base_dir=None):
    """Save plots for a given stylessheet.

    Each script in the plot-scripts directory is run with the given
    stylesheet and saved to a subdirectory in `base_dir`.
    """
    base_dir = base_dir or disk.images_dir
    style_dir = pth.join(base_dir, base_filename(stylesheet))

    with style.context(stylesheet):
        # Create directory after trying to load style so we don't create an
        # empty directory if the stylesheet isn't valid.
        if not pth.exists(style_dir):
            os.makedirs(style_dir)

        for script in disk.iter_plot_scripts():
            image_name = base_filename(script) + image_ext
            with open(script) as f:
                exec(compile(f.read(), script, 'exec'), {})
            plt.savefig(pth.join(style_dir, image_name))
            plt.close('all')
Exemple #39
0
def test_skewt_api():
    'Test the SkewT api'
    with style.context(test_style):
        fig = make_figure(figsize=(9, 9))
        skew = SkewT(fig)

        # Plot the data using normal plotting functions, in this case using
        # log scaling in Y, as dictated by the typical meteorological plot
        p = np.linspace(1000, 100, 10)
        t = np.linspace(20, -20, 10)
        u = np.linspace(-10, 10, 10)
        skew.plot(p, t, 'r')
        skew.plot_barbs(p, u, u)

        # Add the relevant special lines
        skew.plot_dry_adiabats()
        skew.plot_moist_adiabats()
        skew.plot_mixing_lines()
        hide_tick_labels(skew.ax)

        return fig
Exemple #40
0
    def _makedos(self, ax, dos_plotter, dos_options, dos_label=None):
        """This is basically the same as the SDOSPlotter get_plot function."""

        # don't use first 4 colours; these are the band structure line colours
        cycle = cycler('color',
                       rcParams['axes.prop_cycle'].by_key()['color'][4:])
        with context({'axes.prop_cycle': cycle}):
            plot_data = dos_plotter.dos_plot_data(**dos_options)

        mask = plot_data['mask']
        energies = plot_data['energies'][mask]
        lines = plot_data['lines']
        spins = [Spin.up] if len(lines[0][0]['dens']) == 1 else \
            [Spin.up, Spin.down]

        for line_set in plot_data['lines']:
            for line, spin in it.product(line_set, spins):
                if spin == Spin.up:
                    label = line['label']
                    densities = line['dens'][spin][mask]
                else:
                    label = ""
                    densities = -line['dens'][spin][mask]
                ax.fill_betweenx(energies,
                                 densities,
                                 0,
                                 lw=0,
                                 facecolor=line['colour'],
                                 alpha=line['alpha'])
                ax.plot(densities, energies, label=label, color=line['colour'])

            # x and y axis reversed versus normal dos plotting
            ax.set_ylim(dos_options['xmin'], dos_options['xmax'])
            ax.set_xlim(plot_data['ymin'], plot_data['ymax'])

            if dos_label is not None:
                ax.set_xlabel(dos_label)

        ax.set_xticklabels([])
        ax.legend(loc=2, frameon=False, ncol=1, bbox_to_anchor=(1., 1.))
Exemple #41
0
def generate_fig5():
    for dfs in DATA_FILES:
        common.fill_data(dfs)

    X = np.array(SAMPLE_SIZES)
    Y = np.array([i.episodes for i in DATA_FILES[0][0].data])
    Z_avg = np.zeros((X.shape[0], Y.shape[0]))
    Z_min = np.zeros((X.shape[0], Y.shape[0]))
    Z_max = np.zeros((X.shape[0], Y.shape[0]))

    for x, dfs in enumerate(DATA_FILES):
        for y in range(len(dfs[0].data)):
            z = [df.data[y].win_rate for df in dfs]
            Z_avg[x, y] = np.mean(z)
            Z_min[x, y] = min(z)
            Z_max[x, y] = max(z)

    with style.context("ggplot"):
        fig = Figure()
        canvas = FigureCanvas(fig)
        ax = fig.add_subplot(111, projection='3d')
        ax.plot_wireframe(X[:, None], Y[None, :], Z_avg, rstride=3, cstride=8)
        # ax.plot_wireframe(X[:, None], Y[None, :], Z_min, rstride=3, cstride=8)
        # ax.plot_wireframe(X[:, None], Y[None, :], Z_max, rstride=3, cstride=8)
        ax.set_xlabel("Sample Size")
        ax.set_ylabel("SGD steps")
        ax.set_zlabel("Win Rate")
        ax.view_init(40, -60)
        ax.ticklabel_format(style="sci", scilimits=(-2, 2))

        common.save_next_fig(PART_NUM, fig)

        writer = FFMpegWriter(fps=20)
        writer.setup(fig, "figures/part{}/movie.mp4".format(PART_NUM))
        writer.grab_frame()

        for i in range(-60, 360 * 2 - 60, 1):
            ax.view_init(40, i)
            writer.grab_frame()
        writer.finish()
Exemple #42
0
def test_stationplot_api():
    'Test the StationPlot api'
    setup_font()
    with style.context(test_style):
        fig = make_figure(figsize=(9, 9))

        # testing data
        x = np.array([1, 5])
        y = np.array([2, 4])

        # Make the plot
        sp = StationPlot(fig.add_subplot(1, 1, 1), x, y, fontsize=16)
        sp.plot_barb([20, 0], [0, -50])
        sp.plot_text('E', ['KOKC', 'ICT'], color='blue')
        sp.plot_parameter('NW', [10.5, 15], color='red')
        sp.plot_symbol('S', [5, 7], high_clouds, color='green')

        sp.ax.set_xlim(0, 6)
        sp.ax.set_ylim(0, 6)
        hide_tick_labels(sp.ax)

        return fig
Exemple #43
0
def test_station_plot_replace():
    'Test that locations are properly replaced'
    setup_font()
    with style.context(test_style):
        fig = make_figure(figsize=(3, 3))

        # testing data
        x = np.array([1])
        y = np.array([1])

        # Make the plot
        sp = StationPlot(fig.add_subplot(1, 1, 1), x, y, fontsize=16)
        sp.plot_barb([20], [0])
        sp.plot_barb([5], [0])
        sp.plot_parameter('NW', [10.5], color='red')
        sp.plot_parameter('NW', [20], color='blue')

        sp.ax.set_xlim(-3, 3)
        sp.ax.set_ylim(-3, 3)
        hide_tick_labels(sp.ax)

        return fig
Exemple #44
0
def test_station_plot_replace():
    """Test that locations are properly replaced."""
    setup_font()
    with style.context(test_style):
        fig = make_figure(figsize=(3, 3))

        # testing data
        x = np.array([1])
        y = np.array([1])

        # Make the plot
        sp = StationPlot(fig.add_subplot(1, 1, 1), x, y, fontsize=16)
        sp.plot_barb([20], [0])
        sp.plot_barb([5], [0])
        sp.plot_parameter('NW', [10.5], color='red')
        sp.plot_parameter('NW', [20], color='blue')

        sp.ax.set_xlim(-3, 3)
        sp.ax.set_ylim(-3, 3)
        hide_tick_labels(sp.ax)

        return fig
Exemple #45
0
def test_skewt_subplot():
    'Test using SkewT on a sub-plot'
    with style.context(test_style):
        fig = make_figure(figsize=(9, 9))
        hide_tick_labels(SkewT(fig, subplot=(2, 2, 1)).ax)
        return fig
Exemple #46
0
def test_use_url():
    with temp_style('test', DUMMY_SETTINGS):
        with style.context('https://gist.github.com/adrn/6590261/raw'):
            assert mpl.rcParams['axes.facecolor'] == "#adeade"
Exemple #47
0
def test_use():
    mpl.rcParams[PARAM] = 'gray'
    with temp_style('test', DUMMY_SETTINGS):
        with style.context('test'):
            assert mpl.rcParams[PARAM] == VALUE
from matplotlib import pyplot as plt
from matplotlib.testing.decorators import cleanup, switch_backend
from matplotlib.testing.decorators import knownfailureif
from matplotlib._pylab_helpers import Gcf
import matplotlib.style as mstyle
import copy

try:
    # mock in python 3.3+
    from unittest import mock
except ImportError:
    import mock

try:
    with mstyle.context({'backend': 'Qt5Agg'}):
        from matplotlib.backends.qt_compat import QtCore, __version__
    from matplotlib.backends.backend_qt5 import (MODIFIER_KEYS,
                                                 SUPER, ALT, CTRL, SHIFT)

    _, ControlModifier, ControlKey = MODIFIER_KEYS[CTRL]
    _, AltModifier, AltKey = MODIFIER_KEYS[ALT]
    _, SuperModifier, SuperKey = MODIFIER_KEYS[SUPER]
    _, ShiftModifier, ShiftKey = MODIFIER_KEYS[SHIFT]

    py_qt_ver = int(__version__.split('.')[0])
    HAS_QT = py_qt_ver == 5

except ImportError:
    HAS_QT = False