Ejemplo n.º 1
0
    def observe(self):
        """
        :return: Current time stamp job-shop graph
        """

        g = nx.OrderedDiGraph()
        for job_id, job in self.jobs.items():
            for op in job.ops:
                not_start_cond = not (op == job.ops[0])
                not_end_cond = not isinstance(op, EndOperation)

                g.add_node(op.id, **op.x)

                if not_end_cond:  # Construct forward flow conjunctive edges only
                    g.add_edge(op.id,
                               op.next_op.id,
                               distance=(op.next_op.complete_ratio -
                                         op.complete_ratio),
                               type=CONJUNCTIVE_TYPE,
                               direction=FORWARD)

                    for disj_op in op.disjunctive_ops:
                        g.add_edge(op.id, disj_op.id, type=DISJUNCTIVE_TYPE)

                if not_start_cond:
                    g.add_edge(op.id,
                               op.prev_op.id,
                               distance=-(op.complete_ratio -
                                          op.prev_op.complete_ratio),
                               type=CONJUNCTIVE_TYPE,
                               direction=BACKWARD)

        return g
Ejemplo n.º 2
0
def build_sent_graph(df_sent):
    """Builds the dependency graph of a sentence."""
    sent_graph = nx.OrderedDiGraph()
    for index, row in df_sent.iterrows():
        try:
            dep_id, head_id, dep_form = row[0], row[6], row[1]
            pos, deprel = row[3], row[7]
            node_label = row[11]
            sent_graph.add_node(dep_id,
                                attr={
                                    'form': dep_form,
                                    'pos': pos,
                                    'deprel': deprel,
                                    'node_label': node_label
                                })
            sent_graph.add_edge(dep_id, head_id, edge_label='0')
        except IndexError as e:
            print(e)
    sent_graph.node['0']['attr'] = {
        'form': 'DUMMY-ROOT-FORM',
        'pos': 'DUMMY-ROOT-POS',
        'deprel': 'root',
        'node_label': '0'
    }
    return sent_graph
Ejemplo n.º 3
0
    def __init__(self, parameters):
        '''Set the graph up with all initial data and pruning.
        
        This includes parsing the graph file, pruning hubs of the graph
        and initializing vertex beliefs, vertex reliabilities and trust
        values on edges.
        '''
        self.parameters = parameters

        self.centrality_methods = {
            'degree': nx.out_degree_centrality,
            'closeness': nx.closeness_centrality,
            'betweenness': nx.betweenness_centrality,
            'eigenvector': self.eigenvectorCentrality,
            'random': self.randomCentrality,
            'sgd': self.sgdCentrality
        }

        G = nx.read_edgelist(parameters["graph_filepath"],
                             create_using=nx.OrderedGraph())

        self.graph = nx.OrderedDiGraph(G.to_directed())
        self.pruneGraph()

        self.initializeData()
Ejemplo n.º 4
0
    def convert_to_compact(self, G, store_features):
        """Generates a compact networkx graph for the input graph. The features of each node and
        edge are converted to room categories and behavior categories, which may result in a loss
        of information (e.g. s_r -> s category) in the networkx compact graph.
        """
        nxG_compact = nx.OrderedDiGraph()

        # Create nodes
        for node in G.nodes:
            # Create node
            if store_features is True:  # Store a features attribute
                nxG_compact.add_node(node.name, room_category=room2category(node.name),
                                     features=node['features'])
            else:
                nxG_compact.add_node(node.name, room_category=room2category(node.name))

        # Create edges
        for u, v, edge in G.edges(data='object'):
            if store_features is True:
                nxG_compact.add_edge(u.name, v.name,
                                     behavior_category=behavior_id2category(edge.behavior_id),
                                     features=edge['features'])
            else:
                nxG_compact.add_edge(u.name, v.name,
                                     behavior_category=behavior_id2category(edge.behavior_id))

        assert len(nxG_compact.nodes) == len(G.nodes)
        assert len(nxG_compact.edges) == len(G.edges)

        return nxG_compact
