Пример #1
0
 def load_nb(cls, inline=True):
     """
     Loads any resources required for display of plots
     in the Jupyter notebook
     """
     with param.logging_level('ERROR'):
         cls.notebook_context = True
Пример #2
0
    def register(cls, associations, backend, style_aliases={}):
        """
        Register the supplied dictionary of associations between
        elements and plotting classes to the specified backend.
        """
        from .overlay import CompositeOverlay
        if backend not in cls.registry:
            cls.registry[backend] = {}
        cls.registry[backend].update(associations)

        groups = ['style', 'plot', 'norm']
        if backend not in cls._options:
            cls._options[backend] = OptionTree([], groups=groups)
        if backend not in cls._custom_options:
            cls._custom_options[backend] = {}

        for view_class, plot in cls.registry[backend].items():
            expanded_opts = [opt for key in plot.style_opts
                             for opt in style_aliases.get(key, [])]
            style_opts = sorted(set(expanded_opts + plot.style_opts))
            plot_opts = [k for k in plot.params().keys() if k not in ['name']]

            with param.logging_level('CRITICAL'):
                plot.style_opts = style_opts

            opt_groups = {'plot': Options(allowed_keywords=plot_opts)}
            if not isinstance(view_class, CompositeOverlay) or hasattr(plot, 'style_opts'):
                 opt_groups.update({'style': Options(allowed_keywords=style_opts),
                                    'norm':  Options(framewise=False, axiswise=False,
                                                     allowed_keywords=['framewise',
                                                                       'axiswise'])})

            name = view_class.__name__
            if name not in cls._options[backend]:
                cls._options[backend][name] = opt_groups
Пример #3
0
    def register(cls, associations, backend, style_aliases={}):
        """
        Register the supplied dictionary of associations between
        elements and plotting classes to the specified backend.
        """
        from .overlay import CompositeOverlay
        if backend not in cls.registry:
            cls.registry[backend] = {}
        cls.registry[backend].update(associations)

        groups = ['style', 'plot', 'norm']
        if backend not in cls._options:
            cls._options[backend] = OptionTree([], groups=groups)
        if backend not in cls._custom_options:
            cls._custom_options[backend] = {}

        for view_class, plot in cls.registry[backend].items():
            expanded_opts = [opt for key in plot.style_opts
                             for opt in style_aliases.get(key, [])]
            style_opts = sorted(set(opt for opt in (expanded_opts + plot.style_opts)
                                    if opt not in plot._disabled_opts))
            plot_opts = [k for k in plot.params().keys() if k not in ['name']]

            with param.logging_level('CRITICAL'):
                plot.style_opts = style_opts

            opt_groups = {'plot': Options(allowed_keywords=plot_opts)}
            if not isinstance(view_class, CompositeOverlay) or hasattr(plot, 'style_opts'):
                 opt_groups.update({'style': Options(allowed_keywords=style_opts),
                                    'norm':  Options(framewise=False, axiswise=False,
                                                     allowed_keywords=['framewise',
                                                                       'axiswise'])})

            name = view_class.__name__
            cls._options[backend][name] = opt_groups
Пример #4
0
    def _update_backend(cls, backend):

        if cls.__original_docstring__ is None:
            cls.__original_docstring__ = cls.__doc__

        all_keywords = set()
        element_keywords = cls._element_keywords(backend)
        for element, keywords in element_keywords.items():
            with param.logging_level('CRITICAL'):
                all_keywords |= set(keywords)
                setattr(cls, element, cls._create_builder(element, keywords))

        filtered_keywords = [
            k for k in all_keywords if k not in cls._no_completion
        ]
        sorted_kw_set = sorted(set(filtered_keywords))
        if sys.version_info.major == 2:
            kws = ', '.join('{opt}=None'.format(opt=opt)
                            for opt in sorted_kw_set)
            old_doc = cls.__original_docstring__.replace(
                'params(strict=Boolean, name=String)', '')
            cls.__doc__ = '\n    opts({kws})'.format(kws=kws) + old_doc
        else:
            from inspect import Parameter, Signature
            signature = Signature(
                [Parameter('args', Parameter.VAR_POSITIONAL)] + [
                    Parameter(kw, Parameter.KEYWORD_ONLY)
                    for kw in sorted_kw_set
                ])
            cls.__init__.__signature__ = signature
