You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将NetworkX生成的图对象导出为DIMACS文件格式?

Solution: Custom DIMACS Writer for NetworkX

Great question! Since NetworkX doesn’t include a built-in DIMACS format writer, you can easily build one yourself by following the DIMACS graph specification. Here’s a step-by-step solution tailored to your use case:

First, let’s recap the core rules of the DIMACS undirected graph format:

  • The first line starts with p edge, followed by the total number of nodes and edges (e.g., p edge 5000 12000)
  • Each subsequent line represents an edge, starting with e followed by two node IDs (DIMACS standard uses 1-based node numbering)

Step 1: Implement the Custom Export Function

Here’s a reusable function that converts your NetworkX Graph object to valid DIMACS format:

import networkx as nx

def write_dimacs(graph, output_path):
    # Convert nodes to 1-based numbering (matches DIMACS convention)
    # Skip this line if your original graph already uses 1-based IDs
    standardized_graph = nx.convert_node_labels_to_integers(graph, first_label=1)
    
    node_count = standardized_graph.number_of_nodes()
    edge_count = standardized_graph.number_of_edges()
    
    with open(output_path, 'w') as dimacs_file:
        # Write the problem metadata line
        dimacs_file.write(f"p edge {node_count} {edge_count}\n")
        
        # Write each edge one line at a time
        for u, v in standardized_graph.edges():
            # For undirected graphs, we only write each edge once (no duplicates needed)
            dimacs_file.write(f"e {u} {v}\n")

# Use it with your Amazon graph
g = nx.read_edgelist('com-amazon.ungraph.txt', create_using=nx.Graph(), nodetype=int)
write_dimacs(g, 'com-amazon.dimacs')

Step 2: Key Details to Note

  • Node Numbering: The nx.convert_node_labels_to_integers call ensures your nodes start at 1, which is required for most DIMACS-compliant tools. If your original dataset already uses 1-based IDs, you can remove this line to keep your original node numbers intact.
  • Efficiency: For large graphs like the Amazon dataset, this function writes directly to the file line-by-line, so it won’t overload your memory with all edges stored at once.
  • Undirected Edges: Since you’re using nx.Graph(), we only write each edge once (DIMACS doesn’t require duplicate entries for undirected connections).

Quick Verification

To confirm the output is correct, you can check the first few lines of the generated file with a command like:

head com-amazon.dimacs

You should see output similar to this:

p edge 334863 925872
e 1 2
e 1 3
e 1 4
...

内容的提问来源于stack exchange,提问作者Derrick Peh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:10:26