Create a simple graph of processes and artifacts.
761141
def _rdf2dot_simple(g, stream):
    """"""
    from itertools import chain

    import re

    path_re = re.compile(
        r'file:///(?P<type>[a-zA-Z]+)/'
        r'(?P<commit>\w+)'
        r'(?P<path>.+)?'
    )

    inputs = g.query(
        """
        SELECT ?input ?role ?activity ?comment
        WHERE {
            ?activity (prov:qualifiedUsage/prov:entity) ?input .
            ?activity prov:qualifiedUsage ?qual .
            ?qual prov:hadRole ?role .
            ?qual prov:entity ?input .
            ?qual rdf:type ?type .
            ?activity rdf:type wfprov:ProcessRun .
            ?activity rdfs:comment ?comment .
            FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun}
        }
        """
    )
    outputs = g.query(
        """
        SELECT ?activity ?role ?output ?comment
        WHERE {
            ?output (prov:qualifiedGeneration/prov:activity) ?activity .
            ?output prov:qualifiedGeneration ?qual .
            ?qual prov:hadRole ?role .
            ?qual prov:activity ?activity .
            ?qual rdf:type ?type .
            ?activity rdf:type wfprov:ProcessRun ;
                      rdfs:comment ?comment .
            FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun}
        }
        """
    )

    activity_nodes = {}
    artifact_nodes = {}
    for source, role, target, comment, in chain(inputs, outputs):
        # extract the pieces of the process URI
        src_path = path_re.match(source).groupdict()
        tgt_path = path_re.match(target).groupdict()

        # write the edge
        stream.write(
            '\t"{src_commit}:{src_path}" -> '
            '"{tgt_commit}:{tgt_path}" '
            '[label={role}] \n'.format(
                src_commit=src_path['commit'][:5],
                src_path=src_path.get('path') or '',
                tgt_commit=tgt_path['commit'][:5],
                tgt_path=tgt_path.get('path') or '',
                role=role
            )
        )
        if src_path.get('type') == 'commit':
            activity_nodes.setdefault(source, {'comment': comment})
            artifact_nodes.setdefault(target, {})
        if tgt_path.get('type') == 'commit':
            activity_nodes.setdefault(target, {'comment': comment})
            artifact_nodes.setdefault(source, {})

    # customize the nodes
    for node, content in activity_nodes.items():
        node_path = path_re.match(node).groupdict()
        stream.write(
            '\t"{commit}:{path}" '
            '[shape=box label="#{commit}:{path}:{comment}"] \n'.format(
                comment=content['comment'],
                commit=node_path['commit'][:5],
                path=node_path.get('path') or ''
            )
        )
    for node, content in artifact_nodes.items():
        node_path = path_re.match(node).groupdict()
        stream.write(
            '\t"{commit}:{path}" '
            '[label="#{commit}:{path}"] \n'.format(
                commit=node_path['commit'][:5],
                path=node_path.get('path') or ''
            )
        )
    stream.write('}\n')
297977
def main(graph):
    
    args = parse_args(graph)

    if args.drop:
        drop_all(graph)
    create_all(graph)
598669
def plot_dot_graph(graph, filename=None):
    
    if not plot.pygraphviz_available:
        logger.error("Pygraphviz is not installed, cannot generate graph plot!")
        return
    if not plot.PIL_available:
        logger.error("PIL is not installed, cannot display graph plot!")
        return

    agraph = AGraph(graph)
    agraph.layout(prog='dot')
    if filename is None:
        filename = tempfile.mktemp(suffix=".png")
    agraph.draw(filename)
    image = Image.open(filename)
    image.show()
1100357
def new_graph(self, graph, typ):
        """"""
        graph = self.pack(graph)
        return self.sql('new_graph', graph, typ)
345052
def _bsecurate_cli_make_graph_file(args):
    ''''''

    curate.make_graph_file(args.basis, args.outfile, args.render, args.version, args.data_dir)
    return ''
1267497
def main():
    
    fmt,plot='svg',0
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    elif '-f' in sys.argv: # ask for filename
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'r')
        input=f.readlines()
    Data=[]
    for line in input:
        line.replace('\n','')
        if '\t' in line:   # read in the data from standard input
            rec=line.split('\t') # split each line on space to get records
        else:
            rec=line.split() # split each line on space to get records
        Data.append(float(rec[0]))
    
#
    if len(Data) >=10: 
        QQ={'unf1':1}
        pmagplotlib.plot_init(QQ['unf1'],5,5)
        pmagplotlib.plot_qq_unf(QQ['unf1'],Data,'QQ-Uniform') # make plot
    else:
        print('you need N> 10')
        sys.exit()
    pmagplotlib.draw_figs(QQ) 
    files={}
    for key in list(QQ.keys()):
        files[key]=key+'.'+fmt 
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Equal Area Plot'
        EQ = pmagplotlib.add_borders(EQ,titles,black,purple)
        pmagplotlib.save_plots(QQ,files)
    elif plot==1:
        files['qq']=file+'.'+fmt 
        pmagplotlib.save_plots(QQ,files)
    else:
        ans=input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans=="a": pmagplotlib.save_plots(QQ,files)
532239
def log(client, revision, format, no_output, paths):
    """"""
    graph = Graph(client)
    if not paths:
        start, is_range, stop = revision.partition('..')
        if not is_range:
            stop = start
        elif not stop:
            stop = 'HEAD'

        commit = client.repo.rev_parse(stop)
        paths = (
            str(client.path / item.a_path)
            for item in commit.diff(commit.parents or NULL_TREE)
            # if not item.deleted_file
        )

    # NOTE shall we warn when "not no_output and not paths"?
    graph.build(paths=paths, revision=revision, can_be_cwl=no_output)

    FORMATS[format](graph)
968030
def generate_graphs(data, name, results_dir):
    
    graphs.resp_graph_raw(data['raw'], name + '_response_times.svg', results_dir)
    graphs.resp_graph(data['compiled'], name + '_response_times_intervals.svg', results_dir)
    graphs.tp_graph(data['compiled'], name + '_throughput.svg', results_dir)
