Ejemplo n.º 1
0
def visualisation():
    # Build the dataframe
    df = pd.DataFrame({
        'x': 2 * np.pi * i / 100,
        'sin': np.sin(2 * np.pi * i / 100),
        'cos': np.cos(2 * np.pi * i / 100),
    } for i in range(0, 101))

    # Create the plot
    plot = bc.Line(title='Triganometric fun!', data=df, x='x', ylabel='y')

    # Generate the script and HTML for the plot
    script, div = components(plot)

    # Return the webpage
    return """
<!doctype html>
<head>
 <title>My wonderful trigonometric webpage</title>
 {bokeh_css}
</head>
<body>
 <h1>Everyone loves trig!
 {div}

 {bokeh_js}
 {script}
</body>
 """.format(script=script,
            div=div,
            bokeh_css=CDN.render_css(),
            bokeh_js=CDN.render_js())
Ejemplo n.º 2
0
def init(is_reset=False):
    if not os.path.exists("worlds"):
        raise Exception(
            "Admin, please create the 'worlds' directory to save worlds!")
    world = load_world()
    num_turns = len(world.solar_park.generation)
    available_tokens = [world.available_tokens(i) for i in range(num_turns)]
    max_tokens = int(max(available_tokens))
    turn_hours = [str(h).rjust(2, "0") for h in range(9, 9 + num_turns)]

    safe_js = make_custom_js(world.charging_stations, max_tokens,
                             world.current_step)
    data_plots_html, data_plots_js = build_game_data_plots(world)

    return render_template("board.html",
                           **dict(world=world),
                           num_turns=num_turns,
                           available_tokens=available_tokens,
                           max_tokens=max_tokens,
                           turn_hours=turn_hours,
                           safe_js=safe_js,
                           resetted_the_game=is_reset,
                           bokeh_css_resources=CDN.render_css(),
                           bokeh_js_resources=CDN.render_js(),
                           data_plots_html=data_plots_html,
                           data_plots_js=data_plots_js)
Ejemplo n.º 3
0
def users():
    users = pd.read_csv("users.xlsx")
    hover = HoverTool(tooltips=[('Pct', '@pct')], mode='vline')
    users['']
    donut_from_df = bc.Donut(users['City'], level_spacing=[0.0, 0.01])
    '''    
    donut_from_df = Donut(df_users, label = "city",xlabel="city",ylabel="users",
                      values="count",
                      title="Users Per city",
                      title_text_font_size=str(32)+"pt",
                      level_spacing=[0.0, 0.01])'''
    #show(donut_from_df)
    script, div = components(donut_from_df)
    return """
    <!doctype html>
    <head>
     <title>Popular places</title>
     {bokeh_css}
    </head>
    <body>
     <h1>Most Popular Places visited by people!
     {div}
    
     {bokeh_js}
     {script}
    </body>
     """.format(script=script,
                div=div,
                bokeh_css=CDN.render_css(),
                bokeh_js=CDN.render_js())
Ejemplo n.º 4
0
def next_step():
    world = load_world()
    orders = dict()
    for sid, station in world.charging_stations.items():
        if "order_%s" % sid not in request.form:
            raise Exception("Missing order_%s in request." % sid)
        orders[sid] = int(request.form.get("order_%s" % sid))
    move_summary = world.next_step(orders)
    save_world(world)

    num_turns = len(world.solar_park.generation)
    available_tokens = [world.available_tokens(i) for i in range(num_turns)]
    max_tokens = int(max(available_tokens))
    turn_hours = [str(h).rjust(2, "0") for h in range(9, 9 + num_turns)]

    if world.current_step < num_turns:
        safe_js = make_custom_js(world.charging_stations, max_tokens,
                                 world.current_step)
    else:
        safe_js = ""
    data_plots_html, data_plots_js = build_game_data_plots(world)

    return render_template("board.html",
                           **dict(world=world),
                           num_turns=num_turns,
                           available_tokens=available_tokens,
                           max_tokens=max_tokens,
                           completed_a_move=True,
                           move_summary=move_summary,
                           turn_hours=turn_hours,
                           safe_js=safe_js,
                           bokeh_css_resources=CDN.render_css(),
                           bokeh_js_resources=CDN.render_js(),
                           data_plots_html=data_plots_html,
                           data_plots_js=data_plots_js)