Пример #5
0
    def add_style_opts(cls, component, new_options, backend=None):
        """
        Given a component such as an Element (e.g. Image, Curve) or a
        container (e.g Layout) specify new style options to be
        accepted by the corresponding plotting class.

        Note: This is supplied for advanced users who know which
        additional style keywords are appropriate for the
        corresponding plotting class.
        """
        backend = cls.current_backend if backend is None else backend
        if component not in cls.registry[backend]:
            raise ValueError(
                "Component %r not registered to a plotting class" % component)

        if not isinstance(new_options, list) or not all(
                isinstance(el, str) for el in new_options):
            raise ValueError(
                "Please supply a list of style option keyword strings")

        with param.logging_level('CRITICAL'):
            for option in new_options:
                if option not in cls.registry[backend][component].style_opts:
                    plot_class = cls.registry[backend][component]
                    plot_class.style_opts = sorted(plot_class.style_opts +
                                                   [option])
        cls._options[backend][type(component).__name__] = Options(
            'style', merge_keywords=True, allowed_keywords=new_options)
Пример #6
0
    def _update_backend(cls, backend):

        if cls.__original_docstring__ is None:
            cls.__original_docstring__ = cls.__doc__

        if backend not in Store.loaded_backends():
            return

        backend_options = Store.options(backend)
        all_keywords = set()
        for element in backend_options.keys():
            if '.' in element: continue
            element_keywords = []
            options = backend_options['.'.join(element)]
            for group in Options._option_groups:
                element_keywords.extend(options[group].allowed_keywords)

            all_keywords |= set(element_keywords)
            with param.logging_level('CRITICAL'):
                setattr(cls, element[0],
                        cls._build_completer(element[0], element_keywords))

        kws = ', '.join('{opt}=None'.format(opt=opt)
                        for opt in sorted(all_keywords))
        old_doc = cls.__original_docstring__.replace(
            'params(strict=Boolean, name=String)', '')
        cls.__doc__ = '\n    opts({kws})'.format(kws=kws) + old_doc
Пример #7
0
 def load_nb(cls, inline=True):
     """
     Loads any resources required for display of plots
     in the Jupyter notebook
     """
     with param.logging_level('ERROR'):
         cls.notebook_context = True
Пример #8
0
 def tearDown(self):
     Store.current_backend = self.previous_backend
     bokeh_renderer.last_plot = None
     Callback._callbacks = {}
     with param.logging_level('ERROR'):
         Renderer.notebook_context = self.nbcontext
     state.curdoc = None
     curdoc().clear()
Пример #9
0
 def setUp(self):
     self.previous_backend = Store.current_backend
     if not bokeh_renderer:
         raise SkipTest("Bokeh required to test plot instantiation")
     Store.current_backend = 'bokeh'
     self.nbcontext = Renderer.notebook_context
     with param.logging_level('ERROR'):
         Renderer.notebook_context = False
Пример #10
0
    def __call__(self, *args, **params):
        # Abort if IPython not found
        for arg in args:
            if arg not in self._imports:
                self.param.warning('%s extension not recognized and '
                                   'will be skipped.' % arg)
            else:
                __import__(self._imports[arg])

        for k, v in params.items():
            if k in ['raw_css', 'css_files']:
                if not isinstance(v, list):
                    raise ValueError('%s should be supplied as a list, '
                                     'not as a %s type.' %
                                     (k, type(v).__name__))
                getattr(config, k).extend(v)
            elif k == 'js_files':
                getattr(config, k).update(v)
            else:
                setattr(config, k, v)

        if config.apply_signatures and sys.version_info.major >= 3:
            self._apply_signatures()

        if 'holoviews' in sys.modules:
            import holoviews as hv
            import holoviews.plotting.bokeh  # noqa
            if not hv.extension._loaded:
                if hasattr(hv.Store, 'set_current_backend'):
                    hv.Store.set_current_backend('bokeh')
                else:
                    hv.Store.current_backend = 'bokeh'

        try:
            ip = params.pop('ip', None) or get_ipython()  # noqa (get_ipython)
        except Exception:
            return

        if hasattr(ip,
                   'kernel') and not self._loaded and not config._doc_build:
            # TODO: JLab extension and pyviz_comms should be changed
            #       to allow multiple cleanup comms to be registered
            _JupyterCommManager.get_client_comm(self._process_comm_msg,
                                                "hv-extension-comm")
            state._comm_manager = _JupyterCommManager

        nb_load = False
        if 'holoviews' in sys.modules:
            if hv.extension._loaded:
                return
            with param.logging_level('ERROR'):
                hv.plotting.Renderer.load_nb(config.inline)
                if hasattr(hv.plotting.Renderer, '_render_with_panel'):
                    nb_load = True

        if not nb_load and hasattr(ip, 'kernel'):
            load_notebook(config.inline)
        panel_extension._loaded = True
Пример #11
0
    def setUp(self):
        if 'plotly' not in Store.renderers and pn is not None:
            raise SkipTest("Plotly and Panel required to test rendering.")

        self.renderer = PlotlyRenderer.instance()
        self.nbcontext = Renderer.notebook_context
        self.comm_manager = Renderer.comm_manager
        with param.logging_level('ERROR'):
            Renderer.notebook_context = False
            Renderer.comm_manager = CommManager
Пример #12
0
def register_submodel_decorators(classes,superclass=None):
    """
    Register a Model decorator for each of the non-abstract classes provided.
    Only registers those that are subclasses of the given superclass, if specified.
    """
    with param.logging_level('CRITICAL'):
        for c in classes:
            if (isinstance(c, type) and 
                (superclass==None or issubclass(c, superclass)) and
                (not hasattr(c, "_%s__abstract" % c.name))):
               Model.register_decorator(c)
Пример #13
0
def register_submodel_decorators(classes, superclass=None):
    """
    Register a Model decorator for each of the non-abstract classes provided.
    Only registers those that are subclasses of the given superclass, if specified.
    """
    with param.logging_level('CRITICAL'):
        for c in classes:
            if (isinstance(c, type)
                    and (superclass == None or issubclass(c, superclass))
                    and (not hasattr(c, "_%s__abstract" % c.name))):
                Model.register_decorator(c)
Пример #14
0
    def setUp(self):
        if 'plotly' not in Store.renderers or None in (pn, PlotlyRenderer):
            raise SkipTest("Plotly and Panel required to test rendering.")

        self.previous_backend = Store.current_backend
        Store.current_backend = 'plotly'
        self.renderer = PlotlyRenderer.instance()
        self.nbcontext = Renderer.notebook_context
        self.comm_manager = Renderer.comm_manager
        with param.logging_level('ERROR'):
            Renderer.notebook_context = False
            Renderer.comm_manager = CommManager
 def setUp(self):
     if 'bokeh' not in Store.renderers and pn is not None:
         raise SkipTest("Bokeh and Panel required to test 'bokeh' renderer")
     self.image1 = Image(np.array([[0, 1], [2, 3]]), label='Image1')
     self.image2 = Image(np.array([[1, 0], [4, -2]]), label='Image2')
     self.map1 = HoloMap({1: self.image1, 2: self.image2}, label='TestMap')
     self.renderer = BokehRenderer.instance()
     self.nbcontext = Renderer.notebook_context
     self.comm_manager = Renderer.comm_manager
     with param.logging_level('ERROR'):
         Renderer.notebook_context = False
         Renderer.comm_manager = CommManager
Пример #16
0
 def load_nb(cls, inline=True):
     """
     Loads any resources required for display of plots
     in the Jupyter notebook
     """
     load_notebook(inline)
     with param.logging_level('ERROR'):
         try:
             ip = get_ipython()  # noqa
         except:
             ip = None
         if not ip or not hasattr(ip, 'kernel'):
             return
         cls.notebook_context = True
         cls.comm_manager = JupyterCommManager
         state._comm_manager = JupyterCommManager
