예제 #1
0
def temp_20(state):
    
    # dashed line to show corn dies above 43
    hline = hv.HLine(43)
    hline.opts(
    color='green', 
    line_dash='dashed', 
    line_width=2.0)
    
    # dashed line to show corn dies below 0
    lline = hv.HLine(0)
    lline.opts(
    color='green', 
    line_dash='dashed', 
    line_width=2.0)
    
    return temp_df.hvplot.scatter(
        width=900,
        height=400,
        y=[f'TMIN_{state}', f'TMAX_{state}'],
        title=f'{state}', 
        xlabel='Year',
        ylabel='Temperature (C)',
        groupby='Year'
    ).opts(shared_axes=False)* hline*lline
 def h_line(data): #function to draw line
     try:
         hline=hv.HLine(data['y'][0])
         return hline
     except:
         hline=hv.HLine(0)
         return hline
예제 #3
0
def scatter_plot_4(df):
    """ Produce a scatter plot of
    'expected_gain' vs 'date'
    """
    kdims = ['zillow_last_sold_price']
    vdims = ['estimated_to_sold_diff']
    data = hv.Dataset(df, kdims, vdims)
    crv = data.to(hv.Scatter, 'zillow_last_sold_price',
                  'estimated_to_sold_diff')
    crv *= hv.HLine(0)
    crv *= hv.HLine(1E5)
    crv *= hv.HLine(2E5)
    return crv
예제 #4
0
def revenue_noise_std(org, color):
    '''Create a line chart to show weekly revenue noise standard deviation'''

    df_model = df[['date', 'tiktok', 'youtube']].groupby('date').sum()
    noise, _ = sm.tsa.filters.hpfilter(df_model[org])

    return noise.hvplot(), hv.HLine(noise.sum() + noise.std()).opts(
        color=color,
        line_dash='dashed',
        line_width=2.0,
        yformatter=NumeralTickFormatter(format="0.0a"),
        shared_axes=False), hv.HLine(noise.sum() - noise.std()).opts(
            color=color, line_dash='dashed', line_width=2.0, shared_axes=False)
예제 #5
0
def smoothed_ratio(df, raw='new', gamma=GAMMA, stds=[STD],
                   title='Inter-day ratio'):
    """Plots a smoothed-count ratio and its implicit gamma bound.

    The value of the infectious-period parameter `gamma` implies a lower bound
    on the rate at which the number of new infections can decrease. This plot
    shows this rate, which will ideally remain above the bound.
    """
    df = df.copy()
    bound = np.exp(-gamma)
    mn, mx = bound, bound
    smths = [f'smoothed {std}' for std in stds]
    ratios = [f'σ = {std:.1f}' for std in stds]
    for std, smth, ratio in zip(stds, smths, ratios):
        smooth(df, raw=raw, smth=smth, std=std)
        # We add one to the observed value k to account for the fact that
        # according to the bound, the least tolerable value might be between k
        # and k+1 (i.e., for the same reason we applied the floor operation in
        # the difference-plot function).
        df[ratio] = (df[smth] + 1)/df[smth].shift()
        mn, mx = min(mn, df[ratio].min()), max(mx, df[ratio].max())
    ylim = (mn - 0.1*(mx-mn), mx + 0.1*(mx-mn))
    return df.hvplot.line(
        x='date', y=ratios, ylim=ylim, legend='top_right'
    ).opts(title=title) \
        * hv.HLine(bound)
예제 #6
0
 def marker(x, y):
     x_dim = {image.kdims[0].label: x}
     y_dim = {image.kdims[1].label: y}
     crosssection1 = image.sample(**x_dim).opts(norm=dict(framewise=True))
     crosssection1y = image.sample(**y_dim).opts(norm=dict(framewise=True))
     return hv.Layout(image * hv.VLine(x) * hv.HLine(y) + crosssection1 +
                      crosssection1y).cols(2).opts(norm=dict(axiwise=True))