Ejemplo n.º 5
0
def get_graph(input_type, loader, transformers):
    """Given a loader and its transformer return path to desired format
    e.g which output format should each transformer pick to be chained to the following one
    in order to obtain the desired outcome for format
    :param input_type: input type of first node
    :type input_type: str
    :param loader: original loader
    :type loader: KoshLoader
    :param transformers: set of transformers to be added after loader exits
    :type transformers: list of KoshTransformer
    :returns: execution graph
    :rtype: networkx.OrderDiGraph
    """
    if input_type not in loader.types:
        raise RuntimeError(
            "loader cannot load mime_type {}".format(input_type))
    G = nx.OrderedDiGraph()
    G.seed = random.random()
    start_node = (input_type, loader, G.seed)  # so each graph is unique
    G.add_node(start_node)
    if len(transformers) == 0:
        # No transformer
        for out_format in loader.types[input_type]:
            node = (out_format, None, G.seed)
            G.add_edge(start_node, node)
    else:
        populate(G, start_node, loader.types[input_type], transformers)
    return G
Ejemplo n.º 6
0
    def _find_longest_path(self, cell):
        """

        :param cell: a list contains operations and node number such as Genotype.normal or Genotype.reduce
        :return longest_path: : the longest path in the Genotype.normal or Genotype.reduce as defined in Understanding-NAS
        """
        g = nx.OrderedDiGraph()

        g.add_node("c_{k-2}")
        g.add_node("c_{k-1}")
        assert len(cell) % 2 == 0
        steps = len(cell) // 2

        for i in range(steps):
            g.add_node(str(i))

        for i in range(steps):
            for k in [2 * i, 2 * i + 1]:
                op, j = cell[k]
                if j == 0:
                    u = "c_{k-2}"
                elif j == 1:
                    u = "c_{k-1}"
                else:
                    u = str(j - 2)
                v = str(i)
                g.add_edge(u, v, label=op)

        g.add_node("c_{k}")
        for i in range(steps):
            g.add_edge(str(i), "c_{k}")

        longest_path = len(nx.dag_longest_path(g)) - 1

        return longest_path
Ejemplo n.º 7
0
    def __init__(self, input_model):
        super(NNEFImporter, self).__init__()

        self.graph_name = ""
        self.input_model = input_model
        self.nxgraph = nx.OrderedDiGraph()
        self.node_pool = collections.OrderedDict()
Ejemplo n.º 8
0
def test_html_like_labels():
    graph = nx.OrderedDiGraph()
    graph.add_node(
        0,
        label=H.table([
            H.table_row([H.table_cell("A", attributes={"COLSPAN": 2})]),
            H.table_row([H.table_cell("C"),
                         H.table_cell("D")]),
        ]),
    )
    graph.add_node(1, label=H.bold('3 < 7 "hello" & "world" 5 > 2'))
    graph.add_node(2, label=H.join(["hello", H.italic("world")]))
    graph.add_edge(0, 1)
    style = nxv.Style(node=lambda u, d: d)
    actual = nxv.render(graph, style, format="raw")
    expected = textwrap.dedent("""
        digraph "G" {
            graph [];
            node0000 [label=<<TABLE><TR><TD COLSPAN="2">A</TD></TR><TR><TD>C</TD><TD>D</TD></TR></TABLE>>];
            node0001 [label=<<B>3 &lt; 7 &quot;hello&quot; &amp; &quot;world&quot; 5 &gt; 2</B>>];
            node0002 [label=<hello<I>world</I>>];
            node0000 -> node0001 [];
        }
        """).strip()
    assert actual == expected
Ejemplo n.º 9
0
def basic() -> nx.OrderedDiGraph:
    """
    Fairly simple graph for testing
    Returns:
        A simple graph
    """
    graph = nx.OrderedDiGraph()
    graph.add_nodes_from([0, 1, 2, 3, 4, 5])
    graph.add_edge(0, 1, weight=5000)
    graph.add_edge(1, 0, weight=5000)
    graph.add_edge(0, 5, weight=5000)
    graph.add_edge(5, 0, weight=5000)
    graph.add_edge(1, 2, weight=5000)
    graph.add_edge(2, 1, weight=5000)
    graph.add_edge(1, 5, weight=5000)
    graph.add_edge(5, 1, weight=5000)
    graph.add_edge(2, 4, weight=5000)
    graph.add_edge(4, 2, weight=5000)
    graph.add_edge(2, 5, weight=5000)
    graph.add_edge(5, 2, weight=5000)
    graph.add_edge(3, 4, weight=5000)
    graph.add_edge(4, 3, weight=5000)
    graph.add_edge(4, 5, weight=5000)
    graph.add_edge(5, 4, weight=5000)
    return graph
