def add_multiline_to_plot(figure: 'Bokeh Figure', legend: tuple, column_data_source: 'CDS for Bokeh figure', line_width: int=2, line_1_color: str='#CC0000', line_2_color: str='orange') -> 'Bokeh Figure':
        """Adds multiple lines on Bokeh figure, initializes legend and return Bokeh figure."""

        figure.line(x='x', y='y1', line_width=line_width, line_color=line_1_color, legend=legend[0], source=column_data_source)
        figure.line(x='x', y='y2', line_width=line_width, line_color=line_2_color, legend=legend[1], source=column_data_source)
        figure = DataVisualizationUtils.initialise_legend_properties(figure)
        return figure
Esempio n. 2
0
def calibrate(current, reference, figure):
    r = scipy.stats.linregress(x=current, y=reference, alternative='two-sided')
    a, b = current[0], current[-1]
    ca, cb = (
        a * r.slope + r.intercept,
        b * r.slope + r.intercept,
    )
    figure.line(
        x=[a, b],
        y=[ca, cb],
        color="red",
    )

    rps = Label(x=min(current),
                y=(max(reference) - min(reference)) * .8 + min(reference),
                x_units="data",
                y_units="data",
                text=f"slope={r.slope}\nintercept={r.intercept}\n"
                f"rvalue={r.rvalue}\npvalue={r.pvalue}\n"
                f"stderr={r.stderr}\nintercept_stderr={r.intercept_stderr}",
                render_mode='css',
                border_line_color='black',
                border_line_alpha=1.0,
                background_fill_color='white',
                background_fill_alpha=1.0)
    figure.add_layout(rps)
    return dict(slope=r.slope, intercept=r.intercept)
Esempio n. 3
0
def render_bytes_sent_received(
    figure: Figure, df: pd.DataFrame, label: str, read_col: str, write_col: str
):
    time = df[DATETIME_KEY]

    def accumulate(column):
        values = df[column]
        values = values - values.min()
        return resample(values, time)

    read = accumulate(read_col)
    write = accumulate(write_col)

    data = ColumnDataSource(
        dict(rx=read, rx_kb=read / 1024, tx=write, tx_kb=write / 1024, x=read.index)
    )
    tooltips = [("RX", "@rx_kb KiB"), ("TX", "@tx_kb KiB")]

    figure.add_tools(HoverTool(tooltips=tooltips))
    figure.yaxis[0].formatter = NumeralTickFormatter(format="0.0b")

    y_max = max(max(data.data["rx"]), max(data.data["tx"]))
    figure.y_range = Range1d(0, y_max + 0.01)

    figure.line(
        x="x", y="rx", color="blue", legend_label="{} RX".format(label), source=data
    )
    figure.line(
        x="x", y="tx", color="red", legend_label="{} TX".format(label), source=data
    )
Esempio n. 4
0
    def render(**figure_kwargs):

        figure = Figure(**figure_kwargs)
        figure.add_layout(Legend())
        figure.legend.location = "top_left"
        figure.legend.click_policy = "hide"

        figure.line(legend_label=yfast,
                    source=onesource,
                    x='datetime',
                    y=yfast,
                    color='red')
        figure.line(legend_label=yslow,
                    source=onesource,
                    x='datetime',
                    y=yslow,
                    color='blue')
        figure.segment(legend_label=y1hist,
                       source=onesource,
                       x0='datetime',
                       x1='datetime',
                       y0=0,
                       y1=y1hist,
                       line_width=6,
                       color='black',
                       alpha=0.5)

        return figure
Esempio n. 5
0
def step(counts, bins, label, color, figure):
    '''
    Add a step plot to 'figure', inplace of a bar plot

    Input:
     - counts   : array-like
                Y-axis values
     - bins     : array-like
                Limiting values for x-axis bins
     - label    : string
                Label for this distribution
     - color    : string
                Code defining a color; see ~booq.plot.Colors
     - figure   : ~pandas.plotting.figure

    Output:
     - Figure : ~bokeh.plotting.figure
    '''
    _y,_x = histogram2stepfunction(counts,bins)
    figure.line(x=_x,
                y=_y,
                #line_color="#D95B43",line_width=2,
                line_color=color,line_width=2,
                legend='label')

    import numpy as np
    _x = np.diff(bins)/2+bins[:-1]
    figure.circle(x=_x,
                  y=_y,
                  #line_color="#D95B43",line_width=2,
                  line_color=color,line_width=2,
                  fill_color="white",fill_alpha=1,
                  size=9,
                  legend='label')
    return figure
