def main():
    root = Tk()
    root.title('Rotating line')

    canvas = Canvas(root, width=W, height=H, background='black')
    canvas.grid(row=0, column=1)

    lines = [random_line() for line in range(N_LINES)]
    colors = [
        make_discrete_color_series(random_color(), random_color(), N_STEPS)
        for color in range(N_LINES)
    ]
    centers = [random_point() for line in range(N_LINES)]

    for i in range(N_STEPS):
        for j in range(len(lines)):
            lines[j] = rotate(lines[j], DEG_INCR1, centers[j])
            lines[j] = rotate(lines[j], (j + 2) * DEG_INCR2,
                              (lines[j][0] + lines[j][1]) * 0.5)
            canvas.create_line(lines[j][0].as_list(),
                               lines[j][1].as_list(),
                               fill=colors[j][i])
        canvas.update()
        canvas.after(CYCLE_IN_MS)

    root.mainloop()
def main():
    root = Tk()
    root.title('Rescaling')

    W, H = 700, 500
    PAD = 50
    canvas = Canvas(root, width=W, height=H, background='black')
    canvas.grid(row=0, column=1)

    #triangle = make_random_triangle(W, H)
    triangle = [
        Point(W / 2, PAD),
        Point(PAD, H - PAD),
        Point(W - 3 * PAD, H - 4 * PAD)
    ]
    scale_factor = 0.8

    for i in range(37):
        color1 = random_color()
        color2 = random_color()
        center = locate(triangle)['center']
        t_list = [point.as_list() for point in triangle]
        print(t_list)
        canvas.create_polygon(t_list, fill=color1, outline=color2, width=2)
        triangle = rotate_shape(triangle, center, degrees=10)
        [print(point) for point in triangle]

    root.mainloop()
def make_random_ball(max_x, max_y, max_diameter):
    location = Point(random.uniform(0, max_x), random.uniform(0, max_y))
    diameter = random.uniform(5, max_diameter)
    initial_acceleration = Point(random.uniform(0, 20), random.uniform(-20, 0))
    ball = Ball(location, diameter, initial_acceleration)
    ball.set_color(random_color())
    ball.set_outline(random_color())
    return ball
Beispiel #4
0
def create_random_ball(ident):
    diameter = random.uniform(5, MAX_DIAMETER)
    return Ball(
        Point(random.uniform(0, W - diameter), random.uniform(0,
                                                              H - diameter)),
        Point(random.uniform(-MAX_SPEED, MAX_SPEED),
              random.uniform(-MAX_SPEED, MAX_SPEED)), diameter, random_color(),
        random.uniform(ELASTICITY_RANGE[0], ELASTICITY_RANGE[1]), ident)
 def __init__(self, position, velocity, diameter, color, elasticity, ident):
     self.position = position
     self.velocity = velocity
     self.diameter = diameter
     self.color = color
     self.outline = random_color()
     self.elasticity = elasticity
     self.ident = ident
def make_ball_with_trajectory(max_width, max_height):
    diameter = random.uniform(5, 35)
    p1 = Point(random.uniform(0, max_width), random.uniform(0, max_height))
    ball = [p1, p1 + Point(diameter, diameter)]
    trajectory = Point(random.choice([-3, -2, -1, 1, 2, 3]),
                       random.choice([-3, -2, -1, 1, 2, 3]))
    color = random_color()

    return {'ball': ball, 'trajectory': trajectory, 'color': color}
def create_random_ball(max_width, max_height, max_speed, max_diameter,
                       elasticity_range, ident):

    diameter = random.uniform(5, max_diameter)
    return Ball(
        Point(random.uniform(0, max_width - diameter),
              random.uniform(0, max_height - diameter)),
        Point(random.uniform(-max_speed, max_speed),
              random.uniform(-max_speed, max_speed)), diameter, random_color(),
        random.uniform(elasticity_range[0], elasticity_range[1]), ident)
