def main():
    table = Table(screen)
    table.draw()
    algo = Algorithm(args.algo, screen)
    algo.run(table)

    make_gif(table.id_screenshot)
Example #2
0
    def calibrate(self):
        if not self.model.fetch_data():
            self.status.showMessage("No loaded data")
            return

        dataset_initial = self.model.fetch_data()
        maxdub = Algorithm(dataset_initial)
        dataset_correction = [
            maxdub.correct(x, y) for (x, y) in dataset_initial
        ]

        union_ = [(x, y, round(xc, 1), round(yc, 1))
                  for (x, y), (xc,
                               yc) in zip(dataset_initial, dataset_correction)]
        self.model.reset()
        self.model.load_data(union_)
        # self.chartwidget.add_graph(name="Correction Magnitude", model=self.model, xcol=2, ycol=3)
        #print(self.model.fetch_data())

        xdata = []
        ydata = []
        for (_, _, x, y) in self.model.fetch_data():
            xdata.append(x)
            ydata.append(y)
        self.chartwidget.set_data(xdata, ydata)
Example #3
0
 def initialize(self):
     Algorithm.initialize(self)
     # to store results
     # tridiagonal matrix coefficients
     self.alpha = np.zeros(self.maxiter + 1)
     self.beta = np.zeros(self.maxiter)
     self.vectors = np.zeros((self.maxiter + 1, self.n))
     self.w = np.zeros(self.n)
     # starting point
     self.vectors[0] = np.random.randn(self.n)
     self.vectors[0] /= np.sqrt(norm2(self.vectors[0]))
Example #4
0
 def initialize(self):
     Algorithm.initialize(self)
     # to store results
     # tridiagonal matrix coefficients
     self.alpha = np.zeros(self.maxiter + 1)
     self.beta = np.zeros(self.maxiter)
     self.vectors = np.zeros((self.maxiter + 1, self.n))
     self.w = np.zeros(self.n)
     # starting point
     self.vectors[0] = np.random.randn(self.n)
     self.vectors[0] /= np.sqrt(norm2(self.vectors[0]))
Example #5
0
 def __init__(self, A, **kwargs):
     self.A = A
     self.n = self.A.shape[0]
     self.kwargs = kwargs
     # extract appropriate kwargs for stop condition
     maxiter = kwargs.get("maxiter", 300)
     tol = kwargs.get("tol", None)
     gtol = kwargs.get("gtol", None)
     self.stop_condition = StopCondition(maxiter=maxiter, tol=tol, gtol=gtol)
     # maxiter default to matrix size if not given.
     self.maxiter = getattr(self.stop_condition, "maxiter", self.n)
     Algorithm.__init__(self)
Example #6
0
 def __init__(self, A, **kwargs):
     self.A = A
     self.n = self.A.shape[0]
     self.kwargs = kwargs
     # extract appropriate kwargs for stop condition
     maxiter = kwargs.get("maxiter", 300)
     tol = kwargs.get("tol", None)
     gtol = kwargs.get("gtol", None)
     self.stop_condition = StopCondition(maxiter=maxiter,
                                         tol=tol,
                                         gtol=gtol)
     # maxiter default to matrix size if not given.
     self.maxiter = getattr(self.stop_condition, "maxiter", self.n)
     Algorithm.__init__(self)
Example #7
0
 def iterate(self):
     print("Iteration %i / %i" %
           (self.iter_ + 1, self.stop_condition.maxiter))
     print("Outer loop")
     self.outer()
     print("Inner loop")
     self.inner()
     return Algorithm.iterate(self)
Example #8
0
 def iterate(self):
     print("Iteration %i / %i" %
           (self.iter_ + 1, self.stop_condition.maxiter))
     print("Outer loop")
     self.outer()
     print("Inner loop")
     self.inner()
     return Algorithm.iterate(self)
