def select_opt_method(self):
     print self.flag
     if self.flag==1:
         return optimization.hillclimb(self.domain,self.fetcher.cost_func)
     elif self.flag==2:
         return optimization.annealingoptimize(self.domain,self.fetcher.cost_func)
     elif self.flag==3:
         return optimization.geneticoptimize(self.domain,self.fetcher.cost_func)
     else:
         return optimization.randomoptimize(self.domain,self.fetcher.cost_func)
예제 #2
0
    def Last_process(self):
        self.Create_available_course_list()

        if self.v.get() == 0:
            solution_listt = optimization.hillclimb(self.domainn,
                                                    self.Cost_function)
            self.write_listbox(solution_listt)
        elif self.v.get() == 1:
            solution_listt = optimization.annealingoptimize(
                self.domainn, self.Cost_function)
            self.write_listbox(solution_listt)
        elif self.v.get() == 2:
            solution_listt = optimization.geneticoptimize(
                self.domainn, self.Cost_function)
            self.write_listbox(solution_listt)
        elif self.v.get() == 3:
            solution_listt = optimization.randomoptimize(
                self.domainn, self.Cost_function)
            self.write_listbox(solution_listt)
예제 #3
0
def testGenScale():
    data = wineset2()
    print crossvalidate(knnestimate, data)
    print crossvalidate(weightedknn, data)
    weighdomain = [(0, 20)] * 4
    costfunction = createcostfunction(knnestimate, data)

    #rating,age,aisle,bottlesize
    lenghuo_S = optimization.annealingoptimize(weighdomain,
                                               costfunction,
                                               step=2)
    print lenghuo_S
    lenghuo_data = rescale(data, lenghuo_S)
    print crossvalidate(knn3, lenghuo_data)

    climbHill_S = optimization.hillclimb(weighdomain, costfunction)
    print climbHill_S
    climbHill_data = rescale(data, climbHill_S)
    print crossvalidate(knn3, climbHill_data)
예제 #4
0
  def optimize(self):

    self.consumers = [[con.strip()] for con in self.consumers.split(',')]
    #append an empty list to each consumer to be filled by resources
    for consumer in self.consumers:
      consumer.append([]);

    #What a solution looks like:
    # [0,1,2,0,2,0,1,0,0,2,1,2,0,0,1,0,2,1,1,0,2,1,0...]
    #where each list slot represents a particular resource
    #from the resources list, and the value of a slot 
    #represents the consumer that resource is assigned to

    #What the domain looks like
    # [(0,2),(0,2),(0,2),(0,2),(0,2),(0,2),(0,2)...]

    domain = [(0,len(self.consumers)-1)] * len(self.resources)

    #Add up the total strength for each attribute possessed by a resource
    total_attr_strengths = []
    for a in range(0, len(self.resources[0]) - 1):
      total_attr_strengths.append(sum([r[a+1] for r in self.resources]))

    #Ideal attribute strength at each consumer.
    #This is simple right now becuase we're just dividing total
    #strengths by # of consumers.
    self.optimal_attr_strengths = []
    for a in range(0, len(total_attr_strengths)):
      self.optimal_attr_strengths.append(total_attr_strengths[a]/len(self.consumers))

    if self.algo == 'annealing':
      cost, sol = optimization.annealingoptimize(domain, self.provisioning_cost)
    elif self.algo == 'hillclimb':
      cost, sol = optimization.hillclimb(domain, self.provisioning_cost)
    elif self.algo == 'random':
      cost, sol = optimization.randomoptimize(domain, self.provisioning_cost)
    elif self.algo == 'genetic':
      cost, sol = optimization.geneticoptimize(domain, self.provisioning_cost)
    else:
      raise ValueError('Invalid algorithm')

    return cost, sol
예제 #5
0
    draw = ImageDraw.Draw(img)

    # 建立标识位置信息的字典
    pos = dict([(people[i], (sol[i * 2], sol[i * 2 + 1]))
                for i in range(0, len(people))])

    for (a, b) in links:
        draw.line((pos[a], pos[b]), fill=(255, 0, 0))

    for n, p in pos.items():
        draw.text(p, n, (0, 0, 0))

    img.show()