Esempio n. 6
0
def plot_pleak(figure, section):
    '''
    Plot list of peaks given by the user
    '''

    # Get all values from columns plotted by user to find minimum value
    all_values = [
        plotObject.data.loc[:, col]
        for col in plotObject.plots[section]['columns']
    ]

    all_values = [j for i in all_values for j in i if not pd.isna(j)]

    min_value = np.min(all_values)
    min_value = min_value - abs(0.1 * min_value)
    max_value = np.max(all_values) * 1.1

    y_axis = (min_value, 0, max_value)
    for peak, peak_name in plotObject.peaks:
        x_axis = np.ones_like(y_axis) * peak
        figure.line(x_axis,
                    y_axis,
                    line_color='green',
                    line_width=2,
                    name=peak_name)

    return figure
Esempio n. 7
0
def render_global_percent_resource_usage(
    figure: Figure,
    source: ColumnDataSource,
    report: ClusterReport,
    hostnames: List[str],
):
    node_count = len(hostnames)
    figure.y_range = Range1d(0, node_count + 1)
    figure.yaxis.axis_label = "Usage (%)"

    # Draw resource usage
    colors = select_colors(hostnames)
    figure.vbar_stack(
        hostnames,
        x="x_start",
        width=1000.0,
        color=colors,
        line_color="black",
        legend_label=[get_node_description(report, hostname) for hostname in hostnames],
        source=source,
    )

    # Draw ceiling
    figure.line(
        source.data["x"],
        [node_count] * len(source.data["x"]),
        color="red",
        line_width=2,
    )
Esempio n. 8
0
    def bscoreCumulative(self, figurename, dataname):
        """-----------------------------------------------------------------------------------------
        Bokeh plot of cumulative distribution as a line on right hand axis

        :param figurename: string, name of figures (stored in self.figure)
        :param dataname: string, name of data frame (stored in self.frame)
        :return: True
        -----------------------------------------------------------------------------------------"""
        data = self.frame[dataname]
        figure = self.figure[figurename]

        source = ColumnDataSource(data)

        figure.extra_y_ranges = {"cumulative": Range1d(start=0.0, end=1.0)}
        axis2 = LinearAxis(y_range_name="cumulative")
        axis2.ticker.num_minor_ticks = 10
        figure.add_layout(axis2, 'right')
        figure.line(source=source,
                    x='score',
                    y='cumulative',
                    y_range_name='cumulative',
                    line_width=2,
                    color='#1122cc')

        # shaded box showing 95% level
        box = BoxAnnotation(bottom=0.95,
                            top=1.0,
                            y_range_name='cumulative',
                            fill_color='#FFBBBB',
                            line_width=3,
                            line_dash='dashed')
        figure.add_layout(box)

        return True
Esempio n. 9
0
def bokeh_draw_court(figure, line_width=1, line_color='gray'):
    """Returns a figure with the basketball court lines drawn onto it"""

    # hoop
    figure.circle(x=0, y=0, radius=7.5, fill_alpha=0,
                  line_color=line_color, line_width=line_width)

    # backboard
    figure.line(x=range(-30,31), y=-7.5, line_color=line_color)

    # The paint
    # outerbox
    figure.rect(x=0, y=47.5, width=160, height=190,fill_alpha=0, 
                line_color=line_color, line_width=line_width)
    # innerbox
    # left inner box line
    figure.line(x=-60, y=np.arange(-47.5, 143.5), line_color=line_color,
                line_width=line_width)
    # right inner box line
    figure.line(x=60, y=np.arange(-47.5, 143.5), line_color=line_color,
                line_width=line_width)

    # Restricted Zone
    figure.arc(x=0, y=0, radius=40, start_angle=pi, end_angle=0,
               line_color=line_color, line_width=line_width)

    # top free throw arc
    figure.arc(x=0, y=142.5, radius=60, start_angle=pi, end_angle=0,
               line_color=line_color)

    # bottome free throw arc
    figure.arc(x=0, y=142.5, radius=60, start_angle=0, end_angle=pi,
               line_color=line_color, line_dash="dashed")

    # Three point line
    # corner three point lines
    figure.line(x=-220, y=np.arange(-47.5, 92.5), line_color=line_color,
                line_width=line_width)
    figure.line(x=220, y=np.arange(-47.5, 92.5), line_color=line_color,
                line_width=line_width)
    # # three point arc
    figure.arc(x=0, y=0, radius=237.5, start_angle=3.528, end_angle=-0.3863,
               line_color=line_color, line_width=line_width)

    # add center court
    # outer center arc
    figure.arc(x=0, y=422.5, radius=60, start_angle=0, end_angle=pi,
               line_color=line_color, line_width=line_width)
    # inner center arct
    figure.arc(x=0, y=422.5, radius=20, start_angle=0, end_angle=pi,
               line_color=line_color, line_width=line_width)


    # outer lines, consistting of half court lines and out of bounds
    # lines
    figure.rect(x=0, y=187.5, width=500, height=470, fill_alpha=0,
                line_color=line_color, line_width=line_width)
    
    return figure
