tex

A collection of functions to ease the inclusion of \(\TeX\) strings in Python source code.

In order to avoid tqdm’s experimental warning

warnings.filterwarnings("ignore", message='Using `tqdm.autonotebook.tqdm` in notebook mode')

Decorating a function so that it can return a formula

A decorator that allows (optionally) the string returned by any function to be enclosed between $s.


source

to_formula_maybe

 to_formula_maybe (func:Callable[...,Any])

Decorator for adding the argument to_formula to any function

Type Details
func Callable Function returning a string
Returns str \(\LaTeX\) formula

As an example

def to_radians(n_cycles: int) -> float:
    
    return n_cycles * 3.14
to_radians(2)
6.28

A module that allows to inspect functions.

import inspect
inspect.signature(to_radians)
<Signature (n_cycles: int) -> float>
@to_formula_maybe
def to_radians(n_cycles: int) -> float:
    
    return n_cycles * 3.14

Signature of the decorated function is the same

inspect.signature(to_radians)
<Signature (n_cycles: int) -> float>

The function can be used as though it has not been decorated…

to_radians(2)
6.28

…or can be requested to produce a \(\LaTeX\) formula

to_radians(2, to_formula=True)
'$6.28$'

render_latex can be used to properly render it in the notebook:

render_latex(to_radians(2, to_formula=True))

\(\Large 6.28\)

Convenience functions

Enumerating the strings in a list


source

join

 join (strings_list:list[str], nexus:str=' and ', to_formula:bool=True)

Enumerates the strings in a list, optionally enclosing every element between $s

Type Default Details
strings_list list Strings to be joined
nexus str and Text between the second to last and last elements
to_formula bool True If True every string will be enclosed in $s
Returns str \(\LaTeX\)-compatible text
tex = join(['a', 'b', 'c'])
render_latex(tex)

\(\Large a\), \(\Large b\) and \(\Large c\)

tex = join(['a', 'b', 'c'], nexus=' y ')
render_latex(tex)

\(\Large a\), \(\Large b\) y \(\Large c\)

tex = join(['2', '\sigma'])
render_latex(tex)

\(\Large 2\) and \(\Large \sigma\)

tex = join(['2', '3', '4'], nexus=', ')
render_latex(tex)

\(\Large 2\), \(\Large 3\), \(\Large 4\)

Definitions of functions

Customizable mathematical functions.

Gaussian probability density function

The expression of a (univariate) Gaussian probability density function.


source

gaussian_pdf

 gaussian_pdf (x:str|None='x', mean:str|None='\\mu',
               variance:str|None='\\sigma^2')

Returns a string representing the probability density function for a Gaussian distribution

Type Default Details
x str | None x The random variable
mean str | None The mean of the random variable
variance str | None ^2 The variance of the random variable
Returns str \(\LaTeX\)-compatible text

With no arguments, it yields the usual formula,

tex = gaussian_pdf(to_formula=True)
render_latex(tex)

\(\Large \frac{1}{\sqrt{2\pi \sigma^2}}e^{-\frac{(x-\mu)^2}{2\sigma^2}}\)

The arguments allow to use different symbols for the random variable, the mean and the variance

tex = gaussian_pdf(x="n", mean="m", variance="v", to_formula=True)
render_latex(tex)

\(\Large \frac{1}{\sqrt{2\pi v}}e^{-\frac{(n-m)^2}{2v}}\)

Stirling’s approximation to the Q function


source

q_function_approximation

 q_function_approximation (x:str|None='x')

Returns a string representing the Stirling approximation for the Q function

Type Default Details
x str | None x The argument of the Q function
Returns str \(\LaTeX\)-compatible text

With no arguments, the argument is \(x\)

tex = q_function_approximation(to_formula=True)
render_latex(tex)

\(\Large Q(x) \approx \frac{1}{2} e^{-\frac{x^2}{2}}\)

but a specific variable can be passed

tex = q_function_approximation('t', to_formula=True)
render_latex(tex)

\(\Large Q(t) \approx \frac{1}{2} e^{-\frac{t^2}{2}}\)

Part-wise defined functions


source

partwise_function

 partwise_function (function:str, parts:list[tuple[str,str]],
                    add_zero_otherwise:bool|None=True)

Returns a string representing the definition a part-wise mathematical function

Type Default Details
function str The name of the function
parts list Each element is a tuple yields whose 1st element is the value of the function and whose second is a condition stating where the 1st applies
add_zero_otherwise bool | None True If True, one last part stating “0, otherwise” is added
Returns str \(\LaTeX\)-compatible text
tex = partwise_function('f(x)', [('x+1', '0 < x \le 1'), ('x-1', '1 < x \le 2')], to_formula=True)
render_latex(tex)

\(\Large f(x)=\begin{cases} x+1,& 0 < x \le 1 \\x-1,& 1 < x \le 2 \\0,& \text{otherwise}\end{cases}\)

tex = partwise_function('f(x)', [('x+1', '0 < x \le 1')], add_zero_otherwise=False, to_formula=True)
render_latex(tex)

\(\Large f(x)=\begin{cases} x+1,& 0 < x \le 1 \\\end{cases}\)

Numbers

Utilities to turn numbers (or collections thereof) into \(\LaTeX\) source code.

Scalar


source

from_number

 from_number (n:int|float, prefix:str|None='', precision:int|None=3,
              fixed_point_format:bool|None=False)

Returns a string for a given number

Type Default Details
n int | float The number
prefix str | None A string to be prepended to the number
precision int | None 3 Number of decimals if fixed_point_format is True, overall number of figures otherwise (ignored if the number is an integer)
fixed_point_format bool | None False If True, a fixed-point format (f) is used regardless of the actual type
Returns str \(\LaTeX\)-compatible text

Valid for both floating point numbers,

tex = from_number(2.3, to_formula=True)
render_latex(tex)

\(\Large 2.3\)

and integers

tex = from_number(3, to_formula=True)
render_latex(tex)

\(\Large 3\)

With a higher precision

tex = from_number(np.pi, precision=6, to_formula=True)
render_latex(tex)

\(\Large 3.14159\)

Notice that if fixed_point_format is set to False (default), the precision refers to the overall number of figures (g(eneral) format specifier-behaviour). On the other hand, the precision parameter of a fixed-point number controls the number of decimals,

tex = from_number(np.pi, precision=6, fixed_point_format=True, to_formula=True)
render_latex(tex)

\(\Large 3.141593\)

If the number is an integer, precision parameter is ignored

tex = from_number(42, to_formula=True)
render_latex(tex)

\(\Large 42\)

A prefix can be passed:

tex = from_number(42, prefix='a=', to_formula=True)
render_latex(tex)

\(\Large a=42\)

Matrix or vector/list

Functions to turn a matrix or vector into \(\LaTeX\) source code.


source

from_matrix

 from_matrix (m:list|numpy.ndarray, float_point_precision:int=3)

Returns a string for a given array or matrix

Type Default Details
m list | numpy.ndarray Matrix or vector
float_point_precision int 3 Number of decimals (ignored if the number is an integer)
Returns str \(\LaTeX\)-compatible text

from_matrix returns \(\LaTeX\) source code for a list or np.ndarray

This can be applied on lists

tex = from_matrix([1, 2, 3], to_formula=True) + ','
render_latex(tex)

\(\Large \begin{bmatrix}1 & 2 & 3\end{bmatrix}\),

or numpy arrays, both 2D

tex = from_matrix(np.array([[1.11, 3.14], [14.2, 5.1]]), to_formula=True) + ','
render_latex(tex)

\(\Large \begin{bmatrix}1.11 & 3.14 \\ 14.2 & 5.1\end{bmatrix}\),

and 1D

tex = from_matrix(np.array([14.2, 5.1]), to_formula=True)
render_latex(tex)

\(\Large \begin{bmatrix}14.2 & 5.1\end{bmatrix}\)

If the numbers are integers, that is taken into account:

tex = from_matrix(np.array([[1, 3], [4, 5]]), to_formula=True)
render_latex(tex)

\(\Large \begin{bmatrix}1 & 3 \\ 4 & 5\end{bmatrix}\)

tex = from_matrix(np.array([14, 5]), to_formula=True)
render_latex(tex)

\(\Large \begin{bmatrix}14 & 5\end{bmatrix}\)

tex = from_matrix([1, 2], to_formula=True)
render_latex(tex)

\(\Large \begin{bmatrix}1 & 2\end{bmatrix}\)

Dot product


source

dot_product

 dot_product (lhs_template:str, lhs:list, rhs_template:str, rhs:list,
              product_operator:str|None='',
              addition_operator:str|None='+')

Returns a string for the dot product of two vectors, regardless of whether they are symbols or numbers

Type Default Details
lhs_template str Left-hand side template; it should include a replacement field ({}) that will be replaced by one of the elements in lhs
lhs list Left-hand side elements
rhs_template str Right-hand side template; it should include a replacement field ({}) that will be replaced by one of the elements in rhs
rhs list Right-hand side elements
product_operator str | None Symbol to be used as product operator
addition_operator str | None + Symbol to be used as addition operator
Returns str \(\LaTeX\)-compatible text
tex = dot_product('p(y_1|x_{})', [1, 2], 'p(x_{})', [1,2], to_formula=True)
render_latex(tex)

\(\Large p(y_1|x_1)p(x_1)+p(y_1|x_2)p(x_2)\)

