class BinnedStat(Stat): """ Base class for shared functionality accross bins and aggregates dimensions for plotting. """ bin_stat = Instance(BinStats, help=""" A mapping between each dimension and associated binning calculations. """) bins = List(Instance(Bin), help=""" A list of the `Bin` instances that were produced as result of the inputs. Iterating over `Bins` will iterate over this list. Each `Bin` can be inspected for metadata about the bin and the values associated with it. """) stat = Instance(Stat, default=Count(), help=""" The statistical operation to be used on the values in each bin. """) bin_column = String() centers_column = String() aggregate = Bool(default=True) bin_values = Bool(default=False) bin_width = Float() def __init__(self, values=None, column=None, bins=None, stat='count', source=None, **properties): if isinstance(stat, str): stat = stats[stat]() properties['column'] = column or 'vals' properties['stat'] = stat properties['values'] = values properties['source'] = source self._bins = bins super(BinnedStat, self).__init__(**properties) def _get_stat(self): stat_kwargs = {} if self.source is not None: stat_kwargs['source'] = self.source stat_kwargs['column'] = self.column elif self.values is not None: stat_kwargs['values'] = self.values stat_kwargs['bins'] = self._bins return BinStats(**stat_kwargs) def update(self): self.bin_stat = self._get_stat() self.bin_stat.update()
class Base(HasProps): num = Int(12) container = List(String) child = Instance(HasProps)
class Sub(Base, Mixin): sub_num = Int(12) sub_container = List(String) sub_child = Instance(HasProps)
def test_List(self) -> None: p = List(Float) with pytest.raises(ValueError) as e: p.validate("junk") assert matches(str(e.value), r"expected an element of List\(Float\), got 'junk'")
class AttrSpec(HasProps): """A container for assigning attributes to values and retrieving them as needed. A special function this provides is automatically handling cases where the provided iterator is too short compared to the distinct values provided. Once created as attr_spec, you can do attr_spec[data_label], where data_label must be a one dimensional tuple of values, representing the unique group in the data. See the :meth:`AttrSpec.setup` method for the primary way to provide an existing AttrSpec with data and column values and update all derived property values. """ data = Instance(ColumnDataSource) iterable = List(Any, default=None) attrname = String(help='Name of the attribute the spec provides.') columns = Either(ColumnLabel, List(ColumnLabel), help=""" The label or list of column labels that correspond to the columns that will be used to find all distinct values (single column) or combination of values ( multiple columns) to then assign a unique attribute to. If not enough unique attribute values are found, then the attribute values will be cycled. """) default = Any(default=None, help=""" The default value for the attribute, which is used if no column is assigned to the attribute for plotting. If the default value is not provided, the first value in the `iterable` property is used. """) attr_map = Dict(Any, Any, help=""" Created by the attribute specification when `iterable` and `data` are available. The `attr_map` will include a mapping between the distinct value(s) found in `columns` and the attribute value that has been assigned. """) items = Any(default=None, help=""" The attribute specification calculates this list of distinct values that are found in `columns` of `data`. """) sort = Bool(default=True, help=""" A boolean flag to tell the attribute specification to sort `items`, when it is calculated. This affects which value of `iterable` is assigned to each distinct value in `items`. """) ascending = Bool(default=True, help=""" A boolean flag to tell the attribute specification how to sort `items` if the `sort` property is set to `True`. The default setting for `ascending` is `True`. """) bins = Instance(Bins, help=""" If an attribute spec is binning data, so that we can map one value in the `iterable` to one value in `items`, then this attribute will contain an instance of the Bins stat. This is used to create unique labels for each bin, which is then used for `items` instead of the actual unique values in `columns`. """) def __init__(self, columns=None, df=None, iterable=None, default=None, items=None, **properties): """Create a lazy evaluated attribute specification. Args: columns: a list of column labels df(:class:`~pandas.DataFrame`): the data source for the attribute spec. iterable: an iterable of distinct attribute values default: a value to use as the default attribute when no columns are passed items: the distinct values in columns. If items is provided as input, then the values provided are used instead of being calculated. This can be used to force a specific order for assignment. **properties: other properties to pass to parent :class:`HasProps` """ properties['columns'] = self._ensure_list(columns) if df is not None: properties['data'] = ColumnDataSource(df) if default is None and iterable is not None: default_iter = copy(iterable) properties['default'] = next(iter(default_iter)) elif default is not None: properties['default'] = default if iterable is not None: properties['iterable'] = iterable if items is not None: properties['items'] = items super(AttrSpec, self).__init__(**properties) if self.default is None and self.iterable is not None: self.default = next(iter(copy(self.iterable))) if self.data is not None and self.columns is not None: if df is None: df = self.data.to_df() self._generate_items(df, columns=self.columns) if self.items is not None and self.iterable is not None: self.attr_map = self._create_attr_map() @staticmethod def _ensure_list(attr): """Always returns a list with the provided value. Returns the value if a list.""" if isinstance(attr, str): return [attr] elif isinstance(attr, tuple): return list(attr) else: return attr @staticmethod def _ensure_tuple(attr): """Return tuple with the provided value. Returns the value if a tuple.""" if not isinstance(attr, tuple): return (attr, ) else: return attr def _setup_default(self): """Stores the first value of iterable into `default` property.""" self.default = next(self._setup_iterable()) def _setup_iterable(self): """Default behavior is to copy and cycle the provided iterable.""" return cycle(copy(self.iterable)) def _generate_items(self, df, columns): """Produce list of unique tuples that identify each item.""" if self.sort: # TODO (fpliger): this handles pandas API change so users do not experience # the related annoying deprecation warning. This is probably worth # removing when pandas deprecated version (0.16) is "old" enough try: df = df.sort_values(by=columns, ascending=self.ascending) except AttributeError: df = df.sort(columns=columns, ascending=self.ascending) items = df[columns].drop_duplicates() self.items = [tuple(x) for x in items.to_records(index=False)] def _create_attr_map(self, df=None, columns=None): """Creates map between unique values and available attributes.""" if df is not None and columns is not None: self._generate_items(df, columns) iterable = self._setup_iterable() return {item: next(iterable) for item in self._item_tuples()} def _item_tuples(self): return [self._ensure_tuple(item) for item in self.items] def set_columns(self, columns): """Set columns property and update derived properties as needed.""" columns = self._ensure_list(columns) if all([col in self.data.column_names for col in columns]): self.columns = columns else: # we have input values other than columns # assume this is now the iterable at this point self.iterable = columns self._setup_default() def setup(self, data=None, columns=None): """Set the data and update derived properties as needed.""" if data is not None: self.data = data if columns is not None and self.data is not None: self.set_columns(columns) if self.columns is not None and self.data is not None: self.attr_map = self._create_attr_map(self.data.to_df(), self.columns) def update_data(self, data): self.setup(data=data, columns=self.columns) def __getitem__(self, item): """Lookup the attribute to use for the given unique group label.""" if not self.attr_map: return self.default elif self._ensure_tuple(item) not in self.attr_map.keys(): # make sure we have attr map self.setup() return self.attr_map[self._ensure_tuple(item)] @property def series(self): if not self.attr_map: return pd.Series() else: index = pd.MultiIndex.from_tuples(self._item_tuples(), names=self.columns) return pd.Series(list(self.attr_map.values()), index=index)
class HorizonGlyph(AreaGlyph): num_folds = Int(default=3, help="""The count of times the data is overlapped.""") series = Int(default=0, help="""The id of the series as the order it will appear, starting from 0.""") series_count = Int() fold_height = Float(help="""The height of one fold.""") bins = List(Float, help="""The binedges calculated from the number of folds, and the maximum value of the entire source data.""") graph_ratio = Float( help="""Scales heights of each series based on number of folds and the number of total series being plotted. """) pos_color = Color("#006400", help="""The color used for positive values.""") neg_color = Color("#6495ed", help="""The color used for negative values.""") flip_neg = Bool(default=True, help="""When True, the negative values will be plotted as their absolute value, then their individual axes is flipped. If False, then the negative values will still be taken as their absolute value, but the base of their shape will start from the same origin as the positive values. """) def __init__(self, bins=None, **kwargs): # fill alpha depends on how many folds will be layered kwargs['fill_alpha'] = 1.0 / kwargs['num_folds'] if bins is not None: kwargs['bins'] = bins # each series is shifted up to a synthetic y-axis kwargs['base'] = kwargs['series'] * max( bins) / kwargs['series_count'] kwargs['graph_ratio'] = float(kwargs['num_folds']) / float( kwargs['series_count']) super(HorizonGlyph, self).__init__(**kwargs) def build_source(self): data = {} # Build columns for the positive values pos_y = self.y.copy() pos_y[pos_y < 0] = 0 xs, ys = self._build_dims(self.x, pos_y) # list of positive colors and alphas colors = [self.pos_color] * len(ys) alphas = [(bin_idx * self.fill_alpha) for bin_idx in range(0, len(self.bins))] # If we have negative values at all, add the values for those as well if self.y.min() < 0: neg_y = self.y.copy() neg_y[neg_y > 0] = 0 neg_y = abs(neg_y) neg_xs, neg_ys = self._build_dims(self.x, neg_y, self.flip_neg) xs += neg_xs ys += neg_ys colors += ([self.neg_color] * len(neg_ys)) alphas += alphas # create clipped representation of each band data['x_values'] = xs data['y_values'] = ys data['fill_color'] = colors data['fill_alpha'] = colors data['line_color'] = colors return data def _build_dims(self, x, y, flip=False): """ Creates values needed to plot each fold of the horizon glyph. Bins the data based on the binning passed into the glyph, then copies and clips the values for each bin. Args: x (`pandas.Series`): array of x values y (`pandas.Series`): array of y values flip (bool): whether to flip values, used when handling negative values Returns: tuple(list(`numpy.ndarray`), list(`numpy.ndarray`)): returns a list of arrays for the x values and list of arrays for the y values. The data has been folded and transformed so the patches glyph presents the data in a way that looks like an area chart. """ # assign bins to each y value bin_idx = pd.cut(y, bins=self.bins, labels=False, include_lowest=True) xs, ys = [], [] for idx, bin in enumerate(self.bins[0:-1]): # subtract off values associated with lower bins, to get into this bin temp_vals = y.copy() - (idx * self.fold_height) # clip the values between the fold range and zero temp_vals[bin_idx > idx] = self.fold_height * self.graph_ratio temp_vals[bin_idx < idx] = 0 temp_vals[bin_idx == idx] = self.graph_ratio * temp_vals[bin_idx == idx] # if flipping, we must start the values from the top of each fold's range if flip: temp_vals = (self.fold_height * self.graph_ratio) - temp_vals base = self.base + (self.fold_height * self.graph_ratio) else: base = self.base # shift values up based on index of series temp_vals += self.base val_idx = temp_vals > 0 if pd.Series.any(val_idx): ys.append(temp_vals) xs.append(x) # transform clipped data so it always starts and ends at its base value if len(ys) > 0: xs, ys = map( list, zip(*[ generate_patch_base(x, y, base=base) for x, y in zip(xs, ys) ])) return xs, ys def build_renderers(self): # parse all series. We exclude the first attr as it's the x values # added for the index glyph = Patches(xs='x_values', ys='y_values', fill_alpha=self.fill_alpha, fill_color='fill_color', line_color='line_color') renderer = GlyphRenderer(data_source=self.source, glyph=glyph) yield renderer
class MyPlot(Plot): __implementation__ = TypeScript(""" import {Plot, PlotView} from "models/plots/plot" import * as p from "core/properties" import "./custom.less" export class MyPlotView extends PlotView { model: MyPlot render(): void { super.render() this.el.classList.add("bk-my-plot") const angle = `${this.model.gradient_angle}deg` let offset = 0 const colors = [] const step = this.model.gradient_step for (const color of this.model.gradient_colors) { colors.push(`${color} ${offset}px`) offset += step colors.push(`${color} ${offset}px`) } this.el.style.backgroundImage = `repeating-linear-gradient(${angle}, ${colors.join(', ')})` } } export namespace MyPlot { export type Attrs = p.AttrsOf<Props> export type Props = Plot.Props & { gradient_angle: p.Property<number> gradient_step: p.Property<number> gradient_colors: p.Property<string[]> } } export interface MyPlot extends MyPlot.Attrs { width: number | null height: number | null } export class MyPlot extends Plot { properties: MyPlot.Props static init_MyPlot(): void { this.prototype.default_view = MyPlotView this.define<MyPlot.Props>({ gradient_angle: [ p.Number, 0 ], gradient_step: [ p.Number, 20 ], gradient_colors: [ p.Array, ["white", "lightgray"] ], }) this.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)
def test_List(self, detail): p = List(Float) with pytest.raises(ValueError) as e: p.validate("junk", detail) assert str(e).endswith("ValueError") == (not detail)
class EitherSimpleDefault(hp.HasProps): foo = Either(List(Int), Int, default=10)
class HistogramGlyph(AggregateGlyph): """Depicts the distribution of values using rectangles created by binning. The histogram represents a distribution, so will likely include other options for displaying it, such as KDE and cumulative density. """ # derived models bins = Instance(BinnedStat, help="""A stat used to calculate the bins. The bins stat includes attributes about each composite bin.""") bars = List(Instance(BarGlyph), help="""The histogram is comprised of many BarGlyphs that are derived from the values.""") density = Bool(False, help=""" Whether to normalize the histogram. If True, the result is the value of the probability *density* function at the bin, normalized such that the *integral* over the range is 1. If False, the result will contain the number of samples in each bin. For more info check :class:`~bokeh.charts.stats.Histogram` documentation. (default: False) """) def __init__(self, values, label=None, color=None, bins=None, **kwargs): if label is not None: kwargs['label'] = label kwargs['values'] = values if color is not None: kwargs['color'] = color # remove width, since this is handled automatically kwargs.pop('width', None) # keep original bins setting private since it just needs to be # delegated to the Histogram stat self._bins = bins super(HistogramGlyph, self).__init__(**kwargs) self.setup() def _set_sources(self): # No need to set sources, since composite glyphs handle this pass def build_source(self): # No need to build source, since composite glyphs handle this return None def build_renderers(self): """Yield a bar glyph for each bin.""" # TODO(fpliger): We should expose the bin stat class so we could let # users specify other bins other the Histogram Stat self.bins = Histogram(values=self.values, bins=self._bins, density=self.density) bars = [] for bin in self.bins.bins: bars.append( BarGlyph(label=bin.label[0], x_label=bin.center, values=bin.values, color=self.color, fill_alpha=self.fill_alpha, agg=bin.stat, width=bin.width)) # provide access to bars as children for bounds properties self.bars = self.children = bars for comp_glyph in self.bars: for renderer in comp_glyph.renderers: yield renderer @property def y_min(self): return 0.0
def test_List(self): p = List(Float) with pytest.raises(ValueError) as e: p.validate("junk") assert not str(e).endswith("ValueError")
class SomeModel(Model): a = Int(12) b = String("hello") c = List(Int, [1, 2, 3])
class Builder(HasProps): """ A prototype class to inherit each new chart Builder type. It provides useful methods to be used by the inherited builder classes, in order to automate most of the charts creation tasks and leave the core customization to specialized builder classes. In that pattern inherited builders just need to provide the following methods: Required: * :meth:`~bokeh.charts.builder.Builder.yield_renderers`: yields the glyphs to be rendered into the plot. Here you should call the :meth:`~bokeh.charts.builder.Builder.add_glyph` method so that the builder can setup the legend for you. * :meth:`~bokeh.charts.builder.Builder.set_ranges`: setup the ranges for the glyphs. This is called after glyph creation, so you are able to inspect the comp_glyphs for their minimum and maximum values. See the :meth:`~bokeh.charts.builder.Builder.create` method for more information on when this is called and how the builder provides the ranges to the containing :class:`Chart` using the :meth:`Chart.add_ranges` method. Optional: * :meth:`~bokeh.charts.builder.Builder.setup`: provides an area where subclasses of builder can introspect properties, setup attributes, or change property values. This is called before :meth:`~bokeh.charts.builder.Builder.process_data`. * :meth:`~bokeh.charts.builder.Builder.process_data`: provides an area where subclasses of builder can manipulate the source data before renderers are created. """ # Optional Inputs x_range = Instance(Range) y_range = Instance(Range) xlabel = String() ylabel = String() xscale = String() yscale = String() palette = List(Color, help="""Optional input to override the default palette used by any color attribute. """) # Dimension Configuration """ The dimension labels that drive the position of the glyphs. Subclasses should implement this so that the Builder base class knows which dimensions it needs to operate on. An example for a builder working with cartesian x and y coordinates would be dimensions = ['x', 'y']. You should then instantiate the x and y dimensions as attributes of the subclass of builder using the :class:`Dimension <bokeh.charts.properties.Dimension>` class. One for x, as x = Dimension(...), and one as y = Dimension(...). """ dimensions = None # None because it MUST be overridden """ The dimension labels that must exist to produce the glyphs. This specifies what are the valid configurations for the chart, with the option of specifying the type of the columns. The :class:`~bokeh.charts.data_source.ChartDataSource` will inspect this property of your subclass of Builder and use this to fill in any required dimensions if no keyword arguments are used. """ req_dimensions = [] # Attribute Configuration attributes = Dict(String, Instance(AttrSpec), help=""" The attribute specs used to group data. This is a mapping between the role of the attribute spec (e.g. 'color') and the :class:`~bokeh.charts.attributes.AttrSpec` class (e.g., :class:`~bokeh.charts.attributes.ColorAttr`). The Builder will use this attributes property during runtime, which will consist of any attribute specs that are passed into the chart creation function (e.g., :class:`~bokeh.charts.Bar`), ones that are created for the user from simple input types (e.g. `Bar(..., color='red')` or `Bar(..., color=<column_name>)`), or lastly, the attribute spec found in the default_attributes configured for the subclass of :class:`~bokeh.charts.builder.Builder`. """) """ The default attribute specs used to group data. This is where the subclass of Builder should specify what the default attributes are that will yield attribute values to each group of data, and any specific configuration. For example, the :class:`ColorAttr` utilizes a default palette for assigning color based on groups of data. If the user doesn't assign a column of the data to the associated attribute spec, then the default attrspec is used, which will yield a constant color value for each group of data. This is by default the first color in the default palette, but can be customized by setting the default color in the ColorAttr. """ default_attributes = None # None because it MUST be overridden # Derived properties (created by Builder at runtime) attribute_columns = List(ColumnLabel, help=""" All columns used for specifying attributes for the Chart. The Builder will set this value on creation so that the subclasses can know the distinct set of columns that are being used to assign attributes. """) comp_glyphs = List(Instance(CompositeGlyph), help=""" A list of composite glyphs, where each represents a unique subset of data. The composite glyph is a helper class that encapsulates all low level :class:`~bokeh.models.glyphs.Glyph`, that represent a higher level group of data. For example, the :class:`BoxGlyph` is a single class that yields each :class:`GlyphRenderer` needed to produce a Box on a :class:`BoxPlot`. The single Box represents a full array of values that are aggregated, and is made up of multiple :class:`~bokeh.models.glyphs.Rect` and :class:`~bokeh.models.glyphs.Segment` glyphs. """) labels = List( String, help="""Represents the unique labels to be used for legends.""") """List of attributes to use for legends.""" label_attributes = [] """ Used to assign columns to dimensions when no selections have been provided. The default behavior is provided by the :class:`OrderedAssigner`, which assigns a single column to each dimension available in the `Builder`'s `dims` property. """ column_selector = OrderedAssigner comp_glyph_types = List(Instance(CompositeGlyph)) sort_dim = Dict(String, Bool, default={}) sort_legend = List(Tuple(String, Bool), help=""" List of tuples to use for sorting the legend, in order that they should be used for sorting. This sorting can be different than the sorting used for the rest of the chart. For example, you might want to sort only on the column assigned to the color attribute, or sort it descending. The order of each tuple is (Column, Ascending). """) legend_sort_field = String(help=""" Attribute that should be used to sort the legend, for example: color, dash, maker, etc. Valid values for this property depend on the type of chart. """) legend_sort_direction = Enum(SortDirection, help=""" Sort direction to apply to :attr:`~bokeh.charts.builder.Builder.sort_legend`. Valid values are: `ascending` or `descending`. """) source = Instance(ColumnDataSource) tooltips = Either(List(Tuple(String, String)), List(String), Bool, default=None, help=""" Tells the builder to add tooltips to the chart by either using the columns specified to the chart attributes (True), or by generating tooltips for each column specified (list(str)), or by explicit specification of the tooltips using the valid input for the `HoverTool` tooltips kwarg. """) __deprecated_attributes__ = ('sort_legend', ) def __init__(self, *args, **kws): """Common arguments to be used by all the inherited classes. Args: data (:ref:`userguide_charts_data_types`): source data for the chart legend (str, bool): the legend of your plot. The legend content is inferred from incoming input.It can be ``top_left``, ``top_right``, ``bottom_left``, ``bottom_right``. It is ``top_right`` is you set it as True. Attributes: source (obj): datasource object for your plot, initialized as a dummy None. x_range (obj): x-associated datarange object for you plot, initialized as a dummy None. y_range (obj): y-associated datarange object for you plot, initialized as a dummy None. groups (list): to be filled with the incoming groups of data. Useful for legend construction. data (dict): to be filled with the incoming data and be passed to the ChartDataSource for each Builder class. attr (list(AttrSpec)): to be filled with the new attributes created after loading the data dict. """ data = None if len(args) != 0 or len(kws) != 0: # chart dimensions can be literal dimensions or attributes attrs = list(self.default_attributes.keys()) dims = self.dimensions + attrs # pop the dimension inputs from kwargs data_args = {} for dim in dims: if dim in kws.keys(): data_args[dim] = kws[dim] # build chart data source from inputs, given the dimension configuration data_args['dims'] = tuple(dims) data_args['required_dims'] = tuple(self.req_dimensions) data_args['attrs'] = attrs data_args['column_assigner'] = self.column_selector data = ChartDataSource.from_data(*args, **data_args) # make sure that the builder dimensions have access to the chart data source for dim in self.dimensions: getattr(getattr(self, dim), 'set_data')(data) # handle input attrs and ensure attrs have access to data attributes = self._setup_attrs(data, kws) # remove inputs handled by dimensions and chart attributes for dim in dims: kws.pop(dim, None) else: attributes = dict() kws['attributes'] = attributes super(Builder, self).__init__(**kws) # collect unique columns used for attributes self.attribute_columns = collect_attribute_columns(**self.attributes) for k in self.__deprecated_attributes__: if k in kws: setattr(self, k, kws[k]) self._data = data self._legends = [] def _setup_attrs(self, data, kws): """Handle overridden attributes and initialize them with data. Makes sure that all attributes have access to the data source, which is used for mapping attributes to groups of data. Returns: None """ source = ColumnDataSource(data.df) attr_names = self.default_attributes.keys() custom_palette = kws.get('palette') attributes = dict() for attr_name in attr_names: attr = kws.pop(attr_name, None) # if given an attribute use it if isinstance(attr, AttrSpec): attributes[attr_name] = attr # if we are given columns, use those elif isinstance(attr, (str, list)): attributes[attr_name] = self.default_attributes[ attr_name]._clone() # override palette if available if isinstance(attributes[attr_name], ColorAttr): if custom_palette is not None: attributes[attr_name].iterable = custom_palette attributes[attr_name].setup(data=source, columns=attr) else: # override palette if available if (isinstance(self.default_attributes[attr_name], ColorAttr) and custom_palette is not None): attributes[attr_name] = self.default_attributes[ attr_name]._clone() attributes[attr_name].iterable = custom_palette else: attributes[attr_name] = self.default_attributes[ attr_name]._clone() # make sure all have access to data source for attr_name in attr_names: attributes[attr_name].update_data(data=source) return attributes def setup(self): """Perform any initial pre-processing, attribute config. Returns: None """ pass def process_data(self): """Make any global data manipulations before grouping. It has to be implemented by any of the inherited class representing each different chart type. It is the place where we make specific calculations for each chart. Returns: None """ pass def yield_renderers(self): """ Generator that yields the glyphs to be draw on the plot It has to be implemented by any of the inherited class representing each different chart type. Yields: :class:`GlyphRenderer` """ raise NotImplementedError( 'Subclasses of %s must implement _yield_renderers.' % self.__class__.__name__) def set_ranges(self): """Calculate and set the x and y ranges. It has to be implemented by any of the subclasses of builder representing each different chart type, and is called after :meth:`yield_renderers`. Returns: None """ raise NotImplementedError( 'Subclasses of %s must implement _set_ranges.' % self.__class__.__name__) def get_dim_extents(self): """Helper method to retrieve maximum extents of all the renderers. Returns: a dict mapping between dimension and value for x_max, y_max, x_min, y_min """ return { 'x_max': max([renderer.x_max for renderer in self.comp_glyphs]), 'y_max': max([renderer.y_max for renderer in self.comp_glyphs]), 'x_min': min([renderer.x_min for renderer in self.comp_glyphs]), 'y_min': min([renderer.y_min for renderer in self.comp_glyphs]) } def add_glyph(self, group, glyph): """Add a composite glyph. Manages the legend, since the builder might not want all attribute types used for the legend. Args: group (:class:`DataGroup`): the data the `glyph` is associated with glyph (:class:`CompositeGlyph`): the glyph associated with the `group` Returns: None """ if isinstance(glyph, list): for sub_glyph in glyph: self.comp_glyphs.append(sub_glyph) else: self.comp_glyphs.append(glyph) # handle cases where builders have specified which attributes to use for labels label = None if len(self.label_attributes) > 0: for attr in self.label_attributes: # this will get the last attribute group label for now if self.attributes[attr].columns is not None: label = self._get_group_label(group, attr=attr) # if no special case for labeling, just use the group label if label is None: label = self._get_group_label(group, attr='label') # add to legend if new and unique label if str(label) not in self.labels and label is not None: self._legends.append((label, glyph.renderers)) self.labels.append(label) def _get_group_label(self, group, attr='label'): """Get the label of the group by the attribute name. Args: group (:attr:`DataGroup`: the group of data attr (str, optional): the attribute name containing the label, defaults to 'label'. Returns: str: the label for the group """ if attr is 'label': label = group.label else: label = group[attr] if isinstance(label, dict): label = tuple(label.values()) return self._get_label(label) @staticmethod def _get_label(raw_label): """Converts a label by string or tuple to a string representation. Args: raw_label (str or tuple(any, any)): a unique identifier for the data group Returns: str: a label that is usable in charts """ # don't convert None type to string so we can test for it later if raw_label is None: return None if (isinstance(raw_label, tuple) or isinstance(raw_label, list)) and \ len(raw_label) == 1: raw_label = raw_label[0] elif isinstance(raw_label, dict): raw_label = label_from_index_dict(raw_label) return str(raw_label) def collect_attr_kwargs(self): if hasattr(super(self.__class__, self), 'default_attributes'): attrs = set(self.default_attributes.keys()) - set( (super(self.__class__, self).default_attributes or {}).keys()) else: attrs = set() return attrs def get_group_kwargs(self, group, attrs): return {attr: group[attr] for attr in attrs} def create(self, chart=None): """Builds the renderers, adding them and other components to the chart. Args: chart (:class:`Chart`, optional): the chart that will contain the glyph renderers that the `Builder` produces. Returns: :class:`Chart` """ # call methods that allow customized setup by subclasses self.setup() self.process_data() # create and add renderers to chart renderers = self.yield_renderers() if chart is None: chart = Chart() chart.add_renderers(self, renderers) # handle ranges after renders, since ranges depend on aggregations # ToDo: should reconsider where this occurs self.set_ranges() chart.add_ranges('x', self.x_range) chart.add_ranges('y', self.y_range) # sort the legend if we are told to self._legends = self._sort_legend(self.legend_sort_field, self.legend_sort_direction, self._legends, self.attributes) # always contribute legends, let Chart sort it out chart.add_legend(self._legends) chart.add_labels('x', self.xlabel) chart.add_labels('y', self.ylabel) chart.add_scales('x', self.xscale) chart.add_scales('y', self.yscale) if self.tooltips is not None: tooltips = build_hover_tooltips(hover_spec=self.tooltips, chart_cols=self.attribute_columns) chart.add_tooltips(tooltips) return chart @classmethod def generate_help(cls): help_str = '' for comp_glyph in cls.comp_glyph_types: help_str += str(comp_glyph.glyph_properties()) return help_str @staticmethod def _sort_legend(legend_sort_field, legend_sort_direction, legends, attributes): """Sort legends sorted by looping though sort_legend items ( see :attr:`Builder.sort_legend` for more details) """ if legend_sort_field: if len(attributes[legend_sort_field].columns) > 0: # TODO(fpliger): attributes should be consistent and not # need any type checking but for # the moment it is not, specially when going # though a process like binning or when data # is built for HeatMap, Scatter, etc... item_order = [ x[0] if isinstance(x, tuple) else x for x in attributes[legend_sort_field].items ] item_order = [ str(x) if not isinstance(x, string_types) else x for x in item_order ] def foo(leg): return item_order.index(leg[0]) reverse = legend_sort_direction == 'descending' return list(sorted(legends, key=foo, reverse=reverse)) return legends @property def sort_legend(self): deprecated((0, 12, 0), 'Chart.sort_legend', 'Chart.legend_sort_field') return [(self.legend_sort_field, self.legend_sort_direction)] @sort_legend.setter def sort_legend(self, value): deprecated((0, 12, 0), 'Chart.sort_legend', 'Chart.legend_sort_field') self.legend_sort_field, direction = value[0] if direction: self.legend_sort_direction = "ascending" else: self.legend_sort_direction = "descending"
class AutocompleteInputCustom(TextInput): __implementation__ = TypeScript(""" import {TextInput, TextInputView} from "models/widgets/text_input" import {empty, display, undisplay, div, Keys} from "core/dom" import * as p from "core/properties" import {clamp} from "core/util/math" export class AutocompleteInputViewCustom extends TextInputView { model: AutocompleteInputCustom protected _open: boolean = false protected _last_value: string = "" protected _hover_index: number = 0 protected menu: HTMLElement render(): void { super.render() this.input_el.classList.add("bk-autocomplete-input") this.input_el.addEventListener("keydown", (event) => this._keydown(event)) this.input_el.addEventListener("keyup", (event) => this._keyup(event)) this.menu = div({class: ["bk-menu", "bk-below"]}) this.menu.addEventListener("click", (event) => this._menu_click(event)) this.menu.addEventListener("mouseover", (event) => this._menu_hover(event)) this.el.appendChild(this.menu) undisplay(this.menu) } change_input(): void { if (this._open && this.menu.children.length > 0) { this.model.value = this.menu.children[this._hover_index].textContent! this.input_el.focus() this._hide_menu() } else { this.model.value = this.input_el.value this.input_el.focus() this._hide_menu() } } protected _update_completions(completions: string[]): void { empty(this.menu) for (const text of completions) { const item = div({}, text) this.menu.appendChild(item) } if (completions.length > 0) this.menu.children[0].classList.add('bk-active') } protected _show_menu(): void { if (!this._open) { this._open = true this._hover_index = 0 this._last_value = this.model.value display(this.menu) const listener = (event: MouseEvent) => { const {target} = event if (target instanceof HTMLElement && !this.el.contains(target)) { document.removeEventListener("click", listener) this._hide_menu() } } document.addEventListener("click", listener) } } protected _hide_menu(): void { if (this._open) { this._open = false undisplay(this.menu) } } protected _menu_click(event: MouseEvent): void { if (event.target != event.currentTarget && event.target instanceof Element) { this.model.value = event.target.textContent! this.input_el.focus() this._hide_menu() } } protected _menu_hover(event: MouseEvent): void { if (event.target != event.currentTarget && event.target instanceof Element) { let i = 0 for (i = 0; i<this.menu.children.length; i++) { if (this.menu.children[i].textContent! == event.target.textContent!) break } this._bump_hover(i) } } protected _bump_hover(new_index: number): void { const n_children = this.menu.children.length if (this._open && n_children > 0) { this.menu.children[this._hover_index].classList.remove('bk-active') this._hover_index = clamp(new_index, 0, n_children-1) this.menu.children[this._hover_index].classList.add('bk-active') } } _keydown(_event: KeyboardEvent): void {} _keyup(event: KeyboardEvent): void { switch (event.keyCode) { case Keys.Enter: { this.change_input() break } case Keys.Esc: { this._hide_menu() break } case Keys.Up: { this._bump_hover(this._hover_index-1) break } case Keys.Down: { this._bump_hover(this._hover_index+1) break } default: { const value = this.input_el.value if (value.length <= 1) { this._hide_menu() return } const completions: string[] = [] for (const text of this.model.completions) { if (text.indexOf(value) != -1) completions.push(text) } this._update_completions(completions) if (completions.length == 0) this._hide_menu() else this._show_menu() } } } } export namespace AutocompleteInputCustom { export type Attrs = p.AttrsOf<Props> export type Props = TextInput.Props & { completions: p.Property<string[]> } } export interface AutocompleteInputCustom extends AutocompleteInputCustom.Attrs {} export class AutocompleteInputCustom extends TextInput { properties: AutocompleteInputCustom.Props constructor(attrs?: Partial<AutocompleteInputCustom.Attrs>) { super(attrs) } static initClass(): void { this.prototype.type = "AutocompleteInputCustom" this.prototype.default_view = AutocompleteInputViewCustom this.define<AutocompleteInputCustom.Props>({ completions: [ p.Array, [] ], }) } } AutocompleteInputCustom.initClass() """) completions = List(String, help="")
def test_str(self) -> None: prop = bcpn.Nullable(List(Int)) assert str(prop) == "Nullable(List(Int))"
class EitherContainerDefault(hp.HasProps): foo = Either(List(Int), Int, default=[10])
def test_valid(self) -> None: prop = bcpn.NonNullable(List(Int)) assert prop.is_valid([]) assert prop.is_valid([1, 2, 3])
class Parent(hp.HasProps): int1 = Int(default=10) ds1 = NumberSpec() lst1 = List(String)
class HistogramGlyph(AggregateGlyph): """Depicts the distribution of values using rectangles created by binning. The histogram represents a distribution, so will likely include other options for displaying it, such as KDE and cumulative density. """ # input properties bin_width = Float() bin_count = Float( help="""Provide a manually specified number of bins to use.""") # derived models bins = Instance(Bins, help="""A stat used to calculate the bins. The bins stat includes attributes about each composite bin.""") bars = List(Instance(BarGlyph), help="""The histogram is comprised of many BarGlyphs that are derived from the values.""") def __init__(self, values, label=None, color=None, bin_count=None, **kwargs): if label is not None: kwargs['label'] = label kwargs['values'] = values kwargs['bin_count'] = bin_count if color is not None: kwargs['color'] = color # remove width, since this is handled automatically kwargs.pop('width', None) super(HistogramGlyph, self).__init__(**kwargs) self.setup() def _set_sources(self): # No need to set sources, since composite glyphs handle this pass def build_source(self): # No need to build source, since composite glyphs handle this return None def build_renderers(self): """Yield a bar glyph for each bin.""" self.bins = Bins(values=self.values, bin_count=self.bin_count) centers = [bin.center for bin in self.bins.bins] self.bin_width = centers[1] - centers[0] bars = [] for bin in self.bins.bins: bars.append( BarGlyph(label=self.label, x_label=bin.center, values=bin.values, color=self.color, fill_alpha=self.fill_alpha, agg=bin.stat, width=self.bin_width)) # provide access to bars as children for bounds properties self.bars = bars self.children = self.bars for comp_glyph in self.bars: for renderer in comp_glyph.renderers: yield renderer @property def y_min(self): return 0.0
class LuminoDock(HTMLBox): children = List(Either(Tuple(String, Instance(LayoutDOM)), Tuple(String, Instance(LayoutDOM), InsertMode), Tuple(String, Instance(LayoutDOM), InsertMode, Int)), default=[])
class Foo(HasProps): x = Int(12) y = String("hello") z = List(Int, [1, 2, 3]) zz = Dict(String, Int) s = String(None)
class CheckboxWithLegendGroup(CheckboxGroup): colors = List(String, help="List of legend colors") __implementation__ = """
def test_List(self, detail) -> None: p = List(Float) with pytest.raises(ValueError) as e: p.validate("junk", detail) assert (str(e.value) == "") == (not detail)
class EmbedTestUtilModel(Model): a = Int(12) b = String("hello") c = List(Int, [1, 2, 3])
class Bar(Model): """ This is a Bar model. """ thing = List(Int, help="doc for thing")
class HookListModel(Model): hooks = List(String)
class Mixin(HasProps): mixin_num = Int(12) mixin_container = List(String) mixin_child = Instance(HasProps)
class HTML(Markup): """ A bokeh model to render HTML markup including embedded script tags. """ events = Dict(String, List(String))
class FooUnrelated(HasProps): x = Int(12) y = String("hello") z = List(Int, [1, 2, 3])
class Bin(Stat): """Represents a single bin of data values and attributes of the bin.""" label = Either(String, List(String)) start = Either(Float, List(Float)) stop = Either(Float, List(Float)) start_label = String() stop_label = String() center = Either(Float, List(Float)) stat = Instance(Stat, default=Count()) width = Float() def __init__(self, bin_label, values=None, source=None, **properties): if isinstance(bin_label, tuple): bin_label = list(bin_label) else: bin_label = [bin_label] properties['label'] = bin_label bounds = self.process_bounds(bin_label) starts, stops = zip(*bounds) centers = [(start + stop) / 2.0 for start, stop in zip(starts, stops)] if len(starts) == 1: starts = starts[0] stops = stops[0] centers = centers[0] else: starts = list(starts) stops = list(stops) centers = list(centers) properties['start'] = starts properties['stop'] = stops properties['center'] = centers properties['values'] = values super(Bin, self).__init__(**properties) @staticmethod def binstr_to_list(bins): """Produce a consistent display of a bin of data.""" value_chunks = bins.split(',') value_chunks = [ val.replace('[', '').replace(']', '').replace('(', '').replace(')', '') for val in value_chunks ] bin_values = [float(value) for value in value_chunks] return bin_values[0], bin_values[1] def process_bounds(self, bin_label): if isinstance(bin_label, list): return [self.binstr_to_list(dim) for dim in bin_label] else: return [self.binstr_to_list(bin_label)] def update(self): self.stat.set_data(self.values) def calculate(self): self.value = self.stat.value