A comprehensive Python library for programmatically creating and compiling LaTeX documents and snippets.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Mathematical typesetting with equations, matrices, aligned environments, and vector notation. PyLaTeX provides comprehensive support for LaTeX's mathematical capabilities, enabling the creation of complex equations, matrices, and mathematical symbols with proper formatting.
The Math class provides the foundation for mathematical expressions, supporting both inline and display math modes.
class Math(Container):
def __init__(self, *, inline=False, data=None, escape=None):
"""
Create a math environment for equations.
Parameters:
- inline: bool, if True creates inline math ($...$), if False creates display math (\\[...\\])
- data: list or str, initial mathematical content
- escape: bool, whether to escape special characters (usually False for math)
Requires:
- amsmath package (automatically added)
"""Usage example:
from pylatex import Document, Section
from pylatex.math import Math
doc = Document()
with doc.create(Section('Mathematical Expressions')):
# Display math (block)
with doc.create(Math()) as math:
math.append(r'E = mc^2')
# Inline math
doc.append('The famous equation ')
doc.append(Math(data=r'E = mc^2', inline=True))
doc.append(' was derived by Einstein.')
# Complex expressions
with doc.create(Math()) as math:
math.append(r'\int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi}')The Alignat environment creates aligned multi-line equations with proper spacing and alignment.
class Alignat(Environment):
def __init__(self, aligns=2, numbering=True, escape=None):
"""
Create an aligned equation environment.
Parameters:
- aligns: int, number of alignment points (default 2)
- numbering: bool, whether to number equations
- escape: bool, whether to escape special characters
Requires:
- amsmath package (automatically added)
"""Usage example:
from pylatex import Document, Section, NoEscape
from pylatex.math import Alignat
doc = Document()
with doc.create(Section('System of Equations')):
# Basic aligned equations
with doc.create(Alignat(numbering=True)) as agn:
agn.append(r'2x + 3y &= 7 \\')
agn.append(r'x - y &= 1')
# Multiple alignment points
with doc.create(Alignat(aligns=3)) as agn:
agn.append(r'f(x) &= (x+a)(x+b) &= x^2 + (a+b)x + ab \\')
agn.append(r'g(x) &= (x-a)(x-b) &= x^2 - (a+b)x + ab')
# Unnumbered equations
with doc.create(Alignat(numbering=False)) as agn:
agn.append(r'\nabla \times \vec{E} &= -\frac{\partial \vec{B}}{\partial t} \\')
agn.append(r'\nabla \times \vec{B} &= \mu_0\vec{J} + \mu_0\epsilon_0\frac{\partial \vec{E}}{\partial t}')The Matrix class creates various types of mathematical matrices with automatic formatting.
class Matrix(Environment):
def __init__(self, matrix, *, mtype="p", alignment=None):
"""
Create a matrix environment.
Parameters:
- matrix: numpy.ndarray, matrix data as numpy array
- mtype: str, matrix type:
- 'p': parentheses ()
- 'b': brackets []
- 'B': braces {}
- 'v': vertical bars ||
- 'V': double vertical bars ||||
- alignment: str, column alignment ('c', 'l', 'r')
Requires:
- amsmath package (automatically added)
"""Usage example:
import numpy as np
from pylatex import Document, Section, NoEscape
from pylatex.math import Matrix, Math
doc = Document()
with doc.create(Section('Matrices')):
# Basic matrix with parentheses (requires numpy)
matrix_data = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
with doc.create(Math()) as math:
math.append('A = ')
math.append(Matrix(matrix_data, mtype='p'))
# Matrix with brackets
identity = [['1', '0', '0'],
['0', '1', '0'],
['0', '0', '1']]
with doc.create(Math()) as math:
math.append('I = ')
math.append(Matrix(identity, mtype='b'))
# Determinant with vertical bars
det_matrix = [['a', 'b'],
['c', 'd']]
with doc.create(Math()) as math:
math.append(r'\det(M) = ')
math.append(Matrix(det_matrix, mtype='v'))
math.append(' = ad - bc')
# Matrix with mathematical expressions
symbolic_matrix = [[NoEscape(r'\alpha'), NoEscape(r'\beta')],
[NoEscape(r'\gamma'), NoEscape(r'\delta')]]
with doc.create(Math()) as math:
math.append('Greek = ')
math.append(Matrix(symbolic_matrix, mtype='B'))The VectorName class creates properly formatted vector names using LaTeX's mathbf command.
class VectorName(Command):
def __init__(self, name):
"""
Create a bold vector name.
Parameters:
- name: str, vector name (will be rendered in bold math font)
"""Usage example:
from pylatex import Document, Section
from pylatex.math import Math, VectorName
doc = Document()
with doc.create(Section('Vector Operations')):
# Vector definitions
with doc.create(Math()) as math:
math.append(VectorName('v'))
math.append(' = ')
math.append(VectorName('a'))
math.append(' + ')
math.append(VectorName('b'))
# Vector components
with doc.create(Math()) as math:
math.append(VectorName('r'))
math.append(r' = \begin{pmatrix} x \\ y \\ z \end{pmatrix}')
# Cross product
with doc.create(Math()) as math:
math.append(VectorName('c'))
math.append(' = ')
math.append(VectorName('a'))
math.append(r' \times ')
math.append(VectorName('b'))from pylatex import Document, Section, NoEscape
from pylatex.math import Math, Alignat
doc = Document()
with doc.create(Section('Advanced Mathematics')):
# Integral equations
with doc.create(Math()) as math:
math.append(NoEscape(r'''
\oint_{\partial S} \vec{F} \cdot d\vec{l} =
\iint_S (\nabla \times \vec{F}) \cdot \hat{n} \, dS
'''))
# Series expansions
with doc.create(Math()) as math:
math.append(NoEscape(r'''
e^x = \sum_{n=0}^{\infty} \frac{x^n}{n!} =
1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + \cdots
'''))
# Limit definitions
with doc.create(Math()) as math:
math.append(NoEscape(r'''
\lim_{h \to 0} \frac{f(x+h) - f(x)}{h} = f'(x)
'''))import numpy as np
from pylatex import Document, Section, NoEscape
from pylatex.math import Math, Matrix
doc = Document()
with doc.create(Section('Matrix Operations')):
# Matrix multiplication (symbolic)
A = np.array([['a_{11}', 'a_{12}'],
['a_{21}', 'a_{22}']])
B = np.array([['b_{11}', 'b_{12}'],
['b_{21}', 'b_{22}']])
with doc.create(Math()) as math:
math.append('AB = ')
math.append(Matrix(A, mtype='b'))
math.append(Matrix(B, mtype='b'))
math.append(' = ')
result = [['a_{11}b_{11} + a_{12}b_{21}', 'a_{11}b_{12} + a_{12}b_{22}'],
['a_{21}b_{11} + a_{22}b_{21}', 'a_{21}b_{12} + a_{22}b_{22}']]
math.append(Matrix(result, mtype='b'))
# Eigenvalue equation
with doc.create(Math()) as math:
math.append('A')
math.append(VectorName('v'))
math.append(r' = \lambda ')
math.append(VectorName('v'))from pylatex import Document, Section, NoEscape
from pylatex.math import Alignat
doc = Document()
with doc.create(Section('Linear Systems')):
# Augmented matrix representation
with doc.create(Alignat(aligns=4, numbering=False)) as agn:
agn.append(r'2x &+ 3y &- z &= 7 \\')
agn.append(r'x &- y &+ 2z &= 3 \\')
agn.append(r'3x &+ 2y &+ z &= 8')
# Solution steps
with doc.create(Alignat(numbering=False)) as agn:
agn.append(r'x &= \frac{D_x}{D} \\')
agn.append(r'y &= \frac{D_y}{D} \\')
agn.append(r'z &= \frac{D_z}{D}')from pylatex import Document, Section, NoEscape
from pylatex.math import Math
doc = Document()
# Greek letters and symbols
with doc.create(Math()) as math:
math.append(NoEscape(r'\alpha, \beta, \gamma, \delta, \epsilon'))
# Calculus notation
with doc.create(Math()) as math:
math.append(NoEscape(r'\frac{d}{dx}f(x), \frac{\partial}{\partial x}f(x,y)'))
# Set theory
with doc.create(Math()) as math:
math.append(NoEscape(r'A \cup B, A \cap B, A \subset B, x \in A'))
# Logic symbols
with doc.create(Math()) as math:
math.append(NoEscape(r'\forall x \in \mathbb{R}, \exists y \in \mathbb{N}'))
# Operators
with doc.create(Math()) as math:
math.append(NoEscape(r'\sum_{i=1}^{n} x_i, \prod_{i=1}^{n} x_i, \int_a^b f(x)dx'))from pylatex import Document, Command, NoEscape
from pylatex.math import Math
doc = Document()
# Define custom operators
doc.preamble.append(Command('DeclareMathOperator', arguments=[NoEscape(r'\Tr'), 'Tr']))
doc.preamble.append(Command('DeclareMathOperator', arguments=[NoEscape(r'\rank'), 'rank']))
with doc.create(Math()) as math:
math.append(NoEscape(r'\Tr(A) = \sum_{i} A_{ii}'))
with doc.create(Math()) as math:
math.append(NoEscape(r'\rank(A) \leq \min(m, n)'))from pylatex import Document, Section, NoEscape
from pylatex.math import Alignat
from pylatex import Label, Ref
doc = Document()
with doc.create(Section('Referenced Equations')):
# Numbered alignat environment
with doc.create(Alignat()) as agn:
agn.append(NoEscape(r'E &= mc^2'))
agn.append(Label('einstein'))
agn.append(NoEscape(r'\\'))
agn.append(NoEscape(r'F &= ma'))
agn.append(Label('newton'))
doc.append(NoEscape('Einstein\'s equation '))
doc.append(Ref('einstein'))
doc.append(NoEscape(' and Newton\'s law '))
doc.append(Ref('newton'))
doc.append(NoEscape(' are fundamental to physics.'))Mathematical environments automatically include necessary packages:
amsmath package (automatically added)amssymb, amsfontsbm package for bold mathematical symbols\DeclareMathOperator in preamblefrom pylatex import Document, Package
doc = Document()
doc.packages.append(Package('amsmath'))
doc.packages.append(Package('amssymb'))
doc.packages.append(Package('amsfonts'))
doc.packages.append(Package('bm'))from pylatex import Document, NoEscape
from pylatex.math import Math, Alignat
# Use proper spacing
with doc.create(Math()) as math:
math.append(NoEscape(r'a \cdot b \quad \text{not} \quad a.b'))
# Use text in equations
with doc.create(Math()) as math:
math.append(NoEscape(r'P(\text{event}) = \frac{\text{favorable outcomes}}{\text{total outcomes}}'))
# Break long equations
with doc.create(Alignat(numbering=False)) as agn:
agn.append(NoEscape(r'f(x) &= a_0 + a_1x + a_2x^2 + a_3x^3 \\'))
agn.append(NoEscape(r'&\quad + a_4x^4 + a_5x^5 + \cdots'))Mathematical expressions in PyLaTeX maintain LaTeX's high-quality typesetting while providing programmatic control over equation generation and formatting.
Install with Tessl CLI
npx tessl i tessl/pypi-pylatex