Exemplo n.º 1
0
        self.last_power = -1
        self.solver_running = False
        self.grid_type = None
        self.mygrid = None
        self.power = None


state = solver_state()

# >> Init. Bokeh GUI elements << #
plot = Plot(x_range=Range1d(-PLOT_BOUNDARY, params['L'] + PLOT_BOUNDARY),
            y_range=Range1d(-PLOT_BOUNDARY, params['L'] + PLOT_BOUNDARY),
            height=VIEW_SIZE + 3 * COLORBAR_WIDTH,
            width=VIEW_SIZE,
            background_fill_color=FILL_COLOR)
plot.background_fill_alpha = 1.0

# Cell renderer #
cell_source = ColumnDataSource(
    dict(xs=[[0, params['L']], [0, params['L']], [0, 0],
             [params['L'], params['L']]],
         ys=[[0, 0], [params['L'], params['L']], [0, params['L']],
             [0, params['L']]]))
cell_glyph = MultiLine(xs='xs', ys='ys', line_width=1, line_color='silver')
cell = GlyphRenderer(data_source=cell_source, glyph=cell_glyph)

# Mesh renderer #
mesh_source = ColumnDataSource()
mesh_glyph = MultiLine(xs='xs',
                       ys='ys',
                       line_width=0.7,
Exemplo n.º 2
0
def make_calendar(sp500_data_lst,
                  djia_data_lst,
                  nasdaq_data_lst,
                  twitter_data_lst,
                  holiday_lst,
                  nyt_data_lst,
                  approval_data_lst,
                  generic_dem_lst,
                  generic_rep_lst,
                  plot_wid,
                  plot_ht,
                  year,
                  month,
                  firstweekday="Sun"):
    firstweekday = list(day_abbrs).index(firstweekday)
    calendar = Calendar(firstweekday=firstweekday)

    month_days = [
        None if not day else str(day)
        for day in calendar.itermonthdays(year, month)
    ]
    month_weeks = len(month_days) // 7

    workday = "linen"
    weekend = "lightsteelblue"

    def weekday(date):
        return (date.weekday() - firstweekday) % 7

    def pick_weekdays(days):
        return [days[i % 7] for i in range(firstweekday, firstweekday + 7)]

    day_names = pick_weekdays(day_abbrs)
    week_days = pick_weekdays([workday] * 5 + [weekend] * 2)

    source = ColumnDataSource(data=dict(
        days=list(day_names) * month_weeks,
        weeks=sum([[str(week)] * 7 for week in range(month_weeks)], []),
        month_days=month_days,
        day_backgrounds=['white'] * len(month_days),
    ))

    djia_data = [(dj_date, DJIA) for (dj_date, DJIA) in djia_data_lst
                 if dj_date.year == year and dj_date.month == month]

    nasdaq_data = [(nas_date, NASDAQCOM)
                   for (nas_date, NASDAQCOM) in nasdaq_data_lst
                   if nas_date.year == year and nas_date.month == month]

    sp500_data = [(sp500_date, SP500) for (sp500_date, SP500) in sp500_data_lst
                  if sp500_date.year == year and sp500_date.month == month]

    holidays = [(holiday_date, Holiday)
                for (holiday_date, Holiday) in holiday_lst
                if holiday_date.year == year and holiday_date.month == month]

    twitter_data = [
        (twitter_date, topics) for (twitter_date, topics) in twitter_data_lst
        if twitter_date.year == year and twitter_date.month == month
    ]

    nyt_data = [(nyt_date, headlines) for (nyt_date, headlines) in nyt_data_lst
                if nyt_date.year == year and nyt_date.month == month]

    approval_data = [
        (approval_date, approve_estimate)
        for (approval_date, approve_estimate) in approval_data_lst
        if approval_date.year == year and approval_date.month == month
    ]
    approval_data.sort()

    generic_dem = [(generic_date, dem_estimate)
                   for (generic_date, dem_estimate) in generic_dem_lst
                   if generic_date.year == year and generic_date.month == month
                   ]
    generic_dem.sort()

    generic_rep = [(generic_date, rep_estimate)
                   for (generic_date, rep_estimate) in generic_rep_lst
                   if generic_date.year == year and generic_date.month == month
                   ]
    generic_rep.sort()

    colors_djia = [DJIA for _, DJIA in djia_data]
    colors_sp500 = [SP500 for _, SP500 in sp500_data]
    colors_nasdaq = [NASDAQCOM for _, NASDAQCOM in nasdaq_data]

    for i in range(len(colors_djia) - 1):
        avg = np.mean([colors_djia[i], colors_sp500[i], colors_nasdaq[i]])

        if 0 < avg <= 11000:
            colors_djia[i] = '#E52700'
        elif 11000 < avg <= 11100:
            colors_djia[i] = '#E33A00'
        elif 11100 < avg <= 11200:
            colors_djia[i] = '#E14C00'
        elif 11200 < avg <= 11300:
            colors_djia[i] = '#DF5E00'
        elif 11300 < avg <= 11400:
            colors_djia[i] = '#DD6F00'
        elif 11400 < avg <= 11500:
            colors_djia[i] = '#DB8000'
        elif 11500 < avg <= 11600:
            colors_djia[i] = '#D99100'
        elif 11600 < avg <= 11700:
            colors_djia[i] = '#D7A100'
        elif 11700 < avg <= 11800:
            colors_djia[i] = '#D5B100'
        elif 11800 < avg <= 11900:
            colors_djia[i] = '#D3C100'
        elif 11900 < avg <= 12000:
            colors_djia[i] = '#D1D000'
        elif 12000 < avg <= 12100:
            colors_djia[i] = '#BECF00'
        elif 12200 < avg <= 12300:
            colors_djia[i] = '#ABCD00'
        elif 12300 < avg <= 12400:
            colors_djia[i] = '#99CB00'
        elif 12400 < avg <= 12500:
            colors_djia[i] = '#87C900'
        elif 12500 < avg <= 12600:
            colors_djia[i] = '#75C700'
        elif 12500 < avg <= 12600:
            colors_djia[i] = '#64C500'
        else:
            colors_djia[i] = '#53C300'

    holiday_source = ColumnDataSource(data=dict(
        month_djia=[DJIA for _, DJIA in djia_data],
        month_nasdaq=[NASDAQCOM for _, NASDAQCOM in nasdaq_data],
        month_sp500=[SP500 for _, SP500 in sp500_data],
        month_twitter=[topics for _, topics in twitter_data],
        month_holidays=[Holiday for _, Holiday in holidays],
        nyt_days=[day_names[weekday(nyt_date)] for nyt_date, _ in nyt_data],
        nyt_weeks=['0'] + [
            str((weekday(nyt_date.replace(day=1)) + nyt_date.day) // 7)
            for nyt_date, _ in nyt_data
        ],
        month_nyt=[headlines for _, headlines in nyt_data],
        month_approval=[
            approve_estimate for _, approve_estimate in approval_data
        ],
        month_generic_dem=[dem_estimate for _, dem_estimate in generic_dem],
        month_generic_rep=[rep_estimate for _, rep_estimate in generic_rep],
        day_backgrounds=colors_djia,
    ))

    xdr = FactorRange(factors=list(day_names))
    ydr = FactorRange(
        factors=list(reversed([str(week) for week in range(month_weeks)])))
    x_scale, y_scale = CategoricalScale(), CategoricalScale()

    plot = Plot(x_range=xdr,
                y_range=ydr,
                x_scale=x_scale,
                y_scale=y_scale,
                plot_width=plot_wid,
                plot_height=plot_ht)
    plot.title.text = month_names[month] + " " + str(year)
    plot.title.text_font_size = "14pt"
    plot.title.text_color = "black"
    plot.title.offset = 25
    plot.min_border_left = 5
    plot.min_border_top = 5
    plot.min_border_bottom = 190
    plot.border_fill_color = "white"
    plot.background_fill_alpha = 0.5
    plot.border_fill_alpha = 0.3

    rect = Rect(x="days",
                y="weeks",
                width=0.9,
                height=0.9,
                fill_color="day_backgrounds",
                line_color="silver")
    plot.add_glyph(source, rect)

    rect = Rect(x="nyt_days",
                y="nyt_weeks",
                width=0.9,
                fill_color="day_backgrounds",
                height=0.9)
    rect_renderer = plot.add_glyph(holiday_source, rect)

    text = Text(x="days",
                y="weeks",
                text="month_days",
                text_align="center",
                text_baseline="middle")
    plot.add_glyph(source, text)

    xaxis = CategoricalAxis()
    xaxis.major_label_text_font_size = "10pt"
    xaxis.major_label_standoff = 0
    xaxis.major_tick_line_color = None
    xaxis.axis_line_color = None
    plot.add_layout(xaxis, 'above')

    TOOLTIPS = """
	<div style="height:100%; max-width:300px; min-width:200px;background-color: aliceblue; position:relative;">
		<div>
			<span style="font-size: 17px; font-weight: bold;"> Holiday: @month_holidays</span><br>
			<span style="font-size: 15px; font-weight: bold; color: darkgrey;"> Trump Approval Rating: @month_approval{0,0.0}%</span><br>
			<span style="font-size: 15px; font-weight: bold; color: blue;"> Generic Democrat: @month_generic_dem{0,0.0}%</span><br>
			<span style="font-size: 15px; font-weight: bold; color: red;"> Generic Republican: @month_generic_rep{0,0.0}%</span><br>
			<span style="font-size: 17px; font-weight: bold;"> NASDAQ: @month_nasdaq{0,0.00}</span><br>
			<span style="font-size: 17px; font-weight: bold;"> DJIA: @month_djia{0,0.00}</span><br>
			<span style="font-size: 17px; font-weight: bold;">S&P500: @month_sp500{0,0.00}</span><br>
		</div>
		<div>
			<img
			src="/static/img/nyt_logo.png" height="15" width="15"
			style="float: left;"></img>
		</div>
		<div>
			<span style="font-size: 17px; font-weight: bold;">NYT Headlines:</span>
			<span style="font-size: 15px;">@month_nyt</span>
		</div>
		<div>
			<img
			src="/static/img/twitter_logo.png" height="15" width="15"
			style="float: left;"></img>
		</div>
		<div>
			<span style="font-size: 17px; color:blue; font-weight: bold;">Trending Tweets:</span>
			<span style="font-size: 15px; color:blue;">@month_twitter</span>
		</div>
	</div>
	"""

    hover_tool = HoverTool(renderers=[rect_renderer], tooltips=TOOLTIPS)
    # hover_tool = HoverTool(renderers=[rect_renderer], tooltips=[("Holiday", "@month_holidays"),("DJIA", "@month_djia{0,0.00}"),
    # 	("NASDAQ", "@month_nasdaq{0,0.00}"),("S&P500", "@month_sp500{0,0.00}"),("NYT Headlines", "@month_nyt"),("Trending Tweets","@month_twitter")])
    plot.tools.append(hover_tool)

    return plot
Exemplo n.º 3
0
def create_plot(G, layout):
    '''
        Returns a bokeh plot using the given netowrkx graph and layout. 
        Depending on the layout the dimensions of the graphs grid change

            Parameters:
                G (networkx graph) : Netoworkx graph that will be plotted
                layout (networkx layout): The layout of the network graph
            Return:
                plot (bokeh Plot): the plot generated using bokehs functions
    '''

    # the grouped layout is a special layout that uses the positions generated
    # by makegraph.py
    if layout == "grouped":
        G, sidel = get_vertices()
        hsidel = sidel / 2
        plot = Plot(plot_width=1200,
                    plot_height=600,
                    x_range=Range1d(-(hsidel + .1), hsidel + .1),
                    y_range=Range1d(-(hsidel + .1), hsidel + .1),
                    align='center')
    else:
        plot = Plot(plot_width=1200,
                    plot_height=600,
                    x_range=Range1d(-2.1, 2.1),
                    y_range=Range1d(-2.1, 2.1),
                    align='center')
    plot.title.text = "TV Shows Connected By Recommendation"
    plot.background_fill_color = "black"
    plot.background_fill_alpha = 0.1

    if layout == "grouped":
        pos_dict = {}
        for node in G.nodes:
            pos_dict[node] = G.nodes[node]["pos"]
        graph_renderer = from_networkx(G,
                                       pos_dict,
                                       scale=hsidel,
                                       center=(0, 0))

    # The discover layout uses the positions assigned in discover.py
    elif layout == "discover":
        pos_dict = {}
        for node in G.nodes:
            pos_dict[node] = G.nodes[node]["pos"]
        graph_renderer = from_networkx(G, pos_dict, scale=2, center=(0, 0))
    else:
        graph_renderer = from_networkx(G, layout, scale=2, center=(0, 0))

    # The colors for each node is assigned using a scale and if the number of nodes goes over
    # 256 the same color is used for the remaining nodes
    if len(G.nodes) > 256:
        Inferno = [Spectral4[1]] * len(G.nodes) - 256
        Inferno.extend(viridis(len(G.nodes)))
    else:
        Inferno = list(viridis(len(G.nodes)))
    source = graph_renderer.node_renderer.data_source
    nodes = graph_renderer.node_renderer
    edges = graph_renderer.edge_renderer
    source.data['name'] = [x for x in source.data['index']]
    source.data['colors'] = Inferno
    nodes.glyph = Circle(size=15,
                         fill_color='colors',
                         fill_alpha=0.9,
                         line_color='colors')
    nodes.selection_glyph = Circle(size=15,
                                   fill_color=Plasma11[10],
                                   fill_alpha=0.8)
    nodes.hover_glyph = Circle(size=15, fill_color=Plasma11[9])
    nodes.glyph.properties_with_values()

    edges.glyph = MultiLine(line_color="black", line_alpha=0.1, line_width=2)
    edges.selection_glyph = MultiLine(line_color=Plasma11[10], line_width=2)
    edges.hover_glyph = MultiLine(line_color=Plasma11[9], line_width=2)

    # This functions allow nodes to be highlighted when hovered over or clicked on
    graph_renderer.selection_policy = NodesAndLinkedEdges()
    graph_renderer.inspection_policy = NodesAndLinkedEdges()
    #graph_renderer.selection_policy = EdgesAndLinkedNodes()

    # The tooltips to show the data for the plots
    if layout == "grouped":
        node_hover_tool = HoverTool(tooltips=[("", "@name"), ("", "@genre")])
    else:
        node_hover_tool = HoverTool(tooltips=[("", "@name")])
    plot.add_tools(node_hover_tool, WheelZoomTool(), TapTool(),
                   BoxSelectTool())

    plot.renderers.append(graph_renderer)
    return plot
Exemplo n.º 4
0
    def draw_graph(self):

        if len(self.query_topics) <= 10:
            map_topic_to_color = dict(
                zip(self.query_topics, [
                    Category20[20][2 * i]
                    for i in range(len(self.query_topics))
                ]))
        else:
            map_topic_to_color = dict(
                zip(self.query_topics,
                    [Category20[20][i]
                     for i in range(len(self.query_topics))]))

        map_id_to_entity = dict(
            zip(range(len(self.all_entities)), self.all_entities))

        unique_topic = dict([
            (entity,
             max(self.entities_relevant_topics[entity],
                 key=self.entities_relevant_topics[entity].get))
            for entity in self.all_entities
        ])

        colors = []
        for i in range(len(self.all_entities)):
            try:
                colors.append(
                    map_topic_to_color[unique_topic[map_id_to_entity[i]]])
            except KeyError:
                colors.append("#b6b2b2")

        plot = Plot(plot_width=900,
                    plot_height=900,
                    x_range=Range1d(-1.1, 1.1),
                    y_range=Range1d(-1.1, 1.1),
                    toolbar_location="below")

        plot.add_tools(
            HoverTool(tooltips=[("entity", "@entity"), ("topic", "@topics")]),
            TapTool(), WheelZoomTool(), LassoSelectTool())
        plot.background_fill_color = "#d2d2d2"
        plot.background_fill_alpha = 0.25

        graph = from_networkx(self.graph,
                              nx.spring_layout,
                              scale=2,
                              center=(0, 0))

        graph.node_renderer.data_source.column_names.append("size")
        graph.node_renderer.data_source.data.update({
            "size": [
                math.log(
                    self.entities_relevant_appearances[map_id_to_entity[i]]) *
                5 + 10 for i in range(len(self.all_entities))
            ]
        })

        graph.node_renderer.data_source.column_names.append("topics")
        graph.node_renderer.data_source.data.update({
            "topics": [
                unique_topic[map_id_to_entity[i]]
                for i in range(len(self.all_entities))
            ]
        })

        graph.node_renderer.data_source.column_names.append("colors")
        graph.node_renderer.data_source.data.update({"colors": colors})

        graph.node_renderer.data_source.column_names.append("entity")
        graph.node_renderer.data_source.data.update(
            {"entity": self.all_entities})

        graph.node_renderer.glyph = Circle(size="size", fill_color="colors")

        graph.node_renderer.selection_glyph = Circle(size=8,
                                                     fill_color=Spectral4[2])
        graph.node_renderer.hover_glyph = Circle(size=12,
                                                 fill_color=Spectral4[1])

        graph.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
                                              line_alpha=0.,
                                              line_width=1.5)
        graph.edge_renderer.selection_glyph = MultiLine(
            line_color=Spectral4[2], line_width=1.5)
        graph.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1],
                                                    line_width=2)

        graph.selection_policy = NodesAndLinkedEdges()
        graph.inspection_policy = NodesAndLinkedEdges()

        plot.renderers.append(graph)

        div = Div(width=1000)

        layout = row(plot, div)

        s = graph.node_renderer.data_source

        s.callback = CustomJS(args=dict(div=div),
                              code="""
                var inds = cb_obj.selected['1d'].indices;
                var args = [];

                for (i = 0; i < inds.length; i++) {
                    args.push(cb_obj.data['entity'][inds[i]]);
                }
                div.text = "<font size='5' color='#9e9e9e'><b>"+args.join("<br />")+"</b></font>"
                """)

        show(layout)