Пример #1
0
def plot_bacteria_intraction_network(bacteria, node_list, node_size_list, edge_list, color_list, G_name, folder,
                                     color_by_tax_level=2, directed_G=True, control_color_and_shape=True):
    # create the results folder
    if not os.path.exists(folder):
        os.mkdir(folder)

    nodes_colors, nodes_shapes, group_list, tax_to_color_and_shape_map = \
        get_nodes_colors_by_bacteria_tax_level(bacteria, G_name, taxnomy_level=color_by_tax_level, folder=folder)

    bact_short_names = [shorten_single_bact_name(b) for b in bacteria]
    nodes_with_edges = np.unique(np.array(edge_list).flatten()).tolist()

    net = Network(height="750px", width="100%", bgcolor="#FFFFFF", font_color="black", directed=directed_G)
    #net.barnes_hut(gravity=-120000)
    net.force_atlas_2based()

    # for the nodes: you can use either only the group option the automatically colors the group in different colors
    # shaped like dots - no control, or use color and shape to make it you own, in this case group is irrelevant
    for i, node in enumerate(node_list):
        if node in nodes_with_edges:
            if control_color_and_shape:
                net.add_node(node, label=bact_short_names[i], color=nodes_colors[i], value=node_size_list[i],
                            shape=nodes_shapes[i], group=group_list[i])
            else:
                net.add_node(node, label=bact_short_names[i],  value=node_size_list[i],
                            group=group_list[i])

    # for the edges, the colors are what you decide and send
    for i, (u, v) in enumerate(edge_list):
        net.add_edge(u, v, color=color_list[i])


    net.save_graph(os.path.join(folder, G_name + ".html"))
Пример #2
0
def generate_graph(arbre):
    got_net = Network(height="100%",
                      width="100%",
                      bgcolor="#222222",
                      font_color="white")
    dico_couleur = {}
    for streamer in arbre.streamers:
        got_net.add_node(streamer.name,
                         value=streamer.poids,
                         shape='image',
                         image=streamer.photo_profil,
                         size=100)
        dico_couleur[streamer.name] = streamer.couleur

    for depart, arrivee in arbre.groupes_migrants:
        for viewer in arbre.groupes_migrants[depart, arrivee]:
            got_net.add_node(viewer, value=1, color=dico_couleur[depart])
            got_net.add_edge(viewer, depart, color=dico_couleur[depart])
            got_net.add_edge(viewer, arrivee, color=dico_couleur[arrivee])
    got_net.show_buttons()
    got_net.set_edge_smooth(smooth_type='dynamic')
    got_net.force_atlas_2based(gravity=-200,
                               central_gravity=0.01,
                               spring_length=1,
                               spring_strength=0.08,
                               damping=0.4,
                               overlap=0)
    got_net.save_graph("./graphs_v1/" + 'streamgame_v1_42' + ".html")
    return
def kyoki_word_network():
    got_net = Network(height="1000px",
                      width="95%",
                      bgcolor="#FFFFFF",
                      font_color="black",
                      notebook=True)
    # set the physics layout of the network
    #got_net.barnes_hut()
    got_net.force_atlas_2based()
    got_data = pd.read_csv("kyoki.csv")[:150]
    sources = got_data['first']  #count
    targets = got_data['second']  #first
    weights = got_data['count']  #second
    edge_data = zip(sources, targets, weights)

    for e in edge_data:
        src = e[0]
        dst = e[1]
        w = e[2]

        got_net.add_node(src, src, title=src)
        got_net.add_node(dst, dst, title=dst)
        got_net.add_edge(src, dst, value=w)

    neighbor_map = got_net.get_adj_list()

    #add neighbor data to node hover data
    for node in got_net.nodes:
        node["title"] += " Neighbors:<br>" + "<br>".join(
            neighbor_map[node["id"]])
        node["value"] = len(neighbor_map[node["id"]])

    got_net.show_buttons(filter_=['physics'])
    return got_net
