Example #1
0
File: gen.py Project: Puttini/neat
def basicGenerations():
    nbGen = 3

    ga = GenAlgo(2, 1, 5)
    ga.setSeed(0)
    ga.init()

    ga.pAddNode = 0.4
    ga.dThreshold = 2.
    ga.c3 = 2
    ga.init()

    for i, g in enumerate(ga.genomes):
        plt.subplot(nbGen + 1, 5, i + 1)
        drawGraph(g)

    print("Starting genetic algorithm")
    print("Generation %d: %d species" % (0, len(ga.popPerSpecies)))
    for gen in range(nbGen):
        ga.nextGen([len(g.connections) for g in ga.genomes])

        for i, g in enumerate(ga.genomes):
            plt.subplot(nbGen + 1, 5, (gen + 1) * 5 + i + 1)
            drawGraph(g)

        print("Generation %d: %d species" % (gen + 1, len(ga.popPerSpecies)))
Example #2
0
File: gen.py Project: Puttini/neat
def onlyCrossOver():
    nbGen = 3

    ga = GenAlgo(2, 2, 2)
    ga.setSeed(0)
    ga.init()

    g0, g1 = ga.genomes
    for _ in range(2):
        ga.addNode(g0)
        ga.addNode(g1)

    for _ in range(2):
        ga.addConnection(g0)
        ga.addConnection(g1)

    plt.subplot(nbGen + 1, 2, 1)
    drawGraph(g0)
    plt.subplot(nbGen + 1, 2, 2)
    drawGraph(g1)

    for gen in range(nbGen):
        new_gen = [
            ga.crossOver(ga.genomes[0], ga.genomes[1], 1, 1) for _ in range(2)
        ]
        ga.genomes = new_gen

        g0, g1 = ga.genomes

        plt.subplot(nbGen + 1, 2, 2 * (gen + 1) + 1)
        drawGraph(g0)
        plt.subplot(nbGen + 1, 2, 2 * (gen + 1) + 2)
        drawGraph(g1)
Example #3
0
File: gen.py Project: Puttini/neat
def onlyAddNode():
    pop = 3
    nbNodes = 4

    ga = GenAlgo(2, 2, pop)
    ga.setSeed(0)
    ga.init()

    for p in range(pop):
        g = ga.genomes[p]

        plt.subplot(nbNodes + 1, pop, p + 1)
        drawGraph(g)

        for n in range(nbNodes):
            ga.addNode(g)

            plt.subplot(nbNodes + 1, pop, p + (n + 1) * pop + 1)
            drawGraph(g, draw_dis=True)
def main():
    print("*********************************************************")
    print("Program by Krishna Bakka.")
    print("Program 3 - Elliptical curve Encryption.")
    print("*********************************************************")
#commands for getting the input from the command line.
    parser = argparse.ArgumentParser()

    parser.add_argument("-a", dest="a", help="Part 'a' of elliptical curve: y^2 = x^3 + ax + b")
    parser.add_argument("-b", dest="b", help="Part 'b' of elliptical curve: y^2 = x^3 + ax + b")
    parser.add_argument("-x1",dest="x1", help="")
    parser.add_argument("-y1",dest="y1", help="")
    parser.add_argument("-x2",dest="x2", help="")
    parser.add_argument("-y2",dest="y2", help="")

    args = parser.parse_args()
    
    x2 = fractions.Fraction(args.x2)
    y2 = fractions.Fraction(args.y2)
    a = fractions.Fraction(args.a)
    b = fractions.Fraction(args.b)
    x1 = fractions.Fraction(args.x1)
    y1 = fractions.Fraction(args.y1)
             
    if(ifPointsOnGraph(x1,x2,y1,y2,a,b)):
        point3 = []
        point3 = findPoint(x1,x2,y1,y2,a)
        x3 = point3[0]
        y3 = point3[1]
        print()
        print("The points are: ")
        print("(x1,y1) is (",fractions.Fraction(x1).limit_denominator(1000),",",fractions.Fraction(y1).limit_denominator(1000),")")
        print("(x2,y2) is (",fractions.Fraction(x2).limit_denominator(1000),",",fractions.Fraction(y2).limit_denominator(1000),")")
        print("(x3,y3) is (",fractions.Fraction(x3).limit_denominator(1000),",",fractions.Fraction(y3).limit_denominator(1000),")")
        print()
