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"]))
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 __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 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 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, 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 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 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 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 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, 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 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 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 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 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 has_flow_over(self, *args, **kwargs): """A constraint that enforces single commodity flow over the variable and grounds whether flow is active or not based on one of its (indicator) links. """ # v - Σ F*x <= 0 link, max_flow = args self.constraints.append( Constraint(['own_idx', link], [1, -max_flow], '<=', 0, **kwargs)) # Also set the maximum flow value as an upper bound for these variables self.upper_bound = max_flow
def _create_constraints(self): self.constraints = [] for k in range(self.pN): leftCol = k % self.pW == 0 leftCols = leftCol or (k - 1) % self.pW == 0 rightCol = (k + 1) % self.pW == 0 topRow = k < self.pW topRows = k < self.pW * 2 if not topRow: self.constraints.append( Constraint(self.particles[k], self.particles[k - self.pW])) if not topRows: self.constraints.append( Constraint(self.particles[k], self.particles[k - (self.pW * 2)])) if not leftCol: self.constraints.append( Constraint(self.particles[k], self.particles[k - 1])) if not leftCols: self.constraints.append( Constraint(self.particles[k], self.particles[k - 2])) if not topRow and not leftCol: self.constraints.append( Constraint(self.particles[k], self.particles[k - 1 - self.pW])) if not topRow and not rightCol: self.constraints.append( Constraint(self.particles[k], self.particles[k + 1 - self.pW]))
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 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 main(): logger = logging.getLogger('data_big_bang.focused_web_crawler') ap = argparse.ArgumentParser( description='Discover web resources associated with a site.') ap.add_argument('input', metavar='input.yaml', type=str, nargs=1, help='YAML file indicating the sites to crawl.') ap.add_argument('output', metavar='output.yaml', type=str, nargs=1, help='YAML file with the web resources discovered.') args = ap.parse_args() input = yaml.load(open(args.input[0], "rt")) fwc = FocusedWebCrawler() for e in input: e.update({'constraint': Constraint()}) fwc.queue.put(e) # fwc.queue.put({'url': 'http://www.linkedin.com', 'constraint': Constraint()}) # fwc.queue.put({'url': 'http://www.symantec.com', 'constraint': Constraint()}) # fwc.queue.put({'url': 'http://www.dell.com', 'key':'dell', 'constraint': Constraint()}) # fwc.queue.put({'url': 'http://www.apple.com', 'constraint': Constraint()}) # fwc.queue.put({'url': 'http://www.apple.com', 'constraint': Constraint()}) # fwc.queue.put({'url': 'http://www.matasano.com', 'constraint': Constraint()}) # fwc.queue.put({'url': 'http://www.basecamphq.com', 'key': 'basecamp', 'constraint': Constraint()}) # fwc.queue.put({'url': 'http://www.gnip.com', 'key':'gnip', 'constraint': Constraint()}) # fwc.queue.put({'key':'datasift', 'url': 'http://www.datasift.com', 'constraint': Constraint()}) # fwc.queue.put({'url': 'http://www.foundrygroup.com', 'constraint': Constraint()}) # fwc.queue.put({'url': 'http://www.avc.com', 'constraint': Constraint()}) fwc.start() fwc.join() with open(args.output[0], "wt") as s: yaml.dump(fwc.collection, s, default_flow_style=False)
def __init__(self, h5n): self._h5n = h5n # type: H5Nastran self.constraint = Constraint(self._h5n, self) # self.contact = Contact(self.h5n, self) self.coordinate_system = CoordinateSystem(self._h5n, self) self.design = Design(self._h5n, self) # self.domains = None self.dynamic = Dynamic(self._h5n, self) self.element = Element(self._h5n, self) # self.fatigue = None self.load = Load(self._h5n, self) self.material = Material(self._h5n, self) # self.matrix = None # self.modules = None self.node = Node(self._h5n, self) self.parameter = Parameter(self._h5n, self) # self.partition = None self.property = Property(self._h5n, self) self.table = Table(self._h5n, self)