Hebtollah's picture
Update Nmath.py
1a12593 verified
Raw History Blame Contribute Delete
9.59 kB
from manim import (
Axes, Tex, MathTex, Integer, DecimalNumber, VGroup, Line, TexTemplate,
WHITE, UP, DOWN, LEFT, RIGHT, config,
)
import numpy as np
class NAxes(Axes):
MARGIN = 1 # data-units of blank space added at each end (the "+2" in the length formula)
# Latin -> Arabic-Indic digit map
_AR_DIGITS = {
'0': '٠', '1': '١', '2': '٢', '3': '٣', '4': '٤',
'5': '٥', '6': '٦', '7': '٧', '8': '٨', '9': '٩',
}
def __init__(
self,
x_range,
y_range,
axes_color: str = WHITE,
numbers_color: str = WHITE,
lang: str = "en",
frame_padding: float = 1.0, # NEW: space (in scene units) to leave at each edge of the frame
**kwargs,
):
kwargs.pop("x_length", None)
kwargs.pop("y_length", None)
assert lang in ("en", "ar"), 'lang must be "en" or "ar"'
self.lang = lang
x_start, x_end = x_range[0], x_range[1]
y_start, y_end = y_range[0], y_range[1]
x_step = x_range[2] if len(x_range) > 2 else 1
y_step = y_range[2] if len(y_range) > 2 else 1
# --- Strict length formula: length = |start| + |end| + 2 -----------
x_length = abs(x_start) + abs(x_end) + 2
y_length = abs(y_start) + abs(y_end) + 2
# --- Smart fit: shrink (never grow) so the axes stay inside the ----
# --- visible scene frame, leaving `frame_padding` of breathing room --
max_x_length = max(config.frame_width - 2 * frame_padding, 1e-3)
max_y_length = max(config.frame_height - 2 * frame_padding, 1e-3)
if x_length > max_x_length or y_length > max_y_length:
scale_factor = min(max_x_length / x_length, max_y_length / y_length)
x_length *= scale_factor
y_length *= scale_factor
self.axes_color = axes_color
self.numbers_color = numbers_color
# --- Arabic TeX template (only built when needed) -------------------
if self.lang == "ar":
self.ar_template = TexTemplate()
self.ar_template.tex_compiler = "xelatex"
self.ar_template.output_format = ".pdf"
self.ar_template.add_to_preamble(r"""
\usepackage{amsmath,amsfonts,amssymb,mathrsfs,tikz,fancyhdr}
\usepackage{fontspec}
\usepackage{unicode-math}
\usepackage{polyglossia}
\usepackage{bidi}
\setdefaultlanguage[calendar=gregorian]{arabic}
\setmainfont[Script=Arabic,Mapping=arabicdigits]{Amiri}
\newcommand{\seen}{\mbox{\fontspec{Amiri}[Script=Arabic]س}}
\newcommand{\sad}{\mbox{\fontspec{Amiri}[Script=Arabic]ص}}
\newcommand{\ain}{\mbox{\fontspec{Amiri}[Script=Arabic]ع}}
""")
# --- Build the underlying axis lines over an EXTENDED range ---------
m = self.MARGIN
x_range_extended = [x_start - m, x_end + m, x_step]
y_range_extended = [y_start - m, y_end + m, y_step]
super().__init__(
x_range=x_range_extended,
y_range=y_range_extended,
x_length=x_length,
y_length=y_length,
tips=True,
axis_config={
"color": axes_color,
"include_tip": True,
"tip_width": 0.2,
"tip_height": 0.2,
"stroke_width": 2,
"include_numbers": False,
"include_ticks": False,
},
**kwargs,
)
self.x_range = np.array([x_start, x_end, x_step])
self.y_range = np.array([y_start, y_end, y_step])
# --- Double-ended arrows --------------------------------------------
self.x_axis.add_tip(at_start=True)
self.y_axis.add_tip(at_start=True)
self.x_axis.set_color(axes_color)
self.y_axis.set_color(axes_color)
# --- Ticks (dashes) + numbers, perfectly aligned ---------------------
self.ticks = VGroup()
self.numbers = VGroup()
self._add_axis_ticks_and_numbers(
axis=self.x_axis,
values=np.arange(x_start, x_end + x_step / 2, x_step),
tick_vector=UP * 0.08,
number_direction=DOWN,
align="x",
)
self._add_axis_ticks_and_numbers(
axis=self.y_axis,
values=np.arange(y_start, y_end + y_step / 2, y_step),
tick_vector=RIGHT * 0.08,
number_direction=LEFT,
align="y",
)
self.add(self.ticks, self.numbers)
# --- "x" / "y" (or س / ص) labels just past the arrow tips ------------
if self.lang == "en":
x_label = MathTex("x", color=axes_color)
y_label = MathTex("y", color=axes_color)
else: # "ar"
x_label = Tex(r"\seen", tex_template=self.ar_template, color=axes_color)
y_label = Tex(r"\sad", tex_template=self.ar_template, color=axes_color)
x_label.next_to(self.x_axis.get_end(), RIGHT, buff=0.2)
y_label.next_to(self.y_axis.get_end(), UP, buff=0.2)
self.axis_labels = VGroup(x_label, y_label)
self.add(self.axis_labels)
def _to_arabic_number(self, num):
"""Convert a number to Arabic-Indic digits; negative sign goes AFTER
the digits (renders on the left in RTL context), per the given convention."""
if float(num).is_integer():
s = str(abs(int(num)))
else:
s = f"{abs(num):.1f}"
converted = ''.join(self._AR_DIGITS.get(c, c) for c in s)
return '-' + converted if num < 0 else converted
def _make_number_label(self, v):
"""Return the Mobject used for a single tick's number, per self.lang."""
if self.lang == "en":
label = Integer(int(v)) if float(v).is_integer() else DecimalNumber(v, num_decimal_places=1)
label.set_color(self.numbers_color)
else: # "ar"
label = Tex(self._to_arabic_number(v), tex_template=self.ar_template, color=self.numbers_color)
label.scale(0.6)
return label
def _add_axis_ticks_and_numbers(self, axis, values, tick_vector, number_direction, align):
for v in values:
if np.isclose(v, 0):
continue # skip the origin on both axes
point = axis.number_to_point(v)
tick = Line(point - tick_vector, point + tick_vector, color=self.axes_color)
tick.set_stroke(width=3)
self.ticks.add(tick)
label = self._make_number_label(v)
label.next_to(tick, number_direction, buff=0.15)
if align == "x":
label.set_x(point[0])
else:
label.set_y(point[1])
self.numbers.add(label)
class ArTex(Tex):
"""
Subclass of manim's built-in Tex that supports a `tex_type` kwarg.
When tex_type="ar", the order of the glyph submobjects is reversed
(recursively, at every level of the submobject hierarchy) so that
Write() and other animations relying on submobject index order
draw the text in the correct right-to-left order for Arabic text.
"""
def __init__(
self,
*tex_strings,
tex_type: str = "en",
line_stroke_width: float = 3.0,
scale_factor: float = 1.3, # ← Added default scale factor here
**kwargs
):
self.tex_type = tex_type
self.line_stroke_width = line_stroke_width
super().__init__(*tex_strings, **kwargs)
if self.tex_type == "ar":
self._reverse_submobjects_for_rtl()
# Synchronize stroke and fill colors safely
self._sync_stroke_and_fill()
# Automatically apply the default sizing scale
if scale_factor != 1.0:
self.scale(scale_factor)
def _reverse_submobjects_for_rtl(self):
"""
Reverse the order of submobjects, recursively, at every level
of the hierarchy, so that draw order matches RTL writing order.
"""
def reverse_recursive(mobject):
if mobject.submobjects:
mobject.submobjects = list(reversed(mobject.submobjects))
for sub in mobject.submobjects:
reverse_recursive(sub)
reverse_recursive(self)
def _sync_stroke_and_fill(self):
"""
Recursively ensures that all glyphs have matching fill and stroke colors.
Applies a custom line weight to flat paths/horizontal lines.
"""
def process_mobject(mobject):
if mobject.submobjects:
for sub in mobject.submobjects:
process_mobject(sub)
else:
if isinstance(mobject, VMobject):
# Fetch the true overarching color assigned to the mobject
chosen_color = mobject.get_color()
# Using a 0.05 threshold safely catches flat lines and fraction bars.
if mobject.get_height() < 0.05:
# It's a line/fraction bar: apply the custom thicker stroke width
mobject.set_stroke(
color=chosen_color,
width=self.line_stroke_width
)
mobject.set_fill(color=chosen_color, opacity=0.0)
else:
# Normal glyph: Unify colors, convert stroke to fill, drop outline thickness
mobject.set_fill(color=chosen_color, opacity=1.0)
mobject.set_stroke(color=chosen_color, width=0)
process_mobject(self)