Beispiel #8
0
 def nouvel_obstacle(self):
     """
     Ajoute un obstacle à la file d'obstacles de l'objet
     """        
     self.obstacles.append(
         Obstacle_P5(
             util.calcul_nouvelle_pos_y(self.obstacles[-1].min_y),
             self.obstacles[-1].pos_x+util.LARGEUR_OBSTACLE,
             couleur=util.random_color()
         )
     )     
Beispiel #9
0
class Potion(Item):
    quaff = True
    char = '!'
    unided_color = util.random_color(check_unique=potion_colors)
    category = "Potions"

    def __init__(self):
        super(Potion, self).__init__()
        self.name = 'Potion'

    def quaff(self, player):
        pass
def main():
    root = Tk()
    root.title('Triangle')

    W, H = 700, 700
    PAD = 40
    N_TRIANGLE = 300
    canvas = Canvas(root, width=W, height=H, background='black')
    canvas.grid(row=0, column=1)

    points = [get_random_point(W, H) for j in range(3)]

    for i in range(N_TRIANGLE):
        trans_x = random.choice(range(-10, 20, 2))
        trans_y = random.choice(range(-10, 20, 2))
        color1 = random_color()
        color2 = random_color()
        make_triangle(canvas, points, color1, color2)

        points = translate_shape(points, trans_x, trans_y)

    root.mainloop()
def main():
    root = Tk()
    root.title('Regular Polygons')

    W, H = 700, 500
    PAD = 20
    CENTER = Point(W / 2, H / 2)
    REVERSE = False
    radius = H / 2 - PAD
    canvas = Canvas(root, width=W, height=H, background='black')
    canvas.grid(row=0, column=1)

    for i in range(12):
        sides = i + 3 if not REVERSE else 12 - i + 2
        poly = make_regular_poly(sides, CENTER, radius)
        poly_list = [point.as_list() for point in poly]
        canvas.create_polygon(poly_list,
                              fill=random_color(),
                              outline=random_color(),
                              width=2)
        radius -= PAD

    root.mainloop()
Beispiel #12
0
def main():
    root = Tk()
    root.title('Bounding Boxes')

    W, H = 700, 500
    canvas = Canvas(root, width=W, height=H, background='black')
    canvas.grid(row=0, column=1)

    N_TRIANGLE = 10
    BOUND_COLOR = '#ff0000'

    triangles = [make_triangle(W, H) for i in range(N_TRIANGLE)]
    for triangle in triangles:
        bb = locate(triangle)['bb']
        bb = [point.as_list() for point in bb]
        triangle = [point.as_list() for point in triangle]
        canvas.create_polygon(triangle, fill=random_color())
        canvas.create_rectangle(bb, fill=None, outline=BOUND_COLOR)

    root.mainloop()
