Пример #1
0
 def __init__(self):
     self.identify = -1  # initialized the identity, 1 is landlord, 0 is leftside at landlord, 2 is rightside
     self.labels = []    # initialized empty label
     self.bomb = 0       # check for bomb or rocket happen
     self.hand = HandsCards([])
     self.gene = Genetic()
     self.saveInstance = []
Пример #2
0
    def solver (self):

        global solution

        metrics_dict = {}
        for formula in self.formulas:
            solve = Genetic.Genetic(formula)
            solution, generation = solve.solve()

            count_variable = formula.count_variable

            if count_variable in metrics_dict:
                metrics = metrics_dict[count_variable]
            else:
                metrics = Metrics(count_variable)
                metrics_dict[count_variable] = metrics

            if solution is not None:
                metrics.count_success += 1


            else:
                metrics.count_failure += 1

        success_rate = 0
        for count_variable in metrics_dict.keys():
            metrics = metrics_dict[count_variable]

            experiments = metrics.count_success + metrics.count_failure

            if experiments:
                success_rate = metrics.count_success / (metrics.count_success + metrics.count_failure)

        return success_rate, solution, generation
Пример #3
0
def p6():
    condition = problem6.InitialState()
    output = Genetic.Genetic(condition, problem6)
    print(output["thecolors "])
    print(output["value"])
    print(output["generation"])
    xlist = range(len(output["bestG"]))
    plt.plot(xlist, output["bestG"], label="bestVals")
    plt.plot(xlist, output["worstG"], label="worstVals")
    plt.plot(xlist, output["avgG"], label="avgVals")
    plt.legend()
    plt.show()
Пример #4
0
 def __init__(self, colors, positions, ponderation, depart, pourcentage,
              TailleEligible, TaillePopu, NombreGen):
     self.responseList = []
     self.couleurs = colors
     self.Nombrepositions = positions
     self.propositions = []
     if depart == 0:
         self.propositions.append(self.PremiereProposition())
     else:
         self.propositions.append(self.PremierePropositionTest())
     self.actual_prop = self.propositions[-1]
     self.testGenetic = Genetic.Genetic(self.couleurs, self.Nombrepositions,
                                        ponderation, pourcentage,
                                        TailleEligible, TaillePopu,
                                        NombreGen)
Пример #5
0
def main():
	ga = Genetic.Genetic(popSize=1000, mutRate=5)
	ga.getGeneration(10)
Пример #6
0
import pandas as pd

import Genetic
import SiftMach

img_gray = cv.imread("TP_C01_019_copy.png", cv.IMREAD_GRAYSCALE)
img_rgb = cv.imread("TP_C01_019_copy.png", cv.IMREAD_COLOR)

# alpha = .2
# beta = 25
# img_gray = cv.convertScaleAbs(img_gray, alpha=alpha, beta=beta)

df = pd.read_csv('masks_backup.csv', sep=';', index_col=['id'])

siftmach_class = SiftMach.SiftMach(150, 40)
genetic_class = Genetic.Genetic(3, df)

while True:
    for index, gen_mask in enumerate(genetic_class.get_generation()):
        destination_gray_img = cv.filter2D(img_gray, -1, gen_mask)
        amount_of_match = siftmach_class.apply_sift(destination_gray_img, img_rgb)

        df.loc[genetic_class.get_actual_generation_index()[index], "match"] = amount_of_match

        # cv.imshow("mask: " + str(index), destination_gray_img)

        print(
            "index: {} →→ eslesen {} nokta".format(genetic_class.get_actual_generation_index()[index], amount_of_match))

    df.to_csv('mask.csv', sep=';', encoding='utf-8')
    if not genetic_class.selection():
