generativepy.formulas module


Martin McBride, 2022-04-27
Tags formula tex latex
Categories generativepy generative art

The formulas module provides the ability to display formatted mathematical equations.

The module converts latex format equations into bitmap images, with text of any required colour and a transparent background. The image can be dispalyed using the Image class, which allows positioning and scaling of the formula. It is also possible to use the Transform class to apply general transforms to the formula image.

The module contains a single function:

  • rasterise_formula - convert a formula to an image.

Example

Here is an example that displays two formulae:

The code for this can be found on github as maths-formula.py:

from generativepy.drawing import make_image, setup
from generativepy.color import Color
from generativepy.geometry import Image, Text
from generativepy.formulas import rasterise_formula

'''
Create some formulae
'''

def draw(ctx, width, height, frame_no, frame_count):
    setup(ctx, width, height, width=800, background=Color(0.8))

    image1, size1 = rasterise_formula("cosh-formula", r"\cosh{x} = \frac{e^{x}+e^{-x}}{2}", Color("dodgerblue"))
    image2, size2 = rasterise_formula("quadratic", r"x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}", Color("crimson"), dpi=400)
    Image(ctx).of_file_position(image1, (50, 50)).paint()
    Text(ctx).of("Size1 = " + str(size1), (50, 500)).size(20).fill(Color(0))
    Image(ctx).of_file_position(image2, (50, 300)).paint()
    Text(ctx).of("Size2 = " + str(size2), (250, 500)).size(20).fill(Color(0))

make_image("/tmp/maths-formula.png", draw, 800, 600)

rasterise_formula

Convert a formula to an image.

rasterise_formula(name, formula, color, dpi=600)
Parameter Type Description
name string A name for the image. This will be used as the file name for the generated PNG file.
formula string The latex formula.
color Color The colour of the text.
dpi number The nominal resolution of the image. This controls the size of image, see below. Optional, default 600.

Creates a set of axes for drawing a graph.

The position gives the position of the top left of the axes in user coordinates. width and height give the size of the axes area, again in user coordinates.

The name parameter is used to name the output file, and also any temporary files created. It is best to use a unique name that is indicative of the content. The image file will be created in the current folder.

formula is the formula, in latex format. The example code shows a couple of example formulae.

color controls the colour of the text. The text is created on a transparent background.

dpi controls the resolution of the output image, and so indirectly the image size. This value corresponds to the dpi parameter of the dvipng utility.

The default value of 600 creates the formula using a text height of about 60 pixels. The exact size of the image depends on the formula used. The image is cropped tightly to the image area that includes the formula.

You can change the image size by altering the dpi value - a smaller number creates a smaller image, larger value creates a larger image. Since the scaling is applied to the vector data, it is always rendered at the best quality at any size.

You can also resize the image when it is drawn on the page, using the scale method of the Image class. This method can reduce the size of the formula with reasonable quality, but since it works on the bitmap data increasing the size will cause pixellation problems.

The function returns a tuple:

(filename, (width, height))

Here, filename is the name of the output PNG file (in the current version this will always be ".png" where isd the name value passed in to the function). The tuple (width, height) gives the width and height of the image in pixels.

If you found this article useful, you might be interested in the book Computer Graphics in Python or other books by the same author.

Prev

Popular tags

2d arrays abstract data type alignment and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop function function composition function plot functools game development generativepy tutorial generator geometry gif global variable gradient greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing iter iterable iterator itertools join l system lambda function len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas partial application path pattern permutations pie chart polygon positional parameter print pure function python standard library radial gradient range recipes rectangle recursion reduce regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template text text metrics tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip