Example #1
0
class AcePlot(HTMLBox):
    """
    A Bokeh model that wraps around a Ace editor and renders it inside
    a Bokeh plot.
    """

    __javascript__ = ['https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.3/ace.js',
                      'https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.3/ext-language_tools.js']

    __js_require__ = {'paths': {'ace': 'https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.3/ace',
                                'ace_lang_tools': 'https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.3/ext-language_tools'},
                      'exports': {'ace': 'ace'}}

    code = String()

    theme = String(default='chrome')

    language = String(default='python')

    annotations = List(Dict(String, Any), default=[])

    readonly = Bool(default=False)

    height = Override(default=300)

    width = Override(default=300)
Example #2
0
File: vtk.py Project: xtaje/panel
class VTKPlot(HTMLBox):
    """
    A Bokeh model that wraps around a vtk-js library and renders it inside
    a Bokeh plot.
    """

    __javascript__ = [vtk_cdn]

    __js_require__ = {"paths": {"vtk": vtk_cdn[:-3]},
                      "shim": {"vtk": {"exports": "vtk"}}}

    __implementation__ = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'vtk.ts')

    append = Bool(default=False)

    data = String(help="""The serialized vtk.js data""")

    camera = Dict(String, Any)

    enable_keybindings = Bool(default=False)

    orientation_widget = Bool(default=False)

    renderer_el = Any(readonly=True)

    height = Override(default=300)

    width = Override(default=300)
Example #3
0
class VTKVolumePlot(HTMLBox):
    """
    A Bokeh model that wraps around a vtk-js library and renders it inside
    a Bokeh plot.
    """

    __javascript__ = [vtk_cdn]

    __js_require__ = {
        "paths": {
            "vtk": vtk_cdn[:-3]
        },
        "shim": {
            "vtk": {
                "exports": "vtk"
            }
        }
    }

    actor = Any(readonly=True)

    data = Dict(String, Any)

    height = Override(default=300)

    width = Override(default=300)
Example #4
0
class Player(Widget):
    """
    The Player widget provides controls to play through a number of frames.
    """

    start = Int(help="Lower bound of the Player slider")

    end = Int(help="Upper bound of the Player slider")

    value = Int(0, help="Current value of the player app")

    step = Int(1, help="Number of steps to advance the player by.")

    interval = Int(500, help="Interval between updates")

    direction = Int(0,
                    help="""
        Current play direction of the Player (-1: playing in reverse,
        0: paused, 1: playing)""")

    loop_policy = Enum('once', 'reflect', 'loop', default='once')

    show_loop_controls = Bool(True,
                              help="""Whether the loop controls
        radio buttons are shown""")

    width = Override(default=400)

    height = Override(default=250)
Example #5
0
class AbstractVTKPlot(HTMLBox):
    """
    Abstract Bokeh model for vtk plots that wraps around a vtk-js library and
    renders it inside a Bokeh plot.
    """

    __javascript__ = [vtk_cdn]

    __js_skip__ = {'vtk': [vtk_cdn]}

    __js_require__ = {
        "paths": {
            "vtk": vtk_cdn[:-3]
        },
        "exports": {
            "vtk": None
        },
        "shim": {
            "vtk": {
                "exports": "vtk"
            }
        }
    }

    renderer_el = Any(readonly=True)

    orientation_widget = Bool(default=False)

    camera = Dict(String, Any)

    height = Override(default=300)

    width = Override(default=300)
Example #6
0
class Stack(CollisionModifier):
    """Cumulates elements in the order of grouped values.

    Useful for area or bar glyphs.
    """
    name = Override(default='stack')
    method_name = Override(default='__stack__')
Example #7
0
class Dodge(CollisionModifier):
    """Non-cumulative, moves glyphs around so they don't overlap.

    Useful for bar, box, or dot glyphs.
    """
    name = Override(default='dodge')
    method_name = Override(default='__dodge__')
Example #8
0
class TimeAxis(LinearAxis):
    """ An LinearAxis that picks nice numbers for tick locations on a
    time scale. Configured with a ``TimeTickFormatter`` by default.
    """
    __implementation__ = 'time_axis.coffee'

    ticker = Override(default=lambda: TimeTicker())
    formatter = Override(default=lambda: TimeTickFormatter())
