Write a GraphViz graph of the relationships between the fields.
772907
def print_fieldrefs(doc, loader, stream):
    # type: (List[Dict[Text, Any]], Loader, IO) -> None
    """"""
    obj = extend_and_specialize(doc, loader)

    primitives = set(("http://www.w3.org/2001/XMLSchema#string",
                      "http://www.w3.org/2001/XMLSchema#boolean",
                      "http://www.w3.org/2001/XMLSchema#int",
                      "http://www.w3.org/2001/XMLSchema#long",
                      "https://w3id.org/cwl/salad#null",
                      "https://w3id.org/cwl/salad#enum",
                      "https://w3id.org/cwl/salad#array",
                      "https://w3id.org/cwl/salad#record",
                      "https://w3id.org/cwl/salad#Any"))

    stream.write("digraph {\n")
    for entry in obj:
        if entry.get("abstract"):
            continue
        if entry["type"] == "record":
            label = shortname(entry["name"])
            for field in entry.get("fields", []):
                found = set()  # type: Set[Text]
                field_name = shortname(field["name"])
                replace_type(field["type"], {}, loader, found, find_embeds=False)
                for each_type in found:
                    if each_type not in primitives:
                        stream.write(
                            "\"%s\" -> \"%s\" [label=\"%s\"];\n"
                            % (label, shortname(each_type), field_name))
    stream.write("}\n")
717431
def write(models, base=None, graph=None, rdfsonly=False, prefixes=None, logger=logging):
    '''
    
    '''
    prefixes = prefixes or {}
    g = graph or rdflib.Graph()
    #g.bind('bf', BFNS)
    #g.bind('bfc', BFCNS)
    #g.bind('bfd', BFDNS)
    g.bind('v', VNS)
    for k, v in prefixes.items():
        g.bind(k, v)
    for m in models:
        base_out = m.base
        process(m, g, rdfsonly, base=base_out, logger=logger)
    return g
453904
def get_subgraphs(graph=None):
    
    graph = graph or DEPENDENCIES
    keys = set(graph)
    frontier = set()
    seen = set()
    while keys:
        frontier.add(keys.pop())
        while frontier:
            component = frontier.pop()
            seen.add(component)
            frontier |= set([d for d in get_dependencies(component) if d in graph])
            frontier |= set([d for d in get_dependents(component) if d in graph])
            frontier -= seen
        yield dict((s, get_dependencies(s)) for s in seen)
        keys -= seen
        seen.clear()
1242785
def serialize(graph: BELGraph, csv, sif, gsea, graphml, json, bel):
    """"""
    if csv:
        log.info('Outputting CSV to %s', csv)
        to_csv(graph, csv)

    if sif:
        log.info('Outputting SIF to %s', sif)
        to_sif(graph, sif)

    if graphml:
        log.info('Outputting GraphML to %s', graphml)
        to_graphml(graph, graphml)

    if gsea:
        log.info('Outputting GRP to %s', gsea)
        to_gsea(graph, gsea)

    if json:
        log.info('Outputting JSON to %s', json)
        to_json_file(graph, json)

    if bel:
        log.info('Outputting BEL to %s', bel)
        to_bel(graph, bel)
