예제 #1
0
def my_form_json():
    """
        Get Values for the identifiers
        Return Calculated result 
    """

    try:
        identifiers1 = request.data.decode('utf-8')
        json1 = json.loads(identifiers1)
        seprator = getidentifiers.formuladivision(formula)
        if seprator is not None:
            lhsrhs = getlhsrhs(processedformula, seprator)
            f = process_sympy(rhs)
            f1 = process_sympy(lhs)
            latexlhs = sympify(f1)
            l = sympify(f)
            #print(l)
            symbolvalue = makeidentifier(identifiers, json1)
            value = l.evalf(subs=symbolvalue)

            return ("%s %s %.2e" % (latexlhs, seprator, value))
        else:
            l = sympify(formula)
            value = l.evalf(subs=json1)

            return ("%.2e" % value)

    except Exception:
        return ("System is not able to find the result.")
예제 #2
0
 def sympy_check(self):
     expr_tmp_list = []
     for expr in self.expr_list:
         try:
             process_sympy(expr)
             expr_tmp_list.append(expr)
         except:
             print("\n", "expr:", expr,
                   '\nprocess_sympy error:',
                   str(sys.exc_info()))
     self.expr_list = expr_tmp_list
예제 #3
0
def message_received(client, server, message):
    if not hasattr(message_received, "records"):
        #message_received.records = ["tyoPXhzGzrE", "thrwb-JvVSM", "AJdCfaGjWlk", "EYG1XvNUZF0", "ieiRIATCOUI"]
        message_received.records = prepareSymbols()

    #print("Client(%d) said: %s" % (client['id'], message))
    inputExp = strokes2Math(message.encode('ascii'))
    print(inputExp)
    foundVideo = searchSymExps(message_received.records,
                               process_sympy(inputExp.decode("utf-8")))
    server.send_message(client, foundVideo['vid'])
예제 #4
0
def prepareSymbols():
    with open('listfile.data', 'rb') as filehandle:
        # read the data as binary data stream
        records2 = pickle.load(filehandle)
    filehandle.close()

    symbolizedExp = []
    for rec in records2:
        expList = []
        for e in rec[2].splitlines():
            try:
                expList.append(process_sympy(e))
            except:
                continue
        if expList:
            symbolizedExp.append({'vid': rec[3], 'exp': expList})
    return symbolizedExp
예제 #5
0
def test():
    import re
    alegbra_operators = set(pd.read_csv('table/mathjax_alegbra.txt', header=-1)[0])
    geometry_operators = set(pd.read_csv('table/mathjax_geometry.txt', header=-1)[0])
    equation_operators = set(pd.read_csv('table/mathjax_equation.txt', header=-1)[0])
    nlp_noise = set(pd.read_csv('table/nlp_noise.txt', header=-1)[0])
    problems_info = MongoClient(host="localhost", connect=False)['knowledge_graph']['problems_info']
    cursor = problems_info.find({})
    cnt = 0
    total = 0
    for dat in cursor:
        total += 1
        dat = dat['body'].replace(',', ',').replace('$,$', '').replace('$$', '')
        dat = re.sub('(<div>.*?</div>)', '', dat)
        r1 = '\\$(.*?)\\$'
        expr_list = re.findall(r1, dat)
        a = Alegbra(expr_list, alegbra_operators, geometry_operators, equation_operators, nlp_noise)
        a.filter()
        filter = a.expr_list
        a.fmt()
        fmt = a.expr_list
        a.sympy_check()
        check = a.expr_list
        # 测试log
        # if len(check) != len(filter):
        #     print('\n', 'dat:', dat)
        #     print('filter:', filter)
        #     print('fmt:', fmt)
        #     print('check:', check)
        if len(check) > 0:
            print('\n', check, '\n', [process_sympy(expr) for expr in check])
        if len(a.expr_list) > 0:
            cnt += 1
    print('alegbra_operators:', alegbra_operators)
    print('geometry_operators:', geometry_operators)
    print('equation_operators:', equation_operators)
    print('nlp_noise:', nlp_noise)
    print('total:', total, ' cnt:', cnt)
예제 #6
0
__author__ = 'sindytan'

import sympy
from process_latex import process_sympy
from sympy.core import Atom
from sympy.core import Function
from sympy.core import Derivative
from sympy.printing.dot import dotprint
from sympy import *