Example #9
0
class DeckGLPlot(HTMLBox):
    """A Bokeh model that wraps around a DeckGL plot and renders it inside a HTMLBox"""

    __css_raw__ = ["https://api.mapbox.com/mapbox-gl-js/v1.7.0/mapbox-gl.css"]

    @classproperty
    def __css__(cls):
        return bundled_files(cls, 'css')

    __javascript_raw__ = [
        "https://cdn.jsdelivr.net/npm/[email protected]/dist.min.js",
        "https://cdn.jsdelivr.net/npm/@deck.gl/[email protected]/dist.min.js",
        "https://cdn.jsdelivr.net/npm/@loaders.gl/[email protected]/dist/dist.min.js",
        "https://cdn.jsdelivr.net/npm/@loaders.gl/[email protected]/dist/dist.min.js",
        "https://cdn.jsdelivr.net/npm/@loaders.gl/[email protected]/dist/dist.min.js",
        "https://api.mapbox.com/mapbox-gl-js/v1.7.0/mapbox-gl.js",
    ]

    @classproperty
    def __javascript__(cls):
        return bundled_files(cls)

    @classproperty
    def __js_skip__(cls):
        return {
            'deck': cls.__javascript__[:-1],
            'mapboxgl': cls.__javascript__[-1:]
        }

    __js_require__ = {
        'paths': OrderedDict([
            ("deck.gl", "https://cdn.jsdelivr.net/npm/@deck.gl/jupyter-widget@^8.1.2/dist/index"),
            ("mapbox-gl", 'https://cdn.jsdelivr.net/npm/[email protected]/dist/mapbox-gl.min'),
        ]),
        'exports': {"deck.gl": "deck", "mapbox-gl": "mapboxgl"}
    }

    data = Dict(String, Any)

    data_sources = List(Instance(ColumnDataSource))

    initialViewState = Dict(String, Any)

    layers = List(Dict(String, Any))

    mapbox_api_key = String()

    tooltip = Either(Bool, Dict(Any, Any))

    clickState = Dict(String, Any)

    hoverState = Dict(String, Any)

    viewState = Dict(String, Any)

    height = Override(default=400)

    width = Override(default=600)
Example #10
0
class MarkerAttr(AttrSpec):
    """An attribute specification for mapping unique data values to markers."""
    attrname = Override(default='marker')
    iterable = Override(default=list(marker_types.keys()))

    def __init__(self, **kwargs):
        iterable = kwargs.pop('markers', None)
        if iterable is not None:
            kwargs['iterable'] = iterable
        super(MarkerAttr, self).__init__(**kwargs)
Example #11
0
class DashAttr(AttrSpec):
    """An attribute specification for mapping unique data values to line dashes."""
    attrname = Override(default='dash')
    iterable = Override(default=dashes)

    def __init__(self, **kwargs):
        iterable = kwargs.pop('dash', None)
        if iterable is not None:
            kwargs['iterable'] = iterable
        super(DashAttr, self).__init__(**kwargs)
class ColorAttr(AttrSpec):
    """An attribute specification for mapping unique data values to colors.

    .. note::
        Should be expanded to support more complex coloring options.
    """
    attrname = Override(default='color')
    iterable = Override(default=DEFAULT_PALETTE)
    bin = Bool(default=False)

    def __init__(self, **kwargs):
        iterable = kwargs.pop('palette', None)
        if iterable is not None:
            kwargs['iterable'] = iterable
        super(ColorAttr, self).__init__(**kwargs)

    def _generate_items(self, df, columns):
        """Produce list of unique tuples that identify each item."""
        if not self.bin:
            super(ColorAttr, self)._generate_items(df, columns)
        else:

            if len(columns) == 1 and ChartDataSource.is_number(df[columns[0]]):

                self.bins = Bins(source=ColumnDataSource(df),
                                 column=columns[0],
                                 bins=len(self.iterable),
                                 aggregate=False)

                if self.sort:
                    self.bins.sort(ascending=self.ascending)

                self.items = [bin.label[0] for bin in self.bins]
            else:
                raise ValueError(
                    'Binned colors can only be created for one column of \
                                 numerical data.')

    def add_bin_labels(self, data):
        col = self.columns[0]
        # save original values into new column
        data._data[col + '_values'] = data._data[col]

        for bin in self.bins:
            # set all rows associated to each bin to the bin label being mapped to colors
            data._data.ix[data._data[col + '_values'].isin(bin.values),
                          col] = bin.label[0]

        data._data[col] = pd.Categorical(data._data[col],
                                         categories=list(self.items),
                                         ordered=self.sort)
Example #13
0
class AcePlot(HTMLBox):
    """
    A Bokeh model that wraps around a Ace editor and renders it inside
    a Bokeh plot.
    """

    __javascript__ = [
        'https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.11/ace.js',
        'https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.11/ext-language_tools.js',
        'https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.11/ext-modelist.min.js'
    ]

    __js_skip__ = {'ace': __javascript__}

    __js_require__ = {
        'paths': {
            ('ace', ('ace/ace', 'ace/ext-language_tools')):
            '//cdnjs.cloudflare.com/ajax/libs/ace/1.4.7'
        },
        'exports': {
            'ace': 'ace'
        },
        'shim': {
            'ace/ext-language_tools': {
                'deps': ["ace/ace"]
            },
            'ace/ext-modelist': {
                'deps': ["ace/ace"]
            }
        }
    }

    code = String()

    theme = Enum(ace_themes, default='chrome')

    filename = String()

    language = String()

    annotations = List(Dict(String, Any), default=[])

    readonly = Bool(default=False)

    print_margin = Bool(default=False)

    height = Override(default=300)

    width = Override(default=300)
Example #14
0
class Player(Widget):
    """
    The Player widget provides controls to play through a number of frames.
    """

    __implementation__ = os.path.join(
        os.path.abspath(os.path.dirname(__file__)), 'player.ts')

    start = Int(help="Lower bound of the Player slider")

    end = Int(help="Upper bound of the Player slider")

    value = Int(0, help="Current value of the player app")

    step = Int(1, help="Number of steps to advance the player by.")

    interval = Int(500, help="Interval between updates")

    direction = Int(0,
                    help="""
        Current play direction of the Player (-1: playing in reverse,
        0: paused, 1: playing)""")

    loop_policy = Enum('once', 'reflect', 'loop', default='once')

    height = Override(default=250)
Example #15
0
class FileDownload(InputWidget):

    auto = Bool(False, help="""Whether to download on click""")

    button_type = Enum(ButtonType,
                       help="""
    A style for the button, signifying it's role.
    """)

    clicks = Int(0,
                 help="""
    A private property that used to trigger ``on_click`` event handler.
    """)

    data = String(help="""Encoded URI data.""")

    label = String("", help="""The text label for the button to display.""")

    filename = String(help="""Filename to use on download""")

    _transfers = Int(0,
                     help="""
    A private property to create and click the link.
    """)

    title = Override(default='')
Example #16
0
class DerivedDataModel(SomeDataModel):
    prop3 = Int()
    prop4 = Int(default=112)
    prop5 = List(Int, default=[1, 2, 3, 4])
    prop6 = Nullable(Instance(SomeDataModel))

    prop2 = Override(default=119)
Example #17
0
class MyPlot(Plot):

    __implementation__ = """
import {Plot, PlotView} from "models/plots/plot"
import * as p from "core/properties"
import "./custom.less"

export class MyPlotView extends PlotView
  render: () ->
    super()
    @el.classList.add("bk-my-plot")

    angle = "#{@model.gradient_angle}deg"

    offset = 0
    colors = []
    step = @model.gradient_step

    for color in @model.gradient_colors
      colors.push("#{color} #{offset}px")
      offset += step
      colors.push("#{color} #{offset}px")

    @el.style.backgroundImage = "repeating-linear-gradient(#{angle}, #{colors.join(', ')})"

export class MyPlot extends Plot
  type: "MyPlot"
  default_view: MyPlotView

  @define {
    gradient_angle:  [ p.Number, 0                      ]
    gradient_step:   [ p.Number, 20                     ]
    gradient_colors: [ p.Array,  ["white", "lightgray"] ]
  }

  @override {
    background_fill_alpha: 0.0
    border_fill_alpha: 0.0
  }
"""

    gradient_angle = Float(default=0)
    gradient_step = Float(default=20)
    gradient_colors = List(Color, default=["white", "gray"])

    background_fill_alpha = Override(default=0.0)
    border_fill_alpha = Override(default=0.0)
Example #18
0
class VideoStream(HTMLBox):

    format = Enum('png', 'jpeg', default='png')

    paused = Bool(False, help="""Whether the video is paused""")

    snapshot = Bool(False, help="""On change generate a snapshot of the current video frame""")

    timeout = Float(None, help="""
        The timeout between snapshots (if None snapshot only generated
        when snapshot property is changed""")

    value = Any(help="""Snapshot Data""")

    height = Override(default=240)

    width = Override(default=320)