Ejemplo n.º 10
0
    def __init__(self,
                 plot=False,
                 numUsers=1,
                 numMalUsers=0,
                 traPerUser=0,
                 reattachment=False):
        self.time = 1.0
        self.realtime = timeee.time()

        print("DAG: numUsers:" + str(numUsers) + " numMalUsers:" +
              str(numMalUsers) + " traPerUser:"******" reattachment:" + str(reattachment))

        if plot:
            self.graph = nx.OrderedDiGraph()

        self.nodes = []
        self.addedNodes = []
        self.unvalidatedNodes = []
        self.users = []
        self.currTime = 0
        self.nodesToAdd = []
        self.traPerUser = traPerUser
        self.reattachment = reattachment
        self.numMalUsers = numMalUsers

        if numUsers < 3:
            self.users.append(User(id=0, malicious=False))
        # TODO: Num mal needs to be 2lower i sayfaya ekle
        else:
            malUserIds = np.random.choice(range(2, numUsers), numMalUsers)
            for i in range(numUsers):
                self.users.append(User(id=i, malicious=(i in malUserIds)))
Ejemplo n.º 11
0
def TwoTask(networkGraph = None, nTasks=0, deltax = 100, mobileNodeCount = 0,**kwargs):
    #reset global taskId counter
    assert networkGraph is not None, "Network Graph for Task Gen is None"
    #assert nTasks > 1, "Cant create TwoTaskWithProcessing with less than 2 tasks"
    Task.taskId = 1
    G = nx.OrderedDiGraph()
    pos1 = list(networkGraph.nodes())[0].pos
    bound1 = np.array([np.array([pos1[0]-deltax+1,pos1[0]+deltax-1]), np.array([pos1[1]-deltax+1,pos1[1]+deltax-1])])
    pos2 = list(networkGraph.nodes())[-(mobileNodeCount+1)].pos
    bound2 = np.array([np.array([pos2[0]-deltax+1,pos2[0]+deltax-1]), np.array([pos2[1]-deltax+1,pos2[1]+deltax-1])])
    first_constraint = {'location' : bound1}
    task1 = Task(first_constraint)
    G.add_node(task1)
    second_constraint = {'location' : bound2}
    task2 = Task(second_constraint)
    G.add_node(task2)
    
    for i, node in enumerate(list(G.nodes())):
        if i == 0:
            continue
        G.add_edge(list(G.nodes())[i-1], node)
    for task in G.nodes():
        task.set_topology(G)
    #for x in list(G.nodes()):
    #    print(x.taskId)
    return G
Ejemplo n.º 12
0
def OneSink(networkGraph = None, deltax = 100, deltay = 100, verbose = False, sink_location = 'center', **kwargs):
    assert networkGraph is not None, "Network Graph for Task Gen is None"
    Task.taskId = 1
    G = nx.OrderedDiGraph()
    if kwargs['network_creator'] == topologies.Grid:
        ndim = kwargs['dimx']
        posCenterx = np.array([list(networkGraph.nodes())[int(ndim/2)].pos[0]-101, list(networkGraph.nodes())[int(ndim/2)].pos[0]+101])
        posCentery = np.array([list(networkGraph.nodes())[int(ndim/2)*ndim].pos[1]-101, list(networkGraph.nodes())[int(ndim/2)*ndim].pos[1]+101])
        boundCenter = np.array([posCenterx, posCentery])
    else:
        midTask = int(kwargs['nTasks']/2) #actually right task of the two middling tasks
        #includes the left neighbor as a possible sink task
        posCenterx = np.array([list(networkGraph.nodes())[midTask].pos[0]-101, list(networkGraph.nodes())[midTask].pos[0]+1])
        boundCenter = np.array([posCenterx, np.array([-np.inf, np.inf])])
    center_constraint = {'location' : boundCenter}
    if verbose:
        print(f"Boundary for center: {boundCenter}")
    
    for i in range(kwargs['nTasks']-1):
        G.add_node(Task({'location' : None}))

    G.add_node(Task(center_constraint))

    for i in range(kwargs['nTasks']-1):
        G.add_edge(list(G.nodes())[i], list(G.nodes())[-1])

    for task in G.nodes():
        task.set_topology(G)

    return G