# myExpr = "f_{X+Y}(a) = \\frac{d}{da}\int_{\\infty}^{\\infty} F_X(a-y)f_Y(y)dy"
# myExpr = "f_{X+Y}(a) = \\frac{d}{da}\int_{\\infty}^{\\infty} F_X(a-y)f_Y(y)dy + N"
myExpr = '-2 (\\sum_i y_i˙- n w_0) '
# myExpr = '-2 (\sum_i y_i - (\sum_i x_i^T)  w˙- n w_0)'
expr = process_sympy(myExpr)
print expr


# get list of all subtrees / arguments of a SymPy expression
def get_subtrees(expr, subtrees):
    if len(expr.args) > 0:
        if expr.func not in subtrees:
            subtrees += [expr.func]
        for arg in expr.args:
            # if (not isinstance(arg, Atom)) and (arg not in subtrees):
            if arg not in subtrees:
                subtrees += [arg]
            get_subtrees(arg, subtrees)
        return subtrees
    else:
        return subtrees
예제 #7
0
from sympy import *
import sys
sys.path.append("..")
from process_latex import process_sympy

latex = "[!value!]"
math = process_sympy(latex)
print("latex: %s to math: %s" % (latex, math))

latex = "x^2"
math = process_sympy(latex)
print("latex: %s to math: %s" % (latex, math))

latex = "[!value1!]"
math = process_sympy(latex)
print("latex: %s to math: %s" % (latex, math))

latex = "[!value_1!]"
math = process_sympy(latex)
print("latex: %s to math: %s" % (latex, math))

latex = "4\\cdot[!value_1!]\\frac{[!value_2!]}{[!value3!]}"
latex = "4\\cdot[!value_1!]\\frac{[!value_2!]}{[!a!]}"
math = process_sympy(latex)
print("latex: %s to math: %s" % (latex, math))

latex = "4\\cdot[!value_1!]"
math = process_sympy(latex)
print("latex: %s to math: %s" % (latex, math))

latex = "4\\cdot[!a!]"
s = requests.Session()

req = s.get("http://tasks.sprush.rocks:8084/")

for k in range(150):
    text = ""

    for symbol in req.text[666:]:
        if (symbol != '$'):
            text += symbol
        else:
            break

    print(text)
    text = str(process_sympy(text))
    print(text)
    text += "  "

    f = text.replace("Integral(", "").replace("left*", "").replace(
        "right*", "").replace("right", "").replace("left", "").replace(
            "exp*", "exp").replace("(x, 0, 10)",
                                   "").replace(", )", "").replace(", E)", ")")
    f = f.replace("expx**3",
                  "exp(x**3").replace("expx**2",
                                      "exp(x**2)").replace("expx", "exp(x)")
    print(f)

    fp = open('seva.py', 'w')
    fp.write("import scipy.integrate\n")
    fp.write("from numpy import *\n")
예제 #9
0
BAD_STRINGS = [
    "(", ")", "a / b /", "\\frac{d}{dx}", "(\\frac{d}{dx})"
    "\\sqrt{}", "\\sqrt", "{", "}", "1.1.1", "\\mathit{x + y}", "\\mathit{21}",
    "\\frac{2}{}", "\\frac{}{2}", "\\int", "1 +", "a +", "!", "!0", "_", "^",
    "a // b", "a \\cdot \\cdot b", "a \\div \\div b", "|", "||x|", "()",
    "((((((((((((((((()))))))))))))))))", "-", "\\frac{d}{dx} + \\frac{d}{dt}",
    "f()", "f(,", "f(x,,y)", "f(x,y,", "\\sin^x", "\\cos^2", "\\cos 1 \\cos",
    "@", "#", "$", "%", "&", "*", "\\", "~", "\\frac{(2 + x}{1 - x)}"
]

total = 0
passed = 0
for s, eq in GOOD_PAIRS:
    total += 1
    try:
        if process_sympy(s) != eq:
            print("ERROR: \"%s\" did not parse to %s" % (s, eq))
        else:
            passed += 1
    except Exception as e:
        print("ERROR: Exception when parsing \"%s\"" % s)
for s in BAD_STRINGS:
    total += 1
    try:
        process_sympy(s)
        print("ERROR: Exception should have been raised for \"%s\"" % s)
    except Exception:
        passed += 1

print("%d/%d STRINGS PASSED" % (passed, total))
예제 #10
0
]

