Serialize the graph to an object or file if given.

        For additional I/O, see the :mod:`pybel.io` module.
516343
def serialize(self, *, fmt: str = 'nodelink', file: Union[None, str, TextIO] = None, **kwargs):
        
        if file is None:
            return self._serialize_object(fmt=fmt, **kwargs)
        elif isinstance(file, str):
            with open(file, 'w') as file_obj:
                self._serialize_file(fmt=fmt, file=file_obj, **kwargs)
        else:
            self._serialize_file(fmt=fmt, file=file, **kwargs)
307737
def save_frames(obj, filename, fmt=None, backend=None, options=None):
    
    backend = Store.current_backend if backend is None else backend
    renderer = Store.renderers[backend]
    fmt = renderer.params('fig').objects[0] if fmt is None else fmt
    plot = renderer.get_plot(obj)
    for i in range(len(plot)):
        plot.update(i)
        renderer.save(plot, '%s_%s' % (filename, i), fmt=fmt, options=options)
900034
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 in self.obj_dict['attributes'].iterkeys():
        
            if self.obj_dict['attributes'].get(attr, None) is not None:
       
                val = self.obj_dict['attributes'].get(attr)
                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 e in self.obj_dict['edges'].itervalues():
            edge_obj_dicts.extend(e)
            
        if edge_obj_dicts:
            edge_src_set, edge_dst_set = 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'].itervalues():
            node_obj_dicts.extend(e)

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

        
        obj_list = [ (obj['sequence'], obj) for obj in (edge_obj_dicts + node_obj_dicts + sgraph_obj_dicts) ]
        obj_list.sort()
        
        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)
220433
def serialize(self, elt, sw, pyobj, **kw):
        '''
        '''
        if isinstance(pyobj, TypeCode):
            raise TypeError, 'pyobj is a typecode instance.'
        
        what = getattr(pyobj, 'typecode', None)
        if what is not None and type(pyobj) is types.InstanceType:
            tc = pyobj.__class__
            what = Any.serialmap.get(tc)
            if not what:
                tc = (types.ClassType, pyobj.__class__.__name__)
                what = Any.serialmap.get(tc)
        
        self.logger.debug('processContents: %s', self.processContents)

        # failed to find a registered type for class
        if what is None:
            #TODO: seems incomplete.  what about facets.
            #if self.processContents == 'strict':
            what = Any(pname=(self.nspname,self.pname))
                
        self.logger.debug('serialize with %s', what.__class__.__name__)
        what.serialize(elt, sw, pyobj, **kw)
1190558
def serialize(self, format="turtle"):
        
        if self.triples:
            if not self.rdfgraph:
                self._buildGraph()
            return self.rdfgraph.serialize(format=format)
        else:
            return None
1356021
def _serialize_data(self, data):
        

        data.update(data['include'])
        data.update(data['to_many'])
        data.update(data['to_one'])

        for key, val in data.items():
            if isinstance(val, dict):
                pass
            elif isinstance(val, list):
                pass
            else:
                str(val)
945457
function saveGraphSON(graph, filename, callback) {
        var FileOutputStream = Tinkerpop.autoImport('FileOutputStream');
        var stream = new FileOutputStream(filename);
        return Tinkerpop.GraphSONWriter.buildP()
            .then(function (builder) {
            return _newGraphSONMapper()
                .then(function (mapper) { return builder.mapperP(mapper); });
        })
            .then(function (builder) { return builder.createP(); })
            .then(function (writer) { return writer.writeGraphP(stream, graph); })
            .then(function () { return graph; })
            .nodeify(callback);
    }
48935
def serialize(node, stream=None, Dumper=Dumper, **kwds):
    
    return serialize_all([node], stream, Dumper=Dumper, **kwds)
1041419
def save_figure_tofile(fig, fmt, fname):
    """"""
    root, ext = osp.splitext(fname)
    if ext == '.png' and fmt == 'image/svg+xml':
        qimg = svg_to_image(fig)
        qimg.save(fname)
    else:
        if fmt == 'image/svg+xml' and is_unicode(fig):
            fig = fig.encode('utf-8')

        with open(fname, 'wb') as f:
            f.write(fig)
1012835
def dump(self,format='ttl'):

		'''
		
		'''

		return self.rdf.graph.serialize(format=format).decode('utf-8')
544400
def unserialize(jsonstr):
        '''
        
        '''
        topod = json.loads(jsonstr)
        G = json_graph.node_link_graph(topod)
        for n,ndict in G.nodes(data=True):
            if 'nodeobj' not in ndict or 'type' not in ndict:
                raise Exception("Required type information is not present in serialized node {} :{}".format(n, ndict))
            nobj = ndict['nodeobj']
            cls = eval(ndict['type'])
            ndict['nodeobj'] = cls(**dict(nobj))
        t = Topology(nxgraph=G)
        return t
53878
def serialize_rdf(update_graph, signing):
    '''
    '''
    unsorted_s = update_graph.serialize(format = 'pretty-xml')
    unsorted_s = unsorted_s.replace('xmlns:rdf', 'xmlns:RDF')
    unsorted_s = unsorted_s.replace('rdf:', 'RDF:')
    unsorted_s = unsorted_s.replace('RDF:about', 'about')
    unsorted_s = unsorted_s.split('\n')
    start, end = unsorted_s[0:5], unsorted_s[-2:]
    unsorted_s = unsorted_s[5:-2]
    if signing:
        unsorted_s = [line[2:] for line in unsorted_s]
        unsorted_s.append('')
    sorting_s = []
    prev_leading_spaces = -2
    for line in unsorted_s:
        leading_spaces = len(line) - len(line.lstrip())
        if leading_spaces > prev_leading_spaces:
            sorting_s.append([line])
        elif leading_spaces == prev_leading_spaces:
            sorting_s[-1].append(line)
        elif leading_spaces < prev_leading_spaces:
            tmp_line = sorting_s.pop()
            tmp_line = '\n'.join(sorted(tmp_line))
            tmp_line = [sorting_s[-1].pop(), tmp_line, line]
            tmp_line = '\n'.join(tmp_line)
            sorting_s[-1].append(tmp_line)
        prev_leading_spaces = leading_spaces
    if signing:
        sorted_s = '\n'.join(sorting_s[0])
    else:
        sorted_s = []
        sorted_s.extend(start)
        sorted_s.extend(sorting_s[0])
        sorted_s.extend(end)
        sorted_s = '\n'.join(sorted_s)
    return sorted_s
271746
def serialize(obj):
    
    LOGGER.debug('serialize(%s)', obj)

    if isinstance(obj, datetime.date):
        return simplejson.dumps(obj, default=encoders.as_date)

    elif hasattr(obj, '__dict__'):
        return simplejson.dumps(obj, default=encoders.as_object)

    return simplejson.dumps(obj)
145561
def _dumps(self, obj):
        
        if not self.serialized:
            return obj
        return self.serializer.dumps(obj)
1187526
def serialize(self, data):
        '''
        
        '''
        self.set_header('Content-Type', self.content_type)

        return self.dumper(data)
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()
1280069
def to_sif_path(graph: BELGraph, path: str, sep: Optional[str] = None) -> None:
    """"""
    with open(path, 'w') as file:
        to_sif(graph, file, sep=sep)