def _make_data_source(df):
        """
        Creates a ColumnDataSource instance from provided dataframe.

        Parameters:
        -----------
        df : pd.Dataframe, shape [n_rows, n_columns]
            Dataframe to construct ColumnDataSource from.

        Returns:
        --------
        source : ColumnDataSource
            ColumnDataSource instance of the data in df.
        """
        source = ColumnDataSource(df)
        # add a dummy column for colour of each d.p
        source.add(np.zeros(df.shape[0]), name='color')
        return source
    def plot(self, figure, color_attr=None, history_step=None, solid_color='#0485d1', circle_attr=None,
             circle_attr_transform=lambda x: x, circle_line_color='#cb7723', circle_fill_color='#fcb001',
             circle_hover_attrs=[], color_attr_bounds=None):
        """ To simply plot the network in a solid color, use color_attr=None and history_step=None.
            To plot a fixed attribute of each network reach such as redd capacity, set color_attr to the
            name of that attribute and history_step=None.
            To plot an attribute of the network's history that varies over time, use history_step along
            with the name of that attribute.
            color_attr_bounds is None to use the min and max values of that variable in the current plot, or
            specifiable to use a standard color range across multiple plots"""
        lines = [reach.points for reach in self.reaches]
        source = ColumnDataSource({'xs': [list(np.array(line).T[0]) for line in lines],
                                   'ys': [list(np.array(line).T[1]) for line in lines],
                                   'line_widths': [0.5 * reach.strahler_order for reach in self.reaches]})

        figure.add_layout(Label(x=self.migration_reach.midpoint[0], y=self.migration_reach.midpoint[1]+750,
                                text='Migration', text_align='center'))
        figure.add_layout(Label(x=self.ocean_reach.midpoint[0], y=self.ocean_reach.midpoint[1]+750,
                                text='Ocean', text_align='center'))
        if history_step is not None:
            year = 1 + math.floor(history_step / time_settings['WEEKS_PER_YEAR'])
            step_within_year = history_step % time_settings['WEEKS_PER_YEAR']
            days_into_year = 1 + step_within_year * time_settings['DAYS_PER_WEEK']
            date1 = datetime.date.fromordinal(days_into_year).strftime("%b %e")
            date2 = datetime.date.fromordinal(days_into_year + 7).strftime("%b %e")
            timestring = "Timestep {0} (step {1} of year {2}, {3} - {4})".format(history_step,
                                                                                 1 + step_within_year,
                                                                                 year,
                                                                                 date1,
                                                                                 date2)
            figure.add_layout(Label(x=30, y=700, x_units='screen', y_units='screen', text=timestring))
            season, season_color = self.season_label(history_step)
            figure.add_layout(Label(x=650, y=700, x_units='screen', y_units='screen', text=season, text_color=season_color))
        if color_attr is None:
            figure.multi_line('xs', 'ys', source=source, line_color=solid_color, line_width='line_widths')
        else:
            source.add([reach.reach_statistic(color_attr, history_step) for reach in self.reaches], name='color_values')
            color_low_value = min(source.data['color_values']) if color_attr_bounds is None else color_attr_bounds[0]
            color_high_value = max(source.data['color_values']) if color_attr_bounds is None else color_attr_bounds[1]
            mapper = LinearColorMapper(palette='Viridis256', low=color_low_value, high=color_high_value)
            figure.multi_line('xs', 'ys', source=source, line_color={'field': 'color_values', 'transform': mapper}, line_width='line_widths')
            fmt = NumeralTickFormatter(format='00')
            color_bar = ColorBar(color_mapper=mapper, location=(0, 0), title=color_attr, formatter=fmt, label_standoff=7)
            figure.add_layout(color_bar, 'right')
        if circle_attr is not None:
            circle_source = ColumnDataSource({'xs': [reach.midpoint[0] for reach in self.reaches],
                                              'ys': [reach.midpoint[1] for reach in self.reaches]})
            circle_source.add([circle_attr_transform(reach.reach_statistic(circle_attr, history_step))
                               for reach in self.reaches], name='circle_sizes')
            for attr in circle_hover_attrs:
                circle_source.add([reach.reach_statistic(attr, history_step) for reach in self.reaches], name=attr)
            figure.scatter('xs', 'ys', source=circle_source, name='scatterplot', marker='circle', size='circle_sizes',
                           line_color=circle_line_color, fill_color=circle_fill_color, alpha=0.5)
            hover_tooltips = []
            for attr in circle_hover_attrs:
                hover_tooltips.append((attr, "@"+attr))
            figure.add_tools(HoverTool(tooltips=hover_tooltips, names=['scatterplot']))
            figure.toolbar.logo = None
Esempio n. 3
0
])

url = "http://127.0.0.1:5000/alldata"
res = requests.get(url, timeout=20)
data = res.json()
static_source = ColumnDataSource(data)
selection_plot = figure(
    height=100, tools="box_select",
    x_axis_location="above",
    x_axis_type="datetime", toolbar_location=None,
    outline_line_color=None,
    name="small_plot"
)
selection_source = ColumnDataSource()
for k in ['end', 'values', 'start', 'bottom']:
       selection_source.add([], k)
       selection_plot.quad(top='values', bottom='bottom', left='start', right='end',
              source=selection_source, color='#c6dbef', fill_alpha=0.5)

selection_plot.line('Date', 'Price', color='#A6CEE3', source=static_source)
selection_plot.circle('Date', 'Price', color='#A6CEE3', source=static_source, size=1)

style_selection_plot(selection_plot)

# Customize select tool behaviour
select_tool = selection_plot.select(dict(type=BoxSelectTool))
select_tool.dimensions = ['width']