Пример #17
0
    def _update_backend(cls, backend):

        if cls.__original_docstring__ is None:
            cls.__original_docstring__ = cls.__doc__

        all_keywords = set()
        element_keywords = cls._element_keywords(backend)
        for element, keywords in element_keywords.items():
            with param.logging_level('CRITICAL'):
                all_keywords |= set(keywords)
                setattr(cls, element, cls._build_completer(element, keywords))

        kws = ', '.join('{opt}=None'.format(opt=opt)
                        for opt in sorted(all_keywords))
        old_doc = cls.__original_docstring__.replace(
            'params(strict=Boolean, name=String)', '')
        cls.__doc__ = '\n    opts({kws})'.format(kws=kws) + old_doc
Пример #18
0
    def _update_backend(cls, backend):

        if cls.__original_docstring__ is None:
            cls.__original_docstring__ = cls.__doc__

        all_keywords = set()
        element_keywords = cls._element_keywords(backend)
        for element, keywords in element_keywords.items():
            with param.logging_level('CRITICAL'):
                all_keywords |= set(keywords)
                setattr(cls, element,
                        cls._create_builder(element, keywords))

        filtered_keywords = [k for k in all_keywords if k not in cls._no_completion]
        kws = ', '.join('{opt}=None'.format(opt=opt) for opt in sorted(filtered_keywords))
        old_doc = cls.__original_docstring__.replace('params(strict=Boolean, name=String)','')
        cls.__doc__ = '\n    opts({kws})'.format(kws=kws) + old_doc
Пример #19
0
    def register_plots(cls, style_aliases={}):
        """
        Given that the Store.registry dictionary has been populate
        with {<element>:<plot-class>} items, build an OptionTree for the
        supported plot types, registering allowed plotting and style
        keywords.

        This is designed to be backend independent but makes the
        following assumptions:

        * Plotting classes are param.Parameterized objects.

        * Plotting classes have a style_opts list of keywords used to
          control the display style of the output.

        * Overlay plotting is a function of the overlaid elements and
          only has plot options (and not style or normalization
          options).
        """
        from .overlay import CompositeOverlay
        path_items = {}
        for view_class, plot in cls.registry.items():
            name = view_class.__name__
            plot_opts = [k for k in plot.params().keys() if k not in ['name']]
            expanded_opts = [opt for key in plot.style_opts
                             for opt in style_aliases.get(key, [])]
            style_opts = sorted(set(expanded_opts + plot.style_opts))
            with param.logging_level('CRITICAL'):
                plot.style_opts = style_opts
            opt_groups = {'plot': Options(allowed_keywords=plot_opts)}

            if not isinstance(view_class, CompositeOverlay) or hasattr(plot, 'style_opts'):
                opt_groups.update({'style': Options(allowed_keywords=style_opts),
                                   'norm':  Options(framewise=False, axiswise=False,
                                                    allowed_keywords=['framewise',
                                                                      'axiswise'])})
            path_items[name] = opt_groups

        cls.options = OptionTree(sorted(path_items.items()),
                                  groups={'style': Options(),
                                          'plot': Options(),
                                          'norm': Options()})

        for fn in cls.option_setters:
            fn(cls.options)
Пример #20
0
    def register_plots(cls, style_aliases={}):
        """
        Given that the Store.registry dictionary has been populate
        with {<element>:<plot-class>} items, build an OptionTree for the
        supported plot types, registering allowed plotting and style
        keywords.

        This is designed to be backend independent but makes the
        following assumptions:

        * Plotting classes are param.Parameterized objects.

        * Plotting classes have a style_opts list of keywords used to
          control the display style of the output.

        * Overlay plotting is a function of the overlaid elements and
          only has plot options (and not style or normalization
          options).
        """
        from .overlay import CompositeOverlay
        path_items = {}
        for view_class, plot in cls.registry.items():
            name = view_class.__name__
            plot_opts = [k for k in plot.params().keys() if k not in ['name']]
            expanded_opts = [opt for key in plot.style_opts
                             for opt in style_aliases.get(key, [])]
            style_opts = sorted(set(expanded_opts + plot.style_opts))
            with param.logging_level('CRITICAL'):
                plot.style_opts = style_opts
            opt_groups = {'plot': Options(allowed_keywords=plot_opts)}

            if not isinstance(view_class, CompositeOverlay) or hasattr(plot, 'style_opts'):
                opt_groups.update({'style': Options(allowed_keywords=style_opts),
                                   'norm':  Options(framewise=False, axiswise=False,
                                                    allowed_keywords=['framewise',
                                                                      'axiswise'])})
            path_items[name] = opt_groups

        cls.options = OptionTree(sorted(path_items.items()),
                                  groups={'style': Options(),
                                          'plot': Options(),
                                          'norm': Options()})

        for fn in cls.option_setters:
            fn(cls.options)