Ejemplo n.º 13
0
def EncodeDecode(networkGraph = None, nTasks = 19, deltax = 100, deltay = 100, mobileNodeCount = 0, verbose = False, **kwargs):
    assert networkGraph is not None, "Network Graph for Task Gen is None"
    Task.taskId = 1
    G = nx.OrderedDiGraph()
    ndim = kwargs['dimx']
    #encoding happens on the left half of the network,  0 - int(ndim/2)
    validTaskCounts = [5, 13, 19, 25, 31, 37, 43,49,55,61,67,73,79]
    if nTasks ==5:
        n_outer = 1
        n_inner = 1
    else:
        n_outer = int((nTasks-1)/3)
        n_inner = int((n_outer)/2)
    assert nTasks in validTaskCounts, f"{nTasks} is not a valid task count for the EncodeDecode Setup! \n Valid Setups: {validTaskCounts}"
    staticNodes = list(networkGraph.nodes)[:ndim**2]
    posEncode = np.array([list(staticNodes)[0].pos[0]-deltax+1, list(staticNodes)[int(ndim/2)].pos[0]+deltax-1])
    boundEncode = np.array([posEncode, np.array([-np.inf, np.inf])])
    if verbose:
        print(f"Boundary for encode: {boundEncode}")
    posDecode = np.array([list(staticNodes)[int(ndim/2)].pos[0]-deltax+1, list(staticNodes)[-1].pos[0]+deltax-1])
    boundDecode = np.array([posDecode, np.array([-np.inf, np.inf])])
    if verbose:
        print(f"Boundary for Decode: {boundDecode}")
    posCenter = np.array([list(staticNodes)[int(ndim/2)].pos[0]-deltax+1, list(staticNodes)[int(ndim/2)].pos[0]+deltax-1])
    boundCenter = np.array([posCenter, np.array([-np.inf, np.inf])])
    if verbose:
        print(f"Boundary for center: {boundCenter}")

    decode_constraint = {'location' : boundDecode}
    encode_constraint = {'location' : boundEncode}
    center_constraint = {'location' : boundCenter}
    for i in range(n_outer):
        G.add_node(Task(encode_constraint))
    for i in range(n_inner):
        G.add_node(Task())
    G.add_node(Task())
    for i in range(n_inner):
        G.add_node(Task())
    for i in range(n_outer):
        G.add_node(Task(decode_constraint))

    
    #add edges between outer left and inner left:
    for i in range(n_outer):
        for j in range(n_outer, n_outer+n_inner):
            G.add_edge(list(G.nodes())[i], list(G.nodes())[j])
    
    #edges between inner left and center
    for i in range(n_outer, n_outer+n_inner):
        G.add_edge(list(G.nodes())[i], list(G.nodes())[n_outer+n_inner])
    
    for i in range(n_outer+n_inner+1, n_outer+n_inner+1+n_inner):
        G.add_edge(list(G.nodes())[n_outer+n_inner], list(G.nodes())[i])
        for j in range(nTasks - n_outer, nTasks):
            G.add_edge(list(G.nodes())[i], list(G.nodes())[j])
        
    for task in G.nodes():
        task.set_topology(G)

    return G
Ejemplo n.º 14
0
def plot_pred(G, pred, target, devices):
    plt.axes().set_aspect(1.0)  
    
    G = nx.OrderedDiGraph(G, nodelist=range(len(G)))
    plot_graph_edges(G, devices)

    pos=nx.get_node_attributes(G,'pos')
  
    # Fault
    faultpos = G.nodes[target]['pos']
    plt.scatter(faultpos[0], faultpos[1], marker='x', color='red',
                s=130, label='Falta', zorder=25)
           
    # Devices    
    colors = list(map({0.5: 'red', 1: 'None', 1.5: 'black'}.get, devices[:len(G)]))
    nx.set_node_attributes(G, dict(zip(range(len(G)), colors)), 'color')
    nx.set_node_attributes(G, 50, 'size')
    G.nodes[0]['size'] = 150
    ax = nx.draw_networkx_nodes(G, pos, node_shape='s',
                                node_size=[G.nodes[node]['size'] for node in G], 
                                node_color=[G.nodes[node]['color'] for node in G], zorder=20)

    pred = np.array([pred[n] for n in list(G)])
    cmap=plt.cm.viridis
    vmin = 0
    vmax = 1

    ax = nx.draw_networkx_nodes(G, pos, node_size=5000*pred, 
                                alpha=0.2, cmap=cmap, node_color=pred,
                                vmin=vmin, vmax=vmax, zorder=500)
    
    #sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=vmin, vmax=vmax))
    #sm._A = []
    #plt.colorbar(sm,fraction=0.022, pad=0.02, orientation='horizontal')    
    plt.axis('off') 
