예제 #1
0
def test_all_instances(dim):
    size = (dim * (dim - 1)) / 2
    total = int(math.pow(2, size))
    toolow = 0
    toohigh = 0

    formatter = '0' + str(int(size)) + 'b'
    fileout = open("n=" + str(dim), "w")
    for i in range(int(math.pow(2, size))):
        m = Matrix()
        m.createMatrixfromString(dim, format(i, formatter))
        s = BruteForcer(m)
        s.solve()
        lb = DynamicProgramming(m, 0).compute(0, dim - 1)
        ub = DynamicProgramming(m, 1).compute(0, dim - 1)
        g = Greedy(m)
        g.solve()
        if lb != s.get_best():
            toolow += 1
        if ub != s.get_best():
            toohigh += 1
        fileout.write(
            str(s.get_best()) + ";" + str(lb) + ";" + str(ub) + ";" +
            str(g.get_opt_val()) + "\n")
    fileout.close()

    print("Total instances:", total)
    print("Too low:", toolow)
    print("Too high:", toohigh)
예제 #2
0
 def __init__(self, stones, nPlayers, port):
     self.PORT = port
     self.NUMBER_OF_PLAYERS = nPlayers
     self.s.connect((self.HOST, self.PORT))
     self.maxStones = stones
     self.greedy = Greedy(self.STRIDE, self.maxStones)
     self.stones = []
     self.stones.append([])
     self.stones.append([])
예제 #3
0
def calc_greedy_similarity(host, port, dbindex):
    logger.debug('calculating similarity...');

    begin_time = datetime.now()
    logger.debug('Similarity calculation started at : '+str(begin_time))
    dur = begin_time-begin_time

    redisconn=redis.StrictRedis(host=host, port=port, db=dbindex)
    #term_weight_fetcher=TermWeightFetcher(lucene_dir_path)
    term_vector_fetcher=TermVectorFetcher(redisconn, None)
    greedy=Greedy()

    result=[]
    for request in requests:
        for candidate in request.candidates:
            cand_loc =readInfo.getLocation(candidate)
            cand_text=getText(cand_loc)
            cand_tokens=cleansetokenize(cand_text)
            print cand_tokens
            cand_term_vector_list=term_vector_fetcher.get_termvectors(cand_tokens, False)

            for preference in request.preferences:
                pref_loc =readInfo.getLocation(preference.docID)
                pref_text=getText(pref_loc)
                pref_tokens=cleansetokenize(pref_text)
                pref_term_vector_list=term_vector_fetcher.get_termvectors(pref_tokens, False)
            
                check_time=datetime.now()
                similarity_normal=greedy.calc_normal(cand_term_vector_list, pref_term_vector_list)
                result.append(request.id+','+candidate.docID+','+preference.docID+','+str(similarity_normal[0]))
                dur += datetime.now() - check_time
    
            finish_time=datetime.now()
            logger.debug('All duration  : '+str(finish_time-begin_time))
            logger.debug('Similarity calculation duration     : '+str(dur))
            logger.debug('Others duration   : '+str(finish_time-begin_time-dur))
        
    #writing the output file normal
    f = open('result.txt','w')
    #f = open('/data/nrekabsaz/mediaeval-diversity/runs/greedy/'+runname+'.run','w')
    #for tcnt, topic in enumerate(topics):
    #    topic.photos.sort(key=operator.attrgetter("similarity_normal"), reverse=True)
    #    for i,photo in enumerate(topic.photos):
    #        trecLine=str(topic.number) + " Q0 " + str(photo.id) + " " + str(i+1) + " " + str(photo.similarity_normal) + " l2r_mediaeval";
    #        f.write(trecLine+'\n')
    #        if i==49:
    #            break
    #f.close()

    finish_time=datetime.now()
    dur = finish_time - begin_time
    logger.info('Similarity calculation finished at  : '+str(finish_time))
    logger.info('All duration  : '+str(finish_time-begin_time))
    logger.info('Similarity calculation duration     : '+str(dur))
    logger.info('Others duration   : '+str(finish_time-begin_time-dur))
예제 #4
0
파일: connect4.py 프로젝트: danseaman6/AI
    def move(self, state, timeLimit):
        print("{0}'s turn.  {0} is {1}".format(self.name, self.color))

        if self.difficulty == 6:
            m = AlphaBeta(state)
            start = time.clock()
            best_move, value, depth = m.bestMove(30, state, self.color,
                                                 timeLimit)
            print("Alpha: ", value)
            print("Elapsed:", time.clock() - start)
            print("Depth Reached:", depth)
            return best_move, depth

        elif self.difficulty == 7:
            m = Greedy(state)
            time.sleep(randrange(8, 17, 1) / 10.0)
            best_move = m.best_move(state, self.color)
            print("guess greedy worked")
            return best_move, 1

        else:
            m = Minimax(state)
            start = time.clock()
            best_move, value, depth = m.bestMove(30, state, self.color,
                                                 timeLimit)
            print("Alpha: ", value)
            print("Elapsed:", time.clock() - start)
            print("Depth Reached:", depth)
            return best_move, depth
예제 #5
0
    def find_solver(self, algorithm):
        solver = None
        while solver is None:
            if algorithm == 'depth_first' or algorithm == 'dfs':
                solver = Depth_first(self.map)
            elif algorithm == 'breadth_first' or algorithm == 'bf' or algorithm == 'bfs':
                solver = Breadth_first(self.map)
            elif algorithm == 'astar' or algorithm == 'a*':
                solver = AStar(self.map)
            elif algorithm == 'greedy_best_first' or algorithm == 'gbf' or algorithm == 'gbfs':
                solver = Greedy_best_first(self.map)
            elif algorithm == 'iterative_deepening' or algorithm == 'id' or algorithm == 'ids':
                solver = Iterative_deepening(self.map)
            elif algorithm == 'greedy' or algorithm == 'g' or algorithm == 'gs':
                solver = Greedy(self.map)

            #Iterative astar works, but it does not work well.
            #I did not research it much before building it, and I got a few key details wrong.
            #I decided to scrap it and use a different informed custom search (greedy), as it would have taken me far too long to redo it.
            #But I figured it would still be a valuable thing to include just to show my progress.
            elif algorithm == 'iterative_astar' or algorithm == 'ia*':
                solver = Iterative_astar(self.map)
            else:
                print(
                    'Valid searches are: dfs (depth first), bfs (breadth first), A*, greedy, ids (iterative deepening) or gbfs (greedy best first)'
                )
                print('Please enter an algorithm:')
                algorithm = input()

        return solver
예제 #6
0
    def sa_algorithm(self):
        ga = Greedy(self.cities_matrix, self.number_of_cities)
        solution = ga.greedy_algorithm()
        starting_temp = 100
        current_temperature = starting_temp
        min_length = self.tour_length(solution)
        best_solution = []
        i = 0
        coolingRate = 0.00015  #this is the best I've found: 0.0002
        cool_count = 0

        lengths = []
        loop_count = []
        lo = 0
        average_distance = self.cities_matrix.sum() / self.number_of_cities**3
        print(average_distance)
        diff_frac = 0.01 * average_distance**0.5
        print('Diff_frac' + str(diff_frac))
        while current_temperature > 0.05:
            i += 1
            solution = self.optimise(self.cities_matrix, solution,
                                     self.number_of_cities,
                                     current_temperature, diff_frac)
            if i >= 150:
                i = 0  #reset i
                cool_count += 1
                currentLength = self.tour_length(solution)
                #Exponential multiplicative cooling:
                current_temperature = starting_temp * (
                    1 - coolingRate)**cool_count  #t *= 1 - coolingRate

                #current_temperature = starting_temp*math.exp( -( 0.001*1.2*cool_count**1.15 ) )
                #            current_temperature = starting_temp/(1+1.8*math.log(1+0.001*cool_count))
                lo += 1
                loop_count.append(lo)
                lengths.append(currentLength)
                if currentLength < min_length:
                    min_length = currentLength
                    best_solution = solution[:]
    #    plt.plot(loop_count, lengths, 'b.')
    #    filename = 'city'+str(number_of_cities)
    #    plt.savefig(filename, format='svg', dpi=1200)
    #    plt.show()
        return best_solution