Пример #21
0
    def setUp(self):
        if 'matplotlib' not in Store.renderers and pn is not None:
            raise SkipTest("Matplotlib and Panel required to test rendering.")

        self.basename = 'no-file'
        self.image1 = Image(np.array([[0,1],[2,3]]), label='Image1')
        self.image2 = Image(np.array([[1,0],[4,-2]]), label='Image2')
        self.map1 = HoloMap({1:self.image1, 2:self.image2}, label='TestMap')

        self.unicode_table = ItemTable([('β','Δ1'), ('°C', '3×4')],
                                       label='Poincaré', group='α Festkörperphysik')

        self.renderer = MPLRenderer.instance()
        self.nbcontext = Renderer.notebook_context
        self.comm_manager = Renderer.comm_manager
        with param.logging_level('ERROR'):
            Renderer.notebook_context = False
            Renderer.comm_manager = CommManager
Пример #22
0
    def _update_backend(cls, backend):
        if cls.__original_docstring__ is None:
            cls.__original_docstring__ = cls.__doc__

        all_keywords = set()
        element_keywords = cls._element_keywords(backend)
        for element, keywords in element_keywords.items():
            with param.logging_level('CRITICAL'):
                all_keywords |= set(keywords)
                setattr(cls, element, cls._create_builder(element, keywords))

        filtered_keywords = [
            k for k in all_keywords if k not in cls._no_completion
        ]
        sorted_kw_set = sorted(set(filtered_keywords))
        from inspect import Parameter, Signature
        signature = Signature(
            [Parameter('args', Parameter.VAR_POSITIONAL)] +
            [Parameter(kw, Parameter.KEYWORD_ONLY) for kw in sorted_kw_set])
        cls.__init__.__signature__ = signature
Пример #23
0
    def add_style_opts(cls, component, new_options):
        """
        Given a component such as an Element (e.g. Image, Curve) or a
        container (e.g Layout) specify new style options to be
        accepted by the corresponding plotting class.

        Note: This is supplied for advanced users who know which
        additional style keywords are appropriate for the
        corresponding plotting class.
        """
        if component not in cls.registry:
            raise ValueError("Component %r not registered to a plotting class" % component)

        if not isinstance(new_options, list) or not all(isinstance(el, str) for el in new_options):
            raise ValueError("Please supply a list of style option keyword strings")

        with param.logging_level('CRITICAL'):
            for option in new_options:
                if option not in cls.registry[component].style_opts:
                    cls.registry[component].style_opts.append(option)
        cls.register_plots()
Пример #24
0
 def supported_holomap_formats(self_or_cls, optional_formats):
     "Optional formats that are actually supported by this renderer"
     supported = []
     with param.logging_level('CRITICAL'):
         self_or_cls.HOLOMAP_FORMAT_ERROR_MESSAGES = {}
     for fmt in optional_formats:
         with warnings.catch_warnings():
             warnings.simplefilter("ignore")
             try:
                 fig = plt.figure()
                 anim = animation.FuncAnimation(fig, lambda x: x, frames=[0,1])
                 (writer, fmt, anim_kwargs, extra_args) = self_or_cls.ANIMATION_OPTS[fmt]
                 if extra_args != []:
                     anim_kwargs = dict(anim_kwargs, extra_args=extra_args)
                     renderer = self_or_cls.instance(dpi=72)
                     renderer._anim_data(anim, fmt, writer, **anim_kwargs)
                 plt.close(fig)
                 supported.append(fmt)
             except Exception as e:
                 self_or_cls.HOLOMAP_FORMAT_ERROR_MESSAGES[fmt] = str(e)
     return supported