Ejemplo n.º 5
0
def visualisation():
    current_city_name = request.args.get("city_name")
    if current_city_name == None:
        current_city_name = "Mumbai"
    subset = df_iplace[df_iplace['city'] == dropdown.value]
    #plot = create_figure(current_city_name)
    plot = bc.Bar(subset,
                  "placename",
                  values="placename",
                  agg="count",
                  plot_width=1000,
                  plot_height=1000,
                  title="Popular places")

    # Generate the script and HTML for the plot
    script, div = components(plot)

    # Return the webpage
    return """
    <!doctype html>
    <head>
     <title>Popular places</title>
     {bokeh_css}
    </head>
    <body>
     <h1>Most Popular Places visited by people!
     {div}
    
     {bokeh_js}
     {script}
    </body>
     """.format(script=script,
                div=div,
                bokeh_css=CDN.render_css(),
                bokeh_js=CDN.render_js())
def visualisation():
 # Build the dataframe
 df = pd.DataFrame({
 'x': 2*np.pi*i/100,
 'sin': np.sin(2*np.pi*i/100),
 'cos': np.cos(2*np.pi*i/100),
 } for i in range(0,101))

 # Create the plot
 plot = bc.Line(title='Triganometric fun!',
 data=df, x='x', ylabel='y')

 # Generate the script and HTML for the plot
 script, div = components(plot)

 # Return the webpage
 return """
<!doctype html>
<head>
 <title>My wonderful trigonometric webpage</title>
 {bokeh_css}
</head>
<body>
 <h1>Everyone loves trig!
 {div}

 {bokeh_js}
 {script}
</body>
 """.format(script=script, div=div, bokeh_css=CDN.render_css(),
 bokeh_js=CDN.render_js())
Ejemplo n.º 7
0
def test_bokeh():
    from bokeh.io import output_notebook, show
    from bokeh.plotting import figure
    import ipyvolume.bokeh

    x, y, z = np.random.random((3, 100))

    p3.figure()
    scatter = p3.scatter(x, y, z)

    tools = "wheel_zoom,box_zoom,box_select,lasso_select,help,reset,"
    p = figure(title="E Lz space",
               tools=tools,
               webgl=True,
               width=500,
               height=500)
    r = p.circle(x, y, color="navy", alpha=0.2)
    ipyvolume.bokeh.link_data_source_selection_to_widget(
        r.data_source, scatter, 'selected')

    from bokeh.resources import CDN
    from bokeh.embed import components

    script, div = components(p)
    ipyvolume.embed.embed_html(
        "tmp/bokeh.html", [p3.gcc(), ipyvolume.bokeh.wmh],
        all=True,
        extra_script_head=script + CDN.render_js() + CDN.render_css(),
        body_pre="<h2>Do selections in 2d (bokeh)<h2>" + div +
        "<h2>And see the selection in ipyvolume<h2>")
Ejemplo n.º 8
0
def output_pweave():
    """
    Call this once in a Pweave document to include correct
    headers for Bokeh. Analogous to Bokeh's output_notebook
    """
    out = CDN.render_css()
    out += CDN.render_js()
    #display_markdown(out, raw=True)
    display_html(out, raw=True)
Ejemplo n.º 9
0
def output_pweave():
    """
    Call this once in a Pweave document to include correct
    headers for Bokeh. Analogous to Bokeh's output_notebook
    """
    out = CDN.render_css()
    out += CDN.render_js()
    # display_markdown(out, raw=True)
    display_html(out, raw=True)
def visuals():

    plot = bc.Bar(data=top_ten_states_dataFrame, values='count', label='State')
    script, div = components(plot)

    error = None
    try:
        return '''
		<!DOCTYPE html>
		<html>
		<head>
			<title>Train Wreck Header</title>
			<meta charset="utf-8">
			<link rel="stylesheet" type="text/css" href="../static/css/bootstrap.min.css">
			<script type="text/javascript" href="../static/js/bootstrap.min.js"></script>
			<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
			{bokeh_css}
		</head>
		<header style="background-color: #e6e6e6;">
		<!--
			<p> started working </p> -->

			<nav class="navbar navbar-inverse" style="background-color: #4d4d4d;">
				<div class="container-fluid">

					<div class="navbar-header">
						<a class="navbar-brand" href="/" style="color: white;">Train Wreck Analysis</a>
					</div>

					<ul class="nav navbar-nav">
						<li><a href="/">Home</a></li>
						<li><a href="/map/">Map</a></li>
						<li><a href="/visuals/">Bar Chart</a></li>
					</ul>

				</div>
			</nav>
		</header>

		<body>
			<div class="container-fluid" style="margin-left: 20px; float:left; border: solid; border-style: groove; border-width: 5px; height: 650px; width: 700px; padding-top: 20px;">
			 {div}
			 {bokeh_js}
 			 {script}
			</div>
		</body>
		</html>
		'''.format(script=script,
             div=div,
             bokeh_css=CDN.render_css(),
             bokeh_js=CDN.render_js())

    except Exception as e:
        flash(e)
        return render_template('visuals.html', error=error)
Ejemplo n.º 11
0
def make_plot_code(df):
    fraud_file = pd.read_csv('plots/graphfraud.csv')
    not_fraud_file = pd.read_csv('plots/graphnotfraud.csv')
    df = df.drop(['has_header'], axis=1)
    with open('plots/pca.pkl') as f:
        pca = pickle.load(f)

    with open('plots/scaler.pkl') as f:
        scaler = pickle.load(f)
    print df.values
    try:
        df_ = df.fillna(0.)
        x = pca.transform(scaler.transform(df_.values))
    except:
        try:
            df_ = df.fillna(0)
            x = pca.transform(scaler.transform(df_.values))
        except:
            df_ = df.fillna(str(0))
            x = pca.transform(scaler.transform(df_.values))

    p = figure(title="Fraud Visualization", plot_width=400, plot_height=400)
    p.background_fill_color = "#eeeeee"

    p.scatter(not_fraud_file.values[:, 0],
              not_fraud_file.values[:, 1],
              marker='triangle',
              color='orange',
              legend='Not Fraud')
    p.scatter(fraud_file.values[:, 0],
              fraud_file.values[:, 1],
              marker='circle',
              color='red',
              legend='Fraud')
    p.scatter(x[0, 0],
              x[0, 1],
              color='blue',
              legend='Most recent event',
              marker='square',
              size=10)

    script, div = components(p)

    div = ast.literal_eval(json.dumps(div)).replace('\n', "")
    script = ast.literal_eval(json.dumps(script)).replace('\n', "")
    css = CDN.render_css()
    css = ast.literal_eval(json.dumps(css)).replace('\n', "")
    js = CDN.render_js()
    js = ast.literal_eval(json.dumps(js)).replace('\n', "")
    return div, script, css, js
Ejemplo n.º 12
0
def bokehPlot():
    company = app.vars['company']
    script, div = components(plot_price(company))
    return """
    <!doctype html>
    <head>
        {bokeh_css}
    </head>
    <body>
        {div}
        {bokeh_js}
        {script}
    </body>
    """.format(script=script,
               div=div,
               bokeh_css=CDN.render_css(),
               bokeh_js=CDN.render_js())
Ejemplo n.º 13
0
def stockprice():
    if request.method == 'GET':
        return render_template('stocks.html')
    elif request.method == 'POST':
        theTicker = request.form['ticker']
        theOption = request.form.getlist('features')
        theDate = request.form['daterange']
        # call function to build graph
        plot = build_graph(theTicker, theOption, theDate)
        # get the plot components
        script, div = components(plot)
        # render plot on HTML page
        return render_template('stocks.html',
                               script=script,
                               div=div,
                               bokeh_css=CDN.render_css(),
                               bokeh_js=CDN.render_js())
Ejemplo n.º 14
0
def main():
    p = argparse.ArgumentParser()
    p.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
    p.add_argument('outfile', nargs='?', default="site/index.html")
    p.add_argument('-t', '--template', default='template.jinja',
            help="""Jinja2 Tempate file[default: %(default)]""")
    p.add_argument('-v', '--view', default=False,
            help="""Launch browser to view output: %(default)]""")
    a = p.parse_args()

    df = pd.read_csv(a.infile)

    plots = mkplots(df)

    script, div = components(plots)
    
    js_resources = CDN.render_js()
    css_resources = CDN.render_css()
    env = Environment(loader=FileSystemLoader(THIS_DIR),
                          trim_blocks=True)
    # Alias str.format to strformat in template
    env.filters['strformat'] = str.format
    template = env.get_template(a.template)

    html = template.render( date=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                            command=" ".join(sys.argv),
                            workdir=os.getcwd(),
                            user=getpass.getuser(),
                            title="Santa Performance Plots",
                            js_resources=js_resources,
                            css_resources=css_resources,
                            script=script,
                            div=div)

    with open(a.outfile, "w") as f:
        f.write(html.encode('utf-8'))

    # to deploy to gh-pages, use the function `gh=deploy` defined in ~.bash_profile
    # first copy index.html tp the `site/` directory
    # Cribbed from https://gist.github.com/cobyism/4730490
    #    git subtree push --prefix site origin gh-pages
    if a.view:
        view(a.outfile)
Ejemplo n.º 15
0
def visualisation(session_type=None):
    global y_bottom
    global analyzer_log_dict
    global x
    global y

    # PARECERÍA QUE SE ENTRA UNA ÚNICA VEZ POR CLIENTE
    print("New Client Connected")
    plots = []
    plots.append(
        ajax_getplot(x=x,
                     y=y,
                     y_bottom=y_bottom,
                     ref_value=analyzer_log_dict["ref_level"]))
    #plots2 = []
    #plots2.append(get_ajax_plot2())
    return render_template("dashboard.html",
                           bokeh_css=CDN.render_css(),
                           bokeh_js=CDN.render_js(),
                           plots=plots)  #,plots2=plots2)
Ejemplo n.º 16
0
def tickerTape_bokehPlot():
    ticker_str = app_tickerTape.vars['tickerSymbol']
    quandl.ApiConfig.api_key = 'rJS8aE3GNr2x5RBnFtr5'
    quandlData_df = getQuandlData(ticker_str)
    quandlPlot = plotQuandlData(ticker_str, quandlData_df)
    script, div = components(quandlPlot)
    return """
    <!doctype html>
    <head>
        {bokeh_css}
    </head>
    <body>
        {div}

        {bokeh_js}
        {script}
    </body>
    """.format(script=script,
               div=div,
               bokeh_css=CDN.render_css(),
               bokeh_js=CDN.render_js())
Ejemplo n.º 17
0
def popular_places():
    try:
        db = mysql.connect()
        mycursor = db.cursor()
        mycursor.execute("select distinct(city) from placedetails")
        cities = []
        for row in mycursor:
            cities.append(row[0])
        form = AdminForm()
        form.city.choices = [(city, city) for city in cities]
        if request.method == 'POST' and form.validate_on_submit():
            cname = request.form['city']
            subset = df_iplace[df_iplace['city'] == cname]
            places = subset['placename'].value_counts().to_frame()
            plot = bc.Bar(places.iloc[0:5, ],
                          label="index",
                          values="placename",
                          plot_width=1000,
                          plot_height=700,
                          legend="top_right",
                          bar_width=0.3,
                          min_border=30,
                          xlabel="Places",
                          ylabel="Count")
            script, div = components(plot)
            return render_template(
                "admin.html",
                form=form,
                script=script,
                title_text="Top 5 Places visited by people in ",
                div=div,
                bokeh_css=CDN.render_css(),
                bokeh_js=CDN.render_js(),
                city=cname)
        return render_template("admin.html", form=form)
    except:
        print("Exception occured in admin")
    finally:
        db.close()
Ejemplo n.º 18
0
def loadplot(city):
    cname = city
    subset = df_iplace[df_iplace['city'] == cname]
    places = subset['placename'].value_counts().to_frame()
    plot = bc.Bar(places.iloc[0:5, ],
                  label="index",
                  values="placename",
                  plot_width=1000,
                  plot_height=700,
                  legend="top_right",
                  bar_width=0.3,
                  min_border=30,
                  xlabel="Places",
                  ylabel="Count")
    script, div = components(plot)
    return render_template("plot.html",
                           script=script,
                           title_text="Top 5 Places visited by people in ",
                           div=div,
                           bokeh_css=CDN.render_css(),
                           bokeh_js=CDN.render_js(),
                           city=cname)
Ejemplo n.º 19
0
def visualisation():
    plot = mod_data()
    # Generate the script and HTML for the plot
    script, div = components(plot)

    # Return the webpage
    return """
    <!doctype html>
    <head>
     <title>NBA test page</title>
     {bokeh_css}
    </head>
    <body>
     <h1>How rookies will score in the future!
     {div}
    
     {bokeh_js}
     {script}
    </body>
     """.format(script=script,
                div=div,
                bokeh_css=CDN.render_css(),
                bokeh_js=CDN.render_js())
Ejemplo n.º 20
0
def download_url():
    plots = []
    global current_data_frame
    if request.method != 'POST':
        flash("download called with incorrect method")
        return redirect(url_for("get_url"))
    url = request.form['url']
    df = pandas.read_csv(url)
    df['AAPL_p'] = df['AAPL_x']  # make a column for readable date
    df.AAPL_x = pandas.to_datetime(df.AAPL_x)  # datetime to make plottable
    current_data_frame = df

    # generate graph of price/date
    tooltips = [("index", "$index"), ("price", "@AAPL_y"),
                ("date", "@{AAPL_p}")]
    # generate bokeh data source
    cds = ColumnDataSource(df)
    plots.append(generate_plot('AAPL', cds, 'AAPL_x', 'AAPL_y', tooltips))
    plots.append(generate_table('AAPL', cds, None))

    return render_template("dashboard.html",
                           plots=plots,
                           css=CDN.render_css(),
                           js=CDN.render_js())
