示例#1
0
 def test_average_distance_path_calculation(self):
     cities = [[1, 1], [1, 3], [3, 3], [3, 1]]
     algorithm = Algorithm(cities)
     population = [[1, 2, 3, 4], [1, 3, 2, 4],
                   [1, 4, 2, 3]]  #distance [8, 9,65... , 9,65...]
     average = algorithm.get_average_distance_path(population)
     self.assertEqual(average, 9)
示例#2
0
def run():

    time_series = defaultdict(list)

    algoInstance = Algorithm()

    # Everyday job
    base = datetime.datetime(2019, 1, 1)
    date_list = [
        base + datetime.timedelta(hours=x) for x in range((24 * 30 * 5) + 13)
    ]
    di = collections.defaultdict(int)
    # time_series = {}
    for t in date_list:
        start = t.strftime("%Y-%m-%d %H:%M:%S")
        end = (t + datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S")
        dictionary = getEdges(start, end)
        counter = 0
        #     print(dictionary)
        for key, row in dictionary.items():
            counter = counter + 1
            key = row[0] + '---' + row[1]
            time_series_expected[key].append(row[2])  #for plotting: time serie
            #         print('Processing (#', counter, ') - ', start, ' ',  key, '---', row[2])
            algoInstance.feed(key, row[2])
    print('*************************** Analysis Done')
示例#3
0
文件: TSPWindow.py 项目: shpaq23/TSP
    def __init__(self, cities, scale_x, scale_y, algorithm_type):
        """
        initializes objects
        :param cities: cities
        :param scale_x: scale x to draw cities with scale
        :param scale_y: scale y to draw cities with scale
        :param algorithm_type: algorithm type, if 1 - Genetic, if 2 - Greedy
        """

        #RESOLUTION#
        self.res = (1400, 800)
        #SCREEN#
        self.screen = ''
        #ALGORITHM#
        self.algorithm = Algorithm(cities)
        #SCALES#
        self.scale_x = scale_x
        self.scale_y = scale_y
        #CITY SIZE#
        self.size = 8
        #BACKGROUND#
        self.bg = ''
        #PathDistances#
        self.path_distances = []
        #Type of Algorithm#
        self.algorithm_type = algorithm_type
        #AVG distance of population in generations#
        self.avg_distance = []
        #distance and number of population
        self.ver = ""
示例#4
0
def main(size, popsize):
    """
    Make a horse happy by guiding it to a path on the chessboard in such a way that it
    moves to every single square once and only once. The little horsie can jump obviously
    only in the classic L shape (the chess’ horse move).

    Generate random permutations of chess board squares
    Find best individual
    Show statistics

    :param size: Size of the chess board
    :param popsize: Size of population
    """
    print("Running")
    tuples = []
    popl = []
    for i in range(size):
        for j in range(size):
            tuples.append((i, j))
    for i in range(popsize):
        random.shuffle(tuples)
        individ = Individual(size, deepcopy(tuples))
        popl.append(deepcopy(individ))
    finpop = population(popsize, popl, size)
    algo = Algorithm(size, finpop)

    evaluation, fitness, iter = algo.run()
    #statistics
    plt.plot(range(iter), fitness, label='BestFitness vs iteration')

    plt.xlabel('Iteration')
    plt.ylabel('BestFitness')
    plt.title("BestFitness evolution")
    plt.legend()
    plt.show()
    def __init__(self, grids, sep='\n'):
        """ Constructor of the class

        Keyword arguments:
        grids -- string whit grid of the sudoku to resolve, 81 non-blank
        chars e.g "00302060..
        sep -- each file of 9 should be sep for '\n'
        """
        self.digits   = '123456789'  # Valid digits of sudoku grid will contain.
        self.rows     = 'ABCDEFGHI'  # Each row of the sudoku grid will contain.
        self.cols     = self.digits  # Each col of sudoku grid will contain.

        # Each square of sudoku grid, 9 squares per sudoku e.g 'A3'
        self.squares  = self.crossProduct(self.rows, self.cols)

        # List of units in the sudoku  e.g. ['A1','B1','C1','D1','E1','F1','G1','H1','I1']
        self.unitlist = ([self.crossProduct(self.rows, c) for c in self.cols] +
                    [self.crossProduct(r, self.cols) for r in self.rows] +
                    [self.crossProduct(rs, cs) for rs in ('ABC','DEF','GHI')\
                                             for cs in ('123','456','789')])

        # Each unit of sudoku into a dictionary e.g ['A1','B1',...,'I1']
        self.units = dict((s, [u for u in self.unitlist if s in u])\
                                 for s in self.squares)

        # Each square has 20 peers
        self.peers = dict((s, set(sum(self.units[s],[]))-set([s]))\
                                            for s in self.squares)

        self.resultString = " "
        # Constructor of the class algorithm
        Algorithm.__init__(self, grids.strip().split(sep))
    def __init__(self, grids, sep='\n'):
        """ Constructor of the class

        Keyword arguments:
        grids -- the string data of the sudoku without resoved.e.g "00302060...."
        sep -- each file of 9 should be sep for '\n'
        """
        self.digits = '123456789' # Valid digits of sudoku grid will contain.
        self.rows = 'ABCDEFGHI' # Each row of the sudoku grid will contain.
        self.cols = self.digits # Each col of sudoku grid will contain.

        # Each square of sudoku grid, 9 squares per sudoku e.g 'A3'
        self.squares = self.crossProduct(self.rows, self.cols)

        # List of units in  the sudoku
        self.unitlist = ([self.crossProduct(self.rows, col) for col in self.cols] +
                    [self.crossProduct(row, self.cols) for row in self.rows] +
                    [self.crossProduct(rs, cs) for rs in ('ABC', 'DEF', 'GHI')\
                     for cs in ('123', '456', '789')])

        # Each unit of sudoku into a dictionary e.g ['A1','B1',...,'I1']
        self.units = dict((square, [unit for unit in self.unitlist if square in unit])\
                        for square in self.squares)

        # Each square has 20 peers
        self.peers = dict((square, set(sum(self.units[square], []))\
                            -set([square])) for square in self.squares)

        # Constructor of the class algorithm
        Algorithm.__init__(self, grids.strip().split(sep))
示例#7
0
    def genDatapointsLabels(self, filepath):

        algo_obj = Algorithm(self.num_machines)

        for i in range(self.num_data_points):

            # randomly pick the probability of edge formation for this particular graph
            prob_edge = random.uniform(self.min_prob_edge, self.max_prob_edge)

            # generate a dag and get the topologically sorted list of nodes
            mat, topo_sorted_list = self.genAdjMatrix(prob_edge,
                                                      self.num_jobs_arr[i])

            # find the best algorithm for this particular dag
            best_alg = algo_obj.findBestAlgo(mat, self.job_time_arr[i])

            # generate feature vector - min., max., avg. in degree; min, max, avg. out degree; min path length, max path length, max. job time, min. job time, avg. job time
            features = self.genFeatVector(mat, self.num_jobs_arr[i],
                                          self.job_time_arr[i],
                                          topo_sorted_list)

            # append the newly created feature vector and the best alg. index to the training data
            self.training_data.append(features + [self.num_jobs_arr[i]] +
                                      [prob_edge] + [best_alg])

        writeCSV(self.training_data, [
            'min. in deg', 'max. in deg', 'min. out deg', 'max. out deg',
            'avg. deg', 'min job time', 'max job time', 'avg. job time',
            'min path', 'max path', 'num_jobs', 'prob_edge', 'label'
        ], filepath)
示例#8
0
    def __init__(self):
        Algorithm.__init__(self)
	self.MLAlgorithmService = MLAlgorithmService(self)
        self.image=Image(self.baseURL() + "services/kMeansPictures/lenna.png",Width="320px", Height="360px")
        self.resultImage=Image("",Width="320px", Height="360px")
        self.loadingImage = Image(self.baseURL() + "images/blanksearching.gif")
        self.calculateButton = Button("RUN", self.onButtonClick)
        self.log = Button("SHOW LOG", self.openLogFile)
        self.log.setEnabled(False)

        self.image.addLoadListener(self)
        
        topPanel = DockPanel()
        topPanel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE)
        topPanel.add(self.calculateButton, DockPanel.WEST)
        topPanel.add(self.loadingImage, DockPanel.CENTER)
        topPanel.add(self.log, DockPanel.EAST)
        
        panel = DockPanel()
        panel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER)
        panel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE)
        #panel.add(HTML("<h2>Image compression</h2>", True))
        panel.add(topPanel, DockPanel.NORTH)
        panel.add(self.image, DockPanel.WEST)
        panel.add(self.resultImage, DockPanel.EAST)
        
        panel.setWidth("100%")
        self.initWidget(panel)
        self.image.setStyleName("ks-images-Image")
        self.calculateButton.setStyleName("ks-images-Button")
        
        self.loadImage("picturem.png")