Esempio n. 10
0
def bokeh_draw_court(figure, line_width=1, line_color='gray'):
    """Returns a figure with the basketball court lines drawn onto it"""

    # hoop
    figure.circle(x=0, y=0, radius=7.5, fill_alpha=0,
                  line_color=line_color, line_width=line_width)

    # backboard
    figure.line(x=range(-30,31), y=-7.5, line_color=line_color)

    # The paint
    # outerbox
    figure.rect(x=0, y=47.5, width=160, height=190,fill_alpha=0, 
                line_color=line_color, line_width=line_width)
    # innerbox
    # left inner box line
    figure.line(x=-60, y=np.arange(-47.5, 143.5), line_color=line_color,
                line_width=line_width)
    # right inner box line
    figure.line(x=60, y=np.arange(-47.5, 143.5), line_color=line_color,
                line_width=line_width)

    # Restricted Zone
    figure.arc(x=0, y=0, radius=40, start_angle=pi, end_angle=0,
               line_color=line_color, line_width=line_width)

    # top free throw arc
    figure.arc(x=0, y=142.5, radius=60, start_angle=pi, end_angle=0,
               line_color=line_color)

    # bottome free throw arc
    figure.arc(x=0, y=142.5, radius=60, start_angle=0, end_angle=pi,
               line_color=line_color, line_dash="dashed")

    # Three point line
    # corner three point lines
    figure.line(x=-220, y=np.arange(-47.5, 92.5), line_color=line_color,
                line_width=line_width)
    figure.line(x=220, y=np.arange(-47.5, 92.5), line_color=line_color,
                line_width=line_width)
    # # three point arc
    figure.arc(x=0, y=0, radius=237.5, start_angle=3.528, end_angle=-0.3863,
               line_color=line_color, line_width=line_width)

    # add center court
    # outer center arc
    figure.arc(x=0, y=422.5, radius=60, start_angle=0, end_angle=pi,
               line_color=line_color, line_width=line_width)
    # inner center arct
    figure.arc(x=0, y=422.5, radius=20, start_angle=0, end_angle=pi,
               line_color=line_color, line_width=line_width)


    # outer lines, consistting of half court lines and out of bounds
    # lines
    figure.rect(x=0, y=187.5, width=500, height=470, fill_alpha=0,
                line_color=line_color, line_width=line_width)
    
    return figure
Esempio n. 11
0
def render_node_network_connections(figure: Figure, df: pd.DataFrame):
    connections_series = df[NETWORK_CONNECTIONS_KEY]
    connections = resample(connections_series, df[DATETIME_KEY])
    figure.y_range = Range1d(0, connections_series.max() + 10)

    figure.add_tools(HoverTool(tooltips=[("Connection count", "@count")]))
    data = ColumnDataSource(dict(count=connections, x=connections.index))
    figure.line(x="x", y="count", legend_label="Network connections", source=data)
Esempio n. 12
0
def render_node_mem_pct_utilization(figure: Figure, df: pd.DataFrame):
    mem = resample(df[MEM_KEY], df[DATETIME_KEY])
    figure.yaxis[0].formatter = NumeralTickFormatter(format="0 %")
    figure.y_range = Range1d(0, 1)

    figure.add_tools(HoverTool(tooltips=[("Memory", "@mem")]))

    data = ColumnDataSource(dict(mem=mem / 100.0, x=mem.index))
    figure.line(x="x", y="mem", color="red", legend_label="Memory", source=data)
