Exemplo n.º 1
0
    def __init__(self, fancy, screen, world, players, connection):
        self.world = world

        copied_world = world.copy()
        copied_world.script = {}  # No scripts should ever be run on drawer

        copied_world.steps = 2
        self.object_map = dict(zip(world, copied_world))

        self.drawer = Drawer(fancy,
                             [self.object_map[player] for player in players],
                             screen, copied_world)
        self.players = players

        self.ids = None
        self.playerIDs = {}
        self.time_map = {}

        self.last_load = 0  # When the drawer world was last updated
        self.sent_tick = 0  # Tick last player action that's been sent

        self.actions = {}

        self.data = []  # Random debugging data stuff

        self.packet_queue = queue.Queue()
        self.disconnect_message = None

        self.connection = connection
        self.connection.start(self.handle_packet)
Exemplo n.º 2
0
    def __init__(self, grid_width=60, grid_height=40, ai=None):
        pygame.init()

        self.ai = ai
        self.frame_rate = Game.DEFAULT_FRAME_RATE
        self.grid_width = grid_width
        self.grid_height = grid_height
        self.drawer = Drawer(self.grid_width, self.grid_height)
        self.apple = None
        self.snake = None
        self.score = None
        self.game_running = False
Exemplo n.º 3
0
def draw_outliers(ps,
                  outliers,
                  ok,
                  pic_size=(640, 480),
                  is_axis=True,
                  grid=None,
                  filename=None):
    """
    Draw outliers.

    Arguments:
        ps -- points,
        outliers -- list of outliers,
        ok -- outliers count (leaders),
        pic_size -- picture size,
        is_axis -- need to draw axis,
        grid -- grid lines characteristics,
        filename -- file name for picture.
    """

    # Points characteristics.
    min_coords = reduce(lambda p1, p2: (min(p1[0], p2[0]), min(p1[1], p2[1])),
                        ps[1:], ps[0])
    max_coords = reduce(lambda p1, p2: (max(p1[0], p2[0]), max(p1[1], p2[1])),
                        ps[1:], ps[0])

    # Drawer ini.
    D = Drawer(draw_area=min_coords + max_coords, pic_size=pic_size)

    # Axis.
    if is_axis:
        D.Axis()

    # Grid.
    if grid != None:
        D.Grid(grid)

    # Draw points.
    red_pen = aggdraw.Pen('red', 1.0)
    red_brush = aggdraw.Brush('red')
    for p in ps:
        D.Point(p, 3, red_pen, red_brush)

    # Draw outliers.
    black_pen = aggdraw.Pen('black', 2.0)
    steelblue_brush = aggdraw.Brush('steelblue')
    for outlier in outliers[ok:]:
        (r, p) = outlier
        D.Point(p, 3 * r, black_pen)
    for outlier in outliers[:ok]:
        (r, p) = outlier
        D.Point(p, 3 * r, black_pen, steelblue_brush)
        D.Point(p, 3, red_pen, red_brush)

    # Flush save and show.
    D.FSS(filename=filename)
Exemplo n.º 4
0
    def run(self):
        print("Creating driver...")
        driver = self.create_selenium_driver()

        output = []
        for data in self.input_data:
            if len(data) < 4 or len(data) > 5:
                raise Exception('Input data out of bounds (' + str(len(data)) + ') on input row: ' + str(len(output)+1))
            
            count = str(len(output)+1)
            print("Getting URL",count," \'",data[0],"\'...")
            driver.get(data[1])
            price_time = time.strftime("%Y-%m-%d %H:%M", time.localtime())
            price_element = None
            try:
                price_element = driver.find_element_by_id(data[2])
            except NoSuchElementException as err:
                print("NoSuchElementException, the price element was not found: {0}".format(err.msg))
                # Uncomment to save exception screenshot
                #with open('error.png', "wb") as fh:
                #    fh.write(base64.standard_b64decode(err.screen))
                continue
            #driver.save_screenshot(count + '_out.png')

            price_data = []
            #unicode_url = data[1].encode('utf-8')
            #price_data.append(hashlib.md5(unicode_url).hexdigest())
            price_data.append(data[0])
            price_data.append(price_time)
            price_data.append(price_element.text)
            price_data.append(data[3])
            if len(data) is 5:
                price_data.append(data[4])
            output.append(price_data)
            #print (price_element.text)

        print("Writing to file...")
        with open(self.file_txt_path, 'a') as f:
            for price_data in output:
                output = ''
                separator = ''
                for data in price_data:
                    output += separator + data
                    separator = '|'
                f.write(output)
                f.write('\n')

        print("Plotting graph...")
        drawer = Drawer(self.file_txt_path)
        drawer.draw_scatter()
        print ('Done')
