file_path stringlengths 50 109 | content stringlengths 42 76k |
|---|---|
AnimationsWithManim_Elteoremadebeethoven/README.md | <p align="center"><img src ="/_title.gif" /></p>
## Contents (updating)
### [Tutorial files](https://drive.google.com/open?id=10LYJVJsvkcl5a7q_S-ZlSxI7hEBepw3P)
### [Documentation](https://elteoremadebeethoven.github.io/manim_3feb_docs.github.io/html/index.html)
### Freelance job
If you need an animation made in Manim **I can do it for you**. I also give private tutorials on Manim, Python and LaTeX.
* Gmail: theoremofbeethoven@gmail.com
* Discord: theoremofbeethoven#2781
* Reddit: u/TheoremofBeethoven
### This tutorial is based on the manim version of [3 february of 2019](https://github.com/3b1b/manim/tree/3b088b12843b7a4459fe71eba96b70edafb7aa78)
0. Installation on [Windows](https://www.youtube.com/watch?v=ZltiKHFWmv8), [GNU/Linux](https://www.youtube.com/watch?v=z_WJaHYH66M) and [Mac](https://www.youtube.com/watch?v=uZj_GQc6pN4).
1. [Text format](https://github.com/Elteoremadebeethoven/AnimationsWithManim/blob/master/English/1_text_formats/scenes.md)/[Part 1 - Youtube](https://www.youtube.com/watch?v=yI2YJff9SgI)/[Part 2 - YouTube](https://www.youtube.com/watch?v=Km09KYWb9ag)/[Part 3 - YouTube](https://www.youtube.com/watch?v=gIvQsqXy5os)
2. Tex formulas/[YouTube](https://www.youtube.com/watch?v=DGSj7weT-y8)
3. [Text like arrays](https://github.com/Elteoremadebeethoven/AnimationsWithManim/blob/master/English/3_text_like_arrays/scenes.md)/[YouTube](https://www.youtube.com/watch?v=QEdVn8socC8)
4. [Transformations](https://github.com/Elteoremadebeethoven/AnimationsWithManim/blob/master/English/4_transform/scenes.md)/[Part 1 - YouTube](https://www.youtube.com/watch?v=HKPm8FZYaqI)/[Part 2 - YouTube](https://www.youtube.com/watch?v=qfifBmYTEfA)
5. [Visual tools](https://github.com/Elteoremadebeethoven/AnimationsWithManim/blob/master/English/5_visual_tools/scenes.md)/YouTube
6. [Introduction in 2D plot](https://github.com/Elteoremadebeethoven/AnimationsWithManim/blob/master/English/6a_plots_2D/scenes.md)/YouTube
7. [Introduction in 3D plot](https://github.com/Elteoremadebeethoven/AnimationsWithManim/blob/master/English/6b_plots_3D/scenes.md)/YouTube
8. Add images, svgs and audio/YouTube
9. [Update functions](https://github.com/Elteoremadebeethoven/AnimationsWithManim/blob/master/English/update_successions/update_successions.py)/YouTube
10. First project/YouTube
Challenges:
* [Roulette Epicycloids](https://github.com/Elteoremadebeethoven/AnimationsWithManim/blob/master/English/extra/manim_challenges/roulette_epicycloids.py)
* [M mod N Epicycloids](https://github.com/Elteoremadebeethoven/AnimationsWithManim/blob/master/English/extra/manim_challenges/MmodN_epicycloids.py)
* [Dragon fractal](https://github.com/Elteoremadebeethoven/AnimationsWithManim/blob/master/English/extra/manim_challenges/dragon_fractal.py)
* [Analytic Geometry Series](https://github.com/Elteoremadebeethoven/AnimationsWithManim/blob/master/English/extra/manim_challenges/geo_analy.py)
Settings:
* [Leave progress bars by default.](https://www.youtube.com/watch?v=K8dVFqXR2JM)
* [Rendering settings.](https://www.youtube.com/watch?v=d_2V5mC2hx0)
* [Modify the directory "media".](https://www.youtube.com/watch?v=I9rHHiKqTWY)
* [Set FPS via terminal.](https://www.youtube.com/watch?v=cyIz0Oh3lWY)
* [Export as GIF.](https://www.youtube.com/watch?v=juFfUwJUTtI)
Extras:
* [Learn Manim by yourself - How to render most files in old_projects.](https://www.youtube.com/watch?v=vzyzqv8Sp8Y)
* [How to create your own Number Creature.](https://www.youtube.com/watch?v=KGdA8IB6JL0)
* [FAQs](https://github.com/Elteoremadebeethoven/AnimationsWithManim/blob/master/English/extra/faqs/faqs.md)
Support this work in:
* [Patreon](https://patreon.com/theoremofbeethoven)
* [PayPal](https://www.paypal.me/zavdn)
## What is Manim?
[Manim](https://github.com/3b1b/manim) is a free tool for Python created by [Grant Sanderson](http://www.3blue1brown.com/) ([twitter](https://twitter.com/3blue1brown?lang=es)), mathematician from Stanford and owner of the YouTube channel [3Blue1Brown](https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw). It is specialized in scientific subjects, mainly mathematical, so it is based on LaTeX commands (mainly in TeX).
## What is LaTeX?
LaTeX is a processor of specialized texts in the scientific field, however, manim only uses TeX commands (with some exceptions), which refers to the writing of formulas. An example of the code in TeX is:
```latex
\frac{d}{dx}f(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}.
```
If I built this command TeX return:
<p align="center"><img src ="https://raw.githubusercontent.com/Elteoremadebeethoven/AnimacionesConManim/master/TeX.png" /></p>
## Who is tutorials for?
This course is mainly aimed at teachers who want to explain a didactic and graphic form a mathematical development or the resolution of especially complex problems. The course extends to anyone who wants to explain a scientific topic in a original way.
## I need to know Python 3 and LaTeX to take this tutorials?
No, it is not necesary to know something of programming (although it is preferable for faster learning). In addition to learning Python3, teX knowledge is required to write the formulas. Likewise will mention tools such as [Pencil chromestore](http://s1.daumcdn.net/editor/fp/service_nc/pencil/Pencil_chromestore.html), [Codecogs](https://www.codecogs.com/latex/eqneditor.php), [Rinconmatematico](http://rinconmatematico.com/mathjax/), [latex4technics](https://www.latex4technics.com/), [sciweavers](http://www.sciweavers.org/free-online-latex-equation-editor) in other pages to learn and write formulas in TeX.
## I need a modern PC to run Manim?
No, with 512 MB of RAM and an Intel Core Duo processor (or similar) is more than enough, the difference is the compile time (fewer the resources, the longer it will take to render).
## What advantages does Manim offer with respect to other animation tools?
### Advantages:
* It is free and legal.
* Works on Windows, GNU/Linux (any distribution) and Mac perfectly.
* Can be used in old computers.
* Being open source, it is completely customizable to the user's taste.
* It is constantly improving.
* The video files are very high quality and light.
* The formulas are created using TeX commands, so they are of professional quality.
* In the case of not having programming knowledge, it is a good tool to start learning Python and LaTeX.
### Disadvantages:
* If you do not have the LaTeX package (complete) installed, it will occupy more than 4 GB of space on your computer (Though you can opt for basic instead of complete installation of LaTex which is efficient in terms of download size, and then download other package as per the need).
* A graphic interface is not used to perform the animations, everything is based on the Python 3 and TeX commands. The example of the classic Hello world! would be
```python
from manimlib.imports import *
class HelloWorld(Scene):
def construct(self):
helloWorld = TextMobject("Hello world!")
self.play(Write(helloWorld))
self.wait()
```
<p align="center"><img src ="https://raw.githubusercontent.com/Elteoremadebeethoven/AnimacionesConManim/master/HelloWorld.gif" /></p>
## Requirements
* Python 3.7
* pip (to install plug ins of python)
* Cairo
* FFmpeg
* LaTeX (complete)
* Sox
* A few plug ins on the list requirements.txt
|
AnimationsWithManim_Elteoremadebeethoven/ParticularAdvice.md | # Particular advice.
Donations depend on the type of question you ask, if it is very basic it can be 10 USD, but if it is more complex, it can reach up to 50 USD. Contact me (private Discord chat, Reddit chat, Email) and ask the question, I will tell you how much the donation should be.
In case you want me to make a complete animation (that is, all the work of an animation) you can also request it, I will indicate the price.
**email: theoremofbeethoven@gmail.com**
# Asesoramiento particular.
Las donaciones dependen del tipo de pregunta que hagas, si es muy básica puede ser de 10 dólares, pero si es más compleja, puede llegar hasta los 50 dólares. Contacta conmigo (chat privado en Discord, chat de Reddit, Email) y realiza la pregunta, yo te diré de cuanto debe de ser la donación.
En caso de que quieras que yo realize una animación completa (es decir, todo el trabajo de una animación) también la puedes solocitar, yo te indicaré el precio.
**email: elteoremadebeethoven@gmail.com**
# Hire me as a freelance
To apply for the job, some requirements must be met.
1. You must be very clear about the progression of your animation, preferably have sketches of how you want to have your animation, step by step, in great detail.
2. Work less than 100 USD is paid half in advance, if it exceeds 100 USD one third is paid in advance.
3. If you want the source code to be shared (via GitHub or GitLab) the price increases by 25% to the initial price.
4. The cost of the animation depends on:
* The duration.
* The complexity of programming.
* If there is a need to optimize the resources of the PC the price increases.
* If advanced knowledge of Mathematics, Physics or other science is required, the price increases.
* If you want an abstract class (generic code to create animations) the price can even triple due to the modularization of the code.
* The time to make the code.
5. Payment is made via [PayPal](https://www.paypal.me/zavdn).
Contact:
Gmail: theoremofbeethoven@gmail.com
Or Discord: theoremofbeethoven#2781
# Contrátame como freelance
Para solicitar el trabajo se deben cumplir algunos requisitos.
1. Debes de tener muy claro la progresión de tu animación, de preferencia tener bocetos de cómo la quieres, paso a paso, con lujo de detalles.
2. Los trabajos menores a 100 USD se paga la mitad por adelantado, si supera los 100 USD se paga una tercera parte por adelantado.
3. Si se desea que el código fuente sea compartido (via GitHub o GitLab) el precio se incrementa un 25% a la cotización inicial.
4. El costo de la animación depende de:
* La duración.
* La complejidad de programación.
* Si hay necesidad de optimizar los recursos de la PC el precio aumenta.
* Si se requieren conocimientos avanzados de Matemáticas, Física u otra ciencia el precio aumenta.
* Si se desea una clase abstracta (código genérico para crear animaciones) el precio puede hasta triplicarse debido a la modularización del código.
* El tiempo para realizar el código.
5. El pago se realiza via [PayPal](https://www.paypal.me/zavdn).
Contacto:
Gmail: theoremofbeethoven@gmail.com
O Discord: theoremofbeethoven#2781
|
AnimationsWithManim_Elteoremadebeethoven/math_capsules/inscribed_angle.py | from manimlib.imports import *
class DecimalTextNumber(VMobject):
CONFIG = {
"num_decimal_places": 2,
"include_sign": False,
"group_with_commas": True,
"digit_to_digit_buff": 0.05,
"show_ellipsis": False,
"unit_type": "font", # tex or font
"unit": None, # Aligned to bottom unless it starts with "^"
"unit_custom_position": lambda mob: mob.set_color(GREEN).shift(RIGHT*0.1),
"include_background_rectangle": False,
"edge_to_fix": LEFT,
"unit_config": {
"font": "Digital-7",
"stroke_width": 0,
},
"number_config": {
"font": r"Digital-7",
"stroke_width": 0,
}
}
def __init__(self, number=0, **kwargs):
super().__init__(**kwargs)
self.number = number
self.initial_config = kwargs
if isinstance(number, complex):
formatter = self.get_complex_formatter()
else:
formatter = self.get_formatter()
num_string = formatter.format(number)
rounded_num = np.round(number, self.num_decimal_places)
if num_string.startswith("-") and rounded_num == 0:
if self.include_sign:
num_string = "+" + num_string[1:]
else:
num_string = num_string[1:]
self.add(*[
Text(char,color=self.color,**self.number_config)
for char in num_string
])
# Add non-numerical bits
if self.show_ellipsis:
self.add(SingleStringTexMobject("\\dots"))
if num_string.startswith("-"):
minus = self.submobjects[0]
minus.next_to(
self.submobjects[1], LEFT,
buff=self.digit_to_digit_buff
)
self.num_string = num_string
if self.unit is not None:
if self.unit_type == "font":
self.unit_sign = Text(self.unit,**self.unit_config)
elif self.unit_type == "tex":
del self.unit_config["font"]
self.unit_sign = TexMobject(self.unit,**self.unit_config)
self.add(self.unit_sign)
self.arrange(
buff=self.digit_to_digit_buff,
aligned_edge=DOWN
)
# Handle alignment of parts that should be aligned
# to the bottom
for i, c in enumerate(num_string):
if c == "-" and len(num_string) > i + 1:
self[i].align_to(self[i + 1], UP)
self[i].shift(self[i+1].get_height() * DOWN / 2)
elif c == ",":
self[i].shift(self[i].get_height() * DOWN / 2)
if self.unit and self.unit.startswith("^"):
self.unit_sign.align_to(self, UP)
#
if self.include_background_rectangle:
self.add_background_rectangle()
self.unit_custom_position(self.unit_sign)
# if num_string[0] == "-" or num_string[0] == "+":
# self[0].set_width(0.2)
# self[0].set_color(RED)
def get_formatter(self, **kwargs):
config = dict([
(attr, getattr(self, attr))
for attr in [
"include_sign",
"group_with_commas",
"num_decimal_places",
]
])
config.update(kwargs)
return "".join([
"{",
config.get("field_name", ""),
":",
"+" if config["include_sign"] else "",
"," if config["group_with_commas"] else "",
".", str(config["num_decimal_places"]), "f",
"}",
])
def get_complex_formatter(self, **kwargs):
return "".join([
self.get_formatter(field_name="0.real"),
self.get_formatter(field_name="0.imag", include_sign=True),
"i"
])
def set_value(self, number, **config):
full_config = dict(self.CONFIG)
full_config.update(self.initial_config)
full_config.update(config)
new_decimal = DecimalTextNumber(number, **full_config)
# Make sure last digit has constant height
#new_decimal.scale(
# self[-1].get_height() / new_decimal[-1].get_height()
#)
#"""
height = new_decimal.get_height()
yPos = new_decimal.get_center()[1]
for nr in new_decimal:
if "." != nr.text :
nr.scale(height/nr.get_height())
nr.shift([0,(yPos-nr.get_center()[1]),0])
max_width = max(*[f.get_width() for f in new_decimal[1:]])
if new_decimal[0].text == "-" or new_decimal[0].text == "+":
new_decimal[0].set_width(max_width)
new_decimal[0].set_color(RED)
#"""
new_decimal.move_to(self, self.edge_to_fix)
new_decimal.match_style(self)
old_family = self.get_family()
self.submobjects = new_decimal.submobjects
for mob in old_family:
# Dumb hack...due to how scene handles families
# of animated mobjects
mob.points[:] = 0
self.number = number
# if num_string[0] == "-" or num_string[0] == "+":
# self[0].set_width(0.2)
# self[0].set_color(RED)
return self
def get_value(self):
return self.number
def increment_value(self, delta_t=1):
self.set_value(self.get_value() + delta_t)
class ChangingDecimalText(Animation):
CONFIG = {
"suspend_mobject_updating": False,
}
def __init__(self, decimal_mob, number_update_func, **kwargs):
self.check_validity_of_input(decimal_mob)
self.yell_about_depricated_configuration(**kwargs)
self.number_update_func = number_update_func
super().__init__(decimal_mob, **kwargs)
def check_validity_of_input(self, decimal_mob):
if not isinstance(decimal_mob, DecimalTextNumber):
raise Exception(
"ChangingDecimal can only take "
"in a DecimalNumber"
)
def yell_about_depricated_configuration(self, **kwargs):
# Obviously this would optimally be removed at
# some point.
for attr in ["tracked_mobject", "position_update_func"]:
if attr in kwargs:
warnings.warn("""
Don't use {} for ChangingDecimal,
that functionality has been depricated
and you should use a mobject updater
instead
""".format(attr)
)
def interpolate_mobject(self, alpha):
self.mobject.set_value(
self.number_update_func(alpha)
)
class ChangeDecimalToValueText(ChangingDecimalText):
def __init__(self, decimal_mob, target_number, **kwargs):
start_number = decimal_mob.number
super().__init__(
decimal_mob,
lambda a: interpolate(start_number, target_number, a),
**kwargs
)
class ArcBetweenVectors(Arc):
def __init__(self, radius, d1, d2, center, invert_angle=False,**kwargs):
line1 = Line(center.get_center(),d1.get_center())
line2 = Line(center.get_center(),d2.get_center())
h = Line(center.get_center(),center.get_center()+RIGHT)
angle = angle_between_vectors(line1.get_unit_vector(),line2.get_unit_vector())
h1 = angle_between_vectors(h.get_unit_vector(),line1.get_unit_vector())
h2 = angle_between_vectors(h.get_unit_vector(),line2.get_unit_vector())
if line1.get_angle() <= line2.get_angle():
start_angle = h1
else:
start_angle = h2
if invert_angle:
start_angle = -start_angle
super().__init__(start_angle, angle,radius=radius,arc_center=center.get_center(), **kwargs)
def get_angle(self):
return self.angle
class LabelFromArc(TexMobject):
CONFIG = {
"distance_proportion": 1.2
}
def __init__(self, arc, tex_height, *tex_strings, **kwargs):
super().__init__(*tex_strings, **kwargs)
self.set_height(tex_height)
center = arc.get_arc_center()
max_size = max(self.get_width(),self.get_height()) * self.distance_proportion/ 2
vector = Line(center,arc.point_from_proportion(0.5)).get_vector()
end_coord = center+vector + normalize(vector)*max_size
self.move_to(end_coord)
class CircleWithAngles(VGroup):
CONFIG = {
"inner_line_config": {"color":PURPLE_A},
"outer_line_config": {"color":TEAL_A},
"inner_arc_config": {"color":PURPLE_A},
"outer_arc_config": {"color":TEAL_A},
"tex_1_config": {"color": TEAL_A},
"tex_2_config": {"color": PURPLE_A},
}
def __init__(self, radius=3, ang1=30, ang2=130, ang3=260, small_radius=0.4, **kwargs):
digest_config(self, kwargs)
super().__init__(**kwargs)
circle = Circle(radius=radius)
vt_1 = ValueTracker(ang1)
vt_2 = ValueTracker(ang2)
vt_3 = ValueTracker(ang3)
p1 = Dot(circle.point_at_angle(ang1*DEGREES))
p2 = Dot(circle.point_at_angle(ang2*DEGREES))
p3 = Dot(circle.point_at_angle(ang3*DEGREES))
in_lines = VMobject(**self.inner_line_config)
# ------------- LINES
out_lines = VMobject(**self.outer_line_config)
# ------------- ANGLES
out_arc = self.get_arc_between_lines(small_radius,p1,p2,p3)
in_arc = self.get_inner_angle(small_radius,p1,p2,p3,circle)
# ------------- LABELS
theta_2 = TexMobject("2\\theta",**self.tex_2_config)
theta_1 = TexMobject("\\theta",**self.tex_1_config)
# ------------- Equals
theta_1_val = DecimalTextNumber(0,unit="deg",num_decimal_places=3,**self.tex_2_config)
theta_2_val = DecimalTextNumber(0,unit="deg",num_decimal_places=3,**self.tex_1_config)
equal = Text("= 2 * ",font="Digital-7")
theta_eq = VGroup(theta_1_val, equal, theta_2_val)
theta_eq_temp = VGroup(theta_1_val, equal, theta_2_val)
theta_eq.arrange(RIGHT,buff=0.6,aligned_edge=DOWN)
theta_2_val.shift(LEFT*max(*[f.get_width() for f in theta_2_val])*1)
rectangle = Rectangle(width=theta_eq.get_width()+0.2,height=theta_eq.get_height()+0.2)
rectangle.move_to(theta_eq)
theta_eq.add(rectangle)
# UPDATERS
p1.add_updater(lambda mob: mob.move_to(circle.point_at_angle(vt_1.get_value()*DEGREES)))
p2.add_updater(lambda mob: mob.move_to(circle.point_at_angle(vt_2.get_value()*DEGREES)))
p3.add_updater(lambda mob: mob.move_to(circle.point_at_angle(vt_3.get_value()*DEGREES)))
in_lines.add_updater(lambda mob: mob.set_points_as_corners([
p1.get_center(),circle.get_center(),p2.get_center()
]))
out_lines.add_updater(lambda mob: mob.set_points_as_corners([
p1.get_center(),p3.get_center(),p2.get_center()
]))
out_arc.add_updater(lambda mob: mob.become(self.get_arc_between_lines(small_radius,p1,p2,p3)))
in_arc.add_updater(lambda mob: mob.become(self.get_inner_angle(small_radius,p1,p2,p3,circle)))
theta_1.add_updater(
lambda mob: mob.move_to(
p3.get_center()+Line(p3.get_center(),out_arc.point_from_proportion(0.5)).get_vector()*1.7)
)
theta_2.add_updater(
lambda mob: mob.move_to(
circle.get_center()+Line(circle.get_center(),in_arc.point_from_proportion(0.5)).get_vector()*1.7)
)
theta_1_val.add_updater(lambda mob: mob.set_value(self.get_inner_angle(1,p1,p2,p3,circle,False)*180/PI))
theta_2_val.add_updater(lambda mob: mob.set_value(self.get_arc_between_lines(1,p1,p2,p3,False)*180/PI))
rectangle.max_width = rectangle.get_width()
def rect_up(mob):
line = Line(theta_eq_temp.get_left()+LEFT*0.2,theta_eq_temp.get_right()+RIGHT*0.2)
if line.get_width() > mob.max_width:
mob.max_width = line.get_width()
mob.set_width(mob.max_width)
# mob.move_to(line)
mob.align_to(theta_1_val,LEFT)
mob.shift(LEFT*0.1)
rectangle.add_updater(rect_up)
# ------------- Groups
dots = VGroup(p1,p2,p3)
vts = Group(vt_1,vt_2,vt_3)
self.vts = vts
self.add(
circle,dots,
in_lines,out_lines,
in_arc,out_arc,
theta_1,theta_2,
theta_eq,
)
def get_arc_between_lines(self, radius, d1, d2, center,mob=True):
line1 = Line(center.get_center(),d1.get_center())
line2 = Line(center.get_center(),d2.get_center())
h = Line(center.get_center(),center.get_center()+RIGHT)
angle = angle_between_vectors(line1.get_unit_vector(),line2.get_unit_vector())
h1 = angle_between_vectors(h.get_unit_vector(),line1.get_unit_vector())
h2 = angle_between_vectors(h.get_unit_vector(),line2.get_unit_vector())
if line1.get_angle() <= line2.get_angle():
start_angle = h1
else:
start_angle = h2
arc = Arc(start_angle, angle,radius=radius,arc_center=center.get_center(),**self.outer_arc_config)
if mob:
return arc
else:
return angle
def get_inner_angle(self, radius,d1,d2,out_center,in_center,mob=True):
line1 = Line(out_center.get_center(),d1.get_center())
line2 = Line(out_center.get_center(),d2.get_center())
h = Line(out_center.get_center(),out_center.get_center()+RIGHT)
angle = angle_between_vectors(line1.get_unit_vector(),line2.get_unit_vector())
v1 = Line(in_center.get_center(),d1.get_center())
start_angle = angle_between_vectors(h.get_unit_vector(),v1.get_unit_vector())
arc = Arc(start_angle, angle*2,radius=radius,arc_center=in_center.get_center(),**self.inner_arc_config)
if mob:
return arc
else:
return angle*2
class InscribedAngle(MovingCameraScene):
def construct(self):
circle_grp = CircleWithAngles()
v1, v2, v3 = circle_grp.vts
eq = circle_grp[-1]
circle_grp.to_edge(LEFT,buff=1)
eq.to_edge(RIGHT,buff=1)
for mob in circle_grp:
mob.suspend_updating()
mob.update()
self.play(Write(circle_grp))
for mob in circle_grp:
mob.resume_updating()
self.wait()
self.play(v1.set_value,-10,run_time=3,rate_func=linear)
self.wait()
self.play(v2.set_value,225,run_time=5,rate_func=there_and_back)
self.wait()
self.play(
v1.set_value,47,
v2.set_value,110,
v3.set_value,335,
run_time=3,
rate_func=there_and_back
)
self.wait()
circle_grp.remove(eq)
self.play(
FadeOut(eq),
circle_grp[0].scale,0.64,
circle_grp[0].move_to,ORIGIN,
circle_grp[0].to_edge,DOWN,{"buff":0.2}
)
self.wait()
# ---------------------- Transform 2theta by varphi
theta_2 = circle_grp[-1]
varphi = TexMobject("\\varphi")
varphi.match_color(theta_2)
varphi.move_to(theta_2)
varphi.match_updaters(theta_2)
self.play(Transform(theta_2,varphi))
self.wait()
# ---------------------- Cases
titles = VGroup(*[
TextMobject(f) for f in ["Case 1", "Case 2", "Case 3"]
])
titles.arrange(RIGHT,buff=3).to_edge(UP)
# ---------------------- Case 1
self.play(Write(titles[0]))
self.wait()
self.play(
v1.set_value,40,
v2.set_value,290-180,
v3.set_value,290,
run_time=3,
)
case_1 = circle_grp.deepcopy()
case_1.clear_updaters()
self.play(
case_1.set_width,2,
case_1.next_to,titles[0],DOWN,buff=0.2
)
self.wait()
self.bring_to_front(case_1[1])
# ---------------------- Case 2
self.play(Write(titles[1]))
self.wait()
self.play(
v1.set_value,30,
v2.set_value,140,
v3.set_value,260,
run_time=3,
)
self.wait()
case_2 = circle_grp.deepcopy()
case_2.clear_updaters()
self.play(
case_2.set_width,2,
case_2.next_to,titles[1],DOWN,buff=0.2
)
self.wait()
self.bring_to_front(case_2[1])
# ---------------------- Case 3
self.play(Write(titles[2]))
self.wait()
self.play(
v1.set_value,30,
v2.set_value,90,
v3.set_value,325,
run_time=3,
)
case_3 = circle_grp.deepcopy()
case_3.clear_updaters()
self.bring_to_front(case_3[1])
self.wait()
self.play(
case_3.set_width,2,
case_3.next_to,titles[2],DOWN,buff=0.2
)
# ---------------------- Remove updaters
circle_grp.clear_updaters()
self.play(Write(circle_grp,rate_func=lambda t: smooth(1-t),run_time=2.5))
self.wait()
# ------------ Case by case
cases = VGroup(case_1,case_2,case_3)
SCREEN = Rectangle(width=FRAME_WIDTH,height=FRAME_HEIGHT)
grps = VGroup(*[VGroup(t,c) for t,c in zip(titles,cases)])
grps.generate_target()
gt = grps.target[1:]
gp = grps.target[0]
gt.align_to(SCREEN,UP)
gt.shift(UP*grps.get_height())
gp[1].set_height(6)
gp[1].move_to(ORIGIN)
gp[1].to_edge(DOWN)
gp[1].to_edge(LEFT,buff=2)
gp[0].set_x(0)
gt[-1].shift(UP*0.2)
self.play(
MoveToTarget(grps)
)
self.wait()
self.cases_group_1 = VGroup(case_1,titles[0])
self.proof_1(case_1)
# next case
def next_proof(height=6, buff_down=1, buff_left=0.5):
def func(vgr):
tit, gr = vgr
tit.move_to(ORIGIN)
tit.to_edge(UP)
gr.set_height(height)
gr.move_to(ORIGIN)
gr.to_edge(DOWN,buff=buff_down)
gr.to_edge(LEFT,buff=buff_left)
return vgr
return func
frame_1 = self.get_screen_rect()
self.cases_group_1.add(frame_1)
self.play(FadeIn(frame_1))
self.play(
self.cases_group_1.set_height,1,
self.cases_group_1.to_corner,UL,{"buff":0.1},
run_time=2
)
self.play(ApplyFunction(next_proof(), grps[1]))
self.wait()
# case 2
self.cases_group_2 = VGroup(titles[1],case_2)
self.proof_2(case_2)
frame_2 = self.get_screen_rect()
self.cases_group_2.add(frame_2)
self.play(FadeIn(frame_2))
self.play(
self.cases_group_2.set_height,1,
self.cases_group_2.next_to,self.cases_group_1,RIGHT,0,
run_time=2
)
self.play(ApplyFunction(next_proof(6,0.2), grps[2]))
# case 3
self.cases_group_3 = VGroup(titles[2],case_3)
self.proof_3(case_3)
frame_3 = self.get_screen_rect()
self.cases_group_3.add(frame_3)
self.play(FadeIn(frame_3))
all_cases = VGroup(self.cases_group_1,self.cases_group_2,self.cases_group_3)
self.play(
self.camera_frame.set_width,VGroup(frame_1,frame_2).get_width()*1,
self.camera_frame.move_to,VGroup(frame_1,frame_2).get_center(),
self.camera_frame.shift,DOWN*VGroup(frame_1,frame_2).get_height()/2,
self.cases_group_3.set_height,1,
self.cases_group_3.next_to,VGroup(frame_1,frame_2),DOWN,0,
run_time=2
)
# self.play(MoveToTarget(all_cases))
self.wait()
# self.play(v2.set_value,190,run_time=5,rate_func=linear)
def proof_1(self, case):
print("Proof 1")
dots = case[1]
d1, d2, d3 = dots
center = case[0]
theta = case[-2]
varphi = case[-1]
# Radius
r1 = Line(center.get_center(),d1.get_center(),color=RED_A,stroke_width=8)
r2 = Line(center.get_center(),d3.get_center(),color=RED_A,stroke_width=8)
r1_tex = TexMobject("r").add_background_rectangle()
r1_tex.move_to(r1)
r2_tex = r1_tex.deepcopy()
r2_tex.move_to(r2)
# self.add(r1,r2,r1_tex,r2_tex)
self.cases_group_1.add(case,r1,r2,r1_tex,r2_tex,)
self.play(
ShowCreation(r1),
ShowCreation(r2),
Write(r1_tex),
Write(r2_tex),
Animation(dots),
)
self.bring_to_front(dots)
self.wait()
# Arc and theta
arc_p1 = ArcBetweenVectors(0.6,center,d3,d1,True)
arc_p1.match_color(theta)
theta_copy = LabelFromArc(arc_p1, theta.get_height(), "\\theta", distance_proportion=1.5)
theta_copy.match_style(theta)
# psi
arc_psi = ArcBetweenVectors(0.4,d3,d1,center,True)
arc_psi.set_color(RED_A)
psi = LabelFromArc(arc_psi, theta.get_height(), "\\psi", distance_proportion=1.3)
psi.match_color(arc_psi)
# self.add(arc_p1,theta_copy,arc_psi,psi)
self.cases_group_1.add(arc_p1,theta_copy,arc_psi,psi)
self.play(
TransformFromCopy(theta,theta_copy),
ShowCreation(arc_p1),
run_time=2
)
self.wait(2)
self.play(
ShowCreation(arc_psi),
Write(psi),
run_time=2
)
self.wait(2)
# formulas develop
t1 = TexMobject("\\psi","+","2","\\theta","=","180^\\circ",
tex_to_color_map={
"\\psi": psi.get_color(), "\\theta": theta.get_color(),
},
)
t2 = TexMobject("\\psi","+","\\varphi","=","180^\\circ",
tex_to_color_map={
"\\psi": psi.get_color(), "\\varphi": varphi.get_color(),
},
)
t3 = TexMobject("\\psi","+","2","\\theta","=","\\psi","+","\\varphi",
tex_to_color_map={
"\\psi": psi.get_color(), "\\varphi": varphi.get_color(),
"\\theta": theta.get_color()
},
)
t4 = TexMobject("2","\\theta","=","\\varphi",
tex_to_color_map={
"\\psi": psi.get_color(), "\\varphi": varphi.get_color(),
"\\theta": theta.get_color()
},
)
tg = VGroup(t1,t2,t3,t4).arrange(DOWN,buff=0.6)
self.cases_group_1.add(t1,t2,t3,t4)
tg.scale(1.35)
self.align_formulas_with_equal(t2, t1, -2, -2)
self.align_formulas_with_equal(t3, t1, 4, -2)
self.align_formulas_with_equal(t4, t1, -2, -2)
tg.to_edge(RIGHT,buff=0.7)
# row 1
tc1 = theta.deepcopy()
tc2 = theta_copy.deepcopy()
self.play(
TransformFromCopy(psi, t1[0]),
ReplacementTransform(tc1.copy(), t1[3]),
ReplacementTransform(tc2.copy(), t1[3]),
# Transform(tc2, t1[3].copy()),
*[Write(t1[i]) for i in [1,2,-2,-1]],
run_time=3
)
self.cases_group_1.add(tc1,tc2)
self.wait()
self.play(
TransformFromCopy(t1[0],t2[0]),
TransformFromCopy(varphi,t2[2],path_arc=-PI/2),
*[Write(t2[i]) for i in [1,*range(3,len(t2))]],
run_time=3
)
self.wait()
self.play(
TransformFromCopy(t1[:4],t3[:4]),
TransformFromCopy(t2[:3],t3[-3:]),
Write(t3[4]),
run_time=3
)
self.wait()
self.play(
t3[0].fade,0.5,
t3[-3].fade,0.5,
)
self.wait()
self.play(
TransformFromCopy(t3[2:4],t4[:2]),
TransformFromCopy(t3[-1],t4[-1]),
Write(t4[2]),
run_time=3
)
self.wait()
self.play(
Succession(
FadeToColor(t4,YELLOW),
FadeToColor(t4,PURPLE_A),
),
AnimationGroup(
ShowCreationThenDestructionAround(t4.deepcopy()),
ShowCreationThenDestructionAround(t4.deepcopy()),
lag_ratio=1
)
)
self.wait()
# n = 0
# for mob in self.mobjects:
# try:
# t = Text(f"{n}").next_to(mob,UP,0)
# self.add(t)
# n += 1
# except:
# n += 1
# pass
def proof_2(self, case):
print("Proof 2")
dots = case[1]
d1, d2, d3 = dots
center = case[0]
theta = case[-2]
varphi = case[-1]
# Radius
r1 = Line(center.get_center(),d1.get_center(),color=RED_A,stroke_width=8)
r2 = Line(center.get_center(),d2.get_center(),color=RED_A,stroke_width=8)
r3 = Line(center.get_center(),d3.get_center(),color=RED_A,stroke_width=8)
r1_tex = TexMobject("r").add_background_rectangle()
r1_tex.move_to(r1)
r2_tex = r1_tex.deepcopy()
r2_tex.move_to(r2)
r3_tex = r1_tex.deepcopy()
r3_tex.move_to(r3)
arc_p3_2 = ArcBetweenVectors(0.8,center,d2,d3).set_color(TEAL)
arc_p3_1 = ArcBetweenVectors(1,d1,center,d3).set_color(TEAL)
# theta.shift(LEFT*0.2)
th_1 = LabelFromArc(arc_p3_1,theta.get_height()*0.8,"\\theta_1",color=theta.get_color(),distance_proportion=2)
th_2 = LabelFromArc(arc_p3_2,theta.get_height()*0.8,"\\theta_2",color=theta.get_color(),distance_proportion=2)
self.add_foreground_mobjects(dots,case[5])
self.cases_group_2.add(th_1,th_2)
self.play(theta.next_to,d3,DOWN,buff=0.2)
self.wait()
self.play(
ShowCreation(r1),
ShowCreation(r2),
ShowCreation(r3),
Write(r1_tex),
Write(r2_tex),
Write(r3_tex),
)
self.wait()
self.play(
ReplacementTransform(theta.copy()[0],th_1[0]),
ReplacementTransform(theta.copy()[0],th_2[0]),
ShowCreation(arc_p3_1),
ShowCreation(arc_p3_2),
run_time=3.5
)
self.wait()
# self.remove(theta)
self.cases_group_2.add(r1,r2,r3,r1_tex,r2_tex,r3_tex,arc_p3_1,arc_p3_2)
# ---------------- ARC PSI
arc_psi_1 = ArcBetweenVectors(0.4,d3,d1,center,True).set_color(RED_A)
arc_psi_2 = ArcBetweenVectors(0.4,d3,d2,center,True).set_color(RED_A)
arc_psi_2.rotate(-arc_psi_2.get_angle(),about_point=center.get_center())
psi_1 = LabelFromArc(arc_psi_1,theta.get_height()*0.8,"\\psi_1",color=RED_A,distance_proportion=1.6)
psi_2 = LabelFromArc(arc_psi_2,theta.get_height()*0.8,"\\psi_2",color=RED_A,distance_proportion=1.6)
self.play(
*list(map(Write,[arc_psi_1,arc_psi_2,psi_1,psi_2])),
run_time=2
)
self.wait()
self.cases_group_2.add(arc_psi_1,arc_psi_2,psi_1,psi_2)
# ---------------- FORMUAS transformn
tex_formulas_kwargs = {
"tex_to_color_map": {
"\\psi_1": psi_1.get_color(), "\\psi_2": psi_2.get_color(), "\\varphi": varphi.get_color(),
"\\theta_1": th_1.get_color(), "\\theta_2": th_1.get_color(),
}
}
# FORMULAS
f1 = TexMobject(
"\\psi_1","+","\\psi_2","+","\\varphi","=","360^\\circ",**tex_formulas_kwargs
)
f2 = TexMobject(
"(","180^\\circ","-","2","\\theta_1",")","+","(","180^\\circ","-","2","\\theta_2",")","+","\\varphi","=","360^\\circ",
**tex_formulas_kwargs
)
f2.add_background_rectangle()
f3 = TexMobject(
"-","2","\\theta_1","-","2","\\theta_2","+","\\varphi","=","0",**tex_formulas_kwargs
)
f4 = TexMobject(
"\\varphi","=","2","\\theta_1","+","2","\\theta_2",**tex_formulas_kwargs
)
f5 = TexMobject(
"\\varphi","=","2","(","\\theta_1","+","\\theta_2",")",**tex_formulas_kwargs
)
f6 = TexMobject(
"\\varphi","=","2","\\theta",**tex_formulas_kwargs
)
f6[-1].set_color(theta.get_color())
# f2[0].set_color(RED)
fg = VGroup(f1,f2,f3,f4,f5,f6).arrange(DOWN,buff=0.6)
fg.to_edge(RIGHT).to_edge(DOWN)
self.align_formulas_with_equal(f3,f1,-2,5)
self.align_formulas_with_equal(f4,f1,1,5)
self.align_formulas_with_equal(f5,f1,1,5)
self.align_formulas_with_equal(f6,f1,1,5)
# ---------------- FORMUAS transformn
by_case_1 = TextMobject("By Case 1").to_edge(RIGHT)
self.play(
LaggedStart(
TransformFromCopy(psi_1[0],f1[0],path_arc=-PI/2),
TransformFromCopy(psi_2[0],f1[2],path_arc=-PI/2),
TransformFromCopy(varphi,f1[4],path_arc=-PI/2),
lag_ratio=0.6
),
LaggedStart(*[Write(f1[i]) for i in [1,3,5,6]]),
run_time=6
)
self.wait()
self.play(Write(by_case_1))
self.wait()
self.play(
FadeIn(f2[0]),
*[
TransformFromCopy(f1[i],f2[j+1])
for i,j in zip(
[1,3,4,5,6],
[6,13,14,15,16]
)
],
TransformFromCopy(f1[0],f2[1:6+1]),
TransformFromCopy(f1[2],f2[7+1:13+1]),
# LaggedStart(*[Write(f2[i+1]) for i in [6,13]]),
run_time=4
)
self.wait()
self.play(Write(by_case_1,rate_func=lambda t: smooth(1-t)))
self.wait()
self.play(
*[
ApplyMethod(mob.fade,0.7)
for mob in [f2[i+1] for i in [1,8,16]]
]
)
self.wait(2)
self.play(
*[
TransformFromCopy(f2[i+1],f3[j])
for i,j in zip(
[2,3,4,9,10,11,13,14,15],
[*range(len(f3)-1)]
)
],
Write(f3[-1]),
# LaggedStart(*[Write(f2[i+1]) for i in [6,13]]),
run_time=4
)
self.wait()
self.play(
*[
TransformFromCopy(f3[i],f4[j])
for i,j in zip(
[1,2,4,5,7,8],
[2,3,5,6,0,1]
)
],
Write(f4[4]),
# LaggedStart(*[Write(f2[i+1]) for i in [6,13]]),
run_time=4
)
self.wait()
self.play(
*[
ReplacementTransform(f4[i].deepcopy(),f5[j])
for i,j in zip(
[0,1,2,3,4,5,6],
[0,1,2,4,5,2,6]
)
],
Write(f5[3]),
Write(f5[-1]),
# LaggedStart(*[Write(f2[i+1]) for i in [6,13]]),
run_time=4
)
self.wait()
self.play(
*[
ReplacementTransform(f5[i].deepcopy(),f6[j])
for i,j in zip(
[0,1,2],
[0,1,2]
)
],
TransformFromCopy(f5[-5:],f6[-1]),
run_time=4
)
self.foreground_mobjects = []
self.wait()
self.play(
Succession(
FadeToColor(f6,YELLOW),
FadeToColor(f6,PURPLE_A),
),
AnimationGroup(
ShowCreationThenDestructionAround(f6.deepcopy()),
ShowCreationThenDestructionAround(f6.deepcopy()),
lag_ratio=1
)
)
# self.play(
# *[
# TransformFromCopy()
# ],
# )
# self.add(fg)
# VGroup(case,*self.mobjects[start_index:]).set_color(TEAL)
self.cases_group_2.add(fg,by_case_1)
self.wait()
def proof_3(self, case):
print("Proof 3")
dots = case[1]
d1, d2, d3 = dots
center = case[0]
theta = case[-2]
varphi = case[-1]
self.add_foreground_mobject(dots)
def fade_mobs(fade=0.9):
def update(mob):
mob.fade(fade)
return mob
return update
# ---------------- FIGURES DEFINITION
diameter_vector = Line(d3.get_center(),center.get_center()).get_vector()
diameter = Line(d3.get_center(),d3.get_center()+diameter_vector*2,color=RED_A)
d4 = Dot(diameter.get_end())
arc_psi_1 = ArcBetweenVectors(0.6,d2,d4,d3,color=RED_A)
arc_psi_2 = ArcBetweenVectors(0.6,d2,d4,center,color=RED_A)
arc_alpha_1 = ArcBetweenVectors(0.7,d1,d4,d3,color=YELLOW_B,stroke_width=8)
arc_alpha_2 = ArcBetweenVectors(0.7,d1,d4,center,color=YELLOW_B,stroke_width=8)
psi_1 = LabelFromArc(arc_psi_1,theta.get_height()*0.8,"\\psi_1",color=RED_A,distance_proportion=2.1)
psi_2 = LabelFromArc(arc_psi_2,theta.get_height()*0.8,"\\psi_2",color=RED_A,distance_proportion=2.1)
alpha_1 = LabelFromArc(arc_alpha_1,theta.get_height()*0.8,"\\alpha_1",color=YELLOW_B,distance_proportion=2.5)
back_1 = BackgroundRectangle(alpha_1)
alpha_2 = LabelFromArc(arc_alpha_2,theta.get_height()*0.8,"\\alpha_2",color=YELLOW_B,distance_proportion=2.3)
back_2 = BackgroundRectangle(alpha_2)
line_1 = Line(center.get_center(),d1.get_center(),color=varphi.get_color())
line_2 = Line(d3.get_center(),d1.get_center(),color=varphi.get_color())
# ---------
psi_g = VGroup(arc_psi_1,arc_psi_2,psi_1,psi_2)
alpha_g = VGroup(arc_alpha_1,arc_alpha_2,alpha_1,alpha_2)
theta_g = VGroup(theta,varphi,case[-3],case[-4],case[2],case[3])
self.wait()
self.play(
GrowFromCenter(diameter)
)
self.wait()
self.play(
LaggedStart(*[
Write(arc)
for arc in psi_g
]),
)
self.wait(2)
self.play(
*list(map(FadeIn,[back_1,back_2])),
LaggedStart(*[
Write(arc)
for arc in alpha_g
]),
)
self.wait(2)
self.add_foreground_mobjects(back_1,back_2,alpha_g)
self.cases_group_3.add(
arc_psi_1,arc_psi_2,arc_alpha_1,arc_alpha_2,diameter,
psi_1,psi_2,alpha_1,alpha_2,
)
self.add(line_1,line_2)
for i in [psi_g,theta_g]:
for j in i:
j.save_state()
self.play(
*[ApplyFunction(fade_mobs(),i) for i in psi_g],
*[ApplyFunction(fade_mobs(),i) for i in theta_g],
)
self.wait()
# self.play(
# Restore(psi_g),
# Restore(theta_g),
# )
# self.wait()
# self.play(ApplyFunction(show_mobs(),psi_g))
# ---------------- FORMULAS DEFINITION
formulas = [
["\\alpha_1","=","\\psi_1","+","\\theta"],
["\\alpha_2","=","\\psi_2","+","\\varphi"],
["\\alpha_2","=","2","\\alpha_1"],
["\\psi_2","+","\\varphi","=","2","(","\\psi_1","+","\\theta",")"],
["\\psi_2","=","2","\\psi_1"],
["2","\\psi_1","+","\\varphi","=","2","\\psi_1","+","2","\\theta"],
["\\varphi","=","2","\\theta"],
]
tex_formulas_kwargs = {
"tex_to_color_map": {
"\\psi_1": psi_1.get_color(), "\\psi_2": psi_2.get_color(), "\\varphi": varphi.get_color(),
"\\theta": theta.get_color(), "\\alpha_1": alpha_1.get_color(), "\\alpha_2": alpha_2.get_color()
}
}
f = VGroup(*[
TexMobject(*formula, **tex_formulas_kwargs)
for formula in formulas
])
f.arrange(DOWN)
f.scale(1.3)
for fi,i in zip(f[1:],[1,1,3,1,4,1]):
self.align_formulas_with_equal(fi,f[0],i,1)
f.to_edge(RIGHT,buff=1.8)
# --------------------------------------
by_case_1 = TextMobject("By case 1")
by_case_1.next_to(f[2],RIGHT)
by_case_2 = by_case_1.copy()
by_case_2.next_to(f[4],RIGHT)
# ----------- FORMULAS ANIMATIONS
self.play(
FadeOut(back_1),
Restore(theta),
Restore(psi_1),
ReplacementTransform(alpha_1[0],f[0][0]),
run_time=2,
)
self.play(
TransformFromCopy(psi_1[0],f[0][2]),
TransformFromCopy(theta[0],f[0][-1]),
*[Write(f[0][i]) for i in [1,3]],
run_time=3,
)
self.wait()
self.play(
FadeOut(back_2),
Restore(varphi),
Restore(psi_2),
ReplacementTransform(alpha_2[0],f[1][0]),
run_time=2,
)
self.play(
TransformFromCopy(psi_2[0],f[1][2]),
TransformFromCopy(varphi[0],f[1][-1]),
*[Write(f[1][i]) for i in [1,3]],
run_time=3,
)
self.wait()
# By case 1 - 1
self.play(
Write(by_case_1)
)
self.wait()
self.play(
Write(f[2])
)
self.wait()
# -----------------
self.play(
TransformFromCopy(f[0][-3:],f[3][6:9]),
TransformFromCopy(f[1][-3:],f[3][:3]),
*[
TransformFromCopy(f[2][i],f[3][j])
for i,j in zip(
[1,2],
[3,4]
)
],
*[Write(f[3][i]) for i in [5,9]],
run_time=3
)
self.wait()
# ---------------------------
self.wait()
line_3 = Line(d3.get_center(),d2.get_center(),color=TEAL_A)
line_4 = Line(center.get_center(),d2.get_center(),color=PURPLE_A)
save_grp = VGroup(arc_alpha_1,arc_alpha_2,varphi,theta)
for i in save_grp:
try:
i.save_state()
except:
pass
self.play(
FadeOut(line_1),
FadeOut(line_2),
# line_1.fade,1,
# line_2.fade,1,
FadeIn(line_3),
FadeIn(line_4),
*[ApplyMethod(i.fade,0.92) for i in save_grp],
*[Restore(i) for i in [arc_psi_1,arc_psi_2]]
)
self.wait(3)
# by case 2
self.play(
Write(by_case_2)
)
self.wait()
self.play(
Write(f[4])
)
self.wait(3)
self.play(
*[Restore(i) for i in [*save_grp,*case[2:6]]]
)
self.wait()
# ---------------------------
self.play(
# TransformFromCopy(f[3][-3:],f[5][6:9]),
TransformFromCopy(f[3][0],f[5][:2]),
*[
TransformFromCopy(f[3][i],f[5][j])
for i,j in zip(
[1,2,3,4,6,7,8,4],
[2,3,4,5,6,7,9,8]
)
],
run_time=3
)
self.wait()
self.play(
*[ApplyMethod(f[5][i].fade,0.8) for i in [0,1,5,6]],
run_time=2
)
self.play(
*[
TransformFromCopy(f[5][i],f[6][j])
for i,j in zip(
[3,4,8,9],
[0,1,2,3]
)
],
run_time=3
)
# self.play(
# *{Restore(i) for i in [case[2],case[3]]}
# )
# self.add(f,by_case_1,by_case_2)
self.play(
Succession(
FadeToColor(f[6],YELLOW),
FadeToColor(f[6],PURPLE_A),
),
AnimationGroup(
ShowCreationThenDestructionAround(f[6].deepcopy()),
ShowCreationThenDestructionAround(f[6].deepcopy()),
lag_ratio=1
)
)
self.cases_group_3.add(line_1,line_2,line_3,line_4,by_case_1,by_case_2,f)
self.wait()
def align_formulas_with_equal(self, f1, f2, i1, i2):
c1 = f1[i1].get_center()
c2 = f2[i2].get_center()
distance = c2 - c1
f1.shift(RIGHT*distance[0])
def get_screen_rect(self):
return Rectangle(width=FRAME_WIDTH,height=FRAME_HEIGHT)
|
AnimationsWithManim_Elteoremadebeethoven/math_capsules/sine_cosine_laws.py | from manimlib.imports import *
class MeasureDistance(VGroup):
CONFIG = {
"color":RED_B,
"buff":0.3,
"lateral":0.3,
"invert":False,
"dashed_segment_length":0.09,
"dashed":True,
"ang_arrows":30*DEGREES,
"size_arrows":0.2,
"stroke":2.4,
}
def __init__(self,mob,**kwargs):
VGroup.__init__(self,**kwargs)
if self.dashed==True:
medicion=DashedLine(ORIGIN,mob.get_length()*RIGHT,dashed_segment_length=self.dashed_segment_length).set_color(self.color)
else:
medicion=Line(ORIGIN,mob.get_length()*RIGHT)
medicion.set_stroke(None,self.stroke)
pre_medicion=Line(ORIGIN,self.lateral*RIGHT).rotate(PI/2).set_stroke(None,self.stroke)
pos_medicion=pre_medicion.copy()
pre_medicion.move_to(medicion.get_start())
pos_medicion.move_to(medicion.get_end())
angulo=mob.get_angle()
matriz_rotacion=rotation_matrix(PI/2,OUT)
vector_unitario=mob.get_unit_vector()
direccion=np.matmul(matriz_rotacion,vector_unitario)
self.direccion=direccion
self.add(medicion,pre_medicion,pos_medicion)
self.rotate(angulo)
self.move_to(mob)
if self.invert==True:
self.shift(-direccion*self.buff)
else:
self.shift(direccion*self.buff)
self.set_color(self.color)
self.tip_point_index = -np.argmin(self.get_all_points()[-1, :])
def get_tex(self, tex,scale=1,buff=1,invert_dir=False,invert_texto=False,remove_rot=True,**moreargs):
linea_referencia=Line(self[0][0].get_start(),self[0][-1].get_end())
texto=TexMobject(tex,**moreargs)
ancho=texto.get_height()/2
if invert_texto:
inv=PI
else:
inv=0
if remove_rot:
texto.scale(scale).move_to(self)
else:
texto.rotate(linea_referencia.get_angle()).scale(scale).move_to(self)
texto.rotate(inv)
if invert_dir:
inv=-1
else:
inv=1
texto.shift(self.direccion*(buff+1)*ancho)
return texto
class ArcBetweenVectors(Arc):
def __init__(self, radius, d1, d2, center, invert_angle=False,**kwargs):
line1 = Line(center.get_center(),d1.get_center())
line2 = Line(center.get_center(),d2.get_center())
h = Line(center.get_center(),center.get_center()+RIGHT)
angle = angle_between_vectors(line1.get_unit_vector(),line2.get_unit_vector())
h1 = angle_between_vectors(h.get_unit_vector(),line1.get_unit_vector())
h2 = angle_between_vectors(h.get_unit_vector(),line2.get_unit_vector())
if line1.get_angle() <= line2.get_angle():
start_angle = h1
else:
start_angle = h2
if invert_angle:
start_angle = -start_angle
super().__init__(start_angle, angle,radius=radius,arc_center=center.get_center(), **kwargs)
def get_angle(self):
return self.angle
class LabelFromArc(TexMobject):
CONFIG = {
"distance_proportion": 1.2
}
def __init__(self, arc, tex_height, *tex_strings, **kwargs):
super().__init__(*tex_strings, **kwargs)
self.set_height(tex_height)
center = arc.get_arc_center()
max_size = max(self.get_width(),self.get_height()) * self.distance_proportion/ 2
vector = Line(center,arc.point_from_proportion(0.5)).get_vector()
end_coord = center+vector + normalize(vector)*max_size
self.move_to(end_coord)
class Polygon(Polygon):
def get_center_of_edges(self,buff=SMALL_BUFF*3):
vertices = self.get_vertices()
coords_vertices = []
for i in range(len(vertices)):
if i < len(vertices)-1:
p1,p2 = [vertices[i],vertices[i+1]]
else:
p1,p2 = [vertices[-1],vertices[0]]
guide_line = Line(p1,p2)
side = guide_line.get_center()
normal_direction = guide_line.copy()
normal_direction.rotate(-PI/2)
vector_normal_direction = normal_direction.get_unit_vector()
direction = Dot(side).shift(vector_normal_direction*buff).get_center()
coords_vertices.append(direction)
return coords_vertices
class SineCosineLaws(Scene):
CONFIG = {
"triangle_config": {
"color": RED,
"stroke_width": 8,
},
"tex_map": {
"tex_to_color_map": {
"\\alpha": RED_A,
"\\beta": TEAL_A,
"\\gamma": PURPLE_A,
"A": RED_A,
"B": TEAL_A,
"C": PURPLE_A,
"x": GREEN_A,
"y": GOLD_B,
"h_1": YELLOW_B,
"h_2": BLUE_B,
}
}
}
def construct(self):
self.wait(0.5)
du = UP*1.5
d1 = Dot(LEFT*4+du)
d2 = Dot(RIGHT*2+du)
d3 = Dot(RIGHT*4+UP*2+du)
triangle = Polygon(
d1.get_center(),d2.get_center(),d3.get_center(),**self.triangle_config
)
def frac_string(n,d):
return ["{",n,"\\over",d,"}"]
def frac_strings(n,d):
return ["{",*n,"\\over",*d,"}"]
sina_t = ["{\\rm sin}","\\alpha"]
sinb_t = ["{\\rm sin}","\\beta"]
sinc_t = ["{\\rm sin}","\\gamma"]
cosa_t = ["\\,{\\rm cos}","\\alpha"]
cosb_t = ["\\,{\\rm cos}","\\beta"]
cosc_t = ["\\,{\\rm cos}","\\gamma"]
formulas_sine_string_1 = [
[*sinb_t,"=",*frac_string("h_1","C")],
[*sinc_t,"=",*frac_string("h_1","B")],
["C","\\,",*sinb_t,"=","h_1"],
["B","\\,",*sinc_t,"=","h_1"],
["C","\\,",*sinb_t,"=","B","\\,",*sinc_t],
[*frac_strings(["C"],sinc_t),"=",*frac_strings(["B"],sinb_t)]
]
formulas_sine_string_2 = [
[*sina_t,"=",*frac_string("h_2","B")],
[*sinb_t,"=",*frac_string("h_2","A")],
["B","\\,",*sina_t,"=","h_2"],
["A","\\,",*sinb_t,"=","h_2"],
["B","\\,",*sina_t,"=","A","\\,",*sinb_t],
[*frac_strings(["B"],sinb_t),"=",*frac_strings(["A"],sina_t)]
]
sine_law = TexMobject(*[
*frac_strings(["C"],sinc_t),"=",*frac_strings(["B"],sinb_t),"=",*frac_strings(["A"],sina_t),
],**self.tex_map).scale(0.9)
formulas_sine_1 = VGroup(*[
TexMobject(*f,**self.tex_map) for f in formulas_sine_string_1
])
# formulas_sine.arrange_in_grid(None,2)
formulas_sine_arrange_1 = VGroup(
formulas_sine_1[:2].arrange(RIGHT,buff=1),
formulas_sine_1[2:4].arrange(RIGHT,buff=1),
formulas_sine_1[4:].arrange(DOWN),
).arrange(DOWN,buff=0.7).scale(0.9)
formulas_sine_2 = VGroup(*[
TexMobject(*f,**self.tex_map) for f in formulas_sine_string_2
])
# formulas_sine.arrange_in_grid(None,2)
formulas_sine_arrange_2 = VGroup(
formulas_sine_2[:2].arrange(RIGHT,buff=1),
formulas_sine_2[2:4].arrange(RIGHT,buff=1),
formulas_sine_2[4:].arrange(DOWN),
).arrange(DOWN,buff=0.7).scale(0.9)
formulas_sine_arrange_1.to_edge(DOWN,buff=0.3)
formulas_sine_arrange_1.to_edge(LEFT,buff=1)
formulas_sine_arrange_2.to_edge(DOWN,buff=0.3)
formulas_sine_arrange_2.to_edge(RIGHT,buff=1)
sine_law.align_to(formulas_sine_arrange_1,DOWN)
triangle.set_x(0)
center_vertices = triangle.get_center_of_edges()
labels = VGroup(*[
TexMobject(label,**self.tex_map).move_to(point) for label,point in zip(["C","B","A"],center_vertices)
])
fs1 = formulas_sine_1
fs2 = formulas_sine_2
# ------------------------------
h1 = TexMobject("h_1",**self.tex_map)
h2 = TexMobject("h_2",**self.tex_map)
x = TexMobject("x",**self.tex_map)
h1_line = self.get_h(d2,d1,d3)
h2_line = DashedLine(d3.get_center()+RIGHT*0.09,[d3.get_x()+0.09,d2.get_y()-0.09,0])
h3_line = DashedLine(d2.get_center()+RIGHT*0.09,h2_line.get_end())
rec_1 = Square().set_width(0.25)
rec_1 = VMobject().set_points_as_corners([rec_1.get_corner(v) for v in [UR,UL,DL]])
rec_2 = rec_1.deepcopy()
rec_1.next_to(h2_line.get_end(),UL,buff=0)
rec_2.rotate(h1_line.get_angle())
rec_2.next_to(h1_line.get_end(),DL,buff=0)
rec_2.shift(DOWN*0.1+RIGHT*0.05)
x.next_to(h3_line,DOWN,0.1)
h1.next_to(h1_line,RIGHT,0.1)
h1.shift(LEFT*0.15)
h2.next_to(h2_line,RIGHT,0.1)
# h2_line.rotate(PI,about_point=h2_line.get_start())
# ------------------------------
alpha_arc = ArcBetweenVectors(0.3,d1,d3,d2)
beta_arc = ArcBetweenVectors(1.7,d2,d3,d1)
gamma_arc = ArcBetweenVectors(1,d1,d2,d3)
alpha_p_arc = ArcBetweenVectors(0.4,Dot(h2_line.get_end()),d3,d2)
gamma_arc.rotate(gamma_arc.get_angle()*0.9,about_point=gamma_arc.get_arc_center())
alpha = LabelFromArc(alpha_arc,labels[0].get_width()*0.7,"\\alpha",distance_proportion=1.9,**self.tex_map)
beta = LabelFromArc(beta_arc,labels[0].get_width()*1.1,"\\beta",distance_proportion=1.9,**self.tex_map)
gamma = LabelFromArc(gamma_arc,labels[0].get_width()*1.1,"\\gamma",distance_proportion=1.9,**self.tex_map)
alpha_p = LabelFromArc(alpha_p_arc,labels[0].get_width()*1.1,"\\alpha'",distance_proportion=1.9,**self.tex_map)
alpha.shift(LEFT*0.25+DOWN*0.1)
but = TexMobject("{\\rm sin}(\\pi-\\alpha)={\\rm sin}(\\alpha)",**self.tex_map)
but.to_corner(UL)
t1 = Polygon(
d1.get_center(),d2.get_center(),h1_line.get_end(),
color=ORANGE,stroke_width=0,fill_opacity=0
)
t2 = Polygon(
d2.get_center(),d3.get_center(),h1_line.get_end(),
color=ORANGE,stroke_width=0,fill_opacity=0
)
t3 = Polygon(
d2.get_center(),h3_line.get_end(),h2_line.get_start(),
color=ORANGE,stroke_width=0,fill_opacity=0
)
t4 = Polygon(
d1.get_center(),h3_line.get_end(),h2_line.get_start(),
color=ORANGE,stroke_width=0,fill_opacity=0
)
def show_triange(t):
t.set_fill(None,0.3)
return t
def hide_triange(t):
t.set_fill(None,0)
return t
self.add(t1,t2,t3,t4)
# - SHOW CREATIONS
self.add_foreground_mobject(triangle)
self.play(
ShowCreation(triangle,rate_func=linear),
LaggedStart(*list(map(Write,labels)),lag_ratio=0.8),
run_time=2.5
)
self.wait()
self.play(
LaggedStart(*[
TransformFromCopy(m1,m2)
for m1,m2 in zip(labels[::-1],[alpha,beta,gamma])
],lag_ratio=0.7),
LaggedStart(*list(map(ShowCreation,[alpha_arc,beta_arc,gamma_arc])),lag_ratio=0.7),
run_time=3.5
)
self.wait()
self.play(LaggedStart(*list(map(Write,[h1_line,h1,rec_2])),lag_ratio=0.5))
self.all_mobs = VGroup(
fs1,fs2,labels,t1,t2,t3,t4,alpha,beta,gamma,alpha_arc,beta_arc,gamma_arc,
but,h1,h2,rec_1,rec_2,h1_line,h2_line,h3_line,x,sine_law,alpha_p,alpha_p_arc
)
self.funcs = [show_triange,hide_triange]
self.remove_foreground_mobject(triangle)
self.bring_to_front(triangle)
self.laws = VGroup()
self.sine_law()
self.add(h1,h2,x,alpha_p,alpha_p_arc,rec_1,rec_2,h1_line,h2_line,h3_line)
self.cosine_mobs = [labels,t1,t2,t3,t4,alpha,beta,gamma,h1,h2,x,alpha_p,h2_line]
self.cosine_utils = [cosa_t,cosb_t,cosc_t,frac_string,frac_strings]
self.cosine_law_A()
self.cosine_law_B()
self.cosine_law_C()
self.laws.generate_target()
laws = self.laws.target
for i in laws[:-1]:
i.set_width(laws[-1].get_width())
laws.arrange(DOWN)
laws.set_fill(None,1)
laws.shift(DOWN*0.5)
self.play(MoveToTarget(self.laws))
self.wait()
sine_law.shift(UP*0.7)
self.play(*[Write(mob) for mob in sine_law if mob.get_width() > 0.01])
self.wait()
def sine_law(self):
fs1,fs2,labels,t1,t2,t3,t4,alpha,beta,gamma,alpha_arc,beta_arc,gamma_arc,but,h1,h2,rec_1,rec_2,h1_line,h2_line,h3_line,x,sine_law,alpha_p,alpha_p_arc = self.all_mobs
# - TRANSFORMATIONS
show_triange,hide_triange = self.funcs
C,B,A = labels
# ----------------- Sine la
self.play(ApplyFunction(show_triange,t1))
self.wait()
self.play(
LaggedStart(
TransformFromCopy(beta[0],fs1[0][1]),
TransformFromCopy(h1[0],fs1[0][-4]),
TransformFromCopy(C[0],fs1[0][-2]),
lag_ratio=0.7
),
LaggedStart(*[Write(fs1[0][i]) for i in [0,2,-3]]),
run_time=5
)
self.wait()
self.play(ApplyFunction(hide_triange,t1))
self.wait()
self.play(ApplyFunction(show_triange,t2))
self.wait()
self.play(
LaggedStart(
TransformFromCopy(gamma[0],fs1[1][1]),
TransformFromCopy(h1[0],fs1[1][-4]),
TransformFromCopy(B[0],fs1[1][-2]),
lag_ratio=0.7
),
LaggedStart(*[Write(fs1[1][i]) for i in [0,2,-3]]),
run_time=5
)
self.wait()
self.play(ApplyFunction(hide_triange,t2))
# - - - - - - - -
self.wait()
self.play(
LaggedStart(
TransformFromCopy(fs1[0][-2],fs1[2][0]),
AnimationGroup(
TransformFromCopy(fs1[0][0],fs1[2][2]),
TransformFromCopy(fs1[0][1],fs1[2][3]),
lag_ratio=0
),
TransformFromCopy(fs1[0][2],fs1[2][4]),
TransformFromCopy(fs1[0][-4],fs1[2][-1]),
lag_ratio=0.3
),
# LaggedStart(*[Write(fs1[1][i]) for i in [0,2,-3]]),
run_time=5
)
self.wait()
self.play(
LaggedStart(
TransformFromCopy(fs1[1][-2],fs1[3][0]),
AnimationGroup(
TransformFromCopy(fs1[1][0],fs1[3][2]),
TransformFromCopy(fs1[1][1],fs1[3][3]),
lag_ratio=0
),
TransformFromCopy(fs1[1][2],fs1[3][4]),
TransformFromCopy(fs1[1][-4],fs1[3][-1]),
lag_ratio=0.3
),
# LaggedStart(*[Write(fs1[1][i]) for i in [0,2,-3]]),
run_time=5
)
self.wait()
self.play(
TransformFromCopy(fs1[2][:4],fs1[4][:4]),
TransformFromCopy(fs1[3][:4],fs1[4][-4:]),
Write(fs1[4][4]),
run_time=5
)
self.wait()
self.play(
LaggedStart(
TransformFromCopy(fs1[4][0],fs1[5][1]),
TransformFromCopy(fs1[4][-2:],fs1[5][3:5]),
TransformFromCopy(fs1[4][-4],fs1[5][-5]),
TransformFromCopy(fs1[4][2:4],fs1[5][-3:-1]),
lag_ratio=0.5
),
# TransformFromCopy(fs1[4][-2:],fs1[5][3:5]),
# TransformFromCopy(fs1[3][:4],fs1[4][-4:]),
LaggedStart(
Write(fs1[5][2]),
Write(fs1[5][-4]),
Write(fs1[5][6]),
lag_ratio=0.5
),
run_time=5
)
self.wait()
# ------------------------------
self.play(LaggedStart(*list(map(Write,[h2_line,h2,h3_line,x,rec_1])),lag_ratio=0.5))
self.wait()
self.play(Write(alpha_p),Write(alpha_p_arc))
self.wait()
self.play(Write(but))
self.wait()
self.play(Indicate(but),Indicate(alpha_p),Indicate(alpha_p_arc),run_time=3)
self.wait()
self.play(ApplyFunction(show_triange,t3))
self.wait()
self.play(
LaggedStart(
TransformFromCopy(alpha_p[0],fs2[0][1]),
TransformFromCopy(h2[0],fs2[0][-4]),
TransformFromCopy(B[0],fs2[0][-2]),
lag_ratio=0.7
),
LaggedStart(*[Write(fs2[0][i]) for i in [0,2,-3]]),
run_time=5
)
self.wait()
self.play(ApplyFunction(hide_triange,t3))
self.wait()
self.play(ApplyFunction(show_triange,t4))
self.wait()
self.play(
LaggedStart(
TransformFromCopy(beta[0],fs2[1][1]),
TransformFromCopy(h2[0],fs2[1][-4]),
TransformFromCopy(A[0],fs2[1][-2]),
lag_ratio=0.7
),
LaggedStart(*[Write(fs2[1][i]) for i in [0,2,-3]]),
run_time=5
)
self.wait()
self.play(ApplyFunction(hide_triange,t4))
# ------------------------------
self.play(
LaggedStart(*[FadeIn(f) for f in fs2[2:]],lag_ratio=0.5),
run_time=8
)
self.wait()
# self.add(sine_law)
self.play(
ReplacementTransform(fs1[-1],sine_law[:len(fs1[-1])]),
ReplacementTransform(fs2[-1],sine_law[-len(fs2[-1]):]),
run_time=2.5
)
sine_law.save_state()
self.wait()
self.play(
Succession(
FadeToColor(sine_law,YELLOW),
Restore(sine_law)
),
AnimationGroup(
ShowCreationThenDestructionAround(sine_law.copy()),
ShowCreationThenDestructionAround(sine_law.copy()),
lag_ratio=1
)
)
self.wait()
self.remove(sine_law)
self.play(FadeOut(VGroup(fs1,fs2,but)))
self.wait()
def cosine_law_A(self):
labels,t1,t2,t3,t4,alpha,beta,gamma,h1,h2,x,alpha_p,h2_line = self.cosine_mobs
C,B,A = labels
cosa_t,cosb_t,cosc_t,frac_string,frac_strings = self.cosine_utils
show_triange,hide_triange = self.funcs
strings = [
["A","^2=","(","C","+","x",")","^2","+","{h_2}","^2"],
["A","^2=","C","^2","+","2","C","x","+","x^2","+","{h_2}","^2"],
["A","^2=","C","^2","+","2","C","x","+","B^2"],
["A","^2=","B","^2","+","C^2","+","2","C","x"],
["A","^2=","B","^2","+","C^2","+","2","C","B",*cosa_t],
["A","^2=","B","^2","+","C^2","-","2","B","C",*cosa_t],
]
f = VGroup(*[
TexMobject(*f,**self.tex_map)
for f in strings
])
for mob in f[:2]:
# mob[-1].set_color(self.tex_map["tex_to_color_map"]["h_2"])
mob[-1].align_to(mob[-3][-1],LEFT)
f.arrange(DOWN)
for mob in f[1:]:
mob.align_to(f[0],LEFT)
# mob.align_to(f[0],DOWN)
f.to_edge(DOWN,buff=1)
f.shift(LEFT)
f.shift(DOWN)
n = VGroup(*[self.get_label_numbers(fi) for fi in f])
# self.add(f,n)
# ---------------- Animations
self.play(ApplyFunction(show_triange,t4))
self.wait()
LAG = 0.4
h2_c = h2.copy()
self.play(
LaggedStart(
*[
TransformFromCopy(mob,f[0][i])
for mob,i in zip([A,C,x],[0,3,5])
],
ApplyMethod(h2_c.move_to,f[0][10]),
lag_ratio=LAG,
),
LaggedStart(
Animation(Mobject()),
Animation(Mobject()),
Animation(Mobject()),
Animation(Mobject()),
*[Write(f[0][i]) for i in [1,2,4,6,7,8,9,12]],
lag_ratio=LAG*2,
),
run_time=7
)
self.wait()
self.play(ApplyFunction(hide_triange,t4))
LAG = 0.4
self.play(
LaggedStart(
*[
ReplacementTransform(f[0][i].copy(),f[1][j])
for i,j in zip(
[0,1,3,3,4,4,5,5,7,7,7 ,8 ,10,12],
[0,1,2,6,4,8,7,9,3,5,10,11,13,15]
)
],
# ApplyMethod(h2.copy().move_to,f[0][10]),
lag_ratio=0,
),
run_time=7
)
brace = Brace(f[1][9:-2],DOWN)
self.play(GrowFromCenter(brace))
# self.play(LaggedStart(FocusOn(t3),FocusOn(t3),lag_ratio=0.4))
self.play(ApplyFunction(show_triange,t3))
self.play(*[Indicate(mob,run_time=2) for mob in [x,B,h2]])
B2 = brace.get_tex("B^2")[0]
B2[0].set_color(self.tex_map["tex_to_color_map"]["B"])
self.play(Write(B2))
self.play(
LaggedStart(
*[
ReplacementTransform(f[1][i].copy(),f[2][j])
for i,j in zip(
[*range(9)],
[*range(9)],
)
],
lag_ratio=0,
),
run_time=2
)
self.play(ReplacementTransform(B2,f[2][9:]),FadeOut(brace))
# F 2 - 3
self.wait(0.5)
f[3].align_to(f[2],UP)
self.play(
*[
ReplacementTransform(f[2][i],f[3][j])
for i,j in zip([*range(len(f[2]))],[0,1,5,6,4,8,9,10,7,2,3])
],
run_time=2.5
)
but = TexMobject("{\\rm cos}(\\pi\\pm \\alpha)=-{\\rm cos}\\alpha",tex_to_color_map={"\\alpha":RED_A})
but.to_corner(UL)
c1 = TexMobject("-","{\\rm cos}","\\alpha","=","{","x","\\over","B","}",**self.tex_map)
c1[-1].set_color(ORANGE)
c1.to_edge(RIGHT)
c1.shift(DOWN)
c2 = TexMobject("-","B",*cosa_t,"=","x",**self.tex_map)
c2.move_to(c1).align_to(c1,LEFT).shift(LEFT*c1[0].get_width())
self.play(Write(but),run_time=2.5)
self.wait()
self.play(Write(VGroup(*[c for c in c1 if c.get_width() > 0.1])))
self.play(ApplyFunction(hide_triange,t3))
self.wait()
# self.add(c1,c2)
# print
self.play(
*[ReplacementTransform(c1[i],c2[j]) for i,j in zip(
[0,1,2,3,5,7],
[0,2,3,4,5,1]
)],
FadeOut(c1[6]),
run_time=2
)
f[4].next_to(f[3],DOWN,aligned_edge=LEFT)
self.wait()
self.play(
*[TransformFromCopy(f[3][i],f[4][j]) for i,j in zip(range(10),range(10))],
run_time=2
)
self.wait()
self.play(
*[
TransformFromCopy(c2[i],f[4][j])
for i,j in zip([1,2,3],[10,11,12]
)],
ApplyMethod(c2[0].move_to,f[4][7]),
FadeOut(f[4][7]),
run_time=2
)
f[4][7].become(c2[0])
self.wait()
f[5].align_to(f[4],UP)
self.play(*[
ReplacementTransform(f[4][i],f[5][j])
for i,j in zip([*range(len(f[4]))],[*range(9),10,9,11,12])
])
self.wait()
f4 = f[5].copy()
f4.fade(0.5)
self.play(Write(f4,stroke_width=6),FadeToColor(f[4],YELLOW,rate_func=there_and_back,run_time=2))
self.wait()
self.remove(f4,f[4])
self.remove(c2[0])
self.play(
f[5].scale,0.8,
f[5].to_corner,DR,{"buff":0.1},
)
self.play(
f[5].set_fill,None,0.5,
FadeOut(VGroup(*[f[i] for i in [0,1,3]])),
FadeOut(c2[1:]),FadeOut(h2_c),FadeOut(but)
)
self.remove(c2[0])
self.laws.add(f[5])
# ---------------------
# self.add(brace)
def cosine_law_C(self):
labels,t1,t2,t3,t4,alpha,beta,gamma,h1,h2,x,alpha_p,h2_line = self.cosine_mobs
C,B,A = labels
cosa_t,cosb_t,cosc_t,frac_string,frac_strings = self.cosine_utils
show_triange,hide_triange = self.funcs
strings = [
["C","^2=","(","A","-","y",")","^2","+","{h_1}","^2"],
["C","^2=","A","^2","-","2","A","y","+","y","^2","+","{h_1}","^2"],
["C","^2=","A","^2","-","2","A","y","+","B^2"],
["C","^2=","A","^2","+","B^2","-","2","A","y"],
["C","^2=","A","^2","+","B^2","-","2","A","B",*cosc_t],
]
p1,p2,p3 = t2.get_vertices()
y_masure = MeasureDistance(Line(p3,h2_line.get_start()),buff=0.2)
y = y_masure.get_tex("y",**self.tex_map)
# self.add(y_masure,y)
# self.add(*[Dot(p) for p in [p2,p3]])
f = VGroup(*[
TexMobject(*f,**self.tex_map)
for f in strings
])
for mob in f[:2]:
# mob[-1].set_color(self.tex_map["tex_to_color_map"]["h_2"])
mob[-1].align_to(mob[-3][-1],LEFT)
f.arrange(DOWN)
for mob in f[1:]:
mob.align_to(f[0],LEFT)
# mob.align_to(f[0],DOWN)
f.to_edge(DOWN,buff=1)
f.shift(LEFT)
# f.shift(DOWN)
n = VGroup(*[self.get_label_numbers(fi) for fi in f])
# self.add(f,n)
# ---------------- Animations
self.play(LaggedStartMap(FadeIn,y_masure),Write(y))
self.play(ApplyFunction(show_triange,t1))
self.wait()
LAG = 0.4
h2_c = h1.copy()
self.play(
LaggedStart(
*[
TransformFromCopy(mob,f[0][i])
for mob,i in zip([C,A,y],[0,3,5])
],
ApplyMethod(h2_c.move_to,f[0][10]),
lag_ratio=LAG,
),
LaggedStart(
Animation(Mobject()),
Animation(Mobject()),
Animation(Mobject()),
Animation(Mobject()),
*[Write(f[0][i]) for i in [1,2,4,6,7,8,9,12]],
lag_ratio=LAG*2,
),
run_time=7
)
self.wait()
# self.add(n,f)
self.play(ApplyFunction(hide_triange,t1))
LAG = 0.4
self.play(
LaggedStart(
*[
ReplacementTransform(f[0][i].copy(),f[1][j])
for i,j in zip(
[0,1,3,3,4,4,5,5,7,7,7 ,8 ,10,12],
[0,1,2,6,4,8,7,9,3,5,10,11,13,15]
)
],
# ApplyMethod(h2.copy().move_to,f[0][10]),
lag_ratio=0,
),
run_time=7
)
brace = Brace(f[1][9:-2],DOWN)
self.play(GrowFromCenter(brace))
# self.play(LaggedStart(FocusOn(t3),FocusOn(t3),lag_ratio=0.4))
self.play(ApplyFunction(show_triange,t2))
self.play(*[Indicate(mob,run_time=2) for mob in [y,B,h1]])
B2 = brace.get_tex("B^2")[0]
B2[0].set_color(self.tex_map["tex_to_color_map"]["B"])
self.play(Write(B2))
self.play(
LaggedStart(
*[
ReplacementTransform(f[1][i].copy(),f[2][j])
for i,j in zip(
[*range(9)],
[*range(9)],
)
],
lag_ratio=0,
),
run_time=2
)
self.play(ReplacementTransform(B2,f[2][9:]),FadeOut(brace))
# F 2 - 3
self.wait(0.5)
f[3].align_to(f[2],UP)
self.play(
*[
ReplacementTransform(f[2][i],f[3][j])
for i,j in zip([*range(len(f[2]))],[0,1,2,3,7,8,9,10,4,5,6])
],
run_time=2.5
)
c1 = TexMobject("{\\rm cos}","\\gamma","=","{","y","\\over","B","}",**self.tex_map)
c1[-1].set_color(ORANGE)
c1.to_edge(RIGHT)
c1.shift(DOWN)
c2 = TexMobject("B",*cosc_t,"=","y",**self.tex_map)
c2.move_to(c1).align_to(c1,LEFT).shift(LEFT*c1[0].get_width())
self.play(Write(VGroup(*[c for c in c1 if c.get_width() > 0.1])))
self.play(ApplyFunction(hide_triange,t2))
self.wait()
self.play(
*[ReplacementTransform(c1[i],c2[j]) for i,j in zip([0,1,2,4,6],[1,2,3,4,0])],
FadeOut(c1[5]),
run_time=2
)
f[4].next_to(f[3],DOWN,aligned_edge=LEFT)
self.wait()
self.play(
*[TransformFromCopy(f[3][i],f[4][j]) for i,j in zip(range(10),range(10))],
run_time=2
)
self.wait()
self.play(
*[TransformFromCopy(c2[i],f[4][j]) for i,j in zip([0,1,2],[10,11,12])],
run_time=2
)
self.wait()
self.play(FadeOut(c2))
self.wait()
f4 = f[4].copy()
f4.set_fill(None,0)
self.play(Write(f4,stroke_width=6),FadeToColor(f[4],YELLOW,rate_func=there_and_back,run_time=2))
self.wait()
self.laws.add(f[4])
self.remove(h2_c)
self.play(FadeOut(f[:4]))
# self.remove(f4,f[4])
# self.play(f[5].to_corner,DL)
# ---------------------
# self.add(brace)
def cosine_law_B(self):
labels,t1,t2,t3,t4,alpha,beta,gamma,h1,h2,x,alpha_p,h2_line = self.cosine_mobs
C,B,A = labels
cosa_t,cosb_t,cosc_t,frac_string,frac_strings = self.cosine_utils
show_triange,hide_triange = self.funcs
strings = [
["B","^2","=","x","^2","+","h_2","^2",],
["B","^2","=","x","^2","+","A","^2","-","(","C","+","x",")","^2"],
["B","^2","=","x","^2","+","A","^2","-","C","^2","-","2","C","x","-","x","^2"],
["B","^2","=","A","^2","-","C","^2","-","2","C","x"],
["B","^2","=","A","^2","-","C","^2","-","2","C","(","A",*cosb_t,"-","C",")"],
["B","^2","=","A","^2","-","C","^2","-","2","C","A",*cosb_t,"+","2","C","^2"],
["B","^2","=","A","^2","+","C","^2","-","2","A","C",*cosb_t],
]
c_string = [
["A","^2","=","h_2","^2","+","(C","+","x",")","^2"],
["A","^2","-","(C","+","x",")","^2","=","h_2","^2"],
[*cosb_t,"=",*frac_strings(["C","+","x"],["A"])],
["A",*cosb_t,"-","C","=","x"]
]
# self.add(y_masure,y)
# self.add(*[Dot(p) for p in [p2,p3]])
f = VGroup(*[
TexMobject(*i,**self.tex_map)
for i in strings
])
c = VGroup(*[
TexMobject(*i,**self.tex_map)
for i in c_string
])
# f[1].remove(f[1][-1])
for mob,i in zip([f[0],c[0],c[1]],[7,4,11]):
mob[i][0].set_color(BLUE_B)
ex = mob[i-1][-1]
ex.set_color(WHITE)
mob[i-1].remove(ex)
mob.add(ex)
f.arrange(DOWN)
for mob in f[1:]:
mob.align_to(f[0],LEFT)
# mob.align_to(f[0],DOWN)
f.to_edge(DOWN,buff=0.2)
f.to_edge(LEFT,buff=0.2)
c.arrange(DOWN)
c.to_edge(RIGHT,buff=0.1)
c.shift(DOWN*1.3)
c[0].shift(UP*0.3)
c[1].align_to(c[0][:5],RIGHT)
c[1].align_to(c[0],UP)
# f.shift(LEFT)
# f.shift(DOWN)
n = VGroup(*[self.get_label_numbers(fi) for fi in f])
n2 = VGroup(*[self.get_label_numbers(fi) for fi in c])
# self.add(f,c)
# -----------------------------------------------------
# -----------------------------------------------------
self.play(ApplyFunction(show_triange,t3))
self.wait()
LAG = 0.4
h2_c = h1.copy()
f.shift(DOWN*0.5+RIGHT*2)
self.play(
LaggedStart(
*[
TransformFromCopy(mob,f[0][i])
for mob,i in zip([B,x],[0,3])
],
AnimationGroup(
TransformFromCopy(h2[0][0],f[0][6]),
TransformFromCopy(h2[0][1],f[0][7]),
lag_ratio=0
),
lag_ratio=LAG,
),
LaggedStart(
Animation(Mobject()),
Animation(Mobject()),
Animation(Mobject()),
Animation(Mobject()),
*[Write(f[0][i]) for i in [1,2,4,5,8]],
lag_ratio=LAG*2,
),
run_time=7
)
self.wait()
# self.add(n,f)
self.play(ApplyFunction(hide_triange,t3))
self.wait()
self.play(ApplyFunction(show_triange,t4))
self.wait()
self.play(
LaggedStart(
*[
TransformFromCopy(mob,c[0][i])
for mob,i in zip([A],[0])
],
AnimationGroup(
TransformFromCopy(h2[0][0],c[0][3]),
TransformFromCopy(h2[0][1],c[0][4]),
lag_ratio=0
),
*[
TransformFromCopy(mob,c[0][i])
for mob,i in zip([C,x],[7,9])
],
lag_ratio=LAG,
),
LaggedStart(
Animation(Mobject()),
Animation(Mobject()),
Animation(Mobject()),
Animation(Mobject()),
*[Write(c[0][i]) for i in [1,2,12,5,6,8,10,11]],
lag_ratio=LAG*2,
),
run_time=7
)
self.wait()
self.play(*[
ReplacementTransform(c[0][i],c[1][j])
for i,j in zip(range(len(c[0])),[0,1,9,10,11,2,3,4,5,6,7,8,12])
],run_time=3)
self.wait()
self.play(*[TransformFromCopy(f[0][i],f[1][j])
for i,j in zip(range(6),range(6))
])
self.wait()
self.play(*[TransformFromCopy(c[1][i],f[1][j])
for i,j in zip(range(9),range(6,15))
],run_time=3.5)
self.wait()
self.play(ApplyFunction(hide_triange,t4))
self.wait()
self.play(c[1].to_edge,RIGHT,c[1].fade,1)
self.wait()
self.play(*[ReplacementTransform(f[1][i].copy(),f[2][j])
for i,j in zip([*range(9),10,10,11,11,12,12,14,14,14],
[*range(9),9, 13,11,15,14,16,10,12,17]
)
],run_time=3.5)
self.wait()
self.play(*[
ApplyMethod(f[2][i].fade,0.7)
for i in [3,4,15,16,17]
])
self.wait()
self.play(*[ReplacementTransform(f[2][i].copy(),f[3][j])
for i,j in zip([*range(3),*range(6,15)],
[*range(len(f[3]))]
)
],run_time=3.5)
self.wait()
# --------- Show cos beta = (c+x) / a
self.play(ApplyFunction(show_triange,t4))
self.wait()
self.play(
LaggedStart(
Write(c[2][0]),
TransformFromCopy(beta,c[2][1]),
Animation(Mobject()),
Write(c[2][2]),
TransformFromCopy(C,c[2][4]),
Animation(Mobject()),
Write(c[2][5]),
TransformFromCopy(x,c[2][6]),
Animation(Mobject()),
Write(c[2][7]),
TransformFromCopy(A,c[2][8]),
lag_ratio=0.4
),
run_time=10
)
self.wait()
c[3].shift(LEFT*abs(c[2][2].get_x()-c[3][5].get_x()))
c[3].align_to(c[2][1],UP)
self.play(
FadeOut(c[2][7]),
*[
ReplacementTransform(c[2][i],c[3][j])
for i,j in zip(
[0,1,2,4,5,6,8],
[1,2,5,4,3,6,0]
)
],run_time=4)
# ---------------- Trabsfirn 2Cx to 2C(Acos beta + C)
self.wait()
self.play(
*[TransformFromCopy(f[3][i],f[4][j]) for i,j in zip(range(11),range(11))],
*[Write(f[4][i]) for i in [11,17]],
*[TransformFromCopy(c[3][i],f[4][j]) for i,j in zip(range(5),range(12,17))],
run_time=4
)
self.wait()
self.play(ApplyFunction(hide_triange,t4))
self.play(c[3].to_edge,RIGHT,c[3].fade,1)
# ---------------- Expand 2C(Acos beta + C)
self.wait()
self.play(
*[ReplacementTransform(f[4][i].copy(),f[5][j]) for i,j in zip(range(9),range(9))],
*[ReplacementTransform(f[4][i].copy(),f[5][j]) for i,j in zip(
[9,9, 10,10,12,13,14,15,16],
[9,15,10,16,11,12,13,14,16])
],
AnimationGroup(
Animation(Mobject()),
Animation(Mobject()),
Write(f[5][-1]),
lag_ratio=1
),
run_time=4
)
# ------------------------------ LAST
f[6].align_to(f[5],UP)
self.wait()
self.play(*[ShowCreationThenDestructionAround(i,run_time=2.3) for i in [f[5][6:8],f[5][15:]]])
self.wait()
self.play(
*[
ReplacementTransform(f[5][i],f[6][j])
for i,j in zip(
[*range(10),10,11,12,13,14,16,17],
[*range(10),11,10,12,13, 5,6 ,7]
)
],
FadeOut(f[5][15]),
run_time=4
)
# ------ Show
f4 = f[6].copy()
f4.set_fill(None,0)
self.wait()
self.play(Write(f4,stroke_width=6),FadeToColor(f[6],YELLOW,rate_func=there_and_back,run_time=2))
self.wait()
self.play(
f[6].scale,0.8,
f[6].next_to,self.laws[-1],UP,0.2,
f[6].align_to,self.laws[-1],LEFT,
f[6].set_fill,None,0.5
)
self.laws.add(f[6])
self.play(FadeOut(f[:5]))
def get_label_numbers(self,formula,**tex_kwargs):
n = VGroup()
for i,e in enumerate(formula):
t = Text(f"{i}",font="DejaVu").set_height(0.2)
t.next_to(e,DOWN,0)
if e.get_width() > 0.01:
n.add(t)
# else:
# n.add(t)
return n
def get_h(self, dot, d1, d2,invert=True):
line = Line(d1.get_center(),d2.get_center())
vector = line.get_unit_vector()
sign = 1 if invert else -1
normal_vector = rotate_vector(vector,sign*PI/2)
def get_distance_point_line(line,dot):
x_0, y_0, z_0 = dot.get_center()
X_0 = line.point_from_proportion(0)
X_1 = line.point_from_proportion(1)
x_1, y_1, z_1 = X_0
x_2, y_2, z_2 = X_1
return abs((x_2-x_1)*(y_1-y_0)-(x_1-x_0)*(y_2-y_1)/get_norm(line.get_vector()))
distance = get_distance_point_line(line,dot)
return DashedLine(dot.get_center(),dot.get_center()+distance*normal_vector)
|
AnimationsWithManim_Elteoremadebeethoven/math_capsules/mnemonics_trig.py | from manimlib.imports import *
class Sqrt2(VGroup):
def __init__(self, n, **kwargs):
super().__init__(**kwargs)
body = TexMobject("\\frac{\\sqrt{%s}}{2}"%n)[0]
number = body[2]
self.top = body[:3]
body.remove(body[2])
self.add(body,number)
class Mnemonics(Scene):
def construct(self):
# MOBS DEFINITIONS ----------------------------------
l_buff = 1.2
left_labels = VGroup(*[
TextMobject(t) for t in ["Radians:","Degrees:","sin","cos","tan"]
])
left_labels.arrange(DOWN,buff=l_buff)
radians_grp = VGroup(*[
TexMobject(t) for t in ["0",*["\\frac{\\pi}{%s}"%n for n in [6,4,3,2]]]
])
radians_grp.arrange(RIGHT,buff=l_buff)
radians_grp.next_to(left_labels[0],RIGHT,buff=l_buff)
degrees_grp = VGroup(*[
TexMobject(f"{t}^\\circ") for t in [0,30,45,60,90]
])
# TRIG PRE
sin_vals = VGroup(*[
Sqrt2(n) for n in range(5)
])
cos_vals = sin_vals.deepcopy()
cos_vals = cos_vals[::-1]
tan_vals = VGroup(*[
TexMobject("\\frac{\\sqrt{%s}}{\\sqrt{%s}}"%(n,d))[0]
for n,d in zip(range(5),list(range(5))[::-1])
])
# TRIG POST
sin_vals_p = VGroup(*[
TexMobject(t)[0] for t in ["0","\\frac{1}{2}","\\frac{\\sqrt{2}}{2}","\\frac{\\sqrt{3}}{2}","1"]
])
cos_vals_p = VGroup(*[
TexMobject(t)[0] for t in ["0","\\frac{1}{2}","\\frac{\\sqrt{2}}{2}","\\frac{\\sqrt{3}}{2}","1"][::-1]
])
tan_vals_p = VGroup(*[
TexMobject(t)[0] for t in ["0","\\frac{\\sqrt{3}}{3}","1","\\sqrt{3}","\\infty"]
])
degrees_grp.next_to(left_labels[1],RIGHT,buff=1.2)
all_grp = VGroup(
left_labels,
radians_grp,
degrees_grp,
sin_vals,
cos_vals,
tan_vals,
sin_vals_p,
cos_vals_p,
tan_vals_p,
)
all_grp.move_to(ORIGIN)
# - Order the values
for i in range(len(degrees_grp)):
for j,mob in zip(range(1,5),[degrees_grp,sin_vals,cos_vals,tan_vals]):
mob[i].set_x(radians_grp[i].get_x())
mob[i].set_y(left_labels[j].get_y())
for i in range(len(degrees_grp)):
for j,mob in zip(range(2,5),[sin_vals_p,cos_vals_p,tan_vals_p]):
mob[i].set_x(radians_grp[i].get_x())
mob[i].set_y(left_labels[j].get_y())
v_l_buff = 0.5*UP
h_l_buff = 0.7*RIGHT
v_line = Line(left_labels.get_corner(UR)+v_l_buff*0.9,left_labels.get_corner(DR)-v_l_buff)
v_line.shift(RIGHT*0.6)
h_line = Line(all_grp.get_corner(UL)-h_l_buff,all_grp.get_corner(UR)+h_l_buff)
h_line.set_y(v_line.get_start()[1])
h_line_d = h_line.deepcopy().set_y(v_line.get_end()[1])
h_lines = VGroup(h_line,h_line_d)
for i in range(1,4):
line = h_line.copy()
line.set_y((left_labels[i].get_y()+left_labels[i+1].get_y())/2)
h_lines.add(line)
# self.add(*all_grp,v_line,h_lines)
# ----------------------------------------------
# ANIMATIONS -----------------------------------
# ----------------------------------------------
self.play(
LaggedStart(*list(map(GrowFromCenter,[v_line,*h_lines])),run_time=2.5,lag_ratio=0),
Write(left_labels,run_time=2.5),
Write(radians_grp,run_time=2.5),
Write(degrees_grp,run_time=2.5),
)
self.wait()
s_grp = VGroup(*[f[0] for f in sin_vals])
c_grp = VGroup(*[f[0] for f in cos_vals])
s_vals = VGroup(*[f[1] for f in sin_vals])
c_vals = VGroup(*[f[1] for f in cos_vals])[::-1]
self.play(
Write(s_grp),
Write(c_grp),
run_time=3.5
)
self.wait()
self.play(Write(s_vals),run_time=4)
self.play(Write(c_vals),run_time=4)
self.wait()
LAG_RATIO = 0.4
PATH_ARC = 120*DEGREES
self.play(
LaggedStart(*[
Write(tv[3])
for tv in tan_vals
],lag_ratio=LAG_RATIO*3.2),
LaggedStart(*[
TransformFromCopy(sn,tv[:3],path_arc=PATH_ARC,run_time=3)
for sn,tv in zip([t.top for t in sin_vals],tan_vals)
],lag_ratio=LAG_RATIO),
LaggedStart(*[
TransformFromCopy(cn,tv[4:],path_arc=PATH_ARC,run_time=3)
for cn,tv in zip([t.top for t in cos_vals],tan_vals)
],lag_ratio=LAG_RATIO),
)
self.wait()
LAG_RATIO = 0.4
self.play(
AnimationGroup(
LaggedStart(*[
ReplacementTransform(sv,svp)
for sv,svp in zip(sin_vals,sin_vals_p)
],lag_ratio=LAG_RATIO),
LaggedStart(*[
ReplacementTransform(sv,svp)
for sv,svp in zip(cos_vals,cos_vals_p)
],lag_ratio=LAG_RATIO),
LaggedStart(*[
ReplacementTransform(sv,svp)
for sv,svp in zip(tan_vals,tan_vals_p)
],lag_ratio=LAG_RATIO),
lag_ratio=0.8
)
)
self.wait(3)
self.play(*list(map(FadeOut,self.mobjects)))
self.wait() |
AnimationsWithManim_Elteoremadebeethoven/.github/ISSUE_TEMPLATE.md | # __**WARNING**__
**Before writing an issue, please check the following links if someone has already resolved your question. If you are asking things that have already been resolved I will have no choice but to close your issue.**
* [Manim issues](https://github.com/3b1b/manim/issues?q=is%3Aissue+is%3Aclosed)
* [Stackoverflow](https://stackoverflow.com/questions/tagged/manim)
* [Reddit](https://www.reddit.com/r/manim/)
* [Official documentation](https://www.eulertour.com/learn/manim/)
* [My documentation](https://elteoremadebeethoven.github.io/manim_3feb_docs.github.io/html/index.html)
* [Todd tutorial](https://talkingphysics.wordpress.com/2019/01/08/getting-started-animating-with-manim-and-python-3-7/)
* [Malhora tutorial](https://github.com/malhotra5/Manim-Tutorial)
* [My tutorials](https://www.youtube.com/watch?v=ENMyFGmq5OA&list=PL2B6OzTsMUrwo4hA3BBfS7ZR34K361Z8F)
**You can joined to the Discord community [here](https://discordapp.com/invite/mMRrZQW)**
# Points to consider before writing your issue
* This repository works with the Manim version of February 3, unless otherwise indicated. If your code does not work, check that you are using the correct version.
* At the moment Manim works with Python 3.7, not with 3.8. This is because several of the dependencies have not yet been updated.
* If the terminal throws an error, please write it completely with the markdown format.
* Be clear and specific with your problem, share the code (and files, if applicable) and the command you use when rendering the video.
# Fast markdown tutorial.
## Inline code:
**INPUT**
The code is \`TexMobject\` write \`TeX\`.
**OUTPUT**
The code is `TexMobject` write `TeX`.
## Multiline code
**INPUT**
My code is:
\`\`\`python
Here is
a multiline
code
\`\`\`
**OUTPUT**
My code is:
```python
Here is
a multiline
code
```
**[LEARN MORE HERE](https://guides.github.com/features/mastering-markdown/#what)**
|
AnimationsWithManim_Elteoremadebeethoven/English/4_transform/transform_issues.md | # Bad animation with Transform
```python3
class TransformIssues(Scene):
def construct(self):
# 0 1 2
text_1=TextMobject("A","B","C")
# 0
text_2=TextMobject("B")
text_2.next_to(text_1,UP,buff=1)
#Add the elements 0 and 2 of text_1 to screen and text_2
self.play(
*[
FadeIn(text_1[i])
for i in [0,2]
],
FadeIn(text_2)
)
self.wait()
self.play(
ReplacementTransform(text_2,text_1[1])
)
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/TransformIssues.gif" /></p>
```python3
class TransformIssuesSolution1(Scene):
def construct(self):
# 0 1 2
text_1=TextMobject("A","B","C")
# 0
text_2=TextMobject("B")
text_2.next_to(text_1,UP,buff=1)
#Add the elements 0 and 2 of text_1 to screen and text_2
self.play(
*[
FadeIn(text_1[i])
for i in [0,2]
],
FadeIn(text_2)
)
self.wait()
self.play(
# Add [:] to the firts or second parameter
ReplacementTransform(text_2[:],text_1[1])
)
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/TransformIssuesSolution1.gif" /></p>
```python3
class TransformIssuesSolutionInfallible(Scene):
def construct(self):
# 0 1 2
text_1=TextMobject("A","B","C")
# 0
text_2=TextMobject("B")
text_2.next_to(text_1,UP,buff=1)
#Create a copy of the objects
text_1_1_c=TextMobject("B")\
.match_style(text_1[1])\
.match_width(text_1[1])\
.move_to(text_1[1])
#Add the elements 0 and 2 of text_1 to screen and text_2
self.play(
*[
FadeIn(text_1[i])
for i in [0,2]
],
FadeIn(text_2)
)
self.wait()
self.play(
# Add [:] to the firts or second parameter
ReplacementTransform(text_2,text_1_1_c)
)
self.remove(text_1_1_c)
self.add(text_1[1])
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/TransformIssuesSolutionInfallible.gif" /></p>
# For more information see [this](https://github.com/3b1b/manim/issues/425).
|
AnimationsWithManim_Elteoremadebeethoven/English/4_transform/4_transform.py | from big_ol_pile_of_manim_imports import *
class TransformationText1V1(Scene):
def construct(self):
texto1 = TextMobject("First text")
texto2 = TextMobject("Second text")
self.play(Write(texto1))
self.wait()
self.play(Transform(texto1,texto2))
self.wait()
class TransformationText1V2(Scene):
def construct(self):
texto1 = TextMobject("First text")
texto1.to_edge(UP)
texto2 = TextMobject("Second text")
self.play(Write(texto1))
self.wait()
self.play(Transform(texto1,texto2))
self.wait()
class TransformationText2(Scene):
def construct(self):
text1 = TextMobject("Function")
text2 = TextMobject("Derivative")
text3 = TextMobject("Integral")
text4 = TextMobject("Transformation")
self.play(Write(text1))
self.wait()
#Trans text1 -> text2
self.play(ReplacementTransform(text1,text2))
self.wait()
#Trans text2 -> text3
self.play(ReplacementTransform(text2,text3))
self.wait()
#Trans text3 -> text4
self.play(ReplacementTransform(text3,text4))
self.wait()
class CopyTextV1(Scene):
def construct(self):
formula = TexMobject(
"\\frac{d}{dx}", #0
"(", #1
"u", #2
"+", #3
"v", #4
")", #5
"=", #6
"\\frac{d}{dx}", #7
"u", #8
"+", #9
"\\frac{d}{dx}", #10
"v" #11
)
formula.scale(2)
self.play(Write(formula[0:7]))
self.wait()
self.play(
ReplacementTransform(formula[2].copy(),formula[8]),
ReplacementTransform(formula[4].copy(),formula[11]),
ReplacementTransform(formula[3].copy(),formula[9])
)
self.wait()
self.play(
ReplacementTransform(formula[0].copy(),formula[7]),
ReplacementTransform(formula[0].copy(),formula[10])
)
self.wait()
class CopyTextV2(Scene):
def construct(self):
formula = TexMobject("\\frac{d}{dx}",
"(","u","+","v",")","=",
"\\frac{d}{dx}","u","+","\\frac{d}{dx}","v"
)
formula.scale(2)
self.play(Write(formula[0:7]))
self.wait()
self.play(
ReplacementTransform(formula[2].copy(),formula[8]),
ReplacementTransform(formula[4].copy(),formula[11]),
ReplacementTransform(formula[3].copy(),formula[9]),
run_time=3
)
self.wait()
self.play(
ReplacementTransform(formula[0].copy(),formula[7]),
ReplacementTransform(formula[0].copy(),formula[10]),
run_time=3
)
self.wait()
class CopyTextV3(Scene):
def construct(self):
formula = TexMobject("\\frac{d}{dx}",
"(","u","+","v",")","=",
"\\frac{d}{dx}","u","+","\\frac{d}{dx}","v"
)
formula.scale(2)
formula[8].set_color(RED)
formula[11].set_color(BLUE)
self.play(Write(formula[0:7]))
self.wait()
self.play(
ReplacementTransform(formula[2].copy(),formula[8]),
ReplacementTransform(formula[4].copy(),formula[11]),
ReplacementTransform(formula[3].copy(),formula[9]),
run_time=3
)
self.wait()
self.play(
ReplacementTransform(formula[0].copy(),formula[7]),
ReplacementTransform(formula[0].copy(),formula[10]),
run_time=3
)
self.wait()
class CopyTextV4(Scene):
def construct(self):
formula = TexMobject("\\frac{d}{dx}",
"(","u","+","v",")","=",
"\\frac{d}{dx}","u","+","\\frac{d}{dx}","v"
)
formula.scale(2)
for letter,color in [("u",RED),("v",BLUE)]:
formula.set_color_by_tex(letter,color)
self.play(Write(formula[0:7]))
self.wait()
self.play(
ReplacementTransform(formula[2].copy(),formula[8]),
ReplacementTransform(formula[4].copy(),formula[11]),
ReplacementTransform(formula[3].copy(),formula[9]),
run_time=3
)
self.wait()
self.play(
ReplacementTransform(formula[0].copy(),formula[7]),
ReplacementTransform(formula[0].copy(),formula[10]),
run_time=3
)
self.wait()
class CopyTwoFormulas1(Scene):
def construct(self):
formula1 = TexMobject(
"\\neg", #0
"\\forall", #1
"x", #2
":", #3
"P(x)" #4
)
formula2 = TexMobject(
"\\exists", #0
"x", #1
":", #2
"\\neg", #3
"P(x)" #4
)
for size,pos,formula in [(2,2*UP,formula1),(2,2*DOWN,formula2)]:
formula.scale(size)
formula.move_to(pos)
self.play(Write(formula1))
self.wait()
changes = [
[(0,1,2,3,4),
# | | | | |
# v v v v v
(3,0,1,2,4)],
]
for pre_ind,post_ind in changes:
self.play(*[
ReplacementTransform(
formula1[i].copy(),formula2[j]
)
for i,j in zip(pre_ind,post_ind)
],
run_time=2
)
self.wait()
class CopyTwoFormulas2(Scene):
def construct(self):
formula1 = TexMobject(
"\\neg","\\forall","x",":","P(x)"
)
formula2 = TexMobject(
"\\exists","x",":","\\neg","P(x)"
)
for tam,pos,formula in [(2,2*UP,formula1),(2,2*DOWN,formula2)]:
formula.scale(tam)
formula.move_to(pos)
self.play(Write(formula1))
self.wait()
changes = [
# First time
[(2,3,4),
# | | |
# v v v
(1,2,4)],
# Second time
[(0,),
# |
# v
(3,)],
# Third time
[(1,),
# |
# v
(0,)]
]
for pre_ind,post_ind in changes:
self.play(*[
ReplacementTransform(
formula1[i].copy(),formula2[j]
)
for i,j in zip(pre_ind,post_ind)
],
run_time=2
)
self.wait()
class CopyTwoFormulas2Color(Scene):
def construct(self):
formula1 = TexMobject(
"\\neg","\\forall","x",":","P(x)"
)
formula2 = TexMobject(
"\\exists","x",":","\\neg","P(x)"
)
parametters = [(2,2*UP,formula1,GREEN,"\\forall"),
(2,2*DOWN,formula2,ORANGE,"\\exists")]
for size,pos,formula,col,sim in parametters:
formula.scale(size)
formula.move_to(pos)
formula.set_color_by_tex(sim,col)
formula.set_color_by_tex("\\neg",PINK)
self.play(Write(formula1))
self.wait()
changes = [
[(2,3,4),(1,2,4)],
[(0,),(3,)],
[(1,),(0,)]
]
for pre_ind,post_ind in changes:
self.play(*[
ReplacementTransform(
formula1[i].copy(),formula2[j]
)
for i,j in zip(pre_ind,post_ind)
],
run_time=2
)
self.wait()
class CopyTwoFormulas3(Scene):
def construct(self):
formula1 = TexMobject(
"\\neg","\\forall","x",":","P(x)"
)
formula2 = TexMobject(
"\\exists","x",":","\\neg","P(x)"
)
parametters = [(2,2*UP,formula1,GREEN,"\\forall"),
(2,2*DOWN,formula2,ORANGE,"\\exists")]
for size,pos,formula,col,sim in parametters:
formula.scale(size)
formula.move_to(pos)
formula.set_color_by_tex(sim,col)
formula.set_color_by_tex("\\neg",PINK)
self.play(Write(formula1))
self.wait()
changes = [
[(2,3,4),(1,2,4)],
[(0,),(3,)],
[(1,),(0,)]
]
for pre_ind,post_ind in changes:
self.play(*[
ReplacementTransform(
formula1[i],formula2[j]
)
for i,j in zip(pre_ind,post_ind)
],
run_time=2
)
self.wait()
class ChangeTextColorAnimation(Scene):
def construct(self):
text = TextMobject("Text")
text.scale(3)
self.play(Write(text))
self.wait()
self.play(
text.set_color, YELLOW,
run_time=2
)
self.wait()
class ChangeSizeAnimation(Scene):
def construct(self):
text = TextMobject("Text")
text.scale(2)
self.play(Write(text))
self.wait()
self.play(
text.scale, 3,
run_time=2
)
self.wait()
class MoveText(Scene):
def construct(self):
text = TextMobject("Text")
text.scale(2)
text.shift(LEFT*2)
self.play(Write(text))
self.wait()
self.play(
text.shift, RIGHT*2,
run_time=2,
path_arc=0 #Change 0 by -np.pi
)
self.wait()
class ChangeColorAndSizeAnimation(Scene):
def construct(self):
text = TextMobject("Text")
text.scale(2)
text.shift(LEFT*2)
self.play(Write(text))
self.wait()
self.play(
text.shift, RIGHT*2,
text.scale, 2,
text.set_color, RED,
run_time=2,
)
self.wait() |
AnimationsWithManim_Elteoremadebeethoven/English/4_transform/transform_issues.py | from big_ol_pile_of_manim_imports import *
class TextLike1DArrays(Scene):
def construct(self):
text=TextMobject("Te","xt")
# text=TextMobject("Te","xt")[0] # <- Recent versions
for i in text:
self.play(FadeIn(i))
self.wait()
self.play(FadeOut(i))
self.wait()
class TextLike2DArraysV1(Scene):
def construct(self):
text=TextMobject("Te","xt")
# text=TextMobject("Te","xt")[0] # <- Recent versions
self.play(FadeIn(text[0][0]))
self.play(FadeIn(text[0][1]))
self.play(FadeIn(text[1][0]))
self.play(FadeIn(text[1][1]))
self.wait()
class TextLike2DArraysV2(Scene):
def construct(self):
text=TextMobject("Te","xt")
for i in text:
for j in i:
self.play(FadeIn(j))
self.wait()
class TextLike2DArraysV3(Scene):
def construct(self):
text=TextMobject("Te","xt")
# text=TextMobject("Te","xt")[0] # <- Recent versions
for i in range(len(text)):
for j in range(len(text[i])):
self.play(FadeIn(text[i][j]))
self.wait()
class TransformIssues(Scene):
def construct(self):
# 0 1 2
text_1=TextMobject("A","B","C")
# text_1=TextMobject("A","B","C")[0] # <- Recent versions
# 0
text_2=TextMobject("B")
# text_2=TextMobject("B")[0]
text_2.next_to(text_1,UP,buff=1)
#Add the elements 0 and 2 of text_1 to screen and text_2
self.play(
*[
FadeIn(text_1[i])
for i in [0,2]
],
FadeIn(text_2)
)
self.wait()
self.play(
ReplacementTransform(text_2,text_1[1])
)
self.wait()
class TransformVGroup(Scene):
def construct(self):
text_n=TextMobject("A")
text_v=VGroup(TextMobject("A")).next_to(text_n,DOWN)
self.play(Write(text_n))
self.play(ReplacementTransform(text_n,text_v))
#Solution
# ReplacementTransform(text_n,text_v[0])
self.wait()
class TransformIssuesSolution1(Scene):
def construct(self):
# 0 1 2
text_1=TextMobject("A","B","C")
# text_1=TextMobject("A","B","C")[0] # <- Recent versions
# 0
text_2=TextMobject("B")
# text_2=TextMobject("B")[0]
text_2.next_to(text_1,UP,buff=1)
#Add the elements 0 and 2 of text_1 to screen and text_2
self.play(
*[
FadeIn(text_1[i])
for i in [0,2]
],
FadeIn(text_2)
)
self.wait()
self.play(
# Add [:] to the firts or second parameter
ReplacementTransform(text_2[:],text_1[1])
)
self.wait()
class TransformIssuesSolutionInfallible(Scene):
def construct(self):
# 0 1 2
text_1=TextMobject("A","B","C")
# text_1=TextMobject("A","B","C")[0] # <- Recent versions
# 0
text_2=TextMobject("B")
# text_2=TextMobject("B")[0]
text_2.next_to(text_1,UP,buff=1)
#Create a copy of the objects
text_1_1_c=TextMobject("B")\
.match_style(text_1[1])\
.match_width(text_1[1])\
.move_to(text_1[1])
#Add the elements 0 and 2 of text_1 to screen and text_2
self.play(
*[
FadeIn(text_1[i])
for i in [0,2]
],
FadeIn(text_2)
)
self.wait()
self.play(
# Add [:] to the firts or second parameter
ReplacementTransform(text_2,text_1_1_c)
)
self.remove(text_1_1_c)
self.add(text_1[1])
self.wait()
|
AnimationsWithManim_Elteoremadebeethoven/English/4_transform/scenes.md | # Programs
```python3
class TransformationText1V1(Scene):
def construct(self):
texto1 = TextMobject("First text")
texto2 = TextMobject("Second text")
self.play(Write(texto1))
self.wait()
self.play(Transform(texto1,texto2))
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/TransformationText1V1.gif" /></p>
```python3
class TransformationText1V2(Scene):
def construct(self):
texto1 = TextMobject("First text")
texto1.to_edge(UP)
texto2 = TextMobject("Second text")
self.play(Write(texto1))
self.wait()
self.play(Transform(texto1,texto2))
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/TransformationText1V2.gif" /></p>
```python3
class TransformationText2(Scene):
def construct(self):
text1 = TextMobject("Function")
text2 = TextMobject("Derivative")
text3 = TextMobject("Integral")
text4 = TextMobject("Transformation")
self.play(Write(text1))
self.wait()
#Trans text1 -> text2
self.play(ReplacementTransform(text1,text2))
self.wait()
#Trans text2 -> text3
self.play(ReplacementTransform(text2,text3))
self.wait()
#Trans text3 -> text4
self.play(ReplacementTransform(text3,text4))
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/TransformationText2.gif" /></p>
```python3
class CopyTextV1(Scene):
def construct(self):
formula = TexMobject(
"\\frac{d}{dx}", #0
"(", #1
"u", #2
"+", #3
"v", #4
")", #5
"=", #6
"\\frac{d}{dx}", #7
"u", #8
"+", #9
"\\frac{d}{dx}", #10
"v" #11
)
formula.scale(2)
self.play(Write(formula[0:7]))
self.wait()
self.play(
ReplacementTransform(formula[2].copy(),formula[8]),
ReplacementTransform(formula[4].copy(),formula[11]),
ReplacementTransform(formula[3].copy(),formula[9])
)
self.wait()
self.play(
ReplacementTransform(formula[0].copy(),formula[7]),
ReplacementTransform(formula[0].copy(),formula[10])
)
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/CopyTextV1.gif" /></p>
```python3
class CopyTextV2(Scene):
def construct(self):
formula = TexMobject("\\frac{d}{dx}",
"(","u","+","v",")","=",
"\\frac{d}{dx}","u","+","\\frac{d}{dx}","v"
)
formula.scale(2)
self.play(Write(formula[0:7]))
self.wait()
self.play(
ReplacementTransform(formula[2].copy(),formula[8]),
ReplacementTransform(formula[4].copy(),formula[11]),
ReplacementTransform(formula[3].copy(),formula[9]),
run_time=3
)
self.wait()
self.play(
ReplacementTransform(formula[0].copy(),formula[7]),
ReplacementTransform(formula[0].copy(),formula[10]),
run_time=3
)
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/CopyTextV2.gif" /></p>
```python3
class CopyTextV3(Scene):
def construct(self):
formula = TexMobject("\\frac{d}{dx}",
"(","u","+","v",")","=",
"\\frac{d}{dx}","u","+","\\frac{d}{dx}","v"
)
formula.scale(2)
formula[8].set_color(RED)
formula[11].set_color(BLUE)
self.play(Write(formula[0:7]))
self.wait()
self.play(
ReplacementTransform(formula[2].copy(),formula[8]),
ReplacementTransform(formula[4].copy(),formula[11]),
ReplacementTransform(formula[3].copy(),formula[9]),
run_time=3
)
self.wait()
self.play(
ReplacementTransform(formula[0].copy(),formula[7]),
ReplacementTransform(formula[0].copy(),formula[10]),
run_time=3
)
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/CopyTextV3.gif" /></p>
```python3
class CopyTextV4(Scene):
def construct(self):
formula = TexMobject("\\frac{d}{dx}",
"(","u","+","v",")","=",
"\\frac{d}{dx}","u","+","\\frac{d}{dx}","v"
)
formula.scale(2)
for letter,color in [("u",RED),("v",BLUE)]:
formula.set_color_by_tex(letter,color)
self.play(Write(formula[0:7]))
self.wait()
self.play(
ReplacementTransform(formula[2].copy(),formula[8]),
ReplacementTransform(formula[4].copy(),formula[11]),
ReplacementTransform(formula[3].copy(),formula[9]),
run_time=3
)
self.wait()
self.play(
ReplacementTransform(formula[0].copy(),formula[7]),
ReplacementTransform(formula[0].copy(),formula[10]),
run_time=3
)
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/CopyTextV4.gif" /></p>
```python3
class CopyTwoFormulas1(Scene):
def construct(self):
formula1 = TexMobject(
"\\neg", #0
"\\forall", #1
"x", #2
":", #3
"P(x)" #4
)
formula2 = TexMobject(
"\\exists", #0
"x", #1
":", #2
"\\neg", #3
"P(x)" #4
)
for size,pos,formula in [(2,2*UP,formula1),(2,2*DOWN,formula2)]:
formula.scale(size)
formula.move_to(pos)
self.play(Write(formula1))
self.wait()
changes = [
[(0,1,2,3,4),
# | | | | |
# v v v v v
(3,0,1,2,4)],
]
for pre_ind,post_ind in changes:
self.play(*[
ReplacementTransform(
formula1[i].copy(),formula2[j]
)
for i,j in zip(pre_ind,post_ind)
],
run_time=2
)
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/CopyTwoFormulas1.gif" /></p>
```python3
class CopyTwoFormulas2(Scene):
def construct(self):
formula1 = TexMobject(
"\\neg","\\forall","x",":","P(x)"
)
formula2 = TexMobject(
"\\exists","x",":","\\neg","P(x)"
)
for tam,pos,formula in [(2,2*UP,formula1),(2,2*DOWN,formula2)]:
formula.scale(tam)
formula.move_to(pos)
self.play(Write(formula1))
self.wait()
changes = [
# First time
[(2,3,4),
# | | |
# v v v
(1,2,4)],
# Second time
[(0,),
# |
# v
(3,)],
# Third time
[(1,),
# |
# v
(0,)]
]
for pre_ind,post_ind in changes:
self.play(*[
ReplacementTransform(
formula1[i].copy(),formula2[j]
)
for i,j in zip(pre_ind,post_ind)
],
run_time=2
)
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/CopyTwoFormulas2.gif" /></p>
```python3
class CopyTwoFormulas2Color(Scene):
def construct(self):
formula1 = TexMobject(
"\\neg","\\forall","x",":","P(x)"
)
formula2 = TexMobject(
"\\exists","x",":","\\neg","P(x)"
)
parametters = [(2,2*UP,formula1,GREEN,"\\forall"),
(2,2*DOWN,formula2,ORANGE,"\\exists")]
for size,pos,formula,col,sim in parametters:
formula.scale(size)
formula.move_to(pos)
formula.set_color_by_tex(sim,col)
formula.set_color_by_tex("\\neg",PINK)
self.play(Write(formula1))
self.wait()
changes = [
[(2,3,4),(1,2,4)],
[(0,),(3,)],
[(1,),(0,)]
]
for pre_ind,post_ind in changes:
self.play(*[
ReplacementTransform(
formula1[i].copy(),formula2[j]
)
for i,j in zip(pre_ind,post_ind)
],
run_time=2
)
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/CopyTwoFormulas2Color.gif" /></p>
```python3
class CopyTwoFormulas3(Scene):
def construct(self):
formula1 = TexMobject(
"\\neg","\\forall","x",":","P(x)"
)
formula2 = TexMobject(
"\\exists","x",":","\\neg","P(x)"
)
parametters = [(2,2*UP,formula1,GREEN,"\\forall"),
(2,2*DOWN,formula2,ORANGE,"\\exists")]
for size,pos,formula,col,sim in parametters:
formula.scale(size)
formula.move_to(pos)
formula.set_color_by_tex(sim,col)
formula.set_color_by_tex("\\neg",PINK)
self.play(Write(formula1))
self.wait()
changes = [
[(2,3,4),(1,2,4)],
[(0,),(3,)],
[(1,),(0,)]
]
for pre_ind,post_ind in changes:
self.play(*[
ReplacementTransform(
formula1[i],formula2[j]
)
for i,j in zip(pre_ind,post_ind)
],
run_time=2
)
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/CopyTwoFormulas3.gif" /></p>
```python3
class ChangeTextColorAnimation(Scene):
def construct(self):
text = TextMobject("Text")
text.scale(3)
self.play(Write(text))
self.wait()
self.play(
text.set_color, YELLOW,
run_time=2
)
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/ChangeTextColorAnimation.gif" /></p>
```python3
class ChangeSizeAnimation(Scene):
def construct(self):
text = TextMobject("Text")
text.scale(2)
self.play(Write(text))
self.wait()
self.play(
text.scale, 3,
run_time=2
)
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/ChangeSizeAnimation.gif" /></p>
```python3
class MoveText(Scene):
def construct(self):
text = TextMobject("Text")
text.scale(2)
text.shift(LEFT*2)
self.play(Write(text))
self.wait()
self.play(
text.shift, RIGHT*2,
run_time=2,
path_arc=0 #Change 0 by -np.pi
)
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/MoveText.gif" /></p>
```python3
class ChangeColorAndSizeAnimation(Scene):
def construct(self):
text = TextMobject("Text")
text.scale(2)
text.shift(LEFT*2)
self.play(Write(text))
self.wait()
self.play(
text.shift, RIGHT*2,
text.scale, 2,
text.set_color, RED,
run_time=2,
)
self.wait()
```
<p align="center"><img src ="/English/4_transform/gifs/ChangeColorAndSizeAnimation.gif" /></p>
|
AnimationsWithManim_Elteoremadebeethoven/English/6b_plots_3D/6b_plots_3D.py | from big_ol_pile_of_manim_imports import *
#There seems to be no change between Scene and ThreeDScene
class CameraPosition1(ThreeDScene):
def construct(self):
circulo=Circle()
self.play(ShowCreation(circulo))
self.wait()
'''
We have to add this line:
def get_axis(self, min_val, max_val, axis_config):
new_config = merge_config([
axis_config,
{"x_min": min_val, "x_max": max_val},
self.number_line_config,
])
return NumberLine(**new_config)
in manimlib/mobject/coordinate_systems.py
Use:
self.set_camera_orientation(phi,theta,distance,gamma)
to change the camera position
You can change the domain with:
ThreeDAxes(
x_min.
x_max,
y_min,
y_max,
z_min,
z_max
)
'''
class CameraPosition2(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
circle=Circle()
self.set_camera_orientation(phi=0 * DEGREES)
self.play(ShowCreation(circle),ShowCreation(axes))
self.wait()
class CameraPosition3(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
circle=Circle()
self.set_camera_orientation(phi=80 * DEGREES,theta=45*DEGREES)
self.play(ShowCreation(circle),ShowCreation(axes))
self.wait()
class CameraPosition4(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
circle=Circle()
self.set_camera_orientation(phi=80 * DEGREES,theta=45*DEGREES,distance=6)
self.play(ShowCreation(circle),ShowCreation(axes))
self.wait()
class CameraPosition5(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
circle=Circle()
self.set_camera_orientation(phi=80 * DEGREES,theta=45*DEGREES,distance=6,gamma=30*DEGREES)
self.play(ShowCreation(circle),ShowCreation(axes))
self.wait()
#------ Move camera
class MoveCamera1(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
circle=Circle()
self.play(ShowCreation(circle),ShowCreation(axes))
self.move_camera(phi=30*DEGREES,theta=-45*DEGREES,run_time=3)
self.wait()
class MoveCamera2(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
circle=Circle()
self.set_camera_orientation(phi=80 * DEGREES)
self.play(ShowCreation(circle),ShowCreation(axes))
self.begin_ambient_camera_rotation(rate=0.1) #Start move camera
self.wait(5)
self.stop_ambient_camera_rotation() #Stop move camera
self.move_camera(phi=80*DEGREES,theta=-PI/2) #Return the position of the camera
self.wait()
#----------- Funciones parametricas
class ParametricCurve1(ThreeDScene):
def construct(self):
curve1=ParametricFunction(
lambda u : np.array([
1.2*np.cos(u),
1.2*np.sin(u),
u/2
]),color=RED,t_min=-TAU,t_max=TAU,
)
curve2=ParametricFunction(
lambda u : np.array([
1.2*np.cos(u),
1.2*np.sin(u),
u
]),color=RED,t_min=-TAU,t_max=TAU,
)
axes = ThreeDAxes()
self.add(axes)
self.set_camera_orientation(phi=80 * DEGREES,theta=-60*DEGREES)
self.begin_ambient_camera_rotation(rate=0.1)
self.play(ShowCreation(curve1))
self.wait()
self.play(Transform(curve1,curve2),rate_func=there_and_back,run_time=3)
self.wait()
# Add this in the object: .set_shade_in_3d(True)
class ParametricCurve2(ThreeDScene):
def construct(self):
curve1=ParametricFunction(
lambda u : np.array([
1.2*np.cos(u),
1.2*np.sin(u),
u/2
]),color=RED,t_min=-TAU,t_max=TAU,
)
curve2=ParametricFunction(
lambda u : np.array([
1.2*np.cos(u),
1.2*np.sin(u),
u
]),color=RED,t_min=-TAU,t_max=TAU,
)
curve1.set_shade_in_3d(True)
curve2.set_shade_in_3d(True)
axes = ThreeDAxes()
self.add(axes)
self.set_camera_orientation(phi=80 * DEGREES,theta=-60*DEGREES)
self.begin_ambient_camera_rotation(rate=0.1)
self.play(ShowCreation(curve1))
self.wait()
self.play(Transform(curve1,curve2),rate_func=there_and_back,run_time=3)
self.wait()
class ParametricCurve2(ThreeDScene):
def construct(self):
curve1=ParametricFunction(
lambda u : np.array([
1.2*np.cos(u),
1.2*np.sin(u),
u/2
]),color=RED,t_min=-TAU,t_max=TAU,
)
curve2=ParametricFunction(
lambda u : np.array([
1.2*np.cos(u),
1.2*np.sin(u),
u
]),color=RED,t_min=-TAU,t_max=TAU,
)
curve1.set_shade_in_3d(True)
curve2.set_shade_in_3d(True)
axes = ThreeDAxes()
self.add(axes)
self.set_camera_orientation(phi=80 * DEGREES,theta=-60*DEGREES)
self.begin_ambient_camera_rotation(rate=0.1)
self.play(ShowCreation(curve1))
self.wait()
self.play(Transform(curve1,curve2),rate_func=there_and_back,run_time=3)
self.wait()
#----- Surfaces
class SurfacesAnimation(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
cylinder = ParametricSurface(
lambda u, v: np.array([
np.cos(TAU * v),
np.sin(TAU * v),
2 * (1 - u)
]),
resolution=(6, 32)).fade(0.5) #Resolution of the surfaces
paraboloid = ParametricSurface(
lambda u, v: np.array([
np.cos(v)*u,
np.sin(v)*u,
u**2
]),v_max=TAU,
checkerboard_colors=[PURPLE_D, PURPLE_E],
resolution=(10, 32)).scale(2)
para_hyp = ParametricSurface(
lambda u, v: np.array([
u,
v,
u**2-v**2
]),v_min=-2,v_max=2,u_min=-2,u_max=2,checkerboard_colors=[BLUE_D, BLUE_E],
resolution=(15, 32)).scale(1)
cone = ParametricSurface(
lambda u, v: np.array([
u*np.cos(v),
u*np.sin(v),
u
]),v_min=0,v_max=TAU,u_min=-2,u_max=2,checkerboard_colors=[GREEN_D, GREEN_E],
resolution=(15, 32)).scale(1)
hip_one_side = ParametricSurface(
lambda u, v: np.array([
np.cosh(u)*np.cos(v),
np.cosh(u)*np.sin(v),
np.sinh(u)
]),v_min=0,v_max=TAU,u_min=-2,u_max=2,checkerboard_colors=[YELLOW_D, YELLOW_E],
resolution=(15, 32))
ellipsoid=ParametricSurface(
lambda u, v: np.array([
1*np.cos(u)*np.cos(v),
2*np.cos(u)*np.sin(v),
0.5*np.sin(u)
]),v_min=0,v_max=TAU,u_min=-PI/2,u_max=PI/2,checkerboard_colors=[TEAL_D, TEAL_E],
resolution=(15, 32)).scale(2)
sphere = ParametricSurface(
lambda u, v: np.array([
1.5*np.cos(u)*np.cos(v),
1.5*np.cos(u)*np.sin(v),
1.5*np.sin(u)
]),v_min=0,v_max=TAU,u_min=-PI/2,u_max=PI/2,checkerboard_colors=[RED_D, RED_E],
resolution=(15, 32)).scale(2)
self.set_camera_orientation(phi=75 * DEGREES)
self.begin_ambient_camera_rotation(rate=0.2)
self.add(axes)
self.play(Write(sphere))
self.wait()
self.play(ReplacementTransform(sphere,ellipsoid))
self.wait()
self.play(ReplacementTransform(ellipsoid,cone))
self.wait()
self.play(ReplacementTransform(cone,hip_one_side))
self.wait()
self.play(ReplacementTransform(hip_one_side,para_hyp))
self.wait()
self.play(ReplacementTransform(para_hyp,paraboloid))
self.wait()
self.play(ReplacementTransform(paraboloid,cylinder))
self.wait()
self.play(FadeOut(cylinder))
#---- Text on 3D
class Text3D1(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
self.set_camera_orientation(phi=75 * DEGREES,theta=-45*DEGREES)
text3d=TextMobject("This is a 3D text").scale(2)
self.add(axes,text3d)
# This text appears in XY plane, to rotate:
class Text3D2(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
self.set_camera_orientation(phi=75 * DEGREES,theta=-45*DEGREES)
text3d=TextMobject("This is a 3D text").scale(2).set_shade_in_3d(True)
text3d.rotate(PI/2,axis=RIGHT)
self.add(axes,text3d)
# To see the text in the traditional form:
class Text3D3(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
self.set_camera_orientation(phi=75 * DEGREES,theta=-45*DEGREES)
text3d=TextMobject("This is a 3D text")
self.add_fixed_in_frame_mobjects(text3d) #<----- Add this
text3d.to_corner(UL)
self.add(axes)
self.begin_ambient_camera_rotation()
self.play(Write(text3d))
sphere = ParametricSurface(
lambda u, v: np.array([
1.5*np.cos(u)*np.cos(v),
1.5*np.cos(u)*np.sin(v),
1.5*np.sin(u)
]),v_min=0,v_max=TAU,u_min=-PI/2,u_max=PI/2,checkerboard_colors=[RED_D, RED_E],
resolution=(15, 32)).scale(2)
self.play(LaggedStart(ShowCreation,sphere))
self.wait(2)
|
AnimationsWithManim_Elteoremadebeethoven/English/6b_plots_3D/scenes.md | # Configuration
We have to add this method:
```python3
def get_axis(self, min_val, max_val, axis_config):
new_config = merge_config([
axis_config,
{"x_min": min_val, "x_max": max_val},
self.number_line_config,
])
return NumberLine(**new_config)
```
in Axes class: manimlib/mobject/coordinate_systems.py
Use:
```self.set_camera_orientation(phi,theta,distance,gamma)```
to change the camera position
You can change the domain with:
```
ThreeDAxes(
x_min.
x_max,
y_min,
y_max,
z_min,
z_max
)
```
# Programs
```python3
#There seems to be no change between Scene and ThreeDScene
class CameraPosition1(ThreeDScene):
def construct(self):
circulo=Circle()
self.play(ShowCreation(circulo))
self.wait()
```
<p align="center"><img src ="/English/6b_plots_3D/gifs/CameraPosition1.gif" /></p>
```python3
class CameraPosition2(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
circle=Circle()
self.set_camera_orientation(phi=0 * DEGREES)
self.play(ShowCreation(circle),ShowCreation(axes))
self.wait()
```
<p align="center"><img src ="/English/6b_plots_3D/gifs/CameraPosition2.gif" /></p>
```python3
class CameraPosition3(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
circle=Circle()
self.set_camera_orientation(phi=80 * DEGREES,theta=45*DEGREES)
self.play(ShowCreation(circle),ShowCreation(axes))
self.wait()
```
<p align="center"><img src ="/English/6b_plots_3D/gifs/CameraPosition3.gif" /></p>
```python3
class CameraPosition4(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
circle=Circle()
self.set_camera_orientation(phi=80 * DEGREES,theta=45*DEGREES,distance=6)
self.play(ShowCreation(circle),ShowCreation(axes))
self.wait()
```
<p align="center"><img src ="/English/6b_plots_3D/gifs/CameraPosition4.gif" /></p>
```python3
class CameraPosition5(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
circle=Circle()
self.set_camera_orientation(phi=80 * DEGREES,theta=45*DEGREES,distance=6,gamma=30*DEGREES)
self.play(ShowCreation(circle),ShowCreation(axes))
self.wait()
```
<p align="center"><img src ="/English/6b_plots_3D/gifs/CameraPosition5.gif" /></p>
```python3
#------ Move camera
class MoveCamera1(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
circle=Circle()
self.play(ShowCreation(circle),ShowCreation(axes))
self.move_camera(phi=30*DEGREES,theta=-45*DEGREES,run_time=3)
self.wait()
```
<p align="center"><img src ="/English/6b_plots_3D/gifs/MoveCamera1.gif" /></p>
```python3
class MoveCamera2(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
circle=Circle()
self.set_camera_orientation(phi=80 * DEGREES)
self.play(ShowCreation(circle),ShowCreation(axes))
self.begin_ambient_camera_rotation(rate=0.1) #Start move camera
self.wait(5)
self.stop_ambient_camera_rotation() #Stop move camera
self.move_camera(phi=80*DEGREES,theta=-PI/2) #Return the position of the camera
self.wait()
```
<p align="center"><img src ="/English/6b_plots_3D/gifs/MoveCamera2.gif" /></p>
```python3
#----------- Parametric functions
class ParametricCurve1(ThreeDScene):
def construct(self):
curve1=ParametricFunction(
lambda u : np.array([
1.2*np.cos(u),
1.2*np.sin(u),
u/2
]),color=RED,t_min=-TAU,t_max=TAU,
)
curve2=ParametricFunction(
lambda u : np.array([
1.2*np.cos(u),
1.2*np.sin(u),
u
]),color=RED,t_min=-TAU,t_max=TAU,
)
axes = ThreeDAxes()
self.add(axes)
self.set_camera_orientation(phi=80 * DEGREES,theta=-60*DEGREES)
self.begin_ambient_camera_rotation(rate=0.1)
self.play(ShowCreation(curve1))
self.wait()
self.play(Transform(curve1,curve2),rate_func=there_and_back,run_time=3)
self.wait()
```
<p align="center"><img src ="/English/6b_plots_3D/gifs/ParametricCurve1.gif" /></p>
```python3
# Add this in the object: .set_shade_in_3d(True)
class ParametricCurve2(ThreeDScene):
def construct(self):
curve1=ParametricFunction(
lambda u : np.array([
1.2*np.cos(u),
1.2*np.sin(u),
u/2
]),color=RED,t_min=-TAU,t_max=TAU,
)
curve2=ParametricFunction(
lambda u : np.array([
1.2*np.cos(u),
1.2*np.sin(u),
u
]),color=RED,t_min=-TAU,t_max=TAU,
)
curve1.set_shade_in_3d(True)
curve2.set_shade_in_3d(True)
axes = ThreeDAxes()
self.add(axes)
self.set_camera_orientation(phi=80 * DEGREES,theta=-60*DEGREES)
self.begin_ambient_camera_rotation(rate=0.1)
self.play(ShowCreation(curve1))
self.wait()
self.play(Transform(curve1,curve2),rate_func=there_and_back,run_time=3)
self.wait()
```
<p align="center"><img src ="/English/6b_plots_3D/gifs/ParametricCurve2.gif" /></p>
```python3
#----- Surfaces
class SurfacesAnimation(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
cylinder = ParametricSurface(
lambda u, v: np.array([
np.cos(TAU * v),
np.sin(TAU * v),
2 * (1 - u)
]),
resolution=(6, 32)).fade(0.5) #Resolution of the surfaces
paraboloid = ParametricSurface(
lambda u, v: np.array([
np.cos(v)*u,
np.sin(v)*u,
u**2
]),v_max=TAU,
checkerboard_colors=[PURPLE_D, PURPLE_E],
resolution=(10, 32)).scale(2)
para_hyp = ParametricSurface(
lambda u, v: np.array([
u,
v,
u**2-v**2
]),v_min=-2,v_max=2,u_min=-2,u_max=2,checkerboard_colors=[BLUE_D, BLUE_E],
resolution=(15, 32)).scale(1)
cone = ParametricSurface(
lambda u, v: np.array([
u*np.cos(v),
u*np.sin(v),
u
]),v_min=0,v_max=TAU,u_min=-2,u_max=2,checkerboard_colors=[GREEN_D, GREEN_E],
resolution=(15, 32)).scale(1)
hip_one_side = ParametricSurface(
lambda u, v: np.array([
np.cosh(u)*np.cos(v),
np.cosh(u)*np.sin(v),
np.sinh(u)
]),v_min=0,v_max=TAU,u_min=-2,u_max=2,checkerboard_colors=[YELLOW_D, YELLOW_E],
resolution=(15, 32))
ellipsoid=ParametricSurface(
lambda u, v: np.array([
1*np.cos(u)*np.cos(v),
2*np.cos(u)*np.sin(v),
0.5*np.sin(u)
]),v_min=0,v_max=TAU,u_min=-PI/2,u_max=PI/2,checkerboard_colors=[TEAL_D, TEAL_E],
resolution=(15, 32)).scale(2)
sphere = ParametricSurface(
lambda u, v: np.array([
1.5*np.cos(u)*np.cos(v),
1.5*np.cos(u)*np.sin(v),
1.5*np.sin(u)
]),v_min=0,v_max=TAU,u_min=-PI/2,u_max=PI/2,checkerboard_colors=[RED_D, RED_E],
resolution=(15, 32)).scale(2)
self.set_camera_orientation(phi=75 * DEGREES)
self.begin_ambient_camera_rotation(rate=0.2)
self.add(axes)
self.play(Write(sphere))
self.wait()
self.play(ReplacementTransform(sphere,ellipsoid))
self.wait()
self.play(ReplacementTransform(ellipsoid,cone))
self.wait()
self.play(ReplacementTransform(cone,hip_one_side))
self.wait()
self.play(ReplacementTransform(hip_one_side,para_hyp))
self.wait()
self.play(ReplacementTransform(para_hyp,paraboloid))
self.wait()
self.play(ReplacementTransform(paraboloid,cylinder))
self.wait()
self.play(FadeOut(cylinder))
```
<p align="center"><img src ="/English/6b_plots_3D/gifs/SurfacesAnimation.gif" /></p>
```python3
#---- Text on 3D
class Text3D1(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
self.set_camera_orientation(phi=75 * DEGREES,theta=-45*DEGREES)
text3d=TextMobject("This is a 3D text").scale(2)
self.add(axes,text3d)
```
<p align="center"><img src ="/English/6b_plots_3D/gifs/Text3D1.png" /></p>
```python3
# This text appears in XY plane, to rotate:
class Text3D2(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
self.set_camera_orientation(phi=75 * DEGREES,theta=-45*DEGREES)
text3d=TextMobject("This is a 3D text").scale(2).set_shade_in_3d(True)
text3d.rotate(PI/2,axis=RIGHT)
self.add(axes,text3d)
```
<p align="center"><img src ="/English/6b_plots_3D/gifs/Text3D2.png" /></p>
```python3
# To see the text in the traditional form:
class Text3D3(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
self.set_camera_orientation(phi=75 * DEGREES,theta=-45*DEGREES)
text3d=TextMobject("This is a 3D text")
self.add_fixed_in_frame_mobjects(text3d) #<----- Add this
text3d.to_corner(UL)
self.add(axes)
self.begin_ambient_camera_rotation()
self.play(Write(text3d))
sphere = ParametricSurface(
lambda u, v: np.array([
1.5*np.cos(u)*np.cos(v),
1.5*np.cos(u)*np.sin(v),
1.5*np.sin(u)
]),v_min=0,v_max=TAU,u_min=-PI/2,u_max=PI/2,checkerboard_colors=[RED_D, RED_E],
resolution=(15, 32)).scale(2)
self.play(LaggedStart(ShowCreation,sphere))
self.wait(2)
```
<p align="center"><img src ="/English/6b_plots_3D/gifs/Text3D3.gif" /></p>
|
AnimationsWithManim_Elteoremadebeethoven/English/2_formulas_tex/2_formulas_tex.py | from big_ol_pile_of_manim_imports import * |
AnimationsWithManim_Elteoremadebeethoven/English/2_formulas_tex/scenes.md | #
## Programas
###
```python3
````
<p align="center"><img src ="/.gif" /></p>
###
```python3
````
<p align="center"><img src ="/.gif" /></p>
|
AnimationsWithManim_Elteoremadebeethoven/English/0_instalation/conda_installation.md | # Conda installation
## Steps
You need to have LaTeX (MikTeX, TeXLive or MacTeX), FFmpeg and Sox installed.
1. Open your conda shell
2. Clone the repository: `git clone https://github.com/3b1b/manim.git`
3. Move to the repository: `cd manim`
4. Create the enviroment: `conda env create --file=environment.yml --name manimenv`
5. Wait for the installation to complete, and actiavate the enviroment with: `conda activate manimenv`
6. Run: `python -m manim example_scenes.py SquareToCircle -pl`
It may be that you need to install ffmpeg with x264 support, if that is the case try **some** of this lines:
```sh
conda install x264=='1!152.20180717' ffmpeg=4.0.2 -c conda-forge
# or
conda install -c conda-forge x264
```
|
AnimationsWithManim_Elteoremadebeethoven/English/0_instalation/windows/INSTRUCCIONES.md | # Instalación en Windows
La instalación en Windows es particularmente elaborada, por lo que recomiendo ver el video tutorial de instalación en YouTube, pero aquí se esbozarán los pasos para la gente que tenga más conocimientos en computación.
En caso de haber concluido todos los pasos y no lograr compilar los archivos es recomendable instalar una versión ligera de GNU/Linux (como [Lubuntu](https://lubuntu.net/downloads/)) en una máquina viritual y realizar el proceso de instalación de [GNU/Linux](https://github.com/Elteoremadebeethoven/AnimacionesConManim/blob/master/Espa%C3%B1ol/0_instalacion/gnuLinux/INSTRUCCIONES.md). La única desventaja será que este proceso necesitará unos 10 GB de espacio en tu disco duro.
[Video](https://www.youtube.com/watch?v=44fthwtnrF0) de como instalar Lubuntu en una máquina virtual usando VirtualBox.
## Instalar editor de texto plano.
Yo recomiendo [Sublime Text](https://www.sublimetext.com/).
## Descargar Manim del [repositorio oficial](https://github.com/3b1b/manim).
Descomprimir el archivo donde el usuario desee (en este ejemplo lo descomprimiré en Documentos).
## Modificar el archivo constants.py
Cambiar el código al archivo constants.py, en la linea que dice:
"Dropbox (3Blue1Brown)/3Blue1Brown Team Folder"
por la dirección de una carpeta dedicada los videos de manim, yo recomiendo la carpeta de videos "Videos" en el directorio principal.
## Instalación de LaTeX
Instalar la versión completa de [MikTeX](https://miktex.org/download).
1. Vas a "Downloads", luego a "All donwloads".
2. Seleccionar "Net Installar" de 32 bits o 64 bits dependiendo de tu PC.
3. Descargar e instalar, es un proceso que puede durar varias horas ([ver video ayuda](https://www.youtube.com/watch?v=yPnfHRE_W_g) del minuto 0:00 hasta el 6:19, lo demás no se necesita).
## Instalar Python 3.
Ir a la página oficial de [Python](https://www.python.org/), luego a Donwloads y descargar alguna versión de Python superior a la 3.6 (recomiendo la versión más reciente), el instalador debe decir "Windows x86-64 executable installer" e instalar.
## Modificar la variable PATH
Añadir a la variable PATH la carpeta donde se instalo Python 3 (ve a Inicio, busca Python 3, dale click derecho a algún archivo y luego click en "Abrir la ubicación del archivo"), además de la subcarpeta "Scripts".
La ubicación por defecto de la instalación suele ser:
```
C:\Users\Pc\AppData\Local\Programs\Python\Python37
```
Y la subcarpeta "Scripts":
```
C:\Users\Pc\AppData\Local\Programs\Python\Python37\Scripts
```
## Instalar [ffmpeg](https://ffmpeg.zeranoe.com/builds/)
Descargar e instalar de manera normal ([video ayuda](https://www.youtube.com/watch?v=X7wLMejOjjM)) y añade la carpeta de instalación a la variable PATH.
## Instalar [sox](https://sourceforge.net/projects/sox/)
Descarga e instala de manera normal y añade la carpeta de instalación a la variable PATH.
## Instalar Pycairo
1. Ir a esta [página](https://www.lfd.uci.edu/~gohlke/pythonlibs/)
2. Buscar pycairo (pulsa F3 y escirbe pycairo para encontrarlo más rápido).
3. Descarga todas las versiones para Python 3 (dependiendo si tu PC es de 64 o 32 bits).
4. Ir a la ubicación de la carpeta de Python 3 y copia la versión más reciente del archivo .whl a la carpeta.
5. Abre la terminal y muevete a la dirección de la carpeta de Python 3.
Ejemplo:
```
cd C:\Users\Pc\AppData\Local\Programs\Python\Python37
```
6. Ingresa el siguiente comando:
```
python -3 -m pip install
```
Seguido del paquete, por ejemplo:
```
python -3 -m pip install pycairo-pycairo‑1.17.1‑cp37‑cp37m‑win_amd64.whl
```
Si sale el error:
```
Unknown option: -3
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Try `python -h' for more information.
```
Elimina el "-3" y escribe solo:
```
python -m pip install pycairo-pycairo‑1.17.1‑cp37‑cp37m‑win_amd64.whl
```
En caso de que emita un error elimina el archivo de la carpeta de Python 3 y copia una versión anterior a la carpeta y vuelve a intentar compilar el comando anterior (modificando el nombre del paquete).
Realiza esto hasta que alguna de las versiones sea instalada correctamente.
## Instala los requerimientos
Muevete a la carpeta de manim-master que descargaste usando la terminal y ejecuta el comando:
```
python -m pip install -r requirements.txt
```
# Ejecución
En la misma carpeta de manim-master compila por primiera vez un archivo de Manim usando:
```
python extract_scene.py example_scenes.py WriteStuff -l
```
# Almacenamiento
El video se pudo haber guardado ya sea en una subcarpeta de "manim-master" llamada igual al archivo .py que compilaste, es decir
```
manim-master/example_scenes/WriteStuff/420p15
```
O bien en la carpeta que definiste en constants.py en una subcarpeta llamada "animations"
```
Videos/example_scenes/WriteStuff/420p15
```
El 420p15 se refiere a la calidad del video a la que fue exportado. Dependerá de la versión de manim que descargaste el lugar donde se guarde el archivo.
|
AnimationsWithManim_Elteoremadebeethoven/English/0_instalation/gnuLinux/INSTRUCTIONS.md | # Instalation on GNU/Linux
Link to [video tutorial](https://www.youtube.com/watch?v=z_WJaHYH66M).
## Instalation with the terminal:
Open a terminal an run the follow commands:
### Install de LaTeX:
Debian distributions:
```sh
$ sudo apt-get install texlive-full
```
Arch distributions:
```sh
$ sudo pacman -S texlive-most
```
Fedora distributions:
```sh
# yum -y install texlive-collection-latexextra
```
### Install python3.7
Debian distributions:
```sh
$ sudo apt-get install python3.7-minimal
```
Arch distributions: always is update
Fedora distributions:
```sh
# yum install gcc openssl-devel bzip2-devel libffi-devel
# cd /usr/src
# wget https://www.python.org/ftp/python/3.7.3/Python-3.7.3.tgz
# tar xzf Python-3.7.3.tgz
# cd Python-3.7.3
# ./configure --enable-optimizations
# make altinstall
# rm /usr/src/Python-3.7.3.tgz
```
### Install pip:
All distributions:
```sh
$ mkdir pip
$ cd pip
$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
$ python3.7 get-pip.py
```
### Install ffmpeg:
Debian
```sh
$ sudo apt-get install ffmpeg
```
Arch-Linux:
```sh
$ sudo pacman -S ffmpeg
```
Fedora:
```sh
$ sudo dnf install https://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm
$ sudo dnf install https://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-$(rpm -E %fedora).noarch.rpm
$ sudo dnf install ffmpeg ffmpeg-devel
```
### Install sox:
Debian
```sh
$ sudo apt-get install sox
```
Arch-Linux (with AUR):
```sh
$ aurman -S sox
```
Fedora:
Download it from: https://pkgs.org/download/sox
### Install pycairo dependences (only for Debian distributions):
Only for Debian distros:
```sh
$ sudo apt-get install libcairo2-dev libjpeg-dev libgif-dev python3-dev libffi-dev
```
### Install pyreadline, pydub:
All distributions:
```sh
$ python3.7 -m pip install pyreadline
$ python3.7 -m pip install pydub
```
### Download Manim from [actual version](https://github.com/3b1b/manim), or [3/Feb/2019 version](https://github.com/3b1b/manim/tree/3b088b12843b7a4459fe71eba96b70edafb7aa78).
<p align="center"><img src ="/English/0_instalation/gnuLinux/gifs/manimDescarga.png" /></p>
Unzip the file into a directory that does not have spaces
## Install list requirements.txt:
Move the terminal to the manim-master directory:
```sh
~/manim-master$
```
Then run:
```sh
$ python3.7 -m pip install -r requirements.txt
```
# Run Manim
Run this command in manim-master directory:
```sh
$ python3.7 -m manim example_scenes.py SquareToCircle -pl
```
|
AnimationsWithManim_Elteoremadebeethoven/English/0_instalation/macOS/INSTRUCTIONS.md | # Installation on MacOS
Link to [video tutorial](https://www.youtube.com/watch?v=uZj_GQc6pN4).
## Install dependencies.
### Open a terminal
Search "terminal" on Spotlight
<p align="center"><img src ="/English/0_instalation/macOS/gifs/terminal.png" /></p>
### Install Homebrew
Copy the code from [Homebrew](https://brew.sh) and paste it in the terminal
<p align="center"><img src ="/English/0_instalation/macOS/gifs/MacP1.gif" /></p>
### Install LaTeX (versión completa)
Go to [MacTeX](http://www.tug.org/mactex/), download the .pkg file and install it ([help](https://www.youtube.com/watch?v=5CNmIaRxS20)).
<p align="center"><img src ="/English/0_instalation/macOS/gifs/MacP2.gif" /></p>
### Install Python 3
Go to the official website of [Python](https://www.python.org/), and download the 3.7 version ([help](https://www.youtube.com/watch?v=0hGzGdRQeak)).
<p align="center"><img src ="/English/0_instalation/macOS/gifs/MacP3.gif" /></p>
### Install PIP
Run the follow commands:
```sh
brew install curl
mkdir ManimInstall
cd ManimInstall
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py
```
### Install FFmpeg, SoX and Cairo.
Run the follow commands:
#### FFmpeg
```sh
brew install ffmpeg
```
#### Sox
```sh
brew install sox
```
#### More packages
```sh
brew install cairo
```
If that does not works use:
```sh
brew install cairo --use-clang
```
```sh
brew install py2cairo
```
```sh
brew install pkg-config
```
<p align="center"><img src ="/English/0_instalation/macOS/gifs/MacP5.gif" /></p>
### Download Manim from [actual version](https://github.com/3b1b/manim), or [3/Feb/2019 version](https://github.com/3b1b/manim/tree/3b088b12843b7a4459fe71eba96b70edafb7aa78).
<p align="center"><img src ="/English/0_instalation/macOS/gifs/DescargarManim.gif" /></p>
### Unzip the file into a directory that does not have spaces
<p align="center"><img src ="/English/0_instalation/macOS/gifs/pd.png" /></p>
### Install list requirements.txt
Move the terminal to manim-master folder and run this:
```sh
python3 -m pip install pyreadline
python3 -m pip install pydub
```
#### Download the rest
Open `requirements.txt` and replace the content with [this](https://github.com/3b1b/manim/blob/master/requirements.txt) and use:
```
python3 -m pip install -r requirements.txt
```
<p align="center"><img src ="/English/0_instalation/macOS/gifs/MacP6.gif" /></p>
# Run Manim
With the terminal in manim-master directory run this:
```sh
python3 -m manim example_scenes.py WriteStuff -pl
```
That command have to build the follow video:
<p align="center"><img src ="/English/0_instalation/macOS/gifs/MacP8.gif" /></p>
|
AnimationsWithManim_Elteoremadebeethoven/English/5_visual_tools/5_visual_tools.py | from big_ol_pile_of_manim_imports import *
class MoveBraces(Scene):
def construct(self):
text=TexMobject(
"\\frac{d}{dx}f(x)g(x)=", #0
"f(x)\\frac{d}{dx}g(x)", #1
"+", #2
"g(x)\\frac{d}{dx}f(x)" #3
)
self.play(Write(text))
brace1 = Brace(text[1], UP, buff = SMALL_BUFF)
brace2 = Brace(text[3], UP, buff = SMALL_BUFF)
t1 = brace1.get_text("$g'f$")
t2 = brace2.get_text("$f'g$")
self.play(
GrowFromCenter(brace1),
FadeIn(t1),
)
self.wait()
self.play(
ReplacementTransform(brace1,brace2),
ReplacementTransform(t1,t2)
)
self.wait()
class MoveBracesCopy(Scene):
def construct(self):
text=TexMobject(
"\\frac{d}{dx}f(x)g(x)=","f(x)\\frac{d}{dx}g(x)","+",
"g(x)\\frac{d}{dx}f(x)"
)
self.play(Write(text))
brace1 = Brace(text[1], UP, buff = SMALL_BUFF)
brace2 = Brace(text[3], UP, buff = SMALL_BUFF)
t1 = brace1.get_text("$g'f$")
t2 = brace2.get_text("$f'g$")
self.play(
GrowFromCenter(brace1),
FadeIn(t1),
)
self.wait()
self.play(
ReplacementTransform(brace1.copy(),brace2),
ReplacementTransform(t1.copy(),t2)
)
self.wait()
class MoveFrameBox(Scene):
def construct(self):
text=TexMobject(
"\\frac{d}{dx}f(x)g(x)=","f(x)\\frac{d}{dx}g(x)","+",
"g(x)\\frac{d}{dx}f(x)"
)
self.play(Write(text))
framebox1 = SurroundingRectangle(text[1], buff = .1)
framebox2 = SurroundingRectangle(text[3], buff = .1)
self.play(
ShowCreation(framebox1),
)
self.wait()
self.play(
ReplacementTransform(framebox1,framebox2),
)
self.wait()
class MoveFrameBoxCopy(Scene):
def construct(self):
text=TexMobject(
"\\frac{d}{dx}f(x)g(x)=","f(x)\\frac{d}{dx}g(x)","+",
"g(x)\\frac{d}{dx}f(x)"
)
self.play(Write(text))
framebox1 = SurroundingRectangle(text[1], buff = .1)
framebox2 = SurroundingRectangle(text[3], buff = .1)
self.play(ShowCreation(framebox1))
self.wait()
self.play(
ReplacementTransform(framebox1.copy(),framebox2),
path_arc=-np.pi
)
self.wait()
class MoveFrameBoxCopy2(Scene):
def construct(self):
text=TexMobject(
"\\frac{d}{dx}f(x)g(x)=","f(x)\\frac{d}{dx}g(x)","+",
"g(x)\\frac{d}{dx}f(x)"
)
self.play(Write(text))
framebox1 = SurroundingRectangle(text[1], buff = .1)
framebox2 = SurroundingRectangle(text[3], buff = .1)
t1 = TexMobject("g'f")
t2 = TexMobject("f'g")
t1.next_to(framebox1, UP, buff=0.1)
t2.next_to(framebox2, UP, buff=0.1)
self.play(
ShowCreation(framebox1),
FadeIn(t1)
)
self.wait()
self.play(
ReplacementTransform(framebox1.copy(),framebox2),
ReplacementTransform(t1.copy(),t2),
)
self.wait()
class Arrow1(Scene):
def construct(self):
step1 = TextMobject("Step 1")
step2 = TextMobject("Step 2")
arrow = Arrow(LEFT,RIGHT)
step1.move_to(LEFT*2)
arrow.next_to(step1,RIGHT,buff = .1)
step2.next_to(arrow,RIGHT,buff = .1)
self.play(Write(step1))
self.wait()
self.play(GrowArrow(arrow))
self.play(Write(step2))
self.wait()
class Arrow2(Scene):
def construct(self):
step1 = TextMobject("Step 1")
step2 = TextMobject("Step 2")
step1.move_to(LEFT*2+DOWN*2)
step2.move_to(4*RIGHT+2*UP)
arrow1 = Arrow(step1.get_right(),step2.get_left(),buff=0.1)
arrow1.set_color(RED)
arrow2 = Arrow(step1.get_top(),step2.get_bottom(),buff=0.1)
arrow2.set_color(BLUE)
self.play(Write(step1),Write(step2))
self.play(GrowArrow(arrow1))
self.play(GrowArrow(arrow2))
self.wait()
class LineAnimation(Scene):
def construct(self):
step1 = TextMobject("Step 1")
step2 = TextMobject("Step 2")
step1.move_to(LEFT*2+DOWN*2)
step2.move_to(4*RIGHT+2*UP)
arrow1 = Line(step1.get_right(),step2.get_left(),buff=0.1)
arrow1.set_color(RED)
arrow2 = Line(step1.get_top(),step2.get_bottom(),buff=0.1)
arrow2.set_color(BLUE)
self.play(Write(step1),Write(step2))
self.play(ShowCreation(arrow1))
self.play(ShowCreation(arrow2))
self.wait()
class DashedLineAnimation(Scene):
def construct(self):
step1 = TextMobject("Step 1")
step2 = TextMobject("Step 2")
step1.move_to(LEFT*2+DOWN*2)
step2.move_to(4*RIGHT+2*UP)
arrow1 = DashedLine(step1.get_right(),step2.get_left(),buff=0.1)
arrow1.set_color(RED)
arrow2 = Line(step1.get_top(),step2.get_bottom(),buff=0.1)
arrow2.set_color(BLUE)
self.play(Write(step1),Write(step2))
self.play(ShowCreation(arrow1))
self.play(ShowCreation(arrow2))
self.wait()
class LineAnimation2(Scene):
def construct(self):
step1 = TextMobject("Step 1")
step2 = TextMobject("Step 2")
step1.move_to(LEFT*2+DOWN*2)
step2.move_to(4*RIGHT+2*UP)
line = Line(step1.get_right(),step2.get_left(),buff=0.1)
self.play(Write(step1),Write(step2))
self.play(GrowArrow(line))
self.play(
step2.next_to, step2, LEFT*2,
)
self.wait()
class LineAnimation3(Scene):
def construct(self):
step1 = TextMobject("Step 1")
step2 = TextMobject("Step 2")
step3 = step2.copy()
step1.move_to(LEFT*2+DOWN*2)
step2.move_to(4*RIGHT+2*UP)
step3.next_to(step2, LEFT*2)
line = Line(step1.get_right(),step2.get_left(),buff=0.1)
lineCopy = Line(step1.get_right(),step3.get_bottom(),buff=0.1)
self.play(Write(step1),Write(step2))
self.play(GrowArrow(line))
self.play(
ReplacementTransform(step2,step3),
ReplacementTransform(line,lineCopy)
)
self.wait() |
AnimationsWithManim_Elteoremadebeethoven/English/5_visual_tools/scenes.md | # Programs
```python3
class MoveBraces(Scene):
def construct(self):
text=TexMobject(
"\\frac{d}{dx}f(x)g(x)=", #0
"f(x)\\frac{d}{dx}g(x)", #1
"+", #2
"g(x)\\frac{d}{dx}f(x)" #3
)
self.play(Write(text))
brace1 = Brace(text[1], UP, buff = SMALL_BUFF)
brace2 = Brace(text[3], UP, buff = SMALL_BUFF)
t1 = brace1.get_text("$g'f$")
t2 = brace2.get_text("$f'g$")
self.play(
GrowFromCenter(brace1),
FadeIn(t1),
)
self.wait()
self.play(
ReplacementTransform(brace1,brace2),
ReplacementTransform(t1,t2)
)
self.wait()
```
<p align="center"><img src ="/English/5_visual_tools/gifs/MoveBraces.gif" /></p>
```python3
class MoveBracesCopy(Scene):
def construct(self):
text=TexMobject(
"\\frac{d}{dx}f(x)g(x)=","f(x)\\frac{d}{dx}g(x)","+",
"g(x)\\frac{d}{dx}f(x)"
)
self.play(Write(text))
brace1 = Brace(text[1], UP, buff = SMALL_BUFF)
brace2 = Brace(text[3], UP, buff = SMALL_BUFF)
t1 = brace1.get_text("$g'f$")
t2 = brace2.get_text("$f'g$")
self.play(
GrowFromCenter(brace1),
FadeIn(t1),
)
self.wait()
self.play(
ReplacementTransform(brace1.copy(),brace2),
ReplacementTransform(t1.copy(),t2)
)
self.wait()
```
<p align="center"><img src ="/English/5_visual_tools/gifs/MoveBracesCopy.gif" /></p>
```python3
class MoveFrameBox(Scene):
def construct(self):
text=TexMobject(
"\\frac{d}{dx}f(x)g(x)=","f(x)\\frac{d}{dx}g(x)","+",
"g(x)\\frac{d}{dx}f(x)"
)
self.play(Write(text))
framebox1 = SurroundingRectangle(text[1], buff = .1)
framebox2 = SurroundingRectangle(text[3], buff = .1)
self.play(
ShowCreation(framebox1),
)
self.wait()
self.play(
ReplacementTransform(framebox1,framebox2),
)
self.wait()
```
<p align="center"><img src ="/English/5_visual_tools/gifs/MoveFrameBox.gif" /></p>
```python3
class MoveFrameBoxCopy(Scene):
def construct(self):
text=TexMobject(
"\\frac{d}{dx}f(x)g(x)=","f(x)\\frac{d}{dx}g(x)","+",
"g(x)\\frac{d}{dx}f(x)"
)
self.play(Write(text))
framebox1 = SurroundingRectangle(text[1], buff = .1)
framebox2 = SurroundingRectangle(text[3], buff = .1)
self.play(ShowCreation(framebox1))
self.wait()
self.play(
ReplacementTransform(framebox1.copy(),framebox2),
path_arc=-np.pi
)
self.wait()
```
<p align="center"><img src ="/English/5_visual_tools/gifs/MoveFrameBoxCopy.gif" /></p>
```python3
class MoveFrameBoxCopy2(Scene):
def construct(self):
text=TexMobject(
"\\frac{d}{dx}f(x)g(x)=","f(x)\\frac{d}{dx}g(x)","+",
"g(x)\\frac{d}{dx}f(x)"
)
self.play(Write(text))
framebox1 = SurroundingRectangle(text[1], buff = .1)
framebox2 = SurroundingRectangle(text[3], buff = .1)
t1 = TexMobject("g'f")
t2 = TexMobject("f'g")
t1.next_to(framebox1, UP, buff=0.1)
t2.next_to(framebox2, UP, buff=0.1)
self.play(
ShowCreation(framebox1),
FadeIn(t1)
)
self.wait()
self.play(
ReplacementTransform(framebox1.copy(),framebox2),
ReplacementTransform(t1.copy(),t2),
)
self.wait()
```
<p align="center"><img src ="/English/5_visual_tools/gifs/MoveFrameBoxCopy2.gif" /></p>
```python3
class Arrow1(Scene):
def construct(self):
step1 = TextMobject("Step 1")
step2 = TextMobject("Step 2")
arrow = Arrow(LEFT,RIGHT)
step1.move_to(LEFT*2)
arrow.next_to(step1,RIGHT,buff = .1)
step2.next_to(arrow,RIGHT,buff = .1)
self.play(Write(step1))
self.wait()
self.play(GrowArrow(arrow))
self.play(Write(step2))
self.wait()
```
<p align="center"><img src ="/English/5_visual_tools/gifs/Arrow1.gif" /></p>
```python3
class Arrow2(Scene):
def construct(self):
step1 = TextMobject("Step 1")
step2 = TextMobject("Step 2")
step1.move_to(LEFT*2+DOWN*2)
step2.move_to(4*RIGHT+2*UP)
arrow1 = Arrow(step1.get_right(),step2.get_left(),buff=0.1)
arrow1.set_color(RED)
arrow2 = Arrow(step1.get_top(),step2.get_bottom(),buff=0.1)
arrow2.set_color(BLUE)
self.play(Write(step1),Write(step2))
self.play(GrowArrow(arrow1))
self.play(GrowArrow(arrow2))
self.wait()
```
<p align="center"><img src ="/English/5_visual_tools/gifs/Arrow2.gif" /></p>
```python3
class LineAnimation(Scene):
def construct(self):
step1 = TextMobject("Step 1")
step2 = TextMobject("Step 2")
step1.move_to(LEFT*2+DOWN*2)
step2.move_to(4*RIGHT+2*UP)
arrow1 = Line(step1.get_right(),step2.get_left(),buff=0.1)
arrow1.set_color(RED)
arrow2 = Line(step1.get_top(),step2.get_bottom(),buff=0.1)
arrow2.set_color(BLUE)
self.play(Write(step1),Write(step2))
self.play(ShowCreation(arrow1))
self.play(ShowCreation(arrow2))
self.wait()
```
<p align="center"><img src ="/English/5_visual_tools/gifs/LineAnimation.gif" /></p>
```python3
class DashedLineAnimation(Scene):
def construct(self):
step1 = TextMobject("Step 1")
step2 = TextMobject("Step 2")
step1.move_to(LEFT*2+DOWN*2)
step2.move_to(4*RIGHT+2*UP)
arrow1 = DashedLine(step1.get_right(),step2.get_left(),buff=0.1)
arrow1.set_color(RED)
arrow2 = Line(step1.get_top(),step2.get_bottom(),buff=0.1)
arrow2.set_color(BLUE)
self.play(Write(step1),Write(step2))
self.play(ShowCreation(arrow1))
self.play(ShowCreation(arrow2))
self.wait()
```
<p align="center"><img src ="/English/5_visual_tools/gifs/DashedLineAnimation.gif" /></p>
```python3
class LineAnimation2(Scene):
def construct(self):
step1 = TextMobject("Step 1")
step2 = TextMobject("Step 2")
step1.move_to(LEFT*2+DOWN*2)
step2.move_to(4*RIGHT+2*UP)
line = Line(step1.get_right(),step2.get_left(),buff=0.1)
self.play(Write(step1),Write(step2))
self.play(GrowArrow(line))
self.play(
step2.next_to, step2, LEFT*2,
)
self.wait()
```
<p align="center"><img src ="/English/5_visual_tools/gifs/LineAnimation2.gif" /></p>
```python3
class LineAnimation3(Scene):
def construct(self):
step1 = TextMobject("Step 1")
step2 = TextMobject("Step 2")
step3 = step2.copy()
step1.move_to(LEFT*2+DOWN*2)
step2.move_to(4*RIGHT+2*UP)
step3.next_to(step2, LEFT*2)
line = Line(step1.get_right(),step2.get_left(),buff=0.1)
lineCopy = Line(step1.get_right(),step3.get_bottom(),buff=0.1)
self.play(Write(step1),Write(step2))
self.play(GrowArrow(line))
self.play(
ReplacementTransform(step2,step3),
ReplacementTransform(line,lineCopy)
)
self.wait()
```
<p align="center"><img src ="/English/5_visual_tools/gifs/LineAnimation3.gif" /></p>
|
AnimationsWithManim_Elteoremadebeethoven/English/9_project/svg_classes.py | from big_ol_pile_of_manim_imports import *
class CheckSVG(Scene):
CONFIG={
"camera_config":{"background_color": WHITE},
"svg_type":"svg",
"file":"",
"svg_scale":0.9,
"angle":0,
"flip_svg":False,
"fill_opacity": 1,
"remove": [],
"stroke_color": BLACK,
"fill_color": BLACK,
"stroke_width": 3,
"numbers_scale":0.5,
"show_numbers": False,
"animation": False,
"direction_numbers": UP,
"color_numbers": RED,
"space_between_numbers":0,
"show_elements":[],
"color_element":BLUE,
"set_size":"width",
"remove_stroke":[],
"show_stroke":[],
"stroke_":1
}
def construct(self):
if self.set_size=="width":
width_size=FRAME_WIDTH
height_size=None
else:
width_size=None
height_size=FRAME_HEIGHT
if self.svg_type=="svg":
self.imagen=SVGMobject(
"%s"%self.file,
#fill_opacity = 1,
stroke_width = self.stroke_width,
stroke_color = self.stroke_color,
width=width_size,
height=height_size
).rotate(self.angle).set_fill(self.fill_color,self.fill_opacity).scale(self.svg_scale)
else:
self.imagen=self.import_text().set_fill(self.fill_color,self.fill_opacity).rotate(self.angle).set_stroke(self.stroke_color,0)
if self.set_size=="width":
self.imagen.set_width(FRAME_WIDTH)
else:
self.imagen.set_height(FRAME_HEIGHT)
self.imagen.scale(self.svg_scale)
self.personalize_image()
if self.flip_svg==True:
self.imagen.flip()
if self.show_numbers==True:
self.print_formula(self.imagen,
self.numbers_scale,
self.direction_numbers,
self.remove,
self.space_between_numbers,
self.color_numbers)
self.return_elements(self.imagen,self.show_elements)
for st in self.remove_stroke:
self.imagen[st].set_stroke(None,0)
for st in self.show_stroke:
self.imagen[st].set_stroke(None,self.stroke_)
if self.animation==True:
self.play(DrawBorderThenFill(self.imagen))
else:
self.add(self.imagen)
self.wait()
def import_text(self):
return TexMobject("")
def personalize_image(self):
pass
def print_formula(self,text,inverse_scale,direction,exception,buff,color):
text.set_color(RED)
self.add(text)
c = 0
for j in range(len(text)):
permission_print=True
for w in exception:
if j==w:
permission_print=False
if permission_print:
self.add(text[j].set_color(self.stroke_color))
c = c + 1
c=0
for j in range(len(text)):
permission_print=True
element = TexMobject("%d" %c,color=color)
element.scale(inverse_scale)
element.next_to(text[j],direction,buff=buff)
for w in exception:
if j==w:
permission_print=False
if permission_print:
self.add(element)
c = c + 1
def return_elements(self,formula,adds):
for i in adds:
self.add_foreground_mobjects(formula[i].set_color(self.color_element),
TexMobject("%d"%i,color=self.color_element,background_stroke_width=0).scale(self.numbers_scale).next_to(formula[i],self.direction_numbers,buff=self.space_between_numbers))
class CheckFormula(Scene):
CONFIG={
"camera_config":{"background_color": BLACK},
"svg_type":"text",
"file":"",
"svg_scale":0.9,
"angle":0,
"flip_svg":False,
"fill_opacity": 1,
"remove": [],
"stroke_color": WHITE,
"fill_color": WHITE,
"stroke_width": 3,
"numbers_scale":0.5,
"show_numbers": True,
"animation": False,
"direction_numbers": UP,
"color_numbers": RED,
"space_between_numbers":0,
"show_elements":[],
"color_element":BLUE,
"set_size":"width",
"remove_stroke":[],
"show_stroke":[],
"stroke_":1
}
def construct(self):
if self.set_size=="width":
width_size=FRAME_WIDTH
height_size=None
else:
width_size=None
height_size=FRAME_HEIGHT
if self.svg_type=="svg":
self.imagen=SVGMobject(
"%s"%self.file,
#fill_opacity = 1,
stroke_width = self.stroke_width,
stroke_color = self.stroke_color,
width=width_size,
height=height_size
).rotate(self.angle).set_fill(self.fill_color,self.fill_opacity).scale(self.svg_scale)
else:
self.imagen=self.import_text()
if self.set_size=="width":
self.imagen.set_width(FRAME_WIDTH)
else:
self.imagen.set_height(FRAME_HEIGHT)
self.imagen.scale(self.svg_scale)
if self.flip_svg==True:
self.imagen.flip()
if self.show_numbers==True:
self.print_formula(self.imagen.copy(),
self.numbers_scale,
self.direction_numbers,
self.remove,
self.space_between_numbers,
self.color_numbers)
self.return_elements(self.imagen.copy(),self.show_elements)
for st in self.remove_stroke:
self.imagen[st].set_stroke(None,0)
for st in self.show_stroke:
self.imagen[st].set_stroke(None,self.stroke_)
if self.animation==True:
self.play(DrawBorderThenFill(self.imagen))
else:
self.add(self.imagen)
self.personalize_image()
self.wait()
def import_text(self):
return TexMobject("")
def personalize_image(self):
pass
def print_formula(self,text,inverse_scale,direction,exception,buff,color):
text.set_color(RED)
self.add(text)
c = 0
for j in range(len(text)):
permission_print=True
for w in exception:
if j==w:
permission_print=False
if permission_print:
self.add(text[j].set_color(self.stroke_color))
c = c + 1
c=0
for j in range(len(text)):
permission_print=True
element = TexMobject("%d" %c,color=color)
element.scale(inverse_scale)
element.next_to(text[j],direction,buff=buff)
for w in exception:
if j==w:
permission_print=False
if permission_print:
self.add_foreground_mobjects(element)
c = c + 1
def return_elements(self,formula,adds):
for i in adds:
self.add_foreground_mobjects(formula[i].set_color(self.color_element),
TexMobject("%d"%i,color=self.color_element,background_stroke_width=0).scale(self.numbers_scale).next_to(formula[i],self.direction_numbers,buff=self.space_between_numbers))
class CheckFormulaByTXT(Scene):
CONFIG={
"camera_config":{"background_color": BLACK},
"svg_type":"text",
"text": TexMobject(""),
"file":"",
"svg_scale":0.9,
"angle":0,
"flip_svg":False,
"fill_opacity": 1,
"remove": [],
"stroke_color": WHITE,
"fill_color": WHITE,
"stroke_width": 3,
"numbers_scale":0.5,
"show_numbers": True,
"animation": False,
"direction_numbers": UP,
"color_numbers": RED,
"space_between_numbers":0,
"show_elements":[],
"color_element":PURPLE,
"set_size":"width",
"remove_stroke":[],
"show_stroke":[],
"warning_color":RED,
"stroke_":1
}
def construct(self):
self.imagen=self.text
if self.set_size=="width":
self.imagen.set_width(FRAME_WIDTH)
else:
self.imagen.set_height(FRAME_HEIGHT)
self.imagen.scale(self.svg_scale)
if self.flip_svg==True:
self.imagen.flip()
if self.show_numbers==True:
self.print_formula(self.imagen.copy(),
self.numbers_scale,
self.direction_numbers,
self.remove,
self.space_between_numbers,
self.color_numbers)
self.return_elements(self.imagen.copy(),self.show_elements)
for st in self.remove_stroke:
self.imagen[st].set_stroke(None,0)
for st in self.show_stroke:
self.imagen[st].set_stroke(None,self.stroke_)
if self.animation==True:
self.play(DrawBorderThenFill(self.imagen))
else:
c=0
for j in range(len(self.imagen)):
permission_print=True
for w in self.remove:
if j==w:
permission_print=False
if permission_print:
self.add(self.imagen[j])
c = c + 1
self.personalize_image()
self.wait()
def personalize_image(self):
pass
def print_formula(self,text,inverse_scale,direction,exception,buff,color):
text.set_color(self.warning_color)
self.add(text)
c = 0
for j in range(len(text)):
permission_print=True
for w in exception:
if j==w:
permission_print=False
if permission_print:
self.add(text[j].set_color(self.stroke_color))
c = c + 1
c=0
for j in range(len(text)):
permission_print=True
element = TexMobject("%d" %c,color=color)
element.scale(inverse_scale)
element.next_to(text[j],direction,buff=buff)
for w in exception:
if j==w:
permission_print=False
if permission_print:
self.add_foreground_mobjects(element)
c = c + 1
def return_elements(self,formula,adds):
for i in adds:
self.add_foreground_mobjects(formula[i].set_color(self.color_element),
TexMobject("%d"%i,color=self.color_element,background_stroke_width=0).scale(self.numbers_scale).next_to(formula[i],self.direction_numbers,buff=self.space_between_numbers)) |
AnimationsWithManim_Elteoremadebeethoven/English/9_project/9_project.py | from big_ol_pile_of_manim_imports import *
#Import formulas:
from tutorial.formulas_txt.formulas import formulas
class SolveGeneralQuadraticEquation(Scene):
def construct(self):
self.import_formulas()
self.write_formulas()
self.set_changes()
self.step_formula(n_step=1,
changes=self.set_of_changes[0],
fade=[10],
path_arc=-PI/2
)
self.step_formula(n_step=2,
changes=self.set_of_changes[1],
write=[6,14],
pre_copy=[0],
pos_copy=[15]
)
self.step_formula(n_step=3,
changes=self.set_of_changes[2],
pos_write=[10, 11, 13, 14, 15, 16, 18, 20, 28, 29, 31, 32, 33, 34, 36, 38],
)
self.step_formula(n_step=4,
changes=self.set_of_changes[3],
)
self.step_formula(n_step=5,
changes=self.set_of_changes[4],
fade=[20,27],
pre_copy=[29],
pos_copy=[28]
)
self.step_formula(n_step=6,
changes=self.set_of_changes[5],
fade=[19],
)
self.step_formula(n_step=7,
changes=self.set_of_changes[6],
pos_write=[25,28],
)
self.step_formula(n_step=8,
changes=self.set_of_changes[7],
pos_write=[32,26],
)
self.step_formula(n_step=9,
changes=self.set_of_changes[8],
)
self.step_formula(n_step=10,
changes=self.set_of_changes[9],
pos_write=[0, 1, 16, 18, 20],
)
self.step_formula(n_step=11,
changes=self.set_of_changes[10],
fade=[0, 1, 2, 12, 14]
)
self.step_formula(n_step=12,
changes=self.set_of_changes[11],
)
self.step_formula(n_step=13,
changes=self.set_of_changes[12],
fade=[25]
)
self.step_formula(n_step=14,
changes=self.set_of_changes[13],
)
#
c1=SurroundingRectangle(self.formulas[14],buff=0.2)
c2=SurroundingRectangle(self.formulas[14],buff=0.2)
c2.rotate(PI)
self.play(ShowCreationThenDestruction(c1),ShowCreationThenDestruction(c2))
self.wait(2)
def import_formulas(self):
self.formulas=formulas
def write_formulas(self):
self.play(Write(self.formulas[0]))
def set_changes(self):
self.set_of_changes=[
#1
[[
( 0, 1, 3, 4, 5, 6, 7, 8, 9 ),
( 0, 1, 3, 4, 5, 6, 8, 9, 7 )
]],
#2
[[
( 0, 1, 3, 4, 5, 6, 7, 8, 9 ),
( 7, 0, 2, 3, 5, 9, 10, 11, 13 )
]],
#3
[[
( 0, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15 ),
( 0, 2, 3, 5, 6, 7, 9, 21, 22, 24, 25, 26 )
]],
#4
[[
( 0, 2, 10, 11, 13, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 28, 29, 31, 32, 33, 34, 36, 38 ,5,6,7,9,3),
( 1, 11, 2, 0, 4, 5, 6, 7, 9, 11, 12, 13, 15, 16, 17, 19, 20, 22, 23, 24, 25, 27, 29 ,4,5,7,1,2)
]],
#5
[[
( 0, 1, 2, 4, 5, 6, 7, 9, 11, 12, 13, 15, 16, 17, 19, 22, 23, 24, 25, 29),
( 0, 1, 2, 4, 5, 6, 7, 9, 11, 12, 13, 15, 16, 17, 19, 21, 24, 25, 26, 23)
]],
#6
[[
( 0, 1, 2, 4, 5, 6, 7, 9, 11, 12, 13, 15, 16, 17, 21, 23, 24, 25, 26, 28 ),
( 0, 1, 2, 4, 5, 6, 7, 9, 11, 12, 23, 25, 26, 27, 14, 16, 17, 18, 19, 21 )
]],
#7
[[
( 0, 1, 2, 4, 5, 6, 7, 9, 11, 12, 14, 16, 17, 18, 19, 21, 23, 25, 26, 27 ),
( 0, 1, 2, 4, 5, 6, 7, 9, 11, 12, 14, 16, 17, 18, 19, 21, 23, 26, 27, 29 )
]],
#8
[[
( 0, 1, 2, 4, 5, 6, 7, 9, 11, 12, 14, 16, 17, 18, 19, 21, 23, 25, 26, 27, 28, 29, ),
( 0, 1, 2, 4, 5, 6, 7, 9, 11, 12, 14, 16, 17, 18, 19, 21, 23, 25, 27, 28, 29, 30, )
]],
#9
[[
( 0, 1, 2, 4, 5, 6, 7, 9, 11, 12, 14, 16, 17, 18, 19, 21, 23, 25, 26, 27, 28, 29, 30, 32, ),
( 0, 1, 2, 4, 5, 6, 7, 9, 11, 12, 14, 16, 21, 22, 23, 25, 17, 18, 19, 20, 21, 22, 23, 25, )
]],
#10
[[
( 0, 1, 2, 4, 5, 6, 7, 9, 11, 12, 14, 16, 17, 18, 19, 20, 21, 22, 23, 25, ),
( 2, 3, 5, 6, 7, 8, 10, 12, 14, 15, 21, 22, 23, 24, 25, 26, 27, 30, 31, 32, )
]],
#11
[[
( 3, 5, 6, 7, 8, 10, 15, 16, 18, 20, 21, 22, 23, 24, 25, 26, 27, 30, 31, 32, ),
( 0, 1, 3, 4, 5, 6, 8, 9, 10, 12, 14, 15, 16, 17, 18, 19, 20, 21, 24, 25, )
]],
#12
[[
( 0, 1, 3, 4, 5, 6, 8, 9, 10, 12, 14, 15, 16, 17, 18, 19, 20, 21, 24, 25, ),
( 0, 2, 4, 5, 6, 7, 1, 9, 10, 12, 14, 15, 16, 17, 18, 19, 20, 21, 24, 25, )
]],
#13
[[
( 0, 1, 2, 4, 5, 6, 7, 9, 10, 12, 14, 15, 16, 17, 18, 19, 20, 21, 24, ),
( 0, 1, 2, 4, 5, 6, 7, 9, 11, 12, 14, 15, 16, 17, 18, 20, 21, 22, 23, )
]],
#14
[[
( 0, 1, 2, 4, 5, 6, 7, 9, 11, 12, 14, 15, 16, 17, 18, 20, 21, 22, 23, ),
( 0, 1, 3, 4, 16, 17, 18, 5, 6, 7, 9, 10, 11, 12, 13, 15, 16, 17, 18, )
]]
]
def step_formula(self,
pre_write=[],
pos_write=[],
pre_fade=[],
pos_fade=[],
fade=[],
write=[],
changes=[[]],
path_arc=0,
n_step=0,
pre_copy=[],
pos_copy=[],
time_pre_changes=0.3,
time_pos_changes=0.3,
run_time=2,
time_end=0.3,
pre_order=["w","f"],
pos_order=["w","f"]
):
formula_copy=[]
for c in pre_copy:
formula_copy.append(self.formulas[n_step-1][c].copy())
for ani_ in pre_order:
if len(pre_write)>0 and ani_=="w":
self.play(*[Write(self.formulas[n_step-1][w])for w in pre_write])
if len(pre_fade)>0 and ani_=="f":
self.play(*[FadeOut(self.formulas[n_step-1][w])for w in pre_fade])
self.wait(time_pre_changes)
for pre_ind,post_ind in changes:
self.play(*[
ReplacementTransform(
self.formulas[n_step-1][i],self.formulas[n_step][j],
path_arc=path_arc
)
for i,j in zip(pre_ind,post_ind)
],
*[FadeOut(self.formulas[n_step-1][f])for f in fade if len(fade)>0],
*[Write(self.formulas[n_step][w])for w in write if len(write)>0],
*[ReplacementTransform(formula_copy[j],self.formulas[n_step][f])
for j,f in zip(range(len(pos_copy)),pos_copy) if len(pre_copy)>0
],
run_time=run_time
)
self.wait(time_pos_changes)
for ani_ in pos_order:
if len(pos_write)>0 and ani_=="w":
self.play(*[Write(self.formulas[n_step][w])for w in pos_write])
if len(pos_fade)>0 and ani_=="f":
self.play(*[FadeOut(self.formulas[n_step][w])for w in pos_fade])
self.wait(time_end)
|
AnimationsWithManim_Elteoremadebeethoven/English/9_project/scenes.md | #
## Programas
###
```python3
````
<p align="center"><img src ="/.gif" /></p>
###
```python3
````
<p align="center"><img src ="/.gif" /></p>
|
AnimationsWithManim_Elteoremadebeethoven/English/9_project/formulas_txt/formulas.py | from big_ol_pile_of_manim_imports import *
from tutorial.svg_classes import CheckFormulaByTXT
from io import *
formulas=[]
a_color=RED_B
b_color=BLUE_B
c_color=GREEN_B
x_color=YELLOW_B
for i in range(1,17):
formula_open=open("tutorial/formulas_txt/formula%de.txt"%i,"r")
formula=formula_open.readlines()
formulas.append(TexMobject(*formula).scale(1.7))
for i in range(10):
formulas[i].set_color_by_tex("a", a_color)
formulas[i].set_color_by_tex("b", b_color)
formulas[i].set_color_by_tex("c", c_color)
formulas[i].set_color_by_tex("x", x_color)
set_color_formulas=[
(10,
(
(a_color,[10,25,31]),
(b_color,[6,21]),
(c_color,[26]),
(x_color,[3]))
),
(11,
(
(a_color,[6,18,24]),
(b_color,[3,14]),
(c_color,[19]),
(x_color,[0]))
),
(12,
(
(a_color,[7,18,24]),
(b_color,[4,14]),
(c_color,[19]),
(x_color,[0]))
),
(13,
(
(a_color,[7,18,23]),
(b_color,[4,14]),
(c_color,[20]),
(x_color,[0]))
),
(14,
(
(a_color,[13,18]),
(b_color,[4,9]),
(c_color,[15]),
(x_color,[0]))
),
]
for f,changes in set_color_formulas:
for colors,symbols in changes:
for symbol in symbols:
formulas[f][symbol].set_color(colors)
''' Code:
class ConfigFormula(CheckFormulaByTXT):
CONFIG={
"show_elements":[],
"remove": [],
"text": formulas[]
}
'''
class ConfigFormula0(CheckFormulaByTXT):
CONFIG={
"show_elements":[],
"remove": [], #2
"text": formulas[0]
}
class ConfigFormula1(CheckFormulaByTXT):
CONFIG={
"show_elements":[],
"remove": [], #2
"text": formulas[1]
} |
AnimationsWithManim_Elteoremadebeethoven/English/extra/anim_into_up.py | from manimlib.imports import *
class ExampleFail(Scene):
def construct(self):
triangle = Triangle()
square = Square()
triangle.add_updater(lambda mob, dt: mob.shift(RIGHT * 0.1))
# triangle anim
anim1 = Write(triangle, run_time=1)
# square anim
anim2 = FadeIn(square, rate_func=there_and_back)
self.add(triangle)
turn_animation_into_updater(anim1)
self.wait(0.4)
self.add(square)
turn_animation_into_updater(anim2)
self.wait(3)
class ExamplePreSolution(Scene):
def construct(self):
triangle = Triangle()
square = Square()
frame = 1 / self.camera.frame_rate
def update_triangle(mob, dt):
if mob.get_x() < 3:
mob.shift(RIGHT * frame)
triangle.add_updater(update_triangle)
anim1 = Write(triangle,run_time=1)
anim2 = FadeIn(square,rate_func=there_and_back)
self.add(triangle)
turn_animation_into_updater(anim1)
self.wait(0.4)
self.add(square)
turn_animation_into_updater(anim2, cycle=True)
self.wait(3)
def update_move_mob_func(mob, end_coord, fps, run_time=2, func=linear):
DISTANCE = get_norm(mob.get_center() - end_coord)
VECTOR = end_coord - mob.get_center()
UNIT_VECTOR = normalize(VECTOR)
mob.start_time = 0
mob.start_coord = mob.get_center()
def update(mob, dt):
mob.start_time += fps
if mob.start_time < run_time:
alpha = mob.start_time / run_time
alpha_func = func(alpha)
mob.move_to(mob.start_coord)
mob.shift(UNIT_VECTOR * alpha_func * DISTANCE)
return update
class Example(Scene):
def construct(self):
text = TextMobject("Hello world")
fps = 1 / self.camera.frame_rate
update_text = update_move_mob_func(
text,
[1, 2, 0], # End point
fps, # fps
func=smooth,
run_time=3
)
text.add_updater(update_text)
anim = Write(text, run_time=3)
self.add(text)
turn_animation_into_updater(anim)
self.wait(5)
class Example2(Scene):
def construct(self):
triangle = Triangle()
square = Square()
triangle.add_updater(lambda mob, dt: mob.rotate(1 * DEGREES))
anim1 = FadeToColor(triangle, RED)
self.add(triangle)
cycle_animation(
anim1,
run_time=3,
rate_func=there_and_back
)
self.wait()
self.play(Write(TextMobject("Hello world!",height=1)))
self.wait(3)
triangle.clear_updaters()
self.play(FadeOut(triangle))
self.wait(2)
# INTRO VIDEO
class IntroVid(Scene):
def construct(self):
text = TextMobject("Hello world!").scale(2)
text.shift(LEFT * 2)
frame = 1 / self.camera.frame_rate
update_text = update_move_mob_func(
text,
text.get_center() + np.array([4, 0, 0]), # End point
frame, # fps
func=smooth,
run_time=3
)
self.add(text)
turn_animation_into_updater(anim)
self.wait(5)
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/complex_examples.py |
from manimlib.imports import *
# INDEX:
# Mnemonics - 20
# Sin interface - 158
# Sum vectors - 662
# Angle inscr - 936
# Sine laws - 1733
class Sqrt2(VGroup):
def __init__(self, n, **kwargs):
super().__init__(**kwargs)
body = TexMobject("\\frac{\\sqrt{%s}}{2}"%n)[0]
number = body[2]
self.top = body[:3]
body.remove(body[2])
self.add(body,number)
class Mnemonics(Scene):
def construct(self):
# MOBS DEFINITIONS ----------------------------------
l_buff = 1.2
left_labels = VGroup(*[
TextMobject(t) for t in ["Radians:","Degrees:","sin","cos","tan"]
])
left_labels.arrange(DOWN,buff=l_buff)
radians_grp = VGroup(*[
TexMobject(t) for t in ["0",*["\\frac{\\pi}{%s}"%n for n in [6,4,3,2]]]
])
radians_grp.arrange(RIGHT,buff=l_buff)
radians_grp.next_to(left_labels[0],RIGHT,buff=l_buff)
degrees_grp = VGroup(*[
TexMobject(f"{t}^\\circ") for t in [0,30,45,60,90]
])
# TRIG PRE
sin_vals = VGroup(*[
Sqrt2(n) for n in range(5)
])
cos_vals = sin_vals.deepcopy()
cos_vals = cos_vals[::-1]
tan_vals = VGroup(*[
TexMobject("\\frac{\\sqrt{%s}}{\\sqrt{%s}}"%(n,d))[0]
for n,d in zip(range(5),list(range(5))[::-1])
])
# TRIG POST
sin_vals_p = VGroup(*[
TexMobject(t)[0] for t in ["0","\\frac{1}{2}","\\frac{\\sqrt{2}}{2}","\\frac{\\sqrt{3}}{2}","1"]
])
cos_vals_p = VGroup(*[
TexMobject(t)[0] for t in ["0","\\frac{1}{2}","\\frac{\\sqrt{2}}{2}","\\frac{\\sqrt{3}}{2}","1"][::-1]
])
tan_vals_p = VGroup(*[
TexMobject(t)[0] for t in ["0","\\frac{\\sqrt{3}}{3}","1","\\sqrt{3}","\\infty"]
])
degrees_grp.next_to(left_labels[1],RIGHT,buff=1.2)
all_grp = VGroup(
left_labels,
radians_grp,
degrees_grp,
sin_vals,
cos_vals,
tan_vals,
sin_vals_p,
cos_vals_p,
tan_vals_p,
)
all_grp.move_to(ORIGIN)
# - Order the values
for i in range(len(degrees_grp)):
for j,mob in zip(range(1,5),[degrees_grp,sin_vals,cos_vals,tan_vals]):
mob[i].set_x(radians_grp[i].get_x())
mob[i].set_y(left_labels[j].get_y())
for i in range(len(degrees_grp)):
for j,mob in zip(range(2,5),[sin_vals_p,cos_vals_p,tan_vals_p]):
mob[i].set_x(radians_grp[i].get_x())
mob[i].set_y(left_labels[j].get_y())
v_l_buff = 0.5*UP
h_l_buff = 0.7*RIGHT
v_line = Line(left_labels.get_corner(UR)+v_l_buff*0.9,left_labels.get_corner(DR)-v_l_buff)
v_line.shift(RIGHT*0.6)
h_line = Line(all_grp.get_corner(UL)-h_l_buff,all_grp.get_corner(UR)+h_l_buff)
h_line.set_y(v_line.get_start()[1])
h_line_d = h_line.deepcopy().set_y(v_line.get_end()[1])
h_lines = VGroup(h_line,h_line_d)
for i in range(1,4):
line = h_line.copy()
line.set_y((left_labels[i].get_y()+left_labels[i+1].get_y())/2)
h_lines.add(line)
# self.add(*all_grp,v_line,h_lines)
# ----------------------------------------------
# ANIMATIONS -----------------------------------
# ----------------------------------------------
self.play(
LaggedStart(*list(map(GrowFromCenter,[v_line,*h_lines])),run_time=2.5,lag_ratio=0),
Write(left_labels,run_time=2.5),
Write(radians_grp,run_time=2.5),
Write(degrees_grp,run_time=2.5),
)
self.wait()
s_grp = VGroup(*[f[0] for f in sin_vals])
c_grp = VGroup(*[f[0] for f in cos_vals])
s_vals = VGroup(*[f[1] for f in sin_vals])
c_vals = VGroup(*[f[1] for f in cos_vals])[::-1]
self.play(
Write(s_grp),
Write(c_grp),
run_time=3.5
)
self.wait()
self.play(Write(s_vals),run_time=4)
self.play(Write(c_vals),run_time=4)
self.wait()
LAG_RATIO = 0.4
PATH_ARC = 120*DEGREES
self.play(
LaggedStart(*[
Write(tv[3])
for tv in tan_vals
],lag_ratio=LAG_RATIO*3.2),
LaggedStart(*[
TransformFromCopy(sn,tv[:3],path_arc=PATH_ARC,run_time=3)
for sn,tv in zip([t.top for t in sin_vals],tan_vals)
],lag_ratio=LAG_RATIO),
LaggedStart(*[
TransformFromCopy(cn,tv[4:],path_arc=PATH_ARC,run_time=3)
for cn,tv in zip([t.top for t in cos_vals],tan_vals)
],lag_ratio=LAG_RATIO),
)
self.wait()
LAG_RATIO = 0.4
self.play(
AnimationGroup(
LaggedStart(*[
ReplacementTransform(sv,svp)
for sv,svp in zip(sin_vals,sin_vals_p)
],lag_ratio=LAG_RATIO),
LaggedStart(*[
ReplacementTransform(sv,svp)
for sv,svp in zip(cos_vals,cos_vals_p)
],lag_ratio=LAG_RATIO),
LaggedStart(*[
ReplacementTransform(sv,svp)
for sv,svp in zip(tan_vals,tan_vals_p)
],lag_ratio=LAG_RATIO),
lag_ratio=0.8
)
)
self.wait(3)
self.play(*list(map(FadeOut,self.mobjects)))
self.wait()
# ---------------------------------------------
# ---------------------------------------------
# ---------------------------------------------
class SumVectors(Scene):
CONFIG = {
"dot_config": {"fill_opacity": 0},
"total_time": 35,
"velocity": [0.01,0.038,0.02]
}
def construct(self):
number_plane = NumberPlane()
# PATHS
path_1 = Circle(radius=1.7).rotate(PI/4)
path_1.add_updater(lambda mob,dt: mob.rotate(dt*0.1))
path_2 = Square().set_width(4.5).rotate(-PI*1.2/2)
path_2.add_updater(lambda mob,dt: mob.rotate(dt*0.1))
path_3 = Ellipse().scale([7,6,1]).rotate(20*DEGREES)
path_3.t_offset = 0
# path_3.add_updater(lambda mob,dt: mob.rotate(dt*0.05))
paths = VGroup(path_1,path_2,path_3).fade(1)
# DOTS
dot_1 = Dot(**self.dot_config)
dot_1.t_offset = 0
dot_1.add_updater(self.add_updater_path(path_1,self.velocity[0]))
dot_2 = Dot(**self.dot_config)
dot_2.t_offset = 0
dot_2.add_updater(self.add_updater_path(path_2,self.velocity[1],0.15))
dot_3 = Dot(**self.dot_config)
dot_3.t_offset = 0
dot_3.add_updater(self.add_updater_path(path_3,self.velocity[2],-0.2))
# Vectors
vec_kwargs = {
"background_stroke_color": YELLOW,
"background_stroke_opacity": 1,
"background_stroke_width": 3,
}
vec_x_kwargs = {
"background_stroke_color": RED_A,
"background_stroke_opacity": 1,
"background_stroke_width": 3,
}
vec_y_kwargs = {
"background_stroke_color": PURPLE_A,
"background_stroke_opacity": 1,
"background_stroke_width": 3,
}
vec_1 = Arrow(buff=0,**vec_kwargs)
vec_1.add_updater(lambda mob: mob.put_start_and_end_on(ORIGIN,dot_1.get_center()))
vec_2 = Arrow(buff=0,color=BLUE,**vec_kwargs)
vec_2.add_updater(lambda mob: mob.put_start_and_end_on(dot_1.get_center(),dot_2.get_center()))
vec_3 = Arrow(buff=0,color=RED,**vec_kwargs)
vec_3.add_updater(lambda mob: mob.put_start_and_end_on(dot_2.get_center(),dot_3.get_center()))
VGroup(vec_1,vec_2,vec_3).set_style(**vec_kwargs)
# Proy Vectors
ST_OP = 1
vec_1_x = Arrow(buff=0,stroke_opacity=ST_OP,fill_opacity=ST_OP,**vec_x_kwargs)
vec_1_x.add_updater(lambda mob: mob.put_start_and_end_on(ORIGIN,[vec_1.get_end()[0],0,0]))
vec_1_y = Arrow(buff=0,stroke_opacity=ST_OP,fill_opacity=ST_OP,**vec_y_kwargs)
vec_1_y.add_updater(lambda mob: mob.put_start_and_end_on(ORIGIN,[0,vec_1.get_end()[1],0]))
# -----------------
vec_2_x = Arrow(buff=0,color=BLUE,stroke_opacity=ST_OP,fill_opacity=ST_OP,**vec_x_kwargs)
vec_2_x.add_updater(lambda mob: mob.put_start_and_end_on(
vec_1_x.get_end()+UP*0.1,
[vec_2.get_end()[0], 0.1,0]
))
vec_2_y = Arrow(buff=0,color=BLUE,stroke_opacity=ST_OP,fill_opacity=ST_OP,**vec_y_kwargs)
vec_2_y.add_updater(lambda mob: mob.put_start_and_end_on(
vec_1_y.get_end()+RIGHT*0.1,
[0.1,vec_2.get_end()[1],0]
))
# -----------------
vec_3_x = Arrow(buff=0,color=RED,stroke_opacity=ST_OP,fill_opacity=ST_OP,**vec_x_kwargs)
vec_3_x.add_updater(lambda mob: mob.put_start_and_end_on(
vec_2_x.get_end()-UP*0.2,
[vec_3.get_end()[0],-0.1,0]
))
vec_3_y = Arrow(buff=0,color=RED,stroke_opacity=ST_OP,fill_opacity=ST_OP,**vec_y_kwargs)
vec_3_y.add_updater(lambda mob: mob.put_start_and_end_on(
vec_2_y.get_end()-RIGHT*0.2,
[-0.1,vec_3.get_end()[1],0]
))
# -----------------
VGroup(vec_1_x,vec_1_y,vec_2_x,vec_2_y,vec_3_x,vec_3_y).fade(0.2)
VGroup(vec_1_x,vec_2_x,vec_3_x).set_style(**vec_x_kwargs)
VGroup(vec_1_y,vec_2_y,vec_3_y).set_style(**vec_y_kwargs)
# Proy lines
x_line = DashedLine()
x_line.add_updater(lambda mob: mob.become(DashedLine(vec_3_x.get_end(),vec_3.get_end())))
y_line = DashedLine()
y_line.add_updater(lambda mob: mob.become(DashedLine(vec_3_y.get_end(),vec_3.get_end())))
updater_grp = VGroup(
path_1,
path_2,
path_3,
dot_1,
dot_2,
dot_3,
vec_1,
vec_2,
vec_3,
vec_1_x,
vec_1_y,
vec_2_x,
vec_2_y,
vec_3_x,
vec_3_y,
x_line,
y_line,
)
for mob in updater_grp:
mob.update()
mob.suspend_updating()
self.add(
number_plane,
dot_1,
dot_2,
dot_3,
path_1,
path_2,
path_3,
)
# -----------------------
self.add(vec_1)
self.play(
GrowArrow(vec_1),
run_time=2.2,
)
self.add(vec_1_x,vec_1_y)
self.play(
TransformFromCopy(vec_1,vec_1_x),
TransformFromCopy(vec_1,vec_1_y),
run_time=2.2,
)
# -----------------------
self.add(vec_2)
self.play(
GrowArrow(vec_2),
run_time=2.2,
)
self.add(vec_2_x,vec_2_y)
self.play(
TransformFromCopy(vec_2,vec_2_x),
TransformFromCopy(vec_2,vec_2_y),
run_time=2.2,
)
# -----------------------
self.add(vec_3)
self.play(
GrowArrow(vec_3),
run_time=2.2,
)
self.add(vec_3_x,vec_3_y)
self.play(
TransformFromCopy(vec_3,vec_3_x),
TransformFromCopy(vec_3,vec_3_y),
run_time=2.2,
)
self.wait()
# .........................
self.play(
*list(map(ShowCreation,[x_line,y_line]))
)
self.wait()
for mob in updater_grp:
# mob.update()
mob.resume_updating()
self.wait(self.total_time)
def add_updater_path(self,path,vel=1,shift=0):
path.count = 0
def update(mob,dt):
if path.count == 0:
mob.t_offset += (dt * vel + shift)
path.count += 1
mob.t_offset += (dt * vel)
alpha = mob.t_offset % 1
mob.move_to(path.point_from_proportion(alpha))
return update
# -------------------------------------------
# -------------------------------------------
# -------------------------------------------
class DecimalTextNumber(VMobject):
CONFIG = {
"num_decimal_places": 2,
"include_sign": False,
"group_with_commas": True,
"digit_to_digit_buff": 0.05,
"show_ellipsis": False,
"unit_type": "font", # tex or font
"unit": None, # Aligned to bottom unless it starts with "^"
"unit_custom_position": lambda mob: mob.set_color(GREEN).shift(RIGHT*0.1),
"include_background_rectangle": False,
"edge_to_fix": LEFT,
"unit_config": {
"font": "Digital-7",
"stroke_width": 0,
},
"number_config": {
"font": r"Digital-7",
"stroke_width": 0,
}
}
def __init__(self, number=0, **kwargs):
super().__init__(**kwargs)
self.number = number
self.initial_config = kwargs
if isinstance(number, complex):
formatter = self.get_complex_formatter()
else:
formatter = self.get_formatter()
num_string = formatter.format(number)
rounded_num = np.round(number, self.num_decimal_places)
if num_string.startswith("-") and rounded_num == 0:
if self.include_sign:
num_string = "+" + num_string[1:]
else:
num_string = num_string[1:]
self.add(*[
Text(char,color=self.color,**self.number_config)
for char in num_string
])
# Add non-numerical bits
if self.show_ellipsis:
self.add(SingleStringTexMobject("\\dots"))
if num_string.startswith("-"):
minus = self.submobjects[0]
minus.next_to(
self.submobjects[1], LEFT,
buff=self.digit_to_digit_buff
)
self.num_string = num_string
if self.unit is not None:
if self.unit_type == "font":
self.unit_sign = Text(self.unit,**self.unit_config)
elif self.unit_type == "tex":
del self.unit_config["font"]
self.unit_sign = TexMobject(self.unit,**self.unit_config)
self.add(self.unit_sign)
self.arrange(
buff=self.digit_to_digit_buff,
aligned_edge=DOWN
)
# Handle alignment of parts that should be aligned
# to the bottom
for i, c in enumerate(num_string):
if c == "-" and len(num_string) > i + 1:
self[i].align_to(self[i + 1], UP)
self[i].shift(self[i+1].get_height() * DOWN / 2)
elif c == ",":
self[i].shift(self[i].get_height() * DOWN / 2)
if self.unit and self.unit.startswith("^"):
self.unit_sign.align_to(self, UP)
#
if self.include_background_rectangle:
self.add_background_rectangle()
self.unit_custom_position(self.unit_sign)
# if num_string[0] == "-" or num_string[0] == "+":
# self[0].set_width(0.2)
# self[0].set_color(RED)
def get_formatter(self, **kwargs):
config = dict([
(attr, getattr(self, attr))
for attr in [
"include_sign",
"group_with_commas",
"num_decimal_places",
]
])
config.update(kwargs)
return "".join([
"{",
config.get("field_name", ""),
":",
"+" if config["include_sign"] else "",
"," if config["group_with_commas"] else "",
".", str(config["num_decimal_places"]), "f",
"}",
])
def get_complex_formatter(self, **kwargs):
return "".join([
self.get_formatter(field_name="0.real"),
self.get_formatter(field_name="0.imag", include_sign=True),
"i"
])
def set_value(self, number, **config):
full_config = dict(self.CONFIG)
full_config.update(self.initial_config)
full_config.update(config)
new_decimal = DecimalTextNumber(number, **full_config)
# Make sure last digit has constant height
#new_decimal.scale(
# self[-1].get_height() / new_decimal[-1].get_height()
#)
#"""
height = new_decimal.get_height()
yPos = new_decimal.get_center()[1]
for nr in new_decimal:
if "." != nr.text :
nr.scale(height/nr.get_height())
nr.shift([0,(yPos-nr.get_center()[1]),0])
max_width = max(*[f.get_width() for f in new_decimal[1:]])
if new_decimal[0].text == "-" or new_decimal[0].text == "+":
new_decimal[0].set_width(max_width)
new_decimal[0].set_color(RED)
#"""
new_decimal.move_to(self, self.edge_to_fix)
new_decimal.match_style(self)
old_family = self.get_family()
self.submobjects = new_decimal.submobjects
for mob in old_family:
# Dumb hack...due to how scene handles families
# of animated mobjects
mob.points[:] = 0
self.number = number
# if num_string[0] == "-" or num_string[0] == "+":
# self[0].set_width(0.2)
# self[0].set_color(RED)
return self
def get_value(self):
return self.number
def increment_value(self, delta_t=1):
self.set_value(self.get_value() + delta_t)
class ChangingDecimalText(Animation):
CONFIG = {
"suspend_mobject_updating": False,
}
def __init__(self, decimal_mob, number_update_func, **kwargs):
self.check_validity_of_input(decimal_mob)
self.yell_about_depricated_configuration(**kwargs)
self.number_update_func = number_update_func
super().__init__(decimal_mob, **kwargs)
def check_validity_of_input(self, decimal_mob):
if not isinstance(decimal_mob, DecimalTextNumber):
raise Exception(
"ChangingDecimal can only take "
"in a DecimalNumber"
)
def yell_about_depricated_configuration(self, **kwargs):
# Obviously this would optimally be removed at
# some point.
for attr in ["tracked_mobject", "position_update_func"]:
if attr in kwargs:
warnings.warn("""
Don't use {} for ChangingDecimal,
that functionality has been depricated
and you should use a mobject updater
instead
""".format(attr)
)
def interpolate_mobject(self, alpha):
self.mobject.set_value(
self.number_update_func(alpha)
)
class ChangeDecimalToValueText(ChangingDecimalText):
def __init__(self, decimal_mob, target_number, **kwargs):
start_number = decimal_mob.number
super().__init__(
decimal_mob,
lambda a: interpolate(start_number, target_number, a),
**kwargs
)
class Grid(VGroup):
CONFIG = {
"height": 6.0,
"width": 6.0,
"line_kwargs": {}
}
def __init__(self, rows, columns, **kwargs):
digest_config(self, kwargs, locals())
self.rows = rows
self.columns = columns
super().__init__(**kwargs)
x_step = self.width / self.columns
y_step = self.height / self.rows
for x in np.arange(0, self.width + x_step, x_step):
self.add(DashedLine(
[x - self.width / 2., -self.height / 2., 0],
[x - self.width / 2., self.height / 2., 0],
**self.line_kwargs
))
for y in np.arange(0, self.height + y_step, y_step):
self.add(DashedLine(
[-self.width / 2., y - self.height / 2., 0],
[self.width / 2., y - self.height / 2., 0],
**self.line_kwargs
))
class SinInterface(VGroup):
CONFIG = {
"x_size": 16,
"y_size": 6,
"axes_config":{
"x_min": -7,
"x_max": 7,
"y_min": -2.5,
"y_max": 2.5,
"axis_config": {
"color": LIGHT_GREY,
"include_tip": False,
"exclude_zero_from_default_numbers": False,
"decimal_number_config": {
"num_decimal_places": 1,
},
},
"x_axis_config": {
"unit_size":0.8,
},
"y_axis_config": {
"label_direction": LEFT,
"unit_size":0.8,
# "x_min": -2.5,
# "x_max": 2.5,
},
"center_point": ORIGIN,
},
"margin": 1,
"x_margin": 1.2,
"y_margin": None,
"grid_kwargs": {
"stroke_width": 0.5
}
}
def __init__(self, **kwargs):
digest_config(self, kwargs)
super().__init__(**kwargs)
if self.x_size != None:
self.axes_config["x_max"] = self.x_size / 2
self.axes_config["x_min"] = -self.x_size / 2
if self.y_size != None:
self.axes_config["y_max"] = self.y_size / 2
self.axes_config["y_min"] = -self.y_size / 2
axes = Axes(**self.axes_config)
inner_margin = RoundedRectangle(
width=axes.get_width(),
height=axes.get_height(),
fill_opacity=1,
fill_color=BLACK,
stroke_width=0,
stroke_color=WHITE,
)
if self.x_margin == None:
self.x_margin = self.margin
if self.y_margin == None:
self.y_margin = self.margin
# print(self.y_margin)
outer_margin = Rectangle(
width=axes.get_width()+self.x_margin,
height=axes.get_height()+self.y_margin,
fill_opacity=1,
fill_color="#AAAAAA",
stroke_width=0,
stroke_color=WHITE,
)
axes[0].add_numbers()
axes[1].add_numbers()
axes[0][-1].remove(axes[0][-1][0])
axes[0][-1].set_y((inner_margin.get_bottom()[1]+outer_margin.get_bottom()[1])/2)
axes[1][-1].remove(axes[1][-1][0])
axes[1][-1].set_x((inner_margin.get_left()[0]+outer_margin.get_left()[0])/2)
# left_side = axes[1][-1].get_right()
# for n in axes[1][-1]:
# n[:].align_to(inner_margin,RIGHT)
VGroup(axes[0][-1],axes[1][-1]).set_color(BLACK)
for i in [*axes[0][-1],*axes[1][-1]]:
i.scale(0.5)
columns = self.x_size
rows = self.y_size
grid = Grid(rows, columns,width=self.x_size,height=self.y_size,line_kwargs=self.grid_kwargs)
grid.set_width(inner_margin.get_width())
grid.move_to(inner_margin)
self.axes = axes
self.add(outer_margin,inner_margin,grid,axes)
class SinFunctionInterface(Scene):
def construct(self):
A_COLOR = YELLOW
K_COLOR = RED
W_COLOR = TEAL
PHI_COLOR = BLUE
X_COLOR = PURPLE
T_COLOR = GREEN
interface = SinInterface()
interface.to_edge(DOWN,buff=0.2)
axes = interface.axes
# f(x,t) = A * sin(k*x + w*t + s)
A = ValueTracker(1)
k = ValueTracker(1)
w = ValueTracker(1)
s = ValueTracker(0)
t = ValueTracker(0)
graph = axes.get_graph(lambda t: np.sin(t),color=RED)
graph.add_updater(lambda mob: mob.become(
axes.get_graph(
lambda x: A.get_value() * np.sin(
k.get_value() * x + w.get_value() * t.get_value() + s.get_value()
),
color=RED)
))
graph.t_offset = 0
labels = VGroup(
self.get_range_line(-2,2,A,"A",A_COLOR),
self.get_range_line(-2,2,s,"\\phi",PHI_COLOR),
self.get_range_line(-2,2,k,"k",K_COLOR),
self.get_range_line(-2,2,w,"\\omega",W_COLOR),
)
max_tex_width = max(*[l[1].get_width() for l in labels])
for l in range(len(labels)):
line = labels[l][0]
line.align_to(labels[l],LEFT)
line.shift(RIGHT*max_tex_width+0.2*RIGHT)
labels[l][-1].next_to(labels[l][0],RIGHT,0.3)
labels.scale(0.8)
labels.arrange(DOWN,buff=0.2,aligned_edge=LEFT)
labels.to_edge(UP,buff=0.1)
labels.to_edge(LEFT)
# -----------------
t_tex = TexMobject("t",color=T_COLOR)
t_dig = DecimalTextNumber(0,num_decimal_places=3)
t_dig.add_updater(lambda mob: mob.set_value(t.get_value()))
tg = VGroup(t_tex,t_dig).arrange(RIGHT,buff=0.6)
tg_r = Rectangle(width=tg.get_width()+0.3,height=tg.get_height()+0.3)
tg.add(tg_r)
tg.next_to(interface,UP)
tg_l = Line(tg.get_corner(UL),tg.get_corner(DL))
tg_l.next_to(t_tex,RIGHT,buff=abs(tg.get_left()-t_tex.get_left())[0])
tg.add(tg_l)
tg.shift(RIGHT*interface.get_width()/4)
# -------------------
formula = TexMobject(
"y(x,t)=A\\ \\!{\\rm sin}(kx+\\omega t+\\phi)",
tex_to_color_map={
"A": A_COLOR, "k": K_COLOR, "\\omega": W_COLOR, "\\phi": PHI_COLOR,
"x": X_COLOR, "t": T_COLOR
},
)
formula.next_to(tg,UP)
self.play(Write(interface))
self.play(Write(labels),Write(graph))
self.play(Write(tg),Write(formula))
self.add(interface,graph,tg,formula,*labels)
self.wait()
# self.play(ChangeDecimalToValueText(t,1),run_time=2)
RUN_TIME = 4
self.play(A.set_value,1.9,run_time=RUN_TIME)
self.wait(4)
self.play(s.set_value,0.5,run_time=RUN_TIME)
self.wait(4)
self.play(s.set_value,-1.5,run_time=RUN_TIME)
self.wait(4)
self.play(k.set_value,-0.4,run_time=RUN_TIME)
self.wait(4)
self.play(k.set_value,1.7,run_time=RUN_TIME)
self.wait(4)
self.play(Indicate(t_tex),FocusOn(t_tex.get_center()))
self.wait(0.5)
def update_t(mob,dt):
graph.t_offset+= dt * 0.3
mob.set_value(graph.t_offset)
t.add_updater(update_t)
self.add(t)
self.wait(8)
self.play(w.set_value,2,run_time=RUN_TIME)
self.wait(7)
self.play(w.set_value,-1.1,run_time=RUN_TIME)
self.wait(7)
self.play(
A.set_value,-1.7,
k.set_value,0.8,
run_time=RUN_TIME,
)
self.wait(7)
def get_range_line(self,
start,
end,
vt,
tex="\\alpha",
color=WHITE,
tex_config={},
line_config={}
):
line_config["numbers_with_elongated_ticks"] = []
line = NumberLine(x_min=start,x_max=end,**line_config)
tex_ = TexMobject(tex,**tex_config)
tex_.next_to(line,LEFT)
dot = Dot()
dot.add_updater(lambda mob: mob.move_to(line.n2p(vt.get_value())))
digital = DecimalTextNumber(0,num_decimal_places=3,include_sign=True)
digital.add_updater(lambda mob: mob.set_value(vt.get_value()))
digital.next_to(line,RIGHT)
VGroup(line,tex_,digital).set_color(color)
return VGroup(line,tex_,dot,digital)
# --------------------------------------------------------
# --------------------------------------------------------
# --------------------------------------------------------
class CircleWithAngles(VGroup):
CONFIG = {
"inner_line_config": {"color":PURPLE_A},
"outer_line_config": {"color":TEAL_A},
"inner_arc_config": {"color":PURPLE_A},
"outer_arc_config": {"color":TEAL_A},
"tex_1_config": {"color": TEAL_A},
"tex_2_config": {"color": PURPLE_A},
}
def __init__(self, radius=3, ang1=30, ang2=130, ang3=260, small_radius=0.4, **kwargs):
digest_config(self, kwargs)
super().__init__(**kwargs)
circle = Circle(radius=radius)
vt_1 = ValueTracker(ang1)
vt_2 = ValueTracker(ang2)
vt_3 = ValueTracker(ang3)
p1 = Dot(circle.point_at_angle(ang1*DEGREES))
p2 = Dot(circle.point_at_angle(ang2*DEGREES))
p3 = Dot(circle.point_at_angle(ang3*DEGREES))
in_lines = VMobject(**self.inner_line_config)
# ------------- LINES
out_lines = VMobject(**self.outer_line_config)
# ------------- ANGLES
out_arc = self.get_arc_between_lines(small_radius,p1,p2,p3)
in_arc = self.get_inner_angle(small_radius,p1,p2,p3,circle)
# ------------- LABELS
theta_2 = TexMobject("2\\theta",**self.tex_2_config)
theta_1 = TexMobject("\\theta",**self.tex_1_config)
# ------------- Equals
theta_1_val = DecimalTextNumber(0,unit="deg",num_decimal_places=3,**self.tex_1_config)
theta_2_val = DecimalTextNumber(0,unit="deg",num_decimal_places=3,**self.tex_2_config)
equal = Text("= 2 * ",font="Digital-7")
theta_eq = VGroup(theta_1_val, equal, theta_2_val)
theta_eq_temp = VGroup(theta_1_val, equal, theta_2_val)
theta_eq.arrange(RIGHT,buff=0.6,aligned_edge=DOWN)
theta_2_val.shift(LEFT*max(*[f.get_width() for f in theta_2_val])*1)
rectangle = Rectangle(width=theta_eq.get_width()+0.2,height=theta_eq.get_height()+0.2)
rectangle.move_to(theta_eq)
theta_eq.add(rectangle)
# UPDATERS
p1.add_updater(lambda mob: mob.move_to(circle.point_at_angle(vt_1.get_value()*DEGREES)))
p2.add_updater(lambda mob: mob.move_to(circle.point_at_angle(vt_2.get_value()*DEGREES)))
p3.add_updater(lambda mob: mob.move_to(circle.point_at_angle(vt_3.get_value()*DEGREES)))
in_lines.add_updater(lambda mob: mob.set_points_as_corners([
p1.get_center(),circle.get_center(),p2.get_center()
]))
out_lines.add_updater(lambda mob: mob.set_points_as_corners([
p1.get_center(),p3.get_center(),p2.get_center()
]))
out_arc.add_updater(lambda mob: mob.become(self.get_arc_between_lines(small_radius,p1,p2,p3)))
in_arc.add_updater(lambda mob: mob.become(self.get_inner_angle(small_radius,p1,p2,p3,circle)))
theta_1.add_updater(
lambda mob: mob.move_to(
p3.get_center()+Line(p3.get_center(),out_arc.point_from_proportion(0.5)).get_vector()*1.7)
)
theta_2.add_updater(
lambda mob: mob.move_to(
circle.get_center()+Line(circle.get_center(),in_arc.point_from_proportion(0.5)).get_vector()*1.7)
)
theta_1_val.add_updater(lambda mob: mob.set_value(self.get_inner_angle(1,p1,p2,p3,circle,False)*180/PI))
theta_2_val.add_updater(lambda mob: mob.set_value(self.get_arc_between_lines(1,p1,p2,p3,False)*180/PI))
rectangle.max_width = rectangle.get_width()
def rect_up(mob):
line = Line(theta_eq_temp.get_left()+LEFT*0.2,theta_eq_temp.get_right()+RIGHT*0.2)
if line.get_width() > mob.max_width:
mob.max_width = line.get_width()
mob.set_width(mob.max_width)
# mob.move_to(line)
mob.align_to(theta_1_val,LEFT)
mob.shift(LEFT*0.1)
rectangle.add_updater(rect_up)
# ------------- Groups
dots = VGroup(p1,p2,p3)
vts = Group(vt_1,vt_2,vt_3)
self.vts = vts
self.add(
circle,dots,
in_lines,out_lines,
in_arc,out_arc,
theta_1,theta_2,
theta_eq,
)
def get_arc_between_lines(self, radius, d1, d2, center,mob=True):
line1 = Line(center.get_center(),d1.get_center())
line2 = Line(center.get_center(),d2.get_center())
h = Line(center.get_center(),center.get_center()+RIGHT)
angle = angle_between_vectors(line1.get_unit_vector(),line2.get_unit_vector())
h1 = angle_between_vectors(h.get_unit_vector(),line1.get_unit_vector())
h2 = angle_between_vectors(h.get_unit_vector(),line2.get_unit_vector())
if line1.get_angle() <= line2.get_angle():
start_angle = h1
else:
start_angle = h2
arc = Arc(start_angle, angle,radius=radius,arc_center=center.get_center(),**self.outer_arc_config)
if mob:
return arc
else:
return angle
def get_inner_angle(self, radius,d1,d2,out_center,in_center,mob=True):
line1 = Line(out_center.get_center(),d1.get_center())
line2 = Line(out_center.get_center(),d2.get_center())
h = Line(out_center.get_center(),out_center.get_center()+RIGHT)
angle = angle_between_vectors(line1.get_unit_vector(),line2.get_unit_vector())
v1 = Line(in_center.get_center(),d1.get_center())
start_angle = angle_between_vectors(h.get_unit_vector(),v1.get_unit_vector())
arc = Arc(start_angle, angle*2,radius=radius,arc_center=in_center.get_center(),**self.inner_arc_config)
if mob:
return arc
else:
return angle*2
class ArcBetweenVectors(Arc):
def __init__(self, radius, d1, d2, center, invert_angle=False,**kwargs):
line1 = Line(center.get_center(),d1.get_center())
line2 = Line(center.get_center(),d2.get_center())
h = Line(center.get_center(),center.get_center()+RIGHT)
angle = angle_between_vectors(line1.get_unit_vector(),line2.get_unit_vector())
h1 = angle_between_vectors(h.get_unit_vector(),line1.get_unit_vector())
h2 = angle_between_vectors(h.get_unit_vector(),line2.get_unit_vector())
if line1.get_angle() <= line2.get_angle():
start_angle = h1
else:
start_angle = h2
if invert_angle:
start_angle = -start_angle
super().__init__(start_angle, angle,radius=radius,arc_center=center.get_center(), **kwargs)
def get_angle(self):
return self.angle
class LabelFromArc(TexMobject):
CONFIG = {
"distance_proportion": 1.2
}
def __init__(self, arc, tex_height, *tex_strings, **kwargs):
super().__init__(*tex_strings, **kwargs)
self.set_height(tex_height)
center = arc.get_arc_center()
max_size = max(self.get_width(),self.get_height()) * self.distance_proportion/ 2
vector = Line(center,arc.point_from_proportion(0.5)).get_vector()
end_coord = center+vector + normalize(vector)*max_size
self.move_to(end_coord)
class InscribedAngle(MovingCameraScene):
def construct(self):
circle_grp = CircleWithAngles()
v1, v2, v3 = circle_grp.vts
eq = circle_grp[-1]
circle_grp.to_edge(LEFT,buff=1)
eq.to_edge(RIGHT,buff=1)
for mob in circle_grp:
mob.suspend_updating()
mob.update()
self.play(Write(circle_grp))
for mob in circle_grp:
mob.resume_updating()
self.wait()
self.play(v1.set_value,-10,run_time=3,rate_func=linear)
self.wait()
self.play(v2.set_value,225,run_time=5,rate_func=there_and_back)
self.wait()
self.play(
v1.set_value,47,
v2.set_value,110,
v3.set_value,335,
run_time=3,
rate_func=there_and_back
)
self.wait()
circle_grp.remove(eq)
self.play(
FadeOut(eq),
circle_grp[0].scale,0.64,
circle_grp[0].move_to,ORIGIN,
circle_grp[0].to_edge,DOWN,{"buff":0.2}
)
self.wait()
# ---------------------- Transform 2theta by varphi
theta_2 = circle_grp[-1]
varphi = TexMobject("\\varphi")
varphi.match_color(theta_2)
varphi.move_to(theta_2)
varphi.match_updaters(theta_2)
self.play(Transform(theta_2,varphi))
self.wait()
# ---------------------- Cases
titles = VGroup(*[
TextMobject(f) for f in ["Case 1", "Case 2", "Case 3"]
])
titles.arrange(RIGHT,buff=3).to_edge(UP)
# ---------------------- Case 1
self.play(Write(titles[0]))
self.wait()
self.play(
v1.set_value,40,
v2.set_value,290-180,
v3.set_value,290,
run_time=3,
)
case_1 = circle_grp.deepcopy()
case_1.clear_updaters()
self.play(
case_1.set_width,2,
case_1.next_to,titles[0],DOWN,buff=0.2
)
self.wait()
self.bring_to_front(case_1[1])
# ---------------------- Case 2
self.play(Write(titles[1]))
self.wait()
self.play(
v1.set_value,30,
v2.set_value,140,
v3.set_value,260,
run_time=3,
)
self.wait()
case_2 = circle_grp.deepcopy()
case_2.clear_updaters()
self.play(
case_2.set_width,2,
case_2.next_to,titles[1],DOWN,buff=0.2
)
self.wait()
self.bring_to_front(case_2[1])
# ---------------------- Case 3
self.play(Write(titles[2]))
self.wait()
self.play(
v1.set_value,30,
v2.set_value,90,
v3.set_value,325,
run_time=3,
)
case_3 = circle_grp.deepcopy()
case_3.clear_updaters()
self.bring_to_front(case_3[1])
self.wait()
self.play(
case_3.set_width,2,
case_3.next_to,titles[2],DOWN,buff=0.2
)
# ---------------------- Remove updaters
circle_grp.clear_updaters()
self.play(Write(circle_grp,rate_func=lambda t: smooth(1-t),run_time=2.5))
self.wait()
# ------------ Case by case
cases = VGroup(case_1,case_2,case_3)
SCREEN = Rectangle(width=FRAME_WIDTH,height=FRAME_HEIGHT)
grps = VGroup(*[VGroup(t,c) for t,c in zip(titles,cases)])
grps.generate_target()
gt = grps.target[1:]
gp = grps.target[0]
gt.align_to(SCREEN,UP)
gt.shift(UP*grps.get_height())
gp[1].set_height(6)
gp[1].move_to(ORIGIN)
gp[1].to_edge(DOWN)
gp[1].to_edge(LEFT,buff=2)
gp[0].set_x(0)
self.play(
MoveToTarget(grps)
)
self.wait()
self.cases_group_1 = VGroup(case_1,titles[0])
self.proof_1(case_1)
# next case
def next_proof(height=6, buff_down=1, buff_left=0.5):
def func(vgr):
tit, gr = vgr
tit.move_to(ORIGIN)
tit.to_edge(UP)
gr.set_height(height)
gr.move_to(ORIGIN)
gr.to_edge(DOWN,buff=buff_down)
gr.to_edge(LEFT,buff=buff_left)
return vgr
return func
frame_1 = self.get_screen_rect()
self.cases_group_1.add(frame_1)
self.play(FadeIn(frame_1))
self.play(
self.cases_group_1.set_height,1,
self.cases_group_1.to_corner,UL,{"buff":0.1},
run_time=2
)
self.play(ApplyFunction(next_proof(), grps[1]))
self.wait()
# case 2
self.cases_group_2 = VGroup(titles[1],case_2)
self.proof_2(case_2)
frame_2 = self.get_screen_rect()
self.cases_group_2.add(frame_2)
self.play(FadeIn(frame_2))
self.play(
self.cases_group_2.set_height,1,
self.cases_group_2.next_to,self.cases_group_1,RIGHT,0,
run_time=2
)
self.play(ApplyFunction(next_proof(6,0.2), grps[2]))
# case 3
self.cases_group_3 = VGroup(titles[2],case_3)
self.proof_3(case_3)
frame_3 = self.get_screen_rect()
self.cases_group_3.add(frame_3)
self.play(FadeIn(frame_3))
all_cases = VGroup(self.cases_group_1,self.cases_group_2,self.cases_group_3)
self.play(
self.camera_frame.set_width,VGroup(frame_1,frame_2).get_width()*1,
self.camera_frame.move_to,VGroup(frame_1,frame_2).get_center(),
self.camera_frame.shift,DOWN*VGroup(frame_1,frame_2).get_height()/2,
self.cases_group_3.set_height,1,
self.cases_group_3.next_to,VGroup(frame_1,frame_2),DOWN,0,
run_time=2
)
# self.play(MoveToTarget(all_cases))
self.wait()
# self.play(v2.set_value,190,run_time=5,rate_func=linear)
def proof_1(self, case):
print("Proof 1")
dots = case[1]
d1, d2, d3 = dots
center = case[0]
theta = case[-2]
varphi = case[-1]
# Radius
r1 = Line(center.get_center(),d1.get_center(),color=RED_A,stroke_width=8)
r2 = Line(center.get_center(),d3.get_center(),color=RED_A,stroke_width=8)
r1_tex = TexMobject("r").add_background_rectangle()
r1_tex.move_to(r1)
r2_tex = r1_tex.deepcopy()
r2_tex.move_to(r2)
# self.add(r1,r2,r1_tex,r2_tex)
self.cases_group_1.add(case,r1,r2,r1_tex,r2_tex,)
self.play(
ShowCreation(r1),
ShowCreation(r2),
Write(r1_tex),
Write(r2_tex),
Animation(dots),
)
self.bring_to_front(dots)
self.wait()
# Arc and theta
arc_p1 = ArcBetweenVectors(0.6,center,d3,d1,True)
arc_p1.match_color(theta)
theta_copy = LabelFromArc(arc_p1, theta.get_height(), "\\theta", distance_proportion=1.5)
theta_copy.match_style(theta)
# psi
arc_psi = ArcBetweenVectors(0.4,d3,d1,center,True)
arc_psi.set_color(RED_A)
psi = LabelFromArc(arc_psi, theta.get_height(), "\\psi", distance_proportion=1.3)
psi.match_color(arc_psi)
# self.add(arc_p1,theta_copy,arc_psi,psi)
self.cases_group_1.add(arc_p1,theta_copy,arc_psi,psi)
self.play(
TransformFromCopy(theta,theta_copy),
ShowCreation(arc_p1),
run_time=2
)
self.wait(2)
self.play(
ShowCreation(arc_psi),
Write(psi),
run_time=2
)
self.wait(2)
# formulas develop
t1 = TexMobject("\\psi","+","2","\\theta","=","180^\\circ",
tex_to_color_map={
"\\psi": psi.get_color(), "\\theta": theta.get_color(),
},
)
t2 = TexMobject("\\psi","+","\\varphi","=","180^\\circ",
tex_to_color_map={
"\\psi": psi.get_color(), "\\varphi": varphi.get_color(),
},
)
t3 = TexMobject("\\psi","+","2","\\theta","=","\\psi","+","\\varphi",
tex_to_color_map={
"\\psi": psi.get_color(), "\\varphi": varphi.get_color(),
"\\theta": theta.get_color()
},
)
t4 = TexMobject("2","\\theta","=","\\varphi",
tex_to_color_map={
"\\psi": psi.get_color(), "\\varphi": varphi.get_color(),
"\\theta": theta.get_color()
},
)
tg = VGroup(t1,t2,t3,t4).arrange(DOWN,buff=0.6)
self.cases_group_1.add(t1,t2,t3,t4)
tg.scale(1.35)
self.align_formulas_with_equal(t2, t1, -2, -2)
self.align_formulas_with_equal(t3, t1, 4, -2)
self.align_formulas_with_equal(t4, t1, -2, -2)
tg.to_edge(RIGHT,buff=0.7)
# row 1
tc1 = theta.deepcopy()
tc2 = theta_copy.deepcopy()
self.play(
TransformFromCopy(psi, t1[0]),
ReplacementTransform(tc1.copy(), t1[3]),
ReplacementTransform(tc2.copy(), t1[3]),
# Transform(tc2, t1[3].copy()),
*[Write(t1[i]) for i in [1,2,-2,-1]],
run_time=3
)
self.cases_group_1.add(tc1,tc2)
self.wait()
self.play(
TransformFromCopy(t1[0],t2[0]),
TransformFromCopy(varphi,t2[2],path_arc=-PI/2),
*[Write(t2[i]) for i in [1,*range(3,len(t2))]],
run_time=3
)
self.wait()
self.play(
TransformFromCopy(t1[:4],t3[:4]),
TransformFromCopy(t2[:3],t3[-3:]),
Write(t3[4]),
run_time=3
)
self.wait()
self.play(
t3[0].fade,0.5,
t3[-3].fade,0.5,
)
self.wait()
self.play(
TransformFromCopy(t3[2:4],t4[:2]),
TransformFromCopy(t3[-1],t4[-1]),
Write(t4[2]),
run_time=3
)
self.wait()
self.play(
Succession(
FadeToColor(t4,YELLOW),
FadeToColor(t4,PURPLE_A),
),
AnimationGroup(
ShowCreationThenDestructionAround(t4.deepcopy()),
ShowCreationThenDestructionAround(t4.deepcopy()),
lag_ratio=1
)
)
self.wait()
# n = 0
# for mob in self.mobjects:
# try:
# t = Text(f"{n}").next_to(mob,UP,0)
# self.add(t)
# n += 1
# except:
# n += 1
# pass
def proof_2(self, case):
print("Proof 2")
dots = case[1]
d1, d2, d3 = dots
center = case[0]
theta = case[-2]
varphi = case[-1]
# Radius
r1 = Line(center.get_center(),d1.get_center(),color=RED_A,stroke_width=8)
r2 = Line(center.get_center(),d2.get_center(),color=RED_A,stroke_width=8)
r3 = Line(center.get_center(),d3.get_center(),color=RED_A,stroke_width=8)
r1_tex = TexMobject("r").add_background_rectangle()
r1_tex.move_to(r1)
r2_tex = r1_tex.deepcopy()
r2_tex.move_to(r2)
r3_tex = r1_tex.deepcopy()
r3_tex.move_to(r3)
arc_p3_2 = ArcBetweenVectors(0.8,center,d2,d3).set_color(TEAL)
arc_p3_1 = ArcBetweenVectors(1,d1,center,d3).set_color(TEAL)
# theta.shift(LEFT*0.2)
th_1 = LabelFromArc(arc_p3_1,theta.get_height()*0.8,"\\theta_1",color=theta.get_color(),distance_proportion=2)
th_2 = LabelFromArc(arc_p3_2,theta.get_height()*0.8,"\\theta_2",color=theta.get_color(),distance_proportion=2)
self.add_foreground_mobjects(dots,case[5])
self.cases_group_2.add(th_1,th_2)
self.play(theta.next_to,d3,DOWN,buff=0.2)
self.wait()
self.play(
ShowCreation(r1),
ShowCreation(r2),
ShowCreation(r3),
Write(r1_tex),
Write(r2_tex),
Write(r3_tex),
)
self.wait()
self.play(
ReplacementTransform(theta.copy()[0],th_1[0]),
ReplacementTransform(theta.copy()[0],th_2[0]),
ShowCreation(arc_p3_1),
ShowCreation(arc_p3_2),
run_time=3.5
)
self.wait()
# self.remove(theta)
self.cases_group_2.add(r1,r2,r3,r1_tex,r2_tex,r3_tex,arc_p3_1,arc_p3_2)
# ---------------- ARC PSI
arc_psi_1 = ArcBetweenVectors(0.4,d3,d1,center,True).set_color(RED_A)
arc_psi_2 = ArcBetweenVectors(0.4,d3,d2,center,True).set_color(RED_A)
arc_psi_2.rotate(-arc_psi_2.get_angle(),about_point=center.get_center())
psi_1 = LabelFromArc(arc_psi_1,theta.get_height()*0.8,"\\psi_1",color=RED_A,distance_proportion=1.6)
psi_2 = LabelFromArc(arc_psi_2,theta.get_height()*0.8,"\\psi_2",color=RED_A,distance_proportion=1.6)
self.play(
*list(map(Write,[arc_psi_1,arc_psi_2,psi_1,psi_2])),
run_time=2
)
self.wait()
self.cases_group_2.add(arc_psi_1,arc_psi_2,psi_1,psi_2)
# ---------------- FORMUAS transformn
tex_formulas_kwargs = {
"tex_to_color_map": {
"\\psi_1": psi_1.get_color(), "\\psi_2": psi_2.get_color(), "\\varphi": varphi.get_color(),
"\\theta_1": th_1.get_color(), "\\theta_2": th_1.get_color(),
}
}
# FORMULAS
f1 = TexMobject(
"\\psi_1","+","\\psi_2","+","\\varphi","=","360^\\circ",**tex_formulas_kwargs
)
f2 = TexMobject(
"(","180^\\circ","-","2","\\theta_1",")","+","(","180^\\circ","-","2","\\theta_2",")","+","\\varphi","=","360^\\circ",
**tex_formulas_kwargs
)
f2.add_background_rectangle()
f3 = TexMobject(
"-","2","\\theta_1","-","2","\\theta_2","+","\\varphi","=","0",**tex_formulas_kwargs
)
f4 = TexMobject(
"\\varphi","=","2","\\theta_1","+","2","\\theta_2",**tex_formulas_kwargs
)
f5 = TexMobject(
"\\varphi","=","2","(","\\theta_1","+","\\theta_2",")",**tex_formulas_kwargs
)
f6 = TexMobject(
"\\varphi","=","2","\\theta",**tex_formulas_kwargs
)
f6[-1].set_color(theta.get_color())
# f2[0].set_color(RED)
fg = VGroup(f1,f2,f3,f4,f5,f6).arrange(DOWN,buff=0.6)
fg.to_edge(RIGHT).to_edge(DOWN)
self.align_formulas_with_equal(f3,f1,-2,5)
self.align_formulas_with_equal(f4,f1,1,5)
self.align_formulas_with_equal(f5,f1,1,5)
self.align_formulas_with_equal(f6,f1,1,5)
# ---------------- FORMUAS transformn
by_case_1 = TextMobject("By Case 1").to_edge(RIGHT)
self.play(
LaggedStart(
TransformFromCopy(psi_1[0],f1[0],path_arc=-PI/2),
TransformFromCopy(psi_2[0],f1[2],path_arc=-PI/2),
TransformFromCopy(varphi,f1[4],path_arc=-PI/2),
lag_ratio=0.6
),
LaggedStart(*[Write(f1[i]) for i in [1,3,5,6]]),
run_time=6
)
self.wait()
self.play(Write(by_case_1))
self.wait()
self.play(
FadeIn(f2[0]),
*[
TransformFromCopy(f1[i],f2[j+1])
for i,j in zip(
[1,3,4,5,6],
[6,13,14,15,16]
)
],
TransformFromCopy(f1[0],f2[1:6+1]),
TransformFromCopy(f1[2],f2[7+1:13+1]),
# LaggedStart(*[Write(f2[i+1]) for i in [6,13]]),
run_time=4
)
self.wait()
self.play(Write(by_case_1,rate_func=lambda t: smooth(1-t)))
self.wait()
self.play(
*[
ApplyMethod(mob.fade,0.7)
for mob in [f2[i+1] for i in [1,8,16]]
]
)
self.wait(2)
self.play(
*[
TransformFromCopy(f2[i+1],f3[j])
for i,j in zip(
[2,3,4,9,10,11,13,14,15],
[*range(len(f3)-1)]
)
],
Write(f3[-1]),
# LaggedStart(*[Write(f2[i+1]) for i in [6,13]]),
run_time=4
)
self.wait()
self.play(
*[
TransformFromCopy(f3[i],f4[j])
for i,j in zip(
[1,2,4,5,7,8],
[2,3,5,6,0,1]
)
],
Write(f4[4]),
# LaggedStart(*[Write(f2[i+1]) for i in [6,13]]),
run_time=4
)
self.wait()
self.play(
*[
ReplacementTransform(f4[i].deepcopy(),f5[j])
for i,j in zip(
[0,1,2,3,4,5,6],
[0,1,2,4,5,2,6]
)
],
Write(f5[3]),
Write(f5[-1]),
# LaggedStart(*[Write(f2[i+1]) for i in [6,13]]),
run_time=4
)
self.wait()
self.play(
*[
ReplacementTransform(f5[i].deepcopy(),f6[j])
for i,j in zip(
[0,1,2],
[0,1,2]
)
],
TransformFromCopy(f5[-5:],f6[-1]),
run_time=4
)
self.foreground_mobjects = []
self.wait()
self.play(
Succession(
FadeToColor(f6,YELLOW),
FadeToColor(f6,PURPLE_A),
),
AnimationGroup(
ShowCreationThenDestructionAround(f6.deepcopy()),
ShowCreationThenDestructionAround(f6.deepcopy()),
lag_ratio=1
)
)
# self.play(
# *[
# TransformFromCopy()
# ],
# )
# self.add(fg)
# VGroup(case,*self.mobjects[start_index:]).set_color(TEAL)
self.cases_group_2.add(fg,by_case_1)
self.wait()
def proof_3(self, case):
print("Proof 3")
dots = case[1]
d1, d2, d3 = dots
center = case[0]
theta = case[-2]
varphi = case[-1]
self.add_foreground_mobject(dots)
def fade_mobs(fade=0.9):
def update(mob):
mob.fade(fade)
return mob
return update
# ---------------- FIGURES DEFINITION
diameter_vector = Line(d3.get_center(),center.get_center()).get_vector()
diameter = Line(d3.get_center(),d3.get_center()+diameter_vector*2,color=RED_A)
d4 = Dot(diameter.get_end())
arc_psi_1 = ArcBetweenVectors(0.6,d2,d4,d3,color=RED_A)
arc_psi_2 = ArcBetweenVectors(0.6,d2,d4,center,color=RED_A)
arc_alpha_1 = ArcBetweenVectors(0.7,d1,d4,d3,color=YELLOW_B,stroke_width=8)
arc_alpha_2 = ArcBetweenVectors(0.7,d1,d4,center,color=YELLOW_B,stroke_width=8)
psi_1 = LabelFromArc(arc_psi_1,theta.get_height()*0.8,"\\psi_1",color=RED_A,distance_proportion=2.1)
psi_2 = LabelFromArc(arc_psi_2,theta.get_height()*0.8,"\\psi_2",color=RED_A,distance_proportion=2.1)
alpha_1 = LabelFromArc(arc_alpha_1,theta.get_height()*0.8,"\\alpha_1",color=YELLOW_B,distance_proportion=2.5)
back_1 = BackgroundRectangle(alpha_1)
alpha_2 = LabelFromArc(arc_alpha_2,theta.get_height()*0.8,"\\alpha_2",color=YELLOW_B,distance_proportion=2.3)
back_2 = BackgroundRectangle(alpha_2)
line_1 = Line(center.get_center(),d1.get_center(),color=varphi.get_color())
line_2 = Line(d3.get_center(),d1.get_center(),color=varphi.get_color())
# ---------
psi_g = VGroup(arc_psi_1,arc_psi_2,psi_1,psi_2)
alpha_g = VGroup(arc_alpha_1,arc_alpha_2,alpha_1,alpha_2)
theta_g = VGroup(theta,varphi,case[-3],case[-4],case[2],case[3])
self.wait()
self.play(
GrowFromCenter(diameter)
)
self.wait()
self.play(
LaggedStart(*[
Write(arc)
for arc in psi_g
]),
)
self.wait(2)
self.play(
*list(map(FadeIn,[back_1,back_2])),
LaggedStart(*[
Write(arc)
for arc in alpha_g
]),
)
self.wait(2)
self.add_foreground_mobjects(back_1,back_2,alpha_g)
self.cases_group_3.add(
arc_psi_1,arc_psi_2,arc_alpha_1,arc_alpha_2,diameter,
psi_1,psi_2,alpha_1,alpha_2,
)
self.add(line_1,line_2)
for i in [psi_g,theta_g]:
for j in i:
j.save_state()
self.play(
*[ApplyFunction(fade_mobs(),i) for i in psi_g],
*[ApplyFunction(fade_mobs(),i) for i in theta_g],
)
self.wait()
# self.play(
# Restore(psi_g),
# Restore(theta_g),
# )
# self.wait()
# self.play(ApplyFunction(show_mobs(),psi_g))
# ---------------- FORMULAS DEFINITION
formulas = [
["\\alpha_1","=","\\psi_1","+","\\theta"],
["\\alpha_2","=","\\psi_2","+","\\varphi"],
["\\alpha_2","=","2","\\alpha_1"],
["\\psi_2","+","\\varphi","=","2","(","\\psi_1","+","\\theta",")"],
["\\psi_2","=","2","\\psi_1"],
["2","\\psi_1","+","\\varphi","=","2","\\psi_1","+","2","\\theta"],
["\\varphi","=","2","\\theta"],
]
tex_formulas_kwargs = {
"tex_to_color_map": {
"\\psi_1": psi_1.get_color(), "\\psi_2": psi_2.get_color(), "\\varphi": varphi.get_color(),
"\\theta": theta.get_color(), "\\alpha_1": alpha_1.get_color(), "\\alpha_2": alpha_2.get_color()
}
}
f = VGroup(*[
TexMobject(*formula, **tex_formulas_kwargs)
for formula in formulas
])
f.arrange(DOWN)
f.scale(1.3)
for fi,i in zip(f[1:],[1,1,3,1,4,1]):
self.align_formulas_with_equal(fi,f[0],i,1)
f.to_edge(RIGHT,buff=1.8)
# --------------------------------------
by_case_1 = TextMobject("By case 1")
by_case_1.next_to(f[2],RIGHT)
by_case_2 = by_case_1.copy()
by_case_2.next_to(f[4],RIGHT)
# ----------- FORMULAS ANIMATIONS
self.play(
FadeOut(back_1),
Restore(theta),
Restore(psi_1),
ReplacementTransform(alpha_1[0],f[0][0]),
run_time=2,
)
self.play(
TransformFromCopy(psi_1[0],f[0][2]),
TransformFromCopy(theta[0],f[0][-1]),
*[Write(f[0][i]) for i in [1,3]],
run_time=3,
)
self.wait()
self.play(
FadeOut(back_2),
Restore(varphi),
Restore(psi_2),
ReplacementTransform(alpha_2[0],f[1][0]),
run_time=2,
)
self.play(
TransformFromCopy(psi_2[0],f[1][2]),
TransformFromCopy(varphi[0],f[1][-1]),
*[Write(f[1][i]) for i in [1,3]],
run_time=3,
)
self.wait()
# By case 1 - 1
self.play(
Write(by_case_1)
)
self.wait()
self.play(
Write(f[2])
)
self.wait()
# -----------------
self.play(
TransformFromCopy(f[0][-3:],f[3][6:9]),
TransformFromCopy(f[1][-3:],f[3][:3]),
*[
TransformFromCopy(f[2][i],f[3][j])
for i,j in zip(
[1,2],
[3,4]
)
],
*[Write(f[3][i]) for i in [5,9]],
run_time=3
)
self.wait()
# ---------------------------
self.wait()
line_3 = Line(d3.get_center(),d2.get_center(),color=TEAL_A)
line_4 = Line(center.get_center(),d2.get_center(),color=PURPLE_A)
save_grp = VGroup(arc_alpha_1,arc_alpha_2,varphi,theta)
for i in save_grp:
try:
i.save_state()
except:
pass
self.play(
FadeOut(line_1),
FadeOut(line_2),
# line_1.fade,1,
# line_2.fade,1,
FadeIn(line_3),
FadeIn(line_4),
*[ApplyMethod(i.fade,0.92) for i in save_grp],
*[Restore(i) for i in [arc_psi_1,arc_psi_2]]
)
self.wait(3)
# by case 2
self.play(
Write(by_case_2)
)
self.wait()
self.play(
Write(f[4])
)
self.wait(3)
self.play(
*[Restore(i) for i in [*save_grp,*case[2:6]]]
)
self.wait()
# ---------------------------
self.play(
# TransformFromCopy(f[3][-3:],f[5][6:9]),
TransformFromCopy(f[3][0],f[5][:2]),
*[
TransformFromCopy(f[3][i],f[5][j])
for i,j in zip(
[1,2,3,4,6,7,8,4],
[2,3,4,5,6,7,9,8]
)
],
run_time=3
)
self.wait()
self.play(
*[ApplyMethod(f[5][i].fade,0.8) for i in [0,1,5,6]],
run_time=2
)
self.play(
*[
TransformFromCopy(f[5][i],f[6][j])
for i,j in zip(
[3,4,8,9],
[0,1,2,3]
)
],
run_time=3
)
# self.play(
# *{Restore(i) for i in [case[2],case[3]]}
# )
# self.add(f,by_case_1,by_case_2)
self.play(
Succession(
FadeToColor(f[6],YELLOW),
FadeToColor(f[6],PURPLE_A),
),
AnimationGroup(
ShowCreationThenDestructionAround(f[6].deepcopy()),
ShowCreationThenDestructionAround(f[6].deepcopy()),
lag_ratio=1
)
)
self.cases_group_3.add(line_1,line_2,line_3,line_4,by_case_1,by_case_2,f)
self.wait()
def align_formulas_with_equal(self, f1, f2, i1, i2):
c1 = f1[i1].get_center()
c2 = f2[i2].get_center()
distance = c2 - c1
f1.shift(RIGHT*distance[0])
def get_screen_rect(self):
return Rectangle(width=FRAME_WIDTH,height=FRAME_HEIGHT)
# --------------------------------------------------------
# --------------------------------------------------------
# --------------------------------------------------------
class Polygon(Polygon):
def get_center_of_edges(self,buff=SMALL_BUFF*3):
vertices = self.get_vertices()
coords_vertices = []
for i in range(len(vertices)):
if i < len(vertices)-1:
p1,p2 = [vertices[i],vertices[i+1]]
else:
p1,p2 = [vertices[-1],vertices[0]]
guide_line = Line(p1,p2)
side = guide_line.get_center()
normal_direction = guide_line.copy()
normal_direction.rotate(-PI/2)
vector_normal_direction = normal_direction.get_unit_vector()
direction = Dot(side).shift(vector_normal_direction*buff).get_center()
coords_vertices.append(direction)
return coords_vertices
class SineLaw(Scene):
CONFIG = {
"triangle_config": {
"color": RED,
"stroke_width": 8,
},
"tex_map": {
"tex_to_color_map": {
"\\alpha": RED_A,
"\\beta": TEAL_A,
"\\gamma": PURPLE_A,
"A": RED_A,
"B": TEAL_A,
"C": PURPLE_A,
"x": GREEN_A,
"h_1": YELLOW_B,
"h_2": BLUE_B,
}
}
}
def construct(self):
du = UP*1.5
d1 = Dot(LEFT*4+du)
d2 = Dot(RIGHT*2+du)
d3 = Dot(RIGHT*4+UP*2+du)
triangle = Polygon(
d1.get_center(),d2.get_center(),d3.get_center(),**self.triangle_config
)
def frac_string(n,d):
return ["{",n,"\\over",d,"}"]
def frac_strings(n,d):
return ["{",*n,"\\over",*d,"}"]
sina_t = ["{\\rm sin}","\\alpha"]
sinb_t = ["{\\rm sin}","\\beta"]
sinc_t = ["{\\rm sin}","\\gamma"]
cosa_t = ["{\\rm cos}","\\alpha"]
cosb_t = ["{\\rm cos}","\\beta"]
cosc_t = ["{\\rm cos}","\\gamma"]
formulas_sine_string_1 = [
[*sinb_t,"=",*frac_string("h_1","C")],
[*sinc_t,"=",*frac_string("h_1","B")],
["C","\\,",*sinb_t,"=","h_1"],
["B","\\,",*sinc_t,"=","h_1"],
["C","\\,",*sinb_t,"=","B","\\,",*sinc_t],
[*frac_strings(["C"],sinc_t),"=",*frac_strings(["B"],sinb_t)]
]
formulas_sine_string_2 = [
[*sina_t,"=",*frac_string("h_2","B")],
[*sinb_t,"=",*frac_string("h_2","A")],
["B","\\,",*sina_t,"=","h_2"],
["A","\\,",*sinb_t,"=","h_2"],
["B","\\,",*sina_t,"=","A","\\,",*sinb_t],
[*frac_strings(["B"],sinb_t),"=",*frac_strings(["A"],sina_t)]
]
sine_law = TexMobject(*[
*frac_strings(["C"],sinc_t),"=",*frac_strings(["B"],sinb_t),"=",*frac_strings(["A"],sina_t),
],**self.tex_map).scale(0.9)
formulas_sine_1 = VGroup(*[
TexMobject(*f,**self.tex_map) for f in formulas_sine_string_1
])
# formulas_sine.arrange_in_grid(None,2)
formulas_sine_arrange_1 = VGroup(
formulas_sine_1[:2].arrange(RIGHT,buff=1),
formulas_sine_1[2:4].arrange(RIGHT,buff=1),
formulas_sine_1[4:].arrange(DOWN),
).arrange(DOWN,buff=0.7).scale(0.9)
formulas_sine_2 = VGroup(*[
TexMobject(*f,**self.tex_map) for f in formulas_sine_string_2
])
# formulas_sine.arrange_in_grid(None,2)
formulas_sine_arrange_2 = VGroup(
formulas_sine_2[:2].arrange(RIGHT,buff=1),
formulas_sine_2[2:4].arrange(RIGHT,buff=1),
formulas_sine_2[4:].arrange(DOWN),
).arrange(DOWN,buff=0.7).scale(0.9)
formulas_sine_arrange_1.to_edge(DOWN,buff=0.3)
formulas_sine_arrange_1.to_edge(LEFT,buff=1)
formulas_sine_arrange_2.to_edge(DOWN,buff=0.3)
formulas_sine_arrange_2.to_edge(RIGHT,buff=1)
sine_law.align_to(formulas_sine_arrange_1,DOWN)
triangle.set_x(0)
center_vertices = triangle.get_center_of_edges()
labels = VGroup(*[
TexMobject(label,**self.tex_map).move_to(point) for label,point in zip(["C","B","A"],center_vertices)
])
fs1 = formulas_sine_1
fs2 = formulas_sine_2
# ------------------------------
h1 = TexMobject("h_1",**self.tex_map)
h2 = TexMobject("h_2",**self.tex_map)
x = TexMobject("x",**self.tex_map)
h1_line = self.get_h(d2,d1,d3)
h2_line = DashedLine(d3.get_center()+RIGHT*0.09,[d3.get_x()+0.09,d2.get_y()-0.09,0])
h3_line = DashedLine(d2.get_center()+RIGHT*0.09,h2_line.get_end())
rec_1 = Square().set_width(0.25)
rec_1 = VMobject().set_points_as_corners([rec_1.get_corner(v) for v in [UR,UL,DL]])
rec_2 = rec_1.deepcopy()
rec_1.next_to(h2_line.get_end(),UL,buff=0)
rec_2.rotate(h1_line.get_angle())
rec_2.next_to(h1_line.get_end(),DL,buff=0)
rec_2.shift(DOWN*0.1+RIGHT*0.05)
x.next_to(h3_line,DOWN,0.1)
h1.next_to(h1_line,RIGHT,0.1)
h1.shift(LEFT*0.15)
h2.next_to(h2_line,RIGHT,0.1)
# h2_line.rotate(PI,about_point=h2_line.get_start())
# ------------------------------
alpha_arc = ArcBetweenVectors(0.3,d1,d3,d2)
beta_arc = ArcBetweenVectors(1.7,d2,d3,d1)
gamma_arc = ArcBetweenVectors(1,d1,d2,d3)
alpha_p_arc = ArcBetweenVectors(0.4,Dot(h2_line.get_end()),d3,d2)
gamma_arc.rotate(gamma_arc.get_angle()*0.9,about_point=gamma_arc.get_arc_center())
alpha = LabelFromArc(alpha_arc,labels[0].get_width()*0.7,"\\alpha",distance_proportion=1.9,**self.tex_map)
beta = LabelFromArc(beta_arc,labels[0].get_width()*1.1,"\\beta",distance_proportion=1.9,**self.tex_map)
gamma = LabelFromArc(gamma_arc,labels[0].get_width()*1.1,"\\gamma",distance_proportion=1.9,**self.tex_map)
alpha_p = LabelFromArc(alpha_p_arc,labels[0].get_width()*1.1,"\\alpha'",distance_proportion=1.9,**self.tex_map)
alpha.shift(LEFT*0.25+DOWN*0.1)
but = TexMobject("{\\rm sin}(\\pi-\\alpha)={\\rm sin}(\\alpha)",**self.tex_map)
but.to_corner(UL)
t1 = Polygon(
d1.get_center(),d2.get_center(),h1_line.get_end(),
color=ORANGE,stroke_width=0,fill_opacity=0
)
t2 = Polygon(
d2.get_center(),d3.get_center(),h1_line.get_end(),
color=ORANGE,stroke_width=0,fill_opacity=0
)
t3 = Polygon(
d2.get_center(),h3_line.get_end(),h2_line.get_start(),
color=ORANGE,stroke_width=0,fill_opacity=0
)
t4 = Polygon(
d1.get_center(),h3_line.get_end(),h2_line.get_start(),
color=ORANGE,stroke_width=0,fill_opacity=0
)
def show_triange(t):
t.set_fill(None,0.3)
return t
def hide_triange(t):
t.set_fill(None,0)
return t
self.add(t1,t2,t3,t4)
# - SHOW CREATIONS
self.add_foreground_mobject(triangle)
self.play(
ShowCreation(triangle,rate_func=linear),
LaggedStart(*list(map(Write,labels)),lag_ratio=0.8),
run_time=2.5
)
self.wait()
self.play(
LaggedStart(*[
TransformFromCopy(m1,m2)
for m1,m2 in zip(labels[::-1],[alpha,beta,gamma])
],lag_ratio=0.7),
LaggedStart(*list(map(ShowCreation,[alpha_arc,beta_arc,gamma_arc])),lag_ratio=0.7),
run_time=3.5
)
self.wait()
self.play(LaggedStart(*list(map(Write,[h1_line,h1,rec_2])),lag_ratio=0.5))
# - TRANSFORMATIONS
C,B,A = labels
self.play(ApplyFunction(show_triange,t1))
self.wait()
self.play(
LaggedStart(
TransformFromCopy(beta[0],fs1[0][1]),
TransformFromCopy(h1[0],fs1[0][-4]),
TransformFromCopy(C[0],fs1[0][-2]),
lag_ratio=0.7
),
LaggedStart(*[Write(fs1[0][i]) for i in [0,2,-3]]),
run_time=5
)
self.wait()
self.play(ApplyFunction(hide_triange,t1))
self.wait()
self.play(ApplyFunction(show_triange,t2))
self.wait()
self.play(
LaggedStart(
TransformFromCopy(gamma[0],fs1[1][1]),
TransformFromCopy(h1[0],fs1[1][-4]),
TransformFromCopy(B[0],fs1[1][-2]),
lag_ratio=0.7
),
LaggedStart(*[Write(fs1[1][i]) for i in [0,2,-3]]),
run_time=5
)
self.wait()
self.play(ApplyFunction(hide_triange,t2))
# - - - - - - - -
self.wait()
self.play(
LaggedStart(
TransformFromCopy(fs1[0][-2],fs1[2][0]),
AnimationGroup(
TransformFromCopy(fs1[0][0],fs1[2][2]),
TransformFromCopy(fs1[0][1],fs1[2][3]),
lag_ratio=0
),
TransformFromCopy(fs1[0][2],fs1[2][4]),
TransformFromCopy(fs1[0][-4],fs1[2][-1]),
lag_ratio=0.3
),
# LaggedStart(*[Write(fs1[1][i]) for i in [0,2,-3]]),
run_time=5
)
self.wait()
self.play(
LaggedStart(
TransformFromCopy(fs1[1][-2],fs1[3][0]),
AnimationGroup(
TransformFromCopy(fs1[1][0],fs1[3][2]),
TransformFromCopy(fs1[1][1],fs1[3][3]),
lag_ratio=0
),
TransformFromCopy(fs1[1][2],fs1[3][4]),
TransformFromCopy(fs1[1][-4],fs1[3][-1]),
lag_ratio=0.3
),
# LaggedStart(*[Write(fs1[1][i]) for i in [0,2,-3]]),
run_time=5
)
self.wait()
self.play(
TransformFromCopy(fs1[2][:4],fs1[4][:4]),
TransformFromCopy(fs1[3][:4],fs1[4][-4:]),
Write(fs1[4][4]),
run_time=5
)
self.wait()
self.play(
LaggedStart(
TransformFromCopy(fs1[4][0],fs1[5][1]),
TransformFromCopy(fs1[4][-2:],fs1[5][3:5]),
TransformFromCopy(fs1[4][-4],fs1[5][-5]),
TransformFromCopy(fs1[4][2:4],fs1[5][-3:-1]),
lag_ratio=0.5
),
# TransformFromCopy(fs1[4][-2:],fs1[5][3:5]),
# TransformFromCopy(fs1[3][:4],fs1[4][-4:]),
LaggedStart(
Write(fs1[5][2]),
Write(fs1[5][-4]),
Write(fs1[5][6]),
lag_ratio=0.5
),
run_time=5
)
self.wait()
# ------------------------------
self.play(LaggedStart(*list(map(Write,[h2_line,h2,h3_line,x,rec_1])),lag_ratio=0.5))
self.wait()
self.play(Write(alpha_p),Write(alpha_p_arc))
self.wait()
self.play(Write(but))
self.wait()
self.play(Indicate(but),Indicate(alpha_p),Indicate(alpha_p_arc),run_time=3)
self.wait()
self.play(ApplyFunction(show_triange,t3))
self.wait()
self.play(
LaggedStart(
TransformFromCopy(alpha_p[0],fs2[0][1]),
TransformFromCopy(h2[0],fs2[0][-4]),
TransformFromCopy(B[0],fs2[0][-2]),
lag_ratio=0.7
),
LaggedStart(*[Write(fs2[0][i]) for i in [0,2,-3]]),
run_time=5
)
self.wait()
self.play(ApplyFunction(hide_triange,t3))
self.wait()
self.play(ApplyFunction(show_triange,t4))
self.wait()
self.play(
LaggedStart(
TransformFromCopy(beta[0],fs2[1][1]),
TransformFromCopy(h2[0],fs2[1][-4]),
TransformFromCopy(A[0],fs2[1][-2]),
lag_ratio=0.7
),
LaggedStart(*[Write(fs2[1][i]) for i in [0,2,-3]]),
run_time=5
)
self.wait()
self.play(ApplyFunction(hide_triange,t4))
# ------------------------------
self.play(
LaggedStart(*[FadeIn(f) for f in fs2[2:]],lag_ratio=0.5),
run_time=8
)
self.wait()
# self.add(sine_law)
self.play(
ReplacementTransform(fs1[-1],sine_law[:len(fs1[-1])]),
ReplacementTransform(fs2[-1],sine_law[-len(fs2[-1]):]),
run_time=2.5
)
sine_law.save_state()
self.wait()
self.play(
Succession(
FadeToColor(sine_law,YELLOW),
Restore(sine_law)
),
AnimationGroup(
ShowCreationThenDestructionAround(sine_law.copy()),
ShowCreationThenDestructionAround(sine_law.copy()),
lag_ratio=1
)
)
# self.add(but,h1_line,h2_line,h3_line,rec_1,rec_2,x,h1,h2,alpha_p_arc,alpha_p)
# self.add(labels,alpha,beta,gamma)
# self.add(alpha_arc,beta_arc,gamma_arc)
# self.add(triangle,formulas_sine_1,formulas_sine_2,sine_law)
# self.add_foreground_mobject(triangle)
self.wait()
def get_h(self, dot, d1, d2,invert=True):
line = Line(d1.get_center(),d2.get_center())
vector = line.get_unit_vector()
sign = 1 if invert else -1
normal_vector = rotate_vector(vector,sign*PI/2)
def get_distance_point_line(line,dot):
x_0, y_0, z_0 = dot.get_center()
X_0 = line.point_from_proportion(0)
X_1 = line.point_from_proportion(1)
x_1, y_1, z_1 = X_0
x_2, y_2, z_2 = X_1
return abs((x_2-x_1)*(y_1-y_0)-(x_1-x_0)*(y_2-y_1)/get_norm(line.get_vector()))
distance = get_distance_point_line(line,dot)
return DashedLine(dot.get_center(),dot.get_center()+distance*normal_vector)
# --------------------------------------------------------
# --------------------------------------------------------
# --------------------------------------------------------
class CosineLaw(Scene):
def construct(self):
# THIS IS YOUR TASK
pass |
AnimationsWithManim_Elteoremadebeethoven/English/extra/my_workflow_example.py | from manimlib.imports import *
# 1. Draw square and draw triangles.
# 2. Move square and triangles to the left side.
# 3. Draw the right square.
# 4. Perform the transformation of the squares.
# 5. Draw sub squares and show the formulas in the squares.
# 6. Move the formulas in the squares and put them together forming the theorem on the bottom side of the screen.
DEFAULT_STROKE_WIDTH = 2
TRIANGLE_SIDE_PROPORTION = 0.80
BIG_SQUARE_SIDE_LENGTH = 4
DEFAULT_OPACITY = 0.4
BIG_SQUARE_CONFIG = {
"side_length": BIG_SQUARE_SIDE_LENGTH,
"color": WHITE,
"stroke_width": DEFAULT_STROKE_WIDTH
}
SMALL_SQUARE_CONFIG = {
"color": ORANGE,
"fill_opacity": 0,
"stroke_opacity": 0,
"stroke_width": DEFAULT_STROKE_WIDTH
}
TRIANGLE_CONFIG = {
"color": YELLOW,
"fill_opacity": DEFAULT_OPACITY,
"stroke_width": DEFAULT_STROKE_WIDTH
}
# Left group
class PythagoreanGroupOneSquare(VGroup):
CONFIG = {
"triangle_side_proportion": TRIANGLE_SIDE_PROPORTION,
"big_square_kwargs": BIG_SQUARE_CONFIG, #or square_config
"hip_square_kwargs": SMALL_SQUARE_CONFIG,
"triangle_kwargs": TRIANGLE_CONFIG,
}
def __init__(self,**kwargs):
digest_config(self, kwargs)
super().__init__(**kwargs)
self.big_square = Square(**self.big_square_kwargs)
self.alpha_1 = TRIANGLE_SIDE_PROPORTION / 4
self.proportion_points = self.get_proportion_points()
self.triangles = self.get_triangles()
self.hip_square = self.get_hip_square()
self.add(
self.big_square,
self.triangles,
self.hip_square
)
def get_proportion_points(self):
alpha_1 = self.alpha_1
return [(i * 0.25) + alpha_1 for i in range(4)]
def get_triangles(self):
bs = self.big_square
pp = self.proportion_points
return VGroup(*[
Polygon(
bs.point_from_proportion(pp[i % 4]),
bs.point_from_proportion((i + 1) * 0.25),
bs.point_from_proportion(pp[(i + 1) % 4]),
**self.triangle_kwargs
)
for i in range(4)
])
def get_hip_square(self):
bs = self.big_square
pp = self.proportion_points
return Polygon(*[
bs.point_from_proportion(point)
for point in pp
],
**self.hip_square_kwargs
)
# Right group
class PythagoreanGroupTwoSquares(PythagoreanGroupOneSquare):
CONFIG = {
"small_squares_kwargs": SMALL_SQUARE_CONFIG
}
def __init__(self, **kwargs):
VGroup.__init__(self, **kwargs)
self.big_square = Square(**self.big_square_kwargs)
self.alpha_1 = TRIANGLE_SIDE_PROPORTION / 4
self.proportion_points = self.get_proportion_points()
self.inside_point = np.array([
self.big_square.point_from_proportion(self.proportion_points[0])[0], # X coord
self.big_square.point_from_proportion(self.proportion_points[-1])[1], # Y coord
0
])
self.triangles = self.get_triangles()
self.med_square = self.get_med_square()
self.small_square = self.get_small_square()
self.add(
self.big_square,
self.triangles,
self.med_square,
self.small_square
)
def get_proportion_points(self):
alpha_1 = self.alpha_1
return [
0.25 - alpha_1,
0.25 + alpha_1,
0.5 + alpha_1,
1 - alpha_1
]
def get_triangles(self):
bs = self.big_square
pp = self.proportion_points
ip = self.inside_point
self.triangle_kwargs["stroke_width"] = 0.8
triangle_points = [
[
bs.point_from_proportion(0),
bs.point_from_proportion(pp[0]),
ip
], # T_1
[
bs.point_from_proportion(pp[1]),
bs.point_from_proportion(0.5),
bs.point_from_proportion(pp[2])
], # T_2
[
bs.point_from_proportion(pp[2]),
ip,
bs.point_from_proportion(pp[1])
], # T_3
[
ip,
bs.point_from_proportion(pp[3]),
bs.point_from_proportion(1)
] # T_4
]
return VGroup(*[
Polygon(*coords,**self.triangle_kwargs)
for coords in triangle_points
])
def get_med_square(self):
bs = self.big_square
med_square = Square(
side_length = TRIANGLE_SIDE_PROPORTION * BIG_SQUARE_SIDE_LENGTH,
**self.small_squares_kwargs
)
med_square.align_to(bs, UR)
return med_square
def get_small_square(self):
bs = self.big_square
small_square = Square(
side_length = (1 - TRIANGLE_SIDE_PROPORTION) * BIG_SQUARE_SIDE_LENGTH,
**self.small_squares_kwargs
)
small_square.align_to(bs, DL)
return small_square
# Animations
class MoveAndShift(Animation):
def __init__(self, mob, targ_coord, ang, **kwargs):
digest_config(self, kwargs)
self.mobject = mob
self.distance = targ_coord - mob.get_center()
self.ang = ang
def interpolate_mobject(self, alpha):
self.mobject.become(self.starting_mobject)
self.mobject.rotate(
self.ang * alpha,
about_point=self.mobject.get_center()
)
self.mobject.shift(
self.distance * alpha
)
# Scene name capitalized
class Proof(Scene):
STEP = 1
def print_name(sub_scene):
def _sub_scene(self):
name = sub_scene.__name__
name_split = ' '.join(elem.upper() for elem in name.split("_"))
print(f"--- Subscene #{self.STEP} - {name_split}")
sub_scene(self)
print()
self.STEP += 1
return _sub_scene
def construct(self):
self.draw_square_with_triangles()
self.moves_group_to_left()
self.draw_right_square()
self.move_the_triangles_to_right_square()
self.show_sub_squares_and_subformulas()
self.transform_subformulas_into_theorem()
# SUB-SCENES
@print_name
def draw_square_with_triangles(self):
self.left_group = PythagoreanGroupOneSquare()
bs, tr, hs = self.left_group
self.play(
DrawBorderThenFill(VGroup(bs,tr)),
run_time=4
)
self.wait()
@print_name
def moves_group_to_left(self):
self.right_group = PythagoreanGroupTwoSquares()
self.left_group.generate_target()
VGroup(
self.left_group.target, self.right_group
).arrange(RIGHT,buff=1)
self.play(
MoveToTarget(self.left_group)
)
self.wait()
@print_name
def draw_right_square(self):
self.play(
TransformFromCopy(
self.left_group.big_square,
self.right_group.big_square
)
)
self.wait()
@print_name
def move_the_triangles_to_right_square(self):
# self.play(
# TransformFromCopy(
# self.left_group.triangles,
# self.right_group.triangles
# ),
# run_time=4
# )
self.play(
LaggedStart(*[
MoveAndShift(
s_t.copy(), e_t.get_center(), angle,
run_time=1.7
)
for s_t, e_t, angle in zip(
self.left_group.triangles, self.right_group.triangles,
[0, 0, -PI/2, PI/2]
)
])
)
self.wait()
@print_name
def show_sub_squares_and_subformulas(self):
# mobs definition
group = VGroup(
self.left_group.hip_square,
self.right_group.small_square,
self.right_group.med_square,
).set_style(
stroke_opacity=2,
fill_opacity=DEFAULT_OPACITY
)
# formulas definition
formulas = VGroup(*[
TexMobject(t)[0].move_to(square)
for t,square in zip(["c^2","a^2","b^2"], group)
])
self.play(
*list(map(DrawBorderThenFill,group))
)
self.wait()
self.play(
Write(formulas)
)
self.wait()
self.formulas = formulas
@print_name
def transform_subformulas_into_theorem(self):
theorem = TexMobject("c^2", "=", "a^2", "+", "b^2",color=BLUE)
theorem.scale(1.6)
theorem.to_edge(DOWN)
theorem_target = VGroup(theorem[0],theorem[2],theorem[-1])
self.play(
Write(VGroup(theorem[1],theorem[3])),
TransformFromCopy(self.formulas,theorem_target),
run_time=4
)
self.wait(3)
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/pyth_proof.py | from manimlib.imports import *
SQUARE_CONFIG = {
"color": WHITE,
"side_length": 4
}
TRIANGLE_CONFIG = {
"color": ORANGE,
"stroke_width": 1,
"fill_opacity": 0.7
}
class LeftGroup(VGroup):
CONFIG = {
"square_config": SQUARE_CONFIG,
"triangle_config": TRIANGLE_CONFIG,
}
def __init__(self, alpha=0.2,**kwargs):
super().__init__(**kwargs)
square = self.get_square_from_config()
triangles = self.get_triangles_from_config(square, alpha)
self.add(square, triangles)
def get_square_from_config(self):
return Square(**self.square_config)
def get_square_corners(self, square):
return [
square.point_from_proportion(alpha_corners)
for alpha_corners in np.arange(0, 1, 0.25)
]
def get_triangles_from_config(self, square, alpha):
# c1, c2, c3, c4
corners_coords = self.get_square_corners(square)
# l = side_length
side_length = square.side_length / 4
# l * alpha / 4
side_proportion = (1-alpha) * side_length / 4
# p1, p2, p3, p4
middle_points = [
square.point_from_proportion((start + side_proportion)%1)
for start in np.arange(0, 1, 0.25)
]
triangle_ponts = [
(c1, p1, p2)
for c1, p1, p2 in zip(
corners_coords,
middle_points,
[middle_points[-1],*middle_points[:-1]]
)
]
return VGroup(*[
Polygon(*tg, **self.triangle_config)
for tg in triangle_ponts
])
class RightGroup(LeftGroup):
def get_triangles_from_config(self, square, alpha):
left_edge = square.get_left()[0]
down_edge = square.get_bottom()[1]
# c1, c2, c3, c4
c1, c2, c3, c4 = self.get_square_corners(square)
# l = side_length
side_length = square.side_length
# l * alpha / 4
x_side_proportion = alpha * side_length
c_x = left_edge + x_side_proportion
c_y = down_edge + x_side_proportion
c = [c_x, c_y, 0]
m1, m2, m3, m4 = [
c1 + RIGHT * x_side_proportion,
c3 + UP * x_side_proportion,
c4 + RIGHT * x_side_proportion,
c4 + UP * x_side_proportion
]
triangle_ponts= [
(c, p1, p2)
for c, p1, p2 in zip(
# t1 t2, t3, t4
[c1, c1, c3, c],
[c , c, m2, m2],
[m4, m1, m3, m3]
)
]
return VGroup(*[
Polygon(*tg, **self.triangle_config)
for tg in triangle_ponts
])
class MoveAndRotate(Animation):
CONFIG = {
"run_time": 2,
}
def __init__(self, mob, target, angle=PI/2, **kwargs):
digest_config(self, kwargs)
self.mobject = mob
self.mob_target = target
self.angle = angle
def interpolate_mobject(self, alpha):
self.mobject.become(self.starting_mobject)
self.mobject.move_to(
Line(
self.mobject.get_center(),
self.mob_target.get_center()
).point_from_proportion(alpha)
)
angle = interpolate(0,self.angle,alpha)
self.mobject.rotate(
angle,
about_point=self.mobject.get_center(),
)
class PythagoreanProof(Scene):
def setup(self):
self.left_group = LeftGroup()
self.right_group = RightGroup()
def construct(self):
self.show_left_group_at_center()
self.move_left_group_to_left()
self.show_right_rectangle()
self.transform_triangle()
def show_left_group_at_center(self):
self.play(
DrawBorderThenFill(self.left_group)
)
def move_left_group_to_left(self):
self.left_group.generate_target()
VGroup(self.left_group.target, self.right_group).arrange(RIGHT)
self.play(
MoveToTarget(self.left_group)
)
def show_right_rectangle(self):
self.play(
TransformFromCopy(
self.left_group[0],
self.right_group[0]
)
)
def transform_triangle(self):
lg, rg = self.left_group, self.right_group
lgt = lg[1]
rgt = rg[1]
rt1, rt2, rt3, rt4 = rgt
lt1, lt2, lt3, lt4 = lgt
self.play(
*[
ApplyMethod(t1.copy().move_to,t2)
for t1,t2 in [(lt2, rt2), (lt3, rt3)]
],
*[
MoveAndRotate(t1.copy(),t2,a)
for t1,t2,a in zip(
[lt1, lt4],
[rt1, rt4],
[PI/2, -PI/2]
)
]
)
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/manimgl_examples.py | from manimlib import *
# _ _
# __ _ _ __ (_)_ __ ___ __ _| |_ ___
# / _` | '_ \| | '_ ` _ \ / _` | __/ _ \
# | (_| | | | | | | | | | | (_| | || __/
# (_)__,_|_| |_|_|_| |_| |_|\__,_|\__\___|
class AnimateMethod(Scene):
def construct(self):
sq = Square()
sq.save_state()
self.add(sq)
# New form
self.play(
sq.animate.to_edge(DOWN,buff=1)
)
self.wait()
self.play(Restore(sq))
self.wait()
# Old form still works
self.play(
sq.to_edge,DOWN,{"buff": 1}
)
self.wait()
# Multiple methods
self.play(
sq.animate
.scale(2)
.set_color(ORANGE)
.to_corner(UR,buff=1)
)
self.wait()
# _ _ _ _
# (_)___ ___ | | __ _| |_ ___ | |_ _____ __
# | / __|/ _ \| |/ _` | __/ _ \ | __/ _ \ \/ /
# | \__ \ (_) | | (_| | || __/ | || __/> <
# |_|___/\___/|_|\__,_|\__\___| \__\___/_/\_\
#class IsolateTex1(Scene): # THIS IS DEPRECATED, use isolate instead
# def construct(self):
#t1 = Tex("{{x}}")
#t2 = Tex("{{x}} - {{x}}")
#VGroup(t1,t2)\
# .scale(3)\
# .arrange(DOWN)
#self.add(t1)
#self.wait()
#self.play(
# TransformMatchingTex(t1,t2),
# run_time=4
#)
#self.wait()
class IsolateTex1v2(Scene):
def construct(self):
isolate_tex = ["x"]
t1 = Tex("x",isolate=isolate_tex)
t2 = Tex("x - x",isolate=isolate_tex)
VGroup(t1,t2)\
.scale(3)\
.arrange(DOWN)
self.add(t1)
self.wait()
self.play(
TransformMatchingTex(t1,t2),
run_time=4
)
self.wait()
class IsolateTex1v3(Scene):
def construct(self):
t1 = Tex("x")
t2 = Tex("x - x")
VGroup(t1,t2)\
.scale(3)\
.arrange(DOWN)
self.add(t1)
self.wait()
self.play(
# If the formula is complex this animation will not work.
TransformMatchingShapes(t1,t2),
run_time=4
)
self.wait()
class IsolateTex2(Scene):
def construct(self):
isolate_tex = ["x","y","3","="]
t1 = Tex("x+y=3",isolate=isolate_tex)
t2 = Tex("x=3-y",isolate=isolate_tex)
VGroup(t1,t2)\
.scale(3)
t2.align_to(t1,LEFT)
self.add(t1)
self.wait()
self.play(
TransformMatchingTex(
t1,t2,
# Try removing this dictionary
key_map={
"+":"-"
}
),
run_time=4
)
self.wait()
class IsolateTex3(Scene):
def construct(self):
isolate_tex = ["a","b","c","="]
t1 = Tex("a\\times b = c",isolate=isolate_tex)
t2 = Tex("a = { c \\over b }",isolate=isolate_tex)
VGroup(t1,t2)\
.scale(3)
t2.align_to(t1,LEFT)
self.add(t1)
self.wait()
self.play(
TransformMatchingTex(
t1,t2,
key_map={
"\\times":"\\over"
}
),
run_time=4
)
self.wait()
# _____ _ _____ __
# | ___|_ _ __| | __|_ _| __ __ _ _ __ ___ / _| ___ _ __ _ __ ___
# | |_ / _` |/ _` |/ _ \| || '__/ _` | '_ \/ __| |_ / _ \| '__| '_ ` _ \
# | _| (_| | (_| | __/| || | | (_| | | | \__ \ _| (_) | | | | | | | |
# |_| \__,_|\__,_|\___||_||_| \__,_|_| |_|___/_| \___/|_| |_| |_| |_|
class FadeTransformExample(Scene):
def construct(self):
m1 = Text("Hello world").to_corner(UL)
m2 = Text("I'm FadeTransform").to_corner(DR)
self.add(m1)
self.wait()
self.play(
# Equivalent to ReplacementTransform
FadeTransform(m1,m2),
run_time=4
)
class ExtrangeTransform(Scene):
def construct(self):
t1 = Tex("e^","\\frac{-it\\pi}{\\omega}")
t2 = Tex("\\frac{-it\\pi}{\\omega}")
VGroup(t1,t2)\
.scale(3)\
.arrange(DOWN,buff=2)
self.add(t1,t2.copy().fade(0.8))
self.wait()
self.play(
TransformFromCopy(t1[-1],t2[0]),
run_time=6
)
self.wait()
class ExtrangeTransformFixed(Scene):
def construct(self):
t1 = Tex("e^","\\frac{-it\\pi}{\\omega}")
t2 = Tex("\\frac{-it\\pi}{\\omega}")
VGroup(t1,t2)\
.scale(3)\
.arrange(DOWN,buff=2)
self.add(t1,t2.copy().fade(0.8))
self.wait()
self.play(
FadeTransformPieces(t1[-1].copy(),t2[0]),
run_time=4
)
self.wait()
# ____ _ ____
# / ___|_ __ __ _ _ __ | |__ / ___| ___ ___ _ __ ___
# | | _| '__/ _` | '_ \| '_ \\___ \ / __/ _ \ '_ \ / _ \
# | |_| | | | (_| | |_) | | | |___) | (_| __/ | | | __/
# \____|_| \__,_| .__/|_| |_|____/ \___\___|_| |_|\___|
# |_|
class AxesExample(Scene):
def construct(self):
X_MIN = -5
X_MAX = 5
# You can have multiple Axes
axes_config = {
# [min, max, step]
"x_range": [X_MIN,X_MAX,0.5],
"y_range": [-3,3,1],
"height": FRAME_HEIGHT - 2,
"width": FRAME_WIDTH - 2,
"axis_config": {
"include_tip": True,
"numbers_to_exclude": [0],
},
"x_axis_config": {
# see manimlib/mobjects/number_line.py
"line_to_number_buff": 0.5,
"line_to_number_direction": UP,
"color": RED
},
"y_axis_config": {
"decimal_number_config": {
# see manimlib/mobjects/numbers.py
"num_decimal_places": 1,
},
},
}
axes = Axes(**axes_config)
axes.add_coordinate_labels(font_size=20)
graph = axes.get_graph(
lambda x: np.sin(x),
x_min=X_MIN,
x_max=X_MAX
)
self.add(axes,graph)
# _____ _ ____ ____
# |_ _| |__ _ __ ___ ___| _ \/ ___| ___ ___ _ __ ___
# | | | '_ \| '__/ _ \/ _ \ | | \___ \ / __/ _ \ '_ \ / _ \
# | | | | | | | | __/ __/ |_| |___) | (_| __/ | | | __/
# |_| |_| |_|_| \___|\___|____/|____/ \___\___|_| |_|\___|
# New 3D mobjects
class Sphere(Surface):
CONFIG = {
"radius": 1,
"u_range": (0, TAU),
"v_range": (0, PI),
}
def uv_func(self, u, v):
return self.radius * np.array([
np.cos(u) * np.sin(v),
np.sin(u) * np.sin(v),
-np.cos(v)
])
class Torus(Surface):
CONFIG = {
"u_range": (0, TAU),
"v_range": (0, TAU),
"r1": 3,
"r2": 1,
}
def uv_func(self, u, v):
P = np.array([math.cos(u), math.sin(u), 0])
return (self.r1 - self.r2 * math.cos(v)) * P - math.sin(v) * OUT
class ThreeDSceneExample(Scene):
CONFIG = {
"camera_class": ThreeDCamera,
}
def construct(self):
surface_text = Text("For 3d scenes, try using surfaces")
surface_text.fix_in_frame()
surface_text.to_edge(UP)
self.add(surface_text)
self.wait(0.1)
torus1 = Torus(r1=1, r2=1)
torus2 = Torus(r1=3, r2=1)
sphere = Sphere(radius=3, resolution=torus1.resolution)
# Set perspective
frame = self.camera.frame
frame.set_euler_angles(
theta=-30 * DEGREES,
phi=70 * DEGREES,
)
torus2.mesh = SurfaceMesh(torus2)
sphere.mesh = SurfaceMesh(sphere)
surface = sphere
surface.save_state()
self.play(
ShowCreation(surface)
)
self.wait()
self.play(
Transform(surface,torus1)
)
self.wait()
self.play(
Transform(surface,torus2)
)
self.wait()
self.play(Write(torus2.mesh))
self.wait()
self.play(
Restore(surface),
ReplacementTransform(
torus2.mesh,
sphere.mesh
)
)
self.wait()
class ThreeDScene(Scene):
CONFIG = {
"camera_class": ThreeDCamera,
}
def setup(self):
frame = self.camera.frame
frame.set_euler_angles(
theta=-30 * DEGREES,
phi=70 * DEGREES,
)
self.frame = frame
class Functions3D(ThreeDScene):
def construct(self):
axes = ThreeDAxes()
para_hyp = ParametricSurface(
lambda u, v: np.array([
u,
v,
u**2-v**2
]),
v_range=(-2,2),
u_range=(-2,2),
opacity=0.5,
color=RED,
resolution=(15, 32)
)
para_hyp.mesh = SurfaceMesh(para_hyp)
func = Tex("x^2-y^2=z")
func.fix_in_frame()
func.to_corner(DL)
self.play(ShowCreation(axes))
self.play(
ShowCreation(para_hyp),
ShowCreation(para_hyp.mesh),
run_time=3
)
# Set perspective
frame = self.frame
self.play(
# Move camera frame during the transition
frame.animate.increment_phi(10 * DEGREES),
frame.animate.increment_theta(60 * DEGREES),
run_time=3
)
# Add ambient rotation
frame.add_updater(lambda m, dt: m.increment_theta(-0.1 * dt))
self.wait(3)
self.play(Write(func))
self.wait(3)
light = self.camera.light_source
self.add(light)
light.save_state()
self.play(light.animate.move_to(3 * IN), run_time=5)
self.play(light.animate.shift(10 * OUT), run_time=5)
self.wait(3)
self.play(Restore(light))
self.wait(3)
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/leave_progress_bars_by_default/steps.md | # Cómo programar barras de progreso por defecto.
## 1. Abre ```manimlib/config.py``` y realizar los siguientes cambios:
### 1.1 Realiza los cambios en la linea 101, 102 y 103 como se muestra en la imagen.
En la linea 101 cambia ```"--leave_progress_bars"``` por ```"--remove_progress_bars"```.
En la linea 102 cambia ```"store_true"``` por ```"store_false"```.
Opcional: En la linea 103 cambia ```"Leave progress bars displayed in terminal"``` por ```"Remove progress bars displayed in terminal"```.
```python3
parser.add_argument(
"--remove_progress_bars",
action="store_false",
help="Remove progress bars displayed in terminal",
)
```
<p align="center"><img src ="/Español/extras/programar_barras_progreso_por_defecto/capturas/capt1.png" /></p>
### 1.2 Realiza el cambio que se ve en la linea 183.
Cambia ```python3 "leave_progress_bars": args.leave_progress_bars``` por ```python3 "remove_progress_bars": args.remove_progress_bars```.
```python3
"remove_progress_bars": args.remove_progress_bars
```
<p align="center"><img src ="/Español/extras/programar_barras_progreso_por_defecto/capturas/capt2.png" /></p>
## 2. Abre ```manimlib/extract_scene.py``` y realiza el siguiente cambio en la linea 146.
Cambia ```python3 "leave_progress_bars",``` por ```python3 "remove_progress_bars",```.
```python3
"remove_progress_bars",
```
<p align="center"><img src ="/Español/extras/programar_barras_progreso_por_defecto/capturas/capt3.png" /></p>
## 3. Abre ```manimlib/scene/scene.py``` y realiza los siguientes cambios.
### 3.1 En la linea 31 cambia ```python3 "leave_progress_bars": False``` por ```python3 "remove_progress_bars": False```.
```python3
"remove_progress_bars": False,
```
<p align="center"><img src ="/Español/extras/programar_barras_progreso_por_defecto/capturas/capt4.png" /></p>
### 3.2 En la linea 31 cambia ```python3 leave=self.leave_progress_bars,``` por ```python3 leave=self.remove_progress_bars,```.
```python3
leave=self.remove_progress_bars,
```
<p align="center"><img src ="/Español/extras/programar_barras_progreso_por_defecto/capturas/capt5.png" /></p> |
AnimationsWithManim_Elteoremadebeethoven/English/extra/advanced/advanced_animations.py | from manimlib.imports import *
from screen_grid import ScreenGrid
class Scene(Scene):
CONFIG = {
"camera_config":{"background_color":"#161616"},
"include_grid":True
}
def setup(self):
if self.include_grid:
self.add(ScreenGrid().fade(0.7))
r"""
_ __ __ _ _ _
/ | | \/ | ___| |_| |__ ___ __| |___ __ _ ___
| | | |\/| |/ _ \ __| '_ \ / _ \ / _` / __| / _` / __|
| |_ | | | | __/ |_| | | | (_) | (_| \__ \ | (_| \__ \
|_(_) |_| |_|\___|\__|_| |_|\___/ \__,_|___/ \__,_|___/
_ _ _
__ _ _ __ (_)_ __ ___ __ _| |_(_) ___ _ __ ___
/ _` | '_ \| | '_ ` _ \ / _` | __| |/ _ \| '_ \/ __|
| (_| | | | | | | | | | | (_| | |_| | (_) | | | \__ \
\__,_|_| |_|_|_| |_| |_|\__,_|\__|_|\___/|_| |_|___/
"""
"""
See manimlib/mobject/mobject.py
===============================
def to_edge(self, edge=LEFT, buff=DEFAULT_MOBJECT_TO_EDGE_BUFFER):
----------
Default:
edge = LEFT
buff = DEFAULT_MOBJECT_TO_EDGE_BUFFER
"""
class ToEdgeAnimation1(Scene):
def construct(self):
mob = Circle()
self.add(mob)
self.play(
# If we do not enter parameters then
# the animation will use the default ones
mob.to_edge,
)
self.wait()
class ToEdgeAnimation2(Scene):
def construct(self):
mob = Circle()
self.add(mob)
self.play(
# edge
mob.to_edge, UP
)
self.wait()
class ToEdgeAnimation3(Scene):
def construct(self):
mob = Circle()
self.add(mob)
self.play(
# edge, buff
mob.to_edge, UP , 0
)
self.wait()
# Change specific parameters
class ToEdgeAnimation4(Scene):
def construct(self):
mob = Circle()
self.add(mob)
self.play(
# To modify only a single paramter
# the edge = LEFT by default
mob.to_edge,{"buff":0},
)
self.wait()
# Multiple animations
class ToEdgeAnimation5(Scene):
def construct(self):
mob = Circle()
self.add(mob)
self.play(
# Order matters
mob.scale,0.5,
mob.to_edge,{"buff":0},
)
self.wait()
class ToEdgeAnimation6(Scene):
def construct(self):
mob = Circle()
mob.generate_target()
# Order still matters
mob.target.scale(0.1)
mob.target.to_edge(RIGHT,buff=0)
self.add(mob)
self.play(
MoveToTarget(mob)
)
self.wait()
"""
def scale(self, scale_factor, **kwargs):
------------
scale_factor is not predefined
---
"""
class ScaleAnimation(Scene):
def construct(self):
mob = Circle()
dot = Dot([6,0,0])
self.add(mob,dot)
self.play(
mob.scale,3
)
self.play(
# But if we want more args we have to use a dictionary
mob.scale,1/3,{"about_point":dot.get_center()}
# Replace dot.get_center() with ORIGIN
)
self.wait()
"""
def arrange(self, direction=RIGHT, center=True, **kwargs):
-----------------------------
"""
class ArrangeAnimation1(Scene):
def construct(self):
vgroup = VGroup(
Square(),
Circle()
)
self.add(vgroup)
self.wait()
self.play(vgroup.arrange,DOWN)
self.wait()
class ArrangeAnimation2(Scene):
def construct(self):
vgroup = VGroup(
Square(),
Circle()
)
self.add(vgroup)
self.wait()
self.play(vgroup.arrange,DOWN,{"buff":0})
self.wait()
class ArrangeAnimation3(Scene):
def construct(self):
vgroup = VGroup(
Square(),
Circle()
)
text = TextMobject("Hello world").to_corner(UL)
self.add(vgroup)
self.wait()
self.play(
vgroup.arrange,DOWN,{"buff":0},
Write(text)
)
self.wait()
"""
def shift(self, *vectors):
--------
args
"""
class ShiftAnimation1Fail(Scene):
def construct(self):
mob = Circle()
self.add(mob)
self.play(
# We can set "n" paraters
FadeToColor(mob,TEAL),
mob.shift,LEFT,LEFT,
# FadeToColor is a MoveToTarget method
)
self.wait()
class ShiftAnimation1(Scene):
def construct(self):
mob = Circle()
self.add(mob)
self.play(
mob.shift,LEFT,LEFT,LEFT,
mob.set_color,TEAL,
# Color,width,opacity
mob.set_stroke,None,20,
mob.scale,2,
)
self.wait()
# Problems with Groups
class MultipleAnimationVGroupFail(Scene):
def construct(self):
rect, circ = Rectangle(), Circle()
vgroup = VGroup(rect, circ)
self.add(vgroup)
self.play(
vgroup.arrange,DOWN,
rect.set_height,1,
)
self.wait()
class MultipleAnimationVGroup(Scene):
def construct(self):
rect, circ = Rectangle(), Circle()
vgroup = VGroup(rect, circ)
def modify(vg):
r,c = vg
r.set_height(1)
vg.arrange(DOWN,buff=2)
return vg
self.add(vgroup)
self.play(
ApplyFunction(modify, vgroup)
)
self.wait()
r"""
____ _ _ _ _
|___ \ | | (_)_ __ ___ __ _ _ __(_) |_ _ _
__) | | | | | '_ \ / _ \/ _` | '__| | __| | | |
/ __/ _ | |___| | | | | __/ (_| | | | | |_| |_| |
|_____(_) |_____|_|_| |_|\___|\__,_|_| |_|\__|\__, |
|___/
_ _
_ __ _ __ ___ | |__ | | ___ _ __ ___ ___
| '_ \| '__/ _ \| '_ \| |/ _ \ '_ ` _ \/ __|
| |_) | | | (_) | |_) | | __/ | | | | \__ \
| .__/|_| \___/|_.__/|_|\___|_| |_| |_|___/
|_|
"""
"""
def rotate(self, angle, axis=OUT, **kwargs):
"""
class RotationAnimationFail(Scene):
def construct(self):
square1, square2 = VGroup(
Square(),
Square(color=TEAL)
).scale(0.3).set_y(-3)
reference = DashedVMobject(Circle(radius=3,color=GRAY))
self.add(square1,square2,reference)
self.play(
# White square
square1.rotate,2*PI/3,{"about_point":ORIGIN},
# Teal square
Rotate(square2,2*PI/3,about_point=ORIGIN),
run_time=4
)
self.wait()
class RotationAndMoveFail(Scene):
def construct(self):
square1, square2 = VGroup(
Square(color=RED), Square(color=BLUE)
).scale(0.5).set_x(-5)
reference = DashedVMobject(Line(LEFT*5,RIGHT*5,color=GRAY))
self.add(square1,square2,reference)
square2.save_state()
def update_rotate_move(mob,alpha):
square2.restore()
square2.shift(RIGHT*10*alpha)
square2.rotate(3*PI*alpha)
self.play(
# Red square FAIL
square1.rotate,3*PI,
square1.move_to, [5,0,0],
# Blue square
UpdateFromAlphaFunc(square2,update_rotate_move),
run_time=4
)
# Creating a custom animation
class ShiftAndRotate(Animation):
CONFIG = {
"axis": OUT,
"run_time": 5,
"rate_func": smooth,
"about_point": None,
"about_edge": None,
}
def __init__(self, mobject, direction, radians,**kwargs):
assert(isinstance(mobject, Mobject))
digest_config(self, kwargs)
self.mobject = mobject
self.direction = direction
self.radians = radians
def interpolate_mobject(self, alpha):
self.mobject.become(self.starting_mobject)
self.mobject.shift(alpha*self.direction)
self.mobject.rotate(
alpha * self.radians,
axis=self.axis,
about_point=self.about_point,
about_edge=self.about_edge,
)
class RotationAndMove(Scene):
def construct(self):
square1, square2 = VGroup(
Square(color=RED), Square(color=BLUE)
).scale(0.5).set_x(-5)
reference = DashedVMobject(Line(LEFT*5,RIGHT*5,color=GRAY))
self.add(square1,square2,reference)
self.play(
# Red square
square1.rotate,3*PI,
square1.move_to, [5,0,0],
# Blue square
ShiftAndRotate(square2, RIGHT*10, 3*PI),
run_time=4
)
self.wait()
"""
WHAT IS "point_from_proportion"
This is a path (Line):
*---------------------------------*
| |
start end
path.point_from_proportion(alpha):
alpha = 0 alpha = 1
v v
*--------*-------*--------*-------*
^ ^ ^
| alpha = 0.5 |
| |
alpha = 0.25 alpha = 0.75
"""
class RotateWithPath(Scene):
def construct(self):
square1, square2 = VGroup(
Square(color=RED), Square(color=BLUE)
).scale(0.5).set_x(-5)
path = Line(LEFT*5,RIGHT*5,stroke_opatity=0.5)
path.points[1:3] += UP*2
square2.save_state()
def update_rotate_move(mob,alpha):
square2.restore()
square2.move_to(path.point_from_proportion(alpha))
square2.rotate(3*PI*alpha)
self.add(square1,square2,path)
self.play(
# Red square
MoveAlongPath(square1,path),
Rotate(square1,2*PI/3,about_point=square1.get_center()),
# Blue square
UpdateFromAlphaFunc(square2,update_rotate_move),
run_time=4
)
self.wait()
class MoveAlongPathWithAngle(Scene):
def get_pending(self,path,proportion,dx=0.01):
if proportion < 1:
coord_i = path.point_from_proportion(proportion)
coord_f = path.point_from_proportion(proportion+dx)
else:
coord_i = path.point_from_proportion(proportion-dx)
coord_f = path.point_from_proportion(proportion)
line = Line(coord_i,coord_f)
angle = line.get_angle()
return angle
def construct(self):
# PATH
path = Line(LEFT*5, RIGHT*5, stroke_opatity=0.5)
path.points[1] += UP * 4
path.points[2] += DOWN * 4
start_angle = self.get_pending(path, 0)
# TRIANGLE
triangle = Triangle().set_height(0.5)
triangle.move_to(path.get_start())
triangle.rotate(- PI / 2)
triangle.save_state()
triangle.rotate(start_angle, about_point=triangle.get_center())
def update_rotate_move(mob,alpha):
triangle.restore()
angle = self.get_pending(path,alpha)
triangle.move_to(path.point_from_proportion(alpha))
triangle.rotate(angle, about_point=triangle.get_center())
self.add(triangle,path)
self.play(
UpdateFromAlphaFunc(triangle,update_rotate_move),
run_time=4
)
self.wait()
# Creating a custom animation
def get_path_pending(path,proportion,dx=0.001):
if proportion < 1:
coord_i = path.point_from_proportion(proportion)
coord_f = path.point_from_proportion(proportion+dx)
else:
coord_i = path.point_from_proportion(proportion-dx)
coord_f = path.point_from_proportion(proportion)
line = Line(coord_i,coord_f)
angle = line.get_angle()
return angle
class ShiftAndRotateAlongPath(Animation):
CONFIG = {
"run_time": 5,
"rate_func": smooth,
"dx":0.01
}
def __init__(self, mobject, path,**kwargs):
assert(isinstance(mobject, Mobject))
digest_config(self, kwargs)
self.mobject = mobject
self.path = path
def interpolate_mobject(self, alpha):
self.mobject.become(self.starting_mobject)
self.mobject.move_to(
self.path.point_from_proportion(alpha)
)
angle = get_path_pending(self.path,alpha,self.dx)
self.mobject.rotate(
angle,
about_point=self.mobject.get_center(),
)
class MoveAlongPathWithAngle2(Scene):
def construct(self):
path = Line(LEFT*5, RIGHT*5, stroke_opatity=0.5)
path.points[1] += UP * 4
path.points[2] += DOWN * 4
start_angle = get_path_pending(path, 0)
triangle = Triangle().set_height(0.5)
triangle.move_to(path.get_start())
triangle.rotate(- PI / 2)
self.add(triangle,path)
self.play(
ShiftAndRotateAlongPath(triangle,path),
run_time=4
)
self.wait()
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/advanced/resume.md | # Advanced Animations 1
To use this scenes you have to download [this](https://github.com/Elteoremadebeethoven/MyAnimations/blob/master/screen_grid/screen_grid.py) code.
```python
from manimlib.imports import *
from screen_grid import ScreenGrid
class Scene(Scene):
CONFIG = {
"camera_config":{"background_color":"#161616"},
"include_grid":True
}
def setup(self):
if self.include_grid:
self.add(ScreenGrid().fade(0.7))
```
## 1. Methods as animations
In manimlib/mobject/mobject.py we can see this:
```python
def to_edge(self, edge=LEFT, buff=DEFAULT_MOBJECT_TO_EDGE_BUFFER):
# ----------
# Default:
# edge = LEFT
# buff = DEFAULT_MOBJECT_TO_EDGE_BUFFER
```
### ToEdgeAnimation1
```python
class ToEdgeAnimation1(Scene):
def construct(self):
mob = Circle()
self.add(mob)
self.play(
# If we do not enter parameters then
# the animation will use the default ones
mob.to_edge,
)
self.wait()
```
<p align="center"><img src ="./gifs/ToEdgeAnimation1.gif" /></p>
### ToEdgeAnimation2
```python
class ToEdgeAnimation2(Scene):
def construct(self):
mob = Circle()
self.add(mob)
self.play(
# edge
mob.to_edge, UP
)
self.wait()
```
<p align="center"><img src ="./gifs/ToEdgeAnimation2.gif" /></p>
### ToEdgeAnimation3
```python
class ToEdgeAnimation3(Scene):
def construct(self):
mob = Circle()
self.add(mob)
self.play(
# edge, buff
mob.to_edge, UP , 0
)
self.wait()
```
<p align="center"><img src ="./gifs/ToEdgeAnimation3.gif" /></p>
### ToEdgeAnimation4
```python
class ToEdgeAnimation4(Scene):
def construct(self):
mob = Circle()
self.add(mob)
self.play(
# To modify only a single paramter
# the edge = LEFT by default
mob.to_edge,{"buff":0},
)
self.wait()
```
<p align="center"><img src ="./gifs/ToEdgeAnimation4.gif" /></p>
### ToEdgeAnimation5
```python
class ToEdgeAnimation5(Scene):
def construct(self):
mob = Circle()
self.add(mob)
self.play(
# Order matters
mob.scale,0.5,
mob.to_edge,{"buff":0},
)
self.wait()
```
<p align="center"><img src ="./gifs/ToEdgeAnimation5.gif" /></p>
### ToEdgeAnimation6
```python
class ToEdgeAnimation6(Scene):
def construct(self):
mob = Circle()
mob.generate_target()
# Order still matters
mob.target.scale(0.1)
mob.target.to_edge(RIGHT,buff=0)
self.add(mob)
self.play(
MoveToTarget(mob)
)
self.wait()
```
<p align="center"><img src ="./gifs/ToEdgeAnimation6.gif" /></p>
### ScaleAnimation
```python
class ScaleAnimation(Scene):
def construct(self):
mob = Circle()
dot = Dot([6,0,0])
self.add(mob,dot)
self.play(
mob.scale,3
)
self.play(
# But if we want more args we have to use a dictionary
mob.scale,1/3,{"about_point":dot.get_center()}
# Replace dot.get_center() with ORIGIN
)
self.wait()
```
<p align="center"><img src ="./gifs/ScaleAnimation.gif" /></p>
### ArrangeAnimation1
```python
"""
def arrange(self, direction=RIGHT, center=True, **kwargs):
-----------------------------
"""
class ArrangeAnimation1(Scene):
def construct(self):
vgroup = VGroup(
Square(),
Circle()
)
self.add(vgroup)
self.wait()
self.play(vgroup.arrange,DOWN)
self.wait()
```
<p align="center"><img src ="./gifs/ArrangeAnimation1.gif" /></p>
### ArrangeAnimation2
```python
class ArrangeAnimation2(Scene):
def construct(self):
vgroup = VGroup(
Square(),
Circle()
)
self.add(vgroup)
self.wait()
self.play(vgroup.arrange,DOWN,{"buff":0})
self.wait()
```
<p align="center"><img src ="./gifs/ArrangeAnimation2.gif" /></p>
### ArrangeAnimation3
```python
class ArrangeAnimation3(Scene):
def construct(self):
vgroup = VGroup(
Square(),
Circle()
)
text = TextMobject("Hello world").to_corner(UL)
self.add(vgroup)
self.wait()
self.play(
vgroup.arrange,DOWN,{"buff":0},
Write(text)
)
self.wait()
```
<p align="center"><img src ="./gifs/ArrangeAnimation3.gif" /></p>
### ShiftAnimation1Fail
```python
"""
def shift(self, *vectors):
--------
args
"""
class ShiftAnimation1Fail(Scene):
def construct(self):
mob = Circle()
self.add(mob)
self.play(
# We can set "n" paraters
FadeToColor(mob,TEAL),
mob.shift,LEFT,LEFT,
# FadeToColor is a MoveToTarget method
)
self.wait()
```
<p align="center"><img src ="./gifs/ShiftAnimation1Fail.gif" /></p>
### ShiftAnimation1
```python
class ShiftAnimation1(Scene):
def construct(self):
mob = Circle()
self.add(mob)
self.play(
mob.shift,LEFT,LEFT,LEFT,
mob.set_color,TEAL,
# Color,width,opacity
mob.set_stroke,None,20,
mob.scale,2,
)
self.wait()
```
<p align="center"><img src ="./gifs/ShiftAnimation1.gif" /></p>
## 2. Problems with VGroup
### MultipleAnimationVGroupFail
```python
class MultipleAnimationVGroupFail(Scene):
def construct(self):
rect, circ = Rectangle(), Circle()
vgroup = VGroup(rect, circ)
self.add(vgroup)
self.play(
vgroup.arrange,DOWN,
rect.set_height,1,
)
self.wait()
```
<p align="center"><img src ="./gifs/MultipleAnimationVGroupFail.gif" /></p>
### MultipleAnimationVGroup
```python
class MultipleAnimationVGroup(Scene):
def construct(self):
rect, circ = Rectangle(), Circle()
vgroup = VGroup(rect, circ)
def modify(vg):
r,c = vg
r.set_height(1)
vg.arrange(DOWN,buff=2)
return vg
self.add(vgroup)
self.play(
ApplyFunction(modify, vgroup)
)
self.wait()
```
<p align="center"><img src ="./gifs/MultipleAnimationVGroup.gif" /></p>
### RotationAnimationFail
```python
"""
def rotate(self, angle, axis=OUT, **kwargs):
"""
class RotationAnimationFail(Scene):
def construct(self):
square1, square2 = VGroup(
Square(),
Square(color=TEAL)
).scale(0.3).set_y(-3)
reference = DashedVMobject(Circle(radius=3,color=GRAY))
self.add(square1,square2,reference)
self.play(
# White square
square1.rotate,2*PI/3,{"about_point":ORIGIN},
# Teal square
Rotate(square2,2*PI/3,about_point=ORIGIN),
run_time=4
)
self.wait()
```
<p align="center"><img src ="./gifs/RotationAnimationFail.gif" /></p>
### RotationAndMoveFail
```python
class RotationAndMoveFail(Scene):
def construct(self):
square1, square2 = VGroup(
Square(color=RED), Square(color=BLUE)
).scale(0.5).set_x(-5)
reference = DashedVMobject(Line(LEFT*5,RIGHT*5,color=GRAY))
self.add(square1,square2,reference)
square2.save_state()
def update_rotate_move(mob,alpha):
square2.restore()
square2.shift(RIGHT*10*alpha)
square2.rotate(3*PI*alpha)
self.play(
# Red square FAIL
square1.rotate,3*PI,
square1.move_to, [5,0,0],
# Blue square
UpdateFromAlphaFunc(square2,update_rotate_move),
run_time=4
)
```
<p align="center"><img src ="./gifs/RotationAndMoveFail.gif" /></p>
### RotationAndMove
```python
# Creating a custom animation
class ShiftAndRotate(Animation):
CONFIG = {
"axis": OUT,
"run_time": 5,
"rate_func": smooth,
"about_point": None,
"about_edge": None,
}
def __init__(self, mobject, direction, radians,**kwargs):
assert(isinstance(mobject, Mobject))
digest_config(self, kwargs)
self.mobject = mobject
self.direction = direction
self.radians = radians
def interpolate_mobject(self, alpha):
self.mobject.become(self.starting_mobject)
self.mobject.shift(alpha*self.direction)
self.mobject.rotate(
alpha * self.radians,
axis=self.axis,
about_point=self.about_point,
about_edge=self.about_edge,
)
class RotationAndMove(Scene):
def construct(self):
square1, square2 = VGroup(
Square(color=RED), Square(color=BLUE)
).scale(0.5).set_x(-5)
reference = DashedVMobject(Line(LEFT*5,RIGHT*5,color=GRAY))
self.add(square1,square2,reference)
self.play(
# Red square
square1.rotate,3*PI,
square1.move_to, [5,0,0],
# Blue square
ShiftAndRotate(square2, RIGHT*10, 3*PI),
run_time=4
)
self.wait()
```
<p align="center"><img src ="./gifs/RotationAndMove.gif" /></p>
## 3. `point_from_proportion`
```python
"""
WHAT IS "point_from_proportion"
This is a path (Line):
*---------------------------------*
| |
start end
path.point_from_proportion(alpha):
alpha = 0 alpha = 1
v v
*--------*-------*--------*-------*
^ ^ ^
| alpha = 0.5 |
| |
alpha = 0.25 alpha = 0.75
"""
```
### RotateWithPath
```python
class RotateWithPath(Scene):
def construct(self):
square1, square2 = VGroup(
Square(color=RED), Square(color=BLUE)
).scale(0.5).set_x(-5)
path = Line(LEFT*5,RIGHT*5,stroke_opacity=0.5)
path.points[1:3] += UP*2
square2.save_state()
def update_rotate_move(mob,alpha):
square2.restore()
square2.move_to(path.point_from_proportion(alpha))
square2.rotate(3*PI*alpha)
self.add(square1,square2,path)
self.play(
# Red square
MoveAlongPath(square1,path),
Rotate(square1,2*PI/3,about_point=square1.get_center()),
# Blue square
UpdateFromAlphaFunc(square2,update_rotate_move),
run_time=4
)
self.wait()
```
<p align="center"><img src ="./gifs/RotateWithPath.gif" /></p>
### MoveAlongPathWithRotation
```python
class MoveAlongPathWithRotation(Scene):
def get_pending(self,path,proportion,dx=0.01):
if proportion < 1:
coord_i = path.point_from_proportion(proportion)
coord_f = path.point_from_proportion(proportion+dx)
else:
coord_i = path.point_from_proportion(proportion-dx)
coord_f = path.point_from_proportion(proportion)
line = Line(coord_i,coord_f)
angle = line.get_angle()
return angle
def construct(self):
# PATH
path = Line(LEFT*5, RIGHT*5, stroke_opatity=0.5)
path.points[1] += UP * 4
path.points[2] += DOWN * 4
start_angle = self.get_pending(path, 0)
# TRIANGLE
triangle = Triangle().set_height(0.5)
triangle.move_to(path.get_start())
triangle.rotate(- PI / 2)
triangle.save_state()
triangle.rotate(start_angle, about_point=triangle.get_center())
def update_rotate_move(mob,alpha):
triangle.restore()
angle = self.get_pending(path,alpha)
triangle.move_to(path.point_from_proportion(alpha))
triangle.rotate(angle, about_point=triangle.get_center())
self.add(triangle,path)
self.play(
UpdateFromAlphaFunc(triangle,update_rotate_move),
run_time=4
)
self.wait()
```
<p align="center"><img src ="./gifs/MoveAlongPathWithRotation.gif" /></p>
### MoveAlongPathWithRotation2
```python
# Creating a custom animation
def get_path_pending(path,proportion,dx=0.001):
if proportion < 1:
coord_i = path.point_from_proportion(proportion)
coord_f = path.point_from_proportion(proportion+dx)
else:
coord_i = path.point_from_proportion(proportion-dx)
coord_f = path.point_from_proportion(proportion)
line = Line(coord_i,coord_f)
angle = line.get_angle()
return angle
class ShiftAndRotateAlongPath(Animation):
CONFIG = {
"run_time": 5,
"rate_func": smooth,
"dx":0.01
}
def __init__(self, mobject, path,**kwargs):
assert(isinstance(mobject, Mobject))
digest_config(self, kwargs)
self.mobject = mobject
self.path = path
def interpolate_mobject(self, alpha):
self.mobject.become(self.starting_mobject)
self.mobject.move_to(
self.path.point_from_proportion(alpha)
)
angle = get_path_pending(self.path,alpha,self.dx)
self.mobject.rotate(
angle,
about_point=self.mobject.get_center(),
)
class MoveAlongPathWithRotation2(Scene):
def construct(self):
path = Line(LEFT*5, RIGHT*5, stroke_opatity=0.5)
path.points[1] += UP * 4
path.points[2] += DOWN * 4
start_angle = get_path_pending(path, 0)
triangle = Triangle().set_height(0.5)
triangle.move_to(path.get_start())
triangle.rotate(- PI / 2)
self.add(triangle,path)
self.play(
ShiftAndRotateAlongPath(triangle,path),
run_time=4
)
self.wait()
```
<p align="center"><img src ="./gifs/MoveAlongPathWithRotation2.gif" /></p>
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/advanced/check_svg.py | from manimlib.imports import *
class CheckSVG(Scene):
CONFIG={
"camera_config":{"background_color": WHITE},
"svg_type":"svg",
"get_cero":False,
"file":"",
"text":None,
"scale":None,
"width":None,
"height":None,
"color":BLACK,
"angle":0,
"flip":False,
"flip_edge":UP,
"fill_opacity": 1,
"fill_color": None,
"stroke_color": None,
"stroke_opacity":1,
"stroke_width": 3,
"number_type":"Font",
"sheen_factor":None,
"sheen_direction":None,
"gradient_color":False,
"gradient_colors":[BLUE,RED,GREEN],
"cycle_color":False,
"cycle_colors":[RED,BLUE,GREEN,YELLOW,PINK,ORANGE,PURPLE,TEAL,GRAY],
"numbers_scale":0.5,
"show_numbers": False,
"animation": False,
"remove": [],
"direction_numbers": UP,
"color_numbers": GOLD,
"space_between_numbers":0,
"show_elements":[],
"color_element":BLUE,
"set_size":"width",
"remove_stroke":[],
"show_stroke":[],
"show_stroke_stroke":1,
"warning_color":RED,
"wait_time":3,
"show_removers":True,
"background_stroke_width":0
}
def construct(self):
pre_imagen = self.get_svg()
if self.get_cero:
self.imagen=pre_imagen[0]
else:
self.imagen=pre_imagen
# Style
self.imagen.set_color(color=self.color)\
.set_style(
fill_opacity=self.fill_opacity,
stroke_color=self.stroke_color,
stroke_width=self.stroke_width,
stroke_opacity=self.stroke_opacity,
sheen_factor=self.sheen_factor,
sheen_direction=self.sheen_direction,
)
if self.gradient_color:
self.imagen.set_color_by_gradient(*self.gradient_colors)
if self.cycle_color:
get_cycle_color=it.cycle(self.cycle_colors)
for obj in self.imagen:
obj.set_color(next(get_cycle_color))
# Size settings
if self.width!=None:
self.imagen.set_width(self.width)
elif self.height!=None:
self.imagen.set_height(self.height)
elif self.scale!=None:
self.imagen.scale(self.scale)
else:
self.imagen.set_width(FRAME_WIDTH)
if self.imagen.get_height()>FRAME_HEIGHT:
self.imagen.set_height(FRAME_HEIGHT)
# Orientation
self.imagen.rotate(self.angle)
if self.flip==True:
self.imagen.flip(self.flip_edge)
for st in self.remove_stroke:
self.imagen[st].set_stroke(None,0)
for st in self.show_stroke:
self.imagen[st].set_stroke(None,self.show_stroke_stroke)
self.personalize_image()
if self.show_numbers==True:
self.print_formula(self.imagen.copy(),
self.numbers_scale,
self.direction_numbers,
self.remove,
self.space_between_numbers,
self.color_numbers)
if self.animation==True:
self.play(DrawBorderThenFill(self.imagen))
elif self.show_numbers==False:
self.add(self.imagen)
self.wait(self.wait_time)
self.return_elements(self.imagen,self.show_elements)
def get_svg(self):
if self.svg_type == "svg":
try:
pre_imagen = SVGMobject("%s"%self.file)
except:
pre_imagen = self.custom_object()
elif self.svg_type == "text":
pre_imagen = self.import_text()
else:
pre_imagen = self.custom_object()
return pre_imagen
def import_text(self):
return self.text
def custom_object(self):
return VGroup()
def personalize_image(self):
pass
def print_formula(self,text,inverse_scale,direction,exception,buff,color):
text.set_color(self.warning_color)
self.add(text)
for j in range(len(text)):
permission_print=True
for w in exception:
if j==w:
permission_print=False
if permission_print:
self.add(self.imagen[j])
if self.show_removers:
for obj in exception:
self.add_foreground_mobject(text[obj])
c=0
for j in range(len(text)):
permission_print=True
if self.number_type=="TextMobject":
element = TexMobject("%d" %c,color=color,
background_stroke_width=self.background_stroke_width)
else:
element = Text("%d" %c).set_color(color)
element.scale(inverse_scale)
element.next_to(text[j],direction,buff=buff)
for w in exception:
if j==w:
permission_print=False
if permission_print:
self.add_foreground_mobjects(element)
c = c + 1
def return_elements(self,formula,adds):
for i in adds:
self.add_foreground_mobjects(formula[i].set_color(self.color_element),
TexMobject("%d"%i,color=self.color_element,background_stroke_width=0)\
.scale(self.numbers_scale)\
.next_to(formula[i],self.direction_numbers,buff=self.space_between_numbers)
)
class CheckText(CheckSVG):
CONFIG={
"svg_type":"text",
"get_cero":True,
}
class CheckSVGNumbers(CheckSVG):
CONFIG={
"show_numbers": True,
}
class CheckTextNumbers(CheckText):
CONFIG={
"show_numbers": True,
}
class CheckSVGPoints(CheckSVGNumbers):
CONFIG={
"camera_config":{"background_color": BLACK},
"color":WHITE,
"show_element_points":[],
"background_stroke_width":4,
"shadow_point_number":3,
"points_colors":[RED,BLUE,GREEN],
"point_radius":0.05,
"size_points_numbers":0.09,
"number_point_direction":UP,
"number_point_buff":0
}
def personalize_image(self):
cycle_colors=it.cycle(self.points_colors)
for n_obj in self.show_element_points:
for obj in self.imagen[n_obj]:
count=0
for point in obj.points:
next_color=next(cycle_colors)
punto=Dot(color=next_color,radius=self.point_radius)
punto.move_to(point)
if self.number_type=="TextMobject":
number_point=Text("%d"%count,
color=punto.get_color(),
background_stroke_width=self.shadow_point_number
)
else:
number_point=Text("%d"%count)
number_point.match_color(punto)
number_point.set_height(self.size_points_numbers)\
.next_to(punto,
self.number_point_direction,
buff=self.number_point_buff
)
self.add_foreground_mobjects(punto,number_point)
count+=1
def print_formula(self,text,inverse_scale,direction,exception,buff,color):
text.set_color(self.warning_color)
self.add(text)
for j in range(len(text)):
permission_print=True
for w in exception:
if j==w:
permission_print=False
if permission_print:
self.add(self.imagen[j])
if self.show_removers:
for obj in exception:
self.add_foreground_mobject(text[obj])
c=0
for j in range(len(text)):
permission_print=True
if self.number_type=="TextMobject":
element = TexMobject("%d:%d"%(c,len(text.points)),color=color,
background_stroke_width=self.background_stroke_width)
else:
element = Text("%d:%d"%(c,len(text.points))).set_color(color)
element.scale(inverse_scale)
element.next_to(text[j],direction,buff=buff)
for w in exception:
if j==w:
permission_print=False
if permission_print:
self.add_foreground_mobjects(element)
c = c + 1
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/advanced/scene_update_alpha.py | from manimlib.imports import *
from check_svg import *
from screen_grid import ScreenGrid
"""
You have to add
\usepackage{listings}
in your tex_template.tex file
"""
code_string = r"""\begin{lstlisting}[language=Python,basicstyle=\scriptsize\ttfamily]
square2.save_state()
def update_rotate_move(mob, alpha):
square2.restore()
square2.shift(RIGHT*10*alpha)
square2.rotate(3*PI*alpha)
\end{lstlisting}
"""
MORADO_ST ="#A682FE"
ROSA_ST = "#F8206B"
VERDE_ST = "#A1E303"
AMARILLO_ST = "#E6DC6B"
FONDO_ST = "#272822"
AZUL_ST = "#64DAF8"
NARANJA_ST = "#FF9514"
class CodeNumbers(CheckTextNumbers):
CONFIG = {
"numbers_scale": 0.2,
}
def import_text(self):
return TextMobject(code_string)
class GetCode:
def change_color(self,text,pairs,color):
for pair in pairs:
if len(pair) == 2:
a,b = pair
text[a:b].set_color(color)
else:
text[pair[0]].set_color(color)
def get_code(self):
text = TextMobject(code_string)[0]
pairs_blue = [(8,18),(20,23),(61,68),(78,83),(107,113)]
pairs_green = [(23,41)]
pairs_pink = [(89,),(92,),(115,),(118,)]
pairs_purple = [(90,92),(114,)]
pairs_orange = [(42,45),(46,51)]
self.change_color(text,pairs_blue,AZUL_ST)
self.change_color(text,pairs_green,VERDE_ST)
self.change_color(text,pairs_pink,ROSA_ST)
self.change_color(text,pairs_purple,MORADO_ST)
self.change_color(text,pairs_orange,NARANJA_ST)
return text
class ShiftAndRotate(Animation):
CONFIG = {
"axis": OUT,
"run_time": 5,
"rate_func": linear,
"about_point": None,
"about_edge": None,
}
def __init__(self, mobject, direction, radians,**kwargs):
assert(isinstance(mobject, Mobject))
digest_config(self, kwargs)
self.mobject = mobject
self.direction = direction
self.radians = radians
def interpolate_mobject(self, alpha):
self.mobject.become(self.starting_mobject)
self.mobject.shift(alpha*self.direction)
self.mobject.rotate(
alpha * self.radians,
axis=self.axis,
about_point=self.about_point,
about_edge=self.about_edge,
)
class AdvancedAnimationsSetup(Scene,GetCode):
def change_finger(self,index):
self.finger.move_to(
[
0.5,
self.code[self.limits[index]].get_y(),
0
]
)
def get_position_finger(self,index):
return [
0.5,
self.code[self.limits[index]].get_y(),
0
]
def setup(self):
code = self.get_code()
code.scale(0.9)
code.to_corner(UL,buff=0.3)
self.code = code
self.finger = SVGMobject("dedo",stroke_width=0)
self.finger.flip()
self.finger.set_height(0.4)
self.limits = [19,52,69,98,124]
self.change_finger(0)
self.alphas_text = VGroup(
*[TexMobject(r"\tt alpha\rm =",r"\rm\frac{%d}{10}"%i) for i in range(11)]
)
self.alphas_text.to_corner(UR,buff=0.5)
self.alphas_text.shift(LEFT*2)
self.add(
self.code,
self.finger,
self.alphas_text[0]
)
class AdvancedAnimations(AdvancedAnimationsSetup):
def construct(self):
path = Line(LEFT*5,RIGHT*5,stroke_opacity=0.5)
phantom_path = DashedVMobject(path)
path.shift(DOWN*1.5)
phantom_path.add_updater(lambda mob: mob.move_to(path))
square = Square().set_height(0.7)
square.move_to(path.get_start())
square_start = square.copy()
square_start.set_color(RED)
ticks = VGroup(*[
DashedVMobject(Line(DOWN,UP,stroke_opacity=0.3))\
.move_to(path.point_from_proportion(i/10))
for i in range(0,11)
])
marks = VGroup(*[
TexMobject(r"\frac{%d}{10}"%i,height=0.6,fill_opacity=0.2)\
.next_to(ticks[i],UP,buff=0.2)
for i in range(0,11)
])
self.add(phantom_path,square_start,square,ticks,marks)
square.save_state()
self.wait()
self.play(
self.finger.move_to,self.get_position_finger(2)
)
for i in range(0,10):
alpha = i/10
self.wait()
self.play(
self.finger.move_to,self.get_position_finger(3)
)
self.wait()
self.play(
square.move_to,path.point_from_proportion(alpha)
)
self.wait()
self.play(
self.finger.move_to,self.get_position_finger(4)
)
self.play(
Rotate(square,3*PI*alpha)
)
self.play(
marks[i].set_fill,None,1
)
if i > 0:
phantom_square = square.copy()
phantom_square.fade(0.5)
self.add(phantom_square)
self.bring_to_front(square)
self.play(
self.finger.move_to,self.get_position_finger(2)
)
self.play(Restore(square))
self.play(
ReplacementTransform(
self.alphas_text[i],
self.alphas_text[i+1]
)
)
self.wait()
self.play(
ShiftAndRotate(square,RIGHT*10,3*PI),
run_time=10
)
self.wait(3)
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/render_old_projects/steps.md | # Learn Manim by yourself.
This tutorial works with [this manim version (feb/03/19)](https://github.com/3b1b/manim/tree/3b088b12843b7a4459fe71eba96b70edafb7aa78).
## 1. Download this files.
### 1.1 Download this image with the name "generic.png" and place it in ```media/designs/raster_images```
<p align="center"><img src ="/English/extra/render_old_projects/archivos/generic.png" width="400" /></p>
### 1.2 Download this image with the name "generic.svg" and place it in ```media/designs/svg_images```
<p align="center"><img src ="/English/extra/render_old_projects/archivos/generic.svg" width="400" /></p>
### 1.3 Copy the three .svg files from ```manimlib/files``` to ```media/designs/svg_images```
### 1.4 Download [this sound file](https://drive.google.com/open?id=1V_LpJoidm2tAVVBusKaHlky2-MLehTuM) with the name "generic_sound.wav" and place it in ```media/designs/sounds```
## 2. Modify the following files:
### 2.1 ```manimlib/mobject/coordinate_systems.py``` Add this code in the line 54:
```python3
def get_axis(self, min_val, max_val, axis_config):
new_config = merge_config([
axis_config,
{"x_min": min_val, "x_max": max_val},
self.number_line_config,
])
return NumberLine(**new_config)
```
<p align="center"><img src ="/English/extra/render_old_projects/capturas/coord_syst.png" width="700" /></p>
### 2.2 Add this line in ```manimlib/mobject/svg/svg_mobject.py```
```python3
os.path.join(SVG_IMAGE_DIR, "generic.svg")
```
<p align="center"><img src ="/English/extra/render_old_projects/capturas/capt2.png" width="700" /></p>
### 2.3 Open ```manimlib/mobject/types/image_mobject.py``` and replaces the selected part of the left side with the code that is on the right side.
<p align="center"><img src ="/English/extra/render_old_projects/capturas/capt3.png"/></p>
Code:
```python3
path=self.select_image(filename_or_array)
#path = get_full_raster_image_path(filename_or_array)
image = Image.open(path).convert(self.image_mode)
self.pixel_array = np.array(image)
else:
self.pixel_array = np.array(filename_or_array)
self.change_to_rgba_array()
if self.invert:
self.pixel_array[:, :, :3] = 255 - self.pixel_array[:, :, :3]
AbstractImageMobject.__init__(self, **kwargs)
def select_image(self,file_name):
extensions=[".jpg", ".png", ".gif"]
possible_paths = [file_name]
possible_paths += [
os.path.join(RASTER_IMAGE_DIR, file_name + extension)
for extension in ["", *extensions]
]
possible_paths+=[os.path.join(RASTER_IMAGE_DIR, "generic.png")]
for path in possible_paths:
if os.path.exists(path):
return path
```
### 2.4 Open ```manimlib/for_3b1b_videos/pi_creature.py``` and replaces the selected part of the left side with the code that is on the right side.
<p align="center"><img src ="/English/extra/render_old_projects/capturas/capt4.png"/></p>
Code:
```python3
"PiCreatures_plain.svg"
```
### 2.5 Open ```manimlib/mobject/svg/drawings.py``` and replaces the selected part of the left side with the code that is on the right side.
<p align="center"><img src ="/English/extra/render_old_projects/capturas/capt5.png"/></p>
Code:
```python3
"file_name": "Bubbles_speech.svg",
```
------------------------------------
```python3
SVGMobject.__init__(self,file_name="Bubbles_speech" ,**kwargs)
```
### 2.6 Open ```manimlib/once_useful_constructs/light.py``` and add this code in the 21 line:
```python3
from manimlib.utils.space_ops import get_norm
```
<p align="center"><img src ="/English/extra/render_old_projects/capturas/capt6.png" width="700"/></p>
### 2.7 Open ```manimlib/scene/three_d_scene.py``` and replache the 149 with this line:
```python3
if self.camera_config["pixel_width"] == PRODUCTION_QUALITY_CAMERA_CONFIG["pixel_width"]:
```
<p align="center"><img src ="/English/extra/render_old_projects/capturas/capt7.png"/></p>
### 2.7 Open ```manimlib/utils/sounds.py``` and make the changes shown in the code above:
<p align="center"><img src ="/English/extra/render_old_projects/capturas/sound.png"/></p>
```python3
# Add this code below line 41
def select_sound(sound_file_name):
try_sound=os.path.join(SOUND_DIR, sound_file_name)
if os.path.exists(try_sound):
return sound_file_name
else:
return "generic_sound"
# Replace the line 37 with:
select_sound(sound_file_name),
```
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/faqs/faqs.py | from big_ol_pile_of_manim_imports import *
# What is CONFIG? ----------------------------------------------
class WhatIsCONFIG(Scene):
CONFIG={
"object_1":TextMobject("Object 1"),
"object_2":Square(),
"number":3,
"vector":[1,1,0]
}
def construct(self):
self.play(
Write(self.object_1)
)
self.play(
self.object_1.scale,self.number
)
self.play(
ReplacementTransform(
self.object_1,
self.object_2
)
)
self.play(
self.object_2.shift,self.vector
)
self.wait()
class SceneFromAnotherScene(WhatIsCONFIG):
CONFIG={
"object_1":TextMobject("Another object"),
"object_2":Circle(),
"number":4,
"vector":[-1,-1,0]
}
# -----------------------------------------------------------------
# Change the background color -------------------------------------
class ChangeBackgroundColor(Scene):
CONFIG={
"camera_config":{"background_color":RED},
"text":TexMobject(r"\frac{d}{dx}\Bigr|_{y=2}").scale(5)
}
def construct(self):
self.add(self.text)
# -----------------------------------------------------------------
# Remove background stroke width of texts
class RemoveBackgroundStrokeWidth(ChangeBackgroundColor):
CONFIG={
"text":TexMobject(
r"\frac{d}{dx}\Bigr|_{y=2}",
background_stroke_width=0, #<- Add this line
).scale(5)
}
# Yoy can go to manimlib/mobject/svg/tex_mobject.py and change
# background_stroke_width=0 in the SingleStringTexMobject class.
# -----------------------------------------------------------------
# Arrange multiple objects
class ArrangeObjects(Scene):
def construct(self):
text1 = TextMobject("You have")
text2 = TextMobject("to use")
text3 = TextMobject("\\tt VGroup")
text_group = VGroup(
text1,
text2,
text3
)
# .arrange # <- For recent versions
text_group.arrange_submobjects(
DOWN, # <- Direction
aligned_edge = LEFT,
buff=0.4
)
self.add(text_group)
self.wait()
self.play(
text_group.arrange_submobjects,UP,{"aligned_edge":RIGHT,"buff":2}
)
self.wait()
self.play(
text_group.arrange_submobjects,RIGHT,{"buff":0.4}
)
self.wait()
# -----------------------------------------------------------------
# How change the size of the camera -------------------------------
class ChangePositionAndSizeCamera(MovingCameraScene):
def construct(self):
text=TexMobject("\\nabla\\textbf{u}").scale(3)
square=Square()
# Arrange the objects
VGroup(text,square).arrange_submobjects(RIGHT,buff=3)
self.add(text,square)
# Save the state of camera
self.camera_frame.save_state()
# Animation of the camera
self.play(
# Set the size with the width of a object
self.camera_frame.set_width,text.get_width()*1.2,
# Move the camera to the object
self.camera_frame.move_to,text
)
self.wait()
# Restore the state saved
self.play(Restore(self.camera_frame))
self.play(
self.camera_frame.set_height,square.get_width()*1.2,
self.camera_frame.move_to,square
)
self.wait()
self.play(Restore(self.camera_frame))
self.wait()
class ChangePositionAndSizeCameraInAnotherScene(GraphScene,MovingCameraScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 5,
"x_tick_frequency" : 0.5,
}
# Setup the scenes
def setup(self):
GraphScene.setup(self)
MovingCameraScene.setup(self)
def construct(self):
self.setup_axes(animate=False)
graph = self.get_graph(lambda x : x**2,
color = GREEN,
x_min = 0,
x_max = 7
)
dot_at_start_graph=Dot().move_to(graph.points[0])
dot_at_end_grap=Dot().move_to(graph.points[-1])
self.add(graph,dot_at_end_grap,dot_at_start_graph)
self.play(
self.camera_frame.scale,.5,
self.camera_frame.move_to,dot_at_start_graph
)
self.play(
self.camera_frame.move_to,dot_at_end_grap
)
self.wait()
# -----------------------------------------------------------------
# Linear transformation example
class LinearTransformation(LinearTransformationScene):
CONFIG = {
"include_background_plane": True,
"include_foreground_plane": True,
"foreground_plane_kwargs": {
"x_radius": FRAME_WIDTH,
"y_radius": FRAME_HEIGHT,
"secondary_line_ratio": 0
},
"background_plane_kwargs": {
"color": GREY,
"secondary_color": DARK_GREY,
"axes_color": GREY,
"stroke_width": 2,
},
"show_coordinates": False,
"show_basis_vectors": True,
"basis_vector_stroke_width": 6,
"i_hat_color": X_COLOR,
"j_hat_color": Y_COLOR,
"leave_ghost_vectors": False,
}
def construct(self):
mob = Circle()
mob.move_to(RIGHT+UP*2)
vector_array = np.array([[1], [2]])
matrix = [[0, 1], [-1, 1]]
self.add_transformable_mobject(mob)
self.add_vector(vector_array)
self.apply_matrix(matrix)
self.wait()
# --------------------------------------------------------------------
class RemoveAllObjectsInScreen(Scene):
def construct(self):
self.add(
VGroup(
*[
VGroup(
*[
Dot()
for i in range(30)
]
).arrange_submobjects(RIGHT)
for j in range(10)
]
).arrange_submobjects(DOWN)
)
self.play(
*[FadeOut(mob)for mob in self.mobjects]
# All mobjects in the screen are saved in self.mobjects
)
self.wait()
# --------------------------------------------------------------------
# Zoomed Scene
class ZoomedSceneExample(ZoomedScene):
CONFIG = {
"zoom_factor": 0.3,
"zoomed_display_height": 1,
"zoomed_display_width": 6,
"image_frame_stroke_width": 20,
"zoomed_camera_config": {
"default_frame_stroke_width": 3,
},
}
def construct(self):
# Set objects
dot = Dot().shift(UL*2)
image=ImageMobject(np.uint8([[ 0, 100,30 , 200],
[255,0,5 , 33]]))
image.set_height(7)
frame_text=TextMobject("Frame",color=PURPLE).scale(1.4)
zoomed_camera_text=TextMobject("Zommed camera",color=RED).scale(1.4)
self.add(image,dot)
# Set camera
zoomed_camera = self.zoomed_camera
zoomed_display = self.zoomed_display
frame = zoomed_camera.frame
zoomed_display_frame = zoomed_display.display_frame
frame.move_to(dot)
frame.set_color(PURPLE)
zoomed_display_frame.set_color(RED)
zoomed_display.shift(DOWN)
# brackground zoomed_display
zd_rect = BackgroundRectangle(
zoomed_display,
fill_opacity=0,
buff=MED_SMALL_BUFF,
)
self.add_foreground_mobject(zd_rect)
# animation of unfold camera
unfold_camera = UpdateFromFunc(
zd_rect,
lambda rect: rect.replace(zoomed_display)
)
frame_text.next_to(frame,DOWN)
self.play(
ShowCreation(frame),
FadeInFromDown(frame_text)
)
# Activate zooming
self.activate_zooming()
self.play(
# You have to add this line
self.get_zoomed_display_pop_out_animation(),
unfold_camera
)
zoomed_camera_text.next_to(zoomed_display_frame,DOWN)
self.play(FadeInFromDown(zoomed_camera_text))
# Scale in x y z
scale_factor=[0.5,1.5,0]
# Resize the frame and zoomed camera
self.play(
frame.scale, scale_factor,
zoomed_display.scale, scale_factor,
FadeOut(zoomed_camera_text),
FadeOut(frame_text)
)
# Resize the frame
self.play(
frame.scale,3,
frame.shift,2.5*DOWN
)
# Resize zoomed camera
self.play(
ScaleInPlace(zoomed_display,2)
)
self.wait()
self.play(
self.get_zoomed_display_pop_out_animation(),
unfold_camera,
# -------> Inverse
rate_func=lambda t: smooth(1-t),
)
self.play(
Uncreate(zoomed_display_frame),
FadeOut(frame),
)
self.wait()
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/faqs/paths.py | #from manimlib.imports import *
#from big_ol_pile_of_manim_imports import *
class Grid(VGroup):
CONFIG = {
"height": 6.0,
"width": 6.0,
}
def __init__(self, rows, columns, **kwargs):
digest_config(self, kwargs, locals())
super().__init__(**kwargs)
x_step = self.width / self.columns
y_step = self.height / self.rows
for x in np.arange(0, self.width + x_step, x_step):
self.add(Line(
[x - self.width / 2., -self.height / 2., 0],
[x - self.width / 2., self.height / 2., 0],
))
for y in np.arange(0, self.height + y_step, y_step):
self.add(Line(
[-self.width / 2., y - self.height / 2., 0],
[self.width / 2., y - self.height / 2., 0]
))
class ScreenGrid(VGroup):
CONFIG = {
"rows": 8,
"columns": 14,
"height": FRAME_Y_RADIUS * 2,
"width": 14,
"grid_stroke": 0.5,
"grid_color": WHITE,
"axis_color": RED,
"axis_stroke": 2,
"labels_scale": 0.5,
"labels_buff": 0,
"number_decimals": 2
}
def __init__(self, **kwargs):
super().__init__(**kwargs)
rows = self.rows
columns = self.columns
grid = Grid(width=self.width, height=self.height, rows=rows, columns=columns)
grid.set_stroke(self.grid_color, self.grid_stroke)
vector_ii = ORIGIN + np.array((- self.width / 2, - self.height / 2, 0))
vector_si = ORIGIN + np.array((- self.width / 2, self.height / 2, 0))
vector_sd = ORIGIN + np.array((self.width / 2, self.height / 2, 0))
axes_x = Line(LEFT * self.width / 2, RIGHT * self.width / 2)
axes_y = Line(DOWN * self.height / 2, UP * self.height / 2)
axes = VGroup(axes_x, axes_y).set_stroke(self.axis_color, self.axis_stroke)
divisions_x = self.width / columns
divisions_y = self.height / rows
directions_buff_x = [UP, DOWN]
directions_buff_y = [RIGHT, LEFT]
dd_buff = [directions_buff_x, directions_buff_y]
vectors_init_x = [vector_ii, vector_si]
vectors_init_y = [vector_si, vector_sd]
vectors_init = [vectors_init_x, vectors_init_y]
divisions = [divisions_x, divisions_y]
orientations = [RIGHT, DOWN]
labels = VGroup()
set_changes = zip([columns, rows], divisions, orientations, [0, 1], vectors_init, dd_buff)
for c_and_r, division, orientation, coord, vi_c, d_buff in set_changes:
for i in range(1, c_and_r):
for v_i, directions_buff in zip(vi_c, d_buff):
ubication = v_i + orientation * division * i
coord_point = round(ubication[coord], self.number_decimals)
label = TextMobject(f"{coord_point}").scale(self.labels_scale)
label.next_to(ubication, directions_buff, buff=self.labels_buff)
labels.add(label)
self.add(grid, axes, labels)
def coord(x,y,z=0):
return np.array([x,y,z])
def getX(mob):
return mob.get_center()[0]
def getY(mob):
return mob.get_center()[1]
# Abstract class:
class PathScene(Scene):
CONFIG = {
"x_coords":[0, 1, 3, -2, -3],
"y_coords":[3, -2, 1, 2.5, -1]
}
"""
The setup method it is executed before the construct method,
so whatever they write in the setup method will be executed
before the construct method
"""
def setup(self):
self.screen_grid = ScreenGrid()
# tuples = [(0,3),(1,-2)...]
self.tuples = list(zip(self.x_coords,self.y_coords))
dots,labels,numbers = self.get_all_mobs()
self.add(self.screen_grid,dots,labels,numbers)
def get_dots(self,coords):
# This is called list comprehension, learn to use it here:
# https://www.youtube.com/watch?v=AhSvKGTh28Q
dots = VGroup(*[Dot(coord(x,y)) for x,y in coords])
return dots
def get_dot_labels(self,dots,direction=RIGHT):
labels = VGroup(*[
# This is called f-strings, learn to use it here:
# https://www.geeksforgeeks.org/formatted-string-literals-f-strings-python/
TexMobject(f"({getX(dot)},{getY(dot)})",height=0.3)\
.next_to(dot,direction,buff=SMALL_BUFF)
# This is called Multi-line statement, learn how to use it here:
# https://www.programiz.com/python-programming/statement-indentation-comments
for dot in dots
])
return labels
def get_dot_numbers(self,dots):
numbers = VGroup(*[
TextMobject(f"{n}",height=0.2).next_to(dot,DOWN,buff=SMALL_BUFF)
for n,dot in zip(range(1,len(dots)+1),dots)
])
return numbers
def get_all_mobs(self):
dots = self.get_dots(self.tuples)
labels = self.get_dot_labels(dots)
numbers = self.get_dot_numbers(dots)
return dots,labels,numbers
class ShowPoints(PathScene):
pass
class PathAsCorners(PathScene):
def construct(self):
path = VMobject()
path.set_points_as_corners([*[coord(x,y) for x,y in self.tuples]])
self.add(path)
class PathSmoothly(PathScene):
def construct(self):
path = VMobject()
path.set_points_smoothly([*[coord(x,y) for x,y in self.tuples]])
self.add(path)
class PathPoints(PathScene):
def construct(self):
path = VMobject()
path.set_points_smoothly([*[coord(x,y) for x,y in self.tuples]])
bezier_points = VGroup(*[Dot(coord,color=RED) for coord in path.points])
self.add(path,bezier_points)
class AppendPoints(PathScene):
def construct(self):
path = VMobject()
path.set_points_as_corners([*[coord(x,y) for x,y in self.tuples]])
self.add(path)
self.wait()
new_points = np.array([coord(-5,1),coord(-1,1)])
new_dots = self.get_dots(new_points[:,:2])
""" Special atention to this: ----
This is an slice, see: https://railsware.com/blog/python-for-machine-learning-indexing-and-slicing-for-lists-tuples-strings-and-other-sequential-types/
new_points =
[ Columns:
0 1 2
[-5 1 0] <- Row 0
[-1 1 0] <- Row 1
]
So, the first ":" means all rows
The ":2" means only take the elements from the first column to the second one,
that is, the columns 0 and 1
"""
new_labels = self.get_dot_labels(new_dots,UP)
path.become(
VMobject().set_points_as_corners([*path.points,*new_points])
)
# The most recent version have new methods that can do this more easy.
VGroup(new_dots,new_labels).set_color(TEAL)
self.add(new_dots,new_labels)
self.wait(2)
class TransformPathStyle(PathScene):
def construct(self):
path = VMobject()
path.set_points_as_corners([*[coord(x,y) for x,y in self.tuples]])
self.add(path)
self.play(path.make_smooth)
self.wait()
"""
There are 3 methods:
path.make_smooth()
path.make_jagged()
path.change_anchor_mode()
"""
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/faqs/paths.md | # How to create paths in Manim with set of points
## Some useful functions:
```python
def coord(x,y,z=0):
return np.array([x,y,z])
def getX(mob):
return mob.get_center()[0]
def getY(mob):
return mob.get_center()[1]
```
## Abstract class
This class is not a scene, it is the basis for creating our scenes.
```python
# Abstract class:
class PathScene(Scene):
CONFIG = {
"x_coords":[0, 1, 3, -2, -3],
"y_coords":[3, -2, 1, 2.5, -1]
}
"""
The setup method it is executed before the construct method,
so whatever they write in the setup method will be executed
before the construct method
"""
def setup(self):
self.screen_grid = ScreenGrid()
# tuples = [(0,3),(1,-2)...]
self.tuples = list(zip(self.x_coords,self.y_coords))
dots,labels,numbers = self.get_all_mobs()
self.add(self.screen_grid,dots,labels,numbers)
def get_dots(self,coords):
# This is called list comprehension, learn to use it here:
# https://www.youtube.com/watch?v=AhSvKGTh28Q
dots = VGroup(*[Dot(coord(x,y)) for x,y in coords])
return dots
def get_dot_labels(self,dots,direction=RIGHT):
labels = VGroup(*[
# This is called f-strings, learn to use it here:
# https://www.geeksforgeeks.org/formatted-string-literals-f-strings-python/
TexMobject(f"({getX(dot)},{getY(dot)})",height=0.3)\
.next_to(dot,direction,buff=SMALL_BUFF)
# This is called Multi-line statement, learn how to use it here:
# https://www.programiz.com/python-programming/statement-indentation-comments
for dot in dots
])
return labels
def get_dot_numbers(self,dots):
numbers = VGroup(*[
TextMobject(f"{n}",height=0.2).next_to(dot,DOWN,buff=SMALL_BUFF)
for n,dot in zip(range(1,len(dots)+1),dots)
])
return numbers
def get_all_mobs(self):
dots = self.get_dots(self.tuples)
labels = self.get_dot_labels(dots)
numbers = self.get_dot_numbers(dots)
return dots,labels,numbers
```
## Show Points
```python
class ShowPoints(PathScene):
pass
```
<p align="center"><img src ="/English/extra/faqs/gifs/ShowPoints.png" width="800" /></p>
## Path as corners
```python
class PathAsCorners(PathScene):
def construct(self):
path = VMobject()
path.set_points_as_corners([*[coord(x,y) for x,y in self.tuples]])
self.add(path)
```
<p align="center"><img src ="/English/extra/faqs/gifs/PathAsCorners.png" width="800" /></p>
## Path smoothly
```python
class PathSmoothly(PathScene):
def construct(self):
path = VMobject()
path.set_points_smoothly([*[coord(x,y) for x,y in self.tuples]])
self.add(path)
```
<p align="center"><img src ="/English/extra/faqs/gifs/PathSmoothly.png" width="800" /></p>
## Bezier points of a path
```python
class PathBezierPoints(PathScene):
def construct(self):
path = VMobject()
path.set_points_smoothly([*[coord(x,y) for x,y in self.tuples]])
bezier_points = VGroup(*[Dot(coord,color=RED) for coord in path.points])
self.add(path,bezier_points)
```
<p align="center"><img src ="/English/extra/faqs/gifs/PathBezierPoints.png" width="800" /></p>
## Append points
```python
class AppendPoints(PathScene):
def construct(self):
path = VMobject()
path.set_points_as_corners([*[coord(x,y) for x,y in self.tuples]])
self.add(path)
self.wait()
new_points = np.array([coord(-5,1),coord(-1,1)])
new_dots = self.get_dots(new_points[:,:2])
""" Special atention to this: ----
This is an slice, see: https://railsware.com/blog/python-for-machine-learning-indexing-and-slicing-for-lists-tuples-strings-and-other-sequential-types/
new_points =
[ Columns:
0 1 2
[-5 1 0] <- Row 0
[-1 1 0] <- Row 1
]
So, the first ":" means all rows
The ":2" means only take the elements from the first column to the second one,
that is, the columns 0 and 1
"""
new_labels = self.get_dot_labels(new_dots,UP)
path.become(
VMobject().set_points_as_corners([*path.points,*new_points])
)
# The most recent version have new methods that can do this more easy.
VGroup(new_dots,new_labels).set_color(TEAL)
self.add(new_dots,new_labels)
self.wait(2)
```
<p align="center"><img src ="/English/extra/faqs/gifs/AppendPoints.gif" width="800" /></p>
## Change path style
```python
class TransformPathStyle(PathScene):
def construct(self):
path = VMobject()
path.set_points_as_corners([*[coord(x,y) for x,y in self.tuples]])
self.add(path)
self.play(path.make_smooth)
self.wait()
"""
There are 3 methods:
path.make_smooth()
path.make_jagged()
path.change_anchor_mode()
"""
```
<p align="center"><img src ="/English/extra/faqs/gifs/TransformPathStyle.gif" width="800" /></p>
More methods in the [current version](https://github.com/3b1b/manim/blob/master/manimlib/mobject/types/vectorized_mobject.py#L397)
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/faqs/faqs.md | # Manim FAQs ([code](https://github.com/Elteoremadebeethoven/AnimationsWithManim/blob/master/English/extra/faqs/faqs.py))
## What is CONFIG
<p align="center"><img src ="/English/extra/faqs/gifs/WhatIsCONFIG.gif" width="800" /></p>
```python3
class WhatIsCONFIG(Scene):
CONFIG={
"object_1":TextMobject("Object 1"),
"object_2":Square(),
"number":3,
"vector":[1,1,0]
}
def construct(self):
self.play(
Write(self.object_1)
)
self.play(
self.object_1.scale,self.number
)
self.play(
ReplacementTransform(
self.object_1,
self.object_2
)
)
self.play(
self.object_2.shift,self.vector
)
self.wait()
```
## Scene from another Scene
<p align="center"><img src ="/English/extra/faqs/gifs/SceneFromAnotherScene.gif" width="800" /></p>
```python3
class SceneFromAnotherScene(WhatIsCONFIG):
CONFIG={
"object_1":TextMobject("Another object"),
"object_2":Circle(),
"number":4,
"vector":[-1,-1,0]
}
```
## Change background color
<p align="center"><img src ="/English/extra/faqs/gifs/ChangeBackgroundColor.png" width="800" /></p>
```python3
class ChangeBackgroundColor(Scene):
CONFIG={
"camera_config":{"background_color":RED},
"text":TexMobject(r"\frac{d}{dx}\Bigr|_{y=2}").scale(5)
}
def construct(self):
self.add(self.text)
```
## Remove background stroke width of texts
<p align="center"><img src ="/English/extra/faqs/gifs/RemoveBackgroundStrokeWidth.png" width="800" /></p>
```python3
class RemoveBackgroundStrokeWidth(ChangeBackgroundColor):
CONFIG={
"text":TexMobject(
r"\frac{d}{dx}\Bigr|_{y=2}",
background_stroke_width=0, #<- Add this line
).scale(5)
}
```
## Arrange Objects
<p align="center"><img src ="/English/extra/faqs/gifs/ArrangeObjects1.gif" width="800" /></p>
```python3
class ArrangeObjects(Scene):
def construct(self):
text1 = TextMobject("You have")
text2 = TextMobject("to use")
text3 = TextMobject("\\tt VGroup")
text_group = VGroup(
text1,
text2,
text3
)
# .arrange # <- For recent versions
text_group.arrange_submobjects(
DOWN, # <- Direction
aligned_edge = LEFT,
buff=0.4
)
self.add(text_group)
self.wait()
self.play(
text_group.arrange_submobjects,UP,{"aligned_edge":RIGHT,"buff":2}
)
self.wait()
self.play(
text_group.arrange_submobjects,RIGHT,{"buff":0.4}
)
self.wait()
```
## Change position and size of the camera
<p align="center"><img src ="/English/extra/faqs/gifs/ChangePositionAndSizeCamera.gif" width="800" /></p>
```python3
class ChangePositionAndSizeCamera(MovingCameraScene):
def construct(self):
text=TexMobject("\\nabla\\textbf{u}").scale(3)
square=Square()
# Arrange the objects
VGroup(text,square).arrange_submobjects(RIGHT,buff=3)
self.add(text,square)
# Save the state of camera
self.camera_frame.save_state()
# Animation of the camera
self.play(
# Set the size with the width of a object
self.camera_frame.set_width,text.get_width()*1.2,
# Move the camera to the object
self.camera_frame.move_to,text
)
self.wait()
# Restore the state saved
self.play(Restore(self.camera_frame))
self.play(
self.camera_frame.set_height,square.get_width()*1.2,
self.camera_frame.move_to,square
)
self.wait()
self.play(Restore(self.camera_frame))
self.wait()
```
## Change position and size of the camera in other scenes
<p align="center"><img src ="/English/extra/faqs/gifs/ChangePositionAndSizeCameraInAnotherScene.gif" width="800" /></p>
```python3
class ChangePositionAndSizeCameraInAnotherScene(GraphScene,MovingCameraScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 5,
"x_tick_frequency" : 0.5,
}
# Setup the scenes
def setup(self):
GraphScene.setup(self)
MovingCameraScene.setup(self)
def construct(self):
self.setup_axes(animate=False)
graph = self.get_graph(lambda x : x**2,
color = GREEN,
x_min = 0,
x_max = 7
)
dot_at_start_graph=Dot().move_to(graph.points[0])
dot_at_end_grap=Dot().move_to(graph.points[-1])
self.add(graph,dot_at_end_grap,dot_at_start_graph)
self.play(
self.camera_frame.scale,.5,
self.camera_frame.move_to,dot_at_start_graph
)
self.play(
self.camera_frame.move_to,dot_at_end_grap
)
self.wait()
```
## Linear transformation
<p align="center"><img src ="/English/extra/faqs/gifs/LinearTransformation.gif" width="800" /></p>
```python3
class LinearTransformation(LinearTransformationScene):
CONFIG = {
"include_background_plane": True,
"include_foreground_plane": True,
"foreground_plane_kwargs": {
"x_radius": FRAME_WIDTH,
"y_radius": FRAME_HEIGHT,
"secondary_line_ratio": 0
},
"background_plane_kwargs": {
"color": GREY,
"secondary_color": DARK_GREY,
"axes_color": GREY,
"stroke_width": 2,
},
"show_coordinates": False,
"show_basis_vectors": True,
"basis_vector_stroke_width": 6,
"i_hat_color": X_COLOR,
"j_hat_color": Y_COLOR,
"leave_ghost_vectors": False,
}
def construct(self):
mob = Circle()
mob.move_to(RIGHT+UP*2)
vector_array = np.array([[1], [2]])
matrix = [[0, 1], [-1, 1]]
self.add_transformable_mobject(mob)
self.add_vector(vector_array)
self.apply_matrix(matrix)
self.wait()
```
## Remove all objects in screen
<p align="center"><img src ="/English/extra/faqs/gifs/RemoveAllObjectsInScreen.gif" width="800" /></p>
```python3
class RemoveAllObjectsInScreen(Scene):
def construct(self):
self.add(
VGroup(
*[
VGroup(
*[
Dot()
for i in range(30)
]
).arrange_submobjects(RIGHT)
for j in range(10)
]
).arrange_submobjects(DOWN)
)
self.play(
*[FadeOut(mob)for mob in self.mobjects]
# All mobjects in the screen are saved in self.mobjects
)
self.wait()
```
## Zoomed scene example
<p align="center"><img src ="/English/extra/faqs/gifs/ZoomedSceneExample.gif" width="800" /></p>
```python3
class ZoomedSceneExample(ZoomedScene):
CONFIG = {
"zoom_factor": 0.3,
"zoomed_display_height": 1,
"zoomed_display_width": 6,
"image_frame_stroke_width": 20,
"zoomed_camera_config": {
"default_frame_stroke_width": 3,
},
}
def construct(self):
# Set objects
dot = Dot().shift(UL*2)
image=ImageMobject(np.uint8([[ 0, 100,30 , 200],
[255,0,5 , 33]]))
image.set_height(7)
frame_text=TextMobject("Frame",color=PURPLE).scale(1.4)
zoomed_camera_text=TextMobject("Zommed camera",color=RED).scale(1.4)
self.add(image,dot)
# Set camera
zoomed_camera = self.zoomed_camera
zoomed_display = self.zoomed_display
frame = zoomed_camera.frame
zoomed_display_frame = zoomed_display.display_frame
frame.move_to(dot)
frame.set_color(PURPLE)
zoomed_display_frame.set_color(RED)
zoomed_display.shift(DOWN)
# brackground zoomed_display
zd_rect = BackgroundRectangle(
zoomed_display,
fill_opacity=0,
buff=MED_SMALL_BUFF,
)
self.add_foreground_mobject(zd_rect)
# animation of unfold camera
unfold_camera = UpdateFromFunc(
zd_rect,
lambda rect: rect.replace(zoomed_display)
)
frame_text.next_to(frame,DOWN)
self.play(
ShowCreation(frame),
FadeInFromDown(frame_text)
)
# Activate zooming
self.activate_zooming()
self.play(
# You have to add this line
self.get_zoomed_display_pop_out_animation(),
unfold_camera
)
zoomed_camera_text.next_to(zoomed_display_frame,DOWN)
self.play(FadeInFromDown(zoomed_camera_text))
# Scale in x y z
scale_factor=[0.5,1.5,0]
# Resize the frame and zoomed camera
self.play(
frame.scale, scale_factor,
zoomed_display.scale, scale_factor,
FadeOut(zoomed_camera_text),
FadeOut(frame_text)
)
# Resize the frame
self.play(
frame.scale,3,
frame.shift,2.5*DOWN
)
# Resize zoomed camera
self.play(
ScaleInPlace(zoomed_display,2)
)
self.wait()
self.play(
self.get_zoomed_display_pop_out_animation(),
unfold_camera,
# -------> Inverse
rate_func=lambda t: smooth(1-t),
)
self.play(
Uncreate(zoomed_display_frame),
FadeOut(frame),
)
self.wait()
```
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/faqs/tikz.py | class TikzMobject(TextMobject):
CONFIG = {
"stroke_width": 3,
"fill_opacity": 0,
"stroke_opacity": 1,
}
class ExampleTikz(Scene):
def construct(self):
circuit = TikzMobject(r"""
\begin{circuitikz}[american voltages]
\draw
(0,0) to [short, *-] (6,0)
to [V, l_=$\mathrm{j}{\omega}_m \underline{\psi}^s_R$] (6,2)
to [R, l_=$R_R$] (6,4)
to [short, i_=$\underline{i}^s_R$] (5,4)
(0,0) to [open,v^>=$\underline{u}^s_s$] (0,4)
to [short, *- ,i=$\underline{i}^s_s$] (1,4)
to [R, l=$R_s$] (3,4)
to [L, l=$L_{\sigma}$] (5,4)
to [short, i_=$\underline{i}^s_M$] (5,3)
to [L, l_=$L_M$] (5,0);
\end{circuitikz}
"""
)
self.play(Write(circuit))
self.wait()
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/rate_funcs/rate_functions_scenes.py | from manimlib.imports import *
class ExampleRateFunc(Scene):
def construct(self):
path = Line(LEFT*5,RIGHT*5)
dot = Dot(path.get_start())
self.add(path,dot)
self.play(
# This works with any animation
MoveAlongPath(
dot,path,
rate_func=lambda t: smooth(1-t),
# rate_func = smooth <- by default
run_time=4 # 4 sec
)
)
self.wait()
class ExampleRateFunc2(Scene):
def construct(self):
text = TextMobject("Hello world!").scale(3)
self.play(Write(
text,
rate_func=lambda t: smooth(1-t)
))
self.wait()
# Install via pip:
# matplotlib
# pandas
# sklearn
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
class ExampleRateFuncCustom(Scene):
def construct(self):
datas = pd.read_csv('data.csv')
print(datas)
X = datas.iloc[:, 0:1].values
y = datas.iloc[:, 1].values
poly = PolynomialFeatures(degree = 8)
X_poly = poly.fit_transform(X)
poly.fit(X_poly, y)
lin = LinearRegression()
lin.fit(X_poly, y)
plt.scatter(X, y, color = 'blue')
plt.plot(X, lin.predict(poly.fit_transform(X)), color = 'red')
plt.title('Polynomial Regression')
plt.xlabel('Time')
plt.ylabel('Animation progression %')
plt.show()
# See manimlib/utils/bezier.py
reg_func = bezier(lin.predict(poly.fit_transform(X)))
path = Line(LEFT*5,RIGHT*5)
dot = Dot(path.get_start())
self.add(path,dot)
self.play(
MoveAlongPath(
dot,path,
rate_func=reg_func,
run_time=4
)
)
self.wait()
# Custom
def custom_time(t,partitions,start,end,func):
duration = end - start
fragment_time = 1 / partitions
start_time = start * fragment_time
end_time = end * fragment_time
duration_time = duration * fragment_time
def fix_time(x):
return (x - start_time) / duration_time
if t < start_time:
return func(fix_time(start_time))
elif start_time <= t < end_time:
return func(fix_time(t))
else:
return func(fix_time(end_time))
def Custom(partitions,start,end,func=smooth):
return lambda t: custom_time(t,partitions,start,end,func)
class CustomRateFunc(Scene):
def construct(self):
c = Circle().scale(2)
s = Square().scale(2)
l = Line(DOWN,UP).scale(2)
time = DecimalNumber(self.time).add_updater(lambda m: m.set_value(self.time))
time.to_corner(DL)
self.add(time)
self.play(
# 6 partitions, that is (total_time = 4):
# ShowCreation starts at t=(0/6)*total_time=0s and end t=(5/6)*total_time=3.333s
ShowCreation(c, rate_func=Custom(6,0,5)),
# FadeIn starts at t=(2/6)*total_time=1.3333s and end t=(4/6)*total_time=2.6666s
FadeIn(s, rate_func=Custom(6,2,4,func=there_and_back)),
# GrowFromCenter starts at t=(4/6)*total_time=2.6666s and end t=(6/6)*total_time=4s
GrowFromCenter(l,rate_func=Custom(6,4,6)),
run_time=4 # <- total_time
)
self.wait()
# COMPARATION
class TestPath(VGroup):
def __init__(self,name,**kwargs):
super().__init__(**kwargs)
self.name = name.__name__
self.func = name
self.title = Text(f"{self.name}",font="Monaco",stroke_width=0)
self.title.set_height(0.24)
self.line = Line(LEFT*5,RIGHT*5)
self.dot = Dot(self.line.get_start())
self.title.next_to(self.line,LEFT,buff=0.3)
self.add(self.title,self.line,self.dot)
class RateFunctions(Scene):
CONFIG = {
"rate_functions": [
smooth,
linear,
rush_into,
rush_from,
slow_into,
double_smooth,
there_and_back,
running_start,
wiggle,
lingering,
exponential_decay
],
"rt": 3
}
def construct(self):
time_ad = [*[Text("%d"%i,font="Arial",stroke_width=0).to_corner(UL) for i in range(1,4)]][::-1]
rf_group = VGroup(*[
TestPath(rf)
for rf in self.rate_functions
])
for rf in rf_group:
rf.title.set_color(TEAL)
rf.line.set_color([RED,BLUE,YELLOW])
rf_group.arrange(DOWN,aligned_edge=RIGHT)
init_point = rf_group[0].line.get_start()
init_point[0] = 0
end_point = rf_group[-1].line.get_end()
brace = Brace(rf_group[-1].line,DOWN,buff=0.5)
brace_text = brace.get_text("\\tt run\\_time = %d"%self.rt).scale(0.8)
end_point[0] = 0
div_lines = VGroup()
div_texts = VGroup()
for i in range(11):
proportion = i / 10
text = TexMobject("\\frac{%s}{10}"%i)
text.set_height(0.5)
coord_proportion = rf_group[0].line.point_from_proportion(proportion)
coord_proportion[1] = 0
v_line = DashedLine(
init_point + coord_proportion + UP*0.5,
end_point + coord_proportion + DOWN*0.5,
stroke_opacity=0.5
)
text.next_to(v_line,UP,buff=0.1)
div_texts.add(text)
div_lines.add(v_line)
self.add(rf_group,div_lines,div_texts,brace,brace_text)
for i in range(3):
self.add(time_ad[i])
self.wait()
self.remove(time_ad[i])
self.play(*[
MoveAlongPath(vg.dot,vg.line,rate_func=vg.func)
for vg in rf_group
],
run_time=self.rt
)
self.wait(2)
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/vector_fields/vector_fields_scenes.py | from manimlib.imports import *
class VectorFieldScene1(Scene):
def construct(self):
func = lambda p: np.array([
p[0]/2, # x
p[1]/2, # y
0 # z
])
# Normalized
vector_field_norm = VectorField(func)
# Not normalized
vector_field_not_norm = VectorField(func, length_func=linear)
self.play(*[GrowArrow(vec) for vec in vector_field_norm])
self.wait(2)
self.play(ReplacementTransform(vector_field_norm,vector_field_not_norm))
self.wait(2)
# Other way
def functioncurlreal(p, velocity=0.05):
x, y = p[:2]
result = - y * RIGHT + x * UP
result *= velocity
return result
class VectorFieldScene2(Scene):
def construct(self):
vector_field = VectorField(functioncurlreal)
dot1 = Dot([1,1,0], color=RED)
dot2 = Dot([2,2,0], color=BLUE)
self.add(vector_field,dot1,dot2)
self.wait()
for dot in dot1,dot2:
move_submobjects_along_vector_field(
dot,
lambda p: functioncurlreal(p,0.5)
)
self.wait(3)
for dot in dot1,dot2:
dot.clear_updaters()
self.wait()
class VectorFieldScene3(Scene):
def construct(self):
vector_field = VectorField(
lambda p: functioncurlreal(p,0.5),
length_func = lambda norm: 0.6 * sigmoid(norm)
)
dot = Dot([2,3,0]).fade(1)
some_vector = vector_field.get_vector(dot.get_center())
some_vector.add_updater(
lambda mob: mob.become(vector_field.get_vector(dot.get_center()))
)
self.add(vector_field,dot,some_vector)
self.play(
dot.shift,LEFT*4,
run_time=3
)
self.play(
dot.shift,DOWN*5,
run_time=3
)
self.play(
Rotating(dot, radians=PI, about_point=ORIGIN),
run_time=5
)
self.wait()
# Electric field animation, 3Blue1Brown property
# This animation belongs to the file:
# https://github.com/3b1b/manim/blob/master/from_3b1b/old/div_curl.py#L1293
# This code is not my own, I simply updated it to the recent
# version and documented it.
def get_force_field_func(*point_strength_pairs, **kwargs):
radius = kwargs.get("radius", 0.5)
def func(point):
result = np.array(ORIGIN)
for center, strength in point_strength_pairs:
to_center = center - point
norm = get_norm(to_center)
if norm == 0:
continue
elif norm < radius:
to_center /= radius**3
elif norm >= radius:
to_center /= norm**3
to_center *= -strength
result += to_center
return result
return func
class ElectricParticle(Circle):
CONFIG = {
"color": WHITE,
"sign": "+",
}
def __init__(self, radius=0.5 ,**kwargs):
digest_config(self, kwargs)
super().__init__(
stroke_color=WHITE,
stroke_width=0.5,
fill_color=self.color,
fill_opacity=0.8,
radius=radius
)
sign = TexMobject(self.sign)
sign.set_stroke(WHITE, 1)
sign.set_width(0.5 * self.get_width())
sign.move_to(self)
self.add(sign)
class Proton(ElectricParticle):
CONFIG = {
"color": RED_E,
}
class Electron(ElectricParticle):
CONFIG = {
"color": BLUE_E,
"sign": "-"
}
class ChangingElectricField(Scene):
CONFIG = {
"vector_field_config": {},
"num_particles": 6,
"anim_time": 5,
}
def construct(self):
particles = self.get_particles()
vector_field = self.get_vector_field()
def update_vector_field(vector_field):
new_field = self.get_vector_field()
vector_field.become(new_field)
vector_field.func = new_field.func
# The dt parameter will be explained in
# future videos, but here is a small preview.
def update_particles(particles, dt):
func = vector_field.func
for particle in particles:
force = func(particle.get_center())
particle.velocity += force * dt
particle.shift(particle.velocity * dt)
vector_field.add_updater(update_vector_field),
particles.add_updater(update_particles),
self.add(
vector_field,
particles
)
# Animation time:
self.wait(self.anim_time)
# Suspend animation
for mob in vector_field,particles:
mob.suspend_updating()
self.wait()
# Restore animation
for mob in vector_field,particles:
mob.resume_updating()
self.wait(3)
def get_particles(self):
particles = self.particles = VGroup()
for n in range(self.num_particles):
if n % 2 == 0:
particle = Proton(radius=0.2)
particle.charge = +1
else:
particle = Electron(radius=0.2)
particle.charge = -1
particle.velocity = np.random.normal(0, 0.1, 3)
particles.add(particle)
particle.shift(np.random.normal(0, 0.2, 3))
particles.arrange_in_grid(buff=LARGE_BUFF)
return particles
def get_vector_field(self):
func = get_force_field_func(*list(zip(
list(map(lambda x: x.get_center(), self.particles)),
[p.charge for p in self.particles]
)))
self.vector_field = VectorField(func, **self.vector_field_config)
return self.vector_field
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/tex_formulas/steps.md | # Contador de fórmulas en varios frames
Corrobora que la fórmula sea correcta, en este caso es:
```latex
\lim_{x\to\infty}{1\over x}=0
```
Exportala en la terminal usando
```sh
python3 extract_scene.py -g contador_formulas.py Formula
```
```python3
from big_ol_pile_of_manim_imports import *
#exporta -g o -s
def imprimir_formula_paso_1(self,texto,escala,escala_inversa,direccion,excepcion,separacion):
excepcion=0
self.add(texto.scale(escala))
contador = 0
for j in range(len(texto)):
elemento = TexMobject("%d" %contador)
texto[j].set_color(RED)
self.add(texto[j])
elemento.set_fill(opacity=1)
elemento.to_edge(UP)
self.add(elemento)
self.wait(0.02)
elemento.set_fill(opacity=0)
texto[j].set_color(WHITE)
contador = contador + 1
#exporta -s
def imprimir_formula_paso_2(self,texto,escala,escala_inversa,direccion,excepcion,separacion):
texto.scale(escala).set_color(RED)
self.add(texto)
contador = 0
for j in range(len(texto)):
permiso_imprimir=True
for w in excepcion:
if j==w:
permiso_imprimir=False
if permiso_imprimir:
self.add(texto[j].set_color("#808080"))
contador = contador + 1
contador=0
for j in range(len(texto)):
permiso_imprimir=True
elemento = TexMobject("%d" %contador,color=WHITE)
elemento.scale(escala_inversa)
elemento.next_to(texto[j],direccion,buff=separacion)
for w in excepcion:
if j==w:
permiso_imprimir=False
if permiso_imprimir:
self.add(elemento)
contador = contador + 1
class Formula(Scene):
def construct(self):
formula=TexMobject("\\lim","_","{","x","\\to","\\infty","}","{","1","\\over","x","}","=","0")
excepcion=[]
escala=2.5
escala_inversa=0.5
direccion=DOWN
separacion=0
imprimir_formula_paso_1(self,formula,escala,escala_inversa,direccion,excepcion,separacion)
```
esto te creará una carpeta con todos los frames de la animación, cada frame corresponderá a un elemento de la fórmula:
<p align="center"><img src ="/Español/extras/formulas_tex/gifs/frames.png" /></p>
# Contador en un sólo frame
## Paso 1:
Corrobora que la fórmula sea correcta usando
```sh
python extract_scene.py -s contador_formulas.py Formula
```
<p align="center"><img src ="/Español/extras/formulas_tex/gifs/Paso0.png" /></p>
## Paso 2
En la clase "Formula" modifica (NO EN "def imprimir_formula_paso_1" )
```
imprimir_formula_paso_1
```
por
```
imprimir_formula_paso_2
```
y vuelve a compilarlo.
<p align="center"><img src ="/Español/extras/formulas_tex/gifs/Paso1.png" /></p>
## Paso 3
Agrega al arreglo "excepcion" los elementos que están vacios y vuelve a compilar:
```python3
excepcion=[1,2,6,7,11]
```
<p align="center"><img src ="/Español/extras/formulas_tex/gifs/Paso2.png" /></p>
## Posibles errores
En caso de que sin querer agregues un elemento de más éste aparecerá en rojo indicando que lo incluiste en el arreglo de "excepcion", en este ejemplo eliminaremos la linea de quebrados (elemento 9):
```python3
excepcion=[1,2,6,7,11,9]
```
<p align="center"><img src ="/Español/extras/formulas_tex/gifs/Paso_error.png" /></p>
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/sets/fast_render.md | # Copy the following commands:
## manimlib/constans.py
```python3
CUSTOM_QUALITY_CAMERA_CONFIG = {
"pixel_height": 720,
"pixel_width": 1280,
"frame_rate": 10,
}
```
```python3
def set_custom_quality(height,fps):
video_parameters=[
("pixel_height",height),
("pixel_width",int(height*16/9)),
("frame_rate",fps)
]
for v_property,v_value in video_parameters:
CUSTOM_QUALITY_CAMERA_CONFIG[v_property]=v_value
```
## manimlib/config.py
```python3
parser.add_argument(
"-k","--custom_quality",
action="store_true",
help="Custom size in file",
),
parser.add_argument(
"-x","--fps",
help="Custom fps",
),
```
```python3
"fps": args.fps,
```
```python3
if args.low_quality:
camera_config.update(manimlib.constants.LOW_QUALITY_CAMERA_CONFIG)
elif args.medium_quality:
camera_config.update(manimlib.constants.MEDIUM_QUALITY_CAMERA_CONFIG)
elif args.custom_quality:
try:
manimlib.constants.CUSTOM_QUALITY_CAMERA_CONFIG["frame_rate"]=int(args.fps)
except:
pass
camera_config.update(manimlib.constants.CUSTOM_QUALITY_CAMERA_CONFIG)
else:
camera_config.update(manimlib.constants.PRODUCTION_QUALITY_CAMERA_CONFIG)
```
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/manim_challenges/roulette_epicycloids.py | old_version = True
if old_version:
from big_ol_pile_of_manim_imports import *
else:
from manimlib.imports import *
class EpicycloidSceneSimple(Scene):
def construct(self):
radius1 = 2.4
radius2 = radius1/3
self.epy(radius1,radius2)
def epy(self,r1,r2):
# Manim circle
c1 = Circle(radius=r1,color=BLUE)
# Small circle
c2 = Circle(radius=r2,color=PURPLE).rotate(PI)
c2.next_to(c1,RIGHT,buff=0)
c2.start = c2.copy()
# Dot
# .points[0] return the start path coordinate
# .points[-1] return the end path coordinate
dot = Dot(c2.points[0],color=RED)
# Line
line = Line(c2.get_center(),dot.get_center()).set_stroke(BLACK,2.5)
# Path
path = VMobject(color=RED)
# Path can't have the same coord twice, so we have to dummy point
path.set_points_as_corners([dot.get_center(),dot.get_center()+UP*0.001])
# Path group
path_group = VGroup(line,dot,path)
# Alpha, from 0 to 1:
alpha = ValueTracker(0)
self.play(ShowCreation(line),ShowCreation(c1),ShowCreation(c2),GrowFromCenter(dot))
# update function of path_group
def update_group(group):
l,mob,previus_path = group
mob.move_to(c2.points[0])
old_path = path.copy()
# See manimlib/mobject/types/vectorized_mobject.py
old_path.append_vectorized_mobject(Line(old_path.points[-1],mob.get_center()))
old_path.make_smooth()
l.put_start_and_end_on(c2.get_center(),mob.get_center())
path.become(old_path)
# update function of small circle
def update_c2(c):
c.become(c.start)
c.rotate(TAU*alpha.get_value(),about_point=c1.get_center())
c.rotate(TAU*(r1/r2)*alpha.get_value(),about_point=c.get_center())
path_group.add_updater(update_group)
c2.add_updater(update_c2)
self.add(c2,path_group)
self.play(
alpha.set_value,1,
rate_func=linear,
run_time=6
)
self.wait(2)
c2.clear_updaters()
path_group.clear_updaters()
self.play(FadeOut(VGroup(c1,c2,path_group)))
class EpicycloidSceneComplete(Scene):
CONFIG = {
"camera_config": {"background_color":WHITE},
"radius":2.4,
"color_path":RED,
"divisions":[3,4,5,6]
}
def construct(self):
self.show_axes()
self.show_animation()
def show_axes(self,partition=3):
step_size = self.radius/partition
# See all options in manimlib/mobject/number_line.py
x_axis = NumberLine(
x_min = -step_size*7,
x_max = step_size*7.8,
unit_size = step_size,
include_tip = True,
include_numbers = True,
number_scale_val = 0.5,
color=BLACK,
exclude_zero_from_default_numbers = True,
decimal_number_config = {"color":BLACK}
)
y_axis = NumberLine(
x_min = -step_size*5,
x_max = step_size*5.5,
unit_size = step_size,
include_tip = True,
include_numbers = True,
number_scale_val = 0.5,
color=BLACK,
label_direction = UP,
exclude_zero_from_default_numbers = True,
decimal_number_config = {"color":BLACK}
)
y_axis.rotate(PI/2,about_point = ORIGIN)
# rotate labels in y_axis
for number in y_axis.numbers:
number.rotate(-PI/2,about_point = number.get_center())
self.play(Write(x_axis),Write(y_axis))
self.wait()
def show_animation(self):
c = True
for i in self.divisions:
self.epy(self.radius,self.radius/i,c)
c = False
def epy(self,r1,r2,animation):
# Manim circle
c1 = Circle(radius=r1,color=BLUE)
# Small circle
c2 = Circle(radius=r2,color=BLACK).rotate(PI)
c2.next_to(c1,RIGHT,buff=0)
c2.start = c2.copy()
# Dot
dot = Dot(c2.point_from_proportion(0),color=self.color_path)
# Line
line = Line(c2.get_center(),dot.get_center()).set_stroke(BLACK,2.5)
# Path
path = VMobject(color=self.color_path)
path.set_points_as_corners([dot.get_center(),dot.get_center()+UP*0.001])
# Path group
path_group = VGroup(line,dot,path)
# Alpha
alpha = ValueTracker(0)
# If the animation start then shows the animation
if animation:
self.play(ShowCreation(line),ShowCreation(c1),ShowCreation(c2),GrowFromCenter(dot))
else:
self.remove(self.dot)
self.add_foreground_mobjects(dot)
self.play(ShowCreation(line),ShowCreation(c2))
self.remove_foreground_mobjects(dot)
self.add(c1,c2,path)
# update function of path_group
def update_group(group):
l,mob,previus_path = group
mob.move_to(c2.point_from_proportion(0))
old_path = path.copy()
old_path.append_vectorized_mobject(Line(old_path.points[-1],dot.get_center()))
old_path.make_smooth()
l.put_start_and_end_on(c2.get_center(),dot.get_center())
path.become(old_path)
# update function of small circle
def update_c2(c):
c.become(c.start)
c.rotate(TAU*alpha.get_value(),about_point=c1.get_center())
c.rotate(TAU*(r1/r2)*alpha.get_value(),about_point=c.get_center())
path_group.add_updater(update_group)
c2.add_updater(update_c2)
self.add(c2,path_group)
self.play(
alpha.set_value,1,
rate_func=linear,
run_time=6
)
self.wait()
c2.clear_updaters()
path_group.clear_updaters()
self.dot = dot
self.play(FadeOut(path),FadeOut(c2),FadeOut(line))
# With alpha parameter in updater function
class EpicycloidSceneSimple_alpha(Scene):
def construct(self):
radius1 = 2.4
radius2 = radius1/3
self.epy(radius1,radius2)
def epy(self,r1,r2):
# Manim circle
c1 = Circle(radius=r1,color=BLUE)
# Small circle
c2 = Circle(radius=r2,color=PURPLE).rotate(PI)
c2.next_to(c1,RIGHT,buff=0)
c2.start = c2.copy()
# Dot
dot = Dot(c2.points[0],color=YELLOW)
# Line
line = Line(c2.get_center(),dot.get_center()).set_stroke(BLACK,2.5)
# Path
path = VMobject(color=RED)
path.set_points_as_corners([dot.get_center(),dot.get_center()+UP*0.001])
# Path group
path_group = VGroup(line,dot,path)
self.play(ShowCreation(line),ShowCreation(c1),ShowCreation(c2),GrowFromCenter(dot))
# update function of path_group
def update_group(group):
l,mob,previus_path = group
mob.move_to(c2.points[0])
old_path = path.copy()
old_path.append_vectorized_mobject(Line(old_path.points[-1],dot.get_center()))
old_path.make_smooth()
l.put_start_and_end_on(c2.get_center(),dot.get_center())
path.become(old_path)
# update function of small circle
def update_c2(c,alpha):
c.become(c.start)
c.rotate(TAU*alpha,about_point=c1.get_center())
c.rotate(TAU*(r1/r2)*alpha,about_point=c.get_center())
path_group.add_updater(update_group)
self.add(path_group)
self.play(
UpdateFromAlphaFunc(c2,update_c2,rate_func=linear,run_time=6)
)
self.wait()
class EpicycloidSceneComplete_alpha(Scene):
CONFIG = {
"camera_config": {"background_color":WHITE},
"radius":2.4,
"color_path":RED,
"divisions":[3,4,5,6]
}
def construct(self):
self.show_axes()
self.show_animation()
def show_axes(self,partition=3):
step_size = self.radius/partition
# See all options in manimlib/mobject/number_line.py
x_axis = NumberLine(
x_min = -step_size*7,
x_max = step_size*7.8,
unit_size = step_size,
include_tip = True,
include_numbers = True,
number_scale_val = 0.5,
color=BLACK,
exclude_zero_from_default_numbers = True,
decimal_number_config = {"color":BLACK}
)
y_axis = NumberLine(
x_min = -step_size*5,
x_max = step_size*5.5,
unit_size = step_size,
include_tip = True,
include_numbers = True,
number_scale_val = 0.5,
color=BLACK,
label_direction = UP,
exclude_zero_from_default_numbers = True,
decimal_number_config = {"color":BLACK}
)
y_axis.rotate(PI/2,about_point = ORIGIN)
# rotate labels in y_axis
for number in y_axis.numbers:
number.rotate(-PI/2,about_point = number.get_center())
self.play(Write(x_axis),Write(y_axis))
self.wait()
def show_animation(self):
c = True
for i in self.divisions:
self.epy(self.radius,self.radius/i,c)
c = False
def epy(self,r1,r2,animation):
# Manim circle
c1 = Circle(radius=r1,color=BLUE)
# Small circle
c2 = Circle(radius=r2,color=BLACK).rotate(PI)
c2.next_to(c1,RIGHT,buff=0)
c2.start = c2.copy()
# Dot
dot = Dot(c2.points[0],color=self.color_path)
# Line
line = Line(c2.get_center(),dot.get_center()).set_stroke(BLACK,2.5)
# Path
path = VMobject(color=self.color_path)
path.set_points_as_corners([dot.get_center(),dot.get_center()+UP*0.001])
# Path group
path_group = VGroup(line,dot,path)
# If the animation start then shows the animation
if animation:
self.play(ShowCreation(line),ShowCreation(c1),ShowCreation(c2),GrowFromCenter(dot))
else:
self.remove(self.dot)
self.add_foreground_mobjects(dot)
self.play(ShowCreation(line),ShowCreation(c2))
self.remove_foreground_mobjects(dot)
self.add(c1,c2,path)
# update function of path_group
def update_group(group):
l,mob,previus_path = group
mob.move_to(c2.points[0])
old_path = path.copy()
old_path.append_vectorized_mobject(Line(old_path.points[-1],dot.get_center()))
old_path.make_smooth()
l.put_start_and_end_on(c2.get_center(),dot.get_center())
path.become(old_path)
# update function of small circle
def update_c2(c,alpha):
c.become(c.start)
c.rotate(TAU*alpha,about_point=c1.get_center())
c.rotate(TAU*(r1/r2)*alpha,about_point=c.get_center())
path_group.add_updater(update_group)
self.add(path_group)
self.play(
UpdateFromAlphaFunc(c2,update_c2,rate_func=linear,run_time=5)
)
self.wait()
self.dot = dot
self.play(FadeOut(path),FadeOut(c2),FadeOut(line))
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/manim_challenges/geo_analy.py | old_version = False
if old_version:
from big_ol_pile_of_manim_imports import *
else:
from manimlib.imports import *
class Dot(Dot):
CONFIG = {
"fill_color": BLUE,
"fill_opacity": 1,
"stroke_color": RED,
"stroke_width": 1.7,
}
class ParabolaCreation(GraphScene):
CONFIG = {
"x_min": -6,
"x_max": 6,
"x_axis_width": 12,
"y_axis_height": 7,
"graph_origin": 3.5 * DOWN,
"y_min": 0,
"y_max": 7,
}
def construct(self):
self.setup_axes()
self.x_axis.remove(self.x_axis[1])
self.y_axis.remove(self.y_axis[1])
self.play(Write(self.axes))
h = 0; k = 1; p = 1
parabola_function = lambda x: ((x-h)**2)/(4*p) + k
parabola_right = self.get_graph(
parabola_function,
x_min = 0,
x_max = 5,
color = BLUE
).set_stroke(None,3)
parabola_left = self.get_graph(
parabola_function,
x_min = 0,
x_max = -5,
color = BLUE
).set_stroke(None,3)
anim_kwargs = {"run_time":5,"rate_func":linear}
self.move_dot_path(parabola_right,anim_kwargs)
self.move_dot_path(parabola_left,anim_kwargs)
def move_dot_path(self,parabola,anim_kwargs):
h = 0; k = 1; p = 1
parabola_copy = parabola.copy()
focus = Dot(self.coords_to_point(0,2))
dot_guide = Dot(self.coords_to_point(h,p))
dot_d = Dot(self.coords_to_point(0,0))
circle = Circle(radius=1).move_to(self.coords_to_point(h,p))
line_f_d = DashedLine(focus.get_center(),dot_guide.get_center())
line_d_d = DashedLine(dot_guide.get_center(),dot_d.get_center())
group = VGroup(circle,line_f_d,line_d_d,dot_d)
def update_group(group):
c,f_d,d_d,d = group
d.move_to(self.coords_to_point(dot_guide.get_center()[0],0))
radius = get_norm(focus.get_center() - dot_guide.get_center())
new_c = Circle(radius = radius)
new_c.move_to(dot_guide)
c.become(new_c)
f_d.become(DashedLine(focus.get_center(),dot_guide.get_center()))
d_d.become(DashedLine(dot_guide.get_center(),dot_d.get_center()))
group.add_updater(update_group)
self.play(*[
GrowFromCenter(mob) for mob in [circle,line_f_d,line_d_d,dot_guide,dot_d,focus]
])
self.add(
group,
focus,
dot_guide,
)
self.wait()
self.play(
ShowCreation(parabola),
MoveAlongPath(dot_guide,parabola_copy),
**anim_kwargs
)
group.clear_updaters()
self.wait(1.2)
self.play(FadeOut(VGroup(group,dot_guide,focus)))
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/manim_challenges/dragon_fractal.py | old_version = True
if old_version:
from big_ol_pile_of_manim_imports import *
else:
from manimlib.imports import *
class Dragon(MovingCameraScene):
CONFIG = {
"iterations":15,
"angle":90*DEGREES,
"border_proportion":1.25,
"colors":[RED_A,RED_C,RED_E,BLUE_A,
BLUE_C,BLUE_E,YELLOW_A,YELLOW_C,
YELLOW_E,PURPLE_A,PURPLE_C,PURPLE_E]
}
def construct(self):
self.color = it.cycle(self.colors)
path = VGroup()
first_line = Line(ORIGIN, UP / 5, color = next(self.color))
path.add(first_line)
self.camera_frame.set_height(first_line.get_height() * self.border_proportion)
self.camera_frame.move_to(first_line)
self.play(ShowCreation(first_line))
self.add_foreground_mobject(path)
self.target_path = self.get_all_paths(path,self.iterations)
for i in range(self.iterations):
self.duplicate_path(path,i)
self.wait()
def duplicate_path(self,path,i):
set_paths = self.target_path[:2**(i + 1)]
height = set_paths.get_height() * self.border_proportion
new_path = path.copy()
new_path.set_color(next(self.color))
self.add(new_path)
point = self.get_last_point(path)
self.play(
Rotating(
new_path,
radians=self.angle,
about_point=path[-1].points[point],
rate_func=linear
),
self.camera_frame.move_to,set_paths,
self.camera_frame.set_height,height,
run_time=1, rate_func=smooth
)
self.add_foreground_mobject(new_path)
post_path = reversed([*new_path])
path.add(*post_path)
def get_all_paths(self, path, iterations):
target_path = path.copy()
for _ in range(iterations):
new_path = target_path.copy()
point = self.get_last_point(new_path)
new_path.rotate(
self.angle,
about_point=target_path[-1].points[point],
)
post_path = reversed([*new_path])
target_path.add(*post_path)
return target_path
def get_last_point(self, path):
return 0 if len(path) > 1 else -1
|
AnimationsWithManim_Elteoremadebeethoven/English/extra/manim_challenges/MmodN_epicycloids.py | old_version = True
if old_version:
from big_ol_pile_of_manim_imports import *
else:
from manimlib.imports import *
class SimpleMmodN(Scene):
def construct(self):
circle,lines = self.get_m_mod_n_objects(3,60)
self.play(FadeIn(VGroup(circle,lines)))
def get_m_mod_n_objects(self,x,y):
circle = Circle().set_height(FRAME_HEIGHT)
circle.scale(0.85)
lines = VGroup()
for i in range(y):
start_point = circle.point_from_proportion((i%y)/y)
end_point = circle.point_from_proportion(((i*x)%y)/y)
line = Line(start_point,end_point).set_stroke(width=1)
lines.add(line)
return [circle,lines]
class MmodN(SimpleMmodN):
def construct(self):
circle = Circle().set_height(FRAME_HEIGHT)
circle.scale(0.85)
circle.to_edge(RIGHT,buff=1)
self.play(ShowCreation(circle))
for x,y in [(2,100),(3,60),(4,60),(5,70)]:
self.Example3b1b(self.get_m_mod_n_objects(x,y),x,y)
self.play(FadeOut(circle))
def Example3b1b(self,obj,x,y):
circle,lines = obj
lines.set_stroke(width=1)
label = TexMobject(f"f({x},{y})").scale(2.5).to_edge(LEFT,buff=1)
VGroup(circle,lines).to_edge(RIGHT,buff=1)
self.play(
Write(label),
self.LaggedStartLines(lines)
)
self.wait()
lines_c = lines.copy()
lines_c.set_color(PINK)
lines_c.set_stroke(width=3)
self.play(
self.LaggedStartShowCrationThenDestructionLines(lines_c)
)
self.wait()
self.play(FadeOut(lines),Write(label,rate_func=lambda t: smooth(1-t)))
def LaggedStartLines(self,lines):
if old_version:
return LaggedStart(
ShowCreation,lines,
run_time=4
)
else:
return LaggedStartMap(
ShowCreation,lines,
run_time=4
)
def LaggedStartShowCrationThenDestructionLines(self,lines):
if old_version:
return LaggedStart(
ShowCreationThenDestruction,lines,
run_time=6
)
else:
return LaggedStartMap(
ShowCreationThenDestruction,lines,
run_time=6
)
|
AnimationsWithManim_Elteoremadebeethoven/English/3_text_like_arrays/3_text_like_arrays.py | from big_ol_pile_of_manim_imports import *
COLOR_P="#3EFC24"
class TextColor(Scene):
def construct(self):
text = TextMobject("A","B","C","D","E","F")
text[0].set_color(RED)
text[1].set_color(BLUE)
text[2].set_color(GREEN)
text[3].set_color(ORANGE)
text[4].set_color("#DC28E2") #Hexadecimal color
text[5].set_color(COLOR_P)
self.play(Write(text))
self.wait(2)
class FormulaColor1(Scene):
def construct(self):
text = TexMobject("x","=","{a","\\over","b}")
text[0].set_color(RED)
text[1].set_color(BLUE)
text[2].set_color(GREEN)
text[3].set_color(ORANGE)
text[4].set_color("#DC28E2")
self.play(Write(text))
self.wait(2)
class FormulaColor2(Scene):
def construct(self):
text = TexMobject("x","=","\\frac{a}{b}")
text[0].set_color(RED)
text[1].set_color(BLUE)
text[2].set_color(GREEN)
self.play(Write(text))
self.wait(2)
class FormulaColor3(Scene):
def construct(self):
text = TexMobject("\\sqrt{","\\int_{","a}^","{b}","\\left(","\\frac{x}{y}","\\right)","dx}")
text[0].set_color(RED)
text[1].set_color(BLUE)
text[2].set_color(GREEN)
text[3].set_color(YELLOW)
text[4].set_color(PINK)
text[5].set_color(ORANGE)
text[6].set_color(PURPLE)
text[7].set_color(MAROON)
self.play(Write(text))
self.wait(2)
class FormulaColor3Fixed(Scene):
def construct(self):
text = TexMobject("\\sqrt{","\\int_{","a}^","{b}","\\left(","\\frac{x}{y}","\\right)","dx.}")
text[0].set_color(RED)
text[1].set_color(BLUE)
text[2].set_color(GREEN)
text[3].set_color(YELLOW)
text[4].set_color(PINK)
text[5].set_color(ORANGE)
text[6].set_color(PURPLE)
text[7].set_color(MAROON)
self.play(Write(text))
self.wait(3)
class FormulaColor3Fixed2(Scene):
def construct(self):
text = TexMobject("\\sqrt{","\\int_","{a}^","{b}","{\\left(","{x","\\over","y}","\\right)}","d","x",".}")
text[0].set_color(RED)
text[1].set_color(BLUE)
text[2].set_color(GREEN)
text[3].set_color(YELLOW)
text[4].set_color(PINK)
text[5].set_color(ORANGE)
text[6].set_color(PURPLE)
text[7].set_color(MAROON)
text[8].set_color(TEAL)
text[9].set_color(GOLD)
self.play(Write(text))
self.wait(3)
class FormulaColor4(Scene):
def construct(self):
text = TexMobject("\\sqrt{","\\int_","{a","+","c}^","{b}","{\\left(","{x","\\over","y}","\\right)}","d","x",".}")
text[0].set_color(RED)
text[1].set_color(BLUE)
text[2].set_color(GREEN)
text[3].set_color(YELLOW)
text[4].set_color(PINK)
text[5].set_color(ORANGE)
text[6].set_color(PURPLE)
text[7].set_color(MAROON)
text[8].set_color(TEAL)
text[9].set_color(GOLD)
text[10].set_color(GRAY)
text[11].set_color(RED)
self.play(Write(text))
self.wait(3)
class FormulaColor5(Scene):
def construct(self):
text = TexMobject("\\sqrt{","\\int_","{a","+","c}^","{b}","{\\left(","{x","\\over","y}","\\right)}","d","x",".}")
for i,color in zip(text,[PURPLE,BLUE,GREEN,YELLOW,PINK]):
i.set_color(color)
self.play(Write(text))
self.wait(3)
class ColorByCaracter(Scene):
def construct(self):
text = TexMobject("{d","\\over","d","x","}","\\int_","{a}^","{","x","}","f(","t",")d","t","=","f(","x",")")
text.set_color_by_tex("x",RED)
self.play(Write(text))
self.wait(2)
class ColorByCaracterFixed(Scene):
def construct(self):
text = TexMobject("{d","\\over","d","x","}","\\int_","{a}^","{","x","}","f(","t",")d","t","=","f(","x",")")
text.set_color_by_tex("x",RED)
text[6].set_color(RED)
text[8].set_color(WHITE)
self.play(Write(text))
self.wait(2)
class ListFor(Scene):
def construct(self): #no usar siempre frac
text = TexMobject("[0]","[1]","[2]","[3]","[4]","[5]","[6]","[7]")
for i in [0,1,3,4]:
text[i].set_color(RED)
self.play(Write(text))
self.wait(3)
class ForRange1(Scene):
def construct(self): #no usar siempre frac
text = TexMobject("[0]","[1]","[2]","[3]","[4]","[5]","[6]","[7]")
for i in range(3):
text[i].set_color(RED)
self.play(Write(text))
self.wait(3)
class ForRange2(Scene):
def construct(self): #no usar siempre frac
text = TexMobject("[0]","[1]","[2]","[3]","[4]","[5]","[6]","[7]")
for i in range(2,6):
text[i].set_color(RED)
self.play(Write(text))
self.wait(3)
class ForTwoVariables(Scene):
def construct(self): #no usar siempre frac
text = TexMobject("[0]","[1]","[2]","[3]","[4]","[5]","[6]","[7]")
for i,color in [(2,RED),(4,PINK)]:
text[i].set_color(color)
self.play(Write(text))
self.wait(3)
class ChangeSize(Scene):
def construct(self):
text = TexMobject("\\sum_{i=0}^n i=\\frac{n(n+1)}{2}")
self.add(text)
self.wait()
text.scale_in_place(2)
self.wait(2)
class AddAndRemoveText(Scene):
def construct(self):
text = TextMobject("Text or object")
self.wait()
self.add(text)
self.wait()
self.remove(text)
self.wait()
class FadeText(Scene):
def construct(self):
text = TextMobject("Text or object")
self.play(FadeIn(text))
self.wait()
self.play(FadeOut(text),run_time=1)
self.wait()
class FadeTextFromDirection(Scene):
def construct(self):
text = TextMobject("Text or object")
self.play(FadeInFrom(text,DOWN),run_time=1)
self.wait()
class GrowObjectFromCenter(Scene):
def construct(self):
text = TextMobject("Text or object")
self.play(GrowFromCenter(text),run_time=1)
self.wait()
class ShowCreationObject(Scene):
def construct(self):
text = TextMobject("Text or object")
self.play(ShowCreation(text),run_time=1)
self.wait()
class ColoringText(Scene):
def construct(self):
text = TextMobject("Text or object")
self.add(text)
self.wait(0.5)
for letter in text:
self.play(LaggedStart(
ApplyMethod, letter,
lambda m : (m.set_color, YELLOW),
run_time = 0.12
))
self.wait(0.5)
class CrossText1(Scene):
def construct(self):
text = TexMobject("\\sum_{i=1}^{\\infty}i","=","-\\frac{1}{2}")
cross = Cross(text[2])
cross.set_stroke(RED, 6)
self.play(Write(text))
self.wait(.5)
self.play(ShowCreation(cross))
self.wait(2)
class CrossText2(Scene):
def construct(self):
text = TexMobject("\\sum_{i=1}^{\\infty}i","=","-\\frac{1}{2}")
eq = VGroup(text[1],text[2])
cross = Cross(eq)
cross.set_stroke(RED, 6)
self.play(Write(text))
self.wait(.5)
self.play(ShowCreation(cross))
self.wait(2)
class FrameBox1(Scene):
def construct(self):
text=TexMobject(
"\\hat g(", "f", ")", "=", "\\int", "_{t_1}", "^{t_{2}}",
"g(", "t", ")", "e", "^{-2\\pi i", "f", "t}", "dt"
)
frameBox = SurroundingRectangle(text[4], buff = 0.5*SMALL_BUFF)
self.play(Write(text))
self.wait(.5)
self.play(ShowCreation(frameBox))
self.wait(2)
class FrameBox2(Scene):
def construct(self):
text=TexMobject(
"\\hat g(", "f", ")", "=", "\\int", "_{t_1}", "^{t_{2}}",
"g(", "t", ")", "e", "^{-2\\pi i", "f", "t}", "dt"
)
seleccion=VGroup(text[4],text[5],text[6])
frameBox = SurroundingRectangle(seleccion, buff = 0.5*SMALL_BUFF)
frameBox.set_stroke(GREEN,9)
self.play(Write(text))
self.wait(.5)
self.play(ShowCreation(frameBox))
self.wait(2)
class BraceText(Scene):
def construct(self):
text=TexMobject(
"\\frac{d}{dx}f(x)g(x)=","f(x)\\frac{d}{dx}g(x)","+",
"g(x)\\frac{d}{dx}f(x)"
)
self.play(Write(text))
brace_top = Brace(text[1], UP, buff = SMALL_BUFF)
brace_bottom = Brace(text[3], DOWN, buff = SMALL_BUFF)
text_top = brace_top.get_text("$g'f$")
text_bottom = brace_bottom.get_text("$f'g$")
self.play(
GrowFromCenter(brace_top),
GrowFromCenter(brace_bottom),
FadeIn(text_top),
FadeIn(text_bottom)
)
self.wait() |
AnimationsWithManim_Elteoremadebeethoven/English/3_text_like_arrays/scenes.md | # Programs
```python3
COLOR_P="#3EFC24"
class TextColor(Scene):
def construct(self):
text = TextMobject("A","B","C","D","E","F")
text[0].set_color(RED)
text[1].set_color(BLUE)
text[2].set_color(GREEN)
text[3].set_color(ORANGE)
text[4].set_color("#DC28E2") #Hexadecimal color
text[5].set_color(COLOR_P)
self.play(Write(text))
self.wait(2)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/TextColor.gif" /></p>
```python3
class FormulaColor1(Scene):
def construct(self):
text = TexMobject("x","=","{a","\\over","b}")
text[0].set_color(RED)
text[1].set_color(BLUE)
text[2].set_color(GREEN)
text[3].set_color(ORANGE)
text[4].set_color("#DC28E2")
self.play(Write(text))
self.wait(2)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/FormulaColor1.gif" /></p>
```python3
class FormulaColor2(Scene):
def construct(self):
text = TexMobject("x","=","\\frac{a}{b}")
text[0].set_color(RED)
text[1].set_color(BLUE)
text[2].set_color(GREEN)
self.play(Write(text))
self.wait(2)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/FormulaColor2.gif" /></p>
```python3
class FormulaColor3(Scene):
def construct(self):
text = TexMobject("\\sqrt{","\\int_{","a}^","{b}","\\left(","\\frac{x}{y}","\\right)","dx}")
text[0].set_color(RED)
text[1].set_color(BLUE)
text[2].set_color(GREEN)
text[3].set_color(YELLOW)
text[4].set_color(PINK)
text[5].set_color(ORANGE)
text[6].set_color(PURPLE)
text[7].set_color(MAROON)
self.play(Write(text))
self.wait(2)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/FormulaColor3.gif" /></p>
```python3
class FormulaColor3Fixed(Scene):
def construct(self):
text = TexMobject("\\sqrt{","\\int_{","a}^","{b}","\\left(","\\frac{x}{y}","\\right)","dx.}")
text[0].set_color(RED)
text[1].set_color(BLUE)
text[2].set_color(GREEN)
text[3].set_color(YELLOW)
text[4].set_color(PINK)
text[5].set_color(ORANGE)
text[6].set_color(PURPLE)
text[7].set_color(MAROON)
self.play(Write(text))
self.wait(3)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/FormulaColor3Fixed.gif" /></p>
```python3
class FormulaColor3Fixed2(Scene):
def construct(self):
text = TexMobject("\\sqrt{","\\int_","{a}^","{b}","{\\left(","{x","\\over","y}","\\right)}","d","x",".}")
text[0].set_color(RED)
text[1].set_color(BLUE)
text[2].set_color(GREEN)
text[3].set_color(YELLOW)
text[4].set_color(PINK)
text[5].set_color(ORANGE)
text[6].set_color(PURPLE)
text[7].set_color(MAROON)
text[8].set_color(TEAL)
text[9].set_color(GOLD)
self.play(Write(text))
self.wait(3)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/FormulaColor3Fixed2.gif" /></p>
```python3
class FormulaColor4(Scene):
def construct(self):
text = TexMobject("\\sqrt{","\\int_","{a","+","c}^","{b}","{\\left(","{x","\\over","y}","\\right)}","d","x",".}")
text[0].set_color(RED)
text[1].set_color(BLUE)
text[2].set_color(GREEN)
text[3].set_color(YELLOW)
text[4].set_color(PINK)
text[5].set_color(ORANGE)
text[6].set_color(PURPLE)
text[7].set_color(MAROON)
text[8].set_color(TEAL)
text[9].set_color(GOLD)
text[10].set_color(GRAY)
text[11].set_color(RED)
self.play(Write(text))
self.wait(3)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/FormulaColor4.gif" /></p>
```python3
class FormulaColor5(Scene):
def construct(self):
text = TexMobject("\\sqrt{","\\int_","{a","+","c}^","{b}","{\\left(","{x","\\over","y}","\\right)}","d","x",".}")
for i,color in zip(text,[PURPLE,BLUE,GREEN,YELLOW,PINK]):
i.set_color(color)
self.play(Write(text))
self.wait(3)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/FormulaColor5.gif" /></p>
```python3
class ColorByCaracter(Scene):
def construct(self):
text = TexMobject("{d","\\over","d","x","}","\\int_","{a}^","{","x","}","f(","t",")d","t","=","f(","x",")")
text.set_color_by_tex("x",RED)
self.play(Write(text))
self.wait(2)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/ColorByCaracter.gif" /></p>
```python3
class ColorByCaracterFixed(Scene):
def construct(self):
text = TexMobject("{d","\\over","d","x","}","\\int_","{a}^","{","x","}","f(","t",")d","t","=","f(","x",")")
text.set_color_by_tex("x",RED)
text[6].set_color(RED)
text[8].set_color(WHITE)
self.play(Write(text))
self.wait(2)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/ColorByCaracterFixed.gif" /></p>
```python3
class ListFor(Scene):
def construct(self): #no usar siempre frac
text = TexMobject("[0]","[1]","[2]","[3]","[4]","[5]","[6]","[7]")
for i in [0,1,3,4]:
text[i].set_color(RED)
self.play(Write(text))
self.wait(3)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/ListFor.gif" /></p>
```python3
class ForRange1(Scene):
def construct(self): #no usar siempre frac
text = TexMobject("[0]","[1]","[2]","[3]","[4]","[5]","[6]","[7]")
for i in range(3):
text[i].set_color(RED)
self.play(Write(text))
self.wait(3)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/ForRange1.gif" /></p>
```python3
class ForRange2(Scene):
def construct(self): #no usar siempre frac
text = TexMobject("[0]","[1]","[2]","[3]","[4]","[5]","[6]","[7]")
for i in range(2,6):
text[i].set_color(RED)
self.play(Write(text))
self.wait(3)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/ForRange2.gif" /></p>
```python3
class ForTwoVariables(Scene):
def construct(self): #no usar siempre frac
text = TexMobject("[0]","[1]","[2]","[3]","[4]","[5]","[6]","[7]")
for i,color in [(2,RED),(4,PINK)]:
text[i].set_color(color)
self.play(Write(text))
self.wait(3)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/ForTwoVariables.gif" /></p>
```python3
class ChangeSize(Scene):
def construct(self):
text = TexMobject("\\sum_{i=0}^n i=\\frac{n(n+1)}{2}")
self.add(text)
self.wait()
text.scale_in_place(2)
self.wait(2)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/ChangeSize.gif" /></p>
```python3
class AddAndRemoveText(Scene):
def construct(self):
text = TextMobject("Text or object")
self.wait()
self.add(text)
self.wait()
self.remove(text)
self.wait()
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/AddAndRemoveText.gif" /></p>
```python3
class FadeText(Scene):
def construct(self):
text = TextMobject("Text or object")
self.play(FadeIn(text))
self.wait()
self.play(FadeOut(text),run_time=1)
self.wait()
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/FadeText.gif" /></p>
```python3
class FadeTextFromDirection(Scene):
def construct(self):
text = TextMobject("Text or object")
self.play(FadeInFrom(text,DOWN),run_time=1)
self.wait()
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/FadeTextFromDirection.gif" /></p>
```python3
class GrowObjectFromCenter(Scene):
def construct(self):
text = TextMobject("Text or object")
self.play(GrowFromCenter(text),run_time=1)
self.wait()
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/GrowObjectFromCenter.gif" /></p>
```python3
class ShowCreationObject(Scene):
def construct(self):
text = TextMobject("Text or object")
self.play(ShowCreation(text),run_time=1)
self.wait()
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/ShowCreationObject.gif" /></p>
```python3
class ColoringText(Scene):
def construct(self):
text = TextMobject("Text or object")
self.add(text)
self.wait(0.5)
for letter in text:
self.play(LaggedStart(
ApplyMethod, letter,
lambda m : (m.set_color, YELLOW),
run_time = 0.12
))
self.wait(0.5)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/ColoringText.gif" /></p>
```python3
class CrossText1(Scene):
def construct(self):
text = TexMobject("\\sum_{i=1}^{\\infty}i","=","-\\frac{1}{2}")
cross = Cross(text[2])
cross.set_stroke(RED, 6)
self.play(Write(text))
self.wait(.5)
self.play(ShowCreation(cross))
self.wait(2)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/CrossText1.gif" /></p>
```python3
class CrossText2(Scene):
def construct(self):
text = TexMobject("\\sum_{i=1}^{\\infty}i","=","-\\frac{1}{2}")
eq = VGroup(text[1],text[2])
cross = Cross(eq)
cross.set_stroke(RED, 6)
self.play(Write(text))
self.wait(.5)
self.play(ShowCreation(cross))
self.wait(2)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/CrossText2.gif" /></p>
```python3
class FrameBox1(Scene):
def construct(self):
text=TexMobject(
"\\hat g(", "f", ")", "=", "\\int", "_{t_1}", "^{t_{2}}",
"g(", "t", ")", "e", "^{-2\\pi i", "f", "t}", "dt"
)
frameBox = SurroundingRectangle(text[4], buff = 0.5*SMALL_BUFF)
self.play(Write(text))
self.wait(.5)
self.play(ShowCreation(frameBox))
self.wait(2)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/FrameBox1.gif" /></p>
```python3
class FrameBox2(Scene):
def construct(self):
text=TexMobject(
"\\hat g(", "f", ")", "=", "\\int", "_{t_1}", "^{t_{2}}",
"g(", "t", ")", "e", "^{-2\\pi i", "f", "t}", "dt"
)
seleccion=VGroup(text[4],text[5],text[6])
frameBox = SurroundingRectangle(seleccion, buff = 0.5*SMALL_BUFF)
frameBox.set_stroke(GREEN,9)
self.play(Write(text))
self.wait(.5)
self.play(ShowCreation(frameBox))
self.wait(2)
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/FrameBox2.gif" /></p>
```python3
class BraceText(Scene):
def construct(self):
text=TexMobject(
"\\frac{d}{dx}f(x)g(x)=","f(x)\\frac{d}{dx}g(x)","+",
"g(x)\\frac{d}{dx}f(x)"
)
self.play(Write(text))
brace_top = Brace(text[1], UP, buff = SMALL_BUFF)
brace_bottom = Brace(text[3], DOWN, buff = SMALL_BUFF)
text_top = brace_top.get_text("$g'f$")
text_bottom = brace_bottom.get_text("$f'g$")
self.play(
GrowFromCenter(brace_top),
GrowFromCenter(brace_bottom),
FadeIn(text_top),
FadeIn(text_bottom)
)
self.wait()
```
<p align="center"><img src ="/English/3_text_like_arrays/gifs/BraceText.gif" /></p>
|
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/enable_submobject_mode_recent_versions.md | # Enable `submobject_mode` in the most recent version of Manim (jun/21)
## Open manimlib/animation/animation.py and add this parameters to Animation CONFIG:
```python3
"submobject_mode": "None",
"lag_factor": 2,
```
## Replace `get_sub_alpha`.
The [original code](https://github.com/3b1b/manim/blob/41792fdb5f9578c7e49455e19416b8474f29f2a8/manimlib/animation/animation.py#L130) is ([version of jun/21](https://github.com/3b1b/manim/tree/41792fdb5f9578c7e49455e19416b8474f29f2a8)):
```python3
#manimlib/animation/animation.py, line 130-138
def get_sub_alpha(self, alpha, index, num_submobjects):
# TODO, make this more understanable, and/or combine
# its functionality with AnimationGroup's method
# build_animations_with_timings
lag_ratio = self.lag_ratio
full_length = (num_submobjects - 1) * lag_ratio + 1
value = alpha * full_length
lower = index * lag_ratio
return np.clip((value - lower), 0, 1)
```
Replace with:
```python3
def get_sub_alpha(self, alpha, index, num_submobjects):
# TODO, make this more understanable, and/or combine
# its functionality with AnimationGroup's method
# build_animations_with_timings
lag_ratio = self.lag_ratio
full_length = (num_submobjects - 1) * lag_ratio + 1
value = alpha * full_length
lower = index * lag_ratio
if self.submobject_mode in ["lagged_start", "smoothed_lagged_start"]:
prop = float(index) / num_submobjects
if self.submobject_mode is "smoothed_lagged_start":
prop = smooth(prop)
lf = self.lag_factor
return np.clip(lf * alpha - (lf - 1) * prop, 0, 1)
elif self.submobject_mode == "one_at_a_time":
lower = float(index) / num_submobjects
upper = float(index + 1) / num_submobjects
return np.clip((alpha - lower) / (upper - lower), 0, 1)
elif self.submobject_mode == "all_at_once":
return alpha
return np.clip((value - lower), 0, 1)
```
|
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/successions_in_recent_versions.py | from manimlib.imports import *
class AnimationGroupExampleFail(Scene):
def construct(self):
dots = VGroup(*[Dot() for _ in range(10)])
dots.arrange(RIGHT,buff=0.8)
self.add(dots)
for dot in dots:
self.play(
dot.scale,3,
dot.set_color,RED,
rate_func=there_and_back
)
self.wait(2)
class AnimationGroupExample(Scene):
def construct(self):
dots = VGroup(*[Dot() for _ in range(10)])
dots.arrange(RIGHT, buff=0.8)
anim_kwargs = {"rate_func": there_and_back}
self.add(dots)
def dot_func(mob):
mob.scale(3)
mob.set_color(RED)
return mob
self.play(
# Replace AnimationGroup with LaggedStart
AnimationGroup(
*[
ApplyFunction(
dot_func,
dot,
**anim_kwargs
)
for dot in dots
]
)
)
self.wait(2)
class AbsctractScene(Scene):
CONFIG = {
"anim_kwargs": {"rate_func": there_and_back}
}
def setup(self):
dots = VGroup(*[Dot() for _ in range(10)])
dots.arrange(RIGHT, buff=0.8)
# Save the state
dots.save_state()
def dot_func(mob):
mob.scale(3)
mob.set_color(RED)
return mob
self.dots = dots
self.dot_func = dot_func
self.add(self.dots)
class LaggedStartMapExample(AbsctractScene):
def construct(self):
self.play(
LaggedStartMap(
GrowFromCenter,
self.dots
)
)
self.wait()
class LaggedStartMapExample2(AbsctractScene):
def construct(self):
self.play(
LaggedStartMap(
GrowFromCenter,
self.dots,
rate_func=there_and_back
)
)
self.wait()
# What happens if remove the following line?
self.dots.restore()
self.play(
LaggedStart(*[
GrowFromCenter(
dot,
rate_func=there_and_back
)
for dot in self.dots
],
)
)
# In summary, LaggedStartMap is a way
# to run LaggedStart without applying
# the spread (splat) operator.
# But it only applies to animations
# that receive a Mobject as the only argument:
# Examples: Write, FadeIn, GrowFromCenter, ShowCreation, MoveToTarget, etc.
self.wait(2)
class AnimationGroupExample2(AbsctractScene):
CONFIG = {
"lag_ratios": list(np.arange(0,1.1,.1))
}
def construct(self):
self.remove(self.dots)
labels = VGroup(*[
Text("lag_ratio: %.1f -"%lg,stroke_width=0,font="Arial").set_height(0.4)
for lg in self.lag_ratios
])
set_dots = VGroup(*[
self.dots.copy() for _ in self.lag_ratios
])
set_dots.arrange(DOWN,buff=0.5)
set_dots.to_edge(RIGHT)
for label, dots in zip(labels,set_dots):
label.next_to(dots,LEFT,buff=0.4)
self.add(labels,set_dots)
self.play(*[
AnimationGroup(*[
ApplyFunction(
self.dot_func,
dot,
rate_func=there_and_back
)
for dot in dots
],
lag_ratio=lg
)
for dots,lg in zip(set_dots,self.lag_ratios)
])
self.wait()
# Successions
class SuccessionExample1(Scene):
def construct(self):
number_line = NumberLine(x_min=-2,x_max=2)
text = TextMobject("Text")\
.next_to(number_line,DOWN)
dashed_line=DashedLine(
number_line.get_left(),
number_line.get_right(),
color=YELLOW,
).set_stroke(width=11)
self.add(number_line)
self.wait(0.3)
self.play(
LaggedStart(
*[ShowCreationThenDestruction(dashed_segment)
for dashed_segment in dashed_line],
run_time=5
),
AnimationGroup(
Animation(Mobject(),run_time=2.1),
Write(text),lag_ratio=1
)
)
self.wait()
class SuccessionExample2(Scene):
def construct(self):
number_line = NumberLine(x_min=-2,x_max=2)
triangle = RegularPolygon(3,start_angle=-PI/2)\
.scale(0.2)\
.next_to(number_line.get_left(),UP,buff=SMALL_BUFF)
text_1 = TextMobject("1")\
.next_to(number_line.get_tick(-1),DOWN)
text_2 = TextMobject("2")\
.next_to(number_line.get_tick(0),DOWN)
text_3 = TextMobject("3")\
.next_to(number_line.get_tick(1),DOWN)
text_4 = TextMobject("4")\
.next_to(number_line.get_tick(2),DOWN)
self.add(number_line)
self.play(ShowCreation(triangle))
self.wait(0.3)
self.play(
# Pauses are referenced to the beginning of the play
# ==================================================
ApplyMethod(triangle.shift,RIGHT*4,rate_func=linear,run_time=4),
AnimationGroup(
Animation(Mobject(),run_time=1), # 1 second pause
Write(text_1),lag_ratio=1
),
AnimationGroup(
Animation(Mobject(),run_time=2), # 2 seconds pause
Write(text_2),lag_ratio=1
),
AnimationGroup(
Animation(Mobject(),run_time=3), # 3 seconds pause
Write(text_3),lag_ratio=1
),
AnimationGroup(
Animation(Mobject(),run_time=4), # 4 seconds pause
Write(text_4),lag_ratio=1
)
)
self.wait()
class SuccessionExample2Compact(Scene):
def construct(self):
number_line=NumberLine(x_min=-2,x_max=2)
triangle=RegularPolygon(3,start_angle=-PI/2)\
.scale(0.2)\
.next_to(number_line.get_left(),UP,buff=SMALL_BUFF)
numbers=VGroup(
*[TextMobject("%s"%i)\
.next_to(number_line.get_tick(i-2),DOWN) for i in range(1,5)]
)
self.add(number_line)
self.play(ShowCreation(triangle))
self.wait(0.3)
self.play(
ApplyMethod(triangle.shift,RIGHT*4,rate_func=linear,run_time=4),
*[AnimationGroup(
Animation(Mobject(),run_time=i+1), # <- This is a pause
Write(numbers[i]),lag_ratio=1
)for i in range(4)],
)
self.wait()
class SuccessionExample3(Scene):
def construct(self):
number_line = NumberLine(x_min=-2,x_max=2)
text_1 = TextMobject("Theorem of")\
.next_to(number_line,DOWN)
text_2 = TextMobject("Beethoven")\
.next_to(number_line,DOWN)
dashed_line = DashedLine(
number_line.get_left(),
number_line.get_right(),
color=YELLOW,
).set_stroke(width=11)
self.add(number_line,text_1)
self.play(
LaggedStart(
*[ShowCreationThenDestruction(dashed_segment)
for dashed_segment in dashed_line],
run_time=5
),
AnimationGroup(
Animation(Mobject(),run_time=2.1),
ReplacementTransform(text_1,text_2),lag_ratio=1
)
)
self.wait()
# Liminations
class SuccessionFail1(Scene):
def construct(self):
text1 = TextMobject("Theorem")
text2 = TextMobject("of")
text3 = TextMobject("Beethoven")
for text in text1,text2,text3:
text.scale(3)
self.add(text1)
self.play(
AnimationGroup(
ReplacementTransform(text1,text2),
ReplacementTransform(text2,text3),
lag_ratio=1
)
)
self.wait()
class SuccessionFail2(Scene):
def construct(self):
text1 = TextMobject("Theorem")
text2 = TextMobject("of")
text3 = TextMobject("Beethoven")
for text in text1,text2,text3:
text.scale(3)
self.add(text1)
self.play(
AnimationGroup(
Transform(text1,text2),
Transform(text1,text3),
lag_ratio=1
)
)
self.wait()
class Succession2(Scene):
def construct(self):
text1 = TextMobject("Theorem")
text2 = TextMobject("of")
text3 = TextMobject("Beethoven")
for text in text1,text2,text3:
text.scale(3)
self.add(text1)
self.play(
Succession(
Transform(text1,text2),
Transform(text1,text3),
lag_ratio=1.2
)
)
self.wait()
# Real example
class ClockOrganization(VGroup):
CONFIG = {
"numbers" : 4,
"radius" : 3.1,
"color" : WHITE
}
def __init__(self, **kwargs):
digest_config(self, kwargs, locals())
self.generate_nodes()
VGroup.__init__(self, *self.node_list,**kwargs)
def generate_nodes(self):
self.node_list = []
for i in range(self.numbers):
mobject = VMobject()
number = TexMobject(str(i+1))
circle = Circle(radius=0.4,color=self.color)
mobject.add(number)
mobject.add(circle)
mobject.move_to(
self.radius * np.cos((-TAU / self.numbers) * i + 17*TAU / 84) * RIGHT
+ self.radius * np.sin((-TAU / self.numbers) * i + 17*TAU / 84) * UP
)
self.node_list.append(mobject)
def select_node(self, node):
selected_node = self.node_list[node]
selected_node.scale(1.2)
selected_node.set_color(RED)
def deselect_node(self, selected_node):
node = self.node_list[selected_node]
node.scale(0.8)
node.set_color(self.color)
class ClockOrganizationScene(Scene):
def construct(self):
test = ClockOrganization(numbers=21)
self.add(test)
animation_steps = []
num_circ = 15
for i in range(num_circ):
thing = test.deepcopy()
thing.select_node((19+i)%test.numbers-1)
animation_steps.append(thing)
anims = []
theta = 180 * DEGREES / num_circ
lag_constant = 5
for i in range(1,num_circ):
test.node_list[(19+i)%test.numbers-1].generate_target()
test.node_list[(19+i)%test.numbers-1].target.scale(1.2)
test.node_list[(19+i)%test.numbers-1].target.set_color(RED)
stop_smooth = lag_constant * np.sin(i*theta)
anims.append(MoveToTarget(test.node_list[(19+i)%test.numbers-1],rate_func=there_and_back))
anims.append(Animation(Mobject(),run_time=stop_smooth))
self.play(
AnimationGroup(*anims,lag_ratio=0.1)
)
self.wait()
|
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/alpha_dt_examples.py | from manimlib.imports import *
# Contents
# ========
# Abstract scenes : Line
# New Classes (objects): Line
# alpha examples : Line
# dt examples : Line
r"""
_ _ _ _ ____
/ \ | |__ ___| |_ _ __ __ _ ___| |_ / ___| ___ ___ _ __ ___ ___
/ _ \ | '_ \/ __| __| '__/ _` |/ __| __| \___ \ / __/ _ \ '_ \ / _ \/ __|
/ ___ \| |_) \__ \ |_| | | (_| | (__| |_ ___) | (_| __/ | | | __/\__ \
/_/ \_\_.__/|___/\__|_| \__,_|\___|\__| |____/ \___\___|_| |_|\___||___/
"""
class ExampleScene(Scene):
CONFIG = {
"title_config": {
"edge": DL,
"buff": 0.3,
"height": 0.6,
"color": GRAY,
"fade": 0.7,
"extra_str": ""
}
}
def setup(self):
title_str = self.__class__.__name__
ex_str = self.title_config["extra_str"]
title = TextMobject(f"\\tt {title_str}{ex_str}",color=self.title_config["color"])
title.set_height(self.title_config["height"])
title.fade(self.title_config["fade"])
if get_norm(self.title_config["edge"]) > 1:
title.to_corner(self.title_config["edge"],buff=self.title_config["buff"])
else:
title.to_edge(self.title_config["edge"],buff=self.title_config["buff"])
self.add(title)
r"""
_ _ ____ _
| \ | | _____ __ / ___| | __ _ ___ ___ ___ ___
| \| |/ _ \ \ /\ / / | | | |/ _` / __/ __|/ _ \/ __|
| |\ | __/\ V V / | |___| | (_| \__ \__ \ __/\__ \
|_| \_|\___| \_/\_/ \____|_|\__,_|___/___/\___||___/
"""
class NewRegularPolygon(RegularPolygon):
def get_sides(self,**kwargs):
vertices = [*self.get_vertices(), self.get_vertices()[0]]
sides = VGroup(*[
Line(vertices[i],vertices[i+1],**kwargs)
for i in range(len(vertices)-1)
])
return sides
def get_external_sides(self,size=1,**kwargs):
sides = self.get_sides()
external_sides = VGroup()
kwargs["stroke_width"] = self.get_stroke_width()
for side in sides:
unit_vector = side.get_unit_vector()
start = side.get_end()
line = Line(
start,
start + size * unit_vector,
**kwargs
)
external_sides.add(line)
return external_sides
def get_external_angles(self,radius=0.7,**kwargs):
external_sides = self.get_external_sides()
sides = self.get_sides()
ind = -1 if self.start_angle == 0 else 1
angle = abs(external_sides[0].get_angle() - sides[ind].get_angle())
arcs = VGroup(*[
Arc(
sides[n].get_angle(),
angle,
radius=radius,
arc_center=external_sides[n].get_start(),
**kwargs
) for n in range(len(sides))
])
return arcs
class GroupRegularPolygon(VGroup):
CONFIG = {
"polygon_color": RED,
"ext_side_color": BLUE,
"ext_angle_color": TEAL
}
def __init__(self,n,size=1,radius=0.7,height=2,**kwargs):
regular_polygon = NewRegularPolygon(n,**kwargs)
regular_polygon.set_height(height)
super().__init__(
regular_polygon.get_external_sides(**kwargs),
regular_polygon.get_external_angles(**kwargs),
regular_polygon
)
self[0].set_color(self.ext_side_color)
self[1].set_color(self.ext_angle_color)
self[2].set_color(self.polygon_color)
self.regular_polygon = regular_polygon
def get_number_sides(self):
return len(self.regular_polygon.get_sides())
def get_figure_height(self):
return self.regular_polygon.get_height()
class Ball(Circle):
CONFIG = {
"radius": 0.4,
"fill_color": BLUE,
"fill_opacity": 1,
"color": BLUE
}
def __init__(self, ** kwargs):
Circle.__init__(self, ** kwargs)
self.velocity = np.array((2, 0, 0))
def get_top(self):
return self.get_center()[1] + self.radius
def get_bottom(self):
return self.get_center()[1] - self.radius
def get_right_edge(self):
return self.get_center()[0] + self.radius
def get_left_edge(self):
return self.get_center()[0] - self.radius
class Box(Rectangle):
CONFIG = {
"height": 6,
"width": FRAME_WIDTH - 2,
"color": GREEN_C
}
def __init__(self, ** kwargs):
Rectangle.__init__(self, ** kwargs) # Edges
self.top = 0.5 * self.height
self.bottom = -0.5 * self.height
self.right_edge = 0.5 * self.width
self.left_edge = -0.5 * self.width
r"""
_ _
__ _| |_ __ | |__ __ _
/ _` | | '_ \| '_ \ / _` |
| (_| | | |_) | | | | (_| |
\__,_|_| .__/|_| |_|\__,_|
|_|
"""
class SumExternalAngles(ExampleScene):
CONFIG = {
"polygon_sides": [3,5,6,7,4],
"init_buff": 0.6
}
def construct(self):
figures = VGroup(*[GroupRegularPolygon(n) for n in self.polygon_sides])
for figure in figures:
figure.save_state()
figure.height = figure.get_figure_height()
def shrink_polygon(vgroup,alpha):
buff = interpolate(self.init_buff,2,alpha)
for mob in vgroup:
mob.restore()
d_height = interpolate(mob.height,0.0001,alpha)
mob.become(
GroupRegularPolygon(
mob.get_number_sides(),
height = d_height
)
)
vgroup.arrange(RIGHT,buff=buff)
vgroup.set_width(FRAME_WIDTH-0.2)
shrink_polygon(figures,0)
self.play(LaggedStartMap(GrowFromCenter,figures))
self.wait()
self.play(
UpdateFromAlphaFunc(figures,shrink_polygon),
run_time = 6,
rate_func = there_and_back_with_pause
)
self.wait()
r"""
_ _
__| | |_
/ _` | __|
| (_| | |_
\__,_|\__|
"""
class BouncingBall(ExampleScene):
CONFIG = {
"bouncing_time": 5,
"title_config":{
"extra_str": "\\it\\ - by EulerTour",
"buff": 0.2
}
}
def construct(self):
box = Box()
ball = Ball()
self.play(FadeIn(box))
self.play(FadeIn(ball))
def update_ball(ball,dt):
ball.acceleration = np.array((0, -5, 0))
ball.velocity = ball.velocity + ball.acceleration * dt
ball.shift(ball.velocity * dt) # Bounce off ground and roof
if ball.get_bottom() <= box.bottom*0.96 or \
ball.get_top() >= box.top*0.96:
ball.velocity[1] = -ball.velocity[1]
# Bounce off walls
if ball.get_left_edge() <= box.left_edge or \
ball.get_right_edge() >= box.right_edge:
ball.velocity[0] = -ball.velocity[0]
ball.add_updater(update_ball)
self.add(ball)
self.wait(self.bouncing_time)
# Official code: https://github.com/TheRookieNerd/ManimMiniProjects/blob/master/ThreePhase.py
class ThreePhase(ExampleScene):
CONFIG = {
"radians": 0,
"theta_2": 120 * DEGREES,
"theta_3": 240 * DEGREES,
"displacement": 4 * LEFT,
"amp": 2,
"t_offset": 0,
"rate": 0.05,
"x_min": -4, # xmin and max are to define the bounds of the horizontal graph
"x_max": 9,
"color_1": RED,
"color_2": YELLOW,
"color_3": BLUE,
"axes_config": {
"x_min": 0,
"x_max": 10,
"x_axis_config": {
"stroke_width": 2,
},
"y_min": -2.5,
"y_max": 2.5,
"y_axis_config": {
"tick_frequency": 0.25,
"unit_size": 1.5,
"include_tip": False,
"stroke_width": 2,
},
},
"complex_plane_config": {
"axis_config": {
"unit_size": 2
}
},
"title_config": {
"extra_str": "\\it\\ - by The Rookie Nerd",
"buff": 0.2,
}
}
def construct(self):
phase = self.rate
t_tracker = ValueTracker(0)
t_tracker.add_updater(lambda t, dt: t.increment_value(dt))
get_t = t_tracker.get_value
def get_horizontally_moving_tracing(Vector, color, stroke_width=3, rate=0.25):
path = VMobject()
path.set_stroke(color, stroke_width)
path.start_new_path(np.array([self.displacement[0], Vector.get_end()[1], 0]))
path.Vector = Vector
def update_path(p, dt):
p.shift(rate * dt * 3 * RIGHT)
p.add_smooth_curve_to(np.array([self.displacement[0], p.Vector.get_end()[1], 0]))
path.add_updater(update_path)
return path
colorcircle = interpolate_color(BLACK, GREY, .5)
circle = Circle(radius=2, stroke_width=1, color=colorcircle)
axis = Axes(x_min=-2.5, x_max=10, y_min=-3, y_max=3, stroke_width=2, include_tip=False).shift(self.displacement)
text = TextMobject("Real").move_to(6.5 * RIGHT)
text1 = TextMobject("Img").move_to(4 * LEFT + 3.25 * UP)
phase1 = Vector(2 * RIGHT, color=self.color_1)
phase1.shift(self.displacement)
phase2 = Vector(2 * RIGHT, color=self.color_2)
phase2.shift(self.displacement)
phase3 = Vector(2 * RIGHT, color=self.color_3)
phase3.shift(self.displacement)
subphase1 = DashedLine(phase1.get_end(), np.array([self.displacement[0], phase1.get_end()[1], 0]), color=self.color_1)
subphase2 = DashedLine(phase2.get_end(), np.array([self.displacement[0], phase2.get_end()[1], 0]), color=self.color_2)
subphase3 = DashedLine(phase3.get_end(), np.array([self.displacement[0], phase3.get_end()[1], 0]), color=self.color_3)
circle.move_to(self.displacement)
self.play(Write(axis), Write(text), Write(text1))
self.play(ShowCreation(circle))
phase1.add_updater(lambda t: t.set_angle(get_t()))
phase2.add_updater(lambda t: t.set_angle(get_t() + 120 * DEGREES))
phase3.add_updater(lambda t: t.set_angle(get_t() + 240 * DEGREES))
subphase1.add_updater(lambda t: t.put_start_and_end_on(phase1.get_end(), np.array([self.displacement[0], phase1.get_end()[1], 0])))
subphase2.add_updater(lambda t: t.put_start_and_end_on(phase2.get_end(), np.array([self.displacement[0], phase2.get_end()[1], 0])))
subphase3.add_updater(lambda t: t.put_start_and_end_on(phase3.get_end(), np.array([self.displacement[0], phase3.get_end()[1], 0])))
self.play(
GrowArrow(phase1,)
)
self.play(
ShowCreation(subphase1,)
)
self.add(phase1, subphase1)
self.add(
t_tracker,
)
traced_path1 = get_horizontally_moving_tracing(phase1, self.color_1)
self.add(
traced_path1,
)
self.wait(2 * 2 * PI)
traced_path1.suspend_updating()
t_tracker.suspend_updating()
self.play(
GrowArrow(phase2,)
)
arc1 = Arc(0, phase2.get_angle(), radius=.5, arc_center=self.displacement, color=YELLOW)
label1 = TexMobject("120 ^\\circ").move_to(arc1.get_center() + .3 * UP + .5 * RIGHT).scale(.5)
grp1 = VGroup(arc1, label1)
self.play(ShowCreation(arc1),Write(label1))
self.wait()
self.play(FadeOut(grp1))
self.play(
FadeIn(subphase2, )
)
t_tracker.resume_updating()
traced_path1.resume_updating()
traced_path2 = get_horizontally_moving_tracing(phase2, self.color_2)
self.add(
traced_path2,
)
self.wait(2 * PI)
traced_path2.suspend_updating()
traced_path1.suspend_updating()
t_tracker.suspend_updating()
self.play(
GrowArrow(phase3,)
)
self.play(
FadeIn(subphase3,)
)
arc2 = Arc(0, 240 * DEGREES, radius=.85, arc_center=phase1.points[0], color=BLUE)
label2 = TexMobject("240 ^\\circ").move_to(arc2.get_center() + .4 * DOWN + .5 * RIGHT)
grp2 = VGroup(arc2, label2).scale(.5)
self.play(ShowCreation(arc2), Write(label2), run_time=2)
self.wait()
self.play(FadeOut(grp2))
t_tracker.resume_updating()
traced_path1.resume_updating()
traced_path2.resume_updating()
traced_path3 = get_horizontally_moving_tracing(phase3, self.color_3)
self.add(
traced_path3,
)
self.wait(15)
class Oscillator(ExampleScene):
CONFIG={
"amp":2.3,
"t_offset":0,
"rate":0.05,
"x_min":4,
"x_max":9,
"wait_time":5,
"color_1":RED,
"color_2":GREEN,
}
def construct(self):
rate_no_updater=self.rate
def update_curve(c, dt):
other_mob = FunctionGraph(
lambda x: self.amp*np.sin((x - (self.t_offset + self.rate)+rate_no_updater)),
x_min=0,x_max=self.x_max
).shift(LEFT*self.x_min)
c.become(other_mob)
self.t_offset += self.rate
c = FunctionGraph(
lambda x: self.amp*np.sin((x- (self.t_offset + self.rate)+rate_no_updater)),
x_min=0,x_max=self.x_max
).shift(LEFT*self.x_min)
point=Dot()
point.move_to(c.points[0])
point_center=Dot()
circle=Circle(radius=self.amp)\
.shift(RIGHT*point.get_center()[0])
point_center.move_to(circle.get_center())
la=Line(
circle.get_center(),
circle.get_center()+RIGHT*self.amp/2,
color=self.color_1
)
lb=DashedLine(
circle.get_center(),
circle.get_center()+RIGHT*self.amp/2,
color=self.color_2
).rotate(PI)
lc=Line(
circle.get_center(),
circle.get_center()+LEFT*self.amp/2,
color=self.color_1
)
ld=DashedLine(
circle.get_center(),
circle.get_center()+LEFT*self.amp/2,
color=self.color_2
).rotate(PI)
def update_la(la,dt):
a=point.get_center()[1]
b=la.get_length()
alpha_la=4*np.arctan((2*b-np.sqrt(4*(b**2)-a**2))/(a+0.00001))
beta_la=PI/2-alpha_la/2
ap=PI-alpha_la/2
bp=PI/2-beta_la
la.set_angle(bp)
def update_lc(lc,dt):
a=point.get_center()[1]
b=lc.get_length()
alpha_lc=4*np.arctan((2*b-np.sqrt(4*(b**2)-a**2))/(a+0.00001))
beta_lc=PI/2-alpha_lc/2
ap=PI-alpha_lc/2
bp=PI/2-beta_lc
lc.set_angle(bp+2*beta_lc)
self.play( ShowCreation(c),
ShowCreation(point),
ShowCreation(circle),
ShowCreation(la),
ShowCreation(lb),
ShowCreation(lc),
ShowCreation(ld),
)
self.wait()
la.add_updater(update_la)
lc.add_updater(update_lc)
point.add_updater(lambda m: m.move_to(c.points[0]))
lb.add_updater(lambda m: m.put_start_and_end_on(la.points[-1],point.get_center()))
ld.add_updater(lambda m: m.put_start_and_end_on(lc.points[-1],point.get_center()))
c.add_updater(update_curve)
self.add(c,point,la,lb,lc,ld)
self.wait(self.wait_time)
c.remove_updater(update_curve)
self.wait()
|
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/dt_parameter.py | from manimlib.imports import *
class OrderMobjects(Scene):
def construct(self):
mobs = VGroup(*[mob.set_height(4) for mob in [Square(),Circle(),Triangle()]])
mobs.set_fill(opacity=1)
for i in range(1,3):
mobs[i].next_to(mobs[i-1].get_left(),RIGHT,buff=1)
mobs.move_to(ORIGIN)
self.add(*mobs)
self.wait()
# Array
print(self.mobjects) # [Square, Circle, Rectangle]
for mob in self.mobjects:
name = mob.__class__.__name__
print(f"Remove {name}")
self.remove(mob)
self.wait()
self.wait()
"""
CONCLUSION
==========
Every time we use self.add(mob) we are
-------------
adding the objects to the self.mobjects
-------------
array, depending on the order in which
they appear in the array, they will also
be on the screen.
It is important that when using the update
functions you are aware of the order of your
objects in self.mobjects, so that the animation
-------------
is displayed correctly.
"""
class OrderMobjects2(Scene):
def construct(self):
mobs = VGroup(*[mob.set_height(4) for mob in [Square(),Circle(),Triangle()]])
mobs.set_fill(opacity=1)
for i in range(1,3):
mobs[i].next_to(mobs[i-1].get_left(),RIGHT,buff=1)
mobs.move_to(ORIGIN)
self.add(*mobs)
self.wait()
# Random reorganization
random.shuffle(self.mobjects)
self.wait()
# dt = 1 / fps
class AbstractDtScene(Scene):
def setup(self):
path = Line(LEFT*6, RIGHT*6)
measure = VGroup()
for i in range(61):
proportion = 1 / 60
line = Line(DOWN*0.3, UP*0.3, stroke_width=2)
line.move_to(path.point_from_proportion(proportion*i))
measure.add(line)
if i in [15,30,60]:
arrow = Arrow(UP,DOWN)
arrow.next_to(line,UP,buff=0.1)
text = Text(f"{i}",font="Arial",stroke_width=0)
text.set_height(0.5)
text.next_to(arrow,UP)
self.add(arrow,text)
measure.add(path)
# Measure lines
self.measure = measure
self.measure.start = path.point_from_proportion(0)
# Distance between every line
self.dot_distance = path.point_from_proportion(1/60) - path.point_from_proportion(0)
# dot at start
self.dot = Dot(self.measure.start,color=RED)
self.add(self.measure)
class DtExample1Fail(AbstractDtScene):
def construct(self):
def update_dot(mob):
mob.shift(RIGHT * self.dot_distance)
dot = self.dot
dot.add_updater(update_dot)
self.add(dot)
self.wait()
dot.clear_updaters()
self.wait()
class DtExample1(AbstractDtScene):
def construct(self):
# Calculate dt:
dt_calculate = 1 / self.camera.frame_rate
print(f"dt calculate = {dt_calculate}")
print("---------------------------------")
def update_dot(mob,dt):
print(f"n: {mob.counter} - dt : {dt}")
mob.shift(RIGHT * self.dot_distance)
mob.counter += 1
dot = self.dot
dot.counter = 0
dot.add_updater(update_dot)
self.add(dot)
self.wait()
dot.clear_updaters()
self.wait()
class DtExample2(AbstractDtScene):
CONFIG = {
"velocity_factor": 15
}
def construct(self):
# Calculate dt:
self.dt_calculate = 1 / self.camera.frame_rate
print(f"dt calculate = {self.dt_calculate}")
print("---------------------------------")
def update_dot(mob,dt):
if dt == 0 and mob.counter==0:
rate = self.velocity_factor * self.dt_calculate
mob.counter += 1
else:
rate = dt * self.velocity_factor
if dt > 0:
mob.counter=0
print(f"n: {mob.counter} - dt : {dt}")
mob.shift(RIGHT * rate * self.dot_distance)
mob.counter += 1
dot = self.dot
dot.counter = 0
dot.add_updater(update_dot)
self.add(dot)
self.wait(2)
dot.clear_updaters()
self.wait()
def fix_update(mob,dt,velocity_factor,dt_calculate):
if dt == 0 and mob.counter == 0:
rate = velocity_factor * dt_calculate
mob.counter += 1
else:
rate = dt * velocity_factor
if dt > 0:
mob.counter = 0
return rate
class DtExample3(AbstractDtScene):
def construct(self):
# Calculate dt:
self.dt_calculate = 1 / self.camera.frame_rate
print(f"dt calculate = {self.dt_calculate}")
print("---------------------------------")
def update_dot(mob,dt):
rate = fix_update(mob,dt,15,self.dt_calculate)
print(f"n: {mob.counter} - dt : {dt}")
mob.shift(RIGHT * rate * self.dot_distance)
mob.counter += 1
dot = self.dot
dot.counter = 0
dot.add_updater(update_dot)
self.add(dot)
self.wait(2)
dot.clear_updaters()
self.wait()
class UpdateFunctionWithDt1Fail(Scene):
CONFIG={
"amp": 2.3,
"t_offset": 0,
"rate": TAU/4,
"sine_graph_config":{
"x_min": -TAU/2,
"x_max": TAU/2,
"color": RED,
},
}
def construct(self):
def update_curve(c, dt):
rate = self.rate * dt
c.become(self.get_sin_graph(self.t_offset + rate))
# Every frame, the t_offset increase rate / fps
self.t_offset += rate
c = self.get_sin_graph(0)
self.play(ShowCreation(c))
# PRINTS
print(f"fps: {self.camera.frame_rate}")
print(f"dt: {1 / self.camera.frame_rate}")
print(f"rate: {self.rate / self.camera.frame_rate}")
print(f"cy_start: {c.points[0][1]}")
print(f"cy_end: {c.points[-1][1]}")
print(f"t_offset: {self.t_offset}\n")
c.add_updater(update_curve)
self.add(c)
# The animation begins
self.wait(4)
c.remove_updater(update_curve)
self.wait()
print(f"cy_start: {c.points[0][1]}")
print(f"cy_end: {c.points[-1][1]}")
print(f"t_offset: {self.t_offset}\n")
def get_sin_graph(self, dx):
c = FunctionGraph(
lambda x: self.amp * np.sin(x - dx),
**self.sine_graph_config
)
return c
class UpdateFunctionWithDt1(Scene):
CONFIG={
"amp": 2.3,
"t_offset": 0,
"velocity_factor": TAU/4,
"sine_graph_config":{
"x_min": -TAU/2,
"x_max": TAU/2,
"color": RED,
},
}
def construct(self):
def update_curve(c, dt):
rate = fix_update(c,dt,self.velocity_factor,self.dt_calculate)
c.become(self.get_sin_graph(self.t_offset + rate))
self.t_offset += rate
c = self.get_sin_graph(0)
c.counter = 0
self.dt_calculate = 1 / self.camera.frame_rate
self.play(ShowCreation(c))
# PRINTS
print(f"fps: {self.camera.frame_rate}")
print(f"dt: {self.dt_calculate}")
print(f"rate: {self.velocity_factor / self.camera.frame_rate}")
print(f"cy_start: {c.points[0][1]}")
print(f"cy_end: {c.points[-1][1]}")
print(f"t_offset: {self.t_offset}\n")
c.add_updater(update_curve)
self.add(c)
# The animation begins
self.wait(4)
c.remove_updater(update_curve)
self.wait()
print(f"cy_start: {c.points[0][1]}")
print(f"cy_end: {c.points[-1][1]}")
print(f"t_offset: {self.t_offset}\n")
def get_sin_graph(self, dx):
c = FunctionGraph(
lambda x: self.amp * np.sin(x - dx),
**self.sine_graph_config
)
return c
class UpdateFunctionWithDt2(Scene):
def construct(self):
self.t_offset = 0
orbit = Ellipse(color=GREEN).scale(2.5)
planet = Dot()
text = TextMobject("Update function")
planet.move_to(orbit.point_from_proportion(0))
def update_planet(mob,dt):
rate = dt * 0.3
mob.move_to(orbit.point_from_proportion((self.t_offset + rate)%1))
self.t_offset += rate
planet.add_updater(update_planet)
self.add(orbit,planet)
self.wait(4)
self.play(Write(text))
self.wait(4)
planet.clear_updaters()
self.wait(2)
self.play(FadeOut(text))
self.wait()
|
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/value_tracker_examples.py | #from manimlib.imports import *
#from big_ol_pile_of_manim_imports import *
class FunctionTracker(Scene):
def construct(self):
# f(x) = x**2
fx = lambda x: x.get_value()**2
# ValueTrackers definition
x_value = ValueTracker(0)
fx_value = ValueTracker(fx(x_value))
# DecimalNumber definition
x_tex = DecimalNumber(x_value.get_value()).add_updater(lambda v: v.set_value(x_value.get_value()))
fx_tex = DecimalNumber(fx_value.get_value()).add_updater(lambda v: v.set_value(fx(x_value)))
# TeX labels definition
x_label = TexMobject("x = ")
fx_label = TexMobject("x^2 = ")
# Grouping of labels and numbers
group = VGroup(x_tex,fx_tex,x_label,fx_label).scale(2.6)
VGroup(x_tex, fx_tex).arrange_submobjects(DOWN,buff=3)
# Align labels and numbers
x_label.next_to(x_tex,LEFT, buff=0.7,aligned_edge=x_label.get_bottom())
fx_label.next_to(fx_tex,LEFT, buff=0.7,aligned_edge=fx_label.get_bottom())
self.add(group.move_to(ORIGIN))
self.wait(3)
self.play(
x_value.set_value,30,
rate_func=linear,
run_time=10
)
self.wait()
self.play(
x_value.set_value,0,
rate_func=linear,
run_time=10
)
self.wait(3)
class FunctionTrackerWithNumberLine(Scene):
def construct(self):
# f(x) = x**2
fx = lambda x: x.get_value()**2
# ValueTrackers definition
x_value = ValueTracker(0)
fx_value = ValueTracker(fx(x_value))
# DecimalNumber definition
x_tex = DecimalNumber(x_value.get_value()).add_updater(lambda v: v.set_value(x_value.get_value()))
fx_tex = DecimalNumber(fx_value.get_value()).add_updater(lambda v: v.set_value(fx(x_value)))
# TeX labels definition
x_label = TexMobject("x = ")
fx_label = TexMobject("x^2 = ")
# Grouping of labels and numbers
group = VGroup(x_tex,fx_tex,x_label,fx_label).scale(2)
# Set the labels position
x_label.next_to(x_tex,LEFT, buff=0.7,aligned_edge=x_label.get_bottom())
fx_label.next_to(fx_tex,LEFT, buff=0.7,aligned_edge=fx_label.get_bottom())
# Grouping numbers and labels
x_group = VGroup(x_label,x_tex)
fx_group = VGroup(fx_label,fx_tex)
# Align labels and numbers
VGroup(x_group, fx_group).arrange_submobjects(RIGHT,buff=2,aligned_edge=DOWN).to_edge(UP)
# Get NumberLine,Arrow and label from x
x_number_line_group = self.get_number_line_group(
"x",30,0.2,step_label=10,v_tracker=x_value,tick_frequency=2
)
x_number_line_group.to_edge(LEFT,buff=1)
# Get NumberLine,Arrow and label from f(x)
fx_number_line_group = self.get_number_line_group(
"x^2",900,0.012,step_label=100,v_tracker=fx_tex,
tick_frequency=50
)
fx_number_line_group.next_to(x_number_line_group,DOWN,buff=1).to_edge(LEFT,buff=1)
self.add(
x_number_line_group,
fx_number_line_group,
group
)
self.wait()
self.play(
x_value.set_value,30,
rate_func=linear,
run_time=10
)
self.wait()
self.play(
x_value.set_value,0,
rate_func=linear,
run_time=10
)
self.wait(3)
def get_numer_labels_to_numberline(self,number_line,x_max=None,x_min=0,buff=0.2,step_label=1,**tex_kwargs):
# This method return the labels of the NumberLine
labels = VGroup()
x_max = number_line.x_max
for x in range(x_min,x_max+1,step_label):
x_label = TexMobject(f"{x}",**tex_kwargs)
# See manimlib/mobject/number_line.py CONFIG dictionary
x_label.next_to(number_line.number_to_point(x),DOWN,buff=buff)
labels.add(x_label)
return labels
def get_number_line_group(self,label,x_max,unit_size,v_tracker,step_label=1,**number_line_config):
# Set the Label (x,or x**2)
number_label = TexMobject(label)
# Set the arrow
arrow = Arrow(UP,DOWN,buff=0).set_height(0.5)
# Set the number_line
number_line = NumberLine(
x_min=0,
x_max=x_max,
unit_size=unit_size,
numbers_with_elongated_ticks=[],
**number_line_config
)
# Get the labels from number_line
labels = self.get_numer_labels_to_numberline(number_line,step_label=step_label,height=0.2)
# Set the arrow position
arrow.next_to(number_line.number_to_point(0),UP,buff=0)
# Grouping arrow and number_label
label = VGroup(arrow,number_label)
# Set the position of number_label
number_label.next_to(arrow,UP,buff=0.1)
# Grouping all elements
numer_group = VGroup(label,number_line,labels)
# Set the updater to the arrow and number_label
label.add_updater(lambda mob: mob.next_to(number_line.number_to_point(v_tracker.get_value()),UP,buff=0))
return numer_group
#HSL color, see https://pypi.org/project/colour/
def HSL(hue,saturation=1,lightness=0.5):
return Color(hsl=(hue,saturation,lightness))
# This function is come and go, but linear
def double_linear(t):
if t < 0.5:
return linear(t*2)
else:
return linear(1-(t-0.5)*2)
class ValueTrackerWithColor(Scene):
def construct(self):
gradient_rectangle = Rectangle(
width=FRAME_WIDTH-1,
height=1,
fill_opacity=1,
# Gradient direction
sheen_direction=RIGHT,
stroke_width=0
)
square = Square(fill_opacity=1)
square.to_edge(UP,buff=1)
gradient_rectangle.to_edge(DOWN,buff=1)
gradient_rectangle.set_color(color=self.get_hsl_set_colors())
color_tracker = ValueTracker(0)
color_label = Integer(color_tracker.get_value(),unit="^\\circ")
color_label.add_updater(lambda v: v.set_value(color_tracker.get_value()).next_to(square,UP))
square.add_updater(lambda s: s.set_color(HSL(color_tracker.get_value()/360)))
line_color = Line(
gradient_rectangle.get_corner(UL),
gradient_rectangle.get_corner(UR)
)
arrow = Arrow(LEFT,RIGHT)
arrow.add_updater(lambda a: a.put_start_and_end_on(square.get_bottom()+DOWN*0.3,line_color.point_from_proportion(color_tracker.get_value()/360)))
self.add(gradient_rectangle,square,color_label,arrow)
self.wait(3)
self.play(
color_tracker.set_value,360,
rate_func=double_linear,
run_time=20,
)
self.wait(3)
def get_hsl_set_colors(self,saturation=1,lightness=0.5):
return [*[HSL(i/360,saturation,lightness) for i in range(360)]]
class MmodNTracker(Scene):
CONFIG = {
"number_of_lines": 400,
"gradient_colors":[RED,YELLOW,BLUE],
"end_value":100,
"total_time":180,
}
def construct(self):
circle = Circle().set_height(FRAME_HEIGHT*0.9)
mod_tracker = ValueTracker(0)
lines = self.get_m_mod_n_objects(circle,mod_tracker.get_value())
lines.add_updater(
lambda mob: mob.become(
self.get_m_mod_n_objects(circle,mod_tracker.get_value())
)
)
self.add(circle,lines)
self.wait(3)
self.play(
mod_tracker.set_value,self.end_value,
rate_func=linear,
run_time=self.total_time
)
self.wait(3)
def get_m_mod_n_objects(self,circle,x,y=None):
if y==None:
y = self.number_of_lines
lines = VGroup()
for i in range(y):
start_point = circle.point_from_proportion((i%y)/y)
end_point = circle.point_from_proportion(((i*x)%y)/y)
line = Line(start_point,end_point).set_stroke(width=1)
lines.add(line)
lines.set_color_by_gradient(*self.gradient_colors)
return lines
|
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/update_successions.py | from big_ol_pile_of_manim_imports import *
class AddUpdaterFail(Scene):
def construct(self):
dot = Dot()
text = TextMobject("Label")\
.next_to(dot,RIGHT,buff=SMALL_BUFF)
self.add(dot,text)
self.play(dot.shift,UP*2)
self.wait()
class AddUpdater1(Scene):
def construct(self):
dot = Dot()
text = TextMobject("Label")\
.next_to(dot,RIGHT,buff=SMALL_BUFF)
self.add(dot,text)
# Update function
def update_text(obj):
obj.next_to(dot,RIGHT,buff=SMALL_BUFF)
# Add update function to the objects
text.add_updater(update_text)
# Add the object again
self.add(text)
self.play(dot.shift,UP*2)
# Remove update function
text.remove_updater(update_text)
self.wait()
class AddUpdater2(Scene):
def construct(self):
dot = Dot()
text = TextMobject("Label")\
.next_to(dot,RIGHT,buff=SMALL_BUFF)
self.add(dot,text)
# Add update function to the objects
text.add_updater(lambda m: m.next_to(dot,RIGHT,buff=SMALL_BUFF))
# Add the object again
self.add(text)
self.play(dot.shift,UP*2)
# Remove update function
text.clear_updaters()
self.wait()
class AddUpdater3(Scene):
def construct(self):
dot = Dot()
text = TextMobject("Label")\
.next_to(dot,RIGHT,buff=SMALL_BUFF)
self.add(dot,text)
def update_text(obj):
obj.next_to(dot,RIGHT,buff=SMALL_BUFF)
# Only works in play
self.play(
dot.shift,UP*2,
UpdateFromFunc(text,update_text)
)
self.wait()
class UpdateNumber(Scene):
def construct(self):
number_line = NumberLine(x_min=-1,x_max=1)
triangle = RegularPolygon(3,start_angle=-PI/2)\
.scale(0.2)\
.next_to(number_line.get_left(),UP,buff=SMALL_BUFF)
decimal = DecimalNumber(
0,
num_decimal_places=3,
include_sign=True,
unit="\\rm cm", # Change this with None
)
decimal.add_updater(lambda d: d.next_to(triangle, UP*0.1))
decimal.add_updater(lambda d: d.set_value(triangle.get_center()[0]))
# You can get the value of decimal with: .get_value()
self.add(number_line,triangle,decimal)
self.play(
triangle.shift,RIGHT*2,
rate_func=there_and_back, # Change this with: linear,smooth
run_time=5
)
self.wait()
class UpdateValueTracker1(Scene):
def construct(self):
theta = ValueTracker(PI/2)
line_1= Line(ORIGIN,RIGHT*3,color=RED)
line_2= Line(ORIGIN,RIGHT*3,color=GREEN)
line_2.rotate(theta.get_value(),about_point=ORIGIN)
line_2.add_updater(
lambda m: m.set_angle(
theta.get_value()
)
)
self.add(line_1,line_2)
self.play(theta.increment_value,PI/2)
self.wait()
class UpdateValueTracker2(Scene):
CONFIG={
"line_1_color":ORANGE,
"line_2_color":PINK,
"lines_size":3.5,
"theta":PI/2,
"increment_theta":PI/2,
"final_theta":PI,
"radius":0.7,
"radius_color":YELLOW,
}
def construct(self):
# Set objets
theta = ValueTracker(self.theta)
line_1= Line(ORIGIN,RIGHT*self.lines_size,color=self.line_1_color)
line_2= Line(ORIGIN,RIGHT*self.lines_size,color=self.line_2_color)
line_2.rotate(theta.get_value(),about_point=ORIGIN)
line_2.add_updater(
lambda m: m.set_angle(
theta.get_value()
)
)
angle= Arc(
radius=self.radius,
start_angle=line_1.get_angle(),
angle =line_2.get_angle(),
color=self.radius_color
)
# Show the objects
self.play(*[
ShowCreation(obj)for obj in [line_1,line_2,angle]
])
# Set update function to angle
angle.add_updater(
lambda m: m.become(
Arc(
radius=self.radius,
start_angle=line_1.get_angle(),
angle =line_2.get_angle(),
color=self.radius_color
)
)
)
# Remember to add the objects again to the screen
# when you add the add_updater method.
self.add(angle)
self.play(theta.increment_value,self.increment_theta)
# self.play(theta.set_value,self.final_theta)
self.wait()
# dt = 1 / fps
class UpdateFunctionWithDt1(Scene):
CONFIG={
"amp": 2.3,
"t_offset": 0,
"rate": TAU/4,
"sine_graph_config":{
"x_min": -TAU/2,
"x_max": TAU/2,
"color": RED,
},
"wait_time":15,
}
def construct(self):
def update_curve(c, dt):
rate = self.rate * dt
c.become(self.get_sin_graph(self.t_offset + rate))
# Every frame, the t_offset increase rate / fps
self.t_offset += rate
c = self.get_sin_graph(0)
self.play(ShowCreation(c))
print(f"fps: {self.camera.frame_rate}")
print(f"dt: {1 / self.camera.frame_rate}")
print(f"rate: {self.rate / self.camera.frame_rate}")
print(f"cy_start: {c.points[0][1]}")
print(f"cy_end: {c.points[-1][1]}")
print(f"t_offset: {self.t_offset}\n")
c.add_updater(update_curve)
self.add(c)
# The animation begins
self.wait(4)
c.remove_updater(update_curve)
self.wait()
print(f"cy_start: {c.points[0][1]}")
print(f"cy_end: {c.points[-1][1]}")
print(f"t_offset: {self.t_offset}\n")
def get_sin_graph(self, dx):
c = FunctionGraph(
lambda x: self.amp * np.sin(x - dx),
**self.sine_graph_config
)
return c
class UpdateFunctionWithDt2(Scene):
def construct(self):
#Se objects
self.t_offset=0
orbit=Ellipse(color=GREEN).scale(2.5)
planet=Dot()
text=TextMobject("Update function")
planet.move_to(orbit.point_from_proportion(0))
def update_planet(mob,dt):
rate=dt*0.3
mob.move_to(orbit.point_from_proportion((self.t_offset + rate)%1))
self.t_offset += rate
planet.add_updater(update_planet)
self.add(orbit,planet)
self.wait(4)
self.play(Write(text))
self.wait(4)
planet.clear_updaters()
self.wait(2)
self.play(FadeOut(text))
self.wait()
class UpdateCurve(Scene):
def construct(self):
def f(dx=1):
return FunctionGraph(lambda x: 2*np.exp(-2 * (x - dx) ** 2))
c = f()
axes=Axes(y_min=-3, y_max=3)
def update_curve(c, alpha):
dx = interpolate(1, 4, alpha)
c_c = f(dx)
c.become(c_c)
self.play(ShowCreation(axes), ShowCreation(c))
self.wait()
self.play(UpdateFromAlphaFunc(c,update_curve),rate_func=there_and_back,run_time=4)
self.wait()
class InterpolateColorScene(Scene):
def construct(self):
shape = Square(fill_opacity=1).scale(2)
shape.set_color(RED)
def update_color(mob,alpha):
dcolor = interpolate(0,mob.alpha_color,alpha)
mob.set_color(self.interpolate_color_mob(mob.initial_state,shape.new_color,dcolor))
self.add(shape)
self.change_init_values(shape,TEAL,0.5)
self.play(UpdateFromAlphaFunc(shape,update_color))
self.change_init_values(shape,PINK,0.9)
self.play(UpdateFromAlphaFunc(shape,update_color))
self.wait()
def interpolate_color_mob(self,mob,color,alpha):
return interpolate_color(mob.get_color(),color,alpha)
def change_init_values(self,mob,color,alpha):
mob.initial_state = mob.copy()
mob.new_color = color
mob.alpha_color = alpha
class SuccessionExample1Fail(Scene):
def construct(self):
number_line=NumberLine(x_min=-2,x_max=2)
text=TextMobject("Text")\
.next_to(number_line,DOWN)
dashed_line=DashedLine(
number_line.get_left(),
number_line.get_right(),
color=YELLOW,
).set_stroke(width=11)
self.add(number_line)
self.wait(0.3)
self.play(
ShowCreationThenDestruction(
dashed_line,
submobject_mode="lagged_start"
),
run_time=5
)
self.play(Write(text))
self.wait()
class SuccessionExample1(Scene):
def construct(self):
number_line=NumberLine(x_min=-2,x_max=2)
text=TextMobject("Text")\
.next_to(number_line,DOWN)
dashed_line=DashedLine(
number_line.get_left(),
number_line.get_right(),
color=YELLOW,
).set_stroke(width=11)
self.add(number_line)
self.wait(0.3)
self.play(
ShowCreationThenDestruction(dashed_line,submobject_mode="lagged_start",run_time=5),
Succession(Animation, Mobject(), {"run_time" : 2.1},
Write,text)
)
self.wait()
class SuccessionExample2(Scene):
def construct(self):
number_line=NumberLine(x_min=-2,x_max=2)
triangle=RegularPolygon(3,start_angle=-PI/2)\
.scale(0.2)\
.next_to(number_line.get_left(),UP,buff=SMALL_BUFF)
text_1=TextMobject("1")\
.next_to(number_line.get_tick(-1),DOWN)
text_2=TextMobject("2")\
.next_to(number_line.get_tick(0),DOWN)
text_3=TextMobject("3")\
.next_to(number_line.get_tick(1),DOWN)
text_4=TextMobject("4")\
.next_to(number_line.get_tick(2),DOWN)
self.add(number_line)
self.play(ShowCreation(triangle))
self.wait(0.3)
self.play(
ApplyMethod(triangle.shift,RIGHT*4,rate_func=linear,run_time=4),
Succession(Animation, Mobject(), {"run_time" : 1},
Write,text_1),
Succession(Animation, Mobject(), {"run_time" : 2},
Write,text_2),
Succession(Animation, Mobject(), {"run_time" : 3},
Write,text_3),
Succession(Animation, Mobject(), {"run_time" : 4},
Write,text_4)
)
self.wait()
class SuccessionExample2Compact(Scene):
def construct(self):
number_line=NumberLine(x_min=-2,x_max=2)
triangle=RegularPolygon(3,start_angle=-PI/2)\
.scale(0.2)\
.next_to(number_line.get_left(),UP,buff=SMALL_BUFF)
numbers=VGroup(
*[TextMobject("%s"%i)\
.next_to(number_line.get_tick(i-2),DOWN) for i in range(1,5)]
)
self.add(number_line)
self.play(ShowCreation(triangle))
self.wait(0.3)
self.play(
ApplyMethod(triangle.shift,RIGHT*4,rate_func=linear,run_time=4),
*[Succession(Animation, Mobject(), {"run_time" : i+1},
Write,numbers[i])for i in range(4)],
)
self.wait()
class SuccessionExample4Fail(Scene):
def construct(self):
number_line=NumberLine(x_min=-2,x_max=2)
text_1=TextMobject("Theorem of")\
.next_to(number_line,DOWN)
text_2=TextMobject("Beethoven")\
.next_to(number_line,DOWN)
dashed_line=DashedLine(
number_line.get_left(),
number_line.get_right(),
color=YELLOW,
).set_stroke(width=11)
self.add(number_line)
self.play(
ShowCreationThenDestruction(dashed_line,submobject_mode="lagged_start",run_time=5),
Succession(Animation,text_1, {"run_time" : 2},
ReplacementTransform,text_1,text_2),
)
self.wait()
|
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/update_examples_1.py | #from big_ol_pile_of_manim_imports import *
#from manimlib.imports import *
class TangentVector(Scene):
def construct(self):
figure = Ellipse(color=RED).scale(2)
dot = Dot()
alpha = ValueTracker(0)
vector = self.get_tangent_vector(alpha.get_value(),figure,scale=2)
dot.add_updater(lambda m: m.move_to(vector.get_start()))
self.play(
ShowCreation(figure),
GrowFromCenter(dot),
GrowArrow(vector)
)
vector.add_updater(
lambda m: m.become(
self.get_tangent_vector(alpha.get_value()%1,figure,scale=2)
)
)
self.add(vector,dot)
self.play(alpha.increment_value, 2, run_time=8, rate_func=linear)
self.wait()
def get_tangent_vector(self, proportion, curve, dx=0.001, scale=1):
coord_i = curve.point_from_proportion(proportion)
coord_f = curve.point_from_proportion(proportion + dx)
reference_line = Line(coord_i,coord_f)
unit_vector = reference_line.get_unit_vector() * scale
vector = Arrow(coord_i, coord_i + unit_vector, buff=0)
return vector
# TEST - Make a line tangent to the curve
class D0t(Dot):
CONFIG = {
"fill_color": BLUE,
"fill_opacity": 1,
"stroke_color": RED,
"stroke_width": 1.7,
}
class ParabolaCreation(GraphScene):
CONFIG = {
"x_min": -6,
"x_max": 6,
"x_axis_width": 12,
"y_axis_height": 7,
"graph_origin": 3.5 * DOWN,
"y_min": 0,
"y_max": 7,
}
def construct(self):
self.setup_axes()
self.x_axis.remove(self.x_axis[1])
self.y_axis.remove(self.y_axis[1])
self.play(Write(self.axes))
h = 0; k = 1; p = 1
parabola_function = lambda x: ((x-h)**2)/(4*p) + k
parabola_right = self.get_graph(
parabola_function,
x_min = 0,
x_max = 5,
color = BLUE
)
parabola_left = self.get_graph(
parabola_function,
x_min = 0,
x_max = -5,
color = BLUE
)
anim_kwargs = {"run_time":5,"rate_func":linear}
self.move_dot_path(parabola_right,anim_kwargs)
self.move_dot_path(parabola_left,anim_kwargs)
def move_dot_path(self,parabola,anim_kwargs):
h = 0; k = 1; p = 1
parabola_copy = parabola.copy()
focus = D0t(self.coords_to_point(0,2))
dot_guide = D0t(self.coords_to_point(h,p))
dot_d = D0t(self.coords_to_point(0,0))
circle = Circle(radius=1).move_to(self.coords_to_point(h,p))
line_f_d = DashedLine(focus.get_center(),dot_guide.get_center())
line_d_d = DashedLine(dot_guide.get_center(),dot_d.get_center())
group = VGroup(circle,line_f_d,line_d_d,dot_d)
def update_group(group):
c,f_d,d_d,d = group
d.move_to(self.coords_to_point(dot_guide.get_center()[0],0))
radius = get_norm(focus.get_center() - dot_guide.get_center())
new_c = Circle(radius = radius)
new_c.move_to(dot_guide)
c.become(new_c)
f_d.become(DashedLine(focus.get_center(),dot_guide.get_center()))
d_d.become(DashedLine(dot_guide.get_center(),dot_d.get_center()))
group.add_updater(update_group)
self.play(
FadeInFromLarge(circle,scale_factor=2),
*[GrowFromCenter(mob) for mob in [line_f_d,line_d_d,dot_guide,dot_d,focus]],
)
self.add(
group,
focus,
dot_guide,
)
self.wait()
self.add(parabola)
self.bring_to_back(parabola)
self.bring_to_back(self.axes)
self.play(
MoveAlongPath(dot_guide,parabola_copy),
ShowCreation(parabola),
**anim_kwargs
)
group.clear_updaters()
self.wait(1.2)
self.play(FadeOut(VGroup(group,dot_guide,focus)))
class EpicycloidScene(Scene):
def construct(self):
radius1 = 2.4
radius2 = radius1/3
self.epy(radius1,radius2)
def epy(self,r1,r2):
# Manim circle
c1 = Circle(radius=r1,color=BLUE)
# Small circle
c2 = Circle(radius=r2,color=PURPLE).rotate(PI)
c2.next_to(c1,RIGHT,buff=0)
c2.start = c2.copy()
# Dot
# .points[0] return the start path coordinate
# .points[-1] return the end path coordinate
dot = Dot(c2.points[0],color=RED)
# Line
line = Line(c2.get_center(),dot.get_center()).set_stroke(BLACK,2.5)
# Path
path = VMobject(color=RED)
# Path can't have the same coord twice, so we have to dummy point
path.set_points_as_corners([dot.get_center(),dot.get_center()+UP*0.001])
# Path group
path_group = VGroup(line,dot,path)
# Alpha, from 0 to 1:
alpha = ValueTracker(0)
self.play(ShowCreation(line),ShowCreation(c1),ShowCreation(c2),GrowFromCenter(dot))
# update function of path_group
def update_group(group):
l,mob,previus_path = group
mob.move_to(c2.points[0])
old_path = path.copy()
# See manimlib/mobject/types/vectorized_mobject.py
old_path.append_vectorized_mobject(Line(old_path.points[-1],mob.get_center()))
old_path.make_smooth()
l.put_start_and_end_on(c2.get_center(),mob.get_center())
path.become(old_path)
# update function of small circle
def update_c2(c):
c.become(c.start)
c.rotate(TAU*alpha.get_value(),about_point=c1.get_center())
c.rotate(TAU*(r1/r2)*alpha.get_value(),about_point=c.get_center())
path_group.add_updater(update_group)
c2.add_updater(update_c2)
self.add(c2,path_group)
self.play(
alpha.set_value,1,
rate_func=linear,
run_time=6
)
self.wait(2)
c2.clear_updaters()
path_group.clear_updaters()
self.play(FadeOut(VGroup(c1,c2,path_group)))
# The calculations were based on the book of:
# Design Of Machinery - Robert Norton 4th Edition - Chapter 4 - Position Analysis
class SliderCrankMechanism(Scene):
CONFIG={
"a":2,
"b":-6.5,
"c":1.7,
"theta_in":70,
"theta_end":70-2.5*360,
"slider_color":RED,
"crank_color":BLUE,
"piston_color":GREEN,
"anchor_color":TEAL,
"line_stroke":10
}
def construct(self):
O2 = Dot().shift(LEFT*4+DOWN*1.5)
a = self.a
b = self.b
c = self.c
theta_in = self.theta_in
theta_end = self.theta_end
slider_color = self.slider_color
piston_color = self.piston_color
radio = 0.08
base_down=Line(LEFT*4,RIGHT*4)
base_down.shift(0.1*DOWN)
anchor_point = Dot(O2.get_center(),radius=radio)
semi_circle_anchor = Dot(O2.get_center(),radius=0.2,color=self.anchor_color)
anchor_rect = Square(side_length=0.4).set_stroke(None,0).set_fill(self.anchor_color,1).move_to(O2.get_center()+DOWN*semi_circle_anchor.get_width()/2)
anchor_group = VGroup(semi_circle_anchor,anchor_rect)
slider = self.position_slider(O2.get_center(),theta_in,a,slider_color)
theta_3 = np.arcsin((a*np.sin(theta_in*DEGREES)-c)/b)*180/PI
piston = self.position_piston(O2.get_center(),theta_in,theta_3,a,b,c,piston_color)
crank = Line(slider.get_end(),piston.get_center()).set_stroke(self.crank_color,self.line_stroke)
point_bm = Dot(slider.get_end(),radius=radio)
point_mp = Dot(crank.get_end(),radius=radio)
grupo = VGroup(slider,piston,crank,point_mp,point_bm)
base_down.next_to(piston,DOWN,buff=0).shift(LEFT)
self.play(*[FadeIn(objeto)for objeto in [anchor_group,base_down]],
ShowCreation(slider),DrawBorderThenFill(piston),ShowCreation(crank),
GrowFromCenter(point_mp),GrowFromCenter(point_bm),GrowFromCenter(anchor_point),
)
self.add_foreground_mobject(anchor_point)
alpha = ValueTracker(self.theta_in)
def update(grupo):
dx = alpha.get_value()
slider = self.position_slider(O2.get_center(),dx,self.a,self.slider_color)
theta_3 = np.arcsin(np.sign(dx)*((self.a*np.sin(dx*DEGREES)-self.c)/self.b))
piston = self.position_piston(O2.get_center(),dx,theta_3*180/PI,self.a,self.b,self.c,self.piston_color)
crank = Line(slider.get_end(),piston.get_center()).set_stroke(self.crank_color,self.line_stroke)
point_bm = Dot(slider.get_end(),radius=radio)
point_mp = Dot(crank.get_end(),radius=radio)
nuevo_grupo = VGroup(slider,piston,crank,point_mp,point_bm)
grupo.become(nuevo_grupo)
return grupo
self.play(
alpha.set_value,self.theta_end,
UpdateFromFunc(grupo,update),
run_time=8,rate_func=double_smooth)
self.wait()
def position_slider(self,origin,theta_2,length,color):
end_point_x = length * np.cos(theta_2 * DEGREES)
end_point_y = length * np.sin(theta_2 * DEGREES)
end_point = origin + np.array([end_point_x, end_point_y, 0])
slider = Line(origin,end_point, color=color).set_stroke(None,self.line_stroke)
return slider
def position_piston(self,origin,theta_2,theta_3,a,b,c,color):
d = a * np.cos(theta_2 * DEGREES) - b * np.cos(theta_3 * DEGREES)
end_point = origin + RIGHT * d + UP * c
piston = Rectangle(color=color, height=1, witdh=1.5)\
.set_fill(color,0.7).scale(0.7).move_to(origin+RIGHT * d + UP*c)
return piston
class TriangleScene(Scene):
def construct(self):
circle = Circle(radius=3)
base_line = Line(ORIGIN,RIGHT*3,color=ORANGE)
side_1 = Line(ORIGIN,RIGHT*3,color=BLUE)
side_2 = Line(RIGHT*3,RIGHT*3,color=PURPLE)
sides = VGroup(side_1,side_2)
def triangle_update(mob):
side_1,side_2 = mob
new_side_1 = Line(ORIGIN,circle.points[-1],color=BLUE)
new_side_2 = Line(RIGHT*3,circle.points[-1],color=PURPLE)
side_1.become(new_side_1)
side_2.become(new_side_2)
sides.add_updater(triangle_update)
self.add(base_line,sides)
self.play(ShowCreation(circle,run_time=3))
self.wait()
|
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/alpha_projects/ellipse_hyperbola.py | from manimlib.imports import *
class Ellipse(ParametricFunction):
def __init__(self, a, e, **kwargs):
digest_config(self,kwargs)
b = np.sqrt( - ( (e ** 2) - 1 ) * ( a ** 2 ) )
super().__init__(
lambda t: np.array([
a * np.sin(t),
b * np.cos(t),
0
]),
t_min = 0,
t_max = 2 * PI,
**kwargs,
)
def there_and_back_linear(t):
new_t = 2 * t if t < 0.5 else 2 * (1 - t)
return linear(new_t)
class EllipseScene(Scene):
CONFIG = {
"semi_major_axis": 2, # a
"eccentricity": 0, # e
"focus_config": {
"radius": 0.1,
"color": RED
},
"line_config": {
"color": TEAL
},
"number_line_config": {
"unit_size": 9,
"x_min": 0,
"x_max": 1,
"include_numbers": True,
"numbers_to_show": np.arange(0,1.1, 0.1),
"decimal_number_config": {
"num_decimal_places": 1
},
"tick_frequency": 0.1
},
"dot_config": {
"radius": 0.1,
"color": YELLOW,
}
}
def construct(self):
# Ellipse
a, e = self.semi_major_axis, self.eccentricity
ellipse = Ellipse(a, e)
# Focus
dots = VGroup(*[
Dot(**self.focus_config) for _ in range(2)
])
#
dot = Dot(**self.dot_config)
# directrix
lines = VGroup(*[
DashedLine(
DOWN * FRAME_Y_RADIUS,
UP * FRAME_Y_RADIUS,
**self.line_config
) for _ in range(2)
])
# number_line
number_line = NumberLine(**self.number_line_config)
number_line.set_x(0)
number_line.to_edge(DOWN)
# eccentricity
eccentricity = TexMobject("\\varepsilon")
eccentricity.next_to(number_line.n2p(1), RIGHT,buff=0.5)
# add all mobs to a group
group = VGroup(ellipse, lines, dots, dot)
dot.move_to(number_line.n2p(0))
number_plane = NumberPlane().fade(0.5)
self.number_line = number_line
self.play(
FadeIn(number_plane),
*list(map(GrowFromCenter, [ellipse, *dots])),
# This is the same as:
# GrowFromCenter(ellipse),
# GrowFromCenter(dots[0]),
# GrowFromCenter(dots[1])
*list(map(Write, [number_line, eccentricity])),
GrowFromCenter(dot)
)
self.add(group)
self.play(
UpdateFromAlphaFunc(
group, self.get_ellipse_group(group, a, e, 1),
run_time=20,
rate_func=there_and_back_linear
)
)
self.wait()
def get_ellipse_group(self, mob, a, e_start, e_end):
def updater_func(mob,alpha):
ellipse, lines, dots, dot = mob
e_target = interpolate(e_start, e_end, alpha)
c_target = e_target * a
dots[0].set_x(c_target)
dots[1].set_x(-c_target)
f_target = a / (e_target + 0.000001)
lines[0].set_x(f_target)
lines[1].set_x(-f_target)
dot.move_to(self.number_line.n2p(e_target))
ellipse.become(
Ellipse(
a, e_target
)
)
return updater_func |
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/alpha_projects/derivative.py | from manimlib.imports import *
class Derivative(Scene):
CONFIG = {
"x_start": 3,
"x_end": 7,
"axes_config": {
"center_point": [-4.5,-2.5,0],
"x_axis_config": {
"x_min": -1,
"x_max": 10,
"include_numbers": True
},
"y_axis_config": {
"label_direction": UP,
"x_min": -1,
"x_max": 6,
"include_numbers": True
},
},
"func": lambda x: 0.1 * (x - 2) * (x - 8) * (x - 5) + 3,
"func_config": {
"color": RED,
"x_min": 0.8,
"x_max": 9,
},
"dot_radius": 0.1,
"line_config": {}
}
def construct(self):
axes = self.get_axes()
func = self.get_graph(self.func,**self.func_config)
dot_start = self.get_dot_from_x_coord(self.x_start)
dot_end = self.get_dot_from_x_coord(self.x_end)
line = VMobject()
line.add_updater(self.get_line_updater(dot_start,dot_end))
# self.add(axes,func,dot_start,dot_end,line)
self.play(
Write(axes),
ShowCreation(func),
*list(map(GrowFromCenter,[dot_start,dot_end]))
)
self.play(ShowCreation(line))
self.wait()
self.move_dot(dot_end, self.x_end, self.x_start + 0.0001, run_time=8)
line.clear_updaters()
self.remove(dot_end)
line.add_updater(self.get_derivative_updater(dot_start))
self.add(line)
self.wait()
self.move_dot(
dot_start,
self.x_start, 8,
run_time=18,
rate_func=there_and_back
)
self.wait(3)
def get_axes(self):
self.axes = Axes(**self.axes_config)
# FIX Y LABELS
y_labels = self.axes.get_y_axis().numbers
for label in y_labels:
label.rotate(-PI/2)
return self.axes
def get_graph(self,func,**kwargs):
return self.axes.get_graph(
func,
**kwargs
)
def get_f(self,x_coord):
return self.axes.c2p(x_coord, self.func(x_coord))
def get_dot_from_x_coord(self,x_coord,**kwargs):
return Dot(
self.get_f(x_coord),
radius=self.dot_radius,
**kwargs
)
def get_dot_updater(self, start, end):
def updater(mob,alpha):
x = interpolate(start, end, alpha)
coord = self.get_f(x)
mob.move_to(coord)
return updater
def get_line_across_points(self,d1,d2,buff):
reference_line = Line(d1.get_center(),d2.get_center())
vector = reference_line.get_unit_vector()
return Line(
d1.get_center() - vector * buff,
d2.get_center() + vector * buff,
**self.line_config
)
def get_line_updater(self,d1,d2,buff=3,**kwargs):
def updater(mob):
mob.become(
self.get_line_across_points(d1,d2,buff)
)
return updater
def move_dot(self,dot,start,end,*args,**kwargs):
self.play(
UpdateFromAlphaFunc(
dot, self.get_dot_updater(start,end),
*args,
**kwargs
)
)
def get_derivative_updater(self, dot, length=6):
def updater(mob):
derivative = Line(
dot.get_center(),
self.get_dot_from_x_coord(
self.axes.p2c(dot.get_center())[0] + 0.0001
).get_center(),
**self.line_config
)
derivative.set_length(length)
derivative.move_to(dot)
mob.become(derivative)
return updater
|
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/alpha_projects/sum_external_angles.py | from manimlib.imports import *
class NewRegularPolygon(RegularPolygon):
def get_sides(self,**kwargs):
vertices = [*self.get_vertices(), self.get_vertices()[0]]
sides = VGroup(*[
Line(vertices[i],vertices[i+1],**kwargs)
for i in range(len(vertices)-1)
])
return sides
def get_external_sides(self,size=1,**kwargs):
sides = self.get_sides()
external_sides = VGroup()
kwargs["stroke_width"] = self.get_stroke_width()
for side in sides:
unit_vector = side.get_unit_vector()
start = side.get_end()
line = Line(
start,
start + size * unit_vector,
**kwargs
)
external_sides.add(line)
return external_sides
def get_external_angles(self,radius=0.7,**kwargs):
external_sides = self.get_external_sides()
sides = self.get_sides()
ind = -1 if self.start_angle == 0 else 1
angle = abs(external_sides[0].get_angle() - sides[ind].get_angle())
arcs = VGroup(*[
Arc(
sides[n].get_angle(),
angle,
radius=radius,
arc_center=external_sides[n].get_start(),
**kwargs
) for n in range(len(sides))
])
return arcs
class GroupRegularPolygon(VGroup):
CONFIG = {
"polygon_color": RED,
"ext_side_color": BLUE,
"ext_angle_color": TEAL
}
def __init__(self,n,size=1,radius=0.7,height=2,**kwargs):
regular_polygon = NewRegularPolygon(n,**kwargs)
regular_polygon.set_height(height)
super().__init__(
regular_polygon.get_external_sides(**kwargs),
regular_polygon.get_external_angles(**kwargs),
regular_polygon
)
self[0].set_color(self.ext_side_color)
self[1].set_color(self.ext_angle_color)
self[2].set_color(self.polygon_color)
self.regular_polygon = regular_polygon
def get_number_sides(self):
return len(self.regular_polygon.get_sides())
def get_figure_height(self):
return self.regular_polygon.get_height()
def get_polygon_external_sides(self):
return self[0]
def get_polygon_external_angles(self):
return self[1]
def get_regular_polygon(self):
return self[2]
class SumExternalAngles(Scene):
CONFIG = {
"polygon_sides": [3,5,6,7,4],
"init_buff": 0.6
}
def construct(self):
figures = VGroup(*[GroupRegularPolygon(n) for n in self.polygon_sides])
for figure in figures:
figure.save_state()
figure.height = figure.get_figure_height()
def shrink_polygon(vgroup,alpha):
buff = interpolate(self.init_buff,2,alpha)
for mob in vgroup:
mob.restore()
d_height = interpolate(mob.height,0.0001,alpha)
mob.become(
GroupRegularPolygon(
mob.get_number_sides(),
height = d_height
)
)
vgroup.arrange(RIGHT,buff=buff)
vgroup.set_width(FRAME_WIDTH-0.2)
shrink_polygon(figures,0)
regular_polygons = VGroup(*[
figure.get_regular_polygon()
for figure in figures
])
external_sides = VGroup(*[
figure.get_polygon_external_sides()
for figure in figures
])
external_angles = VGroup(*[
figure.get_polygon_external_angles()
for figure in figures
])
self.play(LaggedStartMap(GrowFromCenter,regular_polygons),run_time=2)
self.play(*list(map(ShowCreation,external_sides)))
self.play(*list(map(ShowCreation,external_angles)))
self.wait()
self.play(
UpdateFromAlphaFunc(figures,shrink_polygon),
run_time = 8,
rate_func = there_and_back
)
self.wait(3) |
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/alpha_projects/bezier.py | from manimlib.imports import *
class QuadraticBezier(Scene):
CONFIG = {
"bezier_points": [(6,0),(-4,3),(-6,-2)],
"anim_kwargs": {
"rate_func": linear,
"run_time": 13
},
"bezier_lines_kwargs": {
"color": TEAL,
"stroke_opacity": 0.5,
"stroke_width": 1
},
"bezier_dots_style": {
"color": "#555555",
"fill_opacity": 0.5
},
"dots_radius": 0.15,
"moving_line_style": {
"color": BLUE,
"stroke_width": 3
}
}
def get_coords_points_and_lines(self,**kwargs):
bezier_coords = [np.array([x,y,0]) for x,y in self.bezier_points]
bezier_points = VGroup(*[
Dot(c,radius=self.dots_radius,**self.bezier_dots_style)
for c in bezier_coords
])
lines = VGroup(*[
Line(
bezier_coords[i],
bezier_coords[i+1],
**kwargs
)
for i in range(len(bezier_coords)-1)
])
return bezier_coords,bezier_points,lines
def get_update_function_to_point(self,line):
return lambda mob,alpha: mob.move_to(line.point_from_proportion(alpha))
def get_moving_dot(self,line,**kwargs):
return Dot(line.get_start(),color=RED,radius=self.dots_radius,**kwargs)
def get_update_function_to_moving_line(self,dot1,dot2,**kwargs):
return lambda mob: mob.become( Line(dot1.get_center(),dot2.get_center(),**kwargs) )
def get_update_function_path(self,dot,**kwargs):
def update_function(path):
old_path = path.copy()
old_path.append_vectorized_mobject(
Line(
old_path.points[-1],
dot.get_center(),
**kwargs
)
)
old_path.make_smooth()
path.become(old_path)
return update_function
def setup(self):
bc, bp, bl = self.get_coords_points_and_lines(**self.bezier_lines_kwargs)
moving_dots = VGroup(*[self.get_moving_dot(line) for line in bl])
dot_funcs = [self.get_update_function_to_point(line) for line in bl]
self.play(
ShowCreation(VGroup(bp,bl)),
*list(map(GrowFromCenter,moving_dots))
)
self.bezier_points = bp
self.bezier_coords = bc
self.bezier_lines = bl
self.bezier_points_funcs = dot_funcs
self.moving_dots = moving_dots
def construct(self):
dot1,dot2 = self.moving_dots
moving_line = Line()
moving_line_dot = Dot(radius=self.dots_radius,color=ORANGE)
path = VMobject()
# Moving line setup
moving_line_update_func = self.get_update_function_to_moving_line(dot1,dot2,**self.moving_line_style)
moving_line_update_func(moving_line)
# Moving line update function setup
moving_line_dot_update_func = self.get_update_function_to_point(moving_line)
moving_line_dot_update_func(moving_line_dot,0)
# Path setup
# ---- Initial conditions
path.set_points_as_corners([
moving_line_dot.get_center(),
moving_line_dot.get_center()+UP*0.001
])
# ---- Definition
path_update_func = self.get_update_function_path(moving_line_dot)
path.add_updater(path_update_func)
# Show mobs in screen
self.play(
*list(map(GrowFromCenter,[moving_line,moving_line_dot]))
)
self.add(path)
self.play(
*[
UpdateFromAlphaFunc(dot,func,**self.anim_kwargs)
for dot,func in zip(self.moving_dots,self.bezier_points_funcs)
],
UpdateFromFunc(moving_line,moving_line_update_func),
UpdateFromAlphaFunc(moving_line_dot,moving_line_dot_update_func,**self.anim_kwargs),
)
self.wait()
class CubicBezier(QuadraticBezier):
CONFIG = {
"bezier_points": [(6,-2),(2,1),(-3,2),(-6,-2)]
}
# TASK
# See: https://upload.wikimedia.org/wikipedia/commons/d/db/B%C3%A9zier_3_big.gif
|
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/dt_projects/pendulum.py | from manimlib.imports import *
class Pendulum(VGroup):
CONFIG = {
"theta_max": 10 * DEGREES,
"theta_offset": 0,
"theta_start": None,
"length": 5,
"origin": ORIGIN,
"mass_config": {
"radius": 0.5,
"color": RED
},
"line_config": {
"color": WHITE,
"stroke_width": 3
}
}
def __init__(self,**kwargs):
digest_config(self,kwargs)
super().__init__(**kwargs)
self.mass = self.get_mass()
self.string = self.get_string()
self.vertical_line = self.string.copy()
self.string.save_state()
self.string.initial_state = self.string.copy()
if self.theta_start == None:
self.theta_start = self.theta_max
self.mass.add_updater(lambda mob: mob.move_to(self.string.get_end()))
self.rotate(self.theta_start)
self.add(self.string,self.mass)
def get_mass(self):
return Dot(**self.mass_config)
def get_string(self):
return Line(
self.origin,
self.origin + DOWN * self.length,
**self.line_config
)
def rotate(self,angle):
self.string.rotate(angle, about_point=self.origin)
def restore_string(self):
self.string.restore()
def get_angle(self):
return angle_between(self.string.get_unit_vector(), DOWN) * 180 / PI
def add_mass_updater(self):
self.mass.add_updater(lambda mob: mob.move_to(self.string.get_end()))
class PendulumScene(Scene):
CONFIG = {
"total_time": 13,
"dt_factor": 3,
"gravity": 9.8
}
def construct(self):
dt_calculate = 1 / self.camera.frame_rate
roof = self.get_roof()
roof.to_edge(UP)
pendulum = Pendulum(
origin=roof.get_bottom()
)
pendulum.restore_string()
equation = TexMobject(r"\theta = \theta_{max}\cos\left(\sqrt{\frac{g}{L}}\cdot t\right)")
equation.to_corner(DR)
self.play(ShowCreation(roof))
self.play(
AnimationGroup(
ShowCreation(pendulum.string),
GrowFromCenter(pendulum.mass),
lag_ratio=1
)
)
self.play(
Rotating(
pendulum.string,
radians=10*DEGREES,
about_point=pendulum.origin,
rate_func=smooth,
run_time=1
)
)
self.wait()
self.play(
Write(equation)
)
pendulum.add_updater(self.get_theta_func(pendulum))
self.add(pendulum)
self.wait(self.total_time)
def get_theta_func(self,mob):
func = lambda t: mob.theta_max * np.cos(
t * np.sqrt(
( self.gravity / mob.length )
)
)
def updater_func(mob,dt):
mob.theta_offset += dt * self.dt_factor
new_theta = func(mob.theta_offset)
mob.restore_string()
mob.rotate(new_theta)
return updater_func
def get_roof(self,size=0.2,**line_config):
line = Line(
ORIGIN, UR * size, **line_config
)
lines = VGroup(*[
line.copy() for _ in range(30)
])
lines.arrange(RIGHT,buff=0)
down_line = Line(
lines.get_corner(DL),
lines.get_corner(DR),
**line_config
)
return VGroup(lines, down_line) |
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/dt_projects/charges.py | from manimlib.imports import *
# Electric field animation, 3Blue1Brown property
# This animation belongs to the file:
# https://github.com/3b1b/manim/blob/master/from_3b1b/old/div_curl.py#L1293
# This code is not my own, I simply updated it to the recent
# version and documented it.
def get_force_field_func(*point_strength_pairs, **kwargs):
radius = kwargs.get("radius", 0.5)
def func(point):
result = np.array(ORIGIN)
for center, strength in point_strength_pairs:
to_center = center - point
norm = get_norm(to_center)
if norm == 0:
continue
elif norm < radius:
to_center /= radius**3
elif norm >= radius:
to_center /= norm**3
to_center *= -strength
result += to_center
return result
return func
class ElectricParticle(Circle):
CONFIG = {
"color": WHITE,
"sign": "+",
}
def __init__(self, radius=0.5 ,**kwargs):
digest_config(self, kwargs)
super().__init__(
stroke_color=WHITE,
stroke_width=0.5,
fill_color=self.color,
fill_opacity=0.8,
radius=radius
)
sign = TexMobject(self.sign)
sign.set_stroke(WHITE, 1)
sign.set_width(0.5 * self.get_width())
sign.move_to(self)
self.add(sign)
class Proton(ElectricParticle):
CONFIG = {
"color": RED_E,
}
class Electron(ElectricParticle):
CONFIG = {
"color": BLUE_E,
"sign": "-"
}
class ChangingElectricField(Scene):
CONFIG = {
"vector_field_config": {},
"num_particles": 6,
"anim_time": 18,
}
def construct(self):
particles = self.get_particles()
vector_field = self.get_vector_field()
def update_vector_field(vector_field):
new_field = self.get_vector_field()
vector_field.become(new_field)
vector_field.func = new_field.func
# The dt parameter will be explained in
# future videos, but here is a small preview.
def update_particles(particles, dt):
func = vector_field.func
for particle in particles:
force = func(particle.get_center())
particle.velocity += force * dt
particle.shift(particle.velocity * dt)
self.play(
*list(map(GrowArrow, vector_field)),
*list(map(GrowFromCenter, particles))
)
self.wait()
vector_field.add_updater(update_vector_field),
particles.add_updater(update_particles),
self.add(
vector_field,
particles
)
# Animation time:
self.wait(self.anim_time)
def get_particles(self):
particles = self.particles = VGroup()
for n in range(self.num_particles):
if n % 2 == 0:
particle = Proton(radius=0.2)
particle.charge = +1
else:
particle = Electron(radius=0.2)
particle.charge = -1
particle.velocity = np.random.normal(0, 0.1, 3)
particles.add(particle)
particle.shift(np.random.normal(0, 0.2, 3))
particles.arrange_in_grid(buff=LARGE_BUFF)
return particles
def get_vector_field(self):
func = get_force_field_func(*list(zip(
list(map(lambda x: x.get_center(), self.particles)),
[p.charge for p in self.particles]
)))
self.vector_field = VectorField(func, **self.vector_field_config)
return self.vector_field |
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/dt_projects/bouncing_ball.py | from manimlib.imports import *
# By EulerTour
# https://www.patreon.com/eulertour
class Ball(Circle):
CONFIG = {
"radius": 0.4,
"fill_color": BLUE,
"fill_opacity": 1,
"color": BLUE
}
def __init__(self, ** kwargs):
Circle.__init__(self, ** kwargs)
self.velocity = np.array((2, 0, 0))
def get_top(self):
return self.get_center()[1] + self.radius
def get_bottom(self):
return self.get_center()[1] - self.radius
def get_right_edge(self):
return self.get_center()[0] + self.radius
def get_left_edge(self):
return self.get_center()[0] - self.radius
class Box(Rectangle):
CONFIG = {
"height": 6,
"width": FRAME_WIDTH - 2,
"color": GREEN_C
}
def __init__(self, ** kwargs):
Rectangle.__init__(self, ** kwargs) # Edges
self.top = 0.5 * self.height
self.bottom = -0.5 * self.height
self.right_edge = 0.5 * self.width
self.left_edge = -0.5 * self.width
class BouncingBall(Scene):
CONFIG = {
"bouncing_time": 10,
}
def construct(self):
box = Box()
ball = Ball()
self.play(FadeIn(box))
self.play(FadeIn(ball))
def update_ball(ball,dt):
ball.acceleration = np.array((0, -5, 0))
ball.velocity = ball.velocity + ball.acceleration * dt
ball.shift(ball.velocity * dt) # Bounce off ground and roof
if ball.get_bottom() <= box.bottom*0.96 or \
ball.get_top() >= box.top*0.96:
ball.velocity[1] = -ball.velocity[1]
# Bounce off walls
if ball.get_left_edge() <= box.left_edge or \
ball.get_right_edge() >= box.right_edge:
ball.velocity[0] = -ball.velocity[0]
ball.add_updater(update_ball)
self.add(ball)
self.wait(self.bouncing_time)
ball.clear_updaters()
self.wait(3) |
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/dt_projects/sin_cos.py | from manimlib.imports import *
class SinFunc(FunctionGraph):
CONFIG = {
"color": BLUE_E,
"func": np.sin,
"shift_graph": -2,
"beta": 2,
"amp": 1.5,
"shift_left": -1,
"t_offset": 0
}
def __init__(self, factor=1,**kwargs):
digest_config(self,kwargs)
func = lambda t: self.amp * self.func(self.beta * t + self.t_offset * factor) + self.shift_graph
super().__init__(func, x_min=-(PI + PI / 4), x_max=PI ,**kwargs)
self.shift(RIGHT * self.shift_left)
class CosFunc(SinFunc):
CONFIG = {
"color": RED_E,
"func": np.cos,
"shift_graph": 2,
}
class SinCos(Scene):
CONFIG = {
"total_time": 25, # seconds
"dt_factor": 0.4,
"circle_config": {
"radius": 1.5,
"color": WHITE,
"arc_center": [5,-2,0]
},
"cos_config": {
"color": BLUE
},
"sin_config": {
"color": RED
},
"vertical_line_config": {
"stroke_width": 2,
"stroke_opacity": 0.5,
"color": TEAL
},
"arc_marks_config": {
"color": GRAY,
"stroke_width": 2,
"stroke_opacity": 0.5
},
"sto": 0, # sine t offset
"cto": 0,
"tto": 0, # theta t offset
}
def construct(self):
# Create Main Mobjects
sine = self.sine = SinFunc()
cosine = self.cosine = CosFunc()
circle = self.circle = Circle(**self.circle_config)
circle.next_to(sine, RIGHT, buff=0.5)
dot_theta = self.dot_theta = self.get_dot_from_theta(circle,0)
# guide lines
sine_line = self.sine_line = self.get_sine_line()
cosine_guide_line = self.cgl = self.get_cosine_vertical_guide_line()
cosine_line = self.cosine_line = self.get_cosine_line()
# reference lines
vertical_line = self.vertical_line = self.get_vertical_line()
horizontal_line = self.horizontal_line = self.get_horizontal_line()
# arc marks
arc_dx = 0.5
arc_marks = VGroup(*[
Arc(
radius=r,
arc_center=[vertical_line.get_x(),0,0],
**self.arc_marks_config
)
for r in np.arange(0.5, 3.5 + arc_dx, arc_dx)
])
# Decimal number mobjects
theta_tex = TexMobject("\\theta =")
theta_tex.to_corner(UR).shift(LEFT * 1.5)
theta_number = DecimalNumber(0,unit=r"^\circ")
theta_number.next_to(theta_tex, RIGHT)
theta_number.align_to(theta_tex, DOWN)
# Write in the Screen
self.play(
ShowCreation(VGroup(
vertical_line, horizontal_line
)),
GrowFromCenter(circle),
GrowFromPoint(dot_theta, circle.get_center()),
run_time=2.5
)
self.play(
*list(map(ShowCreation,[
sine,
cosine,
arc_marks,
sine_line,
VGroup(cosine_guide_line, cosine_line) # WHY this?, think about it
])),
Write(VGroup(theta_tex, theta_number)),
run_time=2.5
)
self.wait()
# Add updaters, THE ORDER MATTERS
sine.add_updater(
self.get_updater_func("sto", SinFunc)
)
cosine.add_updater(
self.get_updater_func("cto", CosFunc)
)
dot_theta.add_updater(
self.get_updater_dot(circle)
)
sine_line.add_updater(
lambda mob: mob.become(
self.get_sine_line()
)
)
cosine_guide_line.add_updater(
lambda mob: mob.become(
self.get_cosine_vertical_guide_line()
)
)
cosine_line.add_updater(
lambda mob: mob.become(
self.get_cosine_line()
)
)
theta_number.add_updater(
lambda mob: mob.set_value(
(self.CONFIG["tto"] % (2*PI)) * 180 / PI
)
)
self.wait(self.total_time)
# Stop animation
for mob in [
sine,
cosine,
dot_theta,
sine_line,
cosine_guide_line,
cosine_line,
theta_number,
]:
mob.clear_updaters()
self.wait(2)
def get_updater_func(self, t, TrigFunc, **kwargs):
def update_func(mob,dt):
self.CONFIG[t] += dt * self.dt_factor
mob.become(
TrigFunc(
t_offset=self.CONFIG[t],
**kwargs
)
)
return update_func
def get_dot_from_theta(self,circle,theta,**kwargs):
return Dot(
circle.point_at_angle(theta),
**kwargs
)
def get_updater_dot(self, circle):
def update_func(mob,dt):
self.CONFIG["tto"] += dt * self.dt_factor
mob.move_to(
circle.point_at_angle(self.CONFIG["tto"]%(2*PI))
)
return update_func
def get_sine_line(self):
return Line(
self.sine.get_end(),
self.dot_theta.get_left(),
color=self.sine.get_color()
)
def get_cosine_line(self):
return ArcBetweenPoints(
self.cgl.get_end(),
self.cosine.get_end(),
angle=PI/2,
color=self.cosine.get_color()
)
def get_vertical_line(self):
vertical_line = Line(
ORIGIN,
RIGHT * FRAME_HEIGHT,
**self.vertical_line_config
).rotate(PI/2)
vertical_line.set_x(self.cosine.get_end()[0])
return vertical_line
def get_horizontal_line(self):
return Line(
LEFT * FRAME_X_RADIUS,
RIGHT * FRAME_X_RADIUS,
**self.vertical_line_config
)
def get_cosine_vertical_guide_line(self):
return Line(
self.dot_theta.get_top(),
np.array([
self.dot_theta.get_x(),
0,
0
]),
color=self.cosine.get_color()
)
|
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/successions/successions.py | from manimlib.imports import *
class AnimationGroupExampleFail(Scene):
def construct(self):
dots = VGroup(*[Dot() for _ in range(10)])
dots.arrange(RIGHT,buff=0.8)
self.add(dots)
for dot in dots:
self.play(
dot.scale,3,
dot.set_color,RED,
rate_func=there_and_back
)
self.wait(2)
class AnimationGroupExample(Scene):
def construct(self):
dots = VGroup(*[Dot() for _ in range(10)])
dots.arrange(RIGHT, buff=0.8)
self.add(dots)
def dot_func(mob):
mob.scale(3)
mob.set_color(RED)
return mob
self.play(
# Replace AnimationGroup with LaggedStart
LaggedStart(
*[
ApplyFunction(
dot_func,
dot,
rate_func=there_and_back
)
for dot in dots
]
)
)
self.wait(2)
class AbsctractScene(Scene):
CONFIG = {
"anim_kwargs": {"rate_func": there_and_back}
}
def setup(self):
dots = VGroup(*[Dot() for _ in range(10)])
dots.arrange(RIGHT, buff=0.8)
# Save the state
dots.save_state()
def dot_func(mob):
mob.scale(3)
mob.set_color(RED)
return mob
self.dots = dots
self.dot_func = dot_func
self.add(self.dots)
# LaggedStart != LaggedStartMap (recent version)
# BUT LaggedStartMap (recent version) == LaggedStart (3/feb version)
class LaggedStartMapExample(AbsctractScene):
def construct(self):
self.play(
LaggedStartMap(
GrowFromCenter,
self.dots
)
)
self.wait()
class LaggedStartMapExample2(AbsctractScene):
def construct(self):
self.play(
LaggedStartMap(
GrowFromCenter,
self.dots,
rate_func=there_and_back
)
)
self.wait()
# What happens if remove the following line?
self.dots.restore()
self.play(
LaggedStart(*[
GrowFromCenter(
dot,
rate_func=there_and_back
)
for dot in self.dots
],
)
)
# In summary, LaggedStartMap is a way
# to run LaggedStart without applying
# the spread (splat) operator.
# But it only applies to animations
# that receive a Mobject as the only argument:
# Examples: Write, FadeIn, GrowFromCenter, ShowCreation, MoveToTarget, etc.
self.wait(2)
# Way to put more arguments in LaggedStartMap
class LaggedStartMapExample3(AbsctractScene):
def construct(self):
self.play(
LaggedStartMap(
FadeInFrom, # This receives 2 arguments:
# Mobject and Direction
self.dots,
lambda mob: (mob, UP),
)
)
self.wait()
class AnimationGroupExampleLagRatios(AbsctractScene):
CONFIG = {
"lag_ratios": list(np.arange(0,1.1,.1)) # (0, 0.1, 0.2 ... 1)
}
def construct(self):
self.remove(self.dots)
labels = VGroup(*[
Text("lag_ratio: %.1f -"%lg,stroke_width=0,font="Arial").set_height(0.4)
for lg in self.lag_ratios
])
set_dots = VGroup(*[
self.dots.copy() for _ in self.lag_ratios
])
set_dots.arrange(DOWN,buff=0.5)
set_dots.to_edge(RIGHT)
for label, dots in zip(labels,set_dots):
label.next_to(dots,LEFT,buff=0.4)
self.add(labels,set_dots)
self.play(*[
AnimationGroup(*[
ApplyFunction(
self.dot_func,
dot,
rate_func=there_and_back
)
for dot in dots
],
lag_ratio=lg
)
for dots,lg in zip(set_dots,self.lag_ratios)
])
self.wait()
# Successions vs AnimationGroup
# AnimationGroup
class AnimationGroupExample1(Scene):
def construct(self):
number_line = NumberLine(x_min=-2,x_max=2)
text = TextMobject("Text")\
.next_to(number_line,DOWN)
dashed_line=DashedLine(
number_line.get_left(),
number_line.get_right(),
color=YELLOW,
).set_stroke(width=11)
self.add(number_line)
self.wait(0.3)
self.play(
LaggedStart(
*[ShowCreationThenDestruction(dashed_segment)
for dashed_segment in dashed_line],
run_time=5
),
AnimationGroup(
Animation(Mobject(),run_time=2.1), # PAUSE
Write(text),lag_ratio=1
)
)
self.wait()
class AnimationGroupExample2(Scene):
def construct(self):
number_line = NumberLine(x_min=-2,x_max=2)
triangle = RegularPolygon(3,start_angle=-PI/2)\
.scale(0.2)\
.next_to(number_line.get_left(),UP,buff=SMALL_BUFF)
text_1 = TextMobject("1")\
.next_to(number_line.get_tick(-1),DOWN)
text_2 = TextMobject("2")\
.next_to(number_line.get_tick(0),DOWN)
text_3 = TextMobject("3")\
.next_to(number_line.get_tick(1),DOWN)
text_4 = TextMobject("4")\
.next_to(number_line.get_tick(2),DOWN)
self.add(number_line)
self.play(ShowCreation(triangle))
self.wait(0.3)
self.play(
# Pauses are referenced to the beginning of the play
# ==================================================
ApplyMethod(triangle.shift,RIGHT*4,rate_func=linear,run_time=4),
AnimationGroup(
Animation(Mobject(),run_time=1), # 1 second pause
Write(text_1),lag_ratio=1
),
AnimationGroup(
Animation(Mobject(),run_time=2), # 2 seconds pause
Write(text_2),lag_ratio=1
),
AnimationGroup(
Animation(Mobject(),run_time=3), # 3 seconds pause
Write(text_3),lag_ratio=1
),
AnimationGroup(
Animation(Mobject(),run_time=4), # 4 seconds pause
Write(text_4),lag_ratio=1
)
)
self.wait()
class Pause(Animation):
def __init__(self, duration):
super().__init__(Mobject(), run_time=duration)
class AnimationGroupExample2Compact(Scene):
def construct(self):
number_line=NumberLine(x_min=-2,x_max=2)
triangle=RegularPolygon(3,start_angle=-PI/2)\
.scale(0.2)\
.next_to(number_line.get_left(),UP,buff=SMALL_BUFF)
numbers=VGroup(
*[TextMobject("%s"%i)\
.next_to(number_line.get_tick(i-2),DOWN) for i in range(1,5)]
)
self.add(number_line)
self.play(ShowCreation(triangle))
self.wait(0.3)
self.play(
ApplyMethod(triangle.shift,RIGHT*4,rate_func=linear,run_time=4),
*[AnimationGroup(
# Animation(Mobject(),run_time=i+1), # <- This is a pause
Pause(i+1),
Write(numbers[i]),lag_ratio=1
)for i in range(4)],
)
self.wait()
class AnimationGroupExample3(Scene):
def construct(self):
number_line = NumberLine(x_min=-2,x_max=2)
text_1 = TextMobject("Theorem of")\
.next_to(number_line,DOWN)
text_2 = TextMobject("Beethoven")\
.next_to(number_line,DOWN)
dashed_line = DashedLine(
number_line.get_left(),
number_line.get_right(),
color=YELLOW,
).set_stroke(width=11)
self.add(number_line,text_1)
self.play(
LaggedStart(
*[ShowCreationThenDestruction(dashed_segment)
for dashed_segment in dashed_line],
run_time=5
),
AnimationGroup(
Animation(Mobject(),run_time=2.1),
# Pause(2.1)
ReplacementTransform(text_1,text_2),lag_ratio=1
)
)
self.wait()
# Successions
class AnimationGroupFail1(Scene):
def construct(self):
text1 = TextMobject("Theorem")
text2 = TextMobject("of")
text3 = TextMobject("Beethoven")
for text in text1,text2,text3:
text.scale(3)
self.add(text1)
self.play(
AnimationGroup(
ReplacementTransform(text1,text2),
ReplacementTransform(text2,text3),
lag_ratio=1
)
)
self.wait()
class AnimationGroupFail2(Scene):
def construct(self):
text1 = TextMobject("Theorem")
text2 = TextMobject("of")
text3 = TextMobject("Beethoven")
for text in text1,text2,text3:
text.scale(3)
self.add(text1)
self.play(
AnimationGroup(
Transform(text1,text2),
Transform(text1,text3),
lag_ratio=1
)
)
self.wait()
class Succession1(Scene):
def construct(self):
text1 = TextMobject("Theorem")
text2 = TextMobject("of")
text3 = TextMobject("Beethoven")
for text in text1,text2,text3:
text.scale(3)
self.add(text1)
self.play(
Succession(
Transform(text1,text2),
Transform(text1,text3),
lag_ratio=1.2
)
)
self.wait()
# Real example
class ClockOrganization(VGroup):
CONFIG = {
"numbers" : 4,
"radius" : 3.1,
"color" : WHITE
}
def __init__(self, **kwargs):
digest_config(self, kwargs, locals())
self.generate_nodes()
VGroup.__init__(self, *self.node_list,**kwargs)
def generate_nodes(self):
self.node_list = []
for i in range(self.numbers):
mobject = VMobject()
number = TexMobject(str(i+1))
circle = Circle(radius=0.4,color=self.color)
mobject.add(number)
mobject.add(circle)
mobject.move_to(
self.radius * np.cos((-TAU / self.numbers) * i + 17*TAU / 84) * RIGHT
+ self.radius * np.sin((-TAU / self.numbers) * i + 17*TAU / 84) * UP
)
self.node_list.append(mobject)
def select_node(self, node):
selected_node = self.node_list[node]
selected_node.scale(1.2)
selected_node.set_color(RED)
def deselect_node(self, selected_node):
node = self.node_list[selected_node]
node.scale(0.8)
node.set_color(self.color)
class ClockOrganizationScene(Scene):
def construct(self):
test = ClockOrganization(numbers=21)
self.add(test)
animation_steps = []
num_circ = 15
for i in range(num_circ):
thing = test.deepcopy()
thing.select_node((19+i)%test.numbers-1)
animation_steps.append(thing)
anims = []
theta = 180 * DEGREES / num_circ
lag_constant = 5
for i in range(1,num_circ):
test.node_list[(19+i)%test.numbers-1].generate_target()
test.node_list[(19+i)%test.numbers-1].target.scale(1.2)
test.node_list[(19+i)%test.numbers-1].target.set_color(RED)
stop_smooth = lag_constant * np.sin(i*theta)
anims.append(MoveToTarget(test.node_list[(19+i)%test.numbers-1],rate_func=there_and_back))
anims.append(Animation(Mobject(),run_time=stop_smooth))
self.play(
AnimationGroup(*anims,lag_ratio=0.1)
)
self.wait()
|
AnimationsWithManim_Elteoremadebeethoven/English/update_successions/successions/successions_anim.py | from manimlib.imports import *
class MeasureDistance(VGroup):
CONFIG = {
"color":RED_B,
"buff":0.3,
"lateral":0.3,
"invert":False,
"dashed_segment_length":0.09,
"dashed":True,
"ang_arrows":30*DEGREES,
"size_arrows":0.2,
"stroke":2.4,
}
def __init__(self,mob,**kwargs):
VGroup.__init__(self,**kwargs)
if self.dashed==True:
medicion=DashedLine(ORIGIN,mob.get_length()*RIGHT,dashed_segment_length=self.dashed_segment_length).set_color(self.color)
else:
medicion=Line(ORIGIN,mob.get_length()*RIGHT)
medicion.set_stroke(None,self.stroke)
pre_medicion=Line(ORIGIN,self.lateral*RIGHT).rotate(PI/2).set_stroke(None,self.stroke)
pos_medicion=pre_medicion.copy()
pre_medicion.move_to(medicion.get_start())
pos_medicion.move_to(medicion.get_end())
angulo=mob.get_angle()
matriz_rotacion=rotation_matrix(PI/2,OUT)
vector_unitario=mob.get_unit_vector()
direccion=np.matmul(matriz_rotacion,vector_unitario)
self.direccion=direccion
self.add(medicion,pre_medicion,pos_medicion)
self.rotate(angulo)
self.move_to(mob)
if self.invert==True:
self.shift(-direccion*self.buff)
else:
self.shift(direccion*self.buff)
self.set_color(self.color)
self.tip_point_index = -np.argmin(self.get_all_points()[-1, :])
def add_tips(self):
linea_referencia=Line(self[0][0].get_start(),self[0][-1].get_end())
vector_unitario=linea_referencia.get_unit_vector()
punto_final1=self[0][-1].get_end()
punto_inicial1=punto_final1-vector_unitario*self.size_arrows
punto_inicial2=self[0][0].get_start()
punto_final2=punto_inicial2+vector_unitario*self.size_arrows
lin1_1=Line(punto_inicial1,punto_final1).set_color(self[0].get_color()).set_stroke(None,self.stroke)
lin1_2=lin1_1.copy()
lin2_1=Line(punto_inicial2,punto_final2).set_color(self[0].get_color()).set_stroke(None,self.stroke)
lin2_2=lin2_1.copy()
lin1_1.rotate(self.ang_arrows,about_point=punto_final1,about_edge=punto_final1)
lin1_2.rotate(-self.ang_arrows,about_point=punto_final1,about_edge=punto_final1)
lin2_1.rotate(self.ang_arrows,about_point=punto_inicial2,about_edge=punto_inicial2)
lin2_2.rotate(-self.ang_arrows,about_point=punto_inicial2,about_edge=punto_inicial2)
return self.add(lin1_1,lin1_2,lin2_1,lin2_2)
def get_text(self, text,scale=1,buff=0.1,invert_dir=False,invert_texto=False,remove_rot=False,**moreargs):
linea_referencia=Line(self[0][0].get_start(),self[0][-1].get_end())
texto=TextMobject(text,**moreargs)
ancho=texto.get_height()/2
inv = PI if invert_texto else 0
if remove_rot:
texto.scale(scale).move_to(self)
else:
texto.rotate(linea_referencia.get_angle()).scale(scale).move_to(self)
texto.rotate(inv)
invert_dir = -1 if invert_dir else 1
texto.shift(self.direccion*(buff+1)*ancho*inv)
return texto
class AnimationRectangle(VGroup):
CONFIG = {
"height": 0.7,
"width": 8,
"rectangle_config": {
"stroke_width": 11,
"color": WHITE
},
"lag_rectangle_config": {
"color": YELLOW_D
},
"number_buff": 0.3
}
def __init__(self,lag_ratio=0.5,**kwargs):
digest_config(self, kwargs)
self.lag_ratio = ValueTracker(lag_ratio)
self.rectangle = self.get_rectangle()
self.lag_rectangle = self.get_lag_rectangle()
self.lag_rectangle.add_updater(
lambda mob: mob.become(
self.get_lag_rectangle()
)
)
self.lag_number = self.get_lag_number()
super().__init__(
self.lag_rectangle,
self.rectangle,
self.lag_number
)
def get_rectangle(self):
return Rectangle(
width=self.width,
height=self.height,
fill_opacity=0,
**self.rectangle_config
)
def get_lag_rectangle(self):
if self.lag_ratio == 0:
self.lag_ratio = 0.00001
lag_width = self.width * self.lag_ratio.get_value()
lag_rectangle = Rectangle(
width=lag_width,
height=self.height,
stroke_width=0,
fill_opacity=1,
**self.lag_rectangle_config
)
lag_rectangle.next_to(
self.rectangle.get_left(),
RIGHT,buff=0
)
return lag_rectangle
def get_lag_number(self):
number = Integer(
self.lag_ratio.get_value(),
unit="\\%",
)
number.add_updater(self.get_lag_number_updater())
return number
def get_lag_number_updater(self):
def update(mob):
mob.match_height(self.rectangle)
mob.scale(0.5)
mob.set_value(int(self.lag_ratio.get_value()*100))
mob.next_to(self.lag_rectangle, RIGHT, buff=self.number_buff)
return update
def get_lag_ratio(self):
return self.lag_ratio
class SuccessionsExplanation(Scene):
CONFIG = {
"anim_widths": [1.5,2.5,4,3.5],
"lag_ratios": [0, 0.2, 0.4, 0.6, 1]
}
def construct(self):
value_tracker = ValueTracker(self.lag_ratios[0])
lag_ratio_dn = DecimalNumber(0).add_updater(
lambda dn: dn.set_value(
value_tracker.get_value()
)
)
lag_tex = TextMobject("\\tt lag\\_ratio = ")
VGroup(lag_tex, lag_ratio_dn).arrange(RIGHT,buff=0.4).to_edge(UP)
lag_ratio_dn.shift(UP*0.07)
# SET ANIM RECTS
anim_rects = VGroup(*[
AnimationRectangle(value_tracker.get_value(), width=width)
for width in self.anim_widths
])
anim_rects.arrange(DOWN,aligned_edge=LEFT)
anim_rects.to_edge(LEFT)
anim_rects.to_edge(DOWN,buff=1)
# Arrange anim rects
anim_rects.add_updater(lambda vg: self.arrange_anim_rects(vg))
# Full animation
full_anim = self.get_full_animation(anim_rects)
full_anim_tex = TextMobject("Full animation")
# run_time
run_time_arrow = MeasureDistance(
Line(anim_rects[0].get_corner(UL), anim_rects[0].get_corner(UR)),
buff=0.25
).add_tips()
run_time_tex = run_time_arrow.get_text("\\tt run\\_time",color=RED_B)
run_time_tex.shift(UP*0.5)
# Animations tex
anim_tex = VGroup(*[
TextMobject(f"Animation {i+1}").next_to(ar)
for i,ar in zip(range(len(anim_rects)),anim_rects)
])
# ANIMS
self.play(
LaggedStartMap(FadeIn, [*anim_rects]),
LaggedStartMap(FadeIn, anim_tex)
)
self.wait(3)
self.play(GrowFromCenter(run_time_arrow),run_time=2)
self.play(FadeInFrom(run_time_tex,UP))
self.wait(3)
self.play(
*list(map(FadeOut, [run_time_arrow,run_time_tex,*anim_tex]))
)
self.wait()
full_anim_tex.move_to(full_anim)
self.play(
FadeInFromDown(full_anim),
FadeInFromDown(full_anim_tex),
)
full_anim.add_updater(
lambda mob: mob.become(
self.get_full_animation(anim_rects)
)
)
full_anim_tex.add_updater(lambda tex: tex.move_to(full_anim))
self.add(full_anim,full_anim_tex)
self.wait()
self.play(
Write(VGroup(lag_tex,lag_ratio_dn))
)
self.add(anim_rects,full_anim,full_anim_tex)
for lag_ratio in self.lag_ratios[1:]:
self.play(*[
ApplyMethod(ar.lag_ratio.set_value, lag_ratio)
for ar in anim_rects
],
value_tracker.set_value, lag_ratio,
run_time=3
)
self.wait(5)
self.wait(5)
def arrange_anim_rects(self, anim_rects):
for i in range(1,len(anim_rects)):
anim_rects[i].set_x(anim_rects[i-1].lag_rectangle.get_right()[0])
anim_rects[i].shift(
(anim_rects[i].get_width()/2) * RIGHT
)
def get_full_animation(self, anim_rects):
new_anim_rects = VGroup(*[
ar[:-1] for ar in anim_rects
])
coord_left = new_anim_rects.get_corner(UL) + UP
coord_right = new_anim_rects.get_corner(UR) + UP
return Polygon(
coord_left, coord_left + UP,
coord_right + UP, coord_right,
stroke_width=11, fill_opacity=0,
stroke_opacity=1, color=WHITE
) |
AnimationsWithManim_Elteoremadebeethoven/English/8_svgs/8_svgs.py | from big_ol_pile_of_manim_imports import *
class CheckSVG(Scene):
CONFIG={
"camera_config":{"background_color": WHITE},
"svg_type":"svg",
"file":"",
"svg_scale":0.9,
"angle":0,
"flip_svg":False,
"fill_opacity": 1,
"remove": [],
"stroke_color": BLACK,
"fill_color": BLACK,
"stroke_width": 3,
"numbers_scale":0.5,
"show_numbers": False,
"animation": False,
"direction_numbers": UP,
"color_numbers": RED,
"space_between_numbers":0,
"show_elements":[],
"color_element":BLUE,
"set_size":"width",
"remove_stroke":[],
"show_stroke":[],
"stroke_":1
}
def construct(self):
if self.set_size=="width":
width_size=FRAME_WIDTH
height_size=None
else:
width_size=None
height_size=FRAME_HEIGHT
if self.svg_type=="svg":
self.imagen=SVGMobject(
"%s"%self.file,
#fill_opacity = 1,
stroke_width = self.stroke_width,
stroke_color = self.stroke_color,
width=width_size,
height=height_size
).rotate(self.angle).set_fill(self.fill_color,self.fill_opacity).scale(self.svg_scale)
else:
self.imagen=self.import_text().set_fill(self.fill_color,self.fill_opacity).rotate(self.angle).set_stroke(self.stroke_color,self.stroke_width)
if self.set_size=="width":
self.imagen.set_width(FRAME_WIDTH)
else:
self.imagen.set_height(FRAME_HEIGHT)
self.imagen.scale(self.svg_scale)
self.personalize_image()
if self.flip_svg==True:
self.imagen.flip()
if self.show_numbers==True:
self.print_formula(self.imagen,
self.numbers_scale,
self.direction_numbers,
self.remove,
self.space_between_numbers,
self.color_numbers)
self.return_elements(self.imagen,self.show_elements)
for st in self.remove_stroke:
self.imagen[st].set_stroke(None,0)
for st in self.show_stroke:
self.imagen[st].set_stroke(None,self.stroke_)
if self.animation==True:
self.play(DrawBorderThenFill(self.imagen))
else:
self.add(self.imagen)
self.wait()
def import_text(self):
return TexMobject("")
def personalize_image(self):
pass
def print_formula(self,text,inverse_scale,direction,exception,buff,color):
text.set_color(RED)
self.add(text)
c = 0
for j in range(len(text)):
permission_print=True
for w in exception:
if j==w:
permission_print=False
if permission_print:
self.add(text[j].set_color(self.stroke_color))
c = c + 1
c=0
for j in range(len(text)):
permission_print=True
element = TexMobject("%d" %c,color=color)
element.scale(inverse_scale)
element.next_to(text[j],direction,buff=buff)
for w in exception:
if j==w:
permission_print=False
if permission_print:
self.add(element)
c = c + 1
def return_elements(self,formula,adds):
for i in adds:
self.add_foreground_mobjects(formula[i].set_color(self.color_element),
TexMobject("%d"%i,color=self.color_element,background_stroke_width=0).scale(self.numbers_scale).next_to(formula[i],self.direction_numbers,buff=self.space_between_numbers)) |
AnimationsWithManim_Elteoremadebeethoven/English/8_svgs/scenes.md | #
## Programas
###
```python3
````
<p align="center"><img src ="/.gif" /></p>
###
```python3
````
<p align="center"><img src ="/.gif" /></p>
|
AnimationsWithManim_Elteoremadebeethoven/English/6a_plots_2D/change_label_colors.md | # Change labels colors in `GraphScene`
Add this to the `CONFIG` dictionary:
```python
"x_label_color":RED,
"y_label_color":BLUE
```
In the `setup_axes` method change the lines
```python
x_label = TextMobject(self.x_axis_label)
# and
y_label = TextMobject(self.y_axis_label)
```
with
```python
x_label = TextMobject(self.x_axis_label,color=self.x_label_color)
# and
y_label = TextMobject(self.y_axis_label,color=self.y_label_color)
```
Result:
<p align="center"><img src ="/English/6a_plots_2D/gifs/ChanceColorLabels.png" /></p>
|
AnimationsWithManim_Elteoremadebeethoven/English/6a_plots_2D/6a_plots_2D.py | from big_ol_pile_of_manim_imports import *
class PlotGraph(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 20,
"x_max" : 7,
"x_min" : 4,
"y_tick_frequency" : 5,
"x_tick_frequency" : 0.5,
"axes_color" : BLUE,
"y_labeled_nums": range(30,60,10),
"x_labeled_nums": list(np.arange(4, 7.0+0.5, 0.5)),
"x_label_decimal":1,
"graph_origin": 3 * DOWN + 6 * LEFT,
"x_label_direction":DOWN,
"y_label_direction":RIGHT,
"x_axis_label": None,
"x_axis_width":10
}
def construct(self):
self.setup_axes(animate=False) #animate=True to add animation
self.x_axis.shift(LEFT*abs(self.y_axis[0].points[0]-self.x_axis[0].points[0]))
self.y_axis.shift(DOWN*abs(self.y_axis[0].points[0]-self.x_axis[0].points[0]))
self.y_axis_label_mob.next_to(self.y_axis[0].get_end(),UP)
p=Dot().move_to(self.coords_to_point(self.x_min, self.y_min))
self.add(p)
graph = self.get_graph(lambda x : x**2,
color = GREEN,
x_min = 5,
x_max = 7
)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def Range(in_val,end_val,step=1):
return list(np.arange(in_val,end_val+step,step))
class Plot1(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 5,
"x_tick_frequency" : 0.5,
"axes_color" : BLUE,
"y_labeled_nums": range(0,60,10),
"x_labeled_nums": list(np.arange(2, 7.0+0.5, 0.5)),
"x_label_decimal":1,
"y_label_direction": RIGHT,
"x_label_direction": UP,
"y_label_decimal":3
}
def construct(self):
self.setup_axes(animate=True)
graph = self.get_graph(lambda x : x**2,
color = GREEN,
x_min = 2,
x_max = 4
)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
class Plot1v2(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 5,
"x_tick_frequency" : 1,
"axes_color" : BLUE,
"graph_origin" : np.array((0,0,0))
}
def construct(self):
self.setup_axes(animate=True)
graph = self.get_graph(lambda x : x**2,
color = GREEN,
x_min = 2,
x_max = 4
)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
class Plot2(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 5,
"axes_color" : BLUE,
"x_axis_label" : "$t$",
"y_axis_label" : "$f(t)$",
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
# Add this line
GraphScene.setup_axes(self)
# Parametters of labels
# For x
init_label_x = 2
end_label_x = 7
step_x = 1
# For y
init_label_y = 20
end_label_y = 50
step_y = 5
# Position of labels
# For x
self.x_axis.label_direction = DOWN #DOWN is default
# For y
self.y_axis.label_direction = LEFT
# Add labels to graph
# For x
self.x_axis.add_numbers(*range(
init_label_x,
end_label_x+step_x,
step_x
))
# For y
self.y_axis.add_numbers(*range(
init_label_y,
end_label_y+step_y,
step_y
))
# Add Animation
self.play(
ShowCreation(self.x_axis),
ShowCreation(self.y_axis)
)
class Plot3(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 10,
"axes_color" : BLUE,
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
# Custom parametters
self.x_axis.add_numbers(*[0,2,5,4])
# Y parametters
init_label_y = 0
end_label_y = 50
step_y = 5
self.y_axis.label_direction = LEFT
self.y_axis.add_numbers(*range(
init_label_y,
end_label_y+step_y,
step_y
))
self.play(Write(self.x_axis),Write(self.y_axis))
class Plot4(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 10,
"axes_color" : BLUE,
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
self.x_axis.label_direction = UP
self.x_axis.add_numbers(*[3.5,5,4]) # 3.5 is rounded to 4
self.y_axis.label_direction = LEFT
self.y_axis.add_numbers(*range(0, 50+5, 5))
self.play(Write(self.x_axis),Write(self.y_axis))
class Plot5(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 10,
"x_tick_frequency" : 0.5,
"axes_color" : BLUE,
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
self.x_axis.label_direction = UP
values_x = [
(3.5,"3.5"), # (position 3.5, label "3.5")
(4.5,"\\frac{9}{2}") # (position 4.5, label "9/2")
]
self.x_axis_labels = VGroup() # Create a group named x_axis_labels
# pos. tex.
for x_val, x_tex in values_x:
tex = TexMobject(x_tex) # Convert string to tex
tex.scale(0.7)
tex.next_to(self.coords_to_point(x_val, 0), DOWN) #Put tex on the position
self.x_axis_labels.add(tex) #Add tex in graph
self.play(
Write(self.x_axis_labels),
Write(self.x_axis),
Write(self.y_axis)
)
class Plot6(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 10,
"x_tick_frequency" : 0.5,
"axes_color" : BLUE,
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
self.x_axis.label_direction = UP
# List of values of positions
values_decimal_x=[0,0.5,1,1.5,3.35]
# Transform positions to tex labels
list_x = [*["%s"%i for i in values_decimal_x]]
# List touples of (position,label)
values_x = [
(i,j)
for i,j in zip(values_decimal_x,list_x)
]
self.x_axis_labels = VGroup()
for x_val, x_tex in values_x:
tex = TexMobject(x_tex)
tex.scale(0.7)
tex.next_to(self.coords_to_point(x_val, 0), DOWN)
self.x_axis_labels.add(tex)
self.play(
Write(self.x_axis_labels),
Write(self.x_axis),
Write(self.y_axis)
)
class Plot7(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 10,
"x_tick_frequency" : 0.5,
"axes_color" : BLUE,
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
self.x_axis.label_direction = UP
# Additional parametters
init_val_x = 0
step_x = 0.5
end_val_x = 7
# Position of labels
values_decimal_x=Range(init_val_x,end_val_x,step_x)
# List of labels
list_x=[*["%.1f"%i for i in values_decimal_x]]
# List touples of (posición,etiqueta)
values_x = [
(i,j)
for i,j in zip(values_decimal_x,list_x)
]
self.x_axis_labels = VGroup()
for x_val, x_tex in values_x:
tex = TexMobject(x_tex)
tex.scale(0.7)
tex.next_to(self.coords_to_point(x_val, 0), DOWN)
self.x_axis_labels.add(tex)
self.play(
Write(self.x_axis_labels),
Write(self.x_axis),
Write(self.y_axis)
)
class PlotSinCos(GraphScene):
CONFIG = {
"y_max" : 1.5,
"y_min" : -1.5,
"x_max" : 3*PI/2,
"x_min" : -3*PI/2,
"y_tick_frequency" : 0.5,
"x_tick_frequency" : PI/2,
"graph_origin" : ORIGIN,
"y_axis_label": None, # Don't write y axis label
"x_axis_label": None,
}
def construct(self):
self.setup_axes()
plotSin = self.get_graph(lambda x : np.sin(x),
color = GREEN,
x_min=-4,
x_max=4,
)
plotCos = self.get_graph(lambda x : np.cos(x),
color = GRAY,
x_min=-PI,
x_max=0,
)
plotSin.set_stroke(width=3) # width of line
plotCos.set_stroke(width=2)
# Animation
for plot in (plotSin,plotCos):
self.play(
ShowCreation(plot),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
# width of edges
self.x_axis.set_stroke(width=2)
self.y_axis.set_stroke(width=2)
# color of edges
self.x_axis.set_color(RED)
self.y_axis.set_color(YELLOW)
# Add x,y labels
func = TexMobject("\\sin\\theta")
var = TexMobject("\\theta")
func.set_color(BLUE)
var.set_color(PURPLE)
func.next_to(self.y_axis,UP)
var.next_to(self.x_axis,RIGHT+UP)
# Y labels
self.y_axis.label_direction = LEFT*1.5
self.y_axis.add_numbers(*[-1,1])
#Parametters of x labels
init_val_x = -3*PI/2
step_x = PI/2
end_val_x = 3*PI/2
# List of the positions of x labels
values_decimal_x=Range(init_val_x,end_val_x,step_x)
# List of tex objects
list_x=TexMobject("-\\frac{3\\pi}{2}", # -3pi/2
"-\\pi", # -pi
"-\\frac{\\pi}{2}", # -pi/2
"\\,", # 0 (space)
"\\frac{\\pi}{2}", # pi/2
"\\pi",# pi
"\\frac{3\\pi}{2}" # 3pi/2
)
#List touples (position,label)
values_x = [(i,j)
for i,j in zip(values_decimal_x,list_x)
]
self.x_axis_labels = VGroup()
for x_val, x_tex in values_x:
x_tex.scale(0.7)
if x_val == -PI or x_val == PI: #if x is equals -pi or pi
x_tex.next_to(self.coords_to_point(x_val, 0), 2*DOWN) #Put 2*Down
else: # In another case
x_tex.next_to(self.coords_to_point(x_val, 0), DOWN)
self.x_axis_labels.add(x_tex)
self.play(
*[Write(objeto)
for objeto in [
self.y_axis,
self.x_axis,
self.x_axis_labels,
func,var
]
],
run_time=2
) |
AnimationsWithManim_Elteoremadebeethoven/English/6a_plots_2D/scenes.md | # Function `Range`
We define a function named Range:
```python3
def Range(in_val,end_val,step=1):
return list(np.arange(in_val,end_val+step,step))
```
With this function, if we write this:
```python3
Range(1,3,0.2)
```
return:
```
[1,1.2,1.4,1.6,1.8,2,2.2,2.4,2.6,2.8,3]
```
# Programs
```python3
class Plot1(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 5,
"x_tick_frequency" : 0.5,
"axes_color" : BLUE,
"y_labeled_nums": range(0,60,10),
"x_labeled_nums": list(np.arange(2, 7.0+0.5, 0.5)),
"x_label_decimal":1,
"y_label_direction": RIGHT,
"x_label_direction": UP,
"y_label_decimal":3
}
def construct(self):
self.setup_axes(animate=True)
graph = self.get_graph(lambda x : x**2,
color = GREEN,
x_min = 2,
x_max = 4
)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
```
<p align="center"><img src ="/English/6a_plots_2D/gifs/Plot1.gif" /></p>
```python3
class Plot1v2(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 5,
"x_tick_frequency" : 1,
"axes_color" : BLUE,
"graph_origin" : np.array((0,0,0))
}
def construct(self):
self.setup_axes(animate=True)
graph = self.get_graph(lambda x : x**2,
color = GREEN,
x_min = 2,
x_max = 4
)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
```
<p align="center"><img src ="/English/6a_plots_2D/gifs/Plot1v2.gif" /></p>
```python3
class Plot2(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 5,
"axes_color" : BLUE,
"x_axis_label" : "$t$",
"y_axis_label" : "$f(t)$",
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
# Add this line
GraphScene.setup_axes(self)
# Parametters of labels
# For x
init_label_x = 2
end_label_x = 7
step_x = 1
# For y
init_label_y = 20
end_label_y = 50
step_y = 5
# Position of labels
# For x
self.x_axis.label_direction = DOWN #DOWN is default
# For y
self.y_axis.label_direction = LEFT
# Add labels to graph
# For x
self.x_axis.add_numbers(*range(
init_label_x,
end_label_x+step_x,
step_x
))
# For y
self.y_axis.add_numbers(*range(
init_label_y,
end_label_y+step_y,
step_y
))
# Add Animation
self.play(
ShowCreation(self.x_axis),
ShowCreation(self.y_axis)
)
```
<p align="center"><img src ="/English/6a_plots_2D/gifs/Plot2.gif" /></p>
```python3
class Plot3(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 10,
"axes_color" : BLUE,
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
# Custom parametters
self.x_axis.add_numbers(*[0,2,5,4])
# Y parametters
init_label_y = 0
end_label_y = 50
step_y = 5
self.y_axis.label_direction = LEFT
self.y_axis.add_numbers(*range(
init_label_y,
end_label_y+step_y,
step_y
))
self.play(Write(self.x_axis),Write(self.y_axis))
```
<p align="center"><img src ="/English/6a_plots_2D/gifs/Plot3.gif" /></p>
```python3
class Plot4(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 10,
"axes_color" : BLUE,
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
self.x_axis.label_direction = UP
self.x_axis.add_numbers(*[3.5,5,4]) # 3.5 is rounded to 4
self.y_axis.label_direction = LEFT
self.y_axis.add_numbers(*range(0, 50+5, 5))
self.play(Write(self.x_axis),Write(self.y_axis))
```
<p align="center"><img src ="/English/6a_plots_2D/gifs/Plot4.gif" /></p>
```python3
class Plot5(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 10,
"x_tick_frequency" : 0.5,
"axes_color" : BLUE,
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
self.x_axis.label_direction = UP
values_x = [
(3.5,"3.5"), # (position 3.5, label "3.5")
(4.5,"\\frac{9}{2}") # (position 4.5, label "9/2")
]
self.x_axis_labels = VGroup() # Create a group named x_axis_labels
# pos. tex.
for x_val, x_tex in values_x:
tex = TexMobject(x_tex) # Convert string to tex
tex.scale(0.7)
tex.next_to(self.coords_to_point(x_val, 0), DOWN) #Put tex on the position
self.x_axis_labels.add(tex) #Add tex in graph
self.play(
Write(self.x_axis_labels),
Write(self.x_axis),
Write(self.y_axis)
)
```
<p align="center"><img src ="/English/6a_plots_2D/gifs/Plot5.gif" /></p>
```python3
class Plot6(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 10,
"x_tick_frequency" : 0.5,
"axes_color" : BLUE,
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
self.x_axis.label_direction = UP
# List of values of positions
values_decimal_x=[0,0.5,1,1.5,3.35]
# Transform positions to tex labels
list_x = [*["%s"%i for i in values_decimal_x]]
# List touples of (position,label)
values_x = [
(i,j)
for i,j in zip(values_decimal_x,list_x)
]
self.x_axis_labels = VGroup()
for x_val, x_tex in values_x:
tex = TexMobject(x_tex)
tex.scale(0.7)
tex.next_to(self.coords_to_point(x_val, 0), DOWN)
self.x_axis_labels.add(tex)
self.play(
Write(self.x_axis_labels),
Write(self.x_axis),
Write(self.y_axis)
)
```
<p align="center"><img src ="/English/6a_plots_2D/gifs/Plot6.gif" /></p>
```python3
class Plot7(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 10,
"x_tick_frequency" : 0.5,
"axes_color" : BLUE,
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
self.x_axis.label_direction = UP
# Additional parametters
init_val_x = 0
step_x = 0.5
end_val_x = 7
# Position of labels
values_decimal_x=Range(init_val_x,end_val_x,step_x)
# List of labels
list_x=[*["%.1f"%i for i in values_decimal_x]]
# List touples of (posición,etiqueta)
values_x = [
(i,j)
for i,j in zip(values_decimal_x,list_x)
]
self.x_axis_labels = VGroup()
for x_val, x_tex in values_x:
tex = TexMobject(x_tex)
tex.scale(0.7)
tex.next_to(self.coords_to_point(x_val, 0), DOWN)
self.x_axis_labels.add(tex)
self.play(
Write(self.x_axis_labels),
Write(self.x_axis),
Write(self.y_axis)
)
```
<p align="center"><img src ="/English/6a_plots_2D/gifs/Plot7.gif" /></p>
```python3
class PlotSinCos(GraphScene):
CONFIG = {
"y_max" : 1.5,
"y_min" : -1.5,
"x_max" : 3*PI/2,
"x_min" : -3*PI/2,
"y_tick_frequency" : 0.5,
"x_tick_frequency" : PI/2,
"graph_origin" : ORIGIN,
"y_axis_label": None, # Don't write y axis label
"x_axis_label": None,
}
def construct(self):
self.setup_axes()
plotSin = self.get_graph(lambda x : np.sin(x),
color = GREEN,
x_min=-4,
x_max=4,
)
plotCos = self.get_graph(lambda x : np.cos(x),
color = GRAY,
x_min=-PI,
x_max=0,
)
plotSin.set_stroke(width=3) # width of line
plotCos.set_stroke(width=2)
# Animation
for plot in (plotSin,plotCos):
self.play(
ShowCreation(plot),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
# width of edges
self.x_axis.set_stroke(width=2)
self.y_axis.set_stroke(width=2)
# color of edges
self.x_axis.set_color(RED)
self.y_axis.set_color(YELLOW)
# Add x,y labels
func = TexMobject("\\sin\\theta")
var = TexMobject("\\theta")
func.set_color(BLUE)
var.set_color(PURPLE)
func.next_to(self.y_axis,UP)
var.next_to(self.x_axis,RIGHT+UP)
# Y labels
self.y_axis.label_direction = LEFT*1.5
self.y_axis.add_numbers(*[-1,1])
#Parametters of x labels
init_val_x = -3*PI/2
step_x = PI/2
end_val_x = 3*PI/2
# List of the positions of x labels
values_decimal_x=Range(init_val_x,end_val_x,step_x)
# List of tex objects
list_x=TexMobject("-\\frac{3\\pi}{2}", # -3pi/2
"-\\pi", # -pi
"-\\frac{\\pi}{2}", # -pi/2
"\\,", # 0 (space)
"\\frac{\\pi}{2}", # pi/2
"\\pi",# pi
"\\frac{3\\pi}{2}" # 3pi/2
)
#List touples (position,label)
values_x = [(i,j)
for i,j in zip(values_decimal_x,list_x)
]
self.x_axis_labels = VGroup()
for x_val, x_tex in values_x:
x_tex.scale(0.7)
if x_val == -PI or x_val == PI: #if x is equals -pi or pi
x_tex.next_to(self.coords_to_point(x_val, 0), 2*DOWN) #Put 2*Down
else: # In another case
x_tex.next_to(self.coords_to_point(x_val, 0), DOWN)
self.x_axis_labels.add(x_tex)
self.play(
*[Write(objeto)
for objeto in [
self.y_axis,
self.x_axis,
self.x_axis_labels,
func,var
]
],
run_time=2
)
```
<p align="center"><img src ="/English/6a_plots_2D/gifs/PlotSinCos.gif" /></p>
```python3
class PlotGraph(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 20,
"x_max" : 7,
"x_min" : 4,
"y_tick_frequency" : 5,
"x_tick_frequency" : 0.5,
"axes_color" : BLUE,
"y_labeled_nums": range(30,60,10),
"x_labeled_nums": list(np.arange(4, 7.0+0.5, 0.5)),
"x_label_decimal":1,
"graph_origin": 3 * DOWN + 6 * LEFT,
"x_label_direction":DOWN,
"y_label_direction":RIGHT,
"x_axis_label": None,
"x_axis_width":10
}
def construct(self):
self.setup_axes(animate=False) #animate=True to add animation
self.x_axis.shift(LEFT*abs(self.y_axis[0].points[0]-self.x_axis[0].points[0]))
self.y_axis.shift(DOWN*abs(self.y_axis[0].points[0]-self.x_axis[0].points[0]))
self.y_axis_label_mob.next_to(self.y_axis[0].get_end(),UP)
p=Dot().move_to(self.coords_to_point(self.x_min, self.y_min))
self.add(p)
graph = self.get_graph(lambda x : x**2,
color = GREEN,
x_min = 5,
x_max = 7
)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
```
<p align="center"><img src ="/English/6a_plots_2D/gifs/PlotGraph.gif" /></p>
|
AnimationsWithManim_Elteoremadebeethoven/English/1_text_formats/text_formats.py | from big_ol_pile_of_manim_imports import *
class WriteText(Scene):
def construct(self):
text = TextMobject("This is a regular text")
self.play(Write(text))
self.wait(3)
class AddText(Scene):
def construct(self):
text = TextMobject("This is a regular text")
self.add(text)
self.wait(3)
class Formula(Scene):
def construct(self):
formula = TexMobject("This is a formula")
self.play(Write(formula))
self.wait(3)
class TipesOfText(Scene):
def construct(self):
typesOfText = TextMobject("""
This is a regular text,
$this is a formula$,
$$this is a formula$$
""")
self.play(Write(typesOfText))
self.wait(3)
class TipesOfText2(Scene):
def construct(self):
typesOfText = TextMobject("""
This is a regular text,
$\\frac{x}{y}$,
$$x^2+y^2=a^2$$
""")
self.play(Write(typesOfText))
self.wait(3)
class DisplayFormula(Scene):
def construct(self):
typesOfText = TextMobject("""
This is a regular text,
$\\displaystyle\\frac{x}{y}$,
$$x^2+y^2=a^2$$
""")
self.play(Write(typesOfText))
self.wait(3)
class TextInCenter(Scene):
def construct(self):
text = TextMobject("Text")
self.play(Write(text))
self.wait(3)
class TextOnTopEdge(Scene):
def construct(self):
text = TextMobject("Text")
text.to_edge(UP)
self.play(Write(text))
self.wait(3)
class TextOnBottomEdge(Scene):
def construct(self):
text = TextMobject("Text")
text.to_edge(DOWN)
self.play(Write(text))
self.wait(3)
class TextOnRightEdge(Scene):
def construct(self):
text = TextMobject("Text")
text.to_edge(RIGHT)
self.play(Write(text))
self.wait(3)
class TextOnLeftEdge(Scene):
def construct(self):
text = TextMobject("Text")
text.to_edge(LEFT)
self.play(Write(text))
self.wait(3)
class TextInUpperRightCorner(Scene):
def construct(self):
text = TextMobject("Text")
text.to_edge(UP+RIGHT)
self.play(Write(text))
self.wait(3)
class TextInLowerLeftCorner(Scene):
def construct(self):
text = TextMobject("Text")
text.to_edge(LEFT+DOWN)
self.play(Write(text))
self.wait(3)
class CustomPosition1(Scene):
def construct(self):
textM = TextMobject("Text")
textC = TextMobject("Central text")
textM.move_to(0.25*UP)
self.play(Write(textM),Write(textC))
self.wait(3)
class CustomPosition2(Scene):
def construct(self):
textM = TextMobject("Text")
textC = TextMobject("Central text")
textM.move_to(1*UP+1*RIGHT)
self.play(Write(textM),Write(textC))
self.wait(1)
textM.move_to(1*UP+1*RIGHT)
self.play(Write(textM))
self.wait(3)
class RelativePosition1(Scene):
def construct(self):
textM = TextMobject("Text")
textC = TextMobject("Reference text")
textM.next_to(textC,LEFT,buff=1)
self.play(Write(textM),Write(textC))
self.wait(3)
class RelativePosition2(Scene):
def construct(self):
textM = TextMobject("Text")
textC = TextMobject("Reference text")
textM.shift(UP*0.1)
self.play(Write(textM),Write(textC))
self.wait(3)
class RotateObject(Scene):
def construct(self):
textM = TextMobject("Text")
textC = TextMobject("Reference text")
textM.shift(UP)
textM.rotate(PI/4)
self.play(Write(textM),Write(textC))
self.wait(2)
textM.rotate(PI/4)
self.wait(2)
textM.rotate(PI/4)
self.wait(2)
textM.rotate(PI/4)
self.wait(2)
textM.rotate(PI)
self.wait(2)
class MirrorObject(Scene):
def construct(self):
textM = TextMobject("Text")
textM.flip(UP)
self.play(Write(textM))
self.wait(2)
class SizeTextOnLaTeX(Scene):
def construct(self):
textHuge = TextMobject("{\\Huge Huge Text 012.\\#!?} Text")
texthuge = TextMobject("{\\huge huge Text 012.\\#!?} Text")
textLARGE = TextMobject("{\\LARGE LARGE Text 012.\\#!?} Text")
textLarge = TextMobject("{\\Large Large Text 012.\\#!?} Text")
textlarge = TextMobject("{\\large large Text 012.\\#!?} Text")
textNormal = TextMobject("{\\normalsize normal Text 012.\\#!?} Text")
textsmall = TextMobject("{\\small small Text 012.\\#!?} Texto normal")
textfootnotesize = TextMobject("{\\footnotesize footnotesize Text 012.\\#!?} Text")
textscriptsize = TextMobject("{\\scriptsize scriptsize Text 012.\\#!?} Text")
texttiny = TextMobject("{\\tiny tiny Texto 012.\\#!?} Text normal")
textHuge.to_edge(UP)
texthuge.next_to(textHuge,DOWN,buff=0.1)
textLARGE.next_to(texthuge,DOWN,buff=0.1)
textLarge.next_to(textLARGE,DOWN,buff=0.1)
textlarge.next_to(textLarge,DOWN,buff=0.1)
textNormal.next_to(textlarge,DOWN,buff=0.1)
textsmall.next_to(textNormal,DOWN,buff=0.1)
textfootnotesize.next_to(textsmall,DOWN,buff=0.1)
textscriptsize.next_to(textfootnotesize,DOWN,buff=0.1)
texttiny.next_to(textscriptsize,DOWN,buff=0.1)
self.add(textHuge,texthuge,textLARGE,textLarge,textlarge,textNormal,textsmall,textfootnotesize,textscriptsize,texttiny)
self.wait(3)
class TextFonts(Scene):
def construct(self):
textNormal = TextMobject("{Roman serif text 012.\\#!?} Text")
textItalic = TextMobject("\\textit{Italic text 012.\\#!?} Text")
textTypewriter = TextMobject("\\texttt{Typewritter text 012.\\#!?} Text")
textBold = TextMobject("\\textbf{Bold text 012.\\#!?} Text")
textSL = TextMobject("\\textsl{Slanted text 012.\\#!?} Text")
textSC = TextMobject("\\textsc{Small caps text 012.\\#!?} Text")
textNormal.to_edge(UP)
textItalic.next_to(textNormal,DOWN,buff=.5)
textTypewriter.next_to(textItalic,DOWN,buff=.5)
textBold.next_to(textTypewriter,DOWN,buff=.5)
textSL.next_to(textBold,DOWN,buff=.5)
textSC.next_to(textSL,DOWN,buff=.5)
self.add(textNormal,textItalic,textTypewriter,textBold,textSL,textSC)
self.wait(3)
|
AnimationsWithManim_Elteoremadebeethoven/English/1_text_formats/scenes.md | # Text format
Remember: You have to add this line to include all packages of manim.
```python3
from big_ol_pile_of_manim_imports import *
```
In the first line.
## Programs
```python3
class WriteText(Scene):
def construct(self):
text = TextMobject("This is a regular text")
self.play(Write(text))
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/WriteText.gif" /></p>
```python3
class AddText(Scene):
def construct(self):
text = TextMobject("This is a regular text")
self.add(text)
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/AddText.gif" /></p>
```python3
class Formula(Scene):
def construct(self):
formula = TexMobject("This is a formula")
self.play(Write(formula))
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/Formula.gif" /></p>
```python3
class TypesOfText(Scene):
def construct(self):
typesOfText = TextMobject("""
This is a regular text,
$this is a formula$,
$$this is a formula$$
""")
self.play(Write(typesOfText))
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/TipesOfText.gif" /></p>
```python3
class TypesOfText2(Scene):
def construct(self):
typesOfText = TextMobject("""
This is a regular text,
$\\frac{x}{y}$,
$$x^2+y^2=a^2$$
""")
self.play(Write(typesOfText))
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/TipesOfText2.gif" /></p>
```python3
class DisplayFormula(Scene):
def construct(self):
typesOfText = TextMobject("""
This is a regular text,
$\\displaystyle\\frac{x}{y}$,
$$x^2+y^2=a^2$$
""")
self.play(Write(typesOfText))
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/DisplayFormula.gif" /></p>
```python3
class TextInCenter(Scene):
def construct(self):
text = TextMobject("Text")
self.play(Write(text))
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/TextInCenter.gif" /></p>
```python3
class TextOnTopEdge(Scene):
def construct(self):
text = TextMobject("Text")
text.to_edge(UP)
self.play(Write(text))
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/TextOnTopEdge.gif" /></p>
```python3
class TextOnBottomEdge(Scene):
def construct(self):
text = TextMobject("Text")
text.to_edge(DOWN)
self.play(Write(text))
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/TextOnBottomEdge.gif" /></p>
```python3
class TextOnRightEdge(Scene):
def construct(self):
text = TextMobject("Text")
text.to_edge(RIGHT)
self.play(Write(text))
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/TextOnRightEdge.gif" /></p>
```python3
class TextOnLeftEdge(Scene):
def construct(self):
text = TextMobject("Text")
text.to_edge(LEFT)
self.play(Write(text))
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/TextOnLeftEdge.gif" /></p>
```python3
class TextInUpperRightCorner(Scene):
def construct(self):
text = TextMobject("Text")
text.to_edge(UP+RIGHT)
self.play(Write(text))
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/TextInUpperRightCorner.gif" /></p>
```python3
class TextInLowerLeftCorner(Scene):
def construct(self):
text = TextMobject("Text")
text.to_edge(LEFT+DOWN)
self.play(Write(text))
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/TextInLowerLeftCorner.gif" /></p>
```python3
class CustomPosition1(Scene):
def construct(self):
textM = TextMobject("Text")
textC = TextMobject("Central text")
textM.move_to(0.25*UP)
self.play(Write(textM),Write(textC))
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/CustomPosition1.gif" /></p>
```python3
class CustomPosition2(Scene):
def construct(self):
textM = TextMobject("Text")
textC = TextMobject("Central text")
textM.move_to(1*UP+1*RIGHT)
self.play(Write(textM),Write(textC))
self.wait(1)
textM.move_to(1*UP+1*RIGHT)
self.play(Write(textM))
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/CustomPosition2.gif" /></p>
```python3
class RelativePosition1(Scene):
def construct(self):
textM = TextMobject("Text")
textC = TextMobject("Reference text")
textM.next_to(textC,LEFT,buff=1)
self.play(Write(textM),Write(textC))
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/RelativePosition1.gif" /></p>
```python3
class RelativePosition2(Scene):
def construct(self):
textM = TextMobject("Text")
textC = TextMobject("Reference text")
textM.shift(UP*0.1)
self.play(Write(textM),Write(textC))
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/RelativePosition2.gif" /></p>
```python3
class RotateObject(Scene):
def construct(self):
textM = TextMobject("Text")
textC = TextMobject("Reference text")
textM.shift(UP)
textM.rotate(PI/4) # <- Radians
# You can use .rotate(45*DEGREES) too
self.play(Write(textM),Write(textC))
self.wait(2)
textM.rotate(PI/4)
self.wait(2)
textM.rotate(PI/4)
self.wait(2)
textM.rotate(PI/4)
self.wait(2)
textM.rotate(PI)
self.wait(2)
```
<p align="center"><img src ="/English/1_text_formats/gifs/RotateObject.gif" /></p>
```python3
class FlipObject(Scene):
def construct(self):
textM = TextMobject("Text")
textM.flip(UP)
self.play(Write(textM))
self.wait(2)
```
<p align="center"><img src ="/English/1_text_formats/gifs/MirrorObject.gif" /></p>
```python3
class SizeTextOnLaTeX(Scene):
def construct(self):
textHuge = TextMobject("{\\Huge Huge Text 012.\\#!?} Text")
texthuge = TextMobject("{\\huge huge Text 012.\\#!?} Text")
textLARGE = TextMobject("{\\LARGE LARGE Text 012.\\#!?} Text")
textLarge = TextMobject("{\\Large Large Text 012.\\#!?} Text")
textlarge = TextMobject("{\\large large Text 012.\\#!?} Text")
textNormal = TextMobject("{\\normalsize normal Text 012.\\#!?} Text")
textsmall = TextMobject("{\\small small Text 012.\\#!?} Texto normal")
textfootnotesize = TextMobject("{\\footnotesize footnotesize Text 012.\\#!?} Text")
textscriptsize = TextMobject("{\\scriptsize scriptsize Text 012.\\#!?} Text")
texttiny = TextMobject("{\\tiny tiny Texto 012.\\#!?} Text normal")
textHuge.to_edge(UP)
texthuge.next_to(textHuge,DOWN,buff=0.1)
textLARGE.next_to(texthuge,DOWN,buff=0.1)
textLarge.next_to(textLARGE,DOWN,buff=0.1)
textlarge.next_to(textLarge,DOWN,buff=0.1)
textNormal.next_to(textlarge,DOWN,buff=0.1)
textsmall.next_to(textNormal,DOWN,buff=0.1)
textfootnotesize.next_to(textsmall,DOWN,buff=0.1)
textscriptsize.next_to(textfootnotesize,DOWN,buff=0.1)
texttiny.next_to(textscriptsize,DOWN,buff=0.1)
self.add(textHuge,texthuge,textLARGE,textLarge,textlarge,textNormal,textsmall,textfootnotesize,textscriptsize,texttiny)
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/SizeTextOnLaTeX.gif" /></p>
```python3
class TextFonts(Scene):
def construct(self):
textNormal = TextMobject("\\textrm{Roman serif text 012.\\#!?} Text")
textItalic = TextMobject("\\textit{Italic text 012.\\#!?} Text")
textTypewriter = TextMobject("\\texttt{Typewritter text 012.\\#!?} Text")
textBold = TextMobject("\\textbf{Bold text 012.\\#!?} Text")
textSL = TextMobject("\\textsl{Slanted text 012.\\#!?} Text")
textSC = TextMobject("\\textsc{Small caps text 012.\\#!?} Text")
textNormal.to_edge(UP)
textItalic.next_to(textNormal,DOWN,buff=.5)
textTypewriter.next_to(textItalic,DOWN,buff=.5)
textBold.next_to(textTypewriter,DOWN,buff=.5)
textSL.next_to(textBold,DOWN,buff=.5)
textSC.next_to(textSL,DOWN,buff=.5)
self.add(textNormal,textItalic,textTypewriter,textBold,textSL,textSC)
self.wait(3)
```
<p align="center"><img src ="/English/1_text_formats/gifs/TextFonts.gif" /></p>
|
AnimationsWithManim_Elteoremadebeethoven/English/7_add_audio/7_add_files.py | class AudioTest(Scene):
def construct(self):
group_dots=VGroup(*[Dot()for _ in range(3)])
group_dots.arrange_submobjects(RIGHT)
for dot in group_dots:
self.add_sound("click",gain=-10)
self.add(dot)
self.wait()
self.wait()
class SVGTest(Scene):
def construct(self):
svg = SVGMobject("finger")
#svg = SVGMobject("camera")
self.play(DrawBorderThenFill(svg,rate_func=linear))
self.wait()
class ImageTest(Scene):
def construct(self):
image = ImageMobject("note")
self.play(FadeIn(image))
self.wait()
|
AnimationsWithManim_Elteoremadebeethoven/English/7_add_audio/scenes.md | #
## Programas
###
```python3
````
<p align="center"><img src ="/.gif" /></p>
###
```python3
````
<p align="center"><img src ="/.gif" /></p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.