Beispiel #1
0
def translate_options(options, dictionaries=None, override={}):
    """
    Translate a list of holoviews options using a given dict of dicts.

    Parameters
    ----------
    options : list
        of `Options` objects
    dictionaries : dict of dicts
        Translations to be applied as needed
    override : dict of dicts
        overrides everything else
    """
    if dictionaries is None:
        dictionaries = bokeh2mpl
    # presets forced on some options across all Element types:
    # 1 -- if the default translation dictionary (such as bokeh2mpl) defines
    #      options that need to be forced
    force1 = dictionaries.get('force', {})
    # 2 -- if the case-specific override dict contains a section pertaining
    #      to all elements
    force2 = override.get('all', {})

    options_new = []
    for o in options:
        name_full = o.key
        name = name_full.split('.')[0]
        # lookup dictionary; look in here for keys to check whether
        # translation for a given kwarg is available
        lookup = {
            **dictionaries['all'],
            **extract_if_key_is_substr(dictionaries, name),
            **extract_if_key_is_substr(dictionaries, name_full)
        }
        # 3 -- complete element-specific override variables
        force3 = {
            **extract_if_key_is_substr(override, name),
            **extract_if_key_is_substr(override, name_full),
        }

        kwargs_new = update_element(name_full,
                                    o.kwargs,
                                    lookup,
                                    force={
                                        **force1,
                                        **force2,
                                        **force3
                                    })
        o_new = Options(name_full, **kwargs_new)
        options_new.append(o_new)
    return options_new
Beispiel #2
0
def set_twinaxis_options(l, labels_to_replace_by_yaxis_selector=None):
    """
    l: holoviews Layout
    labels_to_replace_by_yaxis_selector: holoviews Element

    License
    -------
    GNU-GPLv3, (C) A. R.
    (https://github.com/poplarShift/python-data-science-utils)
    """
    if labels_to_replace_by_yaxis_selector is None:
        labels_to_replace_by_yaxis_selector = lambda e: (issubclass(
            type(e), hv.element.Chart) or isinstance(e, (hv.Overlay, hv.
                                                         NdOverlay)))
    options = []

    for el in set(
            l.traverse(
                lambda e: type(e).__name__, lambda e:
                (issubclass(type(e), hv.element.Chart) or isinstance(
                    e, (hv.Overlay, hv.NdOverlay))))):
        option_dict = dict(backend='matplotlib',
                           sublabel_format='',
                           axiswise=True,
                           framewise=True)
        options.append(Options(el, **option_dict))

    for el in set(
            l.traverse(lambda e: type(e).__name__,
                       labels_to_replace_by_yaxis_selector)):
        option_dict = dict(show_legend=False, )
        if 'Overlay' not in el:
            option_dict.update(dict(hooks=[save_legend_artists]))
        options.append(Options(el, **option_dict))

    return l.opts(*options)
Beispiel #3
0
def get_fractal(x_range, y_range):
    (x0, x1), (y0, y1) = x_range, y_range
    image = np.zeros((600, 600), dtype=np.uint8)
    return hv.Image(create_fractal(x0, x1, -y1, -y0, image, 200),
                    bounds=(x0, y0, x1, y1))


# Define stream linked to axis XY-range
range_stream = RangeXY(x_range=(-1., 1.), y_range=(-1., 1.))

# Create DynamicMap to compute fractal per zoom range and
# adjoin a logarithmic histogram
dmap = hv.DynamicMap(get_fractal,
                     label='Manderbrot Explorer',
                     streams=[range_stream]).hist(log=True)

# Define styling options
options = hv.Store.options('bokeh')
options.Image = {
    'style': Options(cmap='fire'),
    'plot': Options(logz=True, height=600, width=600, xaxis=None, yaxis=None)
}
options.Histogram = {
    'norm': Options(framewise=True),
    'plot': Options(logy=True, width=200)
}

doc = BokehRenderer.server_doc(dmap)
doc.title = 'Mandelbrot Explorer'
Beispiel #4
0
        return pn.Tabs(('Polygons', self.poly_table),
                       ('Vertices', self.vertex_table),
                       ('Points', self.point_table))