示例#9
0
    def __init__(self):
        Algorithm.__init__(self)
        self.MLAlgorithmService = MLAlgorithmService(self)
        self.image = Image(self.baseURL() +
                           "services/kMeansPictures/lenna.png",
                           Width="320px",
                           Height="360px")
        self.resultImage = Image("", Width="320px", Height="360px")
        self.loadingImage = Image(self.baseURL() + "images/blanksearching.gif")
        self.calculateButton = Button("RUN", self.onButtonClick)
        self.log = Button("SHOW LOG", self.openLogFile)
        self.log.setEnabled(False)

        self.image.addLoadListener(self)

        topPanel = DockPanel()
        topPanel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE)
        topPanel.add(self.calculateButton, DockPanel.WEST)
        topPanel.add(self.loadingImage, DockPanel.CENTER)
        topPanel.add(self.log, DockPanel.EAST)

        panel = DockPanel()
        panel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER)
        panel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE)
        #panel.add(HTML("<h2>Image compression</h2>", True))
        panel.add(topPanel, DockPanel.NORTH)
        panel.add(self.image, DockPanel.WEST)
        panel.add(self.resultImage, DockPanel.EAST)

        panel.setWidth("100%")
        self.initWidget(panel)
        self.image.setStyleName("ks-images-Image")
        self.calculateButton.setStyleName("ks-images-Button")

        self.loadImage("picturem.png")