def main(cfg):
    print(cfg.pretty(), end="\n\n\n")
    environment = get_environment(**cfg["environment"])
    agent = Agent.from_conf(environment, **cfg["agent"])
    replay_buffer = ReplayBufferBase.from_conf(**cfg["replay_buffer"])
    algorithm = Algorithm.from_conf(environment, agent, replay_buffer,
                                    **cfg["algorithm"])
    algorithm()
Example #10
0
 def compute(self):
     print("Compute start")
     maxdub = Algorithm(self.data)
     # for y,x in self.data:
     #     yc, xc = maxdub.correct(x, y)
     #     self.result.append([y, x, yc, xc])
     #
     # fname = "/home/tech/Workspace/python/magnetic-tools/fields.csv"
     # to_csv(fname, self.result, mode='x')
     # print("Compute Complete")
     return maxdub
Example #11
0
def main(cfg):
    print(cfg.pretty(), end="\n\n\n")
    config_path = cfg.experiment_path + "/.hydra/config.yaml"
    exp_cfg = omegaconf.OmegaConf.load(config_path)
    exp_cfg.environment.monitor = "always"
    environment = get_environment(**exp_cfg["environment"])
    agent = Agent.from_conf(environment, **exp_cfg["agent"])
    replay_buffer = ReplayBuffer.from_conf(**exp_cfg["replay_buffer"])
    algorithm = Algorithm.from_conf(environment, agent, replay_buffer,
                                    **exp_cfg["algorithm"])
    algorithm.restore_model(cfg.experiment_path + "/checkpoints")
    for i in range(cfg["n_episodes"]):
        print("{: 3d}/{: 3d}".format(i + 1, cfg["n_episodes"]), end='\r')
        algorithm.evaluate()
    def __init__(self):
        pygame.init()

        self.window = pygame.display.set_mode((Program.WINDOW_WIDTH, Program.WINDOW_HEIGHT))
        
        self.fps = 10
        self.clock = pygame.time.Clock()

        self.runMenu = True

        self.algo = Algorithm(self.window)

        self.selectionButton = Button(self.window, (color.RED, color.WHITE), 'Selection Sort', (100, 150, 250, 50), self.algo.sort)
        self.bubbleButton = Button(self.window, (color.RED, color.WHITE), 'Bubble Sort', (100, 250, 250, 50), self.algo.sort)
        self.insertionButton = Button(self.window, (color.RED, color.WHITE), 'Insertion Sort', (100, 350, 250, 50), self.algo.sort)
        self.mergeButton = Button(self.window, (color.RED, color.WHITE), 'Merge Sort', (400, 150, 250, 50), self.algo.sort)
        self.quickButton = Button(self.window, (color.RED, color.WHITE), 'Quick Sort', (400, 250, 250, 50), self.algo.sort)
        self.heapButton = Button(self.window, (color.RED, color.WHITE), 'Heap Sort', (400, 350, 250, 50), self.algo.sort)
Example #13
0
from algorithms import Algorithm
from config import target
from facebook import FacebookClient
from config import cookies

def init(client):
    username = client.get_myself_username()
    goals = client.get_friends(target)
    return (username, goals)

if __name__ == '__main__':
    client = FacebookClient(cookies)
    username, goals = init(client)
    print 'Goals: %s' % goals

    algorithm = Algorithm(username, goals, client)
    results = algorithm.bfs()

    print '------------------------------------------'
    print "RESULT PATHS: %s\n" % '\n'.join(results)
    print '------------------------------------------'