domain = [(10, 370)] * (len(people) * 2)  #设定题解范围

if __name__ == "__main__":  #只有在执行当前模块时才会运行此函数
    print(domain)
    s = optimization.randomoptimize(domain, crosscount)  # 随机搜索法,寻找最优题解
    print(s)
    drawnetwork(s)  # 绘制关系网
    s = optimization.hillclimb(domain, crosscount)  # 爬山法,寻找最优题解
    print(s)
    drawnetwork(s)  # 绘制关系网
    s = optimization.annealingoptimize(domain, crosscount)  # 模拟退火算法,寻找最优题解
    print(s)
    drawnetwork(s)  # 绘制关系网
    s = optimization.geneticoptimize(domain, crosscount)  # 遗传算法,寻找最优题解
    print(s)
    drawnetwork(s)  # 绘制关系网
예제 #6
0
s = [1, 4, 3, 2, 7, 3, 6, 3, 2, 4, 5, 3]
optimization.printschedule(s)

cost = optimization.schedulecost(s)
print('Present cost:%f' % cost)

print('\n<----Random Searching---->')
domain = [(0, 9)] * (len(optimization.people) * 2)
print(s)
s = optimization.randomoptimize(domain, optimization.schedulecost)
cost = optimization.schedulecost(s)
print('Present cost:%f' % cost)
optimization.printschedule(s)

print('\n<----Hill Climbing---->')
s = optimization.hillclimb(domain, optimization.schedulecost)
print(s)
cost = optimization.schedulecost(s)
print('Present cost:%f' % cost)
optimization.printschedule(s)

print('\n<----Simulated Annealing---->')
s = optimization.annealingoptimize(domain, optimization.schedulecost)
print(s)
cost = optimization.schedulecost(s)
print('Present cost:%f' % cost)
optimization.printschedule(s)

print('\n<----Genetic Algorithms---->')
s = optimization.geneticoptimize(domain, optimization.schedulecost)
print(s)
예제 #7
0
    # Loop over each student
    for i in range(len(vec)):
        x = int(vec[i])
        dorm = dorms[slots[x]]
        pref = prefs[i][1]
        # First choice costs 0, second choice costs 1
        if pref[0] == dorm:
            cost += 0
        elif pref[1] == dorm:
            cost += 1
        else:
            cost += 3
        # Not on the list costs 3

        # Remove selected slot
        del slots[x]
    #print(cost)
    return cost

print(domain)

s=optimization.randomoptimize(domain,dormcost)
printsolution(s)
s=optimization.hillclimb(domain,dormcost)
printsolution(s)
s=optimization.annealingoptimize(domain,dormcost)
printsolution(s)
s=optimization.geneticoptimize(domain,dormcost,elite=0.2)
printsolution(s)
예제 #8
0
# op.printschedule(s)
# print(op.schedulecost(s))
domain = [(0, 9)] * (len(op.people) * 2)
# s = op.randomoptimize(domain, op.schedulecost)
# s = op.hillclimb(domain, op.schedulecost)
# s = op.annealingoptimize(domain, op.schedulecost)
# s = op.geneticoptimize(domain, op.schedulecost)
# print(domain,s)
# print(op.schedulecost(s))
# op.printschedule(s)

result = {'rand': [], 'hill': [], 'anne': [], 'gene': []}
for i in range(10):
    s1 = op.randomoptimize(domain, op.schedulecost)
    result['rand'].append(op.schedulecost(s1))

    s2 = op.hillclimb(domain, op.schedulecost)
    result['hill'].append(op.schedulecost(s2))

    s3 = op.annealingoptimize(domain, op.schedulecost)
    result['anne'].append(op.schedulecost(s3))

    s4 = op.geneticoptimize(domain, op.schedulecost)
    result['gene'].append(op.schedulecost(s4))

