Write a graph in our own compacted format.

    Returns:
        str.
424401
def write_compacted(g):
    
    d_nodes = {}
    d_edges = {}

    def conv(value):
        if isinstance(value, basestring):
            return value.strip('"')
        else:
            return value

    for node in g.nodes():
        label = None
        attrs = []

        for k, v in sorted(g.node_attributes(node)):
            v_ = conv(v)
            if k == "label":
                label = v_
            else:
                attrs.append((k, v_))

        value = (node, label) if label else node
        d_nodes.setdefault(tuple(attrs), []).append(value)

    for edge in g.edges():
        attrs = [(k, conv(v)) for k, v in sorted(g.edge_attributes(edge))]
        label = str(g.edge_label(edge))
        value = tuple(list(edge) + [label]) if label else edge
        d_edges.setdefault(tuple(attrs), []).append(tuple(value))

    doc = dict(nodes=d_nodes.items(), edges=d_edges.items())
    contents = str(doc)
    return contents
1254479
def writeMesh(self, vertices, faces, normals, values,
                  name='', reshape_faces=True):
        

        # Store properties
        self._hasNormals = normals is not None
        self._hasValues = values is not None
        self._hasFaces = faces is not None

        # Get faces and number of vertices
        if faces is None:
            faces = np.arange(len(vertices))
            reshape_faces = True

        if reshape_faces:
            Nfaces = faces.size // 3
            faces = faces.reshape((Nfaces, 3))
        else:
            is_triangular = np.array([len(f) == 3
                                      for f in faces])
            if not(np.all(is_triangular)):
                logger.warning('''Faces doesn't appear to be triangular,
                be advised the file cannot be read back in vispy''')
        # Number of vertices
        N = vertices.shape[0]

        # Get string with stats
        stats = []
        stats.append('%i vertices' % N)
        if self._hasValues:
            stats.append('%i texcords' % N)
        else:
            stats.append('no texcords')
        if self._hasNormals:
            stats.append('%i normals' % N)
        else:
            stats.append('no normals')
        stats.append('%i faces' % faces.shape[0])

        # Write header
        self.writeLine('# Wavefront OBJ file')
        self.writeLine('# Created by vispy.')
        self.writeLine('#')
        if name:
            self.writeLine('# object %s' % name)
        else:
            self.writeLine('# unnamed object')
        self.writeLine('# %s' % ', '.join(stats))
        self.writeLine('')

        # Write data
        if True:
            for i in range(N):
                self.writeTuple(vertices[i], 'v')
        if self._hasNormals:
            for i in range(N):
                self.writeTuple(normals[i], 'vn')
        if self._hasValues:
            for i in range(N):
                self.writeTuple(values[i], 'vt')
        if True:
            for i in range(faces.shape[0]):
                self.writeFace(faces[i])
4648
def formatted(self):
        """"""
        return ' '.join(self.compact[i:i + 4] for i in range(0, len(self.compact), 4))
897338
def writeMNIST(sc, input_images, input_labels, output, format, num_partitions):
  """"""
  # load MNIST gzip into memory
  with open(input_images, 'rb') as f:
    images = numpy.array(mnist.extract_images(f))

  with open(input_labels, 'rb') as f:
    if format == "csv2":
      labels = numpy.array(mnist.extract_labels(f, one_hot=False))
    else:
      labels = numpy.array(mnist.extract_labels(f, one_hot=True))

  shape = images.shape
  print("images.shape: {0}".format(shape))          # 60000 x 28 x 28
  print("labels.shape: {0}".format(labels.shape))   # 60000 x 10

  # create RDDs of vectors
  imageRDD = sc.parallelize(images.reshape(shape[0], shape[1] * shape[2]), num_partitions)
  labelRDD = sc.parallelize(labels, num_partitions)

  output_images = output + "/images"
  output_labels = output + "/labels"

  # save RDDs as specific format
  if format == "pickle":
    imageRDD.saveAsPickleFile(output_images)
    labelRDD.saveAsPickleFile(output_labels)
  elif format == "csv":
    imageRDD.map(toCSV).saveAsTextFile(output_images)
    labelRDD.map(toCSV).saveAsTextFile(output_labels)
  elif format == "csv2":
    imageRDD.map(toCSV).zip(labelRDD).map(lambda x: str(x[1]) + "|" + x[0]).saveAsTextFile(output)
  else:  # format == "tfr":
    tfRDD = imageRDD.zip(labelRDD).map(lambda x: (bytearray(toTFExample(x[0], x[1])), None))
    # requires: --jars tensorflow-hadoop-1.0-SNAPSHOT.jar
    tfRDD.saveAsNewAPIHadoopFile(output, "org.tensorflow.hadoop.io.TFRecordFileOutputFormat",
                                 keyClass="org.apache.hadoop.io.BytesWritable",
                                 valueClass="org.apache.hadoop.io.NullWritable")
641381
def dump_nt_sorted(g: Graph) -> List[str]:
    
    return [l.decode('ascii') for l in sorted(g.serialize(format='nt').splitlines()) if l]
220988
def graph_format(new_mem, old_mem, is_firstiteration=True):
    """"""
    if is_firstiteration:
        output = "  n/a   "
    elif new_mem - old_mem > 50000000:
        output = "   +++++"
    elif new_mem - old_mem > 20000000:
        output = "   ++++ "
    elif new_mem - old_mem > 5000000:
        output = "   +++  "
    elif new_mem - old_mem > 1000000:
        output = "   ++   "
    elif new_mem - old_mem > 50000:
        output = "   +    "
    elif old_mem - new_mem > 10000000:
        output = "---     "
    elif old_mem - new_mem > 2000000:
        output = " --     "
    elif old_mem - new_mem > 100000:
        output = "  -     "
    else:
        output = "        "
    return output
