Module contents

Contents

Module contents#

trelliscope#

Trelliscope main module.

This module contains the core Trelliscope object that enables the creation and configuration of Trelliscope apps.

class trelliscope.trelliscope.Trelliscope(data_frame, name, description=None, key_cols=None, tags=None, path=None, force_plot=False, primary_panel=None, pretty_meta_data=False, keysig=None, server=None, javascript_version=None, show_progress_bar=True)[source]#

Bases: object

Main Trelliscope class..

__init__(data_frame, name, description=None, key_cols=None, tags=None, path=None, force_plot=False, primary_panel=None, pretty_meta_data=False, keysig=None, server=None, javascript_version=None, show_progress_bar=True)[source]#

Instantiate a Trelliscope display object.

Parameters:
  • data_frame (DataFrame) – A data frame that contains the metadata of the display as well as a column that indicates the panels to be displayed.

  • name (str) – Name of the trelliscope display.

  • description (str) – Description of the trelliscope display. If none is provided, the name will be used as the description.

  • key_cols (list[str]) – Variable names in the data frame that uniquely define a row of the data. If not supplied, an attempt will be made to infer them.

  • tags (list[str]) – Optional vector of tag names to identify the display in the case that there are many to search through.

  • path (str) – Directory in which to place the trelliscope display when it is written using [write_display()].

  • force_plot (bool) – Should the panels be forced to be plotted, even if they have already been plotted and have not changed since the previous plotting?

  • javascript_version (str) – If a specific version of the Trelliscope JavaScript from the CDN is desired it can be specified here. If the default value of None is provided, the JavaScript version compatible with this version of the Python Package will be used.

  • show_progress_bar (bool) – Flag to show progress bar when creating Trelliscope app files.

add_panel(panel)[source]#

Adds the panel to the Trelliscope object.

Return type:

Trelliscope

Returns:

Returns a copy of this object with the meta added. The original object is not modified.

set_meta(meta)[source]#

Adds the provided meta to the stored dictionary with a key of the meta’s varname.

If this key was already present it will be replaced.

Parameters:

meta (Meta) – The Meta object to add.

Return type:

Trelliscope

Returns:

Returns a copy of this object with the meta added. The original object is not modified.

set_metas(meta_list)[source]#

Helper method to add a list of metas at once.

Parameters:

meta_list (list) – list(Meta) - The list of meta objects to add.

Return type:

Trelliscope

Returns:

Returns a copy of this object with the meta added. The original object is not modified.

set_state(state)[source]#

Sets the state to the provided one.

Parameters:

state (DisplayState) – DisplayState - The new state to add.

Return type:

Trelliscope

Returns:

Returns a copy of this object with the meta added. The original object is not modified.

add_view(view)[source]#

Adds the provided view to the stored dictionary.

The key will be the view’s name, and it will replace a view of that name if it already existed.

Parameters:

view (View) – The view to add.

Return type:

Trelliscope

Returns:

A copy of this object with the view added. The original object is not modified.

add_input(input)[source]#

Adds the provided input to the stored dictionary.

The key will be the input’s name, and it will replace an input of that name if it already existed.

Parameters:

input (Input) – The input to add.

Return type:

Trelliscope

Returns:

Returns a copy of this object with the meta added. The original object is not modified.

add_inputs(inputs)[source]#

Convenience method to add muliple inputs.

Returns a copy of the Trelliscope object. The original is not modified.

get_output_path()[source]#

Returns the output path where the Trelliscope is saved.

Return type:

str

get_displays_path()[source]#

Returns the path of the displays directory.

The output path is a child of the main output path.

Return type:

str

get_dataset_display_path()[source]#

Returns the path of the display directory.

The path is a child of the main displays directory.

Return type:

str

to_dict()[source]#

Returns a dictionary representation of this Trelliscope object.

Return type:

dict

to_json(pretty=True)[source]#

Returns a json string of the information stored in this object.

Parameters:

pretty (bool) – bool - Should the json be pretty printed / indented?

Return type:

str

write_display(force_write=False, jsonp=True)[source]#

Write the contents of this display.

In the process, all necessary Trelliscope parameters will be inferred if they are not present.

Parameters:
  • force_write (bool) – Should the panels be forced to be written even if they have already been written?

  • jsonp (bool) – If true, app files are written as “jsonp” format, otherwise “json” format. The “jsonp” format makes it possible to browse a trelliscope app without the need for a web server.

Returns:

Returns a copy of this object with the meta added. The original object is not modified.

infer()[source]#

Infer Metas, State and Views of Trelliscope object.

Infer a trelliscope.metas.Meta object for each variable in the Trelliscope data.

Using _infer_metas().

Infer a State using _infer_state(), including Layout, Label and Filter states if they are not already specified.

Finally, for each defined View the State is inferred separately.

Return type:

Trelliscope

Returns:

Returns a copy of this object with the meta added. The original object is not modified.

infer_panels()[source]#

If no panels are already present, this method will look through each column to infer panel columns.

If it finds columns that can be inferred, it will create the appropriate panel class and add it to the Trelliscope object.

Return type:

Trelliscope

Returns:

Returns a copy of this object with the meta added. The original object is not modified.

write_or_copy_panels(panel_col)[source]#

Writes the panels to the output directory, or copies them if they are already files.

If the panel_col of the Trelliscope dataframe contains Figures or HTML widgets, then they are written to output files. If they reference local files, then they are copied instead.

Parameters:

panel_col (str) – Column name containing panel data.

Return type:

Trelliscope

Returns:

Returns a copy of this object with the meta added. The original object is not modified.

set_default_labels(varnames)[source]#

Add a labels state specification to a trelliscope display.

Parameters:

varnames (list) – list(str) - The varnames for the labels.

Return type:

Trelliscope

Returns:

Returns a copy of this object with the meta added. The original object is not modified.

set_default_layout(ncol=1, page=1)[source]#

Add a layout state specification to a trelliscope display.

