Z3QFree.scala 7.75 KB
Newer Older
Christian Müller's avatar
Christian Müller committed
1
2
3
package de.tum.workflows.toz3

import java.util
Christian Müller's avatar
Christian Müller committed
4
5
6

import de.tum.workflows.foltl.FOLTL
import de.tum.workflows.foltl.FOLTL._
Christian Müller's avatar
Christian Müller committed
7
import com.microsoft.z3._
Christian Müller's avatar
Christian Müller committed
8
import com.microsoft.z3.enumerations.Z3_lbool
Christian Müller's avatar
Christian Müller committed
9
import com.typesafe.scalalogging.LazyLogging
Christian Müller's avatar
Christian Müller committed
10
11
import de.tum.workflows.Utils
import de.tum.workflows.foltl.FOTransformers
Christian Müller's avatar
Christian Müller committed
12
import de.tum.workflows.foltl.FormulaFunctions
Christian Müller's avatar
Christian Müller committed
13
14
15

object Z3QFree extends LazyLogging {

Christian Müller's avatar
Christian Müller committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

  val TIMEOUT = 60000 // in milliseconds

  /**
    * Computes an interpolant using Z3
    *
    * @param f1 QFree Formula
    * @param f2 QFree Formula
    * @return
    */
  def interpolate(f1:Formula, f2:Formula): Option[Formula] = {

    val (time, res) = Utils.time {
      // Set up Z3
      val cfg = new util.HashMap[String, String]()
      cfg.put("timeout", TIMEOUT.toString())
      //      cfg.put("unsat_core", "true")
      val ctx = InterpolationContext.mkContext()

      val params = ctx.mkParams()

      val f1s = FOTransformers.eliminatePredicates(f1)
      val f2s = FOTransformers.eliminatePredicates(f2)

      val f1i = ctx.MkInterpolant(Z3QFree.translate(f1s, ctx))
      val f2i = ctx.MkInterpolant(Z3QFree.translate(f2s, ctx))

      val itp = ctx.ComputeInterpolant(ctx.mkAnd(f1i, f2i), params)

      if (itp.status == Z3_lbool.Z3_L_FALSE) {
        logger.debug("Unsat, interpolating")
        Some(mapback(itp.interp.head))
Christian Müller's avatar
Christian Müller committed
48
49
50
51
52
      } else {
        logger.info("Sat instead")
        logger.info(Z3.printModel(itp.model))
        None
      }
Christian Müller's avatar
Christian Müller committed
53
54
55
56
57
58
59
60
    }
    if (time > 1000) {
      logger.debug(s"Z3 call took $time ms")
    }
    res

  }

Christian Müller's avatar
Christian Müller committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
  def checkSatQFree(f: Formula) = {
    val (time, res) = Utils.time {
      // Set up Z3
      val cfg = new util.HashMap[String, String]()
      cfg.put("timeout", TIMEOUT.toString())
      val ctx = new Context(cfg)

      val s = ctx.mkSolver()

      // Can only check universal things
      if (!f.isQFree) {
        logger.error("Trying to encode formula with quantifiers")
      }

      val satform = FOTransformers.eliminatePredicates(f)

      // Checking QFree
      s.add(Z3QFree.translate(satform, ctx))

      // Send to z3
      val c = s.check()
      if (c == Status.UNKNOWN) {
        logger.info(s"Z3 status unknown: ${s.getReasonUnknown()}")
      }
      if (c == Status.SATISFIABLE) {
        //        logger.info(s"Z3 status satisfiable")
        //      logger.info(s"${s.getModel()}")
        Some(s.getModel)
      } else {
        None
      }
    }
    // Logging only calls that take longer than a second
    if (time > 1000) {
      logger.debug(s"Z3 call took $time ms")
    }
    res
  }
Christian Müller's avatar
Christian Müller committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144