def test_accuracy(n_train, n_test):
    #n_train = load_list(c.NODES_FILENAME)
    #n_test = load_list(c.TEST_NODES_FILENAME)

    td = []
    succeeds = 0

    for n in n_test:

        # exclude rarer nodes to fix overrepresentation
        if n.reach_percentage() < 0.1 or len(n.passages) < 100:
            continue

        for i in pick_random_passage(n, 10):
            passage = n.passages[i]
            route = n.get_route(i)

            # pick random spot from passage.route
            # use 2 data points for calculation
            spot = random.randint(0, len(route) - 2)
            real_arrival = passage.enters_meas_area(route[spot + 1][2])

            print(n_train[spot + 1])

            predict_p, pred_parts = predict_path(n_train, route[spot],
                                                 route[spot + 1], 3)

            if predict_p == 0:
                continue
            predict_t = calculate_arrival(predict_p, route[spot], pred_parts)

            t = (predict_t - real_arrival) / 3600
            if abs(t) > 13:
                n.add_passage(passage, n.passage_i[i])
                #print("Already visited area")
                c = random_color()
                passage.plot(c)
                n.draw(c)
                Map.draw_circle(route[spot + 1][0], route[spot + 1][1], 2000,
                                "red")
                #print(n.label[i])
                print(predict_t / 3600, real_arrival / 3600, "(",
                      format_date(route[spot + 1][2]),
                      format_date(passage.enters_meas_area()), ")")

            if abs(t) < 0.5:
                succeeds += 1

            #print(t)
            td.append(t)

    print("Average time delta", np.mean(td))
    text = "Predictions in 1 hour margin {0}%\n".format(
        int(succeeds / len(td) * 100))
    text += "n=" + str(len(td))

    def draw_chart(values):
        plt.hist(values, np.arange(-5, 5, step=0.5), density=False)
        plt.xlabel("hours")
        plt.ylabel("propability")
        plt.xticks(np.arange(-5, 6, step=1))
        #plt.yticks(np.arange(0, 1, step=0.2))
        plt.ticklabel_format(axis='x')
        plt.gca().set_aspect('auto', adjustable='datalim')
        #plt.text(0, .025, r'$\mu=100,\ \sigma=15$')
        # xy scale is dependant on data, bad practice
        plt.text(-5, 400, text)
        plt.show()

    draw_chart(td)
Beispiel #14
0
 def __init__(self, position, velocity, color_scheme, radius, identifier):
     Ball.__init__(self, position, velocity, radius, identifier)
     self.color_scheme = color_scheme
     self.color = util.random_color()
Beispiel #15
0
    def plot(self, points, key, color=Color.BLUE):
        # self.update_idletasks()
        self.clear()
        self.zoom(1)
        # self.drawgrid()

        plot_items = [self.overlay_items[key] for key in self.overlay_items]
        if key not in self.overlay_items:
            plot_items.append({"points": points, "color": color})

        self.x_axis_marker = self.create_element("line",
                                                 coords=(0, -0.05, 0, 0.05),
                                                 fill=Color.PALE_BLUE)
        self.y_axis_marker = self.create_element("line",
                                                 coords=(-0.05, 0, 0.05, 0),
                                                 fill=Color.PALE_BLUE)
        coords = []
        minimum = 0
        maximum = 0
        prev_real = None
        prev_imag = None
        T = 1e-14
        line_coords = []

        for graph in plot_items:
            points = graph["points"]
            line_color = graph["color"]
            coords.clear()
            line_coords.clear()
            for orientation in points:
                if isinstance(orientation, (np.ndarray, list)):
                    for line in orientation:
                        if isinstance(line, (int, float)):
                            line_coords.append(line if len(line_coords) %
                                               2 == 0 else -line)
                        elif isinstance(line, (complex, np.complex)):
                            coords.append(line.real)
                            coords.append(-line.imag)
                        elif isinstance(line[0], complex):
                            for point in line:
                                if point.real < minimum:
                                    minimum = point.real
                                if point.real > maximum:
                                    maximum = point.real
                                coords.append(point.real)
                                coords.append(-point.imag)
                            self.create_element(
                                "line",
                                coords=coords,
                                smooth=self.smooth,
                                fill=graph["color"] if
                                not self.has_random_color else random_color())
                            coords.clear()
                        elif isinstance(line, (np.ndarray, list)):
                            if len(line) == 2:
                                coords.append(line[0])
                                coords.append(-line[1])
                            else:
                                for half_plane in line:
                                    if isinstance(half_plane,
                                                  (np.ndarray, list)):
                                        for point in half_plane:
                                            if point.real < minimum:
                                                minimum = point.real
                                            if point.real > maximum:
                                                maximum = point.real
                                            coords.append(point.real)
                                            coords.append(-point.imag)
                                    self.create_element(
                                        "line",
                                        coords=coords,
                                        smooth=self.smooth,
                                        fill=graph["color"]
                                        if not self.has_random_color else
                                        random_color())
                                    coords.clear()
                        elif isinstance(line, tuple):
                            coords.append(line)
                    if coords:
                        self.create_element(
                            "line",
                            coords=coords,
                            smooth=self.smooth,
                            fill=graph["color"]
                            if not self.has_random_color else random_color())
                        coords.clear()
                elif isinstance(orientation, (int, np.int64, float)):
                    self.create_element(coords=(orientation, 0),
                                        fill=graph["color"])
                elif isinstance(orientation, complex):
                    self.create_element(coords=(orientation.real,
                                                -1 * orientation.imag),
                                        fill=graph["color"])
                elif isinstance(orientation, tuple):
                    line_coords.append((orientation[0], -1 * orientation[1]))

            if line_coords:
                self.create_element(
                    "line",
                    coords=line_coords,
                    smooth=self.smooth,
                    fill=graph["color"]
                    if not self.has_random_color else random_color())

            if maximum == minimum == 0:
                maximum = 1
                minimum = -1

            self.key = key
            if key not in self.cache:
                self.cache[key] = {
                    "zoomlevel": self.winfo_width() / abs(maximum - minimum),
                    "delta": [self.winfo_width() / 2,
                              self.winfo_height() / 2]
                }

        self.zoom(self.cache[key]["zoomlevel"], (0, 0))
        self.pan(self.cache[key]["delta"])
        self.drawgrid()