201814
function graph (processedTypes, typeTheme) {
  var result = ''

  if (typeTheme.group) {
    result += 'subgraph cluster_' + groupId++ + ' {'
    if (typeTheme.color) {
      result += 'color=' + typeTheme.color + ';'
    }
    if (typeTheme.groupLabel) {
      result += 'label="' + typeTheme.groupLabel + '";'
    }
  }

  result += _.map(processedTypes, v => {
    // sort if desired
    if (this.theme.field.sort) {
      v.fields = _.sortBy(v.fields, 'name')
    }

    var rows = _.map(v.fields, v => {
      return {
        text: createField.call(this, v),
        port: v.name + 'port'
      }
    })

    return createTable.call(this, {
      typeName: getTypeDisplayName(v.name),
      color: typeTheme.color,
      stereotype: typeTheme.stereotype,
      rows: rows
    })
  }).join('\n')

  if (typeTheme.group) {
    result += '}'
  }

  result += '\n\n'
  return result
}
1084652
def Main():
  
  argument_parser = argparse.ArgumentParser(description=(
      'Plots memory usage from profiling data.'))

  argument_parser.add_argument(
      '--output', dest='output_file', type=str, help=(
          'path of the output file to write the graph to instead of using '
          'interactive mode. The output format deduced from the extension '
          'of the filename.'))

  argument_parser.add_argument(
      'profile_path', type=str, help=(
          'path to the directory containing the profiling data.'))

  options = argument_parser.parse_args()

  if not os.path.isdir(options.profile_path):
    print('No such directory: {0:s}'.format(options.profile_path))
    return False

  names = ['time', 'identifier', 'status']

  measurements = {}

  glob_expression = os.path.join(options.profile_path, 'tasks-*.csv.gz')
  for csv_file_name in glob.glob(glob_expression):
    data = numpy.genfromtxt(
        csv_file_name, delimiter='\t', dtype=None, encoding='utf-8',
        names=names, skip_header=1)

    label = os.path.basename(csv_file_name)
    label = label.replace('tasks-', '').replace('.csv.gz', '')

    for time, identifier, status in data:
      if identifier not in measurements:
        measurements[identifier] = TaskMeasurements()

      task_measurement = measurements[identifier]

      if status == 'completed':
        task_measurement.completed_time = time
        task_measurement.merging_duration = time - task_measurement.merging_time

      elif status == 'created':
        task_measurement.created_time = time

      # TODO: add support for:
      # elif status == 'merge_on_hold':
      # elif status == 'merge_resumed':

      elif status == 'merge_started':
        task_measurement.merging_time = time

      elif status == 'pending_merge':
        task_measurement.pending_merge_time = time

      elif status == 'processed':
        task_measurement.processed_time = time

      elif status == 'processing_started':
        task_measurement.processing_time = time

      elif status == 'processing_completed':
        task_measurement.processing_duration = (
            time - task_measurement.processing_time)

      elif status == 'scheduled':
        task_measurement.scheduled_time = time

  before_pending_merge_duration = {}
  before_queued_duration = {}
  merging_duration = {}
  pending_merge_duration = {}
  processing_duration = {}
  queued_duration = {}

  for identifier, task_measurement in measurements.items():
    before_pending_merge_duration[task_measurement.scheduled_time] = (
        task_measurement.pending_merge_time - (
            task_measurement.processing_time +
            task_measurement.processing_duration))

    before_queued_duration[task_measurement.scheduled_time] = (
        task_measurement.scheduled_time - task_measurement.created_time)

    merging_duration[task_measurement.merging_time] = (
        task_measurement.merging_duration)

    pending_merge_duration[task_measurement.processing_time] = (
        task_measurement.merging_time - task_measurement.pending_merge_time)

    processing_duration[task_measurement.processing_time] = (
        task_measurement.processing_duration)

    queued_duration[task_measurement.scheduled_time] = (
        task_measurement.processing_time - task_measurement.scheduled_time)

  keys = sorted(before_pending_merge_duration.keys())
  values = [before_pending_merge_duration[key] for key in keys]
  pyplot.plot(keys, values, label='Before pending merge')

  keys = sorted(before_queued_duration.keys())
  values = [before_queued_duration[key] for key in keys]
  pyplot.plot(keys, values, label='Before queued')

  keys = sorted(merging_duration.keys())
  values = [merging_duration[key] for key in keys]
  pyplot.plot(keys, values, label='Merging')

  keys = sorted(pending_merge_duration.keys())
  values = [pending_merge_duration[key] for key in keys]
  pyplot.plot(keys, values, label='Pending merge')

  keys = sorted(processing_duration.keys())
  values = [processing_duration[key] for key in keys]
  pyplot.plot(keys, values, label='Processing')

  keys = sorted(queued_duration.keys())
  values = [queued_duration[key] for key in keys]
  pyplot.plot(keys, values, label='Queued')

  pyplot.title('Task status duration')

  pyplot.xlabel('Time')
  pyplot.xscale('linear')

  pyplot.ylabel('Duration')
  pyplot.yscale('linear')

  pyplot.legend()

  if options.output_file:
    pyplot.savefig(options.output_file)
  else:
    pyplot.show()

  return True
385550
def packageGraph(self, packagelevel=None):
        """"""
        packages = {}
        for module in self.listModules():
            package_name = self.packageOf(module.modname, packagelevel)
            if package_name not in packages:
                dirname = os.path.dirname(module.filename)
                packages[package_name] = Module(package_name, dirname)
            package = packages[package_name]
            for name in module.imports:
                package_name = self.packageOf(name, packagelevel)
                if package_name != package.modname: # no loops
                    package.imports.add(package_name)
        graph = ModuleGraph()
        graph.modules = packages
        return graph
840342
def output_component(graph, edge_stack, u, v):
    """"""
    edge_list = []
    while len(edge_stack) > 0:
        edge_id = edge_stack.popleft()
        edge_list.append(edge_id)

        edge = graph.get_edge(edge_id)
        tpl_a = (u, v)
        tpl_b = (v, u)
        if tpl_a == edge['vertices'] or tpl_b == edge['vertices']:
            break

    return edge_list
