dimacs.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """For reading in DIMACS file format
  2. www.cs.ubc.ca/~hoos/SATLIB/Benchmarks/SAT/satformat.ps
  3. """
  4. from sympy.core import Symbol
  5. from sympy.logic.boolalg import And, Or
  6. import re
  7. def load(s):
  8. """Loads a boolean expression from a string.
  9. Examples
  10. ========
  11. >>> from sympy.logic.utilities.dimacs import load
  12. >>> load('1')
  13. cnf_1
  14. >>> load('1 2')
  15. cnf_1 | cnf_2
  16. >>> load('1 \\n 2')
  17. cnf_1 & cnf_2
  18. >>> load('1 2 \\n 3')
  19. cnf_3 & (cnf_1 | cnf_2)
  20. """
  21. clauses = []
  22. lines = s.split('\n')
  23. pComment = re.compile(r'c.*')
  24. pStats = re.compile(r'p\s*cnf\s*(\d*)\s*(\d*)')
  25. while len(lines) > 0:
  26. line = lines.pop(0)
  27. # Only deal with lines that aren't comments
  28. if not pComment.match(line):
  29. m = pStats.match(line)
  30. if not m:
  31. nums = line.rstrip('\n').split(' ')
  32. list = []
  33. for lit in nums:
  34. if lit != '':
  35. if int(lit) == 0:
  36. continue
  37. num = abs(int(lit))
  38. sign = True
  39. if int(lit) < 0:
  40. sign = False
  41. if sign:
  42. list.append(Symbol("cnf_%s" % num))
  43. else:
  44. list.append(~Symbol("cnf_%s" % num))
  45. if len(list) > 0:
  46. clauses.append(Or(*list))
  47. return And(*clauses)
  48. def load_file(location):
  49. """Loads a boolean expression from a file."""
  50. with open(location) as f:
  51. s = f.read()
  52. return load(s)