Creates a graph from saved GraphDef file and returns a saver.
492066
def create_graph():
  """"""
  # Creates graph from saved graph_def.pb.
  with tf.gfile.FastGFile(os.path.join(
      FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    _ = tf.import_graph_def(graph_def, name='')
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))
717118
def _get_graph(graph, filename):
    """"""
    try:
        rendered = graph.rendered_file
    except AttributeError:
        try:
            graph.render(os.path.join(server.tmpdir, filename), format='png')
            rendered = filename
        except OSError:
            rendered = None
    graph.rendered_file = rendered
    return rendered
558826
def _make_graph(bsname, version=None, data_dir=None):
    '''
    
    '''

    if not graphviz_avail:
        raise RuntimeError("graphviz package is not installed")

    data_dir = api.fix_data_dir(data_dir)

    md = api._get_basis_metadata(bsname, data_dir)

    if version is None:
        version = md['latest_version']
    else:
        version = str(version)

    if not version in md['versions']:
        raise RuntimeError("Version {} of {} doesn't exist".format(version, bsname))

    gr = graphviz.Digraph(comment='Basis Set Graph: ' + bsname)

    # Read the table file
    table_path = os.path.join(data_dir, md['versions'][version]['file_relpath'])
    table_data = fileio.read_json_basis(table_path)

    table_edges = {}
    for el, entry in table_data['elements'].items():
        if entry not in table_edges:
            table_edges[entry] = []
        table_edges[entry].append(el)

    for k, v in table_edges.items():
        gr.edge(bsname, k, label=compact_elements(v))

    # Element file
    for elfile in table_edges.keys():
        element_path = os.path.join(data_dir, elfile)
        element_data = fileio.read_json_basis(element_path)

        element_edges = {}

        for el, components in element_data['elements'].items():
            components = components['components']
            components_str = '\n'.join(components)

            # skip if this element for the table basis doesn't come from this file
            if el not in table_data['elements']:
                continue
            if table_data['elements'][el] != elfile:
                continue

            if components_str not in element_edges:
                element_edges[components_str] = []
            element_edges[components_str].append(el)

        for k, v in element_edges.items():
            if len(v):
                gr.edge(elfile, k, label=compact_elements(v))

    return gr
461899
public static void saveGraph(DirectedGraph<Integer, DefaultEdge> graph, File file) throws IOException {
		SerializableDirectedGraph serialGraph = new SerializableDirectedGraph(graph);
		BufferedOutputStream fos;
		ObjectOutputStream out;
		fos = new BufferedOutputStream(new FileOutputStream(file));
		out = new ObjectOutputStream(fos);
		out.writeObject(serialGraph);
		out.close();

	}
793801
def _gen_trend_graph(start, end, force_overwrite=False):
    
    filename = graphs.get_trend_graph_filename(start, end)
    csv_filename = os.path.join(GRAPH_ROOT, filename + '.csv')
    png_filename = os.path.join(GRAPH_ROOT, filename + '.png')

    _check_directory_exists(csv_filename)
    _check_directory_exists(png_filename)

    if not settings.GRAPH_DEBUG or force_overwrite:
        if os.path.exists(csv_filename):
            if os.path.exists(png_filename):
                return

    query = CPUJob.objects.filter(
        date__range=(start, end)
    )
    query = query.values('date').annotate(Sum('cpu_usage'))
    query = query.order_by('date')

    t_start = start
    t_end = end

    start_str = start.strftime('%Y-%m-%d')
    end_str = end.strftime('%Y-%m-%d')

    fig, ax = plt.subplots(figsize=(6, 4))
    ax.set_xlim(start, end)
    ax.set_title('%s - %s' % (start_str, end_str))
    ax.set_ylabel("CPU Time (hours)")
    ax.set_xlabel("Date")

    locator = mdates.AutoDateLocator()
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator))
    ax.xaxis.set_minor_locator(mdates.DayLocator())

    data = {}
    x_data = []
    y_data = []

    with open(csv_filename, 'w') as csv_file:
        csv_writer = csv.writer(csv_file)
        for row in query.iterator():
            csv_writer.writerow([
                row['date'], row['cpu_usage__sum'] / 3600.00
            ])

            date = row['date']

            data[date] = row['cpu_usage__sum']

    start = t_start
    end = t_end
    while start <= end:
        total = 0
        if start in data:
            total = data[start]
        x_data.append(start)
        y_data.append(total / 3600.00)
        start = start + datetime.timedelta(days=1)

    del data

    ax.plot(x_data, y_data)

    del x_data
    del y_data

    fig.autofmt_xdate()
    plt.tight_layout()
    plt.savefig(png_filename)
    plt.close()