예제 #7
0
def MipSolver(facilities: [], customers: []):
    # Create the mip solver with the CBC backend.
    solver = pywraplp.Solver('simple_mip_program',
                             pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)

    m = len(facilities)
    n = len(customers)
    #define  vars
    x = np.empty(m, dtype=object)
    y = np.empty((m, n), dtype=object)
    for i in range(m):
        x[i] = solver.IntVar(0, 1, 'X[%d]' % i)
        for j in range(n):
            y[i][j] = solver.IntVar(0, 1,
                                    'Y[%d' % i + ']' + '[' + str(j) + ']')
    #define the constraint
    # rang buoc ve demand and capacity
    for i in range(m):
        constraint_capacity = solver.RowConstraint(0, facilities[i].capacity,
                                                   '')
        for j in range(n):
            constraint_capacity.SetCoefficient(y[i][j], customers[j].demand)

    for i in range(m):
        constraint1 = solver.RowConstraint(0, n, '')
        constraint1.SetCoefficient(x[i], n)
        for j in range(n):
            constraint1.SetCoefficient(y[i][j], -1)

    for j in range(n):
        constaint = solver.Constraint(1, 1, '')
        for i in range(m):
            constaint.SetCoefficient(y[i][j], 1)
    # minimum
    objective = solver.Objective()
    for j in range(m):
        objective.SetCoefficient(x[j], facilities[j].setup_cost)
    for i in range(m):
        for j in range(n):
            twc = length(facilities[i].location, customers[j].location)
            objective.SetCoefficient(y[i][j], twc)
    objective.SetMinimization()

    status = solver.Solve()

    if status == pywraplp.Solver.OPTIMAL:
        obj = solver.Objective().Value()
        solution = np.empty(n, dtype=int)
        for j in range(n):
            for i in range(m):
                if (y[i][j].solution_value() == 1):
                    solution[j] = i
        return obj, solution
    else:
        return Greedy(customers, facilities)
예제 #8
0
class Voronoi:

    HOST = 'localhost'
    PORT = 9000
    STRIDE = 60
    NUMBER_OF_PLAYERS = 2

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def __init__(self, stones, nPlayers, port):
        self.PORT = port
        self.NUMBER_OF_PLAYERS = nPlayers
        self.s.connect((self.HOST, self.PORT))
        self.maxStones = stones
        self.greedy = Greedy(self.STRIDE, self.maxStones)
        self.stones = []
        self.stones.append([])
        self.stones.append([])

    def start(self):
        while 1:
            serverResponse = self.s.recv(1024)
            data = serverResponse.split()

            # Check if the game has ended
            if int(data[0]) == 1:
                break

            self.noOfMoves = int(data[1]) - 1
            self.playersMovedTillNow = int(data[1])
            if (self.playersMovedTillNow < self.NUMBER_OF_PLAYERS):
                for i in range(0, self.playersMovedTillNow):
                    self.lastMoveOfOpponent_x = int(data[2 + i * 3])
                    self.lastMoveOfOpponent_y = int(data[2 + i * 3 + 1])
                    self.stones[1].append(
                        Stone(self.lastMoveOfOpponent_x,
                              self.lastMoveOfOpponent_y))
                    self.greedy.updatePull(self.stones, 1)
            else:
                startIndex = self.playersMovedTillNow - self.NUMBER_OF_PLAYERS + 1
                for i in range(startIndex, self.playersMovedTillNow):
                    self.lastMoveOfOpponent_x = int(data[2 + i * 3])
                    self.lastMoveOfOpponent_y = int(data[2 + i * 3 + 1])
                    self.stones[1].append(
                        Stone(self.lastMoveOfOpponent_x,
                              self.lastMoveOfOpponent_y))
                    self.greedy.updatePull(self.stones, 1)

            nextMove = self.greedy.move(self.stones)

            self.stones[0].append(Stone(nextMove.x, nextMove.y))
            self.greedy.updatePull(self.stones, 0)

            self.s.sendall(str(nextMove.x) + " " + str(nextMove.y))

        self.s.close()
예제 #9
0
def main():
    if (len(sys.argv) != 4):
        print(
            "Parametros incorrectos, debe especificar grilla, estrategia y lanzaderas"
        )
        print("Estrategias reconocidas: 'g' Greedy,\t 'd' Dinamica")
        print("Greedy: python battleship.py grid.txt g 2")
        print("Dinamica: python battleship.py grid.txt d 2")
        exit(1)

    grid, ships = read_grid(sys.argv[1])  # Archivo
    lanzaderas = int(sys.argv[3])
    new_grid = realocate_ships(grid)
    if (sys.argv[2] == 'g'):
        strategy = Greedy(grid, lanzaderas, ships)
        new_strategy = Greedy(new_grid, lanzaderas, ships)
    elif (sys.argv[2] == 'd'):
        strategy = Dinamica(grid, lanzaderas, ships)
        new_strategy = Dinamica(new_grid, lanzaderas, ships)
    else:
        print(
            "Estrategia no reconocida, utilice 'g' para Greedy y 'd' para Dinamica"
        )
        exit(2)

    print("Configuracion de juego:")
    print("Estrategia " + str(strategy) + " con " + str(strategy.lanzaderas) +
          " lanzaderas ")
    print_board(grid, ships)

    game(grid, list(ships), strategy)

    print("Utilizando estrategia para reubicar barcos para que duren mas\n\n")

    print("Antes")
    print_board(grid, ships)
    print("Reubicados")
    print_board(new_grid, ships)
    sleep(3)
    game(new_grid, list(ships), new_strategy)
def measure_greedy():
    greedy = Greedy(Graph(0))
    avg_memory_consumption = []

    for i in range(START_COUNTING_FROM_NODE, NUM_OF_NODES):
        mem_usage_data = []

        print(f"Measuring Greedy for {i} nodes.")

        for j in range(NUM_OF_SAMPLES):
            graph = Graph(i)
            greedy.graph = graph
            starting_node = next(iter(graph.graph))

            mem_usage = memory_usage((greedy.greedy_approach, (), {
                'start_node': starting_node
            }))
            mem_usage_data.append(mem_usage[-1])

        avg_memory_consumption.append(sum(mem_usage_data) / NUM_OF_SAMPLES)

    return avg_memory_consumption
예제 #11
0
def test_random():
    """
        Test all approaches on random graph.
    """
    num_of_nodes = 7
    graph = Graph(num_of_nodes)

    starting_node = next(iter(graph.graph))

    print("{:-^100}".format(" TESTING RANDOM PATH "))

    dfs = DFS(graph)
    paths_dfs = dfs.depth_first_search(starting_node)
    print("DEPTH FIRST SEARCH")
    print("Number of Hamilton Cycles found:", len(paths_dfs))
    print("Shortest path:", graph.get_shortest_path(paths_dfs), end="\n\n")

    bfs = BFS(graph)
    paths_bfs = bfs.breadth_first_search(starting_node)
    print("BREADTH FIRST SEARCH")
    print("Number of Hamilton Cycles found:", len(paths_bfs))
    print("Shortest path:", graph.get_shortest_path(paths_bfs), end="\n\n")

    greedy = Greedy(graph)
    path_greedy = greedy.greedy_approach(starting_node)
    print("GREEDY APPROACH")
    print("Path length:",
          (path_greedy, graph.calculate_path_length(path_greedy)),
          end="\n\n")

    a_star_custom = AStarCustom(graph)
    path_a_star = a_star_custom.a_star(starting_node)
    print("A* APPROACH")
    print("Path length:",
          (path_a_star, graph.calculate_path_length(path_a_star)),
          end="\n")

    print("{:-^100}".format(" END OF TEST "), end="\n\n")
예제 #12
0
def run_test(difficulty, algorithm, output_name):
	genotype = get_test_data_path(difficulty)
	if algorithm == 'greedy':
		g = Greedy(genotype)
		t = Tester(g, None, genotype, output_name)
		t.run_analysis()
	elif algorithm == 'optimal':
		o = Optimal(genotype)
		t = Tester(o, None, genotype, output_name)
		t.run_analysis()
	elif algorithm == 'exhaustive':
		e = Exhaustive(genotype)
		t = Tester(e, None, genotype, output_name)
		t.run_analysis()
예제 #13
0
def run_training(difficulty, algorithm, output_name):
	genotype, haplotype = get_training_file_paths(difficulty)
	if algorithm == 'greedy':
		g = Greedy(genotype)
		t = Tester(g, haplotype, genotype, output_name)
		t.run_analysis()
	elif algorithm == 'optimal':
		o = Optimal(genotype)
		t = Tester(o, haplotype, genotype, output_name)
		t.run_analysis()
	elif algorithm == 'exhaustive':
		e = Exhaustive(genotype)
		t = Tester(e, haplotype, genotype, output_name)
		t.run_analysis()
예제 #14
0
def main():

    #For argument passing
    fileargs = argparse.ArgumentParser()
    fileargs.add_argument('file', help="file number to run", type=int)
    args = fileargs.parse_args()

    #Initialize Knapsack Objects for tasks
    weights = []
    values = []
    valueIndices = []  #Copy of the original order of values
    heapWeights = []
    heapValues = []

    #Concate checks and balances
    if args.file < 10:
        c_file = "./KnapsackTestData/p0" + str(args.file) + "_c.txt"
        w_file = "./KnapsackTestData/p0" + str(args.file) + "_w.txt"
        v_file = "./KnapsackTestData/p0" + str(args.file) + "_v.txt"
    else:
        c_file = "./KnapsackTestData/p" + str(args.file) + "_c.txt"
        w_file = "./KnapsackTestData/p" + str(args.file) + "_w.txt"
        v_file = "./KnapsackTestData/p" + str(args.file) + "_v.txt"

    print("File containing the capacity, weights, and values are:",
          c_file[19:] + ", " + w_file[19:] + ", " + v_file[19:])
    print()

    #Read in from files
    file = open(c_file)

    #Max weight
    maxCapacity = int(file.readline())
    file.close()

    #Weights
    file = open(w_file)
    for line in file:
        weights.append(int(line))
        heapWeights.append(int(line))
    file.close()

    #Values
    file = open(v_file)
    for line in file:
        valueIndices.append(int(line))
        values.append(int(line))
        heapValues.append(int(line))
    file.close()

    totalWeights = len(weights)
    totalValues = len(values)

    print("Knapsack capacity =", maxCapacity, ". Total number of items =",
          totalWeights)
    print()
    #Dynamic Programming
    dynamicClass = Dynamic()
    dpTable = [[0 for x in range(maxCapacity + 1)]
               for x in range(totalWeights + 1)]

    begin = time.time()
    dpResult = dynamicClass.dynamicApproach(weights, values, maxCapacity,
                                            totalWeights, dpTable)
    dpOptimal = dynamicClass.dynamicOptimal(weights, maxCapacity, totalWeights,
                                            dpTable)
    dpTime = time.time() - begin

    print("Traditional Dynamic Programming Optimal value:", dpResult)
    print("Traditional Dynamic Programming Optimal subset:", dpOptimal)
    print("Traditional Dynamic Programming Time Taken:", dpTime)
    print()

    #Greedy approach using in-built sorting
    greedyOptSubset = []
    greedyOptValues = []
    greedyClass = Greedy()

    greedyClass.quickSort(0, totalValues - 1, values, weights)
    greedyResult = greedyClass.greedyApproach(values, maxCapacity, weights,
                                              greedyOptValues)
    greedyOptSubset = optimalSubset(valueIndices, greedyOptValues)

    print("Greedy Approach Optimal value:", greedyResult)
    print("Greedy Approach Optimal subset:", greedyOptSubset)
    print("Greedy Approach Number of Operations:",
          greedyClass.greedyOperations)
    print()

    #Greedy approach using a max-heap
    heapOptSubset = []
    heapOptValues = []
    totalHeapValues = len(heapValues)
    heapClass = Heap()

    heapClass.heapSort(heapValues, heapWeights, totalHeapValues)
    heapOptValue = heapClass.heapApproach(heapValues, heapWeights, maxCapacity,
                                          heapOptValues)
    heapOptSubset = optimalSubset(valueIndices, heapOptValues)

    print("Heap-based Greedy Approach Optimal value:", heapOptValue)
    print("Heap-based Greedy Approach Optimal subset:", heapOptSubset)
    print("Heap-based Approach Number of Operations:",
          heapClass.heapOperations)
    print()
    graphMaker()
예제 #15
0
def test_exercise_progress():

    db = mongoengine.connect(config.db_name)
    db.drop_database(config.db_name)

    # Editor user
    u = utils.sample_user()
    u.save()

    exe = model.exercise.Exercise(author=u, title="An exercise's title", description="## This is an exercise\n\n* El1\n* El2",
                        boilerplate_code='b', reference_code='#', tags=['sort','trees'])

    test = model.exercise.Test(input='1\n', output='1')
    test.save()
    exe.tests.append(test)

    test = model.exercise.Test(input='2\n', output='2')
    test.save()
    exe.tests.append(test)

    test = model.exercise.Test(input='3\n', output='3')
    test.save()
    exe.tests.append(test)

    exe.save()

    wrong_code = '\n'.join([
        '#include <iostream>',
        '',
        'int main() {',
        'int i;',
        'std::cin >> i;',
        'if (i > 2) std::cout << i;',
        'return 0;',
        '}'
    ])

    working_code = '\n'.join([
        '#include <iostream>',
        '',
        'int main() {',
        'int i;',
        'std::cin >> i;',
        'std::cout << i;',
        'return 0;',
        '}'
    ])

    u = model.user.User(email='test@{}'.format(config.email_domain), username='******', secret_hash='hash', salt='salt')
    u.save()

    submission = job.Submission(exercise=exe, code=wrong_code, user=u)
    submission.save()

    submission = job.Submission(exercise=exe, code=working_code, user=u)
    submission.save()

    submission = job.Submission(exercise=exe, code="nothing at all", user=u)
    submission.save()

    greedy_app = Greedy(db)
    greedy_app.fetch_and_process()

    # Progression for this user
    progress, created = model.exercise.ExerciseProgress.objects.get_or_create(user=u, exercise=exe)

    assert progress.best_results[0].passed == True
    assert progress.best_results[1].passed == True
    assert progress.best_results[2].passed == True

    assert progress.score <= 42
