Workflow to convert formula (image) to python

motivation

Even if you find a mathematical formula in a dissertation or textbook, it takes time to utilize it. Even more, it takes more time to drop it in the document. Therefore, we created a workflow that can be used for programming and subsequent documentation by using mathematical expression images as input.

Latex from image

Use a service called Mathpix to latex it. Registration is required, but it will latex the image with a nice touch.

It is like this image.png

Get AsciiMath string

We will process the AsciiMath string and convert it to a form that can be used in python.

--Copy Ascii Math on the "data" tab of Mathpix Based on this character string, we will make it available in the program.

image.png

Preprocessing

Preprocess the string

--a: Paste the Ascii Math string --shoki_dict: The dictionary to be replaced first * Updated from time to time

translate_1.py


import re
# a = "sigma=(E alpha DeltaT)/(1-nu)*(1)/(1.5+3.25//beta-0.5 exp(-16//beta))"
# a = "M_(max)=(w*l^(2))/(8)"
a= "delta_(max)=(5*w*l^(4))/(384 E*I)"
# a ="K=(1.7 xx10^(5))/((delta_(1)+delta_(0))/(lambda_(1))+(delta_(2)+delta_(0))/(lambda_(2)))xx(0.6P)/(H)+(10^(6)lambda_(f))/(delta_(1)+delta_(2))"
shoki_tikan_dict = {" ":"*",
                   "xx":"*",
                   "^":"**",
                   "//":"/"}
for i in shoki_tikan_dict:
    a = a.replace(i,shoki_tikan_dict[i])
    
temp = re.sub("_\((.*?)\)","0",a)#So that you can get the variable ignoring the subscript_()To 0
hensu = re.findall("[A-Za-z]+",temp)#Extract variables
li_moji = list(set(hensu))#Clear variable duplication
print(a)
print(li_moji)

When the above is executed, the following is output. If there is something wrong with the formula here, correct it. Also, make sure that the variables are extracted properly. (Ignore the extra ones, OK. In the example, ignore "exp") sigma=(EalphaDeltaT)/(1-nu)(1)/(1.5+3.25/beta-0.5exp(-16/beta)) ['nu', 'sigma', 'DeltaT', 'beta', 'alpha', 'exp', 'E']

Convert expression

Convert Greek letters and subscripts into formulas

--moji_dict: List used when extracting parameters (Greek letters) * Updated from time to time

translate_2.py


moji_dict = {'lambda':"λ",
             'delta':"δ",
            'sigma':"σ",
            'alpha':"α",
            'DeltaT':"ΔT",
            'nu':'ν',
            'beta':'β',
            'epsi':"ε",
            'pi':'π',
            'mu':'μ'}


def tikan(moji_retsu,taisho,moji_dict):
#     print(taisho)
    taisho_temp = taisho+"_"
    seiki_1 = taisho_temp + "\(.*?\)"
    seiki_2 = taisho_temp + "\((.*?)\)"
    b = re.findall(seiki_1,moji_retsu)

    if len(b) != 0:
        if taisho in moji_dict:
            tikan_moji = moji_dict[taisho]
        else:
            tikan_moji = taisho
#             print(tikan_moji)
            
        newList = [re.sub(seiki_2,tikan_moji+"\\1",item) for item in b]
        moji_retsu = re.sub(seiki_2,tikan_moji+"\\1",moji_retsu)

    elif taisho in moji_dict:
        tikan_moji = moji_dict[taisho]
        newList = [tikan_moji]
        moji_retsu = moji_retsu.replace(taisho,tikan_moji)

    else:
        tikan_moji = taisho
        newList = [taisho]
        
    return moji_retsu,newList

li=[]
for i in li_moji:
    a,p = tikan(a,i,moji_dict)
    li.extend(p)
li=list(set(li))
li.sort()

a = re.sub("\(([0-9])\)","\\1",a)
print(a)
print(li)

When you execute the above, the following will be output σ=(EαΔT)/(1-ν)1/(1.5+3.25/β-0.5exp(-16/β)) ['E', 'exp', 'ΔT', 'α', 'β', 'ν', 'σ']

Next, add subscripts to form the formula. That's all you can do automatically, and the rest is manually made into an expression that can be used in python.

result_Eq.py