total_good = 0
passed_good = 0
total = 0
passed = 0
for s, eq, *args in GOOD_PAIRS:
    placeholder_values = {}
    if args:
        placeholder_values = args[0] if len(args) > 0 else placeholder_values

    # counters
    total += 1
    total_good += 1
    try:
        parsed = process_sympy(s, placeholder_values)
    except Exception as e:
        print("ERROR: Exception when parsing \"%s\"" % s)

    try:
        if isinstance(eq,(list,)):
            check = eq == parsed
            if check:
                value = 0
            else:
                value = 1
        else:
            value = eq - parsed
            value_simp = simplify(value)

        if srepr(parsed) != srepr(eq) and value != 0 and value_simp != 0:
예제 #11
0
파일: run.py 프로젝트: ferret-guy/Cam-Grade
warped = find_box(cv2.imread("test/pic-sheet.jpg"), draw=True)
dat = {}
from io import BytesIO
for i, (img, pts) in enumerate(warped):
    image_uri = "data:image/png;base64," + base64.b64encode(
        cv2.imencode(".png", img)[1])
    print "sending request {}".format(i)
    r = requests.post("https://api.mathpix.com/v3/latex",
                      data=json.dumps({'url': image_uri}),
                      headers={
                          "app_id": "<>",
                          "app_key": "<>",
                          "Content-type": "application/json"
                      })
    #print json.dumps(json.loads(r.text), indent=4, sort_keys=True)
    out = process_sympy(json.loads(r.text)['latex_anno'].replace(" ", ""))
    cv2.imshow("equ {}".format(i), img)
    print "{}:".format(i)
    pprint(out)
    print ""
    dat[str(i)] = json.loads(r.text)
    dat[str(i)]['numpy'] = str(srepr(out))
    dat[str(i)]['points'] = pts