예제 #16
0
def main():

    print('============================================')
    print(
        'Program ini menunjukan kota-kota yang bisa \nanda kunjungi saat piknik antar kota dengan keluarga \ndan menunjukan kota-kota dengan jarak antar kota terpendek'
    )
    print(
        'sehingga memudahkan anda untuk mendapatkan kota untuk singgah \natau memperbanyak tujuan piknik anda'
    )
    print('-------------------------------------------')
    print(
        'This program shows cities that can be visited \non your family trip and help you to get the list of cities that have shortest distance between them.'
    )
    print(
        'So by using this program you can get some cities for stop by \nor multiply your destination for your trip'
    )
    print('============================================')
    print(
        'Berikut adalah daftar kota yang kami sediakan:\n(Here the list of the cities that we provide)\n'
    )

    #List Kota
    kota = set([
        'Cilegon', 'Tangerang', 'Jakarta', 'Bogor', 'Cikampek', 'Bekasi',
        'Bandung', 'Cirebon', 'Cimahi', 'Cianjur', 'Garut', 'Sumedang',
        'Subang', 'Tasikmalaya', 'Purwokerto', 'Magelang', 'Semarang', 'Jogja',
        'Surabaya', 'Malang'
    ])

    #adjacency list city in Java
    jarak = {
        'Cilegon': {
            'Tanggerang': 84
        },
        'Tanggerang': {
            'Jakarta': 35,
            'Cilegon': 84
        },
        'Jakarta': {
            'Bogor': 54,
            'Cikampek': 76,
            'Bekasi': 50,
            'Tanggerang': 35
        },
        'Bekasi': {
            'Cikampek': 41,
            'Jakarta': 50
        },
        'Cikampek': {
            'Bandung': 80,
            'Cirebon': 146,
            'Jakarta': 76,
            'Bekasi': 41
        },
        'Bogor': {
            'Bandung': 182,
            'Jakarta': 54
        },
        'Bandung': {
            'Tasikmalaya': 124,
            'Cimahi': 14,
            'Cianjur': 67,
            'Garut': 71,
            'Sumedang': 76,
            'Subang': 54,
            'Cikampek': 80,
            'Bogor': 182
        },
        'Tasikmalaya': {
            'Purwokerto': 144,
            'Bandung': 124,
            'Garut': 53
        },
        'Cimahi': {
            'Bandung': 14
        },
        'Cianjur': {
            'Bandung': 67
        },
        'Garut': {
            'Bandung': 71,
            'Tasikmalaya': 53
        },
        'Sumedang': {
            'Bandung': 76
        },
        'Subang': {
            'Bandung': 54
        },
        'Purwokerto': {
            'Magelang': 145,
            'Tasikmalaya': 144
        },
        'Magelang': {
            'Semarang': 72,
            'Jogja': 53,
            'Surabaya': 339,
            'Purwokerto': 145
        },
        'Cirebon': {
            'Tegal': 88,
            'Cikampek': 146
        },
        'Tegal': {
            'Semarang': 160,
            'Cirebon': 88
        },
        'Semarang': {
            'Jogja': 129,
            'Surabaya': 348,
            'Magelang': 72,
            'Tegal': 160
        },
        'Jogja': {
            'Surabaya': 324,
            'Magelang': 53,
            'Semarang': 129
        },
        'Surabaya': {
            'Malang': 94,
            'Magelang': 339,
            'Semarang': 348,
            'Jogja': 324
        },
        'Malang': {
            'Surabaya': 94
        }
    }

    finish = ' '
    daftarkota(kota)
    print('============================================')
    print(
        'Tulis nama kota asal dan tujuan anda dengan \nhuruf kapital pada huruf pertama (contohnya: Bekasi)'
    )
    print('-------------------------------------------')
    print(
        'Please write your departure city and destination with a capital letter in the first letter (example: Bekasi)'
    )

    start = input('Kota Anda Sekarang : ').strip()
    start = start.lower()
    start = ''.join(start[0].upper() + start[1:])
    if start not in kota:
        print(
            '\n Format Nama Kota Yang Anda Masukkan Salah atau Tidak Terdaftar'
        )

    finish = input('Kota Tujuan Anda : ')
    path = Greedy(jarak, start, finish)
    print('Kota Asal = ', start)
    if (path):
        print('Urutan Kota Berdasar Algoritma Greedy : ', end='')
        for i in path:
            print(i, end='>')

    else:
        print('Tidak Ditemukan Jalan')
예제 #17
0
def try_all_approaches(num_of_samples: int, num_of_nodes: int):
    """
        Execute all approaches on the same graphs for given number of nodes and samples (the more samples the more
        statistically accurate results).
            Returns: Achieved path lengths and execution times for all approaches.
    """
    graph = Graph(0)

    dfs = DFS(graph)
    dfs_path_lengths = []
    dfs_execution_times = []

    bfs = BFS(graph)
    bfs_path_lengths = []
    bfs_execution_times = []

    greedy = Greedy(graph)
    greedy_path_lengths = []
    greedy_execution_times = []

    a_star_custom = AStarCustom(graph)
    a_star_path_lengths = []
    a_star_execution_times = []
    for i in range(a_star_custom.num_of_heuristics):
        a_star_path_lengths.append([])
        a_star_execution_times.append([])

    for j in range(num_of_samples):
        graph = Graph(num_of_nodes)
        starting_node = next(iter(graph.graph))

        start = time.time()
        dfs.graph = graph
        paths_dfs = dfs.depth_first_search(starting_node)
        dfs_path_lengths.append(Graph.get_shortest_path(paths_dfs)[1])
        execution_time = time.time() - start
        dfs_execution_times.append(execution_time)

        start = time.time()
        bfs.graph = graph
        paths_bfs = bfs.breadth_first_search(starting_node)
        bfs_path_lengths.append(Graph.get_shortest_path(paths_bfs)[1])
        execution_time = time.time() - start
        bfs_execution_times.append(execution_time)

        start = time.time()
        greedy.graph = graph
        path_greedy = greedy.greedy_approach(starting_node)
        greedy_path_lengths.append(Graph.calculate_path_length(path_greedy))
        execution_time = time.time() - start
        greedy_execution_times.append(execution_time)

        for i in range(a_star_custom.num_of_heuristics):
            start = time.time()
            a_star_custom.graph = graph
            a_star_custom.heuristic_choice = i
            path_a_star = a_star_custom.a_star(starting_node)
            execution_time = time.time() - start
            a_star_path_lengths[i].append(
                Graph.calculate_path_length(path_a_star))
            a_star_execution_times[i].append(execution_time)

    dfs_avg_results = sum(dfs_path_lengths) / num_of_samples, sum(
        dfs_execution_times) / num_of_nodes, "DFS Recurrent"
    bfs_avg_results = sum(bfs_path_lengths) / num_of_samples, sum(
        bfs_execution_times) / num_of_nodes, "BFS"
    greedy_avg_results = sum(greedy_path_lengths) / num_of_samples, sum(
        greedy_execution_times) / num_of_nodes, "Greedy"
    a_star_avg_results = []
    for i in range(a_star_custom.num_of_heuristics):
        label = "A* heuristic " + str(i)
        a_star_avg_results.append(
            (sum(a_star_path_lengths[i]) / num_of_samples,
             sum(a_star_execution_times[i]) / num_of_samples, label))

    data = [dfs_avg_results, bfs_avg_results, greedy_avg_results]
    data.extend(a_star_avg_results)

    return data