code = """
    if (window.xrange_base_start == undefined){
        window.xrange_base_start = main_plot.get('x_range').get('start');
Esempio n. 4
0
 def test_add_with_name(self):
     ds = ColumnDataSource()
     name = ds.add([1, 2, 3], name="foo")
     assert name == "foo"
     name = ds.add([4, 5, 6], name="bar")
     assert name == "bar"
Esempio n. 5
0
 def test_remove_exists(self):
     ds = ColumnDataSource()
     name = ds.add([1, 2, 3], "foo")
     assert name
     ds.remove("foo")
     assert ds.column_names == []
Esempio n. 6
0
 def test_add_with_and_without_name(self):
     ds = ColumnDataSource()
     name = ds.add([1, 2, 3], "foo")
     assert name == "foo"
     name = ds.add([4, 5, 6])
     assert name == "Series 1"
Esempio n. 7
0
])

url = "http://127.0.0.1:5000/alldata"
res = requests.get(url, timeout=20)
data = res.json()
static_source = ColumnDataSource(data)
selection_plot = figure(height=100,
                        tools="box_select",
                        x_axis_location="above",
                        x_axis_type="datetime",
                        toolbar_location=None,
                        outline_line_color=None,
                        name="small_plot")
selection_source = ColumnDataSource()
for k in ['end', 'values', 'start', 'bottom']:
    selection_source.add([], k)
    selection_plot.quad(top='values',
                        bottom='bottom',
                        left='start',
                        right='end',
                        source=selection_source,
                        color='#c6dbef',
                        fill_alpha=0.5)

selection_plot.line('Date', 'Price', color='#A6CEE3', source=static_source)
selection_plot.circle('Date',
                      'Price',
                      color='#A6CEE3',
                      source=static_source,
                      size=1)
Esempio n. 8
0
class DraughtPlot():
    """
    Plots a draughtsman plot (a.k.a a pair plot) of provided data

    Parameters:
    -----------
    X : pd.Dataframe, shape [n_instances, n_features]
        The training set.
    
    y : {None or array-like}, shape [n_instances] (default=None)
        Target class of each of the n_instances instances.

    features : {None or list}, (default=None) 
        List of the feature names to plot. If None, the first five
        features of X are used. If the target needs to be included in the
        Draughtsman plot include the string "target" in the feature  list.

    url : str, (default="localhost:8888")
        Location (port) of the jupyter notebook to output figure too.
    
    Attributes:
    -----------
    X : pd.Dataframe, shape [n_instances, n_features]
        The training set.
    
    y : {None or array-like}, shape [n_instances] 
        Target class of each of the n_instances instances.

    brush_idxs : array-like
        Indices of the different clusters plotted.

    features : list
        Names of features which are plotted.
    """
    def __init__(self, X, y=None, features=None, url="localhost:8888"):
        """
        Constructer for the DraughtPlot class. 
        """
        self.X = X
        self.y = y
        self.features = features
        # could be updated to make an educated guess of the five features.
        if self.features is None:
            self.features = self.X.columns[:5].tolist()
        if 'target' in self.features:
            self.X['target'] = self.y
        self.corr_matrix = X[self.features]
        app = Application(FunctionHandler(
            self._make_bokeh_doc))  # make document
        show(app, notebook_url=url)  # show document in notebook

    def _make_bokeh_doc(self, doc):
        """
        Function which is called when generating the Bokeh document. Main 
        function which constructs the application.
        
        Parameters:
        -----------
        doc : bokeh.Document
            Document instance to collect bokeh models in.
        """
        self._make_data_source()
        self._make_figures()
        self._initalise_figures()
        self._make_widgets()
        doc_layout = self._make_doc_layout()
        doc.add_root(doc_layout)

    def _make_doc_layout(self):
        """
        Constructs the document layout object.
        
        Returns:
        --------
        doc_layout : bokeh.layouts.layout object
            Grid layout of bokeh models used in figure.
        """
        cb_figure = Column(self._create_colour_bar())
        widgets = Column(self.widgets['select_color'],
                         self.widgets['change_color'])
        draughtsman_plot = gridplot(self.figures.tolist())
        doc_layout = layout([[draughtsman_plot, cb_figure, widgets]])
        return doc_layout

    def _make_figures(
        self,
        fig_props={
            'plot_height':
            150,
            'plot_width':
            150,
            'tools': ('box_zoom,'
                      'wheel_zoom,'
                      'box_select,'
                      'lasso_select,'
                      'reset,'
                      'help,'
                      'save')
        }):
        """
        Creates a grid of empty figures and stores references to each object in
        an array.

        Parameters:
        -----------
        fig_props : dict,
            kwargs to pass to each figure instance when instantiated.
        """
        self.figures = np.array([])
        # could replace this with a single for loop using itertools
        for i, __ in enumerate(self.features):
            for j, __ in enumerate(self.features):
                xlabel, ylabel = self._get_axis_labels(i, j)
                fig = figure(x_axis_label=xlabel,
                             y_axis_label=ylabel,
                             **fig_props)
                self.figures = np.append(self.figures, fig)
        num_features = len(self.features)
        self.figures = self.figures.reshape((num_features, num_features))

    def _make_widgets(self, widget_width=200):
        """
        Generates the widgets to be used for interaction.

        Parameters:
        -----------
        widget_width : int, (default=200)
            width of the widgets in pixels.
        """
        # dictionary storing: (widget type, kwargs, callback) for each widget
        widget_definitions = {
            'select_color': (Select, {
                'options': self.X.columns.tolist(),
                'title': 'Select colour',
                'width': widget_width
            }, None),
            'change_color': (
                Button,
                {
                    'label': 'Change colour',
                    'width': widget_width
                },
                self._change_color,
            )
        }
        self.widgets = {}
        for widget_name, widget_def in widget_definitions.items():
            widget = widget_def[0](**widget_def[1])
            if widget_def[2] is not None:
                widget.on_click(widget_def[2])
            self.widgets[widget_name] = widget

    def _change_color(self):
        """
        Callback for change_color button. 
        """
        feature_name = self.widgets['select_color'].value
        feature_data = self.X[feature_name].values
        self.source.patch(
            {'cluster_number': [(slice(len(feature_data)), feature_data)]})
        # update the color_mapper limits
        self.color_mapper['transform'].low = feature_data.min()
        self.color_mapper['transform'].high = feature_data.max()

    def _get_axis_labels(self, col_num, row_num):
        """
        For given column and row numbers provides the labels for the 
        x and y axis for specified figure.

        Parameters:
        -----------
        col_num : int
            Column index of figure

        row_num : int
            Row index of figure

        Returns:
        --------
        x_label : str
            x axis label for figure at [row_num, col_num]

        y_label : str
            y axis label for figure at [row_num, col_num]
        """
        x_label, y_label = '', ''
        if col_num == (len(self.features) - 1):
            x_label = self.features[row_num]
        if row_num == 0:
            y_label = self.features[col_num]
        return x_label, y_label

    def _initalise_figures(self):
        """
        For each figure in self.figures plots the relevant graph (text,
        histogram, or scatter) to the figure and stores the GlyphRenderer
        object returned.
        """
        self._glyphs = np.array([])  # for storing GlyphRenders
        self._make_color_mapper()
        for i, fy in enumerate(self.features):
            for j, fx in enumerate(self.features):
                plot_type = self._check_fig_type(i, j)
                if plot_type == 'histogram':
                    cnts, edges = self._gen_hist_data(self.X[fx].to_numpy())
                    glyphs = self._plot_histogram(figure=self.figures[i, j],
                                                  counts=cnts,
                                                  bin_edges=edges)
                if plot_type == 'scatter':
                    glyphs = self._plot_scatter(self.figures[i, j], fx, fy)
                if plot_type == 'text':
                    # plot a scatter for the time being
                    glyphs = self._plot_text(self.figures[i, j], i, j)
                    # turn of the figure axis and grid
                    self.figures[i, j].axis.visible = False
                    self.figures[i, j].grid.visible = False
                self._glyphs = np.append(self._glyphs, glyphs)
        num_features = len(self.features)
        self._glyphs = self._glyphs.reshape((num_features, num_features))
        (self._glyphs[1, 0].data_source.selected.on_change(
            'indices', self._update_plot))

    def _plot_histogram(
        self,
        figure,
        counts,
        bin_edges,
        hist_props={
            'color': 'grey',
            'selection_color': 'grey',
            'selection_fill_alpha': 0.1,
            'fill_alpha': 0.4,
            'line_alpha': 0.75
        }):
        """
        Plots a histogram to a given figure.

        Parameters:
        -----------
        figure : bokeh.plotting.figure object
            Figure object to plot the histogram.

        counts : array-like, shape [n_bins]
            Counts in each bin of histogram.

        bin_edges : array-like, shape [n_bins+1]
            Edges of the bins. 
        
        hist_props : dict 
            kwargs to pass to figure.quad method.

        Returns:
        --------
        hist : GlyphRenderer object
            GlyphRenderer object of plotted data.
        """
        left_edges = bin_edges[:-1]
        right_edges = bin_edges[1:]
        hist = figure.quad(bottom=0,
                           left=left_edges,
                           right=right_edges,
                           top=counts,
                           **hist_props)
        return hist

    def _make_color_mapper(self):
        """
        Makes the color mapper object used to control the colour of data points 
        in all the plots.
        """
        high_value = np.max(self.source.data['cluster_number'])
        self.color_mapper = linear_cmap(field_name='cluster_number',
                                        palette=Viridis256,
                                        low=1,
                                        high=high_value)

    def _plot_scatter(self, figure, f1, f2):
        """
        Plots scatter graph of given features (f1 and f2) for all training instances.

        Parameters:
        -----------
        figure : bokeh.figure object 
            Figure object to plot scatter too.
        
        f1 : str
            Name of feature to plot on x-axis.
        
        f2 : str
            Name of feature to plot on y-axis.

        Returns:
        --------
        scatter : bokeh.GlyphRenderer object
            GlyphRenderer object for plotted data.
        """
        scatter = figure.scatter(x=f1,
                                 y=f2,
                                 source=self.source,
                                 color=self.color_mapper,
                                 marker='markers',
                                 line_color='black',
                                 line_width=0.3,
                                 nonselection_fill_color=self.color_mapper,
                                 nonselection_fill_alpha=0.1)
        return scatter

    def _create_colour_bar(self):
        """
        Creates a colorbar in an empty bokeh figure.

        Returns:
        --------
        colorbar_fig : bokeh.figure object
            Figure object containing the colorbar.
        """
        self.color_bar = ColorBar(color_mapper=self.color_mapper['transform'],
                                  width=8)
        colorbar_fig = figure(plot_height=188 * len(self.features),
                              plot_width=85,
                              toolbar_location=None,
                              outline_line_color=None)
        colorbar_fig.add_layout(self.color_bar, 'center')
        return colorbar_fig

    def _plot_text(self, figure, col_num, row_num):
        """
        Adds text, describing statistical properties of features of figure
        located at  [col_num, row_num].
        
        Parameters:
        -----------
        figure : bokeh.figure object
            Figure object to plot text too.

        col_num : int
            Column index of figure object.
        
        row_num : int
            Row index of figure object.

        Returns:
        --------
        text : GlyphRenderer object of the text.
        """
        figure_text = self._generate_panel_text(col_num, row_num)
        text = figure.text(x=[0],
                           y=[0],
                           text=[figure_text],
                           text_font='times',
                           text_font_style='italic',
                           text_font_size='12pt',
                           text_align='center',
                           text_baseline='middle')
        return text

    def _generate_panel_text(self, col_num, row_num):
        """
        Returns the text for the figure at (col_num, row_num).

        Parameters:
        -----------
        col_num : int 
            Column index of figure panel
        row_num : int 
            Row index of figure panel

        Returns:
        --------
        text : str
            Text describing features correlations (Pearson's r).
        """
        correlation_coeff = self.corr_matrix.iloc[row_num, col_num]
        text = 'r: {:.2f}'.format(correlation_coeff)
        return text

    @property
    def corr_matrix(self):
        """
        Get or calculate (set) the correlation matrix of data. The correlation
        matrix is initialised using all the data provided to DraughtPlot.

        To calculate the correlation matrix, the setter calls the .corr()
        method of pd.DataFrame.

        Returns:
        --------
        _corr_matrix : array-like, shape [n_features, n_features]
            Correlation matrix of the training set (X).
        """
        return self._corr_matrix

    @corr_matrix.setter
    def corr_matrix(self, df):
        self._corr_matrix = df.corr()

    def _gen_hist_data(self, x, n_bins=20):
        """
        Creates a histogram of data provided in x.

        Parameters:
        -----------
        x : array-like, shape [n_instances]
            Array of data to generate histogram of.

        n_bins: int, (default=20)
            Number of bins to use in histogram.

        Returns:
        --------
        counts : array-like, shape [n_bins]
            Number of instances in each bin.

        bin_edges : array-like, shape [n_bins+1]
            Edges of the bins.

        TO DO: 
            1. Need to make bins never change for a given feature.
            Or get them from the figure?
        """
        counts, bin_edges = np.histogram(x, bins=n_bins)
        return counts, bin_edges

    @staticmethod
    def _check_fig_type(col_num, row_num):
        """
        Given the (row, column) index of a figure return the type of figure it
        is. Possible values are "histogram", "scatter" or "text".

        Parameters:
        -----------    
        col_num : int
            Column index of figure panel.

        row_num : int
            Row index of figure panel.

        Returns:
        --------
        figure_type : str
            Type of the figure at position [row_num, col_num]. Can take values 
            equal too: "histogram", "scatter" or "text".
        """
        if row_num == col_num:
            figure_type = "histogram"
        elif col_num > row_num:
            figure_type = "scatter"
        else:
            figure_type = "text"
        return figure_type

    def _make_data_source(self):
        """
        Creates a ColumnDataSource of the provided data using given features, 
        ensures a cluster_number column exists in the df.
        """
        try:
            cols_to_keep = self.features + ["cluster_number"]
            self.source = ColumnDataSource(self.X[cols_to_keep])
        except KeyError:
            # No cluster_number column defined, make a dummy one
            self.source = ColumnDataSource(self.X[self.features])
            cluster_numbers = np.ones(self.X.shape[0])
            self.source.add(data=cluster_numbers, name="cluster_number")
        # create markers for the scatter plot if target is binary
        self.markers = np.array(["circle"] *
                                len(self.source.data["cluster_number"]))
        if utils.is_binary(self.y):
            self.markers[self.y == 0] = "square"
        self.source.add(data=self.markers, name="markers")

    def _update_plot(self, attr, old, new):
        """
        Updates the text description with data points select in the scatter.

        Parameters:
        -----------
        attr : str
            Attribute to monitor (i.e., indices, value) of data.
        
        old : Any
            Old value(s) of attr

        new : Any
            New value(s) of attr.
        """
        inds = new
        # get data selected by user, or all data.
        if len(inds) > 0 and len(inds) < self.X.shape[0]:
            X_view = self.X.iloc[inds, :][self.features]
        else:
            X_view = self.X[self.features]
        self.corr_matrix = X_view
        for i, __ in enumerate(self.features):
            for j, __ in enumerate(self.features):
                plot_type = self._check_fig_type(i, j)
                if plot_type == "text":
                    (self._glyphs[i, j].data_source.data["text"]) = [
                        self._generate_panel_text(i, j)
                    ]

    @staticmethod
    def show_example(fpath="data/static/DraughtPlot_example.gif"):
        """
        Displays a .gif demonstrating how to use the tool.

        Parameters:
        -----------
        fpath : str, default="data/static/DraughtPlot_example.gif"
            Location of example .gif to show.
        """
        return Image(filename=fpath)
Esempio n. 9
0
 def test_add_with_and_without_name(self):
     ds = ColumnDataSource()
     name = ds.add([1,2,3], "foo")
     self.assertEquals(name, "foo")
     name = ds.add([4,5,6])
     self.assertEquals(name, "Series 1")
Esempio n. 10
0
 def test_remove_exists(self):
     ds = ColumnDataSource()
     name = ds.add([1,2,3], "foo")
     assert name
     ds.remove("foo")
     assert ds.column_names == []
Esempio n. 11
0
 def test_add_with_and_without_name(self):
     ds = ColumnDataSource()
     name = ds.add([1,2,3], "foo")
     assert name == "foo"
     name = ds.add([4,5,6])
     assert name == "Series 1"
Esempio n. 12
0
 def test_add_with_name(self):
     ds = ColumnDataSource()
     name = ds.add([1,2,3], name="foo")
     assert name == "foo"
     name = ds.add([4,5,6], name="bar")
     assert name == "bar"
Esempio n. 13
0
def create_selection_plot(main_plot, theme):

    static_source = ColumnDataSource(data)
    selection_plot = figure(
        height=100, tools="box_select", x_axis_location="above",
        x_axis_type="datetime", toolbar_location=None,
        outline_line_color=None, name="small_plot"
    )
    selection_source = ColumnDataSource()
    for k in ['end', 'values', 'start', 'bottom']:
        selection_source.add([], k)

    if theme == 'default':
        selection_color = '#c6dbef'
    elif theme == 'dark':
        selection_color = "#FFAD5C"

    selection_plot.quad(top='values', bottom='bottom', left='start', right='end',
          source=selection_source, color=selection_color, fill_alpha=0.5)

    selection_plot.line('Date', 'Price', color='#A6CEE3', source=static_source)
    selection_plot.circle('Date', 'Price', color='#A6CEE3', source=static_source, size=1)

    style_selection_plot(selection_plot, theme)

    select_tool = selection_plot.select(dict(type=BoxSelectTool))
    select_tool.dimensions = ['width']

    code = """
        if (window.xrange_base_start == undefined){
            window.xrange_base_start = main_plot.get('x_range').get('start');
        }
        if (window.xrange_base_end == undefined){
            window.xrange_base_end = main_plot.get('x_range').get('end');
        }

        data = source.get('data');
        sel = source.get('selected')['1d']['indices'];
        var mi = 1000000000;
        var ma = -100000;
        if (sel.length == 0){
           var url = "http://127.0.0.1:5000/alldata";
           source_data = selection_source.get('data');
           source_data.bottom = []
           source_data.values = [];
           source_data.start = [];
           source_data.end = [];

            // reset main plot ranges
            main_range.set('start', window.xrange_base_start);
            main_range.set('end', window.xrange_base_end);
        }else{
           for (i=0; i<sel.length; i++){
            if (mi>sel[i]){
                mi = sel[i];
            }
            if (ma<sel[i]){
                ma = sel[i];
            }
           }
           var url = "http://127.0.0.1:5000/subsample/"+data.Date[mi]+"/"+data.Date[ma];
           source_data = selection_source.get('data');
           source_data.bottom = [0]
           source_data.values = [700];
           source_data.start = [data.Date[mi]];
           source_data.end = [data.Date[ma]];

           main_range = main_plot.get('x_range');
           main_range.set('start', data.Date[mi]);
           main_range.set('end', data.Date[ma]);
        }

        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", url, true);
        xmlhttp.send();

        selection_source.trigger('change');

        if (sel.length==0){
            $("#details_panel").addClass("hidden");
            $("#details_panel").html("");
        }else{

            var url = "http://127.0.0.1:5000/details";
            xhr = $.ajax({
                type: 'GET',
                url: url,
                contentType: "application/json",
                // data: jsondata,
                header: {
                  client: "javascript"
                }
            });

            xhr.done(function(details) {
                $("#details_panel").removeClass("hidden");
                $("#details_panel").html("<h3>Selected Region Report</h3>");
                $("#details_panel").append("<div>From " + details.start + " to " + details.end + "</div>");
                $("#details_panel").append("<div>Number of original samples " + details.original_samples_no + "</div>");
                $("#details_panel").append("<div>Number of samples " + details.samples_no + "</div>");
                $("#details_panel").append("<div>Factor " + details.factor + "</div>");
            });
        }

    """

    callback = CustomJS(
           args={'source': static_source,
                 'selection_source': selection_source,
                 'main_plot': main_plot},
           code=code)
    static_source.callback = callback

    return selection_plot
Esempio n. 14
0
def create_selection_plot(main_plot, theme):

    static_source = ColumnDataSource(data)
    selection_plot = figure(height=100,
                            tools="box_select",
                            x_axis_location="above",
                            x_axis_type="datetime",
                            toolbar_location=None,
                            outline_line_color=None,
                            name="small_plot")
    selection_source = ColumnDataSource()
    for k in ['end', 'values', 'start', 'bottom']:
        selection_source.add([], k)

    if theme == 'default':
        selection_color = '#c6dbef'
    elif theme == 'dark':
        selection_color = "#FFAD5C"

    selection_plot.quad(top='values',
                        bottom='bottom',
                        left='start',
                        right='end',
                        source=selection_source,
                        color=selection_color,
                        fill_alpha=0.5)

    selection_plot.line('Date', 'Price', color='#A6CEE3', source=static_source)
    selection_plot.circle('Date',
                          'Price',
                          color='#A6CEE3',
                          source=static_source,
                          size=1)

    style_selection_plot(selection_plot, theme)

    select_tool = selection_plot.select(dict(type=BoxSelectTool))
    select_tool.dimensions = ['width']

    code = """
        if (window.xrange_base_start == undefined){
            window.xrange_base_start = main_plot.get('x_range').get('start');
        }
        if (window.xrange_base_end == undefined){
            window.xrange_base_end = main_plot.get('x_range').get('end');
        }

        data = source.get('data');
        sel = source.get('selected')['1d']['indices'];
        var mi = 1000000000;
        var ma = -100000;
        if (sel.length == 0){
           var url = "http://127.0.0.1:5000/alldata";
           source_data = selection_source.get('data');
           source_data.bottom = []
           source_data.values = [];
           source_data.start = [];
           source_data.end = [];

            // reset main plot ranges
            main_range.set('start', window.xrange_base_start);
            main_range.set('end', window.xrange_base_end);
        }else{
           for (i=0; i<sel.length; i++){
            if (mi>sel[i]){
                mi = sel[i];
            }
            if (ma<sel[i]){
                ma = sel[i];
            }
           }
           var url = "http://127.0.0.1:5000/subsample/"+data.Date[mi]+"/"+data.Date[ma];
           source_data = selection_source.get('data');
           source_data.bottom = [0]
           source_data.values = [700];
           source_data.start = [data.Date[mi]];
           source_data.end = [data.Date[ma]];

           main_range = main_plot.get('x_range');
           main_range.set('start', data.Date[mi]);
           main_range.set('end', data.Date[ma]);
        }

        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", url, true);
        xmlhttp.send();

        selection_source.trigger('change');

        if (sel.length==0){
            $("#details_panel").addClass("hidden");
            $("#details_panel").html("");
        }else{

            var url = "http://127.0.0.1:5000/details";
            xhr = $.ajax({
                type: 'GET',
                url: url,
                contentType: "application/json",
                // data: jsondata,
                header: {
                  client: "javascript"
                }
            });

            xhr.done(function(details) {
                $("#details_panel").removeClass("hidden");
                $("#details_panel").html("<h3>Selected Region Report</h3>");
                $("#details_panel").append("<div>From " + details.start + " to " + details.end + "</div>");
                $("#details_panel").append("<div>Number of original samples " + details.original_samples_no + "</div>");
                $("#details_panel").append("<div>Number of samples " + details.samples_no + "</div>");
                $("#details_panel").append("<div>Factor " + details.factor + "</div>");
            });
        }

    """

    callback = Callback(args={
        'source': static_source,
        'selection_source': selection_source,
        'main_plot': main_plot
    },
                        code=code)
    static_source.callback = callback

    return selection_plot
Esempio n. 15
0
def weightlifting_figs(data, height = 500, width = 1000):
	#Timeseries Plot
	wz_max = WheelZoomTool(dimensions='width')
	plot_max_tools_s = [HoverTool(tooltips=[("Squat", "@s_m : @squat_max")], names=["squat_clamp"],mode='vline'), PanTool(dimensions='width'), wz_max, ResetTool(), SaveTool()]
	plot_max_tools_d = [HoverTool(tooltips=[("Deadlift", "@d_m : @deadlift_max"), (" ", " ")], names=["deadlift_clamp"],mode='vline'), PanTool(dimensions='width'), wz_max, ResetTool(), SaveTool()]
	plot_max_tools_b = [HoverTool(tooltips=[("Bench Press", "@b_m : @bench_max")], names=["bench_clamp"],mode='vline'), PanTool(dimensions='width'), wz_max, ResetTool(), SaveTool()]
	plot_max_tools_o = [HoverTool(tooltips=[("OHP", "@o_m : @ohp_max")], names=["ohp_clamp"],mode='vline'), PanTool(dimensions='width'), wz_max, ResetTool(), SaveTool()]


	wz_mvps = WheelZoomTool(dimensions='width')
	plot_mvps_tools_s = [HoverTool(tooltips=[("Squat", "@s_mvps{1} : @squat_max_vol_per_set{1}")], names=["s_mvps"],mode='vline'), PanTool(dimensions='width'), wz_mvps, ResetTool(), SaveTool()]
	plot_mvps_tools_d = [HoverTool(tooltips=[("Deadlift", "@d_mvps{1} : @deadlift_max_vol_per_set{1}")], names=["d_mvps"],mode='vline'), PanTool(dimensions='width'), wz_mvps, ResetTool(), SaveTool()]
	plot_mvps_tools_b = [HoverTool(tooltips=[("Bench Press", "@b_mvps{1} : @bench_max_vol_per_set{1}")], names=["b_mvps"],mode='vline'), PanTool(dimensions='width'), wz_mvps, ResetTool(), SaveTool()]
	plot_mvps_tools_o = [HoverTool(tooltips=[("OHP", "@o_mvps{1} : @ohp_max_vol_per_set{1}")], names=["o_mvps"],mode='vline'), PanTool(dimensions='width'), wz_mvps, ResetTool(), SaveTool()]

	wz_tv = WheelZoomTool(dimensions='width')
	plot_tv_tools_s = [HoverTool(tooltips=[("Squat", "@s_tv{1} : @squat_total_vol{1}")], names=["s_tv"],mode='vline'), PanTool(dimensions='width'), wz_tv, ResetTool(), SaveTool()]
	plot_tv_tools_d = [HoverTool(tooltips=[("Deadlift", "@d_tv{1} : @deadlift_total_vol{1}")], names=["d_tv"],mode='vline'), PanTool(dimensions='width'), wz_tv, ResetTool(), SaveTool()]
	plot_tv_tools_b = [HoverTool(tooltips=[("Bench Press", "@b_tv{1} : @bench_total_vol{1}")], names=["b_tv"],mode='vline'), PanTool(dimensions='width'), wz_tv, ResetTool(), SaveTool()]
	plot_tv_tools_o = [HoverTool(tooltips=[("OHP", "@o_tv{1} : @ohp_total_vol{1}")], names=["o_tv"],mode='vline'), PanTool(dimensions='width'), wz_tv, ResetTool(), SaveTool()]

	data['date_str'] = data['date'].map(str)

	cds_max = ColumnDataSource(dict(date=data['date'], date_str=data['date_str'], stair_amount=data['stair_amount'], squat_max=data['squat_max'], deadlift_max=data['deadlift_max'], bench_max=data['bench_max'], ohp_max=data['ohp_max']))

	#MVPS and TV plots are hooked into the MA slider, so share a cds
	cds_w = ColumnDataSource(dict(date=data['date'], date_str=data['date_str'], stair_amount=data['stair_amount'], squat_max=data['squat_max'], deadlift_max=data['deadlift_max'], bench_max=data['bench_max'], ohp_max=data['ohp_max'], squat_max_vol_per_set=data['squat_max_vol_per_set'], deadlift_max_vol_per_set=data['deadlift_max_vol_per_set'], bench_max_vol_per_set=data['bench_max_vol_per_set'], ohp_max_vol_per_set=data['ohp_max_vol_per_set'], squat_total_vol=data['squat_total_vol'], deadlift_total_vol=data['deadlift_total_vol'], bench_total_vol=data['bench_total_vol'], ohp_total_vol=data['ohp_total_vol']))
	cds_s = ColumnDataSource(dict(date=data['date'], date_str=data['date_str'], stair_amount=data['stair_amount'], squat_max=data['squat_max'], deadlift_max=data['deadlift_max'], bench_max=data['bench_max'], ohp_max=data['ohp_max'], squat_max_vol_per_set=data['squat_max_vol_per_set'], deadlift_max_vol_per_set=data['deadlift_max_vol_per_set'], bench_max_vol_per_set=data['bench_max_vol_per_set'], ohp_max_vol_per_set=data['ohp_max_vol_per_set'], squat_total_vol=data['squat_total_vol'], deadlift_total_vol=data['deadlift_total_vol'], bench_total_vol=data['bench_total_vol'], ohp_total_vol=data['ohp_total_vol']))

	d = cds_max.data
	d_w = cds_w.data

	#Calculate clamp values
	s_m, d_m, b_m, o_m, s_mvps, d_mvps, b_mvps, o_mvps, s_tv, d_tv, b_tv, o_tv = [], [], [], [], [], [], [], [], [], [], [], []

	#***TODO: Make general
	#First values
	s_m.append(155.0)
	d_m.append(145.0)
	b_m.append(135.0)
	o_m.append(70.0)
	s_mvps.append(775.0)
	d_mvps.append(725.0)
	b_mvps.append(675.0)
	o_mvps.append(350.0)
	s_tv.append(4425.0)
	d_tv.append(2650.0)
	b_tv.append(3525.0)
	o_tv.append(1700.0)

	#Find max of all previous values to clamp
	for c in range(1,len(d['date'])):
		#Clamp
		if math.isnan(d['squat_max'][c]):
			s_m.append(max(s_m[c - 1], s_m[0]))
		else:
			s_m.append(max(s_m[c - 1],d['squat_max'][c]))
		if math.isnan(d['deadlift_max'][c]):
			d_m.append(max(d_m[c - 1], d_m[0]))
		else:
			d_m.append(max(d_m[c - 1],d['deadlift_max'][c])) 
		if math.isnan(d['bench_max'][c]):
			b_m.append(max(b_m[c - 1], b_m[0]))
		else:
			b_m.append(max(b_m[c - 1],d['bench_max'][c]))
		if math.isnan(d['ohp_max'][c]):
			o_m.append(max(o_m[c - 1], o_m[0]))
		else:
			o_m.append(max(o_m[c - 1],d['ohp_max'][c]))

		#Extend for vlaues that are not present
		if math.isnan(d_w['squat_max_vol_per_set'][c]):
			s_mvps.append(s_mvps[c - 1])
		else:
			s_mvps.append(d_w['squat_max_vol_per_set'][c])
		if math.isnan(d_w['deadlift_max_vol_per_set'][c]):
			d_mvps.append(d_mvps[c - 1])
		else:
			d_mvps.append(d_w['deadlift_max_vol_per_set'][c])
		if math.isnan(d_w['bench_max_vol_per_set'][c]):
			b_mvps.append(b_mvps[c - 1])
		else:
			b_mvps.append(d_w['bench_max_vol_per_set'][c])
		if math.isnan(d_w['ohp_max_vol_per_set'][c]):
			o_mvps.append(o_mvps[c - 1])
		else:
			o_mvps.append(d_w['ohp_max_vol_per_set'][c])

		if math.isnan(d_w['squat_total_vol'][c]):
			s_tv.append(s_tv[c - 1])
		else:
			s_tv.append(d_w['squat_total_vol'][c])
		if math.isnan(d_w['deadlift_total_vol'][c]):
			d_tv.append(d_tv[c - 1])
		else:
			d_tv.append(d_w['deadlift_total_vol'][c])
		if math.isnan(d_w['bench_total_vol'][c]):
			b_tv.append(b_tv[c - 1])
		else:
			b_tv.append(d_w['bench_total_vol'][c])
		if math.isnan(d_w['ohp_total_vol'][c]):
			o_tv.append(o_tv[c - 1])
		else:
			o_tv.append(d_w['ohp_total_vol'][c])

	#Put the calculated data into the CDS
	cds_max.add(d['date'], name='date')
	cds_max.add(s_m, name='s_m')
	cds_max.add(d_m, name='d_m')
	cds_max.add(b_m, name='b_m')
	cds_max.add(o_m, name='o_m')

	cds_w.add(d['date'], name='date')
	cds_w.add(s_mvps, name='s_mvps')
	cds_w.add(d_mvps, name='d_mvps')
	cds_w.add(b_mvps, name='b_mvps')
	cds_w.add(o_mvps, name='o_mvps')

	cds_w.add(s_tv, name='s_tv')
	cds_w.add(d_tv, name='d_tv')
	cds_w.add(b_tv, name='b_tv')
	cds_w.add(o_tv, name='o_tv')

	cds_s.add(d['date'], name='date')
	cds_s.add(s_mvps, name='s_mvps')
	cds_s.add(d_mvps, name='d_mvps')
	cds_s.add(b_mvps, name='b_mvps')
	cds_s.add(o_mvps, name='o_mvps')

	cds_s.add(s_tv, name='s_tv')
	cds_s.add(d_tv, name='d_tv')
	cds_s.add(b_tv, name='b_tv')
	cds_s.add(o_tv, name='o_tv')

	#Plot: MAXes
	plot_max = figure(x_axis_type="datetime", title="MAXes", h_symmetry=False, v_symmetry=False,
				  min_border=0, plot_height=height, plot_width=width, toolbar_location="above", outline_line_color="#666666", active_scroll=wz_max,tools=plot_max_tools_d)
	
	plot_max.yaxis.axis_label = "lbs"
	plot_max.add_tools(plot_max_tools_s[0], plot_max_tools_b[0] ,plot_max_tools_o[0])

	plot_max.line('date', 's_m', source=cds_max, name='squat_clamp', line_color="#8B0A50", line_width=2, line_alpha=0.6, legend="Squat (Clamp)")
	plot_max.cross('date', 'squat_max', source=cds_max, name="squat_max", line_color="#8B0A50", line_width=1, line_alpha=0.6, legend="Squat (Actual)")    

	plot_max.line('date', 'd_m', source=cds_max, name='deadlift_clamp', line_color="#333366", line_width=2, line_alpha=0.6, legend="Deadlift (Clamp)")
	plot_max.cross('date', 'deadlift_max', source=cds_max, name="deadlift_max", line_color="#333366", line_width=1, line_alpha=0.6, legend="Deadlift (Actual)")    

	plot_max.line('date', 'b_m', source=cds_max, name='bench_clamp', line_color="#FF7700", line_width=2, line_alpha=0.6, legend="Bench Press (Clamp)")
	plot_max.cross('date', 'bench_max', source=cds_max, name="bench_max", line_color="#FF7700", line_width=1, line_alpha=0.6, legend="Bench Press (Actual)")    

	plot_max.line('date', 'o_m', source=cds_max, name='ohp_clamp', line_color="#C74D56", line_width=2, line_alpha=0.6, legend="OHP (Clamp)")
	plot_max.cross('date', 'ohp_max', source=cds_max, name="ohp_max", line_color="#C74D56", line_width=1, line_alpha=0.6, legend="OHP (Actual)")    

	plot_max.legend.location = "top_left"
	plot_max.legend.click_policy="hide"

	#Plot: MVPS
	plot_mvps = figure(x_axis_type="datetime", title="Maximum Volume Per Set", h_symmetry=False, v_symmetry=False,
				  min_border=0, plot_height=height, plot_width=width, x_range=plot_max.x_range, toolbar_location="above", outline_line_color="#666666", tools=plot_mvps_tools_d, active_scroll=wz_mvps)

	plot_mvps.add_tools(plot_mvps_tools_s[0], plot_mvps_tools_b[0] ,plot_mvps_tools_o[0])

	plot_mvps.cross('date', 'squat_max_vol_per_set', source=cds_s, line_color="#8B0A50", line_width=1, line_alpha=0.6, legend="Squat")
	plot_mvps.line('date', 's_mvps', name="s_mvps", source=cds_w, line_color="#8B0A50", line_width=1, line_alpha=0.6, legend="Squat (MA)")

	plot_mvps.cross('date', 'deadlift_max_vol_per_set', source=cds_s, line_color="#333366", line_width=1, line_alpha=0.6, legend="Deadlift")
	plot_mvps.line('date', 'd_mvps', name="d_mvps", source=cds_w, line_color="#333366", line_width=1, line_alpha=0.6, legend="Deadlift (MA)")

	plot_mvps.cross('date', 'bench_max_vol_per_set', source=cds_s, line_color="#FF7700", line_width=1, line_alpha=0.6, legend="Bench Press")
	plot_mvps.line('date', 'b_mvps', name="b_mvps", source=cds_w, line_color="#FF7700", line_width=1, line_alpha=0.6, legend="Bench Press (MA)")

	plot_mvps.cross('date', 'ohp_max_vol_per_set', source=cds_s, line_color="#C74D56", line_width=1, line_alpha=0.6, legend="Overhead Press")
	plot_mvps.line('date', 'o_mvps', name="o_mvps", source=cds_w, line_color="#C74D56", line_width=1, line_alpha=0.6, legend="Overhead Press (MA)")
				
	#Plot: Total Volume
	plot_mvps.yaxis.axis_label = "lbs"
	plot_mvps.legend.location = "top_left"
	plot_mvps.legend.click_policy="hide"

	plot_tv = figure(x_axis_type="datetime", title="Total Volume", h_symmetry=False, v_symmetry=False,
				  min_border=0, plot_height=height, plot_width=width, x_range=plot_max.x_range, toolbar_location="above", outline_line_color="#666666", tools=plot_tv_tools_d, active_scroll=wz_tv)
	
	plot_tv.add_tools(plot_tv_tools_s[0], plot_tv_tools_b[0] ,plot_tv_tools_o[0])
	
	plot_tv.cross('date', 'squat_total_vol', source=cds_s, line_color="#8B0A50", line_width=1, line_alpha=0.6, legend="Squat")
	plot_tv.line('date', 's_tv', name='s_tv', source=cds_w, line_color="#8B0A50", line_width=1, line_alpha=0.6, legend="Squat (MA)")

	plot_tv.cross('date', 'deadlift_total_vol', source=cds_s, line_color="#333366", line_width=1, line_alpha=0.6, legend="Deadlift")
	plot_tv.line('date', 'd_tv', name='d_tv', source=cds_w, line_color="#333366", line_width=1, line_alpha=0.6, legend="Deadlift (MA)")

	plot_tv.cross('date', 'bench_total_vol', source=cds_s, line_color="#FF7700", line_width=1, line_alpha=0.6, legend="Bench Press")
	plot_tv.line('date', 'b_tv', name='b_tv', source=cds_w, line_color="#FF7700", line_width=1, line_alpha=0.6, legend="Bench Press (MA)")

	plot_tv.cross('date', 'ohp_total_vol', source=cds_s, line_color="#C74D56", line_width=1, line_alpha=0.6, legend="Overhead Press")
	plot_tv.line('date', 'o_tv', name='o_tv', source=cds_w, line_color="#C74D56", line_width=1, line_alpha=0.6, legend="Overhead Press (MA)")

	plot_tv.yaxis.axis_label = "lbs"
	plot_tv.legend.location = "top_left"
	plot_tv.legend.click_policy="hide"

	div_squat_max = Div()
	div_deadlift_max = Div()
	div_bench_max = Div()
	div_ohp_max = Div()

	div_squat_max_vol_per_set = Div()
	div_deadlift_max_vol_per_set = Div()
	div_bench_max_vol_per_set = Div()
	div_ohp_max_vol_per_set = Div()

	div_squat_total_vol = Div()
	div_deadlift_total_vol = Div()
	div_bench_total_vol = Div()
	div_ohp_total_vol = Div()

	#Calculate number of stairs climbed on stairmaster
	num_stairs = sum([_ for _ in data['stair_amount'] if math.isnan(_)==False])
	num_esb = num_stairs/1860 #1860 steps in the Empire State Building
	div_stairs = Div(text=str(int(num_stairs)) + " (" + str(int(num_esb)) + " Empire St.)")

	#Calculate number of missile frigates lifted
	num_ohp = (sum([_ for _ in data['squat_total_vol'] if math.isnan(_)==False]) + sum([_ for _ in data['deadlift_total_vol'] if math.isnan(_)==False]) + sum([_ for _ in data['bench_total_vol'] if math.isnan(_)==False]) + sum([_ for _ in data['ohp_total_vol'] if math.isnan(_)==False]))/8200000
	div_num_ohp = Div(text=str('{0:.2f}'.format(num_ohp)))
	div_workouts = Div(text=str(len(data['date'])))

	#Calculate Wilks
	#TODO: Pull in actual weight
	bw = 150/2.2
	totals = s_m[-1]/2.2 + d_m[-1]/2.2 + b_m[-1]/2.2

	#Static constant
	wilks_c = 500/(-216.0475144 + (16.2606339)*bw + (-0.002388645)*bw**2 + (-0.00113732)*bw**3 + (0.000007019)*bw**4 + (-0.00000001291)*bw**5) 
	div_wilks = Div(text=str('{0:.2f}'.format(wilks_c*totals)))

	ma_cb = CustomJS(args=dict(w=cds_w, s=cds_s), code=MA_SLIDER_CODE)
	plot_max.x_range.callback = CustomJS(args=dict(d_s_m=div_squat_max, d_d_m=div_deadlift_max, d_b_m=div_bench_max, d_o_m=div_ohp_max, d_s_mvps=div_squat_max_vol_per_set, d_d_mvps=div_deadlift_max_vol_per_set, d_b_mvps=div_bench_max_vol_per_set, d_o_mvps=div_ohp_max_vol_per_set, d_s_tv=div_squat_total_vol, d_d_tv=div_deadlift_total_vol, d_b_tv=div_bench_total_vol, d_o_tv=div_ohp_total_vol, s=cds_s), code=LIFTS_STATS_CODE)

	ma_slider = Slider(start=1, end=30, value=1, step=1, title="Moving Average", callback=ma_cb)
	return components((div_stairs, div_num_ohp, div_workouts, div_wilks, div_squat_max, div_deadlift_max, div_bench_max, div_ohp_max, div_squat_max_vol_per_set, div_deadlift_max_vol_per_set, div_bench_max_vol_per_set, div_ohp_max_vol_per_set, div_squat_total_vol, div_deadlift_total_vol, div_bench_total_vol, div_ohp_total_vol, plot_max, plot_mvps, plot_tv, ma_slider))
Esempio n. 16
0
 def test_add_with_name(self):
     ds = ColumnDataSource()
     name = ds.add([1,2,3], name="foo")
     self.assertEquals(name, "foo")
     name = ds.add([4,5,6], name="bar")
     self.assertEquals(name, "bar")
Esempio n. 17
0
def meditation_figs(data, height=500, width=1300):
    #Timeseries Plot
    bz_daily = BoxZoomTool()
    wz_cumu = WheelZoomTool(dimensions='width')

    plot_daily_tools = [
        PanTool(dimensions='width'), bz_daily,
        ResetTool(),
        SaveTool()
    ]
    plot_cumu_tools = [
        PanTool(dimensions='width'), wz_cumu,
        ResetTool(),
        SaveTool()
    ]

    data['date_str'] = data['date'].map(str)

    cds_w = ColumnDataSource(
        dict(date=data['date'],
             date_str=data['date_str'],
             meditation_time=data['meditation_time']))
    cds_s = ColumnDataSource(
        dict(date=data['date'],
             date_str=data['date_str'],
             meditation_time=data['meditation_time']))

    d = cds_w.data
    d_s = cds_w.data

    #Calculate weeklong MA value, and cumulative value
    m_t_ma, m_t_c = [], []

    # #MA (inital values: 10;0;0;10;10;10;10)
    m_t_ma.append(10.0)
    m_t_ma.append(5.0)
    m_t_ma.append(3.33)
    m_t_ma.append(5.0)
    m_t_ma.append(6.0)
    m_t_ma.append(6.67)
    m_t_ma.append(7.14)

    for j in range(7, len(d['date'])):
        m_t_ma.append(
            (d['meditation_time'][j] + d['meditation_time'][j - 1] +
             d['meditation_time'][j - 2] + d['meditation_time'][j - 3] +
             d['meditation_time'][j - 4] + d['meditation_time'][j - 5] +
             d['meditation_time'][j - 6]) / 7.0)

    # print(d['date'].count())
    # print(d.get(datetime.date(2018,12,30)))
    cds_w.add(m_t_ma, name='m_t_ma')

    #Cumu (inital value: 10)
    m_t_c.append(10.0)

    for k in range(1, d['date'].count()):
        m_t_c.append(d['meditation_time'][k] + m_t_c[-1])

    cds_w.add(m_t_c, name='m_t_c')

    #PLOT DAILY
    plot_daily = figure(x_axis_type="datetime",
                        title="Daily Meditation",
                        h_symmetry=False,
                        v_symmetry=False,
                        min_border=0,
                        plot_height=height,
                        plot_width=width,
                        toolbar_location="above",
                        outline_line_color="#666666",
                        tools=plot_daily_tools)
    glyph = VBar(x="date",
                 top="meditation_time",
                 bottom=0,
                 width=.8,
                 fill_color="#41A2E8",
                 line_color="#41A2E8")
    plot_daily.add_glyph(cds_w, glyph)
    plot_daily.line('date',
                    'm_t_ma',
                    name='m_t_ma',
                    source=cds_w,
                    line_color="#8B0A50",
                    line_width=3,
                    line_alpha=0.6,
                    legend="Moving Average (7 days)")

    plot_daily.legend.location = "top_left"
    plot_daily.legend.click_policy = "hide"
    plot_daily.yaxis.axis_label = "Minutes"

    #plot_daily.Bar('date', 'meditation_time', source=cds_w, name='meditation_time')
    plot_cumu = figure(x_axis_type="datetime",
                       title="Cumulative Meditation",
                       h_symmetry=False,
                       v_symmetry=False,
                       min_border=0,
                       plot_height=height,
                       plot_width=width,
                       toolbar_location="above",
                       outline_line_color="#666666",
                       active_scroll=wz_cumu,
                       tools=plot_cumu_tools)

    glyph = VBar(x="date",
                 top="m_t_c",
                 bottom=0,
                 width=.8,
                 fill_color="#41A2E8",
                 line_color="#41A2E8")
    plot_cumu.add_glyph(cds_w, glyph)
    plot_cumu.yaxis.visible = False

    #plot_daily = Histogram(cds_w, 'meditation_time', title="Daily Meditation", plot_height=height, plot_width=width, active_scroll=wz)

    #plot_cumu = Histogram(cds_w, 'meditation_time', title="Daily Meditation", plot_height=height, plot_width=width, active_scroll=wz)
    #plot_max = figure(x_axis_type="datetime", title="MAXes", h_symmetry=False, v_symmetry=False, min_border=0, plot_height=height, plot_width=width, toolbar_location="above", outline_line_color="#666666", active_scroll=wz_max,tools=plot_max_tools_d)

    script, (plot_daily_div, plot_cumu_div) = components(
        (plot_daily, plot_cumu))

    return script, plot_daily_div, plot_cumu_div
Esempio n. 18
0
 def test_remove_exists(self):
     ds = ColumnDataSource()
     name = ds.add([1,2,3], "foo")
     assert name
     ds.remove("foo")
     self.assertEquals(ds.column_names, [])
Esempio n. 19
0
def mood_figs(data, height=500, width=1000):

    #Timeseries Plot
    wz = WheelZoomTool(dimensions='width')
    plot_ts_tools = [
        HoverTool(tooltips=[("Date", "@date_str"), (
            "A", "@a_l:@a_u (@a_be)"), ("V", "@v_l:@v_u (@v_be)")]),
        PanTool(dimensions='width'), wz,
        ResetTool(),
        SaveTool()
    ]

    data['date_str'] = data['date'].map(str)

    cds_working = ColumnDataSource(
        dict(date=data['date'],
             date_str=data['date_str'],
             a_l=data['a_l'],
             a_u=data['a_u'],
             a_be=data['a_be'],
             v_l=data['v_l'],
             v_u=data['v_u'],
             v_be=data['v_be']))
    cds_static = ColumnDataSource(
        dict(date=data['date'],
             date_str=data['date_str'],
             a_l=data['a_l'],
             a_u=data['a_u'],
             a_be=data['a_be'],
             v_l=data['v_l'],
             v_u=data['v_u'],
             v_be=data['v_be']))

    plot_ts = figure(x_axis_type="datetime",
                     title="Mood (AV Circumplex Model)",
                     h_symmetry=False,
                     v_symmetry=False,
                     min_border=0,
                     plot_height=height,
                     plot_width=width,
                     y_range=[1, 9],
                     toolbar_location="above",
                     outline_line_color="#666666",
                     tools=plot_ts_tools,
                     active_scroll=wz)

    plot_ts.line('date',
                 'a_l',
                 source=cds_working,
                 line_color="#8B0A50",
                 line_width=1,
                 line_alpha=0.6,
                 legend="A (Lower Bound)")
    plot_ts.line('date',
                 'a_u',
                 source=cds_working,
                 line_color="#8B0A50",
                 line_width=1,
                 line_alpha=0.6,
                 legend="A (Upper Bound)")
    plot_ts.line('date',
                 'a_be',
                 source=cds_working,
                 line_color="#8B0A50",
                 line_width=3,
                 line_alpha=0.6,
                 legend="A (Best Est.)")

    plot_ts.line('date',
                 'v_l',
                 source=cds_working,
                 line_color="#00E5EE",
                 line_width=1,
                 line_alpha=0.6,
                 legend="V (Lower Bound)")
    plot_ts.line('date',
                 'v_u',
                 source=cds_working,
                 line_color="#00E5EE",
                 line_width=1,
                 line_alpha=0.6,
                 legend="V (Upper Bound)")
    plot_ts.line('date',
                 'v_be',
                 source=cds_working,
                 line_color="#00E5EE",
                 line_width=3,
                 line_alpha=0.6,
                 legend="V (Best Est.)")

    plot_ts.legend.location = "top_left"
    plot_ts.legend.click_policy = "hide"

    #Vis_Rep Plot
    plot_vr = figure(title="Mood (AV Circumplex Model)",
                     h_symmetry=False,
                     v_symmetry=False,
                     min_border=0,
                     plot_height=height,
                     plot_width=width,
                     x_range=[1, 9],
                     y_range=[1, 9],
                     toolbar_location="above",
                     outline_line_color="#666666",
                     x_axis_label='Alertness',
                     y_axis_label="Valence")

    #***TODO IMPROVE: Hookup slider
    alpha_fudge, color_fudge = 30, 150
    cds_working_2 = ColumnDataSource(cds_working.data)
    d = cds_working_2.data

    def get_oval(a_l, a_u, v_l, v_u, v_be, a_be):
        x = float((a_u + a_l) / 2)
        y = float((v_u + v_l) / 2)
        w = (a_u - a_l)
        h = (v_u - v_l)
        alpha = float((1 + abs(5 - a_be)**3) *
                      alpha_fudge) / 100  #***TODO FIX: Indicate better

        c_val = int((1 + abs(5 - v_be)**3) * color_fudge)

        #Some bug in Bokeh or something; does not accept (R,G,B) tuples as colors
        if v_be >= 5:
            color = "#%02x%02x%02x" % (0, c_val, 0)
        else:
            color = "#%02x%02x%02x" % (c_val, 0, 0)

        return x, y, w, h, alpha, color

    x, y, w, h, alpha, color = [], [], [], [], [], []
    for c in range(len(d['date'])):
        x_, y_, w_, h_, alpha_, color_ = get_oval(d['a_l'][c], d['a_u'][c],
                                                  d['v_l'][c], d['v_u'][c],
                                                  d['v_be'][c], d['a_be'][c])
        x.append(x_)
        y.append(y_)
        w.append(w_)
        h.append(h_)
        alpha.append(alpha_)
        color.append(color_)

    cds_working_2.add(x, name='x')
    cds_working_2.add(y, name='y')
    cds_working_2.add(w, name='w')
    cds_working_2.add(h, name='h')
    cds_working_2.add(alpha, name='alpha')
    cds_working_2.add(color, name='color')

    plot_vr.oval('x',
                 'y',
                 'w',
                 'h',
                 color='color',
                 source=cds_working_2,
                 alpha='alpha')

    div_days = Div()
    div_avg_a = Div()
    div_avg_v = Div()
    div_good_days = Div()
    div_poor_days = Div()
    div_caution_days = Div()
    div_warning_days = Div()

    ma_cb = CustomJS(args=dict(w=cds_working, s=cds_static),
                     code=MA_SLIDER_CODE)
    plot_ts.x_range.callback = CustomJS(args=dict(d_d=div_days,
                                                  d_avg_a=div_avg_a,
                                                  d_avg_v=div_avg_v,
                                                  d_g_d=div_good_days,
                                                  d_p_d=div_poor_days,
                                                  d_c_d=div_caution_days,
                                                  d_w_d=div_warning_days,
                                                  s=cds_static),
                                        code=MOOD_STATS_CODE)
    ma_slider = Slider(start=1,
                       end=30,
                       value=1,
                       step=1,
                       title="Moving Average",
                       callback=ma_cb)
    return components(
        (div_days, div_avg_a, div_avg_v, div_good_days, div_poor_days,
         div_caution_days, div_warning_days, plot_ts, plot_vr, ma_slider))