def map():
    scale = 5
    '''
		create a dataframe without null row or column values 
	'''
    halfComplete_dataFrame = df1[df1['City, State'].str.contains(',',
                                                                 na=False)]

    cities_dataFrame = pd.DataFrame(halfComplete_dataFrame['City, State'])
    cities_dataFrame = cities_dataFrame.rename(columns={'City, State': 'City'})
    top_cities_dataFrame = cities_dataFrame.groupby(
        ['City']).size().reset_index().rename(columns={0: 'count'})
    top_ten_cities_dataFrame = top_cities_dataFrame.sort_values(
        by='count', ascending=False).head(10)

    geolocator = Nominatim()

    lat_long_list = []
    for row in top_ten_cities_dataFrame['City']:
        topTenCitiesList.append(str(row))
    #print topTenCitiesList

    for row in top_ten_cities_dataFrame['count']:
        topTenCitiesCount.append(row)

    #print topTenCitiesCount

    for i, val in enumerate(topTenCitiesList):
        loc = geolocator.geocode(val)
        #cities_tpl=cities_tpl+(val,)
        #long_tpl=long_tpl+(loc.longitude,)
        #lat_tpl=lat_tpl+(loc.latitude,)
        city_lat_list.append(loc.latitude)
        city_long_list.append(loc.longitude)

    #print topTenCitiesList
    #print topTenCitiesCount
    #print city_lat_list
    #print city_long_list
    #print cities_tpl
    map_options = GMapOptions(lat=39.8282,
                              lng=-98.5795,
                              map_type="roadmap",
                              zoom=5)
    plot = GMapPlot(x_range=DataRange1d(),
                    y_range=DataRange1d(),
                    map_options=map_options,
                    plot_width=1100,
                    plot_height=800)
    #plot.title.text = "Top ten cities"
    plot.api_key = "AIzaSyBfcQ8lTsXC5du_Mj0IyFLuXepDt_Euawo"
    source = ColumnDataSource(data=dict(
        lat=city_lat_list,
        lon=city_long_list,
        #text=topTenCitiesList,
    ))
    circle = Circle(x="lon",
                    y="lat",
                    tags=topTenCitiesList,
                    size=15,
                    fill_color="blue",
                    fill_alpha=0.8,
                    line_color=None)
    plot.add_glyph(source, circle)
    plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool())
    script, div = components(plot)

    error = None
    try:
        return '''
		<!DOCTYPE html>
		<html>
		<head>
			<title>Train Wreck Header</title>
			<meta charset="utf-8">
			<link rel="stylesheet" type="text/css" href="../static/css/bootstrap.min.css">
			<script type="text/javascript" href="../static/js/bootstrap.min.js"></script>
			<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
			{bokeh_css}
		</head>
		<header style="background-color: #e6e6e6;">
		<!--
			<p> started working </p> -->

			<nav class="navbar navbar-inverse" style="background-color: #4d4d4d;">
				<div class="container-fluid">

					<div class="navbar-header">
						<a class="navbar-brand" href="/" style="color: white;">Train Wreck Analysis</a>
					</div>

					<ul class="nav navbar-nav">
						<li><a href="/">Home</a></li>
						<li><a href="/map/">Map</a></li>
						<li><a href="/visuals/">Bar Chart</a></li>
					</ul>

				</div>
			</nav>
		</header>

		<body>
			<div class="container-fluid" style="float:center; border: solid; border-style: groove; border-width: 5px; height: 820px; width: 1200px; padding-top: 2px; padding-left: 42px; padding-right: 2px; margin:0 auto; margin-top: -18px;">
			 {div}
			 {bokeh_js}
 			 {script}
			</div>
		</body>
		</html>
		'''.format(script=script,
             div=div,
             bokeh_css=CDN.render_css(),
             bokeh_js=CDN.render_js())
    except Exception as e:
        flash(e)
        return render_template('map.html', error=error)
