Exemple #1
0
    def execute(self):
        if self.__on_init() == False:
            self.__running = False

        champfactory = ChampionFactory()

        ## Simulates champion select:
        comp_champ = champfactory.create_champion('viking', self.__comp_rect,
                                                  self.__ground)
        player_champ = champfactory.create_champion('samurai',
                                                    self.__player_rect,
                                                    self.__ground)

        self.__computer = Computer(champion=comp_champ)
        self.__player = Player(champion=player_champ, name="Player1")
        self.__computer.setRival(self.__player.getChampion())
        self.__player.setRival(self.__computer.getChampion())

        clock = pygame.time.Clock()
        while (self.__running):
            if not USE_PYGAME_CLOCK:
                clock.tick(PYGAME_FPS)
            else:
                clock.tick()
            self.__on_loop()
            self.__on_render()

            for event in pygame.event.get():
                self.__on_event(event)

        self.__on_cleanup()
Exemple #2
0
def cal(phase):
    result = 0
    for value in phase:
        A = Computer(program, [value, result])
        A.execute()
        result = A.outputs[0]
    return result
def add_product():
    """ Adds a product to products """
    content = request.json
    try:
        id = None
        type = None
        product = None
        if content["type"] == AbstractProduct.CELLPHONE_TYPE:
            cellphone = Cellphone(content['name'], content['price'],
                                  content['cost'], content["date_stocked"],
                                  content["date_sold"], content["is_sold"],
                                  content["camera"], content["security"],
                                  content["screen_body_ratio"])
            prod_manager.add_product(cellphone)
            id = cellphone.get_id()
            type = cellphone.get_type()
            product = cellphone
        elif content["type"] == AbstractProduct.COMPUTER_TYPE:
            computer = Computer(content["name"], content["price"],
                                content["cost"], content["date_stocked"],
                                content["date_sold"], content["is_sold"],
                                content["graphics_card"], content["case"],
                                content["memory_type"])
            prod_manager.add_product(computer)
            id = computer.get_id()
            type = computer.get_type()
            product = computer
        print("id = ", id)
        print("type = ", type)
        print("prod = ", product.to_dict())
        response = app.response_class(status=200)
    except ValueError as e:
        response = app.response_class(response=str(e), status=400)
    return response
Exemple #4
0
def part2(file):
    debug = True
    buffer = deque()

    def chr_output(value):
        buffer.append(chr(value))

    def chr_input():
        return ord(buffer.popleft())

    program = parse_program(file)
    computer = Computer(program, int_input, chr_output)
    computer.run()
    view = list(map(str.strip, ''.join(buffer).strip().split('\n')))
    height = len(view)
    width = len(view[0])

    robot = find_robot(view)
    steps = build_steps(robot, view)
    actions, procedures = compact(steps)[-1]
    actions = ','.join('ABC'[i] for i in actions) + '\n'

    buffer.clear()
    buffer.extend(actions)
    for procedure in procedures:
        buffer.extend(procedure + '\n')
    buffer.extend(('y' if debug else 'n') + '\n')

    map_buffer = [[]]
    map_buffer_offset = height + 7

    def map_output(value):
        nonlocal map_buffer
        nonlocal map_buffer_offset

        if value > 255:
            print(value)
            return

        c = chr(value)

        if map_buffer_offset > 0:
            sys.stdout.write(c)
            if c == '\n':
                map_buffer_offset -= 1
            return

        map_buffer[-1].append(c)

        if c == '\n':
            map_buffer.append([])
            return

        if len(map_buffer) > height:
            cur_buffer, map_buffer = map_buffer[:-1], map_buffer[-1:]
            sys.stdout.write(''.join(''.join(s) for s in cur_buffer))

    computer = Computer(program, chr_input, map_output)
    computer.set(0, 2)
    computer.run()
Exemple #5
0
def main(player_first = True):
    WIDTH = 3
    HEIGHT = 3

    board = Board(WIDTH, HEIGHT)
    interaction = Interaction(WIDTH, HEIGHT)
    computer = Computer()
    turn = 'X'
    if player_first:
        computer_tile = 'O'
    else:
        computer_tile = 'X'

    while board.get_winner() is None and not board.is_cat_game():
        if turn == computer_tile:
            x, y = computer.get_move(board, computer_tile)
            board.place_tile(turn, x, y)
        else:
            x, y = interaction.get_move(turn, board)
            board.place_tile(turn, x, y)
        if turn == 'X':
            turn = 'O'
        else:
            turn = 'X'

    if board.is_cat_game():
        interaction.display_cat_game(board)
    else:
        interaction.display_winner(board, board.get_winner() != computer_tile)
Exemple #6
0
 def __init__(self, addr, program, network):
     self._addr = addr
     self._computer = Computer(program, self._processInput, self._output)
     self._network = network
     self._processing = None
     self._write_buffer = []
     self._inputMode = 0
Exemple #7
0
def run():
    pile = Deck.standard_deck()
    pile.shuffle()

    player_hand = Hand("Player")
    computer_hand = Hand("Computer")

    player = Player()
    computer = Computer()

    while not player.stopped:

        if player_stops():
            player.stop()
        else:
            player.draw(player_hand, pile)

        print(player_hand)

        if RuleSet.sums_to_21(player_hand) or RuleSet.is_bust(player_hand):
            break

        print("---------")
        print("Total: {0}".format(player_hand.sum()))

    computer.play(computer_hand, pile, player_hand)

    print("\n=== WINNER ===")
    print("---------")
    winning_hand = RuleSet().determine_winner(computer_hand, player_hand)

    if RuleSet.sums_to_21(winning_hand):
        print("{0} got 21".format(winning_hand.holder))
    else:
        print("{0} won ({1})".format(winning_hand.holder, winning_hand.sum()))
Exemple #8
0
 def  __init__(self, computer, resource_response):
     ip = computer.ip_address
     port = computer.port
     Computer.__init__(self, ip, port)
     self.resource_response = resource_response
     self.task_to_solve = None
     self.work_response = None
def intcode(library, program):
    """ Create an IntCode Computer """

    computer = Computer(library, program)
    computer.flash_memory()

    return computer
Exemple #10
0
def main():
    # updated input
    input = "1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,9,19,1,10,19,23,2,9,23,27,1,6,27,31,2,31,9,35,1,5,35,39,1,10,39,43,1,10,43,47,2,13,47,51,1,10,51,55,2,55,10,59,1,9,59,63,2,6,63,67,1,5,67,71,1,71,5,75,1,5,75,79,2,79,13,83,1,83,5,87,2,6,87,91,1,5,91,95,1,95,9,99,1,99,6,103,1,103,13,107,1,107,5,111,2,111,13,115,1,115,6,119,1,6,119,123,2,123,13,127,1,10,127,131,1,131,2,135,1,135,5,0,99,2,14,0,0"
    inputList = [int(d) for d in input.split(",")]

    # part A
    inputA = inputList.copy()
    inputA[1] = 12
    inputA[2] = 2
    computerA = Computer(inputA)
    outputA = computerA.run()
    print(f"Part a: {next(outputA)[0]}")

    # part B
    for noun, verb in product(range(0, 100), range(0, 100)):
        inputB = inputList.copy()
        inputB[1] = noun
        inputB[2] = verb
        outputB = Computer(inputB).run()

        if next(outputB)[0] == 19690720:
            print(
                f"noun is {noun}, verb is {verb}, the number seeked (100*noun + verb) is: {100*noun + verb}"
            )
            break
def game():
    board = [i for i in range(10)]
    print("Press 0 at any time to quit")
    h = input("If you want to go first enter X, otherwise enter O ")
    c = 'O'
    if h == "0":
        quit()
    elif h.upper() == "O":
        h, c = 'O', "X"
    else:
        h = "X"
    comp = Computer(c, h)

    # Human move if Human is X
    if h == "X":
        print_board(board)
        board = m(board, h)

    while board is not 0:
        # Computer move
        board = comp.make_move(board)
        if board == 0:
            break
        # Human move
        board = m(board, h)
Exemple #12
0
def solve_part_one() -> int:
    """Uncomment the `print` statements to see how the beam looks on a plane."""

    with open("19_input", "r") as f:
        program: List[int] = [int(code) for code in f.read().split(",")]

    x_min = 0
    x_max = 50  # excluding x_max
    y_min = 0
    y_max = 50  # excluding y_max

    affected_field_count = 0

    for y in range(y_min, y_max):
        # print(f"{y}: ", end="")
        for x in range(x_min, x_max):
            drone = Computer(opcodes=program.copy(), inputs=[x, y])
            drone.solve()
            # drone.inputs will contain the output of the program;
            # 0 - no effect, 1 - affected field
            affected_field_count += drone.inputs[-1]

            # print("." if drone.inputs[-1] == 0 else "#", end="")
        # print()

    return affected_field_count
Exemple #13
0
 def engine_stop(self, engine_id):
     """Stop a specific engine"""
     # delete computer information in db
     DrQueueComputer.delete_from_db(engine_id)
     # shutdown computer
     self.ip_client.shutdown(engine_id)
     return True
Exemple #14
0
def part2(state):
    TARGET = 19690720
    for noun, verb in itertools.product(range(100), repeat=2):
        comp = Computer(state, mem_override={1: noun, 2: verb})
        comp.run()
        if comp.mem0 == TARGET:
            return 100 * noun + verb
Exemple #15
0
def build_computer(cpu, ram, motherboard):
    computer = Computer()
    computer.motherboard = motherboard
    computer.cpu = cpu
    computer.ram = ram

    return computer
