def post(self, request, *args, **kwargs): #Definition of the symbols to be used within sympy. symbols = ['theta', 'x_1', 'x_2', 'y_2', 'y_1'] symbol_output = SymbolConstructor(symbols) #Read student answer step_number = json.loads(request.POST['step_number']) s_name = 'Step ' + str(step_number) print("\n \n entre aqui2 \n\n") #reading student answer and cleaning it. student_ans = CleanStudentAns( json.loads(request.POST['student_answer'])) #getting the data from the steps database datae = StepConstructor(s_name, self.prob_cons.prob_in).step_base #creating the step_student db. step_student = StudentStepCons(self.student_prob.p_student, datae) #Compare student answer with db answer. for i in range(0, len(student_ans.data_st)): data_est = student_ans.data_st[i] for j in range(0, datae.number_of_substeps): sub_name = 'Substep ' + str(j + 1) data_sol = SubstepConstructor(datae, sub_name) for s in ['\\left', '\\right']: data_est_s = data_est.replace(s, '') data_sol_s = data_sol.substep_base.answer.replace(s, '') data_est_sympy = process_sympy(data_est_s) data_sol_sympy = process_sympy(data_sol_s) data_sol_sympy = str(data_sol_sympy).replace('{1}', '1') data_sol_sympy = sympy.simplify( data_sol_sympy.replace('{2}', '2')) data_est_sympy = str(data_est_sympy).replace('{1}', '1') data_est_sympy = sympy.simplify( data_est_sympy.replace('{2}', '2')) data_sim = sympy.simplify(data_est_sympy - data_sol_sympy) #TO DO: Change this so each substep of the student has to be OK. if data_sim == 0: self.data = True break if data_sim != 0: self.data = False i_temp = i + 1 datax = json.dumps(self.data) return HttpResponse(datax, content_type='application/json') else: return HttpResponse("Lo estas llamando malito")
def LatexToSympy(data): # str list[4] data ode = process_sympy( data[0] ) sol = process_sympy( data[1] ) func = data[2] var = data[3] #Print_data_before_identification(ode,sol) print('>> latex translated to sympy') return SimpleIdentify(ode ,sol, func, var)
def formatSinglePart(strLatex): strEquation = str(process_sympy(strLatex)) if "dot*" in strEquation: strEquation = formatDot(strEquation) if "_{" in strEquation: strEquation = formatVariableName(strEquation) return strEquation
def parseIntegrateInput(f, lower, upper): try: process_sympy(f) except Exception: f = None # Check and set the evaluation bounds of the sum. try: lower = sp.Rational(lower) upper = sp.Rational(upper) except TypeError: lower = None upper = None # Return the input as a tuple. return (f, lower, upper)
def getQImage4Equation(self): iEditLine = len(self.equation) iHeight = 1.0 iWidth = 2.5 #if (iEditLine>4): # iHeight=0.2*(iEditLine-4)+1; if hasattr(self, 'rect'): # if self.rect.height()>100: # iHeight=self.rect.height()/100.0 if self.rect.width() > 200: iWidth = 2.5 * self.rect.width() / 200 InvariantFig = Figure(figsize=(iWidth, iHeight)) canvas = FigureCanvas(InvariantFig) SympyLines = [] for i in range(iEditLine): strData = self.equation[i] try: if '=' in strData: str1 = strData.split('=') leftEquation = str1[0].replace('$', '') rightEquation = str1[1].replace('$', '') strLeftEquation = str(process_sympy(leftEquation)) strRightEquation = str(process_sympy(rightEquation)) SympyLines.append('='.join( [strLeftEquation, strRightEquation])) InvariantFig.text(0.1, iHeight - 0.2 * (i + 1), strData, fontsize=10) except Exception as e: SympyLines.append(strData + "Error:" + str(e)) # print (str(e)) #try: # InvariantFig.text(0.1,iHeight-0.2*(i+1), strData,family="Consolas", fontsize=10) #except: # pass canvas.draw() size = canvas.size() width, height = size.width(), size.height() im = QImage(canvas.buffer_rgba(), width, height, QImage.Format_ARGB32) return im
def check_equations_and_generate_pngs(latex_equations): for i in latex_equations: print i is_multiple = len(latex_equations[0].split("="))>1 if(is_multiple): equations_raw = [process_sympy(i[2:-2]) for i in latex_equations] else: equations_raw = [process_sympy(i) for i in latex_equations] for i, equation in enumerate(latex_equations): sympy_equation_to_png(equation, "output"+str(i)+".png") if(is_multiple): equations = [sympy.simplify((i.args[0]-i.args[1]).doit()) for i in equations_raw] for i in equations: print "Equation "+str(i), sympy.solveset(i, domain=sympy.S.Complexes) solution_sets = [sympy.solveset(i, domain=sympy.S.Complexes) for i in equations] print "solution_sets" print solution_sets return [True]+[solution_sets[i-1].is_subset(solution_sets[i]) for i in range(1, len(solution_sets))] else: equations = [sympy.simplify(i.doit()) for i in equations_raw] return [True]+[sympy.solveset(equations[i-1]-equations[i])==sympy.solveset(0) for i in range(1, len(equations))]
def check_equations(latex_equations): equations = [process_sympy(i) for i in latex_equations] solution_sets = [ sympy.solveset(i, domain=sympy.S.Complexes) for i in equations ] for i in range(len(solution_sets)): if (solution_sets[i] != solution_sets[0]): print "You have a mistake in line ", i + 1, "!" print "The line is " print latex_equations[i] return print "No mistakes!"
def parseGraphInput(f, n, handed, lower, upper, plotSum, posCol, negCol): try: process_sympy(f) except Exception: f = None # Check and set the number of samples. try: n = int(n) except ValueError: n = None # Check and set the method of evaluating the Riemann sum. validHandedValues = ["left", "center", "centre", "right"] if (handed is not None): handed = handed.lower() if (handed not in validHandedValues): handed = None # Check and set the evaluation bounds of the sum. try: lower = sp.Rational(lower) upper = sp.Rational(upper) except TypeError: lower = None upper = None # Check and set the input for evaluating the running sum. if (plotSum is not None): if (plotSum.lower() in ("true", "false")): plotSum = plotSum.lower() == "true" else: plotSum = None # Return the input as a tuple. return (f, n, handed, lower, upper, plotSum, posCol, negCol)
def start(): global expr_r global expr_g global expr_b global max_r, max_b, max_g if request.method == "GET": return open("static/one-time.html").read() else: latex_r = request.form["r"] latex_g = request.form["g"] latex_b = request.form["b"] max_r = int(request.form["max_r"]) max_g = int(request.form["max_g"]) max_b = int(request.form["max_b"]) print max_r print max_g print max_b expr_r = process_sympy(latex_r).simplify() expr_g = process_sympy(latex_g).simplify() expr_b = process_sympy(latex_b).simplify() draw_image() return open("static/one-time.html").read()
def analyse_equations_handler(): equations_str = [] try: equations_str = request.get_json(force=True)['equations'] except: return json.dumps({'status': 'badrequest'}), 400 equations = [] invalid_equations = [] for i, eqs in enumerate(equations_str): try: eq = process_sympy(eqs) equations.append(eq) except: invalid_equations.append(i) if len(invalid_equations) > 0: res = { 'status': 'failparseequation', 'invalid_equations': invalid_equations } return json.dumps(res), 400 invalid_equations, free_vars, intermediate_vars, _ = uncertainty.analyse_equations( equations) if invalid_equations: res = { 'status': 'invalidequation', 'invalid_equations': invalid_equations } return json.dumps(res), 400 free_vars_name = [s.name for s in free_vars] intermediate_vars_name = [s.name for s in intermediate_vars] dimensions, constraints = unit.analyse_dimension(equations, free_vars, intermediate_vars) dimensions_name = {} for k in dimensions: dimensions_name[k.name] = dimensions[k] res = { 'status': 'ok', 'free_variables': free_vars_name, 'intermediate_variables': intermediate_vars_name, 'dimensions': dimensions_name, 'dimension_constraints': constraints } return json.dumps(res)
def ship_math(self): if len(self.math_fragment_stack) > 0: s = ' '.join(self.math_fragment_stack) if self.convert: try: m = process_latex.process_sympy(s) except: print("**** sympy conversion failed on {}".format(s)) m = s.strip() separator = " === " else: m = s.strip() separator = ":" if self.trace: print("Math{} {}".format(separator, m)) pos = len(self.equations) self.equations.append(m) for l in self.labels: if l in self.equation_labels: print("Warning: attempt to re-use label {}".format(l)) else: self.equation_labels[l] = pos self.labels = [] self.math_fragment_stack = []
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))
def parse_expression(latex_string): return sympy.sympify(process_sympy(latex_string))
def calculate_latex(latex_str, latex_out=False): expression = process_latex.process_sympy(latex_str) result = expression.doit() if latex_out: return sympy.latex(result) return result
from latex2sympy.process_latex import process_sympy import sympy eq = process_sympy("\cos s + 1 = 0") print(eq) res = sympy.solveset(eq) print(res)
def full_procedure_handler(): try: args = request.get_json(force=True) equations_str = args['equations'] units_str = args['units'] measures_str = args['measures'] values_str = args['values'] uncertainties_str = args['uncertainties'] check_unit = args['check_unit'] p = float(args['p']) except: return json.dumps({'status': 'badrequest'}), 400 for k in units_str: units_str[k] = unit.parse_unit(units_str[k], reserve_name=True) if units_str[k] == None: return json.dumps({'status': 'invalidunit', 'unit': k}), 400 equations = [] for eqs in equations_str: try: eq = process_sympy(eqs) equations.append(eq) except: return json.dumps({'status': 'failedparseequation'}), 400 invalid_equations, free_vars, intermediate_vars, symbols = uncertainty.analyse_equations( equations) if invalid_equations: return json.dumps({'status': 'invalidequation'}), 400 for k in symbols: if k not in units_str: return json.dumps({'status': 'badrequest'}), 400 if symbols[ k] in free_vars and k not in measures_str and k not in values_str: return json.dumps({'status': 'badrequest'}), 400 units = {} measures = {} values = {} uncertainties = {} try: for k in units_str: units[symbols[k]] = units_str[k] for k in measures_str: data = [sympy.S(i) for i in measures_str[k][0]] measure_instrument = get_instrument(measures_str[k][1], unit=units_str[k]) if measure_instrument == None: return json.dumps({ 'status': 'invalidinstrument', 'var': k }), 400 measures[symbols[k]] = (data, measure_instrument) for k in values_str: values[symbols[k]] = sympy.S(values_str[k]) for k in uncertainties_str: uncertainties[symbols[k]] = sympy.S(uncertainties_str[k]) if check_unit == 'true': valid, symbol = uncertainty.check_unit(equations, units) if not valid: return json.dumps({ 'status': 'inconsistentunit', 'lhs': symbol }), 400 latex = uncertainty.full_procedure(equations, measures, values, uncertainties, units, p) return json.dumps({'status': 'ok', 'latex': latex}) except Exception: traceback.print_exc() return json.dumps({'status': 'badrequest'}), 400
def latex_transfor_test(str=a): result = process_sympy(str) print result
def input(request, user): if request.method == "GET": form = SearchForm(request.GET) if form.is_valid(): raw_in = form.cleaned_data["i"] # remove question number raw_in = raw_in.rstrip("=") raw_in = re.sub(r"^\s*(?:[a-zA-Z]\s*[\).]|\d+\s*(?:\)|\.(?!\d)))", "", raw_in) raw_in = re.sub(r"[.,]+\s*\Z", r"", raw_in) try: # sympy doesn't care about 'y =' or 'f(x) =', ignore this pre_sym = raw_in if pre_sym.startswith("y ="): pre_sym = pre_sym[len("y ="):] pre_sym = re.sub( r"\A[a-zA-Z][\s]*[(][\s]*[xyz][\s]*[)][\s]*[=]", r"", pre_sym) expr = process_sympy(pre_sym) expr = expr.subs([(sympy.Symbol('e'), sympy.E), (sympy.Symbol('i'), sympy.I)]) wild = sympy.Wild('w') expr = expr.replace(wild**sympy.Symbol('circ'), (sympy.pi / 180) * wild) if isinstance(expr, sympy.Eq): input = 'solve(Eq(%s,%s,evaluate=False),dict=True)' % ( expr.args[0], expr.args[1]) else: input = str(expr) except Exception as e: print(e) input = raw_in # possible query parameter latex = raw_in # query parameter which can show image on top latex_mathjax = ''.join( ['<script type="math/tex; mode=display">', latex, '</script>']) if input.strip().lower() in ('random', 'example', 'random example'): return redirect('/random') g = SymPyGamma() r = None rLatex = [] if latex: rLatex = [{ "title": "Input", "input": input, "output": latex_mathjax }] t0 = time.time() r_new = g.eval(input) t1 = time.time() print("Time evaluating: " + str(t1 - t0)) if r_new: if r: r.extend(r_new) else: r = r_new if not r: r = [{ "title": "Input", "input": input, "output": "Can't handle the input." }] r = [elem for elem in r if elem["title"] not in ["Error", "Input"]] # For some reason the |random tag always returns the same result return ("result.html", { "input": input, "wolfram": raw_in, "result": r, "rLatex": rLatex, "form": form, "MEDIA_URL": settings.MEDIA_URL })
def process_formulae(formulae, formulae_json): #for each formula for formula in formulae: print("Formula Expression: " + formula) #formula annotation recommendation formula_feedback = "i" for formula_iter in formulae_json.Formulae: if formula_iter.Expression == formula: formula_feedback = input("Formula Name: " + formula_iter.Name + " y=yes/n=no/i=input?") if formula_feedback == "y" or formula_feedback == "i": break #TODO: do not break for all formulae, but jump to the next formula! #ask for formula name and QID if formula_feedback == "y": formula_name = formula_iter.Name formula_qid = formula_iter.WikiQID break else: formula_name = input("Formula Name: ") formula_qid = input("Formula QID: ") #extract identifiers processed_formula = process_sympy(formula) id = sympify(processed_formula) identifiers = id.atoms(Symbol) #create dictionary for formula identifiers formula_identifiers_json = Identifiers() #for each identifier for identifier in identifiers: identifier_symbol = str(identifier) print("Identifier Symbol: " + identifier_symbol) #identifier annotation recommendation identifier_feedback = "i" for formula_iter in formulae_json.Formulae: for identifier_iter in formula_iter.Identifiers: if identifier_iter.Symbol == identifier_symbol: identifier_feedback = input("Identifier Name: " + identifier_iter.Name + " yes/no/input?") if identifier_feedback == "y" or identifier_feedback == "i": break #ask for identifier name and QID if identifier_feedback == "y": identifier_name = identifier_iter.Name identifier_qid = identifier_iter.WikiQID else: identifier_name = input("Identifier Name: ") identifier_qid = input("Identifier QID: ") #store formula identifiers in json formula_identifiers_json.Identifiers.append( Identifier(identifier_symbol, identifier_name, identifier_qid)) #store formulae with identifiers in json formulae_json.Formulae.append( Formula(formula, formula_name, formula_qid, formula_identifiers_json.Identifiers)) return formulae_json
def convertInput(function): sympyedFunction = process_sympy(function).subs(e, E).subs("lambda", lamda) return sp.sympify(str(sympyedFunction))
def main(): data = read_in() results = process_sympy(data['latex2sympy']) print json.dumps(results)