#function for drawing the graph.
        graph.drawGraph(x1,x2,y1,y2,x3,y3,a,b)
        print("*********************************************************")
Example #5
0
File: gen.py Project: Puttini/neat
def onlyAddConnection():
    pop = 3
    nbConnections = 4

    ga = GenAlgo(2, 2, pop)
    ga.setSeed(0)
    ga.init()

    for g in ga.genomes:
        for _ in range(3):
            ga.addNode(g)

    for p in range(pop):
        g = ga.genomes[p]

        plt.subplot(nbConnections + 1, pop, p + 1)
        drawGraph(g)

        for n in range(nbConnections):
            ga.addConnection(g)

            plt.subplot(nbConnections + 1, pop, p + (n + 1) * pop + 1)
            drawGraph(g, draw_dis=True)
Example #6
0
def makeCode(term, bw):
    sys.path.append(os.path.abspath(BASIS_FUNCTIONS_DIR))
    sys.path.append(os.path.abspath(PLATFORM))
    #tree = pparser.parseExp(term)
    #print(tree)
    #tree = lisparse.parse_program(term)
    tree = preprocessor.preprocess_text(term)
    tree = preprocessor.convert2primitives(tree)
    graph.drawGraph(tree, SOURCE_GRAPH)
    src_json = json.dumps(tree, indent=4, separators=(',', ': '))
    f = open(PROJECT_DIR + "/" + SOURCE_JSON, "w")
    f.write(src_json)
    f.close()
    tree = primitivelib.convertToPrimitives(tree)
    rootgen = __import__("generateRoot")
    node_list = rootgen.generateRoot(tree, bw)
    generateNodes(node_list, bw)
    graph.drawGraph(tree, PRIMITIVE_GRAPH)
    primitive_json = json.dumps(tree, indent=4, separators=(',', ': '))
    f = open(PROJECT_DIR + "/" + PRIMITIVE_JSON, "w")
    f.write(primitive_json)
    graph.makeHTML(src_json, primitive_json)
    f.close()
    return tree
Example #7
0
File: gen.py Project: Puttini/neat
def onlyChangeWeights():
    nbRows = 4
    nbCols = 3

    ga = GenAlgo(2, 2, 1)
    ga.setSeed(0)
    ga.init()

    g = ga.genomes[0]
    for _ in range(4):
        ga.addNode(g)

    for row in range(nbRows):
        for col in range(nbCols):
            if row != 0 or col != 0:
                for c in g.connections:
                    ga.changeWeight(c)
            plt.subplot(nbRows, nbCols, col + row * nbCols + 1)
            drawGraph(g, use_pos=True, draw_dis=False)

    print(" --- Final connection weights ---")
    for c in g.connections:
        if c.enabled:
            print("%d -> %d : %f" % (c.n0, c.n1, c.w))
Example #8
0
def do1b(address):  #visualizeNet in observerActions.txt

    #basic action to visualize the networkX output
    graph.openClearNetworkXdisplay()
    graph.drawGraph()
Example #9
0
                temp.append(calc[0])
                temp.append(calc[1])
                temp.append(calc[2])
                temp.append(calc[3])
                temp.append(calc[4])
                temp.append(calc[5])

                ids = []

                for element in calc[5]:
                    dependencies = []
                    for x, y in columnCollections.items():
                        if y == element:
                            dependencies.append(x)
                            break
                    ids.append(dependencies)

                temp.append(ids)
                temp.append(calc[6])
                final.append(temp)

            with open("output/" + tablaeuSource + ".csv", 'w',
                      newline='') as myfile:
                wr = csv.writer(myfile, delimiter=';')
                wr.writerows(final)