Пример #4
0
def generate_network_plot(species,
                          path_to_template=template,
                          path_to_reactions=path):
    net = Network(directed=True)
    with open(path_to_reactions, 'r') as f:
        reactions_data = json.load(f)

    contained_reactions = {}

    for r in reactions_data['camp-data'][0]['reactions']:
        if 'reactants' in r:
            tmp = reactions_data['camp-data'][0]['reactions']
            if species in r['reactants']:
                contained_reactions.update({tmp.index(r): {}})
            if species in r['products']:
                contained_reactions.update({tmp.index(r): {}})

    logging.debug(contained_reactions)
    nodes = {}
    edges = []

    if contained_reactions:
        for i in contained_reactions:
            tmp = reactions_data['camp-data'][0]['reactions']
            reac_data = tmp[i]['reactants']
            prod_data = tmp[i]['products']
            reactants = [x for x in reac_data]
            products = [x for x in prod_data]
            first = '+'.join(reactants)
            second = '+'.join(products)
            name = first + '->' + second
            net.add_node(name,
                         label=name,
                         color='green',
                         borderWidthSelected=3)
            for j in reactants:
                nodes.update({j: {}})
                edges.append([j, name])
            for k in products:
                nodes.update({k: {}})
                edges.append([name, k])
    else:
        net.add_node(
            species,
            label=species,
        )
    if species in nodes:
        nodes.pop(species)
    net.add_node(species, label=species, color='blue', size=50)
    for n in nodes:
        net.add_node(n, label=n, borderWidthSelected=3, size=40)
    for e in edges:
        net.add_edge(e[0], e[1])
    net.force_atlas_2based(gravity=-100, overlap=1)
    net.show(str(path_to_template))
Пример #5
0
def show_network(G):

    nt = Network("700px", "700px", directed=True)
    nt.from_nx(G)

    #UNCOMMENT BELOW TO PLAY WITH PHYSICS OF SHOWN GRAPH
    #nt.show_buttons(filter_=["physics"])
    #nt.show_buttons(filter_=['nodes', 'interaction', 'selection'])
    nt.toggle_physics(status=True)
    nt.force_atlas_2based(gravity=-500,
                          central_gravity=0.02,
                          damping=0.2,
                          overlap=0.5)
    nt.show("Most_Related_Artists.html")
Пример #6
0
def plot_graph(graph,
               background_color='white',
               font_color='grey',
               with_edge_label=True,
               central_gravity=2.0,
               solver='',
               height='750px',
               width='100%',
               filter_=['']):
    ''' Creates a pyvis interactive Network Graph from a 
        NetworkX graph object.
    '''
    G = Network(notebook=True,
                height=height,
                width=width,
                bgcolor=background_color,
                font_color=font_color)

    color = {
        0: '#fb217f',
        1: '#fb217f',
        2: '#88b1fb',
        3: '#88b1fb',
        4: '#88b1fb'
    }
    deg = dict(graph.in_degree())

    for node in graph:
        md = max(deg.values())
        color_id = min(deg[node], 4)
        G.add_node(node,
                   title=node,
                   label=node,
                   size=(md - deg[node] + 1) * 4,
                   color=color[color_id])

    for edge in graph.edges():
        if with_edge_label:
            label = graph.get_edge_data(edge[0], edge[1])['relation']
        else:
            label = ''
        G.add_edge(edge[0], edge[1], label=label)
    if solver == 'barnes_hut':
        G.barnes_hut(central_gravity=central_gravity)
    else:
        G.force_atlas_2based(central_gravity=central_gravity)
    G.show_buttons(filter_=filter_)
    return G