Esempio n. 13
0
def addPlotsToFigure(figure, section):
    """
    Add lines or scatter to the figure
    """

    try:
        figure.xaxis.ticker.desired_num_ticks = 30

    except AttributeError as err:
        logging.info(f"AttributeError: {err}")
        print("bokeh package needs to be updated (pip install bokeh -U)")
        sys.exit()

    for i, column in enumerate(plotObject.plots[section]["columns"]):

        # assert that it is present in dataframe
        if column not in plotObject.data.columns:
            logging.info(f"Column not found: {column}")
            continue

        # get boolean with rows without na. Only those will be plotted
        bool_not_na = (~pd.isna(plotObject.data.loc[:, column])).to_list()

        if re.search(r"^line$", plotObject.plots[section]['plotType'][i],
                     re.IGNORECASE):
            # If line...
            figure.line(
                plotObject.data.loc[bool_not_na,
                                    plotObject.plots[section]['x_axis']],
                plotObject.data.loc[bool_not_na, column],
                line_width=2,
                color=d3['Category20'][20][plotObject.color],
                legend_label=column,
                name=column)

        elif re.search(r"^scatter$", plotObject.plots[section]['plotType'][i],
                       re.IGNORECASE):
            # If scatter...
            figure.circle(
                plotObject.data.loc[bool_not_na,
                                    plotObject.plots[section]['x_axis']],
                plotObject.data.loc[bool_not_na, column],
                size=1,
                color=d3['Category20'][20][plotObject.color],
                legend_label=column,
                name=column)

        # Change color for the next plot
        plotObject.color += 2 if plotObject.color < 18 else 17

    # plot threshold
    figure = plot_threshold(figure, section)

    # plot peaks of interest
    figure = plot_pleak(figure, section)

    return figure
Esempio n. 14
0
def second_limit(H_fit1_file, H_fit2_df, figure=None):
    Xs2 = np.asarray(v_serie)
    Xs2 = 1 / Xs2
    Ys2 = H_fit1_file.to_numpy()
    Ys2 = np.array(Ys2, dtype='float')

    # Main loop for 2nd extrapolation and plotting the figure
    for T2 in np.arange(0, len(T_serie), 1):
        poly_X = np.append(
            Xs2, 0)  # Adding a 0 to the X set to have the value at this point

        if len(v_serie) > 1:  # Fit only if there are enough points to do so.
            coeff_poly = np.polyfit(
                Xs2, Ys2[:, T2],
                fit_order_2)  # Fitting a 4th order polynom on the data
            poly_Y = np.polyval(
                coeff_poly, poly_X
            )  # Calculating the values for each point and get the value at 0
            # The point at X=0 is at the end of the array, putting it at the right place in the dataframe.

            H_fit2_df.iloc[[0], [T2]] = poly_Y[-1]

        else:  # If only one point, just take the value of the point.
            H_fit2_df.iloc[[0], [T2]] = Ys2[[0], [T2]]
            poly_Y = np.concatenate((Ys2[[0], [T2]], Ys2[[0], [T2]]))

        if figure != None:
            figure.square(
                Xs2,
                Ys2[:, T2],  # Data points
                legend_label="T Values",
                line_width=1,
                color='black',
                size=10,
                fill_color='white')

            figure.line(
                poly_X,
                poly_Y,  # Lines to check the quality of the fit.
                legend_label="Fit",
                line_width=2,
                color=colors[T2])

            figure.diamond(0,
                           poly_Y[-1],
                           line_width=1,
                           color='black',
                           size=15,
                           fill_color='white')
    return H_fit2_df
Esempio n. 15
0
def render_node_per_cpu_pct_utilization(figure: Figure, df: pd.DataFrame):
    time = df[DATETIME_KEY]
    cpu_series = df[CPU_KEY]

    cpu_count = len(cpu_series.iloc[0])
    cpus = [
        resample(cpu_series.apply(lambda res: res[i]), time) for i in range(cpu_count)
    ]
    cpu_mean = resample(cpu_series.apply(lambda res: average(res)), time)

    figure.yaxis[0].formatter = NumeralTickFormatter(format="0 %")
    figure.y_range = Range1d(0, 1)

    data = {}
    tooltips = []

    for (i, cpu) in enumerate(cpus):
        key = f"cpu_{i}"
        data[key] = cpu / 100.0
        data[f"{key}_x"] = cpu.index
        tooltips.append((f"CPU #{i}", f"@{key}"))

    data["cpu_mean"] = cpu_mean / 100.0
    data["cpu_mean_x"] = cpu_mean.index
    tooltips.append(("CPU avg.", "@cpu_mean"))

    figure.add_tools(HoverTool(tooltips=tooltips))

    data = ColumnDataSource(data)

    colors = select_colors(cpus)
    for (i, color) in enumerate(colors):
        figure.line(
            x=f"cpu_{i}_x",
            y=f"cpu_{i}",
            color=color,
            legend_label=f"CPU #{i}",
            source=data,
        )

    figure.line(
        x="cpu_mean_x",
        y="cpu_mean",
        color="red",
        legend_label="Average CPU",
        line_dash="dashed",
        line_width=5,
        source=data,
    )
