I'll implement a Python writer for our binary format and create a MiniZinc integration that solves a maximum independent set problem on our graph.
bindb_writer.py
import struct
import numpy as np
from scipy.sparse import csr_matrix
from enum import IntEnum
from typing import Tuple, List, Union, BinaryIO
from bindb_reader import TypeTag, EdgeType
class BinaryWriter:
def __init__(self, filename: str):
self.file = open(filename, 'wb')
self.position = 0
def write_tag(self, tag: TypeTag) -> None:
self.file.write(struct.pack('B', tag))
self.position += 1
def write_uint8(self, value: int) -> None:
self.file.write(struct.pack('B', value))
self.position += 1
def write_uint32(self, value: int) -> None:
self.file.write(struct.pack('<I', value)) # Little-endian
self.position += 4
def write_uint64(self, value: int) -> None:
self.file.write(struct.pack('<Q', value)) # Little-endian
self.position += 8
def write_bytes(self, data: bytes) -> None:
self.file.write(data)
self.position += len(data)
def write_array(self, arr: np.ndarray) -> None:
self.write_tag(TypeTag.ARRAY)
self.write_uint64(len(arr))
# Determine element size
if arr.dtype == np.uint8:
elem_size = 1
elif arr.dtype == np.uint32:
elem_size = 4
elif arr.dtype == np.uint64:
elem_size = 8
else:
# Convert to closest supported type
if arr.dtype.itemsize <= 1:
arr = arr.astype(np.uint8)
elem_size = 1
elif arr.dtype.itemsize <= 4:
arr = arr.astype(np.uint32)
elem_size = 4
else:
arr = arr.astype(np.uint64)
elem_size = 8
self.write_uint8(elem_size)
self.write_bytes(arr.tobytes())
def write_sparse_matrix(self, matrix: csr_matrix) -> None:
self.write_tag(TypeTag.SPARSE_MATRIX)
rows, cols = matrix.shape
self.write_uint32(rows)
self.write_uint32(cols)
self.write_uint64(matrix.nnz)
# Ensure CSR format
matrix = matrix.tocsr()
# Write CSR components
self.write_array(matrix.indptr.astype(np.uint32))
self.write_array(matrix.indices.astype(np.uint32))
self.write_array(matrix.data.astype(np.uint8))
def write_bitvector(self, bits: np.ndarray) -> None:
self.write_tag(TypeTag.BITVECTOR)
# Convert to boolean if needed
if bits.dtype != bool:
bits = bits.astype(bool)
bit_count = len(bits)
self.write_uint64(bit_count)
# Pack bits into bytes
byte_count = (bit_count + 7) // 8
packed = np.zeros(byte_count, dtype=np.uint8)
for i in range(bit_count):
if bits[i]:
byte_idx = i // 8
bit_idx = i % 8
packed[byte_idx] |= (1 << bit_idx)
self.write_bytes(packed.tobytes())
def close(self) -> None:
self.file.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def save_graph_to_bindb(filename: str, matrix: csr_matrix) -> None:
"""Save a graph to our binary format"""
with BinaryWriter(filename) as writer:
writer.write_sparse_matrix(matrix)
def save_dense_to_bindb(filename: str, matrix: np.ndarray) -> None:
"""Save a dense matrix to our binary format"""
with BinaryWriter(filename) as writer:
writer.write_array(matrix.flatten())
graph_maxindset.py
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
from scipy.sparse import csr_matrix
import seaborn as sns
import time
import os
from minizinc import Instance, Model, Solver
from bindb_reader import load_graph_from_bindb, EdgeType
from bindb_writer import save_graph_to_bindb
def visualize_solution(original: csr_matrix, solution: np.ndarray, max_nodes: int = 50):
"""Visualize the maximum independent set solution"""
# Create a subgraph with first max_nodes nodes
n = min(original.shape[0], max_nodes)
submatrix = original[:n, :n]
solution_subset = solution[:n]
# Create NetworkX directed graph
G = nx.DiGraph()
# Add all nodes first
for i in range(n):
G.add_node(i,
in_solution=bool(solution_subset[i]),
color='red' if solution_subset[i] else 'lightblue')
# Add edges with attributes
rows, cols = submatrix.nonzero()
for i, (row, col) in enumerate(zip(rows, cols)):
edge_type = EdgeType(submatrix[row, col])
G.add_edge(row, col,
weight=edge_type.value,
color=edge_type.color,
width=edge_type.width,
type=edge_type.name)
# Create layout
pos = nx.spring_layout(G, k=2, iterations=50)
# Draw the graph
plt.figure(figsize=(12, 10))
# Draw nodes with different colors for solution
node_colors = [G.nodes[node]['color'] for node in G.nodes()]
node_sizes = [800 if G.nodes[node]['in_solution'] else 500 for node in G.nodes()]
nx.draw_networkx_nodes(G, pos,
node_color=node_colors,
node_size=node_sizes,
alpha=0.7)
# Draw edges
edges = G.edges(data=True)
for edge in edges:
nx.draw_networkx_edges(G, pos,
edgelist=[(edge[0], edge[1])],
edge_color=edge[2]['color'],
width=edge[2]['width'],
alpha=0.8,
arrows=True,
arrowsize=15,
arrowstyle='->')
# Draw labels
nx.draw_networkx_labels(G, pos, font_size=10)
plt.title(f"Maximum Independent Set Solution (first {n} nodes)")
plt.axis('off')
plt.tight_layout()
# Add legend
from matplotlib.lines import Line2D
from matplotlib.patches import Patch
legend_elements = [
Patch(facecolor='red', edgecolor='black', label='In Independent Set'),
Patch(facecolor='lightblue', edgecolor='black', label='Not Selected')
]
plt.legend(handles=legend_elements, loc='upper right')
plt.savefig('max_independent_set.png', dpi=150, bbox_inches='tight')
plt.show()
def create_minizinc_model(matrix: csr_matrix) -> str:
"""Create a MiniZinc model for the maximum independent set problem"""
n = matrix.shape[0]
# Convert to dense matrix for adjacency
adj_matrix = matrix.toarray()
# Create MiniZinc model
model = """
% Maximum Independent Set problem
int: n;
array[1..n, 1..n] of int: graph; % Adjacency matrix
% Decision variables: 1 if node is in the independent set, 0 otherwise
array[1..n] of var 0..1: selected;
% Constraint: no two adjacent nodes can be in the set
constraint forall(i,j in 1..n where i < j /\ graph[i,j] > 0) (
selected[i] + selected[j] <= 1
);
% Constraint: no two adjacent nodes can be in the set (reverse direction)
constraint forall(i,j in 1..n where i < j /\ graph[j,i] > 0) (
selected[i] + selected[j] <= 1
);
% Objective: maximize number of nodes in the set
solve maximize sum(selected);
output ["Selected nodes = ", show(selected)];
"""
# Create the model.mzn file
with open("model.mzn", "w") as f:
f.write(model)
# Create the data.dzn file
with open("data.dzn", "w") as f:
f.write(f"n = {n};\n")
f.write("graph = [| ")
# Write adjacency matrix (only need upper triangle due to constraint structure)
for i in range(n):
if i > 0:
f.write("\n | ")
for j in range(n):
f.write(f"{int(adj_matrix[i,j])}")
if j < n-1:
f.write(", ")
if i < n-1:
f.write(" ")
f.write(" |];\n")
return "model.mzn"
def solve_max_independent_set(matrix: csr_matrix) -> np.ndarray:
"""Solve the maximum independent set problem using MiniZinc"""
n = matrix.shape[0]
print(f"Creating MiniZinc model for {n} nodes...")
# Use a subset for larger graphs to make it tractable
max_nodes_for_minizinc = 200
if n > max_nodes_for_minizinc:
print(f"Graph too large, using first {max_nodes_for_minizinc} nodes for MiniZinc...")
matrix = matrix[:max_nodes_for_minizinc, :max_nodes_for_minizinc]
n = max_nodes_for_minizinc
# Create MiniZinc model
model_file = create_minizinc_model(matrix)
print("Solving maximum independent set problem...")
start_time = time.time()
# Load the model and data
model = Model(model_file)
gecode = Solver.lookup("gecode")
instance = Instance(gecode, model)
# Solve with timeout
result = instance.solve(timeout=datetime.timedelta(minutes=2))
end_time = time.time()
print(f"Solved in {end_time - start_time:.2f} seconds")
# Extract solution
if result.status.has_solution():
solution = np.zeros(n, dtype=np.uint8)
selected = result["selected"]
for i in range(n):
solution[i] = selected[i+1] # MiniZinc uses 1-based indexing
# Count selected nodes
selected_count = np.sum(solution)
print(f"Found maximum independent set with {selected_count} nodes")
# If we used a subset, expand to full size
if n < matrix.shape[0]:
full_solution = np.zeros(matrix.shape[0], dtype=np.uint8)
full_solution[:n] = solution
solution = full_solution
return solution
else:
print("No solution found")
return np.zeros(matrix.shape[0], dtype=np.uint8)
def mark_independent_set(original_matrix: csr_matrix, solution: np.ndarray) -> csr_matrix:
"""Create a new graph marking the independent set"""
# We'll use edge type 4 (CRITICAL) to mark edges between independent set nodes
n = original_matrix.shape[0]
matrix = original_matrix.copy()
# For visualization purposes, add self-loops with value 4 to nodes in the solution
for i in range(n):
if solution[i]:
matrix[i, i] = EdgeType.CRITICAL.value
return matrix
def main():
import datetime # For MiniZinc timeout
# Read the graph
print("Reading graph from binary file...")
matrix, metadata = load_graph_from_bindb('graph.bindb')
# Solve maximum independent set problem
solution = solve_max_independent_set(matrix)
# Create new graph with marked independent set
print("Creating new graph with marked independent set...")
marked_graph = mark_independent_set(matrix, solution)
# Save the new graph
output_file = 'graph_solution.bindb'
print(f"Saving solution to {output_file}...")
save_graph_to_bindb(output_file, marked_graph)
# Visualize
print("Generating visualization...")
visualize_solution(matrix, solution, max_nodes=30)
# Report file sizes
orig_size = os.path.getsize('graph.bindb')
new_size = os.path.getsize(output_file)
print("\n=== Summary ===")
print(f"Original graph: {orig_size} bytes")
print(f"Solution graph: {new_size} bytes")
print(f"Nodes in independent set: {np.sum(solution)}")
if __name__ == "__main__":
main()
graph_subgraph.py
import numpy as np
from scipy.sparse import csr_matrix
import networkx as nx
import matplotlib.pyplot as plt
from bindb_reader import load_graph_from_bindb, EdgeType
from bindb_writer import save_graph_to_bindb
def extract_subgraph(matrix: csr_matrix, nodes: list) -> csr_matrix:
"""Extract a subgraph containing only the specified nodes"""
# Get the submatrix
submatrix = matrix[nodes, :][:, nodes]
return submatrix
def main():
# Read the original graph
print("Reading original graph...")
matrix, metadata = load_graph_from_bindb('graph.bindb')
# Get central nodes (highest degree nodes)
print("Finding central nodes...")
n = matrix.shape[0]
out_degrees = np.array(matrix.sum(axis=1)).flatten()
in_degrees = np.array(matrix.sum(axis=0)).flatten()
total_degrees = out_degrees + in_degrees
# Take top 100 nodes by degree
top_nodes = np.argsort(total_degrees)[-100:]
# Extract subgraph
print("Extracting subgraph...")
subgraph = extract_subgraph(matrix, top_nodes)
# Save the subgraph
print("Saving subgraph...")
save_graph_to_bindb('graph_central.bindb', subgraph)
# Visualize
print("Visualizing subgraph...")
G = nx.from_scipy_sparse_array(subgraph, create_using=nx.DiGraph)
# Add edge attributes
for u, v, d in G.edges(data=True):
edge_type = EdgeType(int(subgraph[u, v]))
d['color'] = edge_type.color
d['width'] = edge_type.width
# Create layout
pos = nx.spring_layout(G, k=1.5, iterations=50, seed=42)
# Draw
plt.figure(figsize=(12, 10))
# Draw nodes
nx.draw_networkx_nodes(G, pos, node_color='lightblue',
node_size=300, alpha=0.7)
# Draw edges
edges = G.edges(data=True)
for u, v, d in edges:
nx.draw_networkx_edges(G, pos,
edgelist=[(u, v)],
edge_color=d['color'],
width=d['width'],
alpha=0.7,
arrows=True,
arrowsize=10,
arrowstyle='->')
plt.title("Central Subgraph (Top 100 nodes by degree)")
plt.axis('off')
plt.tight_layout()
plt.savefig('central_subgraph.png', dpi=150, bbox_inches='tight')
print(f"Original graph: {n} nodes, {matrix.nnz} edges")
print(f"Subgraph: 100 nodes, {subgraph.nnz} edges")
print(f"Subgraph saved to graph_central.bindb")
print(f"Visualization saved to central_subgraph.png")
if __name__ == "__main__":
main()
To run the Maximum Independent Set solver:
pip install minizinc networkx matplotlib scipy numpy
Make sure you have the MiniZinc solver installed on your system. You can download it from https://www.minizinc.org/software.html.
Then run:
python graph_maxindset.py
This will:
- Read the graph from our binary format
- Create a MiniZinc model for the maximum independent set problem
- Solve it using the Gecode solver
- Mark nodes in the solution by adding self-loops with the CRITICAL edge type
- Save the result to a new binary file called
graph_solution.bindb
- Visualize the solution
I've also included a simpler example in graph_subgraph.py that extracts a subgraph of the most central nodes and saves it to a new binary file.
The BinaryWriter class complements our BinaryReader, implementing:
- Writing primitive types (uint8, uint32, uint64)
- Writing arrays of numeric data
- Writing sparse matrices in CSR format
- Writing bit vectors
This gives you full read/write capabilities for the binary format from both C++ and Python, with a practical example of using a constraint solver (MiniZinc) to solve graph problems and save the results.