Example #14
0
    def main(self):
        args = self.__parse()

        with open(args.save_configuration if args.
                  save_configuration else self.__app_dir +
                  '/outputs/save/config.json') as f:
            save_config = json.load(f)

        if args.action == 'extract':

            with open(args.builder_configuration if args.
                      builder_configuration else self.__app_dir +
                      '/datasets/' + args.extractor + '/config.json') as f:
                dataset_builder_config = json.load(f)

            dataset = DatasetBuilder(args.extractor).build(
                args.dataset_filename_in, **dataset_builder_config)

            with open(args.extractor_configuration if args.
                      extractor_configuration else self.__app_dir +
                      '/extractors/' + args.extractor + '/config.json') as f:
                extractor_config = json.load(f)

            features = Extractor(args.extractor).extract(
                dataset, **extractor_config)

            Save.features(
                args.features_filename_out, features,
                **save_config['extract'] if 'extract' in save_config else {})

        elif args.action == 'predict':

            with open(args.features_filename_in) as f:
                features = json.load(f)

            with open(args.algorithm_configuration if args.
                      algorithm_configuration else self.__app_dir +
                      '/algorithms/' + args.algorithm + '/config.json') as f:
                algorithm_config = json.load(f)

            algorithm = Algorithm(args.algorithm,
                                  features=features,
                                  **algorithm_config)

            if args.kfold:
                y_tests, y_predictions, y_labels = algorithm.stratified_k_fold(
                    folds=args.kfold)
            else:
                raise RuntimeError

            Save.predictions(
                args.y_tests_filename, args.y_predictions_filename,
                args.y_labels_filename, y_tests, y_predictions, y_labels,
                **save_config['predict'] if 'predict' in save_config else {})

        elif args.action == 'eval':

            with open(args.y_tests_filename) as f:
                y_tests = json.load(f)

            with open(args.y_predictions_filename) as f:
                y_predictions = json.load(f)

            with open(args.y_labels_filename) as f:
                y_labels = json.load(f)

            Save.metrics(
                args.metrics_filename_out, y_tests, y_predictions, y_labels,
                **save_config['eval'] if 'eval' in save_config else {})

        elif args.action == 'plot':

            with open(args.metrics_filename_in) as f:
                metrics = json.load(f)

            with open(args.plot_configuration if args.
                      plot_configuration else self.__app_dir +
                      '/outputs/plot/config.json') as f:
                plot_config = json.load(f)

            Plot.all(args.plot_filename_out, metrics, **plot_config)
Example #15
0
import logging
from structures import Corpus, Merge
from algorithms import Algorithm
from visualization import Visualization
import utilities

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)s %(levelname)s %(message)s',
                    filename='scitext.log',
                    filemode='w')
'''
TODO:
# ADD MERGE class and functionality with master config and then allow linek to all config classes

'''
config = utilities.get_config('./config/data/master.yaml')
print('\n\nreading from the following configuration files: \n\n ',
      config['config_files'])

corpi_list = [Corpus(config_file) for config_file in config['config_files']]
corpi = Merge([corpus() for corpus in corpi_list])

alg = Algorithm(corpi, './config/algorithms.yaml')
alg.run()

vis = Visualization('./config/visualization.yaml', './config/algorithms.yaml',
                    alg)
vis.run()
Example #16
0
def main_loop(problem):
    """
    Synopsis
    --------
    Evolve the (M)HD equations through t = 0 to t = "max time".

    Args
    ----
    problem: object-like.
    User defined simulation problem.

    Attributes
    ----------
    None.

    TODO
    ----
    None.
    """

    timing = Timer(problem.parameter)
    timing.start_sim()

    log = Log(problem.parameter)

    log.logo()

    log.options()

    print("    Initialising IO...")
    io = OutputInput(problem.parameter, log)

    if problem.parameter['restart file'] is not None:
        V = io.input(problem.parameter)

    #  Initialise grid.
    grid = Grid(problem.parameter, log)

    #  Initialise Algorithms.
    print("    Assigning algorithms...")
    algorithm = Algorithm(problem.parameter, log)

    #  Generate state vector to hold conservative
    #  and primative variables.
    #  Initialise the state vector accourding to
    #  user defined problem.
    if problem.parameter['restart file'] is None:
        print("    Creating arrays...")
        V = grid.state_vector(problem.parameter, log)
        print("    Setting intial conditions...")
        problem.initialise(V, grid, log)

    #  Apply boundary conditions.
    print("    Applying boundary conditions...")
    grid.boundary(V, problem.parameter)
    print("")

    #  Check initial grid for nans.
    if np.isnan(np.sum(V)):
        print("Error, nan in initial conditions, exiting.")
        print("")
        sys.exit()

    U = np.empty(shape=V.shape, dtype=np.float64)
    prims_to_cons(V, U, algorithm.igamma_1)
    del V

    #  First output.
    timing.start_io()
    io.output(U, grid, algorithm, problem.parameter)
    timing.stop_io()
    print("")

    log.begin()

    while grid.t < grid.t_max:

        timing.start_step()
        U = algorithm.time_incriment(U, grid, algorithm, timing,
                                     problem.parameter)
        timing.stop_step()

        log.step(grid, timing)

        timing.start_io()
        io.output(U, grid, algorithm, problem.parameter)
        timing.stop_io()

        grid.update_dt()

    else:

        timing.start_step()
        U = algorithm.time_incriment(U, grid, algorithm, timing,
                                     problem.parameter)
        timing.stop_step()

        log.step(grid, timing)

    timing.start_io()
    io.output(U, grid, algorithm, problem.parameter)
    timing.stop_io()

    timing.stop_sim()

    log.end(timing)

    return U
