Guest User

Untitled

a guest
May 26th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. class ExternalSolver(SATSolver):
  2. def __init__(self, path):
  3. self.path = path
  4.  
  5. args = shlex.split(self.path)
  6. self.proc = subprocess.Popen(args,
  7. stdin=subprocess.PIPE,
  8. stdout=subprocess.PIPE,
  9. stderr=subprocess.PIPE)
  10.  
  11. def solve(self, formula):
  12. # Compose the formula to send
  13. dimacsFormula = getDIMACSFormula(formula)
  14.  
  15. (outdata, errdata) = self.proc.communicate(dimacsFormula)
  16.  
  17.  
  18. if self.proc.returncode >= 0 and len(outdata) > 0:
  19. solFile = StringIO(outdata)
  20. solution = parseDIMACSSolution(solFile)
  21. return solution
  22.  
  23. def abort(self):
  24. self.proc.kill()
  25.  
  26.  
  27. class _PortfolioThread(Thread):
  28. def __init__(self, solver, formula, sem):
  29. Thread.__init__(self)
  30.  
  31. self.solution = None
  32. self.solver = solver
  33. self.formula = formula
  34. self.sem = sem
  35.  
  36. def run(self):
  37. self.solution = self.solver.solve(self.formula)
  38. self.sem.release()
  39.  
  40. class PortfolioSolver(SATSolver):
  41. def __init__(self, solvers):
  42. self.solvers = solvers
  43.  
  44. def solve(self, formula):
  45. solverThreads = []
  46. solution = None
  47.  
  48. sem = Semaphore(0)
  49.  
  50. for solver in self.solvers:
  51. sThread = _PortfolioThread(solver, formula, sem)
  52. solverThreads.append(sThread)
  53.  
  54. sThread.start()
  55.  
  56. # Wait for at least one thread to finish
  57. sem.acquire()
  58.  
  59. for sThread in solverThreads:
  60. if solution is None:
  61. if sThread.solution is not None:
  62. solution = sThread.solution
  63.  
  64. sThread.solver.abort()
  65.  
  66. assert solution is not None, "Solver returned with invalid solution"
  67.  
  68. for sThread in solverThreads:
  69. sThread.join()
  70.  
  71. return solution
  72.  
  73. def abort(self):
  74. pass
Add Comment
Please, Sign In to add comment