예제 #7
0
 def load_indices(Index): 
     #scatter = hv.Scatter(multi_df[Index], kdims = ['JDK_RS_ratio', 'JDK_RS_momentum'])
     scatter = hv.Scatter(multi_df[Index], kdims = ['JDK_RS_momentum'])
     
     ##Colors
     explicit_mapping = {'Leading': 'green', 'Lagging': 'yellow', 'Weakening': 'red', 'Improving': 'blue'}
     ##Plot Joining all together
     scatter = scatter.opts(opts.Scatter(tools=['hover'], height = 500, width=500, size = 10, xlim = x_range, ylim = y_range,
                                         color = 'Quadrant', cmap=explicit_mapping,
                                        ))
     
     ##Line connecting the dots
     #curve = hv.Curve(multi_df[Index], kdims = ['JDK_RS_ratio', 'JDK_RS_momentum'])
     curve = hv.Curve(multi_df[Index], kdims = [ 'JDK_RS_momentum'])
     curve = curve.opts(opts.Curve(color = 'black', line_width = 1))
 
     ##Vertical and Horizontal Lines
     vline = hv.VLine(100).opts(color = 'black', line_width = 1)
     hline = hv.HLine(100).opts(color = 'black', line_width = 1)    
 
 
     #All Together
 
     full_scatter = scatter * vline * hline * curve
     full_scatter = full_scatter.opts(legend_cols= True)
 
     return full_scatter
예제 #8
0
 def cross_hair_info(x, y):
     text = hv.Text(x + 0.05,
                    y,
                    "%.3f %.3f %.3f" % (x, y, img[x, y]),
                    halign="left",
                    valign="bottom")
     return hv.HLine(y) * hv.VLine(x) * text
예제 #9
0
    def redeemable_plot(self):
        # Limits the target raise bounds when ploting the charts
        self.bounds_target_raise()
        df_hatch_params_to_plot = self.output_scenarios()
        # Drop NaN rows
        df_hatch_params_to_plot = df_hatch_params_to_plot.dropna()
        with pd.option_context('mode.chained_assignment', None):
            df_hatch_params_to_plot['Redeemable'] = df_hatch_params_to_plot['Redeemable'].mul(100)
        redeemable_plot = df_hatch_params_to_plot.hvplot.area(title='Redeemable (%)',
                                                              x='Total XDAI Raised',
                                                              y='Redeemable',
                                                              xformatter='%.0f',
                                                              yformatter='%.1f',
                                                              hover=True,
                                                              ylim=(0, 100),
                                                              xlim=self.config_bounds['min_max_raise']['xlim']
                                                              ).opts(axiswise=True)
        try:
            redeemable_target = df_hatch_params_to_plot[df_hatch_params_to_plot['Total XDAI Raised'] >= self.target_raise].iloc[0]['Redeemable']
        except:
            redeemable_target = 0
        
        with param.edit_constant(self):
            self.target_redeemable = round(redeemable_target, 2)

        return redeemable_plot * hv.VLine(self.target_raise).opts(color='#E31212') * hv.HLine(redeemable_target).opts(color='#E31212')
예제 #10
0
def covid_viewer_v2(ds):
    '''
    covid viewer, for actives_vs_beds
    '''
    opts.defaults(
        opts.Curve(tools=['hover'], width=800, height = 600, ylabel='')
    )
    logtog = pn.widgets.Toggle(name='Log (Y-axis)', button_type='default', value=False)
    xlim=(np.datetime64('2020-03-01'), np.datetime64('2020-03-25'))


    hv_ds = hv.Dataset(ds, ['date', 'place'], ['active_per_beds'])
    avb = hv_ds.to(hv.Curve, 'date', 'active_per_beds').overlay('place').opts(
        legend_position='top_left', shared_axes=True,
        ylim=(0, 0.13),
        xlim=xlim, title='Severe Cases per Open Hospital Bed')
    avb_log = hv_ds.to(hv.Curve, 'date', 'active_per_beds').overlay('place').opts(
        legend_position='top_left', shared_axes=True, logy=True,
        ylim=(1e-6, 10),
        xlim=xlim, title='Severe Cases per Open Hospital Bed (Log Scale)')
    max_line = hv.HLine(1).opts( opts.HLine(color='red', line_width=6),
                                opts.Points(color='#D3D3D3'))


    # layout = (avb_log)
    # layout.opts(
    #     opts.Curve(width=400, height=300, framewise=True))
    # pn_layout = pn.pane.HoloViews(layout)
    # return pn.Row(logtog, pn_layout)
    return avb
예제 #11
0
파일: tech.py 프로젝트: rogervs/tec-lab
    def impact_hours_rewards(self):
        expected_raise = self.total_impact_hours * self.raise_horizon
        if expected_raise > self.maximum_raise:
            expected_raise = self.maximum_raise