def create_html_template(layout):

    # bokeh components required to embed the input bokeh layout into a html
    # template using e.g. Jinja2
    s_script, s_div = components(layout)

    template = Template('''
    <head>
        <meta charset="utf-8">
        <title>Sentiment Analysis Corona-Crisis | Mehrshad Pakdel</title>
        {{ js_resources|safe }}
        {{ css_resources|safe }}
        {{ js_CDN_resources|safe }}
        {{ css_CDN_resources|safe }}
        {{ s_script|safe }}
        
        <style type="text/css">
            .container {
            width: 60%;
            margin-left: auto;
            margin-right: auto;
            }
            h1 {
            font-family:helvetica,verdana;
            color:#737373;
            font-size: 30px;
            font-weight: normal;
            text-transform: uppercase;
            margin-top: 1.5em;
            }
            
            h2  {
            font-family:helvetica,verdana;
            color:#ff8096;
            font-size: 20px;
            font-weight: normal;
            }
           
            p {
            font-family:helvetica,verdana;
            color:#737373;
            font-size: 16px;
            text-align: justify;
            text-justify: inter-word;
            }
            
            ul {
            font-family:helvetica,verdana;
            color:#737373;
            font-size: 16px; 
            }
            
            a {
            font-family:helvetica,verdana;
            color:teal;
            text-decoration: none; 
            font-size: 16px; 
            }
            .centerimg {
              display: block;
              margin-left: auto;
              margin-right: auto;
              width: 50%;
            }
            .centerdiv {
            margin: 0 auto;
            width: 90%;
            }
        </style>
    </head>
    <body>
        <div class="container">
        
            <h1>Twitter Geo-Sentiment Analysis<br>During Corona Crisis</h1>
            
            <h2>The Idea</h2>
            
            <p>Sentiment analysis of social media data is a powerful tool. I came 
            up with this idea to analyze twitter data using corona keywords.
            This analysis allows to create temporal and spatial snapshots of 
            the public opinion regarding topics related to the Corona-Crisis 
            such as social distancing, curfews or healthcare occupancy.
            To limit the number of languages for the sentiment analysis, I 
            first started out to analyze tweets captured in Germany.</p> 
            
            <h2>Workflow</h2>
            
            <ul>
                <li>Retrieve Corona-related tweets by using the Twitter's standard API and the <a href="http://docs.tweepy.org/en/latest/" target="_blank">Tweepy</a> library for Python</li>
                <li>Collect tweet data and save them to a SQLite database using <a href="https://docs.python.org/3/library/sqlite3.html" target="_blank">sqlite3</a></li>
                <li>Tweet text processing and sentiment analysis using <a href="https://textblob.readthedocs.io/en/dev/" target="_blank">TextBlob</a> for english and german languages</li>
                <li>Mapping user locations to geographic coordinates and creating map of germany using <a href="https://geopandas.org/" target="_blank">geopandas</a> and <a href="https://docs.bokeh.org/en/latest/" target="_blank">bokeh</a></li>
                <li>Creating interactive graphs with <a href="https://docs.bokeh.org/en/latest/" target="_blank">bokeh</a></li>
                <li>Bringing everything together and create customized html templates using <a href="https://palletsprojects.com/p/jinja/" target="_blank">Jinja2</a></li>
                <li>Have a look at the source code in the <a href="https://github.com/MehrshadPakdel/Corona-GeoSentiment" target="_blank">GitHub repository</a></li>
            </ul>
            
        <h2>The Data</h2>
        
        <div class="centerdiv">
        
            {{ s_div|safe }}
            
        </div>

        <h2>Wrap-up</h2>
        
        <p>Sentiment analysis of tweets related to the Corona-Crisis 
        revealed some interesting insights of public's opinion. We can
        visualize differences in the public's sentiment, the tweet locations
        and their quantity over time. Fluctuations in both polarity and 
        subjectivity of the tweet are observed over time. The mean 
        polarity seems to be slightly positive which might be surprising 
        considering the nature of social media. Interestingly, on 24.05.
        there is a slight trend towards a negative polarity visible.
        However, the sensitivity of this type of sentiment
        analysis is limited and probably requires more advanced natural 
        language processing approaches.</p>
        
        <h2>About</h2>
    
        <img src="./img/img.jpg" alt="Profile Picture" style="width:125px;height:125px;" class="centerimg">
        
        <p style="text-align:center;color:teal">Mehrshad Pakdel</p>
        
        <p  style="margin-bottom: 4em;">Hey there! After my PhD in biochemistry and first
        professional experience as a Consultant for Data Analytics, I am
        thrilled about data science and coding. As an aspiring data
        scientist, I am excited to learn new Python techniques and 
        frameworks. If you have questions about this project, please 
        don't hesitate to contact me via <a href="https://www.linkedin.com/in/mehrshad-pakdel/" target="_blank">LinkedIn</a>.</p>
        <br>
        <p style="text-align:center;"><a href="./notice.html" target="_blank" style="font-size: 14px;color:#737373;margin-bottom: 4em;">Legal Notice</a></p>
    </div>
    </body>''')

    js_resources = INLINE.render_js()
    css_resources = INLINE.render_css()
    js_CDN_resources = CDN.render_js()
    css_CDN_resources = CDN.render_css()

    html = template.render(js_resources=js_resources,
                           css_resources=css_resources,
                           js_CDN_resources=js_CDN_resources,
                           css_CDN_resources=css_CDN_resources,
                           s_script=s_script,
                           s_div=s_div)

    return html