Пример #7
0
  def _graph(self):
    try:
        counter = {}
        net = Network(height="100%", width="100%", bgcolor="white", font_color="white")
        net.force_atlas_2based(gravity=-250, central_gravity=0.005, spring_length=0, spring_strength=0, damping=1, overlap=1)
        exists = []
        for entry in self.edge_data:
            src = entry['challenger_id']
            pokemon = entry['challenger']
            if src in exists:
                continue
            t = "00"
            if 'alolan' in pokemon.lower():
                t = "61"
            my_img = '/static/icons/pokemon_icon_%s_%s.png' % (f'{src:03}', t)
            net.add_node(src, ' ', image=my_img, shape='circularImage', size=50, color={'highlight': {'border': entry['color']}}, borderWidthSelected=5)
            exists.append(src)

        fix_list = [346,26,82]
        for src in fix_list:
            my_img = '/static/icons/pokemon_icon_%s_%s.png' % (f'{src:03}', t)
            net.add_node(src, ' ', image=my_img, shape='circularImage', size=50, color={'highlight': {'border': entry['color']}}, borderWidthSelected=5)

        for entry in self.edge_data:
            src = entry['challenger_id']
            pokemon = entry['challenger']
            opponent = entry['opponent']
            if opponent.lower() not in self.include:
                continue
            if pokemon.lower() not in self.include:
                continue
            dst = entry['opponent_id']
            w = entry['weight']/10
            net.add_edge(src, dst, value=w, arrows='to', arrowStrikethrough=False, smooth=True, color={"color": entry['color'], "highlight": entry['color'], "opacity": 0.05}, selfReferenceSize=50)

        net.set_edge_smooth('continuous')
        #net.show_buttons(filter_=['physics'])
        os.makedirs("/data/%s" % self.config['settings']['cup'], exist_ok=True)
        net.save_graph("/data/%s/%svs%s.html" % (self.config['settings']['cup'], self.config['settings']['my_shield'], self.config['settings']['op_shield']))
        return True
    except Exception as e:
      traceback.print_exc()
      logging.info(e)
Пример #8
0
def netView_sat(nlp_data_dataframe, year):
    '''
    Function to generate the network view.
    Input: Dataframe
    Output: Network chart
    '''
    from pyvis.network import Network

    nlp_net = Network(height="750px",
                      width="100%",
                      bgcolor="#222222",
                      font_color="white")

    # set the physics layout of the network
    nlp_net.force_atlas_2based()

    sources = nlp_data_dataframe.loc[:, 'Source']
    targets = nlp_data_dataframe.loc[:, 'Target']
    weights = nlp_data_dataframe['Weight']

    edge_data = zip(sources, targets, weights)

    for e in edge_data:
        src = e[0]
        dst = e[1]
        w = e[2]

        nlp_net.add_node(src, src, title=src)
        nlp_net.add_node(dst, dst, title=dst)
        nlp_net.add_edge(src, dst, value=w)

    neighbor_map = nlp_net.get_adj_list()

    # add neighbor data to node hover data
    for node in nlp_net.nodes:
        node[
            "title"] += "<br>Neighbors:<br><style>body{font-size:18px;}</style>" + "<br>".join(
                neighbor_map[node["id"]])
        node["value"] = len(neighbor_map[node["id"]])
    nlp_net.toggle_stabilization(True)
    nlp_net.show_buttons(filter_=['physics'])
    nlp_net.show("NLP-Enquete-Satisfied" + year + ".html")
from pyvis.network import Network
import networkx as nx
import pandas as pd
from collections import Counter

net = Network(height="1000px", width="100%",directed=True,bgcolor="#222222", font_color="white")

# set the physics layout of the network
net.barnes_hut()
net.force_atlas_2based()
data = pd.read_csv("details.csv",encoding = "ISO-8859-1", error_bad_lines=False) 

people = data['Person']
supervisors = data['Supervisor']
jobtype = data['Type']

color = {'PhD' : 'blueviolet' , 'postdoc' : 'magenta' , 'link' : 'turquoise'}

all_people = set(list(people)+list(supervisors))
#node_size = Counter(supervisors)

for person in all_people:
    net.add_node(person, title=person,size=5) #,shape='ellipse')

for person, supervisor, job in zip(people,supervisors, jobtype):
    if job != 'link':
        net.add_edge(supervisor, person, arrow=True,color=color[job])

neighbor_map = net.get_adj_list()

