def __init__(self, planning_problem, number_stages=2): prob_domain = planning_problem.prob_domain initial_state = planning_problem.initial_state goal = planning_problem.goal self.act_vars = [st('action',stage) for stage in range(number_stages)] domains = {av:prob_domain.actions for av in self.act_vars} domains.update({ st(var,stage):dom for (var,dom) in prob_domain.feats_vals.items() for stage in range(number_stages+1)}) # initial state constraints: constraints = [Constraint((st(var,0),), is_(val)) for (var,val) in initial_state.items()] # goal constraints on the final state: constraints += [Constraint((st(var,number_stages),), is_(val)) for (var,val) in goal.items()] # precondition constraints: constraints += [Constraint((st(var,stage), st('action',stage)), if_(val,act)) # st(var,stage)==val if st('action',stage)=act for act,strps in prob_domain.strips_map.items() for var,val in strps.preconditions.items() for stage in range(number_stages)] # effect constraints: constraints += [Constraint((st(var,stage+1), st('action',stage)), if_(val,act)) # st(var,stage+1)==val if st('action',stage)==act for act,strps in prob_domain.strips_map.items() for var,val in strps.effects.items() for stage in range(number_stages)] # frame constraints: constraints += [Constraint((st(var,stage), st('action',stage), st(var,stage+1)), eq_if_not_in_({act for act in prob_domain.actions if var in prob_domain.strips_map[act].effects})) for var in prob_domain.feats_vals for stage in range(number_stages) ] CSP.__init__(self, domains, constraints)
def creat_constraint(self, constraint): constraint = constraint.split(' ') if constraint[1] == 'before': self.constraints.append( Constraint((constraint[0], constraint[2]), before)) elif constraint[1] == 'same-day': self.constraints.append( Constraint((constraint[0], constraint[2]), same_day)) elif constraint[1] == 'one-day-between': self.constraints.append( Constraint((constraint[0], constraint[2]), one_day_between)) elif constraint[1] == 'one-hour-between': self.constraints.append( Constraint((constraint[0], constraint[2]), one_hour_between)) return
def get_binary_constraints_from_lines(lines): binary_constraints = list() for line in lines: match = search(r"^constraint, (?P<t1>\S*) (?P<type>\S*) (?P<t2>\S*)", line) if match is not None: t1 = match.group("t1") binary_constraint_type = match.group("type") t2 = match.group("t2") if binary_constraint_type == "before": scope = (t1, t2) condition = lambda t1, t2: t1.finish_time <= t2.start_time elif binary_constraint_type == "after": scope = (t1, t2) condition = lambda t1, t2: t1.start_time >= t2.finish_time elif binary_constraint_type == "same-day": scope = (t1, t2) condition = lambda t1, t2: t1.start_time.day == t2.start_time.day elif binary_constraint_type == "starts-at": scope = (t1, t2) condition = lambda t1, t2: t1.start_time.day == t2.finish_time.day and t1.start_time.hour == t2.finish_time.hour else: exit("Invalid binary constraint") binary_constraints.append(Constraint(scope, condition)) return binary_constraints
def get_range_hour_domain_constraint(match): t = match.group("t") scope = (t, ) constraint_type = match.group("type") required_hour = hours_of_day[match.group("hour")] if constraint_type == "starts-before": condition = lambda t: t.start_time.hour <= required_hour elif constraint_type == "ends-before": condition = lambda t: t.finish_time.hour <= required_hour elif constraint_type == "starts-after": condition = lambda t: t.start_time.hour >= required_hour elif constraint_type == "ends-after": condition = lambda t: t.finish_time.hour >= required_hour else: exit("Invalid hard domain constraint (starts/ends before/after hour)") return Constraint(scope, condition)
def get_range_day_hour_constraint(match): t = match.group("t") scope = (t, ) constraint_type = match.group("type") required_day = days_in_week[match.group("day")] required_hour = hours_of_day[match.group("hour")] required_time = Time(required_day, required_hour) if constraint_type == "starts-before": condition = lambda t: t.start_time <= required_time elif constraint_type == "starts-after": condition = lambda t: t.start_time >= required_time elif constraint_type == "ends-before": condition = lambda t: t.finish_time <= required_time elif constraint_type == "ends-after": condition = lambda t: t.finish_time >= required_time else: exit("Invalid hard domain constraint (starts/ends before/after)") return Constraint(scope, condition)
def get_day_hour_to_day_hour_constraint(match): t = match.group("t") scope = (t, ) constraint_type = match.group("type") # required begin time required_begin_day = days_in_week[match.group("start_day")] required_begin_hour = hours_of_day[match.group("start_hour")] required_begin_time = Time(required_begin_day, required_begin_hour) # required end time required_end_day = days_in_week[match.group("finish_day")] required_end_hour = hours_of_day[match.group("finish_hour")] required_end_time = Time(required_end_day, required_end_hour) if constraint_type == "starts-in": condition = lambda t: t.start_time >= required_begin_time and t.start_time <= required_end_time elif constraint_type == "ends-in": condition = lambda t: t.finish_time >= required_begin_time and t.finish_time <= required_end_time else: exit("Invalid hard domain constraint (from day-hour to day-hour)") return Constraint(scope, condition)
def get_at_hour_constraint(match): t = match.group("t") scope = (t, ) condition = lambda t: t.start_time.hour == hours_of_day[match.group("hour") ] return Constraint(scope, condition)
def get_at_day_constraint(match): t = match.group("t") scope = (t, ) condition = lambda t: t.start_time.day == days_in_week[match.group("day")] return Constraint(scope, condition)
task_domain[task] = sorted(set((x, x + duration) for x in di)) # get binary constraints if 'binary' in line: for line in file: if '#' in line: break line = line.strip() line = line.replace(',', '') line = line.split(' ') # print(line) t1 = line[1] t2 = line[3] if line[2] == 'before': # print('hhhhhhhh') hard_constraint.append(Constraint((t1, t2), binary_before)) if line[2] == 'after': pass if line[2] == 'same-day': hard_constraint.append(Constraint((t1, t2), binary_same_day)) if line[2] == 'starts-at': pass # get hard fomain if 'domain' in line: for line in file: if '#' in line: break
def is_(val): """is a value""" # isv = lambda x: x == val # alternative definition # isv = partial(eq,val) # another alternative definition def isv(x): return val == x isv.__name__ = str(val) + "==" return isv csp0 = CSP({'X': {1, 2, 3}, 'Y': {1, 2, 3}, 'Z': {1, 2, 3}}, [Constraint(('X', 'Y'), lt), Constraint(('Y', 'Z'), lt)]) C0 = Constraint(('A', 'B'), lt) C1 = Constraint(('B',), ne_(2)) C2 = Constraint(('B', 'C'), lt) csp1 = CSP({'A': {1, 2, 3, 4}, 'B': {1, 2, 3, 4}, 'C': {1, 2, 3, 4}}, [C0, C1, C2]) csp2 = CSP({'A': {1, 2, 3, 4}, 'B': {1, 2, 3, 4}, 'C': {1, 2, 3, 4}, 'D': {1, 2, 3, 4}, 'E': {1, 2, 3, 4}}, [Constraint(('B',), ne_(3)), Constraint(('C',), ne_(2)), Constraint(('A', 'B'), ne), Constraint(('B', 'C'), ne), Constraint(('C', 'D'), lt),
for d in del_list_wed: if d in cur: cur.remove(d) for d in del_list_thu: if d in cur: cur.remove(d) for d in del_list_fri: if d in cur: cur.remove(d) domain_fs[b[0]] = set(cur) elif (i[0] == 'constraint'): b = i[1].strip(" ").split(" ") test_cons.append(((b[0], b[-1]), before)) if b[1] == 'before': cons.append(Constraint((b[0], b[-1]), before)) if b[1] == 'same-day': cons.append(Constraint((b[0], b[-1]), same_day)) if b[1] == 'after': cons.append(Constraint((b[0], b[-1]), after)) if b[1] == 'starts-at': cons.append(Constraint((b[0], b[-1]), starts_at)) fuzzyScheduler = CSP_1(domain_fs, cons, task) solution = Con_solver(fuzzyScheduler).solve_one() if solution: cost = 0 for i in solution: if 'soft' in task[i]: if solution[i] + task[i]['duration'] < task[i]['soft']:
#print(line) task_duration[line[1]] = int(line[2]) di = set() duration = int(line[2]) for item in domain: if item % 10 + duration <= 9: di.add(item) task_domain[line[1]] = set((x, x + duration) for x in di) # get binary constraint elif line[0]=='constraint': #print(line) t1 = line[1] t2 = line[-1] if 'before' in line: hard_constraint.append(Constraint((t1,t2),binary_before)) if 'after' in line: hard_constraint.append(Constraint((t1,t2),binary_after)) if 'same' in line: hard_constraint.append(Constraint((t1,t2),binary_same_day)) if 'starts' in line: hard_constraint.append(Constraint((t1,t2),binary_starts_at)) # get soft constraint elif (line[0]=='domain') and (line[-1] not in week_to_num) and (line[-1] not in time_to_num): #print(line) task = line[1] day = week_to_num[line[4]] time = time_to_num[line[5]] soft_cost[task]=int(line[-1]) soft_constraint[task]=day*10+time # get hard constraint
(xA, yA) = A (xB, yB) = B return abs(xA - xB) <= 1 and abs(yA - yB) <= 1 def not_close(A, B): return not close(A, B) A = 'house' B = 'hotel' C = 'rec' D = 'garbage' CEM = 'cem' LAKE = 'lake' # stuff not at each other Ca = Constraint((A, B), ne) Cb = Constraint((A, C), ne) Cc = Constraint((A, D), ne) Cd = Constraint((B, C), ne) Ce = Constraint((B, D), ne) Cf = Constraint((C, D), ne) # house hotel not close cemetery C0a = Constraint((A, CEM), not_close) C0b = Constraint((B, CEM), not_close) # rec close to lake C1 = Constraint((C, LAKE), close) # house hotel close rec C2a = Constraint((A, C), close)
"""is a value""" # isv = lambda x: x == val # alternative definition # isv = partial(eq,val) # another alternative definition def isv(x): return val == x isv.__name__ = str(val) + "==" return isv csp0 = CSP({ 'X': {1, 2, 3}, 'Y': {1, 2, 3}, 'Z': {1, 2, 3} }, [Constraint(['X', 'Y'], lt), Constraint(['Y', 'Z'], lt)]) C0 = Constraint(['A', 'B'], lt, "A < B") C1 = Constraint(['B'], ne_(2), "B != 2") C2 = Constraint(['B', 'C'], lt, "B < C") csp1 = CSP({ 'A': {1, 2, 3, 4}, 'B': {1, 2, 3, 4}, 'C': {1, 2, 3, 4} }, [C0, C1, C2], positions={ "A": (1, 0), "B": (3, 0), "C": (5, 0), "A < B": (2, 1),
print("late week") elif newDomain[1] == "early-morning,": print("early Morning") newDomain = [] elif newDomain[1] == "midday": print("midday") elif newDomain[1] == "late-afternoon,": print("lateAfternoon") constraintList = [] from constraint import sameDay, oneDayBetween, oneHourBetween, before for constraint in constraints: if constraint[1] == "before": C = Constraint((constraint[0], constraint[2]), before) elif constraint[1] == "same-day": C = Constraint((constraint[0], constraint[2]), sameDay) elif constraint[1] == "one-day-between": C = Constraint((constraint[0], constraint[2]), oneDayBetween) elif constraint[1] == "one-hour-between": C = Constraint((constraint[0], constraint[2]), oneHourBetween) constraintList.append(C) csp1 = CSP(newmeetingsDict, constraintList) from operator import lt, ne, eq, gt from cspExamples import test, ne_ from searchGeneric import Searcher, AStarSearcher #Applying AStar search on it? from display import Displayable, visualize from cspConsistency import Search_with_AC_from_CSP, ac_search_solver
# deal with valid line and distribute them into task, all constraints and soft constraints for line in temp_list: # print(line) if "task," in line: # print(line[1]) task[line[1]] = value_domain(int(line[-1])) # soft constraints elif "ends-by" in line: t = (Date[line[3]], Time[line[4]]) cost_unit[line[1]] = line[-1] soft_cons.append([line[1], t, line[-1]]) # binary constraints of cons elif "constraint," in line: if "before" in line: cons.append(Constraint((line[1], line[3]), before)) elif "after" in line: cons.append(Constraint((line[1], line[3]), after)) elif "same-day" in line: cons.append(Constraint((line[1], line[3]), same_day)) elif "starts-at" in line: cons.append(Constraint((line[1], line[3]), start_at)) # hard domain constraints elif "domain," in line: if len(line) == 3 and line[-1] in Date: date = Date[line[-1]] cons.append(Constraint((line[1], ), on_(date))) elif len(line) == 3 and line[-1] in Time: time = Time[line[-1]] cons.append(Constraint((line[1], ), at_(time))) elif "starts-before" in line and len(line) == 5:
def fulfil_afternoon(meeting): for domain in meetings[meeting][:]: if "pm" not in domain[2:]: meetings[meeting].remove(domain) with open("sample.txt") as file: for line in file: #Split file into lines request = [] for word in line.split(" "): request.append(word.rstrip(",")) if request[0] == "meeting": meetings[request[1].rstrip("\n")] = domains.copy() if request[0] == "constraint": if request[2] == "before": constraint = Constraint((request[1], request[-1].strip()), before) constraints.append(constraint) if request[2] == "same-day": constraint = Constraint((request[1], request[-1].strip()), same_day) constraints.append(constraint) if request[2] == "one-day-between": constraint = Constraint((request[1], request[-1].strip()), one_day_between) constraints.append(constraint) if request[2] == "one-hour-between": constraint = Constraint((request[1], request[-1].strip()), one_hour_between) constraints.append(constraint) if request[0] == "domain": if request[-1].rstrip("\n") == "hard":
# new method to find the binary constraints and domain constraint and soft const. # the old method is in the last of the code, this one is much more simple. # I check the csp examples code, in class constraints, there is a range list and a relation in it. # so I init a scope contain two task name, and relation contain the Size relationship of two tasks. file = open(filename, 'r', encoding='utf-8') for line in file: line = line_process(line) # get the task name and fill in scope # this step is to get binary const if line[0] == 'constraint': scope = (line[1], line[3]) if line[2] == 'before': # if t1 before t2, in here, I use lambda function to let t1.end_time <= t2.start_time hard_constraints_list.append(Constraint(scope, before_compare)) elif line[2] == 'same-day': hard_constraints_list.append(Constraint(scope, same_day_compare)) elif line[2] == 'after': hard_constraints_list.append(Constraint(scope, after_compare)) elif line[2] == 'starts-at': temp = starts_at_compare(scope[0], scope[1]) hard_constraints_list.append(Constraint(scope, starts_at_compare)) # get the domain constraints if line[0] == 'domain' and line[2] != 'ends-by': check = line[2] if line[2] in workday: scope = (line[1], ) hard_const_day = workday[line[2]] hard_constraints_list.append(
my_content.append(line) # when read tasks for line in my_content: if "task" in line: data = line.strip().split(' ') variables.append((data[1], int(data[2]))) # when read binary constraints for line in my_content: if "constraint" in line: data = line.strip().split(' ') scope = (data[1], data[3]) if data[2] == "before": condition = bc_before constraints.append(Constraint(scope, bc_before)) if data[2] == "after": condition = bc_after constraints.append(Constraint(scope, condition)) if data[2] == "same-day": condition = bc_same_day constraints.append(Constraint(scope, condition)) if data[2] == "starts-at": condition = bc_starts_at constraints.append(Constraint(scope, condition)) # when read soft constraints and unary constraints for line in my_content: if "domain" in line: data = line.strip().split(' ') if data[2] == "ends-by": # read soft constraints
domain = set() for i in range(11, 60): if not i % 10 == 0: domain.add(i) for t in task: time = [] for i in domain: if i % 10 + int(task[t]) <= 9: time.append((i, i + int(task[t]))) task_domain[t] = sorted(time) if len(line) == 4 and 'constraint' in line: l1 = line[1] l2 = line[3] if line[2] == 'before': hard_domain.append(Constraint((l1, l2), before)) elif line[2] == 'after': hard_domain.append(Constraint((l1, l2), after)) elif line[2] == 'same-day': hard_domain.append(Constraint((l1, l2), same_day)) elif line[2] == 'starts-at': hard_domain.append(Constraint((l1, l2), starts_at)) if 'domain' in line: if len(line) == 3: t = line[1] s = line[2] if s in dayn: dd = dayn[s] hard_domain.append(Constraint((t, ), start_day(dd))) if s in timen:
line = line[:line.index('#')] line = list(map(lambda x: x.strip(), line.split(','))) # task and duration if line[0] == "task": task, dur = line[1].split() # creating domains dictionary domains[task] = set(range(len(working_days) * len(working_hours))) # creating duration dictionary duration[task] = int(dur) # binary constraint elif line[0] == "constraint": t1, c, t2 = line[1].split() c = c.replace('-', '_') b = c + "('" + t1 + "','" + t2 + "')" # creating constraints list constraints.append(Constraint((t1.strip(), t2.strip()), eval(b))) # hard domain constraints elif line[0] == "domain": task = line[1].split()[0] # soft deadline constraints if line[1].split()[-1].isdigit(): for t in domains[task]: soft_constraint(task, t, line[1].split()[1:]) # hard constraints else: domains[task] = domains[task] & set( domain_num(' '.join(line[-1].split()[1:]))) fp.close() for k in domains.keys():
(TaskStartTime, TaskStartTime + duration) for TaskStartTime in CertainDaySchedule) # will give result like {'t1': {(14, 17), (21, 24)},'t2': {(24, 26), (26, 28)}.....}until all domains((timeStart , TimeEnd)of all tasks has been added into the TaskDict} #print(TaskDictionary) # elif read binary constraints elif input[0] == 'constraint': t1 = input[1] t2 = input[-1] #print(t1) #eg: 'constraint, t1 before t2' # import from cspProblem.py ,we use class Constraint(object) # A Constraint consists of * scope: a tuple of variables and # * condition: a function that can applied to a tuple of values for the variables if 'before' in input: HardConstraintsList.append(Constraint((t1, t2), ConsBefore)) if 'same' in input: HardConstraintsList.append(Constraint((t1, t2), ConsSameDay)) if 'after' in input: HardConstraintsList.append(Constraint((t1, t2), ConsAfter)) if 'starts' in input: HardConstraintsList.append(Constraint((t1, t2), ConsStartsAt)) # elif read soft deadliine constraints #domain, <t>, ends, by, <WeekdayValue>, <TimeValue>, <cost> # cost per hour of missing deadline elif (input[0] == 'domain') and (input[-2] in TimeDict): #soft deadline constaints is in the above format #print(input) #['domain', 't1', 'ends', 'by', 'mon', '3pm', '10'] taskNum = input[1] #get value from dict of weekdict and timedict