Пример #7
0
def main(args):
    if len(args) == 4:
        k = int(args[1])
        iterations = int(args[2])
        runs = int(args[3])
        numFile = int(args[4])

        f = []
        for (dirpath, dirnames, filenames) in walk("Data"):
            f.extend(filenames)
            break

        files = [dirpath + "/" + filename for filename in f]
        file = files[numFile]
        cities, capacity, dep, name = readProblemFile(file)
        outName = "out" + name + ".csv"
        with open(outName, "w+") as out:
            print name

            times = []
            results = []
            for run in xrange(runs):

                print "Run:", run
                firstGeneration = []
                secondGeneration = queue.Queue()
                inicio = time.time()
                for i in xrange(k):
                    solution = initSolution(capacity, cities, dep)
                    firstGeneration.append(solution)

                best = deepcopy(firstGeneration[0])
                for it in xrange(iterations):
                    print "   It:", it
                    print "      Genetic"
                    for i in xrange(k):
                        mother = firstGeneration[i]
                        aux = firstGeneration[:]
                        aux.remove(mother)
                        father = choice(aux)
                        ga = Genetic(mother, father)
                        ga.cross()

                    print "      SA"
                    for solution in firstGeneration:
                        SA = SimulatedAnnealing(solution, secondGeneration)
                        SA.start()

                    for i in xrange(k):
                        solution = secondGeneration.get()
                        if best == None or solution.getCost() < best.getCost():
                            best = deepcopy(solution)
                        firstGeneration[i] = (solution)

                print "   Best:", best.getCost()
                fim = time.time()
                duracao = fim - inicio
                times.append(duracao)
                results.append(best.getCost())

            writeOutFile(out, name, times, results)
Пример #8
0
        CardType(4, 'heart', 'image/' + 'heart' + '5' + '.jpg'),CardType(4, 'dimond', 'image/' + 'dimond' + '6' + '.jpg'),
        CardType(5, 'heart', 'image/' + 'heart' + '5' + '.jpg'),CardType(5, 'heart', 'image/' + 'heart' + '5' + '.jpg')]
pre_8 = [CardType(3, 'club', 'image/' + 'club' + '3' + '.jpg'),CardType(3, 'spade', 'image/' + 'spade' + '3' + '.jpg'),
        CardType(3, 'heart', 'image/' + 'heart' + '3' + '.jpg'),CardType(4, 'heart', 'image/' + 'heart' + '4' + '.jpg'),
        CardType(4, 'heart', 'image/' + 'heart' + '4' + '.jpg'),CardType(4, 'heart', 'image/' + 'heart' + '4' + '.jpg'),
        CardType(5, 'heart', 'image/' + 'heart' + '4' + '.jpg'),CardType(5, 'heart', 'image/' + 'heart' + '4' + '.jpg')]
single = hand.getLegalSingle(pre_single)
two = hand.getLegalPair(pre_two)
three = hand.getLegalThree(pre_three)
t31 = hand.getLegalThreeWithOne(pre_31)
t4 = hand.getLegalBomb(pre_4)
t5 = hand.getLegalChain(pre_5)
t6 =hand.getLegalPairChain(pre_6)
t8 = new.getLegalAirplaneWithWings(pre_8)

landlord = Genetic()
# dna = landlord.getDNA(1)
# print(landlord.checkOutput(new1, pre_8))
lanlord_dnas = np.load('database/DNAlandlord.npy')
print(lanlord_dnas)
# dna = lanlord_dnas[1]
# data = pre_8.copy()
# data.append(dna)
# data.append((len(pre_8)))
# print(data)
# np.save("t", data)
#
# d_left = np.load("t.npy",allow_pickle=True)
# print(d_left)
# print(d_left[1].getRank())
# print("single")
Пример #9
0
import Image
import Genetic

if __name__ == '__main__':
    input_picture = int(input('Print image number (1200 - 1799): '))
    img = Image.PuzzlePicture(512, 64,
                              'data_train/64/' + str(input_picture) + '.png')
    img.show_image()
    img.cut_picture()
    metric = img.get_metric_matching_info()
    genetic = Genetic.Genetic(64, 8, metric, 'images_parts/')

    polulation = genetic.init_population()
    genetic.do_genetic(polulation)
    img.debug(input_picture)
Пример #10
0
from mpi4py import MPI
import sys
import Genetic

size = int(sys.argv[1])
generations = int(sys.argv[2])

sizeOfRanges = 10

genetic = Genetic.Genetic()
genetic.initPopulation(size)
listOfDividedPopulations = genetic.dividePopulation(sizeOfRanges)

comm = MPI.COMM_WORLD
rank = comm.rank
name = MPI.Get_processor_name()