# add neighbor data to node hover data
Пример #10
0
    def extract_neighborhood (self, radius, subgraph, paths, node_id, html_path):
        """
        extract the neighbor entities from the subgraph, while
        generating a network diagram
        """
        hood = RCNeighbors()
        g = Network(notebook=False, height="450px", width="100%")
        g.force_atlas_2based()

        for p in self.prov.values():
            if "used" in p.view:
                p_id = self.get_id(p.view["id"])
        
                if p_id in subgraph:
                    scale, impact = self.scale[p_id]
                    rank = (radius - paths[p_id], 0, 0.0, impact)
                    p.view["rank"] = rank
                    hood.prov.append([ p_id, rank, "{:.4f}".format(impact), p.view["title"], p.view["ror"], True ])

                    title = "{}<br/>rank: {:.4f}<br/>{}".format(p.view["title"], impact, p.view["ror"])
                    g.add_node(p_id, label=p.view["title"], title=title, color="orange", size=scale)

        for d in self.data.values():
            if "used" in d.view:
                d_id = self.get_id(d.view["id"])
        
                if d_id in subgraph:
                    p_id = self.get_id(d.view["provider"])
                    scale, impact = self.scale[d_id]
                    rank = (radius - paths[d_id], 0, 0.0, impact)
                    d.view["rank"] = rank
                    hood.data.append([ d_id, rank, "{:.4f}".format(impact), d.view["title"], self.labels[p_id], True ])

                    title = "{}<br/>rank: {:.4f}<br/>provider: {}".format(d.view["title"], impact, self.labels[p_id])
                    g.add_node(d_id, label=d.view["title"], title=title, color="red", size=scale)

                    if p_id in subgraph:
                        g.add_edge(d_id, p_id, color="gray")

        for a in self.auth.values():
            if "used" in a.view:
                a_id = self.get_id(a.view["id"])

                if a_id in subgraph:
                    if node_id in a.view["mle"]:
                        count, pt_est = a.view["mle"][node_id]
                    else:
                        count = 0
                        pt_est = 0.0

                    scale, impact = self.scale[a_id]
                    rank = (radius - paths[a_id], count, pt_est, impact)
                    a.view["rank"] = rank
                    hood.auth.append([ a_id, rank, "{:.4f}".format(impact), a.view["title"], a.view["orcid"], True ])

                    title = "{}<br/>rank: {:.4f}<br/>{}".format(a.view["title"], impact, a.view["orcid"])
                    g.add_node(a_id, label=a.view["title"], title=title, color="purple", size=scale)

        for t in self.topi.values():
            if "used" in t.view:
                t_id = self.get_id(t.view["id"])

                if t_id in subgraph:
                    if node_id in t.view["mle"]:
                        count, pt_est = t.view["mle"][node_id]
                    else:
                        count = 0
                        pt_est = 0.0

                    scale, impact = self.scale[t_id]
                    rank = (radius - paths[t_id], count, pt_est, impact)
                    t.view["rank"] = rank
                    hood.topi.append([ t_id, rank, "{:.4f}".format(impact), t.view["title"], None, True ])

                    title = "{}<br/>rank: {:.4f}".format(t.view["title"], impact)
                    g.add_node(t_id, label=t.view["title"], title=title, color="cyan", size=scale)

        for j in self.jour.values():
            if "used" in j.view:
                j_id = self.get_id(j.view["id"])

                if j_id in subgraph:
                    if j.view["title"] == "unknown":
                        shown = False
                    else:
                        shown = True

                    if node_id in j.view["mle"]:
                        count, pt_est = j.view["mle"][node_id]
                    else:
                        count = 0
                        pt_est = 0.0

                    scale, impact = self.scale[j_id]
                    rank = (radius - paths[j_id], count, pt_est, impact)
                    j.view["rank"] = rank
                    hood.jour.append([ j_id, rank, "{:.4f}".format(impact), j.view["title"], j.view["issn"], shown ])

                    title = "{}<br/>rank: {:.4f}<br/>{}".format(j.view["title"], impact, j.view["issn"])
                    g.add_node(j_id, label=j.view["title"], title=title, color="green", size=scale)

        for p in self.publ.values():
            p_id = self.get_id(p.view["id"])

            if p_id in subgraph:
                if len(p.view["title"]) >= self.MAX_TITLE_LEN:
                    abbrev_title = p.view["title"][:self.MAX_TITLE_LEN] + "..."
                else:
                    abbrev_title = p.view["title"]

                scale, impact = self.scale[p_id]
                rank = (radius - paths[p_id], 0, 0.0, impact)
                p.view["rank"] = rank
                hood.publ.append([ p_id, rank, "{:.4f}".format(impact), abbrev_title, p.view["doi"], True ])

                title = "{}<br/>rank: {:.4f}<br/>{}".format(p.view["title"], impact, p.view["doi"])
                g.add_node(p_id, label=p.view["title"], title=title, color="blue", size=scale)

                if p.view["journal"]:
                    j_id = self.get_id(p.view["journal"])

                    if j_id in subgraph:
                        g.add_edge(p_id, j_id, color="gray")

                for d in p.view["datasets"]:
                    d_id = self.get_id(d)
            
                    if d_id in subgraph:
                        g.add_edge(p_id, d_id, color="gray")

                for a in p.view["authors"]:
                    a_id = self.get_id(a)
            
                    if a_id in subgraph:
                        g.add_edge(p_id, a_id, color="gray")

                for t in p.view["topics"]:
                    t_id = self.get_id(t)
            
                    if t_id in subgraph:
                        g.add_edge(p_id, t_id, color="gray")

        #g.show_buttons()
        g.write_html(html_path, notebook=False)

        return hood