Ejemplo n.º 15
0
 def sort_graph(G_):
     G_sort = nx.OrderedDiGraph()
     G_sort.graph["id"] = G_.graph["id"]
     G_sort.add_nodes_from(
         sorted(G_.nodes(data=True), key=lambda x: x[1]['order']))
     G_sort.add_edges_from(
         sorted(G_.edges(data=True), key=lambda x: x[2]['order']))
     return G_sort
Ejemplo n.º 16
0
def create_graphs_from_scan_ids(scan_dependents: list, scan_events: dict,
                                ion_injection_times: dict):
    """
    Create Directed Graph from scan dependent relationships

    :param scan_dependents:
    :param scan_events:
    :param ion_injection_times:
    :return:
    :rtype:
    """

    graphs = []
    G = nx.OrderedDiGraph()
    G.add_edges_from(
        sorted(list(scan_dependents), key=operator.itemgetter(0, 1)))
    for subgraph in [G.subgraph(c) for c in nx.weakly_connected_components(G)]:

        edges = sorted(list(subgraph.edges()), key=operator.itemgetter(0, 1))
        nodes = sorted(subgraph.nodes())

        replicates_within, its = collections.OrderedDict(
        ), collections.OrderedDict()
        for n in nodes:
            replicates_within.setdefault(scan_events[n], []).append(n)
            its.setdefault(scan_events[n], []).append(ion_injection_times[n])

        G = nx.OrderedDiGraph()
        for rw in replicates_within:

            scan_info = [(None, None, 0.0)]
            scan_info.extend(
                re.findall(r'([\w\.-]+)@([a-zA-Z]+)(\d+\.\d+)', rw))

            G.add_node(rw,
                       scanids=replicates_within[rw],
                       mslevel=len(scan_info),
                       coltype=scan_info[-1][1],
                       colenergy=float(scan_info[-1][2]),
                       injectiontimes=its[rw],
                       flag=True)
        G.add_edges_from([(scan_events[e[0]], scan_events[e[1]])
                          for e in edges])
        graphs.append(G)

    return graphs
Ejemplo n.º 17
0
 def test_attribute_dict_integrity(self):
     # we must not replace dict-like graph data structures with dicts
     G = nx.OrderedGraph()
     G.add_nodes_from("abc")
     H = to_networkx_graph(G, create_using=nx.OrderedGraph)
     assert list(H.nodes) == list(G.nodes)
     H = nx.OrderedDiGraph(G)
     assert list(H.nodes) == list(G.nodes)
    def observe(self, detach_done=True):
        """
        :return: Current time stamp job-shop graph
        """

        g = nx.OrderedDiGraph()
        for job_id, job in self.jobs.items():
            for op in job.ops:
                not_start_cond = not (op == job.ops[0])
                not_end_cond = not (op == job.ops[-1])

                done_cond = op.x['type'] == DONE_NODE_SIG

                if detach_done:
                    if not done_cond:
                        g.add_node(op.id, **op.x)
                        if not_end_cond:  # Construct forward flow conjunctive edges only
                            g.add_edge(op.id,
                                       op.next_op.id,
                                       processing_time=op.processing_time,
                                       type=CONJUNCTIVE_TYPE,
                                       direction=FORWARD)

                            for disj_op in op.disjunctive_ops:
                                if disj_op.x['type'] != DONE_NODE_SIG:
                                    g.add_edge(op.id,
                                               disj_op.id,
                                               type=DISJUNCTIVE_TYPE)

                        if not_start_cond:
                            if op.prev_op.x['type'] != DONE_NODE_SIG:
                                g.add_edge(op.id,
                                           op.prev_op.id,
                                           processing_time=-1 *
                                           op.prev_op.processing_time,
                                           type=CONJUNCTIVE_TYPE,
                                           direction=BACKWARD)
                else:
                    g.add_node(op.id, **op.x)
                    if not_end_cond:  # Construct forward flow conjunctive edges only
                        g.add_edge(op.id,
                                   op.next_op.id,
                                   processing_time=op.processing_time,
                                   type=CONJUNCTIVE_TYPE,
                                   direction=FORWARD)

                    if not_start_cond:
                        g.add_edge(op.id,
                                   op.prev_op.id,
                                   processing_time=-1 *
                                   op.prev_op.processing_time,
                                   type=CONJUNCTIVE_TYPE,
                                   direction=BACKWARD)

                    for disj_op in op.disjunctive_ops:
                        g.add_edge(op.id, disj_op.id, type=DISJUNCTIVE_TYPE)

        return g
Ejemplo n.º 19
0
 def execution_graph(self, seed=None, verbose=False,
                     png_template="LOADER_GRAPH_{}"):
     """makes a new graph with unique seed
     Helps networkx differentiate between identical loaders/transformers/operators
     :param seed: seed to use for new graph
     :type seed: int
     :param verbose: verbose generation, also generates a png with the grap representation
                     Mostly used for debug purposes
     :type verbose: bool
     :param png_template: template to use to generate graph png in verbose mode
                          "_IN"/"_OUT" will be appended and seed will be fed
     :type png_template: str
     :return a new graph with new seed
     :rtype: networkx.OrderedDiGraph
     """
     G = nx.OrderedDiGraph()
     if seed is None:
         seed = random.random()
     G.seed = seed
     if verbose:
         try:
             if "DISPLAY" not in os.environ or os.environ["DISPLAY"] == "":
                 import matplotlib
                 matplotlib.use("agg", force=True)
             import matplotlib.pyplot as plt
             nx.draw(self._graph)
             plt.show()
             png_name = png_template + "_IN.png"
             plt.savefig(png_name.format(seed))
             plt.clf()
         except ImportError:
             raise RuntimeError("Could not import matplotlib, will not plot anything")
     used_nodes = collections.OrderedDict()
     for (n1, n2) in self._graph.edges():
         if n1 in used_nodes:
             # we already generated a new random number for that node
             N1 = used_nodes[n1]
         else:
             # Never seen that node
             seed = get_seed(self._graph, n1, G.seed)
             N1 = n1[0], n1[1], seed
             used_nodes[n1] = N1
         if n2 in used_nodes:
             # we already generated a new random number for that node
             N2 = used_nodes[n2]
         else:
             # Never seen that node
             seed = get_seed(self._graph, n2, G.seed)
             N2 = n2[0], n2[1], seed
             used_nodes[n2] = N2
         G.add_edge(N1, N2)
     if verbose:
         nx.draw(G)
         plt.show()
         png_name = png_template + "_OUT.png"
         plt.savefig(png_name.format(seed))
         plt.clf()
     return G
Ejemplo n.º 20
0
    def get_graph(self):
        try:
            graph = tree_graph(self.tree)
        except:
            graph = nx.OrderedDiGraph()

        G = nx.drawing.nx_agraph.to_agraph(graph)

        return G, self.active_nodes