#         self.param['maximum_raise'].bounds =  (expected_raise, expected_raise * 10)
#         self.param['maximum_raise'].step = expected_raise / 10
#         if self.target_raise > self.maximum_raise:
#             self.target_raise = self.maximum_raise
#         self.param['target_raise'].bounds =  (self.minimum_raise, self.maximum_raise)
#         self.param['target_raise'].step = self.maximum_raise / 100

        x = np.linspace(self.minimum_raise, self.maximum_raise)

        R = self.maximum_impact_hour_rate

        m = self.raise_horizon

        H = self.total_impact_hours

        y = [R * (x / (x + m * H)) for x in x]

        df = pd.DataFrame([x, y]).T
        df.columns = ['Total XDAI Raised', 'Impact Hour Rate']

        try:
            expected_impact_hour_rate = df[
                df['Total XDAI Raised'] >
                expected_raise].iloc[0]['Impact Hour Rate']
        except:
            expected_impact_hour_rate = df['Impact Hour Rate'].max()
        try:
            target_impact_hour_rate = df[
                df['Total XDAI Raised'] >
                self.target_raise].iloc[0]['Impact Hour Rate']
        except:
            target_impact_hour_rate = df['Impact Hour Rate'].max()
        impact_hours_plot = df.hvplot.area(title='Expected and Target Raise',
                                           x='Total XDAI Raised',
                                           xformatter='%.0f',
                                           hover=True)

        return impact_hours_plot * hv.VLine(expected_raise) * hv.HLine(
            expected_impact_hour_rate) * hv.VLine(
                self.target_raise) * hv.HLine(target_impact_hour_rate)
예제 #12
0
 def redeemable(self):
     df_hatch_params = self.output_scenarios()
     # Drop NaN rows
     df_hatch_params_to_plot = df_hatch_params.dropna()
     df_hatch_params_to_plot['Redeemable'] = df_hatch_params_to_plot['Redeemable'] * 100
     redeemable_plot = df_hatch_params_to_plot.hvplot.area(title='Redeemable (%)', x='Total XDAI Raised', y='Redeemable', xformatter='%.0f', yformatter='%.1f', hover=True, ylim=(0, 100), xlim=(0,1000)).opts(axiswise=True)
     redeemable_target = 100 * df_hatch_params[df_hatch_params_to_plot['Total XDAI Raised'] ==self.target_raise].iloc[0]['Redeemable']
     return redeemable_plot * hv.VLine(self.target_raise).opts(color='#E31212') * hv.HLine(redeemable_target).opts(color='#E31212')
def plot_price_diff_holiday_period(        
        pivot_stats:Dict[Text, pd.DataFrame], 
        holiday_key:Text, 
        yr_range:Text, 
    ) -> Tuple:

    '''
    Purpose: 
        Visualise the price change for holiday period. 

    Input  :
        pivot_stats : Str. Ticker symbol.
        holiday_key : Str. Specify the name of the holiday. 
        yr_range    : Str. Year range. 
    
    Return :
        Tuple obj containing the holoview plots.
    '''

    logger.info('Start running (plot_price_diff_holiday_period) function.')

    # Look for the dataframe within the dictionary. 
    pivot_data = pivot_stats['compiled_holiday'] if yr_range == 'max_yr' else pivot_stats[f'compiled_holiday_{yr_range}']
    boo_holiday = pivot_data['holiday_category'] == holiday_key

    # Visualise the price change.
    errorbar = pivot_data.loc[boo_holiday, :].hvplot.errorbars(y='avg_diff', yerr1='std_diff') 
    bar_avg_diff = pivot_data.loc[boo_holiday, :].hvplot(kind='bar', y='avg_diff', width=HV_PN_WIDTH, tools=HV_TOOLS_FOR_TICKER)
    logger.debug('----- Plotted (bar_avg_diff).')

    # Visualise the probability and horizontal lines for probability. 
    upper_prob_hline = hv.HLine(0.7).opts(line_width=1, color='black')
    lower_prob_hline = hv.HLine(0.3).opts(line_width=1, color='black')
    bar_up_prob = pivot_data.loc[boo_holiday, :].hvplot(kind='bar', y='up_prob', width=HV_PN_WIDTH, ylim=(0,1), tools=HV_TOOLS_FOR_TICKER)
    logger.debug('----- Plotted (bar_up_prob).')

    # Visualise up and down counts. 
    bar_counts = pivot_data.loc[boo_holiday, :].hvplot(
        kind='bar', y=['up_counts', 'down_counts'], 
        width=HV_PN_WIDTH, stacked=True, legend='top', tools=HV_TOOLS_FOR_TICKER
    )
    logger.debug('----- Plotted (bar_counts).')

    logger.info('Returning the holoview plot objs for (plot_price_diff_holiday_period).')
    return pivot_data, ( (bar_avg_diff * errorbar), (bar_up_prob * upper_prob_hline * lower_prob_hline), bar_counts )
