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:
objectMain 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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_displays_path()[source]#
Returns the path of the displays directory.
The output path is a child of the main output path.
- Return type:
- get_dataset_display_path()[source]#
Returns the path of the display directory.
The path is a child of the main displays directory.
- Return type:
- 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:
- 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.Metaobject 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:
- Returns:
Returns a copy of this object with the meta added. The original object is not modified.
- Infer a
- 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:
- 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:
- 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:
- 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:
- Return type:
- 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:
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:
- 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 specificationsadd (
bool) – Should existing filter state specifications be added to? If False, the entire filter state specification will be overridden.
- Return type:
- 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:
- 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:
- Returns:
Returns a copy of this object with the meta added. The original object is not modified.
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 theplot_function.
- Return type:
- Returns:
A dataframe with 1 column with the name of
panel_column_namecontaining figure objects, The dataframe will have a multi-level index, with the level names given byfacet_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:
objectStores settings associated with panel.
The PanelOptions object is used by the
trelliscope.trelliscope.Trelliscope.set_panel_options()method to pre-specify information about thePanelbefore it is actually created. Then, later when thePanelobject 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 fromwidth/height.
- Raises:
ValueError – If
widthorheightis not a positive numeric value. Or, ifforceorprerenderis not a boolean. Or, ifformatnot an allowed value.
- class trelliscope.panels.Panel(varname, panel_type_str, source, aspect_ratio=1.5, is_image=True, writeable=False)[source]#
Bases:
objectBase 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.
- get_extension()[source]#
Get the extension of this Panel.
- Raises:
NotImplementedError – if not overwritten in subclasses.
- Return type:
- 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.FigurePanelor atrelliscope.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:
PanelPanel 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:
PanelCreate 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:
PanelCreate 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.
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:
objectBase class for the various state classes.
- class trelliscope.state.LayoutState(ncol=1, page=1)[source]#
Bases:
StateState definition for Layout of trelliscope display.
- class trelliscope.state.LabelState(varnames=[])[source]#
Bases:
StateState 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:
- 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:
StateState of panel sorting.
- __init__(varname, dir='asc', meta_type=None)[source]#
Create Sort state.
- Parameters:
varname (
str) – str - The variable namedir (
Literal['asc','desc']) – str (“asc” or “desc”) - The direction of the sortvarname – 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?).
- class trelliscope.state.FilterState(varname, filtertype, applies_to=None, meta_type=None)[source]#
Bases:
StateState of filters applied to panels and their attributes.
- 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:
- 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:
- class trelliscope.state.CategoryFilterState(varname, regexp=None, values=None)[source]#
Bases:
FilterStateState for filtering category/factor data types.
- __init__(varname, regexp=None, values=None)[source]#
Create filter state for a category/factor variable.
- 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:
FilterStateBase filter state for a range filter.
- class trelliscope.state.NumberRangeFilterState(varname, min=None, max=None)[source]#
Bases:
RangeFilterStateRange filter state for numeric variable.
- class trelliscope.state.DateRangeFilterState(varname, min=None, max=None)[source]#
Bases:
RangeFilterStateRange filter state for date-type variables.
- class trelliscope.state.DatetimeRangeFilterState(varname, min=None, max=None)[source]#
Bases:
RangeFilterStateRange filter state for datetime-type variables.
- class trelliscope.state.DisplayState[source]#
Bases:
objectContains 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.
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:
objectThe 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 variablefilterable (
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.
- to_json(pretty=True)[source]#
Gets a JSON string containing all the attributes of a meta.
This is used when serializing.
- check_varname(df)[source]#
Check that the variable column exists.
- Raises:
ValueError – If the varname is not found.
- Return type:
- check_variable(df)[source]#
Overridden in subclasses to contain more specific checks.
If the check fails, this should raise an error.
- Return type:
- 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:
- 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:
MetaA 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
digitsis not an integer scalar. Or, iflocaleis given butdigitsis not.
- check_variable(df)[source]#
Check that the variable column is a numeric type.
- Raises:
ValueError – if
self.varnamecolumn in the data frame is not numeric.
- class trelliscope.metas.CurrencyMeta(varname, label=None, tags=None, code='USD')[source]#
Bases:
MetaA Meta for currency data.
- check_variable(df)[source]#
Check that the variable column is a numeric type.
- Raises:
ValueError – if
self.varnamecolumn in the data frame is not numeric.
- class trelliscope.metas.StringMeta(varname, label=None, tags=None)[source]#
Bases:
MetaA Meta for string data.
- 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.
- class trelliscope.metas.PanelMeta(panel, label=None, tags=None)[source]#
Bases:
MetaA Meta for Panels.
- __init__(panel, label=None, tags=None)[source]#
Create Meta for Panel objects.
- Parameters:
- 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:
- Returns:
Dictionary representation as expected by the trelliscope javascript.
- class trelliscope.metas.FactorMeta(varname, label=None, tags=None, levels=None)[source]#
Bases:
MetaA meta for a categorical, factor variable.
- __init__(varname, label=None, tags=None, levels=None)[source]#
Create Meta for categorical factor types.
- 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:
- Returns:
Updated dataframe with varname column as categorical.
- Raises:
NotImplementedError – Work in progress.
- class trelliscope.metas.DateMeta(varname, label=None, tags=None)[source]#
Bases:
MetaMeta for date types.
- class trelliscope.metas.DatetimeMeta(varname, label=None, tags=None, timezone='UTC')[source]#
Bases:
MetaMeta for datetime types.
- class trelliscope.metas.GraphMeta(varname, label=None, tags=None, idvarname=None, direction='none')[source]#
Bases:
MetaMeta for Graph types.
- __init__(varname, label=None, tags=None, idvarname=None, direction='none')[source]#
Create Meta object for Graph variable.
- 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:
MetaMeta for Geo types.
- __init__(varname, latvar, longvar, label=None, tags=None)[source]#
Create Meta object for Geo variable 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:
objectPre-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 Viewfilter_state (
FilterState) – Filter state in this View.filter_states (
list) – List of filter states in this View.
currencies#
List of valid currencies to check attribute types for Trelliscope display.
input#
Input objects for Trelliscope.
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:
objectBase Panel source class.
- class trelliscope.panel_source.FilePanelSource(is_local)[source]#
Bases:
PanelSourcePanel source class for reading from local files.
- class trelliscope.panel_source.RESTPanelSource(url, api_key=None, headers=None)[source]#
Bases:
PanelSourcePanel source class for requesting panel from REST endpoint.
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:
objectConfigurable 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).
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:
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.
- 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.
- 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.
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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.
- 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:
- 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.
- 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.
- trelliscope.utils.is_all_remote(col)[source]#
Check if every value in the provided column starts with “http”.`.
- Return type:
- trelliscope.utils.sanitize(text, to_lower=True)[source]#
Sanitize string by replacing spaces and more.
TODO: explain why and how.
- 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.
- 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.
- trelliscope.utils.write_window_js_file(file_path, window_var_name, content)[source]#
Wrap javascript and write to file.
- Return type:
- trelliscope.utils.get_file_path(directory, filename_no_ext, jsonp)[source]#
Get filepath, of a .json or .jsonp file from a directory.
- Return type:
- 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.
- trelliscope.utils.is_dataframe_grouped(df)[source]#
Check if pandas dataframe is grouped.
- Return type:
- trelliscope.utils.get_dataframe_grouped_columns(df)[source]#
Get columns that a dataframe is grouped by.
- Return type:
- trelliscope.utils.get_string_columns(df)[source]#
Get names of columns in the dataframe that are string types.
- Return type:
- trelliscope.utils.get_string_or_factor_columns(df)[source]#
Get names of columns in the dataframe that are category or string types.
- Return type:
- trelliscope.utils.get_numeric_columns(df)[source]#
Get names of columns that contain numeric types.
- Return type:
- 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.
- 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: