Example #1
0
    def get_face_card_design(self, value, symbol):
        from for_3b1b_videos.pi_creature import PiCreature
        sub_rect = Rectangle(
            stroke_color=BLACK,
            fill_opacity=0,
            height=0.9 * self.get_height(),
            width=0.6 * self.get_width(),
        )
        sub_rect.move_to(self)

        # pi_color = average_color(symbol.get_color(), GREY)
        pi_color = symbol.get_color()
        pi_mode = {
            "J": "plain",
            "Q": "thinking",
            "K": "hooray"
        }[value]
        pi_creature = PiCreature(
            mode=pi_mode,
            color=pi_color,
        )
        pi_creature.set_width(0.8 * sub_rect.get_width())
        if value in ["Q", "K"]:
            prefix = "king" if value == "K" else "queen"
            crown = SVGMobject(file_name=prefix + "_crown")
            crown.set_stroke(width=0)
            crown.set_fill(YELLOW, 1)
            crown.stretch_to_fit_width(0.5 * sub_rect.get_width())
            crown.stretch_to_fit_height(0.17 * sub_rect.get_height())
            crown.move_to(pi_creature.eyes.get_center(), DOWN)
            pi_creature.add_to_back(crown)
            to_top_buff = 0
        else:
            to_top_buff = SMALL_BUFF * sub_rect.get_height()
        pi_creature.next_to(sub_rect.get_top(), DOWN, to_top_buff)
        # pi_creature.shift(0.05*sub_rect.get_width()*RIGHT)

        pi_copy = pi_creature.copy()
        pi_copy.rotate(np.pi, about_point=sub_rect.get_center())

        return VGroup(sub_rect, pi_creature, pi_copy)
Example #2
0
    def add_coordinate_labels(self, numbers=None, **kwargs):
        if numbers is None:
            numbers = self.get_default_coordinate_values()

        self.coordinate_labels = VGroup()
        for number in numbers:
            z = complex(number)
            if abs(z.imag) > abs(z.real):
                axis = self.get_y_axis()
                value = z.imag
                kwargs = merge_dicts_recursively(
                    kwargs,
                    {"number_config": {"unit": "i"}},
                )
            else:
                axis = self.get_x_axis()
                value = z.real
            number_mob = axis.get_number_mobject(value, **kwargs)
            self.coordinate_labels.add(number_mob)
        self.add(self.coordinate_labels)
        return self
Example #3
0
 def get_basis_vectors(self, i_hat_color=X_COLOR, j_hat_color=Y_COLOR):
     """
     Returns a VGroup of the Basis Vectors (1,0) and (0,1)
     Parameters
     ----------
     i_hat_color (str)
         The hex colour to use for the basis vector in the x direction
     
     j_hat_color (str)
         The hex colour to use for the basis vector in the y direction
     
     Returns
     -------
     VGroup
         VGroup of the Vector Mobjects representing the basis vectors.
     """
     return VGroup(*[
         Vector(
             vect, color=color, stroke_width=self.basis_vector_stroke_width)
         for vect, color in [([1, 0], i_hat_color), ([0, 1], j_hat_color)]
     ])
Example #4
0
    def add_numbers(self,
                    x_values=None,
                    excluding=None,
                    font_size=24,
                    **kwargs):
        if x_values is None:
            x_values = self.get_tick_range()

        kwargs["font_size"] = font_size

        if excluding is None:
            excluding = self.numbers_to_exclude

        numbers = VGroup()
        for x in x_values:
            if excluding is not None and x in excluding:
                continue
            numbers.add(self.get_number_mobject(x, **kwargs))
        self.add(numbers)
        self.numbers = numbers
        return numbers
    def __init__(self, x_range=None, y_range=None, **kwargs):
        super().__init__(**kwargs)
        if x_range is not None:
            self.x_range[:len(x_range)] = x_range
        if y_range is not None:
            self.y_range[:len(y_range)] = y_range

        self.x_axis = self.create_axis(
            self.x_range,
            self.x_axis_config,
            self.width,
        )
        self.y_axis = self.create_axis(self.y_range, self.y_axis_config,
                                       self.height)
        self.y_axis.rotate(90 * DEGREES, about_point=ORIGIN)
        # Add as a separate group in case various other
        # mobjects are added to self, as for example in
        # NumberPlane below
        self.axes = VGroup(self.x_axis, self.y_axis)
        self.add(*self.axes)
        self.center()
Example #6
0
 def __init__(self, texmob, **kwargs):
     VMobject.__init__(self, **kwargs)
     rect = Rectangle(width=texmob.get_width() + self.margin,
                      height=texmob.get_height() + self.margin)
     rect.move_to(texmob)
     w = rect.get_width()
     h = rect.get_height()
     alpha = w / h
     hp = np.ceil(self.partitions / (2 * (alpha + 1)))
     wp = np.ceil(alpha * hp)
     sides = VGroup(*[
         Line(rect.get_corner(c1), rect.get_corner(c2))
         for c1, c2 in zip([UL, UR, DR, DL], [UR, DR, DL, UL])
     ])
     total_points = []
     for side, p in zip(sides, [wp, hp, wp, hp]):
         path = FreehandDraw(side, p).points
         for point in path:
             total_points.append(point)
     total_points.append(total_points[0])
     self.set_points_smoothly(total_points)
Example #7
0
    def construct(self):
        # construction of demo props
        lines = VGroup()
        for i in range(-5, 6):
            lines.add(Line(3 * UP + i * RIGHT, 3 * DOWN + i * RIGHT))

        # LaggedStartMap is used when you want to apply one animation to lots of mobjects
        # with lagged start

        # run_time is for the whole LaggedStartMap animation, not for individual animations
        # lag_ratio - how much does it wait before running next animation (as a ratio of the time
        # of one animation)
        # rate_func applies for individual animations, launching the animations is always linear,
        # because lag_ratio is constant
        self.play(
            LaggedStartMap(ShowCreation,
                           lines,
                           run_time=10,
                           lag_ratio=0.5,
                           rate_func=linear))
        self.wait()
Example #8
0
 def __init__(self, focal_point, **kwargs):
     digest_config(self, kwargs)
     circles = VGroup()
     for x in range(self.n_circles):
         circle = Circle(
             radius=self.big_radius,
             stroke_color=BLACK,
             stroke_width=0,
         )
         circle.add_updater(
             lambda c: c.move_to(focal_point)
         )
         circle.save_state()
         circle.set_width(self.small_radius * 2)
         circle.set_stroke(self.color, self.start_stroke_width)
         circles.add(circle)
     animations = [
         Restore(circle)
         for circle in circles
     ]
     super().__init__(*animations, **kwargs)
Example #9
0
 def add_shadow_mobjects(self,
                         shadow=2,
                         mobject=None,
                         color=WHITE,
                         opacity=0.9,
                         shift=([0.03, -0.01, 0]),
                         **kwargs):
     from manimlib.mobject.types.vectorized_mobject import VGroup
     group = VGroup()
     if mobject == None:
         mobject = self
     if shadow == 2:
         if isinstance(mobject, (Mobject)):
             mobject_2 = mobject.copy()
             mobject = mobject.copy()
         if isinstance(color, (list, tuple)) and len(color) == 2:
             color_2 = color[1]
             color = color[0]
         else:
             color_2 = invert_color(color)
         if isinstance(opacity, (list, tuple)) and len(opacity) == 2:
             opacity_2 = opacity[1]
             opacity = opacity[0]
         else:
             opacity_2 = opacity
         if isinstance(shift, (tuple)) and len(shift) == 2:
             shift_2 = shift[1]
             shift = shift[0]
         else:
             shift_2 = [each * -1 for each in shift]
         group.add(
             mobject_2.set_color(color_2).set_opacity(opacity_2).shift(
                 shift_2))  #
     elif shadow == 1:
         mobject = mobject.copy()
     else:
         return self
     group.add(mobject.set_color(color).set_opacity(opacity).shift(shift))
     self.remove(self.submobjects)
     return self.add_to_back(group, **kwargs).push_self_into_submobjects()
    def get_riemann_rectangles(self,
                               graph,
                               x_range=None,
                               dx=None,
                               input_sample_type="left",
                               stroke_width=1,
                               stroke_color=BLACK,
                               fill_opacity=1,
                               colors=(BLUE, GREEN),
                               show_signed_area=True):
        if x_range is None:
            x_range = self.x_range[:2]
        if dx is None:
            dx = self.x_range[2]
        if len(x_range) < 3:
            x_range = [*x_range, dx]

        rects = []
        xs = np.arange(*x_range)
        for x0, x1 in zip(xs, xs[1:]):
            if input_sample_type == "left":
                sample = x0
            elif input_sample_type == "right":
                sample = x1
            elif input_sample_type == "center":
                sample = 0.5 * x0 + 0.5 * x1
            else:
                raise Exception("Invalid input sample type")
            height = get_norm(self.i2gp(sample, graph) - self.c2p(sample, 0))
            rect = Rectangle(width=x1 - x0, height=height)
            rect.move_to(self.c2p(x0, 0), DL)
            rects.append(rect)
        result = VGroup(*rects)
        result.set_submobject_colors_by_gradient(*colors)
        result.set_style(
            stroke_width=stroke_width,
            stroke_color=stroke_color,
            fill_opacity=fill_opacity,
        )
        return result