899995
public void export( Graph pGraph, Schema pSchema, DotWriter pDotWriter, boolean pOutRefsOnly )
  {
    pDotWriter.printHeaderStart( pGraph.getStyleForGraph() );

    if( pGraph.isCollapseSubgraphs() )
    {
      _writeSubgraphRecursiveCollapsed( pGraph, pSchema, pDotWriter, pOutRefsOnly );

      List<Graph> lEndGraphs = _getEndGraphListRecursive( pGraph );

      List<GraphAssociation> lGraphAssociations = new ArrayList<GraphAssociation>();

      for( Graph lGraphFrom : lEndGraphs )
      {
        for( Graph lGraphTo : lEndGraphs )
        {
          GraphAssociation lGraphAssociation = new GraphAssociation();
          lGraphAssociation._graphFrom = lGraphFrom;
          lGraphAssociation._graphTo = lGraphTo;

          for( Table lTableFrom : pSchema.getTables() )
          {
            if( lGraphFrom.containsTableRecursive( lTableFrom ) )
            {
              for( Table lTableTo : pSchema.getTables() )
              {
                if( lGraphTo.containsTableRecursive( lTableTo ) )
                {
                  for( Association lAssociation : pSchema.getAssociations() )
                  {
                    if( lAssociation.getTableFrom() == lTableFrom && lAssociation.getTableTo() == lTableTo )
                    {
                      lGraphAssociation._countTableFks += 1;
                    }
                  }
                }
              }
            }
          }

          if( lGraphAssociation._countTableFks > 0 )
          {
            lGraphAssociations.add( lGraphAssociation );
          }
        }
      }

      for( GraphAssociation lGraphAssociation : _filterGraphAssociations( lGraphAssociations ) )
      {
        _printGraphAssociation( lGraphAssociation, pDotWriter );
      }
    }
    else
    {
      List<Association> lExtraAssociations = new ArrayList<Association>();
      boolean lOtherTablesFound = false;

      for( Table lTable : pSchema.getTables() )
      {
        if( !pGraph.containsTableRecursive( lTable ) )
        {
          List<Association> lVisibleAssociation = pGraph.getVisibleAssociation( lTable, pSchema, pOutRefsOnly );

          if( !lVisibleAssociation.isEmpty() )
          {
            lExtraAssociations.addAll( lVisibleAssociation );
            lOtherTablesFound = true;
            _printTable( lTable, pDotWriter, lVisibleAssociation, pOutRefsOnly, pGraph.getStyleForTable( lTable ) );
          }
        }
      }

      _writeSubgraphRecursive( pGraph, pSchema, pDotWriter, pOutRefsOnly, new ArrayList<Table>(), lOtherTablesFound, pGraph.isRenderClusterForSubgraphs() );

      for( Association lAssociation : pSchema.getAssociations() )
      {
        if( lExtraAssociations.contains( lAssociation )
            || (pGraph.allAssociations() && (pGraph.containsTableRecursive( lAssociation.getTableFrom() ) || (!pOutRefsOnly && pGraph.containsTableRecursive( lAssociation.getTableTo() )))) )
        {
          _printAssociation( lAssociation, pDotWriter, pGraph );
        }
      }
    }

    pDotWriter.printHeaderEnd();
  }
1224979
def relations_used(self):
        
        g = self.get_graph()
        types = set()
        for (x,y,d) in g.edges(data=True):
            types.add(d['pred'])
        return list(types)
633112
def show_relations(self):
        '''  '''
        for src_node in self.iter_nodes():
            for relation in src_node.outgoing:
                for dst_node in src_node.outgoing[relation]:
                    print(repr(src_node.obj), '-', relation, '-', repr(dst_node.obj))
383279
def graph_simplify(G):
    
    spurs = []
    path_nodes = []
    for k, d in G.degree().iteritems():
        if d == 1:
            spurs.append(k)
        elif d == 2:
            path_nodes.append(k)

    logging.debug("Remove {0} spurs.".format(len(spurs)))
    G.remove_nodes_from(spurs)

    SG = G.subgraph(path_nodes)
    cc = nx.connected_components(SG)
    for c in cc:
        if len(c) == 1:
            continue
        c = set(c)
        neighbors = set()
        for x in c:
            neighbors |= set(G.neighbors(x))
        neighbors -= c
        newtag = list(c)[0] + "*"
        for n in neighbors:
            G.add_edge(newtag, n)
        G.remove_nodes_from(c)
    logging.debug("Contract {0} path nodes into {1} nodes.".\
                    format(len(path_nodes), len(cc)))
