Ejemplo n.º 1
0
 def sym_constraints(self, problem):
     problem.addConstraint(
         constraint.FunctionConstraint(lambda x, y: x - y < 0),
         [self.rows()[i] for i in [0, -1]])
     problem.addConstraint(
         constraint.MaxSumConstraint((self.n_cols() + 1) / 2),
         [self.rows()[0]])
Ejemplo n.º 2
0
    def solve(self, numslots):
        values = self.values
        dur = self.dur
        timeout = self.timeout
        problem = constraint.Problem()
        slots = list(range(numslots))
        problem.addVariables(slots, values)
        if dur is not None:
            if self.relError is None and self.absError is None:
                absError = min(values)
            elif self.absError is None:
                absError = self.relError * dur
            elif self.relError is None:
                absError = self.absError
            else:
                absError = min(self.absError, self.relError * dur)
            problem.addConstraint(constraint.MinSumConstraint(dur - absError))
            problem.addConstraint(constraint.MaxSumConstraint(dur + absError))

        if self.fixedslots:
            for idx, slotdur in self.fixedslots.items():
                try:
                    slot = slots[idx]
                    problem.addConstraint(
                        lambda s, slotdur=slotdur: s == slotdur,
                        variables=[slot])
                except IndexError:
                    pass

        self._applyConstraints(problem, slots)

        for callback in self._constraintCallbacks:
            callback(problem, slots)

        return getSolutions(problem, numSlots=numslots, timeout=timeout)
    def __init__(self):
        self.credit_limit = 120
        self.theo_limit = 10
        self.area_limit = [18, 8, 8]
        self.max_allowed_lectures = 8  # In Master it is unrealistic to do more than N lectures (except thesis practical courses seminars etc.)
        self.taken_lecture_names = ['Computer Vision I: Variational Methods', 'Computer Vision II: Multiple View Geometry', 'Natural Language Processing',
                                    'Introduction to Deep Learning', 'Advanced Deep Learning for Computer Vision']

        self.preferred_areas = ['COMPUTER GRAPHICS AND VISION', 'MACHINE LEARNING AND ANALYTICS', 'DIGITAL BIOLOGY AND DIGITAL MEDICINE']

        self.problem = constraint.Problem()
        self.lectures = self.create_lectures()
        self.taken_lectures = []
        for lecture in self.lectures:
            if lecture.name in self.taken_lecture_names:
                self.taken_lectures.append(lecture)
        for taken_lecture in self.taken_lectures:
            self.lectures.remove(taken_lecture)

        self.taken_lectures.extend(  # Not classical lectures
            [Lecture(name='Seminar', ec=5, area='None'), Lecture(name='Practical Course', ec=10, area='None'), Lecture(name='IDP', ec=16, area='None'),
             Lecture(name='Guided Research', ec=10, area='None'), Lecture(name='Thesis', ec=30, area='None'), Lecture(name='Language', ec=6, area='None')])

        self.exitings_credits = 0
        self.existing_theo_credits = 0
        for taken_lecture in self.taken_lectures:
            self.exitings_credits += taken_lecture.ec
            if taken_lecture.theo:
                self.existing_theo_credits += taken_lecture.ec

        self.lectures = sorted(self.lectures)
        self.problem.addVariables(self.lectures, [0, 1])
        self.problem.addConstraint(constraint.MaxSumConstraint(self.max_allowed_lectures - len(self.taken_lecture_names)), self.lectures)
        self.problem.addConstraint(constraint.FunctionConstraint(self.area_constraint), self.lectures)
        self.problem.addConstraint(constraint.FunctionConstraint(self.credit_constraint), self.lectures)
        self.problem.addConstraint(constraint.FunctionConstraint(self.theo_constraint), self.lectures)
        start = time()
        solutions = self.problem.getSolutions()
        print(f'Took {time() - start}')
        print(len(solutions))
        solutions = self.solution_sorting(solutions)
        print(len(solutions))
        for i in range(100):
            print(self.get_credits_for_solution(solutions[i]))
            print(self.solution_to_str(solutions[i]))
