Python - First Attempt to Accelerate Latex Formula Editing

Subscribe Send me a message home page tags


This post presents a python helper script that helps to accelerate Latex editing. The general idea is to

Note that Python already supports string template. For example:

1
2
3
4
A = "x + y - z"
B = "2x + 10y + z"
expression = "({A}) * ({B})".format(A = A, B = B)
print(expression)

This code above gives the following result:

(x + y - z) * (2x + 10y + z)

There are two issues with this approch:

For example, we need to add extra {} for latex command:

1
2
3
4
A = "x + y - z"
B = "2x + 10y + z"
expression = r"\frac{{ {A} }} {{ {B} }}".format(A = A, B = B)
print(expression)

The code above gives us:

\frac{ x + y - z } { 2x + 10y + z }

The objective is to something like the following

objective.png

Here, we use back apostrophe to expand a variable inside a string. In order to achive this, we need the following code

helper_methods.png

We could define normal python function to change the syntax a little bit:

1
2
3
4
5
6
7
8
9
10
def sum(expression, bottom=None, top=None, data=None):
    _expression = expr(expression, data)
    if bottom is None and top is None:
        return "\sum{}".format(_expression)

    if bottom is None:
        return "\sum^{} {}".format(top, _expression)

    if top is None:
        return "\sum_{} {}".format(bottom, _expression)

Now we can do following:

usage.png

This gives us:

\sum_{ t \in V } { \mathcal{M}_{q}(t) \cdot log \frac{\mathcal{M}_{q}(t)}{\mathcal{M}_{d}(t)} } = \sum_{ t \in V } { \mathcal{M}_{q}(t) \cdot log \mathcal{M}_{q}(t) } - \sum_{ t \in V } { \mathcal{M}_{q}(t) \cdot log \mathcal{M}_{d}(t) }

We can also define customized function. However, this time we need to specify the local data:

customized_function.png

The code can be found at https://gist.github.com/meretciel/3b372d7c0c11189239ae7ceb00a74f32

----- END -----

Welcome to join reddit self-learning community.
Send me a message Subscribe to blog updates

Want some fun stuff?

/static/shopping_demo.png