Beispiel #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 = []
 def __init__(self):
     self.First_Gen = Genetic.Chromosomes_Offset()
     self.Gen_S = Genetic.Gen_Selection()
     self.Gen_C = Genetic.CrossOver()
     self.Gen_M = Genetic.Mutation()
     self.Gen_List = self.Get_Gene()
     self.score = self.Get_Score()
     self.E_Cons = self.Get_ECons()
     self.F_Cons = 10
def _main():
  global CURRENT_GEN_NUMBER, SURVIVORS_PER_GEN
  print("Initializing...")
  while True:
    # wait for generation to finish
    print("Waiting for generation " + str(CURRENT_GEN_NUMBER) + " to finish.")
    while not genDoneRunning(CURRENT_GEN_NUMBER):
      sleep(0.01)
    # sleep little bit longer to avoid race conditions
    # with workers who still may be writing to Results files
    sleep(0.1)
    
    print("Getting the best runs from generation " + str(CURRENT_GEN_NUMBER) + ".")
    bestRuns = getBestRuns(CURRENT_GEN_NUMBER, SURVIVORS_PER_GEN)
    print("The best runs are: " + str(bestRuns))
    nextGenRuns = []
    # Genetic spawns a list of new runs based on the best from this gen
    print("Creating new runs...")
    for goodRun in streamRunfiles(CURRENT_GEN_NUMBER, bestRuns):
      nextGenRuns += Genetic.mutate_batch(goodRun, RUNS_PER_GEN / SURVIVORS_PER_GEN)
    
    # a new generation is born from Genetic's mutations
    CURRENT_GEN_NUMBER += 1
    makeGen(CURRENT_GEN_NUMBER)
    
    print("Writing new runs...")
    # write all new runs to separate files
    for runNum, runFrames in enumerate(nextGenRuns):
      writeRun(CURRENT_GEN_NUMBER, runNum, '\n'.join(map(str, runFrames)))
    
    print("Done writing runs.")
Beispiel #4
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
Beispiel #5
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()
def guess_password(target):
    geneset = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!."
    startTime = datetime.datetime.now()

    def fnGetFitness(genes):
        return get_fitness(genes, target)

    def fnDisplay(genes):
        display(genes, target, startTime)

    optimalFitness = len(target)
    best = Genetic.get_best(fnGetFitness, len(target), optimalFitness, geneset, fnDisplay)
    self.assertEqual(best.Genes, target)
Beispiel #7
0
    def test(self, size=8):
        geneSet = [i for i in range(size)]
        startTime = datetime.datetime.now()

        def fnDisplay(candidate):
            Display(candidate, startTime, size)

        def fnGetFitness(genes):
            return GetFitness(genes, size)

        optimalFitness = Fitness(0)
        best = Genetic.getBest(fnGetFitness, 2 * size, optimalFitness, geneSet,
                               fnDisplay)

        self.assertTrue(not optimalFitness > best.Fitness)
Beispiel #8
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)
Beispiel #9
0
def Mainthread():
    for k in range(10):
        if (k == 0):
            Gen_C = Genetic.Chromosomes_Offset()
            Gen_List = Gen_C.initGen(8)
            for i in range(len(Gen_List)):
                f = open('./CrS/' + str(i) + '.txt', 'w')
                f.write(Gen_List[i][0])
                f.write(Gen_List[i][1])
                f.close()
            Mgen = []
            Sgen = []
            for i in range(len(Gen_List)):
                Mgen.append(Gen_List[i][0])
                Sgen.append(Gen_List[i][1])
            for i in range(len(Mgen)):
                Model = Model_Converter.GeneticModel(Mgen[i], Sgen[i]).model
                model_json = Model.to_json()
                f = open('./model/model' + str(i) + '.json', 'w')
                f.write(model_json)
                f.close()
        else:
            Gen_M = gen_main.GenMain()
            Gen_M.main()

        for j in range(8):
            json_file = open("./model/model" + str(i) + ".json", "r")
            loaded_model_json = json_file.read()
            json_file.close()
            loaded_model = keras.models.model_from_json(loaded_model_json)
            memory = SequentialMemory(limit=50000, window_length=1)
            policy = BoltzmannQPolicy()
            dqn = DQNAgent(model=loaded_model,
                           nb_actions=nb_actions,
                           memory=memory,
                           nb_steps_warmup=10,
                           target_model_update=1e-2,
                           policy=policy)
            dqn.compile(Adam(lr=1e-3), metrics=['mae'])
            dqn.fit(env, nb_steps=30000, visualize=False, verbose=2)
            dqn.save_weights('t_score/dqn_' + str(k) + '_' + str(j) +
                             '{}_weights.h5f'.format(env_name),
                             overwrite=True)
            Calc_E_Cons_and_Perfomance(dqn, j)
 def __init__(self, algorithm, version, amountSolutions, maxIterations,
              param1, param2):
     self.version = version
     self.amountSolutions = amountSolutions
     if algorithm == 0:
         #print "VNE Algorithm: Genetic"
         self.algorithm = GA.GeneticAlgorithm(self.version,
                                              self.amountSolutions,
                                              maxIterations, param1, param2)
     else:
         #print "VNE Algorithm: Harmony Search"
         self.algorithm = HS.HarmonySearch(self.version,
                                           self.amountSolutions,
                                           maxIterations, param1, param2)
     if self.version == 2 or self.version == 8 or self.version >= 11:
         self.globalMemory = dict()
         self.maxMetrics = [[], [], [], [], [], [], [], [], [], [], [], [],
                            [], [], []]
         self.minMetrics = [[], [], [], [], [], [], [], [], [], [], [], [],
                            [], [], []]
Beispiel #11
0
import Genetic as g
import Summary as s
sentences = [s.Simple_Sentence("hello there"), s.Simple_Sentence("am"), s.Simple_Sentence("A big boy now")]
target = [1, 0, 2]
pop = g.population(5)
for i in pop:
    i.calc_rankings(sentences)
    print i.weights
    print i.rankings
    print g.fitness(i, target)
    print "----"

Beispiel #12
0
'''
Created on Jul 25, 2015

@author: michael
'''
import Genetic
import time
if __name__ == '__main__':
    #MAIN:
    start = time.time()        
    print "Begin Program"        
    Gen = Genetic.genetic()
    Gen.GENETIC()
    print "End Program"
    end = time.time()
    print "total running time", (end - start)