Esempio n. 16
0
def plot_threshold(figure, section):
    '''
    Plot thresholds
    '''

    min_mz = np.min(plotObject.data.loc[:, plotObject.plots[section]['x_axis']])
    max_mz = np.max(plotObject.data.loc[:, plotObject.plots[section]['x_axis']])

    x_axis = (min_mz, max_mz)

    for threshold_i in plotObject.plots[section]['threshold']:
        y_axis = np.ones_like(x_axis)*threshold_i
        figure.line(x_axis, y_axis, line_color='black', line_dash="4 4", name="Threshold")

    return figure
Esempio n. 17
0
    def make_new_graph(self):
        """
        Creates a new set of graphs.
        """
        self.active_lines = {}
        legend_strings = []
        figure = default_figure(self.get_figure_opts())

        for y, i in zip(self.key_group, range(len(self.key_group))):
            print("make_new_graph(): plotting {}".format(y))

            if y == self.indep_var:
                print("make_new_graph(): y={} is the indep var".format(y))
                continue

            print("make_new_graph(): y={} is a dep var".format(y))

            # storing the line renderer objects will allow us to update the
            # lines without triggering a page redraw
            line = figure.line(self.indep_var, y, source=self.source,
                    color=self.colors[i], line_width=1.5)
            self.active_lines[y] = line
            legend_strings.append((y, [line]))

        l = Legend(legends=legend_strings, location=(0, 0))
        figure.add_layout(l, 'right')
        return figure
Esempio n. 18
0
def third_limit(H_fit2_file, figure=None):
    Xs3 = np.asarray(
        T_serie) * 1  # sampling value to get the T in s (sampling is 0.001)
    Xs3 = 1 / Xs3
    Ys3 = H_fit2_file.to_numpy()
    Ys3 = Ys3.reshape(
        len(Xs3)) * Xs3  # Ys3 is a 2 dimensional array with only one row.

    if figure != None:
        figure.diamond(Xs3,
                       Ys3,
                       legend_label="R",
                       line_width=1,
                       color='black',
                       size=15,
                       fill_color='white')

    Xs3 = Xs3[:n_points]
    Ys3 = Ys3[:n_points]

    coeff_poly = np.polyfit(
        Xs3, Ys3, fit_order_3)  # Linear fit on the data in the paper.
    poly_X = np.append(
        Xs3, 0)  # Adding a 0 to the X set to have the value at this point.
    poly_Y = np.polyval(
        coeff_poly,
        poly_X)  # Calculating the values for each point and get the value at 0
    # The point at X=0 is at the end of the array.
    R = poly_Y[-1]

    if figure != None:
        figure.line(poly_X,
                    poly_Y,
                    legend_label="R= " + "{:6.4f}".format(R),
                    line_width=2,
                    color='red')
        figure.legend.location = "bottom_right"

    return R
Esempio n. 19
0
        def draw_bytes(title, read_col, write_col):
            if resources.iloc[0].get(read_col) is None or resources.iloc[
                    0].get(write_col) is None:
                return

            def accumulate(column):
                values = resources.apply(lambda res: res[column])
                values = values - values.min()
                return resample(values, time)

            read = accumulate(read_col)
            write = accumulate(write_col)

            figure.yaxis[0].formatter = NumeralTickFormatter(format="0.0b")
            figure.line(read.index,
                        read,
                        color="blue",
                        legend_label="{} RX".format(title))
            figure.line(write.index,
                        write,
                        color="red",
                        legend_label="{} TX".format(title))