Exemplo n.º 5
0
def do(l,ex):
    from draw import Drawer 
    draw_cmd = 'AP'
    a = 0
    b = 6 # adjust if the c is None thing gets changed, should be the total number of graphs on the plot (e.g. Global, StAlone, TkOnly, TPFMS, Picky, TuneP => b = 6)
    z = 0.2
    for_leg = []
    for i,n,m in l:
        c = Drawer.colors.get(n, None)
        if c is None:
            continue
        offset_x_tgae(m, 1+a*z/b-z/2)
        a += 1
        m.SetLineWidth(2)
        m.SetLineColor(c)
        m.SetMarkerColor(c)
        m.SetMarkerStyle(Drawer.markers.get(n, 20))
        m.Draw(draw_cmd)
        m.GetYaxis().SetRangeUser(1e-5, 1)
        draw_cmd = 'Psame'
        for_leg.append(n)
    leg = Drawer.make_legend((0.200, 0.483, 0.661, 0.657), for_leg)
    leg.SetNColumns(2)
    leg.Draw()
    ps.save('probe_charge_misid_prob%s' % ex)
Exemplo n.º 6
0
def run(title, need_pulling=True):
    if need_pulling:
        time_puller = pull_time.TimePuller()
        assert time_puller.pull_properties(title) != -1
        DataPulling.pulling(title,
                            time_puller.get_start_time() / 1000,
                            time_puller.get_finish_time() / 1000)
    drawer = Drawer()

    for dl in TYPE_LIST:
        drawer.load_data(dl.format(JSON_DIR, title))
        drawer.draw_line_graph(dl.format(PIC_DIR, title))
Exemplo n.º 7
0
def run(Ns, save_anim=False):
    # --- user input ---
    fig, ax = plt.subplots()
    ax.set_xlim([0, 1])
    ax.set_ylim([0, 1])
    draw = Drawer(fig, ax)
    plt.show()

    # --- find Fourier series for drawn shape ---
    fouriers = [Fourier(draw.points, N) for N in Ns]

    # --- plot drawn shape against Fourier approximation ---
    fig, axs = plt.subplots(1, len(Ns))
    ps = draw.points
    t_start, t_end = ps[0, 0].real, ps[-1, 0].real
    ts = np.linspace(t_start, t_end, 100)

    fs = [f(ts) for f in fouriers]
    for ax, f in zip(axs, fs):
        ax.plot(ps[:, 1].real, ps[:, 1].imag)
        ax.plot(f.real, f.imag)

    plt.legend(("User Input", "Fourier Approximation"))
    plt.show()

    # --- animate Fourier drawing ---
    anim_fig, anim_axs = plt.subplots(1, len(Ns))
    anim_fig.suptitle(f"Fourier approximations of orders {Ns}")
    anims = []
    for anim_ax, fourier in zip(anim_axs, fouriers):
        anim_ax.set_xlim([0, 1])
        anim_ax.set_ylim([0, 1])
        anim_ax.set_title(f"N = {len(fourier.n) // 2}")
        anims.append(Animator(anim_ax, fourier))

    group_anim = GroupAnimator(anim_fig, anims, ts[-1])

    if save_anim:
        fig.savefig('images\comparison.png')
        group_anim.save('images\drawing.gif', writer='imagemagick', fps=30)
    plt.show()
Exemplo n.º 8
0
class Local:
    def __init__(self, fancy, screen, world, players):
        self.players = players
        self.drawer = Drawer(fancy, players, screen, world)

    def update(self):
        for player in self.players:
            player.action = player.get_action()
        self.drawer.update()

    def render(self):
        self.drawer.render()

    def cleanup(self):
        self.drawer.cleanup()
Exemplo n.º 9
0
from optparse import OptionParser
from parser import Parser
from draw import Drawer

if __name__ == '__main__':
    opt_parser = OptionParser()
    opt_parser.add_option("-o",
                          "--output",
                          dest="output",
                          help="where to save the image")

    (options, args) = opt_parser.parse_args()

    try:
        parser = Parser(args[0])
        drawer = Drawer(parser.screen, parser.figures, parser.palette)
        drawer.draw()

        if vars(options)['output']:
            drawer.save(vars(options)['output'])
    except (ValueError, FileNotFoundError) as error:
        print(error)
Exemplo n.º 10
0
ps.c.SetLogx()

quantity = 'qinvpt'
which = 'TkOnly'
#which = 'Global'
rhos = [
    0.6996, 0.7089, 0.6888, 0.6752, 0.6458, 0.6437, 0.5965, 0.5758, 0.5617,
    0.5406, 0.5262, 0.5074
]  # for 42 MC
rhos = [
    0.7026, 0.7127, 0.7015, 0.6918, 0.6789, 0.6938, 0.6770, 0.6785, 0.6849,
    0.6771, 0.6739, 0.6742
]  # for 44 MC

from draw import Drawer
drawer = Drawer(fn)