Exemple #16
0
    def mouse_clicked(self, evt):
        if evt.y <= 0:
            return

        for i in range(len(self.SQUARE_COORDINATES)):
            if ((evt.x <= self.SQUARE_COORDINATES[i]['bottom_right_corner_x'])
                    and (evt.y <=
                         self.SQUARE_COORDINATES[i]['bottom_right_corner_y'])):
                self.draw_text(i, self.SQUARE_COORDINATES[i]['letter_x'],
                               self.SQUARE_COORDINATES[i]['letter_y'])
                break

        if self.game_has_a_winner():
            messagebox.showinfo('The Xs win!', 'The Xs win!')
            self.reset()
            return
        elif self.game_is_a_draw():
            messagebox.showinfo('Draw', 'This game is a draw')
            self.reset()
            return

        computer = Computer(self.squares)
        messagebox.showinfo('Computer Message', computer.message())
        i = computer.square()
        self.draw_text(i, self.SQUARE_COORDINATES[i]['letter_x'],
                       self.SQUARE_COORDINATES[i]['letter_y'])

        if self.game_has_a_winner():
            messagebox.showinfo('The Os win!', 'The Os win!')
            self.reset()
        elif self.game_is_a_draw():
            messagebox.showinfo('Draw', 'This game is a draw')
            self.reset()
Exemple #17
0
def get_intersection(code):
    computer = Computer(code, [])
    computer.run()

    x = 0
    y = 0
    sum_alignment = 0
    items = defaultdict(list)
    for ascii_item in computer.get_whole_output():
        if ascii_item == 10:
            y += 1
            print()
        else:
            x += 1
            items[y].append(ascii_item)
            print(chr(ascii_item), end='')

    # check for intersections
    sum_alignment = 0
    num_intersections = 0
    for x in range(len(items[0])):
        for y in range(len(items.keys())):
            if x > 0 and x < len(items[0]) - 1:
                if y > 0 and y < len(items.keys()) - 1:
                    if chr(items[y][x]) == '#' and chr(
                            items[y - 1][x]) == '#' and chr(
                                items[y + 1][x]) == '#' and chr(
                                    items[y][x - 1]) == '#' and chr(
                                        items[y][x + 1]) == '#':
                        num_intersections += 1
                        sum_alignment += x * y
    print("Star 1: Sum of alignment:", sum_alignment)
