Python networkx.readwrite.json_graph.tree_data() Examples

The following are 7 code examples of networkx.readwrite.json_graph.tree_data(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx.readwrite.json_graph , or try the search function .
Example #1
Source File: beam_search.py    From avsr-tf1 with GNU General Public License v3.0 6 votes vote down vote up
def create_html(predicted_ids, parent_ids, scores, labels_ids, vocab, filename, output_dir):
    graph = create_graph(
        predicted_ids=predicted_ids,
        parent_ids=parent_ids,
        scores=scores,
        vocab=vocab)

    json_str = json.dumps(json_graph.tree_data(graph, (0, 0)), ensure_ascii=True)

    transcript = [vocab[sym] for sym in labels_ids]
    transcript.remove('EOS')
    transcript = ''.join(transcript)

    output_fname = path.join(output_dir, filename + '.html')
    num_subdirs = filename.count('/')  # too hacky ?

    makedirs(path.dirname(output_fname), exist_ok=True)

    html_str = HTML_TEMPLATE.substitute(DATA=json_str, WALK='../'*num_subdirs, transcript=transcript)

    with open(output_fname, 'w') as f:
        f.write(html_str) 
Example #2
Source File: topology.py    From vitrage with Apache License 2.0 6 votes vote down vote up
def as_tree(graph, root=OPENSTACK_CLUSTER, reverse=False):
        if nx.__version__ >= '2.0':
            linked_graph = json_graph.node_link_graph(
                graph, attrs={'name': 'graph_index'})
        else:
            linked_graph = json_graph.node_link_graph(graph)
        if 0 == nx.number_of_nodes(linked_graph):
            return {}
        if reverse:
            linked_graph = linked_graph.reverse()
        if nx.__version__ >= '2.0':
            return json_graph.tree_data(
                linked_graph,
                root=root,
                attrs={'id': 'graph_index', 'children': 'children'})
        else:
            return json_graph.tree_data(linked_graph, root=root) 
Example #3
Source File: generate_graphs.py    From sockeye with Apache License 2.0 5 votes vote down vote up
def generate(input_data, output_dir, include_pad=False):

    path_base = os.path.dirname(os.path.realpath(__file__))

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # Copy required files
    shutil.copy2(path_base+"/templates/tree.css", output_dir)
    shutil.copy2(path_base+"/templates/tree.js", output_dir)

    with open(input_data) as beams:
        for i, line in enumerate(beams):
            beam = json.loads(line)

            graph = create_graph(predicted_ids=beam["predicted_tokens"],
                                 parent_ids=beam["parent_ids"],
                                 scores=beam["scores"],
                                 normalized_scores=beam["normalized_scores"],
                                 include_pad=include_pad)

            json_str = json.dumps(
                json_graph.tree_data(graph, (0, 0)),
                ensure_ascii=True)

            html_str = HTML_TEMPLATE.substitute(DATA=json_str, SENT=str(i))
            output_path = os.path.join(output_dir, "{:06d}.html".format(i))
            with open(output_path, "w", encoding="utf-8") as out:
                out.write(html_str)
    print("Output beams written to: {}".format(output_dir)) 
Example #4
Source File: top_k_seq2seq.py    From reaction_prediction_seq2seq with Apache License 2.0 5 votes vote down vote up
def draw_graph(graph):
    from string import Template
    import shutil
    from networkx.readwrite import json_graph
    import json
    
    HTML_TEMPLATE = Template("""
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>Beam Search</title>
        <link rel="stylesheet" type="text/css" href="tree.css">
        <script src="http://d3js.org/d3.v3.min.js"></script>
      </head>
      <body>
        <script>
          var treeData = $DATA
        </script>
        <script src="tree.js"></script>
      </body>
    </html>""")
    
    seq2seq_path = '/scratch/make_build/gram_as_foreight_lang/seq2seq'
    vis_path = base_path+'/vis/graph_beam/'
    os.makedirs(base_path+'/vis/graph_beam/', exist_ok=True)
    shutil.copy2(seq2seq_path+"/bin/tools/beam_search_viz/tree.css", vis_path)
    shutil.copy2(seq2seq_path+"/bin/tools/beam_search_viz/tree.js", vis_path)
    
    json_str = json.dumps(json_graph.tree_data(graph, (0, 0)), ensure_ascii=False)

    html_str = HTML_TEMPLATE.substitute(DATA=json_str)
    output_path = os.path.join(vis_path, "graph.html")
    with open(output_path, "w") as file:
        file.write(html_str)
    print(output_path) 
Example #5
Source File: generate_beam_viz.py    From reaction_prediction_seq2seq with Apache License 2.0 5 votes vote down vote up
def main():
  beam_data = np.load(ARGS.data)

  # Optionally load vocabulary data
  vocab = None
  if ARGS.vocab:
    with open(ARGS.vocab) as file:
      vocab = file.readlines()
    vocab = [_.strip() for _ in vocab]
    vocab += ["UNK", "SEQUENCE_START", "SEQUENCE_END"]

  if not os.path.exists(ARGS.output_dir):
    os.makedirs(ARGS.output_dir)

  # Copy required files
  shutil.copy2("/home/bowen/pycharm_deployment_directory/synthesis/prototype_models/google_seq2seq/bin/tools/beam_search_viz/tree.css", ARGS.output_dir)
  shutil.copy2("/home/bowen/pycharm_deployment_directory/synthesis/prototype_models/google_seq2seq/bin/tools/beam_search_viz/tree.js", ARGS.output_dir)

  for idx in range(len(beam_data["predicted_ids"])):
    predicted_ids = beam_data["predicted_ids"][idx]
    parent_ids = beam_data["beam_parent_ids"][idx]
    scores = beam_data["scores"][idx]

    graph = create_graph(
        predicted_ids=predicted_ids,
        parent_ids=parent_ids,
        scores=scores,
        vocab=vocab)

    json_str = json.dumps(
        json_graph.tree_data(graph, (0, 0)),
        ensure_ascii=False)

    html_str = HTML_TEMPLATE.substitute(DATA=json_str)
    output_path = os.path.join(ARGS.output_dir, "{:06d}.html".format(idx))
    with open(output_path, "w") as file:
      file.write(html_str)
    print(output_path) 
Example #6
Source File: generate_beam_viz.py    From conv_seq2seq with Apache License 2.0 5 votes vote down vote up
def main():
  beam_data = np.load(ARGS.data)

  # Optionally load vocabulary data
  vocab = None
  if ARGS.vocab:
    with open(ARGS.vocab) as file:
      vocab = file.readlines()
    vocab = [_.strip() for _ in vocab]
    vocab += ["UNK", "SEQUENCE_START", "SEQUENCE_END"]

  if not os.path.exists(ARGS.output_dir):
    os.makedirs(ARGS.output_dir)

  # Copy required files
  shutil.copy2("./bin/tools/beam_search_viz/tree.css", ARGS.output_dir)
  shutil.copy2("./bin/tools/beam_search_viz/tree.js", ARGS.output_dir)

  for idx in range(len(beam_data["predicted_ids"])):
    predicted_ids = beam_data["predicted_ids"][idx]
    parent_ids = beam_data["beam_parent_ids"][idx]
    scores = beam_data["scores"][idx]

    graph = create_graph(
        predicted_ids=predicted_ids,
        parent_ids=parent_ids,
        scores=scores,
        vocab=vocab)

    json_str = json.dumps(
        json_graph.tree_data(graph, (0, 0)),
        ensure_ascii=False)

    html_str = HTML_TEMPLATE.substitute(DATA=json_str)
    output_path = os.path.join(ARGS.output_dir, "{:06d}.html".format(idx))
    with open(output_path, "w") as file:
      file.write(html_str)
    print(output_path) 
Example #7
Source File: generate_beam_viz.py    From seq2seq with Apache License 2.0 5 votes vote down vote up
def main():
  beam_data = np.load(ARGS.data)

  # Optionally load vocabulary data
  vocab = None
  if ARGS.vocab:
    with open(ARGS.vocab) as file:
      vocab = file.readlines()
    vocab = [_.strip() for _ in vocab]
    vocab += ["UNK", "SEQUENCE_START", "SEQUENCE_END"]

  if not os.path.exists(ARGS.output_dir):
    os.makedirs(ARGS.output_dir)

  # Copy required files
  shutil.copy2("./bin/tools/beam_search_viz/tree.css", ARGS.output_dir)
  shutil.copy2("./bin/tools/beam_search_viz/tree.js", ARGS.output_dir)

  for idx in range(len(beam_data["predicted_ids"])):
    predicted_ids = beam_data["predicted_ids"][idx]
    parent_ids = beam_data["beam_parent_ids"][idx]
    scores = beam_data["scores"][idx]

    graph = create_graph(
        predicted_ids=predicted_ids,
        parent_ids=parent_ids,
        scores=scores,
        vocab=vocab)

    json_str = json.dumps(
        json_graph.tree_data(graph, (0, 0)),
        ensure_ascii=False)

    html_str = HTML_TEMPLATE.substitute(DATA=json_str)
    output_path = os.path.join(ARGS.output_dir, "{:06d}.html".format(idx))
    with open(output_path, "w") as file:
      file.write(html_str)
    print(output_path)