이번 섹션에서는 솔루션에 대한 solver search 시간 제한을 설정하는 방법에 대해 설명한다.
Setting a time limit for the solver
만약 너의 프로그램이 동작하는데 오랜 시간이 걸린다면, solver에 대해 시간 제한을 설정하는 것을 추천한다.
이는 프로그램이 합리적인 정도의 시간으로 종료될 것이다.
아래의 예제는 solver에게 10s의 시간 제한을 어떻게 설정하였는지를 보여준다.
from ortools.sat.python import cp_model
def SolveWithTimeLimitSampleSat():
#creates the model
model = cp_model.CpModel()
#create the variables
num_vals = 3
x = model.NewIntVar(0, num_vals - 1, 'x')
y = model.NewIntVar(0, num_vals - 1, 'y')
z = model.NewIntVar(0, num_vals - 1, 'z')
#adds an all-different constraint
model.Add(x!=y)
#creates a solver and solves the model
solver = cp_model.CpSolver()
#sets a time limit of 10 seconds.
solver.parameters.max_time_in_seconds = 10.0
status = solver.Solve(model)
if status == cp_model.OPTIMAL:
print('x = %i' % solver.Value(x))
print('y = %i' % solver.Value(y))
print('z = %i' % solver.Value(z))
SolveWithTimeLimitSampleSat()
Stopping a search after a specified number of solutions
시간제약을 세팅하는 방법의 대안으로, 특정 정답의 숫자만큼 발견한 후 solver를 종료시킬 수 있다.
아래 예제는 5개의 정답을 찾은 후 탐색을 멈추는 코드이다.
from ortools.sat.python import cp_model
class VarArraySolutionPrinterWithLimit(cp_model.CpSolverSolutionCallback):
def __init__(self, variables, limit):
cp_model.CpSolverSolutionCallback.__init__(self)
self.__variables = variables
self.__solution_count = 0
self.__solution_limit = limit
def on_solution_callback(self):
self.__solution_count += 1
for v in self.__variables:
print('%s=%i' % (v, self.Value(v)), end=' ')
print()
if self.__solution_count >= self.__solution_limit:
print('Stop search after %i solutions' % self.__solution_limit)
self.StopSearch()
def solution_count(self):
return self.__solution_count
def StopAfterNSolutionsSampleSat():
#creates the model
model = cp_model.CpModel()
#creates the variables
num_vals = 3
x = model.NewIntVar(0, num_vals - 1, 'x')
y = model.NewIntVar(0, num_vals - 1, 'y')
z = model.NewIntVar(0, num_vals - 1, 'z')
#create a solver and solve
solver = cp_model.CpSolver()
solution_printer = VarArraySolutionPrinterWithLimit([x, y, z], 5)
#enumerate all solutions
solver.parameters.enumerate_all_solutions = True
#solve
status = solver.Solve(model, solution_printer)
print('Status = %s' % solver.StatusName(status))
print('Number of solutions found: %i' % solution_printer.solution_count())
assert solution_printer.solution_count() == 5
StopAfterNSolutionsSampleSat()
Reference :
https://developers.google.com/optimization/cp/cp_tasks
문제 해결사 제한 설정 | OR-Tools | Google Developers
이 페이지는 Cloud Translation API를 통해 번역되었습니다. Switch to English 의견 보내기 문제 해결사 제한 설정 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 다음
developers.google.com
댓글