Exemple #18
0
 def __init__(self):
     """Initialize the board as a nested array, specifying four tiles
     in the middle"""
     self.grid = Grid(600, 600, 100)
     self.WIDTH = self.grid.SPACING * 0.85
     self.HEIGHT = self.grid.SPACING * 0.85
     self.computer = Computer(self)
     self.row = self.grid.HEIGHT // self.grid.SPACING
     self.col = self.grid.WIDTH // self.grid.SPACING
     self.full_tile = self.row * self.col
     self.full = False
     self.tile = [[0] * self.col for i in range(self.row)]
     # Initialize starting four tiles.
     # 1 stands for black tile
     # 2 stands for white tile
     self.tile[self.row // 2 - 1][self.col // 2 - 1] = 2
     self.tile[self.row // 2][self.col // 2] = 2
     self.tile[self.row // 2 - 1][self.col // 2] = 1
     self.tile[self.row // 2][self.col // 2 - 1] = 1
     self.black_tile = 2
     self.white_tile = 2
     self.counter = 1  # Indicate whether player or AI's turn
     self.legal_move = False
     self.flip_tiles = []
     self.interval = 2000
     self.over = False
     self.text_position_x = self.grid.WIDTH / 2 - 100
     self.text_position_y = self.grid.HEIGHT / 2
Exemple #19
0
def main():
    to_guess = input("Numero a adivinar: ")
    computer = Computer(to_guess)
    while computer.game.check_win():
        computer.play()
    print("\nNumero adivinado por la computadora: ",computer.getNumber())
    print("Se ha terminado en ",computer.game.get_tries()," intentos")
Exemple #20
0
class TestComputer(unittest.TestCase):
    WIDTH = 3
    HEIGHT = 3

    def setUp(self):
        self.computer = Computer()
        self.board = Board(self.WIDTH, self.HEIGHT)

    def update_board_to(self, new_board):
        for y in range(0, self.HEIGHT):
            for x in range(0, self.WIDTH):
                tile = new_board[y][x]  # Swap to match
                if tile is not '-':
                    self.board.place_tile(tile, x, y)

    def assert_board(self, board, tile, expected_move):
        self.update_board_to(board)
        move = self.computer.get_move(self.board, tile)
        self.assertEqual(move, expected_move)

    def test_win(self):
        self.assert_board([['X', 'O', 'X'], ['X', 'O', 'X'], ['-', '-', 'O']],
                          'X', (0, 2))

    def test_stop_loss(self):
        self.assert_board([['X', 'O', 'X'], ['X', '-', 'O'], ['-', '-', 'O']],
                          'O', (0, 2))

    def test_beat_trap(self):
        self.update_board_to([['X', '-', '-'], ['-', 'O', '-'],
                              ['-', '-', 'X']])
        move = self.computer.get_move(self.board, 'O')
        self.assertNotEqual(move, (0, 2))
        self.assertNotEqual(move, (2, 0))
Exemple #21
0
def check_events(screen, settings, chessmans, chessboard):
    '''
    检查输入输出状态
    :param screen:界面引用
    :param settings:游戏设置
    :param chessmans:棋子group
    :param chessboard:棋盘
    :return:
    '''
    for event in pygame.event.get():
        if event.type in (pygame.QUIT, ):  #pygame.KEYDOWN
            sys.exit()
        elif settings.player_round and event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            return put_chessman(screen, settings.player_color,
                                [mouse_x, mouse_y], settings, chessmans,
                                chessboard)
        elif settings.player_round == False:
            computer = Computer(settings, chessboard)
            # # if(color_num==1):
            computer_act_list = computer.max_min_search(
                settings, computer.root, 2)
            # print(computer_act_list)
            computer_act = random.choice(computer_act_list)
            print(computer_act)
            return put_chessman(screen, settings.computer_color, computer_act,
                                settings, chessmans, chessboard)
        return None
Exemple #22
0
def main(player_first=True):
    WIDTH = 3
    HEIGHT = 3

    board = Board(WIDTH, HEIGHT)
    interaction = Interaction(WIDTH, HEIGHT)
    computer = Computer()
    turn = 'X'
    if player_first:
        computer_tile = 'O'
    else:
        computer_tile = 'X'

    while board.get_winner() is None and not board.is_cat_game():
        if turn == computer_tile:
            x, y = computer.get_move(board, computer_tile)
            board.place_tile(turn, x, y)
        else:
            x, y = interaction.get_move(turn, board)
            board.place_tile(turn, x, y)
        if turn == 'X':
            turn = 'O'
        else:
            turn = 'X'

    if board.is_cat_game():
        interaction.display_cat_game(board)
    else:
        interaction.display_winner(board, board.get_winner() != computer_tile)
Exemple #23
0
def run_until(x, y, target_output, program):
    while True:
        comp = Computer(program, input=(x, y))
        comp.run()
        if comp.collect() == target_output:
            return x
        x += 1
Exemple #24
0
def part1():
    lines = read_file_lines()
    program = [int(code) for code in lines[0].split(',')]
    computer = Computer(program)
    computer.run()
    out = computer.send_output()
    print(len([x for x in out[2:-1:3] if x == 2]))
Exemple #25
0
def main():
    audit_data = []
    config_profile_mapping = config_profile_map()
    client = JamfApi()
    response = client.jamf_call(
        method='get',
        path='/computers',
    )

    computer_ids = [x.get('id', {}) for x in response.json().get('computers', {})]

    for computer_id in computer_ids:

        response = client.jamf_call(
            method='get',
            path=f"/computers/id/{computer_id}",
        )
        computer = Computer(response.json().get('computer'))
        configuration_profile_ids = [x.get('id') for x in computer.configuration_profiles()]

        for configuration_profile_id in configuration_profile_ids:
            if configuration_profile_id in config_profile_mapping.keys():
                audit_data.append(f"{computer.serial_number()},{config_profile_mapping[configuration_profile_id]}")

    for line in audit_data:
        print(line)
    print(len(audit_data))
Exemple #26
0
def part2():
    ascii_answer = "A,B,B,A,C,B,C,C,B,A\n" + \
        "R,10,R,8,L,10,L,10\n" + \
        "R,8,L,6,L,6\n" + \
        "L,10,R,10,L,6\n" + \
        "n\n"
    

    raw_answer = [ord(c) for c in ascii_answer] 
    print(raw_answer)

    code = parse_input("input.txt")
    code[0] = 2

    computer = Computer(code)
    output = computer.run_on_input(raw_answer)
    as_ascii = [chr(n) for n in output[:-1]]
    rows = "".join(as_ascii).split("\n")

    for y, r in enumerate(rows):
        for x, c in enumerate(r):
            print(c, end="")
        print()

    print("Answer to Part 2: ", output[-1])
Exemple #27
0
def part1():
    code = parse_input("input.txt")
    computer = Computer(code)
    output = computer.run_on_input([])
    as_ascii = [chr(n) for n in output]
    rows = "".join(as_ascii).split("\n")

    grid = defaultdict(lambda: ".")
    scaffolding = set()
    for y, r in enumerate(rows):
        for x, c in enumerate(r):
            grid[(x, y)] = c
            if c == '#':
                scaffolding.add((x, y))
            # print(c, end="")
        # print()
    
    intersections = set()
    a1 = 0
    for c in scaffolding:
        if all(a in scaffolding for a in get_adjacent(*c)):
            intersections.add(c)
            grid[c] = "0"
            a1 += c[0] * c[1]
    
    print_grid(grid)
    print("Answer to Part 1: ", a1)
Exemple #28
0
 def test_play_ok(self):
     juego = Computer()
     self.assertTrue(juego.play())
     self.assertFalse(juego.error)
     self.assertTrue(juego.loop_bien)
     self.assertTrue(juego.loop_regular)
     self.assertTrue(juego.loop_general)
Exemple #29
0
def feedback(data, permutation):
    e_out = 0
    a_queue = deque([permutation[0], e_out])
    b_queue = deque([permutation[1]])
    c_queue = deque([permutation[2]])
    d_queue = deque([permutation[3]])
    e_queue = deque([permutation[4]])

    a = Computer(data.copy()).run(a_queue)
    b = Computer(data.copy()).run(b_queue)
    c = Computer(data.copy()).run(c_queue)
    d = Computer(data.copy()).run(d_queue)
    e = Computer(data.copy()).run(e_queue)

    while True:
        b_queue.append(next(a, None))
        c_queue.append(next(b, None))
        d_queue.append(next(c, None))
        e_queue.append(next(d, None))

        try:
            e_out = next(e)
            a_queue.append(e_out)
        except:
            break
    return e_out
Exemple #30
0
def test_all_legal_moves():
    """Test all_legal_moves method.
    When the game is initialized, there are four legal moves
    for either black or white tile"""
    tile = Tile()
    computer = Computer(tile)
    legal_move = computer.all_legal_moves()
    assert legal_move == [(2, 3), (3, 2), (4, 5), (5, 4)]
Exemple #31
0
def main():
    f = open("input.txt")
    s = f.readline()
    memory = list(map(int, s.split(",")))

    c = Computer(memory, 12, 2)
    c.execute()
    print(c.read(0))
Exemple #32
0
 def __init__(self, program):
     self.com = Computer(program)
     self.graph = {}
     self.buffer = ''
     self.x = self.y = 0
     self.c_x = self.c_y = 0
     self.im = Image.new('RGB', (50, 50))
     self.direc = [0,-1]
Exemple #33
0
def intcode(library, program):
    """ Create an IntCode Computer """

    computer = Computer(library, program)
    computer.flash_memory()
    computer.halt_condition = True

    return computer
Exemple #34
0
def content():
    data = request.form['data']
    ass = Assembler(data)
    ass.gen_bin_instructions()
    c = Computer()
    program_start, end = ass.load(c.ram)
    c.run(program_start)
    return jsonify({
        'assembler': ass.show_ins_table(),
        'run': c.ram.show_relevant(program_start, end),
        'storage': show_bin_rep(data)
    })
def main():
    player = Player()
    computer = Computer()

    print("Welcome to Simple Turn Based Game")
    print("Featuring a simple A.I.\n")

    while 1:
        while 1:
            print("Press q to quit at any time\n")
            # Give player choices
            print("1. Weak Attack")
            print("2. Strong Attack")
            print("3. Heal")
            print("4. Improve Attack")
            print("5. Improve Defense")
            print("6. Show Health\n")
            choice = input(": ")
            print()

            if choice == 'q':
                print("Exiting...")
                return
            elif choice == '1':
                computer.atked_weak()
                break
            elif choice == '2':
                computer.atked_strong()
                break
            elif choice == '3':
                player.heal()
                break
            elif choice == '4':
                computer.imp_player_atk()
                break
            elif choice == '5':
                player.imp_def()
                break
            elif choice == '6':
                win_cond(player, computer)
            else:
                print("That is not an option.\n")

        print()
        if win_cond(player, computer):
            return

        print()

        # AI's turn
        computer.move(player.hp)

        if win_cond(player, computer):
            return
        print("\n")
Exemple #36
0
 def __init__(self):
     self.board = Board()
     self.bag = Bag()
     self.dict = utility.get_dictionary()
     self.user = User(self.bag)
     self.computer = Computer(self.bag)
     self.moves_log = []
class TestComputer(unittest.TestCase):
    WIDTH = 3
    HEIGHT = 3
    def setUp(self):
        self.computer = Computer()
        self.board = Board(self.WIDTH, self.HEIGHT)

    def update_board_to(self, new_board):
        for y in range(0, self.HEIGHT):
            for x in range(0, self.WIDTH):
                tile = new_board[y][x] # Swap to match
                if tile is not '-':
                    self.board.place_tile(tile, x, y)

    def assert_board(self, board, tile, expected_move):
        self.update_board_to(board)
        move = self.computer.get_move(self.board, tile)
        self.assertEqual(move, expected_move)

    def test_win(self):
        self.assert_board(
                [['X', 'O', 'X'],
                 ['X', 'O', 'X'],
                 ['-', '-', 'O']],
                'X', (0, 2))

    def test_stop_loss(self):
        self.assert_board(
                [['X', 'O', 'X'],
                 ['X', '-', 'O'],
                 ['-', '-', 'O']],
                'O', (0, 2))

    def test_beat_trap(self):
        self.update_board_to(
                [['X', '-', '-'],
                 ['-', 'O', '-'],
                 ['-', '-', 'X']])
        move = self.computer.get_move(self.board, 'O')
        self.assertNotEqual(move, (0, 2))
        self.assertNotEqual(move, (2, 0))
Exemple #38
0
 def identify_computer(self, engine_id, cache_time):
     """Gather information about computer"""
     # look if engine info is already stored
     engine = DrQueueComputer.query_db(engine_id)
     now = int(time.time())
     # check existence and age of info
     if (engine != None) and (now <= engine["date"] + cache_time):
         print ("DEBUG: Engine %i was found in DB" % engine_id)
     # store new info
     else:
         print ("DEBUG: Engine %i was not found in DB" % engine_id)
         # run command only on specific computer
         dview = self.ip_client[engine_id]
         dview.block = True
         dview.execute(
             "import DrQueue\nfrom DrQueue import Computer as DrQueueComputer\nengine = DrQueueComputer("
             + str(engine_id)
             + ")"
         )
         engine = dview["engine"]
         engine["date"] = int(time.time())
         DrQueueComputer.store_db(engine)
     return engine
    def __init__(self, humanBoard, computerBoard, humanScore, computerScore, 
                            humanIsFirstPlayer, humanIsNext, diceQueue, didLoad):
        self.human = Human(humanScore)
        self.computer = Computer(computerScore)
        self.diceQueue = diceQueue
        self.humanIsFirstPlayer = humanIsFirstPlayer
        self.humanIsNext = humanIsNext
        self.exitCode = 0
        self.board = Board(humanBoard, computerBoard)
        self.turnCount = 0
        self.returnList = [False, 0, 0]

        if didLoad:
            self.resumeRound()
        else:
            self.newRound()
class TableWindow(QWidget):
    """
    Визуализира играта.
    """
    def __init__(self):

        super(TableWindow, self).__init__()
        self.cols = []
        self.pc = Computer("B")
        self.vsPC = True
        self.win_dialog = WinDialog()
        self.compuret_win = ComputerWinDialog()

        self.first_player_time = Timer()
        self.first_player_time.start()

        self.col_one_edit = QTextEdit()
        self.col_one_edit.setReadOnly(True)

        self.col_two_edit = QTextEdit()
        self.col_two_edit.setReadOnly(True)

        self.col_three_edit = QTextEdit()
        self.col_three_edit.setReadOnly(True)

        self.col_four_edit = QTextEdit()
        self.col_four_edit.setReadOnly(True)

        self.col_five_edit = QTextEdit()
        self.col_five_edit.setReadOnly(True)

        self.col_six_edit = QTextEdit()
        self.col_six_edit.setReadOnly(True)

        self.col_seven_edit = QTextEdit()
        self.col_seven_edit.setReadOnly(True)

        self.col_eight_edit = QTextEdit()
        self.col_eight_edit.setReadOnly(True)

        self.col_nine_edit = QTextEdit()
        self.col_nine_edit.setReadOnly(True)

        self.col_ten_edit = QTextEdit()
        self.col_ten_edit.setReadOnly(True)

        self.col_one_edit = QTextEdit()
        self.col_one_edit.setReadOnly(True)

        label_on_turn = QLabel()
        label_on_turn.setText("On turn:")

        self.player = QLabel()
        self.player.setText("R")

        self.player_time = QLabel()
        self.player_time.setText("Time player R:")

        self.player_game_time = QLabel()
        self.player_game_time.setText(" ")

        self.adding_to_vector()
        self.onTurn = 1
        self.t = Table()

        self.read_table()

        firstButton = QPushButton("&")
        firstButton.setFocusPolicy(Qt.NoFocus)
        firstButton.clicked.connect(self.first_button_clicked)

        secondButton = QPushButton("&")
        secondButton.setFocusPolicy(Qt.NoFocus)
        secondButton.clicked.connect(self.second_button_clicked)

        thirdButton = QPushButton("&")
        thirdButton.setFocusPolicy(Qt.NoFocus)
        thirdButton.clicked.connect(self.third_button_clicked)

        fourthButton = QPushButton("&")
        fourthButton.setFocusPolicy(Qt.NoFocus)
        fourthButton.clicked.connect(self.fourth_button_clicked)

        fifthButton = QPushButton("&")
        fifthButton.setFocusPolicy(Qt.NoFocus)
        fifthButton.clicked.connect(self.fifth_button_clicked)

        sixthButton = QPushButton("&")
        sixthButton.setFocusPolicy(Qt.NoFocus)
        sixthButton.clicked.connect(self.sixth_button_clicked)

        seventhButton = QPushButton("&")
        seventhButton.setFocusPolicy(Qt.NoFocus)
        seventhButton.clicked.connect(self.seventh_button_clicked)

        eighthButton = QPushButton("&")
        eighthButton.setFocusPolicy(Qt.NoFocus)
        eighthButton.clicked.connect(self.eighth_button_clicked)

        ninthButton = QPushButton("&")
        ninthButton.setFocusPolicy(Qt.NoFocus)
        ninthButton.clicked.connect(self.ninth_button_clicked)

        tenthButton = QPushButton("&")
        tenthButton.setFocusPolicy(Qt.NoFocus)
        tenthButton.clicked.connect(self.tenth_button_clicked)

        layout = QGridLayout()
        layout.addWidget(firstButton, 0, 0)
        layout.addWidget(secondButton, 0, 1)
        layout.addWidget(thirdButton, 0, 2)
        layout.addWidget(fourthButton, 0, 3)
        layout.addWidget(fifthButton, 0, 4)
        layout.addWidget(sixthButton, 0, 5)
        layout.addWidget(seventhButton, 0, 6)
        layout.addWidget(eighthButton, 0, 7)
        layout.addWidget(ninthButton, 0, 8)
        layout.addWidget(tenthButton, 0, 9)
        layout.addWidget(self.col_one_edit, 1, 0)
        layout.addWidget(self.col_two_edit, 1, 1)
        layout.addWidget(self.col_three_edit, 1, 2)
        layout.addWidget(self.col_four_edit, 1, 3)
        layout.addWidget(self.col_five_edit, 1, 4)
        layout.addWidget(self.col_six_edit, 1, 5)
        layout.addWidget(self.col_seven_edit, 1, 6)
        layout.addWidget(self.col_eight_edit, 1, 7)
        layout.addWidget(self.col_nine_edit, 1, 8)
        layout.addWidget(self.col_ten_edit, 1, 9)
        layout.addWidget(label_on_turn, 2, 0)
        layout.addWidget(self.player, 2, 1)
        layout.addWidget(self.player_time, 2, 2)
        layout.addWidget(self.player_game_time, 2, 3)

        self.setLayout(layout)

        self.setWindowTitle("Connect Four")
        self.resize(550, 450)

    def adding_to_vector(self):
        """Добавя бутоните към масив от позициите
        на който може да се постави елемента"""
        self.cols.append(self.col_one_edit)
        self.cols.append(self.col_two_edit)
        self.cols.append(self.col_three_edit)
        self.cols.append(self.col_four_edit)
        self.cols.append(self.col_five_edit)
        self.cols.append(self.col_six_edit)
        self.cols.append(self.col_seven_edit)
        self.cols.append(self.col_eight_edit)
        self.cols.append(self.col_nine_edit)
        self.cols.append(self.col_ten_edit)

    def read_table(self):
        """Прочита таблицата от Table и я попълва в UI-a.
        Ако има победител, пуска нов прозер.
        """
        result = ""
        i = 0
        for col in self.cols:
            for j in range(0, len(self.t.matrix)):
                result += self.t.matrix[j][i] + "\n-\n"
            i += 1
            col.setText(result)
            result = ""
        if self.t.has_winner():
            if self.t.get_winner() == Table.RED:
                print(self.first_player_time.stop())
                self.player_game_time.setText(str(self.first_player_time.stop()))
                self.win_dialog.show()
            else:
                self.compuret_win.show()

    def first_button_clicked(self):
        """Метод, който се извиква при натискането на първия бутон.
        Извършва ход в играта на позиция 0.
        """
        if self.onTurn == 1:
            self.t.commit_turn(0, "R")
            self.first_player_time.sleep()
            if self.vsPC:
                pos = self.pc.get_turn(self.t.matrix)
                self.t.commit_turn(pos, "B")
                self.first_player_time.start()
            else:
                self.onTurn = 2
                self.player.setText("B")
        else:
            self.t.commit_turn(0, "B")
            self.player.setText("R")
            self.onTurn = 1
            self.first_player_time.start()
        self.read_table()

    def second_button_clicked(self):
        """Метод, който се извиква при натискането на втория бутон.
        Извършва ход в играта на позиция 1.
        """
        if self.onTurn == 1:
            self.t.commit_turn(1, "R")
            self.first_player_time.sleep()
            if self.vsPC:
                self.t.commit_turn(self.pc.get_turn(
                    self.t.matrix), "B")
                self.first_player_time.start()
            else:
                self.onTurn = 2
                self.player.setText("B")
        else:
            self.t.commit_turn(1, "B")
            self.player.setText("R")
            self.onTurn = 1
            self.first_player_time.start()
        self.read_table()

    def third_button_clicked(self):
        """Метод, който се извиква при натискането на третия бутон.
        Извършва ход в играта на позиция 2.
        """
        if self.onTurn == 1:
            self.t.commit_turn(2, "R")
            self.first_player_time.sleep()
            if self.vsPC:
                self.t.commit_turn(self.pc.get_turn(
                    self.t.matrix), "B")
                self.first_player_time.start()
            else:
                self.onTurn = 2
                self.player.setText("B")
        else:
            self.t.commit_turn(2, "B")
            self.player.setText("R")
            self.onTurn = 1
            self.first_player_time.start()
        self.read_table()

    def fourth_button_clicked(self):
        """Метод, който се извиква при натискането на четвътия бутон.
        Извършва ход в играта на позиция 3.
        """
        if self.onTurn == 1:
            self.t.commit_turn(3, "R")
            self.first_player_time.sleep()
            if self.vsPC:
                self.t.commit_turn(self.pc.get_turn(
                    self.t.matrix), "B")
                self.first_player_time.start()
            else:
                self.onTurn = 2
                self.player.setText("B")
        else:
            self.t.commit_turn(3, "B")
            self.player.setText("R")
            self.onTurn = 1
            self.first_player_time.start()
        self.read_table()

    def fifth_button_clicked(self):
        """Метод, който се извиква при натискането на петия бутон.
        Извършва ход в играта на позиция 4.
        """
        if self.onTurn == 1:
            self.t.commit_turn(4, "R")
            self.first_player_time.sleep()
            if self.vsPC:
                self.t.commit_turn(self.pc.get_turn(
                    self.t.matrix), "B")
                self.first_player_time.start()
            else:
                self.onTurn = 2
                self.player.setText("B")
        else:
            self.t.commit_turn(4, "B")
            self.player.setText("R")
            self.onTurn = 1
            self.first_player_time.start()
        self.read_table()

    def sixth_button_clicked(self):
        """Метод, който се извиква при натискането на шестия бутон.
        Извършва ход в играта на позиция 5.
        """
        if self.onTurn == 1:
            self.t.commit_turn(5, "R")
            self.first_player_time.sleep()
            if self.vsPC:
                self.t.commit_turn(self.pc.get_turn(
                    self.t.matrix), "B")
                self.first_player_time.start()
            else:
                self.onTurn = 2
                self.player.setText("B")
        else:
            self.t.commit_turn(5, "B")
            self.player.setText("R")
            self.onTurn = 1
            self.first_player_time.start()
        self.read_table()

    def seventh_button_clicked(self):
        """Метод, който се извиква при натискането на седмия бутон.
        Извършва ход в играта на позиция 6.
        """
        if self.onTurn == 1:
            self.t.commit_turn(6, "R")
            self.first_player_time.sleep()
            if self.vsPC:
                self.t.commit_turn(self.pc.get_turn(
                    self.t.matrix), "B")
                self.first_player_time.start()
            else:
                self.onTurn = 2
                self.player.setText("B")
        else:
            self.t.commit_turn(6, "B")
            self.player.setText("R")
            self.onTurn = 1
            self.first_player_time.start()
        self.read_table()

    def eighth_button_clicked(self):
        """Метод, който се извиква при натискането на осмият бутон.
        Извършва ход в играта на позиция 7.
        """
        if self.onTurn == 1:
            self.t.commit_turn(7, "R")
            self.first_player_time.sleep()
            if self.vsPC:
                self.t.commit_turn(self.pc.get_turn(
                    self.t.matrix), "B")
                self.first_player_time.start()
            else:
                self.onTurn = 2
                self.player.setText("B")
        else:
            self.t.commit_turn(7, "B")
            self.player.setText("R")
            self.onTurn = 1
            self.first_player_time.start()
        self.read_table()

    def ninth_button_clicked(self):
        """Метод, който се извиква при натискането на деветия бутон.
        Извършва ход в играта на позиция 8.
        """
        if self.onTurn == 1:
            self.t.commit_turn(8, "R")
            self.first_player_time.sleep()
            if self.vsPC:
                self.t.commit_turn(self.pc.get_turn(
                    self.t.matrix), "B")
                self.first_player_time.start()
            else:
                self.onTurn = 2
                self.player.setText("B")
        else:
            self.t.commit_turn(8, "B")
            self.player.setText("R")
            self.onTurn = 1
            self.first_player_time.start()
        self.read_table()

    def tenth_button_clicked(self):
        """Метод, който се извиква при натискането на десетия бутон.
        Извършва ход в играта на позиция 9.
        """
        if self.onTurn == 1:
            self.t.commit_turn(9, "R")
            self.first_player_time.sleep()
            if self.vsPC:
                self.t.commit_turn(self.pc.get_turn(
                    self.t.matrix), "B")
                self.first_player_time.start()
            else:
                self.onTurn = 2
                self.player.setText("B")
        else:
            self.t.commit_turn(9, "B")
            self.player.setText("R")
            self.onTurn = 1
            self.first_player_time.start()
        self.read_table()
    def __init__(self):

        super(TableWindow, self).__init__()
        self.cols = []
        self.pc = Computer("B")
        self.vsPC = True
        self.win_dialog = WinDialog()
        self.compuret_win = ComputerWinDialog()

        self.first_player_time = Timer()
        self.first_player_time.start()

        self.col_one_edit = QTextEdit()
        self.col_one_edit.setReadOnly(True)

        self.col_two_edit = QTextEdit()
        self.col_two_edit.setReadOnly(True)

        self.col_three_edit = QTextEdit()
        self.col_three_edit.setReadOnly(True)

        self.col_four_edit = QTextEdit()
        self.col_four_edit.setReadOnly(True)

        self.col_five_edit = QTextEdit()
        self.col_five_edit.setReadOnly(True)

        self.col_six_edit = QTextEdit()
        self.col_six_edit.setReadOnly(True)

        self.col_seven_edit = QTextEdit()
        self.col_seven_edit.setReadOnly(True)

        self.col_eight_edit = QTextEdit()
        self.col_eight_edit.setReadOnly(True)

        self.col_nine_edit = QTextEdit()
        self.col_nine_edit.setReadOnly(True)

        self.col_ten_edit = QTextEdit()
        self.col_ten_edit.setReadOnly(True)

        self.col_one_edit = QTextEdit()
        self.col_one_edit.setReadOnly(True)

        label_on_turn = QLabel()
        label_on_turn.setText("On turn:")

        self.player = QLabel()
        self.player.setText("R")

        self.player_time = QLabel()
        self.player_time.setText("Time player R:")

        self.player_game_time = QLabel()
        self.player_game_time.setText(" ")

        self.adding_to_vector()
        self.onTurn = 1
        self.t = Table()

        self.read_table()

        firstButton = QPushButton("&")
        firstButton.setFocusPolicy(Qt.NoFocus)
        firstButton.clicked.connect(self.first_button_clicked)

        secondButton = QPushButton("&")
        secondButton.setFocusPolicy(Qt.NoFocus)
        secondButton.clicked.connect(self.second_button_clicked)

        thirdButton = QPushButton("&")
        thirdButton.setFocusPolicy(Qt.NoFocus)
        thirdButton.clicked.connect(self.third_button_clicked)

        fourthButton = QPushButton("&")
        fourthButton.setFocusPolicy(Qt.NoFocus)
        fourthButton.clicked.connect(self.fourth_button_clicked)

        fifthButton = QPushButton("&")
        fifthButton.setFocusPolicy(Qt.NoFocus)
        fifthButton.clicked.connect(self.fifth_button_clicked)

        sixthButton = QPushButton("&")
        sixthButton.setFocusPolicy(Qt.NoFocus)
        sixthButton.clicked.connect(self.sixth_button_clicked)

        seventhButton = QPushButton("&")
        seventhButton.setFocusPolicy(Qt.NoFocus)
        seventhButton.clicked.connect(self.seventh_button_clicked)

        eighthButton = QPushButton("&")
        eighthButton.setFocusPolicy(Qt.NoFocus)
        eighthButton.clicked.connect(self.eighth_button_clicked)

        ninthButton = QPushButton("&")
        ninthButton.setFocusPolicy(Qt.NoFocus)
        ninthButton.clicked.connect(self.ninth_button_clicked)

        tenthButton = QPushButton("&")
        tenthButton.setFocusPolicy(Qt.NoFocus)
        tenthButton.clicked.connect(self.tenth_button_clicked)

        layout = QGridLayout()
        layout.addWidget(firstButton, 0, 0)
        layout.addWidget(secondButton, 0, 1)
        layout.addWidget(thirdButton, 0, 2)
        layout.addWidget(fourthButton, 0, 3)
        layout.addWidget(fifthButton, 0, 4)
        layout.addWidget(sixthButton, 0, 5)
        layout.addWidget(seventhButton, 0, 6)
        layout.addWidget(eighthButton, 0, 7)
        layout.addWidget(ninthButton, 0, 8)
        layout.addWidget(tenthButton, 0, 9)
        layout.addWidget(self.col_one_edit, 1, 0)
        layout.addWidget(self.col_two_edit, 1, 1)
        layout.addWidget(self.col_three_edit, 1, 2)
        layout.addWidget(self.col_four_edit, 1, 3)
        layout.addWidget(self.col_five_edit, 1, 4)
        layout.addWidget(self.col_six_edit, 1, 5)
        layout.addWidget(self.col_seven_edit, 1, 6)
        layout.addWidget(self.col_eight_edit, 1, 7)
        layout.addWidget(self.col_nine_edit, 1, 8)
        layout.addWidget(self.col_ten_edit, 1, 9)
        layout.addWidget(label_on_turn, 2, 0)
        layout.addWidget(self.player, 2, 1)
        layout.addWidget(self.player_time, 2, 2)
        layout.addWidget(self.player_game_time, 2, 3)

        self.setLayout(layout)

        self.setWindowTitle("Connect Four")
        self.resize(550, 450)
Exemple #42
0
 def openlog(self, file):
     """Open logfile and write header."""
     logfile = open(file, "ab")
     logfile.write("Log started at " + strftime("%a, %d %b %Y %H:%M:%S", localtime()) + ".\n")
     logfile.write("Running on " + DrQueueComputer.get_hostname() + " under " + DrQueueComputer.get_os() + ".\n\n")
     return logfile
Exemple #43
0
def main(args):
    print('starting..!.')
    # get all the relevant data from the preprocessing
    X_train, y_train, X_test, y_test, num_splits, tunned_parameters, random_state = args
    
    # multiprocessing dose not update the seed - so we make sure its random
    np.random.seed(random_state)

    # shuffle to introduce randomness in the smaller samples
    X_train, y_train = shuffle(X_train, y_train)
    
    # init paramters to make code more readable
    num_test_samples = len(y_test)
    num_dimensions = len(X_train[0])
    max_iterations = 3000
    range_of_samples_to_check = 1000
    num_training_samples = len(y_train)
    #final_points = [2000, 4000,  6000, 8000, num_training_samples] # for PCA
    final_points = [2000,  6000,  num_training_samples] # without PCA
    num_splits -= len(final_points) # since we add the final points by hand
    
    # in each itreation we use different amount of data to see how the model improvese with increased data    
    total_amount_of_data = [int(range_of_samples_to_check / num_splits) for i in range(num_splits)] 
    total_amount_of_data_intervals = np.cumsum(total_amount_of_data).tolist()

    # we add final points to show that the model has converged
    total_amount_of_data_intervals += final_points 
    print('total_amount_of_data_intervals', total_amount_of_data_intervals)

    # make the two computer centers that run the program
    computer_1 = Computer()
    computer_2 = Computer()

    # container for the accuricies
    accuracies_distributed, accuracies_single, accuracies_central = [], [], []

    # container for the weights
    distributed_weights, single_weights, central_weights  = {}, {}, {}
    
    loop_start_time = time.time()
    for loop_num, n in enumerate(total_amount_of_data_intervals):
        
        # split the data differently according to if it is odd or even
        if n % 2 == 0:
            m = int(n / 2)
            
        else:
            # if odd, we add one ovservation to ensure that there is the same amount of 
            # observations in both places.
            m = int((n + 1) / 2)

			
        # init the computer before distributed run 
        computer_1.cost = 999999999 # due to minimization
        computer_1.num_data_points = m
        computer_1.is_first_run = True
        computer_1.is_cost_small_enough = False
        
        computer_2.cost = 999999999 # due to minimization
        computer_2.num_data_points = m    
        computer_2.is_first_run = True
        computer_2.is_cost_small_enough = False
		
        learning_rate =tunned_parameters['distributed'][str(n)]['learning_rate']
        weight_decay = tunned_parameters['distributed'][str(n)]['weight_decay']
        Gamma = lambda x: np.sign(x)*(abs(x) - weight_decay)     
        theta = np.zeros(num_dimensions)
        for i in range(max_iterations):
            is_converged_computer_1, computer_1_gradient, computer_1_cost_small_enough = computer_1.get_gradients(X_train[:m], y_train[:m], theta)
            is_converged_computer_2, computer_2_gradient, computer_2_cost_small_enough = computer_2.get_gradients(X_train[m:2*m], y_train[m:2*m], theta)
            total_gradients = computer_1_gradient + computer_2_gradient
            if is_converged_computer_1:
                # if either of the computers has converge we stopp
                print('distributed converge')
                theta = computer_1_gradient
                break
            elif is_converged_computer_2:
                print('distributed converge2')
                theta = computer_2_gradient
                break
            elif computer_1_cost_small_enough:
                print('distributed cost1')
                theta = computer_1_gradient
                break
            elif computer_2_cost_small_enough:
                print('distributed cost2')
                theta = computer_2_gradient
                break
            else:
                theta = Gamma(theta - learning_rate * total_gradients)
        if i == max_iterations - 1:
            print('distributed maxItr')

        # Evaluate the model -- check for error rate
        total_correct_distributed = 0
        for i in range(num_test_samples):
            prediction = np.sign(np.dot(theta, X_test[i]))
            if prediction == y_test[i]:
                total_correct_distributed += 1
        
        distributed_weights[str(n)] = theta
        accuracies_distributed.append(1 - total_correct_distributed / num_test_samples)
        
    ############## If only one computer did the analysis on there own data ############################
        # initalize the data center
        computer_1.cost = 999999999 # due to minimization
        computer_1.num_data_points = m
        computer_1.is_first_run = True
        computer_1.is_cost_small_enough = False

        learning_rate = tunned_parameters['single'][str(n)]['learning_rate']
        weight_decay = tunned_parameters['single'][str(n)]['weight_decay']
        Gamma = lambda x: np.sign(x) * (abs(x) - weight_decay)        
        theta = np.zeros(num_dimensions)
        for i in range(max_iterations):
            is_converged, gradient, is_cost_small_enough = computer_1.get_gradients(X_train[:m], y_train[:m], theta)
            if is_converged:
                print('single converge')
                theta = gradient
                break
            elif is_cost_small_enough:
                theta = gradient
                print('single cost')
                break
            else:
                theta = Gamma(theta - learning_rate * gradient)
        if i == max_iterations - 1:
            print('single maxItr')
        
        # Evaluate the model -- check for error rate
        total_correct_single = 0
        for i in range(num_test_samples):
            prediction = np.sign(np.dot(theta, X_test[i]))
            if prediction == y_test[i]:
                total_correct_single += 1

        single_weights[str(n)] = theta
        accuracies_single.append(1 - total_correct_single / num_test_samples)
    
    ############ If all data was at a centeralized location ###########################################
        # initalize the data center
        theta = np.zeros(num_dimensions)
        computer_1.cost = 999999999 # due to minimization
        computer_1.num_data_points = 2*m
        computer_1.is_first_run = True
        computer_1.is_cost_small_enough = False

        learning_rate = tunned_parameters['central'][str(n)]['learning_rate']
        weight_decay = tunned_parameters['central'][str(n)]['weight_decay']
        Gamma = lambda x: np.sign(x) * (abs(x) - weight_decay)
        for i in range(max_iterations):
            is_converged, gradient, is_cost_small_enough = computer_1.get_gradients(X_train[:2*m], y_train[:2*m], theta )
            if is_converged:
                theta = gradient
                print('central converge')
                break
            elif is_cost_small_enough:
                theta = gradient
                print('central cost')
                break
            else:
                theta = Gamma(theta - learning_rate * gradient)
        if i == max_iterations - 1:
            print('central maxItr')
		

        # Evaluate the model -- check for error rate
        total_correct_all_data = 0
        for i in range(num_test_samples):
            prediction = np.sign(np.dot(theta, X_test[i]))
            if prediction == y_test[i]:
                total_correct_all_data += 1
        
        central_weights[str(n)] = theta
        accuracies_central.append(1 - total_correct_all_data / num_test_samples)
        print('loop {} out of {}, time from first loop: {}'.format(loop_num, len(total_amount_of_data_intervals), time.time() - loop_start_time))
    print('Leaving..!.1')
    return (
            {
           'distributed':np.array(accuracies_distributed),
           'single':np.array(accuracies_single),
           'central_all_data':np.array(accuracies_central),
           'total_amount_of_data_intervals':np.array(total_amount_of_data_intervals)},
           {
           'distributed': distributed_weights,
           'single': single_weights,
           'central':central_weights}
           )
Exemple #44
0
import pygame
from console import Console
from computer import Computer
from level import Screen
from pygame.locals import *
pygame.init()

screen = pygame.display.set_mode((1024,768))
spaceConsole = Console()
spaceComputer = Computer()

oxigen = 25
testStates = [["close",1],["open",0]]

testTransitions = {"open":("close","capsule","open")}
testObjects = {oxigen, "capsule"}

testScreen = Screen(testObjects,testStates,testTransitions)

while 1:
    line = spaceConsole.update()
    if line is not None:
        line = line.lower()
        spaceComputer.processString(line,testScreen)
        print testScreen.getState()
    pygame.display.flip()
Exemple #45
0
class Game:
    def __init__(self):
        self.board = Board()
        self.bag = Bag()
        self.dict = utility.get_dictionary()
        self.user = User(self.bag)
        self.computer = Computer(self.bag)
        self.moves_log = []
        
    
    def get_user_letters(self):
        ''' Return the list of user's Letters
        
            @return: the list of user's Letters.
        '''
        return self.user.get_letters()
    
    def get_computer_letters(self):
        ''' Return the list of computer's Letters
        
            @return: the list of computer's Letters.
        '''
        return self.computer.get_letters()
    
    def get_user(self):
        return self.user
    
    def get_computer(self):
        return self.computer
        
    def computer_make_move(self):
        return self.computer.make_move(self.board, 
                                       self.dict, 
                                       self.moves_log)
    
    def get_players_char_letters(self, player):
        '''
            Return the list of letters the given player currently has.
            
            @param player: string indicating the player ('user' or 'computer')
            @return: the list of letters.
        '''
        letters = []
        lts = getattr(self, player).get_letters()
        for l in lts:
            letters.append(l.get_character())
        return letters
    
    def user_swap_letters(self, letters):
        ''' Return the given list of Letters to the bag, and take
            the same amount of letters from the bag.
            
            @param letters: the list of letters to put back.
            @return: True if it is possible, otherwise False.
        '''
        res = self.user.swap_letters(self.bag, letters)
        return res
    
    def computer_swap_letters(self):
        ''' Return the an amount of Letters to the bag, and take
            the same amount of letters from the bag.
            
            @return: True if it is possible, otherwise False.
        '''     
        amount = random.randint(1, 7)
        res = self.computer.swap_letters(self.bag, amount)
        return res
class Tournament(object):

#----------------------------------------------------------------------------------------------------
#   Function Name: __init__
#   Purpose: To initialize the object
#   Parameters: 
#           The human board
#           The computer board
#           The human score
#           The computer score
#           The humanIsFirstPlayer flag
#           The humanIsNext flag
#           The list of loaded dice rolls
#           The didLoad flag
#   Return Value:  none
#   Local Variables: 
#           All the same variables initializing the classes data members
#   Algorithm: 
#           1. Set up all the parameters as object data member
#           2. If the user is loading a game, resume around, if not then start a new one
#----------------------------------------------------------------------------------------------------


    def __init__(self, humanBoard, computerBoard, humanScore, computerScore, 
                            humanIsFirstPlayer, humanIsNext, diceQueue, didLoad):
        self.human = Human(humanScore)
        self.computer = Computer(computerScore)
        self.diceQueue = diceQueue
        self.humanIsFirstPlayer = humanIsFirstPlayer
        self.humanIsNext = humanIsNext
        self.exitCode = 0
        self.board = Board(humanBoard, computerBoard)
        self.turnCount = 0
        self.returnList = [False, 0, 0]

        if didLoad:
            self.resumeRound()
        else:
            self.newRound()


#----------------------------------------------------------------------------------------------------
#   Function Name: newRound
#   Purpose: To start a new round
#   Parameters: none
#   Return Value:  none
#   Local Variables: 
#           numSquares - The number of squares that the user would like
#           cround - An instance of a round to be played
#   Algorithm: 
#           1. Get the number of squares that the user would like to have
#           2. Reset the boards with the new amount of squares
#           3. Choose the first player
#           4. Begin a new round
#----------------------------------------------------------------------------------------------------


    def newRound(self):
        numSquares = self.getNumSquares()
        self.board.resetBoards(numSquares)
        self.chooseFirstPlayer()
        self.returnList[2] = 0
        cround = cRound(self.board, self.human, self.computer, self.turnCount, 
                                    self.humanIsNext, self.humanIsFirstPlayer, self.diceQueue, 
                                    self.returnList)
        cround.play()
        self.askToPlayAgain()
        self.subsequentRound()


#----------------------------------------------------------------------------------------------------
#   Function Name: resumeRound
#   Purpose: To resume a round
#   Parameters: none
#   Return Value:  none
#   Local Variables: 
#           cround - An instance of a round to be played
#   Algorithm: 
#           1. Set the turn count to an arbitrary large number
#           2. Set the handicap square in the return list to 0
#           3. Play a round with loaded data
#           4. Ask the player if they would like to play again
#           5. If so, begin a another round
#----------------------------------------------------------------------------------------------------


    def resumeRound(self):
        self.turnCount = 4
        self.returnList[2] = 0
        cround = cRound(self.board, self.human, self.computer, self.turnCount,
                                    self.humanIsNext, self.humanIsFirstPlayer, self.diceQueue, 
                                    self.returnList)
        cround.play()
        self.askToPlayAgain()
        self.subsequentRound()

#----------------------------------------------------------------------------------------------------
#   Function Name: subsequentRound
#   Purpose: To start a subsequent round
#   Parameters: none
#   Return Value:  none
#   Local Variables: 
#           numSquares - The number of squares that the user would like
#           cround - An instance of a round to be played
#   Algorithm: 
#           1. Set the turncount to 0
#           2. Get the number of squares from the suer
#           3. Reset the boards using the new numSquares
#           4. Compute and apply the handicap
#           5. Choose the first player
#           6. Play a round
#           7. Ask if the user wants to play another round
#           8. If so, then recurse
#----------------------------------------------------------------------------------------------------

    def subsequentRound(self):
        self.turnCount = 0
        numSquares = self.getNumSquares()
        self.board.resetBoards(numSquares)
        self.computeHandicap()
        self.chooseFirstPlayer()
        cround = cRound(self.board, self.human, self.computer, self.turnCount,
                                    self.humanIsNext, self.humanIsFirstPlayer, self.diceQueue, 
                                    self.returnList)
        cround.play()
        self.askToPlayAgain()
        self.subsequentRound()

#----------------------------------------------------------------------------------------------------
#   Function Name: getNumSquares
#   Purpose: To retrieve the number of board squares from the user
#   Parameters: none
#   Return Value:  squares - the desired  number of squares
#   Local Variables: 
#           squares - the desired number of squares
#   Algorithm: 
#           1. Ask for the user's validated input
#           2. Return their input 
#----------------------------------------------------------------------------------------------------

    def getNumSquares(self):
        squares = Interface.validateRange(
            "How many squares would you like to use? (9, 10, or 11): ",
                 9, 11)
        return squares


#----------------------------------------------------------------------------------------------------
#   Function Name: computeHandicap
#   Purpose: To compute and apply the handicap from the previous round
#   Parameters: none
#   Return Value:  none
#   Local Variables: 
#           ones - the ones place value from the winning score
#           tens - the tens place value from the winning score
#           handicapSquare - the square to be handicapped
#           boardSize - the size of the game board
#   Algorithm: 
#           1. Compute which square is the handicapped one 
#           2. If the square is out of the bounds of the game board, then make it
#                   the largest square on the gameboard
#           3. Set the handicap square in the return list to be sent to round
#           4. Apply the handicap
#----------------------------------------------------------------------------------------------------


    def computeHandicap(self):
        ones = self.returnList[1]%10
        tens = int(self.returnList[1]/10)
        handicapSquare = ones + tens
        boardSize = len(self.board.humanBoard)

        if handicapSquare > boardSize:
            handicapSquare = boardSize

        self.returnList[2] = handicapSquare

        self.applyHandicap(handicapSquare)


#----------------------------------------------------------------------------------------------------
#   Function Name: applyHandicap
#   Purpose: To correctly apply the handicap
#   Parameters: The handicapSquare
#   Return Value:  none
#   Local Variables: none
#   Algorithm: 
#           1. If the human own and is the first player, give handicap to Computer
#           2. If human won and was not the first player, give human the handicap
#           3. If computer won and was the first player, give human the handicap
#           4. If computer won ans was not the first player, give computer the handicap
#----------------------------------------------------------------------------------------------------

    def applyHandicap(self, handicapSquare):
        if self.returnList[0] and self.humanIsFirstPlayer:
            Interface.printMsg("The Computer gets a handicap.")
            self.board.computerBoard[handicapSquare-1] = "*"
        if self.returnList[0] and not self.humanIsFirstPlayer:
            Interface.printMsg("You get a handicap.")
            self.board.humanBoard[handicapSquare-1] = "*"
        if not self.returnList[0] and not self.humanIsFirstPlayer:
            Interface.printMsg("You get a handicap.")
            self.board.humanBoard[handicapSquare-1] = "*"
        if not self.returnList[0] and self.humanIsFirstPlayer:
            Interface.printMsg("The Computer gets a handicap.")
            self.board.computerBoard[handicapSquare-1] = "*"



#----------------------------------------------------------------------------------------------------
#   Function Name: chooseFirstPlayer
#   Purpose: To choose the first player
#   Parameters: none
#   Return Value:  none
#   Local Variables: 
#           humanRoll - the human's roll
#           computerRoll - the computer's roll
#   Algorithm: 
#           1. If the dice queue has contents in it then:
#               a. Load the humanRoll from dice queue
#               b. Pop that roll from the queue
#               c. Load the computer roll from the dice queue
#               d. Pop that roll from the queue
#           3. Otherwise:
#               a. Generate a random roll for the human
#               b. Generate a random roll for the computer
#           4. If the human roll is greater than computer roll, then set
#                   humanIsFirstPlayer and humanIsNext to 1
#           5. If the human roll is less than the computer roll then set
#                   humanIsFirstPlayer and humanIsNext to 0
#           6. If the rolls are equal, then recurse
#----------------------------------------------------------------------------------------------------


    def chooseFirstPlayer(self):
        if self.diceQueue:
            Interface.printMsg("You are rolling...")
            humanRoll = self.diceQueue[0][0] + self.diceQueue[0][1]
            self.diceQueue.pop(0)
            Interface.printMsg("You rolled " + repr(humanRoll))
            Interface.printMsg("The Computer is rolling...")
            computerRoll = self.diceQueue[0][0] + self.diceQueue[0][1]
            Interface.printMsg("The Computer rolled " + repr(computerRoll))
            self.diceQueue.pop(0)
        else:
            Interface.printMsg("You are rolling...")
            humanRoll = self.human.rollDice()
            Interface.printMsg("You rolled " + repr(humanRoll))
            Interface.printMsg("The Computer is rolling...")
            computerRoll = self.computer.rollDice()
            Interface.printMsg("The Computer rolled " + repr(computerRoll))

        if humanRoll > computerRoll:
            Interface.printMsg("You go first!")
            self.humanIsFirstPlayer = 1
            self.humanIsNext = 1
        elif humanRoll < computerRoll:
            Interface.printMsg("The Computer goes first!")
            self.humanIsFirstPlayer = 0
            self.humanIsNext = 0
        else:
            Interface.printMsg("It was a tie!")
            self.chooseFirstPlayer()

#----------------------------------------------------------------------------------------------------
#   Function Name: askToPlayAgain
#   Purpose: To see if the user would like to play another round
#   Parameters: none
#   Return Value:  True if they will play again
#   Local Variables: 
#           willPlay - a flag indicating if the user will play another round
#   Algorithm: 
#           1. Get the user's input on whether they will play again or not
#           2. If they want to play again, return true
#           3. Otherwise terminate the program
#----------------------------------------------------------------------------------------------------


    def askToPlayAgain(self):
        willPlay = Interface.validateBoolean("Would you like to play another round? (y/n): ")

        if willPlay:
            return True
        self.terminate()


#----------------------------------------------------------------------------------------------------
#   Function Name: terminate
#   Purpose: To display the winner and terminate the program
#   Parameters: none
#   Return Value:  none
#   Local Variables: none
#   Algorithm: 
#           1. Infer and display the winner of the tournament
#           2. Exit the program
#----------------------------------------------------------------------------------------------------

    def terminate(self):
        print "\n\n"
        print ("\tHuman:  " + repr(self.human.score) + 
                    "\t\tComputer:  " + repr(self.computer.score))
        print "\n\n"
        if self.computer.score < self.human.score:
            print "\tYou won the tournament!"
        if self.computer.score > self.human.score:
            print "\tThe Computer won the tournament!"
        if self.computer.score == self.human.score:
            print "\tThe tournament was a draw!"

        print "\n\n"
        print "Program is terminating."
        sys.exit()
class ComputerTest(unittest.TestCase):

    def setUp(self):
        self.pc = Computer("B")

    def test_potential_enemy_win_horizontal(self):
        matrix = [
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "R", "R", "R", "E", "E", "E"]
        ]
        self.assertEqual(self.pc.potential_enemy_win_horizontal(
            matrix), (3, 4))

    def test_potential_enemy_win_horizontal_not_win(self):
        matrix = [
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "R", "R", "E", "E", "E", "E"]
        ]
        self.assertEqual(self.pc.potential_enemy_win_horizontal(
            matrix), (-1, -1))

    def test_potential_enemy_win_horizontal_not_win_v2(self):
        matrix = [
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "E", "E", "R", "B", "E"],
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "E", "E", "E", "E", "E"]
        ]
        self.assertEqual(self.pc.potential_enemy_win_horizontal(
            matrix), (-1, -1))

    def test_potential_enemy_win_vertical(self):
        matrix = [
            ["E", "E", "E", "R", "E", "E", "E"],
            ["E", "E", "E", "R", "E", "E", "E"],
            ["E", "E", "E", "R", "E", "E", "E"],
            ["E", "E", "E", "E", "E", "E", "E"]
        ]
        self.assertEqual(self.pc.potential_enemy_win_vertical(matrix), (3, 3))

    def test_potential_enemy_win_vertical_not_win(self):
        matrix = [
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "E", "R", "E", "E", "E"],
            ["E", "E", "E", "R", "E", "E", "E"],
            ["E", "E", "E", "E", "E", "E", "E"]
        ]
        self.assertEqual(self.pc.potential_enemy_win_vertical(
            matrix), (-1, -1))

    def test_potential_player_win_horizontal(self):
        matrix = [
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "B", "B", "B", "E", "E"],
            ["R", "E", "E", "E", "E", "E", "E"],
            ["E", "R", "E", "R", "B", "B", "E"]
        ]
        self.assertEqual(self.pc.potential_player_win_horizontal(
            matrix), (1, 5))

    def test_potential_player_not_win_horizontal(self):
        matrix = [
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "B", "B", "E", "E", "E"],
            ["R", "E", "E", "E", "E", "E", "E"],
            ["E", "R", "E", "R", "B", "B", "E"]
        ]
        self.assertEqual(self.pc.potential_player_win_horizontal(
            matrix), (-1, -1))

    def test_potential_player_win_first_diagonal(self):
        matrix = [
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "B", "B", "R", "E", "E"],
            ["R", "E", "E", "B", "E", "E", "E"],
            ["E", "B", "E", "R", "B", "B", "E"]
        ]
        self.assertEqual(self.pc.potential_player_win_first_diagonal(
            matrix), (0, 1))

    def test_potential_player_not_win_first_diagonal(self):
        matrix = [
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "E", "E", "E", "E", "E"]
        ]
        self.assertEqual(self.pc.potential_player_win_first_diagonal(
            matrix), (-1, -1))

    def test_get_turn_with_series_of_two_vertical(self):
        matrix = [
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "E", "E", "R", "E", "E"],
            ["E", "E", "E", "E", "R", "E", "E"]
        ]
        self.assertEqual(self.pc.get_turn_with_series_of_two_vertical(
            matrix), (1, 4))

    def test_get_turn_with_series_of_two_horizontal(self):
        matrix = [
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "E", "E", "E", "E", "E"],
            ["E", "E", "E", "R", "R", "E", "E"]
        ]
        self.assertEqual(self.pc.get_turn_with_series_of_two_horizontal(
            matrix), (3, 2))
 def setUp(self):
     self.pc = Computer("B")