Example #11
0
 def get_coordinate_labels(self, x_vals=None, y_vals=None):
     coordinate_labels = VGroup()
     if x_vals is None:
         x_vals = list(range(-int(self.x_radius), int(self.x_radius) + 1))
     if y_vals is None:
         y_vals = list(range(-int(self.y_radius), int(self.y_radius) + 1))
     for index, vals in enumerate([x_vals, y_vals]):
         num_pair = [0, 0]
         for val in vals:
             if val == 0:
                 continue
             num_pair[index] = val
             point = self.coords_to_point(*num_pair)
             num = TexMobject(str(val))
             num.add_background_rectangle()
             num.set_height(
                 self.written_coordinate_height
             )
             num.next_to(point, DOWN + LEFT, buff=SMALL_BUFF)
             coordinate_labels.add(num)
     self.coordinate_labels = coordinate_labels
     return coordinate_labels
Example #12
0
 def generate_points(self):
     self.add(Rectangle(
         height=self.height,
         width=self.height / self.height_to_width,
         stroke_color=WHITE,
         stroke_width=2,
         fill_color=self.color,
         fill_opacity=1,
     ))
     if self.turned_over:
         self.set_fill(DARK_GREY)
         self.set_stroke(LIGHT_GREY)
         contents = VectorizedPoint(self.get_center())
     else:
         value = self.get_value()
         symbol = self.get_symbol()
         design = self.get_design(value, symbol)
         corner_numbers = self.get_corner_numbers(value, symbol)
         contents = VGroup(design, corner_numbers)
         self.design = design
         self.corner_numbers = corner_numbers
     self.add(contents)
Example #13
0
    def show(
        self,
        text_anim: Animation = Write,
        arrow_anim: Animation = FadeInFromDown,
        **kwargs,
    ) -> AnimationGroup:
        """Workaround and shortcut method to overcome the bugs in `Write`.

        Args:
            text_anim (Animation, optional): The animation on the reactants and products. Defaults to Write.
            arrow_anim (Animation, optional): The animation on the arrow. Defaults to FadeInFromDown.

        Returns:
            AnimationGroup: The group of animations on the text and arrow.
        """
        text = VGroup(self[0:2 * len(self.reactants) - 1],
                      self[2 * len(self.reactants):])
        arrow = self[2 * len(self.reactants) - 1]

        if "text_kwargs" not in kwargs.keys():
            kwargs["text_kwargs"] = dict()

        if "arrow_kwargs" not in kwargs.keys():
            kwargs["arrow_kwargs"] = dict()

        if "group_kwargs" not in kwargs.keys():
            kwargs["group_kwargs"] = dict()

        print(kwargs["group_kwargs"])

        anim_group = AnimationGroup(text_anim(text), arrow_anim(arrow),
                                    **kwargs)

        try:
            print(anim_group.run_time)
        except Exception:
            pass
        return anim_group