def overlay_curves(track, quantity, hist_names, stat, ymin, ymax):
    drawopt = 'AP'
    curves = []
    for hist_name, color in hist_names:
        curve = drawer.get_curve(track, quantity, hist_name, stat)
        curves.append(curve)

        curve.SetLineWidth(2)
        curve.SetLineColor(color)
        curve.SetMarkerStyle(20)
        curve.SetMarkerSize(0)
        curve.SetMinimum(ymin)
        curve.SetMaximum(ymax)
Exemplo n.º 11
0
    price: List[float] = []
    with open(file_path, 'r') as f:
        for row in f:
            col_1, col_2, col_3 = row.split()
            area_dis.append((int(col_1), float(col_2)))
            price.append(float(col_3))
    return area_dis, price


if __name__ == "__main__":
    train_x, train_y = getInput('./dataForTrainingLinear.txt')
    test_x, test_y = getInput('./dataForTestingLinear.txt')

    train_x = np.hstack((np.array(train_x), np.ones((len(train_x), 1))))
    test_x = np.hstack((np.array(test_x), np.ones(((len(test_x), 1)))))
    train_y = np.array(train_y).reshape(len(train_y))
    test_y = np.array(test_y).reshape(len(test_y))

    lr = LinearRegression(learning_rate=0.00015,
                          initial_w=np.zeros(train_x.shape[1]))

    #history_error, history_loss, history_test_error, history_test_loss = lr.train_gradient_descent(
    #    epoch=150000, epoch_per_round=10000, train_x=train_x, train_y=train_y, test_x=test_x, test_y=test_y)
    history_error, history_loss, history_test_error, history_test_loss = lr.train_stochastic_gradient_descent(
        iteration_num=150000, iter_per_round=10000, batch_size=1, train_x=train_x, train_y=train_y, test_x=test_x, test_y=test_y)

    variable_x = range(10000, 150001, 10000)
    Drawer().draw_error_and_loss(variable_x, history_error, history_loss)
    Drawer().draw_error_and_loss(
        variable_x, history_test_error, history_test_loss)
Exemplo n.º 12
0
from io import BytesIO

response = requests.get(url)
img = Image.open(BytesIO(response.content))

xmax, ymax = img.size

t = xmax / 200

xmax = round(xmax / t)
ymax = round(ymax / t)

img = img.resize((xmax, ymax))

img = img.convert('1')  # convert image to black and white

#img.show()

from draw import Drawer

d = Drawer(xmax, ymax)

for x in range(xmax):
    for y in range(ymax):
        #print(img.getpixel((x,y)))
        if (img.getpixel((x, y)) == 0):
            color = 0
            d.draw(x, y)
        else:
            color = 1
Exemplo n.º 13
0
    )

    def __init__(self, service=None):
        # just steal the uuid code from MIDISerivce

        super().__init__(service=service)
        self.connectable = True
        self._rx = self._server_rx

    def read(self, nbytes=None):
        return self._rx.read(nbytes)


service = CustomUART()
ad = ProvideServicesAdvertisement(service)
drawer = Drawer(output=board.DISPLAY)

while True:
    if ble.connected:
        hexcode = service.read(6).decode('utf-8')
        print('connected!' + hexcode)

        drawer.draw(hexcode)

    else:
        print('not connected...')
        if not ble.advertising:
            ble.start_advertising(ad)
    time.sleep(1)