Ejemplo n.º 23
0
def visualisation():
 # Build the dataframe
 df=pd.read_csv('C:\Users\sunil\OneDrive\Documents\SIH\static\sihnewdata.csv')
 #print df.head(10)
 #for mess 0
 mess0df=df[df['Mess_No']==0]
 mess0df=df.iloc[-21:,:]
 li=[]
 for i in range(0,len(mess0df)):
     li.append(i)    

 #source = ColumnDataSource(df)
 # Create the plot
 plot = plot = figure(plot_width=590, plot_height=120)
 #plot.multi_line(x=[li, df['No_of_Students_in_Hostel']] , y=[li, df['No_of_Actual_Diners']], color=['red','green'])
 plot.line(x=li,y=mess0df['No_of_Actual_Diners'],color='green')
 plot.line(x=li,y=mess0df['No_of_Students_in_Hostel'],color='red')
 #show(plot)
 # Generate the script and HTML for the plot
 script0, div0 = components(plot)
 
 #-------------
  #for mess 1
 mess1df=df[df['Mess_No']==1]
 mess1df=mess1df.iloc[-21:,:]
 li=[]
 for i in range(0,len(mess1df)):
     li.append(i)    

 #source = ColumnDataSource(df)
 # Create the plot
 plot1  = figure(plot_width=590, plot_height=120)
 plot1.line(x=li,y=mess1df['No_of_Actual_Diners'],color='green')
 plot1.line(x=li,y=mess1df['No_of_Students_in_Hostel'],color='red')
 #show(plot)
 # Generate the script and HTML for the plot
 script1, div1 = components(plot1)
 #----------------
 #for mess 2
 mess2df=df[df['Mess_No']==2]
 mess2df=mess2df.iloc[-21:,:]
 li=[]
 for i in range(0,len(mess2df)):
     li.append(i)    

 #source = ColumnDataSource(df)
 # Create the plot
 plot2  = figure(plot_width=590, plot_height=120)
 plot2.line(x=li,y=mess2df['No_of_Actual_Diners'],color='green')
 plot2.line(x=li,y=mess2df['No_of_Students_in_Hostel'],color='red')
 #show(plot)
 # Generate the script and HTML for the plot
 script2, div2 = components(plot2)
 #----------------
  #for mess 3 or use a group by(better way to do it but this is okay for basic version-will enhance later)
 mess3df=df[df['Mess_No']==3]
 mess3df=mess3df.iloc[-21:,:]
 li=[]
 for i in range(0,len(mess3df)):
     li.append(i)    

 #source = ColumnDataSource(df)
 # Create the plot
 plot3  = figure(plot_width=590, plot_height=120)
 plot3.line(x=li,y=mess3df['No_of_Actual_Diners'],color='green')
 plot3.line(x=li,y=mess3df['No_of_Students_in_Hostel'],color='red')
 #show(plot)
 # Generate the script and HTML for the plot
 script3, div3 = components(plot3)

#------------

 wastagedf_B=mess0df[mess0df.Type_Of_Meal=='B']
 wastagedf_B=wastagedf_B.iloc[-7:,:]
 print("wastage")
 print(wastagedf_B)
 wastagedf_L=mess0df[mess0df.Type_Of_Meal=='L']
 wastagedf_L=wastagedf_L.iloc[-7:,:]
 wastagedf_D=mess0df[mess0df.Type_Of_Meal=='D']
 wastagedf_D=wastagedf_D.iloc[-7:,:]

 plot_wastage  = figure(plot_width=590, plot_height=120)
 plot_wastage.line(x=[1,2,3,4,5,6,7],y=wastagedf_B['Total Wastage'],color='green')
 plot_wastage.line(x=[1,2,3,4,5,6,7],y=wastagedf_L['Total Wastage'],color='red')
 plot_wastage.line(x=[1,2,3,4,5,6,7],y=wastagedf_D['Total Wastage'],color='blue')
 #show(plot)
 #Generate the script and HTML for the plot
 script4, div4 = components(plot_wastage)