class PolyExporter(param.Parameterized):

    filename = param.String(default='')

    path = param.ClassSelector(class_=Path, precedence=-1)

    save = param.Action(default=lambda x: x._save())

    def __init__(self, path, **params):
        self._polys = paths_to_polys(path)
        super(PolyExporter, self).__init__(path=path, **params)

    def _save(self):
        pass

    def panel(self):
        return pn.Row(self.param, self._polys.options(width=800, height=600))


options = Store.options('bokeh')

options.Points = Options('plot', padding=0.1)
options.Points = Options('style', size=10, line_color='black')
options.Path = Options('plot', padding=0.1)
options.Polygons = Options('plot', padding=0.1)
Beispiel #5
0
def init_notebook():
    # Enable inline plotting in the notebook
    try:
        get_ipython().enable_matplotlib(gui='inline')
    except NameError:
        pass

    print('Populated the namespace with:\n' + ', '.join(init_mooc_nb) +
          '\nfrom code/edx_components:\n' + ', '.join(edx_components.__all__) +
          '\nfrom code/functions:\n' + ', '.join(functions.__all__))

    holoviews.notebook_extension('matplotlib')
    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True

    # Set plot style.
    options = Store.options(backend='matplotlib')
    options.Contours = Options('style', linewidth=2, color='k')
    options.Contours = Options('plot', aspect='square')
    options.HLine = Options('style', linestyle='--', color='b', linewidth=2)
    options.VLine = Options('style', linestyle='--', color='r', linewidth=2)
    options.Image = Options('style', cmap='RdBu_r')
    options.Image = Options('plot', title_format='{label}')
    options.Path = Options('style', linewidth=1.2, color='k')
    options.Path = Options('plot', aspect='square', title_format='{label}')
    options.Curve = Options('style', linewidth=2, color='k')
    options.Curve = Options('plot', aspect='square', title_format='{label}')
    options.Overlay = Options('plot',
                              show_legend=False,
                              title_format='{label}')
    options.Layout = Options('plot', title_format='{label}')
    options.Surface = Options('style',
                              cmap='RdBu_r',
                              rstride=1,
                              cstride=1,
                              lw=0.2)
    options.Surface = Options('plot', azimuth=20, elevation=8)

    # Turn off a bogus holoviews warning.
    # Temporary solution to ignore the warnings
    warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')

    module_dir = os.path.dirname(__file__)
    matplotlib.rc_file(os.path.join(module_dir, "matplotlibrc"))

    np.set_printoptions(precision=2,
                        suppress=True,
                        formatter={'complexfloat': pretty_fmt_complex})

    # In order to make the notebooks readable through nbviewer we want to hide
    # the code by default. However the same code is executed by the students,
    # and in that case we don't want to hide the code. So we check if the code
    # is executed by one of the mooc developers. Here we do by simply checking
    # for some files that belong to the internal mooc repository, but are not
    # published.  This is a temporary solution, and should be improved in the
    # long run.

    developer = os.path.exists(
        os.path.join(module_dir, os.path.pardir, 'scripts'))

    display_html(
        display.HTML(nb_html_header +
                     (hide_outside_ipython if developer else '')))

    # Patch a bug in holoviews
    from patch_holoviews import patch_all
    patch_all()
Beispiel #6
0
def init_notebook():
    print_information()
    check_versions()

    code_dir = os.path.dirname(os.path.realpath(__file__))
    hv_css = os.path.join(code_dir, 'hv_widgets_settings.css')
    holoviews.plotting.widgets.SelectionWidget.css = hv_css

    holoviews.notebook_extension('matplotlib')

    # Enable inline plotting in the notebook
    get_ipython().enable_matplotlib(gui='inline')

    Store.renderers['matplotlib'].fig = 'svg'
    Store.renderers['matplotlib'].dpi = 100

    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True

    latex_packs = [r'\usepackage{amsmath}',
                   r'\usepackage{amssymb}'
                   r'\usepackage{bm}']

    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.latex.preamble'] = \
        latex_packs

    # Set plot style.
    options = Store.options(backend='matplotlib')
    options.Contours = Options('style', linewidth=2, color='k')
    options.Contours = Options('plot', aspect='square')
    options.HLine = Options('style', linestyle='--', color='b', linewidth=2)
    options.VLine = Options('style', linestyle='--', color='r', linewidth=2)
    options.Image = Options('style', cmap='RdBu_r')
    options.Image = Options('plot', title_format='{label}')
    options.Path = Options('style', linewidth=1.2, color='k')
    options.Path = Options('plot', aspect='square', title_format='{label}')
    options.Curve = Options('style', linewidth=2, color='k')
    options.Curve = Options('plot', aspect='square', title_format='{label}')
    options.Overlay = Options('plot', show_legend=False, title_format='{label}')
    options.Layout = Options('plot', title_format='{label}')
    options.Surface = Options('style', cmap='RdBu_r', rstride=2, cstride=2,
                              lw=0.2, edgecolors='k')
    options.Surface = Options('plot', azimuth=20, elevation=8)

    # Set slider label formatting
    for dimension_type in [float, np.float64, np.float32]:
        holoviews.Dimension.type_formatters[dimension_type] = pretty_fmt_complex

    matplotlib.rc_file(os.path.join(code_dir, "matplotlibrc"))

    np.set_printoptions(precision=2, suppress=True,
                        formatter={'complexfloat': pretty_fmt_complex})
