1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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 48 49 50 51 52 53 54 55 56 57 58 59 60 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 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 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 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 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2020 Authors of CryptoMiniSat, see AUTHORS file
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2
# of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
from __future__ import with_statement # Required in 2.5
from __future__ import print_function
import optparse
import gzip
import re
import fnmatch
from xor_to_cnf_class import *
from debuglib import *
import subprocess
import os
import stat
import time
import resource
from functools import partial
def unique_file(fname_begin, fname_end=".cnf"):
counter = 1
while 1:
fname = "out/" + fname_begin + '_' + str(counter) + fname_end
try:
fd = os.open(
fname, os.O_CREAT | os.O_EXCL, stat.S_IREAD | stat.S_IWRITE)
os.fdopen(fd).close()
return fname
except OSError:
pass
counter += 1
if counter > 300:
print("Cannot create unique_file, last try was: %s" % fname)
exit(-1)
def setlimits(maxtime):
# sys.stdout.write("Setting resource limit in child (pid %d): %d s\n" %
# (os.getpid(), maxtime))
resource.setrlimit(resource.RLIMIT_CPU, (maxtime, maxtime))
class solution_parser:
def __init__(self, options):
self.options = options
@staticmethod
def test_found_solution(solution, fname, debugLibPart=None):
if debugLibPart is None:
print("Verifying solution for CNF file %s" % fname)
else:
print("Verifying solution for CNF file %s, part %d" %
(fname, debugLibPart))
if fnmatch.fnmatch(fname, '*.gz'):
f = gzip.open(fname, "r")
else:
f = open(fname, "r")
clauses = 0
thisDebugLibPart = 0
for line in f:
line = line.rstrip()
# skip empty lines
if len(line) == 0:
continue
# count debug lib parts
if line[0] == 'c' and "Solver::solve" in line:
thisDebugLibPart += 1
# if we are over debugLibPart, exit
if debugLibPart is not None and thisDebugLibPart >= debugLibPart:
f.close()
return
# check solution against clause
try:
if line[0] != 'c' and line[0] != 'p':
if line[0] != 'x':
solution_parser._check_regular_clause(line, solution)
else:
assert line[0] == 'x', "Line must start with p, c, v or x"
solution_parser._check_xor_clause(line, solution)
clauses += 1
except:
if debugLibPart is not None:
print("--> Error in part: %s. We are reading up to and including part: %s"
% (thisDebugLibPart, debugLibPart-1))
raise
f.close()
print("Verified %d original xor®ular clauses" % clauses)
def sampling_vars_solution_check(self, fname, sampling_vars, solution):
assert len(sampling_vars) > 0
a = XorToCNF()
tmpfname = unique_file("tmp_for_xor_to_cnf_convert")
a.convert(fname, tmpfname, len(sampling_vars))
with open(tmpfname, "a") as f:
# NOTE: the "p cnf..." header will be wrong
for i in sampling_vars:
if i not in solution:
print("ERROR: solution does not contain sampling var %d" % i)
print("Sampling vars were: %s" % sampling_vars)
exit(-1)
if solution[i]:
f.write("%d 0\n" % i)
else:
f.write("-%d 0\n" % i)
print("-> added partial solution to temporary CNF file %s" % tmpfname)
# execute with the other solver
toexec = "../../build/utils/lingeling-ala/lingeling %s" % tmpfname
print("sampling check -- solving with other solver: %s" % toexec)
curr_time = time.time()
try:
p = subprocess.Popen(toexec.rsplit(),
stdout=subprocess.PIPE,
preexec_fn=partial(setlimits, self.options.maxtime),
universal_newlines=True)
except OSError:
print("ERROR: Lingeing didn't run... did you install it? It should be in the path as `lingeling`")
raise
consoleOutput2 = p.communicate()[0]
os.unlink(tmpfname)
# if other solver was out of time, then we can't say anything
diff_time = time.time() - curr_time
if diff_time > self.options.maxtime - self.options.maxtimediff:
print("Other solver: too much time to solve, aborted!")
return None
# extract output from the other solver
print("Checking other solver output...")
otherSolverUNSAT, _, _ = self.parse_solution_from_output(
consoleOutput2.split("\n"))
# check if the other solver finds a solution with the sampling vars
# set as per partial solution returned
if otherSolverUNSAT is True:
print("ERROR; The other solver did NOT find a solution with the partial solution given")
exit(-1)
return False
print("OK, other solver found a solution using the partial solution")
return True
def check_unsat(self, fname):
a = XorToCNF()
tmpfname = unique_file("tmp_for_xor_to_cnf_convert")
a.convert(fname, tmpfname)
# execute with the other solver
toexec = "../../build/utils/lingeling-ala/lingeling %s" % tmpfname
print("UNSAT check -- solving with other solver: %s" % toexec)
curr_time = time.time()
try:
p = subprocess.Popen(toexec.rsplit(),
stdout=subprocess.PIPE,
preexec_fn=partial(setlimits, self.options.maxtime),
universal_newlines=True)
except OSError:
print("ERROR: Lingeling didn't run... did you install it? It should be in the path as `lingeling`")
raise
consoleOutput2 = p.communicate()[0]
os.unlink(tmpfname)
# if other solver was out of time, then we can't say anything
diff_time = time.time() - curr_time
if diff_time > self.options.maxtime - self.options.maxtimediff:
print("Other solver: too much time to solve, aborted!")
return None
# extract output from the other solver
print("Checking other solver output...")
otherSolverUNSAT, otherSolverSolution, _ = self.parse_solution_from_output(
consoleOutput2.split("\n"))
# check if the other solver agrees with us
return otherSolverUNSAT
def check_debug_lib(self, fname, must_check_unsat=True):
largestPart = self._find_largest_debuglib_part(fname)
for debugLibPart in range(1, largestPart + 1):
fname_debug = "%s-debugLibPart%d.output" % (fname, debugLibPart)
print("Checking debug lib part %s -- %s " % (debugLibPart, fname_debug))
if (os.path.isfile(fname_debug) is False):
print("Error: Filename to be read '%s' is not a file!" % fname_debug)
exit(-1)
# take file into mem
f = open(fname_debug, "r")
text = f.read()
output_lines = text.splitlines()
f.close()
unsat, solution, conflict = self.parse_solution_from_output(output_lines)
assumps = self._get_assumps(fname, debugLibPart)
if unsat is False:
print("debugLib is SAT")
self._check_assumps_inside_solution(assumps, solution)
self.test_found_solution(solution, fname, debugLibPart)
else:
print("debugLib is UNSAT")
if must_check_unsat:
assert conflict is not None, "debugLibPart must create a conflict in case of UNSAT"
self._check_assumps_inside_conflict(assumps, conflict)
tmpfname = unique_file("tmp_for_extract_libpart")
self._extract_lib_part(fname, debugLibPart, assumps, tmpfname)
# check with other solver
ret = self.check_unsat(tmpfname)
if ret is None:
print("Cannot check, other solver took too much time")
elif ret is True:
print("UNSAT verified by other solver")
else:
print("Grave bug: SAT-> UNSAT : Other solver found solution!!")
exit(-1)
os.unlink(tmpfname)
self.remove_debuglib_files(fname)
def remove_debuglib_files(self, fname):
#removing debuglib files
largestPart = self._find_largest_debuglib_part(fname)
for debugLibPart in range(1, largestPart + 1):
fname_debug = "%s-debugLibPart%d.output" % (fname, debugLibPart)
os.unlink(fname_debug)
@staticmethod
def parse_solution_from_output(output_lines, ignoreNoSolution=False):
if len(output_lines) == 0:
print("Error! SAT solver output is empty!")
print("output lines: %s" % output_lines)
exit(-1)
# solution will be put here
satunsatfound = False
vlinefound = False
solution = {}
conflict = None
# parse in solution
for line in output_lines:
# skip comment
if re.match('^conflict ', line):
line = line.strip().split()[1:]
conflict = [int(elem) for elem in line]
continue
if (re.match('^c ', line)):
continue
# solution
if (re.match('^s ', line)):
if (satunsatfound):
print("ERROR: solution twice in solver output!")
exit(400)
if 'UNSAT' in line:
unsat = True
satunsatfound = True
continue
if 'SAT' in line:
unsat = False
satunsatfound = True
continue
print("ERROR: line starts with 's' but no SAT/UNSAT on line")
exit(400)
# parse in solution
if (re.match('^v ', line)):
vlinefound = True
myvars = line.split(' ')
for var in myvars:
var = var.strip()
if var == "" or var == 'v':
continue
if (int(var) == 0):
break
intvar = int(var)
solution[abs(intvar)] = (intvar >= 0)
continue
if (line.strip() == ""):
continue
print("Error! SAT solver output contains a line that is neither 'v' nor 'c' nor 's'!")
print("Line is:", line.strip())
exit(-1)
# print("Parsed values:", solution)
if (ignoreNoSolution is False and
(satunsatfound is False or (
unsat is False and vlinefound is False))):
print("Error: Cannot find line starting with 's' or 'v' in output!")
print(output_lines)
print("Error code 500")
exit(-1)
if (ignoreNoSolution is True and
(satunsatfound is False or (
unsat is False and vlinefound is False))):
print("Probably timeout, since no solution printed. Could, of course, be segfault/assert fault, etc.")
print("Making it look like an UNSAT, so no checks!")
return (True, [])
if (satunsatfound is False):
print("Error: Cannot find if SAT or UNSAT. Maybe didn't finish running?")
print(output_lines)
print("Error code 500")
exit(-1)
if (unsat is False and vlinefound is False):
print("Error: Solution is SAT, but no 'v' line")
print (output_lines)
print("Error code 500")
exit(-1)
return unsat, solution, conflict
def _extract_lib_part(self, fname, debug_num, assumps, tofile):
fromf = open(fname, "r")
thisDebugLibPart = 0
maxvar = 0
numcls = 0
for line in fromf:
line = line.strip()
# ignore empty strings and headers
if not line or line[0] == "p":
continue
# process (potentially special) comments
if line[0] == "c":
if "Solver::solve" in line:
thisDebugLibPart += 1
continue
# break out if we reached the debug lib part
if thisDebugLibPart >= debug_num:
break
# count clauses and get max var number
numcls += 1
maxvar = max(maxvar, get_max_var_from_clause(line))
fromf.close()
# now we can create the new CNF file
fromf = open(fname, "r")
tof = open(tofile, "w")
tof.write("p cnf %d %d\n" % (maxvar, numcls + len(assumps)))
thisDebugLibPart = 0
for line in fromf:
line = line.strip()
# skip empty lines and headers
if not line or line[0] == "p":
continue
# parse up special header
if line[0] == "c":
if "Solver::solve" in line:
thisDebugLibPart += 1
continue
# break out if we reached the debug lib part
if thisDebugLibPart >= debug_num:
break
tof.write(line + '\n')
# add assumptions
for lit in assumps:
tof.write("%d 0\n" % lit)
fromf.close()
tof.close()
def _get_assumps(self, fname, debugLibPart):
f = open(fname, "r")
thispart = 0
solveline = None
for line in f:
if "Solver::solve" in line:
thispart += 1
if thispart == debugLibPart:
solveline = line
break
f.close()
assert solveline is not None
ret = re.match("c.*Solver::solve\((.*)\)", solveline)
assert ret is not None
assumps = ret.group(1).strip().split()
assumps = [int(x) for x in assumps]
print("Assumptions: ", assumps)
return assumps
def _check_assumps_inside_conflict(self, assumps, conflict):
for lit in conflict:
if -1 * lit not in assumps:
print("ERROR: Final conflict contains %s but assumps is %s" %(conflict, assumps))
print("ERROR: lit ", lit, " is in conflict but its inverse is not is assumps!")
exit(-100)
print("OK, final conflict only contains elements from assumptions")
def _check_assumps_inside_solution(self, assumps, solution):
for lit in assumps:
var = abs(lit)
val = lit > 0
if var in solution:
if solution[var] != val:
print("Solution pinted has literal %s but assumptions contained the inverse: '%s'" % (-1 * lit, assumps))
exit(-100)
print("OK, all assumptions inside solution")
def _find_largest_debuglib_part(self, fname):
largestPart = 0
dirList2 = os.listdir("out/.")
fname_no_out = fname.replace("out/", "")
for fname_debug in dirList2:
if fnmatch.fnmatch(fname_debug, "%s-debugLibPart*.output" % fname_no_out):
largestPart += 1
return largestPart
@staticmethod
def max_vars_in_file(fname):
maxvar = 0
with open(fname, "r") as f:
for line in f:
line = line.strip()
# ignore comments
if not line or line[0] == "c" or line[0] == 'p':
continue
# calculate max variable
maxvar = max(maxvar, get_max_var_from_clause(line))
return maxvar
@staticmethod
def _check_regular_clause(line, solution):
lits = line.split()
for lit in lits:
numlit = int(lit)
if numlit == 0:
break
if abs(numlit) not in solution:
continue
if solution[abs(numlit)] ^ (numlit < 0):
return True
# print not set vars
for lit in lits:
numlit = int(lit)
if numlit == 0:
break
if abs(numlit) not in solution:
print("var %d in XOR clause not set" % abs(numlit))
#print("Every other var set to FALSE")
#print("Orig clause in DIMACS: ", lits)
print("Error: clause '%s' not satisfied." % line.strip())
raise NameError("Error: clause '%s' not satisfied." % line)
return False
@staticmethod
def _check_xor_clause(line, solution):
line = line.lstrip('x')
lits = line.split()
final = False
for lit in lits:
numlit = int(lit)
if numlit != 0:
if abs(numlit) not in solution:
raise NameError("Error: var %d not solved, but referred to in a xor-clause of the CNF" % abs(numlit))
final ^= solution[abs(numlit)]
final ^= numlit < 0
if final is False:
print("Error: xor-clause '%s' not satisfied." % line.strip())
raise NameError("Error: xor-clause '%s' not satisfied." % line)
return final
def parse_arguments():
class PlainHelpFormatter(optparse.IndentedHelpFormatter):
def format_description(self, description):
if description:
return description + "\n"
else:
return ""
usage = """usage: %prog solution cnf
For example:
%prog my_solution_file.out my_problem.cnf.gz"""
parser = optparse.OptionParser(usage=usage, formatter=PlainHelpFormatter())
parser.add_option("--verbose", "-v", action="store_true",
default=False, dest="verbose", help="Be more verbose")
parser.add_option("--tout", "-t", dest="maxtime", type=int, default=100,
help="Max time to run. Default: %default")
parser.add_option("--textra", dest="maxtimediff", type=int, default=10,
help="Extra time on top of timeout for processing."
" Default: %default")
# parse options
options, args = parser.parse_args()
return options, args
if __name__ == "__main__":
options, args = parse_arguments()
print("Options are:", options)
print("args are:", args)
if len(args) != 2:
print("ERROR: You must give exactly two parameters, "
"one SOLUTION and one CNF")
print("You gave {n} parameters".format(**{"n": len(args)}))
exit(-1)
sol_file = args[0]
cnf_file = args[1]
print("Verifying CNF file '{cnf}' against solution in file '{sol}'".format(
**{"cnf": cnf_file, "sol": sol_file}))
print("Checking debug libs...")
sol_parser = solution_parser(options)
sol_parser.check_debug_lib(cnf_file)
print("Checking console output...")
sol = {}
with open(sol_file) as f:
dat = f.read()
dat = dat.split("\n")
unsat, solution, _ = sol_parser.parse_solution_from_output(dat)
if not unsat:
sol_parser.test_found_solution(solution, cnf_file)
exit(0)
# check with other solver
ret = sol_parser.check_unsat(cnf_file)
if ret is None:
print("Other solver time-outed, cannot check")
elif ret is True:
print("UNSAT verified by other solver")
else:
print("Grave bug: SAT-> UNSAT : Other solver found solution!!")
exit(-1)
|