Esempio n. 20
0
def bokeh_draw_court(figure, line_color='gray', line_width=1):
    """Returns a figure with the basketball court lines drawn onto it
    This function draws a court based on the x and y-axis values that the NBA
    stats API provides for the shot chart data.  For example the center of the
    hoop is located at the (0,0) coordinate.  Twenty-two feet from the left of
    the center of the hoop in is represented by the (-220,0) coordinates.
    So one foot equals +/-10 units on the x and y-axis.
    Parameters
    ----------
    figure : Bokeh figure object
        The Axes object to plot the court onto.
    line_color : str, optional
        The color of the court lines. Can be a a Hex value.
    line_width : float, optional
        The linewidth the of the court lines in pixels.
    Returns
    -------
    figure : Figure
        The Figure object with the court on it.
    """

    # hoop
    figure.circle(x=0,
                  y=0,
                  radius=7.5,
                  fill_alpha=0,
                  line_color=line_color,
                  line_width=line_width)

    # backboard
    figure.line(x=range(-30, 31), y=-12.5, line_color=line_color)

    # The paint
    # outerbox
    figure.rect(x=0,
                y=47.5,
                width=160,
                height=190,
                fill_alpha=0,
                line_color=line_color,
                line_width=line_width)
    # innerbox
    # left inner box line
    figure.line(x=-60,
                y=np.arange(-47.5, 143.5),
                line_color=line_color,
                line_width=line_width)
    # right inner box line
    figure.line(x=60,
                y=np.arange(-47.5, 143.5),
                line_color=line_color,
                line_width=line_width)

    # Restricted Zone
    figure.arc(x=0,
               y=0,
               radius=40,
               start_angle=pi,
               end_angle=0,
               line_color=line_color,
               line_width=line_width)

    # top free throw arc
    figure.arc(x=0,
               y=142.5,
               radius=60,
               start_angle=pi,
               end_angle=0,
               line_color=line_color)

    # bottome free throw arc
    figure.arc(x=0,
               y=142.5,
               radius=60,
               start_angle=0,
               end_angle=pi,
               line_color=line_color,
               line_dash="dashed")

    # Three point line
    # corner three point lines
    figure.line(x=-220,
                y=np.arange(-47.5, 92.5),
                line_color=line_color,
                line_width=line_width)
    figure.line(x=220,
                y=np.arange(-47.5, 92.5),
                line_color=line_color,
                line_width=line_width)
    # # three point arc
    figure.arc(x=0,
               y=0,
               radius=237.5,
               start_angle=3.528,
               end_angle=-0.3863,
               line_color=line_color,
               line_width=line_width)

    # add center court
    # outer center arc
    figure.arc(x=0,
               y=422.5,
               radius=60,
               start_angle=0,
               end_angle=pi,
               line_color=line_color,
               line_width=line_width)
    # inner center arct
    figure.arc(x=0,
               y=422.5,
               radius=20,
               start_angle=0,
               end_angle=pi,
               line_color=line_color,
               line_width=line_width)

    # outer lines, consistting of half court lines and out of bounds lines
    figure.rect(x=0,
                y=187.5,
                width=500,
                height=470,
                fill_alpha=0,
                line_color=line_color,
                line_width=line_width)

    return figure
Esempio n. 21
0
def first_limit(H_file, H_fit1_df, figure=None):
    for value_v in iterate_on_v:

        # Selecting each subset of the dataframe corresponding to the desired v value.
        H_subset = H_file[H_file['v_value'] == v_serie[value_v]]

        # Shifting to numpy for the fit.
        H_np_subset = H_subset.to_numpy()

        # Building all the Xs values for the fits. Repetition of the same array, as the X values are all the same.
        Xs = H_np_subset[:, 1]  # Size values are the 2nd column, index = 1
        Xs = 1 / Xs  # Inverting the values as the graph shows 1/size
        poly_X = np.insert(
            Xs, 0,
            0)  # Adding a 0 to the X set to have the value at this point

        # Hard coded indexes to take all the T_values, should be ok as long as I do not change the dataframe structure
        H_Ys = H_np_subset[:, 2:np.shape(H_np_subset)[1]]

        # Creating a figure for the desired v value.
        if (v_serie[value_v] == watch_v and figure != None):
            ListY = H_Ys.T.tolist()

            for plots in np.arange(0, len(ListY), 1):
                figure.circle(Xs,
                              ListY[plots],
                              legend_label="All T For v=" + str(watch_v),
                              line_width=1,
                              color='black',
                              size=10,
                              fill_color='white')

        #This is the main loop, populating the array with the fitted values
        for T in np.arange(0, len(T_serie), 1):
            if len(s_serie
                   ) > 1:  # Fit only if there are enough points to do so.

                H_coeff_poly = np.polyfit(
                    Xs, H_Ys[:,
                             T], fit_order_1)  # Fitting a polynom on the data
                H_poly_Y = np.polyval(
                    H_coeff_poly, poly_X
                )  # Calculating the values for each point and get the value at 0

                # The point at X=0 is at the beginning of the array, putting it at the right place in the dataframe.
                H_fit1_df.iloc[[value_v], [T]] = H_poly_Y[0]

            else:  # If only one point, just take the value of the point.
                H_fit1_df.iloc[[value_v], [T]] = H_Ys[:, T]
                H_poly_Y = H_Ys[:, T]

            # Showing the fit for the desired v_value
            if (v_serie[value_v] == watch_v and figure != None):
                figure.line(
                    poly_X,
                    H_poly_Y,  # Adding points to check the quality of the fit.
                    legend_label="Fits",
                    line_width=2,
                    color=colors[T])

                figure.square(0,
                              H_poly_Y[0],
                              line_width=1,
                              color='black',
                              size=10,
                              fill_color='white')

    return H_fit1_df