예제 #14
0
def _show_sunset_hour(df, geoloc):
    hover = HoverTool(tooltips=[
        ('Date', '@datetime{%m/%d}'),
        ('Hour of Sunset', '@hour{0.1f}'),
        ('Length of Day', '@daylight{0.1f}'),
    ],
                      formatters={
                          'datetime': 'datetime',
                      },
                      mode='vline')

    sunset_df = df.copy()
    sunset_df = df.loc[df['sun_down'] == False, :]
    sunset_df = sunset_df.assign(**{
        'hour': sunset_df['hour'] - 12,
        'hour_24': sunset_df['hour_24'] - 12
    })

    lat, lon = geoloc.latitude, geoloc.longitude
    address = geoloc.address
    sunset_curve = sunset_df.hvplot('datetime',
                                    'hour',
                                    hover_cols=['daylight'],
                                    responsive=True)
    sunset_curve = sunset_curve.opts(
        invert_yaxis=True,
        color='darkblue',
        xlabel='Date',
        ylabel='PM Hour of Sunset [Local Time]',
        title=f'Yearly Sunset Hour at {address} ({lat:.1f} N, {lon:.1f} E)',
        hooks=[_format_datetime_axis],
        show_grid=True,
        gridstyle={'ygrid_line_alpha': 0},
        tools=[hover],
        ylim=(4, 9))

    sun_up = hv.Area(df.loc[df['sun_down'] == False], 'datetime', 'hour')
    sun_up = sun_up.opts(color='tan', alpha=0.15, responsive=True)

    sun_down = hv.Area(sunset_df, 'datetime', ['hour', 'hour_24'])
    sun_down = sun_down.opts(color='darkblue', alpha=0.15, responsive=True)

    five_pm_line = hv.HLine(5).opts(color='black',
                                    alpha=0.1,
                                    line_dash='dotted',
                                    responsive=True)

    five_pm_txt = hv.Text(pd.datetime(2020, 7, 4), 5, '5 PM')
    five_pm_txt = five_pm_txt.opts(text_font_size='1.5em',
                                   text_alpha=0.2,
                                   text_baseline='bottom',
                                   text_align='left',
                                   responsive=True)

    overlay = (sunset_curve * sun_up * sun_down * five_pm_line * five_pm_txt)
    return overlay
예제 #15
0
def scatter_plot_3(df):
    """ Produce a scatter plot of 
    'zillow_last_sold_price' vs 'sold_to_estimated_ratio'
    """
    kdims = ['zillow_last_sold_price']
    vdims = ['sold_to_estimated_ratio']
    data = hv.Dataset(df, kdims, vdims)
    crv = data.to(hv.Scatter, 'zillow_last_sold_price',
                  'sold_to_estimated_ratio')
    crv *= hv.HLine(1)
    return crv
예제 #16
0
def reproduction(df, r, c, col='new', a=1, b=3, gamma=GAMMA,
                 title='Effective reproduction number'):
    """Plots estimated reproduction numbers."""
    df = _posterior(df, r, c, col, a, b, gamma)
    return df[df.r >= 0].hvplot.line(
        x='date', y='r', legend='top_right', ylim=(0, df.r.max()+0.5)
    ).opts(title=title) \
        * df[df.r >= 0].hvplot.scatter(
            x='date', y='r', c='r', cmap='bkr', colorbar=False
    ).redim.range(r=(0, 1.5)) \
        * df.hvplot.area(x='date', y='r5', y2='r95', alpha=0.2) \
        * hv.HLine(1)