Ejemplo n.º 21
0
def sizes_to_graph(fpath, total=True, progress=True):
    if is_path(fpath) and total is True:
        total = count_lines(fpath)

    logger.info("constructing tree")
    g = nx.OrderedDiGraph()
    total_size = 0
    total_descendants = 0

    with ensure_file(fpath, "rb") as f:
        for line in tqdm(f,
                         total=total,
                         desc="adding files to tree",
                         disable=not progress):
            *path_b_items, size_b = line.strip().split(SEP)
            path = SEP.join(path_b_items)
            prefix = ROOT + os.sep.encode()
            if not path.startswith(prefix):
                path = os.path.join(ROOT, path)
            size = int(size_b)
            g.add_node(path, size=size, descendants=0)
            total_size += size
            total_descendants += 1

            child = path
            for parent in path_parents(path):
                parent_in_g = parent in g

                # calculate size and descendants up front: probably slower
                # child_d = g.nodes[child]
                # if parent_in_g:
                #     parent_d = g.nodes[parent]
                #     parent_d["size"] += child_d["size"]
                #     parent_d["descendants"] += 1 + child_d["descendants"]
                # else:
                #     total_descendants += 1
                #     g.add_node(
                #         parent,
                #         size=child_d["size"],
                #         descendants=child_d["descendants"] + 1
                #     )

                g.add_edge(parent, child)
                # allow size and descendants to be calculated later
                if parent_in_g:
                    break
                total_descendants += 1
                child = parent

    logger.info(
        "constructed tree with files of total size %s",
        ieee_size(total_size),
    )
    g.graph["total_size"] = total_size
    g.graph["total_descendants"] = total_descendants - 1
    return g
    def call(self):
        DG = nx.OrderedDiGraph()

        edge_labels = self.get_edge_labels()
        edge_colors = self.get_edge_colors()

        levels = {}
        for n in self.nodes:

            if n.state():
                color = '#9bba5e' if n.first_fixed else '#5eba7d'
            else:
                color = '#d0d0d0'
            DG.add_node(n.pi, label=n.s_binary(), color=color)
            if n.level() in levels:
                levels[n.level()] = levels[n.level()] + 1
            else:
                levels[n.level()] = 1
            for p in list(n.elements.keys()):
                if n.pi != p:
                    DG.add_edge(p, n.pi)

        node_positions = {}
        tmp = levels.copy()
        for n in self.nodes:
            l = n.level()
            st = -50 * l
            sp = (400 + l * 100) / (levels[l] + 1)
            node_positions[n.pi] = (sp * (levels[l] - tmp[l] + 1) + st,
                                    -50 * l)
            tmp[l] = tmp[l] - 1

        colors = list(map(lambda n: n[1]['color'], DG.nodes(data=True)))
        labels = {node[0]: node[1]['label'] for node in DG.nodes(data=True)}

        edge_colors_ord = list(
            map(lambda e: edge_colors[e[0], e[1]], DG.edges(data=True)))

        plt.figure(figsize=(10, 8))
        nx.draw(DG,
                connectionstyle='arc3, rad = 0.03',
                node_size=600,
                node_color=colors,
                pos=node_positions,
                prog='dot',
                labels=labels,
                edge_color=edge_colors_ord,
                font_size=7)
        nx.draw_networkx_edge_labels(DG,
                                     node_positions,
                                     edge_labels=edge_labels,
                                     font_size=6,
                                     label_pos=0.25)

        #     plt.axis('off')
        plt.show()
Ejemplo n.º 23
0
def load_qrep(fn):
    assert ".pkl" in fn
    with open(fn, "rb") as f:
        query = pickle.load(f)

    query["subset_graph"] = \
            nx.OrderedDiGraph(json_graph.adjacency_graph(query["subset_graph"]))
    query["join_graph"] = json_graph.adjacency_graph(query["join_graph"])

    return query
Ejemplo n.º 24
0
def random_ordered_tree(n, seed=None, pool=None):
    import kwarray
    rng = kwarray.ensure_rng(seed, 'python')
    tree = nx.dfs_tree(nx.random_tree(n, seed=seed))
    otree = nx.OrderedDiGraph()
    otree.add_edges_from(tree.edges)
    if pool is not None:
        for node in otree.nodes:
            otree.nodes[node]['label'] = rng.choice(pool)
    return otree
Ejemplo n.º 25
0
    def get_graph(self):
        # Create a graph from the JSON data, or fall back to an empty graph
        try:
            graph = tree_graph(self.tree)
        except:
            graph = nx.OrderedDiGraph()

        G = nx.drawing.nx_agraph.to_agraph(graph)

        return G, self.active_nodes