sizeOfPopulationPerProcess = (size // sizeOfRanges) // (comm.size - 1)

if rank == 0:
    print('root rank', rank, ', with name', name)
    amountOfNodes = comm.size - 1

    dataList = []
    for x in range(amountOfNodes):
        begin = x * sizeOfPopulationPerProcess
        end = (x + 1) * sizeOfPopulationPerProcess
        dataList.append(listOfDividedPopulations[begin:end])

    counter = 0
    for data in dataList:
Пример #11
0
import random


class Problem():
    def initial_state(self):
        return [random.randint(0, 30) for i in range(4)]

    def rand_gen(self, gen_num=None):
        return random.randint(0, 30)

    def heuristic(self, state):
        heuristic_result = 0
        heuristic_result = state[
            0] + 2 * state[1] + 3 * state[2] + 4 * state[3] - 40
        return heuristic_result

    def is_goal(self, state):
        return self.heuristic(state) == 0


from Genetic import *
p = Problem()
a = Genetic(p)
a.solve()
Пример #12
0
    def genetic_algo(self, batch, result_filename):
        print(
            '***NOTE: if you want to test more than value of parameter type them and seperate with spacebar\n\
            like: 10 20 30 . And press Enter to accept.\n Type \'-1\' to use default value of parameter.***\n'
        )

        iteration = input('Type number of iteration: ')
        population_size = input('Type population size greater than 0: ')
        arena_size = input('Type arena size greater than 0: ')
        muatation_ratio = input('To ACTIVATE mutation type percent [0-100]  ')
        crossover_ratio = input('To ACTIVATE crossover type percent [0-100]  ')

        try:
            iteration = self.create_int_list(iteration)
            population_size = self.create_int_list(population_size)
            arena_size = self.create_int_list(arena_size)
            muatation_ratio = self.create_float_list(muatation_ratio)
            crossover_ratio = self.create_float_list(crossover_ratio)

        except Exception:
            print('*** Something went wrong! ***')
            sys.exit(-1)

        time = Time()

        self.csv_title(result_filename, 'Iteration', 'Population size',
                       'Arena size', 'Muatation', 'Crossover', 'Type')
        for graph in batch:
            self.print_graph(graph)
            for iters in iteration:
                for pop in population_size:
                    for arena in arena_size:
                        for mut in muatation_ratio:
                            for cros in crossover_ratio:
                                result_genetic = []
                                time_tabu = []
                                time_avg = 0
                                cost_avg = 0
                                for test in range(self.n_tests):
                                    tmp_tab = []
                                    genetic = Genetic(graph)
                                    if iters == -1:
                                        iters = genetic.number_of_iteration
                                    if pop == -1:
                                        pop = genetic.population_size
                                    if arena == -1:
                                        arena = int(pop * 0.3)
                                    if mut == -1:
                                        mut = genetic.mutation_ratio
                                    if cros == -1:
                                        cros = genetic.crossover_ratio

                                    genetic.set_genetic_properties(
                                        iters, pop, arena, mut, cros)

                                    time.start()
                                    genetic.genetic()
                                    time.stop()

                                    time_avg += time.result
                                    cost_avg += genetic.global_best_cost

                                    tmp_tab.append(genetic)
                                    tmp_tab.append(time.result)
                                    result_genetic.append(
                                        tmp_tab
                                    )  # in this list signle elements is: [tabu, time]

                                    del time.result

                                genetic = result_genetic[0][0]
                                global_time = result_genetic[0][1]
                                global_cost = genetic.global_best_cost
                                for genetic_solution in result_genetic:
                                    tmp_cost = int(repr(genetic_solution[0]))
                                    if tmp_cost < global_cost:
                                        genetic = genetic_solution[0]
                                        global_cost = tmp_cost
                                        global_time = genetic_solution[1]
                                time_avg /= self.n_tests
                                cost_avg /= self.n_tests
                                print(
                                    '\n-----------------------------------------------------------'
                                )
                                genetic.print()

                                print(
                                    'Time = {0:7f} [sec]'.format(global_time))
                                print(
                                    'Iteration: {}. Population size: {}. Arena size: {}. Mutation: {}.  Crossover: {} '
                                    .format(iters, pop, arena, mut, cros))
                                time_as_str = '{0:7f}'.format(global_time)
                                time_as_str_avg = '{0:7f}'.format(time_avg)
                                self.save_as_csv(result_filename,
                                                 len(graph[0]), time_as_str,
                                                 genetic.global_best_cost,
                                                 genetic.global_best_path,
                                                 iters, pop, arena, mut, cros,
                                                 'best found')
                                if self.n_tests > 1:
                                    self.save_as_csv(result_filename,
                                                     len(graph[0]),
                                                     time_as_str_avg, cost_avg,
                                                     '-', iters, pop, arena,
                                                     mut, cros, 'avg')