772945
def pretty_view(graph, oriented=False, construction=False,
                graphviz_prog=DEFAULT_GRAPHVIZ_PROG):
    """"""
    layout = create_layout(graph, graphviz_prog=graphviz_prog)
    matrix_view = defaultdict(lambda: ' ')

    # Add the edge to the view

    # print('GRAPH EDGES:', tuple(graph.edges()))
    # print('LAYOUT:', layout)

    edges = ((layout[source], layout[target])
             for source, target in graph.edges())
    # print('EDGES:', tuple(edges))

    for source, target in edges:
        previous_edge_char = None
        previous_position = source
        while source != target:
            for is_dir, transform, edge_char in DIRECTIONS:
                first_loop = previous_edge_char is None
                if is_dir(source, target):
                    previous_source = source
                    source = transform(source)
                    if not first_loop:  # first loop: no previous char
                        char = CHARACTER[previous_edge_char, edge_char]
                        if not isinstance(char, str):
                            char = char.value
                        matrix_view[previous_source] = char
                        if construction:
                            old = defaultdict(lambda: ' ', matrix_view)
                            yield view.build(matrix_view)
                        assert isinstance(matrix_view[previous_source], str)
                    if source != target:
                        previous_edge_char = edge_char
                    previous_position = previous_source
                    break  # for loop ; don't test the remain directions

        if oriented:
            matrix_view[previous_position] = ORIENTATION[previous_edge_char, edge_char]
        if construction:
            yield view.build(matrix_view)

    # mark the place where nodes labels will be added
    # for node, coords in layout.items():
        # matrix_view[coords] = node[0]
    # Add the node labels to the view
    # matrix_view = view.clean(matrix_view)
    for node, (x, y) in layout.items():
        if len(node) == 1:
            matrix_view[x, y] = node
            continue
        row_min, row_max = (view.previous_unwrittable_on_row(matrix_view, (x, y)),
                            view.next_unwrittable_on_row(matrix_view, (x, y)))
        col_min, col_max = (view.previous_unwrittable_on_col(matrix_view, (x, y)),
                              view.next_unwrittable_on_col(matrix_view, (x, y)))
        # print('NODE ' + node + ':',
              # '→row: [{};{}]'.format(row_min, row_max).ljust(20),
              # '↓col: [{};{}]'.format(col_min, col_max))
        print_coords = [itertools.count(x), itertools.cycle((y,))]
        if row_min is None:  # write left to right, end at (x, y)
            if row_max is None or row_max > (x + len(node) / 2):  # enough space at the right
                factor = 2
            else:
                factor = 1
            print_coords[0] = tuple(
                x - (len(node) // factor) + offset + 1
                for offset in range(len(node))
            )
            # print('DEBUG 1:', y, len(node), print_coords[0])
        elif row_max is None:  # write left to right, beginning at (x, y)
            if row_min < (x - len(node) / 2):  # enough space at the left
                factor = 1
            else:
                factor = 0
            print_coords[0] = tuple(
                x + offset - (len(node) // 2) * factor
                for offset in range(len(node))
            )
            # print('DEBUG 2:', print_coords[0])
        elif (row_max - row_min) > len(node) + 1:  # write left to right, if enough place
            print_coords[0] = tuple(
                x + offset
                for offset in range(len(node))
            )
            # print('DEBUG 3:', print_coords[0])

        elif col_min is None:  # write up to down, end at (x, y)
            if col_max is None or col_max > (x + len(node) / 2):  # enough space at the right
                factor = 2
            else:
                factor = 1
            print_coords = (itertools.cycle((x,)), tuple(
                y - (len(node) // factor) + offset + 1
                for offset in range(len(node))
            ))
            # print('DEBUG 4:', y, len(node), print_coords[1])
        elif col_max is None:  # write up to down, beginning at (x, y)
            if col_min < (x - len(node) / 2):  # enough space at the left
                factor = 1
            else:
                factor = 0
            print_coords = (itertools.cycle((x,)), tuple(
                y + offset - (len(node) // 2) * factor
                for offset in range(len(node))
            ))
            # print('DEBUG 5:', print_coords[1])
        elif (col_max - col_min) > len(node) + 1:  # write up to down, if enough place
            print_coords = (itertools.cycle((x,)), tuple(
                y + offset
                for offset in range(len(node))
            ))
            # print('DEBUG 6:', print_coords[1])
        else:  # not enough space
            if (row_max - row_min) > (col_max - col_min):
                # more space on Y axis
                node = node[:row_max - row_min]  # cut the node
                print_coords = (itertools.cycle((x,)), tuple(
                    x + offset
                    for offset in range(len(node))
                ))
                # print('DEBUG 7:', print_coords[1])
            else:
                # more space on X axis
                node = node[:col_max - col_min]  # cut the node
                print_coords[0] = tuple(
                    x + offset
                    for offset in range(len(node))
                )
                # print('DEBUG 8:', print_coords[0])

        for letter, i, j in zip(node, *print_coords):
            matrix_view[i, j] = letter




    if construction:
        yield view.build(matrix_view)
    else:
        yield from view.build(matrix_view)
369082
def to_string(self):
        

        graph = list()

        if self.obj_dict.get('strict', None) is not None:
            if self == self.get_parent_graph() and self.obj_dict['strict']:
                graph.append('strict ')

        if self.obj_dict['name'] == '':
            if ('show_keyword' in self.obj_dict and
                    self.obj_dict['show_keyword']):
                graph.append('subgraph {\n')
            else:
                graph.append('{\n')
        else:
            graph.append('%s %s {\n' % (self.obj_dict['type'],
                                        self.obj_dict['name']))

        for attr, value in sorted(self.obj_dict['attributes'].items(),
                                  key=itemgetter(0)):
            if value is not None:
                graph.append('%s=%s' % (attr, quote_if_necessary(value)))
            else:
                graph.append(attr)

            graph.append(';\n')

        edges_done = set()

        edge_obj_dicts = list()
        for e in self.obj_dict['edges'].values():
            edge_obj_dicts.extend(e)

        if edge_obj_dicts:
            edge_src_set, edge_dst_set = list(
                zip(*[obj['points'] for obj in edge_obj_dicts]))
            edge_src_set, edge_dst_set = set(edge_src_set), set(edge_dst_set)
        else:
            edge_src_set, edge_dst_set = set(), set()

        node_obj_dicts = list()
        for e in self.obj_dict['nodes'].values():
            node_obj_dicts.extend(e)

        sgraph_obj_dicts = list()
        for sg in self.obj_dict['subgraphs'].values():
            sgraph_obj_dicts.extend(sg)

        obj_list = sorted([
            (obj['sequence'], obj)
            for obj
            in (edge_obj_dicts + node_obj_dicts + sgraph_obj_dicts)])

        for _idx, obj in obj_list:
            if obj['type'] == 'node':
                node = Node(obj_dict=obj)

                if self.obj_dict.get('suppress_disconnected', False):
                    if (node.get_name() not in edge_src_set and
                            node.get_name() not in edge_dst_set):
                        continue

                graph.append(node.to_string() + '\n')

            elif obj['type'] == 'edge':
                edge = Edge(obj_dict=obj)

                if self.obj_dict.get('simplify', False) and edge in edges_done:
                    continue

                graph.append(edge.to_string() + '\n')
                edges_done.add(edge)
            else:
                sgraph = Subgraph(obj_dict=obj)
                graph.append(sgraph.to_string() + '\n')

        graph.append('}\n')

        return ''.join(graph)
1266951
def WriteClientGraphSeries(
      self,
      graph_series,
      client_label,
      timestamp,
      cursor=None,
  ):
    """"""
    args = {
        "client_label": client_label,
        "report_type": graph_series.report_type.SerializeToDataStore(),
        "timestamp": mysql_utils.RDFDatetimeToTimestamp(timestamp),
        "graph_series": graph_series.SerializeToString(),
    }

    query = """
      INSERT INTO client_report_graphs (client_label, report_type, timestamp,
                                        graph_series)
      VALUES (%(client_label)s, %(report_type)s, FROM_UNIXTIME(%(timestamp)s),
              %(graph_series)s)
      ON DUPLICATE KEY UPDATE graph_series = VALUES(graph_series)
    """

    cursor.execute(query, args)
1100357
def new_graph(self, graph, typ):
        """"""
        graph = self.pack(graph)
        return self.sql('new_graph', graph, typ)
217494
def graph(data):
    """"""
    title = data['name'] + ' (' + data['rating'] + ') '
    plt.title(title)
    plt.xlabel('Episode Number')
    plt.ylabel('Ratings')
    rf,ef=graphdata(data)
    col=['red', 'green' , 'orange']
    for i in range(len(rf)):
        x,y=ef[i],rf[i]
        k = i + 1
        plt.plot(x, y,color=col[i%3])
    x1, x2, y1, y2 = plt.axis()
    y2 = 10
    if y1 > 7:
        y1 = 7
    plt.axis([x1, x2, y1, y2])
    plt.show()
1125776
def gdfs_to_graph(gdf_nodes, gdf_edges):
    

    G = nx.MultiDiGraph()
    G.graph['crs'] = gdf_nodes.crs
    G.graph['name'] = gdf_nodes.gdf_name.rstrip('_nodes')

    # add the nodes and their attributes to the graph
    G.add_nodes_from(gdf_nodes.index)
    attributes = gdf_nodes.to_dict()
    for attribute_name in gdf_nodes.columns:
        # only add this attribute to nodes which have a non-null value for it
        attribute_values = {k:v for k, v in attributes[attribute_name].items() if pd.notnull(v)}
        nx.set_node_attributes(G, name=attribute_name, values=attribute_values)

    # add the edges and attributes that are not u, v, key (as they're added
    # separately) or null
    for _, row in gdf_edges.iterrows():
        attrs = {}
        for label, value in row.iteritems():
            if (label not in ['u', 'v', 'key']) and (isinstance(value, list) or pd.notnull(value)):
                attrs[label] = value
        G.add_edge(row['u'], row['v'], key=row['key'], **attrs)

    return G
255442
def graphviz(self, directory, **kwargs):
        ""
        import os
        if not os.path.isdir(directory):
            os.mkdir(directory)
        output = os.path.join(directory, 'evodag-%s')
        for k, m in enumerate(self.models):
            m.graphviz(output % k, **kwargs)
310049
def write(self)->None:
        ""
        self.tbwriter.add_graph(model=self.model, input_to_model=self.input_to_model)
343352
def write(G):
    
    
    # Document root
    grxml = Document()
    if (type(G) == graph):
        grxmlr = grxml.createElement('graph')
    elif (type(G) == digraph ):
        grxmlr = grxml.createElement('digraph')
    elif (type(G) == hypergraph ):
        return write_hypergraph(G)
    else:
        raise InvalidGraphType
    grxml.appendChild(grxmlr)

    # Each node...
    for each_node in G.nodes():
        node = grxml.createElement('node')
        node.setAttribute('id', str(each_node))
        grxmlr.appendChild(node)
        for each_attr in G.node_attributes(each_node):
            attr = grxml.createElement('attribute')
            attr.setAttribute('attr', each_attr[0])
            attr.setAttribute('value', each_attr[1])
            node.appendChild(attr)

    # Each edge...
    for edge_from, edge_to in G.edges():
        edge = grxml.createElement('edge')
        edge.setAttribute('from', str(edge_from))
        edge.setAttribute('to', str(edge_to))
        edge.setAttribute('wt', str(G.edge_weight((edge_from, edge_to))))
        edge.setAttribute('label', str(G.edge_label((edge_from, edge_to))))
        grxmlr.appendChild(edge)
        for attr_name, attr_value in G.edge_attributes((edge_from, edge_to)):
            attr = grxml.createElement('attribute')
            attr.setAttribute('attr', attr_name)
            attr.setAttribute('value', attr_value)
            edge.appendChild(attr)

    return grxml.toprettyxml()