bokeh.util¶
Provide a collection of general utilities useful for implementing Bokeh functionality.
bokeh.util.browser
¶
Utility functions for helping with operations involving browsers.
-
get_browser_controller
(browser=None)[source]¶ Return a browser controller.
- Parameters
browser name, or
None
(default:None
) If passed the string'none'
, a dummy web browser controller is returnedOtherwise, use the value to select an appropriate controller using the
webbrowser
standard library module. In the value isNone
then a system default is used.
Note
If the environment variable
BOKEH_BROWSER
is set, it will take precedence.- Returns
a web browser controller
- Return type
controller
-
view
(location, browser=None, new='same', autoraise=True)[source]¶ Open a browser to view the specified location.
- Parameters
location (str) – Location to open If location does not begin with “http:” it is assumed to be a file path on the local filesystem.
browser (str or None) – what browser to use (default: None) If
None
, use the system default browser.new (str) –
How to open the location. Valid values are:
'same'
- open in the current tab'tab'
- open a new tab in the current window'window'
- open in a new windowautoraise (bool) – Whether to automatically raise the location in a new browser window (default: True)
- Returns
None
bokeh.util.callback_manager
¶
Provides PropertyCallbackManager
and EventCallbackManager
mixin classes for adding on_change
and on_event
callback
interfaces to classes.
-
class
EventCallbackManager
(*args, **kw)[source]¶ A mixin class to provide an interface for registering and triggering event callbacks on the Python side.
-
class
PropertyCallbackManager
(*args, **kw)[source]¶ A mixin class to provide an interface for registering and triggering callbacks.
bokeh.util.compiler
¶
Provide functions and classes to help with various JS and CSS compilation.
-
exception
CompilationError
(error)[source]¶ A
RuntimeError
subclass for reporting JS compilation errors.
-
class
CoffeeScript
(*args, **kw)[source]¶ An implementation for a Bokeh custom model in CoffeeScript.
Example
class MyExt(Model): __implementation__ = CoffeeScript(""" <CoffeeScript code> """)
Note that
CoffeeScript
is the default implementation language for custom model implementations. The following is equivalent to example above:class MyExt(Model): __implementation__ == """ <some coffeescript code> """
-
class
FromFile
(path)[source]¶ A custom model implementation read from a separate source file.
- Parameters
path (str) – The path to the file containing the extension source code
-
class
Inline
(code, file=None)[source]¶ Base class for representing Bokeh custom model implementations that may be given as inline code in some language.
-
class
JavaScript
(code, file=None)[source]¶ An implementation for a Bokeh custom model in JavaScript
Example
class MyExt(Model): __implementation__ = JavaScript(""" <JavaScript code> """)
-
class
TypeScript
(code, file=None)[source]¶ An implementation for a Bokeh custom model in TypeScript
Example
class MyExt(Model): __implementation__ = TypeScript(""" <TypeScript code> """)
-
calc_cache_key
(custom_models)[source]¶ Generate a key to cache a custom extension implementation with.
There is no metadata other than the Model classes, so this is the only base to generate a cache key.
We build the model keys from the list of
model.full_name
. This is not ideal but possibly a better solution can be found found later.
bokeh.util.dependencies
¶
Utilities for checking dependencies
-
import_optional
(mod_name)[source]¶ Attempt to import an optional dependency.
Silently returns None if the requested module is not available.
- Parameters
mod_name (str) – name of the optional module to try to import
- Returns
imported module or None, if import fails
bokeh.util.deprecation
¶
bokeh.util.future
¶
Utilities for Py2/Py3 interop.
-
with_metaclass
(meta, *bases)[source]¶ Add metaclasses in both Python 2 and Python 3.
Function from jinja2/_compat.py. License: BSD.
Use it like this:
class BaseForm(object): pass class FormType(type): pass class Form(with_metaclass(FormType, BaseForm)): pass
This requires a bit of explanation: the basic idea is to make a dummy metaclass for one level of class instantiation that replaces itself with the actual metaclass. Because of internal type checks we also need to make sure that we downgrade the custom metaclass for one level to something closer to type (that’s why __call__ and __init__ comes back from type etc.).
This has the advantage over six.with_metaclass of not introducing dummy classes into the final MRO.
bokeh.util.hex
¶
Functions useful for dealing with hexagonal tilings.
For more information on the concepts employed here, see this informative page
-
axial_to_cartesian
(q, r, size, orientation, aspect_scale=1)[source]¶ Map axial (q,r) coordinates to cartesian (x,y) coordinates of tiles centers.
This function can be useful for positioning other Bokeh glyphs with cartesian coordinates in relation to a hex tiling.
This function was adapted from:
- Parameters
q (array[float]) – A NumPy array of q-coordinates for binning
r (array[float]) – A NumPy array of r-coordinates for binning
size (float) –
The size of the hexagonal tiling.
The size is defined as the distance from the center of a hexagon to the top corner for “pointytop” orientation, or from the center to a side corner for “flattop” orientation.
orientation (str) – Whether the hex tile orientation should be “pointytop” or “flattop”.
aspect_scale (float, optional) –
Scale the hexagons in the “cross” dimension.
For “pointytop” orientations, hexagons are scaled in the horizontal direction. For “flattop”, they are scaled in vertical direction.
When working with a plot with
aspect_scale != 1
, it may be useful to set this value to match the plot.
- Returns
(array[int], array[int])
-
cartesian_to_axial
(x, y, size, orientation, aspect_scale=1)[source]¶ Map Cartesion (x,y) points to axial (q,r) coordinates of enclosing tiles.
This function was adapted from:
- Parameters
x (array[float]) – A NumPy array of x-coordinates to convert
y (array[float]) – A NumPy array of y-coordinates to convert
size (float) –
The size of the hexagonal tiling.
The size is defined as the distance from the center of a hexagon to the top corner for “pointytop” orientation, or from the center to a side corner for “flattop” orientation.
orientation (str) – Whether the hex tile orientation should be “pointytop” or “flattop”.
aspect_scale (float, optional) –
Scale the hexagons in the “cross” dimension.
For “pointytop” orientations, hexagons are scaled in the horizontal direction. For “flattop”, they are scaled in vertical direction.
When working with a plot with
aspect_scale != 1
, it may be useful to set this value to match the plot.
- Returns
(array[int], array[int])
-
hexbin
(x, y, size, orientation='pointytop', aspect_scale=1)[source]¶ Perform an equal-weight binning of data points into hexagonal tiles.
For more sophisticated use cases, e.g. weighted binning or scaling individual tiles proportional to some other quantity, consider using HoloViews.
- Parameters
x (array[float]) – A NumPy array of x-coordinates for binning
y (array[float]) – A NumPy array of y-coordinates for binning
size (float) –
The size of the hexagonal tiling.
The size is defined as the distance from the center of a hexagon to the top corner for “pointytop” orientation, or from the center to a side corner for “flattop” orientation.
orientation (str, optional) – Whether the hex tile orientation should be “pointytop” or “flattop”. (default: “pointytop”)
aspect_scale (float, optional) –
Match a plot’s aspect ratio scaling.
When working with a plot with
aspect_scale != 1
, this parameter can be set to match the plot, in order to draw regular hexagons (instead of “stretched” ones).This is roughly equivalent to binning in “screen space”, and it may be better to use axis-aligned rectangular bins when plot aspect scales are not one.
- Returns
DataFrame
The resulting DataFrame will have columns q and r that specify hexagon tile locations in axial coordinates, and a column counts that provides the count for each tile.
Warning
Hex binning only functions on linear scales, i.e. not on log plots.
bokeh.util.logconfig
¶
Configure the logging system for Bokeh.
By default, logging is not configured, to allow users of Bokeh to have full
control over logging policy. However, it is useful to be able to enable
logging arbitrarily during when developing Bokeh. This can be accomplished
by setting the environment variable BOKEH_PY_LOG_LEVEL
. Valid values are,
in order of increasing severity:
debug
info
warn
error
fatal
none
The default logging level is none
.
bokeh.util.options
¶
Utilities for specifying, validating, and documenting configuration options.
-
class
Options
(kw=None)[source]¶ Leverage the Bokeh properties type system for specifying and validating configuration options.
Subclasses of
Options
specify a set of configuration options using standard Bokeh properties:class ConnectOpts(Options): host = String(default="127.0.0.1", help="a host value") port = Int(default=5590, help="a port value")
Then a
ConnectOpts
can be created by passing a dictionary containing keys and values corresponding to the configuration options, as well as any additional keys and values. The items corresponding to the properties onConnectOpts
will be *removed* from the dictionary. This can be useful for functions that accept their own set of config keyword arguments in addition to some set of Bokeh model properties.
bokeh.util.paths
¶
bokeh.util.serialization
¶
Functions for helping with serialization and deserialization of Bokeh objects.
Certain NumPy array dtypes can be serialized to a binary format for performance and efficiency. The list of supported dtypes is:
np.int32
np.float32
np.int16
np.int8
np.float64
np.uint16
np.uint8
np.uint32
-
array_encoding_disabled
(array)[source]¶ Determine whether an array may be binary encoded.
The NumPy array dtypes that can be encoded are:
np.int32
np.float32
np.int16
np.int8
np.float64
np.uint16
np.uint8
np.uint32
- Parameters
array (np.ndarray) – the array to check
- Returns
bool
-
convert_datetime_array
(array)[source]¶ Convert NumPy datetime arrays to arrays to milliseconds since epoch.
- Parameters
array –
(obj) A NumPy array of datetime to convert
If the value passed in is not a NumPy array, it will be returned as-is.
- Returns
array
-
convert_datetime_type
(obj)[source]¶ Convert any recognized date, time, or datetime value to floating point milliseconds since epoch.
- Arg:
obj (object) : the object to convert
- Returns
milliseconds
- Return type
-
convert_timedelta_type
(obj)[source]¶ Convert any recognized timedelta value to floating point absolute milliseconds.
- Arg:
obj (object) : the object to convert
- Returns
milliseconds
- Return type
-
decode_base64_dict
(data)[source]¶ Decode a base64 encoded array into a NumPy array.
- Parameters
data (dict) – encoded array data to decode
Data should have the format encoded by
encode_base64_dict()
.- Returns
np.ndarray
-
encode_binary_dict
(array, buffers)[source]¶ Send a numpy array as an unencoded binary buffer
The encoded format is a dict with the following structure:
{ '__buffer__' : << an ID to locate the buffer >>, 'shape' : << array shape >>, 'dtype' : << dtype name >>, 'order' : << byte order at origin (little or big)>> }
- Parameters
array (np.ndarray) – an array to encode
buffers (set) –
Set to add buffers to
This is an “out” parameter. The values it contains will be modified in-place.
- Returns
dict
-
encode_base64_dict
(array)[source]¶ Encode a NumPy array using base64:
The encoded format is a dict with the following structure:
{ '__ndarray__' : << base64 encoded array data >>, 'shape' : << array shape >>, 'dtype' : << dtype name >>, }
- Parameters
array (np.ndarray) – an array to encode
- Returns
dict
-
is_datetime_type
(obj)[source]¶ Whether an object is any date, time, or datetime type recognized by Bokeh.
- Arg:
obj (object) : the object to test
- Returns
True if
obj
is a datetime type- Return type
-
is_timedelta_type
(obj)[source]¶ Whether an object is any timedelta type recognized by Bokeh.
- Arg:
obj (object) : the object to test
- Returns
True if
obj
is a timedelta type- Return type
-
make_globally_unique_id
()[source]¶ Return a globally unique UUID.
Some situations, e.g. id’ing dynamically created Divs in HTML documents, always require globally unique IDs.
- Returns
str
-
make_id
()[source]¶ Return a new unique ID for a Bokeh object.
Normally this function will return simple monotonically increasing integer IDs (as strings) for identifying Bokeh objects within a Document. However, if it is desirable to have globally unique for every object, this behavior can be overridden by setting the environment variable
BOKEH_SIMPLE_IDS=no
.- Returns
str
-
serialize_array
(array, force_list=False, buffers=None)[source]¶ Transforms a NumPy array into serialized form.
- Parameters
array (np.ndarray) – the NumPy array to transform
force_list (bool, optional) – whether to only output to standard lists This function can encode some dtypes using a binary encoding, but setting this argument to True will override that and cause only standard Python lists to be emitted. (default: False)
buffers (set, optional) –
If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encoding will be used (default: None)
If force_list is True, then this value will be ignored, and no buffers will be generated.
This is an “out” parameter. The values it contains will be modified in-place.
- Returns
list or dict
-
transform_array
(array, force_list=False, buffers=None)[source]¶ Transform a NumPy arrays into serialized format
Converts un-serializable dtypes and returns JSON serializable format
- Parameters
array (np.ndarray) – a NumPy array to be transformed
force_list (bool, optional) – whether to only output to standard lists This function can encode some dtypes using a binary encoding, but setting this argument to True will override that and cause only standard Python lists to be emitted. (default: False)
buffers (set, optional) –
If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encoding will be used (default: None)
If force_list is True, then this value will be ignored, and no buffers will be generated.
This is an “out” parameter. The values it contains will be modified in-place.
- Returns
JSON
-
transform_array_to_list
(array)[source]¶ Transforms a NumPy array into a list of values
- Parameters
array (np.nadarray) – the NumPy array series to transform
- Returns
list or dict
-
transform_column_source_data
(data, buffers=None, cols=None)[source]¶ Transform
ColumnSourceData
data to a serialized format- Parameters
data (dict) – the mapping of names to data columns to transform
buffers (set, optional) –
If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encoding will be used (default: None)
This is an “out” parameter. The values it contains will be modified in-place.
cols (list[str], optional) – Optional list of subset of columns to transform. If None, all columns will be transformed (default: None)
- Returns
JSON compatible dict
-
traverse_data
(obj, use_numpy=True, buffers=None)[source]¶ Recursively traverse an object until a flat list is found.
If NumPy is available, the flat list is converted to a numpy array and passed to transform_array() to handle
nan
,inf
, and-inf
.Otherwise, iterate through all items, converting non-JSON items
-
transform_series
(series, force_list=False, buffers=None)[source]¶ Transforms a Pandas series into serialized form
- Parameters
series (pd.Series) – the Pandas series to transform
force_list (bool, optional) – whether to only output to standard lists This function can encode some dtypes using a binary encoding, but setting this argument to True will override that and cause only standard Python lists to be emitted. (default: False)
buffers (set, optional) –
If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encoding will be used (default: None)
If force_list is True, then this value will be ignored, and no buffers will be generated.
This is an “out” parameter. The values it contains will be modified in-place.
- Returns
list or dict
bokeh.util.session_id
¶
Utilities for generating and manipulating session IDs.
A session ID would typically be associated with each browser tab viewing an application or plot. Each session has its own state separate from any other sessions hosted by the server.
-
check_session_id_signature
(session_id, secret_key=None, signed=False)[source]¶ Check the signature of a session ID, returning True if it’s valid.
The server uses this function to check whether a session ID was generated with the correct secret key. If signed sessions are disabled, this function always returns True.
-
generate_secret_key
()[source]¶ Generate a new securely-generated secret key appropriate for SHA-256 HMAC signatures. This key could be used to sign Bokeh server session IDs for example.
-
generate_session_id
(secret_key=None, signed=False)[source]¶ Generate a random session ID.
Typically, each browser tab connected to a Bokeh application has its own session ID. In production deployments of a Bokeh app, session IDs should be random and unguessable - otherwise users of the app could interfere with one another.
If session IDs are signed with a secret key, the server can verify that the generator of the session ID was “authorized” (the generator had to know the secret key). This can be used to have a separate process, such as another web application, which generates new sessions on a Bokeh server. This other process may require users to log in before redirecting them to the Bokeh server with a valid session ID, for example.
bokeh.util.string
¶
Functions useful for string manipulations or encoding.
-
decode_utf8
(u)[source]¶ Decode a sequence of bytes to a UTF-8 string
- Parameters
u (str) – the bytes to decode
- Returns
UTF-8 string
-
encode_utf8
(u)[source]¶ Encode a UTF-8 string to a sequence of bytes.
- Parameters
u (str) – the string to encode
- Returns
bytes
-
escape
(s, quote=("'", '"'))[source]¶ Perform HTML-safe escaping.
Replaces special characters “&”, “<” and “>” to HTML-safe sequences, and optionally translates quote characters.
-
format_docstring
(docstring, *args, **kwargs)[source]¶ Safely format docstrings.
When Python is executed with the
-OO
option, doc strings are removed and replaced the valueNone
. This function guards against applying the string formatting options in that case.
-
indent
(text, n=2, ch=' ')[source]¶ Indent all the lines in a given block of text by a specified amount.
bokeh.util.tornado
¶
Internal utils related to Tornado
bokeh.util.terminal
¶
Provide utilities for formatting terminal output.
bokeh.util.version
¶
Provide a version for the Bokeh library.
This module uses versioneer to manage version strings. During development, versioneer will compute a version string from the current git revision. For packaged releases based off tags, the version string is hard coded in the files packaged for distribution.
-
__version__
¶ The full version string for this installed Bokeh library
- Functions:
- base_version:
Return the base version string, without any “dev”, “rc” or local build information appended.
bokeh.util.warnings
¶
Provide Bokeh-specific warning subclasses.
The primary use of these subclasses to to force them to be unconditionally displayed to users by default.