示例#10
0
    def __init__(self,
                 objective_fun=None,
                 start_pop=None,
                 population_filename=None,
                 plot_data=False,
                 time_eval=False,
                 sigma=DEFAULT_SIGMA,
                 lbd=None,
                 mean=None):

        Algorithm.__init__(self, objective_fun, start_pop, population_filename,
                           plot_data, time_eval)

        self.sigma = sigma
        self.m = mean
        self.lbd = lbd
        self.mu = None
        self.weights = None
        self.mu_w = None
        self.cc = None
        self.cs = None
        self.c1 = None
        self.cmu = None
        self.d_s = None
        self.chiN = None
        if self.population and self.point_dim:
            self.init_default_parameters()
示例#11
0
    def __init__(self,
                 objective_fun=None,
                 start_pop=None,
                 population_filename=None,
                 plot_data=False,
                 time_eval=False,
                 mean=None,
                 lbd=None,
                 hist_size=None,
                 path_len=None):

        Algorithm.__init__(self, objective_fun, start_pop, population_filename,
                           plot_data, time_eval)
        self.m = mean
        self.lbd = lbd
        self.mu = None
        self.weights = None
        self.weights_pop = None
        self.mu_eff = None
        self.cc = None
        self.cp = None
        self.Ft = None
        self.c_Ft = None
        self.path_len = path_len
        self.path_ratio = None
        self.hist_size = hist_size
        if self.population and self.point_dim:
            self.init_default_parameters()