print(result)
print('rand', sum(result['rand']) / 10, min(result['rand']))
print('hill', sum(result['hill']) / 10, min(result['hill']))
print('anne', sum(result['anne']) / 10, min(result['anne']))
print('gene', sum(result['gene']) / 10, min(result['gene']))
예제 #9
0
    # 遍历每一名学生
    for i in range(len(vec)):
        x = int(vec[i])
        dorm = dorms[slots[x]]
        pref = prefs[i][1]
        # 首选成本值为0,次选成本值为1
        if pref[0] == dorm: cost += 0
        elif pref[1] == dorm: cost += 1
        else: cost += 3
        # 不在选择之列则成本值为3

        # 删除选中的槽
        del slots[x]

    return cost


if __name__ == "__main__":  #只有在执行当前模块时才会运行此函数
    print(domain)
    s = optimization.randomoptimize(domain, dormcost)  # 随机搜索法,寻找最优题解
    print(s)
    printsolution(s)  # 打印最优解代表的含义
    s = optimization.hillclimb(domain, dormcost)  # 爬山法,寻找最优题解
    print(s)
    printsolution(s)  # 打印最优解代表的含义
    s = optimization.annealingoptimize(domain, dormcost)  # 模拟退火算法,寻找最优题解
    print(s)
    printsolution(s)  # 打印最优解代表的含义
    s = optimization.geneticoptimize(domain, dormcost)  # 遗传算法,寻找最优题解
    print(s)
    printsolution(s)  # 打印最优解代表的含义
예제 #10
0
#coding:gbk
'''
Created on 2015Äê8ÔÂ30ÈÕ

@author: fxy
'''
import socialnetwork
import optimization

sol = optimization.hillclimb(socialnetwork.domain, socialnetwork.crosscount)
print socialnetwork.crosscount(sol)
print sol
socialnetwork.drawNetWork(sol)
print "lll"
예제 #11
0
print op.schedulecost(s)
op.printschedule(s)
print 'running time',time.clock()-start
print

print 'random optimization:',
start = time.clock()
sol = op.randomoptimize(domain)
print op.schedulecost(sol)
op.printschedule(sol)
print 'running time',time.clock()-start
print

print 'hill climb:',
start = time.clock()
sol = op.hillclimb(domain)
print op.schedulecost(sol)
op.printschedule(sol)
print 'running time',time.clock()-start
print 

print 'annealing optimization:',
start = time.clock()
sol = op.annealingoptimize(domain)
print op.schedulecost(sol)
op.printschedule(sol)
print 'running time',time.clock()-start
print

print 'genetic optimization:',
start = time.clock()
예제 #12
0
    def Command_of_schedule_showing(self):
        if len(
                self.Course_code_shower.get(0, END)
        ) == 0:  #If there is no course code in listbox,program will show an error.
            self.Error_Message_Function(
                """Please First use the\nFetching Button""")
            return

        selections = map(int, self.Course_code_shower.curselection(
        ))  #Returning the list of indexes selected in the listbox
        all_course_types = self.Course_code_shower.get(0, END)
        selected_course_types = [all_course_types[i] for i in selections]

        if len(
                selected_course_types
        ) == 0:  #If demanded course codes is not selected,program will show an error.
            self.Error_Message_Function("""Please Select\nSome Course Code""")
            return
            #Returning the list of selected course codes.
        self.List_of_all_avaiable_courses = list()
        for course_types in selected_course_types:  #Creating a list of courses from the course code dictionary with adding lists togetgher.
            self.List_of_all_avaiable_courses.extend(
                self.Dictionary_of_course_codes[course_types])

        if len(
                self.Course_number_taker.get()
        ) == 0:  #If demanded course number is not provided,program will show an error.
            self.Error_Message_Function("""Please give\nCourse number""")
            return

        try:
            number_of_courses = int(self.Course_number_taker.get(
            ))  #Getting the demanded number of course from entry
        except:  #If it is not a number,program will comply.
            self.Error_Message_Function(
                """Please give\nCourse number\nproperlyas integer""")
            return

        if number_of_courses > len(
                self.List_of_all_avaiable_courses
        ):  #If demeanded course number exceed avaiable course number,there will be an error.
            self.Error_Message_Function(
                """These course codes\nhave insufficient course""")
            return
        self.domain = [(0, len(self.List_of_all_avaiable_courses) - i - 1)
                       for i in range(number_of_courses)]
        #Domain
        type_of_optimization = Optimization_Dictionary[self.Radio_Values.get()]
        #Type of optimization come from the dictionary.
        if type_of_optimization == "Hill Climbing":
            solution = optimization.hillclimb(self.domain,
                                              self.My_Cost_Function)

        elif type_of_optimization == "Simulated Annealing":
            solution = optimization.annealingoptimize(self.domain,
                                                      self.My_Cost_Function)

        elif type_of_optimization == "Genetic Optimization":
            if number_of_courses < 3:  #For genetic optimization,we need at least three course demand
                self.Error_Message_Function(
                    """Genetic Optimization is\n valid for \nmore than  3 courses"""
                )
                return
            solution = optimization.geneticoptimize(self.domain,
                                                    self.My_Cost_Function)

        elif type_of_optimization == "Random Optimization":
            solution = optimization.randomoptimize(self.domain,
                                                   self.My_Cost_Function)

        Last_Showing = self.My_Representation_function(
            solution
        )  #This returns a dictionary where keys are days and values will be list of tuple(time,course).
        self.Last_Showing_Part.delete(0.0, END)  #Deleting all the elements
        for days in Days_of_Week:  #List of days
            self.Last_Showing_Part.insert(END, days + ":\n")
            if days in Last_Showing:  #If day inside of dictionary, inserting all tuples in the list(value of day).
                for times, course in Last_Showing[days]:
                    self.Last_Showing_Part.insert(
                        END,
                        times + '(%s %s),' % (course.code, course.course_name))
            else:  #If day is not inside of the dictionary inserting no classes.
                self.Last_Showing_Part.insert(END, 'NO CLASSES')
            self.Last_Showing_Part.insert(END, '\n')
	# draw people
	for n,p in pos.items():
		draw.text(p, n, (0,0,0))

	img.show()


domain = [(10,370)] * (len(people)*2)

print '--- random ---'
s = optimization.randomoptimize(domain, crosscount)
print crosscount(s)
print s

print '--- hill climb ---'
s = optimization.hillclimb(domain, crosscount)
print crosscount(s)
print s

print '--- simulated annealing ---'
s = optimization.annealingoptimize(domain, crosscount)
print crosscount(s)
print s

print '--- genetic optimize ---'
gen = optimization.genetic()
s = gen.geneticoptimize(domain, crosscount)
print crosscount(s)
print s
drawnetwork(s)
예제 #14
0
        dorm = dorms[slots[student]]
        pref = prefs[i][1]
        if dorm == pref[0]: continue
        elif dorm == pref[1]: cost += 1
        else: cost += 3
        del slots[student]
    return cost


if __name__ == '__main__':
    sol = randomOptimize(domain, dormCost)
    print 'RandomOptimize'
    print 'Cost: ', dormCost(sol)
    printSolution(sol)
    print '------------------------------'
    sol = hillclimb(domain, dormCost)
    print 'HillClimb'
    print 'Cost: ', dormCost(sol)
    printSolution(sol)
    print '------------------------------'
    sol = randomStartHillClimb(domain, dormCost)
    print 'RandomStartHillClimb'
    print 'Cost: ', dormCost(sol)
    printSolution(sol)
    print '------------------------------'
    sol = simulatedAnnealing(domain, dormCost)
    print 'SimulatedAnnealing'
    print 'Cost: ', dormCost(sol)
    printSolution(sol)
    print '------------------------------'
    sol = geneticOptimize(domain, dormCost)
예제 #15
0
print dorm.dormcost(s)
dorm.printsolution(s)
print 'running time', time.clock() - start
print