Example #19
0
class PointGlyph(XyGlyph):
    """A set of glyphs placed in x,y coordinates with the same attributes."""

    fill_color = Override(default=DEFAULT_PALETTE[1])
    fill_alpha = Override(default=0.7)
    marker = String(default='circle')
    size = Float(default=8)

    def __init__(self,
                 x=None,
                 y=None,
                 color=None,
                 line_color=None,
                 fill_color=None,
                 marker=None,
                 size=None,
                 **kwargs):
        kwargs['x'] = x
        kwargs['y'] = y
        if marker is not None: kwargs['marker'] = marker
        if size is not None: kwargs['size'] = size

        if color:
            line_color = color
            fill_color = color

        kwargs['line_color'] = line_color
        kwargs['fill_color'] = fill_color

        super(PointGlyph, self).__init__(**kwargs)
        self.setup()

    def get_glyph(self):
        return marker_types[self.marker]

    def build_renderers(self):
        glyph_type = self.get_glyph()
        glyph = glyph_type(x='x_values',
                           y='y_values',
                           line_color=self.line_color,
                           fill_color=self.fill_color,
                           size=self.size,
                           fill_alpha=self.fill_alpha,
                           line_alpha=self.line_alpha)
        yield GlyphRenderer(glyph=glyph)
Example #20
0
class AbstractVTKPlot(HTMLBox):
    """
    Abstract Bokeh model for vtk plots that wraps around a vtk-js library and
    renders it inside a Bokeh plot.
    """

    __javascript_raw__ = [vtk_cdn]

    @classproperty
    def __javascript__(cls):
        return bundled_files(AbstractVTKPlot)

    @classproperty
    def __js_skip__(cls):
        return {'vtk': cls.__javascript__}

    __js_require__ = {
        "paths": {
            "vtk": vtk_cdn[:-3]
        },
        "exports": {
            "vtk": None
        },
        "shim": {
            "vtk": {
                "exports": "vtk"
            },
        }
    }

    axes = Instance(VTKAxes)

    camera = Dict(String, Any)

    color_mappers = List(Instance(ColorMapper))

    height = Override(default=300)

    orientation_widget = Bool(default=False)

    interactive_orientation_widget = Bool(default=False)

    width = Override(default=300)

    annotations = List(Dict(String, Any))
Example #21
0
class Custom(HTMLBox):

    __implementation__ = TypeScript(CODE)

    text = String(default="Custom text")

    slider = Instance(Slider)

    margin = Override(default=5)
Example #22
0
class HighTable(TableWidget):
    ''' Two dimensional grid for visualisation and editing large amounts
    of data.
    '''

    __implementation__ = "high_table.coffee"

    columns = List(Instance(TableColumn), help="""
    The list of child column widgets.
    """)

    fit_columns = Bool(True, help="""
    Whether columns should be fit to the available width. This results in no
    horizontal scrollbar showing up, but data can get unreadable if there is
    no enough space available. If set to ``True``, columns' width is
    understood as maximum width.
    """)

    sortable = Bool(True, help="""
    Allows to sort table's contents. By default natural order is preserved.
    To sort a column, click on it's header. Clicking one more time changes
    sort direction. Use Ctrl + click to return to natural order. Use
    Shift + click to sort multiple columns simultaneously.
    """)

    reorderable = Bool(True, help="""
    Allows the reordering of a tables's columns. To reorder a column,
    click and drag a table's header to the desired location in the table.
    The columns on either side will remain in their previous order.
    """)

    editable = Bool(False, help="""
    Allows to edit table's contents. Needs cell editors to be configured on
    columns that are required to be editable.
    """)

    selectable = Either(Bool(True), Enum("checkbox"), help="""
    Whether a table's rows can be selected or not. Using ``checkbox`` is
    equivalent  to ``True``, but makes selection visible through a checkbox
    for each row,  instead of highlighting rows. Multiple selection is
    allowed and can be achieved by either clicking multiple checkboxes (if
    enabled) or using Shift + click on rows.
    """)

    row_headers = Bool(True, help="""
    Enable or disable row headers, i.e. the index column.
    """)

    scroll_to_selection = Bool(True, help="""
    Whenever a selection is made on the data source, scroll the selected
    rows into the table's viewport if none of the selected rows are already
    in the viewport.
    """)

    height = Override(default=400)