示例#12
0
 def test2(self):
     x = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                   [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                   [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
     algo = Algorithm(x)
     count_islands = algo.RunSearch()
     assert count_islands == 0
示例#13
0
    def test10(self):
        x = None
        algo = Algorithm(x)

        try:
            algo.ValidateInputs()
        except Exception as e:
            assert str(e) == "Incorrect inputs. 2 dimensional matrix required"
示例#14
0
 def main():
     print("\nTesting: \n")
     tests()
     print(
         "\nThe tests are finished. This is a bigger example and here is the input:\n"
     )
     algo = Algorithm("data.txt", "param.in", True)
     algo.run()
示例#15
0
文件: main.py 项目: amaior/BBU
 def run_statistics(self):
     results = []
     for _ in range(30):
         algorithm = Algorithm(self.problem)
         results.append(algorithm.run().fitness)
     print("Average fitness: {}".format(statistics.mean(results)))
     print("Standard deviation of fitness: {}".format(
         statistics.stdev(results)))
示例#16
0
    def __init__(self):

        Algorithm.__init__(self)

        text = "<div class='infoProse'>This is the Machine Learning Algorithms page.  "
        text += "It demonstrates ... ."
        text += "<p>This sample also demonstrates ta-ta-ta: </p></div>"
        self.initWidget(HTML(text, True))
示例#17
0
    def __init__(self):

        Algorithm.__init__(self)

        text="<div class='infoProse'>This is the Machine Learning Algorithms page.  "
        text+="It demonstrates ... ."
        text+="<p>This sample also demonstrates ta-ta-ta: </p></div>"
        self.initWidget(HTML(text, True))
示例#18
0
    def test8(self):
        x = np.array([[1, 1, 1, 0, 0], [1, 1, 0, "a", 0], [0, 0, 1, "bcd", 0],
                      [0, 0, 0, 1, 1]])
        algo = Algorithm(x)

        try:
            algo.ValidateInputs()
        except Exception as e:
            assert str(e) == "Incorrect inputs. Only 0s and 1s required!"
def test_algorithm_process():
    """geomag.Algorithmtest.test_algorithm_process()

    confirms that algorithm.process returns an obspy.core.stream object
    """
    algorithm = Algorithm()
    timeseries = Stream()
    outputstream = algorithm.process(timeseries)
    assert_is_instance(outputstream, Stream)
示例#20
0
def test_algorithm_process():
    """geomag.Algorithmtest.test_algorithm_process()

    confirms that algorithm.process returns an obspy.core.stream object
    """
    algorithm = Algorithm()
    timeseries = Stream()
    outputstream = algorithm.process(timeseries)
    assert_is_instance(outputstream, Stream)
示例#21
0
 def configure(self, arguments):
     """Configure algorithm using comand line arguments.
     Parameters
     ----------
     arguments: Namespace
         parsed command line arguments
     """
     Algorithm.configure(self, arguments)
     self.statefile = arguments.adjusted_statefile
     self.load_state()
 def configure(self, arguments):
     """Configure algorithm using comand line arguments.
     Parameters
     ----------
     arguments: Namespace
         parsed command line arguments
     """
     Algorithm.configure(self, arguments)
     self.statefile = arguments.adjusted_statefile
     self.load_state()
示例#23
0
def test_algorithm_channels():
    """geomag.Algorithmtest.test_algorithm_channels()

    confirms that algorithm.get_input_channels returns the correct channels
    confirms that algorithm.get_output_channels returns the correct channels
    """
    inchannels = ['H', 'E', 'Z', 'F']
    outchannels = ['H', 'D', 'Z', 'F']
    algorithm = Algorithm(inchannels=inchannels, outchannels=outchannels)
    assert_equals(algorithm.get_input_channels(), inchannels)
    assert_equals(algorithm.get_output_channels(), outchannels)
示例#24
0
 def __init__(self):
     self.algorithm = Algorithm()
     self.conn = lite.connect(os.path.join(main_dir,'Quora.db'))
     self.cur = self.conn.cursor()
     self.cur.execute('''select id,question1,question2 from test''')
     rows = self.cur.fetchall()
     for row in rows:
         answer = self.algorithm.apply(row[1],row[2])
         self.ApplyChangeInDatabase(row[0],answer)
     self.conn.commit()
     self.conn.close()
def test_algorithm_channels():
    """geomag.Algorithmtest.test_algorithm_channels()

    confirms that algorithm.get_input_channels returns the correct channels
    confirms that algorithm.get_output_channels returns the correct channels
    """
    inchannels = ['H', 'E', 'Z', 'F']
    outchannels = ['H', 'D', 'Z', 'F']
    algorithm = Algorithm(inchannels=inchannels,
            outchannels=outchannels)
    assert_equals(algorithm.get_input_channels(), inchannels)
    assert_equals(algorithm.get_output_channels(), outchannels)
示例#26
0
def Main():
    try:
        matrix = ReadInputs()
        algo = Algorithm(matrix)
        algo.ValidateInputs()
    except Exception as e:
        print("Error in inputs:" + str(e))
        sys.exit(1)

    count_islands = algo.RunSearch()
    print("Number of islands is: " + str(count_islands))
    sys.exit(0)
示例#27
0
class Scheduler():
    def __init__(self):
        self.tickNo = 1
        self.dbm = DataManager()
        self.algo = Algorithm(self.dbm)
        self.rCon = redis.Redis(host='localhost', port=6379, db=0)

    def run(self):
        while True:
            self.algo.execute(self.tickNo)
            time.sleep(5)
            self.tickNo = self.tickNo + 1
 def __init__(self, matrix=None, pier_correction=None, statefile=None,
         data_type=None, location=None):
     Algorithm.__init__(self, inchannels=('H', 'E', 'Z', 'F'),
         outchannels=('X', 'Y', 'Z', 'F'))
     # state variables
     self.matrix = matrix
     self.pier_correction = pier_correction
     self.statefile = statefile
     self.data_type = data_type
     self.location = location
     if (matrix is None):
         self.load_state()
示例#29
0
def usa_90():
    print(
        "Problem minimalizacji kosztu dla sieci amerykanskiej z 2 sieczkami predefiniowanymi i 90 demand na kazdym"
    )
    print("Chromosomy: " + str(Parameters.amount_of_chromosomes_usa))
    print("Przepustowosc: " + str(OpticalFibersCapacity.L96.value))
    network = Network.Network.generate_network_with_admissible_paths(
        'Resources/net-us.xml')
    chromosome_creator = ChromosomeCreator()
    chromosome_utils = ChromosomeUtils()
    chromosomes = chromosome_creator.generate_chromosomes_usa_90(
        network, Parameters.amount_of_chromosomes_usa)

    # algorithm = Algorithm(chromosomes, network)
    # chromosomes = algorithm.pick_bests(chromosomes, chromosome_utils.get_network_transponders_cost,
    #                                    Parameters.amount_of_chromosomes_usa, Parameters.optical_fiber_capacity_usa)
    algorithm = Algorithm(chromosomes, network)
    chromosomes = algorithm.algorithm_usa_90(
        Parameters.optical_fiber_capacity_usa)

    print(algorithm.results)
    plot_gen = PlotGenerator([[algorithm.results, 'g--']])
    plot_gen.show_plot()

    best_chromosome = algorithm.pick_bests_sorted(
        chromosomes,
        chromosome_utils.get_network_transponders_configuration_cost, 1,
        Parameters.optical_fiber_capacity_usa)[0]
    for key in sorted(best_chromosome.paths_dict):
        print("{} -> ".format(key))
        for demand, path, transponders in zip(
                best_chromosome.paths_demand[key],
                best_chromosome.paths_dict[key],
                best_chromosome.transponders_used[key]):
            print("{} {}".format(
                demand,
                chromosome_utils.get_transponders_configuration_cost(
                    transponders)),
                  end="")
            print("{} {} ".format(path, transponders))
        print()

    t1, t2, t3 = 0, 0, 0
    for key in sorted(best_chromosome.paths_dict):
        for transponders in best_chromosome.transponders_used[key]:
            t1 += transponders[0]
            t2 += transponders[1]
            t3 += transponders[2]
    print("10:{} 40:{} 100:{}".format(t1 * 2, t2 * 2, t3 * 2))

    return algorithm.results, algorithm.time_elapsed, best_chromosome
    def __init__(self, grids):
        """
        Constructor method for the BacktrackingAlgorithm child class.

        Keyword arguments:
        grids -- String which contains the unsolved game, it should have 81
        characters, all of them digits 0-9, for example:
        "008009320000080040900500007000040090000708000060020000600001008050030000072900100"
        """
        Algorithm.__init__(self, grids)

        self.puzzle = []
        self.blanks = []
        self.runningTime = 0
示例#31
0
def main():
    algorithm = Algorithm()

    optimalIndividual = algorithm.run()
    print('Result: The detected minimum cost is ' +
          str(optimalIndividual.getFitness()))
    print("For:" + str(optimalIndividual.getChromosome()))

    mean, standardDeviation = algorithm.statistics(30)
    print("Mean:%3.9f " % mean)
    print("Standard deviation:%3.9f " % standardDeviation)
    bestFitnessList = algorithm.statisticsForPlot()
    plt.plot(bestFitnessList)
    plt.show()
示例#32
0
文件: Reader.py 项目: gonzaponte/Flow
 def __init__( self, ID = 'Reader', filelist = list(), **kwargs ):
     '''
         Initialize with an ID, a list of the files to be read and,
         optionally, other keyword arguments that will be used by
         other methods.
     '''
     Algorithm.__init__( self, ID )
     self.Files  = list(filelist) if hasattr( filelist, '__iter__' ) else [filelist]
     self.Nfiles = len(self.Files)
     self.Ifile  = 0
     self.Ievt   = 0
     self.Nread  = 0
     self.File   = None
     self.EOF    = '__EOF__'
     self.kwargs = kwargs
示例#33
0
def run_algorithm():
    # empty the Descriptors, Keypoints and Results folders first
    for f in os.listdir(app.config['DESCRIPTORS_FOLDER']):
        os.remove(os.path.join(app.config['DESCRIPTORS_FOLDER'], f))
    for f in os.listdir(app.config['KEYPOINTS_FOLDER']):
        os.remove(os.path.join(app.config['KEYPOINTS_FOLDER'], f))
    for f in os.listdir(app.config['RESULTS_FOLDER']):
        os.remove(os.path.join(app.config['RESULTS_FOLDER'], f))

    algorithm = Algorithm()
    result = algorithm.run_algorithm()
    if result == "success":
        resp = jsonify({'message': 'Algorithm successfully run'})
        resp.status_code = 200
        return resp
    def run(self):
        self.iterations = 0
        if not self.is_initialized() and self.lbd:
            self.gen_random_population(size=self.lbd)
        elif not self.is_initialized():
            self.gen_random_population()
        prev_best = self.sel_best()

        mean_time = 0 if self.time_eval else None
        # MAIN LOOP
        while not self.check_end_cond(prev_best):
            if self.time_eval:
                payload = self.evaluate_single_iteration_with_time()
                prev_best = payload['data']
                mean_time += payload['time']
            else:
                prev_best = self.single_iteration()

        if mean_time is not None:
            mean_time = mean_time / self.iterations

        return Algorithm.Result(best_point=self.sel_best(),
                                end_reason=self.end_reason,
                                mean_iteration_time=mean_time,
                                iteration_num=self.iterations)
    def __init__(self,
                 objective_fun=None,
                 start_pop=None,
                 population_filename=None,
                 plot_data=False,
                 time_eval=False,
                 f=DEFAULT_F,
                 cr=DEFAULT_CR,
                 lbd=None):
        Algorithm.__init__(self, objective_fun, start_pop, population_filename,
                           plot_data, time_eval)

        self.H = start_pop  # NUMPY ARRAY OF VECTORS
        self.cr = cr  # FLOAT - parameter for crossover
        self.f = f  # FLOAT
        self.lbd = None
示例#36
0
    def __init__(self):
        super().__init__()





        timer = QTimer(self)
        timer.setInterval(20) # interval in ms
        timer.timeout.connect(self.update)
        timer.start(0)

        self.title= "Emergency Response System"
        self.top=100
        self.left=100
        self.width=500
        self.height=500


        #button = QPushButton('button', self)
        #button.move(0,0)
        #button.clicked.connect(self.on_click)




        CarMaintainer()
        Algorithm()
        self.InitWindow()
示例#37
0
    def __init__(self):
        print("Main start")
        # set a candidate snake
        FitnessFunction.setKey(
            self,
            "1111000000000000000000000000000000000000000000000000000000001111")

        # create initial Nest
        myPop = Nest(50, True)

        # evolve out Nest until we reach an optimum
        gencount = 0
        while myPop.getFittest().get_fitness() < FitnessFunction.getMaxFitness(
                self):
            gencount += 1
            print("#" * 128)
            print("generation: ", gencount, " Fittest: ",
                  myPop.getFittest().get_fitness())
            self.print_snake(myPop)
            print("_" * 128)
            myPop = Algorithm.evolve_pop(myPop)

        print("*" * 128)
        print("Snake found")
        print("generation: ", gencount)
        self.print_snake(myPop)
        print("*" * 128)
示例#38
0
    def explore(self):
        start = time.time()
        while True:
            # Only update the UPDATED GRIDS, based on the sensor reading
            updatedGrids = self.robot.readSensors(self.completeMap)
            for n in updatedGrids:
                x, y = n[0], n[1]
                self.ui.drawGrid(x, y)

            # This checking must be done here because if not, there will be one extra ROBOT drawing (including one moveForward())
            # If the checking is done in ui.drawRobot(), the moveForward() cannot be prevented although the robot should have stopped already before moving forward
            if self.ui.checkTimeout() == False or self.ui.setMapPercentage() == False:
                break

            initialState = State(copy.deepcopy(self.robot))
            actions = Algorithm.A_star(initialState)

            for action in actions:
                r = self.robot.do(action)
                if r == False:
                    break

                self.ui.drawRobot()
                # Only update the UPDATED GRIDS, based on the sensor reading
                updatedGrids = self.robot.readSensors(self.completeMap)
                for n in updatedGrids:
                    x, y = n[0], n[1]
                    self.ui.drawGrid(x, y)

        end = time.time()
        print("RUNNING TIME:", end - start)
示例#39
0
    def configure(self, arguments):
        """Configure algorithm using comand line arguments.

        Parameters
        ----------
        arguments: Namespace
            parsed command line arguments
        """
        Algorithm.configure(self, arguments)
        self.alpha = arguments.sqdist_alpha
        self.beta = arguments.sqdist_beta
        self.gamma = arguments.sqdist_gamma
        self.m = arguments.sqdist_m
        self.mag = arguments.sqdist_mag
        self.statefile = arguments.sqdist_statefile
        self.load_state()
示例#40
0
    def configure(self, arguments):
        """Configure algorithm using comand line arguments.

        Parameters
        ----------
        arguments: Namespace
            parsed command line arguments
        """
        Algorithm.configure(self, arguments)
        self.alpha = arguments.sqdist_alpha
        self.beta = arguments.sqdist_beta
        self.gamma = arguments.sqdist_gamma
        self.m = arguments.sqdist_m
        self.mag = arguments.sqdist_mag
        self.statefile = arguments.sqdist_statefile
        self.load_state()
示例#41
0
def start_algorithm(scheduleInfoId):
    conn = _mssql.connect(server=Constants.SERVER_IP, user=Constants.USER, password=Constants.PASSWORD,
                               database=Constants.DATABASE)
    conn.execute_query('SELECT * FROM Edu_Semesters_ScheduleInfo WHERE ID = %d', scheduleInfoId)

    semesterId = 0
    isBachelor = True
    yearOfAdmission = ''
    for row in conn:
        j = json.loads(row['Settings'])
        semesterId = j['semesterId']
        isBachelor = j['isBachelor']
        yearOfAdmission = j['yearsOfAdmission']

    helper = DatabaseHelper(semesterId, yearOfAdmission, isBachelor, scheduleInfoId)
    times = helper.getTimes()
    days = helper.getDays()

    [c, ad_options] = helper.readSettings()
    # c.set_voenka_day(3)
    # c.set_bekturova_day(4)
    print c.toString()

    rooms = helper.getRooms()
    teachers = helper.getTeachers()
    students = helper.getStudents()
    courses = helper.getCourses()
    courseClasses = helper.getCourseClasses()
    # print 'Length1: ', len(courseClasses)

    courseClasses = helper.createCourseClasses()
    # print 'Length2: ', len(courseClasses)

    if len(courseClasses) > 0:
        roomReservations = helper.getRoomReservations()

        conf = Configuration(rooms, teachers, courses, courseClasses, roomReservations, ad_options, times, days)

        conn.execute_non_query(
            'UPDATE Edu_Semesters_ScheduleInfo SET StatusID = 2 WHERE ID = %d',
            scheduleInfoId)
        s = Schedule(10, 3, 70, 10, c, conf)
        a = Algorithm(100, 10, 5, s, scheduleInfoId)
        a.Start()
    else: conn.execute_non_query(
            'UPDATE Edu_Semesters_ScheduleInfo SET StatusID = 3 WHERE ID = %d',
        scheduleInfoId)
示例#42
0
 def __init__(self,codes):
     self.fitness = 0
     self.active = True
     self.positionx = 20
     self.positiony = 300
     self.speed=0
     self.direction=0
     self.algo = Algorithm(codes)
    def loadAlgorithms(self,filename):

        listalg = open(filename,'r')

        if os.path.dirname(os.path.abspath(self.ConfigPath['DB']))+'/AlgorithmsDB':
            os.remove(self.ConfigPath['prefix']+self.ConfigPath['DB']+'/AlgorithmsDB')
            self.algorithm= shelve.open(self.ConfigPath['prefix']+self.ConfigPath['DB']+'/AlgorithmsDB')

        alg=None

        self.algorithm = shelve.open(self.ConfigPath['prefix']+self.ConfigPath['DB']+'/AlgorithmsDB')

        for line in  listalg:
            line= line.strip()
            line= line.strip('\n')
            line= line.strip(' ')
            line= line.replace('"','')
            line= line.replace(' ','')

            data=line.split(':')[0]

            if (data=='algorithms'):
                flag=True
                continue

            if line == '':
                continue

            if (line == (data+':')):
                if (flag):
                    flag=False
                    alg=Algorithm(data)
                    continue
                self.algorithm[alg.Name]=alg
                alg = Algorithm(data)
                continue
            else:
                if(data=='keys'):
                    for keys in line.split(':')[1].split(','):
                        alg.properties[data].append(keys)
                else:
                    alg.properties[data] = str(line.split(':')[1])

        self.algorithm[alg.Name]=alg
        self.algorithm.close()
示例#44
0
class car:
    accelmult = 1
    dirmult = 0.1
    def __init__(self,codes):
        self.fitness = 0
        self.active = True
        self.positionx = 20
        self.positiony = 300
        self.speed=0
        self.direction=0
        self.algo = Algorithm(codes)
    def draw(self):
        pass
    def update(self,obstacles):
        x = 0
        y = 0
        min = 2000
        for z in obstacles:
            temp = z.distance()
            if temp<min:
                x = z.horizontal
                y = z.vertical
                min = temp
        inputs = []
        inputs.append(self.positionx)
        inputs.append(self.positiony)
        inputs.append(self.direction)
        inputs.append(self.speed)
        inputs.append(x)
        inputs.append(y)
        self.algo.update(inputs)
        self.speed += accelmult * self.algo.getAccel()
        self.direction += dirmult * self.algo.getDir()
        self.positionx += self.speed * math.sin(self.direction)
        self.positiony += self.speed * math.cos(self.direction)
        
    def checkcollision(self,obs):
        return obs.distance(self.positionx,self.positiony) < obs.radius
    def getCodes(self):
        return self.algo.getCodes()      
示例#45
0
 def __init__(self, alpha=None, beta=None, gamma=None, phi=1, m=1,
              yhat0=None, s0=None, l0=None, b0=None, sigma0=None,
              zthresh=6, fc=0, hstep=0, statefile=None, mag=False):
     Algorithm.__init__(self, inchannels=None, outchannels=None)
     self.alpha = alpha
     self.beta = beta
     self.gamma = gamma
     self.phi = phi
     self.m = m
     self.zthresh = zthresh
     self.fc = fc
     self.hstep = hstep
     self.statefile = statefile
     self.mag = mag
     # state variables
     self.yhat0 = yhat0
     self.s0 = s0
     self.l0 = l0
     self.b0 = b0
     self.sigma0 = sigma0
     self.last_observatory = None
     self.last_channel = None
     self.next_starttime = None
     self.load_state()
示例#46
0
def main():
	d = Data(computeSamples = False)
	trainIndices, testIndices = d.splitData()
	algo = Algorithm(d.getTrainSample(), d.getTestSample())
	# algo.computeRegressionInput()
	# algo.predictXGboost()
	algo.predictNN()
	# algo.predict()
	algo.writeSubmission()
	print(algo.evalPrecision())
示例#47
0
 def __init__(self, input, weight, relax, sort='+', name="PushRight-RelaxLeft"):
     Algorithm.__init__(self, input, weight, relax, sort, name)
示例#48
0
# Create the initial random population
my_pop = Population(10000, True)

# Loop until number of generations is complete
generation_count = 0
while my_pop.fitness_of_the_fittest() < FitnessCalc.get_max_fitness():
    generation_count += 1

    # Output the best solution every 100 generations
    if generation_count % 100 == 0:
        print("Outputting Current Status")
        my_pop.OutputFittest()

    # Quit after a set number of generations
    if generation_count == 500:
        break

    # Output current generation data and produce next generation
    print("Average Fitness : %s" % my_pop.get_average_fitness())
    print("Generation : %s Fittest : %s " % (generation_count, my_pop.fitness_of_the_fittest()))
    my_pop = Algorithm.evolve_population(my_pop)
    print("******************************************************")
    
# Output algorithm run time
finish = time()
print ("Time elapsed : %s " % (finish - start)) 

# Output the best solution found
my_pop.OutputFittest()
 def __init__(self, informat=None, outformat=None):
     Algorithm.__init__(self, inchannels=CHANNELS[informat],
             outchannels=CHANNELS[outformat])
     self.informat = informat
     self.outformat = outformat
示例#50
0
 def __init__(self,codes):
     self.positionx = 20
     self.positiony = 300
     self.speed=0
     self.direction=0
     self.algo = Algorithm(codes)
示例#51
0
 def __init__(self, input, weight, relax, sort='+', name="RelaxLeft-OnUsage"):
     Algorithm.__init__(self, input, weight, relax, sort, name)
示例#52
0
 def __init__(self, input, weight, sort="+", name="PushRight"):
     Algorithm.__init__(self, input, weight, 0, sort, name)
示例#53
0
        'MAX_FEATURES'         : 20,      # Number of features to use; or factors
        'DEFAULT_FEATURE_VALUE': 0.1,     # Initialization value for features
        'SQR_INIT'             : 0.01,    # DEFAULT_FEATURE_VALUE * DEFAULT_FEATURE_VALUE
        'MAX_EPOCHS'           : 50,      # Max epochs per feature
        'MIN_EPOCHS'           : 1,

        'MAX_MOVIES'           : 1683,    # Movies in entire training set (+1)
        'MAX_USERS'            : 944,     # Users in entire training set (+1)
        'MAX_RATINGS'          : 100001,  # Ratings in entire training set (+1)

        'TRAINING_DATASET'     : 'dataset/u1.base',
        'TEST_DATASET'         : 'dataset/u1.test',
        'RECORD_RESULTS_TO_SQL': True,
    }
    
    
]