#
Exemplo n.º 14
0
class Client:
    def __init__(self, fancy, screen, world, players, connection):
        self.world = world

        copied_world = world.copy()
        copied_world.script = {}  # No scripts should ever be run on drawer

        copied_world.steps = 2
        self.object_map = dict(zip(world, copied_world))

        self.drawer = Drawer(fancy,
                             [self.object_map[player] for player in players],
                             screen, copied_world)
        self.players = players

        self.ids = None
        self.playerIDs = {}
        self.time_map = {}

        self.last_load = 0  # When the drawer world was last updated
        self.sent_tick = 0  # Tick last player action that's been sent

        self.actions = {}

        self.data = []  # Random debugging data stuff

        self.packet_queue = queue.Queue()
        self.disconnect_message = None

        self.connection = connection
        self.connection.start(self.handle_packet)

    def update(self):
        self.connection.update()

        if self.disconnect_message is not None:
            raise RuntimeError('Disconnected from server "{}"'.format(
                self.disconnect_message))

        received = []
        while True:
            try:
                packet = self.packet_queue.get_nowait()
            except:
                break

            if hasattr(packet, 'tick'):
                if packet.tick < self.world.tick:
                    if packet.type != networking.PacketType.NORMAL:
                        packet.handle_client(self)
                else:
                    dt = packet.tick - self.world.tick
                    while len(received) < dt + 1:
                        received.append([])
                    received[dt].append(packet)
            else:
                packet.handle_client(self)

        #print(self.world.spawn, self.drawer.world.spawn, self.drawer.cameras[0].player.world.spawn)
        #print(id(self.world), id(self.drawer.world), id(self.drawer.cameras[0].player.world))

        for i, packet_group in enumerate(received):
            if i != 0:
                self.tick()
            for packet in packet_group:
                packet.handle_client(self)

        if self.connection.last_received + 3 < time.time():
            self.connection.send(packets.DisconnectPacket('Timed Out'))
            raise RuntimeError('Server connection timed out')

        if self.world.tick - self.last_load > 0:
            self.drawer.load(self.world, self.object_map)
            self.last_load = self.world.tick

        actions = []
        for player in self.drawer.players:
            player.action = player.get_action()
            actions.append(player.action)

        target_tick = round(self.drawer.world.tick)
        #print(self.actions)
        for i in range(max(-float('inf'), self.sent_tick + 1, *self.actions),
                       target_tick + 1):
            self.actions[i] = actions

        if self.ids is not None:
            while self.sent_tick < target_tick:
                self.sent_tick += 1
                self.time_map[self.sent_tick] = time.time()
                self.connection.send(
                    packets.UpdateClientPacketServer(
                        self.sent_tick, self.actions[self.sent_tick]))

        self.drawer.update()
        #self.data.append([time.time(), self.world.tick, self.last_load, self.sent_tick, self.drawer.world.tick, self.drawer.target_tick])

    def handle_packet(self, packet):
        self.packet_queue.put(packet)

    def render(self):
        self.drawer.render()

    def cleanup(self):
        self.drawer.cleanup()

        self.connection.stop()

        with open('data.json', 'w') as f:
            json.dump(self.data, f)

    def tick(
        self
    ):  # Called when a packet is received for a tick that hasn't happened yet
        actions = self.actions.pop(self.world.tick, None)
        if actions is not None:
            for player, action in zip(self.players, actions):
                player.action = action
        self.world.update()