Beispiel #16
0
 def collide(self, next_velocity, partner):
     if self.color_scheme == PongBall.BOUNCE:
         self.color = util.random_color()
     self.velocity = next_velocity
Beispiel #17
0
def build_material(item=None,
                   i_POLYTAG=lx.symbol.i_POLYTAG_MATERIAL,
                   pTag=None,
                   parent=None,
                   name=None,
                   preset=None,
                   shader=False):
    """Builds a material in the shader tree, including a mask, material, and shader with default settings.

    :param item: item for mask to filter (optional)
    :type item: modo.item.Item() object

    :param i_POLYTAG: lx.symbol.i_POLYTAG_* (optional)
    :type i_POLYTAG: int

    :param pTag: pTag string (optional)
    :type pTag: str

    :param parent: parent (optional)
    :type parent: modo.item.Item() object

    :param name: name (optional)
    :type name: str

    :param preset: path to modo preset file (.lxp)
    :type preset: str

    :param shader: include shader in material group
    :type shader: bool
    """

    scene = modo.Scene()

    color = util.random_color()

    mask = add_mask(item, i_POLYTAG, pTag, parent, name)

    # debug("Added mask '%s'" % mask.name)

    if parent:
        parent = get_masks(names=parent)[0]
        if parent:
            mask.setParent(parent, parent.childCount())

            # debug("Set parent to '%s'" % parent.name)

    if preset:

        # debug("Doing preset '%s' in mask '%s'" % (preset, mask.name))

        preset_contents = do_preset(preset, mask)

    elif not preset:

        # debug("No preset specified. Building default material.")

        if (shader):
            sname = ' '.join([name, SHADERNAME]) if name else None
            shdr = add_shader(sname)
            shdr.setParent(mask)
            # debug("Added shader '%s'" % shdr.name)

        mname = ' '.join([name, MATNAME]) if name else None
        if lx.eval("user.value mecco_tagger.materialType ?") == MAT_ADVANCED:
            channels = {lx.symbol.sICHAN_ADVANCEDMATERIAL_DIFFCOL: color}
        elif lx.eval("user.value mecco_tagger.materialType ?") == MAT_UNREAL:
            channels = {"base": color}
        if lx.eval("user.value mecco_tagger.materialType ?") == MAT_UNITY:
            channels = {"albedo": color}
        mat = add_material(mname, channels)
        mat.setParent(mask)

        # debug("Added material '%s'" % mat.name)

    move_to_base_shader(mask)

    return mask