Best Python code snippet using slash
latex.py
Source:latex.py
...122 mul_symbol_table[self._settings['mul_symbol'] or 'dot']123 self._delim_dict = {'(': ')', '[': ']'}124 def parenthesize(self, item, level):125 if precedence(item) <= level:126 return r"\left(%s\right)" % self._print(item)127 else:128 return self._print(item)129 def doprint(self, expr):130 tex = Printer.doprint(self, expr)131 if self._settings['mode'] == 'plain':132 return tex133 elif self._settings['mode'] == 'inline':134 return r"$%s$" % tex135 elif self._settings['itex']:136 return r"$$%s$$" % tex137 else:138 env_str = self._settings['mode']139 return r"\begin{%s}%s\end{%s}" % (env_str, tex, env_str)140 def _needs_brackets(self, expr):141 """142 Returns True if the expression needs to be wrapped in brackets when143 printed, False otherwise. For example: a + b => True; a => False;144 10 => False; -10 => True.145 """146 return not ((expr.is_Integer and expr.is_nonnegative)147 or (expr.is_Atom and expr is not S.NegativeOne))148 def _needs_function_brackets(self, expr):149 """150 Returns True if the expression needs to be wrapped in brackets when151 passed as an argument to a function, False otherwise. This is a more152 liberal version of _needs_brackets, in that many expressions which need153 to be wrapped in brackets when added/subtracted/raised to a power do154 not need them when passed to a function. Such an example is a*b.155 """156 if not self._needs_brackets(expr):157 return False158 else:159 # Muls of the form a*b*c... can be folded160 if expr.is_Mul and not self._mul_is_clean(expr):161 return True162 # Pows which don't need brackets can be folded163 elif expr.is_Pow and not self._pow_is_clean(expr):164 return True165 # Add and Function always need brackets166 elif expr.is_Add or expr.is_Function:167 return True168 else:169 return False170 def _needs_mul_brackets(self, expr, last=False):171 """172 Returns True if the expression needs to be wrapped in brackets when173 printed as part of a Mul, False otherwise. This is True for Add,174 but also for some container objects that would not need brackets175 when appearing last in a Mul, e.g. an Integral. ``last=True``176 specifies that this expr is the last to appear in a Mul.177 """178 from sympy import Integral, Piecewise, Product, Sum179 return expr.is_Add or (not last and180 any([expr.has(x) for x in (Integral, Piecewise, Product, Sum)]))181 def _mul_is_clean(self, expr):182 for arg in expr.args:183 if arg.is_Function:184 return False185 return True186 def _pow_is_clean(self, expr):187 return not self._needs_brackets(expr.base)188 def _do_exponent(self, expr, exp):189 if exp is not None:190 return r"\left(%s\right)^{%s}" % (expr, exp)191 else:192 return expr193 def _print_bool(self, e):194 return r"\mathrm{%s}" % e195 _print_BooleanTrue = _print_bool196 _print_BooleanFalse = _print_bool197 def _print_NoneType(self, e):198 return r"\mathrm{%s}" % e199 def _print_Add(self, expr, order=None):200 if self.order == 'none':201 terms = list(expr.args)202 else:203 terms = self._as_ordered_terms(expr, order=order)204 tex = self._print(terms[0])205 for term in terms[1:]:206 if not _coeff_isneg(term):207 tex += " + " + self._print(term)208 else:209 tex += " - " + self._print(-term)210 return tex211 def _print_Float(self, expr):212 # Based off of that in StrPrinter213 dps = prec_to_dps(expr._prec)214 str_real = mlib.to_str(expr._mpf_, dps, strip_zeros=True)215 # Must always have a mul symbol (as 2.5 10^{20} just looks odd)216 # thus we use the number separator217 separator = self._settings['mul_symbol_latex_numbers']218 if 'e' in str_real:219 (mant, exp) = str_real.split('e')220 if exp[0] == '+':221 exp = exp[1:]222 return r"%s%s10^{%s}" % (mant, separator, exp)223 elif str_real == "+inf":224 return r"\infty"225 elif str_real == "-inf":226 return r"- \infty"227 else:228 return str_real229 def _print_Mul(self, expr):230 coeff, _ = expr.as_coeff_Mul()231 if not coeff.is_negative:232 tex = ""233 else:234 expr = -expr235 tex = "- "236 from sympy.simplify import fraction237 numer, denom = fraction(expr, exact=True)238 separator = self._settings['mul_symbol_latex']239 numbersep = self._settings['mul_symbol_latex_numbers']240 def convert(expr):241 if not expr.is_Mul:242 return str(self._print(expr))243 else:244 _tex = last_term_tex = ""245 if self.order not in ('old', 'none'):246 args = expr.as_ordered_factors()247 else:248 args = expr.args249 for i, term in enumerate(args):250 term_tex = self._print(term)251 if self._needs_mul_brackets(term, last=(i == len(args) - 1)):252 term_tex = r"\left(%s\right)" % term_tex253 if re.search("[0-9][} ]*$", last_term_tex) and \254 re.match("[{ ]*[-+0-9]", term_tex):255 # between two numbers256 _tex += numbersep257 elif _tex:258 _tex += separator259 _tex += term_tex260 last_term_tex = term_tex261 return _tex262 if denom is S.One:263 # use the original expression here, since fraction() may have264 # altered it when producing numer and denom265 tex += convert(expr)266 else:267 snumer = convert(numer)268 sdenom = convert(denom)269 ldenom = len(sdenom.split())270 ratio = self._settings['long_frac_ratio']271 if self._settings['fold_short_frac'] \272 and ldenom <= 2 and not "^" in sdenom:273 # handle short fractions274 if self._needs_mul_brackets(numer, last=False):275 tex += r"\left(%s\right) / %s" % (snumer, sdenom)276 else:277 tex += r"%s / %s" % (snumer, sdenom)278 elif len(snumer.split()) > ratio*ldenom:279 # handle long fractions280 if self._needs_mul_brackets(numer, last=True):281 tex += r"\frac{1}{%s}%s\left(%s\right)" \282 % (sdenom, separator, snumer)283 elif numer.is_Mul:284 # split a long numerator285 a = S.One286 b = S.One287 for x in numer.args:288 if self._needs_mul_brackets(x, last=False) or \289 len(convert(a*x).split()) > ratio*ldenom or \290 (b.is_commutative is x.is_commutative is False):291 b *= x292 else:293 a *= x294 if self._needs_mul_brackets(b, last=True):295 tex += r"\frac{%s}{%s}%s\left(%s\right)" \296 % (convert(a), sdenom, separator, convert(b))297 else:298 tex += r"\frac{%s}{%s}%s%s" \299 % (convert(a), sdenom, separator, convert(b))300 else:301 tex += r"\frac{1}{%s}%s%s" % (sdenom, separator, snumer)302 else:303 tex += r"\frac{%s}{%s}" % (snumer, sdenom)304 return tex305 def _print_Pow(self, expr):306 # Treat x**Rational(1,n) as special case307 if expr.exp.is_Rational and abs(expr.exp.p) == 1 and expr.exp.q != 1:308 base = self._print(expr.base)309 expq = expr.exp.q310 if expq == 2:311 tex = r"\sqrt{%s}" % base312 elif self._settings['itex']:313 tex = r"\root{%d}{%s}" % (expq, base)314 else:315 tex = r"\sqrt[%d]{%s}" % (expq, base)316 if expr.exp.is_negative:317 return r"\frac{1}{%s}" % tex318 else:319 return tex320 elif self._settings['fold_frac_powers'] \321 and expr.exp.is_Rational \322 and expr.exp.q != 1:323 base, p, q = self._print(expr.base), expr.exp.p, expr.exp.q324 if expr.base.is_Function:325 return self._print(expr.base, "%s/%s" % (p, q))326 if self._needs_brackets(expr.base):327 return r"\left(%s\right)^{%s/%s}" % (base, p, q)328 return r"%s^{%s/%s}" % (base, p, q)329 elif expr.exp.is_Rational and expr.exp.is_negative and expr.base.is_commutative:330 # Things like 1/x331 return self._print_Mul(expr)332 else:333 if expr.base.is_Function:334 return self._print(expr.base, self._print(expr.exp))335 else:336 if expr.is_commutative and expr.exp == -1:337 #solves issue 4129338 #As Mul always simplify 1/x to x**-1339 #The objective is achieved with this hack340 #first we get the latex for -1 * expr,341 #which is a Mul expression342 tex = self._print(S.NegativeOne * expr).strip()343 #the result comes with a minus and a space, so we remove344 if tex[:1] == "-":345 return tex[1:].strip()346 if self._needs_brackets(expr.base):347 tex = r"\left(%s\right)^{%s}"348 else:349 tex = r"%s^{%s}"350 return tex % (self._print(expr.base),351 self._print(expr.exp))352 def _print_Sum(self, expr):353 if len(expr.limits) == 1:354 tex = r"\sum_{%s=%s}^{%s} " % \355 tuple([ self._print(i) for i in expr.limits[0] ])356 else:357 def _format_ineq(l):358 return r"%s \leq %s \leq %s" % \359 tuple([self._print(s) for s in (l[1], l[0], l[2])])360 tex = r"\sum_{\substack{%s}} " % \361 str.join('\\\\', [ _format_ineq(l) for l in expr.limits ])362 if isinstance(expr.function, Add):363 tex += r"\left(%s\right)" % self._print(expr.function)364 else:365 tex += self._print(expr.function)366 return tex367 def _print_Product(self, expr):368 if len(expr.limits) == 1:369 tex = r"\prod_{%s=%s}^{%s} " % \370 tuple([ self._print(i) for i in expr.limits[0] ])371 else:372 def _format_ineq(l):373 return r"%s \leq %s \leq %s" % \374 tuple([self._print(s) for s in (l[1], l[0], l[2])])375 tex = r"\prod_{\substack{%s}} " % \376 str.join('\\\\', [ _format_ineq(l) for l in expr.limits ])377 if isinstance(expr.function, Add):378 tex += r"\left(%s\right)" % self._print(expr.function)379 else:380 tex += self._print(expr.function)381 return tex382 def _print_BasisDependent(self, expr):383 from sympy.vector import Vector384 o1 = []385 if expr == expr.zero:386 return expr.zero._latex_form387 if isinstance(expr, Vector):388 items = expr.separate().items()389 else:390 items = [(0, expr)]391 for system, vect in items:392 inneritems = list(vect.components.items())393 inneritems.sort(key = lambda x:x[0].__str__())394 for k, v in inneritems:395 if v == 1:396 o1.append(' + ' + k._latex_form)397 elif v == -1:398 o1.append(' - ' + k._latex_form)399 else:400 arg_str = '(' + LatexPrinter().doprint(v) + ')'401 o1.append(' + ' + arg_str + k._latex_form)402 outstr = (''.join(o1))403 if outstr[1] != '-':404 outstr = outstr[3:]405 else:406 outstr = outstr[1:]407 return outstr408 def _print_Indexed(self, expr):409 tex = self._print(expr.base)+'_{%s}' % ','.join(410 map(self._print, expr.indices))411 return tex412 def _print_IndexedBase(self, expr):413 return self._print(expr.label)414 def _print_Derivative(self, expr):415 dim = len(expr.variables)416 if requires_partial(expr):417 diff_symbol = r'\partial'418 else:419 diff_symbol = r'd'420 if dim == 1:421 tex = r"\frac{%s}{%s %s}" % (diff_symbol, diff_symbol,422 self._print(expr.variables[0]))423 else:424 multiplicity, i, tex = [], 1, ""425 current = expr.variables[0]426 for symbol in expr.variables[1:]:427 if symbol == current:428 i = i + 1429 else:430 multiplicity.append((current, i))431 current, i = symbol, 1432 else:433 multiplicity.append((current, i))434 for x, i in multiplicity:435 if i == 1:436 tex += r"%s %s" % (diff_symbol, self._print(x))437 else:438 tex += r"%s %s^{%s}" % (diff_symbol, self._print(x), i)439 tex = r"\frac{%s^{%s}}{%s} " % (diff_symbol, dim, tex)440 if isinstance(expr.expr, C.AssocOp):441 return r"%s\left(%s\right)" % (tex, self._print(expr.expr))442 else:443 return r"%s %s" % (tex, self._print(expr.expr))444 def _print_Subs(self, subs):445 expr, old, new = subs.args446 latex_expr = self._print(expr)447 latex_old = (self._print(e) for e in old)448 latex_new = (self._print(e) for e in new)449 latex_subs = r'\\ '.join(450 e[0] + '=' + e[1] for e in zip(latex_old, latex_new))451 return r'\left. %s \right|_{\substack{ %s }}' % (latex_expr, latex_subs)452 def _print_Integral(self, expr):453 tex, symbols = "", []454 # Only up to \iiiint exists455 if len(expr.limits) <= 4 and all(len(lim) == 1 for lim in expr.limits):456 # Use len(expr.limits)-1 so that syntax highlighters don't think457 # \" is an escaped quote458 tex = r"\i" + "i"*(len(expr.limits) - 1) + "nt"459 symbols = [r"\, d%s" % self._print(symbol[0])460 for symbol in expr.limits]461 else:462 for lim in reversed(expr.limits):463 symbol = lim[0]464 tex += r"\int"465 if len(lim) > 1:466 if self._settings['mode'] in ['equation', 'equation*'] \467 and not self._settings['itex']:468 tex += r"\limits"469 if len(lim) == 3:470 tex += "_{%s}^{%s}" % (self._print(lim[1]),471 self._print(lim[2]))472 if len(lim) == 2:473 tex += "^{%s}" % (self._print(lim[1]))474 symbols.insert(0, r"\, d%s" % self._print(symbol))475 return r"%s %s%s" % (tex,476 str(self._print(expr.function)), "".join(symbols))477 def _print_Limit(self, expr):478 e, z, z0, dir = expr.args479 tex = r"\lim_{%s \to " % self._print(z)480 if z0 in (S.Infinity, S.NegativeInfinity):481 tex += r"%s}" % self._print(z0)482 else:483 tex += r"%s^%s}" % (self._print(z0), self._print(dir))484 if isinstance(e, C.AssocOp):485 return r"%s\left(%s\right)" % (tex, self._print(e))486 else:487 return r"%s %s" % (tex, self._print(e))488 def _hprint_Function(self, func):489 '''490 Logic to decide how to render a function to latex491 - if it is a recognized latex name, use the appropriate latex command492 - if it is a single letter, just use that letter493 - if it is a longer name, then put \operatorname{} around it and be494 mindful of undercores in the name495 '''496 func = self._deal_with_super_sub(func)497 if func in accepted_latex_functions:498 name = r"\%s" % func499 elif len(func) == 1 or func.startswith('\\'):500 name = func501 else:502 name = r"\operatorname{%s}" % func503 return name504 def _print_Function(self, expr, exp=None):505 '''506 Render functions to LaTeX, handling functions that LaTeX knows about507 e.g., sin, cos, ... by using the proper LaTeX command (\sin, \cos, ...).508 For single-letter function names, render them as regular LaTeX math509 symbols. For multi-letter function names that LaTeX does not know510 about, (e.g., Li, sech) use \operatorname{} so that the function name511 is rendered in Roman font and LaTeX handles spacing properly.512 expr is the expression involving the function513 exp is an exponent514 '''515 func = expr.func.__name__516 if hasattr(self, '_print_' + func):517 return getattr(self, '_print_' + func)(expr, exp)518 else:519 args = [ str(self._print(arg)) for arg in expr.args ]520 # How inverse trig functions should be displayed, formats are:521 # abbreviated: asin, full: arcsin, power: sin^-1522 inv_trig_style = self._settings['inv_trig_style']523 # If we are dealing with a power-style inverse trig function524 inv_trig_power_case = False525 # If it is applicable to fold the argument brackets526 can_fold_brackets = self._settings['fold_func_brackets'] and \527 len(args) == 1 and \528 not self._needs_function_brackets(expr.args[0])529 inv_trig_table = ["asin", "acos", "atan", "acot"]530 # If the function is an inverse trig function, handle the style531 if func in inv_trig_table:532 if inv_trig_style == "abbreviated":533 func = func534 elif inv_trig_style == "full":535 func = "arc" + func[1:]536 elif inv_trig_style == "power":537 func = func[1:]538 inv_trig_power_case = True539 # Can never fold brackets if we're raised to a power540 if exp is not None:541 can_fold_brackets = False542 if inv_trig_power_case:543 if func in accepted_latex_functions:544 name = r"\%s^{-1}" % func545 else:546 name = r"\operatorname{%s}^{-1}" % func547 elif exp is not None:548 name = r'%s^{%s}' % (self._hprint_Function(func), exp)549 else:550 name = self._hprint_Function(func)551 if can_fold_brackets:552 if func in accepted_latex_functions:553 # Wrap argument safely to avoid parse-time conflicts554 # with the function name itself555 name += r" {%s}"556 else:557 name += r"%s"558 else:559 name += r"{\left (%s \right )}"560 if inv_trig_power_case and exp is not None:561 name += r"^{%s}" % exp562 return name % ",".join(args)563 def _print_UndefinedFunction(self, expr):564 return self._hprint_Function(str(expr))565 def _print_FunctionClass(self, expr):566 if hasattr(expr, '_latex_no_arg'):567 return expr._latex_no_arg(self)568 return self._hprint_Function(str(expr))569 def _print_Lambda(self, expr):570 symbols, expr = expr.args571 if len(symbols) == 1:572 symbols = self._print(symbols[0])573 else:574 symbols = self._print(tuple(symbols))575 args = (symbols, self._print(expr))576 tex = r"\left( %s \mapsto %s \right)" % (symbols, self._print(expr))577 return tex578 def _print_Min(self, expr, exp=None):579 args = sorted(expr.args, key=default_sort_key)580 texargs = [r"%s" % self._print(symbol) for symbol in args]581 tex = r"\min\left(%s\right)" % ", ".join(texargs)582 if exp is not None:583 return r"%s^{%s}" % (tex, exp)584 else:585 return tex586 def _print_Max(self, expr, exp=None):587 args = sorted(expr.args, key=default_sort_key)588 texargs = [r"%s" % self._print(symbol) for symbol in args]589 tex = r"\max\left(%s\right)" % ", ".join(texargs)590 if exp is not None:591 return r"%s^{%s}" % (tex, exp)592 else:593 return tex594 def _print_floor(self, expr, exp=None):595 tex = r"\lfloor{%s}\rfloor" % self._print(expr.args[0])596 if exp is not None:597 return r"%s^{%s}" % (tex, exp)598 else:599 return tex600 def _print_ceiling(self, expr, exp=None):601 tex = r"\lceil{%s}\rceil" % self._print(expr.args[0])602 if exp is not None:603 return r"%s^{%s}" % (tex, exp)604 else:605 return tex606 def _print_Abs(self, expr, exp=None):607 tex = r"\left\lvert{%s}\right\rvert" % self._print(expr.args[0])608 if exp is not None:609 return r"%s^{%s}" % (tex, exp)610 else:611 return tex612 _print_Determinant = _print_Abs613 def _print_re(self, expr, exp=None):614 if self._needs_brackets(expr.args[0]):615 tex = r"\Re {\left (%s \right )}" % self._print(expr.args[0])616 else:617 tex = r"\Re{%s}" % self._print(expr.args[0])618 return self._do_exponent(tex, exp)619 def _print_im(self, expr, exp=None):620 if self._needs_brackets(expr.args[0]):621 tex = r"\Im {\left ( %s \right )}" % self._print(expr.args[0])622 else:623 tex = r"\Im{%s}" % self._print(expr.args[0])624 return self._do_exponent(tex, exp)625 def _print_Not(self, e):626 from sympy import Equivalent, Implies627 if isinstance(e.args[0], Equivalent):628 return self._print_Equivalent(e.args[0], r"\not\equiv")629 if isinstance(e.args[0], Implies):630 return self._print_Implies(e.args[0], r"\not\Rightarrow")631 if (e.args[0].is_Boolean):632 return r"\neg (%s)" % self._print(e.args[0])633 else:634 return r"\neg %s" % self._print(e.args[0])635 def _print_LogOp(self, args, char):636 arg = args[0]637 if arg.is_Boolean and not arg.is_Not:638 tex = r"\left(%s\right)" % self._print(arg)639 else:640 tex = r"%s" % self._print(arg)641 for arg in args[1:]:642 if arg.is_Boolean and not arg.is_Not:643 tex += r" %s \left(%s\right)" % (char, self._print(arg))644 else:645 tex += r" %s %s" % (char, self._print(arg))646 return tex647 def _print_And(self, e):648 args = sorted(e.args, key=default_sort_key)649 return self._print_LogOp(args, r"\wedge")650 def _print_Or(self, e):651 args = sorted(e.args, key=default_sort_key)652 return self._print_LogOp(args, r"\vee")653 def _print_Xor(self, e):654 args = sorted(e.args, key=default_sort_key)655 return self._print_LogOp(args, r"\veebar")656 def _print_Implies(self, e, altchar=None):657 return self._print_LogOp(e.args, altchar or r"\Rightarrow")658 def _print_Equivalent(self, e, altchar=None):659 args = sorted(e.args, key=default_sort_key)660 return self._print_LogOp(args, altchar or r"\equiv")661 def _print_conjugate(self, expr, exp=None):662 tex = r"\overline{%s}" % self._print(expr.args[0])663 if exp is not None:664 return r"%s^{%s}" % (tex, exp)665 else:666 return tex667 def _print_polar_lift(self, expr, exp=None):668 func = r"\operatorname{polar\_lift}"669 arg = r"{\left (%s \right )}" % self._print(expr.args[0])670 if exp is not None:671 return r"%s^{%s}%s" % (func, exp, arg)672 else:673 return r"%s%s" % (func, arg)674 def _print_ExpBase(self, expr, exp=None):675 # TODO should exp_polar be printed differently?676 # what about exp_polar(0), exp_polar(1)?677 tex = r"e^{%s}" % self._print(expr.args[0])678 return self._do_exponent(tex, exp)679 def _print_elliptic_k(self, expr, exp=None):680 tex = r"\left(%s\right)" % self._print(expr.args[0])681 if exp is not None:682 return r"K^{%s}%s" % (exp, tex)683 else:684 return r"K%s" % tex685 def _print_elliptic_f(self, expr, exp=None):686 tex = r"\left(%s\middle| %s\right)" % \687 (self._print(expr.args[0]), self._print(expr.args[1]))688 if exp is not None:689 return r"F^{%s}%s" % (exp, tex)690 else:691 return r"F%s" % tex692 def _print_elliptic_e(self, expr, exp=None):693 if len(expr.args) == 2:694 tex = r"\left(%s\middle| %s\right)" % \695 (self._print(expr.args[0]), self._print(expr.args[1]))696 else:697 tex = r"\left(%s\right)" % self._print(expr.args[0])698 if exp is not None:699 return r"E^{%s}%s" % (exp, tex)700 else:701 return r"E%s" % tex702 def _print_elliptic_pi(self, expr, exp=None):703 if len(expr.args) == 3:704 tex = r"\left(%s; %s\middle| %s\right)" % \705 (self._print(expr.args[0]), self._print(expr.args[1]), \706 self._print(expr.args[2]))707 else:708 tex = r"\left(%s\middle| %s\right)" % \709 (self._print(expr.args[0]), self._print(expr.args[1]))710 if exp is not None:711 return r"\Pi^{%s}%s" % (exp, tex)712 else:713 return r"\Pi%s" % tex714 def _print_gamma(self, expr, exp=None):715 tex = r"\left(%s\right)" % self._print(expr.args[0])716 if exp is not None:717 return r"\Gamma^{%s}%s" % (exp, tex)718 else:719 return r"\Gamma%s" % tex720 def _print_uppergamma(self, expr, exp=None):721 tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]),722 self._print(expr.args[1]))723 if exp is not None:724 return r"\Gamma^{%s}%s" % (exp, tex)725 else:726 return r"\Gamma%s" % tex727 def _print_lowergamma(self, expr, exp=None):728 tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]),729 self._print(expr.args[1]))730 if exp is not None:731 return r"\gamma^{%s}%s" % (exp, tex)732 else:733 return r"\gamma%s" % tex734 def _print_expint(self, expr, exp=None):735 tex = r"\left(%s\right)" % self._print(expr.args[1])736 nu = self._print(expr.args[0])737 if exp is not None:738 return r"\operatorname{E}_{%s}^{%s}%s" % (nu, exp, tex)739 else:740 return r"\operatorname{E}_{%s}%s" % (nu, tex)741 def _print_fresnels(self, expr, exp=None):742 tex = r"\left(%s\right)" % self._print(expr.args[0])743 if exp is not None:744 return r"S^{%s}%s" % (exp, tex)745 else:746 return r"S%s" % tex747 def _print_fresnelc(self, expr, exp=None):748 tex = r"\left(%s\right)" % self._print(expr.args[0])749 if exp is not None:750 return r"C^{%s}%s" % (exp, tex)751 else:752 return r"C%s" % tex753 def _print_subfactorial(self, expr, exp=None):754 x = expr.args[0]755 if self._needs_brackets(x):756 tex = r"!\left(%s\right)" % self._print(x)757 else:758 tex = "!" + self._print(x)759 if exp is not None:760 return r"%s^{%s}" % (tex, exp)761 else:762 return tex763 def _print_factorial(self, expr, exp=None):764 x = expr.args[0]765 if self._needs_brackets(x):766 tex = r"\left(%s\right)!" % self._print(x)767 else:768 tex = self._print(x) + "!"769 if exp is not None:770 return r"%s^{%s}" % (tex, exp)771 else:772 return tex773 def _print_factorial2(self, expr, exp=None):774 x = expr.args[0]775 if self._needs_brackets(x):776 tex = r"\left(%s\right)!!" % self._print(x)777 else:778 tex = self._print(x) + "!!"779 if exp is not None:780 return r"%s^{%s}" % (tex, exp)781 else:782 return tex783 def _print_binomial(self, expr, exp=None):784 tex = r"{\binom{%s}{%s}}" % (self._print(expr.args[0]),785 self._print(expr.args[1]))786 if exp is not None:787 return r"%s^{%s}" % (tex, exp)788 else:789 return tex790 def _print_RisingFactorial(self, expr, exp=None):791 tex = r"{\left(%s\right)}^{\left(%s\right)}" % \792 (self._print(expr.args[0]), self._print(expr.args[1]))793 return self._do_exponent(tex, exp)794 def _print_FallingFactorial(self, expr, exp=None):795 tex = r"{\left(%s\right)}_{\left(%s\right)}" % \796 (self._print(expr.args[0]), self._print(expr.args[1]))797 return self._do_exponent(tex, exp)798 def _hprint_BesselBase(self, expr, exp, sym):799 tex = r"%s" % (sym)800 need_exp = False801 if exp is not None:802 if tex.find('^') == -1:803 tex = r"%s^{%s}" % (tex, self._print(exp))804 else:805 need_exp = True806 tex = r"%s_{%s}\left(%s\right)" % (tex, self._print(expr.order),807 self._print(expr.argument))808 if need_exp:809 tex = self._do_exponent(tex, exp)810 return tex811 def _hprint_vec(self, vec):812 if len(vec) == 0:813 return ""814 s = ""815 for i in vec[:-1]:816 s += "%s, " % self._print(i)817 s += self._print(vec[-1])818 return s819 def _print_besselj(self, expr, exp=None):820 return self._hprint_BesselBase(expr, exp, 'J')821 def _print_besseli(self, expr, exp=None):822 return self._hprint_BesselBase(expr, exp, 'I')823 def _print_besselk(self, expr, exp=None):824 return self._hprint_BesselBase(expr, exp, 'K')825 def _print_bessely(self, expr, exp=None):826 return self._hprint_BesselBase(expr, exp, 'Y')827 def _print_yn(self, expr, exp=None):828 return self._hprint_BesselBase(expr, exp, 'y')829 def _print_jn(self, expr, exp=None):830 return self._hprint_BesselBase(expr, exp, 'j')831 def _print_hankel1(self, expr, exp=None):832 return self._hprint_BesselBase(expr, exp, 'H^{(1)}')833 def _print_hankel2(self, expr, exp=None):834 return self._hprint_BesselBase(expr, exp, 'H^{(2)}')835 def _hprint_airy(self, expr, exp=None, notation=""):836 tex = r"\left(%s\right)" % self._print(expr.args[0])837 if exp is not None:838 return r"%s^{%s}%s" % (notation, exp, tex)839 else:840 return r"%s%s" % (notation, tex)841 def _hprint_airy_prime(self, expr, exp=None, notation=""):842 tex = r"\left(%s\right)" % self._print(expr.args[0])843 if exp is not None:844 return r"{%s^\prime}^{%s}%s" % (notation, exp, tex)845 else:846 return r"%s^\prime%s" % (notation, tex)847 def _print_airyai(self, expr, exp=None):848 return self._hprint_airy(expr, exp, 'Ai')849 def _print_airybi(self, expr, exp=None):850 return self._hprint_airy(expr, exp, 'Bi')851 def _print_airyaiprime(self, expr, exp=None):852 return self._hprint_airy_prime(expr, exp, 'Ai')853 def _print_airybiprime(self, expr, exp=None):854 return self._hprint_airy_prime(expr, exp, 'Bi')855 def _print_hyper(self, expr, exp=None):856 tex = r"{{}_{%s}F_{%s}\left(\begin{matrix} %s \\ %s \end{matrix}" \857 r"\middle| {%s} \right)}" % \858 (self._print(len(expr.ap)), self._print(len(expr.bq)),859 self._hprint_vec(expr.ap), self._hprint_vec(expr.bq),860 self._print(expr.argument))861 if exp is not None:862 tex = r"{%s}^{%s}" % (tex, self._print(exp))863 return tex864 def _print_meijerg(self, expr, exp=None):865 tex = r"{G_{%s, %s}^{%s, %s}\left(\begin{matrix} %s & %s \\" \866 r"%s & %s \end{matrix} \middle| {%s} \right)}" % \867 (self._print(len(expr.ap)), self._print(len(expr.bq)),868 self._print(len(expr.bm)), self._print(len(expr.an)),869 self._hprint_vec(expr.an), self._hprint_vec(expr.aother),870 self._hprint_vec(expr.bm), self._hprint_vec(expr.bother),871 self._print(expr.argument))872 if exp is not None:873 tex = r"{%s}^{%s}" % (tex, self._print(exp))874 return tex875 def _print_dirichlet_eta(self, expr, exp=None):876 tex = r"\left(%s\right)" % self._print(expr.args[0])877 if exp is not None:878 return r"\eta^{%s}%s" % (self._print(exp), tex)879 return r"\eta%s" % tex880 def _print_zeta(self, expr, exp=None):881 if len(expr.args) == 2:882 tex = r"\left(%s, %s\right)" % tuple(map(self._print, expr.args))883 else:884 tex = r"\left(%s\right)" % self._print(expr.args[0])885 if exp is not None:886 return r"\zeta^{%s}%s" % (self._print(exp), tex)887 return r"\zeta%s" % tex888 def _print_lerchphi(self, expr, exp=None):889 tex = r"\left(%s, %s, %s\right)" % tuple(map(self._print, expr.args))890 if exp is None:891 return r"\Phi%s" % tex892 return r"\Phi^{%s}%s" % (self._print(exp), tex)893 def _print_polylog(self, expr, exp=None):894 s, z = map(self._print, expr.args)895 tex = r"\left(%s\right)" % z896 if exp is None:897 return r"\operatorname{Li}_{%s}%s" % (s, tex)898 return r"\operatorname{Li}_{%s}^{%s}%s" % (s, self._print(exp), tex)899 def _print_jacobi(self, expr, exp=None):900 n, a, b, x = map(self._print, expr.args)901 tex = r"P_{%s}^{\left(%s,%s\right)}\left(%s\right)" % (n, a, b, x)902 if exp is not None:903 tex = r"\left(" + tex + r"\right)^{%s}" % (self._print(exp))904 return tex905 def _print_gegenbauer(self, expr, exp=None):906 n, a, x = map(self._print, expr.args)907 tex = r"C_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)908 if exp is not None:909 tex = r"\left(" + tex + r"\right)^{%s}" % (self._print(exp))910 return tex911 def _print_chebyshevt(self, expr, exp=None):912 n, x = map(self._print, expr.args)913 tex = r"T_{%s}\left(%s\right)" % (n, x)914 if exp is not None:915 tex = r"\left(" + tex + r"\right)^{%s}" % (self._print(exp))916 return tex917 def _print_chebyshevu(self, expr, exp=None):918 n, x = map(self._print, expr.args)919 tex = r"U_{%s}\left(%s\right)" % (n, x)920 if exp is not None:921 tex = r"\left(" + tex + r"\right)^{%s}" % (self._print(exp))922 return tex923 def _print_legendre(self, expr, exp=None):924 n, x = map(self._print, expr.args)925 tex = r"P_{%s}\left(%s\right)" % (n, x)926 if exp is not None:927 tex = r"\left(" + tex + r"\right)^{%s}" % (self._print(exp))928 return tex929 def _print_assoc_legendre(self, expr, exp=None):930 n, a, x = map(self._print, expr.args)931 tex = r"P_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)932 if exp is not None:933 tex = r"\left(" + tex + r"\right)^{%s}" % (self._print(exp))934 return tex935 def _print_hermite(self, expr, exp=None):936 n, x = map(self._print, expr.args)937 tex = r"H_{%s}\left(%s\right)" % (n, x)938 if exp is not None:939 tex = r"\left(" + tex + r"\right)^{%s}" % (self._print(exp))940 return tex941 def _print_laguerre(self, expr, exp=None):942 n, x = map(self._print, expr.args)943 tex = r"L_{%s}\left(%s\right)" % (n, x)944 if exp is not None:945 tex = r"\left(" + tex + r"\right)^{%s}" % (self._print(exp))946 return tex947 def _print_assoc_laguerre(self, expr, exp=None):948 n, a, x = map(self._print, expr.args)949 tex = r"L_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)950 if exp is not None:951 tex = r"\left(" + tex + r"\right)^{%s}" % (self._print(exp))952 return tex953 def _print_Ynm(self, expr, exp=None):954 n, m, theta, phi = map(self._print, expr.args)955 tex = r"Y_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi)956 if exp is not None:957 tex = r"\left(" + tex + r"\right)^{%s}" % (self._print(exp))958 return tex959 def _print_Znm(self, expr, exp=None):960 n, m, theta, phi = map(self._print, expr.args)961 tex = r"Z_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi)962 if exp is not None:963 tex = r"\left(" + tex + r"\right)^{%s}" % (self._print(exp))964 return tex965 def _print_Rational(self, expr):966 if expr.q != 1:967 sign = ""968 p = expr.p969 if expr.p < 0:970 sign = "- "971 p = -p972 return r"%s\frac{%d}{%d}" % (sign, p, expr.q)973 else:974 return self._print(expr.p)975 def _print_Order(self, expr):976 s = self._print(expr.expr)977 if expr.point and any(p != S.Zero for p in expr.point) or \978 len(expr.variables) > 1:979 s += '; '980 if len(expr.variables) > 1:981 s += self._print(expr.variables)982 elif len(expr.variables):983 s += self._print(expr.variables[0])984 s += r'\rightarrow'985 if len(expr.point) > 1:986 s += self._print(expr.point)987 else:988 s += self._print(expr.point[0])989 return r"\mathcal{O}\left(%s\right)" % s990 def _print_Symbol(self, expr):991 if expr in self._settings['symbol_names']:992 return self._settings['symbol_names'][expr]993 return self._deal_with_super_sub(expr.name)994 _print_RandomSymbol = _print_Symbol995 _print_MatrixSymbol = _print_Symbol996 def _deal_with_super_sub(self, string):997 name, supers, subs = split_super_sub(string)998 name = translate(name)999 supers = [translate(sup) for sup in supers]1000 subs = [translate(sub) for sub in subs]1001 # glue all items together:1002 if len(supers) > 0:1003 name += "^{%s}" % " ".join(supers)1004 if len(subs) > 0:1005 name += "_{%s}" % " ".join(subs)1006 return name1007 def _print_Relational(self, expr):1008 if self._settings['itex']:1009 gt = r"\gt"1010 lt = r"\lt"1011 else:1012 gt = ">"1013 lt = "<"1014 charmap = {1015 "==": "=",1016 ">": gt,1017 "<": lt,1018 ">=": r"\geq",1019 "<=": r"\leq",1020 "!=": r"\neq",1021 }1022 return "%s %s %s" % (self._print(expr.lhs),1023 charmap[expr.rel_op], self._print(expr.rhs))1024 def _print_Piecewise(self, expr):1025 ecpairs = [r"%s & \text{for}\: %s" % (self._print(e), self._print(c))1026 for e, c in expr.args[:-1]]1027 if expr.args[-1].cond == true:1028 ecpairs.append(r"%s & \text{otherwise}" %1029 self._print(expr.args[-1].expr))1030 else:1031 ecpairs.append(r"%s & \text{for}\: %s" %1032 (self._print(expr.args[-1].expr),1033 self._print(expr.args[-1].cond)))1034 tex = r"\begin{cases} %s \end{cases}"1035 return tex % r" \\".join(ecpairs)1036 def _print_MatrixBase(self, expr):1037 lines = []1038 for line in range(expr.rows): # horrible, should be 'rows'1039 lines.append(" & ".join([ self._print(i) for i in expr[line, :] ]))1040 mat_str = self._settings['mat_str']1041 if mat_str is None:1042 if self._settings['mode'] == 'inline':1043 mat_str = 'smallmatrix'1044 else:1045 if (expr.cols <= 10) is True:1046 mat_str = 'matrix'1047 else:1048 mat_str = 'array'1049 out_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}'1050 out_str = out_str.replace('%MATSTR%', mat_str)1051 if mat_str == 'array':1052 out_str = out_str.replace('%s', '{' + 'c'*expr.cols + '}%s')1053 if self._settings['mat_delim']:1054 left_delim = self._settings['mat_delim']1055 right_delim = self._delim_dict[left_delim]1056 out_str = r'\left' + left_delim + out_str + \1057 r'\right' + right_delim1058 return out_str % r"\\".join(lines)1059 _print_ImmutableMatrix = _print_MatrixBase1060 _print_Matrix = _print_MatrixBase1061 def _print_MatrixElement(self, expr):1062 return self._print(expr.parent) + '_{%s, %s}'%(expr.i, expr.j)1063 def _print_MatrixSlice(self, expr):1064 def latexslice(x):1065 x = list(x)1066 if x[2] == 1:1067 del x[2]1068 if x[1] == x[0] + 1:1069 del x[1]1070 if x[0] == 0:1071 x[0] = ''1072 return ':'.join(map(self._print, x))1073 return (self._print(expr.parent) + r'\left[' +1074 latexslice(expr.rowslice) + ', ' +1075 latexslice(expr.colslice) + r'\right]')1076 def _print_BlockMatrix(self, expr):1077 return self._print(expr.blocks)1078 def _print_Transpose(self, expr):1079 mat = expr.arg1080 from sympy.matrices import MatrixSymbol1081 if not isinstance(mat, MatrixSymbol):1082 return r"\left(%s\right)^T" % self._print(mat)1083 else:1084 return "%s^T" % self._print(mat)1085 def _print_Adjoint(self, expr):1086 mat = expr.arg1087 from sympy.matrices import MatrixSymbol1088 if not isinstance(mat, MatrixSymbol):1089 return r"\left(%s\right)^\dag" % self._print(mat)1090 else:1091 return "%s^\dag" % self._print(mat)1092 def _print_MatAdd(self, expr):1093 terms = list(expr.args)1094 tex = " + ".join(map(self._print, terms))1095 return tex1096 def _print_MatMul(self, expr):1097 from sympy import Add, MatAdd, HadamardProduct1098 def parens(x):1099 if isinstance(x, (Add, MatAdd, HadamardProduct)):1100 return r"\left(%s\right)" % self._print(x)1101 return self._print(x)1102 return ' '.join(map(parens, expr.args))1103 def _print_HadamardProduct(self, expr):1104 from sympy import Add, MatAdd, MatMul1105 def parens(x):1106 if isinstance(x, (Add, MatAdd, MatMul)):1107 return r"\left(%s\right)" % self._print(x)1108 return self._print(x)1109 return ' \circ '.join(map(parens, expr.args))1110 def _print_MatPow(self, expr):1111 base, exp = expr.base, expr.exp1112 from sympy.matrices import MatrixSymbol1113 if not isinstance(base, MatrixSymbol):1114 return r"\left(%s\right)^{%s}" % (self._print(base), self._print(exp))1115 else:1116 return "%s^{%s}" % (self._print(base), self._print(exp))1117 def _print_ZeroMatrix(self, Z):1118 return r"\bold{0}"1119 def _print_Identity(self, I):1120 return r"\mathbb{I}"1121 def _print_tuple(self, expr):1122 return r"\left ( %s\right )" % \1123 r", \quad ".join([ self._print(i) for i in expr ])1124 def _print_Tuple(self, expr):1125 return self._print_tuple(expr)1126 def _print_list(self, expr):1127 return r"\left [ %s\right ]" % \1128 r", \quad ".join([ self._print(i) for i in expr ])1129 def _print_dict(self, d):1130 keys = sorted(d.keys(), key=default_sort_key)1131 items = []1132 for key in keys:1133 val = d[key]1134 items.append("%s : %s" % (self._print(key), self._print(val)))1135 return r"\left \{ %s\right \}" % r", \quad ".join(items)1136 def _print_Dict(self, expr):1137 return self._print_dict(expr)1138 def _print_DiracDelta(self, expr, exp=None):1139 if len(expr.args) == 1 or expr.args[1] == 0:1140 tex = r"\delta\left(%s\right)" % self._print(expr.args[0])1141 else:1142 tex = r"\delta^{\left( %s \right)}\left( %s \right)" % (1143 self._print(expr.args[1]), self._print(expr.args[0]))1144 if exp:1145 tex = r"\left(%s\right)^{%s}" % (tex, exp)1146 return tex1147 def _print_Heaviside(self, expr, exp=None):1148 tex = r"\theta\left(%s\right)" % self._print(expr.args[0])1149 if exp:1150 tex = r"\left(%s\right)^{%s}" % (tex, exp)1151 return tex1152 def _print_KroneckerDelta(self, expr, exp=None):1153 i = self._print(expr.args[0])1154 j = self._print(expr.args[1])1155 if expr.args[0].is_Atom and expr.args[1].is_Atom:1156 tex = r'\delta_{%s %s}' % (i, j)1157 else:1158 tex = r'\delta_{%s, %s}' % (i, j)1159 if exp:1160 tex = r'\left(%s\right)^{%s}' % (tex, exp)1161 return tex1162 def _print_LeviCivita(self, expr, exp=None):1163 indices = map(self._print, expr.args)1164 if all(map(lambda x: x.is_Atom, expr.args)):1165 tex = r'\varepsilon_{%s}' % " ".join(indices)1166 else:1167 tex = r'\varepsilon_{%s}' % ", ".join(indices)1168 if exp:1169 tex = r'\left(%s\right)^{%s}' % (tex, exp)1170 return tex1171 def _print_ProductSet(self, p):1172 if len(p.sets) > 1 and not has_variety(p.sets):1173 return self._print(p.sets[0]) + "^%d" % len(p.sets)1174 else:1175 return r" \times ".join(self._print(set) for set in p.sets)1176 def _print_RandomDomain(self, d):1177 try:1178 return 'Domain: ' + self._print(d.as_boolean())1179 except Exception:1180 try:1181 return ('Domain: ' + self._print(d.symbols) + ' in ' +1182 self._print(d.set))1183 except:1184 return 'Domain on ' + self._print(d.symbols)1185 def _print_FiniteSet(self, s):1186 items = sorted(s.args, key=default_sort_key)1187 return self._print_set(items)1188 def _print_set(self, s):1189 items = sorted(s, key=default_sort_key)1190 items = ", ".join(map(self._print, items))1191 return r"\left\{%s\right\}" % items1192 _print_frozenset = _print_set1193 def _print_Range(self, s):1194 if len(s) > 4:1195 it = iter(s)1196 printset = next(it), next(it), '\ldots', s._last_element1197 else:1198 printset = tuple(s)1199 return (r"\left\{"1200 + r", ".join(self._print(el) for el in printset)1201 + r"\right\}")1202 def _print_Interval(self, i):1203 if i.start == i.end:1204 return r"\left\{%s\right\}" % self._print(i.start)1205 else:1206 if i.left_open:1207 left = '('1208 else:1209 left = '['1210 if i.right_open:1211 right = ')'1212 else:1213 right = ']'1214 return r"\left%s%s, %s\right%s" % \1215 (left, self._print(i.start), self._print(i.end), right)1216 def _print_Union(self, u):1217 return r" \cup ".join([self._print(i) for i in u.args])1218 def _print_Complement(self, u):1219 return r" \setminus ".join([self._print(i) for i in u.args])1220 def _print_Intersection(self, u):1221 return r" \cap ".join([self._print(i) for i in u.args])1222 def _print_EmptySet(self, e):1223 return r"\emptyset"1224 def _print_Naturals(self, n):1225 return r"\mathbb{N}"1226 def _print_Integers(self, i):1227 return r"\mathbb{Z}"1228 def _print_Reals(self, i):1229 return r"\mathbb{R}"1230 def _print_ImageSet(self, s):1231 return r"\left\{%s\; |\; %s \in %s\right\}" % (1232 self._print(s.lamda.expr),1233 ', '.join([self._print(var) for var in s.lamda.variables]),1234 self._print(s.base_set))1235 def _print_Contains(self, e):1236 return r"%s \in %s" % tuple(self._print(a) for a in e.args)1237 def _print_FiniteField(self, expr):1238 return r"\mathbb{F}_{%s}" % expr.mod1239 def _print_IntegerRing(self, expr):1240 return r"\mathbb{Z}"1241 def _print_RationalField(self, expr):1242 return r"\mathbb{Q}"1243 def _print_RealField(self, expr):1244 return r"\mathbb{R}"1245 def _print_ComplexField(self, expr):1246 return r"\mathbb{C}"1247 def _print_PolynomialRing(self, expr):1248 domain = self._print(expr.domain)1249 symbols = ", ".join(map(self._print, expr.symbols))1250 return r"%s\left[%s\right]" % (domain, symbols)1251 def _print_FractionField(self, expr):1252 domain = self._print(expr.domain)1253 symbols = ", ".join(map(self._print, expr.symbols))1254 return r"%s\left(%s\right)" % (domain, symbols)1255 def _print_PolynomialRingBase(self, expr):1256 domain = self._print(expr.domain)1257 symbols = ", ".join(map(self._print, expr.symbols))1258 inv = ""1259 if not expr.is_Poly:1260 inv = r"S_<^{-1}"1261 return r"%s%s\left[%s\right]" % (inv, domain, symbols)1262 def _print_Poly(self, poly):1263 cls = poly.__class__.__name__1264 expr = self._print(poly.as_expr())1265 gens = list(map(self._print, poly.gens))1266 domain = "domain=%s" % self._print(poly.get_domain())1267 args = ", ".join([expr] + gens + [domain])1268 if cls in accepted_latex_functions:1269 tex = r"\%s {\left (%s \right )}" % (cls, args)1270 else:1271 tex = r"\operatorname{%s}{\left( %s \right)}" % (cls, args)1272 return tex1273 def _print_RootOf(self, root):1274 cls = root.__class__.__name__1275 expr = self._print(root.expr)1276 index = root.index1277 if cls in accepted_latex_functions:1278 return r"\%s {\left(%s, %d\right)}" % (cls, expr, index)1279 else:1280 return r"\operatorname{%s} {\left(%s, %d\right)}" % (cls, expr, index)1281 def _print_RootSum(self, expr):1282 cls = expr.__class__.__name__1283 args = [self._print(expr.expr)]1284 if expr.fun is not S.IdentityFunction:1285 args.append(self._print(expr.fun))1286 if cls in accepted_latex_functions:1287 return r"\%s {\left(%s\right)}" % (cls, ", ".join(args))1288 else:1289 return r"\operatorname{%s} {\left(%s\right)}" % (cls, ", ".join(args))1290 def _print_PolyElement(self, poly):1291 mul_symbol = self._settings['mul_symbol_latex']1292 return poly.str(self, PRECEDENCE, "{%s}^{%d}", mul_symbol)1293 def _print_FracElement(self, frac):1294 if frac.denom == 1:1295 return self._print(frac.numer)1296 else:1297 numer = self._print(frac.numer)1298 denom = self._print(frac.denom)1299 return r"\frac{%s}{%s}" % (numer, denom)1300 def _print_euler(self, expr):1301 return r"E_{%s}" % self._print(expr.args[0])1302 def _print_catalan(self, expr):1303 return r"C_{%s}" % self._print(expr.args[0])1304 def _print_MellinTransform(self, expr):1305 return r"\mathcal{M}_{%s}\left[%s\right]\left(%s\right)" % (self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2]))1306 def _print_InverseMellinTransform(self, expr):1307 return r"\mathcal{M}^{-1}_{%s}\left[%s\right]\left(%s\right)" % (self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2]))1308 def _print_LaplaceTransform(self, expr):1309 return r"\mathcal{L}_{%s}\left[%s\right]\left(%s\right)" % (self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2]))1310 def _print_InverseLaplaceTransform(self, expr):1311 return r"\mathcal{L}^{-1}_{%s}\left[%s\right]\left(%s\right)" % (self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2]))1312 def _print_FourierTransform(self, expr):1313 return r"\mathcal{F}_{%s}\left[%s\right]\left(%s\right)" % (self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2]))1314 def _print_InverseFourierTransform(self, expr):1315 return r"\mathcal{F}^{-1}_{%s}\left[%s\right]\left(%s\right)" % (self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2]))1316 def _print_SineTransform(self, expr):1317 return r"\mathcal{SIN}_{%s}\left[%s\right]\left(%s\right)" % (self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2]))1318 def _print_InverseSineTransform(self, expr):1319 return r"\mathcal{SIN}^{-1}_{%s}\left[%s\right]\left(%s\right)" % (self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2]))1320 def _print_CosineTransform(self, expr):1321 return r"\mathcal{COS}_{%s}\left[%s\right]\left(%s\right)" % (self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2]))1322 def _print_InverseCosineTransform(self, expr):1323 return r"\mathcal{COS}^{-1}_{%s}\left[%s\right]\left(%s\right)" % (self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2]))1324 def _print_DMP(self, p):1325 try:1326 if p.ring is not None:1327 # TODO incorporate order1328 return self._print(p.ring.to_sympy(p))1329 except SympifyError:1330 pass1331 return self._print(repr(p))1332 def _print_DMF(self, p):1333 return self._print_DMP(p)1334 def _print_Object(self, object):1335 return self._print(Symbol(object.name))1336 def _print_Morphism(self, morphism):1337 domain = self._print(morphism.domain)1338 codomain = self._print(morphism.codomain)1339 return "%s\\rightarrow %s" % (domain, codomain)1340 def _print_NamedMorphism(self, morphism):1341 pretty_name = self._print(Symbol(morphism.name))1342 pretty_morphism = self._print_Morphism(morphism)1343 return "%s:%s" % (pretty_name, pretty_morphism)1344 def _print_IdentityMorphism(self, morphism):1345 from sympy.categories import NamedMorphism1346 return self._print_NamedMorphism(NamedMorphism(1347 morphism.domain, morphism.codomain, "id"))1348 def _print_CompositeMorphism(self, morphism):1349 # All components of the morphism have names and it is thus1350 # possible to build the name of the composite.1351 component_names_list = [self._print(Symbol(component.name)) for1352 component in morphism.components]1353 component_names_list.reverse()1354 component_names = "\\circ ".join(component_names_list) + ":"1355 pretty_morphism = self._print_Morphism(morphism)1356 return component_names + pretty_morphism1357 def _print_Category(self, morphism):1358 return "\\mathbf{%s}" % self._print(Symbol(morphism.name))1359 def _print_Diagram(self, diagram):1360 if not diagram.premises:1361 # This is an empty diagram.1362 return self._print(S.EmptySet)1363 latex_result = self._print(diagram.premises)1364 if diagram.conclusions:1365 latex_result += "\\Longrightarrow %s" % \1366 self._print(diagram.conclusions)1367 return latex_result1368 def _print_DiagramGrid(self, grid):1369 latex_result = "\\begin{array}{%s}\n" % ("c" * grid.width)1370 for i in xrange(grid.height):1371 for j in xrange(grid.width):1372 if grid[i, j]:1373 latex_result += latex(grid[i, j])1374 latex_result += " "1375 if j != grid.width - 1:1376 latex_result += "& "1377 if i != grid.height - 1:1378 latex_result += "\\\\"1379 latex_result += "\n"1380 latex_result += "\\end{array}\n"1381 return latex_result1382 def _print_FreeModule(self, M):1383 return '{%s}^{%s}' % (self._print(M.ring), self._print(M.rank))1384 def _print_FreeModuleElement(self, m):1385 # Print as row vector for convenience, for now.1386 return r"\left[ %s \right]" % ",".join(1387 '{' + self._print(x) + '}' for x in m)1388 def _print_SubModule(self, m):1389 return r"\left< %s \right>" % ",".join(1390 '{' + self._print(x) + '}' for x in m.gens)1391 def _print_ModuleImplementedIdeal(self, m):1392 return r"\left< %s \right>" % ",".join(1393 '{' + self._print(x) + '}' for [x] in m._module.gens)1394 def _print_QuotientRing(self, R):1395 # TODO nicer fractions for few generators...1396 return r"\frac{%s}{%s}" % (self._print(R.ring), self._print(R.base_ideal))1397 def _print_QuotientRingElement(self, x):1398 return r"{%s} + {%s}" % (self._print(x.data), self._print(x.ring.base_ideal))1399 def _print_QuotientModuleElement(self, m):1400 return r"{%s} + {%s}" % (self._print(m.data),1401 self._print(m.module.killed_module))1402 def _print_QuotientModule(self, M):1403 # TODO nicer fractions for few generators...1404 return r"\frac{%s}{%s}" % (self._print(M.base),1405 self._print(M.killed_module))1406 def _print_MatrixHomomorphism(self, h):1407 return r"{%s} : {%s} \to {%s}" % (self._print(h._sympy_matrix()),1408 self._print(h.domain), self._print(h.codomain))1409 def _print_BaseScalarField(self, field):1410 string = field._coord_sys._names[field._index]1411 return r'\boldsymbol{\mathrm{%s}}' % self._print(Symbol(string))1412 def _print_BaseVectorField(self, field):1413 string = field._coord_sys._names[field._index]1414 return r'\partial_{%s}' % self._print(Symbol(string))1415 def _print_Differential(self, diff):1416 field = diff._form_field1417 if hasattr(field, '_coord_sys'):1418 string = field._coord_sys._names[field._index]1419 return r'\mathrm{d}%s' % self._print(Symbol(string))1420 else:1421 return 'd(%s)' % self._print(field)1422 string = self._print(field)1423 return r'\mathrm{d}\left(%s\right)' % string1424 def _print_Tr(self, p):1425 #Todo: Handle indices1426 contents = self._print(p.args[0])1427 return r'\mbox{Tr}\left(%s\right)' % (contents)1428 def _print_totient(self, expr):1429 return r'\phi\left( %s \right)' % self._print(expr.args[0])1430 def _print_divisor_sigma(self, expr, exp=None):1431 if len(expr.args) == 2:1432 tex = r"_%s\left(%s\right)" % tuple(map(self._print,1433 (expr.args[1], expr.args[0])))1434 else:1435 tex = r"\left(%s\right)" % self._print(expr.args[0])1436 if exp is not None:1437 return r"\sigma^{%s}%s" % (self._print(exp), tex)1438 return r"\sigma%s" % tex1439def translate(s):1440 r'''1441 Check for a modifier ending the string. If present, convert the1442 modifier to latex and translate the rest recursively.1443 Given a description of a Greek letter or other special character,1444 return the appropriate latex.1445 Let everything else pass as given.1446 >>> from sympy.printing.latex import translate1447 >>> translate('alphahatdotprime')1448 "{\\dot{\\hat{\\alpha}}}'"1449 '''1450 # Process the rest1451 tex = tex_greek_dictionary.get(s)...
_sw_update.py
Source:_sw_update.py
...16INSTANCE_ACTION_MIGRATE = 'migrate'17INSTANCE_ACTION_STOP_START = 'stop-start'18ALARM_RESTRICTIONS_STRICT = 'strict'19ALARM_RESTRICTIONS_RELAXED = 'relaxed'20def _print(indent_by, field, value, remains=''):21 print("%s%s%s%s %s" % (' ' * indent_by, field + ':',22 ' ' * (42 - indent_by - len('%s' % field) - 1), value,23 remains))24def _display_strategy_step(strategy_step, active=False):25 """26 Software Update - Display Strategy Step Information27 """28 # If active flag is passed29 # skip steps that are not started:'initial' or completed cleanly: 'success'30 # this leaves failed and in-progress states31 if active:32 if strategy_step.result in ['initial', 'success']:33 return False34 _print(12, "step-id", strategy_step.step_id)35 _print(12, "step-name", strategy_step.step_name)36 if 0 < len(strategy_step.entity_type):37 _print(12, "entity-type", strategy_step.entity_type)38 if 0 < len(strategy_step.entity_names):39 _print(12, "entity-names", strategy_step.entity_names)40 if 0 < len(strategy_step.entity_uuids):41 _print(12, "entity-uuids", strategy_step.entity_uuids)42 _print(12, "timeout", strategy_step.timeout, 'seconds')43 if 0 < len(strategy_step.start_date_time):44 _print(12, "start-date-time", strategy_step.start_date_time)45 if 0 < len(strategy_step.end_date_time):46 _print(12, "end-date-time", strategy_step.end_date_time)47 _print(12, "result", strategy_step.result)48 _print(12, "reason", strategy_step.reason)49 return True50def _display_strategy_stage(strategy_stage, details=False, active=False):51 """52 Software Update - Display Strategy Stage Information53 """54 # If active flag is passed, only display a stage that is in progress55 if active:56 if not strategy_stage.inprogress:57 return False58 _print(8, "stage-id", strategy_stage.stage_id)59 _print(8, "stage-name", strategy_stage.stage_name)60 _print(8, "total-steps", strategy_stage.total_steps)61 _print(8, "current-step", strategy_stage.current_step)62 _print(8, "timeout", strategy_stage.timeout, 'seconds')63 _print(8, "start-date-time", strategy_stage.start_date_time)64 if strategy_stage.inprogress:65 _print(8, "inprogress", "true")66 else:67 _print(8, "end-date-time", strategy_stage.end_date_time)68 _print(8, "result", strategy_stage.result)69 _print(8, "reason", strategy_stage.reason)70 if details or active:71 print(" steps:")72 for step in strategy_stage.steps:73 if _display_strategy_step(step, active):74 print("")75 return True76def _display_strategy_phase(strategy_phase, details=False, active=False):77 """78 Software Update - Display Strategy Phase Information79 """80 # If active flag is passed, only display a phase that is in progress81 if active:82 if not strategy_phase.inprogress:83 return84 print(" %s-phase:" % strategy_phase.phase_name)85 _print(4, "total-stages", strategy_phase.total_stages)86 _print(4, "current-stage", strategy_phase.current_stage)87 _print(4, "stop-at-stage", strategy_phase.stop_at_stage)88 _print(4, "timeout", strategy_phase.timeout, 'seconds')89 _print(4, "completion-percentage",90 ("%s%%" % strategy_phase.completion_percentage))91 _print(4, "start-date-time", strategy_phase.start_date_time)92 if strategy_phase.inprogress:93 _print(4, "inprogress", "true")94 else:95 _print(4, "end-date-time", strategy_phase.end_date_time)96 _print(4, "result", strategy_phase.result)97 _print(4, "reason", strategy_phase.reason)98 if details or active:99 print(" stages:")100 for stage in strategy_phase.stages:101 if _display_strategy_stage(stage, details, active):102 print("")103def _display_strategy(strategy, details=False, active=False):104 """105 Software Update - Display Strategy Information106 """107 if strategy.name == STRATEGY_NAME_SW_PATCH:108 print("Strategy Patch Strategy:")109 elif strategy.name == STRATEGY_NAME_SW_UPGRADE:110 print("Strategy Upgrade Strategy:")111 elif strategy.name == STRATEGY_NAME_FW_UPDATE:112 print("Strategy Firmware Update Strategy:")113 elif strategy.name == STRATEGY_NAME_KUBE_ROOTCA_UPDATE:114 print("Strategy Kubernetes RootCA Update Strategy:")115 elif strategy.name == STRATEGY_NAME_KUBE_UPGRADE:116 print("Strategy Kubernetes Upgrade Strategy:")117 else:118 print("Strategy Unknown Strategy:")119 _print(2, "strategy-uuid", strategy.uuid)120 _print(2, "controller-apply-type", strategy.controller_apply_type)121 _print(2, "storage-apply-type", strategy.storage_apply_type)122 _print(2, "worker-apply-type", strategy.worker_apply_type)123 if APPLY_TYPE_PARALLEL == strategy.worker_apply_type:124 _print(2, "max-parallel-worker-hosts",125 strategy.max_parallel_worker_hosts)126 _print(2, "default-instance-action", strategy.default_instance_action)127 _print(2, "alarm-restrictions", strategy.alarm_restrictions)128 _print(2, "current-phase", strategy.current_phase)129 _print(2, "current-phase-completion",130 ("%s%%" % strategy.current_phase_completion_percentage))131 _print(2, "state", strategy.state)132 if details or active:133 if 0 < strategy.build_phase.total_stages:134 _display_strategy_phase(strategy.build_phase, details, active)135 if 0 < strategy.apply_phase.total_stages:136 _display_strategy_phase(strategy.apply_phase, details, active)137 if 0 < strategy.abort_phase.total_stages:138 _display_strategy_phase(strategy.abort_phase, details, active)139 else:140 if strategy.current_phase == strategy.build_phase.phase_name:141 if strategy.build_phase.inprogress:142 _print(2, "inprogress", "true")143 else:144 _print(2, "build-result", strategy.build_phase.result)145 _print(2, "build-reason", strategy.build_phase.reason)146 elif strategy.current_phase == strategy.apply_phase.phase_name:147 if strategy.apply_phase.inprogress:148 _print(2, "inprogress", "true")149 else:150 _print(2, "apply-result", strategy.apply_phase.result)151 _print(2, "apply-reason", strategy.apply_phase.reason)152 elif strategy.current_phase == strategy.abort_phase.phase_name:153 if strategy.abort_phase.inprogress:154 _print(2, "inprogress", "true")155 _print(2, "apply-result", strategy.apply_phase.result)156 _print(2, "apply-reason", strategy.apply_phase.reason)157 _print(2, "abort-result", "")158 _print(2, "abort-reason", "")159 else:160 _print(2, "apply-result", strategy.apply_phase.result)161 _print(2, "apply-reason", strategy.apply_phase.reason)162 _print(2, "abort-result", strategy.abort_phase.result)163 _print(2, "abort-reason", strategy.abort_phase.reason)164def create_strategy(os_auth_uri, os_project_name, os_project_domain_name,165 os_username, os_password, os_user_domain_name,166 os_region_name, os_interface,167 strategy_name, controller_apply_type,168 storage_apply_type, swift_apply_type, worker_apply_type,169 max_parallel_worker_hosts,170 default_instance_action, alarm_restrictions, **kwargs):171 """172 Software Update - Create Strategy173 """174 token = openstack.get_token(os_auth_uri, os_project_name,175 os_project_domain_name, os_username, os_password,176 os_user_domain_name)177 url = token.get_service_url(os_region_name, openstack.SERVICE.VIM,...
1_test_sync_label.py
Source:1_test_sync_label.py
...3def run():4 5 #################### _sync deco + _sync(ref=) + _sync([' ', ' '])6 7 _print('test1')8 @_spawn(_name='work1')9 def _():10 _print('\tdoing1')11 sleep(1)12 _print('\tmiddle1')13 a.val = 'middle'14 sleep(1)15 _print('\tdone1')16 17 @_spawn(_name='work2')18 def _():19 _print('\twork2 doing')20 sleep(0.1)21 _sync('lol',ref='work1')22 _print('\twork2 pause work')23 sleep(3)24 @_do25 def _():26 if a.val == 'middle':27 print('fail')28 exit(0)29 sleep(1)30 _label('lol')31 _print('\twork2 done')32 _return(ref='work1')33 _print('\tmain should wait for work')34 _sync(['work1','work2'])35 36 ################# _sync([' ', ' '])37 a.val = None38 39 _print('test2')40 def _():41 _print('\tdoing1')42 sleep(1)43 _print('\tmiddle1')44 a.val = 'middle'45 sleep(1)46 _print('\tdone1')47 work1 = _spawn(_, _name='work1')48 49 def _():50 _print('\twork2 doing')51 sleep(0.1)52 _sync('lol1',ref='work1')53 _print('\twork2 pause work')54 sleep(3)55 @_do56 def _():57 if a.val == 'middle':58 print('\tfail')59 exit(0)60 sleep(1)61 _label('lol1')62 _print('\twork2 done')63 _return(ref='work1')64 work2 = _spawn(_, _name='work2')65 66 _print('main should wait for work')67 _sync(['work1','work2'])68 69 ############## _sync([ , ])70 a.val = None71 72 _print('test3')73 def _():74 _print('\tdoing1')75 sleep(1)76 _print('\tmiddle1')77 a.val = 'middle'78 sleep(1)79 _print('\tdone1')80 work1 = _spawn(_, _name='work1')81 82 def _():83 _print('\twork2 doing')84 sleep(0.1)85 _sync('lol3',ref='work1')86 _print('\twork2 pause work')87 sleep(3)88 @_do89 def _():90 if a.val == 'middle':91 print('fail')92 exit(0)93 sleep(1)94 _label('lol3')95 _print('\twork2 done')96 _return(ref='work1')97 work2 = _spawn(_, _name='work2')98 99 _print('main should wait for work')...
test_if_while.py
Source:test_if_while.py
...3a=_State(2)4def run():5 ################################################6 7 _print(col.yellow,'test case1 (_if(cond, true_func, false_func)',col.white)8 9 _print('\tval a:', a.val)10 def is_true():11 _print('\t\ttrue (bad)')12 bad()13 def is_false():14 _print('\t\tfalse (good)')15 _print('\ta.val == 0?')16 _if(lambda: a.val == 0, is_true, is_false)17 def is_true():18 _print('\t\ttrue (good)')19 def is_false():20 _print('\t\tfalse (bad)')21 bad()22 _print('\ta.val != 0')23 _if(lambda: a.val != 0, is_true, is_false)24 25 ################################################26 _print(col.yellow,'test case2 (_if, _elif, _end_if)',col.white)27 28 a.val = 229 _do(lambda: print('\tval a:', a.val) )30 _print('\ta.val == 0?')31 _if(lambda: a.val == 0)32 33 _print('\t\tis true (good)')34 _elif(lambda: a.val == 3)35 36 _print('\t\tval is:', a.val, '(bad)')37 38 bad()39 40 _else()41 42 _print('\t\tis else (good)')43 _end_if()44 45 ################################################46 47 _print(col.yellow,'test case3 (with _if , with _elif, with _else)',col.white)48 49 _do(lambda: print('\tval a:', a.val) )50 _print('\ta.val == 0 or a.val == 3 or else?' )51 with _if(lambda: a.val == 0):52 _print('\tis true')53 _do(exit,-1)54 with _elif(lambda: a.val == 3):55 _print('\tval is:', a.val)56 _do(exit,-1)57 with _else():58 _print('\tis else (good)')59 60 _print(col.yellow,'test case4',col.white)61 a.val = 262 with _if(lambda: a.val == 2):63 _print('\tis 2 (good)')64 with _elif(lambda: a.val == 3):65 _print('\tval is:', a.val, '(fail)')66 bad()67 with _else():68 _print('\tis none')69 bad()70 ################################################71 72 _print(col.yellow,'test case4 (while)',col.white)73 with _while(lambda: a.val != 5):74 a.inc()75 @_do76 def _():...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!