Ejemplo n.º 4
0
def _besttimesig_with_combinations(duration,
                                   tempo,
                                   timesigs,
                                   maxcombinations=3,
                                   tolerance=0.25):
    assert isinstance(duration, (int, float, F))
    assert isinstance(tempo, (int, float, F)) and tempo > 0
    assert isinstance(timesigs, (tuple, list))
    assert isinstance(maxcombinations, int) and maxcombinations > 0
    import constraint
    p = constraint.Problem()
    possibledurs = [t * (60.0 / tempo) for t in timesigs]
    possibledurs += [0]
    V = range(maxcombinations)
    p.addVariables(V, possibledurs)

    def objective(solution):
        # this is the function to MINIMIZE
        values = solution.values()
        numcombinations = sum(value > 0 for value in values)
        # TODO: use timesig complexity here to make a more intelligent choice
        return numcombinations

    p.addConstraint(constraint.MinSumConstraint(duration - tolerance))
    p.addConstraint(constraint.MaxSumConstraint(duration + tolerance))
    solutions = p.getSolutions()
    if not solutions:
        warnings.warn("No solutions")
        return None
    solutions.sort(key=objective)

    def getvalues(solution):
        values = [
            value for name, value in sorted(solution.items()) if value > 0
        ]
        values.sort()
        return tuple(values)

    solutions = list(map(getvalues, solutions))
    best = solutions[0]
    solutions = set(solutions)

    return best, solutions
Ejemplo n.º 5
0
def solve(board):
    problem = constraint.Problem(constraint.BacktrackingSolver())
    
    # Build Variables
    for y in range(SIZE):
        for x in range(SIZE):
            if board[y,x] == -1:
                problem.addVariable(str([y,x]), [1, 100])

    # Constraints for variables near numbers
    for y in range(SIZE):
        for x in range(SIZE):
            if board[y,x] in [0,1,2,3,4]:
                val = 0
                adj_vars = []
                if y>0 and board[y-1,x] == -1: adj_vars.append(str([y-1,x]))
                if y<SIZE-1 and board[y+1,x] == -1: adj_vars.append(str([y+1,x]))
                if x>0 and board[y,x-1] == -1: adj_vars.append(str([y,x-1]))
                if x<SIZE-1 and board[y,x+1] == -1: adj_vars.append(str([y,x+1]))
                val += 100*board[y,x] + len(adj_vars) - board[y,x]
                problem.addConstraint(constraint.ExactSumConstraint(val), adj_vars)

    # Sum of each scan must be less than 200, since only 1 light per scan
    # For horizontal scans 
    for y in range(SIZE):
        curr_scan = []
        for x in range(SIZE):
            if board[y,x] == -1: curr_scan.append(str([y,x]))
            else:
                if len(curr_scan) > 0:
                    problem.addConstraint(constraint.MaxSumConstraint(199), curr_scan)
                curr_scan = []
        if len(curr_scan) > 0:
            problem.addConstraint(constraint.MaxSumConstraint(199), curr_scan)
    # For vertical scans 
    for x in range(SIZE):
        curr_scan = []
        for y in range(SIZE):
            if board[y,x] == -1: curr_scan.append(str([y,x]))
            else:
                if len(curr_scan) > 0:
                    problem.addConstraint(constraint.MaxSumConstraint(199), curr_scan)
                curr_scan = []
        if len(curr_scan) > 0:
            problem.addConstraint(constraint.MaxSumConstraint(199), curr_scan)

    # For each point, pair of scans passing through point must contain 100 at least once
    scans = []
    for y in range(SIZE):
        for x in range(SIZE):
            if board[y,x] != -1: continue
            scan = []
            scan.append(str([y,x]))
            # Up
            for i in reversed(range(y)):
                if board[i,x] >= 0: break
                else: scan.append(str([i,x]))
            # Down
            for i in range(y+1,SIZE):
                if board[i,x] >= 0: break
                else: scan.append(str([i,x]))
            # Left
            for i in reversed(range(x)):
                if board[y,i] >= 0: break
                else: scan.append(str([y,i]))
            # Right
            for i in range(x+1,SIZE):
                if board[y,i] >= 0: break
                else: scan.append(str([y,i]))
            scan.sort()
            if scan not in scans: scans.append(scan)
    for scan in scans:
        problem.addConstraint(constraint.SomeInSetConstraint([100]), scan)
    
    solution = problem.getSolution()

    for y in range(SIZE):
        for x in range(SIZE):
            if str([y,x]) in solution:
                board[y,x] = -1 if solution[str([y,x])] == 1 else 100
    return board
Ejemplo n.º 6
0
players_evil = 4
players_good = len(players) - players_evil

problem = constraint.Problem()

# Every player is good or evil
problem.addVariables(players, [GOOD, EVIL])

