Makes graph object from .gdf loaded data
559013
def makeNetwork(self):
        """"""
        if "weight" in self.data_friendships.keys():
            self.G=G=x.DiGraph()
        else:
            self.G=G=x.Graph()
        F=self.data_friends
        for friendn in range(self.n_friends):
            if "posts" in F.keys():
                G.add_node(F["name"][friendn],
                             label=F["label"][friendn],
                             posts=F["posts"][friendn])
            elif "agerank" in F.keys():
                G.add_node(F["name"][friendn],
                             label=F["label"][friendn],
                             gender=F["sex"][friendn],
                             locale=F["locale"][friendn], 
                             agerank=F["agerank"][friendn])
            else:
                G.add_node(F["name"][friendn],
                             label=F["label"][friendn],
                             gender=F["sex"][friendn],
                             locale=F["locale"][friendn])
        F=self.data_friendships
        for friendshipn in range(self.n_friendships):
            if "weight" in F.keys():
                G.add_edge(F["node1"][friendshipn],F["node2"][friendshipn],weight=F["weight"][friendshipn])
            else:
                G.add_edge(F["node1"][friendshipn],F["node2"][friendshipn])
767651
private void fromInput(List<FileModel> vertices, GraphRewrite event)
    {
        if (vertices.isEmpty() && StringUtils.isNotBlank(getInputVariablesName()))
        {
            for (WindupVertexFrame windupVertexFrame : Variables.instance(event).findVariable(getInputVariablesName()))
            {
                if (windupVertexFrame instanceof FileModel)
                    vertices.add((FileModel) windupVertexFrame);
                if (windupVertexFrame instanceof FileReferenceModel)
                    vertices.add(((FileReferenceModel) windupVertexFrame).getFile());
            }
        }
    }
823787
def _get_dotgraphs(self, hdrgo, usrgos, pltargs, go2parentids):
        """"""
        gosubdagplotnts = self._get_gosubdagplotnts(hdrgo, usrgos, pltargs, go2parentids)
        # Create DAG graphs as dot language strings. Loop through GoSubDagPlotNt list
        dotstrs = [obj.get_dotstr() for obj in gosubdagplotnts]
        return dotstrs
375092
def display_graph(g, format='svg', include_asset_exists=False):
    
    try:
        import IPython.display as display
    except ImportError:
        raise NoIPython("IPython is not installed.  Can't display graph.")

    if format == 'svg':
        display_cls = display.SVG
    elif format in ("jpeg", "png"):
        display_cls = partial(display.Image, format=format, embed=True)

    out = BytesIO()
    _render(g, out, format, include_asset_exists=include_asset_exists)
    return display_cls(data=out.getvalue())
38026
def from_jgif(graph_jgif_dict):
    
    graph = BELGraph()

    root = graph_jgif_dict['graph']

    if 'label' in root:
        graph.name = root['label']

    if 'metadata' in root:
        metadata = root['metadata']

        for key in METADATA_INSERT_KEYS:
            if key in metadata:
                graph.document[key] = metadata[key]

    parser = BELParser(graph)
    parser.bel_term.addParseAction(parser.handle_term)

    for node in root['nodes']:
        node_label = node.get('label')

        if node_label is None:
            log.warning('node missing label: %s', node)
            continue

        try:
            parser.bel_term.parseString(node_label)
        except NakedNameWarning as e:
            log.info('Naked name: %s', e)
        except ParseException:
            log.info('Parse exception for %s', node_label)

    for i, edge in enumerate(root['edges']):
        relation = edge.get('relation')
        if relation is None:
            log.warning('no relation for edge: %s', edge)

        if relation in {'actsIn', 'translocates'}:
            continue  # don't need legacy BEL format

        edge_metadata = edge.get('metadata')
        if edge_metadata is None:
            log.warning('no metadata for edge: %s', edge)
            continue

        bel_statement = edge.get('label')
        if bel_statement is None:
            log.debug('No BEL statement for edge %s', edge)

        evidences = edge_metadata.get('evidences')

        if relation in UNQUALIFIED_EDGES:
            pass  # FIXME?

        else:
            if not evidences:  # is none or is empty list
                log.debug('No evidence for edge %s', edge)
                continue

            for evidence in evidences:
                citation = evidence.get('citation')

                if not citation:
                    continue

                if 'type' not in citation or 'id' not in citation:
                    continue

                summary_text = evidence['summary_text'].strip()

                if not summary_text or summary_text == placeholder_evidence:
                    continue

                parser.control_parser.clear()
                parser.control_parser.citation = reformat_citation(citation)
                parser.control_parser.evidence = summary_text
                parser.control_parser.annotations.update(evidence[EXPERIMENT_CONTEXT])

                try:
                    parser.parseString(bel_statement, line_number=i)
                except Exception as e:
                    log.warning('JGIF relation parse error: %s for %s', e, bel_statement)

    return graph
1275427
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 ')

        graph_type = self.obj_dict['type']
        if (graph_type == 'subgraph' and
                not self.obj_dict.get('show_keyword', True)):
            graph_type = ''
        s = '{type} {name} {{\n'.format(
            type=graph_type,
            name=self.obj_dict['name'])
        graph.append(s)

        for attr in sorted(self.obj_dict['attributes']):

            if self.obj_dict['attributes'].get(attr, None) is not None:

                val = self.obj_dict['attributes'].get(attr)
                if val == '':
                    val = '""'
                if val is not None:
                    graph.append('%s=%s' %
                                 (attr, quote_if_necessary(val)))
                else:
                    graph.append( attr )

                graph.append( ';\n' )


        edges_done = set()

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

        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 k in self.obj_dict['nodes']:
            node_obj_dicts.extend(self.obj_dict['nodes'][k])

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


        obj_list = [(obj['sequence'], obj)
                    for obj in (edge_obj_dicts +
                                node_obj_dicts + sgraph_obj_dicts) ]
        obj_list.sort(key=lambda x: x[0])

        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)