Beispiel #7
0
            deltas, weights = [], []
            for k, cf in cfs.items():
                preferred = featurepref[k]
                weight_arr = cf.situated.data.flat
                feature_slice = feature_arr[weight_arr>0]
                weight_slice = weight_arr[weight_arr>0]
                if feature.cyclic:
                    feature_delta = circular_dist(preferred, feature_slice, feature.range[1])
                else:
                    feature_delta = np.abs(feature_slice-preferred)
                deltas.append(feature_delta)
                weights.append(weight_slice)
            deltas = np.concatenate(deltas)
            weights = np.concatenate(weights)
            bin_range = (0, feature.range[1]/2.) if feature.cyclic else None
            bins, edges = np.histogram(deltas, range=bin_range, bins=self.p.num_bins,
                                       weights=weights, normed=self.p.normalized)
            # Construct Elements
            label = ' '.join([s,p])
            group = '%s Weight Distribution' % self.p.feature
            histogram = Histogram(bins, edges, group=group, label=label,
                                  kdims=[' '.join([self.p.feature, 'Difference'])],
                                  vdims=['Weight'])

            layout.WeightDistribution['_'.join([s,p])] = histogram

        return layout

options = Store.options(backend='matplotlib')
options.Histogram.Weight_Isotropy = Options('plot', projection='polar', show_grid=True)
Beispiel #8
0
        plot = dict(width=self.width, height=self.table_height)
        for col in self.point_columns:
            if col not in self.points:
                self.points = self.points.add_dimension(col, 0, None, True)
        self.point_stream = PointDraw(source=self.points, data={})
        projected = gv.project(self.points, projection=ccrs.PlateCarree())
        self.point_table = Table(projected).opts(plot=plot, style=style)
        self.point_link = PointTableLink(source=self.points,
                                         target=self.point_table)

    def view(self):
        return (self.tiles * self.polys * self.points +
                self.point_table).cols(1)


class PolyAndPointAnnotator(PolyAnnotator, PointAnnotator):
    """
    Allows drawing and annotating Points and Polygons using a bokeh
    DataTable.
    """
    def view(self):
        return (self.tiles * self.polys * self.points + self.poly_table +
                self.point_table + self.vertex_table).cols(1)


options = Store.options('bokeh')

options.Points = Options('plot', padding=0.1)
options.Path = Options('plot', padding=0.1)
options.Polygons = Options('plot', padding=0.1)
Beispiel #9
0
def add_backend_to_opts(opts, backend):
    for k, o in enumerate(opts):
        opts[k] = Options(o.key, **{**o.kwargs, **{'backend': backend}})