def VisitTriangles(face):
    # 访问网
    visitvalue = face.Visit
    notvisitvalue = not visitvalue
    faces = [face]
    # 访问过
    face.Visit = notvisitvalue

    delaunaynet = VGroup()

    while faces:
        eachface = faces[-1]
        faces.pop(-1)
        # 面所在的三条边
        e1 = eachface.HalfEdge
        e2 = e1.Suc
        e3 = e2.Suc
        # 标记访问过
        e1.Visit = notvisitvalue
        e2.Visit = notvisitvalue
        e3.Visit = notvisitvalue
        # 面对三个点
        p1 = e1.Start.Point
        p2 = e2.Start.Point
        p3 = e3.Start.Point
        delaunaynet.add(Polygon(p1, p2, p3))
        ei = [e1, e2, e3]
        for each in ei:
            et = each.Twin
            if et:
                etf = et.Face
                # 未访问过
                if etf.Visit == visitvalue:
                    # 访问过
                    etf.Visit = notvisitvalue
                    faces.append(etf)

    return delaunaynet
Example #15
0
    def add_black_keys(self):
        key = Rectangle(*self.black_key_dims)
        key.set_fill(self.black_key_color, 1)
        key.set_stroke(width=0)

        self.black_keys = VGroup()
        for i in range(len(self.white_keys) - 1):
            if i % self.white_keys_per_octave not in self.black_pattern:
                continue
            wk1 = self.white_keys[i]
            wk2 = self.white_keys[i + 1]
            bk = key.copy()
            bk.move_to(midpoint(wk1.get_top(), wk2.get_top()), UP)
            big_bk = bk.copy()
            big_bk.stretch((bk.get_width() + self.key_buff) / bk.get_width(),
                           0)
            big_bk.stretch((bk.get_height() + self.key_buff) / bk.get_height(),
                           1)
            big_bk.move_to(bk, UP)
            for wk in wk1, wk2:
                wk.become(Difference(wk, big_bk).match_style(wk))
            self.black_keys.add(bk)
        self.add(*self.black_keys)
Example #16
0
def set_up_the_bubbles(coordinates_at_a_time, Rdata_at_a_time, axes, color_mat):

    # the argument coordinates_at_a_time and Rdata_at_a_time is 
    # just one column in coordinates and Rdata
    # specifically coordinates_at_a_time = coordinates[:,0]
    # Rdata_at_a_time = Rdata[:,0]

    #dimension check
    assert(coordinates_at_a_time.shape[0] == Rdata_at_a_time.shape[0] and len(color_mat))
    assert(len(coordinates_at_a_time.shape) == 2)
    assert(isinstance(color_mat,list))
    

    bubbles = VGroup()
    for i,bubbledata in enumerate(zip(coordinates_at_a_time,Rdata_at_a_time)):
        bubbles.add(
            Circle(
                radius = bubbledata[1], 
                color = color_mat[i], 
                fill_opacity = FILL_OPACITY).shift(bubbledata[0])
            )

    return bubbles
Example #17
0
 def __init__(self, **kwargs):
     #### EULERTOUR_INIT_START ####
     if not hasattr(self, "args"):
         self.args = serialize_args([])
     if not hasattr(self, "config"):
         self.config = serialize_config({
             **kwargs,
         })
     #### EULERTOUR_INIT_START ####
     VGroup.__init__(self, **kwargs)
     self.x_axis = self.create_axis(
         self.x_min, self.x_max, self.x_axis_config
     )
     self.y_axis = self.create_axis(
         self.y_min, self.y_max, self.y_axis_config
     )
     self.y_axis.rotate(90 * DEGREES, about_point=ORIGIN)
     # Add as a separate group incase various other
     # mobjects are added to self, as for example in
     # NumberPlane below
     self.axes = VGroup(self.x_axis, self.y_axis)
     self.add(*self.axes)
     self.shift(self.center_point)