  def checkUniversal(f: Formula) = {

    val (time, res) = Utils.time {
      // Set up Z3
      val cfg = new util.HashMap[String, String]()
      cfg.put("timeout", TIMEOUT.toString())
      val ctx = new Context(cfg)

      val s = ctx.mkSolver()

      // Can only check universal things
      if (f.hasSubFormula {
        case Exists(_,_) => true
      }) {
        logger.error("Trying to encode formula with existential quantifiers")
      }

      val neg = Neg(f).simplify()

      // neg is now in E*, so can be solved as SAT Problem
      val stripped = FormulaFunctions.stripQuantifiers(neg)

      val satform = FOTransformers.eliminatePredicates(stripped)

      // Checking QFree
      s.add(Z3QFree.translate(satform, ctx))

      // Send to z3
      val c = s.check()
      if (c == Status.UNKNOWN) {
        logger.info(s"Z3 status unknown: ${s.getReasonUnknown()}")
      }
      if (c == Status.SATISFIABLE) {
        //        logger.info(s"Z3 status satisfiable")
        //      logger.info(s"${s.getModel()}")
      }
      (c, s)
    }
    // Logging only calls that take longer than a second
    if (time > 1000) {
      logger.debug(s"Z3 call took $time ms")
    }
    res
  }

Christian Müller's avatar
Christian Müller committed
145
  def toZ3(ctx: Context, f: Formula): BoolExpr = {
Christian Müller's avatar
Christian Müller committed
146
    // texpr is an expression e with the form given by the following grammar:
Christian Müller's avatar
Christian Müller committed
147
148
149
150
151
152
153
154
155
    //   e ::= 0 | t | succ(e)
    // tvar is Some(t) if e contains t or None otherwise

    f match {
      case Fun(name, ind, params) => {
        logger.error("Trying to encode function symbols into QFree SAT")
        ctx.mkFalse()
      }

Christian Müller's avatar
Christian Müller committed
156
      case op: TemporalFormula => {
Christian Müller's avatar
Christian Müller committed
157
158
159
160
        logger.error("Trying to encode temporal operators into QFree SAT")
        ctx.mkFalse()
      }

Christian Müller's avatar
Christian Müller committed
161
      case q: FOLTL.Quantifier => {
Christian Müller's avatar
Christian Müller committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
        logger.error("Trying to encode quantifiers into QFree SAT")
        ctx.mkFalse()
      }

      case And(f1, f2) => {
        val e1 = toZ3(ctx, f1)
        val e2 = toZ3(ctx, f2)
        ctx.mkAnd(e1, e2)
      }

      case Eq(f1, f2) => {
        val e1 = toZ3(ctx, f1)
        val e2 = toZ3(ctx, f2)
        ctx.mkEq(e1, e2)
      }

      case Or(f1, f2) => {
        val e1 = toZ3(ctx, f1)
        val e2 = toZ3(ctx, f2)
        ctx.mkOr(e1, e2)
      }

      case Implies(f1, f2) => {
        val e1 = toZ3(ctx, f1)
        val e2 = toZ3(ctx, f2)
        ctx.mkImplies(e1, e2)
      }

      case Neg(f1) => {
        val e = toZ3(ctx, f1)
        ctx.mkNot(e)
      }

      case True => {
        ctx.mkTrue()
      }
      case False => {
        ctx.mkFalse()
      }
Christian Müller's avatar
Christian Müller committed
201
202

      case Var(x, t) => {
Christian Müller's avatar
testing    
Christian Müller committed
203
        // FIXME: Here we're just assuming all Variables are Boolean
Christian Müller's avatar
Christian Müller committed
204
205
206
207
208
        ctx.mkBoolConst(x)
      }
    }
  }

Christian Müller's avatar
Christian Müller committed
209
210
  def simplifyQFree(f: Formula) = {
    val TIMEOUT = 30000 // in milliseconds
Christian Müller's avatar
Christian Müller committed
211
    val cfg = new util.HashMap[String, String]()
Christian Müller's avatar
Christian Müller committed
212
213
214
215
216
217
218
219
220
221
222
223
224
    cfg.put("timeout", TIMEOUT.toString())

    val ctx = new Context(cfg)
    val simp = ctx.mkTactic("ctx-solver-simplify")
    val params = ctx.mkParams()

    val satform = FOTransformers.eliminatePredicates(f)

    val goal = ctx.mkGoal(false, false, false)
    goal.add(Z3QFree.translate(satform, ctx))
    val ar = simp.apply(goal)

    val sub = ar.getSubgoals()
Christian Müller's avatar
Christian Müller committed
225
    val mapped = if (sub.isEmpty) {
Christian Müller's avatar
Christian Müller committed
226
227
228
229
230
231
232
233
234
235
236
237
      True
    } else if (sub.size > 1) {
      logger.error("Simplification Error: Returned several goals")
      False
    } else {
      val form = sub.head.AsBoolExpr()
      mapback(form)
    }
    mapped
  }
  
  def simplifyUniv(form:Formula) = {
Christian Müller's avatar
Christian Müller committed
238
    val f = form.toNegNf
Christian Müller's avatar
Christian Müller committed
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
    val quantifiers = FormulaFunctions.collectQuantifiers(f)
    if (quantifiers.exists(_._1)) {
      logger.error("Existential formula given to simplifyUniv")
      False
    } else {
      val stripped = FormulaFunctions.stripQuantifiers(f)
      val satform = FOTransformers.eliminatePredicates(stripped)
      val simped = simplifyQFree(satform)
      quantifiers.foldRight(simped)((q, inner) => if(q._1) Exists(q._2, inner) else Forall(q._2, inner))
    }
  }

  def mapback(e: Expr): Formula = {
    e match {
      case f2 if f2.isAnd()   => And.make(f2.getArgs.map(mapback).toList)
      case f2 if f2.isOr()    => Or.make(f2.getArgs.map(mapback).toList)
      case f2 if f2.isEq()    => Eq.make(f2.getArgs.map(mapback).toList)
      case f2 if f2.isNot()   => Neg(mapback(f2.getArgs().head))
      case f2 if f2.isTrue()  => True
      case f2 if f2.isFalse() => False
      // TODO: typemap
      case f2 if f2.isConst() => {
        val f = FunFromVar.unapply(f2.getFuncDecl.getName.toString)
        if (f.isDefined) {
          f.get
        } else {
          logger.error(s"Simplification Error: Could not parse constant $f2")
          Var("unknown")
        }
      }
      case x => {
        logger.error(s"Simplification Error: Could not parse $x")
        Var("unknown")
      }
    }
  }

Christian Müller's avatar
Christian Müller committed
276
277
278
279
280
281
282
283
284
285
286
287
  def modelFacts(model: Model): List[(Fun, Formula)] = {
    val sortedConsts = model.getConstDecls().sortBy(_.getName.toString())

    val funs = sortedConsts.map(s => {
      val fun = FunFromVar.unapply(s.getName.toString).get
      val interp = Z3QFree.mapback(model.getConstInterp(s))
      (fun, interp)
    }) toList

    funs
  }

Christian Müller's avatar
Christian Müller committed
288
289
290
291
292
293
294
  def translate(f: Formula, ctx: Context) = {
    //    logger.info(s"Using formula:\n$f")
    val expr = toZ3(ctx, f)
    //    logger.info(s"Built Z3 expression:\n$expr")
    expr
  }
}