Exemplo n.º 15
0
    # batch gradient descent
    # history_loss, history_test_loss, history_score,_ = lr.train_gradient_descent(
    #    epoch=150000, epoch_per_round=10000, train_x=train_x, train_y=train_y, test_x=test_x, test_y=test_y)

    # stochastic gradient descent
    history_loss, history_test_loss, history_score, _ = lr.train_stochastic_gradient_descent(
        iteration_num=500000,
        iter_per_round=100,
        batch_size=1,
        train_x=train_x,
        train_y=train_y,
        test_x=test_x,
        test_y=test_y)
    print('Coefficient:', lr.w)
    variable_x = range(100, 500001, 100)
    Drawer().draw_score(variable_x, history_score, ifSGD=True)
    Drawer().draw_loss(variable_x, history_loss, ifSGD=True)
    Drawer().draw_loss(variable_x, history_test_loss, ifSGD=True)

    # Error of stochastic gradient descent with different batch_size
    all_train_loss: List[float] = []
    all_test_loss: List[float] = []
    all_train_score: List[float] = []
    all_test_score: List[float] = []
    for i in range(10, 401, 10):
        lr = LogisticRegression(learning_rate=0.00015,
                                initial_w=np.zeros(train_x.shape[1]))
        history_loss, history_test_loss, history_score, history_test_score = lr.train_stochastic_gradient_descent(
            iteration_num=1,
            iter_per_round=1,
            batch_size=i,
Exemplo n.º 16
0
def main():
    """ Main program for playing the game. """
    pg.init()
    clock = pg.time.Clock()
    fps = 60
    pg.display.set_caption('Tricky Circles')
    icon = pg.image.load('resources/icon.jpg')
    pg.display.set_icon(icon)

    # Create display
    screen = pg.display.set_mode(SCREEN_SIZE)

    # Load resources such as wallpaper and fonts
    bg = pg.image.load('resources/desert.jpg')
    font = pg.font.Font('resources/western.ttf', 30)
    font_big = pg.font.Font('resources/western.ttf', 50)

    # Create buttons
    space = 50  # Space in between action buttons: a, b, x
    button_x = pg.Rect((WIDTH / 2 - BUTTON_WIDTH / 2, 250), BUTTON_SIZE)
    button_a = pg.Rect((button_x.x - space - BUTTON_WIDTH, button_x.y),
                       BUTTON_SIZE)
    button_b = pg.Rect((button_x.x + space + BUTTON_WIDTH, button_x.y),
                       BUTTON_SIZE)

    button_solve = pg.Rect((10, 0), BUTTON_SIZE)
    button_reset = pg.Rect((BUTTON_WIDTH + 20, button_solve.y), BUTTON_SIZE)
    button_info = pg.Rect((WIDTH - BUTTON_WIDTH / 2, button_solve.y),
                          BUTTON_SMALL)

    button_difficulty = pg.Rect((WIDTH / 2 - BUTTON_WIDTH / 2, 0), BUTTON_SIZE)
    button_min = pg.Rect(button_difficulty.topleft, BUTTON_SMALL)
    button_plus = pg.Rect(button_difficulty.midtop, BUTTON_SMALL)

    buttons = {
        'A': button_a,
        'X': button_x,
        'B': button_b,
        'Solve': button_solve,
        'Reset': button_reset,
        '-': button_min,
        '+': button_plus,
        '?': button_info
    }

    # Create starting level
    difficulty = 4  # Number of circles
    level_maker = CreateLevels()
    level = level_maker.get_random(difficulty)
    solver = Solver(level)
    min_moves, _ = solver.solve()  # Minimum moves needed to solve level

    # Creates Drawer for drawing levels
    drawer = Drawer(screen, WIDTH, level)
    drawer.draw_level(font, bg, min_moves, buttons, animation=False)

    auto_solve = False

    while True:

        if level.circles == level.answer:  # Level is solved

            # Draw finish-screen, depending on how level was solved
            if auto_solve:
                new_level = drawer.draw_solved(font_big, "Try it yourself?")
                auto_solve = False
            elif level.counter == min_moves:
                new_level = drawer.draw_solved(font_big, "Perfect score!")
            else:
                new_level = drawer.draw_solved(
                    font_big, "Solved in {} moves!".format(level.counter))

            if new_level:
                # Start a new game
                print('New game')
                level = level_maker.get_random(difficulty)
                drawer.level = level
                solver = Solver(level)
                min_moves, _ = solver.solve()
            else:
                # Reset level to try again
                print('Retry level')
                level.reset()

            drawer.draw_level(font, bg, min_moves, buttons, animation=False)

        for event in pg.event.get():

            # Quit when exit-button is clicked
            if event.type == pg.QUIT:
                pg.quit()
                exit()

            if event.type == pg.MOUSEBUTTONDOWN:
                mouse_pos = event.pos  # Get mouse position

                # Checks if mouse position is over a button
                # Perform corresponding action
                if button_info.collidepoint(*mouse_pos):
                    print('Show info')
                    drawer.show_help()

                if button_a.collidepoint(*mouse_pos):
                    print('A clicked, ', level.counter + 1)
                    drawer.animate_ab(font, bg, min_moves, buttons, 'a')
                    level.click_a()
                if button_b.collidepoint(*mouse_pos):
                    print('B clicked, ', level.counter + 1)
                    drawer.animate_ab(font, bg, min_moves, buttons, 'b')
                    level.click_b()
                if button_x.collidepoint(*mouse_pos):
                    print('X clicked, ', level.counter + 1)
                    drawer.animate_x(font, bg, min_moves, buttons)
                    level.click_x()

                if button_reset.collidepoint(*mouse_pos):
                    print("Reset level")
                    level.reset()

                if button_difficulty.collidepoint(*mouse_pos):
                    changed = False

                    # Check whether - or + was clicked
                    if button_min.collidepoint(*mouse_pos):
                        if difficulty > 4:  # 4 is minimum
                            difficulty -= 1
                            changed = True
                    else:
                        if difficulty < 8:  # 8 is maximum
                            difficulty += 1
                            changed = True

                    if changed:  # When minimum/maximum was not exceeded
                        print("Set difficulty {}".format(difficulty))

                        # Create new level with new difficulty
                        level = level_maker.get_random(difficulty)
                        drawer.level = level
                        solver = Solver(level)
                        min_moves, _ = solver.solve()

                if button_solve.collidepoint(*mouse_pos):
                    print('Show solution')
                    auto_solve = True

                    # Get solution for current level-state
                    # Solution is represented by sequence of actions to perform
                    solver = Solver(level)
                    _, min_actions = solver.solve()

                    # Execute and animate each action separately
                    for action in min_actions:
                        if action == 'a':
                            drawer.animate_ab(font, bg, min_moves, buttons,
                                              'a')
                            level.click_a()
                        if action == 'b':
                            drawer.animate_ab(font, bg, min_moves, buttons,
                                              'b')
                            level.click_b()
                        if action == 'x':
                            drawer.animate_x(font, bg, min_moves, buttons)
                            level.click_x()

                        # Redraw Level after each animated action
                        drawer.draw_level(font,
                                          bg,
                                          min_moves,
                                          buttons,
                                          animation=False)
                        pg.display.update()
                        pg.time.delay(500)  # So that animation can be followed

                # Redraw Level after each event
                drawer.draw_level(font,
                                  bg,
                                  min_moves,
                                  buttons,
                                  animation=False)

        pg.display.update()
        clock.tick(fps)
Exemplo n.º 17
0
 def __init__(self, fancy, screen, world, players):
     self.players = players
     self.drawer = Drawer(fancy, players, screen, world)
Exemplo n.º 18
0
def draw_data(tree,
              draw_trajectory=False,
              draw_clusters=True,
              pic_size=(640, 480),
              is_axis=True,
              grid=None,
              filename=None):
    """
    Draw data.

    Arguments:
        tree -- clustering tree,
        pic_size -- picture size,
        is_axis -- need to draw axi,
        grid -- grid lines characteristics,
        filename -- file name for picture.
    """

    # Points characteristics.
    min_coords = reduce(lambda p1, p2: (min(p1[0], p2[0]), min(p1[1], p2[1])),
                        ps[1:], ps[0])
    max_coords = reduce(lambda p1, p2: (max(p1[0], p2[0]), max(p1[1], p2[1])),
                        ps[1:], ps[0])

    # Drawer ini.
    D = Drawer(draw_area=min_coords + max_coords, pic_size=pic_size)

    # Axis.
    if is_axis:
        D.Axis()

    # Grid.
    if grid != None:
        D.Grid(grid)

    # Draw clusters lines.
    if draw_clusters:
        leaf1 = tree.LeftLeaf()
        while leaf1 != None:
            leaf2 = tree.NextLeafLeftRoRight(leaf1)
            while leaf2 != None:

                # Draw.
                d1 = leaf1.Data
                d2 = leaf2.Data
                kn1 = ClusterNumber(leaf1)
                kn2 = ClusterNumber(leaf2)
                is_not_outliers = (not leaf1.IsOutlier) and (
                    not leaf2.IsOutlier)
                if is_not_outliers and (kn1 != -1) and (kn1 == kn2):
                    D.Line(d1, d2, pen=aggdraw.Pen(pretty_color(kn1), 1.0))

                leaf2 = tree.NextLeafLeftRoRight(leaf2)
            leaf1 = tree.NextLeafLeftRoRight(leaf1)

    backcolor = D.Backcolor
    backcolor_pen = aggdraw.Pen(backcolor, 1.0)
    backcolor_brush = aggdraw.Brush(backcolor)

    # Draw points.
    leaf = tree.LeftLeaf()
    while leaf != None:

        # Default colors and etc.
        color = 'red'
        point_radius = 3

        # Define color if cluster number is set.
        if draw_clusters:
            kn = ClusterNumber(leaf)
            if leaf.IsOutlier:
                color = 'black'
                point_radius = 5
            elif kn != -1:
                color = pretty_color(kn)

        # Define pen, brush and draw point.
        point_pen = aggdraw.Pen(color, 1.0)
        point_brush = aggdraw.Brush(color)
        D.Point(leaf.Data, point_radius, pen=point_pen, brush=point_brush)
        if draw_clusters:
            if not leaf.IsOutlier:
                D.Point(leaf.Data, 1, pen=backcolor_pen, brush=backcolor_brush)
        leaf = tree.NextLeafLeftRoRight(leaf)

    # Flush save and show.
    D.FSS(filename=filename)
Exemplo n.º 19
0
if __name__ == "__main__":

    # load stones from file
    stones = base.loadStones("stones.txt")
    print("stones are", stones)

    # prepare board and marks
    board, marks = base.makeBoard10();

    # create both players
    p1 = Player("pepa", board, marks, stones, 1)
    p2 = Player("franta", board, marks, stones, -1)

    # not necessary, only if you want to draw board to png files
    d = Drawer()
    d.draw(p1.board, p1.marks, "init.png");

    moveidx = 0
    while True:
        p1play = True
        p2play = True

        m = p1.move()  # first player, we assume that a corrent output is returned

        # the following if/else is simplified. On Brute, we will check if return value
        # from move() is valid ...
        if len(m) == 0:
            p1play = False
        else:
            stoneIdx, stone = m
Exemplo n.º 20
0
                else:
                    black_image.putpixel((x, y), 0)
    epd.init()
    try:
        epd.display(epd.getbuffer(black_image), epd.getbuffer(red_image))
        time.sleep(2)
    finally:
        epd.sleep()


logging.info("Display initialising")
epd = epd5in83bc.EPD()
epd.init()
epd.Clear()
logging.info("Drawer initialising")
drawer = Drawer()
cleared = False
try:
    while True:
        now = dt.datetime.now()
        hour = now.hour
        if hour < 1 or hour > 4:
            logging.info("Rendering")
            img = drawer.render()
            logging.info("Drawing to display")
            show_image(epd, img)
            if cleared:
                logging.info("Good morning " + now.strftime("%Y-%m-%d %H:%M:%S"))
            cleared = False
            logging.info("Sleeping")
        elif not cleared:
Exemplo n.º 21
0
class Game():

    DEFAULT_FRAME_RATE = 20

    def __init__(self, grid_width=60, grid_height=40, ai=None):
        pygame.init()

        self.ai = ai
        self.frame_rate = Game.DEFAULT_FRAME_RATE
        self.grid_width = grid_width
        self.grid_height = grid_height
        self.drawer = Drawer(self.grid_width, self.grid_height)
        self.apple = None
        self.snake = None
        self.score = None
        self.game_running = False

    def init_game(self):
        self.snake = Snake(self.get_random_object())
        self.apple = self.get_random_object()
        self.score = 0
        self.game_running = True

    def get_random_object(self):
        if self.snake:
            curr_head = self.snake.head
        else:
            curr_head = None

        random_object = Object(randint(0, self.grid_width - 1),
                               randint(0, self.grid_height - 1))
        while random_object == curr_head or random_object == self.apple:
            random_object = Object(randint(0, self.grid_width - 1),
                                   randint(0, self.grid_height - 1))

        return random_object

    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

        key_presses = pygame.key.get_pressed()

        if key_presses[pygame.K_DOWN]:
            self.snake.direction = Direction.DOWN
        elif key_presses[pygame.K_UP]:
            self.snake.direction = Direction.UP
        elif key_presses[pygame.K_LEFT]:
            self.snake.direction = Direction.LEFT
        elif key_presses[pygame.K_RIGHT]:
            self.snake.direction = Direction.RIGHT

    def step(self):
        collision = self.snake.move(self.apple, self.grid_width - 1,
                                    self.grid_height - 1)

        if (collision == ObjectName.APPLE):
            self.score += 1
            self.apple = self.get_random_object()
        elif (collision == ObjectName.TAIL or collision == ObjectName.WALL):
            self.init_game()

    def game_loop(self):
        if (self.ai):
            Thread(target=self.ai, args=[self], daemon=True).start()

        while self.game_running:

            self.handle_events()
            self.step()
            self.drawer.draw(self.snake, self.apple, self.score)
            pygame.display.flip()
            pygame.time.delay(1000 // self.frame_rate)
Exemplo n.º 22
0
    for x1_ind in range(x1_range + 1):
        for x2_ind in range(x2_range + 1):
            x1 = (math.pi * x1_ind) / x1_range
            x2 = (math.pi * x2_ind) / x2_range
            y = math.sin(x1) + math.cos(x2)
            s.append([x1, x2, y])
    return s


refile = open("2varSamples.json", "r")
samples = json.loads(refile.read())
approximator = TwoVariableApproximator(samples, 3)
progress = [approximator.objective()]

for i in range(10000):
    approximator.one_gradient_descent_step()
    progress.append(approximator.objective())
    print(progress[-1])

obj_function_plot = Drawer(xlimits=(0, len(progress)),
                           ylimits=(0, 1.2 * progress[0]))
for i in range(len(progress)):
    obj_function_plot.add_points([[i, progress[i]]])
print("bettas", approximator.bettas)
print("estimate:", approximator.approximation([0.5, 0.5]),
      approximator.approximation([0.75, 0.25]))
print("expected:",
      math.sin(0.5) + math.cos(0.5),
      math.sin(0.75) + math.cos(0.25))
obj_function_plot.draw()
Exemplo n.º 23
0
#!/usr/bin/env python3
from draw import Drawer
import os

if __name__ == '__main__':

    options = {
        # Data directory
        'output_directory': "./",
        # Price data file
        'file_name': "watch_prices.txt",
    }
    file_txt_path = os.path.join(options['output_directory'],
                                 options['file_name'])
    drawer = Drawer(file_txt_path)
    drawer.draw_scatter()
Exemplo n.º 24
0
import json
import requests
import boto3

from draw import Drawer, Rect

prev_content = ''

session = requests.session()

drawer = Drawer(1920, 1080)

s3 = boto3.resource('s3')
bucket = s3.Bucket('s3.doldamgil.spidycoder.com')


def heartbeat():
    global prev_content
    try:
        response = session.patch(
            'https://test.rest.doldamgil.spidycoder.com:4430/gyms/1/edges/1')
        content = response.content.decode('utf-8')
        data = json.loads(content)

        if prev_content != content:
            prev_content = content

            gym_id = data['gymId']
            edge_code = data['edgeCode']
            wall_creation_time = data['wallCreationTime']
            creator_id = data['creatorId']
Exemplo n.º 25
0
    return s


def get_approximations(a_approximator):
    global num_of_samples
    s = []
    for i in range(0, num_of_samples):
        x_sample = i * 2 * math.pi / num_of_samples
        y_sample = a_approximator.approximation(x_sample)
        s.append([x_sample, y_sample])
    return s


samples = get_samples()

main_plot = Drawer()
main_plot.add_points(points=samples)

approximator = OneVariableApproximator(samples, 5)

progress = [approximator.objective()]
for i in range(10000):
    approximator.one_gradient_descent_step()
    progress.append(approximator.objective())

obj_function_plot = Drawer(xlimits=(0, len(progress)),
                           ylimits=(0, 1.2 * progress[0]))
for i, p in zip(range(len(progress)), progress):
    pair = [i, p]
    print(pair)
    obj_function_plot.add_pkoints([pair])
Exemplo n.º 26
0
else:
    seed = args.seed
    random.seed(seed)

if args.show_seed:
    print("Seed:", seed)

# Start of path generation and drawing
if args.path:
    path = Path.from_string(args.path)
    grid = path.grid
else:
    grid = Grid(args.width, args.height)

drawer = Drawer(grid, args.cell_size, args.wall_thickness, args.padding,
                args.hide_arrows, args.hide_start, args.hide_finish,
                args.hide_github)

# Check image dimensions
if drawer.img_width > 32512 or drawer.img_height > 32600:
    parser.error(
        'The generated map would exceed the maximum dimensions: 32512x32600')

# Warning on big maps
if not args.path and not args.ignore_warning \
    and args.width > 40 and args.height > 40:
    print('WARNING: A huge map is about to be generated! Because of the way '
          'map generation is implemented, the time to create the path grows '
          'really fast. Maps bigger than 40x40 can take several minutes to '
          'generate. Also, take into account that a 50x50 map could take '
          '30 minutes to finish playing with 1 player. You can suppress this '
Exemplo n.º 27
0
def main(args):

    fd_infer_time, ld_infer_time, hpe_infer_time, ge_infer_time = 0 ,0 ,0 ,0

    start = time.time()
    face_detector = FaceDetector(args.model_fd, args.device_fd, args.ext_fd)
    fd_load_time = time.time() - start 

    start = time.time()
    landmarks_detector = LandmarksDetector(args.model_ld, args.device_ld, args.ext_ld)
    ld_load_time = time.time() - start 

    start = time.time()
    head_pose_estimator = HeadPoseEstimator(args.model_hpe, args.device_hpe, args.ext_hpe)
    hpe_load_time = time.time() - start 

    start = time.time()
    gaze_estimator = GazeEstimator(args.model_ge, args.device_ge, args.ext_ge)
    ge_load_time = time.time() - start 
    log.info("Models Loading...")
    log.info("Face detection load time       :{:.4f}ms".format(fd_load_time))    
    log.info("Landmarks estimation load time :{:.4f}ms".format(ld_load_time))     
    log.info("Head pose estimation load time :{:.4f}ms".format(hpe_load_time))     
    log.info("Gaze estimation load time      :{:.4f}ms".format(ge_load_time))  
    log.info('All Models loaded')
    mouse_controller = MouseController('high', 'fast')


    if args.input == 0:
        input_feeder = InputFeeder('cam', args.input)
    elif args.input.endswith('.jpg') or args.input.endswith('.bmp'):
        input_feeder = InputFeeder('image', args.input)
    else:
        input_feeder = InputFeeder('video', args.input)
    
    input_feeder.load_data()
    init_w  = input_feeder.init_w
    init_h =  input_feeder.init_h
    

    counter = 0

    for flag, frame in input_feeder.next_batch():
        
        if not flag:
            break

        counter +=1

        key = cv2.waitKey(60)
        try:
            start = time.time()
            outputs = face_detector.predict(frame)
            
            face = face_detector.preprocess_output(frame, outputs, init_w, init_h)
            
            fd_infer_time += time.time() - start

            start = time.time()
            outputs = landmarks_detector.predict(face)
            
            left_eye, right_eye, real_landmraks = landmarks_detector.preprocess_output(face, outputs)
           
            ld_infer_time += time.time() - start

            start = time.time()

            outputs = head_pose_estimator.predict(face)
            head_pose_angles = head_pose_estimator.preprocess_output(outputs)
            
            hpe_infer_time += time.time() - start

            
            start = time.time()
            
            outputs = gaze_estimator.predict(left_eye, right_eye, head_pose_angles)
            
            gaze = gaze_estimator.preprocess_output(outputs)
            
            ge_infer_time += time.time() - start
  

            log.info("Face detection time       :{:.4f}ms".format(fd_infer_time/counter))    
            log.info("Landmarks estimation time :{:.4f}ms".format(ld_infer_time/counter))     
            log.info("Head pose estimation time :{:.4f}ms".format(hpe_infer_time/counter))     
            log.info("Gaze estimation time      :{:.4f}ms".format(ge_infer_time/counter))     

            if args.input != 0:
                drawer = Drawer(face, real_landmraks, head_pose_angles, gaze)
                drawer.draw_landmarks(20)
                drawer.draw_head_pose()
                drawer.draw_gazes()
                drawer.show()
            roll_cos = math.cos(head_pose_angles[2] *  math.pi/180)

            roll_sin = math.sin(head_pose_angles[2] *  math.pi/180)

            mouse_x = gaze[0] * roll_cos + gaze[0] * roll_sin
            mouse_y = gaze[1] * roll_cos + gaze[1] * roll_sin

            mouse_controller.move(mouse_x, mouse_y)

        except Exception as e:
            log.error(e)
        finally:
            if key == 27:
                break

    input_feeder.close()