我们从Python开源项目中,提取了以下19个代码示例,用于说明如何使用sympy.latex()。
def test_latex_printing(): assert latex(v[0]) == '\\mathbf{\\hat{0}}' assert latex(v[1]) == '\\mathbf{\\hat{i}_{N}}' assert latex(v[2]) == '- \\mathbf{\\hat{i}_{N}}' assert latex(v[5]) == ('(a)\\mathbf{\\hat{i}_{N}} + ' + '(- b)\\mathbf{\\hat{j}_{N}}') assert latex(v[6]) == ('(a^{2} + \\mathbf{{x}_{N}})\\mathbf{\\' + 'hat{i}_{N}} + \\mathbf{\\hat{k}_{N}}') assert latex(v[8]) == ('\\mathbf{\\hat{j}_{N}} + (\\mathbf{{x}_' + '{C}}^{2} - \\int f{\\left (b \\right )}\\,' + ' db)\\mathbf{\\hat{k}_{N}}') assert latex(s) == '3 \\mathbf{{y}_{C}} \\mathbf{{x}_{N}}^{2}' assert latex(d[0]) == '(\\mathbf{\\hat{0}}|\\mathbf{\\hat{0}})' assert latex(d[4]) == ('(a)(\\mathbf{\\hat{i}_{N}}{|}\\mathbf' + '{\\hat{k}_{N}})') assert latex(d[9]) == ('(\\mathbf{\\hat{k}_{C}}{|}\\mathbf{\\' + 'hat{k}_{N}}) + (\\mathbf{\\hat{i}_{N}}{|' + '}\\mathbf{\\hat{k}_{N}})') assert latex(d[11]) == ('(a^{2} + b)(\\mathbf{\\hat{i}_{N}}{|}\\' + 'mathbf{\\hat{k}_{N}}) + (\\int f{\\left (' + 'b \\right )}\\, db)(\\mathbf{\\hat{k}_{N}' + '}{|}\\mathbf{\\hat{k}_{N}})')
def latex(self, rate = False): """Return the latex code for the reaction. By default the kinetic parameter of the reaction is included. To use the rate instead, use rate = True. :Example: >>> from crnpy.reaction import Reaction >>> from crnpy.crncomplex import Complex >>> r = Reaction("r1", Complex(A = 1, B = 2), Complex(C = 1), "k1*A*B**2") >>> print(r.latex()) r_{1}: A + 2 B \\xrightarrow{k_{1}} C >>> print(r.latex(True)) r_{1}: A + 2 B \\xrightarrow{A B^{2} k_{1}} C :rtype: string. """ return "{}: {} {} {}".format(sp.latex(self.reactionid), sp.latex(self.reactant.symp()), str("\\xrightarrow{" + sp.latex(self.rate if rate else self.kinetic_param) + "}") if self.rate else str("\\rightarrow"), sp.latex(self.product.symp()))
def parseToMathTex(self, expression): self.expression = str(expression) self.latexExpression = sp.latex(sp.sympify(self.expression)) print (sp.latex(sp.sympify(self.expression))) self.renderExpression(self.latexExpression)
def preview(expr, **kwargs): """ support function to display nice formula :param expr: :param kwargs: :return: """ latex_str = sp.latex(expr, **kwargs) latex_str = latex_str.replace("operator_name", "mathrm") plt.text(0.1, 0.1, latex_str, fontsize=20) plt.axis('off') plt.show()
def latex(self, prec=15, nested_scope=None): """Return the corresponding math mode latex string.""" return latex(self.value)
def latex(self, prec=15, nested_scope=None): """Return the corresponding math mode latex string.""" # TODO prec ignored return sympy.latex(self.sym(nested_scope))
def get_latex_representation(expr, registry): symbol_table = {} for ex in expr.free_symbols: try: symbol_table[ex] = registry.lut[str(ex)][3] except: symbol_table[ex] = r"\rm{" + str(ex).replace('_', '\ ') + "}" # invert the symbol table dict to look for keys with identical values invert_symbols = {} for key, value in symbol_table.items(): if value not in invert_symbols: invert_symbols[value] = [key] else: invert_symbols[value].append(key) # if there are any units with identical latex representations, substitute # units to avoid uncanceled terms in the final latex expression. for val in invert_symbols: symbols = invert_symbols[val] for i in range(1, len(symbols)): expr = expr.subs(symbols[i], symbols[0]) prefix = None if isinstance(expr, Mul): coeffs = expr.as_coeff_Mul() if coeffs[0] == 1 or not isinstance(coeffs[0], Float): pass else: expr = coeffs[1] prefix = Float(coeffs[0], 2) latex_repr = latex(expr, symbol_names=symbol_table, mul_symbol="dot", fold_frac_powers=True, fold_short_frac=True) if prefix is not None: latex_repr = latex(prefix, mul_symbol="times") + '\\ ' + latex_repr if latex_repr == '1': return '' else: return latex_repr
def _sympy_formatter(self): def formatter(x): if (isinstance(x, sympy.Basic)): return '${}$'.format(sympy.latex(x)) else: return x new = self.copy() for col in self.columns.drop('atom'): if self[col].dtype == np.dtype('O'): new._frame.loc[:, col] = self[col].apply(formatter) return new
def _polynomial_factorization(self, init_time, text, debug, queue): result_data = calc_result_data(text, True) result_data.calc_type = calc_type.POLYNOMIAL_FACTORIZATION text = text_calculator.formula_to_py(result_data.formula_str) try: start_time = init_time exec('result = sympy.factor(text)') in globals(), locals() result_data.auto_record_time(start_time) result_data.success = True start_time = time.time() str_calc_result = str(result) result_data.latex = sympy.latex(result) result_data.auto_record_time(start_time) result_data.calc_result = str_calc_result except Exception as ex: result_data.success = False result_data.calc_result = '{} - {}'.format(type(ex), ex.message) result_data.auto_record_time(start_time) queue.put(result_data)
def latex(self): return self._latex
def latex(self, value): if isinstance(value, str): self._latex = value else: raise Exception('LaTeX should be string.')
def md(*args): s = '' for x in args: if (isinstance(x, sp.Basic) or isinstance(x, sp.MutableDenseMatrix) or isinstance(x, tuple)): s = s + sp.latex(x) elif (isinstance(x, str)): s = s + x elif (isinstance(x, int) or isinstance(x, float)): s = s + str(x) else: print(type(x)) Display.display_markdown(s, raw=True)
def line(name, *args): def conv(x): if (isinstance(x, sp.Basic) or isinstance(x, sp.MutableDenseMatrix) or isinstance(x, tuple)): return sp.latex(x) elif isinstance(x, str): return x else: print(type(x)) line = [ conv(x) for x in args ] try: _Document_[name].append(line) except: _Document_[name] = [line]
def _algebraic_equations(self, init_time, text, debug, queue): result_data = calc_result_data(text, True) result_data.calc_type = calc_type.ALGEBRAIC_EQUATIONS text = text_calculator.formula_to_py(result_data.formula_str) try: start_time = init_time text_line = text.split(text_calculator.EQUATION_VAR_FORMULA_SEPARATOR) if len(text_line) < 2: result_data.success = False result_data.calc_result = error.string_calculator.wrong_format_to_calc_equations() else: var_org = text_line[0] var_init_field = var_org.replace(u' ', u',') var_init_symbol = var_org formula_list = text_line[1:] if any((not formula.endswith(text_calculator.EQUATION_KEYWORD)) for formula in formula_list): result_data.success = False result_data.calc_result = error.string_calculator.wrong_format_to_calc_equations() else: formula_list_replaced = [eq.replace(text_calculator.EQUATION_KEYWORD, u'') for eq in formula_list] exec_py = '{} = sympy.symbols(\'{}\', real=True)'.format(var_init_field, var_init_symbol) exec_py += '\nresult = sympy.solve([{}], {})'.format(','.join(formula_list_replaced), var_init_field) start_time = init_time exec(exec_py) in globals(), locals() result_data.auto_record_time(start_time) result_data.success = True start_time = time.time() str_calc_result = str(result) result_data.latex = sympy.latex(result) result_data.auto_record_time(start_time) result_data.formula_str = '\n'.join(formula_list) result_data.calc_result = str_calc_result except Exception as ex: result_data.success = False result_data.calc_result = '{} - {}'.format(type(ex), ex.message) result_data.auto_record_time(start_time) queue.put(result_data)