Parameters:
  • ncol (int) – The number of columns displayed on a single page.

  • page (int) – The initial page to display.

Return type:

Trelliscope

Returns:

Returns a copy of this object with the meta added. The original object is not modified.

set_default_sort(varnames, sort_directions=None, add=False)[source]#

Adds a SortState to the Trelliscope.

Parameters:
  • varnames (list[str]) – A list of variable names to sort on.

  • sort_directions (list[Literal['asc', 'desc']]) – A list of “asc” and “desc” for each variable to sort on. If None, then ascending sort will be used for all variables. If a single direction is passed in the list, it will be used for all varnames.

  • add (bool) – Should an existing sort specification be added to? (If False (default), the entire sort specification will be overridden).

Return type:

Trelliscope

Returns:

Returns a copy of the Trelliscope object. The original is not modified.

set_default_filters(filters=None, add=True)[source]#

Add a filter state specifications to a trelliscope display.

Parameters:
  • filters (list[FilterState]) – A list of FilterState specifications

  • add (bool) – Should existing filter state specifications be added to? If False, the entire filter state specification will be overridden.

Return type:

Trelliscope

Returns:

Returns a copy of this object with the meta added. The original object is not modified.

set_primary_panel(panel_column_name)[source]#

Sets the primary panel.

Note that a panel with this name should already be defined as a panel.

Parameters:

panel_column_name (str) – The name of the panel column.

Return type:

Trelliscope

Returns:

Returns a copy of this object with the meta added. The original object is not modified.

set_panel_options(panel_options_dictionary)[source]#

Set information about the Panel objects before they are actually created.

Then, later when the Panel object is inferred, data from this object will be used to populate it.

If panel objects already exist for the associated panels, a warning will be generated.

Parameters:

panel_options_dictionary (dict[str, PanelOptions]) – This should be a dictionary mapping the name of the panel to a PanelOptions object.

Return type:

Trelliscope

Returns:

Returns a copy of this object with the meta added. The original object is not modified.

view_trelliscope()[source]#

Attempts to open the current Trelliscope in a browser.

Note: The Trelliscope should be written first using write_display()

Return type:

None

facets#

Create dataframes with figure facets from dataframes containing input data.

Each facet is a figure belonging to a group of data.

trelliscope.facets.facet_panels(df, panel_column_name, facet_columns, plot_function, params)[source]#

Create figure facets from a dataframe by applying a plot function.

Parameters:
  • df (DataFrame) – Dataframe input containing data for plotting and grouping.

  • panel_column_name (str) – The names of the output column containing the figure objects.

  • facet_columns (list) – Columns to group data by, creating a figure for each group.

  • plot_function (Callable[[DataFrame, ...], Figure]) – Plotting function to apply to each group, taking a pd.DataFrame as the first argument.

  • params (dict[str, Any]) – Additional keyword argument passed to the plot_function.

Return type:

DataFrame

Returns:

A dataframe with 1 column with the name of panel_column_name containing figure objects, The dataframe will have a multi-level index, with the level names given by facet_columns.

Examples

from trelliscope.facets import facet_panels

import plotly.graph_objs as go
import pandas as pd

df = pd.DataFrame(
    [
        ("Belgium","Europe",1977,9821800),
        ("Belgium","Europe",1982,9856303),
        ("Belgium","Europe",1987,9870200),
        ("Belgium","Europe",1992,10045622),
        ("Belgium","Europe",1997,10199787),
        ("Belgium","Europe",2002,10311970),
        ("Belgium","Europe",2007,10392226),
        ("Singapore","Asia",1977,2325300),
        ("Singapore","Asia",1982,2651869),
        ("Singapore","Asia",1987,2794552),
        ("Singapore","Asia",1992,3235865),
        ("Singapore","Asia",1997,3802309),
        ("Singapore","Asia",2002,4197776)
    ],
    columns=["Country", "Continent", "Year", "Population"]
)

def plot_population(df: pd.DataFrame, **kwargs) -> go.Figure:
    return go.Figure(go.Scatter(x=df["Year"], y=df["Population"]))

df_facets = facet_panels(
    df=df,
    panel_column_name="panel",
    facet_columns=["Country", "Continent"],
    plot_function=plot_population,
    params={"layout": {"title": "Population over time"}}
)

panels#

Panels module.

class trelliscope.panels.PanelOptions(width=600, height=400, format=None, force=False, prerender=True, type=None, aspect=None)[source]#

Bases: object

Stores settings associated with panel.

The PanelOptions object is used by the trelliscope.trelliscope.Trelliscope.set_panel_options() method to pre-specify information about the Panel before it is actually created. Then, later when the Panel object is inferred, data from this object will be used to populate it.

__init__(width=600, height=400, format=None, force=False, prerender=True, type=None, aspect=None)[source]#

Create PanelOptions objects.

Parameters:
  • width (int) – Strictly positive integer representing the panel width in pixels.

  • height (int) – Stricly positive integer representing the panel height in pixels.

  • format (str) – One of ‘png’, ‘svg’ or ‘html’. If None then is inferred.

  • force (bool) – (Default False) Whether to force creation of plots, even if they already exist.

  • prerender (bool) – (Default True) Prerender.

  • type (str) – Type of panel. TODO: list possible types.

  • aspect (float) – Aspect ratio of the panel, if not given it is determined from width / height.

Raises:

ValueError – If width or height is not a positive numeric value. Or, if force or prerender is not a boolean. Or, if format not an allowed value.

class trelliscope.panels.Panel(varname, panel_type_str, source, aspect_ratio=1.5, is_image=True, writeable=False)[source]#

Bases: object

Base Panel object.

__init__(varname, panel_type_str, source, aspect_ratio=1.5, is_image=True, writeable=False)[source]#

Create Panel object.

Parameters:
  • varname (str) – Variable name.

  • panel_type_str (str) – Panel type, one of [‘img’, ‘iframe’].

  • source (PanelSource) – PanelSource object, defining where the load the panel content from.

  • aspect_ratio (float) – Aspect ratio of the displayed panel.

  • is_image (bool) – Boolean flag whether panel is an image.

  • writeable (bool) – Boolean flag whether panel is writable.