def solve_it(input_data):

    lines = input_data.split('\n')

    parts = lines[0].split()
    facility_count = int(parts[0])
    customer_count = int(parts[1])

    facilities = []
    for i in range(1, facility_count + 1):
        parts = lines[i].split()
        facilities.append(
            Facility(i - 1, float(parts[0]), int(parts[1]),
                     Point(float(parts[2]), float(parts[3]))))

    customers = []
    for i in range(facility_count + 1, facility_count + 1 + customer_count):
        parts = lines[i].split()
        customers.append(
            Customer(i - 1 - facility_count, int(parts[0]),
                     Point(float(parts[1]), float(parts[2]))))

    # distance_matrix[i][j] is the distance between the i-th customer and the j-th facility.
    distance_matrix = [[((customer.location.x - facility.location.x) ** 2 + (customer.location.y - facility.location.y) ** 2) ** 0.5 \
                        for facility in facilities]  for customer in customers]

    # distance_matrix_facilities[i][j] is the distance between the i-th facility and the j-th facility.
    distance_matrix_facilities = [[((fa.location.x - fb.location.x) ** 2 + (fa.location.y - fb.location.y) ** 2) ** 0.5 \
                                    for fb in facilities]  for fa in facilities]

    # distance_matrix_facilities_indice[i] contains the indice of the nearest facilities for the i-th facility.
    distance_matrix_facilities_indice = [[i for i in range(len(facilities))]
                                         for j in range(len(facilities))]

    for i, row in enumerate(distance_matrix_facilities_indice):
        row.sort(key=lambda x: distance_matrix_facilities[i][x])

    # read initial solution generated by Guided Local Search.

    objective_init, assignment_init = Greedy(customers, facilities)

    best_objective = objective_init
    best_assignment = assignment_init
    best_facility_open = [0] * len(facilities)
    for index in best_assignment:
        best_facility_open[index] = 1
    best_output = None

    # number of facilities to form a sub-problem.
    n_sub_facilities = 50

    round_limit = 10000

    for round in range(round_limit):

        start_time = time.time()

        # Randomly choose a facility and its top-n nearest neighbor facilities.
        sub_facilities = np.random.choice(len(facilities))
        sub_facilities = distance_matrix_facilities_indice[
            sub_facilities][:n_sub_facilities]

        sub_facilities_set = set(sub_facilities)

        # Select all customers that are served by the above facilities.
        sub_customers = [
            i for i in range(len(customers))
            if best_assignment[i] in sub_facilities_set
        ]

        objective_old = 0.0

        for customer in sub_customers:
            objective_old += distance_matrix[customer][
                best_assignment[customer]]

        for facility in sub_facilities:
            objective_old += best_facility_open[facility] * facilities[
                facility].setup_cost

        solver = pywraplp.Solver('SolveIntegerProblem',
                                 pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)

        sub_assignment = [[
            solver.IntVar(0.0, 1.0, 'a' + str(i) + ',' + str(j))
            for j in range(len(sub_facilities))
        ] for i in range(len(sub_customers))]

        sub_facility_open = [
            solver.IntVar(0.0, 1.0, 'f' + str(j))
            for j in range(len(sub_facilities))
        ]

        # Constraint: each customer must be assigned to exactly one facility.
        for i in range(len(sub_customers)):
            solver.Add(
                sum([sub_assignment[i][j]
                     for j in range(len(sub_facilities))]) == 1)

        # Constraint: a customer must be assigned to an open facility.
        for i in range(len(sub_customers)):
            for j in range(len(sub_facilities)):
                solver.Add(sub_assignment[i][j] <= sub_facility_open[j])

        # Constraint: the capacity of each facility must not be exceeded.
        for j in range(len(sub_facilities)):
            solver.Add(sum([sub_assignment[i][j] * customers[sub_customers[i]].demand \
                for i in range(len(sub_customers))]) <= facilities[sub_facilities[j]].capacity)

        objective = solver.Objective()

        # Objective: sum all the distance.
        for i in range(len(sub_customers)):
            for j in range(len(sub_facilities)):
                objective.SetCoefficient(
                    sub_assignment[i][j],
                    distance_matrix[sub_customers[i]][sub_facilities[j]])

        # Objective: sum all the setup cost.
        for j in range(len(sub_facilities)):
            objective.SetCoefficient(sub_facility_open[j],
                                     facilities[sub_facilities[j]].setup_cost)

        objective.SetMinimization()
        """Solve the problem and print the solution."""
        SEC = 100
        MIN = 60 * SEC
        solver.SetTimeLimit(1 * MIN)
        result_status = solver.Solve()

        end_time = time.time()

        if result_status != solver.OPTIMAL and result_status != solver.FEASIBLE:

            print('[Round %9d/%9d] [N-Sub-Facilities %4d] [Best Objective %f] [Old Objective %f] [New Objective N/A] [Time %f]' % \
                (round + 1, round_limit, n_sub_facilities, best_objective, objective_old, end_time - start_time))
            continue

        objective_new = solver.Objective().Value()
        assignment_new = []

        for i in range(len(sub_customers)):
            for j in range(len(sub_facilities)):
                if sub_assignment[i][j].solution_value() == 1:
                    assignment_new.append(sub_facilities[j])
                    break

        print('[Round %9d/%9d] [N-Sub-Facilities %4d] [Best Objective %f] [Old Objective %f] [New Objective %f] [Time %f] %s' % \
                (round + 1, round_limit, n_sub_facilities, best_objective, objective_old, objective_new, end_time - start_time, \
                'best model found' if objective_old >= objective_new + 1 else ''))

        if objective_old >= objective_new + 1:
            best_objective -= objective_old - objective_new
            for i, j in enumerate(assignment_new):
                best_assignment[sub_customers[i]] = j

            best_facility_open = [0] * len(facilities)
            for index in best_assignment:
                best_facility_open[index] = 1

            best_output = str(best_objective) + ' ' + '0' + '\n' + ' '.join(
                [str(assign) for assign in best_assignment])
            with open("mip-output.txt", 'w') as best_mip_output_file:
                best_mip_output_file.write(best_output)

    return best_output
예제 #19
0
파일: main.py 프로젝트: broekm006/SmartGrid
def what_to_run(self, wijk, algo, sec_algo, NoT, vis):
    ''' Kijkt welke variant van greedy'''
    wijk = "wijk" + wijk
    load = Load(wijk, wijk)

    print()
    print("INNITIAL UPPER & LOWERBOUND (before k-means and/or HAC)")
    print()
    print(wijk)
    Solution.bounds(Solution, load.batteries, load.houses)


    if algo == "random":
        random = Random_connect(load.houses, load.batteries)
    elif algo == "greedy_output":
        greedy = Greedy(load.houses, load.batteries, "output")
    elif algo == "greedy_distance":
        greedy = Greedy(load.houses, load.batteries, "distance")
    elif algo == "greedy_priority":
        greedy = Greedy(load.houses, load.batteries, "priority")
    elif algo == "k_means_output":
        k_means = K_means2(load.houses, load.batteries, "output", "")
        k_means.results()
    elif algo == "k_means_distance":
        k_means = K_means2(load.houses, load.batteries, "distance", "")
        k_means.results()
    elif algo == "k_means_priority":
        k_means = K_means2(load.houses, load.batteries, "priority", "")
        k_means.results()
    elif algo == "HAC":
        splitter = Cluster_merge(load.houses)
        sec_algo = "escape"
        grid_visualisatie = Grid_visualizer(splitter.houses, splitter.batteries, "gridview", "Hierarchical Agglomerative Clustering", splitter.solutions, splitter.best_solution)



    else:
        print("Error running algorithm")

    if sec_algo == "hill_climber" and algo == "greedy_output" or sec_algo == "hill_climber" and algo == "greedy_distance" or sec_algo == "hill_climber"  and algo == "greedy_priority":
        hill_climber = Hill_climber(greedy.houses, greedy.batteries, NoT, 1)
        if vis == 'True':
            grid_visualisatie = Grid_visualizer(hill_climber.houses, hill_climber.batteries, "gridview", "Greedy + Hill Climber")
    elif sec_algo == "hill_climber" and algo == "k_means_output" or sec_algo == "hill_climber" and algo == "k_means_distance" or sec_algo == "hill_climber" and algo == "k_means_priority":
        hill_climber = Hill_climber(k_means.houses, k_means.batteries, NoT, 1)
        if vis == 'True':
            grid_visualisatie = Grid_visualizer(hill_climber.houses, hill_climber.batteries, "gridview", "K-Means + Hill Climber")
    elif sec_algo == "simulated_annealing" and algo == "greedy_output" or sec_algo == "simulated_annealing" and algo == "greedy_distance" or sec_algo == "simulated_annealing" and algo == "greedy_priority":
        sim = Simulated_annealing(greedy.houses, greedy.batteries, NoT, 1)
        if vis == 'True':
            grid_visualisatie = Grid_visualizer(sim.houses, sim.batteries, "gridview", "Greedy + Simulated Annealing")
    elif sec_algo == "simulated_annealing" and algo == "k_means_output" or sec_algo == "simulated_annealing" and algo == "k_means_distance" or sec_algo == "simulated_annealing" and algo == "k_means_priority":
        sim = Simulated_annealing(k_means.houses, k_means.batteries, NoT, 1)
        if vis == 'True':
            grid_visualisatie = Grid_visualizer(sim.houses, sim.batteries, "gridview", "K-Means + Simulated Annealing")
    elif sec_algo == "simulated_annealing" and algo == "HAC":
        sim = Simulated_annealing(splitter.houses, splitter.batteries, NoT, 1)
        if vis == 'True':
            grid_visualisatie = Grid_visualizer(splitter.houses, splitter.batteries, "gridview", "Hierarchical Agglomerative Clustering", splitter.solutions, splitter.best_solution)
    elif sec_algo == "hill_climber" and algo == "HAC":
        sim = Hill_climber(splitter.houses, splitter.batteries, NoT, 1)
        if vis == 'True':
            grid_visualisatie = Grid_visualizer(splitter.houses, splitter.batteries, "gridview", "Hierarchical Agglomerative Clustering", splitter.solutions, splitter.best_solution)
    elif sec_algo == "escape":
        pass

    else:
        print("Error running secondary algorithm")
