def build_from_parameters_layer(self, net, name='pydot', blobs=False, output_png=None): # type: (List[XLayer], str, bool, str) -> pydot.Dot """ TODO """ pdg = pydot.Dot(name, graph_type='digraph', rankdir='BT') if blobs: raise NotImplementedError("") # net = self._add_blobs(net) pydot_nodes = [] pydot_edges = [] for P in net: logger.debug("Name: {}, Layer type: {}, Bottoms: {}" .format(P.name, P.type, P.bottoms)) # if blobs and P.layer_type and 'blob' in P.layer_type: # pydot_attrs = copy.deepcopy(BLOB_STYLE) # pydot_attrs['LayerParameter'] = P # else: pydot_attrs = copy.copy(LAYER_STYLE_DEFAULT) pydot_attrs['LayerParameter'] = P # pydot_attrs['fillcolor'] = PydotFactory.cm[1] if P.type[0] in ['Input', 'StrInput']: pydot_attrs['shape'] = 'oval' pydot_attrs['fillcolor'] = PydotFactory.cm['input'] elif P.type[0] in ['Cvx']: pydot_attrs['fillcolor'] = PydotFactory.cm['input'] elif 'Variable' in P.type: pydot_attrs['shape'] = 'oval' pydot_attrs['fillcolor'] = PydotFactory.cm['variable'] elif set(['Quantize', 'UnQuantize', 'QuantizeInter', 'QuantizeBias']) & set(P.type): # Quantization node pydot_attrs['fillcolor'] = PydotFactory.cm['quantize'] elif P.target != 'cpu': # TODO multiple targets pydot_attrs['fillcolor'] = PydotFactory.cm['target'][0] node = pydot.Node(P.name, **pydot_attrs) pydot_nodes.append(node) for bottom in P.bottoms: src = bottom # if not blobs or P.layer_type and 'blob' in \ # P.layer_type else bottom + '_blob' dst = P.name edge_label = src + "->" + dst logger.debug("--Add bottom edge: {}".format(edge_label)) edge = pydot.Edge(src, dst, label=edge_label) pydot_edges.append(edge) # !! Blobs (if there are) should already be added to net for # this to work # for top in layer.tops: # dst = top # edge_label = P.name + '->' + dst # logger.debug("--Add top edge: {}".format(edge_label)) # edge = pydot.Edge(P.name, dst, label=edge_label) # pydot_edges.append(edge) # Building the pydot graph for node in pydot_nodes: pdg.add_node(node) for edge in pydot_edges: pdg.add_edge(edge) # Draw the original DAG computation graph if output_png is not None: if not output_png.endswith('.png'): raise ValueError("PydotFactory can only write pydot graphs to" " png files but {} was provided." .format(output_png)) viz_graph = visualize(pdg, output_png) return pdg
def to_pydot(N, strict=True): """Return a pydot graph from a NetworkX graph N. Parameters ---------- N : NetworkX graph A graph created with NetworkX Examples -------- >>> K5=nx.complete_graph(5) >>> P=nx.to_pydot(K5) Notes ----- """ try: import pydot except ImportError: raise ImportError('to_pydot() requires pydot: ' 'http://code.google.com/p/pydot/') # set Graphviz graph type if N.is_directed(): graph_type = 'digraph' else: graph_type = 'graph' strict = N.number_of_selfloops() == 0 and not N.is_multigraph() name = N.graph.get('name') graph_defaults = N.graph.get('graph', {}) if name is None: P = pydot.Dot(graph_type=graph_type, strict=strict, **graph_defaults) else: P = pydot.Dot('"%s"' % name, graph_type=graph_type, strict=strict, **graph_defaults) try: P.set_node_defaults(**N.graph['node']) except KeyError: pass try: P.set_edge_defaults(**N.graph['edge']) except KeyError: pass for n, nodedata in N.nodes_iter(data=True): str_nodedata = dict((k, str(v)) for k, v in nodedata.items()) p = pydot.Node(str(n), **str_nodedata) P.add_node(p) if N.is_multigraph(): for u, v, key, edgedata in N.edges_iter(data=True, keys=True): str_edgedata = dict((k, str(v)) for k, v in edgedata.items()) edge = pydot.Edge(str(u), str(v), key=str(key), **str_edgedata) P.add_edge(edge) else: for u, v, edgedata in N.edges_iter(data=True): str_edgedata = dict((k, str(v)) for k, v in edgedata.items()) edge = pydot.Edge(str(u), str(v), **str_edgedata) P.add_edge(edge) return P
def _get_dot_add_edges(self, graph, entity, targets, relation, relations, style, edgelabels=True, constraint=None): """Adds edges to `graph` for relations between `entity` and all members in `targets`. `style` is a dict with options to pydot.Edge(). """ import pydot nodes = graph.get_node(asstring(entity)) if not nodes: return node = nodes[0] for e in targets: s = asstring(e) if isinstance(e, owlready2.ThingClass): pass elif isinstance(e, (owlready2.ObjectPropertyClass, owlready2.PropertyClass)): label = asstring(e) nodes = graph.get_node(label) if nodes: kw = style.copy() if isinstance(edgelabels, dict): kw['label'] = edgelabels.get(label, label) elif edgelabels: kw['label'] = label edge = pydot.Edge(node, nodes[0], **kw) if constraint is not None: edge.set_constraint(constraint) graph.add_edge(edge) elif isinstance(e, owlready2.Restriction): rname = asstring(e.property) rtype = owlready2.class_construct._restriction_type_2_label[ e.type] if relations is True or rname in relations: vname = asstring(e.value) others = graph.get_node(vname) # Only proceede if there is only one node named `vname` # and an edge to that node does not already exists if (len(others) == 1 and (node.get_name(), vname) not in graph.obj_dict['edges'].keys()): other = others[0] else: continue if rtype in ('min', 'max', 'exactly'): label = '%s %s %d' % (rname, rtype, e.cardinality) else: label = '%s %s' % (rname, rtype) kw = style.copy() if isinstance(edgelabels, dict): slabel = '%s %s' % (rname, rtype) kw['label'] = edgelabels.get(slabel, label) + ' ' elif edgelabels: kw['label'] = label + ' ' # Add some extra space edge = pydot.Edge(node, other, **kw) if constraint is not None: edge.set_constraint(constraint) graph.add_edge(edge) elif hasattr(self, '_verbose') and self._verbose: print('* get_dot_graph() * Ignoring: ' '%s %s %s' % (node.get_name(), relation, s))
def stretch(pgm, graph_output=False, observed=False, silent=True, stretch_tries=1000): # # Extraction of relevant data from input # nodes = pgm.nodes nodes_num = len(nodes) efprob_domains = efprob_domains_of_pgm(pgm) channels = efprob_channels_of_pgm(pgm) # collect parents and children in a dictionary and initial nodes in a list children = {} parents = {} for n in nodes: children[n] = [] parents[n] = [] for e in pgm.edges(): children[e[0]].append(e[1]) parents[e[1]].append(e[0]) # collect number of elements of each node's domain in a dictionary node_sizes = {} for ck in channels.keys(): node_sizes[ck] = len(channels[ck].cod[0]) def list_size(node_list): return reduce(operator.mul, [node_sizes[n] for n in node_list], 1) initial_nodes = [] final_nodes = [] # non-initial and non-final nodes intermediate_nodes = [] for n in nodes: if len(parents[n]) == 0: initial_nodes.append(n) else: if len(children[n]) == 0: final_nodes.append(n) else: intermediate_nodes.append(n) # update with the order as actually used in the channel parents[n] = [dn.name for dn in channels[n].dom.names] # # Initialisation of data structures that will be build up: (a) # list of channels, (b) nodes pointers, (c) node copies, (d) # graph, optionally # # (a) List of channels, where the first entry consists of the # (product of the) initial states. This list of channels is the # main part of the output # channel_list = [idn(Dom([], names=Name("Empty")))] pointer = 1 # # (b) Dictionary with index level (natural number) for each node # node_pointer = {} # # (c) Dictionary for keeping track of how many copies are needed of a # node, so that copying can be done lazily, whenever needed. # node_copies = {} # # (d) Optional graph of the linearised graph; original nodes are # in green # if graph_output: stretched_graph = pydot.Dot(graph_type='digraph') # auxiliary function for addition of a named black bullet to # the graph, to be used as copy node; set fontsize to 12 to # see the names of the copy nodes, for debugging. Otherwise # the name is suppressed def add_copy_node(name): stretched_graph.add_node( pydot.Node(name, width=0.15, height=0.15, fixedsize=True, style="filled", fillcolor="black", fontsize=0)) # # Phase one: find the most "narrow" way of stretching the Bayesian # network into linear form, via repeated (stretch_tries many # times) random trials. The narrowness of a stretching is # calculated as the size of the states involved, expressed as # product of the number of items of component states. There are # probably more systematic ways of finding a narrow stretching. # stretch_size = sys.maxsize stretch_outcome = [] processed_initial_nodes = set([]) for st in range(stretch_tries): current_size = 0 current_stretch = [] current_processed_initial_nodes = set([]) available_nodes = [n for n in initial_nodes] unprocessed_nodes = [] node_copies = {} for n in initial_nodes: node_copies[n] = len(children[n]) + (1 if observed else 0) unprocessed_nodes = [] copy_of_intermediate_nodes = [n for n in intermediate_nodes] # find a random permutation of the intermediate nodes in the # list 'unprocessed_nodes'; the code below will go through # this list in order to find a stretching # # To be done, using instead: r = np.random.permutation(n) # unprocessed_nodes = unprocessed_nodes[r] for i in range(len(intermediate_nodes)): rand_index = random.randint(0, len(intermediate_nodes) - i - 1) rand_node = copy_of_intermediate_nodes[rand_index] unprocessed_nodes.append(rand_node) copy_of_intermediate_nodes.remove(rand_node) # put final nodes first, so that they are handled first, # keeping the size down unprocessed_nodes = final_nodes + unprocessed_nodes iterations = 0 while len(unprocessed_nodes) > 0: for un in unprocessed_nodes: iterations += 1 parents_un = parents[un] proceed = all([pn in available_nodes for pn in parents_un]) if not proceed: # handle this node un later continue #print("==> Parents found for node", un) current_stretch.append(un) for pn in parents_un: node_copies[pn] -= 1 if node_copies[pn] == 0: available_nodes.remove(pn) if pn in initial_nodes: current_processed_initial_nodes.add(pn) available_nodes.append(un) node_copies[un] = len(children[un]) + (1 if observed else 0) s = list_size(available_nodes) if s > current_size: current_size = s #print("Available nodes:", s) unprocessed_nodes.remove(un) # print("Stretch attempt", st, "ends with size:", current_size) if current_size < stretch_size: stretch_size = current_size stretch_outcome = current_stretch processed_initial_nodes = current_processed_initial_nodes for n in initial_nodes: if not n in processed_initial_nodes: #print("Post addition of", n) stretch_outcome.append(n) if not silent: print("Stretch search done after", stretch_tries, "tries with max size", stretch_size) # # Phase two: building the actual channel list, based on the list # of non-initial nodes 'stretch_outcome' # available_nodes = [n for n in initial_nodes] available_initial_nodes = [n for n in initial_nodes] for n in initial_nodes: node_copies[n] = len(children[n]) + (1 if observed else 0) if graph_output: stretched_graph.add_node( pydot.Node(n, style="filled", fillcolor="green")) if len(children[n]) > 0 and observed: # n is not a final node copy_name = n + "!copy" + str(node_copies[n]) # add copy nodes add_copy_node(copy_name) stretched_graph.add_edge(pydot.Edge(n, copy_name)) stretched_graph.add_edge(pydot.Edge(copy_name, " " + n + " ")) for node in stretch_outcome: if not silent: print("==> node", node, "(", pointer, "of", len(stretch_outcome), ") of sizes", [node_sizes[n] for n in available_nodes], "in total", list_size(available_nodes)) node_chan = channels[node] parents_node = parents[node] num_parents_node = len(parents[node]) copy_list = (len(available_nodes) - len(available_initial_nodes)) * [1] #print("Copy list length", len(copy_list)) new_available_nodes = [] new_available_initial_nodes = [] parent_copy_list = [] parent_chan_list = [] parent_initial_nodes = [] copy_position_correction = 0 for i in range(len(available_nodes)): n_i = available_nodes[i] initial_n_i = (n_i in available_initial_nodes) if n_i in parents_node: node_copies[n_i] -= 1 if initial_n_i: if not silent: print("--> initial node", n_i, "added") copy_position_correction += 1 parent_initial_nodes.append(n_i) parent_chan_list.append(channels[n_i]) # pointer - 1 is used since the initial node is # added to the previous channel node_pointer[n_i] = pointer - 1 if node_copies[n_i] > 0: parent_copy_list.append(2) parent_initial_nodes.append(n_i) else: parent_copy_list.append(1) else: new_available_nodes.append(n_i) if node_copies[n_i] > 0: # more copies of un needed later on new_available_nodes.append(n_i) copy_list[i - copy_position_correction] += 1 else: if initial_n_i: copy_position_correction += 1 new_available_initial_nodes.append(n_i) else: new_available_nodes.append(n_i) available_nodes = parent_initial_nodes + new_available_nodes available_initial_nodes = new_available_initial_nodes copy_list = parent_copy_list + copy_list # update the last channel with the required copying lcs = len(channel_list) last_channel = channel_list[lcs - 1] if len(parent_initial_nodes) > 0: parent_chan = reduce(lambda c1, c2: c1 @ c2, parent_chan_list) last_channel = parent_chan @ last_channel channel_list[lcs - 1] = copy_chan(last_channel, copy_list) #print(" ", available_nodes, channel_list[lcs-1].cod.names ) # # Now search for the precise positions of the parent nodes # #print("==> Searching locations of parents", parents_node, # "with availables", available_nodes) search_copy_of_nodes = [u for u in available_nodes] swaps = list(range(len(available_nodes))) # # find the actual occurrences of un's parents in available domains # for i in range(num_parents_node): # print("... searching for parent: ", parents_node[i] ) # # try to locate i-th parent among domains # for j in range(len(available_nodes)): if search_copy_of_nodes[j] == parents_node[i]: #print("Parent", parents_node[i], "found at", j) tmp = swaps[j] swaps[j] = swaps[i] swaps[i] = tmp search_copy_of_nodes[j] = search_copy_of_nodes[i] search_copy_of_nodes[i] = parents_node[i] break # # incorporate swaps into available nodes and arguments # inv_swaps = len(available_nodes) * [0] swapped_doms = [] swapped_available_nodes = [] for i in range(len(available_nodes)): inv_swaps[swaps[i]] = i swapped_available_nodes.append(available_nodes[swaps[i]]) available_nodes = swapped_available_nodes #print( swaps, inv_swaps ) #print("Swapped nodes", available_nodes) swapped_doms = [efprob_domains[n] for n in swapped_available_nodes] swapped_dom = reduce(lambda d1, d2: d1 + d2, swapped_doms) # # Build the channel that incorporates the node and does the swapping # node_chan_id = node_chan diff = len(available_nodes) - num_parents_node if diff > 0: identities_doms = [] for i in range(diff): d_i = swapped_dom.get_nameditem(i + num_parents_node) identities_doms.append(d_i) identities_dom = reduce(lambda d1, d2: d1 + d2, identities_doms) identities = idn(identities_dom) node_chan_id = node_chan @ identities # # Add the channel to the list, with its domains permuted # channel_list.append(perm_chan(node_chan_id, dom_perm=inv_swaps)) #print("Swapped chan dom", channel_list[len(channel_list)-1].dom.names ) node_pointer[node] = pointer pointer += 1 node_copies[node] = len(children[node]) + (1 if observed else 0) if node in initial_nodes: available_initial_nodes.remove(node) available_nodes = available_initial_nodes + \ [node] + available_nodes[num_parents_node:] #print("Nodes at end", available_nodes) #print("Codomain at end:", channel_list[len(channel_list)-1].cod.names ) # # Add node to the graph, with links to its parents, if needed # via (binary) copying. # if graph_output: stretched_graph.add_node( pydot.Node(node, style="filled", fillcolor="green")) for i in range(num_parents_node): parent_node_i = parents_node[i] copies_i = node_copies[parent_node_i] copy_name_i = parent_node_i + "!copy" + str(copies_i) copy_name_Si = parent_node_i + "!copy" + str(copies_i + 1) parent_node_i_children_num = len(children[parent_node_i]) if not observed: if parent_node_i_children_num == 1: # parent_node_i --> node is the only edge # parent_node_i --> ... stretched_graph.add_edge( pydot.Edge(parent_node_i, node)) else: if parent_node_i_children_num == copies_i + 1: # add just one copy and connect its base to parent_i add_copy_node(copy_name_i) stretched_graph.add_edge( pydot.Edge(parent_node_i, copy_name_i)) stretched_graph.add_edge( pydot.Edge(copy_name_i, node)) else: if copies_i == 0: # connect directly to last copy node stretched_graph.add_edge( pydot.Edge(copy_name_Si, node)) else: # add copy node and connect to previous add_copy_node(copy_name_i) stretched_graph.add_edge( pydot.Edge(copy_name_Si, copy_name_i)) stretched_graph.add_edge( pydot.Edge(copy_name_i, node)) else: # observed case if copies_i == 1: # connect directly to last copy node # print("no more copying needed") stretched_graph.add_edge(pydot.Edge( copy_name_Si, node)) else: # add copy node and connect to previous add_copy_node(copy_name_i) stretched_graph.add_edge( pydot.Edge(copy_name_Si, copy_name_i)) stretched_graph.add_edge(pydot.Edge(copy_name_i, node)) if observed and node_copies[node] > 1: # add copy node for children to connect to in next round copy_name_i = node + "!copy" + str(node_copies[node]) add_copy_node(copy_name_i) stretched_graph.add_edge(pydot.Edge(node, copy_name_i)) stretched_graph.add_edge( pydot.Edge(copy_name_i, " " + node + " ")) # # Collect the results in a dictionary # result = {'pointer': node_pointer, 'channels': channel_list} if graph_output: result['graph'] = stretched_graph return result
# first you create a new graph, you do that with pydot.Dot() graph = pydot.Dot(graph_type='graph') # the idea here is not to cover how to represent the hierarchical data # but rather how to graph it, so I'm not going to work on some fancy # recursive function to traverse a multidimensional array... # I'm going to hardcode stuff... sorry if that offends you # let's add the relationship between the king and vassals for i in range(3): # we can get right into action by "drawing" edges between the nodes in our graph # we do not need to CREATE nodes, but if you want to give them some custom style # then I would recomend you to do so... let's cover that later # the pydot.Edge() constructor receives two parameters, a source node and a destination # node, they are just strings like you can see edge = pydot.Edge("king", "lord%d" % i) # and we obviosuly need to add the edge to our graph graph.add_edge(edge) # now let us add some vassals vassal_num = 0 for i in range(3): # we create new edges, now between our previous lords and the new vassals # let us create two vassals for each lord for j in range(2): edge = pydot.Edge("lord%d" % i, "vassal%d" % vassal_num) graph.add_edge(edge) vassal_num += 1 # ok, we are set, let's save our graph into a file graph.write_svg('example1_graph.svg')
def draw(node, feature_list, result_list, path): graph = pydot.Dot(graph_type='graph') cid = 0 que = Queue.Queue() node.Id = setNodeId(node.depth) que.put(node) while (que.qsize() > 0): node = que.get() feature = feature_list[node.feature] node_txt = feature + '\n' + show_content(node, result_list) graph.add_node(pydot.Node(node.Id, label=node_txt)) for index in node.children.keys(): if node.children[index].leaf == True: if len(node.children[index].counts.keys()) == 1: edge_txt = '' node.children[index].Id = setNodeId( node.children[index].depth, cid) value = node.children[index].counts[ node.children[index].counts.keys()[0]] result = result_list[node.children[index].counts.keys()[0]] graph.add_node( pydot.Node(node.children[index].Id, label=result + "\n" + str(value), shape='box')) if node.feature not in node.continuous: edge_txt = str(index) else: if str(index) == "smaller": edge_txt = u'≤' + str(node.feature_split) else: edge_txt = '>' + str(node.feature_split) edge = pydot.Edge(node.Id, node.children[index].Id, label=edge_txt) graph.add_edge(edge) cid += 1 else: edge_txt = '' node_txt = show_content(node.children[index], result_list) node.children[index].Id = setNodeId( node.children[index].depth, cid) graph.add_node( pydot.Node(node.children[index].Id, label=node_txt, shape='box')) if node.feature not in node.continuous: edge_txt = str(index) else: if str(index) == "smaller": edge_txt = u'≤' + str(node.feature_split) else: edge_txt = '>' + str(node.feature_split) edge = pydot.Edge(node.Id, node.children[index].Id, label=edge_txt) graph.add_edge(edge) cid += 1 else: edge_txt = '' node.children[index].Id = setNodeId(node.children[index].depth, cid) if node.feature not in node.continuous: edge_txt = str(index) else: if str(index) == "smaller": edge_txt = u'≤' + str(node.feature_split) else: edge_txt = '>' + str(node.feature_split) edge = pydot.Edge(node.Id, node.children[index].Id, label=edge_txt) graph.add_edge(edge) que.put(node.children[index]) cid += 1 graph.write_png(path)
def get_edge(source_col_id, target_col_id, corr_coef, selected): label = "{:.2f}".format(corr_coef) return pydot.Edge(source_col_id, target_col_id, label=label, color=EDGE_COLOR[selected])
def make_graph(db_name, room_id, file_prefix, limit): conn = sqlite3.connect(db_name) sql = ( "SELECT json FROM event_json as j " "INNER JOIN events as e ON e.event_id = j.event_id " "WHERE j.room_id = ?" ) args = [room_id] if limit: sql += ( " ORDER BY topological_ordering DESC, stream_ordering DESC " "LIMIT ?" ) args.append(limit) c = conn.execute(sql, args) events = [FrozenEvent(json.loads(e[0])) for e in c.fetchall()] events.sort(key=lambda e: e.depth) node_map = {} state_groups = {} graph = pydot.Dot(graph_name="Test") for event in events: c = conn.execute( "SELECT state_group FROM event_to_state_groups " "WHERE event_id = ?", (event.event_id,) ) res = c.fetchone() state_group = res[0] if res else None if state_group is not None: state_groups.setdefault(state_group, []).append(event.event_id) t = datetime.datetime.fromtimestamp( float(event.origin_server_ts) / 1000 ).strftime('%Y-%m-%d %H:%M:%S,%f') content = json.dumps(unfreeze(event.get_dict()["content"])) label = ( "<" "<b>%(name)s </b><br/>" "Type: <b>%(type)s </b><br/>" "State key: <b>%(state_key)s </b><br/>" "Content: <b>%(content)s </b><br/>" "Time: <b>%(time)s </b><br/>" "Depth: <b>%(depth)s </b><br/>" "State group: %(state_group)s<br/>" ">" ) % { "name": event.event_id, "type": event.type, "state_key": event.get("state_key", None), "content": cgi.escape(content, quote=True), "time": t, "depth": event.depth, "state_group": state_group, } node = pydot.Node( name=event.event_id, label=label, ) node_map[event.event_id] = node graph.add_node(node) for event in events: for prev_id, _ in event.prev_events: try: end_node = node_map[prev_id] except: end_node = pydot.Node( name=prev_id, label="<<b>%s</b>>" % (prev_id,), ) node_map[prev_id] = end_node graph.add_node(end_node) edge = pydot.Edge(node_map[event.event_id], end_node) graph.add_edge(edge) for group, event_ids in state_groups.items(): if len(event_ids) <= 1: continue cluster = pydot.Cluster( str(group), label="<State Group: %s>" % (str(group),) ) for event_id in event_ids: cluster.add_node(node_map[event_id]) graph.add_subgraph(cluster) graph.write('%s.dot' % file_prefix, format='raw', prog='dot') graph.write_svg("%s.svg" % file_prefix, prog='dot')
def edges(edges): for edge in edges: graph.add_edge(pydot.Edge(edge[0], edge[1]))
def make_graph(pdus, room, filename_prefix): pdu_map = {} node_map = {} origins = set() colors = set(("red", "green", "blue", "yellow", "purple")) for pdu in pdus: origins.add(pdu.get("origin")) color_map = {color: color for color in colors if color in origins} colors -= set(color_map.values()) color_map[None] = "black" for o in origins: if o in color_map: continue try: c = colors.pop() color_map[o] = c except: print "Run out of colours!" color_map[o] = "black" graph = pydot.Dot(graph_name="Test") for pdu in pdus: name = make_name(pdu.get("pdu_id"), pdu.get("origin")) pdu_map[name] = pdu t = datetime.datetime.fromtimestamp( float(pdu["ts"]) / 1000 ).strftime('%Y-%m-%d %H:%M:%S,%f') label = ( "<" "<b>%(name)s </b><br/>" "Type: <b>%(type)s </b><br/>" "State key: <b>%(state_key)s </b><br/>" "Content: <b>%(content)s </b><br/>" "Time: <b>%(time)s </b><br/>" "Depth: <b>%(depth)s </b><br/>" ">" ) % { "name": name, "type": pdu.get("pdu_type"), "state_key": pdu.get("state_key"), "content": cgi.escape(json.dumps(pdu.get("content")), quote=True), "time": t, "depth": pdu.get("depth"), } node = pydot.Node( name=name, label=label, color=color_map[pdu.get("origin")] ) node_map[name] = node graph.add_node(node) for pdu in pdus: start_name = make_name(pdu.get("pdu_id"), pdu.get("origin")) for i, o in pdu.get("prev_pdus", []): end_name = make_name(i, o) if end_name not in node_map: print "%s not in nodes" % end_name continue edge = pydot.Edge(node_map[start_name], node_map[end_name]) graph.add_edge(edge) # Add prev_state edges, if they exist if pdu.get("prev_state_id") and pdu.get("prev_state_origin"): prev_state_name = make_name( pdu.get("prev_state_id"), pdu.get("prev_state_origin") ) if prev_state_name in node_map: state_edge = pydot.Edge( node_map[start_name], node_map[prev_state_name], style='dotted' ) graph.add_edge(state_edge) graph.write('%s.dot' % filename_prefix, format='raw', prog='dot') # graph.write_png("%s.png" % filename_prefix, prog='dot') graph.write_svg("%s.svg" % filename_prefix, prog='dot')
continue callerSourceName = sourceNameByRoutineNames.get(caller) calleeSourceName = sourceNameByRoutineNames.get(callee) if not callerSourceName or not calleeSourceName: continue regionPosition0 = getRegionPosition(caller, routines) if options.less == True and regionPosition0 not in [ "inside", "within", "outside" ]: continue regionPosition1 = getRegionPosition(callee, routines) if options.less == True and regionPosition1 not in [ "inside", "within", "outside" ]: continue edge = pydot.Edge(caller, callee, penwidth=graphPenWidth) graph.add_edge(edge) legend = pydot.Cluster(graph_name='Legend', label='Legend', penwidth=moduleClusterPenwidth) exampleSymbolAnalysis1 = SymbolAnalysis() exampleSymbolAnalysis1.name = "local_name (module data with domain dependant spec)" exampleSymbolAnalysis1.sourceModule = "source module" exampleSymbolAnalysis1.sourceSymbol = "source symbol name" exampleSymbolAnalysis1.symbolType = SymbolType.MODULE_DATA_WITH_DOMAIN_DEPENDANT_SPEC exampleSymbolAnalysis2 = SymbolAnalysis() exampleSymbolAnalysis2.name = "local_name (module data used in callee graph with domain dependant spec)" exampleSymbolAnalysis2.sourceModule = "source module" exampleSymbolAnalysis2.sourceSymbol = "source symbol name" exampleSymbolAnalysis2.symbolType = SymbolType.MODULE_DATA_USED_IN_CALLEE_GRAPH_WITH_DOMAIN_DEPENDANT_SPEC
# add a node for the decision output {True,False} to # the dictionary of nodes dtext = ['True', 'False'] colors = ['darkgreen', 'red'] for i in range(len(dectree[o]) - 1): nodename = dtext[i] + '\\n %.3f' % dectree[o][i + 1][0] nodes[o].append(dot.Node(nodename, fontsize='6.', fontcolor=colors[i])) # add nodes to graph for o in order: for i in range(len(nodes[o])): graph.add_node(nodes[o][i]) # add edges to graph for o in order: for i in range(1, len(nodes[o])): # Edge from kmer to decision graph.add_edge(dot.Edge(nodes[o][0], nodes[o][i])) children = dectree[o][i][1] tchildren = children[:] for child in tchildren: if child not in order: children.remove(child) if len(children): # Edge from decision to child k-mers for child in children: graph.add_edge(dot.Edge(nodes[o][i], nodes[child][0])) graph.write_jpeg(project_path + 'fig/' + virus_family + '_decisiontree_%s_%s_%s.jpg' % (k, m, fdx))
def plot(self, filename): # Fixes a bug in https://github.com/yahoo/graphkit/blob/e70718bbc7b394280c39c1fda381bcebd4c3de8d/graphkit/network.py#L378 import pydot import os def get_node_name(a): if isinstance(a, DataPlaceholderNode): return a return a.name if self.graph is None: self.compose() graph = self.graph.net.graph g = pydot.Dot(graph_type="digraph", layout="twopi") # For styles, see: # https://github.com/pydot/pydot/blob/master/pydot.py # Colors: https://graphviz.org/doc/info/colors.html # https://www.graphviz.org/doc/info/shapes.html # https://www.graphviz.org/doc/info/attrs.html styles = dict( fontsize=9, fontname='helvetica', width=0, height=0, margin='0.1,0.05' ) # draw nodes for nx_node in graph.nodes(): if isinstance(nx_node, DataPlaceholderNode): if nx_node in self.roots: index = self.roots.index(nx_node) pos = f'{index},0!' node = pydot.Node(name=nx_node, pos=pos, shape="rect", style="bold", **styles) elif nx_node in self.leafs: node = pydot.Node(name=nx_node, shape="rect", style="bold", color='brown2', fontcolor='brown2', **styles) else: node = pydot.Node(name=nx_node, shape="rect", **styles) else: # Transformation nodes node = pydot.Node(name=nx_node.name, shape="rect", style="rounded", color='grey50', fontcolor='grey50', **styles) g.add_node(node) # draw edges for src, dst in graph.edges(): src_name = get_node_name(src) dst_name = get_node_name(dst) edge = pydot.Edge(src=src_name, dst=dst_name, arrowsize=.5, minlen=0) g.add_edge(edge) # Store file basename, ext = os.path.splitext(filename) if ext.lower() == ".png": g.write_png(filename) elif ext.lower() == ".dot": g.write_dot(filename) elif ext.lower() in [".jpg", ".jpeg"]: g.write_jpeg(filename) elif ext.lower() == ".pdf": g.write_pdf(filename) elif ext.lower() == ".svg": g.write_svg(filename)
def graph(self): assets = [] if (self.theAssetName == '' and self.theEnvironmentName != ''): assets = self.dbProxy.classModelElements(self.theEnvironmentName, self.hideConcerns) if (len(assets) == 0 and self.theEnvironmentName == ''): self.theAssetName = 'Component' self.nodeList = set([]) for asset in assets: self.buildNode(asset[0], asset[1]) edgeList = set([]) fontSize = '7.5' for association in self.theAssociations: headName = association.headAsset() headDim = association.headDimension() tailName = association.tailAsset() tailDim = association.tailDimension() headObjt = headName tailObjt = tailName if (self.theAssetName != '' and headName not in self.nodeList): self.buildNode(headDim, headName) self.nodeList.add(headName) if (self.theAssetName != '' and tailName not in self.nodeList): self.buildNode(tailDim, tailName) self.nodeList.add(tailName) if (((headName, tailName) not in edgeList) and ((tailName, headName) not in edgeList)): headType = association.headType() headMultiplicity = association.headMultiplicity() headRole = association.headRole() tailRole = association.tailRole() tailMultiplicity = association.tailMultiplicity() tailType = association.tailType() headNav = association.headNavigation() tailNav = association.tailNavigation() aHead = self.arrowType(headDim, headType, headNav) aTail = self.arrowType(headDim, tailType, tailNav) hLabel = headMultiplicity + ' ' + headRole tLabel = tailMultiplicity + ' ' + tailRole fontColour = 'black' edgeColour = 'black' edgeStyle = 'solid' edgeLabel = '' if ((aHead == 'empty') or (aTail == 'empty')): hLabel = '' tLabel = '' if (headType == 'Dependency'): edgeLabel = '<<safeguards>>' hLabel = '' tLabel = '' edgeStyle = 'dashed' elif (tailType == 'Dependency'): edgeLabel = '<<safeguards>>' hLabel = '' tLabel = '' edgeStyle = 'dashed' if (headDim == 'persona'): hLabel = '' tLabel = '' if (headDim == 'goalconcern' or headDim == 'taskconcern'): hLabel = '' tLabel = '' fontColour = 'blue' edgeColour = 'blue' if (headDim == 'obstacleconcern'): hLabel = '' tLabel = '' fontColour = 'red' edgeColour = 'red' assocRationale = association.rationale() if (assocRationale != ''): objtUrl = 'comment#' + assocRationale if (assocRationale not in self.nodeList): self.theGraph.add_node( pydot.Node(assocRationale, shape='note', margin=0, fontsize=fontSize, fontcolor='blue', color='blue', URL=objtUrl)) if (((assocRationale, headName) not in edgeList) and (headDim not in [ 'goalconcern', 'obstacleconcern', 'taskconcern', 'usecaseconcern' ])): edge1 = pydot.Edge(assocRationale, headObjt, dir='none', fontsize=fontSize, color='blue', URL=objtUrl) self.theGraph.add_edge(edge1) edgeList.add((assocRationale, headName)) if (((assocRationale, tailName) not in edgeList) and (headDim not in [ 'goalconcern', 'obstacleconcern', 'taskconcern', 'usecaseconcern' ])): edge2 = pydot.Edge(assocRationale, tailObjt, dir='none', fontsize=fontSize, color='blue', URL=objtUrl) self.theGraph.add_edge(edge2) edgeList.add((assocRationale, tailName)) edgeLabel, hLabel, tLabel = self.filterBlankStrings( edgeLabel, hLabel, tLabel) if (headDim == 'goalconcern' or headDim == 'obstacleconcern' or headDim == 'taskconcern'): objtUrl = headDim + '#' + headName edge = pydot.Edge(headObjt, tailObjt, label=edgeLabel, headlabel=hLabel, taillabel=tLabel, arrowhead=aHead, arrowtail=aTail, style=edgeStyle, dir='both', fontcolor=fontColour, color=edgeColour, fontsize=fontSize, URL=objtUrl) else: # head and tail are visually different to head/tail in model terms, so switch the arrows and labels around edge = pydot.Edge(headObjt, tailObjt, label=edgeLabel, headlabel=tLabel, taillabel=hLabel, arrowhead=aTail, arrowtail=aHead, style=edgeStyle, dir='both', fontcolor=fontColour, color=edgeColour, fontsize=fontSize) self.theGraph.add_edge(edge) edgeList.add((headName, tailName)) return self.layout()
def add_edge(self, src, dst, id, **kwargs): e = pydot.Edge(src, dst, id=id, **fix_labels(kwargs)) return self.g.add_edge(e)
def e(src, dst): "Defines a new edge." edge = pydot.Edge(src, dst) graph.add_edge(edge)
def get_pydot_graph(caffe_net, rankdir, label_edges=True): """Create a data structure which represents the `caffe_net`. Parameters ---------- caffe_net : object rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. label_edges : boolean, optional Label the edges (default is True). Returns ------- pydot graph object """ pydot_graph = pydot.Dot(caffe_net.name, graph_type='digraph', rankdir=rankdir) pydot_nodes = {} pydot_edges = [] for layer in caffe_net.layer: node_label = get_layer_label(layer, rankdir) node_name = "%s_%s" % (layer.name, layer.type) if (len(layer.bottom) == 1 and len(layer.top) == 1 and layer.bottom[0] == layer.top[0]): # We have an in-place neuron layer. pydot_nodes[node_name] = pydot.Node(node_label, **NEURON_LAYER_STYLE) else: layer_style = LAYER_STYLE_DEFAULT layer_style['fillcolor'] = choose_color_by_layertype(layer.type) pydot_nodes[node_name] = pydot.Node(node_label, **layer_style) for bottom_blob in layer.bottom: pydot_nodes[bottom_blob + '_blob'] = pydot.Node( '%s' % bottom_blob, **BLOB_STYLE) edge_label = '""' pydot_edges.append({ 'src': bottom_blob + '_blob', 'dst': node_name, 'label': edge_label }) for top_blob in layer.top: pydot_nodes[top_blob + '_blob'] = pydot.Node('%s' % (top_blob)) if label_edges: edge_label = get_edge_label(layer) else: edge_label = '""' pydot_edges.append({ 'src': node_name, 'dst': top_blob + '_blob', 'label': edge_label }) # Now, add the nodes and edges to the graph. for node in pydot_nodes.values(): pydot_graph.add_node(node) for edge in pydot_edges: pydot_graph.add_edge( pydot.Edge(pydot_nodes[edge['src']], pydot_nodes[edge['dst']], label=edge['label'])) return pydot_graph
).get('label').replace('"', "").split(','): Q_d.add(edge.get_destination()) Q_d_name = ','.join(Q_d) P_d_name = ','.join(P_d) is_existed_edge = False for new_edge in Edges: if new_edge.get_source() == P_d_name and new_edge.get_destination( ) == Q_d_name: new_label = set( new_edge.get_attributes().get('label').split(",")) new_label.add(char) new_label = ",".join(new_label) new_edge.get_attributes().update({'label': new_label}) is_existed_edge = True if not is_existed_edge: Edges.append(pydot.Edge(P_d_name, Q_d_name, label=char)) if Q_d_name and Q_d_name not in Q: P.append(Q_d) Q.add(Q_d_name) shape = "circle" for node in graph.get_node_list(): if node.get_name() in Q_d_name and node.get_attributes().get( 'shape') == "doublecircle": shape = "doublecircle" break g.node(Q_d_name, shape=shape) for edge in Edges: g.edge(edge.get_source(), edge.get_destination(), edge.get_attributes().get('label'))
def draw(parent_name, child_name): edge = pydot.Edge(str(parent_name), str(child_name)) graph.add_edge(edge)
def dot_edge(src, dst, label, color): return pydot.Edge(src=quoted(src), dst=quoted(dst), label=quoted(label), color=color)
def edge(self, src, dst, style='solid', color='black'): if src is None or dst is None: return srcnode = self.node(src) dstnode = self.node(dst) self.g.add_edge(pydot.Edge(srcnode, dstnode, color=color, style=style))
def create_edge(self, node_in, node_out, message): self.graph.add_edge(pydot.Edge(node_in, node_out, label=message, labelfontcolor="#009933", fontsize="12.0", color="blue"))
def construct(self, graph): for child in self.children: graph.add_node(pydot.Node(child.id(), label=child.name())) edge = pydot.Edge(self.id(), child.id()) graph.add_edge(edge) child.construct(graph)
def get_beam_dot(self, dictionary=None, n_best=None): """ Create pydot graph representation of the beam. :param outputs: self.outputs from the beam :param dictionary: tok 2 word dict to save words in the tree nodes :returns: pydot graph """ try: import pydot except ImportError: print("Please install pydot package to dump beam visualization") graph = pydot.Dot(graph_type='digraph') outputs = [i.tolist() for i in self.outputs] bookkeep = [i.tolist() for i in self.bookkeep] all_scores = [i.tolist() for i in self.all_scores] if n_best is None: n_best = int(self.beam_size / 2) # get top nbest hyp top_hyp_idx_n_best = [] n_best_colors = [ 'aquamarine', 'chocolate1', 'deepskyblue', 'green2', 'tan' ] sorted_finished = self.get_rescored_finished(n_best=n_best) for hyptail in sorted_finished: # do not include EOS since it has rescored score not from original # self.all_scores, we color EOS with black top_hyp_idx_n_best.append(self.get_hyp_from_finished(hyptail)) # create nodes for tstep, lis in enumerate(outputs): for hypid, token in enumerate(lis): if tstep == 0: hypid = 0 # collapse all __NULL__ nodes node_tail = self.HypothesisTail(timestep=tstep, hypid=hypid, score=all_scores[tstep][hypid], tokenid=token) color = 'white' rank = None for i, hypseq in enumerate(top_hyp_idx_n_best): if node_tail in hypseq: if n_best <= 5: # color nodes only if <=5 color = n_best_colors[i] rank = i break label = ("<{}".format( dictionary. vec2txt([token]) if dictionary is not None else token) + " : " + "{:.{prec}f}>".format( all_scores[tstep][hypid], prec=3)) graph.add_node( pydot.Node( node_tail.__repr__(), label=label, fillcolor=color, style='filled', xlabel='{}'.format(rank) if rank is not None else '')) # create edges for revtstep, lis in reversed(list(enumerate(bookkeep))): for i, prev_id in enumerate(lis): from_node = graph.get_node('"{}"'.format( self.HypothesisTail( timestep=revtstep, hypid=prev_id, score=all_scores[revtstep][prev_id], tokenid=outputs[revtstep][prev_id]).__repr__()))[0] to_node = graph.get_node('"{}"'.format( self.HypothesisTail(timestep=revtstep + 1, hypid=i, score=all_scores[revtstep + 1][i], tokenid=outputs[revtstep + 1][i]).__repr__()))[0] newedge = pydot.Edge(from_node.get_name(), to_node.get_name()) graph.add_edge(newedge) return graph
def get_graph(modules, connections, ports): edges=[] edges_toAdd={} tmp_dict = Modules2dict(modules) for key in tmp_dict: if globals()['modules_dict'].has_key(key) == False: globals()['modules_dict'][key] = tmp_dict[key] ports_dict = getPortDict(ports) for connection in connections: inputModuleName , outputModuleName, inputModulePort = getInputOutput(connection) inputModuleNameToplot = checkName(inputModuleName,ports_dict,modules_dict) outputModuleNameToplot = checkName(outputModuleName,ports_dict,modules_dict) if isModule(modules_dict[inputModuleName],'Split'): if edges_toAdd.has_key(inputModuleName): edges_toAdd[inputModuleName][1].append(outputModuleNameToplot) else: edges_toAdd[inputModuleName]=[[],[]] edges_toAdd[inputModuleName][1]=[outputModuleNameToplot] elif isModule(modules_dict[outputModuleName],'Split'): if edges_toAdd.has_key(outputModuleName): edges_toAdd[outputModuleName][0].append(inputModuleNameToplot) else: edges_toAdd[outputModuleName]=[[],[]] edges_toAdd[outputModuleName][0]=[inputModuleNameToplot] else: edges.append( [inputModuleNameToplot, outputModuleNameToplot, inputModulePort] ) for split_module in edges_toAdd: # split from/to a port (input, output) if len(edges_toAdd[split_module][0]) == 0: edges_toAdd[split_module][0]=[checkName(split_module,ports_dict,modules_dict)] elif len(edges_toAdd[split_module][1]) == 0: edges_toAdd[split_module][1]=[checkName(split_module,ports_dict,modules_dict)] for i in edges_toAdd[split_module][0]: for j in edges_toAdd[split_module][1]: edges.append( [ i, j, ' ' ]) port_list = getPortLists(ports) graphSIZE = len(modules_dict) graph=pydot.Dot(size=str(graphSIZE)+','+str(graphSIZE)) for edge in edges: myedge=pydot.Edge(edge[0],edge[1]) myedge.set_label(edge[2]) graph.add_edge(myedge) for module in modules: if isModule(module,'Network'): for edge in get_graph(module.modules, module.connections, module.ports).get_edge_list(): graph.add_edge(edge) for port in port_list: inputPort = checkName(port[0],ports_dict,modules_dict) # outputPort = formatPortNames(port[0],port[1],modules_dict) outputPort = formatPortNames(port[0],port[1],modules_dict,printAllPorts) if outputPort != inputPort: #graph.add_node(pydot.Node(inputPort+'->'+outputPort)) #for edge in edges: # for i in range(len(edge)): # if inputPort in edge[i]: # edge[i] += ' '+outputPort myedge=pydot.Edge(outputPort,inputPort) myedge.set_arrowsize(1) # myedge.set_label('label') graph.add_edge(myedge) return graph
def graph(self): for location in self.theLocs.locations(): locName = location.name() assetInstances = location.assetInstances() personaInstances = location.personaInstances() locCluster = pydot.Cluster(locName, label=locName, URL='location#' + locName) locCluster.add_node( pydot.Node('point_' + locName, label='', shape="none", fontcolor="white", URL='location#' + locName)) for inst in assetInstances: instName = inst[0] assetName = inst[1] locCluster.add_node( pydot.Node(instName, URL='asset#' + assetName)) for persona in personaInstances: instName = persona[0] personaName = persona[1] locCluster.add_node( pydot.Node(instName, shape='circle', URL='persona#' + personaName)) self.theGraph.add_subgraph(locCluster) for edges in self.theLocs.links(): self.theGraph.add_edge( pydot.Edge('point_' + edges[0], 'point_' + edges[1], arrowhead='none', arrowtail='none', dir='both')) edgeList = set([]) b = Borg() risks = set([]) for trace in self.theOverlayTraces: riskName = trace.fromName() locName = trace.toName() if (riskName, locName) not in edgeList: edgeList.add((riskName, locName)) if riskName not in risks: risks.add(riskName) riskObjt = self.dbProxy.dimensionObject(riskName, 'risk') riskScores = self.dbProxy.riskScore(riskObjt.threat(), riskObjt.vulnerability(), self.theEnvironmentName, riskName) highestScore = 0 for riskScore in riskScores: currentScore = riskScore[2] if (currentScore > highestScore): highestScore = currentScore self.theGraph.add_node( pydot.Node(riskName, shape='diamond', style='filled', color=threatColourCode(highestScore), fontcolor=riskTextColourCode(highestScore), fontname=self.fontName, fontsize=self.fontSize, URL='risk#' + riskName)) for edges in edgeList: self.theGraph.add_edge(pydot.Edge(edges[0], 'point_' + edges[1])) return self.layout()
def get_dot_graph(self, root=None, graph=None, relations='is_a', leafs=None, parents=False, style=None, edgelabels=True, constraint=False): """Returns a pydot graph object for visualising the ontology. Parameters ---------- root : None | string | owlready2.ThingClass instance Name or owlready2 entity of root node to plot subgraph below. If `root` is None, all classes will be included in the subgraph. graph : None | pydot.Dot instance Pydot graph object to plot into. If None, a new graph object is created using the keyword arguments. relations : True | str | sequence Sequence of relations to visualise. If True, all relations are included. leafs : None | sequence A sequence of leaf node names for generating sub-graphs. parents : bool | str Whether to include parent nodes. If `parents` is a string, only parent nodes down to the given name will included. style : None | dict | "uml" A dict mapping the name of the different graphical elements to dicts of pydot style settings. Supported graphical elements include: - graph : overall settings pydot graph - class : nodes for classes - individual : nodes for invididuals - is_a : edges for is_a relations - equivalent_to : edges for equivalent_to relations - disjoint_with : edges for disjoint_with relations - inverse_of : edges for inverse_of relations - relations : with relation names XXX - other : edges for other relations and restrictions If style is None, a very simple default style is used. Some pre-defined styles can be selected by name (currently only "uml"). edgelabels : bool | dict Whether to add labels to the edges of the generated graph. It is also possible to provide a dict mapping the full labels (with cardinality stripped off for restrictions) to some abbriviations. constraint : None | bool Note: This method requires pydot. """ warnings.warn( """The emmo.ontology.get_dot_graph() method is deprecated. Use emmo.ontology.get_graph() instead. This requires that you install graphviz instead of the old pydot package.""", DeprecationWarning) # FIXME - double inheritance leads to dublicated nodes. Make sure # to only add a node once! import pydot from .ontology import NoSuchLabelError if style is None or style == 'default': style = self._default_style elif style == 'uml': style = self._uml_style graph = self._get_dot_graph(root=root, graph=graph, relations=relations, leafs=leafs, style=style, edgelabels=edgelabels) # Add parents # FIXME - facture out into an recursive function to support # multiple inheritance if parents and root: r = self.get_by_label(root) if isinstance(root, str) else root while True: parent = r.is_a.first() if (parent is None or parent is owlready2.Thing): break label = asstring(parent) if self.is_defined(label): node = pydot.Node(label, **style.get('defined_class', {})) # If label contains a hyphen, the node name will # be quoted (bug in pydot?). To work around, set # the name explicitly... node.set_name(label) else: node = pydot.Node(label, **style.get('class', {})) node.set_name(label) graph.add_node(node) if relations is True or 'is_a' in relations: kw = style.get('is_a', {}).copy() if isinstance(edgelabels, dict): kw['label'] = edgelabels.get('is_a', 'is_a') elif edgelabels: kw['label'] = 'is_a' rootnode = graph.get_node(asstring(r))[0] edge = pydot.Edge(rootnode, node, **kw) graph.add_edge(edge) if (isinstance(parents, str) and label == parents): break r = parent # Add edges for node in graph.get_nodes(): try: entity = self.get_by_label(node.get_name()) except (KeyError, NoSuchLabelError): continue # Add is_a edges targets = [e for e in entity.is_a if not isinstance(e, ( owlready2.ThingClass, owlready2.ObjectPropertyClass, owlready2.PropertyClass))] self._get_dot_add_edges( graph, entity, targets, 'relations', relations, # style=style.get('relations', style.get('other', {})), style=style.get('other', {}), edgelabels=edgelabels, constraint=constraint, ) # Add equivalent_to edges if relations is True or 'equivalent_to' in relations: self._get_dot_add_edges( graph, entity, entity.equivalent_to, 'equivalent_to', relations, style.get('equivalent_to', {}), edgelabels=edgelabels, constraint=constraint, ) # disjoint_with if hasattr(entity, 'disjoints') and ( relations is True or 'disjoint_with' in relations): self._get_dot_add_edges( graph, entity, entity.disjoints(), 'disjoint_with', relations, style.get('disjoint_with', {}), edgelabels=edgelabels, constraint=constraint, ) # Add inverse_of if (hasattr(entity, 'inverse_property') and (relations is True or 'inverse_of' in relations) and entity.inverse_property not in (None, entity)): self._get_dot_add_edges( graph, entity, [entity.inverse_property], 'inverse_of', relations, style.get('inverse_of', {}), edgelabels=edgelabels, constraint=constraint, ) return graph
def fill_graph(cls, models, graph, level=1, filter=None): ''' Fills a pydot graph with a models structure. ''' import pydot pool = Pool() Model = pool.get('ir.model') sub_models = set() if level > 0: for model in models: for field in model.fields: if field.name in ('create_uid', 'write_uid'): continue if field.relation and not graph.get_node(field.relation): sub_models.add(field.relation) if sub_models: model_ids = Model.search([ ('model', 'in', list(sub_models)), ]) sub_models = Model.browse(model_ids) if set(sub_models) != set(models): cls.fill_graph(sub_models, graph, level=level - 1, filter=filter) for model in models: if filter and re.search(filter, model.model): continue label = '"{' + model.model + '\\n' if model.fields: label += '|' for field in model.fields: if field.name in ('create_uid', 'write_uid', 'create_date', 'write_date', 'id'): continue label += '+ ' + field.name + ': ' + field.ttype if field.relation: label += ' ' + field.relation label += '\l' label += '}"' node_name = '"%s"' % model.model node = pydot.Node(node_name, shape='record', label=label) graph.add_node(node) for field in model.fields: if field.name in ('create_uid', 'write_uid'): continue if field.relation: node_name = '"%s"' % field.relation if not graph.get_node(node_name): continue args = {} tail = model.model head = field.relation edge_model_name = '"%s"' % model.model edge_relation_name = '"%s"' % field.relation if field.ttype == 'many2one': edge = graph.get_edge(edge_model_name, edge_relation_name) if edge: continue args['arrowhead'] = "normal" elif field.ttype == 'one2many': edge = graph.get_edge(edge_relation_name, edge_model_name) if edge: continue args['arrowhead'] = "normal" tail = field.relation head = model.model elif field.ttype == 'many2many': if graph.get_edge(edge_model_name, edge_relation_name): continue if graph.get_edge(edge_relation_name, edge_model_name): continue args['arrowtail'] = "inv" args['arrowhead'] = "inv" edge = pydot.Edge(str(tail), str(head), **args) graph.add_edge(edge)
def _get_dot_graph(self, root=None, graph=None, relations='is_a', leafs=None, style=None, visited=None, edgelabels=True): """Help method. See get_dot_graph(). `visited` is used to filter out circular dependencies. """ import pydot if graph is None: kwargs = style.get('graph', {}) kwargs.setdefault('newrank', True) graph = pydot.Dot(**kwargs) if relations is True: relations = ['is_a'] + list(self.get_relations()) elif isinstance(relations, str): relations = [relations] relations = set(r if isinstance(r, str) else asstring(r) if len(r.label) == 1 else r.name for r in relations) if visited is None: visited = set() if root is None: for root in self.get_root_classes(): self._get_dot_graph(root=root, graph=graph, relations=relations, leafs=leafs, style=style, visited=visited, edgelabels=edgelabels) return graph elif isinstance(root, (list, tuple, set)): for r in root: self._get_dot_graph(root=r, graph=graph, relations=relations, leafs=leafs, style=style, visited=visited, edgelabels=edgelabels) return graph elif isinstance(root, str): root = self.get_by_label(root) if root in visited: if hasattr(self, '_verbose') and self._verbose: warnings.warn('Circular dependency of class %r' % asstring(root)) return graph visited.add(root) label = asstring(root) nodes = graph.get_node(label) if nodes: if len(nodes) > 1: warnings.warn( 'More than one node corresponding to label: %s' % label) node = nodes[0] else: if self.is_individual(label): node = pydot.Node(label, **style.get('individual', {})) node.set_name(label) elif self.is_defined(label): node = pydot.Node(label, **style.get('defined_class', {})) node.set_name(label) else: node = pydot.Node(label, **style.get('class', {})) node.set_name(label) graph.add_node(node) if leafs and label in leafs: return graph for sc in root.subclasses(): label = asstring(sc) if self.is_individual(label): subnode = pydot.Node(label, **style.get('individual', {})) subnode.set_name(label) elif self.is_defined(label): subnode = pydot.Node(label, **style.get('defined_class', {})) subnode.set_name(label) else: subnode = pydot.Node(label, **style.get('class', {})) subnode.set_name(label) graph.add_node(subnode) if relations is True or 'is_a' in relations: kw = style.get('is_a', {}).copy() if isinstance(edgelabels, dict): kw['label'] = edgelabels.get('is_a', 'is_a') elif edgelabels: kw['label'] = 'is_a' edge = pydot.Edge(subnode, node, **kw) graph.add_edge(edge) self._get_dot_graph(root=sc, graph=graph, relations=relations, leafs=leafs, style=style, visited=visited, edgelabels=edgelabels) return graph
def gen_tao(node, graph): graph.add_node(pydot.Node("tao_root", label=" ", shape="point")) gen_tao_nodes(node, graph) graph.add_edge(pydot.Edge("tao_root", get_tao_start(node)))