I'm trying to model a directed graph in z3, but I've gotten stuck. I've added a single axiom to the graph here, being that the existence of an edge implies the existence of the nodes it connects. But just this alone results in unsat
GraphSort = Datatype('GraphSort')
GraphSort.declare('Graph',
('V', ArraySort(IntSort(), BoolSort())),
('E', ArraySort(IntSort(), ArraySort(IntSort(), BoolSort()))),
)
GraphSort = GraphSort.create()
V = GraphSort.V
E = GraphSort.E
G = Const('G', GraphSort)
n, m = Consts('n m', IntSort())
Graph_axioms = [
ForAll([G, n, m], Implies(E(G)[n][m], And(V(G)[n], V(G)[m]))),
]
s = Solver()
s.add(Graph_axioms)
I'm trying to model graphs such that V(G)[n]
implies the existence of node n
and E(G)[n][m]
implies the existance of an edge from n
to m
. Does anyone have any tips as to what's going wrong here? Or better even, any general tips to modelling graphs in z3?
Edit:
With the explanation given by alias, I came up with the following slightly hacky solution:
from itertools import product
from z3 import *
import networkx as nx
GraphSort = Datatype('GraphSort')
GraphSort.declare('Graph',
('V', ArraySort(IntSort(), BoolSort())),
('E', ArraySort(IntSort(), ArraySort(IntSort(), BoolSort()))),
)
GraphSort = GraphSort.create()
V = GraphSort.V
E = GraphSort.E
class Graph(DatatypeRef):
def __new__(cls, name):
# Hijack z3 DatatypeRef instance
inst = Const(name, GraphSort)
inst.__class__ = Graph
return inst
def __init__(G, name):
G.axioms = []
n, m = Ints('n m')
G.add(ForAll(
[n, m],
Implies(E(G)[n][m], And(V(G)[n], V(G)[m]))
))
def add(G, *v):
G.axioms.extend(v)
def add_networkx(G, nx_graph):
g = nx.convert_node_labels_to_integers(nx_graph)
Vs = g.number_of_nodes()
Es = g.number_of_edges()
n = Int('n')
G.add(ForAll(n, V(G)[n] == And(0 <= n, n < Vs)))
G.add(*[E(G)[i][k] for i, k in g.edges()])
G.add(Sum([
If(E(G)[i][k], 1, 0) for i, k in product(range(Vs), range(Vs))
]) == Es)
def assert_into(G, solver):
for ax in G.axioms:
solver.add(ax)
s = Solver()
G = Graph('G')
G.add_networkx(nx.petersen_graph())
G.assert_into(s)