예제 #17
0
    def graph(self):
        net_tput = pd.DataFrame(data={'Time': self._timestamps, 'Send': self._send_rates,
                                      'Recv': self._recv_rates, 'Total': self._total_rates})
        net_tput['Time'] = net_tput.Time.astype('datetime64[s]')

        net_vdims = [('Recv', 'Throughput')]
        net_ds = hv.Dataset(net_tput, ['Time'], net_vdims)

        net_curve = net_ds.to(hv.Curve, 'Time', 'Recv').options(ylim=(0, self._bandwidth * 1.2))
        overlay =  net_curve * hv.HLine(self._bandwidth)
        overlay.opts(opts.HLine(color='red', line_width=3))
        return overlay
예제 #18
0
 def _plot_threshold(self, y, **kwargs):
     return hv.HLine(
         y,
         group='threshold',
         **kwargs,
     ).options(
         color=self.LATENCY_THRESHOLD_COLOR
     ).options(
         backend='matplotlib',
         linestyle='--',
     ).options(
         backend='bokeh',
         line_dash='dashed',
     )
예제 #19
0
    def plot_orig_capacity(self, cpu: CPU):
        """
        Plot the orig capacity of a CPU onto a given axis

        :param cpu: The CPU
        :type cpu: int
        """
        orig_capacities = self.trace.plat_info['cpu-capacities']['orig']
        return hv.HLine(orig_capacities[cpu], label='orig capacity').options(
            backend='matplotlib',
            linestyle='--',
        ).options(
            backend='bokeh',
            line_dash='dashed',
        )
예제 #20
0
 def update_control_vlines(self, x1: float, x2: float, stroke_count: int,
                           data):
     if None in [x1, x2]:
         x1, x2 = self.vlines_positions
     xs, _, cov = data
     xmin, xmax = np.min(xs), np.max(xs)
     bounds = (xmin, xmin, xmax, xmax)
     hline = hv.VLine(x=x1).opts(color=orange1)
     vline = hv.HLine(y=x2).opts(color=orange2)
     self.vlines_positions = (x1, x2)
     image = hv.Image(np.rot90(cov), bounds=bounds)
     points_3 = hv.Points([(x1, x1), (x2, x2),
                           (x2, x1)]).opts(line_color=blue)
     point = hv.Points([(x1, x2)]).opts(fill_color=orange1,
                                        line_color="white")
     return image * hline * vline * points_3 * point
예제 #21
0
def posterior_diff(df, r, c, col='new', a=1, b=3, gamma=GAMMA,
                   title='Infectious-period bound'):
    """Plots the difference between the inferred rate and a gamma bound.

    This plot provides an indication of whether or not the inferred rates are
    sufficiently smooth; see `smoothed_diff` -- which does the same for
    smoothed, observed counts -- for more details.
    """
    df = _posterior(df, r, c, col, a, b, gamma)
    df['γ bound'] = df.posterior.shift()*np.exp(-gamma)
    df['difference'] = df.posterior - df['γ bound']
    return df.hvplot.line(
        x='date', y=['posterior', 'γ bound', 'difference'],
        line_dash=['dashed', 'dashed', 'solid'], legend='top_left'
    ).opts(title=title) \
        * hv.HLine(np.exp(-gamma))
예제 #22
0
파일: euler.py 프로젝트: yiyulanghuan/demo
def background(func, size=(500, 500)):
    """
    Given the ODE y'=f(x,y),
    
       bg,vec,xaxis_line,yaxis_line = background()
    
    returns a grayscale image of the slopes y',
            a vector field representation of the slopes, and
            a set of axis lines for -5<x<5, -5<y<5
    """

    # compute the data
    vals = np.linspace(-5, 5, num=150)
    X, Y = np.meshgrid(vals, vals)

    clines = func(X, Y)  # f(x,y)
    theta = np.arctan2(clines, 1)  # angle of the slope y' at x,y

    # Obtain the vector field (subsample the grid)
    h, w = size
    vf_opts = dict(size_index=3,
                   height=h,
                   width=w,
                   xticks=9,
                   yticks=9,
                   alpha=0.3,
                   muted_alpha=0.05)
    vec_field = hv.VectorField(
        (vals[::3], vals[::3], theta[::3, ::3], 0 * clines[::3, ::3] + 1),
        label='vector_field').options(**vf_opts)

    # Normalize the given array so that it can be used with the RGB element's alpha channel
    def norm(arr):
        arr = (arr - arr.min())
        return arr / arr.max()

    normXY = norm(clines)
    img_field = hv.RGB( (vals, vals, normXY, normXY, normXY, 0*clines+0.1), vdims=['R','G','B','A'] )\
                .options(width=size[0], height=size[1], shared_axes=False)

    # finally, we add the axes as VLine, HLine and return an array of the plot Elements
    hv_opts = dict(color='k', alpha=0.8, line_width=1.5)
    return [
        img_field, vec_field,
        hv.HLine(0).options(**hv_opts),
        hv.VLine(0).options(**hv_opts)
    ]