예제 #20
0
from backtracking import Backtracking
from breadth import Breadth
from greedy import Greedy
from graph import Graph
from insert import GraphPopulator
import time

if __name__ == '__main__':

    # graph = Graph('all')
    # populator = GraphPopulator(graph)
    # populator.insert()
    # backtracking = Backtracking(graph)
    # backtracking.run()

    graph = Graph('north')
    populator = GraphPopulator(graph)
    populator.insert_north()

    # breadth = Breadth(graph)
    # breadth.breadth()

    greedy = Greedy(graph)
    greedy.greedy()

# graph.print_graph_with_colors()


예제 #21
0
from greedy import Greedy
from annealing import Annealing

# A call to initialize an instance of the network class

# will create a new map with new cities
# change the N parameter to adjust how many cities appear, annealer does better with fewer

n = Network(N=15)

# Calls the greedy and annealer algorithms on the network created in the above block.
# Visualizes results for comparison.

print("Greedy")

g = Greedy(n)
g.run()
n.draw_route(g.route, text=" - Greedy")

print()
print("Annealing")

a = Annealing(
    n, T=50,
    c=0.9995)  # larger T means more time exploring and less time descending
# If you make T much bigger, add more nines to c so you
# don't get a zero division error

a.run(n_times=12000)  # can be slow
n.draw_route(a.route, text=" - Annealing")
a.score_plot()
예제 #22
0
파일: main.py 프로젝트: 2easy/ctsp
#!/usr/bin/env python
from greedy import Greedy
from stabu_search import SimpleTabooSearch
from simulated_annealing import SimulatedAnnealing
from ant_colony import AntColony


# Generate simple example
from helpers import gen_dists, compute_cost, gen_random
#dists1 = gen_dists([(0,0), (-4,0), (1,4), (3,4), (3,2), (8,-6), (-2,-3), (-4,-3)])
dists1 = gen_dists(gen_random(128))

#print(dists1)

# example usage of greedy algorithm sovle
greedy = Greedy(dists1)
g_sol = greedy.solve()
print("GREEDY SOLUTION:\t\t\t"+str(g_sol)+" ---> " + str(greedy.cost))

# example usage of SimpleTabooSearch find solution at once
sts = SimpleTabooSearch(dists1)
sts_sol = sts.solve()
print("SIMPLE TABOO SEARCH SOLUTION:\t\t"+ str(sts_sol)+ " ---> "+ str(sts.cost))

san = SimulatedAnnealing(dists1,g_sol)
san_sol = san.solve()
print("GREEDY - SIMULATED ANNEALING SOLUTION:\t\t"+ str(san_sol)+ " ---> "+ str(san.cost))

san2 = SimulatedAnnealing(dists1,sts_sol)
san_sol2 = san2.solve()
print("SIMPLE TABOO - SIMULATED ANNEALING SOLUTION:\t\t"+ str(san_sol2)+ " ---> "+ str(san2.cost))
예제 #23
0
def dqn_evaluation(player, dqn, nb_episodes):
    player.reset_battles()
    dqn.test(player, nb_episodes=nb_episodes, visualize=False, verbose=False)

    print(
        "DQN Evaluation: %d victories out of %d episodes"
        % (player.n_won_battles, nb_episodes)
    )
def create_model(n_action=None,load=None):
    if load is not None:
        pass

if __name__=='__main__':
    env_player = SimpleRLPlayer(battle_format="gen8randombattle")

    opponent = Greedy(battle_format="gen8randombattle")

    # Output dimension
    n_action = len(env_player.action_space)

    model = Sequential()
    model.add(Dense(128, activation="elu", input_shape=(1, 10)))

    # Our embedding have shape (1, 10), which affects our hidden layer
    # dimension and output dimension
    # Flattening resolve potential issues that would arise otherwise
    model.add(Flatten())
    model.add(Dense(64, activation="elu"))
    model.add(Dense(n_action, activation="linear"))

    memory = SequentialMemory(limit=10000, window_length=1)
예제 #24
0
async def main():
    player = Greedy(player_configuration=PlayerConfiguration('a very greedy bot', 'password'),
                    server_configuration=ShowdownServerConfiguration
                    )
    await player.accept_challenges(None, 10)
예제 #25
0
def main():

    print('============================================')
    print(
        'This program shows cities that can be visited \nSo by using this program you can get some cities for stop by \nor multiply your destination for your trip\n'
    )
    print('-------------------------------------------')
    print(
        ' \non your family trip and help you to get the list of cities that have shortest distance between them.\n'
    )
    print('============================================')
    print('Here the list of the cities that we provide:\n')

    #List Kota
    kota = set([
        'Cilegon', 'Tangerang', 'Jakarta', 'Bogor', 'Cikampek', 'Bekasi',
        'Bandung', 'Cirebon', 'Cimahi', 'Cianjur', 'Garut', 'Sumedang',
        'Subang', 'Tasikmalaya', 'Purwokerto', 'Magelang', 'Semarang', 'Jogja',
        'Surabaya', 'Malang'
    ])

    #adjacency list city in Java
    jarak = {
        'Cilegon': {
            'Tanggerang': 84
        },
        'Tanggerang': {
            'Jakarta': 35,
            'Cilegon': 84
        },
        'Jakarta': {
            'Bogor': 54,
            'Cikampek': 76,
            'Bekasi': 50,
            'Tanggerang': 35
        },
        'Bekasi': {
            'Cikampek': 41,
            'Jakarta': 50
        },
        'Cikampek': {
            'Bandung': 80,
            'Cirebon': 146,
            'Jakarta': 76,
            'Bekasi': 41
        },
        'Bogor': {
            'Bandung': 182,
            'Jakarta': 54
        },
        'Bandung': {
            'Tasikmalaya': 124,
            'Cimahi': 14,
            'Cianjur': 67,
            'Garut': 71,
            'Sumedang': 76,
            'Subang': 54,
            'Cikampek': 80,
            'Bogor': 182
        },
        'Tasikmalaya': {
            'Purwokerto': 144,
            'Bandung': 124,
            'Garut': 53
        },
        'Cimahi': {
            'Bandung': 14
        },
        'Cianjur': {
            'Bandung': 67
        },
        'Garut': {
            'Bandung': 71,
            'Tasikmalaya': 53
        },
        'Sumedang': {
            'Bandung': 76
        },
        'Subang': {
            'Bandung': 54
        },
        'Purwokerto': {
            'Magelang': 145,
            'Tasikmalaya': 144
        },
        'Magelang': {
            'Semarang': 72,
            'Jogja': 53,
            'Surabaya': 339,
            'Purwokerto': 145
        },
        'Cirebon': {
            'Tegal': 88,
            'Cikampek': 146
        },
        'Tegal': {
            'Semarang': 160,
            'Cirebon': 88
        },
        'Semarang': {
            'Jogja': 129,
            'Surabaya': 348,
            'Magelang': 72,
            'Tegal': 160
        },
        'Jogja': {
            'Surabaya': 324,
            'Magelang': 53,
            'Semarang': 129
        },
        'Surabaya': {
            'Malang': 94,
            'Magelang': 339,
            'Semarang': 348,
            'Jogja': 324
        },
        'Malang': {
            'Surabaya': 94
        }
    }

    finish = ' '
    daftarkota(kota)
    print('============================================')
    print(
        'Please write your departure city and destination with a capital letter in the first letter (example: Bekasi)'
    )
    print('-------------------------------------------')

    start = input('Your Current City : ').strip()
    start = start.lower()
    start = ''.join(start[0].upper() + start[1:])
    if start not in kota:
        print(
            '\n The Format Name of City You Enter is Incorrect or Unregistered'
        )

    finish = input('Your Destination City : ')
    path = Greedy(jarak, start, finish)
    print('Current City = ', start)
    if (path):
        print('City Order Based On Algoritma Greedy : ', end='')
        for i in path:
            print(i, end=' -> ')

    else:
        print('Path Not Found')