if __name__ == "__main__":
    parse()
    drawGraph(tablaeuSource, onlyConnectedFileds)
Example #10
0
    def bestCurve(self):

        # If the starting point is at a lower point than the end point,
        # it's useless to start the algorithm because the ball won't ever
        # finish the trail.
        if self.hBegin[1] < self.hEnd[1]:
            print "The answer is obvious. The ball can't get there..."
            return;

        self.createPopulation()
        self.plotMin=[]
        self.plotMax=[]
        self.plotMed=[]
        
        self.retMin = []
        self.retMax = []
        self.retMed = []
        self.retStDev = []
        
        # Starts the algorithm itself for a given number of generations.
        for i in xrange(self.numberGenerations):
            self.currentGeneration = i
            
            # If we are using cross over, we will produce two individuals at a time.
            if self.useCrossover:
                limit = self.sizePopulation / 2
            else:
                limit = self.sizePopulation

            # Now, it's time to produce the next generation.
            newGen = []

            # We will need these values for the roulette selection.
            if (self.useSelectionParents == 2):
                #Minimization Problem: 1 / (1 + fitness)
                totalFitness = 0
                   
                # First, we find the total fitness.
                for member in self.population:
                    totalFitness += (1/(1 + member.fitness))

                # Then, we divide th fitness of each individual by the total fitness.
                for member in self.population:
                    member.probFitness = (1/(1 + member.fitness)) / totalFitness
            
                
            for _ in xrange(limit):
                # We have to select two parents to the crossover.
                parentOne = None
                parentTwo = None
                                
                if(self.useSelectionParents == 1):
                    # Select parents by tournament selection.
                    parentOne = self.tournamentSelection()
                    parentTwo = self.tournamentSelection()
                elif (self.useSelectionParents == 2):
                    # Select parents by roulette selection.
                    parentOne = self.rouletteWheelSelection()
                    parentTwo = self.rouletteWheelSelection()
                    
                else:
                    pass

                sonOne = self.cloneParent(parentOne);
                sonTwo = self.cloneParent(parentTwo);
                    
                #crossover
                if( self.useCrossover ):
                    if self.rCO.random() < self.getCrossOverProb():
                        self.crossOver(sonOne , sonTwo)
                            
                if ( self.useMutation ):
                    self.mutation(sonOne)
                    self.mutation(sonTwo)

                newGen.extend([sonOne, sonTwo]);            
            
            # evaluate the newGeneration
            for i in newGen:
                i.fitness=calcBrachTime(i.points)

            newGen.sort(key = attrgetter('fitness'))
            self.population.sort(key = attrgetter('fitness'))

            # We select the individual that will survive to the next generation.
            if( self.useElitism ):
                self.elitism(self.population, newGen)
                            
            self.plotMed.append(self.currentGeneration)
            avg=self.avg()
            self.plotMed.append(avg)
            self.retMed.append(avg)
            
            min,max=self.findMinAndMaxFit()
            
            self.plotMin.append(self.currentGeneration)
            self.plotMin.append(min)
            
            self.plotMax.append(self.currentGeneration)
            self.plotMax.append(max)
            
            self.retMin.append(min)
            self.retMax.append(max)
            self.retStDev.append(self.stDev(avg))
            
            if self.plot and self.currentGeneration%self.plotOn==0:
                drawGraph(self)
            
        if (self.printPopulation):
            #self.printPopulation()
            print "\nBEST INDIVIDUAL:"
            self.printIndividual(self.population[0])        
        
        
        return [self.population[0].fitness,self.population[0].points,self.retMin,self.retMed,self.retMax,self.retStDev] 
 def __init__(self,
              type,
              num_nodes,
              num_classes=3472,
              graph_type="WS",
              num_neighbors=4,
              probability=0.5):
     super(Network, self).__init__()
     self.start = keras.layers.DepthwiseConv2D(3, strides=2)
     self.batch = keras.layers.BatchNormalization()
     if type == "small":
         self.stage_start = TripletBlock(strides=2)
         graph = generator.generateGraph(graph_type, num_nodes,
                                         num_neighbors, probability)
         generator.drawGraph(graph)
         self.stage = Stage(graph)
         graph = generator.generateGraph(graph_type, num_nodes,
                                         num_neighbors, probability)
         generator.drawGraph(graph)
         self.stage2 = Stage(graph)
         graph = generator.generateGraph(graph_type, num_nodes,
                                         num_neighbors, probability)
         generator.drawGraph(graph)
         self.stage3 = Stage(graph)
         self.relu = keras.layers.ReLU()
         self.conv = keras.layers.Conv2D(109 * 4, 1)
         self.batch2 = keras.layers.BatchNormalization()
     elif type == "normal":
         graph = generator.generateGraph(graph_type, num_nodes,
                                         num_neighbors, probability)
         generator.drawGraph(graph)
         self.stage_start = Stage(graph)
         graph = generator.generateGraph(graph_type, num_nodes,
                                         num_neighbors, probability)
         generator.drawGraph(graph)
         self.stage = Stage(graph)
         graph = generator.generateGraph(graph_type, num_nodes,
                                         num_neighbors, probability)
         generator.drawGraph(graph)
         self.stage2 = Stage(graph)
         graph = generator.generateGraph(graph_type, num_nodes,
                                         num_neighbors, probability)
         generator.drawGraph(graph)
         self.stage3 = Stage(graph)
         self.relu = keras.layers.ReLU()
         self.conv = keras.layers.Conv2D(109 * 4, 1)
         self.batch2 = keras.layers.BatchNormalization()
     self.avrg = keras.layers.AveragePooling2D(7, 1)
     self.end = keras.layers.Dense(num_classes)
