def relation(interval_or_relation, var=x): """Return LaTeX that represents an interval or a relation as a chained inequality. e.g. [1, 5] --> 1 < x < 5 """ if isinstance(interval_or_relation, (sympy.StrictLessThan, sympy.LessThan, sympy.StrictGreaterThan, sympy.GreaterThan)): interval = functions.relation_to_interval(interval_or_relation) else: interval = interval_or_relation if isinstance(interval_or_relation, sympy.Union): raise NotImplementedError('unions are not yet supported') if interval.left == -sympy.oo and interval.right == sympy.oo: return r'{0} < {1} < {2}'.format(sympy.latex(-sympy.oo), sympy.latex(var), sympy.latex(sympy.oo)) elif interval.left == -sympy.oo: operator = r'<' if interval.right_open else r'\le' return r'{0} {1} {2}'.format(sympy.latex(var), operator, sympy.latex(interval.right)) elif interval.right == sympy.oo: operator = r'>' if interval.left_open else r'\ge' return r'{0} {1} {2}'.format(sympy.latex(var), operator, sympy.latex(interval.left)) else: left_operator = r'<' if interval.left_open else r'\le' right_operator = r'<' if interval.right_open else r'\le' return r'{0} {1} {2} {3} {4}'.format( sympy.latex(interval.left), left_operator, sympy.latex(var), right_operator, sympy.latex(interval.right) )
def print_latex(): # edo_main() for i in range(1, 7): Respostas[i] = sympy.nsimplify(Respostas[i], rational=True, tolerance=0.05).evalf(prec) # 0- Raizes; 1- Forma Natural da respsota; 2- Resposta Natural; # 3- Resposta Particular; 4- Resposta Transitoria; 5- Respsota Forcada # 6- Resposta Completa; 7-Sinal de entrada x(t); 8 - eq ### eqDiferencialEntradaLatex = latex(Respostas[8]) ##Perfumaria dif = 0.9 - 0.77 xdif = -0.15 font = {"family": "Sans", "weight": "normal", "size": 18} plt.rc("font", **font) ##Obtendo as respostas em Latex RespostasEmLatex = [0] * (len(Respostas)) raizEmLatex = [0] * (len(Respostas[0])) str_raizLatex = "" for i in range(len(Respostas[0])): raizEmLatex[i] = "$" + str(latex(Respostas[0][i])) + "$" for i in range(len(raizEmLatex)): rn = "r" + str(i + 1) + " = " rn = "$" + str(latex(rn)) + "$" str_raizLatex = str_raizLatex + "\t" + rn + raizEmLatex[i] ##print len(RespostasEmLatex) for i in range(len(Respostas)): RespostasEmLatex[i] = "$" + str(latex(Respostas[i])) + "$" # print RespostasEmLatex # xTLatex = '$' + latex(xT) +'$' ###Preparando para imprimir log_figure = plt.figure("Representacao", facecolor="white") ax1 = plt.axes(frameon=False) ax1.get_xaxis().tick_bottom() ax1.get_xaxis().set_visible(False) ax1.axes.get_yaxis().set_visible(False) for i in range(0, 8, 1): plt.axhline(0.86 - dif * i, xmin=-5, xmax=5, color="black", lw=0.2, linestyle=":") # log_figure.figure("Forma_Representativa:") plt.title("") plt.text(xdif, 0.89, "Eq dif: 0=" + ur"$" + eqDiferencialEntradaLatex + "$") plt.text(xdif, 0.89 - dif, "Forma Natural:" + ur"" + RespostasEmLatex[1]) plt.text(xdif, 0.9 - 2 * dif, "yn(t) = " + ur"" + RespostasEmLatex[2]) plt.text(xdif, 0.9 - 3 * dif, "ypar(t) = " + ur"" + RespostasEmLatex[3]) plt.text(xdif, 0.9 - 4 * dif, "ytran(t) = " + ur"" + RespostasEmLatex[4]) plt.text(xdif, 0.9 - 5 * dif, "yfor(t) = " + ur"" + RespostasEmLatex[5]) plt.text(xdif, 0.9 - 6 * dif, "yc(t) = " + ur"" + RespostasEmLatex[6]) plt.text(xdif, 0.9 - 7 * dif, "x(t) = " + ur"" + RespostasEmLatex[7]) plt.text(xdif, 0.9 - 8 * dif, "Raiz(es): " + ur"" + str_raizLatex) plt.subplots_adjust(left=0.11, bottom=0.08, right=0.50, top=0.88, wspace=0.22, hspace=0.21) ##log_figure.set_size_inches(19.2,10.8) # log_figure.show() plt.show() return log_figure
def formula(quantity): """ returns error formula of quantity as latex code Args: quantity: Quantity object Return: latex code string of error formula """ assert isinstance(quantity, Quantity) if quantity.error_formula is None: raise ValueError("quantity '%s' doesn't have an error formula." % quantity.name) formula = quantity.error_formula if isinstance(formula,str): return formula else: # replace "_err" by sigma function sigma = Function("\sigma") for var in formula.free_symbols: if var.name[-4:] == "_err": formula = formula.subs(var, sigma( Symbol(var.name[:-4], **var._assumptions))) latex_code = latex(sigma(quantity)) + " = " + latex(formula) form_button, form_code = pytex.hide_div('Formula', '$%s$' % (latex_code) , hide = False) latex_button, latex_code = pytex.hide_div('LaTex', latex_code) res = 'Error Formula for %s<div width=20px/>%s%s<hr/>%s<br>%s' % ( '$%s$' % latex(quantity), form_button, latex_button, form_code, latex_code) return render_latex(res)
def baseparms_pretty_latex(delta,Pb,Pd,Kd): base_latex = [] delta_b = Pb.T * delta delta_d = Pd.T * delta n_b = len(delta_b) n_d = len(delta_d) for i in range(n_b): _latex = latex( delta_b[i] ) l = [] for j in range(n_d): c = Kd[i,j] if c == -1 or c == 1: _latex += ' ' + ('+ ' if c > 0 else'') + latex( c * delta_d[j] ) elif c != 0 and j not in l: ll = [] for jj in range(j,n_d): cc = Kd[i,jj] if cc == c: l.append(jj) ll.append(delta_d[jj]) p = (' \, ( ',' ) ') if (len(ll) > 1) else (' \, ','') ll_sum = ' + '.join( [ latex( lli ) for lli in ll] ) _latex += ' ' + ('+ ' if c > 0 else'') + latex( c.n() ) + p[0] + ll_sum + p[1] base_latex.append(_latex) return base_latex;
def formula(self, quantity, adjust=True): """ returns error formula of quantity as latex code Args: quantity: name of quantity or Quantity object adjust: if True, replaces "_err" suffix by "\sigma" function and adds equals sign in front Return: latex code string of error formula """ quantity = quantities.parse_expr(quantity, self.data) assert isinstance(quantity, quantities.Quantity) if quantity.error_formula is None: raise ValueError("quantity '%s' doesn't have an error formula.") formula = quantity.error_formula if isinstance(formula,str): return formula else: # replace "_err" by sigma function if adjust: sigma = Function("\sigma") for var in formula.free_symbols: if var.name[-4:] == "_err": formula = formula.subs(var, sigma( Symbol(var.name[:-4], **var._assumptions))) return latex(sigma(quantity)) + " = " + latex(formula) return formula
def table_groesse(expr,variables,container,name,formula=False,einheit="default"): (X,expr,Sexpr)=eval_expr(expr,variables,container,name) if einheit!="default": X.convert_einheit(einheit) x=ur"\bigskip" if formula==True: x+=ur"\begin{equation*} "+name+" = "+sy.latex(expr)+"\end{equation*}" x+=ur"\begin{equation*} S"+name+" = "+sy.latex(Sexpr)+"\end{equation*}" s=ur"" s2=ur"" if X.x.dimensionality.string != "dimensionless": x+=ur"S"+name+" = "+sy.latex(Sexpr)+ur"\\" s=ur"" s2=ur"" if X.x.dimensionality.string != "dimensionless": s+=name+" in "+str(X.x.dimensionality.string) else: s+=name for k in X.x.magnitude: s+="& %.3f " % k s2+="r|" s+=ur"\\ \hline " if X.Sx.dimensionality.string!= "dimensionless": s+="S"+name+" in "+str(X.Sx.dimensionality.string) else: s+="S"+name for k in X.Sx.magnitude: s+="& %.3f " % k s+=ur"\\ \hline" x+=ur"""\normalsize \vspace{3 mm} \begin{tabular}{| l | """+s2+"""} \hline """+s+ur""" \end{tabular} \\ \bigskip """ return x
def arc_length_explain(self, start, stop, a_type = None, explanation_type=None, preview = None): if a_type is None: a_type = self.a_type v = self.v_ u = self.u start = sym.sympify(start) stop = sym.sympify(stop) if explanation_type is None: explanation_type = self.kwargs.get('explanation_type', 'simple') if preview is None: preview = self.kwargs.get('preview', False) explanation = ArcLengthProb(path='arc_length/explanation', a_type = a_type, explanation_type = explanation_type, preview = preview).explain() explanation += """ <p> For this problem the curve is $_C$_ is given by $_%s$_ with the independent variable being $_%s$_ on the interval $_[%s,%s]$_. So the arc length is $$s =\\int_{%s}^{%s} \sqrt{1+\\left(\\frac{d%s}{d%s}\\right)^2}\,d%s$$ $$\\frac{d%s}{d%s} = %s = %s$$ \\begin{align} \\sqrt{1 + \\left(%s\\right)^2} &= \\sqrt{%s} \\\\ &= \sqrt{\\left(%s\\right)^2} = %s \\end{align} </p> """%tuple(map(lambda x: sym.latex(x).replace("\\log","\\ln"), [sym.Eq(v, self.v), u, start, stop, start, stop, v, u, u, v, u, self.Dv, self.dv, self.dv, 1 + (self.dv**2).expand(), self.ds, self.ds])) aa = [sym.latex(self.arc_length(start, stop,'integral')), "\\left." + sym.latex(self.Ids).replace('\\log', '\\ln') + "\\right|_{%s=%s}^{%s=%s}"%(u, start, u, stop), sym.latex(self.arc_length(start, stop,'exact')).replace("\\log", "\\ln") + '\\approx %.3f'%(self.arc_length(start, stop,'numeric'))] # Add self.numeric / self.anti explanation += """ <p> Thus the arclength is given by %s </p> """%(tools.align(*aa)) # return explanation
def simplex_table_to_tex_table_only(table): ret = """\\begin{tabular}{|c|""" ret += ("c|"*(table.amount_of_vars + 1)) ret += "} \\hline" ret += " & \\T \\B $ " for j in range(table.amount_of_vars): ret += "$&$" ret += "x_{"+"{0:<2}".format(j) +"}" ret += "$\\\\ \\hline " for i in range(table.amount_of_equations): ret += "$x_{" + "{0:<2}".format(table.basis[i]) + "}$" ret += "& \\T \\B $ " ret += latex(table.free[i]) for j in range(table.amount_of_vars): ret += "$&$" ret += latex(table.limits[i][j]) ret += "$\\\\ \\hline " ret += "$\Psi$ & $" ret += latex(table.target_free) for j in range(table.amount_of_vars): ret += "$&\\T \\B$" ret += latex(table.target[j]) ret += "$\\\\ \\hline " ret += """\\end{tabular}""" return ret
def print_latex(): # 0- Raizes; 1- Forma Natural da respsota; 2- Resposta Natural; # 3- Resposta Particular; 4- Resposta Transitoria; 5- Respsota Forcada # 6- Resposta Completa # 7-Sinal de entrada x(t) ##Perfumaria dif = 0.9 -0.75 xdif = -0.15 font = {'family' : 'Arial', 'weight' : 'normal', 'size' : 18} plt.rc('font', **font) #plt.rc('text', usetex=True) ##Obtendo as respostas em Latex RespostasEmLatex = [0]*(len(Respostas)) #print len(RespostasEmLatex) for i in range(len(Respostas)):RespostasEmLatex[i] = '$'+str(latex(Respostas[i])) +'$' ## Tratamento Inicial para as raizes: #replace(a, old, new[, count]) #r'$\left( \begin{array}{ll} 2 & 3 \\ 4 & 5 \end{array} \right)$' #$\begin{bmatrix}-1.5, & 1.0\end{bmatrix}$ #\begin{Bmatrix} x & y \\ z & v \end{Bmatrix} #print RespostasEmLatex[0] #RespostasEmLatex[0]= RespostasEmLatex[0].replace("bmatrix","Bmatrix") #RespostasEmLatex[0]= RespostasEmLatex[0].replace("}$","})$",1) #print RespostasEmLatex[0] #### #print RespostasEmLatex xTLatex = '$' + latex(xT) +'$' ###Preparando para imprimir log_figure = plt.figure("Representacao",facecolor='white') ax1 = plt.axes(frameon = False) ax1.get_xaxis().tick_bottom() ax1.get_xaxis().set_visible(False) ax1.axes.get_yaxis().set_visible(False) for i in range(0,7,1):plt.axhline(dif*i,xmin = -5,xmax = 5, color = 'black',lw =1.5, linestyle = ':') #log_figure.figure("Forma_Representativa:") plt.title('') #print RespostasEmLatex[0] #plt.text(xdif,0.05,'Raizes:'+str(Respostas[0])) plt.text(xdif,0.9,'Forma Natural:'+ur''+RespostasEmLatex[1]) plt.text(xdif,0.9-dif,'yn(t) = '+ur''+RespostasEmLatex[2]) plt.text(xdif,0.9-2*dif,'ypar(t) = '+ur''+RespostasEmLatex[3]) plt.text(xdif,0.9-3*dif,'ytran(t) = '+ur''+RespostasEmLatex[4]) plt.text(xdif,0.9-4*dif,'yfor(t) = '+ur''+RespostasEmLatex[5]) plt.text(xdif,0.9-5*dif,'yc(t) = '+ur''+RespostasEmLatex[6]) plt.text(xdif,0.9-6*dif,'x(t) = '+ur''+xTLatex) log_figure.show()
def visit_Call(self, node): buffer = [] fname = node.func.id # Only apply to lowercase names (i.e. functions, not classes) if fname in self.__class__.EXCEPTIONS: node.func.id = self.__class__.EXCEPTIONS[fname].__name__ self.latex = sympy.latex(self.evaluator.eval_node(node)) else: result = self.format(fname, node) if result: self.latex = result elif fname[0].islower() and fname not in OTHER_SYMPY_FUNCTIONS: buffer.append("\\mathrm{%s}" % fname.replace('_', '\\_')) buffer.append('(') latexes = [] for arg in node.args: if isinstance(arg, ast.Call) and arg.func.id[0].lower() == arg.func.id[0]: latexes.append(self.visit_Call(arg)) else: latexes.append(sympy.latex(self.evaluator.eval_node(arg))) buffer.append(', '.join(latexes)) buffer.append(')') self.latex = ''.join(buffer) else: self.latex = sympy.latex(self.evaluator.eval_node(node)) return self.latex
def solution_statement(self): lines = solutions.Lines() derivative = self._qp['equation'].diff() lines += r'''$y = {equation}, y' = {derivative}$'''.format( equation=sympy.latex(self._qp['equation']), derivative=sympy.latex(derivative) ) original_y_coordinate = self._qp['equation'].subs({x: self._qp['location']}) lines += r'$y({original_x_coordinate}) = {original_y_coordinate}$'.format( original_x_coordinate=self._qp['location'], original_y_coordinate=original_y_coordinate ) derivative_at_original_location = derivative.subs({x: self._qp['location']}) lines += r'''$y'({original_x_coordinate}) = {derivative_at_original_location}$'''.format( original_x_coordinate=self._qp['location'], derivative_at_original_location=sympy.latex(derivative_at_original_location) ) unevaluated_approximation_of_answer = noevals.noevalAdd(original_y_coordinate, noevals.noevalMul(self._qp['delta'], derivative_at_original_location)) answer = original_y_coordinate + self._qp['delta'] * derivative_at_original_location lines += r'$\therefore y({new_x_coordinate}) \approx {unevaluated_approximation_of_answer} = {answer}$'.format( new_x_coordinate=self._qp['new_location'], unevaluated_approximation_of_answer=noevals.latex(unevaluated_approximation_of_answer), answer=sympy.latex(answer) ) return lines.write()
def solution_statement(self): lines = solutions.Lines() second_derivative = self._qp['equation'].diff().diff() second_derivative_leibniz_form = r'{derivative}({location})'.format( derivative=expressions.derivative(upper_variable="x", lower_variable="y", degree=2), location=self._qp['location'] ) second_derivative_at_original_location = second_derivative.subs({x: self._qp['location']}) lines += r'''The function is {concave_or_convex} at $x = {location}$ since the second derivative ${second_derivative_leibniz_form} = {second_derivative_at_original_location}$ is {greater_than_or_less_than} than $0$.'''.format( concave_or_convex=self._qp['concave_or_convex'], location=self._qp['location'], second_derivative_leibniz_form=second_derivative_leibniz_form, second_derivative_at_original_location=sympy.latex(second_derivative_at_original_location), greater_than_or_less_than='greater than' if second_derivative_at_original_location > 0 else 'less than' ) lines += r'''Therefore, the gradient of ${equation}$ {increases_or_decreases} as $x$ moves from ${location}$ to ${new_location}$ and as a result, linear approximation {under_or_over}estimates the true value of ${unevaluated_f_of_new_location}$'''.format( equation=sympy.latex(self._qp['equation']), increases_or_decreases='increases' if second_derivative_at_original_location > 0 else 'decreases', location=self._qp['location'], new_location=self._qp['new_location'], under_or_over='under' if self._qp['concave_or_convex'] else 'over', unevaluated_f_of_new_location=sympy.latex(self._qi['noeval_equation'].subs({x: self._qp['new_location']})) ) return lines.write()
def solution_statement(self): lines = solutions.Lines() if self._qp['question_type'] == 'one_x': answer = self._qp['prob_table'][self._qp['x_value']] ** self._qp['n_days'] lines += r'$Pr(X = {x_value}$, {n_days} days in a row$) = {probability_of_x}^{n_days} = {answer}.$'.format( x_value=self._qp['x_value'], n_days=self._qp['n_days'], probability_of_x=sympy.latex(self._qp['prob_table'][self._qp['x_value']]), answer=sympy.latex(answer) ) elif self._qp['question_type'] == 'any_x': sum_of_probabilities = ' + '.join([r'''Pr(X = {0})^{1}'''.format(k, self._qp['n_days']) for k in self._qp['prob_table']]) lines += r'''$Pr(X$ is the same number {n_days} days in a row$) = {sum_of_probabilities}$'''.format( n_days=self._qp['n_days'], sum_of_probabilities=sum_of_probabilities ) sum_of_probabilities = ' + '.join(['({0})^{1}'.format(sympy.latex(v), self._qp['n_days']) for v in self._qp['prob_table'].values()]) answer = sum(v ** self._qp['n_days'] for v in self._qp['prob_table'].values()) lines += r'''$= {sum_of_probabilities} = {answer}$'''.format( sum_of_probabilities=sum_of_probabilities, answer=sympy.latex(answer) ) return lines.write()
def prob1_25(part=1): cs = CartesianCS x, y, z = sym.symbols('x, y, z') A = sym.Matrix([cs.x, 2*cs.y, 3*cs.z]) B = sym.Matrix([3 * cs.y, -2 * cs.x, 0]) print('\\item \\curl{A} = $%s$' % my_xyzvec(cs.curl(A))) print('\\item \\curl{B} = $%s$' % my_xyzvec(cs.curl(B))) print('\\item \\diver{A} = $%s$' % sym.latex(cs.div(A))) print('\\item \\diver{B} = $%s$' % sym.latex(cs.div(B))) if part == 1: lhs = cs.div(A.cross(B)) print('lhs = %s' % sym.latex(lhs)) t1 = B.dot(cs.curl(A)) print('B dot (curl(A): %s' %sym.latex(t1)) t2 = A.dot(cs.curl(B)) print('A dot (curl(B): %s' % sym.latex(t2)) rhs = t1 - t2 print('B dot curl(A) - A dot curl(B): %s' % sym.latex(rhs)) if part == 2: lhs = cs.grad(A.dot(B)) print('lhs = %s' % sym.latex(lhs)) t1 = B.dot(cs.curl(A)) print('B dot (curl(A): %s' %sym.latex(t1)) t2 = A.dot(cs.curl(B)) print('A dot (curl(B): %s' % sym.latex(t2)) rhs = t1 - t2 print('B dot curl(A) - A dot curl(B): %s' % sym.latex(rhs))
def __str__(self): s = "" xi = [r'\vec i', r'\vec j', r'\vec k'] phi = r"\phi(\vec r)" for key in sorted(self.stateMap.keys()): s += self.beginTable() qNums = str(self.stateMap[key]).strip("]").strip("[") genericFactor = self.genericFactor(self.stateMap[key]) s += "$\phi_{%d} \\rightarrow \phi_{%s}$\\\\\n" % (key, qNums) s += "\hline\n" s += "$%s$ & $%s$\\\\\n" % (phi, latex(self.orbitals[key]/genericFactor)) s += "\hline\n" for i in range(self.dim): s+= "$%s\cdot \\nabla %s$ & $%s$\\\\\n" % \ (xi[i], phi, latex(self.gradients[key][i]/genericFactor)) s += "\hline\n" s += "$\\nabla^2 %s$ & $%s$\\\\\n" % (phi, latex(self.Laplacians[key]/genericFactor)) s += self.endTable(caption="Orbital expressions %s : %s. Factor $%s$ is omitted." % \ (self.__class__.__name__, qNums, latex(genericFactor))) if (key+1)%self.figsPrPage == 0: s += "\\clearpage\n" return s
def simplex_table_to_tex_solution_only(table): solution = '' var, target = table.solution for i in range(table.amount_of_vars): solution += "$x_{" + "{0:<2}".format(i) + "} = " + latex(var[i]) + '$\\\\' solution += '$\Psi = ' + latex(target) + '$' return solution
def print_latex(): # 0- Raizes; 1- Forma Natural da respsota; 2- Resposta Natural; # 3- Resposta Particular; 4- Resposta Transitoria; 5- Respsota Forcada # 6- Resposta Completa # 7-Sinal de entrada x(t) dif = 0.9 -0.75 fontSize = 18 ##Obtendo as respostas em Latex RespostasEmLatex = [0]*(len(Respostas)) print len(RespostasEmLatex) for i in range(len(Respostas)):RespostasEmLatex[i] = '$'+str(latex(Respostas[i])) +'$' #print RespostasEmLatex xTLatex = '$' + latex(xT) +'$' ###Preparando para imprimir log_figure = plt.figure('Latex Representation') plt.title('Respostas na forma representativa',fontsize = fontSize) plt.text(0.001,0.9,'Forma Natural:'+ur''+RespostasEmLatex[1],fontsize = fontSize) plt.text(0.001,0.9-dif,'yn(t) = '+ur''+RespostasEmLatex[2],fontsize = fontSize) plt.text(0.001,0.9-2*dif,'ypar(t) = '+ur''+RespostasEmLatex[3],fontsize = fontSize) plt.text(0.001,0.9-3*dif,'ytran(t) = '+ur''+RespostasEmLatex[4],fontsize = fontSize) plt.text(0.001,0.9-4*dif,'yfor(t) = '+ur''+RespostasEmLatex[5],fontsize = fontSize) plt.text(0.001,0.9-5*dif,'yc(t) = '+ur''+RespostasEmLatex[6],fontsize = fontSize) plt.text(0.001,0.9-6*dif,'x(t) = '+ur''+xTLatex,fontsize = fontSize) log_figure.show()
def problem_to_str(obj, gs = None, hs = None, plain = True): strret = '' gpresent = gs is not None and len(gs)>0 hpresent = hs is not None and len(hs)>0 if not plain: strret += 'Minimizing ' strret += '$\mathcal{L}(%s)$' % sp.latex(obj) if gpresent or hpresent: strret += ('\n\nsubject to \t') if gpresent: for g in gs: strret += ' $%s$, \t' % sp.latex(g) strret += '\n' if hpresent: for h in hs: strret += '$\mathcal{L}(%s) = 0$, \t' % sp.latex(h) strret = strret.strip(',') else: strret += '\t subject to no constraints' else: strret += 'Minimizing ' strret += ' L(%s) ' % str(obj) if gpresent or hpresent: strret += ('\nsubject to \t') if gpresent: for g in gs: strret += ' %s, \t' % str(g) strret += '\n' if hpresent: for h in hs: strret += '$L(%s) = 0$, \t' % str(h) strret = strret.strip(',') else: strret += '\t subject to no constraints' return strret
def do_it(j_foo, s0, _s0, s1, _s1, is_swap, is_map, zones_amount): s0_max, s0_min = process_maxmin(_s0) s1_max, s1_min = process_maxmin(_s1) j_foo = j_foo.replace(str(s0), 'x') j_foo = j_foo.replace(str(s1), 'y') j_foo = j_foo.replace('L', '') zone_pl = '' is_zone = False if zones_amount != None: is_zone = True zone_pl += "set pal maxcolors 4; set pm3d corners2color c1; unset colorbox;" map_pl = 'set pm3d\n' if is_map: map_pl += 'set pm3d map\n' for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]: file_mod = list() if is_map: file_mod.append('map') if is_zone: file_mod.append('zone') if is_swap: file_mod.append('swap') if x: file_mod.append('rx') if y: file_mod.append('ry') s0_rev, s0_max, s0_min = process_reverse(x, s0_max, s0_min) s1_rev, s1_max, s1_min = process_reverse(y, s1_max, s1_min) gr3d = gnu_rend() gr3d.put_some(plot_tpl % (latex(s0), s0_min, s0_max, s0_rev, latex(s1), s1_min, s1_max, s1_rev, map_pl, zone_pl, j_foo) ) gr3d.compile( report_plot_file_name % ( (len(file_mod) and "_" or "") + "_".join(file_mod) ) )
def print_latex_new(): ##Obtendo as respostas em Latex RespostasEmLatex = [0]*(len(Respostas)) raizEmLatex = [0]*(len(Respostas[0])) str_raizLatex ="" for i in range(len(Respostas[0])): raizEmLatex[i] = '$'+str(latex(Respostas[0][i])) +'$' for i in range(len(raizEmLatex)): rn = "r"+str(i+1)+" = " rn = '$'+str(latex(rn)) +'$' str_raizLatex = str_raizLatex+"\t"+rn+raizEmLatex[i] ##print len(RespostasEmLatex) for i in range(len(Respostas)): RespostasEmLatex[i] = '$'+str(latex(Respostas[i])) +'$' #print RespostasEmLatex #xTLatex = '$' + latex(xT) +'$' ###Preparando para imprimir dif = 0.9 -0.77 xdif = -0.15 font = {'family' : 'Sans', 'weight' : 'normal', 'size' : 18} figure_latex = Figure(facecolor = 'white') plot_latex = figure_latex.add_subplot(111) #plot_latex.rc('font',**font) #axes_latex = plot_latex.axes(frameon = False) #axes_latex.get_xaxis().tick_bottom() #axes_latex.get_xaxis().set_visible(False) #axes_latex.axes.get_yaxis().set_visible(False) plot_latex.plot(arange(0.0,50.0,1.2)) plot_latex.canvas.draw()
def solution_statement(self): lines = solutions.Lines() ball_combinations = itertools.combinations(self._qp['items'], self._qp['n_selections']) valid_total_sum_combinations = [i for i in ball_combinations if sum(i) == self._qp['sum']] # e.g. Pr(sum = 14) = 3! * Pr(ball1 = 3 and ball2 = 5 and ball3 = 6) lines += r'$Pr(\text{{sum}} = {sum}) = {sum_of_probabilities}$'.format( sum=self._qp['sum'], sum_of_probabilities=expressions.sum_combination_probabilities(valid_total_sum_combinations) ) probability_of_a_single_combination = self.single_combination_probability() prob_instance = r'{n_valid_permutations} \times {probability_of_a_single_combination}'.format( n_valid_permutations=math.factorial(self._qp['n_selections']), probability_of_a_single_combination=sympy.latex(probability_of_a_single_combination) ) # e.g. = 6 * (1/120) + 6 * (1/120) lines += r'$= {probabilities_sum}$'.format( probabilities_sum=' + '.join([prob_instance] * len(valid_total_sum_combinations)) ) answer = probability_of_a_single_combination * math.factorial(self._qp['n_selections']) * len(valid_total_sum_combinations) # e.g. = 1/20 lines += r'$= {answer}$'.format(answer=sympy.latex(answer)) return lines.write()
def print_model(model, print_residuals=True): from sympy import latex if print_residuals: from dolo.symbolic.model import compute_residuals res = compute_residuals(model) if len(model.equations_groups) > 0: if print_residuals: eqs = [["", "Equations", "Residuals"]] else: eqs = [["", "Equations"]] for groupname in model.equations_groups: eqg = model.equations_groups eqs.append([groupname, ""]) if print_residuals: eqs.extend( [["", "${}$".format(latex(eq)), str(res[groupname][i])] for i, eq in enumerate(eqg[groupname])] ) else: eqs.extend([["", "${}$".format(latex(eq))] for eq in eqg[groupname]]) txt = print_table(eqs, header=True) return txt else: if print_residuals: table = [(i + 1, "${}$".format(latex(eq)), str(res[i])) for i, eq in enumerate(model.equations)] else: table = [(i + 1, "${}$".format(latex(eq))) for i, eq in enumerate(model.equations)] txt = print_table([["", "Equations"]] + table, header=True) return txt
def _latex(self, *args): equations = [] t = sympy.Symbol('t') for eq in self._equations.itervalues(): # do not use SingleEquations._latex here as we want nice alignment varname = sympy.Symbol(eq.varname) if eq.type == DIFFERENTIAL_EQUATION: lhs = sympy.Derivative(varname, t) else: # Normal equation or parameter lhs = varname if not eq.type == PARAMETER: rhs = eq.expr.sympy_expr if len(eq.flags): flag_str = ', flags: ' + ', '.join(eq.flags) else: flag_str = '' if eq.type == PARAMETER: eq_latex = r'%s &&& \text{(unit: $%s$%s)}' % (sympy.latex(lhs), sympy.latex(eq.unit), flag_str) else: eq_latex = r'%s &= %s && \text{(unit: $%s$%s)}' % (sympy.latex(lhs), sympy.latex(rhs), sympy.latex(eq.unit), flag_str) equations.append(eq_latex) return r'\begin{align}' + r'\\'.join(equations) + r'\end{align}'
def substitute(expr, var, value): latex = sympy.latex(expr) print(latex) latex = latex.replace(sympy.latex(var), sympy.latex(value)) return latex
def print_latex(): for i in range(1,7):Respostas[i] = sympy.nsimplify(Respostas[i].evalf(prec), rational = True,tolerance = 0.05) # 0- Raizes; 1- Forma Natural da respsota; 2- Resposta Natural; # 3- Resposta Particular; 4- Resposta Transitoria; 5- Respsota Forcada # 6- Resposta Completa # 7-Sinal de entrada x(t) ### eqDiferencialEntradaLatex = latex(eq) ##Perfumaria dif = 0.9 -0.77 xdif = -0.15 font = {'family' : 'Sans', 'weight' : 'normal', 'size' : 18} plt.rc('font', **font) ##Obtendo as respostas em Latex RespostasEmLatex = [0]*(len(Respostas)) raizEmLatex = [0]*(len(Respostas[0])) str_raizLatex ="" for i in range(len(Respostas[0])): raizEmLatex[i] = '$'+str(latex(Respostas[0][i])) +'$' for i in range(len(raizEmLatex)): rn = "r"+str(i+1)+" = " rn = '$'+str(latex(rn)) +'$' str_raizLatex = str_raizLatex+"\t"+rn+raizEmLatex[i] ##print len(RespostasEmLatex) for i in range(len(Respostas)): RespostasEmLatex[i] = '$'+str(latex(Respostas[i])) +'$' #print RespostasEmLatex xTLatex = '$' + latex(xT) +'$' ###Preparando para imprimir log_figure = plt.figure("Representacao",facecolor='white') ax1 = plt.axes(frameon = False) ax1.get_xaxis().tick_bottom() ax1.get_xaxis().set_visible(False) ax1.axes.get_yaxis().set_visible(False) for i in range(0,8,1): plt.axhline(0.86-dif*i,xmin = -5,xmax = 5, color = 'black',lw =0.2, linestyle = ':') #log_figure.figure("Forma_Representativa:") plt.title("Eq dif: 0="+ur'$'+eqDiferencialEntradaLatex+'$', loc = 'left',fontsize = 15) plt.text(xdif,0.89,'Forma Natural:'+ur''+RespostasEmLatex[1]) plt.text(xdif,0.9-dif,'yn(t) = '+ur''+RespostasEmLatex[2]) plt.text(xdif,0.9-2*dif,'ypar(t) = '+ur''+RespostasEmLatex[3]) plt.text(xdif,0.9-3*dif,'ytran(t) = '+ur''+RespostasEmLatex[4]) plt.text(xdif,0.9-4*dif,'yfor(t) = '+ur''+RespostasEmLatex[5]) plt.text(xdif,0.9-5*dif,'yc(t) = '+ur''+RespostasEmLatex[6]) plt.text(xdif,0.9-6*dif,'x(t) = '+ur''+xTLatex) plt.text(xdif,0.9-7*dif,'Raiz(es): '+ur''+str_raizLatex) ##log_figure.set_size_inches(19.2,10.8) #log_figure.show() plt.show() return log_figure
def question_statement(self): return r'Find $Pr(X {minor_direction} {minor_bound} | X {major_direction} {major_bound})$.'.format( minor_direction=self._qp['minor_direction'], minor_bound=sympy.latex(self._qp['minor_bound']), major_direction=self._qp['major_direction'], major_bound=sympy.latex(self._qp['major_bound']) )
def solution_statement(self): lines = solutions.Lines() if self._qp['question_type'] == 'mean': lines += r'$E(X) = \sum\limits_{{i=1}}^{{n}} x_{{i}} \times Pr(X = x_{{i}})$' lines += r'$= {expectation_of_x} = {answer}$'.format( expectation_of_x=expressions.discrete_expectation_x(self._qp['prob_table']), answer=self._qp['answer'] ) elif self._qp['question_type'] == 'variance': lines += r'$Var(X) = E(X^2) - (E(X))^2$' lines += r'$= [{expectation_of_x_squared}] - [{expectation_of_x}]^2$'.format( expectation_of_x_squared=expressions.discrete_expectation_x_squared(self._qp['prob_table']), expectation_of_x=expressions.discrete_expectation_x(self._qp['prob_table']) ) expectation_of_x = prob_table.expectation_x(self._qp['prob_table']) expectation_of_x_squared = prob_table.expectation_x(self._qp['prob_table'], power=2) lines += r'$= {expectation_of_x_squared} - {expectation_of_x}^2 = {answer}$'.format( expectation_of_x_squared=sympy.latex(expectation_of_x_squared), expectation_of_x=sympy.latex(expectation_of_x), answer=sympy.latex(self._qp['answer']) ) elif self._qp['question_type'] == 'mode': lines += r'${answer}$'.format( answer=prob_table.mode(self._qp['prob_table']) ) return lines.write()
def solution_statement(self): lines = solutions.Lines() integral, integral_intermediate, integral_intermediate_eval = \ expressions.integral_trifecta(expr=self._qp['equation'], lb=self._qi['domain'].left, ub=self._qi['domain'].right) lines += r'$Pr(X {direction} {unknown}) = {integral}$'.format( direction=self._qi['inequality'], unknown=self._qi['unknown'], integral=integral ) lines += r'$= {0}$'.format(integral_intermediate) lines += r'$= {integral_intermediate_eval} = {value}$'.format( integral_intermediate_eval=integral_intermediate_eval, value=sympy.latex(self._qi['value']) ) if self._qp['direction'] == 'left': left_side = self._qp['equation'].integrate().subs({x: self._qi['unknown']}) right_side = self._qi['value'] + self._qp['equation'].integrate().subs({x: self._qp['domain'].left}) else: left_side = -1 * self._qp['equation'].integrate().subs({x: self._qi['unknown']}) right_side = self._qi['value'] - self._qp['equation'].integrate().subs({x: self._qp['domain'].right}) lines += r'${0} = {1}$'.format(sympy.latex(left_side), sympy.latex(right_side)) lines += expressions.shrink_solution_set(left_side, self._qp['domain'], expr_equal_to=right_side, var=self._qi['unknown']) return lines.write()
def integrar(self,event): x = sympy.Symbol("x") fx = self.fun.GetValue() # Función original fx = preproc(fx) Fx = sympy.integrate(eval(fx)) # Función integrada str_Fx = "$\int \, (%s) \,dx \,= \,%s + C$"%(sympy.latex(eval(fx)), sympy.latex(Fx)) self.string.set_text(str_Fx) self.canvas.draw()
def derivar(self,event): x = sympy.Symbol("x") fx = self.fun.GetValue() # Función original fx = preproc(fx) Fx = sympy.diff(eval(fx)) # Función derivada str_Fx = "$\\frac{d}{dx}(%s)\, = \,%s$"%(sympy.latex(eval(fx)), sympy.latex(Fx)) self.string.set_text(str_Fx) self.canvas.draw() # "Redibujar"
def to_latex(self, comments=False): COMP = { 'LEQ' : r"""\leq""", 'EQ' : r"""=""", 'GEQ' : r"""\geq""", } prefix = r""" \[ \left\{ \begin{array}{""" prefix += "cc"*(len(self.variables)+2) + "}" suffix1 = r""" \end{array} \right. \] \[""" suffix2 = r"""\]""" lines = [prefix] if self.standard: for constraint in self.constraints: lines.append(constraint.std_latex_array(out_var=self.out)) # import pdb; pdb.set_trace() utility_line = "z & = & " utility = self.utility_constraint if utility.get_scalar()[1] == 0: skip = True else: skip = False utility_line += sympy.latex(utility.get_scalar()[1]) for variable in self.variables: var_coeff = utility.get_coeff(variable)[1] substitution = utility.substitutions.get(variable, variable) if var_coeff > 0: if skip: utility_line += " & & " + sympy.latex(sympy.Mul(var_coeff, substitution, evaluate=False)) skip = False else: utility_line += " & + & " + sympy.latex(sympy.Mul(var_coeff, substitution, evaluate=False)) elif var_coeff < 0: utility_line += " & - & " + sympy.latex(sympy.Mul(-var_coeff, substitution, evaluate=False)) skip = False lines.append(utility_line) lines.append(suffix1) else: for constraint in self.constraints: lines.append(constraint.latex_array()) lines.append(suffix1) lines.append(self.optimizer + " z="+sympy.latex(self.utility)) lines.append(suffix2) if self.current_solution: lines.append(self.view_solution()) if comments: return "\n".join([self.comments] + lines) else: return "\n".join(lines)
# argument # register_size, gates, measurements, controlled_gates, circuit and # input_register need to be in data data = json.loads(sys.argv[1]) try: # Initialize a new simulation using this data sim = QuantumSimulation(data) # Run the simulation sim.simulate() # Print out a JSONified version of the results print pipes.quote( json.dumps({ 'results': sim.results, 'probabilities': sim.probabilities })) except InvalidMatrix, e: # If some of the matrices weren't unitary when they were meant to be, # or weren't hermitian when they were meant to be then return an # error back to ruby print pipes.quote( json.dumps({ 'error': { 'type': 'invalid_matrix', 'matrix': urllib.quote(latex(e.matrix)), 'size': e.matrix.rows, 'mtype': e.mtype } }))
def eq_solver(equation): list_eq = [] for eq in equation: string = "" # left : 0 , right : 1 for i, side in enumerate(eq.split("=")): if side[0] not in ["+", "-"]: side = "+" + side pos_sign = [i for i, char in enumerate(side) if char in ["+", "-"]] pos_sign.append(len(side)) for j in range(len(pos_sign) - 1): string += process_str(side[pos_sign[j]:pos_sign[j + 1]], i) list_eq.append(string) print(list_eq) result = sympy.solve([parse_expr(i) for i in list_eq]) # print(result) str_result = "" if type(result) == dict: for i, key in enumerate(result): if i == 0: if len(result) == 1: str_result += "( {} = {} )".format( sympy.latex(key), sympy.latex(result[key])) else: str_result += "( {} = {} ,".format( sympy.latex(key), sympy.latex(result[key])) elif i == len(result) - 1: str_result += " {} = {} )".format(sympy.latex(key), sympy.latex(result[key])) else: str_result += " {} = {} ,".format(sympy.latex(key), sympy.latex(result[key])) return [str_result] else: if len(result) == 0: return ["PHƯƠNG TRÌNH VÔ NGHIỆM"] list_result = [] for r in result: str_result = "" for i, key in enumerate(r): if i == 0: if len(r) == 1: str_result += "( {} = {} )".format( sympy.latex(key), sympy.latex(r[key])) else: str_result += "( {} = {} ,".format( sympy.latex(key), sympy.latex(r[key])) elif i == len(r) - 1: str_result += " {} = {} )".format(sympy.latex(key), sympy.latex(r[key])) else: str_result += " {} = {} ,".format(sympy.latex(key), sympy.latex(r[key])) # Replace "//" to "/" list_result.append(str_result) return list_result
plt.ylabel('Angle (rad)') plt.grid() plt.show() # DETERMINE THE IMPULSE RESPONSE OF THE SYSTEM (kick) # F(s) = 1, X1(s) = G_x, x1(t) = inv_lap(x1) x1_t = sym.inverse_laplace_transform(G_x, s, t) print(sym.latex(x1_t)) sym.pprint(G_x) # unfortunately I seem to be getting a bad result here as it cannot be computed in the # c.impulse_response() # DETERMINE THE STEP RESPONSE OF THE SYSTEM (push) x3_step_t = sym.inverse_laplace_transform(G_x/s, s, t) sym.pprint(x3_step_t) print(sym.latex(x3_step_t)) ''' # DETERMINE THE FREQUENCY RESPONSE OF THE SYSTEM (shake) w = sym.symbols('w', real=True, positive=True) x3_freq_t = sym.inverse_laplace_transform(G_x * w**2 / (s**2 + w**2), s, t) sym.pprint(x3_freq_t.simplify()) print(sym.latex(x3_freq_t)) ''' t_imp, x3_imp = C.impulse_response(G_x) plt.plot(t_imp, x3_imp) plt.xlabel('Time (s)') plt.ylabel('Angle (rad)') plt.grid() plt.show() '''
def latex(self, prec=15, nested_scope=None): """Return the corresponding math mode latex string.""" # pylint: disable=unused-argument # TODO prec ignored return sympy.latex(self.sym(nested_scope))
print(r'\bm{\mbox{Two dimensioanal submanifold - Unit sphere}}') print(r'\text{Basis not normalised}') sp2coords = (theta, phi) = symbols('theta phi', real=True) sp2param = [sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta)] sp2 = g3.sm(sp2param, sp2coords, norm=False) # submanifold (etheta, ephi) = sp2.mv() # sp2 basis vectors (rtheta, rphi) = sp2.mvr() # sp2 reciprocal basis vectors sp2grad = sp2.grad sph_map = [1, theta, phi] # Coordinate map for sphere of r = 1 print(r'(\theta,\phi)\rightarrow (r,\theta,\phi) = ', latex(sph_map)) (etheta, ephi) = sp2.mv() print(r'e_\theta | e_\theta = ', etheta | etheta) print(r'e_\phi | e_\phi = ', ephi | ephi) print('g =', sp2.g) print(r'\text{g\_inv = }', latex(sp2.g_inv)) #print(r'\text{signature = ', latex(sp2.signature())) Cf1 = sp2.Christoffel_symbols(mode=1) Cf1 = permutedims(Array(Cf1), (2, 0, 1)) print(r'\text{Christoffel symbols of the first kind: }') print(r'\Gamma_{1, \alpha, \beta} = ', latex(Cf1[0, :, :]), r'\quad', r'\Gamma_{2, \alpha, \beta} = ', latex(Cf1[1, :, :]))
sys.path.insert(0, dir_path) from jkPyLaTeX import LatexDoc, ldtTaller from random import shuffle from sympy import symbols, latex, sin, cos, tan, diff x = symbols('x') exercises = '' answers = '' excN = list(range(2, 10)) shuffle(excN) for c in excN: eji = c * x**2 + x * cos(c * x) / x exercises += ' \\item $%s$' % latex(eji) answers += ' \\item $%s$' % latex(diff(eji)) #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # Create the document doc = ldtTaller('doc', 'Derivative', 'Calculus', '') # Add content doc.addSlice('exercises', exercises) doc.addSlice('answers', answers) #template or content fnameMainSlice = './example/example.tex' doc.setMainSlice(fnameMainSlice) #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #Save the files necessary to compile in ./texOut
display(pF) # %% F = -log(pF[0]) - C F = F.expand(force=True) F = F.collect(sigma_s) F = F.collect(Sigma_x) F = syp.nsimplify(F) display(F) # %% gd_mux = Eq(-diff("F", mux, evaluate=False), -syp.separatevars(diff(F, mux), force=True), evaluate=False) display(gd_mux) print(syp.latex(gd_mux)) # %% d_dmux = Eq(-diff("F", dmux, evaluate=False), -diff(F, dmux).simplify(), evaluate=False) display(d_dmux) print(syp.latex(d_dmux)) # %% a = symbols("a", real=True) sa = syp.Function("s")(a) F = F.subs(s, sa) da = Eq(-diff("F", "a", evaluate=False), -diff(F, a).simplify(),