예제 #26
0
        best_nodice = [0, None]
        for choice in values:
            if choice[0] > best_choice[0] and choice[1] > self.n_dice:
                best_choice = choice
            elif choice[0] > best_nodice[0]:
                best_nodice[0] = choice[0]
        if best_choice[0] == 0:  # Never updated
            return best_nodice

        return best_choice


### We'll make some basic strategies

if __name__ == "__main__":
    gd = Greedy(num_dice=NUM_DICE)
    al500 = DiceBasic(2)
    al250 = RealBasic(200)
    best_game = ['', 1000]
    best_values = []

    wins = {al500.name: 0, al250.name: 0}
    num_turns = 0
    for game_num in range(50000):
        print("GAMES :: {}".format(wins), end='\r')
        current_points = {al500.name: 0, al250.name: 0}
        has_won = False
        this_game = 0
        these_values1 = []
        these_values2 = []
예제 #27
0
    def clustering(self, houses, batteries, counter):
        ''' Use K-means to cluster and assign houses to batteries '''

        # count clustering iterations
        counter += 1

        # capacitated clustering
        greedy = Greedy(houses, batteries, self.greedy)
        houses = copy.deepcopy(greedy.houses)
        batteries = copy.deepcopy(greedy.batteries)

        # Save solution
        solution = Solution(copy.deepcopy(houses), copy.deepcopy(batteries))
        self.solutions.append(solution)

        for battery in batteries:
            houses = Sort.distance(Sort, houses, battery)

        # calculate cable costs
        cable_costs = Helper.houses_costs(Helper, batteries, houses)
        battery_costs = 0
        for battery in batteries:
            battery_costs += battery.cost
        costs = cable_costs + battery_costs

        # for each cluster, new centre = means of all connected houses coördinates
        for battery in batteries:
            x = 0
            y = 0
            count = 0

            for house in battery.connected:
                x += house.x
                y += house.y
                count += 1

            # Avoid dividing by zero battery is not connected to any house (HAC)
            if count != 0:
                # average
                mean_x = round(x / count)
                mean_y = round(y / count)

                # new centre
                battery.x = mean_x
                battery.y = mean_y

        # Stops when costs haven't changed
        if costs < self.costs:
            self.costs = costs

            # disconnect
            for battery in batteries:
                battery.connected = []
                battery.current_usage = 0

            for house in houses:
                house.connected = False
                house.connection = False
                house.costs = 0

            # --> Solution
            self.batteries = batteries
            self.houses = houses

            # try again
            self.clustering(houses, batteries, counter)
        else:
            pass
예제 #28
0
    def genetic(self):
        #init
        ga = Greedy(self.cities_matrix, self.tourlength)
        initial = ga.greedy_algorithm()
        current_pop = []
        for i in range(100):
            baby = initial[:]
            #swap a few in initial
            if random.random() < 0.95:
                baby = self.rnd_swap(baby)
                if random.random() < 0.7:
                    baby = self.rnd_swap(baby)
                    if random.random() < 0.4:
                        baby = self.rnd_swap(baby)
            #current.shuffle()#shuffle to a certain degree
    #        current = random.sample(range(1, tourlength + 1), tourlength)

            current_pop.append((baby, self.tour_length(baby)))

    #    print("currentpopppppp"+str(len(current_pop)))

        min_length = min(list(map(lambda x: x[1], current_pop)))
        curr_best = list(filter(lambda x: x[1] == min_length, current_pop))[0]
        #    print(curr_best)
        ########################

        new_best = curr_best[:]
        checker = 0
        new_pop = []
        while checker < 20:  #while not(max fitness hasn't improved in x generations)
            for i in range(100):
                parents = self.select_parents(current_pop)
                dad, mum = parents[0], parents[1]
                #SPLICE
                rand_index = random.randint(0, self.tourlength - 1)
                #take the prefix of dad and add the suffix of mum
                child_with_duplicates = dad[0][:rand_index] + mum[0][
                    rand_index:]

                #MUTATE
                for j in range(len(child_with_duplicates)):
                    #for city in child_with_duplicates:
                    if random.random(
                    ) < 0.01:  #with a 1% chance randomly mutate each city
                        #city = random.sample(range(1, tourlength + 1), tourlength)[0]
                        child_with_duplicates[j] = random.randint(
                            1, self.tourlength)
                #make a set of all the cities not included
                not_included = [x for x in range(1, self.tourlength + 1)]
                for c in child_with_duplicates:
                    if c in not_included:
                        not_included.remove(c)

                random.shuffle(not_included)
                #check over for repetitions, if there is: add the first from the set
                child = []
                for c in child_with_duplicates:
                    if c in child:
                        child.append(not_included[0])
                        not_included.pop(0)
                    else:
                        child.append(c)
                #add child to current_pop[i]
                new_pop.append((child, self.tour_length(child)))
            current_pop = new_pop
            new_pop = []

            min_length = min(list(map(lambda x: x[1], current_pop)))
            new_best = list(filter(lambda x: x[1] == min_length,
                                   current_pop))[0]

            #        print("new_best: " + str(new_best[1]) + "curr_best: " + str(curr_best[1]))
            #        print("curr_best[1] > new_best[1] : " + str(curr_best[1] > new_best[1]))
            ########################

            if curr_best[1] > new_best[1]:
                curr_best = new_best
                checker == 0
            elif curr_best[1] == new_best[1]:
                checker += 1

    #            else :
    #                checker == 0
    #        print("new_best: " + str(new_best[1]))
    #        print("Fittest in generation: " + str(curr_best[0]))
    #        print("Length: " + str(curr_best[1]))
    #        print("checker:" + str(checker))

        return curr_best[0]
예제 #29
0
def graphMaker():
    #Initializing lists
    nonHeap_x = []
    nonHeap_y = []
    heap_x = []
    heap_y = []

    #For 8 files 0 through 8
    for i in range(9):
        #Initialize
        weights_list = []
        values_list = []
        heap_weight = []
        heap_values = []
        used_vals = []
        used_Heapvals = []

        #Reopening and initailizing files
        c_file = "./KnapsackTestData/p0" + str(i) + "_c.txt"
        w_file = "./KnapsackTestData/p0" + str(i) + "_w.txt"
        v_file = "./KnapsackTestData/p0" + str(i) + "_v.txt"

        #Capacity
        file = open(c_file)
        maxCap = int(file.readline())
        file.close()

        #Weights
        file = open(w_file)
        for line in file:
            weights_list.append(int(line))
            heap_weight.append(int(line))
        file.close()

        #Values
        file = open(v_file)
        for line in file:
            values_list.append(int(line))
            heap_values.append(int(line))
        file.close()

        #Greedy non heap
        greedyClass = Greedy()
        greedyClass.quickSort(0,
                              len(values_list) - 1, values_list, weights_list)
        greedyClass.greedyApproach(values_list, maxCap, weights_list,
                                   used_vals)
        greedyOps = greedyClass.greedyOperations
        nonHeap_x.append(len(values_list))
        nonHeap_y.append(greedyOps)

        #Greedy heap
        heapClass = Heap()
        heapClass.heapSort(heap_values, heap_weight, len(heap_values))
        heapClass.heapApproach(heap_values, heap_weight, maxCap, used_Heapvals)
        heapGredOps = heapClass.heapOperations
        heap_x.append(len(values_list))
        heap_y.append(heapGredOps)

    #Printing the two graphs one by one.
    print("Printing Non-Heap Greedy")
    plt.title("Greedy Non-Heap")
    plt.xlabel("n")
    plt.ylabel("Time (B-ops)")
    plt.plot(nonHeap_x, nonHeap_y, 'bo')
    plt.show()

    print("Printing Heap Greedy")
    plt.title("Heap Greedy")
    plt.xlabel("n")
    plt.ylabel("Time (B-ops)")
    plt.plot(heap_x, heap_y, 'go')
    plt.show()
            [visited_steep1, visited_gre1, visited_steep2, visited_gre2])
    return np.array(all_distance), np.array(all_visited), np.array(all_time)


def statistic(all_distance):
    best = all_distance.argmin(axis=0)
    mean = all_distance.mean(axis=0)
    worst = all_distance.max(axis=0)
    return best, worst, mean