Пример #25
0
    def add_style_opts(cls, component, new_options):
        """
        Given a component such as an Element (e.g. Image, Curve) or a
        container (e.g Layout) specify new style options to be
        accepted by the corresponding plotting class.

        Note: This is supplied for advanced users who know which
        additional style keywords are appropriate for the
        corresponding plotting class.
        """
        if component not in cls.registry:
            raise ValueError("Component %r not registered to a plotting class" % component)

        if not isinstance(new_options, list) or not all(isinstance(el, str) for el in new_options):
            raise ValueError("Please supply a list of style option keyword strings")

        with param.logging_level('CRITICAL'):
            for option in new_options:
                if option not in cls.registry[component].style_opts:
                    cls.registry[component].style_opts.append(option)
        cls.register_plots()
Пример #26
0
    def add_style_opts(cls, component, new_options, backend=None):
        """
        Given a component such as an Element (e.g. Image, Curve) or a
        container (e.g Layout) specify new style options to be
        accepted by the corresponding plotting class.

        Note: This is supplied for advanced users who know which
        additional style keywords are appropriate for the
        corresponding plotting class.
        """
        backend = cls.current_backend if backend is None else backend
        if component not in cls.registry[backend]:
            raise ValueError("Component %r not registered to a plotting class" % component)

        if not isinstance(new_options, list) or not all(isinstance(el, str) for el in new_options):
            raise ValueError("Please supply a list of style option keyword strings")

        with param.logging_level('CRITICAL'):
            for option in new_options:
                if option not in cls.registry[backend][component].style_opts:
                    plot_class = cls.registry[backend][component]
                    plot_class.style_opts = sorted(plot_class.style_opts+[option])
        cls._options[backend][type(component).__name__] = Options('style', merge_keywords=True, allowed_keywords=new_options)
Пример #27
0
    def __call__(self, *args, **params):
        # Abort if IPython not found
        for arg in args:
            if arg not in self._imports:
                self.param.warning('%s extension not recognized and '
                                   'will be skipped.' % arg)
            else:
                __import__(self._imports[arg])

        for k, v in params.items():
            if k in ['raw_css', 'css_files']:
                if not isinstance(v, list):
                    raise ValueError('%s should be supplied as a list, '
                                     'not as a %s type.' %
                                     (k, type(v).__name__))
                getattr(config, k).extend(v)
            elif k == 'js_files':
                getattr(config, k).update(v)
            else:
                setattr(config, k, v)

        if config.apply_signatures and sys.version_info.major >= 3:
            self._apply_signatures()

        loaded = self._loaded

        # Short circuit pyvista extension load if VTK is already initialized
        if loaded and args == ('vtk', ) and 'vtk' in self._loaded_extensions:
            curframe = inspect.currentframe()
            calframe = inspect.getouterframes(curframe, 2)
            if len(calframe) >= 3 and 'pyvista' in calframe[2].filename:
                return

        if 'holoviews' in sys.modules:
            import holoviews as hv
            import holoviews.plotting.bokeh  # noqa
            loaded = loaded or getattr(hv.extension, '_loaded', False)

            if hv.Store.current_backend in hv.Store.renderers:
                backend = hv.Store.current_backend
            else:
                backend = 'bokeh'
            if hasattr(hv.Store, 'set_current_backend'):
                hv.Store.set_current_backend(backend)
            else:
                hv.Store.current_backend = backend

        try:
            ip = params.pop('ip', None) or get_ipython()  # noqa (get_ipython)
        except Exception:
            return

        newly_loaded = [
            arg for arg in args
            if arg not in panel_extension._loaded_extensions
        ]
        if loaded and newly_loaded:
            self.param.warning(
                "A HoloViz extension was loaded previously. This means "
                "the extension is already initialized and the following "
                "Panel extensions could not be properly loaded: %s. "
                "If you are loading custom extensions with pn.extension(...) "
                "ensure that this is called before any other HoloViz "
                "extension such as hvPlot or HoloViews." % newly_loaded)
        else:
            panel_extension._loaded_extensions += newly_loaded

        if hasattr(ip,
                   'kernel') and not self._loaded and not config._doc_build:
            # TODO: JLab extension and pyviz_comms should be changed
            #       to allow multiple cleanup comms to be registered
            _JupyterCommManager.get_client_comm(self._process_comm_msg,
                                                "hv-extension-comm")
            state._comm_manager = _JupyterCommManager

        if 'ipywidgets' in sys.modules and config.embed:
            # In embedded mode the ipywidgets_bokeh model must be loaded
            __import__(self._imports['ipywidgets'])

        nb_load = False
        if 'holoviews' in sys.modules:
            if getattr(hv.extension, '_loaded', False):
                return
            with param.logging_level('ERROR'):
                hv.plotting.Renderer.load_nb(config.inline)
                if hasattr(hv.plotting.Renderer, '_render_with_panel'):
                    nb_load = True

        if not nb_load and hasattr(ip, 'kernel'):
            load_notebook(config.inline)
        panel_extension._loaded = True
Пример #28
0
 def tearDown(self):
     with param.logging_level('ERROR'):
         Renderer.notebook_context = self.nbcontext
         Renderer.comm_manager = self.comm_manager
Пример #29
0
from __future__ import absolute_import, division, unicode_literals

import base64
import json

import param
with param.logging_level('CRITICAL'):
    from plotly import utils
    from plotly.offline import get_plotlyjs, init_notebook_mode
    import plotly.graph_objs as go

from ..renderer import Renderer, MIME_TYPES, HTML_TAGS
from ...core.options import Store
from ...core import HoloMap
from .widgets import PlotlyScrubberWidget, PlotlySelectionWidget


plotly_msg_handler = """
/* Backend specific body of the msg_handler, updates displayed frame */
var plot = $('#{plot_id}')[0];
var data = JSON.parse(msg);
$.each(data.data, function(i, obj) {{
  $.each(Object.keys(obj), function(j, key) {{
    plot.data[i][key] = obj[key];
  }});
}});
var plotly = window._Plotly || window.Plotly;
plotly.relayout(plot, data.layout);
plotly.redraw(plot);
"""
Пример #30
0
def patch_all():
    with param.logging_level('error'):
        patch_core_util()
        patch_plotting_util()
        patch_mpl_chart3d()
        patch_mpl_element()
Пример #31
0
def patch_all():
    with param.logging_level('error'):
        patch_core_util()
        patch_plotting_util()
        patch_mpl_chart3d()
        patch_mpl_element()
Пример #32
0
import json

import param
with param.logging_level('CRITICAL'):
    from plotly.offline.offline import utils, get_plotlyjs, init_notebook_mode

from ..renderer import Renderer, MIME_TYPES
from ...core.options import Store
from ...core import HoloMap
from .widgets import PlotlyScrubberWidget, PlotlySelectionWidget

plotly_msg_handler = """
/* Backend specific body of the msg_handler, updates displayed frame */
var plot = $('#{plot_id}')[0];
var data = JSON.parse(msg);
$.each(data.data, function(i, obj) {{
  $.each(Object.keys(obj), function(j, key) {{
    plot.data[i][key] = obj[key];
  }});
}});
Plotly.relayout(plot, data.layout);
Plotly.redraw(plot);
"""