Пример #11
0
net = Network(height="750px",
              width="100%",
              bgcolor="#222222",
              font_color="white")

# file_name = 'Friends_DF.csv'
file_name = 'File_CSV.csv'
f = os.path.abspath(file_name)
table = pd.read_csv(f)

row_count = len(table['name'])  # сколько строчек
TIME_LIMIT = 60
USER = table['name'][0]

if row_count > 1500:
    net.force_atlas_2based(gravity=-1000)
else:
    net.barnes_hut()  # растановка nodes


def show_graph():
    net.show("facebook_net.html")
    plt.axis('off')  # hide the axes
    mpld3.show()


def create_graph():
    sources = table['name']
    targets = table['friend']
    edge_data = zip(sources, targets)
Пример #12
0
    parser.print_help()
    exit(0)

main_domain = args.domain

# net =  Network(height="100%", width="100%", heading="{} - Graph".format(main_domain), bgcolor="#2d2e2e", font_color="white")
net = Network(
    height="100%",
    width="100%",
    heading=
    '<script>document.getElementsByTagName("center")[0].remove()</script>',
    bgcolor="#2d2e2e",
    font_color="white")
# net.barnes_hut()
# net.repulsion()
net.force_atlas_2based(gravity=-500, damping=2.0, overlap=5.0)
# net.hrepulsion(damping=5)
# def read_subdomain_data():
# with open("subdomain.txt", "rb") as f:
#     # data = read_subdomain_data()
#     json_data = {} #{"domain" : "tiket.com"}
#     for i in f.readlines():
#         tmp = i.split()
#         ip = tmp[0].decode()
#         domains = filter(None, tmp[1].decode().split(","))
#         # print(list(tmp))
#         # json_data[ip] = []
#         json_data[ip] = []
#         # json_data["ip"].append({ip : []})
#         # subdomain_data = tmp[1]
#         for domain in list(domains):
Пример #13
0
d = pd.merge(d, player)
d = pd.merge(d, team)

d = d.sort_values('cnt', ascending=False)

d['pick_str'] = d['team_pick'] + ' - ' + d['cnt'].astype('str') + ' times'
d['player_pick_str'] = d['player'] + ' - ' + d['cnt'].astype('str') + ' times'

nt = Network(
    directed=False,
    # notebook=True,
    height="480px",
    width="1260px",
    heading='')

nt.force_atlas_2based(damping=2)

with streamlit_analytics.track(unsafe_password="******"):
    icon = st.checkbox('Show icons (slows it down a bit)')