to_dict()[source]#

Return a dictionary of this Panel’s attributes..

get_extension()[source]#

Get the extension of this Panel.

Raises:

NotImplementedError – if not overwritten in subclasses.

Return type:

str

check_valid(df)[source]#

Check that the dataframe contains the panel variable as a column.

static create_panel(df, panel_column, panel_options=None, is_known_figure_col=False, is_known_image_col=False)[source]#

A factory method to create a new panel object by inferring the type of the panel.

This method infers the type and other parameters based on the data found in the panel_col column in the data frame.

Params:

df: The pandas DataFrame to create the panel from. panel_column: The name of the panel column. panel_options: Optionally pass explicit panel options, otherwise defaults are used. is_known_figure_col: Boolean flag to use if type of panel is a figure, inferred if False. is_known_image_col: Boolean flag to use if type of panel is an image, inferred if False.

Returns:

Either a trelliscope.panels.FigurePanel or a trelliscope.panels.ImagePanel.

Raises:
  • NotImplementedError – If panel options are passed but panel_options.prerender=False.

  • ValueError – If is_known_image_col and is_known_image_col are False and panel type cannot be inferred otherwise.

class trelliscope.panels.ImagePanel(varname, source, aspect_ratio=1.5, should_copy_to_output=True)[source]#

Bases: Panel

Panel for displaying images directly.

__init__(varname, source, aspect_ratio=1.5, should_copy_to_output=True)[source]#

Create Panel object to display image.

Parameters:
  • varname (str) – Variable name.

  • source (PanelSource) – Panel source object to define where image comes from.

  • aspect_ratio (float) – Aspect ratio to display.

  • should_copy_to_output (bool) – Boolean whether image files should be copied to output directory.

class trelliscope.panels.IFramePanel(varname, source, aspect_ratio=1.5)[source]#

Bases: Panel

Create Panel object to embed iframes.

__init__(varname, source, aspect_ratio=1.5)[source]#

Create Panel object to embed iframes.

Parameters:
  • varname (str) – Variable name.

  • source (PanelSource) – Panel source object to define where html source to iframe comes from.

  • aspect_ratio (float) – Aspect ratio to display.

class trelliscope.panels.FigurePanel(varname, source, extension='png', aspect_ratio=1.5)[source]#

Bases: Panel

Create Panel object from plotly Figures directly.

Effectively creates an Image panel by saving the Figure to a static file.

__init__(varname, source, extension='png', aspect_ratio=1.5)[source]#

Create Panel object to display png image from a plotly Figure.

Parameters:
  • varname (str) – Variable name.

  • source (PanelSource) – Panel source to define where figure file is loaded from.

  • extension (str) – Extension of figure file, defaults to ‘png’.

  • aspect_ratio (float) – Aspect ratio to display.

get_extension()[source]#

Get expected extension of the figure file.

Return type:

str

state#

State definitions for Trelliscope.

The State of a Trelliscope includes a Layout, the Labels displayed underneath panels, Sorting options and applied Filters. The State controls the initial state the Trelliscope display opens in.

class trelliscope.state.State(type)[source]#

Bases: object

Base class for the various state classes.

__init__(type)[source]#

Create a new State for a given type.

Parameters:

type (str) – Type of the State, one of [‘layout’, ‘labels’, ‘sort’, ‘filter’].

to_dict()[source]#

Returns a dictionary that can be serialized to json.

Return type:

dict

to_json(pretty=True)[source]#

Returns a json version of this object that can be saved to output.

check_with_data(df)[source]#

Ensure that the state is consistent with this dataset.

This function should be overridden by subclasses to do any state specific checks that need to be done.

class trelliscope.state.LayoutState(ncol=1, page=1)[source]#

Bases: State

State definition for Layout of trelliscope display.

__init__(ncol=1, page=1)[source]#

Create Layout state.

Parameters:
  • ncol (int) – Number of columns in a single page to show.

  • page (int) – Initial page number to open on.

check_with_data(df)[source]#

Check if layout data is valid given the data.

Parameters:

df (DataFrame) – Dataframe to check for this layout.

Return type:

bool

Returns:

Boolean indicating if data is valid. Currently, always True.

class trelliscope.state.LabelState(varnames=[])[source]#

Bases: State

State of shown panel labels.

__init__(varnames=[])[source]#

Create Label state.

Parameters:

varnames (list) – List of variables to display as labels.

check_with_data(df)[source]#

Check if varnames are all columns of the provided data.

Parameters:

df (DataFrame) – Dataframe that should contain columns matching varnames.

Return type:

bool

Returns:

True if all varnames are columns in the dataframe.

Raises:

ValueError – if any of the varnames are not a column in the dataframe.

class trelliscope.state.SortState(varname, dir='asc', meta_type=None)[source]#

Bases: State

State of panel sorting.

__init__(varname, dir='asc', meta_type=None)[source]#

Create Sort state.

Parameters:
  • varname (str) – str - The variable name

  • dir (Literal['asc', 'desc']) – str (“asc” or “desc”) - The direction of the sort

  • varname – The variable name to sort by.

  • dir – The direction to sort, one of [‘asc’, ‘desc’].

  • meta_type (str) – Optional meta type. (TODO: Should this be a Meta type or indeed a string?).

check_with_data(df)[source]#

Check if varname exists as a column in the dataframe. Raise an error otherwise.

Return type:

bool

check_with_meta(meta)[source]#

Check if the passed Meta is sortable.

class trelliscope.state.FilterState(varname, filtertype, applies_to=None, meta_type=None)[source]#

Bases: State

State of filters applied to panels and their attributes.

__init__(varname, filtertype, applies_to=None, meta_type=None)[source]#

Create Filter state.