tex = dot_product('{}', [0.1, 0.2], '{}', [0.75, 0.9], product_operator=r'\cdot', to_formula=True)
render_latex(tex)

\(\Large 0.1\cdot0.75+0.2\cdot0.9\)

Law of total probability


source

total_probability

 total_probability (fixed_symbol:str, varying_symbol_template:str, n:int,
                    start_at:int=1)

Returns a string for law of total probability

Type Default Details
fixed_symbol str The symbol that stays the same in the summation
varying_symbol_template str A template for the varying symbol that includes a replacement field ({}) for the index
n int The number of values for the varying symbol
start_at int 1 The index at which varying_symbol_templatestarts
Returns str \(\LaTeX\)-compatible text
tex = total_probability('x_1', 'y_{}', 3, to_formula=True)
render_latex(tex)

\(\Large p(x_1,y_1)+p(x_1,y_2)+p(x_1,y_3)\)

Starting at a different index

tex = total_probability('x_1', 'y_{}', 3, start_at=3, to_formula=True)
render_latex(tex)

\(\Large p(x_1,y_3)+p(x_1,y_4)+p(x_1,y_5)\)

Enumerations


source

enumerate_math

 enumerate_math (numbers_list:list[float], assigned_to:str|None=None,
                 nexus:str|None=' and ', precision:int|None=3,
                 start_at:int|None=1)

Builds a \(\TeX\) string from a list of numbers in which each one is printed after (optionally) being assigned to an indexed variable that follows a given pattern

Type Default Details
numbers_list list The elements to be enumerated
assigned_to str | None None Some text with a replacement field (this means that any { or } must be escaped by doubling it)
nexus str | None and The text joining the second to last and last elements
precision int | None 3 The number of decimal places
start_at int | None 1 The index of the first element that enters the enumeration
Returns str \(\LaTeX\)-compatible text

Using the optional assigned_to arguement,

tex = enumerate_math([0.7, 0.9], assigned_to='w_t^{{({})}}')
render_latex(tex)

\(\Large w_t^{(1)} = 0.7\) and \(\Large w_t^{(2)} = 0.9\)

and without it

tex = enumerate_math([0.7, 0.9])
render_latex(tex)

\(\Large 0.7\) and \(\Large 0.9\)

Starting at a different index on the left-hand-side

tex = enumerate_math([0.722341, 0.9], assigned_to='w_t^{{({})}}', start_at=2)
render_latex(tex)

\(\Large w_t^{(2)} = 0.722\) and \(\Large w_t^{(3)} = 0.9\)



source

enumerate_assignments

 enumerate_assignments (lhs_template:str, rhs_template:str,
                        rhs:list[float], nexus:str=' and ',
                        precision:int=3, start_at:int=1)

Constructs a enumeration of assignments from left-hand-side and right-hand-side templates and right-hand-side values. It’s similar to enumerate_math when the argument assigned_to is passed to the latter, but more general since the right-hand expression is also obtained from a template

Type Default Details
lhs_template str Text with a replacement field that will be replaced by an index
rhs_template str Text with a replacement field that will be replaced by one of the corresponding elements in rhs
rhs list Elements to be enumerated
nexus str and The text joining the second to last and last elements
precision int 3 The number of decimal places
start_at int 1 The index of the first element that enters the enumeration
Returns str \(\LaTeX\)-compatible text
tex = enumerate_assignments('s_{}', '{}', [1.3,4.1])
render_latex(tex)

\(\Large s_1 = 1.3\) and \(\Large s_2 = 4.1\)

tex = enumerate_assignments('s_{}', '2^{{{}}}', [1.3,4.1], start_at=4)
render_latex(tex)

\(\Large s_4 = 2^{1.3}\) and \(\Large s_5 = 2^{4.1}\)

tex = enumerate_assignments('s_{}', '2^{{{}}}', [1.3,4.1, 3], start_at=4, nexus=', ')
render_latex(tex)

\(\Large s_4 = 2^{1.3}\), \(\Large s_5 = 2^{4.1}\), \(\Large s_6 = 2^{3}\)

Expanding a symbol


source

expand

 expand (template:str, n:int, to_math:bool=False, nexus:str=' and ',
         start_at:int=1)

Expand a symbol according to a pattern

Type Default Details
template str String with a single replacement field ({})
n int Requested number of terms
to_math bool False If True, every output term is enclosed between $’s
nexus str and String joining the second to last and last terms
start_at int 1 The number at which indexes start
Returns str \(\LaTeX\)-compatible text
tex = expand('s_{}', 3, True)
render_latex(tex)

\(\Large s_1\), \(\Large s_2\) and \(\Large s_3\)

tex = expand('s_{}', 3, True, nexus=', ')
render_latex(tex)

\(\Large s_1\), \(\Large s_2\), \(\Large s_3\)