Esempio n. 22
0
    def _draw_court(self, figure, line_width=1):
        import numpy as np
        pi = 3.14
        # hoop
        figure.circle(x=0,
                      y=0,
                      radius=7.5,
                      fill_alpha=0,
                      line_color=self.f_color,
                      line_width=line_width)

        # backboard
        figure.line(x=range(-30, 31), y=-12.5, line_color=self.f_color)

        # The paint
        # outerbox
        figure.rect(x=0,
                    y=47.5,
                    width=160,
                    height=190,
                    fill_alpha=0,
                    line_color=self.f_color,
                    line_width=line_width)
        # innerbox
        # left inner box line
        figure.line(x=-60,
                    y=np.arange(-47.5, 143.5),
                    line_color=self.f_color,
                    line_width=line_width)
        # right inner box line
        figure.line(x=60,
                    y=np.arange(-47.5, 143.5),
                    line_color=self.f_color,
                    line_width=line_width)

        # Restricted Zone
        figure.arc(x=0,
                   y=0,
                   radius=40,
                   start_angle=pi,
                   end_angle=0,
                   line_color=self.f_color,
                   line_width=line_width)

        # top free throw arc
        figure.arc(x=0,
                   y=142.5,
                   radius=60,
                   start_angle=pi,
                   end_angle=0,
                   line_color=self.f_color)

        # bottome free throw arc
        figure.arc(x=0,
                   y=142.5,
                   radius=60,
                   start_angle=0,
                   end_angle=pi,
                   line_color=self.f_color,
                   line_dash="dashed")

        # Three point line
        # corner three point lines
        figure.line(x=-220,
                    y=np.arange(-47.5, 92.5),
                    line_color=self.f_color,
                    line_width=line_width)
        figure.line(x=220,
                    y=np.arange(-47.5, 92.5),
                    line_color=self.f_color,
                    line_width=line_width)
        # # three point arc
        figure.arc(x=0,
                   y=0,
                   radius=237.5,
                   start_angle=3.528,
                   end_angle=-0.3863,
                   line_color=self.f_color,
                   line_width=line_width)

        return figure
Esempio n. 23
0
        x_values.append(walk[0])
        y_values.append(walk[1])
        path.append(walk)

    min_distance = min(distances)
    max_distance = max(distances)

    distances_length = len(distances)
    distances_sum = 0
    for i in distances:
        distances_sum += i

    avg_distance = int(distances_sum / distances_length)

    print(path)
    print(f'Minimun distance: {min_distance}')
    print(f'Maximun distance: {max_distance}')
    print(f'average distance: {avg_distance}')

    return x_values, y_values


if __name__ == "__main__":
    number_steps = int(input('How many steps do you want to walk: '))
    number_reps = int(input('How many reps do you want to do: '))
    main(number_steps, number_reps)
    output_file('simple__graphic.html')
    figure = figure()
    figure.line(x_values, y_values, line_width=2)
    show(figure)