Parameters:
  • varname (str) – Variable name to filter.

  • filtertype (Literal['category', 'numberrange', 'daterange', 'datetimerange']) – Type of filter, one of .

  • applies_to (list[Meta]) – List of Meta types this filter state applies to.

  • meta_type (str) – Meta type. (TODO: explain.)

check_with_data(df)[source]#

Check if varname is a column in the dataframe.

Parameters:

df (DataFrame) – Data that should contain the column matching varname.

Raises:

ValueError – If dataframe does not contain the expected varname column.

Return type:

bool

check_with_meta(meta)[source]#

Check if the provided Meta is valid for this filter state.

Parameters:

meta (Meta) – The Meta object to check.

Raises:

ValueError – If the provided Meta is not in the list of metas in applies_to.

Return type:

bool

class trelliscope.state.CategoryFilterState(varname, regexp=None, values=None)[source]#

Bases: FilterState

State for filtering category/factor data types.

__init__(varname, regexp=None, values=None)[source]#

Create filter state for a category/factor variable.

Parameters:
  • varname (str) – The variable this filter applies to.

  • regexp (str) – Regular expression to apply

  • values (str | list[str]) – Either a string for the value or a list of possible values

check_with_data(df)[source]#

Check if the filter is valid for the provided dataframe.

Parameters:

df (DataFrame) – The dataframe to check.

Raises:

ValueError – if any of the filter values are not in the dataframe column matching varname.

class trelliscope.state.RangeFilterState(varname, filtertype, applies_to, min=None, max=None)[source]#

Bases: FilterState

Base filter state for a range filter.

__init__(varname, filtertype, applies_to, min=None, max=None)[source]#

Create base filter state that filters on a variable in a min/max range.

This base class init function should likely only be called by subclass init functions.

Parameters:
  • varname (str) – The variable name

  • filtertype (str) – The filter type

  • applies_to (list) – List of meta types. None indicates this applies to all meta definitions.

  • min (int | datetime) – The minimum value for the range

  • max (int | datetime) – The maximum value for the range

class trelliscope.state.NumberRangeFilterState(varname, min=None, max=None)[source]#

Bases: RangeFilterState

Range filter state for numeric variable.

__init__(varname, min=None, max=None)[source]#

Create filter state for a range filter applied to a numeric variable.

Parameters:
  • varname (str) – The variable name to apply filter to.

  • min (int) – Minimum value for the range.

  • max (int) – Maximum value for the range.

class trelliscope.state.DateRangeFilterState(varname, min=None, max=None)[source]#

Bases: RangeFilterState

Range filter state for date-type variables.

__init__(varname, min=None, max=None)[source]#

Create a range filter state applies to a date-type variable.

Parameters:
  • varname (str) – The variable name to apply filter to,

  • min (date) – Minimum date.

  • max (date) – Maximum date.

class trelliscope.state.DatetimeRangeFilterState(varname, min=None, max=None)[source]#

Bases: RangeFilterState

Range filter state for datetime-type variables.

__init__(varname, min=None, max=None)[source]#

Create a range filter state applies to a datetime-type variable.

Parameters:
  • varname (str) – The variable name to apply filter to,

  • min (datetime) – Minimum datetime.

  • max (datetime) – Maximum datetime.

class trelliscope.state.DisplayState[source]#

Bases: object

Contains the collection of all states necessary to define a display.

__init__()[source]#

Create default display state.

Display state is further customized using the set() method.

set(state, add=False)[source]#

Sets the provided state, either overwriting or adding to the current state.

Updates the object in-place and does not return a value.

Parameters:
  • state (State) – New state to set.

  • add (bool) – Whether to add the provided State, or to overwrite the State if a State of the same type already exists.

Return type:

None

to_dict()[source]#

Returns a dictionary that can be serialized to json.

Return type:

dict

to_json(pretty=True)[source]#

Returns a json version of this object that can be saved to output.

Return type:

str

metas#

Meta objects that configure the types of Trelliscope variables.

A Meta contains configuration for a single variable in Trelliscope, which can be a number, datetime, graph, or one of many other types.

class trelliscope.metas.Meta(type, varname, filterable, sortable, label=None, tags=None)[source]#

Bases: object

The base class for all Meta variants.

The Meta objects describe each variable in the Trelliscope widget and controls their filtering, sorting, tags, rounding, etc.

__init__(type, varname, filterable, sortable, label=None, tags=None)[source]#

Create the Meta object.

Parameters:
  • type (str) – Type of the variable, should match one of the class TYPE_* attributes.

  • varname (str) – Name of variable

  • filterable (bool) – Boolean whether variable can be filtered by.

  • sortable (bool) – Boolean whether variable can be sorted by.

  • label (str) – Label of the variable being displayed.

  • tags (list) – List of string tags used for categorizing the variable.

to_dict()[source]#

Gets a dictionary containing the attributes of the meta.

This could be used directly, but if JSON is desired, consider using the to_json method instead, which calls this one internally.

Return type:

dict[str, Any]

Returns:

A dictionary of this class properties.

to_json(pretty=True)[source]#

Gets a JSON string containing all the attributes of a meta.

This is used when serializing.

Parameters:

pretty (bool) – Boolean whether to dump JSON with indent=2.

Return type:

str

Returns:

JSON representation of this object.

check_varname(df)[source]#

Check that the variable column exists.

Raises:

ValueError – If the varname is not found.

Return type:

None

check_variable(df)[source]#

Overridden in subclasses to contain more specific checks.

If the check fails, this should raise an error.

Return type:

None

Params:

df: The dataframe to check.

Raises:

ValueError – If the check fails.

check_with_data(df)[source]#

Runs checks of this meta on the dataframe.

Calls methods to check that the variable exists in the dataframe and any additional checks for specific subclasses. If these checks fail, this will raise an error.

Return type:

None

Params:

df: The dataframe to check.

Raises:

ValueError – If any of the checks fail.

class trelliscope.metas.NumberMeta(varname, label=None, tags=None, digits=None, locale=True)[source]#

Bases: Meta

A Meta for numeric data.

