def read_input(self, filename): """ P: float M: float N: integer C: integer items: list of tuples constraints: list of sets Return true iff this process finished successfully """ with open(filename) as f: self.P = float(f.readline()) self.M = float(f.readline()) self.N = int(f.readline()) self.C = int(f.readline()) self.items = [] self.map_name_to_items = dict() self.constraints = Constraint() self.raw_constraints = list() # this is constraints without modification for i in range(self.N): name, cls, weight, cost, val = f.readline().split(";") item = Item(name, int(cls), float(weight), float(cost), float(val)) self.items.append(item) self.map_name_to_items[name] = item for i in range(self.C): one_list_of_constraint = eval(f.readline()) self.constraints.createConflict(one_list_of_constraint) self.raw_constraints.append(one_list_of_constraint) self.initialized = True self.filename = filename return True
def __init__(self, variables1, value1, variables2, value2): Constraint.__init__( self, lambda vars1, vars2: abs( vars1.index(value1) - vars2.index(value2)) == 1, (variables1, variables2)) self.value1 = value1 self.value2 = value2
class TestTableau(unittest.TestCase): def test_pivot_1(self): case = [Constraint([1, 1], 2), Constraint([2, -1], 0), Constraint([-1, 2], 1)] ''' x0 + x1 >= 2 2x0 - x1 >= 0 -x0 + 2 * x1 >= 1 || || \/ x0 + x1 - s0 = 0 2x0 - x1 - s1 = 0 -x0 + 2 * x1 - s2 = 0 s0 >= 2 s1 >= 0 s2 >= 1 ''' tab = Tableau(case) tab.pivot("s0", "x0") assert_frame_equal(tab.data, pd.DataFrame(data=[[1.0, -1.0], [2.0, -3.0], [-1.0, 3.0]], index=["x0", "s1", "s2"], columns=["s0", "x1"])) tab.pivot("s2", "x1") assert_frame_equal(tab.data, pd.DataFrame(data=[[2.0/3.0, -1.0/3.0], [1.0, -1.0], [1.0/3.0, 1.0/3.0]], index=["x0", "s1", "x1"], columns=["s0", "s2"]))
def isSubsumed(self, my_state, old_state, old_constraint): if not set(my_state) == set(old_state): return my_concretes = {k: v for k, v in my_state.iteritems() if not isinstance(v, SymbolicType)} old_concretes = {k: v for k, v in old_state.iteritems() if not isinstance(v, SymbolicType)} # all purely concrete variables must be equal for var in my_concretes.viewkeys() & old_concretes.viewkeys(): if my_concretes[var] != old_concretes[var]: return # assert that the states must be equal my_constraint = self.current_constraint state_vars = set() for var in set(my_state): # use a variable name that is illegal in python state_var = var + "$" state_sym_var = SymbolicInteger(state_var, 32) state_vars.add(state_var) my_p = Predicate(state_sym_var == my_state[var], True) my_constraint = Constraint(my_constraint, my_p) old_p = Predicate(state_sym_var == old_state[var], True) old_constraint = Constraint(old_constraint, old_p) (_, my_asserts, _) = my_constraint.buildZ3Asserts() (_, old_asserts, old_sym_vars) = old_constraint.buildZ3Asserts() old_inputs = [v[1] for k, v in old_sym_vars.iteritems() if not k in state_vars] subsumed = Implies(And(my_asserts), Exists(old_inputs, And(old_asserts))) return z3_wrap.findCounterexample([], subsumed, []) == None
def __init__(self, variables): Constraint.__init__(self, lambda *values: len([row1 for name1, row1 in zip(variables, values) if \ len([row2 for name2, row2 in zip(variables, values) if \ row2 == row1 or \ abs(name2 - name1) == abs(row2 - row1) \ ]) != 1 \ ]) == 0, variables)
def read_file(filename): with open(filename) as f: content = f.readlines() filename_k_dict = {"graphs/graph0.txt": 3, "graphs/graph1.txt": 3, "graphs/graph-color-1.txt": 4, "graphs/graph-color-2.txt": 4, "graphs/rand-50-4-color1.txt": 4, "graphs/rand-100-4-color1.txt": 4, "graphs/rand-100-6-color1.txt": 6, "graphs/spiral-500-4-color1.txt": 4, "gcolor1.txt": 4, "gcolor2.txt": 4, "gcolor3.txt": 4} #k = int(raw_input("k: ")) #k = filename_k_dict[filename] k =4 variable_dict = {} nr_of_variables, nr_of_constraints = map(int, content[0].rstrip().split(" ")) # Reads all the variables into a variable dictionary. # key = variable index and value = Variable object for i in range(1, nr_of_variables + 1): vertex_info = map(float, content[i].rstrip().split(" ")) v = Variable(index=int(vertex_info[0]), x=vertex_info[1], y=vertex_info[2], k=k) variable_dict[v.index] = v constraints = [] # Reads all constraints into a list containing Constraint objects for j in range(i + 1, nr_of_variables + nr_of_constraints + 1): constraint_info = map(int, content[j].rstrip().split(" ")) constr = Constraint(variable_dict, involved_variables=constraint_info) constr.constraining_func = makefunc(var_names=["x", "y"], expression="x != y") constraints.append(constr) return variable_dict, constraints
def __init__(self, variables1, value1, variables2, value2): Constraint.__init__( self, lambda vars1, vars2: len([ i for i, val1 in enumerate(vars1) if val1 == value1 and vars2[i] == value2 ]) == 1, (variables1, variables2)) self.value1 = value1 self.value2 = value2
class TestFourierMotzkin(unittest.TestCase): def test_fourier_motzkin_sat(self): case = [Constraint([1, 1], 0.8), Constraint([1, -1], 0.2)] ''' x0 + x1 >= 0.8 x0 - x1 >= 0.2 ''' result = fourier_motzkin(case) self.assertDictEqual(result, {"x0": 0.5, "x1": 0.3})
def from_dict(self, dictionnary): self.title = dictionnary.get("title", "") self.description = dictionnary.get("description", "") self.utility = dictionnary["utility"] self.utility_constraint = Constraint("z", "EQ", self.utility) self.variables = dictionnary["variables"] self.optimizer = dictionnary["optimizer"] self.constraints = [Constraint(*constraint) for constraint in dictionnary["constraints"]] for constraint in self.constraints: constraint.set_variables(self.variables) self.comments = "Forme initiale du problème." self.standard = False
def test_is_valid(self): goal = Goal("New Goal") self.assertTrue(goal.is_valid()) goal.add_neighbor(Variable("New Variable"), Constraint([])) self.assertFalse(goal.is_valid()) goal = Goal("New Goal") constraint = Constraint([[Equals(3)]]) variable = Variable("New Variable", 5) goal.add_neighbor(variable, constraint) self.assertFalse(goal.is_valid())
def __init__(self, n, d=2.7, B=list([1, 1])): super().__init__(n=n, d=d, name='cube', B=B) self.constraint_sets = list() for j, bj in enumerate(self.B, start=1): self.constraint_sets.append([ Constraints(constraints=[ Constraint(_operator=Operator.lt, value=it * j - self.L + self.L * bj), Constraint(_operator=Operator.gt, value=it * j + it * d + self.L - self.L * bj) ]) for it in self.variables ]) self.bounds = [self._bounds(i=ii, d=d) for ii in self.variables]
def __init__(self, n, d=2.7, B=list([1, 1])): super().__init__(n=n, d=d, name='simplex', B=B) self.constraint_sets = [ Constraints(constraints=[ Constraint(_operator=Operator.lt, value=2 * j - 2 - self.L * (1 - bj)), Constraint(_operator=Operator.lt, value=2 * j - 2 - self.L * (1 - bj)), Constraint(_operator=Operator.gt, value=j * d + self.L * (1 - bj)) ]) for j, bj in enumerate(self.B, start=1) ] self.bounds = [self._bounds(i=ii, d=d) for ii in self.variables]
def is_exactly(self, *args, **kwargs): """A constraint that forces the variable to take a specific value. Useful for a sanity check. """ # v = N N = args[0] self.constraints.append(Constraint(['own_idx'], [1], '=', N, **kwargs))
def has_at_least(self, *args, **kwargs): """A constraint that forces at least N of the variable's (indicator) links to be active, regardless of its own value. """ # Σ x >= N N, link = args self.constraints.append(Constraint([link], [1], '>=', N, **kwargs))
def __init__(self, engine): self.symbolic_variables = {} self.constraints = {} self.engine = engine self.root_constraint = Constraint(None, None) self.current_constraint = self.root_constraint self.target_reached = False
def get_pivot_line(self, variable): var_constraints = list() std_var_constraints = list() best_value = inf best_index = -1 for idx, constraint in enumerate(self.constraints): var_constraint = constraint.var_constraint(variable) var_constraints.append(constraint.var_constraint(variable)) var_constraint.canonize() coeff = var_constraint.get_coeff(variable)[0] if coeff > 0: var_constraint.l_part /= coeff var_constraint.r_part /= coeff if var_constraint.r_part < best_value: best_value = var_constraint.r_part best_index = idx else: var_constraint = Constraint(variable, "GEQ", 0) std_var_constraints.append(var_constraint) return var_constraints, std_var_constraints, best_index
def implies_at_least(self, *args, **kwargs): """A constraint that enforces that, if the (indicator) variable is active, at least N of its (indicator) links must be active. """ # N*v - Σ x <= 0 N, link = args self.constraints.append( Constraint(['own_idx', link], [N, -1], '<=', 0, **kwargs))
def set_in_base(self, variable, idx, comment="\nOn fait entrer la variable ${variable}$ dans la base."): out_var = self.constraints[idx].l_part self.constraints[idx].in_base(variable) for idx_constraint, constraint in enumerate(self.constraints): if idx_constraint == idx: continue constraint.substitutions[variable] = self.constraints[idx].r_part self.utility_constraint = Constraint("z", "EQ", self.utility) self.utility_constraint.set_variables(self.variables) self.utility_constraint.substitutions[variable] = self.constraints[idx].r_part self.utility = self.utility_constraint.r_part self.comments = comment.format(variable=variable, idx=idx) self.out.remove(variable) self.out.append(out_var) self.base.append(variable) self.base.remove(out_var) self.update_solution()
def __init__(self, engine): self.symbolic_variables = {} self.constraints = {} self.engine = engine self.root_constraint = Constraint(None, None) self.current_constraint = self.root_constraint self.branch_result_stack = [] self.tracer = None
def implies(self, *args, **kwargs): """A constraint that enforces that, if the (indicator) variable is active, all of its (indicator) links must be active. """ # X*v - Σ x <= 0 link = args[0] self.constraints.append( Constraint(['own_idx', link], [link, -1], '<=', 0, **kwargs))
def implied_by(self, *args, **kwargs): """A constraint that enforces that, if any (indicator) links are active, the (indicator) variable must also be active. """ # X*v - Σ x >= 0 link = args[0] self.constraints.append( Constraint(['own_idx', link], [link, -1], '>=', 0, **kwargs))
def read_file(filename): with open(filename) as f: content = f.readlines() filename_k_dict = { "graphs/graph0.txt": 3, "graphs/graph1.txt": 3, "graphs/graph-color-1.txt": 4, "graphs/graph-color-2.txt": 4, "graphs/rand-50-4-color1.txt": 4, "graphs/rand-100-4-color1.txt": 4, "graphs/rand-100-6-color1.txt": 6, "graphs/spiral-500-4-color1.txt": 4, "gcolor1.txt": 4, "gcolor2.txt": 4, "gcolor3.txt": 4 } #k = int(raw_input("k: ")) #k = filename_k_dict[filename] k = 4 variable_dict = {} nr_of_variables, nr_of_constraints = map(int, content[0].rstrip().split(" ")) # Reads all the variables into a variable dictionary. # key = variable index and value = Variable object for i in range(1, nr_of_variables + 1): vertex_info = map(float, content[i].rstrip().split(" ")) v = Variable(index=int(vertex_info[0]), x=vertex_info[1], y=vertex_info[2], k=k) variable_dict[v.index] = v constraints = [] # Reads all constraints into a list containing Constraint objects for j in range(i + 1, nr_of_variables + nr_of_constraints + 1): constraint_info = map(int, content[j].rstrip().split(" ")) constr = Constraint(variable_dict, involved_variables=constraint_info) constr.constraining_func = makefunc(var_names=["x", "y"], expression="x != y") constraints.append(constr) return variable_dict, constraints
def iff_exactly(self, *args, **kwargs): """A constraint that enforces that if the (indicator) variable is active, exactly N of its (indicator) links must also be active (and vice versa). """ # N*v - Σ x = 0 N, link = args self.constraints.append( Constraint(['own_idx', link], [N, -1], '=', 0, **kwargs))
def iff(self, *args, **kwargs): """A constraint that enforces that if the (indicator) variable is active, all of its (indicator) links must also be active (and vice versa). """ # X*v - Σ x = 0 link = args[0] self.constraints.append( Constraint(['own_idx', link], [link, -1], '=', 0, **kwargs))
def consumes_flow_between(self, *args, **kwargs): """A constraint that enforces flow consumption from connected flow variables, thereby ensuring their connectivity in a tree structure. """ # Σ x - Σ y = 1 incoming_link, outgoing_link = args self.constraints.append( Constraint([incoming_link, outgoing_link], [1, -1], '=', 1, **kwargs))
def add(self, cmd): assert (len(cmd) == 2) negate, pred, args = self.process_constraint(cmd[1]) instr_cons = Constraint(pred, args, False) if negate: self.instructions.append(AssertNDG(instr_cons)) else: self.instructions.append(Assert(instr_cons))
def __init__(self, _name, _type, _demand_list, _priority=0, _qualifier=None, _category=None, _location=None): Constraint.__init__(self, _name, _type, _demand_list, _priority) self.qualifier = _qualifier # different or same self.category = _category # disaster, region, or update self.location = _location self.comparison_operator = None if self.qualifier == "same": self.comparison_operator = operator.eq elif self.qualifier == "different": self.comparison_operator = operator.ne
def get_linear_constraints_dict(self): constraints_dict = {} for p in self.polygons: cluster_src = p.cluster for e in p.edge_list: if e["tgt_cluster"] is not None: cluster_tgt = e["tgt_cluster"] c = Constraint(e["x1"], e["y1"], e["x2"], e["y2"], p.mid_x, p.mid_y, cluster_src, cluster_tgt) constraints_dict[(cluster_src, cluster_tgt)] = c return constraints_dict
def requires_flow_between(self, *args, **kwargs): """A constraint that enforces flow consumption from connected flow variables if the current (indicator) variable is active. This doesn't enforce a tree structure by itself without other constraints to activate this variable. """ # Σ x - Σ y = v incoming_link, outgoing_link = args self.constraints.append( Constraint([incoming_link, outgoing_link, 'own_idx'], [1, -1, -1], '=', 0, **kwargs))
def __init__(self, constraint_set_list): self.feature_table = get_feature_table() self.constraints = list() for constraint in constraint_set_list: constraint_name = constraint["type"] bundles_list = constraint["bundles"] if not constraint_name: raise ValueError("Missing 'type' key") constraint_class = Constraint.get_constraint_class_by_name(constraint_name) self.constraints.append(constraint_class(bundles_list))
def __init__(self, n, d=2.7, B=list([1, 1])): super().__init__(n=n, d=d, name='ball', B=B) self.constraint_sets = [ Constraints(constraints=[ Constraint(_operator=Operator.gt, value=d * d + self.L * (1 - bj)) ]) for bj in self.B ] self.bounds = [self._bounds(i=ii, d=d) for ii in self.variables]
def iff_multiple(self, *args, **kwargs): """A constraint that enforces that if the (indicator) variable is active, exactly N of its (indicator) links must also be active (and vice versa). """ # N*v - Σ x - Σ y - Σ z = 0 N = args[0] links = args[1:] self.constraints.append( Constraint(['own_idx'] + [l for l in links], [N] + [-1 for l in links], '=', 0, **kwargs))
def build_constraints(self, obstacles): self.obstacle_constraints = [] slack_num = 0 for i in range(self.steps_i.shape[1]-1): for obs in obstacles: self.obstacle_constraints.append( Constraint.from_obstacle(obs, self.steps_i[:,i], self.steps_i[:,i+1], self.slacks_i[slack_num])) slack_num += 1 return self
def read_file(filename): with open(filename) as f: content = f.readlines() nr_of_columns, nr_of_rows = map(int, content[0].rstrip().split(" ")) # (x, y) dimensions = (nr_of_columns, nr_of_rows) variable_dict = {} rows = [] columns = [] constraints = [] variable_index = 0 # Add all rows as variables for i in range(1, nr_of_rows+1): segments = map(int, content[i].rstrip().split(" ")) variable = Variable(index=variable_index, direction="row", direction_nr=variable_index, length=nr_of_columns, segments=segments) variable_dict[variable_index] = variable variable_index += 1 rows.append(variable) # Add all columns as variables for i in range(nr_of_rows+1, nr_of_rows+nr_of_columns+1): # Reversing the segments order to make it on the right format segments = map(int, content[i].rstrip().split(" "))[::-1] variable = Variable(index=variable_index, direction="column", direction_nr=i-(nr_of_rows+1),length=nr_of_rows, segments=segments) variable_dict[variable_index] = variable variable_index += 1 columns.append(variable) # Creating one constraint for each cell shared by a column and a row for column in columns: for row in rows: constraint = Constraint(variable_dict, involved_variables=[column.index, row.index]) constraint.constraining_func = makefunc(["x", "y"], "x == y") constraints.append(constraint) return dimensions, variable_dict, constraints
def build_constraints(variables): constraints = [] # Loop all variables for i in range(len(variables)): # Create new constraint constraint = Constraint() constraint.method = Builder.makefunc(['n'], 'n[0] == n[1]') # Add as constraint constraint.vars = [i] # Add the other constraints for j in range(len(variables)): if j != i and variables[i].index[0:1] != variables[j].index[0:1]: constraint.vars.append(j) # Add to constraints constraints.append(constraint) # Return the list of created constraints return constraints
def __init__(self, variable1, variable2): Constraint.__init__(self, lambda var1, var2: var1 == var2, (variable1, variable2))
for r2 in rules: if MCNetsRule.CS(r1,r2): csedges.append([r1, r2]) for r1 in rules: for r2 in rules: if r1.no == r2.no: continue cnt = 0 if MCNetsRule.IC(r1, r2): cnt = cnt + 1 n_ic = n_ic + 1 c = Constraint() c.addVariable(xvar(r1), 1.0) c.addVariable(xvar(r2), 1.0) c.setType(Constraint.LT) c.setBound(1.0) constr.append(c) # (17) if MCNetsRule.CS(r1,r2): cnt = cnt + 1 n_cs = n_cs + 1 if MCNetsRule.CD(r1,r2): cnt = cnt + 1 n_cd = n_cd + 1
def __init__(self, variables1, value1, variables2, value2): Constraint.__init__(self, lambda vars1, vars2: vars1.index(value1) - vars2.index(value2) == 1, (variables1, variables2)) self.value1 = value1 self.value2 = value2
def __init__(self, touched_variables): Constraint.__init__(self, lambda variables: len([x for x in variables if len([y for y in variables if x == y]) > 1]) == 0, (touched_variables,))
def __init__(self, variables1, value1, variables2, value2): Constraint.__init__(self, lambda vars1, vars2: len([i for i, val1 in enumerate(vars1) if val1 == value1 and vars2[i] == value2]) == 1, (variables1, variables2)) self.value1 = value1 self.value2 = value2
def __init__(self, prices, variables, exact_price): Constraint.__init__(self, lambda *values: sum([num*prices[var] for var, num in zip(variables, values)]) == exact_price, variables)
return v def xevar(g, e): global binary v = "xe_" + str(g[0]) + "_" + str(g[1]) + "_" + str(e[0]) + "_" + str(e[1]) binary.add(v) return v # # Constraints of type (i) # for g in p.GS(): c = Constraint() c.addVariable(xvar(g), 1.0) c.addVariable(xevar(g, p.h(g)), -1.0) c.setType(Constraint.EQ) c.setBound(0.0) constr.append(c) # # Constraints of type (ii) # for t in p.T: zero = True for x in p.T[t]: if x != 0: zero = False
def __init__(self, variable1, variable2, variable3): Constraint.__init__(self, lambda var1, var2, var3: (var1 + var2) % 10 == var3 or (var1 + var2) % 10 + 1 == var3, (variable1, variable2, variable3))
def __init__(self, variable1, variable2, diff): Constraint.__init__(self, lambda var1, var2: abs(var1 - var2) == diff, (variable1, variable2))
def __init__(self, variables, value): Constraint.__init__(self, lambda vars: len([x for x in vars if x == value]) > 0, (variables,))
def __init__(self, variable, value): Constraint.__init__(self, lambda var: var == value, (variable,))
class Solver: def __init__(self): self.initialized = False self.filename = "uninitialized solver" self.solution = None ############################ I/O METHODS ############################ def read_input(self, filename): """ P: float M: float N: integer C: integer items: list of tuples constraints: list of sets Return true iff this process finished successfully """ with open(filename) as f: self.P = float(f.readline()) self.M = float(f.readline()) self.N = int(f.readline()) self.C = int(f.readline()) self.items = [] self.map_name_to_items = dict() self.constraints = Constraint() self.raw_constraints = list() # this is constraints without modification for i in range(self.N): name, cls, weight, cost, val = f.readline().split(";") item = Item(name, int(cls), float(weight), float(cost), float(val)) self.items.append(item) self.map_name_to_items[name] = item for i in range(self.C): one_list_of_constraint = eval(f.readline()) self.constraints.createConflict(one_list_of_constraint) self.raw_constraints.append(one_list_of_constraint) self.initialized = True self.filename = filename return True def output_solution(self): import os if 'output' not in os.listdir("."): os.mkdir('output') if self.solution is None: raise RuntimeError("hasn't found a solution yet") return self.write_output(self.filename.replace('in','out'), self.solve()) def write_output(self, filename, items_chosen): with open(filename, "w") as f: for i in items_chosen: f.write("{0}\n".format(i.name)) return True def solve(self, resolve=False): """ Run our algorithm, save and return the solution. It will return saved solution from now on and return it in future unless RESOLVE is false. If you want to resolve the problem, set RESOLVE to True. This is different from run_algorithm for this doesn't solve anything but only deals with the logistic issues. """ if not self.initialized: raise RuntimeError("solver hasn't been initialized with input problem.") if resolve or self.solution is None: # WE DECLARE A SEPARATE ALGORITHMIC CALL TO MAKE OUR IMPLMENTATION CLEAN. self.solution = self.run_algorithm() return self.solution def run_algorithm(self): """ Solve the problem using algorithm and return the items chosen for the solution. """ raise NotImplementedError