Example #18
0
def get_det_text(matrix,
                 determinant=None,
                 background_rect=False,
                 initial_scale_factor=2):
    parens = Tex("(", ")")
    parens.scale(initial_scale_factor)
    parens.stretch_to_fit_height(matrix.get_height())
    l_paren, r_paren = parens.split()
    l_paren.next_to(matrix, LEFT, buff=0.1)
    r_paren.next_to(matrix, RIGHT, buff=0.1)
    det = TexText("det")
    det.scale(initial_scale_factor)
    det.next_to(l_paren, LEFT, buff=0.1)
    if background_rect:
        det.add_background_rectangle()
    det_text = VGroup(det, l_paren, r_paren)
    if determinant is not None:
        eq = Tex("=")
        eq.next_to(r_paren, RIGHT, buff=0.1)
        result = Tex(str(determinant))
        result.next_to(eq, RIGHT, buff=0.2)
        det_text.add(eq, result)
    return det_text
Example #19
0
 def diminish(self,
              *mobjects,
              run_time=1,
              pre_time=0.5,
              post_time=1,
              **kwargs):
     '''
     if not isinstance(mobject_or_chars, (list, tuple, ndarray)):
         mobject_or_chars = [mobject_or_chars]
     mobject = VGroup(*[MobjectOrChars(each) for each in mobject_or_chars])
     '''
     if not mobjects:
         mobjects = ListedMobject(self.mobjects)
     imobjs = Group()
     vmobjs = VGroup()
     mobjs = Group()
     for each in mobjects:
         if isinstance(each, ImageMobjectGroup):
             imobjs.add(each)
         elif isinstance(each, VMobject):
             vmobjs.add(each)
         else:
             mobjs.add(each)
     '''
     vmobjs=VGroup(*[each.remove_from_group(mobjects) for each in mobjects if isinstance(each, VMobject)])
     mobjs=Group(*[each for each in mobjects if isinstance(each, Mobject)])
     '''
     #mobject = GroupedMobject(mobjects)
     #keys = ["shift"]
     #[exec("mobject."+key+"(["+','.join(str(x) for x in kwargs.get(key))+"])",
     #      {"mobject": mobject}) for key in keys if key in kwargs]
     #self.wait(pre_time)
     self.play(
         AnimationGroup(DiminishToPoint(vmobjs, [0, 0, 0]), DFadeOut(mobjs),
                        ShrinkToCenter(imobjs)))
     self.wait(post_time)
     return self
 def get_vertical_lines_to_graph(
     self, graph,
     x_min=None,
     x_max=None,
     num_lines=20,
     **kwargs
 ):
     """
     Obtains multiple lines from the x axis to the Graph/curve.
     
     Parameters
     ----------
     graph (ParametricFunction)
         The graph on which the line should extend to.
     
     x_min (Union[int, float])
         The lower bound from which lines can appear.
     
     x_max (Union[int, float])
         The upper bound until which the lines can appear.
     
     num_lines (Union[int, float])
         The number of lines (evenly spaced)
         that are needed.
     
     Returns
     -------
     VGroup
         The VGroup of the evenly spaced lines.
     
     """
     x_min = x_min or self.x_min
     x_max = x_max or self.x_max
     return VGroup(*[
         self.get_vertical_line_to_graph(x, graph, **kwargs)
         for x in np.linspace(x_min, x_max, num_lines)
     ])
Example #21
0
    def construct(self):
        words = TextMobject(
            "3",
            "Blue",
            "1",
            "Brown",
        )
        words.scale(2)
        words[::2].scale(1.2)
        buff = 0.2
        words.arrange(
            DOWN,
            buff=buff,
            aligned_edge=LEFT,
        )
        words[0].match_x(words[1][0])
        words[2].match_x(words[3][0])
        self.add(words)

        logo = Logo()
        logo.next_to(words, LEFT)
        self.add(logo)

        VGroup(logo, words).center()
Example #22
0
 def add_iris_back(self):
     blue_iris_back = AnnularSector(
         inner_radius=self.pupil_radius,
         outer_radius=self.outer_radius,
         angle=270 * DEGREES,
         start_angle=180 * DEGREES,
         fill_color=self.iris_background_blue,
         fill_opacity=1,
         stroke_width=0,
     )
     brown_iris_back = AnnularSector(
         inner_radius=self.pupil_radius,
         outer_radius=self.outer_radius,
         angle=90 * DEGREES,
         start_angle=90 * DEGREES,
         fill_color=self.iris_background_brown,
         fill_opacity=1,
         stroke_width=0,
     )
     self.iris_background = VGroup(
         blue_iris_back,
         brown_iris_back,
     )
     self.add(self.iris_background)