예제 #23
0
    def __call__(self, skyplots, **params):

        self.p = param.ParamOverrides(self, params)

        pointer = hv.streams.PointerXY(x=0, y=0)
        cross_opts = dict(style={'line_width': 1, 'color': 'black'})
        cross_dmap = hv.DynamicMap(lambda x, y: (hv.VLine(x).opts(**cross_opts) *
                                                 hv.HLine(y).opts(**cross_opts)), streams=[pointer])
        plots = []
        for s in skyplots:
            if self.p.crosshair:
                plot = (s*cross_dmap).relabel(s.label)
            else:
                plot = s
            plots.append(plot)

        return hv.Layout(plots)
예제 #24
0
    def coordinate_gating(self, df, col1, col2, xlimit, ylimit, type):
        renderer = hv.renderer('bokeh')
        d = {col1: df[col1], col2: df[col2], "category": 0}
        xycols = pd.DataFrame(data=d)

        set1 = []
        set2 = []
        set3 = []
        set4 = []
        for index in range(len(xycols)):
            x = float(xycols[col1][index])
            y = float(xycols[col2][index])
            xlimit = float(xlimit)
            ylimit = float(ylimit)
            if x < xlimit and y > ylimit:
                #xycols["category"][index] = 1
                set1.append((xycols[col1][index], xycols[col2][index]))
            elif x > xlimit and y > ylimit:
                #xycols["category"][index] = 2
                set2.append((xycols[col1][index], xycols[col2][index]))
            elif x < xlimit and y < ylimit:
                #xycols["category"][index] = 3
                set3.append((xycols[col1][index], xycols[col2][index]))
            elif x > xlimit and y < ylimit:
                #xycols["category"][index] = 4
                set4.append((xycols[col1][index], xycols[col2][index]))

        categories = {}
        categories["upper left"] = np.around(100*len(set1)/len(xycols), decimals=2)
        categories["upper right"] = np.around(100*len(set2)/len(xycols), decimals=2)
        categories["bottom left"] = np.around(100*len(set3)/len(xycols), decimals=2)
        categories["bottom right"] = np.around(100*len(set4)/len(xycols), decimals=2)

        linex = hv.VLine(xlimit)
        liney = hv.HLine(ylimit)
        body = linex * liney * hv.Points(set1, label=str("upper left: " + str(categories["upper left"]) + "%")) * \
               hv.Points(set2, label=str("upper right: " + str(categories["upper right"]) + "%")) * \
               hv.Points(set3, label=str("bottom left: " + str(categories["bottom left"]) + "%")) * \
               hv.Points(set4, label=str("bottom right: " + str(categories["bottom right"]) + "%"))
        body = body.opts(plot=dict(width=800, height=600))
        body = body.opts(opts.Points(tools=['box_select', 'lasso_select', 'hover'], size=6, fill_alpha=0.6))
        body = body.redim.label(x=col1, y=col2)
        if os.path.isfile(os.path.join(self.directory, str("coordinate_gating_"+str(type)))):
            os.remove(os.path.join(self.directory, str("coordinate_gating_"+str(type))))
        renderer.save(body, os.path.join(self.directory, str("coordinate_gating_"+str(type))))