for i, r in d.iterrows():
    nt.add_node(r['player'],
                size=r['times_picked'],
                color={
                    'background': '#40D0EF',
                    'border': '#03AED3'
                },
                title='<b>' + r['player'] + ' - Picked ' +
                str(r['times_picked']) + '  times </b> <br> ' +
                d.loc[d.player == r['player']].groupby('player').apply(
                    lambda x: ', <br>'.join(x.pick_str)).to_frame(
Пример #14
0
my_obj = pd.DataFrame(final, columns=["Source", "Target", "Weight"])

# Write Pandas DataFrame as csv file
my_obj.to_csv(key+'.csv', encoding='utf-8', index=False)

# Write Pandass DataFrame as json file
# my_obj.to_json(key+".json")

# Create Network Graph/
ts_net = Network(height="100%", width="100%",
                 bgcolor="#222222", font_color="white")

# set the physics layout of the network
# ts_net.repulsion(damping=0.9, spring_length=200, node_distance=350)
if net_type == "atlas":
    ts_net.force_atlas_2based(gravity=-50, central_gravity=0.01,
                              spring_length=100, spring_strength=0.08, damping=0.4, overlap=0)
if net_type == "barnes":
    ts_net.barnes_hut(gravity=-80000, central_gravity=0.3,
                      spring_length=25, spring_strength=0.001, damping=0.09, overlap=0)
if net_type == "repulsion":
    ts_net.repulsion(damping=0.9, spring_length=200, node_distance=350)
if net_type == "hrepulsion":
    ts_net.hrepulsion(node_distance=120, central_gravity=0.0,
                      spring_length=100, spring_strength=0.01, damping=0.09)

ts_data = pd.read_csv(key+".csv")

# Call Columns in csv File by Column Names
sources = ts_data['Source']
targets = ts_data['Target']
weights = ts_data['Weight']
Пример #15
0
def create_and_return_flow_diagram(request_dict,
                                   path_to_reactions=path_to_reactions,
                                   path_to_template=path_to_template,
                                   csv_results_path=csv_results_path_default):
    global userSelectedMinMax
    global minAndMaxOfSelectedTimeFrame
    global previous_vals
    global csv_results_path_default
    
    logging.info("using csv_results_path: " + csv_results_path)
    csv_results_path_default = csv_results_path

    if (('maxMolval' in request_dict and 'minMolval' in request_dict)
        and (request_dict['maxMolval'] != ''
        and request_dict['minMolval'] != '')
        and (request_dict['maxMolval'] != 'NULL'
             and request_dict['minMolval'] != 'NULL')):
        userSelectedMinMax = [
            float(request_dict["minMolval"]),
            float(request_dict["maxMolval"])]
        logging.info("new user selected min and max: " + str(userSelectedMinMax))
    if 'startStep' not in request_dict:
        request_dict.update({'startStep': 1})

    if 'maxArrowWidth' not in request_dict:
        request_dict.update({'maxArrowWidth': 10})
    minAndMaxOfSelectedTimeFrame = [999999999999, -1]
    # load csv file
    
    csv = pd.read_csv(csv_results_path)

    start_step = int(request_dict['startStep'])
    end_step = int(request_dict['endStep'])

    # scale with correct scaling function
    scale_type = request_dict['arrowScalingType']
    max_width = request_dict['maxArrowWidth']

    previousMin = float(request_dict["currentMinValOfGraph"])
    previousMax = float(request_dict["currentMaxValOfGraph"])
    previous_vals = [previousMin, previousMax]

    isPhysicsEnabled = request_dict['isPhysicsEnabled']
    if isPhysicsEnabled == 'true':
        max_width = 2  # change for max width with optimized performance

    # load species json and reactions json

    with open(path_to_reactions, 'r') as f:
        reactions_data = json.load(f)

    # completely new method of creating nodes and filtering elements
    selected_species = request_dict['includedSpecies'].split(',')
    blockedSpecies = request_dict['blockedSpecies'].split(',')

    (network_content, raw_yields, edgeColors, quantities, minVal, maxVal,
     raw_yield_values, species_colors, species_sizes,
     total_quantites,
     reaction_names_on_hover) = new_find_reactions_and_species(
        selected_species, reactions_data, blockedSpecies,
        csv, start_step, end_step, max_width, scale_type,
        csv_results_path)

    # add edges and nodes
    # force network to be 100% width and height before it's sent to page
    net = Network(height='100%', width='100%', directed=True)
    # make it so we can manually change arrow colors
    net.inherit_edge_colors(False)
    shouldMakeSmallNode = False
    if isPhysicsEnabled == "true":
        net.toggle_physics(False)
        net.force_atlas_2based()
    else:
        net.force_atlas_2based(gravity=-200, overlap=1)
    
    reac_nodes = network_content['reaction_nodes']
    hover_names = reaction_names_on_hover
    names = [getReactName(hover_names, x) for x in reac_nodes]
    colors = [species_colors[x] for x in network_content['species_nodes']]
    if shouldMakeSmallNode:
        net.add_nodes(names, color=["#FF7F7F" for x in reac_nodes], size=[
                      10 for x in list(reac_nodes)], title=names)
        net.add_nodes(network_content['species_nodes'], color=colors,
                      size=[
                        10 for x in list(network_content['species_nodes'])])
    else:
        net.add_nodes(names, color=[
                      "#FF7F7F" for x in reac_nodes], title=names)
        net.add_nodes(network_content['species_nodes'], color=colors,
                      size=[species_sizes[x] for x in list(
                        network_content['species_nodes'])])
    net.set_edge_smooth('dynamic')
    # add edges individually so we can modify contents
    i = 0
    values = edgeColors
    for edge in network_content['edges']:
        unbeu1 = unbeautifyReaction(edge[0])
        unbeu2 = unbeautifyReaction(edge[1])
        val = unbeu1+"__TO__"+unbeu2

        flux = str(raw_yields[unbeu1+"__TO__"+unbeu2])
        colorVal = ""
        try:
            colorVal = values[val]
        except KeyError:
            colorVal = values[val.replace('->', '-')]
        if colorVal == "#e0e0e0":
            # don't allow blocked edge to show value on hover
            if "→" in edge[0]:
                be1 = beautifyReaction(reaction_names_on_hover[unbeu1])
                net.add_edge(be1, edge[1], color=colorVal, width=edge[2])
            elif "→" in edge[1]:
                try:
                    be2 = beautifyReaction(reaction_names_on_hover[unbeu2])
                    net.add_edge(edge[0], be2, color=colorVal, width=edge[2])
                except KeyError:
                    be2 = beautifyReaction(unbeu2)
                    net.add_edge(edge[0], be2, color=colorVal, width=edge[2])
            else:
                net.add_edge(edge[0], edge[1],
                             color=colorVal, width=edge[2])
        else:
            # hover over arrow to show value for arrows within range

            # check if value is reaction by looking for arrow
            if "→" in edge[0]:
                be1 = beautifyReaction(reaction_names_on_hover[unbeu1])
                net.add_edge(be1, edge[1], color=colorVal, width=float(
                             edge[2]), title="flux: "+flux)
            elif "→" in edge[1]:
                try:
                    be2 = beautifyReaction(reaction_names_on_hover[unbeu2])
                    net.add_edge(edge[0], be2, color=colorVal, width=float(
                        edge[2]), title="flux: "+flux)
                except KeyError:
                    be2 = beautifyReaction(unbeu2)
                    net.add_edge(edge[0], be2, color=colorVal, width=float(
                        edge[2]), title="flux: "+flux)
            else:
                net.add_edge(edge[0], edge[1], color=colorVal,
                             width=float(edge[2]), title="flux: "+flux)
        i = i+1
    net.show(path_to_template)
    if minAndMaxOfSelectedTimeFrame[0] == minAndMaxOfSelectedTimeFrame[1]:
        minAndMaxOfSelectedTimeFrame = [0, maxVal]
    with open(path_to_template, 'r+') as f:
        #############################################
        # here we are going to replace the contents #
        #############################################
        a = """<script>
        network.on("stabilizationIterationsDone", function () {
            network.setOptions( { physics: false } );
        });
        </script>"""
        logging.debug("((DEBUG)) [min,max] of selected time frame: " +
              str(minAndMaxOfSelectedTimeFrame))
        logging.debug("((DEBUG)) [min,max] given by user: "******"""<script>
        parent.document.getElementById("flow-start-range2").value = "NULL";
        parent.document.getElementById("flow-end-range2").value = "NULL";
        console.log("inputting NULL");"""

        else:
            a = '<script>\
            parent.document.getElementById("flow-start-range2").value = \
            "'+formattedMinOfSelected+'";'
            a += 'parent.document.getElementById("flow-end-range2").value = \
                "'+str(
                formattedMaxOfSelected)+'";'
        a += """
        currentMinValOfGraph = """+formattedPrevMin+""";
        currentMaxValOfGraph = """+formattedPrevMax+""";
        """
        if (str(formattedPrevMin) != str(formattedMinOfSelected)
            or str(formattedPrevMax) != str(formattedMaxOfSelected)
                or previousMax == 1):
            logging.debug("previousMin:" + str(formattedPrevMin) + 
                  "does not equal " + str(formattedMinOfSelected))
            logging.debug("previousMax: " + str(formattedPrevMax) +
                  " does not equal " + str(formattedMaxOfSelected))
            logging.debug("previousMin: " + str(previousMin) + " equals 0")
            logging.debug("previousMax: " + str(previousMax) + " equals 1")
            a += 'parent.document.getElementById("flow-start-range2").value =\
                "'+str(formattedMinOfSelected)+'";\
                    parent.document.getElementById("flow-end-range2").value =\
                "'+str(formattedMaxOfSelected)+'";'
            a += ('parent.reloadSlider("'+str(formattedMinOfSelected)+'","'
                  + str(formattedMaxOfSelected)+'", "'+str(
                  formattedMinOfSelected)+'", "'
                  + str(formattedMaxOfSelected)+'", '+str(get_step_length(csv_results_path))+');</script>')
        else:
            logging.debug("looks like min and max are the same")
            isNotDefaultMin = int(userSelectedMinMax[0]) != 999999999999
            isNotDefaultmax = int(userSelectedMinMax[1]) != -1
            block1 = 'parent.document.getElementById("flow-start-range2")'
            rangeId = block1+'.value = '
            if isNotDefaultmax or isNotDefaultMin:
                a += (rangeId+str(
                    formattedUserMin)+'"; \
                        '+rangeId+'"'+formattedUserMax+'";')
                block1 = 'parent.reloadSlider("' + formattedUserMin + '", "'
                fmos = str(formattedMinOfSelected)
                block2 = formattedUserMax + '", "' + fmos
                block3 = '", "' + formattedMaxOfSelected + '", '+str(get_step_length(csv_results_path))+');\
                         </script>'
                a += block1 + block2 + block3
            else:
                fmos = formattedMinOfSelected
                block1 = 'parent.reloadSlider("' + fmos + '", "'
                block2 = formattedMaxOfSelected + '", "' + str(fmos)
                a += block1 + '", "' + formattedMaxOfSelected + '", '+str(get_step_length(csv_results_path))+');</script>'
        if isPhysicsEnabled == 'true':
            # add options to reduce text size
            a += \
                """<script>
                var container = document.getElementById("mynetwork");
                var options = {physics: false,
                                nodes: {
                                    shape: "dot",
                                    size: 10,
                                    font: {size: 5}
                                    }
                                };
                var network = new vis.Network(container, data, options);
                </script>"""

        lines = f.readlines()
        for i, line in enumerate(lines):
            # find a pattern so that we can add next to that line
            if line.startswith('</script>'):
                lines[i] = lines[i]+a
        f.truncate()
        f.seek(0)  # rewrite into the file
        for line in lines:
            f.write(line)
        f.close()
    # read from file and return the contents
    with open(path_to_template, 'r') as f:
        return f.read()
Пример #16
0
                bgcolor="white",
                font_color="#444444",
                directed=True,
                heading='',
                notebook=True)
for link in graph_file['links']:
    similarity = float(link['weight'])
    if similarity >= threshold and similarity != 1.0:
        graph.add_node(link['source'], size=10, color='#78CABC')
        graph.add_node(link['target'], size=10, color='#78CABC')
        graph.add_edge(link['source'],
                       link['target'],
                       weight=round(similarity * 100))
        page_graph.add_edge(link['source'], link['target'], weight=similarity)

graph.force_atlas_2based()
graph.show('graph.html')
st_graph('graph.html')

#Page Rank
st.header('Page Rank')
n_words = st.sidebar.slider("Page Rank", 1, 20, 10)
summary, ranks = page_rank(n_words, page_graph)
word_dict = {word: ranks[word] for word in summary[:n_words]}
plt.barh(list(word_dict.keys()), list(word_dict.values()), align='center')
plt.gca().invert_yaxis()
st.pyplot()

#NER POS
st.subheader("Sentence")
text = st.selectbox("", sentences)