Exemple #49
0
def main(args):
    print('starting..!.')
    
    # get all the relevant data from the preprocessing
    X, y, num_splits, random_state = args

    # shuffle the data so we get different data for each run of this program
    # Then the program us run multiple times to get a good esitmate    
    # multiprocessing dose not do different seed, so we take a random number to start different seeds
    np.random.seed(random_state)
    X, y = shuffle(X, y)
    
    # init parameters to make code more readable
    max_iterations = 3000 
    num_samples = len(y)
    num_dimensions = len(X[0])
    range_of_samples_to_check = 1000 # since the model converges on very few images
	
    # in each itreation we use different amount of data to see how the model improvese with increased data    
    total_amount_of_data = [int(range_of_samples_to_check/num_splits) for i in range(num_splits)] 
    total_amount_of_data_in_intervals = np.cumsum(total_amount_of_data).tolist()

    # we add points to show that the model has converged
    #total_amount_of_data_in_intervals += [2000, 4000,  6000, 8000,  num_samples] # PCA
    total_amount_of_data_in_intervals  +=  [2000,  6000,  num_samples] 

    # initialize dictonaries that contain information from the cross validation
    distributed_solution = {}
    single_solution = {}
    all_data_solution = {}
	
    splited_data_intervals = []
	
    for n in total_amount_of_data_in_intervals:
        distributed_solution[n] = {'weight_decays': [], 'learning_rates': [], 'error_rates':[]}
        single_solution[n] = {'weight_decays': [], 'learning_rates': [], 'error_rates':[]}
        all_data_solution[n] = {'weight_decays': [], 'learning_rates': [], 'error_rates':[]}
        if n % 2 == 0:
            m = int(n / 2)
            splited_data_intervals.append(m)
		
        else:
            # if odd, we make the first data set have 1 more record than the second
            m = int((n + 1) / 2)
            splited_data_intervals.append(m)


    # make the two computer centers that run the program
    computer_1 = Computer() 
    computer_2 = Computer()
            
    
    loop_start_time = time.time()

    # tune the weight decay and learning rate with grid search and 5 fold cross validation
    learning_rates = [0.1, 0.05, 0.01, 0.005, 0.0001, 0.00005, 10**(-5), 5*10**(-6)]
    #weight_decays = [1.5, 1.0, 0.5, 0.1, 0.01]
    for splited_index, n in enumerate(total_amount_of_data_in_intervals):
        all_results_for_each_n_distributed = []
        all_results_for_each_n_single = []
        all_results_for_each_n_central = []
        half_data = splited_data_intervals[splited_index] # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        if n < 360:
            weight_decays = [15, 10, 5, 1, 0.01, 10**(-5), 10**(-10), 10**(-20)]
        else:
            weight_decay = [10**(-5), 10**(-10), 10**(-20)]
        for weight_decay in weight_decays:
            Gamma = lambda x: np.sign(x) * (abs(x) - weight_decay)
            for learning_rate in learning_rates:
                # initalize lists to gather errors from the cross validation
                error_rates_distributed = []
                error_rates_single = []
                error_rates_central = []
                kf = KFold(n_splits = 5)
                for train_index, test_index in kf.split(X[:2*half_data]): 
                    X_train, X_test = X[train_index], X[test_index]
                    y_train, y_test = y[train_index], y[test_index]
                    
					
                    num_test_samples = len(y_test)
                    m = int(len(y_train) / 2)                            
                    
                    # now we perform the distributed lasso regression
                    # initalize for the distributed algorithm
                    computer_1.cost = 999999999 # due to minimization
                    computer_1.num_data_points = m
                    computer_1.is_first_run = True
                    computer_1.is_cost_small_enough = False
                    
                    computer_2.cost = 999999999 # due to minimization
                    computer_2.num_data_points = m
                    computer_2.is_first_run = True
                    computer_2.is_cost_small_enough = False
                    theta = np.zeros(num_dimensions)
                    for i in range(max_iterations):
                        is_converged_computer_1, computer_1_gradient, computer_1_cost_small_enough = computer_1.get_gradients(X_train[:m], y_train[:m], theta )
                        is_converged_computer_2, computer_2_gradient, computer_2_cost_small_enough = computer_2.get_gradients(X_train[m:2*m], y_train[m:2*m], theta )
                        total_gradients = computer_1_gradient + computer_2_gradient
                        if is_converged_computer_1:
                            theta = computer_1_gradient
                            # if either of the computers has converge we stopp
                            break
                        elif is_converged_computer_2:
                            theta = computer_2_gradient
                            break
                        elif computer_1_cost_small_enough:
                            theta = computer_1_gradient
                            break
                        elif computer_2_cost_small_enough:
                            theta = computer_2_gradient
                            break
                        else:
                            theta  =  Gamma(theta - learning_rate * total_gradients)

                    # Evaluate the model -- check for error rate
                    total_correct_distributed = 0
                    for i in range(num_test_samples):
                        prediction = np.sign(np.dot(theta, X_test[i]))
                        if prediction == y_test[i]:
                            total_correct_distributed += 1
                    error_rates_distributed.append(1 - total_correct_distributed / num_test_samples)
                    
                    ############ If all data was at a centeralized location ###########################################
                    computer_1.num_data_points = 2 * m
                    computer_1.cost = 999999999
                    computer_1.is_first_run = True
                    computer_1.is_cost_small_enough = False
                
                    theta = np.zeros(num_dimensions)
                    for i in range(max_iterations):
                        is_converged, gradient, is_cost_small_enough = computer_1.get_gradients(X_train[:2*m], y_train[:2*m], theta)
                        if is_converged:
                            theta = gradient
                            print('converge all', (learning_rate, weight_decay))
                            break
                        elif is_cost_small_enough:
                            theta = gradient
                            print('cost all', (learning_rate, weight_decay))
                            break
                        else:
                            theta = Gamma(theta - learning_rate * gradient)

         
                    # Evaluate the model -- check for error rate
                    total_correct_all_data = 0
                    for i in range(num_test_samples):
                        prediction = np.sign(np.dot(theta, X_test[i]))
                        if prediction == y_test[i]:
                            total_correct_all_data += 1
                    
                    error_rates_central.append(1 - total_correct_all_data / num_test_samples)
                
                
                
                ############## If only one computer did the analysis on there own data ############################
                # we do another cross validation so that the ratio between training and testing is the same as for the other models
                kf = KFold(n_splits = 5)
                for train_index, test_index in kf.split(X[:half_data]): 
                    X_train, X_test = X[train_index], X[test_index]
                    y_train, y_test = y[train_index], y[test_index]
                    
					
                    num_test_samples = len(y_test)
                    m = int(len(y_train) ) 
                    computer_1.cost = 999999999
                    computer_1.num_data_points = m
                    computer_1.is_first_run = True
                    computer_1.is_cost_small_enough = False
                    theta = np.zeros(num_dimensions)
                    for i in range(max_iterations):
                        is_converged, gradient, is_cost_small_enough = computer_1.get_gradients(X_train[:m], y_train[:m], theta)         
                        if is_converged:
                            theta = gradient
                            break
                        elif is_cost_small_enough:
                            theta = gradient
                            break
                        else:
                            theta = Gamma(theta - learning_rate * gradient)

               
                    # Evaluate the model -- check for error rate
                    total_correct_single = 0
                    for i in range(num_test_samples):
                        prediction = np.sign(np.dot(theta, X_test[i]))
                        if prediction == y_test[i]:
                            total_correct_single += 1
                    
                    error_rates_single.append(1 - total_correct_single / num_test_samples)
                

                
                # After cross validation is finsihed for a pair of weight decay and learning rate we save the results
                # we use tuples so we can find the min error rate, and at the same time have the correct weight decay and learning rate
                all_results_for_each_n_distributed.append((np.mean(error_rates_distributed), weight_decay, learning_rate))
                all_results_for_each_n_single.append((np.mean(error_rates_single), weight_decay, learning_rate))
                all_results_for_each_n_central.append((np.mean(error_rates_central), weight_decay, learning_rate))
                
        print('all_results_for_each_n_central', all_results_for_each_n_central)
        error_rate, weight_decay, learning_rate = min(all_results_for_each_n_distributed) 
        distributed_solution[n]['weight_decays'].append(weight_decay)
        distributed_solution[n]['learning_rates'].append(learning_rate)
        distributed_solution[n]['error_rates'].append(error_rate)
		
        error_rate, weight_decay, learning_rate = min(all_results_for_each_n_single) 
        single_solution[n]['error_rates'].append(error_rate)
        single_solution[n]['weight_decays'].append(weight_decay)
        single_solution[n]['learning_rates'].append(learning_rate)
		
        error_rate, weight_decay, learning_rate = min(all_results_for_each_n_central) 
        all_data_solution[n]['error_rates'].append(error_rate)
        all_data_solution[n]['weight_decays'].append(weight_decay)
        all_data_solution[n]['learning_rates'].append(learning_rate)
        print('\n{} out of {} total loop time: {}'.format(splited_index, len(total_amount_of_data_in_intervals), time.time() - loop_start_time), flush = True)
        #print('distributed_solution[n]', distributed_solution[n]['error_rates'])
        #print('single_solution[n]', single_solution[n])
        #print('all_data_solution[n]', all_data_solution[n], flush = True)
    #print('len(distributed_solution[n][error_rates])', len(distributed_solution[n]['error_rates']))
    #print('distributed_solution[n][error_rates]', distributed_solution[n]['error_rates'])
    print('Leaving..!.1')
    return (distributed_solution, single_solution, all_data_solution)
 def setUp(self):
     self.computer = Computer()
     self.board = Board(self.WIDTH, self.HEIGHT)