A Number Meta is always filterable and sortable.

__init__(varname, label=None, tags=None, digits=None, locale=True)[source]#

Create Meta for numeric data.

Parameters:
  • varname (str) – Name of variable.

  • label (str) – Label of the variable being displayed.

  • tags (list) – List of string tags used for categorizing the variable.

  • digits (int) – Number of digits to display in the variable.

  • locale (bool) – Boolean choice whether to use locale for digits (TODO: describe this.)

Raises:

ValueError – If digits is not an integer scalar. Or, if locale is given but digits is not.

check_variable(df)[source]#

Check that the variable column is a numeric type.

Raises:

ValueError – if self.varname column in the data frame is not numeric.

class trelliscope.metas.CurrencyMeta(varname, label=None, tags=None, code='USD')[source]#

Bases: Meta

A Meta for currency data.

__init__(varname, label=None, tags=None, code='USD')[source]#

Create Meta for currencies.

Parameters:
  • varname – Name of the variable.

  • label (str) – Displayed label of the variable.

  • tags (list[str]) – list of string tags.

  • code (str) – Currency code, default ‘USD’.

check_variable(df)[source]#

Check that the variable column is a numeric type.

Raises:

ValueError – if self.varname column in the data frame is not numeric.

class trelliscope.metas.StringMeta(varname, label=None, tags=None)[source]#

Bases: Meta

A Meta for string data.

__init__(varname, label=None, tags=None)[source]#

Create a Meta for string data.

Parameters:
  • varname (str) – Name of the variable.

  • label (str) – Displayed label for the variable.

  • tags (list[str]) – List of string tags.

check_variable(df)[source]#

Check that variable column is a vector of atomic types.

Verifies that the column in the data frame is an atomic vector (not a nested type). It does not have to be a string, rather anything that can easily be coerced to it.

Raises:

ValueError – if varname column in data frame is not an atomic vector.

cast_variable(df)[source]#

Converts the variable column in the data frame to be a string type.

Return type:

DataFrame

Returns:

The updated Pandas DataFrame

class trelliscope.metas.PanelMeta(panel, label=None, tags=None)[source]#

Bases: Meta

A Meta for Panels.

__init__(panel, label=None, tags=None)[source]#

Create Meta for Panel objects.

Parameters:
  • panel (Panel) – Panel value.

  • label (str) – Label to display for the panel.

  • tags (list[str]) – List of string tags.

Raises:

ValueError – if Panel is invalid.

to_dict()[source]#

Returns a dictionary representation.

Different than parent class method since there are additional panel properties renamed in the output. The output dictionary contains the keys as expected by the Trelliscope JavaScript.

The output includes aspect, source and paneltype. The output excludes panel_source and panel_type.

Return type:

dict

Returns:

Dictionary representation as expected by the trelliscope javascript.

check_variable(df)[source]#

Checks that the variable is an appropriate type for panels.

class trelliscope.metas.FactorMeta(varname, label=None, tags=None, levels=None)[source]#

Bases: Meta

A meta for a categorical, factor variable.

__init__(varname, label=None, tags=None, levels=None)[source]#

Create Meta for categorical factor types.

Parameters:
  • varname (str) – Name of the variable.

  • label (str) – Displayed label of the variable.

  • tags (list) – List of string tags.

  • levels (list) – Factor levels, inferred if not given.

infer_levels(df)[source]#

Infers the factor levels from the dataframe.

If the column is a category, the category levels will be used directly. If the column is not, it will be cast as a category to pull the levels.

Parameters:

df (DataFrame) – Dataframe to infer factor levels from.

Returns:

None. Changes this Meta object in-place.

check_variable(df)[source]#

Infers the levels for this factor and verifies that the dataframe matches.

cast_variable(df)[source]#

Converts the self.varname column in the data frame a categorical type.

This will change the original data frame.

Parameters:

df (DataFrame) – Dataframe that contains the variable to be converted.

Return type:

DataFrame

Returns:

Updated dataframe with varname column as categorical.

Raises:

NotImplementedError – Work in progress.

class trelliscope.metas.DateMeta(varname, label=None, tags=None)[source]#

Bases: Meta

Meta for date types.

__init__(varname, label=None, tags=None)[source]#

Create Meta object for date types.

Parameters:
  • varname (str) – Name of the variable.

  • label (str) – Displayed label of the variable.

  • tags (list[str]) – List of string tags.

check_variable(df)[source]#

Check that variable column is a datetime type.

class trelliscope.metas.DatetimeMeta(varname, label=None, tags=None, timezone='UTC')[source]#

Bases: Meta

Meta for datetime types.

__init__(varname, label=None, tags=None, timezone='UTC')[source]#

Create Meta object for a datetime variable.

Parameters:
  • varname (str) – Name of the variable.

  • label (str) – Displayed label of the variable.

  • tags (list[str]) – List of string tags.

  • timezone (str) – Timezone of the datetime values, defaults to “UTC”..

check_variable(df)[source]#

Check that variable column is a datetime type.

cast_variable(df)[source]#

Converts the self.varname column in the data frame to be a DateTime type.

This will change the original data frame.

Return type:

DataFrame

Returns:

The updated Pandas DataFrame

class trelliscope.metas.GraphMeta(varname, label=None, tags=None, idvarname=None, direction='none')[source]#

Bases: Meta

Meta for Graph types.

__init__(varname, label=None, tags=None, idvarname=None, direction='none')[source]#

Create Meta object for Graph variable.

Parameters:
  • varname (str) – Name of the variable.

  • label (str) – Displayed label of the variable.

  • tags (list[str]) – List of string tags.

  • idvarname (str) – TODO: Add description

  • direction (str) – One of [“none”, “to”, “from”]. # TODO: add description

check_variable(df)[source]#

Check that the variable column is a Graph type.

Raises:

NotImplementedError – Check is not yet implemented.

class trelliscope.metas.GeoMeta(varname, latvar, longvar, label=None, tags=None)[source]#