Beispiel #10
0
def init_notebook():
    print_information()
    check_versions()

    holoviews.notebook_extension("matplotlib")
    holoviews.output(widget_location='bottom')

    # Enable inline plotting in the notebook
    get_ipython().enable_matplotlib(gui="inline")

    Store.renderers["matplotlib"].fig = "svg"
    Store.renderers["matplotlib"].dpi = 100

    holoviews.plotting.mpl.MPLPlot.fig_rcparams["text.usetex"] = False

    latex_packs = [
        r"\usepackage{amsmath}", r"\usepackage{amssymb}"
        r"\usepackage{bm}"
    ]

    holoviews.plotting.mpl.MPLPlot.fig_rcparams[
        "text.latex.preamble"] = latex_packs

    # Set plot style.
    options = Store.options(backend="matplotlib")
    options.Contours = Options("style", linewidth=2, color="k")
    options.Contours = Options("plot", padding=0, aspect="square")
    options.HLine = Options("style", linestyle="--", color="b", linewidth=2)
    options.VLine = Options("style", linestyle="--", color="r", linewidth=2)
    options.Image = Options("style", cmap="RdBu_r")
    options.Image = Options("plot", padding=0, title="{label}")
    options.Path = Options("style", linewidth=1.2, color="black")
    options.Path = Options("plot", padding=0, aspect="square", title="{label}")
    options.Curve = Options("style", linewidth=2, color="black")
    options.Curve = Options("plot",
                            padding=0,
                            aspect="square",
                            title="{label}")
    options.Overlay = Options("plot",
                              padding=0,
                              show_legend=False,
                              title="{label}")
    options.Layout = Options("plot", title="{label}")
    options.Surface = Options("style",
                              cmap="RdBu_r",
                              rstride=2,
                              cstride=2,
                              lw=0.2,
                              edgecolor="black")
    options.Surface = Options("plot", azimuth=20, elevation=8)

    # Set slider label formatting
    for dimension_type in [float, np.float64, np.float32]:
        holoviews.Dimension.type_formatters[
            dimension_type] = lambda x: pretty_fmt_complex(x, 4)

    code_dir = os.path.dirname(os.path.realpath(__file__))
    matplotlib.rc_file(os.path.join(code_dir, "matplotlibrc"))

    np.set_printoptions(precision=2,
                        suppress=True,
                        formatter={"complexfloat": pretty_fmt_complex})

    # Silence Kwant warnings from color scale overflow
    warnings.filterwarnings("ignore",
                            category=RuntimeWarning,
                            message="The plotted data contains")
Beispiel #11
0
def init_notebook(mpl=True):
    # Enable inline plotting in the notebook
    if mpl:
        try:
            get_ipython().enable_matplotlib(gui='inline')
        except NameError:
            pass

    print('Populated the namespace with:\n' + ', '.join(init_mooc_nb) +
          '\nfrom code/edx_components:\n' + ', '.join(edx_components.__all__) +
          '\nfrom code/functions:\n' + ', '.join(functions.__all__))

    holoviews.notebook_extension('matplotlib')

    Store.renderers['matplotlib'].fig = 'svg'

    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True

    latex_packs = [
        r'\usepackage{amsmath}', r'\usepackage{amssymb}'
        r'\usepackage{bm}'
    ]

    holoviews.plotting.mpl.MPLPlot.fig_rcparams[
        'text.latex.preamble'] = latex_packs

    # Set plot style.
    options = Store.options(backend='matplotlib')
    options.Contours = Options('style', linewidth=2, color='k')
    options.Contours = Options('plot', aspect='square')
    options.HLine = Options('style', linestyle='--', color='b', linewidth=2)
    options.VLine = Options('style', linestyle='--', color='r', linewidth=2)
    options.Image = Options('style', cmap='RdBu_r')
    options.Image = Options('plot', title_format='{label}')
    options.Path = Options('style', linewidth=1.2, color='k')
    options.Path = Options('plot', aspect='square', title_format='{label}')
    options.Curve = Options('style', linewidth=2, color='k')
    options.Curve = Options('plot', aspect='square', title_format='{label}')
    options.Overlay = Options('plot',
                              show_legend=False,
                              title_format='{label}')
    options.Layout = Options('plot', title_format='{label}')
    options.Surface = Options('style',
                              cmap='RdBu_r',
                              rstride=1,
                              cstride=1,
                              lw=0.2)
    options.Surface = Options('plot', azimuth=20, elevation=8)

    # Turn off a bogus holoviews warning.
    # Temporary solution to ignore the warnings
    warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')

    module_dir = os.path.dirname(__file__)
    matplotlib.rc_file(os.path.join(module_dir, "matplotlibrc"))

    np.set_printoptions(precision=2,
                        suppress=True,
                        formatter={'complexfloat': pretty_fmt_complex})

    # Patch a bug in holoviews
    if holoviews.__version__.release <= (1, 4, 3):
        from patch_holoviews import patch_all
        patch_all()