Esempio n. 24
0
def bokeh_draw_court(figure, line_color='gray', line_width=1):
    """Returns a figure with the basketball court lines drawn onto it

    This function draws a court based on the x and y-axis values that the NBA
    stats API provides for the shot chart data.  For example the center of the
    hoop is located at the (0,0) coordinate.  Twenty-two feet from the left of
    the center of the hoop in is represented by the (-220,0) coordinates.
    So one foot equals +/-10 units on the x and y-axis.

    Parameters
    ----------
    figure : Bokeh figure object
        The Axes object to plot the court onto.
    line_color : str, optional
        The color of the court lines. Can be a a Hex value.
    line_width : float, optional
        The linewidth the of the court lines in pixels.

    Returns
    -------
    figure : Figure
        The Figure object with the court on it.

    """

    # hoop
    figure.circle(x=0, y=0, radius=7.5, fill_alpha=0,
                  line_color=line_color, line_width=line_width)

    # backboard
    figure.line(x=range(-30, 31), y=-12.5, line_color=line_color)

    # The paint
    # outerbox
    figure.rect(x=0, y=47.5, width=160, height=190, fill_alpha=0,
                line_color=line_color, line_width=line_width)
    # innerbox
    # left inner box line
    figure.line(x=-60, y=np.arange(-47.5, 143.5), line_color=line_color,
                line_width=line_width)
    # right inner box line
    figure.line(x=60, y=np.arange(-47.5, 143.5), line_color=line_color,
                line_width=line_width)

    # Restricted Zone
    figure.arc(x=0, y=0, radius=40, start_angle=pi, end_angle=0,
               line_color=line_color, line_width=line_width)

    # top free throw arc
    figure.arc(x=0, y=142.5, radius=60, start_angle=pi, end_angle=0,
               line_color=line_color)

    # bottome free throw arc
    figure.arc(x=0, y=142.5, radius=60, start_angle=0, end_angle=pi,
               line_color=line_color, line_dash="dashed")

    # Three point line
    # corner three point lines
    figure.line(x=-220, y=np.arange(-47.5, 92.5), line_color=line_color,
                line_width=line_width)
    figure.line(x=220, y=np.arange(-47.5, 92.5), line_color=line_color,
                line_width=line_width)
    # # three point arc
    figure.arc(x=0, y=0, radius=237.5, start_angle=3.528, end_angle=-0.3863,
               line_color=line_color, line_width=line_width)

    # add center court
    # outer center arc
    figure.arc(x=0, y=422.5, radius=60, start_angle=0, end_angle=pi,
               line_color=line_color, line_width=line_width)
    # inner center arct
    figure.arc(x=0, y=422.5, radius=20, start_angle=0, end_angle=pi,
               line_color=line_color, line_width=line_width)

    # outer lines, consistting of half court lines and out of bounds lines
    figure.rect(x=0, y=187.5, width=500, height=470, fill_alpha=0,
                line_color=line_color, line_width=line_width)

    return figure
Esempio n. 25
0
    def draw(args, figure):
        node, frame, method = args
        time = frame["datetime"]
        resources = frame["resources"]

        if method == "cpu":
            figure.plot_width = 950
            figure.plot_height = 400
        else:
            figure.plot_width = 950
            figure.plot_height = 400

        figure.min_border_right = 20

        if method in ("cpu", "mem"):
            figure.y_range = Range1d(0, 1)

        if len(resources) == 0:
            return

        def draw_bytes(title, read_col, write_col):
            if resources.iloc[0].get(read_col) is None or resources.iloc[
                    0].get(write_col) is None:
                return

            def accumulate(column):
                values = resources.apply(lambda res: res[column])
                values = values - values.min()
                return resample(values, time)

            read = accumulate(read_col)
            write = accumulate(write_col)

            figure.yaxis[0].formatter = NumeralTickFormatter(format="0.0b")
            figure.line(read.index,
                        read,
                        color="blue",
                        legend_label="{} RX".format(title))
            figure.line(write.index,
                        write,
                        color="red",
                        legend_label="{} TX".format(title))

        if method == "cpu":
            cpu_count = len(resources.iloc[0]["cpu"])
            cpus = [
                resample(resources.apply(lambda res: res["cpu"][i]), time)
                for i in range(cpu_count)
            ]
            cpu_mean = resample(
                resources.apply(lambda res: average(res["cpu"])), time)

            processes = (process_name(p) for p in report.cluster.nodes[node]
                         if process_name(p))
            figure.title = Title(
                text="{}: {}".format(node, ",".join(processes)))

            figure.yaxis[0].formatter = NumeralTickFormatter(format="0 %")

            palette = d3["Category20"][20]
            for (i, cpu) in enumerate(cpus):
                color = palette[i % 20]
                figure.line(cpu.index,
                            cpu / 100.0,
                            color=color,
                            legend_label=f"CPU #{i}")
            figure.line(cpu_mean.index,
                        cpu_mean / 100.0,
                        color="red",
                        legend_label=f"Average CPU",
                        line_dash="dashed",
                        line_width=5)
        elif method == "mem":
            mem = resample(resources.apply(lambda res: res["mem"]), time)
            figure.yaxis[0].formatter = NumeralTickFormatter(format="0 %")
            figure.line(mem.index,
                        mem / 100.0,
                        color="red",
                        legend_label="Memory")
        elif method == "network":
            draw_bytes("Net", "net-read", "net-write")
        elif method == "net-connections":
            connections = resample(
                resources.apply(lambda res: res["connections"]), time)
            figure.line(connections.index,
                        connections,
                        legend_label="Network connections")
        elif method == "io":
            draw_bytes("Disk", "disk-read", "disk-write")