Example #23
0
File: vtk.py Project: xtaje/panel
class VTKVolumePlot(HTMLBox):
    """
    A Bokeh model that wraps around a vtk-js library and renders it inside
    a Bokeh plot.
    """

    __javascript__ = [vtk_cdn]

    __js_require__ = {"paths": {"vtk": vtk_cdn[:-3]},
                      "shim": {"vtk": {"exports": "vtk"}}}

    __implementation__ = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'vtkvolume.ts')

    actor = Any(readonly=True)

    data = Dict(String, Any)

    height = Override(default=300)

    width = Override(default=300)
Example #24
0
class VTKPlot(HTMLBox):
    """
    A Bokeh model that wraps around a vtk-js library and renders it inside
    a Bokeh plot.
    """

    __javascript__ = [vtk_cdn]

    __js_skip__ = {'vtk': [vtk_cdn]}

    __js_require__ = {
        "paths": {
            "vtk": vtk_cdn[:-3]
        },
        "exports": {
            "vtk": None
        },
        "shim": {
            "vtk": {
                "exports": "vtk"
            }
        }
    }

    append = Bool(default=False)

    data = String(help="""The serialized vtk.js data""")

    camera = Dict(String, Any)

    axes = Instance(VTKAxes)

    enable_keybindings = Bool(default=False)

    orientation_widget = Bool(default=False)

    renderer_el = Any(readonly=True)

    height = Override(default=300)

    width = Override(default=300)
Example #25
0
class WaterfallRenderer(Renderer):

    latest = Seq(Float)

    palette = Seq(Color)

    num_grams = Int()

    gram_length = Int()

    tile_width = Int()

    level = Override(default="glyph")
Example #26
0
class TimeTicker(CompositeTicker):
    """ Generate nice ticks across different time scales.
    """
    __implementation__ = 'time_ticker.coffee'

    num_minor_ticks = Override(default=4)
    tickers = Override(default=lambda: [
        AdaptiveTicker(mantissas=[1, 2, 5],
                       base=10,
                       min_interval=ONE_NANO,
                       max_interval=500 * ONE_MILLI,
                       num_minor_ticks=5),
        AdaptiveTicker(mantissas=[1, 2, 5, 10, 15, 20, 30],
                       base=60,
                       min_interval=ONE_SECOND,
                       max_interval=30 * ONE_MINUTE,
                       num_minor_ticks=4),
        AdaptiveTicker(mantissas=[1, 2, 4, 6, 8, 12],
                       base=24,
                       min_interval=ONE_HOUR,
                       max_interval=None,
                       num_minor_ticks=4)
    ])
Example #27
0
class WaterfallRenderer(Renderer):

    __implementation__ = join(dirname(__file__), "waterfall.coffee")

    latest = Seq(Float)

    palette = Seq(Color)

    num_grams = Int()

    gram_length = Int()

    tile_width = Int()

    level = Override(default="glyph")
Example #28
0
class WaterfallRenderer(Renderer):
    __implementation__ = join(dirname(__file__), "waterfall.ts")

    latest = Seq(Float, default=[])

    palette = Seq(Color)

    time_length = Int()

    fft_length = Int()

    min_value = Float()

    max_value = Float()

    update = Bool()

    level = Override(default = "glyph")
class FontAwesomeButton(bokeh.models.AbstractButton):
    __implementation__ = 'font_awesome_button.ts'

    label = Override(default="FontAwesomeButton")
    clicks = Int(0)
    def on_click(self, handler):
        ''' Set up a handler for button clicks.

        Args:
            handler (func) : handler function to call when button is clicked.

        Returns:
            None

        '''
        self.on_event(ButtonClick, handler)


    def js_on_click(self, handler):
        ''' Set up a JavaScript handler for button clicks. '''
        self.js_on_event(ButtonClick, handler)
Example #30
0
class CatAttr(AttrSpec):
    """An attribute specification for mapping unique data values to labels.

    .. note::
        this is a special attribute specification, which is used for defining which
        labels are used for one aspect of a chart (grouping) vs another (stacking or
        legend)
    """
    attrname = Override(default='nest')

    def __init__(self, **kwargs):
        super(CatAttr, self).__init__(**kwargs)

    def _setup_iterable(self):
        return iter(self.items)

    def get_levels(self, columns):
        """Provides a list of levels the attribute represents."""
        if self.columns is not None:
            levels = [columns.index(col) for col in self.columns]
            return levels
        else:
            return []