Example #12
0
ourStart = (0, 0)
ourGoal = (3, 75)

'''
Perform astar to derive shortest path, then translate directions into
GoPiGo instructions.
'''

pathway = astar.aStarSearch(ourMap, ourStart, ourGoal) 

directions = translator.translate(pathway)

#Prints visual representation of our map and labels important points.

print("our example graph: ")
graph.drawGraph(ourMap, ourStart, ourGoal, pathway)
print()

print("Start node: %s" % str(ourStart))
print("Goal node: %s" % str(ourGoal))
print("A* Results: %s" % str(pathway))
print()

#Prints directions in the form of directions, then executes GoPiGo instructions.

print("Translated directions to get from start node to goal node:")
for d in directions:
    print(d)

for d in directions:
    enable_encoders()
Example #13
0
from google_sheet import read_gg_sheet
from topology import format, topologicalSort, preprocessData, prepareToDraw
from graph import drawGraph

if __name__ == '__main__':
    list_of_records = read_gg_sheet(secret_key_file='secret.json')
    apps = preprocessData(list_of_records)
    jobs_order = topologicalSort(apps)
    print(jobs_order[1])
    list_nodes, list_edges = prepareToDraw(apps)
    drawGraph(list_nodes, list_edges)





Example #14
0
        '42': [('43', 1)],
        '43': [('34', 7), ('44', 0.001)],
        '44': [('34', 7), ('45', 0.001)],
        '45': [('45', 0.3)]
    }

    emptyGraph = utils.creerGraph(0)

    graphWithoutConnections = utils.add_vertices(emptyGraph,
                                                 vertices,
                                                 src='31',
                                                 dest='45')

    g = utils.add_edges(graphWithoutConnections, edges)

    utils.drawGraph(g)

    pop = utils.creerPopulation(g, 200, True)

    distance_initial = utils.getCout(g, utils.getFittest(g, pop))

    print("Première génération : ")
    utils.displayPop(pop)

    ga = utils.GA()

    for i in range(0, 100):
        pop = utils.evoluerPopulation(ga, g, pop)
        print("G-" + str(i + 1))
        utils.displayPop(pop)
        #utils.drawGraph(g, utils.convert_to_tuples(g, utils.removeNones(utils.getFittest(g, pop))))