231129
function getTextureFromData(gl, data, opts) {
  if (data instanceof Texture2D) {
    return data;
  }
  return new Texture2D(gl, Object.assign({data}, opts));
}
347963
def _use_gl(objs):
    ''' 

    '''
    from ..models.plots import Plot
    return _any(objs, lambda obj: isinstance(obj, Plot) and obj.output_backend == "webgl")
360143
def make_dot_graph(filename, format='png', tool='dot', stop=True):
    
    if stop:
        stop_trace()

    dot_data = get_dot()

    # normalize filename
    regex_user_expand = re.compile('\A~')
    if regex_user_expand.match(filename):
        filename = os.path.expanduser(filename)
    else:
        filename = os.path.expandvars(filename)  # expand, just in case

    if format == 'dot':
        f = open(filename, 'w')
        f.write(dot_data)
        f.close()

    else:
        # create a temporary file to be used for the dot data
        fd, tempname = tempfile.mkstemp()
        with os.fdopen(fd, 'w') as f:
            f.write(dot_data)

        cmd = '%(tool)s -T%(format)s -o%(filename)s %(tempname)s' % locals()
        try:
            ret = os.system(cmd)
            if ret:
                raise PyCallGraphException( \
                    'The command "%(cmd)s" failed with error ' \
                    'code %(ret)i.' % locals())
        finally:
            os.unlink(tempname)
268365
def html(self, obj, fmt=None, css=None, **kwargs):
        
        plot, fmt =  self._validate(obj, fmt)
        figdata, _ = self(plot, fmt, **kwargs)
        if css is None: css = self.css

        if fmt in ['html', 'json']:
            return figdata
        else:
            if fmt == 'svg':
                figdata = figdata.encode("utf-8")
            elif fmt == 'pdf' and 'height' not in css:
                _, h = self.get_size(plot)
                css['height'] = '%dpx' % (h*self.dpi*1.15)

        if isinstance(css, dict):
            css = '; '.join("%s: %s" % (k, v) for k, v in css.items())
        else:
            raise ValueError("CSS must be supplied as Python dictionary")

        b64 = base64.b64encode(figdata).decode("utf-8")
        (mime_type, tag) = MIME_TYPES[fmt], HTML_TAGS[fmt]
        src = HTML_TAGS['base64'].format(mime_type=mime_type, b64=b64)
        html = tag.format(src=src, mime_type=mime_type, css=css)
        return html
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)
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)
416492
def graph_to_dot(graph, node_renderer=None, edge_renderer=None):
    """"""
    node_pairs = list(graph.nodes.items())
    edge_pairs = list(graph.edges.items())

    if node_renderer is None:
        node_renderer_wrapper = lambda nid: ''
    else:
        node_renderer_wrapper = lambda nid: ' [%s]' % ','.join(
            ['%s=%s' % tpl for tpl in list(node_renderer(graph, nid).items())])

    # Start the graph
    graph_string = 'digraph G {\n'
    graph_string += 'overlap=scale;\n'

    # Print the nodes (placeholder)
    for node_id, node in node_pairs:
        graph_string += '%i%s;\n' % (node_id, node_renderer_wrapper(node_id))

    # Print the edges
    for edge_id, edge in edge_pairs:
        node_a = edge['vertices'][0]
        node_b = edge['vertices'][1]
        graph_string += '%i -> %i;\n' % (node_a, node_b)

    # Finish the graph
    graph_string += '}'

    return graph_string
284271
def load_graph_xml(xml, filename, load_all=False):
    ''''''
    ret = []
    try:
        root = objectify.fromstring(xml)
    except Exception:
        return []
    if root.tag != 'graphs':
        return []
    if not hasattr(root, 'graph'):
        return []
    for g in root.graph:
        name = g.attrib['name']
        expressions = [e.text for e in g.expression]
        if load_all:
            ret.append(GraphDefinition(name, e, g.description.text, expressions, filename))
            continue
        if have_graph(name):
            continue
        for e in expressions:
            if expression_ok(e):
                ret.append(GraphDefinition(name, e, g.description.text, expressions, filename))
                break
    return ret
946208
def from_json_file(file: TextIO, check_version=True) -> BELGraph:
    """"""
    graph_json_dict = json.load(file)
    return from_json(graph_json_dict, check_version=check_version)
283317
def from_bytes(bytes_graph: bytes, check_version: bool = True) -> BELGraph:
    
    graph = loads(bytes_graph)

    raise_for_not_bel(graph)
    if check_version:
        raise_for_old_graph(graph)

    return graph
472051
def _as_graph_element(self):
    """"""
    if self.is_sequence():
      raise TypeError('A Pretty Tensor that holds a sequence cannot be '
                      'represented as a graph element.')
    else:
      # Self might be holding something else that isn't a true tensor, so
      # if the 'tensor' can behave like a graph element, look for its
      # _AsGraphElement method and call it. Graph elements themselves may not
      # have or need this method, so just return other items directly.
      obj = self.tensor
      conv_fn = getattr(obj, '_as_graph_element', None)
      if conv_fn and isinstance(conv_fn, collections.Callable):
        obj = conv_fn()
      return obj