1001435
def write(graph, fileformat=None, filename=None):
        

        filewriter = None
        if fileformat is None:
            fileformat = 'turtle'
        if filename is not None:

            with open(filename, 'wb') as filewriter:
                LOG.info("Writing triples in %s to %s", fileformat, filename)
                # rdflib serialize
                graph.serialize(filewriter, format=fileformat)
        else:
            print(graph.serialize(fileformat).decode())
        return
530233
def graph(self, ig):
        

        res = copy.copy(self)
        res._edges = ig
        res._nodes = None
        return res
698909
def _draw_ascii_graph(self, field):
        ''''''
        row_strings = []
        for y in range(len(field[0])):
            row = ''
            for x in range(len(field)):
                row += field[x][y]
            row_strings.insert(0, row)
        graph_string = '\n'.join(row_strings)
        return graph_string
114162
def dump_tf_graph(tfgraph, tfgraphdef):
    
    print("Nodes ({})".format(len(tfgraphdef.node)))
    f = "{:15} {:59} {:20} {}"
    print(f.format("kind", "scopeName", "shape", "inputs"))
    for node in tfgraphdef.node:
        scopename = node.name
        kind = node.op
        inputs = node.input
        shape = tf.graph_util.tensor_shape_from_node_def_name(tfgraph, scopename)
        print(f.format(kind, scopename, str(shape), inputs))
600098
def serialize(self):
        
        forward_edges, backward_edges = build_edges(self.nodes.values())

        return {
            'nodes': {k: v.serialize() for k, v in self.nodes.items()},
            'macros': {k: v.serialize() for k, v in self.macros.items()},
            'docs': {k: v.serialize() for k, v in self.docs.items()},
            'parent_map': backward_edges,
            'child_map': forward_edges,
            'generated_at': self.generated_at,
            'metadata': self.metadata,
            'disabled': [v.serialize() for v in self.disabled],
        }
614400
def write_graph(self, filename):
        
        f = open(filename, 'w')
        f.write(self._get_graphviz_data())
        f.close()
1193549
def print_cyjs_graph(self):
        
        cyjs_dict = {'edges': self._edges, 'nodes': self._nodes}
        cyjs_str = json.dumps(cyjs_dict, indent=1, sort_keys=True)
        return cyjs_str
810523
def format(self, vertices):
        
        buf = io.StringIO()

        buf.write(self.name + '\n')
        buf.write('{\n')
        buf.write('    type {};\n'.format(self.type_))
        buf.write('    faces\n')
        buf.write('    (\n')
        for f in self.faces:
            s = f.format(vertices)
            buf.write('        {}\n'.format(s))
        buf.write('    );\n')
        buf.write('}')
        return buf.getvalue()
1068945
def _to_bel_lines_footer(graph) -> Iterable[str]:
    
    unqualified_edges_to_serialize = [
        (u, v, d)
        for u, v, d in graph.edges(data=True)
        if d[RELATION] in UNQUALIFIED_EDGES and EVIDENCE not in d
    ]

    isolated_nodes_to_serialize = [
        node
        for node in graph
        if not graph.pred[node] and not graph.succ[node]
    ]

    if unqualified_edges_to_serialize or isolated_nodes_to_serialize:
        yield '###############################################\n'
        yield 'SET Citation = {"PubMed","Added by PyBEL","29048466"}'
        yield 'SET SupportingText = "{}"'.format(PYBEL_AUTOEVIDENCE)

        for u, v, data in unqualified_edges_to_serialize:
            yield '{} {} {}'.format(u.as_bel(), data[RELATION], v.as_bel())

        for node in isolated_nodes_to_serialize:
            yield node.as_bel()

        yield 'UNSET SupportingText'
        yield 'UNSET Citation'
32060
def __serializedDot(self):
		
		temp = ""
		for x,y,z in self.rdflib_graph.triples((None, None, None)):
			temp += """"%s" -> "%s" [label="%s"];\n""" % (self.namespace_manager.normalizeUri(x), self.namespace_manager.normalizeUri(z), self.namespace_manager.normalizeUri(y))
		temp = "digraph graphname {\n%s}" % temp
		return temp
958841
def generate(self):
        
        logger.info('Generating graphs')
        self._generate_graph(
            'by-version',
            'Downloads by Version',
            self._stats.per_version_data,
            'Version'
        )
        self._generate_graph(
            'by-file-type',
            'Downloads by File Type',
            self._stats.per_file_type_data,
            'File Type'
        )
        self._generate_graph(
            'by-installer',
            'Downloads by Installer',
            self._stats.per_installer_data,
            'Installer'
        )
        self._generate_graph(
            'by-implementation',
            'Downloads by Python Implementation/Version',
            self._stats.per_implementation_data,
            'Implementation/Version'
        )
        self._generate_graph(
            'by-system',
            'Downloads by System Type',
            self._stats.per_system_data,
            'System'
        )
        self._generate_graph(
            'by-country',
            'Downloads by Country',
            self._stats.per_country_data,
            'Country'
        )
        self._generate_graph(
            'by-distro',
            'Downloads by Distro',
            self._stats.per_distro_data,
            'Distro'
        )
        self._generate_badges()
        logger.info('Generating HTML')
        html = self._generate_html()
        html_path = os.path.join(self.output_dir, 'index.html')
        with open(html_path, 'wb') as fh:
            fh.write(html.encode('utf-8'))
        logger.info('HTML report written to %s', html_path)
        logger.info('Writing SVG badges')
        for name, svg in self._badges.items():
            path = os.path.join(self.output_dir, '%s.svg' % name)
            with open(path, 'w') as fh:
                fh.write(svg)
            logger.info('%s badge written to: %s', name, path)