Of course. This is an excellent way to demonstrate the full read/write cycle and integrate with a powerful constraint-solving library.
First, I'll create the Python writer module. It will be the counterpart to the C++ writer and the Python reader.
bindb_writer.py
python
import struct
import numpy as np
from scipy.sparse import csr_matrix
from enum import IntEnum
# Re-define TypeTag here to avoid circular dependency
class TypeTag(IntEnum):
NULL_TYPE = 0
UINT8 = 1
UINT32 = 2
UINT64 = 3
ARRAY = 4
SPARSE_MATRIX = 5
BITVECTOR = 6
class BinaryWriter:
"""
Writes data in the custom binary format, compatible with the C++ implementation.
"""
def __init__(self, filename: str):
self.file = open(filename, 'wb')
self.position = 0
def write_tag(self, tag: TypeTag):
data = struct.pack('B', tag.value)
self.file.write(data)
self.position += 1
def write_uint8(self, value: int):
data = struct.pack('B', value)
self.file.write(data)
self.position += 1
def write_uint32(self, value: int):
data = struct.pack('<I', value) # Use little-endian
self.file.write(data)
self.position += 4
def write_uint64(self, value: int):
data = struct.pack('<Q', value) # Use little-endian
self.file.write(data)
self.position += 8
def write_bytes(self, data: bytes):
self.file.write(data)
self.position += len(data)
def write_array(self, arr: np.ndarray):
if not isinstance(arr, np.ndarray):
raise TypeError("Input must be a NumPy array.")
self.write_tag(TypeTag.ARRAY)
self.write_uint64(arr.size)
self.write_uint8(arr.dtype.itemsize)
self.write_bytes(arr.tobytes())
def write_sparse_matrix(self, matrix: csr_matrix):
if not isinstance(matrix, csr_matrix):
raise TypeError("Input must be a SciPy CSR matrix.")
self.write_tag(TypeTag.SPARSE_MATRIX)
self.write_uint32(matrix.shape[0]) # rows
self.write_uint32(matrix.shape[1]) # cols
self.write_uint64(matrix.nnz) # non-zero elements
# 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):
if not (isinstance(bits, np.ndarray) and bits.dtype == bool):
raise TypeError("Input must be a NumPy boolean array.")
self.write_tag(TypeTag.BITVECTOR)
self.write_uint64(bits.size)
# Pack bits into bytes, ensuring little-endian bit order within bytes
packed = np.packbits(bits, bitorder='little')
self.write_bytes(packed.tobytes())
def close(self):
self.file.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
Next, let's create the main script that uses MiniZinc. The problem we'll solve is finding the transitive closure of a small subgraph. This is a great fit because the input is a graph and the output is also a graph (the original graph plus new edges).
Install MiniZinc: You must have the MiniZinc IDE/toolchain installed on your system and available in your PATH. You can download it from the official MiniZinc website.
Install Python Dependencies:
bash
pip install -r requirements.txt
Generate the Initial Graph: Run the C++ program first if you haven't already.
bash
make
./test_bindb
This creates the graph.bindb file.
Run the Python Solver:
bash
python solve_and_write.py
Expected Output
code
Reading graph from 'graph.bindb'...
Original graph: 1000 nodes, 49451 edges.
Extracting a 15x15 subgraph for MiniZinc.
Subgraph has 10 edges.
Configuring and running MiniZinc solver...
MiniZinc found a solution! Transitive closure has 15 edges.
(5 new edges were added to satisfy transitivity)
Writing new graph with transitive closure to 'graph_closure.bindb'...
Write complete.
Verifying by reading 'graph_closure.bindb' back...
✓ Verification PASSED: Written file matches in-memory data.
This complete example demonstrates a powerful workflow:
High-performance I/O in C++ for data generation.
Interoperable binary format that can be read by different languages.
High-level modeling in Python with MiniZinc for complex problem-solving.
Writing back results into the same efficient binary format.
import asyncio
import minizinc
import numpy as np
from scipy.sparse import csr_matrix
from bindb_reader import load_graph_from_bindb, EdgeType
from bindb_writer import BinaryWriter
# Define the MiniZinc model for Transitive Closure
# We want the smallest set of edges 'tc' that includes the original
# adjacency matrix 'adj' and is transitively closed.
mzn_model = """
int: N;
set of int: NODES = 1..N;
array[NODES, NODES] of bool: adj;
array[NODES, NODES] of var bool: tc;
% 1. If an edge exists in the original graph, it must exist in the closure.
constraint forall(i, j in NODES where adj[i, j]) (
tc[i, j]
);
% 2. The transitive property: if i->k and k->j, then i->j
constraint forall(i, j, k in NODES) (
(tc[i, k] /\ tc[k, j]) -> tc[i, j]
);
% We want the minimal transitive closure (don't add unnecessary edges)
solve minimize sum(i, j in NODES) (bool2int(tc[i, j]));
"""
async def main():
"""
Main workflow:
1. Read the graph generated by the C++ code.
2. Extract a small subgraph to solve with MiniZinc.
3. Use MiniZinc to compute the transitive closure of the subgraph.
4. Create a new graph from the result.
5. Write the new graph to a new binary file using the Python writer.
6. Verify by reading the new file back.
"""
input_file = 'graph.bindb'
output_file = 'graph_closure.bindb'
subgraph_size = 15 # MiniZinc can be slow for large N^3 problems
# --- Step 1: Read the input graph ---
print(f"Reading graph from '{input_file}'...")
try:
original_matrix, metadata = load_graph_from_bindb(input_file)
except FileNotFoundError:
print(f"Error: Input file '{input_file}' not found.")
print("Please run the C++ program './test_bindb' first to generate it.")
return
print(f"Original graph: {metadata['rows']} nodes, {metadata['nnz']} edges.")
# --- Step 2: Extract a subgraph ---
print(f"Extracting a {subgraph_size}x{subgraph_size} subgraph for MiniZinc.")
sub_matrix = original_matrix[:subgraph_size, :subgraph_size]
# For MiniZinc, we only need a boolean adjacency matrix (is there an edge or not?)
adj_bool = sub_matrix.toarray() > 0
original_edge_count = np.sum(adj_bool)
print(f"Subgraph has {original_edge_count} edges.")
# --- Step 3: Solve with MiniZinc ---
print("\nConfiguring and running MiniZinc solver...")
# Configure the solver (Gecode is commonly available)
gecode = minizinc.Solver.lookup("gecode")
instance = minizinc.Instance(gecode, minizinc.Model(mzn_model))
# Assign our Python data to the model's parameters
instance["N"] = subgraph_size
instance["adj"] = adj_bool
# Solve the model asynchronously
result = await instance.solve()
if not result.status.has_solution():
print("MiniZinc could not find a solution.")
return
# Extract the transitive closure matrix from the solution
tc_result = np.array(result["tc"])
closure_edge_count = np.sum(tc_result)
new_edges_added = closure_edge_count - original_edge_count
print(f"MiniZinc found a solution! Transitive closure has {closure_edge_count} edges.")
print(f" ({new_edges_added} new edges were added to satisfy transitivity)")
# --- Step 4: Create a new graph from the result ---
# Start with the original subgraph's dense matrix (with edge types)
new_adj_dense = sub_matrix.toarray().copy()
# Add the new edges found by MiniZinc.
# We'll give them the 'WEAK' type to distinguish them.
for i in range(subgraph_size):
for j in range(subgraph_size):
# If the closure has an edge that the original didn't...
if tc_result[i, j] and new_adj_dense[i, j] == 0:
# ...add it as a 'WEAK' edge.
new_adj_dense[i, j] = EdgeType.WEAK.value
# Convert the final dense matrix back to a sparse CSR format
new_csr_matrix = csr_matrix(new_adj_dense, dtype=np.uint8)
# --- Step 5: Write the new graph to a file ---
print(f"\nWriting new graph with transitive closure to '{output_file}'...")
with BinaryWriter(output_file) as writer:
writer.write_sparse_matrix(new_csr_matrix)
print("Write complete.")
# --- Step 6: Verification ---
print(f"Verifying by reading '{output_file}' back...")
read_back_matrix, _ = load_graph_from_bindb(output_file)
if np.array_equal(new_csr_matrix.toarray(), read_back_matrix.toarray()):
print("✓ Verification PASSED: Written file matches in-memory data.")
else:
print("✗ Verification FAILED: Data mismatch after write/read cycle.")
if __name__ == "__main__":
# The python-minizinc library uses asyncio, so we run our main function this way
asyncio.run(main())