Ejemplo n.º 26
0
def tree_graph(data, attrs=_attrs):
    """Return graph from tree data format.

    Parameters
    ----------
    data : dict
        Tree formatted graph data

    Returns
    -------
    G : NetworkX OrderedDiGraph

    attrs : dict
        A dictionary that contains two keys 'id' and 'children'. The
        corresponding values provide the attribute names for storing
        NetworkX-internal graph data. The values should be unique. Default
        value: :samp:`dict(id='id', children='children')`.

    Examples
    --------
    >>> from networkx.readwrite import json_graph
    >>> G = nx.OrderedDiGraph([(1,2)])
    >>> data = json_graph.tree_data(G,root=1)
    >>> H = json_graph.tree_graph(data)

    Notes
    -----
    The default value of attrs will be changed in a future release of NetworkX.

    See Also
    --------
    tree_graph, node_link_data, adjacency_data
    """
    graph = nx.OrderedDiGraph()
    id_ = attrs['id']
    children = attrs['children']

    def add_children(parent, children_):
        for data in children_:
            child = data[id_]
            graph.add_edge(parent, child)
            grandchildren = data.get(children, [])
            if grandchildren:
                add_children(child, grandchildren)
            nodedata = dict((make_str(k), v) for k, v in data.items()
                            if k != id_ and k != children)
            graph.add_node(child, **nodedata)

    root = data[id_]
    children_ = data.get(children, [])
    nodedata = dict((make_str(k), v) for k, v in data.items()
                    if k != id_ and k != children)
    graph.add_node(root, **nodedata)
    add_children(root, children_)
    return graph
Ejemplo n.º 27
0
def crear_grafo(circuito):
    g = nx.OrderedDiGraph()
    for i in range(0, len(circuito)):
        for j in range(0, len(circuito[0])):
            puerta = circuito[i][j]
            g.add_node(puerta)
            if (puerta.puerta_entrada1 != None):
                g.add_edge(puerta.puerta_entrada1, puerta)
            if (puerta.puerta_entrada2 != None):
                g.add_edge(puerta.puerta_entrada2, puerta)
    nx.draw(g)
Ejemplo n.º 28
0
    def __init__(self):
        self._root = None
        self._edges = None

        # DiGraph with edges pointing towards root
        self._disto_proximal = nx.OrderedDiGraph()

        # views of disto_proximal
        self._undirected = self._disto_proximal.to_undirected(as_view=True)
        self._proximo_distal = self._disto_proximal.reverse(copy=False)

        self._length_key = "_length"
Ejemplo n.º 29
0
def simple_network():
    g = nx.graph_atlas(150)
    h = nx.OrderedDiGraph()
    for u, v in g.edges():
        h.add_edge(u, v)

    net = pg.create_empty_network()

    for n in h.nodes:
        pg.create_bus(net, level="BP", name="BUS{}".format(n))

    for n in [0, 3, "F"]:
        pg.create_bus(net, level="MP", name="BUSMP{}".format(n))

    for u, v in h.edges:
        pg.create_pipe(net,
                       "BUS{}".format(u),
                       "BUS{}".format(v),
                       length_m=1e4,
                       diameter_m=0.05,
                       name="PIPE{}-{}".format(u, v))

    for i in [2, 4, 5]:
        pg.create_load(net,
                       "BUS{}".format(i),
                       p_kW=10.0,
                       name="LOAD{}".format(i))

    for i in [0, 3]:
        bus_mp = "BUSMP{}".format(i)
        bus_bp = "BUS{}".format(i)
        pg.create_station(net,
                          bus_mp,
                          bus_bp,
                          p_lim_kW=50,
                          p_Pa=1.022e5,
                          name="STATION{}".format(i))

    pg.create_pipe(net,
                   "BUSMP0",
                   "BUSMP3",
                   length_m=300,
                   diameter_m=0.05,
                   name="PIPEMP0-3")
    pg.create_pipe(net,
                   "BUSMPF",
                   "BUSMP0",
                   length_m=300,
                   diameter_m=0.05,
                   name="PIPEMPF-0")
    pg.create_feeder(net, "BUSMPF", p_lim_kW=50, p_Pa=0.9e5, name="FEEDER")

    return net
Ejemplo n.º 30
0
 def paths_to_otree(paths):
     tree = nx.OrderedDiGraph()
     for path in sorted(paths):
         parts = tuple(path.split(sep))
         node_path = []
         for i in range(1, len(parts) + 1):
             node = parts[0:i]
             tree.add_node(node)
             tree.nodes[node]['label'] = node[-1]
             node_path.append(node)
         for u, v in ub.iter_window(node_path, 2):
             tree.add_edge(u, v)
     return tree