# There are always an exact number of evil players
problem.addConstraint(constraint.ExactSumConstraint(players_evil))

# Assume no evil players if a mission passes
mission_passed = known_good_player = constraint.ExactSumConstraint(GOOD)

# Assume at most 1 evil player if the 4th mission passes
mission_4_passed = constraint.MaxSumConstraint(EVIL)

# Know at least 1 evil player is on every failed mission
mission_failed = known_evil_player = constraint.MinSumConstraint(EVIL)

# problem.addConstraint(known_good_player, [1])

# The following is a simulated game
# Players 1, 2, 3, 4 are evil, but we don't "know" this
problem.addConstraint(mission_failed, [1, 2, 3])
problem.addConstraint(mission_failed, [1, 5, 6, 7])
problem.addConstraint(mission_passed, [5, 6, 7, 8])
# problem.addConstraint(mission_4_passed, [4, 5, 7, 8, 6])

solutions = problem.getSolutions()
Ejemplo n.º 7
0
# prenose eksploziv
# 20kg=20000g nosivost
# 50dm3=50000cm3 zapremina
# 17000din budzet
# max razarna moc

problem = constraint.Problem()

problem.addVariable("#M-84", range(0, 5))
problem.addVariable("#M-75", range(0, 31))
problem.addVariable("#P98", range(0, 11))
problem.addVariable("#TMA-4", range(0, 21))
problem.addVariable("#TMPR-6", range(0, 6))

problem.addConstraint(
    constraint.MaxSumConstraint(20000, [480, 355, 160, 30, 72]))
problem.addConstraint(
    constraint.MaxSumConstraint(17000, [1000, 2500, 800, 7000, 10000]))
problem.addConstraint(
    constraint.MaxSumConstraint(
        50000, [6 * 11.5, 5.7 * 8.9, 2 * 2, 28.5 * 110, 29 * 132]))

energy = -1
for solution in problem.getSolutions():
    power = 5.6  * solution["#M-84"]\
          + 9.9  * solution["#M-75"]\
          + 2.7  * solution["#P98"]\
          + 30.5 * solution["#TMA-4"]\
          + 45.4 * solution["#TMPR-6"]

    energy = max(energy, power)
Ejemplo n.º 8
0
import constraint

# 10e = 1170din

problem = constraint.Problem()

problem.addVariable("#brasno", range(0, 11))
problem.addVariable("#plazma", range(0, 21))
problem.addVariable("#jaja", range(0, 8))
problem.addVariable("#mleko", range(0, 6))
problem.addVariable("#visnja", range(0, 4))
problem.addVariable("#nutela", range(0, 9))

problem.addConstraint(constraint.ExactSumConstraint(10))
problem.addConstraint(
    constraint.MaxSumConstraint(1170, [30, 300, 50, 170, 400, 450]))
problem.addConstraint(
    constraint.MaxSumConstraint(500, [30, 10, 150, 32, 3, 15]))
problem.addConstraint(constraint.MaxSumConstraint(150, [5, 30, 2, 15, 45, 68]))

best_protein = -1
for solution in problem.getSolutions():
    kolicina_proteina = 20 * solution["#brasno"]\
                      + 15 * solution["#plazma"]\
                      + 70 * solution["#jaja"]\
                      + 40 * solution["#mleko"]\
                      + 40 * solution["#visnja"]\
                      + 7 * solution["#nutela"]
    if best_protein < kolicina_proteina:
        best_protein = kolicina_proteina
Ejemplo n.º 9
0
import constraint

problem = constraint.Problem()

# min{30000/360, 14000/200} = min{83.33, 70} = 70
problem.addVariable('R', range(71))
# min{30000/240, 14000/60} = min{125, 233.33} = 125
problem.addVariable('S', range(126))


def ogr(r, s):
    if r >= (3.0 * s / 2):
        return True


problem.addConstraint(constraint.MaxSumConstraint(30000, [360, 240]), 'RS')
problem.addConstraint(constraint.MaxSumConstraint(14000, [200, 60]), 'RS')
problem.addConstraint(ogr, 'RS')

resenje = problem.getSolutions()

max_zarada = 0
max_R = 0
max_S = 0

for r in resenje:
    if max_zarada < r['R'] * 200 + r['S'] * 80:
        max_zarada = r['R'] * 200 + r['S'] * 80
        max_R = r['R']
        max_S = r['S']