matrixA, coordsA = prepare_coords_and_matrix(pathA)

matrixB, coordsB = prepare_coords_and_matrix(pathB)
steep = Steepest()
gre = Greedy()

all_distanceA, all_visitedA, all_timeA = do(matrixA, steep, gre, coordsA)
all_distanceB, all_visitedB, all_timeB = do(matrixB, steep, gre, coordsB)
best, worst, mean = statistic(all_distanceA)
bestT, worstT, meanT = statistic(all_timeA)
print("Best  distances for korA100:")
print("Steepest Vert | Greedy Vert |  Steepest Edges | Greedy Edges")
print(all_distanceA[best[0]][0], "         ", all_distanceA[best[1]][1],
      "           ", all_distanceA[best[2]][2], "          ",
      all_distanceA[best[3]][3])
print("Worst distances for kroA100:")
print("Steepest Vert | Greedy Vert |  Steepest Edges | Greedy Edges")
print(worst[0], "           ", worst[1], "            ", worst[2],
      "           ", worst[3])
print("Means distances for kroA100:")
예제 #31
0
def solve_it(input_data):
    # Modify this code to run your optimization algorithm

    # parse the input
    lines = input_data.split('\n')

    parts = lines[0].split()
    facility_count = int(parts[0])
    customer_count = int(parts[1])

    facilities = []
    for i in range(1, facility_count + 1):
        parts = lines[i].split()
        facilities.append(
            Facility(i - 1, float(parts[0]), int(parts[1]),
                     Point(float(parts[2]), float(parts[3]))))

    customers = []
    for i in range(facility_count + 1, facility_count + 1 + customer_count):
        parts = lines[i].split()
        customers.append(
            Customer(i - 1 - facility_count, int(parts[0]),
                     Point(float(parts[1]), float(parts[2]))))

    # distance_matrix[i][j] is the distance between the i-th customer and the j-th facility.
    distance_matrix = [[((customer.location.x - facility.location.x) ** 2 + (customer.location.y - facility.location.y) ** 2) ** 0.5 \
                        for facility in facilities]  for customer in customers]

    # read initial solution generated by Guided Local Search.
    objective_init, assignment_init = Greedy(customers, facilities)

    best_objective = objective_init
    best_assignment = assignment_init
    best_non_empty_facilities_set = set([assign for assign in best_assignment])
    best_non_empty_facilities = [
        facility for facility in best_non_empty_facilities_set
    ]
    best_empty_facilities = [
        facility for facility in range(len(facilities))
        if facility not in best_non_empty_facilities_set
    ]
    best_facility_open = [0] * len(facilities)
    for index in best_assignment:
        best_facility_open[index] = 1
    best_output = None
    #-------------------------------------------------------------------------------------------------------------------
    #-------------------------------------------------------------------------------------------------------------------

    # number of open facilities in the sub-problem
    n_non_empty_sub_facilities = 3

    # number of closed facilities in the sub-problem
    n_empty_sub_facilities = 10

    # number of facilities in the sub-problem
    n_sub_facilities = n_non_empty_sub_facilities + n_empty_sub_facilities

    round_limit = 10000000

    for round in range(round_limit):

        has_improvement = False

        while True:
            # for sub_facilities in itertools.combinations(range(len(facilities)), n_sub_facilities):

            start_time = time.time()

            # Randomly sample n_non_empty_sub_facilities facilities from open facilities
            sub_facilities_a = np.random.choice(best_non_empty_facilities,
                                                n_non_empty_sub_facilities,
                                                replace=False)

            # Randomly sample n_non_empty_sub_facilities facilities from closed facilities
            sub_facilities_b = np.random.choice(best_empty_facilities,
                                                n_empty_sub_facilities,
                                                replace=False)

            # merge the above two groups of facilities
            sub_facilities = np.append(sub_facilities_a, sub_facilities_b)

            sub_facilities_set = set(sub_facilities)

            # Select all customers that are served by the above facilities.
            sub_customers = [
                i for i in range(len(customers))
                if best_assignment[i] in sub_facilities_set
            ]

            objective_old = 0.0

            for customer in sub_customers:
                objective_old += distance_matrix[customer][
                    best_assignment[customer]]

            for facility in sub_facilities:
                objective_old += best_facility_open[facility] * facilities[
                    facility].setup_cost

            solver = pywraplp.Solver(
                'SolveIntegerProblem',
                pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)

            sub_assignment = [[
                solver.IntVar(0.0, 1.0, 'a' + str(i) + ',' + str(j))
                for j in range(len(sub_facilities))
            ] for i in range(len(sub_customers))]

            sub_facility_open = [
                solver.IntVar(0.0, 1.0, 'f' + str(j))
                for j in range(len(sub_facilities))
            ]

            # Constraint: each customer must be assigned to exactly one facility.
            for i in range(len(sub_customers)):
                solver.Add(
                    sum([
                        sub_assignment[i][j]
                        for j in range(len(sub_facilities))
                    ]) == 1)

            # Constraint: a customer must be assigned to an open facility.
            for i in range(len(sub_customers)):
                for j in range(len(sub_facilities)):
                    solver.Add(sub_assignment[i][j] <= sub_facility_open[j])

            # Constraint: the capacity of each facility must not be exceeded.
            for j in range(len(sub_facilities)):
                solver.Add(sum([sub_assignment[i][j] * customers[sub_customers[i]].demand \
                    for i in range(len(sub_customers))]) <= facilities[sub_facilities[j]].capacity)

            objective = solver.Objective()

            # Objective: sum all the distance.
            for i in range(len(sub_customers)):
                for j in range(len(sub_facilities)):
                    objective.SetCoefficient(
                        sub_assignment[i][j],
                        distance_matrix[sub_customers[i]][sub_facilities[j]])

            # Objective: sum all the setup cost.
            for j in range(len(sub_facilities)):
                objective.SetCoefficient(
                    sub_facility_open[j],
                    facilities[sub_facilities[j]].setup_cost)

            objective.SetMinimization()
            """Solve the problem and print the solution."""
            SEC = 1000
            MIN = 60 * SEC
            solver.SetTimeLimit(1 * MIN)
            result_status = solver.Solve()

            end_time = time.time()

            if result_status != solver.OPTIMAL and result_status != solver.FEASIBLE:

                print('[Round %9d/%9d] [N-Sub-Facilities %4d] [Best Objective %f] [Old Objective %f] [New Objective N/A] [Time %f]' % \
                    (round + 1, round_limit, n_sub_facilities, best_objective, objective_old, end_time - start_time))
                continue

            objective_new = solver.Objective().Value()
            assignment_new = []

            for i in range(len(sub_customers)):
                for j in range(len(sub_facilities)):
                    if sub_assignment[i][j].solution_value() == 1:
                        assignment_new.append(sub_facilities[j])
                        break

            print('[Round %9d/%9d] [N-Sub-Facilities %4d] [Best Objective %f] [Old Objective %f] [New Objective %f] [Time %f] %s' % \
                    (round + 1, round_limit, n_sub_facilities, best_objective, objective_old, objective_new, end_time - start_time, \
                    'best model found' if objective_old >= objective_new + 1 else ''))

            if objective_old >= objective_new + 1:
                best_objective -= objective_old - objective_new
                for i, j in enumerate(assignment_new):
                    best_assignment[sub_customers[i]] = j

                best_non_empty_facilities_set = set(
                    [assign for assign in best_assignment])
                best_non_empty_facilities = [
                    facility for facility in best_non_empty_facilities_set
                ]
                best_empty_facilities = [
                    facility for facility in range(len(facilities))
                    if facility not in best_non_empty_facilities_set
                ]

                best_facility_open = [0] * len(facilities)
                for index in best_assignment:
                    best_facility_open[index] = 1

                best_output = str(
                    best_objective) + ' ' + '0' + '\n' + ' '.join(
                        [str(assign) for assign in best_assignment])
                with open("mip-output.txt", 'w') as best_mip_output_file:
                    best_mip_output_file.write(best_output)

                has_improvement = True

        if not has_improvement:
            n_sub_facilities += 1

    return best_output