import math
σ=(E*α*ΔT)/(1-ν)*1/(1.5+3.25/β-0.5*math.exp(-16/β))

Now that the expression is complete, it's time to extract the parameters.

paramater_print.py


print("paramater_dict= {")
for i in li:
    print("    " + "'" + i +"':['',''],")
print("    }")

When you execute the above, the following will be output.

out.py


paramater_dict= {
    'E':['',''],
    'exp':['',''],
    'ΔT':['',''],
    'α':['',''],
    'β':['',''],
    'ν':['',''],
    'σ':['',''],
    }

This is the end of automatic operation, and the following actions are manually performed for the parameters.

--Delete unnecessary parameters --Change the order --Added description and units

result.py


paramater_dict= {
    'E':['Young's modulus','MPa'],
    'ΔT':['Inside and outside temperature difference','K'],
    'α':['Coefficient of linear expansion','/K'],
    'β':['Biot number',''],
    'ν':['Poisson's ratio',''],
    'σ':['Thermal stress','MPa'],
    }

It's a good idea, so can you use it?

run.py


import math

E = 200
ΔT = 10
α = 0.00005
β = 2
ν = 0.3

σ=(E*α*ΔT)/(1-ν)*1/(1.5+3.25/β-0.5*math.exp(-16/β))
print(σ)

If you do the above, you will get the answer. 0.045716739515498046

Documentation

At this point, you can easily document using sympy by applying the following article. Create mechanical design calculation material with python + sympy

Regarding the created formula

Create formulas as appropriate and share them below (updated as appropriate) Formulas and functions (updated as appropriate)

Afterword

I thought about using a library such as latex2sympy, but it was quite difficult. I learned regular expressions that I'm not good at! Mathpix cannot be used due to company security. .. .. I'm sorry

Recommended Posts

Workflow to convert formula (image) to python
Sample to convert image to Wavelet with Python
Convert PDF to image (JPEG / PNG) with Python
[python] Convert date to string
Convert numpy int64 to python int
[Python] Convert list to Pandas [Pandas]
Convert Scratch project to Python
[Python] Convert Shift_JIS to UTF-8
Convert python 3.x code to python 2.x
Convert the image in .zip to PDF with Python
Convert markdown to PDF in Python
Convert list to DataFrame with python
Python> list> Convert double list to single list
Convert a string to an image
[Python] Convert natural numbers to ordinal numbers
Convert decimal numbers to n-ary numbers [python]
Convert PDF to image with ImageMagick
Introduction to image analysis opencv python
Python> tuple> Convert double tuple to single tuple
Convert memo at once with Python 2to3
HTML email with image to send with python
Convert Python> two value sequence to dictionary
[Python] How to convert a 2D list to a 1D list
How to convert Python to an exe file
[Python] Convert csv file delimiters to tab delimiters
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
Convert Hiragana to Romaji with Python (Beta)
Convert from katakana to vowel kana [python]
Convert FX 1-minute data to 5-minute data with Python
python> Convert tuple to list> aList = list (pi_tuple)
How to adjust image contrast in Python
Convert Python date types to RFC822 format
Convert HEIC files to PNG files with Python
Convert Chinese numerals to Arabic numerals with Python
Convert from Markdown to HTML in Python
Convert absolute URLs to relative URLs in Python
Updated to Python 2.7.9
Convert to HSV
"Backport" to python 2
Convert FBX files to ASCII <-> BINARY in Python
Convert "number" of excel date to python datetime
Image characters and post to slack (python slackbot)
Convert PDFs to images in bulk with Python
Python script to convert latitude / longitude to mesh code
[Python] Convert from DICOM to PNG or CSV
How to use Python Image Library in python3 series
Convert svg file to png / ico with Python
How to crop an image with Python + OpenCV
Convert Windows epoch values to date with python
How to convert SVG to PDF and PNG [Python]
Convert STL to Voxel mesh using Python VTK
Convert exponential notation float to str in Python
Post an article with an image to WordPress with Python
Convert cubic mesh code to WKT in Python
Convert strings to character-by-character list format with python
Convert timezoned date and time to Unixtime in Python2.7
Convert jupyter notebook .ipynb files to python executable .py files
I want to convert an image to WebP with lollipop
Tool to make mask image for ETC in Python
Python practice Convert the input year to the Japanese calendar
How to convert / restore a string with [] in python