Bases: Meta

Meta for Geo types.

__init__(varname, latvar, longvar, label=None, tags=None)[source]#

Create Meta object for Geo variable type.

Parameters:
  • varname (str) – Name of the variable.

  • latvar (str) – Name of the Latitude variable.

  • longvar (str) – Name of the Longitude variable.

  • label (str) – Displayed label of the variable.

  • tags (list[str]) – List of string tags.

check_varname(df)[source]#

Check that dataframe has latitude and longitude variable columns.

check_variable(df)[source]#

Check data types of the latitude and longitude variables in the dataframe.

to_dict()[source]#

Dictionary representation of the object, excluding latvar and longvar.

Return type:

dict

class trelliscope.metas.HrefMeta(varname, label=None, tags=None)[source]#

Bases: Meta

Meta for Href variables.

__init__(varname, label=None, tags=None)[source]#

Create Meta object for Href variable.

Parameters:
  • varname (str) – Name of the variable.

  • label (str) – Displayed label of the variable.

  • tags (list) – List of string tags.

check_variable(df)[source]#

Check variable column is a string type.

view#

Objects that define the View of a Trelliscope display.

A specified View for Trelliscope contains a pre-defined State, including layouts, labels, sorting and filter states.

class trelliscope.view.View(name, layout_state=None, label_state=None, sort_state=None, sort_states=[], filter_state=None, filter_states=[])[source]#

Bases: object

Pre-defined View for Trelliscope display.

A Trelliscope can have multiple Views, which are selectable in the app.

__init__(name, layout_state=None, label_state=None, sort_state=None, sort_states=[], filter_state=None, filter_states=[])[source]#

Create a pre-defined View state for Trelliscope display.

Parameters:
  • name (str) – Name of the view, used for selecting the View from a dropdown menu in the app.

  • layout_state (LayoutState) – Layout in this View.

  • label_state (LabelState) – Labels displayed in this View.

  • sort_state (SortState) – Sorting state in this View.

  • sort_states (list) – List of sorting states in this View

  • filter_state (FilterState) – Filter state in this View.

  • filter_states (list) – List of filter states in this View.

to_dict()[source]#

Create dictioanry of attributes of a View expected by Trelliscope app.

Return type:

dict

to_json(pretty=True)[source]#

Format dictionary of this object as json.

Parameters:

pretty (bool) – If True, dumps to json using indent=2.

Return type:

str

currencies#

List of valid currencies to check attribute types for Trelliscope display.

trelliscope.currencies.get_valid_currencies()[source]#

Get a list of pre-defined currencies.

Return type:

list[str]

Returns:

A list of the ISO 4217 alpha code of common currencies.

input#

Input objects for Trelliscope.

class trelliscope.input.Input[source]#

Bases: object

Input object passed to trelliscope.

TODO: explain how this is used.

__init__()[source]#

Initialize with default name=””.

property name#

Name of Input.

panel_source#

Definitions of sources for Panels.

Panels can be laoded from files, REST endpoints and websockets. Depending on the panel’s source, the properties expected by Trelliscope are different.

class trelliscope.panel_source.PanelSource(source_type)[source]#

Bases: object

Base Panel source class.

__init__(source_type)[source]#

Create the base Panel source.

Parameters:

source_type (str) – Type of source. One of [‘file’, ‘REST’, ‘websocket’].

to_dict()[source]#

Dictionary of class properties as expected by Trelliscope.

class trelliscope.panel_source.FilePanelSource(is_local)[source]#

Bases: PanelSource

Panel source class for reading from local files.

__init__(is_local)[source]#

Create file panel source.

Parameters:

is_local (bool) – Boolean flag whether to read from local file.

to_dict()[source]#

Dictionary of class properties as expected by Trelliscope.

class trelliscope.panel_source.RESTPanelSource(url, api_key=None, headers=None)[source]#

Bases: PanelSource

Panel source class for requesting panel from REST endpoint.

__init__(url, api_key=None, headers=None)[source]#

Create REST panel source.

Parameters:
  • url (str) – URL for GET request for panel.

  • api_key (str) – Optional api key to authenticate with REST api.

  • headers (str) – Optional additional headers to send with request.

to_dict()[source]#

Dictionary of class properties as expected by Trelliscope.

class trelliscope.panel_source.LocalWebSocketPanelSource(url, port)[source]#

Bases: PanelSource

Panel source class for loading from local websockets.

__init__(url, port)[source]#

Create local websocket panel source.

Parameters:
  • url (str) – Local URL of websocket.

  • port (int) – Port to connect to.

progress_bar#

Progress bar used for printing progress when creating Trelliscope display.

class trelliscope.progress_bar.ProgressBar(total, prefix='', suffix='Complete', decimals=1, length=50, fill='█', print_end='\\r')[source]#

Bases: object

Configurable progress bar created by printing progress of an iteration.

Code based loosely on: https://stackoverflow.com/a/34325723

__init__(total, prefix='', suffix='Complete', decimals=1, length=50, fill='█', print_end='\\r')[source]#

Create Progress bar.

Parameters:
  • total (int) – Total expected iterations.

  • prefix (str) – Prefix of progress messages.

  • suffix (str) – Suffix of progress messages.

  • decimals (int) – Number of decimals to show of progress percentage.

  • length (int) – Total number of characters in a completed progress bar.

  • fill (str) – Character that represents a single bar in the progress bar.

  • print_end (str) – String appended after the last printed value, passed to print(…, end=print_end).

print_progress_bar_at_iteration(iteration)[source]#

Print progress bar at given iteration.

Parameters:

iteration (int) – integer iteration.

Return type:

None

record_progress()[source]#

Prints current progress and then adds 1 to internal count of iterations.

Return type:

None

record_finish()[source]#

Print empty newline, should be used after tracked iteration is finished.

Return type:

None

html_utils#

Contains utility functions that facilitate writing the html and support files for viewing.

trelliscope.html_utils.write_index_html(output_path, trelliscope_id, javascript_version=None)[source]#