1232730
def make_graph_pygraphviz(self, recs, nodecolor,
                              edgecolor, dpi,
                              draw_parents=True, draw_children=True):
        """"""
        import pygraphviz as pgv

        grph = pgv.AGraph(name="GO tree")

        edgeset = set()
        for rec in recs:
            if draw_parents:
                edgeset.update(rec.get_all_parent_edges())
            if draw_children:
                edgeset.update(rec.get_all_child_edges())

        edgeset = [(self.label_wrap(a), self.label_wrap(b))
                   for (a, b) in edgeset]

        # add nodes explicitly via add_node
        # adding nodes implicitly via add_edge misses nodes
        # without at least one edge
        for rec in recs:
            grph.add_node(self.label_wrap(rec.item_id))

        for src, target in edgeset:
            # default layout in graphviz is top->bottom, so we invert
            # the direction and plot using dir="back"
            grph.add_edge(target, src)

        grph.graph_attr.update(dpi="%d" % dpi)
        grph.node_attr.update(shape="box", style="rounded,filled",
                              fillcolor="beige", color=nodecolor)
        grph.edge_attr.update(shape="normal", color=edgecolor,
                              dir="back", label="is_a")
        # highlight the query terms
        for rec in recs:
            try:
                node = grph.get_node(self.label_wrap(rec.item_id))
                node.attr.update(fillcolor="plum")
            except:
                continue

        return grph
817576
def main():
    """"""
    query = ' '.join(sys.stdin.readlines())

    sys.stdout.write(pretty_print_graphql(query))
477968
def build_groetzch_graph():
    """"""
    # Because the graph is so complicated, we want to
    # build it via adjacency matrix specification
    
    # -- Initialize the matrix to all zeros
    adj = [[0 for _ in range(11)] for _ in range(11)]

    # -- Add individual edge connections
    row_connections = []

    row_connections.append( (1,2,7,10) )
    row_connections.append( (0,3,6,9) )
    row_connections.append( (0,4,6,8) )
    row_connections.append( (1,4,8,10) )
    row_connections.append( (2,3,7,9) )
    row_connections.append( (6,7,8,9,10) )
    row_connections.append( (1,2,5) )
    row_connections.append( (0,4,5) )
    row_connections.append( (2,3,5) )
    row_connections.append( (1,4,5) )
    row_connections.append( (0,3,5) )

    for j, tpl in enumerate(row_connections):
        for i in tpl:
            adj[j][i] = 1
            adj[i][j] = 1
    
    # Debug print the adjacency matrix
    #for row in adj:
    #    print row

    graph, _ = create_graph_from_adjacency_matrix(adj)

    return graph
522379
def main():
    """"""
    desc = 'Benchmark the files generated by generate.py'
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument(
        '--src',
        dest='src_dir',
        default='generated',
        help='The directory containing the sources to benchmark'
    )
    parser.add_argument(
        '--out',
        dest='out_dir',
        default='../../doc',
        help='The output directory'
    )
    parser.add_argument(
        '--include',
        dest='include',
        default='include',
        help='The directory containing the headeres for the benchmark'
    )
    parser.add_argument(
        '--boost_headers',
        dest='boost_headers',
        default='../../../..',
        help='The directory containing the Boost headers (the boost directory)'
    )
    parser.add_argument(
        '--compiler',
        dest='compiler',
        default='g++',
        help='The compiler to do the benchmark with'
    )
    parser.add_argument(
        '--repeat_count',
        dest='repeat_count',
        type=int,
        default=5,
        help='How many times a measurement should be repeated.'
    )

    args = parser.parse_args()

    compiler = compiler_info(args.compiler)
    results = benchmark(
        args.src_dir,
        args.compiler,
        [args.include, args.boost_headers],
        args.repeat_count
    )

    plot_diagrams(results, configs_in(args.src_dir), compiler, args.out_dir)
1173617
def edges_dump(self):
        """"""
        self._flush_edges()
        for (
                graph, orig, dest, idx, branch, turn, tick, extant
        ) in self.sql('edges_dump'):
            yield (
                self.unpack(graph),
                self.unpack(orig),
                self.unpack(dest),
                idx,
                branch,
                turn,
                tick,
                bool(extant)
            )