print 'random optimization:',
start = time.clock()
s = op.randomoptimize(dorm.domain, costf=dorm.dormcost)
print dorm.dormcost(s)
dorm.printsolution(s)
print 'running time', time.clock() - start
print

print 'hill climb:',
start = time.clock()
s = op.hillclimb(dorm.domain, costf=dorm.dormcost)
print dorm.dormcost(s)
dorm.printsolution(s)
print 'running time', time.clock() - start
print

print 'annealing optimization:',
start = time.clock()
s = op.annealingoptimize(dorm.domain, costf=dorm.dormcost)
print dorm.dormcost(s)
dorm.printsolution(s)
print 'running time', time.clock() - start
print

print 'genetic optimization:',
start = time.clock()
예제 #16
0
#coding:gbk
'''
Created on 2015Äê8ÔÂ30ÈÕ

@author: fxy
'''
import socialnetwork
import optimization
sol=optimization.hillclimb(socialnetwork.domain, socialnetwork.crosscount)
print socialnetwork.crosscount(sol)
print sol
socialnetwork.drawNetWork(sol)
print "lll"
예제 #17
0
import optimization
s = [1,4,3,2,7,3,6,3,2,4,5,3]

reload(optimization)
domain = [(0,9)] * (len(optimization.people) * 2)
s = optimization.randomoptimize(domain, optimization.schedulecost)
optimization.schedulecost(s)
optimization.printschedule(s)

s = optimization.hillclimb(domain, optimization.schedulecost)
optimization.schedulecost(s)
optimization.printschedule(s)

s = optimization.annealingoptimize(domain, optimization.schedulecost, T=10000, cool=0.95, step=3)
optimization.schedulecost(s)
optimization.printschedule(s)

s = optimization.geneticoptimize(domain, optimization.schedulecost)
optimization.printschedule(s)

#######################
import dorm
dorm.printsolution([0,0,0,0,0,0,0,0,0,0])

s = optimization.randomoptimize(dorm.domain, dorm.dormcost)
dorm.dormcost(s)
s = optimization.geneticoptimize(dorm.domain, dorm.dormcost)
dorm.printsolution(s)

#######################
import socialnetwork
예제 #18
0
import optimization
reload(optimization)
domain=[(0,9)]*(len(optimization.people)*2)
s=optimization.hillclimb(domain,optimization.schedulecost)
print optimization.schedulecost(s)
예제 #19
0
import optimization as op
import socialnetwork as so
import time

print 'random optimization:',
start = time.clock()
sol = op.randomoptimize(so.domain,so.crosscount)
print so.crosscount(sol)
print 'running time',time.clock()-start
print
so.drawnetwork(sol)


print 'hill climb:',
start = time.clock()
sol = op.hillclimb(so.domain,so.crosscount)
print so.crosscount(sol)
print 'running time',time.clock()-start
print
so.drawnetwork(sol)

print 'annealing optimization:',
start = time.clock()
sol = op.annealingoptimize(so.domain,so.crosscount)
print so.crosscount(sol)
print 'running time',time.clock()-start
print
so.drawnetwork(sol)

print 'genetic optimization:',
start = time.clock()
    # draw people
    for n, p in pos.items():
        draw.text(p, n, (0, 0, 0))

    img.show()


domain = [(10, 370)] * (len(people) * 2)

print '--- random ---'
s = optimization.randomoptimize(domain, crosscount)
print crosscount(s)
print s

print '--- hill climb ---'
s = optimization.hillclimb(domain, crosscount)
print crosscount(s)
print s

print '--- simulated annealing ---'
s = optimization.annealingoptimize(domain, crosscount)
print crosscount(s)
print s

print '--- genetic optimize ---'
gen = optimization.genetic()
s = gen.geneticoptimize(domain, crosscount)
print crosscount(s)
print s
drawnetwork(s)
예제 #21
0
def test_hillclimb(domain):
    sys.stderr.write("testing hillclimb optimization...\n")
    s = optimization.hillclimb(domain, optimization.schedulecost)
    print optimization.schedulecost(s)
    optimization.printschedule(s)