if __name__ == "__main__":
    print 'Machine Details:'
    print '   Platform ID:  %s' % platform.platform()
    print '   Executable:   %s' % sys.executable
    print '   Python:       %s' % platform.python_version()
    print '   Compiler:     %s' % platform.python_compiler()

    for i, params in enumerate(params_suite):
        print "-----------------------------------------------------------------------------------------"
        print "                                Running training ", i
        print "-----------------------------------------------------------------------------------------"
        train = Algorithm(params)
        train.run()
示例#54
0
 def __init__(self, informat='obs'):
     Algorithm.__init__(self, inchannels=CHANNELS[informat],
             outchannels=['G'])
     self._informat = informat
示例#55
0
    def tsbtnPlay_click(self, sender, event_args):
        self._treeView1.Nodes.Clear()
        
        del self._list_of_files[0:] #delete all files in list of files

        self._find_files(self._directory_path,self._list_of_files) #finds all files recursively in the given path

        if len(self._list_of_files) == 0: #although doesn't work, but was meant to give an error message if no path selected
            MessageBox.Show("No files were found in the specified directory","Empty Dataset",MessageBoxButtons.OK,MessageBoxIcon.Exclamation)
        else:
            data_type = '' #to pass as an argument, to tell what type of data is in file listing

            #extracting features from the files can be based on 
            #frequent two word phrases
            #only words
            #noun and verbs
            feature_extraction = FeatureExtraction(self._list_of_files)
            if self._rbFrequentPhrases.Checked:
                self._file_listing = feature_extraction.get_bag_of_frequent_phrases()
                data_type = 'frequent_phrases'
            elif self._rbCommonWordsRepeat.Checked:
                self._file_listing = feature_extraction.get_bag_of_words()
                data_type = 'bag_of_words'
            elif self._rbNounVerbs.Checked:
                self._file_listing = feature_extraction.get_bag_of_nouns_verbs()
                data_type = 'noun_verb'

            #for key in self._file_listing:
            #    MessageBox.Show(str(self._file_listing[key]))
            
            document_representation = DocumentRepresentation(self._file_listing)
            if self._rbDefault.Checked:
                self._similarity_table = document_representation.get_similarity_matrix(representation = 'bow', data=data_type)
            elif self._rbVectorSpaceModel.Checked:
                self._similarity_table = document_representation.get_similarity_matrix(representation = 'vsm', data=data_type)

            for key in self._file_listing:
                self._unordered_filelist.append(key)

            algorithm = Algorithm(self._similarity_table,self._unordered_filelist, self._list_of_files)
            if self._rbHAC.Checked:
                self._cluster_set = algorithm.hierarchical_agglomerative_clustering()
            lst = algorithm.get_clusters_by_max_purity()
            #MessageBox.Show(str(self._cluster_set))
            #MessageBox.Show(str(lst))

            self._all_clusters = algorithm.get_clusters_at_all_levels()

            try:
                EvaluationMainObject = Evaluation()
                EvaluationMainObject.SetCluterList(lst)
                EvaluationMainObject.SetValueOfR()
                EvaluationMainObject.SetDocumentDictionary(self._list_of_files)
                EvaluationMainObject.CalculateIndividualPurity()
                purity = EvaluationMainObject.GetTotalPurity()
                EvaluationMainObject.CalculateEntropy()
                entropy = EvaluationMainObject.GetTotalEntropy()

                self._add_list_items(str(purity),str(entropy))
            except DivideByZeroException:
                MessageBox.Show("Division By Zero")
            
            self._populate_tree(lst)
示例#56
0
 def __init__(self, input, weight, name="PushLeft"):        
     Algorithm.__init__(self, input, weight, 0, '-', name)
示例#57
0
 def __init__(self, informat='obs', outformat='geo'):
     Algorithm.__init__(self, inchannels=CHANNELS[informat],
             outchannels=CHANNELS[outformat])
     self._informat = informat
     self._outformat = outformat