Example #1
0
    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
Example #2
0
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
Example #3
0
 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']))
Example #5
0
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
Example #6
0
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
Example #7
0
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)
Example #8
0
 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
Example #9
0
    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)
Example #10
0
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 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)
Example #12
0
    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)
Example #13
0
    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)
Example #15
0
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 generate_preferred_constraint(activity, interval_list):
    return Constraint(constraint_type=ConstraintUtil.CONSTRAINT_PREFERRED,
                      costs=costs,
                      activity=activity,
                      preferred=interval_list)
def generate_excluded_constraint(activity, interval_list):
    return Constraint(constraint_type=ConstraintUtil.CONSTRAINT_EXCLUSIVE,
                      costs=costs,
                      activity=activity,
                      excluded=interval_list)
Example #18
0
 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']))
Example #19
0
 def generate_constraints(self):
     for pair in self.constraint_pairs:
         self.constraints.append(
             Constraint(pair, self.legal_constraint_values))
Example #20
0
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'])
Example #22
0
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
Example #23
0
def create_constraints_edges_squares():
    return Constraint(lambda v, neigh_list , graph: v.variable.value not in neigh_list)