680584
def create(fmt):
        
        w = None
        if fmt == 'tree':
            w = AsciiTreeGraphRenderer()
        elif fmt == 'dot':
            w = DotGraphRenderer(image_format='dot')
        elif fmt == 'png':
            w = DotGraphRenderer(image_format='png')
        elif fmt == 'ndot':
            w = NativeDotGraphRenderer()
        elif fmt == 'obo':
            w = OboFormatGraphRenderer()
        elif fmt == 'obog':
            w = OboJsonGraphRenderer()
        else:
            w = SimpleListGraphRenderer()
        return w
940478
def save_model(self, steps):
        
        with self.graph.as_default():
            last_checkpoint = self.model_path + '/model-' + str(steps) + '.cptk'
            self.saver.save(self.sess, last_checkpoint)
            tf.train.write_graph(self.graph, self.model_path,
                                 'raw_graph_def.pb', as_text=False)
1274040
def generate_graphs(data_frames, hardware_info, steps, outdir,
                    verbose=False):
    """"""
    _setup_matplotlib()
    # Hash of hosts containing (data, hardware, steps) tuple
    collectl_info = collections.defaultdict(dict)

    for host, data_frame in data_frames.items():
        if verbose:
            print('Generating CPU graph for {}...'.format(host))
        graph, data_cpu = graph_cpu(data_frame, steps, hardware_info[host]['num_cpus'])

        graph.get_figure().savefig(
            os.path.join(outdir, '{}_cpu.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        ifaces = set([series.split('_')[0]
                      for series in data_frame.keys()
                      if series.startswith(('eth', 'ib'))])

        if verbose:
            print('Generating network graphs for {}...'.format(host))
        graph, data_net_bytes = graph_net_bytes(data_frame, steps, ifaces)
        graph.get_figure().savefig(
            os.path.join(outdir, '{}_net_bytes.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        graph, data_net_pkts = graph_net_pkts(data_frame, steps, ifaces)
        graph.get_figure().savefig(
            os.path.join(outdir, '{}_net_pkts.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        if verbose:
            print('Generating memory graph for {}...'.format(host))
        graph, data_mem = graph_memory(data_frame, steps, hardware_info[host]["memory"])
        graph.get_figure().savefig(
            os.path.join(outdir, '{}_memory.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        if verbose:
            print('Generating storage I/O graph for {}...'.format(host))
        drives = set([
            series.split('_')[0]
            for series in data_frame.keys()
            if series.startswith(('sd', 'vd', 'hd', 'xvd'))
        ])
        graph, data_disk = graph_disk_io(data_frame, steps, drives)
        graph.get_figure().savefig(
            os.path.join(outdir, '{}_disk_io.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        print('Serializing output to pickle object for node {}...'.format(host))
        # "Clean" dataframes ready to be plotted
        collectl_info[host] = { "hardware": hardware_info,
                                "steps": steps, "cpu": data_cpu, "mem": data_mem,
                                "disk": data_disk, "net_bytes": data_net_bytes,
                                "net_pkts": data_net_pkts
                              }
    return collectl_info
234951
def save_graph_to_file(graph_file_name, module_spec, class_count):
  """"""
  sess, _, _, _, _, _ = build_eval_session(module_spec, class_count)
  graph = sess.graph

  output_graph_def = tf.graph_util.convert_variables_to_constants(
      sess, graph.as_graph_def(), [FLAGS.final_tensor_name])

  with tf.gfile.GFile(graph_file_name, 'wb') as f:
    f.write(output_graph_def.SerializeToString())
707088
def _make_graph(self, max_insert):
        ''''''
        if len(self.partial_links) != 0:
            raise Error('Error in _make_graph(). Cannot continue because there are partial links')
        
        self.contig_links = {}
        for key in self.links:
            for l in self.links[key]:
                insert_size = l.insert_size()
                if insert_size <= max_insert:
                    if key not in self.contig_links:
                        self.contig_links[key] = {}
                    dirs = ''.join(l.dirs)
                    self.contig_links[key][dirs] = self.contig_links[key].get(dirs, 0) + 1
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)
780247
def _create_word_graph_file(name, file_storage, word_set):
    """"""
    word_graph_file = file_storage.create_file(name)
    spelling.wordlist_to_graph_file(sorted(list(word_set)),
                                    word_graph_file)
    return copy_to_ram(file_storage).open_file(name)
519162
def save(self, cfg, filename, print_ir=False, format='dot', options=None):
        
        if options is None:
            options = {}

        try:
            dot_graph = Dot(**self.graph_format)

            # Add nodes.
            nodes = {}
            for bb in cfg.basic_blocks:
                nodes[bb.address] = self._create_node(bb, cfg.name, print_ir, options)

                dot_graph.add_node(nodes[bb.address])

            # Add edges.
            for bb_src in cfg.basic_blocks:
                for bb_dst_addr, branch_type in bb_src.branches:
                    if bb_dst_addr in nodes:
                        edge = self._create_edge(nodes[bb_src.address], nodes[bb_dst_addr], branch_type)

                        dot_graph.add_edge(edge)
                    else:
                        logger.warning("Destination basic block not found! (0x%x)", bb_dst_addr)

            # Save graph.
            dot_graph.write("{}.{}".format(filename, format), format=format)
        except Exception:
            logger.error("Failed to save basic block graph: %s (%s)", filename, format, exc_info=True)
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
924955
def save_dot(self, file_name='graph.dot'):
        
        s = self.get_string()
        with open(file_name, 'wt') as fh:
            fh.write(s)
659437
def generate_graph(self):
        
        logger.debug('Generating graph for %s', self._graph_id)
        # tools to use
        tools = [
            PanTool(),
            BoxZoomTool(),
            WheelZoomTool(),
            SaveTool(),
            ResetTool(),
            ResizeTool()
        ]

        # generate the stacked area graph
        try:
            g = Area(
                self._data, x='Date', y=self._y_series_names,
                title=self._title, stack=True, xlabel='Date',
                ylabel='Downloads', tools=tools,
                # note the width and height will be set by JavaScript
                plot_height=400, plot_width=800,
                toolbar_location='above', legend=False
            )
        except Exception as ex:
            logger.error("Error generating %s graph", self._graph_id)
            logger.error("Data: %s", self._data)
            logger.error("y=%s", self._y_series_names)
            raise ex

        lines = []
        legend_parts = []
        # add a line at the top of each Patch (stacked area) for hovertool
        for renderer in g.select(GlyphRenderer):
            if not isinstance(renderer.glyph, Patches):
                continue
            series_name = renderer.data_source.data['series'][0]
            logger.debug('Adding line for Patches %s (series: %s)', renderer,
                         series_name)
            line = self._line_for_patches(self._data, g, renderer, series_name)
            if line is not None:
                lines.append(line)
                legend_parts.append((series_name, [line]))

        # add the Hovertool, specifying only our line glyphs
        g.add_tools(
            HoverTool(
                tooltips=[
                    (self._y_name, '@SeriesName'),
                    ('Date', '@FmtDate'),
                    ('Downloads', '@Downloads'),
                ],
                renderers=lines,
                line_policy='nearest'
            )
        )

        # legend outside chart area
        legend = Legend(legends=legend_parts, location=(0, 0))
        g.add_layout(legend, 'right')
        return components(g)