Example #23
0
    def init_points(self) -> None:
        # Star by creating two of the pentagons, meeting
        # back to back on the positive x-axis
        phi = (1 + math.sqrt(5)) / 2
        x, y, z = np.identity(3)
        pentagon1 = Polygon(
            [phi, 1 / phi, 0],
            [1, 1, 1],
            [1 / phi, 0, phi],
            [1, -1, 1],
            [phi, -1 / phi, 0],
        )
        pentagon2 = pentagon1.copy().stretch(-1, 2, about_point=ORIGIN)
        pentagon2.reverse_points()
        x_pair = VGroup(pentagon1, pentagon2)
        z_pair = x_pair.copy().apply_matrix(np.array([z, -x, -y]).T)
        y_pair = x_pair.copy().apply_matrix(np.array([y, z, x]).T)

        self.add(*x_pair, *y_pair, *z_pair)
        for pentagon in list(self):
            pc = pentagon.copy()
            pc.apply_function(lambda p: -p)
            pc.reverse_points()
            self.add(pc)
Example #24
0
 def get_basis_vector_labels(self, **kwargs):
     """
     Returns naming labels for the basis vectors.
     Parameters
     ----------
     **kwargs
         Any valid keyword arguments of get_vector_label:
             vector,
             label (str,TexMobject)
             at_tip (bool=False),
             direction (str="left"),
             rotate (bool),
             color (str),
             label_scale_factor=VECTOR_LABEL_SCALE_FACTOR (int, float),
     """
     i_hat, j_hat = self.get_basis_vectors()
     return VGroup(*[
         self.get_vector_label(
             vect, label, color=color, label_scale_factor=1, **kwargs)
         for vect, label, color in [
             (i_hat, "\\hat{\\imath}", X_COLOR),
             (j_hat, "\\hat{\\jmath}", Y_COLOR),
         ]
     ])
Example #25
0
 def show_different_levels_of_zooming(self):
     self.zoom_in_on(1/2., 6)
     self.wait()
     self.acl = VGroup(self.axes, self.circles, self.labels)
     self.acl.save_state()
     # First Zoom
     self.play_farey_sum_animation(0, 1, 1, 1)
     self.wait()
     # Second Zoom
     self.play_zooming_animation(1/np.sqrt(2), 9, run_time = 2)
     self.play_farey_sum_animation(2, 3, 3, 4)
     self.wait()
     # Third Zoom
     self.play_zooming_animation(0.73, 5, run_time = 2)
     self.play_farey_sum_animation(5, 7, 8, 11)
     self.wait()
     # Fourth Zoom
     self.play_zooming_animation(0.74, 5, run_time = 2)
     self.play_farey_sum_animation(11, 15, 14, 19)
     self.play_farey_sum_animation(14, 19, 17, 23)
     self.wait()
     # Reset
     self.play(Restore(self.acl), lag_ratio = 0, run_time = 4)
     self.wait()
Example #26
0
 def get_parts_by_tex(self, tex):
     return VGroup(*[
         self.get_part_by_custom_span_tuple(match_obj.span())
         for match_obj in re.finditer(re.escape(tex), self.tex_string)
     ])
Example #27
0
 def append_new_submobject(glyphs):
     if glyphs:
         submobject = VGroup(*glyphs)
         submobject.submob_label = glyphs[0].glyph_label
         new_submobjects.append(submobject)
Example #28
0
 def get_on_screen_pi_creatures(self):
     mobjects = self.get_mobject_family_members()
     return VGroup(
         *[pi for pi in self.get_pi_creatures() if pi in mobjects])
Example #29
0
 def create_pi_creatures(self):
     """
     Likely updated for subclasses
     """
     return VGroup(self.create_pi_creature())
Example #30
0
 def setup(self):
     self.pi_creatures = VGroup(*self.create_pi_creatures())
     self.pi_creature = self.get_primary_pi_creature()
     if self.pi_creatures_start_on_screen:
         self.add(*self.pi_creatures)