#---------
 wastestatsB1=wastagedf_B.groupby('Meal_1')['Wastage_1'].sum()
 wastestatsB2=wastagedf_B.groupby('Meal_2')['Wastage_2'].sum()
 wastestatsB3=wastagedf_B.groupby('Meal_3')['Wastage_3'].sum()

 print("wastage for Breakfast Menu1,2,3")
 print(wastestatsB1)
 print(wastestatsB2)
 print(wastestatsB3)
 # Return the webpage

 return render_template('vis.html',script0=script0, div0=div0,script1=script1, div1=div1,script2=script2, div2=div2,script3=script3, div3=div3,bokeh_css=CDN.render_css(),bokeh_js=CDN.render_js())
Ejemplo n.º 24
0
api_endpt = config['quandl.com']['api_endpt']
api_key = config['quandl.com']['api_key']

from flask import Flask, Blueprint, g, flash, redirect, render_template, request, url_for

from bokeh.embed import components
from bokeh.plotting import figure
from bokeh.resources import CDN

import requests
import zipfile
import pandas as pd
from math import pi

bokeh_css = CDN.render_css()
bokeh_js = CDN.render_js()

app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(SECRET_KEY=os.urandom(16))


def getTickerList():
    r = requests.get(api_endpt + 'databases/WIKI/codes',
                     params={'api_key': api_key})
    os.makedirs(app.instance_path, exist_ok=True)
    with open(os.path.join(app.instance_path, 'WIKI-datasets-codes.zip'),
              mode='wb') as f:
        f.write(r.content)

    with zipfile.ZipFile(
Ejemplo n.º 25
0
def render_flexmeasures_template(html_filename: str, **variables):
    """Render template and add all expected template variables, plus the ones given as **variables."""
    variables["documentation_exists"] = False
    if os.path.exists(
        "%s/static/documentation/html/index.html" % flexmeasures_ui.root_path
    ):
        variables["documentation_exists"] = True

    variables["show_queues"] = False
    if current_user.is_authenticated:
        if (
            current_user.has_role(ADMIN_ROLE)
            or current_app.config.get("FLEXMEASURES_MODE", "") == "demo"
        ):
            variables["show_queues"] = True

    variables["start_time"] = time_utils.get_default_start_time()
    if "start_time" in session:
        variables["start_time"] = session["start_time"]

    variables["end_time"] = time_utils.get_default_end_time()
    if "end_time" in session:
        variables["end_time"] = session["end_time"]

    variables["page"] = html_filename.split("/")[-1].replace(".html", "")
    if "show_datepicker" not in variables:
        variables["show_datepicker"] = variables["page"] in ("analytics", "portfolio")

    variables["contains_plots"] = False
    if any([n.endswith(("plots_div", "plots_divs")) for n in variables.keys()]):
        variables["contains_plots"] = True
        variables["bokeh_css_resources"] = CDN.render_css()
        variables["bokeh_js_resources"] = CDN.render_js()

    variables["resolution"] = session.get("resolution", "")
    variables["resolution_human"] = time_utils.freq_label_to_human_readable_label(
        session.get("resolution", "")
    )
    variables["horizon_human"] = time_utils.freq_label_to_human_readable_label(
        session.get("forecast_horizon", "")
    )

    variables["flexmeasures_version"] = flexmeasures_version

    (
        variables["git_version"],
        variables["git_commits_since"],
        variables["git_hash"],
    ) = get_git_description()
    app_start_time = current_app.config.get("START_TIME")
    variables["app_running_since"] = time_utils.naturalized_datetime_str(app_start_time)
    variables["loaded_plugins"] = ", ".join(
        f"{p_name} (v{p_version})"
        for p_name, p_version in current_app.config.get("LOADED_PLUGINS", {}).items()
    )

    variables["user_is_logged_in"] = current_user.is_authenticated
    variables[
        "user_is_admin"
    ] = current_user.is_authenticated and current_user.has_role(ADMIN_ROLE)
    variables[
        "user_is_anonymous"
    ] = current_user.is_authenticated and current_user.has_role("anonymous")
    variables["user_email"] = current_user.is_authenticated and current_user.email or ""
    variables["user_name"] = (
        current_user.is_authenticated and current_user.username or ""
    )
    variables["js_versions"] = current_app.config.get("FLEXMEASURES_JS_VERSIONS")
    variables["chart_options"] = json.dumps(chart_options)

    variables["menu_logo"] = current_app.config.get("FLEXMEASURES_MENU_LOGO_PATH")
    variables["extra_css"] = current_app.config.get("FLEXMEASURES_EXTRA_CSS_PATH")

    return render_template(html_filename, **variables)