예제 #25
0
def curves_data_US(year=1971):

    oil_z2 = oil.loc[oil.country == 'United States',
                     'NY.GDP.PETR.RT.ZS'].iloc[::-1]
    oil_z2 = oil_z2 - oil_z2.iloc[0]

    money_z2 = money.loc[money.country == 'United States',
                         'FM.LBL.BMNY.GD.ZS'].iloc[::-1]
    money_z2 = money_z2 - money_z2.iloc[0]

    z_2 = oil_z2.iloc[year - 1971] - 10

    z_1 = -money_z2.iloc[year - 1971] - 10

    as_eq = pd.DataFrame([P(), AS(P=P(), Z_2=0)],
                         index=['Price-Level', 'Real Output']).T
    ad_eq = pd.DataFrame([P(), AD(P=P(), Z_1=0)],
                         index=['Price-Level', 'Real Output']).T

    as_shock = pd.DataFrame([P(), AS(P=P(), Z_2=z_2 + 10)],
                            index=['Price-Level', 'Real Output']).T
    ad_shock = pd.DataFrame([P(), AD(P=P(), Z_1=z_1 + 10)],
                            index=['Price-Level', 'Real Output']).T

    result = findIntersection(lambda x: AS(P=x, Z_2=z_2 + 10),
                              lambda x: AD(P=x, Z_1=-z_1 - 10), 0.0)
    r = result + 1e-4 if result == 0 else result

    plot = hv.Curve(as_eq, vdims='Price-Level',kdims='Real Output').options(alpha=0.2, color='#1BB3F5') *\
                              hv.Curve(ad_eq, vdims='Price-Level',kdims='Real Output').options(alpha=0.2, color='orange') *\
                              hv.Curve(as_shock, vdims='Price-Level',kdims='Real Output', label='AS').options(alpha=1, color='#1BB3F5') *\
                              hv.Curve(ad_shock, vdims='Price-Level',kdims='Real Output', label='AD').options(alpha=1, color='orange') *\
                              hv.VLine(-result[0]).options(color='black', alpha=0.2, line_width=1) *\
                              hv.HLine(AD(P=-r[0], Z_1=z_1+10)).options(color='black', alpha=0.2, line_width=1)

    gdp_mean = gdp.loc[gdp.country == 'United States',
                       'NY.GDP.PCAP.KD'].iloc[0]
    gdp_iqr = iqr(gdp.loc[gdp.country == 'United States', 'NY.GDP.PCAP.KD'])

    gdp_plot_US = gdp.loc[gdp.country=='United States',:].iloc[::-1,:].hvplot.line(x='year', y='NY.GDP.PCAP.KD', title='GDP per capita growth (constant 2010 US$)') *\
    hv.VLine(year).options(color='black') * pd.DataFrame([[(AD(P=-r[0], Z_1=-z_1-10))*gdp_iqr*0.3+gdp_mean*4, year]], columns=['Real Output', 'year']).hvplot.scatter(y='Real Output', x='year',color='red')

    return plot.options(xticks=[0],
                        yticks=[0],
                        title_format="US Short-Run AS-AD Model") + gdp_plot_US
예제 #26
0
    def generate_graph_network_speed(self):
        pingbound_network_test = self.df_speed_test["ping"].min()

        fig_network_speed_below_pingbound = hv.Curve(
            (self.df_speed_test["date"], self.df_speed_test["downstream"] / 1000),
            "Date",
            "Network Speed",
            label="Messured downlink speed when ping below {} ms".format(
                str(pingbound_network_test)))

        fig_highlight_below_acceptable_network_speed = hv.Scatter(
            (self.df_speed_test["date"][
                 self.df_speed_test["downstream"] / 1000 < self.acceptable_network_speed],
             self.df_speed_test["downstream"][
                 self.df_speed_test["downstream"] / 1000 < self.acceptable_network_speed] / 1000),
            "Date",
            "Network Speed",
            label="Highlight downstream speed below {} mbit/s".format(
                str(self.acceptable_network_speed))).opts(color="red", size=10)

        fig_horizontal_marker = hv.HLine(
            self.acceptable_network_speed,
            label="Acceptable network speed at {} mbit/s".format(
                str(self.acceptable_network_speed))).opts(color="black")

        fig_upstream_below_ping_bound = hv.Curve(
            (self.df_speed_test["date"], self.df_speed_test["upstream"] / 1000),
            "Date",
            "Network Speed",
            label="Messured uplink when ping below {} ms".format(
                str(pingbound_network_test))).opts(color="purple")

        fig_network_speeds_under_upper_bound = (
                fig_network_speed_below_pingbound *
                fig_highlight_below_acceptable_network_speed * fig_upstream_below_ping_bound * fig_horizontal_marker
        ).opts(
            title="Network Speed when Ping below {} ms".format(pingbound_network_test),
            legend_position="top_left",
            padding=0.05)

        # Safe newly generated plot
        hv.save(fig_network_speeds_under_upper_bound,
                os.path.join(self.path, "webpage", "figures",
                             "fig_network_speeds_under_upper_bound.html"),
                backend='bokeh')