Writes the main index.html file for the Trelliscope to the output directory.

Parameters:
  • output_path (str) – The absolute path to the directory that will contain the file.

  • trelliscope_id (str) – The ID of the Trelliscope object.

  • javascript_version (str) – The version of the Trelliscope JavaScript library to include from the CDN. If none is provided, the value will be read from the main config file.

Return type:

None

trelliscope.html_utils.write_id_file(output_path, trelliscope_id)[source]#

Writes the id file that belongs in the main output directory.

Parameters:
  • output_path (str) – The absolute path to the directory that will contain the file.

  • trelliscope_id (str) – The ID of the Trelliscope object.

Return type:

None

utils#

Utility methods and data validation checks.

trelliscope.utils.check_int(value_to_check, name, get_error_message_function=<function __generic_error_message>)[source]#

Verify that the value is an integer or raise an error.

Parameters:
  • value_to_check (Any) – The value in question.

  • name (str) – The variable name for the error message.

  • get_error_message_function (Callable) – The function to call to get the error message template.

Raises:

TypeError – If the check fails.

trelliscope.utils.check_positive_numeric(value_to_check, name, get_error_message_function=<function __generic_error_message>)[source]#

Verify that the value is a positive number (int or float). If not, raise an error.

Argss:

value_to_check: The value in question. name: The variable name for the error message. get_error_message_function: The function to call to get the error message template.

Raises:

TypeError – If the check fails.

trelliscope.utils.check_bool(value_to_check, name, get_error_message_function=<function __generic_error_message>)[source]#

Verify that the provided value is a boolean. If not, raise an error.

Parameters:
  • value_to_check – The value in question.

  • name (str) – The variable name for the error message.

  • get_error_message_function (Callable) – The function to call to get the error message template.

Raises:

TypeError – If the check fails.

trelliscope.utils.check_scalar(value_to_check, name, get_error_message_function=<function __generic_error_message>)[source]#

Verify that the provided value is a scalar value, otherwise raise an error.

Check specifically that the value is NOT an iterable. Note that for these purposes strings are considered scalars, even though they are technically iterable.

Parameters:
  • value_to_check (Any) – The value in question.

  • name (str) – The variable name for the error message.

  • get_error_message_function (Callable) – The function to call to get the error message template.

Raises:

TypeError – If the check fails.

trelliscope.utils.check_enum(value_to_check, possible_values, get_error_message_function=<function __generic_error_message>)[source]#

Verify that the provided value is in a list of possible values, or raise an error.

Parameters:
  • value_to_check (Any) – The value in question.

  • possible_values (list[Any]) – An iterable list of values.

  • get_error_message_function (Callable) – The function to call to get the error message template.

Raises:

ValueError – If the check fails.

trelliscope.utils.check_is_list(value_to_check, get_error_message_function)[source]#

Verify that the provided value is a list.

Parameters:
  • value_to_check – The value in question.

  • get_error_message_function (Callable) – The function to call to get the error message template.

Raises:

ValueError – If the check fails.

trelliscope.utils.check_has_variable(df, varname, get_error_message_function)[source]#

Verify that the dataframe contains the column.

Parameters:
  • df (DataFrame) – Pandas DataFrame.

  • varname (str) – The variable name to check.

  • get_error_message_function (Callable) – The function to call to get the error message template.

Raises:

ValueError – If the check fails.

trelliscope.utils.check_numeric(df, varname, get_error_message_function)[source]#

Verify that in the dataframe, the varname column is numeric.

Parameters:
  • df (DataFrame) – Pandas DataFrame.

  • varname (str) – The variable name to check.

  • get_error_message_function (Callable) – The function to call to get the error message template.

Raises:

ValueError – If the check fails.

trelliscope.utils.check_string_datatype(df, varname, get_error_message_function=<function __generic_error_message>)[source]#

Verify that in the dataframe, the column ‘varname’ is a string datatype.

Parameters:
  • df (DataFrame) – Pandas DataFrame.

  • varname (str) – The variable name to check.

  • get_error_message_function (Callable) – The function to call to get the error message template.

Raises:

ValueError – If the check fails.

trelliscope.utils.check_datetime(df, varname, get_error_message_function=<function __generic_error_message>)[source]#

Verify that in the dataframe, the varname column is a datetime column.

The column can either contain DateTime objects, or it can contain strings that can be easily coerced to DateTime objects.

Params:

df: Pandas DataFrame. varname: The variable name to check. get_error_message_function: The function to call to get the error message template.

Raises:

ValueError – If the check fails.

trelliscope.utils.check_atomic_vector(df, varname, get_error_message_function=<function __generic_error_message>)[source]#

Verify that in the dataframe, the column ‘varname’ is an atomic vector.

Specifically we check that the vector is not a nested type.

Params:

df: Pandas DataFrame. varname: The variable name to check. get_error_message_function: The function to call to get the error message template.

Raises:

ValueError – If the check fails.

trelliscope.utils.check_valid_currency(value_to_check, get_error_message_function)[source]#

Verify that the provided currency is a valid one (e.g., USD, EUR).

Params:

value_to_check: the value in question. get_error_message_function: The function to call to get the error message template.

Raises:

ValueError – If the check fails.

trelliscope.utils.check_range(df, varname, min, max, get_error_message_function)[source]#

Verify that all values in ‘varname’ column in the dataframe are within this range.

Parameters:
  • df (DataFrame) – Pandas DataFrame

  • varname (str) – The column

  • min (float) – float - The minimum value of the range (inclusive)

  • max (float) – float - The maximum value of the range (inclusive)

  • get_error_message_function (Callable) – The function to call to get the error message template

Raises:

ValueError – If the check fails.

trelliscope.utils.check_latitude_variable(df, varname, get_error_message_function)[source]#

Verify that the latitude variable is numeric and in the proper range.

Params:

df: Pandas DataFrame. varname: The latitude column. get_error_message_function: The function to call to get the error message template.

Raises:

ValueError - If the check fails.

trelliscope.utils.check_longitude_variable(df, varname, get_error_message_function)[source]#

Verify that the longitude variable is numeric and in the proper range.

Params:

df: Pandas DataFrame. varname: The longitude column. get_error_message_function: The function to call to get the error message template.

Raises:

ValueError – If the check fails.

trelliscope.utils.custom_json_serializer(obj)[source]#

JSON serializer for objects not serializable by built-in json.

trelliscope.utils.check_exhaustive_levels(df, levels, varname, get_error_message_function)[source]#

Verifies that the values in the varname column contains only specified values.

Checks that all values in the varname column of the dataframe are in levels. If any extras are found, an error is raised.

Parameters:
  • df (DataFrame) – Pandas DataFrame.

  • levels (list) – The list of possible values.

  • varname (str) – The name of the column to check.

  • get_error_message_function (Callable) – The function to call to get the error message template.

Raises:

ValueError – If the check fails.

trelliscope.utils.check_graph_var(df, varname, id_varname, get_error_message_function)[source]#

Check if varname column is a Graph type.

Raises:

NotImplementedError

trelliscope.utils.find_figure_columns(df)[source]#

Finds columns in the dataframe that are all plotly Figure objects.

Note this method places a dependency on plotly, which is otherwise not needed for basic Trelliscope functionality.

trelliscope.utils.is_figure_column(df, col)[source]#

Determine if the column is explicitly filled with Figure objects.

Parameters:
  • df (DataFrame) – pd.DataFrame - The dataframe

  • col (str) – str - The column to check

trelliscope.utils.find_image_columns(df)[source]#

Finds the columns in the dataframe that are all image references.

trelliscope.utils.get_extension(item)[source]#

Gets the file extension of the provided string filepath.

Return type:

str

Returns:

The extension (with no leading “.”, so it will return “jpg” not “.jpg”.)

trelliscope.utils.is_image_column(df, col)[source]#

Check if all values in a column are image references.

Parameters:
  • df (DataFrame) – Dataframe that contains data to check..

  • col (str) – Column of the dataframe to check.

Return type:

bool

Returns:

True if all values in the provided column have a valid image extension. False otherwise.

trelliscope.utils.check_image_extension(list_to_check, get_error_message_function=<function __generic_error_message>)[source]#

Verify that each element in the list has a valid image extension.

Parameters:
  • list_to_check (list[str]) – The list of strings.

  • get_error_message_function (Callable) – The function to call to get the error message template

Raises:

ValueError - If the check fails.

Return type:

None

trelliscope.utils.is_all_remote(col)[source]#

Check if every value in the provided column starts with “http”.`.

Return type:

bool

trelliscope.utils.sanitize(text, to_lower=True)[source]#

Sanitize string by replacing spaces and more.

TODO: explain why and how.

Parameters:
  • text (str) – Text to santize.

  • to_lower – If true, output is all lowercse.

Return type:

str

Returns:

Sanitized string.

trelliscope.utils.get_jsonp_wrap_text_dict(jsonp, function_name)[source]#

Gets the starting and ending text to use for the config file.

If it is jsonp, it will have a function name and ()’s. If it is not (ie, regular json), it will have empty strings.

Parameters:
  • jsonp (bool) – Boolean if text should be for .jsonp file or regular .json.

  • function_name (str) – Name of function to include if jsonp=true.

Return type:

dict[str, Any]

Returns:

Dictionary of text with ‘start’ and ‘end’ keys.

trelliscope.utils.write_json_file(file_path, jsonp, function_name, content)[source]#

Wrap content with standard ‘start’ and ‘end’ values, then write it to file.

Parameters:
  • file_path (str) – Output path to write file to.

  • jsonp (bool) – Boolean to write .jsonp format. Affects how the content is wrapped.

  • content (str) – The string content to write to file.

Return type:

None

trelliscope.utils.write_window_js_file(file_path, window_var_name, content)[source]#

Wrap javascript and write to file.

Return type:

None

trelliscope.utils.get_file_path(directory, filename_no_ext, jsonp)[source]#

Get filepath, of a .json or .jsonp file from a directory.

Return type:

str

trelliscope.utils.read_jsonp(file)[source]#

Reads the json content of the .json or .jsonp file.

If the file is a .jsonp file, the function name and ()’s will be ignored.

Parameters:

file (str) – The full path to the file.

Return type:

dict[str, Any]

Returns:

The dictionary content of the .json or .jsonp file.

trelliscope.utils.is_dataframe_grouped(df)[source]#

Check if pandas dataframe is grouped.

Return type:

bool

trelliscope.utils.get_dataframe_grouped_columns(df)[source]#

Get columns that a dataframe is grouped by.

Return type:

list

trelliscope.utils.get_string_columns(df)[source]#

Get names of columns in the dataframe that are string types.

Return type:

list

trelliscope.utils.get_string_or_factor_columns(df)[source]#

Get names of columns in the dataframe that are category or string types.

Return type:

list

trelliscope.utils.get_numeric_columns(df)[source]#

Get names of columns that contain numeric types.

Return type:

list

trelliscope.utils.get_uniquely_identifying_cols(df)[source]#

Determine list of columns names that create a unique index.

Only string and numeric columns are considered. Starting with the first string column, keep adding the next column until the combination of selected columns is unique for each row.

Numeric columns are only used after all string columns are included and the combination is still not unique.

Return type:

list[str]

Returns:

List of column names in the dataframe that create a unique combination of values for each row.

trelliscope.utils.is_string_column(column)[source]#

Checks to see if the provided Series is a string datatype.

Includes checking that it is not a Figure object.

Return type:

bool

trelliscope.utils.is_datetime_column(column, must_be_datetime_objects)[source]#

Checks to see if all values in Series are valid datetime objects.

Parameters:
  • column (Series) – The series to check.

  • must_be_datetime_objects (bool) – Must the values already be datetime objects? If False, this will check to see if they can all be coerced to valid objects.