def __init__(self, tts): self.tts = tts self.resetViolations() back_constraint = Constraint(self.isCorrectBack, self.backToleranceExceeded) lowerleg_constraint = Constraint(self.isLowerLegStraight, self.lowerLegToleranceExceeded) knee_constraint = Constraint(self.isCorrectKnee, self.kneeToleranceExceeded) self.constraints = [back_constraint, lowerleg_constraint] statesList = self.getStates() super(Squats, self).__init__(statesList, tts, "Squats") self.RESTANGLE_KNEE = 80 self.RESTANGLE_BACK = 80 self.RESTTHIGHANGLE = 80 self.MAXFRONTTHIGHANGLE = 85 self.ACTIVETHIGHANGLE = 20 self.CONCENTRICTHIGHANGLE = 70 self.ECCENTRICTHIGHANGLE = 30 self.MAXBACKVIOLATIONS = 5 self.MAXLOWERLEGVIOLATIONS = 5 self.MAXKNEEVIOLATIONS = 1 self.MINBACKANGLE = 50 self.MINKNEEANGLE = 50
def BinRelVec(filtered, func_ent): binRelVec = {"In", "Orthogonal"} operations = {"+", "=", "-"} constraints = [] for i, ent in enumerate(filtered): if type(ent) is VarDecl or type(ent) is int: continue if ent[1] in binRelVec: c = Constraint() c.func = ent[1] vec, space = find2PrevVarDecl(filtered[:i]) c.args.append(vec) c.args.append(space) constraints.append(c) if ent[0] in binRelVec: c = Constraint() c.func = ent[0] vec1, vec2 = find2PrevVarDecl(filtered[:i]) c.args.append(vec1) c.args.append(vec2) constraints.append(c) if ent[0] in operations: if ent[0]=="=": #exp = s1 + s2 exp = findPrevVarDecl(filtered[:i]) s1, s2 = findNext2VarDecl(filtered[i+1:]) c = Constraint() c.func = "Sum" c.args = [exp, s1, s2] constraints.append(c) return constraints
def __init__( self, evaluator=None, tag='cieq', sense='<', edge=0.0, scale=1.0, variables=None): Constraint.__init__(self,evaluator, tag,sense,edge, scale,variables)
def __init__(self, assignment_length, domain_length, constraints): self.fails = 0 self.assignment = [] # array of ints self.assignment_length = assignment_length # int corresponding to number of variables # set to none and of proper size for i in range(assignment_length): self.assignment.append(None) self.domain_length = domain_length # int corresponding to number of entries in domain self.constraints = Constraint(constraints)
def __init__(self, tts): self.tts = tts self.resetViolations() self.constraints = [ Constraint(self.isCorrectElbow, self.elbowToleranceExceeded), Constraint(self.isCorrectBack, self.backToleranceExceeded) ] statesList = self.getStates() super(BicepCurl, self).__init__(statesList, tts, "bicepCurl") self.RESTANGLE = 150 self.CONCENTRICANGLE = 140 self.ACTIVEANGLE = 55 self.ECCENTRICANGLE = 65 self.MAXELBOWVIOLATIONS = 5 self.MAXBACKVIOLATIONS = 3
def generate_strict_constraint(activity: Activity, interval): return Constraint(constraint_type=ConstraintUtil.CONSTRAINT_EXACT, costs=costs, activity=activity, strict_interval=TimeInterval(interval['start'], interval['end'], interval['day']))
def getConstraintsFromFile(constraintFileName): constraints = [] constraintFile = open(constraintFileName) #parse the constraint file. Each line is a new constraint, for example A = B, or B > C lines = constraintFile.readlines() for line in lines: #tokenize the line tokens = line.split() #grab the first token, it's a variable name var1 = tokens.pop(0) #grab the second token, it's an operator =, !, >, or < operator = tokens.pop(0) #grab the last token, it's another variable name var2 = tokens.pop(0) #now let's take that stuff we just extracted from the line and make a constraint out of it constraint = Constraint(var1, operator, var2) #add that constraint to the list constraints.append(constraint) constraintFile.close() return constraints
def generate_problem(prob): """ generate the problem from various parameters. """ var_list = [ Variable(type_of_var[i], [my_bounds[0][i], my_bounds[1][i]], 'x%d' % (i + 1)) for i in range(len(my_obj.coefficient)) ] var_names = [var_list[i].name for i in range(len(var_list))] constraints = [ Constraint('c%d' % (i + 1), rows[i][1], relation[i], right_side[i]) for i in range(len(rows)) ] row_names = [constraints[i].name for i in range(len(constraints))] if my_obj.preference == 'min': prob.objective.set_sense(prob.objective.sense.minimize) elif my_obj.preference == 'max': prob.objective.set_sense(prob.objective.sense.maximize) else: print('You had input the wrong objective preference!') prob.variables.add(obj=my_obj.coefficient, lb=my_bounds[0], ub=my_bounds[1], names=var_names, types=type_of_var) prob.linear_constraints.add(lin_expr=rows, senses=relation, rhs=right_side, names=row_names) return var_list, constraints
def build_constraint(n, d, node, node_xml): expressions = [] raw_expressions = check_attribute(node_xml, "expressions", True) raw_expressions = raw_expressions.split(";") for e in raw_expressions: expressions.append(misc.remove_starting_and_ending_space(e)) types = [] raw_constraint_types = check_attribute(node_xml, "types", False) if raw_constraint_types is not None: raw_constraint_types = raw_constraint_types.split(";") for c in raw_constraint_types: c = misc.remove_starting_and_ending_space(c) if c in ["forall", "exist", "unique"]: types.append(c) else: misc.error( "Xml::__build_constraint() -> unknown constraint type \"" + c + "\"") raise NameError quantifiers = [] raw_quantifiers = check_attribute(node_xml, "quantifiers", False) if raw_quantifiers is not None: raw_quantifiers = raw_quantifiers.split(";") for l in raw_quantifiers: l = misc.remove_starting_and_ending_space(l) if misc.check_letter(l, True): quantifiers.append(l) ranges = [] raw_ranges = check_attribute(node_xml, "ranges", False) if raw_ranges is not None: raw_ranges = raw_ranges.split(";") for r in raw_ranges: r = misc.remove_starting_and_ending_space(r) if r == "all": ranges.append(r) elif r[0] is "[" and r[-1] is "]": boundaries = r[1:-1].split(",") if len(boundaries) != 2: misc.error( "Xml::build_constraint() -> wrong ranges syntax") raise ValueError ranges.append( (misc.remove_starting_and_ending_space(boundaries[0]), misc.remove_starting_and_ending_space(boundaries[1]))) else: misc.error("Xml::build_constraint() -> wrong ranges syntax") raise ValueError if len(quantifiers) != len(ranges) or len(quantifiers) != len(types): misc.error( "Xml::build_constraint() -> the number of quantifiers must equal the number of ranges and types" ) raise ValueError return Constraint(n, d, node, expressions, types, quantifiers, ranges)
def function(self, x): edg = self.edge scl = self.scale result = Constraint.function(self, x) result = result - edg / scl return result
def function(self,x): edg = self.edge scl = self.scale result = Constraint.function(self,x) result = result - edg/scl return result
def __init__(self, tts): self.tts = tts self.constraints = [ Constraint(self.isCorrectBack, self.toleranceExceeded) ] statesList = self.getStates() super(Pushup, self).__init__(statesList, tts, "pushup") self.RESTHANDANGLE = 160 self.RESTBACKANGLE = 160 self.CONCENTRICANGLE = 140 self.ACTIVEHANDANGLE = 65 self.ECCENTRICHANDANGLE = 75
def generate_distance_constraint(activity, content): factor = { 'minute': 1, 'hour': 60, 'day': 24 * 60, }[content['unit']] return Constraint(constraint_type=ConstraintUtil.CONSTRAINT_DISTANCE, costs=costs, activity=activity, relative_activity=content['activity_type'] if content['activity_type'] != 'self' else activity.name, distance_from=content['value'] * factor)
def gradient(self,x): snz = self.sense result = Constraint.gradient(self,x) if snz == '>': result = -1 * result elif snz == '<': result = +1 * result else: raise Exception, 'unrecognized sense %s' % snz return result
def function(self,x): snz = self.sense edg = self.edge scl = self.scale result = Constraint.function(self,x) if snz == '>': result = edg/scl - result elif snz == '<': result = result - edg/scl else: raise Exception, 'unrecognized sense %s' % snz return result
def generate_constraint(self, constraint_pair): piece1 = self.variables[constraint_pair[0]] piece2 = self.variables[constraint_pair[1]] domain1 = self.domains[constraint_pair[0]] domain2 = self.domains[constraint_pair[1]] legal_values = [] for pos1 in domain1: for pos2 in domain2: if pos1 != pos2: if not self.overlap(piece1, pos1, piece2, pos2): legal_values.append((pos1, pos2)) return Constraint(constraint_pair, legal_values)
def genConstraints(self): print "Generating Constraints" self.constraints = [] index = 0 shared = self.config.sharedSites for x in xrange(0, len(shared)): loc = shared[x] owners = [] for line in self.config.lines: if line.isShared(loc) != False: owners.extend(line.getOwners()) j = self.config.T while j >= 0: start = j if (j - self.config.repeatKTimeSteps) >= 0: end = j - self.config.repeatKTimeSteps else: end = 0 arr = [] for e in self.events: if (e.agent in owners and e.site == loc and e.startTime <= start and e.startTimeEnd >= end): arr.append(e) if (len(arr) >= 1): c = Constraint( arr, self.config.creward[x], index, "At least one agent inspect " + str(loc) + " between " + str(start) + " - " + str(end)) index += 1 self.constraints.append(c) j -= self.config.repeatKTimeSteps print
def generate_relative_constraint(activity: Activity, parsed_activity): direction = -1 for item in parsed_activity: if item == 'after': direction = item break if item == 'before': direction = item break factor = { 'minute': 1, 'hour': 60, 'day': 24 * 60, }[parsed_activity[direction]['relative_within']['unit']] return Constraint( constraint_type=ConstraintUtil.CONSTRAINT_RELATIVE, costs=costs, activity=activity, relative_activity_direction=map_relative_activity_direction(direction), relative_activity=parsed_activity[direction]['activity_type'], distance_from=parsed_activity[direction]['relative_within']['value'] * factor)
def BinRelFunc(filtered, func_ent): binRelFunc = {"Injection", "Surjection", "Bijection"} # function contraint eg. Injection(f) fconstraint = Constraint() # Bin rel constraint eg. From(f, A, B) tconstraint = Constraint() for i, ent in enumerate(filtered): if type(ent) is VarDecl or type(ent) is int: continue if ent[0] in binRelFunc: fconstraint.func = ent[0] fconstraint.args.append(func_ent) elif ent[1] == "From": fromSet = findNextVarDecl(filtered[i:]) tconstraint.func = "From" tconstraint.args.append(func_ent) tconstraint.args.append(fromSet) elif ent[1] == "To": to = findNextVarDecl(filtered[i:]) tconstraint.args.append(to) return [fconstraint, tconstraint]
def gradient(self,x): result = Constraint.gradient(self,x) return result
def generate_preferred_constraint(activity, interval_list): return Constraint(constraint_type=ConstraintUtil.CONSTRAINT_PREFERRED, costs=costs, activity=activity, preferred=interval_list)
def get_problem(location): """ use the parameters to generate the content such as distance matrix,decision variables,rows and etc. """ num_of_customers = len(location) - 1 cus_depot = len(location) # # manhatten distance # for i in range(len(location)): # for j in range(len(location)): # distance[i,j] = abs(location[i][0]-location[j][0])+abs(location[i][1]-location[j][1]) # euclidean distance distance = np.zeros((cus_depot, cus_depot), dtype=np.int32) for i in range(len(location)): for j in range(len(location)): distance[i, j] = ((location[i][0] - location[j][0])**2 + (location[i][1] - location[j][1])**2)**0.5 decision_variables = [] for i in range(num_of_customers + 1): decision_variables.append([]) for j in range(num_of_customers + 1): decision_variables[i].append( Variable('I', [0, 1], 'x%d%d' % (i, j))) for i in range(num_of_customers + 1): decision_variables[0][i]['upper_bound'] = 2.0 variables_1dim = [] rel = np.zeros((cus_depot, cus_depot), dtype=np.int16) x = 0 dist_1dim = [] mapping = dict( ) # get a dict like : mapping = {(0,1):0,(0,2):1,(0,3):2 ...} ind1 = [] # ind1 each customer has remain decision_variables list_customer = list(range(cus_depot)) for i in range(cus_depot): ind1.append(num_of_customers - i) for i in range(cus_depot): for j in range(ind1[i]): variables_1dim.append(decision_variables[i][i + j + 1]) dist_1dim.append(float(distance[i][i + j + 1])) rel[i][i + j + 1] = x mapping[(i, i + j + 1)] = x x += 1 # for customer i # m<i,give x_mi # m>i give x_im m\in {0,1,...,5} rows1 = [] for i in range(num_of_customers): rows1.append([]) for j in range(2): rows1[i].append([]) for i in range(1, cus_depot): list_cur = copy.deepcopy(list_customer) list_cur.remove(i) for j in list_cur: if j < i: rows1[i - 1][0].append(mapping[(j, i)]) rows1[i - 1][1].append(1) else: rows1[i - 1][0].append(mapping[(i, j)]) rows1[i - 1][1].append(1) ''' [[['x01', 'x12', 'x13', 'x14', 'x15'], [1, 1, 1, 1, 1]], [['x02', 'x12', 'x23', 'x24', 'x25'], [1, 1, 1, 1, 1]], [['x03', 'x13', 'x23', 'x34', 'x35'], [1, 1, 1, 1, 1]], [['x04', 'x14', 'x24', 'x34', 'x45'], [1, 1, 1, 1, 1]], [['x05', 'x15', 'x25', 'x35', 'x45'], [1, 1, 1, 1, 1]]] transfer to variables_1dim and get: [['x0', 'x5', 'x6', 'x7', 'x8'], [1, 1, 1, 1, 1]] [['x1', 'x5', 'x9', 'x10', 'x11'], [1, 1, 1, 1, 1]] [['x2', 'x6', 'x9', 'x12', 'x13'], [1, 1, 1, 1, 1]] [['x3', 'x7', 'x10', 'x12', 'x14'], [1, 1, 1, 1, 1]] [['x4', 'x8', 'x11', 'x13', 'x14'], [1, 1, 1, 1, 1]] [['x0', 'x1', 'x2', 'x3', 'x4'], [1, 1, 1, 1, 1]] ''' # for depot0 : row2 = [[]] for i in range(2): row2[0].append([]) for i in range(num_of_customers): row2[0][0].append(i) row2[0][1].append(1) ''' [['x01', 'x02', 'x03', 'x04', 'x05'], [1, 1, 1, 1, 1]] ''' rows = rows1 + row2 my_obj = Objective('min', dist_1dim) right_side = [2.0] * num_of_customers right_side.append(2.0 * K) constraints = [ Constraint('c%d' % (i + 1), rows[i], 'E', right_side[i]) for i in range(len(rows)) ] relation = ['E'] * len(constraints) var_names = [ 'x%d' % (i + 1) for i in range(int(cus_depot * (cus_depot - 1) / 2)) ] row_names = ['c%d' % (i + 1) for i in range(cus_depot)] lowerbounds = [] upperbounds = [] var_types = [] for i in range(len(variables_1dim)): # lowerbounds.append(float(variables_1dim[i].lower_bound)) # upperbounds.append(float(variables_1dim[i].upper_bound)) lowerbounds.append(variables_1dim[i].lower_bound) upperbounds.append(variables_1dim[i].upper_bound) var_types.append(variables_1dim[i].type) lin_expression = [ cplex.SparsePair(ind=rows[i][0], val=rows[i][1]) for i in range(len(rows)) ] return dist_1dim, cus_depot, num_of_customers, my_obj, lowerbounds, upperbounds, var_types, var_names, lin_expression, row_names, relation, right_side, mapping
def generate_excluded_constraint(activity, interval_list): return Constraint(constraint_type=ConstraintUtil.CONSTRAINT_EXCLUSIVE, costs=costs, activity=activity, excluded=interval_list)
class ConstraintSatisfactionProblem: def __init__(self, assignment_length, domain_length, constraints): self.fails = 0 self.assignment = [] # array of ints self.assignment_length = assignment_length # int corresponding to number of variables # set to none and of proper size for i in range(assignment_length): self.assignment.append(None) self.domain_length = domain_length # int corresponding to number of entries in domain self.constraints = Constraint(constraints) # runs setup, then starts recursive backtrack search def backtrack_search(self, mrv, lcv, infer): # reset some necessary instance variables self.fails = 0 for i in range(self.assignment_length): self.assignment[i] = None # calls the recursive backtrack search self.backtrack_search_helper(mrv, lcv, infer, {}) # recursive backtrack search def backtrack_search_helper(self, mrv, lcv, infer, inconsistencies): print("Decided:", self.assignment) # base case: assignment is complete and valid if self.is_complete() and self.constraints.is_satisfied( self.assignment): return self.assignment # minimum remaining values heuristic if mrv: var = self.mrv_heuristic() else: var = self.no_variable_heuristic() # least constraining value heuristic if lcv: domain_list = self.lcv_heuristic(var) else: domain_list = [] for i in range(self.domain_length): domain_list.append(i) if infer: # find infer values if var in inconsistencies.keys(): for inconsistency in inconsistencies[var]: if inconsistency in domain_list: domain_list.remove( inconsistency) # don't consider inconsistencies #print("domain list: ", domain_list) for val in domain_list: self.assignment[var] = val print("trying val; ", val, ";", self.assignment, ";", self.constraints.is_satisfied(self.assignment)) if self.constraints.is_satisfied(self.assignment): if infer: inconsistencies = self.mac_infer( var) # find inconsistencies from inference #print(inconsistencies) if inconsistencies is not None: result = self.backtrack_search_helper( mrv, lcv, infer, inconsistencies) else: return None else: result = self.backtrack_search_helper( mrv, lcv, infer, inconsistencies) if result is not None: # potential value found, use it for previous recursive iteration return result else: # increment fails self.fails += 1 # backtracking self.assignment[var] = None # no solution, return None return None # checks to see if assignment is complete def is_complete(self): for i in range(self.assignment_length): if self.assignment[i] is None: return False return True # returns next variable def no_variable_heuristic(self): for i in range(self.assignment_length): if self.assignment[i] is None: return i #return range(i, self.assignment_length) return 0 # returns variable based on minimum remaining values def mrv_heuristic(self): min_remaining = (None, float('-inf')) # iterate through unassigned variables for i in range(self.assignment_length): if self.assignment[i] is None: temp = self.constraints.possible_count(self.assignment, i) # if more constraining than previous most constraining, it is the new most constraint if temp > min_remaining[1]: min_remaining = (i, temp) return min_remaining[0] # returns values based on least constrained value def lcv_heuristic(self, var): tuple_list = [] domain_list = [] # iterate through each possible value for i in range(self.domain_length): lc_val = self.constraints.constrain_count(self.assignment, var, i) #print("*", lc_val) # find correct index to insert j = 0 index = 0 while j < len(tuple_list): if tuple_list[j][1] < lc_val[1]: index += 1 j += 1 tuple_list.insert(index, lc_val) for i in range(len(tuple_list)): domain_list.append(tuple_list[i][0]) #print("domain list:",domain_list, "\n") return domain_list # mac-3 inference def mac_infer(self, var): # dictionary mapping unassigned var ints to set of values that they cannot be: inconsistencies = {} queue = [] # add all arcs with with one unassinged variables and given variable in them for initial in self.constraints.unassigned_neighbors( self.assignment, var): queue.append(initial) while queue: # iterate through arcs arc = queue.pop() temp = self.mac_revise(arc, inconsistencies) # occurs when no possible value for some variable, means this tree is bad if temp is None: return None # add inconsistencies if found inconsistencies[arc[0]] = temp #print("inconsistencies:", inconsistencies) return inconsistencies # determines if arc is an inconsistency def mac_revise(self, arc, inconsistencies): # set of all values var1 and var2 cannot be revised = set() if arc[0] in inconsistencies.keys(): revised = inconsistencies[arc[0]] constraints = self.constraints.get_constraints(arc[0], arc[1]) #print("constraints:",constraints) if constraints is None: return None # iterate through assignment, looking for inconsistencies for x in range(self.domain_length): cannot = 0 for y in range(self.domain_length): if (x, y) not in constraints: cannot += 1 if cannot == self.domain_length: revised.add(x) # no possible values, bad decision in past if len(revised) == self.domain_length: return None return revised
def getConstraintsFromCNF(cnf, constraintId, splotModel): clauseList = [clause.strip() for clause in cnf.split("or")] treeNodeIdList = [clause if (clause.find("~") == -1) else clause[1:] for clause in clauseList] return Constraint(constraintId, clauseList, treeNodeIdList, splotModel)
def create_constraints_edges_squares(): return Constraint(lambda v, neigh_list , graph: v.variable.value not in neigh_list)
def gradient(self, x): result = Constraint.gradient(self, x) return result
def create_constraint_queens(): return Constraint(constraint_queens)
def generate_instances_constraint(activity: Activity, parsed_activity): return Constraint(constraint_type=ConstraintUtil.CONSTRAINT_INSTANCES, costs=costs, activity=activity, instances_week=parsed_activity['instances_per_week'], instances_day=parsed_activity['instances_per_day'])
def setUp(self): self.simple_csp = CSProblem() self.simple_csp.domains['x'] = set([1, 2, 3, 4, 5]) self.simple_csp.domains['y'] = set([1, 2, 3, 4, 5]) self.simple_csp.constraints.append(Constraint(['x', 'y'], 'x > 2*y', ['x', 'y']))
def generate_constraints(self): for pair in self.constraint_pairs: self.constraints.append( Constraint(pair, self.legal_constraint_values))