예제 #27
0
def posterior_ratio(df, r, c, col='new', a=1, b=3, gamma=GAMMA,
                    title='Inter-day ratio'):
    """Plots an inferred-rate ratio and its implicit gamma bound.

    This plot provides an indication of whether or not the inferred rates are
    sufficiently smooth by considering their rate of change; see
    `smoothed_ratio` -- which does the same for smoothed, observed counts -- for
    more details.
    """
    df = _posterior(df, r, c, col, a, b, gamma)
    bound = np.exp(-gamma)
    df['ratio'] = df.posterior/df.posterior.shift()
    # mn, mx = min(bound, df.ratio.min()), max(bound, df.ratio.max())
    # ylim = (mn - 0.1*(mx-mn), mx + 0.1*(mx-mn))
    return df.hvplot.line(
        x='date', y='ratio', legend='top_right'
    ).opts(title=title) \
        * hv.HLine(bound)
예제 #28
0
def create_hvplot(df, label, axes=4):
    ''' use hvplot to display the data from brEFB'''
    #import hvplot
    import hvplot.pandas
    import holoviews as hv
    color = ['blue', 'orange', 'green', 'red']
    if axes > 3:
        ycols = {
            'trans': ['td 0', 'td 1', 'td 2', 'td 3'],
            'setpoints': ['sp 0', 'sp 1', 'sp 2', 'sp 3']
        }
    elif axes in {0, 1, 2, 3}:
        td = 'td ' + str(axes)
        sp = 'sp ' + str(axes)
        # have to put them twice to trick bokeh into showing the legend - it won't for a single y value
        ycols = {'trans': [td, td], 'setpoints': [sp, sp]}
        color = color[axes]
    else:
        print('Invalid axis')
        return

    p1 = df.hvplot(x='t',
                   y=ycols['trans'],
                   kind='scatter',
                   color=color,
                   ylabel='br-EFB units',
                   title=label,
                   height=400,
                   width=900,
                   ylim=(-1.1, 1.1))
    p2 = df.hvplot(x='t',
                   y=ycols['setpoints'],
                   kind='line',
                   line_dash='dashed',
                   color=color,
                   ylabel='br-EFB units',
                   title=label,
                   height=400,
                   width=900,
                   ylim=(-1.1, 1.1))
    p3 = hv.HLine(0.0).opts(line_dash='dotted', color='black')
    return p1 * p2 * p3
예제 #29
0
def smoothed_diff(df, raw='new', gamma=GAMMA, std=STD,
                  title='Infections-period bound'):
    """Plots the difference between smoothed counts and an implicit gamma bound.

    The value of the infectious-period parameter `gamma` implies a lower bound
    on the rate at which the number of new infections can decrease. This plot
    shows the difference between the smoothed counts and this implicit bound.
    The difference will ideally remain non-negative.
    """
    df = df.copy()
    smooth(df, raw=raw, smth='smoothed', std=std)
    # We floor the bound to make it more realistic (and lenient), since
    # otherwise, for example, a decoy from 1 to 0 would not be allowed.
    df['γ bound'] = np.floor(df.smoothed.shift()*np.exp(-gamma))
    df['difference'] = df.smoothed - df['γ bound']
    return df.hvplot.line(
        x='date', y=['smoothed', 'γ bound', 'difference'],
        line_dash=['dashed', 'dashed', 'solid'], legend='top_left'
    ).opts(title=title) \
        * hv.HLine(np.exp(-gamma))
예제 #30
0
def plot_player_ratings_scatter(
    player_ratings: pd.DataFrame,
    x_col: str,
    y_col: str,
    color_col: str = "overall",
    size_col: str = "overall",
    **plot_opts,
) -> hv.Overlay:
    scatter_base = (player_ratings.reset_index().hvplot.scatter(
        x=x_col,
        y=y_col,
        c=color_col,
        hover_cols=["name", "overall"],
    ).opts(
        size=abs(dim(size_col)) * 2,
        **plot_opts,
    ))
    overlay = (scatter_base * hv.VLine(0).opts(color="gray") *
               hv.HLine(0).opts(color="gray"))
    return overlay