cv2.waitKey(0)
returnData = {
    # HTTP Status Code:
    "status": 200,
    # Response Body:
    "body": dat,
    # Send any number of HTTP headers
    "headers": {
예제 #12
0
__author__ = 'sindytan'

import sympy
from process_latex import process_sympy
from sympy.core import Atom
from sympy.core import Function
from sympy.core import Derivative
from sympy.printing.dot import dotprint
from sympy import *

# myExpr = "f_{X+Y}(a) = \\frac{d}{da}\int_{\\infty}^{\\infty} F_X(a-y)f_Y(y)dy"
# myExpr = "f_{X+Y}(a) = \\frac{d}{da}\int_{\\infty}^{\\infty} F_X(a-y)f_Y(y)dy + N"
myExpr = '-2 (\\sum_i y_i˙- n w_0) '
# myExpr = '-2 (\sum_i y_i - (\sum_i x_i^T)  w˙- n w_0)'
expr = process_sympy(myExpr)
print expr

# get list of all subtrees / arguments of a SymPy expression
def get_subtrees(expr, subtrees):
    if len(expr.args) > 0:
        if expr.func not in subtrees:
            subtrees += [expr.func]
        for arg in expr.args:
            # if (not isinstance(arg, Atom)) and (arg not in subtrees):
            if arg not in subtrees:
                subtrees += [arg]
            get_subtrees(arg, subtrees)
        return subtrees
    else:
        return subtrees
예제 #13
0
def getlatexformula(formula):
    pformula = prepformula(formula)
    f = process_sympy(pformula)
    global latexformula
    latexformula = sympify(f)
    return latexformula
v = Matrix([1, 2])

# sub settings
sub_settings_symbols = {}
sub_settings_symbols[Symbol('M' + hashlib.md5('M'.encode()).hexdigest(),
                            real=True)] = M
sub_settings_symbols[Symbol('v' + hashlib.md5('v'.encode()).hexdigest(),
                            real=True)] = v

# one parameters
latex = "\\begin{matrix}1&2\\\\3&4\\end{matrix}\\cdot[!v!]"
equation_sympy_check = MatMul(
    M, Symbol('v' + hashlib.md5('v'.encode()).hexdigest(), real=True))
equation_sympy_subs_check = MatMul(M, v)
# placeholders
equation_sympy = process_sympy(latex)
print('latex = %s' % latex)
print('equation_sympy = %s' % equation_sympy)
print('equation_sympy_check = %s' % equation_sympy_check)
print('equation_sympy = %s' % (srepr(equation_sympy)))

equation_sympy_subs = equation_sympy.subs(sub_settings_symbols, evaluate=False)
print('equation_sympy_subs = %s' % equation_sympy_subs)
print('equation_sympy_subs_check = %s' % equation_sympy_subs_check)

# two parameters

# sub settings
print('')
print('============== Two Parameters -> M*v = Matrix*Vector =============')
sub_settings_symbols = {}
예제 #15
0
    "f(x,y,",
    "\\sin^x",
    "\\cos^2",
    "\\cos 1 \\cos",
    "@","#","$","%","&","*",
    "\\",
    "~",
    "\\frac{(2 + x}{1 - x)}"
]

total = 0
passed = 0
for s, eq in GOOD_PAIRS:
    total += 1
    try:
        if process_sympy(s) != eq:
            print("ERROR: \"%s\" did not parse to %s" % (s, eq))
        else:
            passed += 1
    except Exception as e:
        print("ERROR: Exception when parsing \"%s\"" % s)
for s in BAD_STRINGS:
    total += 1
    try:
        process_sympy(s)
        print("ERROR: Exception should have been raised for \"%s\"" % s)
    except Exception:
        passed += 1 

print("%d/%d STRINGS PASSED" % (passed, total))
예제 #16
0
def huluwa_solvers(expr_txt, txt_type='auto', debug_m=True):
    """
    :param expr_txt:
        需要求解的表达式,可能是单独的表达式,也可能是list形式,比如: 'x^2 + 3x + 8 = 9'或 '[x^2 + 3x + 8 = 9, y + x = 9]'
    :param txt_type:
        文本类型 latex/sympy/body
    :param debug_m:
        debug模式会返回所有模板结果,即便没有求得最终解
        非debug即正常模式,只返回有解的结果(下一步可以优化为只返回最优结果)
    :return:
    """
    global log_info, theme_info, step_info, element_relations, debug
    debug = debug_m
    # print('.....................------>', debug)
    # 解析方程组
    expr_txt = parse_expr_input(expr_txt)
    print('初始化模板信息......')
    get_theme_info()
    print('初始化解题步骤信息......')
    get_step_info()
    print('初始化数学元素关系图信息......')
    get_element_relations()
    log_info = []
    # import re
    if txt_type is 'auto':
        txt_type = parse_txt_type(expr_txt)
    print('txt_type:', txt_type)
    # txt_type = parse_txt_type(expr_txt)
    # print('txt_type:', txt_type)
    expr_list = []
    try:
        if txt_type == 'latex':
            if type(expr_txt) is list:
                expr_list = [[
                    parse_expr(str(process_sympy(x)), evaluate=False)
                    for x in expr_txt
                ]]
            else:
                expr_list = [
                    parse_expr(str(process_sympy(expr_txt)), evaluate=False)
                ]
            # print('expr_list:', expr_list)
        if txt_type == 'sympy':
            if type(expr_txt) is list:
                expr_list = [[parse_expr(x, evaluate=False) for x in expr_txt]]
            else:
                expr_list = [parse_expr(expr_txt, evaluate=False)]
        if txt_type == 'body':
            expr_txt = expr_txt.replace(',',
                                        ',').replace('$,$',
                                                     '').replace('$$', '')
            expr_txt = rex.sub('(<div>.*?</div>)', '', expr_txt)
            r1 = '\\$(.*?)\\$'
            latex_list = rex.findall(r1, expr_txt)
            a = Alegbra(latex_list)
            a.filter()
            a.fmt()
            a.sympy_check()
            expr_list = a.expr_list
    except:
        error = ' '.join([
            'huluwa_solvers expr:', expr_txt, '异常 at Line:',
            str(sys.exc_info()[-1].tb_lineno),
            str(sys.exc_info())
        ])
        print(error)
        log_info.append(error)
    return solvers(expr_list)
예제 #17
0
    "f(x,y,",
    "\\sin^x",
    "\\cos^2",
    "\\cos 1 \\cos",
    "@","#","$","%","&","*",
    "\\",
    "~",
    "\\frac{(2 + x}{1 - x)}"
]

total = 0
passed = 0
for s, eq in GOOD_PAIRS:
    total += 1
    try:
        if process_sympy(s) != eq:
            print("ERROR: \"%s\" did not parse to %s" % (s, eq))
        else:
            print(process_sympy(s))
            passed += 1
    except Exception as e:
        print("ERROR: Exception when parsing \"%s\"" % s)
for s in BAD_STRINGS:
    total += 1
    try:
        process_sympy(s)
        print("ERROR: Exception should have been raised for \"%s\"" % s)
    except Exception:
        passed += 1 

print("%d/%d STRINGS PASSED" % (passed, total))