Example #17
0
# So the position will start from 1, 1
def mouse_pos_to_cell(pos):
    y = x = -1
    for z in range(0, c.cell_nr + 1):
        if z * c.cell_side > pos[1] and y == -1:
            y = z
        if z * c.cell_side > pos[0] and x == -1:
            x = z
    return y, x


# Configure the board
board = Board(c.cell_nr, c.cell_nr)
board.create_dest((1, 1))
board.create_dest((c.cell_nr, c.cell_nr))
al = Algorithm(board)
end_pos = al.board.en

# Configure pygame window
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode(
    (c.cell_side * c.cell_nr, c.cell_side * c.cell_nr))
run = True

# Init the algorithm , check if it's finish
init = False
finish = False

while run:
    screen.fill(c.color['white'])
Example #18
0
        write_ply('../data/test_perturbed', [cloud_p.T], ['x', 'y', 'z'])

    # Optimization parameters
    max_iter = 50  # Maximum iterations in main loop
    dist_threshold = 0.1  # d_max
    RMS_threshold = 1e-5  # Convergence threshold
    kNeighbors = 20  # To compute PCA
    eps = 1e-3  # Covariance matrix parameter (for Generalized-ICP only)

    # Transformation estimation
    Comparison = 0
    if Comparison == 0:
        # Run and compare all methods
        plt.title("Convergence of the different methods")
        algos = [
            Algorithm('plane-to-plane'),
            Algorithm('point-to-plane'),
            Algorithm('point-to-point')
        ]
        for algo in algos:
            start = time()
            cloud_p_opt, RMS_list, R, T = optimize(cloud_p, cloud_o, algo,
                                                   kNeighbors, max_iter,
                                                   dist_threshold,
                                                   RMS_threshold, eps)
            print("Optimization for " + algo.name +
                  " lasted: {}s".format(round(time() - start, 2)))
            plt.plot(RMS_list, label=algo.name)
    elif Comparison == 1:
        # Compare Generalized-ICP with exact and relaxed gradients
        # Exact Gradient
Example #19
0
    districts = [1, 2, 3]
    start_condition = 1
    iterative_algorithm = 0
    additional_algorithm = 0
    plotter = 1
    setting = "standard"

    # special conditions
    lineplot = False
    option = [1, 0, 4]
    x_first = False

    # the code below enables user friendliness and is not to be changed
    for i in districts:
        title = f'District {i}: '
        algo = Algorithm(i, setting)
        plot = Plots(algo.grid)

        # start conditions
        if iterative_algorithm in [0, 1, 2]:
            if start_condition == 0:
                print("please fill in a start condition")
                break
            elif start_condition == 1:
                random()
                title += 'Random connection'
            elif start_condition == 2:
                priority_first()
                title += 'Priority first'
            elif start_condition == 3:
                proximity_first()