PLOTLY_WARNING = """
<div class="alert alert-warning">
The plotly backend is experimental, and is
not supported at this time.  If you would like to volunteer to help
maintain this backend by adding documentation, responding to user
issues, keeping the backend up to date as other code changes, or by
adding support for other elements, please email [email protected]
Пример #33
0
 def tearDown(self):
     with param.logging_level('ERROR'):
         Renderer.notebook_context = self.nbcontext
         Renderer.comm_manager = self.comm_manager
     Store.current_backend = self.previous_backend
Пример #34
0
    def __call__(self, *args, **params):
        from .reactive import ReactiveHTML, ReactiveHTMLMetaclass
        reactive_exts = {
            v._extension_name: v
            for k, v in param.concrete_descendents(ReactiveHTML).items()
        }
        for arg in args:
            if arg in self._imports:
                try:
                    if (arg == 'ipywidgets' and get_ipython()
                            and  # noqa (get_ipython)
                            not "PANEL_IPYWIDGET" in os.environ):
                        continue
                except Exception:
                    pass
                __import__(self._imports[arg])
            elif arg in reactive_exts:
                ReactiveHTMLMetaclass._loaded_extensions.add(arg)
            else:
                self.param.warning('%s extension not recognized and '
                                   'will be skipped.' % arg)

        for k, v in params.items():
            if k in ['raw_css', 'css_files']:
                if not isinstance(v, list):
                    raise ValueError('%s should be supplied as a list, '
                                     'not as a %s type.' %
                                     (k, type(v).__name__))
                getattr(config, k).extend(v)
            elif k == 'js_files':
                getattr(config, k).update(v)
            else:
                setattr(config, k, v)

        if config.apply_signatures:
            self._apply_signatures()

        loaded = self._loaded

        # Short circuit pyvista extension load if VTK is already initialized
        if loaded and args == ('vtk', ) and 'vtk' in self._loaded_extensions:
            curframe = inspect.currentframe()
            calframe = inspect.getouterframes(curframe, 2)
            if len(calframe) >= 3 and 'pyvista' in calframe[2].filename:
                return

        if 'holoviews' in sys.modules:
            import holoviews as hv
            import holoviews.plotting.bokeh  # noqa
            loaded = loaded or getattr(hv.extension, '_loaded', False)

            if hv.Store.current_backend in hv.Store.renderers:
                backend = hv.Store.current_backend
            else:
                backend = 'bokeh'
            if hasattr(hv.Store, 'set_current_backend'):
                hv.Store.set_current_backend(backend)
            else:
                hv.Store.current_backend = backend

        # Abort if IPython not found
        try:
            ip = params.pop('ip', None) or get_ipython()  # noqa (get_ipython)
        except Exception:
            return

        newly_loaded = [
            arg for arg in args
            if arg not in panel_extension._loaded_extensions
        ]
        if loaded and newly_loaded:
            self.param.warning(
                "A HoloViz extension was loaded previously. This means "
                "the extension is already initialized and the following "
                "Panel extensions could not be properly loaded: %s. "
                "If you are loading custom extensions with pn.extension(...) "
                "ensure that this is called before any other HoloViz "
                "extension such as hvPlot or HoloViews." % newly_loaded)
        else:
            panel_extension._loaded_extensions += newly_loaded

        if hasattr(ip,
                   'kernel') and not self._loaded and not config._doc_build:
            # TODO: JLab extension and pyviz_comms should be changed
            #       to allow multiple cleanup comms to be registered
            _JupyterCommManager.get_client_comm(self._process_comm_msg,
                                                "hv-extension-comm")
            state._comm_manager = _JupyterCommManager

        if 'ipywidgets' in sys.modules and config.embed:
            # In embedded mode the ipywidgets_bokeh model must be loaded
            __import__(self._imports['ipywidgets'])

        nb_loaded = getattr(self, '_repeat_execution_in_cell', False)
        if 'holoviews' in sys.modules:
            if getattr(hv.extension, '_loaded', False):
                return
            with param.logging_level('ERROR'):
                hv.plotting.Renderer.load_nb(config.inline)
                if hasattr(hv.plotting.Renderer, '_render_with_panel'):
                    nb_loaded = True

        if not nb_loaded and hasattr(ip, 'kernel'):
            load_notebook(config.inline)
        panel_extension._loaded = True

        if 'comms' in params:
            return

        # Try to detect environment so that we can enable comms
        try:
            import google.colab  # noqa
            config.comms = "colab"
            return
        except ImportError:
            pass

        # Check if we're running in VSCode
        if "VSCODE_PID" in os.environ:
            config.comms = "vscode"

        if "pyodide" in sys.modules:
            config.comms = "ipywidgets"

        if config.notifications:
            display(state.notifications)  # noqa
Пример #35
0
 def tearDown(self):
     with param.logging_level('ERROR'):
         Stream.registry = defaultdict(list)