latex.py 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277
  1. """
  2. A Printer which converts an expression into its LaTeX equivalent.
  3. """
  4. from __future__ import annotations
  5. from typing import Any, Callable, TYPE_CHECKING
  6. import itertools
  7. from sympy.core import Add, Float, Mod, Mul, Number, S, Symbol, Expr
  8. from sympy.core.alphabets import greeks
  9. from sympy.core.containers import Tuple
  10. from sympy.core.function import Function, AppliedUndef, Derivative
  11. from sympy.core.operations import AssocOp
  12. from sympy.core.power import Pow
  13. from sympy.core.sorting import default_sort_key
  14. from sympy.core.sympify import SympifyError
  15. from sympy.logic.boolalg import true, BooleanTrue, BooleanFalse
  16. from sympy.tensor.array import NDimArray
  17. # sympy.printing imports
  18. from sympy.printing.precedence import precedence_traditional
  19. from sympy.printing.printer import Printer, print_function
  20. from sympy.printing.conventions import split_super_sub, requires_partial
  21. from sympy.printing.precedence import precedence, PRECEDENCE
  22. from mpmath.libmp.libmpf import prec_to_dps, to_str as mlib_to_str
  23. from sympy.utilities.iterables import has_variety, sift
  24. import re
  25. if TYPE_CHECKING:
  26. from sympy.vector.basisdependent import BasisDependent
  27. # Hand-picked functions which can be used directly in both LaTeX and MathJax
  28. # Complete list at
  29. # https://docs.mathjax.org/en/latest/tex.html#supported-latex-commands
  30. # This variable only contains those functions which SymPy uses.
  31. accepted_latex_functions = ['arcsin', 'arccos', 'arctan', 'sin', 'cos', 'tan',
  32. 'sinh', 'cosh', 'tanh', 'sqrt', 'ln', 'log', 'sec',
  33. 'csc', 'cot', 'coth', 're', 'im', 'frac', 'root',
  34. 'arg',
  35. ]
  36. tex_greek_dictionary = {
  37. 'Alpha': r'\mathrm{A}',
  38. 'Beta': r'\mathrm{B}',
  39. 'Gamma': r'\Gamma',
  40. 'Delta': r'\Delta',
  41. 'Epsilon': r'\mathrm{E}',
  42. 'Zeta': r'\mathrm{Z}',
  43. 'Eta': r'\mathrm{H}',
  44. 'Theta': r'\Theta',
  45. 'Iota': r'\mathrm{I}',
  46. 'Kappa': r'\mathrm{K}',
  47. 'Lambda': r'\Lambda',
  48. 'Mu': r'\mathrm{M}',
  49. 'Nu': r'\mathrm{N}',
  50. 'Xi': r'\Xi',
  51. 'omicron': 'o',
  52. 'Omicron': r'\mathrm{O}',
  53. 'Pi': r'\Pi',
  54. 'Rho': r'\mathrm{P}',
  55. 'Sigma': r'\Sigma',
  56. 'Tau': r'\mathrm{T}',
  57. 'Upsilon': r'\Upsilon',
  58. 'Phi': r'\Phi',
  59. 'Chi': r'\mathrm{X}',
  60. 'Psi': r'\Psi',
  61. 'Omega': r'\Omega',
  62. 'lamda': r'\lambda',
  63. 'Lamda': r'\Lambda',
  64. 'khi': r'\chi',
  65. 'Khi': r'\mathrm{X}',
  66. 'varepsilon': r'\varepsilon',
  67. 'varkappa': r'\varkappa',
  68. 'varphi': r'\varphi',
  69. 'varpi': r'\varpi',
  70. 'varrho': r'\varrho',
  71. 'varsigma': r'\varsigma',
  72. 'vartheta': r'\vartheta',
  73. }
  74. other_symbols = {'aleph', 'beth', 'daleth', 'gimel', 'ell', 'eth', 'hbar',
  75. 'hslash', 'mho', 'wp'}
  76. # Variable name modifiers
  77. modifier_dict: dict[str, Callable[[str], str]] = {
  78. # Accents
  79. 'mathring': lambda s: r'\mathring{'+s+r'}',
  80. 'ddddot': lambda s: r'\ddddot{'+s+r'}',
  81. 'dddot': lambda s: r'\dddot{'+s+r'}',
  82. 'ddot': lambda s: r'\ddot{'+s+r'}',
  83. 'dot': lambda s: r'\dot{'+s+r'}',
  84. 'check': lambda s: r'\check{'+s+r'}',
  85. 'breve': lambda s: r'\breve{'+s+r'}',
  86. 'acute': lambda s: r'\acute{'+s+r'}',
  87. 'grave': lambda s: r'\grave{'+s+r'}',
  88. 'tilde': lambda s: r'\tilde{'+s+r'}',
  89. 'hat': lambda s: r'\hat{'+s+r'}',
  90. 'bar': lambda s: r'\bar{'+s+r'}',
  91. 'vec': lambda s: r'\vec{'+s+r'}',
  92. 'prime': lambda s: "{"+s+"}'",
  93. 'prm': lambda s: "{"+s+"}'",
  94. # Faces
  95. 'bold': lambda s: r'\boldsymbol{'+s+r'}',
  96. 'bm': lambda s: r'\boldsymbol{'+s+r'}',
  97. 'cal': lambda s: r'\mathcal{'+s+r'}',
  98. 'scr': lambda s: r'\mathscr{'+s+r'}',
  99. 'frak': lambda s: r'\mathfrak{'+s+r'}',
  100. # Brackets
  101. 'norm': lambda s: r'\left\|{'+s+r'}\right\|',
  102. 'avg': lambda s: r'\left\langle{'+s+r'}\right\rangle',
  103. 'abs': lambda s: r'\left|{'+s+r'}\right|',
  104. 'mag': lambda s: r'\left|{'+s+r'}\right|',
  105. }
  106. greek_letters_set = frozenset(greeks)
  107. _between_two_numbers_p = (
  108. re.compile(r'[0-9][} ]*$'), # search
  109. re.compile(r'[0-9]'), # match
  110. )
  111. def latex_escape(s: str) -> str:
  112. """
  113. Escape a string such that latex interprets it as plaintext.
  114. We cannot use verbatim easily with mathjax, so escaping is easier.
  115. Rules from https://tex.stackexchange.com/a/34586/41112.
  116. """
  117. s = s.replace('\\', r'\textbackslash')
  118. for c in '&%$#_{}':
  119. s = s.replace(c, '\\' + c)
  120. s = s.replace('~', r'\textasciitilde')
  121. s = s.replace('^', r'\textasciicircum')
  122. return s
  123. class LatexPrinter(Printer):
  124. printmethod = "_latex"
  125. _default_settings: dict[str, Any] = {
  126. "full_prec": False,
  127. "fold_frac_powers": False,
  128. "fold_func_brackets": False,
  129. "fold_short_frac": None,
  130. "inv_trig_style": "abbreviated",
  131. "itex": False,
  132. "ln_notation": False,
  133. "long_frac_ratio": None,
  134. "mat_delim": "[",
  135. "mat_str": None,
  136. "mode": "plain",
  137. "mul_symbol": None,
  138. "order": None,
  139. "symbol_names": {},
  140. "root_notation": True,
  141. "mat_symbol_style": "plain",
  142. "imaginary_unit": "i",
  143. "gothic_re_im": False,
  144. "decimal_separator": "period",
  145. "perm_cyclic": True,
  146. "parenthesize_super": True,
  147. "min": None,
  148. "max": None,
  149. "diff_operator": "d",
  150. }
  151. def __init__(self, settings=None):
  152. Printer.__init__(self, settings)
  153. if 'mode' in self._settings:
  154. valid_modes = ['inline', 'plain', 'equation',
  155. 'equation*']
  156. if self._settings['mode'] not in valid_modes:
  157. raise ValueError("'mode' must be one of 'inline', 'plain', "
  158. "'equation' or 'equation*'")
  159. if self._settings['fold_short_frac'] is None and \
  160. self._settings['mode'] == 'inline':
  161. self._settings['fold_short_frac'] = True
  162. mul_symbol_table = {
  163. None: r" ",
  164. "ldot": r" \,.\, ",
  165. "dot": r" \cdot ",
  166. "times": r" \times "
  167. }
  168. try:
  169. self._settings['mul_symbol_latex'] = \
  170. mul_symbol_table[self._settings['mul_symbol']]
  171. except KeyError:
  172. self._settings['mul_symbol_latex'] = \
  173. self._settings['mul_symbol']
  174. try:
  175. self._settings['mul_symbol_latex_numbers'] = \
  176. mul_symbol_table[self._settings['mul_symbol'] or 'dot']
  177. except KeyError:
  178. if (self._settings['mul_symbol'].strip() in
  179. ['', ' ', '\\', '\\,', '\\:', '\\;', '\\quad']):
  180. self._settings['mul_symbol_latex_numbers'] = \
  181. mul_symbol_table['dot']
  182. else:
  183. self._settings['mul_symbol_latex_numbers'] = \
  184. self._settings['mul_symbol']
  185. self._delim_dict = {'(': ')', '[': ']'}
  186. imaginary_unit_table = {
  187. None: r"i",
  188. "i": r"i",
  189. "ri": r"\mathrm{i}",
  190. "ti": r"\text{i}",
  191. "j": r"j",
  192. "rj": r"\mathrm{j}",
  193. "tj": r"\text{j}",
  194. }
  195. imag_unit = self._settings['imaginary_unit']
  196. self._settings['imaginary_unit_latex'] = imaginary_unit_table.get(imag_unit, imag_unit)
  197. diff_operator_table = {
  198. None: r"d",
  199. "d": r"d",
  200. "rd": r"\mathrm{d}",
  201. "td": r"\text{d}",
  202. }
  203. diff_operator = self._settings['diff_operator']
  204. self._settings["diff_operator_latex"] = diff_operator_table.get(diff_operator, diff_operator)
  205. def _add_parens(self, s) -> str:
  206. return r"\left({}\right)".format(s)
  207. # TODO: merge this with the above, which requires a lot of test changes
  208. def _add_parens_lspace(self, s) -> str:
  209. return r"\left( {}\right)".format(s)
  210. def parenthesize(self, item, level, is_neg=False, strict=False) -> str:
  211. prec_val = precedence_traditional(item)
  212. if is_neg and strict:
  213. return self._add_parens(self._print(item))
  214. if (prec_val < level) or ((not strict) and prec_val <= level):
  215. return self._add_parens(self._print(item))
  216. else:
  217. return self._print(item)
  218. def parenthesize_super(self, s):
  219. """
  220. Protect superscripts in s
  221. If the parenthesize_super option is set, protect with parentheses, else
  222. wrap in braces.
  223. """
  224. if "^" in s:
  225. if self._settings['parenthesize_super']:
  226. return self._add_parens(s)
  227. else:
  228. return "{{{}}}".format(s)
  229. return s
  230. def doprint(self, expr) -> str:
  231. tex = Printer.doprint(self, expr)
  232. if self._settings['mode'] == 'plain':
  233. return tex
  234. elif self._settings['mode'] == 'inline':
  235. return r"$%s$" % tex
  236. elif self._settings['itex']:
  237. return r"$$%s$$" % tex
  238. else:
  239. env_str = self._settings['mode']
  240. return r"\begin{%s}%s\end{%s}" % (env_str, tex, env_str)
  241. def _needs_brackets(self, expr) -> bool:
  242. """
  243. Returns True if the expression needs to be wrapped in brackets when
  244. printed, False otherwise. For example: a + b => True; a => False;
  245. 10 => False; -10 => True.
  246. """
  247. return not ((expr.is_Integer and expr.is_nonnegative)
  248. or (expr.is_Atom and (expr is not S.NegativeOne
  249. and expr.is_Rational is False)))
  250. def _needs_function_brackets(self, expr) -> bool:
  251. """
  252. Returns True if the expression needs to be wrapped in brackets when
  253. passed as an argument to a function, False otherwise. This is a more
  254. liberal version of _needs_brackets, in that many expressions which need
  255. to be wrapped in brackets when added/subtracted/raised to a power do
  256. not need them when passed to a function. Such an example is a*b.
  257. """
  258. if not self._needs_brackets(expr):
  259. return False
  260. else:
  261. # Muls of the form a*b*c... can be folded
  262. if expr.is_Mul and not self._mul_is_clean(expr):
  263. return True
  264. # Pows which don't need brackets can be folded
  265. elif expr.is_Pow and not self._pow_is_clean(expr):
  266. return True
  267. # Add and Function always need brackets
  268. elif expr.is_Add or expr.is_Function:
  269. return True
  270. else:
  271. return False
  272. def _needs_mul_brackets(self, expr, first=False, last=False) -> bool:
  273. """
  274. Returns True if the expression needs to be wrapped in brackets when
  275. printed as part of a Mul, False otherwise. This is True for Add,
  276. but also for some container objects that would not need brackets
  277. when appearing last in a Mul, e.g. an Integral. ``last=True``
  278. specifies that this expr is the last to appear in a Mul.
  279. ``first=True`` specifies that this expr is the first to appear in
  280. a Mul.
  281. """
  282. from sympy.concrete.products import Product
  283. from sympy.concrete.summations import Sum
  284. from sympy.integrals.integrals import Integral
  285. if expr.is_Mul:
  286. if not first and expr.could_extract_minus_sign():
  287. return True
  288. elif precedence_traditional(expr) < PRECEDENCE["Mul"]:
  289. return True
  290. elif expr.is_Relational:
  291. return True
  292. if expr.is_Piecewise:
  293. return True
  294. if any(expr.has(x) for x in (Mod,)):
  295. return True
  296. if (not last and
  297. any(expr.has(x) for x in (Integral, Product, Sum))):
  298. return True
  299. return False
  300. def _needs_add_brackets(self, expr) -> bool:
  301. """
  302. Returns True if the expression needs to be wrapped in brackets when
  303. printed as part of an Add, False otherwise. This is False for most
  304. things.
  305. """
  306. if expr.is_Relational:
  307. return True
  308. if any(expr.has(x) for x in (Mod,)):
  309. return True
  310. if expr.is_Add:
  311. return True
  312. return False
  313. def _mul_is_clean(self, expr) -> bool:
  314. for arg in expr.args:
  315. if arg.is_Function:
  316. return False
  317. return True
  318. def _pow_is_clean(self, expr) -> bool:
  319. return not self._needs_brackets(expr.base)
  320. def _do_exponent(self, expr: str, exp):
  321. if exp is not None:
  322. return r"\left(%s\right)^{%s}" % (expr, exp)
  323. else:
  324. return expr
  325. def _print_Basic(self, expr):
  326. name = self._deal_with_super_sub(expr.__class__.__name__)
  327. if expr.args:
  328. ls = [self._print(o) for o in expr.args]
  329. s = r"\operatorname{{{}}}\left({}\right)"
  330. return s.format(name, ", ".join(ls))
  331. else:
  332. return r"\text{{{}}}".format(name)
  333. def _print_bool(self, e: bool | BooleanTrue | BooleanFalse):
  334. return r"\text{%s}" % e
  335. _print_BooleanTrue = _print_bool
  336. _print_BooleanFalse = _print_bool
  337. def _print_NoneType(self, e):
  338. return r"\text{%s}" % e
  339. def _print_Add(self, expr, order=None):
  340. terms = self._as_ordered_terms(expr, order=order)
  341. tex = ""
  342. for i, term in enumerate(terms):
  343. if i == 0:
  344. pass
  345. elif term.could_extract_minus_sign():
  346. tex += " - "
  347. term = -term
  348. else:
  349. tex += " + "
  350. term_tex = self._print(term)
  351. if self._needs_add_brackets(term):
  352. term_tex = r"\left(%s\right)" % term_tex
  353. tex += term_tex
  354. return tex
  355. def _print_Cycle(self, expr):
  356. from sympy.combinatorics.permutations import Permutation
  357. if expr.size == 0:
  358. return r"\left( \right)"
  359. expr = Permutation(expr)
  360. expr_perm = expr.cyclic_form
  361. siz = expr.size
  362. if expr.array_form[-1] == siz - 1:
  363. expr_perm = expr_perm + [[siz - 1]]
  364. term_tex = ''
  365. for i in expr_perm:
  366. term_tex += str(i).replace(',', r"\;")
  367. term_tex = term_tex.replace('[', r"\left( ")
  368. term_tex = term_tex.replace(']', r"\right)")
  369. return term_tex
  370. def _print_Permutation(self, expr):
  371. from sympy.combinatorics.permutations import Permutation
  372. from sympy.utilities.exceptions import sympy_deprecation_warning
  373. perm_cyclic = Permutation.print_cyclic
  374. if perm_cyclic is not None:
  375. sympy_deprecation_warning(
  376. f"""
  377. Setting Permutation.print_cyclic is deprecated. Instead use
  378. init_printing(perm_cyclic={perm_cyclic}).
  379. """,
  380. deprecated_since_version="1.6",
  381. active_deprecations_target="deprecated-permutation-print_cyclic",
  382. stacklevel=8,
  383. )
  384. else:
  385. perm_cyclic = self._settings.get("perm_cyclic", True)
  386. if perm_cyclic:
  387. return self._print_Cycle(expr)
  388. if expr.size == 0:
  389. return r"\left( \right)"
  390. lower = [self._print(arg) for arg in expr.array_form]
  391. upper = [self._print(arg) for arg in range(len(lower))]
  392. row1 = " & ".join(upper)
  393. row2 = " & ".join(lower)
  394. mat = r" \\ ".join((row1, row2))
  395. return r"\begin{pmatrix} %s \end{pmatrix}" % mat
  396. def _print_AppliedPermutation(self, expr):
  397. perm, var = expr.args
  398. return r"\sigma_{%s}(%s)" % (self._print(perm), self._print(var))
  399. def _print_Float(self, expr):
  400. # Based off of that in StrPrinter
  401. dps = prec_to_dps(expr._prec)
  402. strip = False if self._settings['full_prec'] else True
  403. low = self._settings["min"] if "min" in self._settings else None
  404. high = self._settings["max"] if "max" in self._settings else None
  405. str_real = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high)
  406. # Must always have a mul symbol (as 2.5 10^{20} just looks odd)
  407. # thus we use the number separator
  408. separator = self._settings['mul_symbol_latex_numbers']
  409. if 'e' in str_real:
  410. (mant, exp) = str_real.split('e')
  411. if exp[0] == '+':
  412. exp = exp[1:]
  413. if self._settings['decimal_separator'] == 'comma':
  414. mant = mant.replace('.','{,}')
  415. return r"%s%s10^{%s}" % (mant, separator, exp)
  416. elif str_real == "+inf":
  417. return r"\infty"
  418. elif str_real == "-inf":
  419. return r"- \infty"
  420. else:
  421. if self._settings['decimal_separator'] == 'comma':
  422. str_real = str_real.replace('.','{,}')
  423. return str_real
  424. def _print_Cross(self, expr):
  425. vec1 = expr._expr1
  426. vec2 = expr._expr2
  427. return r"%s \times %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']),
  428. self.parenthesize(vec2, PRECEDENCE['Mul']))
  429. def _print_Curl(self, expr):
  430. vec = expr._expr
  431. return r"\nabla\times %s" % self.parenthesize(vec, PRECEDENCE['Mul'])
  432. def _print_Divergence(self, expr):
  433. vec = expr._expr
  434. return r"\nabla\cdot %s" % self.parenthesize(vec, PRECEDENCE['Mul'])
  435. def _print_Dot(self, expr):
  436. vec1 = expr._expr1
  437. vec2 = expr._expr2
  438. return r"%s \cdot %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']),
  439. self.parenthesize(vec2, PRECEDENCE['Mul']))
  440. def _print_Gradient(self, expr):
  441. func = expr._expr
  442. return r"\nabla %s" % self.parenthesize(func, PRECEDENCE['Mul'])
  443. def _print_Laplacian(self, expr):
  444. func = expr._expr
  445. return r"\Delta %s" % self.parenthesize(func, PRECEDENCE['Mul'])
  446. def _print_Mul(self, expr: Expr):
  447. from sympy.simplify import fraction
  448. separator: str = self._settings['mul_symbol_latex']
  449. numbersep: str = self._settings['mul_symbol_latex_numbers']
  450. def convert(expr) -> str:
  451. if not expr.is_Mul:
  452. return str(self._print(expr))
  453. else:
  454. if self.order not in ('old', 'none'):
  455. args = expr.as_ordered_factors()
  456. else:
  457. args = list(expr.args)
  458. # If there are quantities or prefixes, append them at the back.
  459. units, nonunits = sift(args, lambda x: (hasattr(x, "_scale_factor") or hasattr(x, "is_physical_constant")) or
  460. (isinstance(x, Pow) and
  461. hasattr(x.base, "is_physical_constant")), binary=True)
  462. prefixes, units = sift(units, lambda x: hasattr(x, "_scale_factor"), binary=True)
  463. return convert_args(nonunits + prefixes + units)
  464. def convert_args(args) -> str:
  465. _tex = last_term_tex = ""
  466. for i, term in enumerate(args):
  467. term_tex = self._print(term)
  468. if not (hasattr(term, "_scale_factor") or hasattr(term, "is_physical_constant")):
  469. if self._needs_mul_brackets(term, first=(i == 0),
  470. last=(i == len(args) - 1)):
  471. term_tex = r"\left(%s\right)" % term_tex
  472. if _between_two_numbers_p[0].search(last_term_tex) and \
  473. _between_two_numbers_p[1].match(str(term)):
  474. # between two numbers
  475. _tex += numbersep
  476. elif _tex:
  477. _tex += separator
  478. elif _tex:
  479. _tex += separator
  480. _tex += term_tex
  481. last_term_tex = term_tex
  482. return _tex
  483. # Check for unevaluated Mul. In this case we need to make sure the
  484. # identities are visible, multiple Rational factors are not combined
  485. # etc so we display in a straight-forward form that fully preserves all
  486. # args and their order.
  487. # XXX: _print_Pow calls this routine with instances of Pow...
  488. if isinstance(expr, Mul):
  489. args = expr.args
  490. if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]):
  491. return convert_args(args)
  492. include_parens = False
  493. if expr.could_extract_minus_sign():
  494. expr = -expr
  495. tex = "- "
  496. if expr.is_Add:
  497. tex += "("
  498. include_parens = True
  499. else:
  500. tex = ""
  501. numer, denom = fraction(expr, exact=True)
  502. if denom is S.One and Pow(1, -1, evaluate=False) not in expr.args:
  503. # use the original expression here, since fraction() may have
  504. # altered it when producing numer and denom
  505. tex += convert(expr)
  506. else:
  507. snumer = convert(numer)
  508. sdenom = convert(denom)
  509. ldenom = len(sdenom.split())
  510. ratio = self._settings['long_frac_ratio']
  511. if self._settings['fold_short_frac'] and ldenom <= 2 and \
  512. "^" not in sdenom:
  513. # handle short fractions
  514. if self._needs_mul_brackets(numer, last=False):
  515. tex += r"\left(%s\right) / %s" % (snumer, sdenom)
  516. else:
  517. tex += r"%s / %s" % (snumer, sdenom)
  518. elif ratio is not None and \
  519. len(snumer.split()) > ratio*ldenom:
  520. # handle long fractions
  521. if self._needs_mul_brackets(numer, last=True):
  522. tex += r"\frac{1}{%s}%s\left(%s\right)" \
  523. % (sdenom, separator, snumer)
  524. elif numer.is_Mul:
  525. # split a long numerator
  526. a = S.One
  527. b = S.One
  528. for x in numer.args:
  529. if self._needs_mul_brackets(x, last=False) or \
  530. len(convert(a*x).split()) > ratio*ldenom or \
  531. (b.is_commutative is x.is_commutative is False):
  532. b *= x
  533. else:
  534. a *= x
  535. if self._needs_mul_brackets(b, last=True):
  536. tex += r"\frac{%s}{%s}%s\left(%s\right)" \
  537. % (convert(a), sdenom, separator, convert(b))
  538. else:
  539. tex += r"\frac{%s}{%s}%s%s" \
  540. % (convert(a), sdenom, separator, convert(b))
  541. else:
  542. tex += r"\frac{1}{%s}%s%s" % (sdenom, separator, snumer)
  543. else:
  544. tex += r"\frac{%s}{%s}" % (snumer, sdenom)
  545. if include_parens:
  546. tex += ")"
  547. return tex
  548. def _print_AlgebraicNumber(self, expr):
  549. if expr.is_aliased:
  550. return self._print(expr.as_poly().as_expr())
  551. else:
  552. return self._print(expr.as_expr())
  553. def _print_PrimeIdeal(self, expr):
  554. p = self._print(expr.p)
  555. if expr.is_inert:
  556. return rf'\left({p}\right)'
  557. alpha = self._print(expr.alpha.as_expr())
  558. return rf'\left({p}, {alpha}\right)'
  559. def _print_Pow(self, expr: Pow):
  560. # Treat x**Rational(1,n) as special case
  561. if expr.exp.is_Rational:
  562. p: int = expr.exp.p # type: ignore
  563. q: int = expr.exp.q # type: ignore
  564. if abs(p) == 1 and q != 1 and self._settings['root_notation']:
  565. base = self._print(expr.base)
  566. if q == 2:
  567. tex = r"\sqrt{%s}" % base
  568. elif self._settings['itex']:
  569. tex = r"\root{%d}{%s}" % (q, base)
  570. else:
  571. tex = r"\sqrt[%d]{%s}" % (q, base)
  572. if expr.exp.is_negative:
  573. return r"\frac{1}{%s}" % tex
  574. else:
  575. return tex
  576. elif self._settings['fold_frac_powers'] and q != 1:
  577. base = self.parenthesize(expr.base, PRECEDENCE['Pow'])
  578. # issue #12886: add parentheses for superscripts raised to powers
  579. if expr.base.is_Symbol:
  580. base = self.parenthesize_super(base)
  581. if expr.base.is_Function:
  582. return self._print(expr.base, exp="%s/%s" % (p, q))
  583. return r"%s^{%s/%s}" % (base, p, q)
  584. elif expr.exp.is_negative and expr.base.is_commutative:
  585. # special case for 1^(-x), issue 9216
  586. if expr.base == 1:
  587. return r"%s^{%s}" % (expr.base, expr.exp)
  588. # special case for (1/x)^(-y) and (-1/-x)^(-y), issue 20252
  589. if expr.base.is_Rational:
  590. base_p: int = expr.base.p # type: ignore
  591. base_q: int = expr.base.q # type: ignore
  592. if base_p * base_q == abs(base_q):
  593. if expr.exp == -1:
  594. return r"\frac{1}{\frac{%s}{%s}}" % (base_p, base_q)
  595. else:
  596. return r"\frac{1}{(\frac{%s}{%s})^{%s}}" % (base_p, base_q, abs(expr.exp))
  597. # things like 1/x
  598. return self._print_Mul(expr)
  599. if expr.base.is_Function:
  600. return self._print(expr.base, exp=self._print(expr.exp))
  601. tex = r"%s^{%s}"
  602. return self._helper_print_standard_power(expr, tex)
  603. def _helper_print_standard_power(self, expr, template: str) -> str:
  604. exp = self._print(expr.exp)
  605. # issue #12886: add parentheses around superscripts raised
  606. # to powers
  607. base = self.parenthesize(expr.base, PRECEDENCE['Pow'])
  608. if expr.base.is_Symbol:
  609. base = self.parenthesize_super(base)
  610. elif (isinstance(expr.base, Derivative)
  611. and base.startswith(r'\left(')
  612. and re.match(r'\\left\(\\d?d?dot', base)
  613. and base.endswith(r'\right)')):
  614. # don't use parentheses around dotted derivative
  615. base = base[6: -7] # remove outermost added parens
  616. return template % (base, exp)
  617. def _print_UnevaluatedExpr(self, expr):
  618. return self._print(expr.args[0])
  619. def _print_Sum(self, expr):
  620. if len(expr.limits) == 1:
  621. tex = r"\sum_{%s=%s}^{%s} " % \
  622. tuple([self._print(i) for i in expr.limits[0]])
  623. else:
  624. def _format_ineq(l):
  625. return r"%s \leq %s \leq %s" % \
  626. tuple([self._print(s) for s in (l[1], l[0], l[2])])
  627. tex = r"\sum_{\substack{%s}} " % \
  628. str.join('\\\\', [_format_ineq(l) for l in expr.limits])
  629. if isinstance(expr.function, Add):
  630. tex += r"\left(%s\right)" % self._print(expr.function)
  631. else:
  632. tex += self._print(expr.function)
  633. return tex
  634. def _print_Product(self, expr):
  635. if len(expr.limits) == 1:
  636. tex = r"\prod_{%s=%s}^{%s} " % \
  637. tuple([self._print(i) for i in expr.limits[0]])
  638. else:
  639. def _format_ineq(l):
  640. return r"%s \leq %s \leq %s" % \
  641. tuple([self._print(s) for s in (l[1], l[0], l[2])])
  642. tex = r"\prod_{\substack{%s}} " % \
  643. str.join('\\\\', [_format_ineq(l) for l in expr.limits])
  644. if isinstance(expr.function, Add):
  645. tex += r"\left(%s\right)" % self._print(expr.function)
  646. else:
  647. tex += self._print(expr.function)
  648. return tex
  649. def _print_BasisDependent(self, expr: 'BasisDependent'):
  650. from sympy.vector import Vector
  651. o1: list[str] = []
  652. if expr == expr.zero:
  653. return expr.zero._latex_form
  654. if isinstance(expr, Vector):
  655. items = expr.separate().items()
  656. else:
  657. items = [(0, expr)]
  658. for system, vect in items:
  659. inneritems = list(vect.components.items())
  660. inneritems.sort(key=lambda x: x[0].__str__())
  661. for k, v in inneritems:
  662. if v == 1:
  663. o1.append(' + ' + k._latex_form)
  664. elif v == -1:
  665. o1.append(' - ' + k._latex_form)
  666. else:
  667. arg_str = r'\left(' + self._print(v) + r'\right)'
  668. o1.append(' + ' + arg_str + k._latex_form)
  669. outstr = (''.join(o1))
  670. if outstr[1] != '-':
  671. outstr = outstr[3:]
  672. else:
  673. outstr = outstr[1:]
  674. return outstr
  675. def _print_Indexed(self, expr):
  676. tex_base = self._print(expr.base)
  677. tex = '{'+tex_base+'}'+'_{%s}' % ','.join(
  678. map(self._print, expr.indices))
  679. return tex
  680. def _print_IndexedBase(self, expr):
  681. return self._print(expr.label)
  682. def _print_Idx(self, expr):
  683. label = self._print(expr.label)
  684. if expr.upper is not None:
  685. upper = self._print(expr.upper)
  686. if expr.lower is not None:
  687. lower = self._print(expr.lower)
  688. else:
  689. lower = self._print(S.Zero)
  690. interval = '{lower}\\mathrel{{..}}\\nobreak {upper}'.format(
  691. lower = lower, upper = upper)
  692. return '{{{label}}}_{{{interval}}}'.format(
  693. label = label, interval = interval)
  694. #if no bounds are defined this just prints the label
  695. return label
  696. def _print_Derivative(self, expr):
  697. if requires_partial(expr.expr):
  698. diff_symbol = r'\partial'
  699. else:
  700. diff_symbol = self._settings["diff_operator_latex"]
  701. tex = ""
  702. dim = 0
  703. for x, num in reversed(expr.variable_count):
  704. dim += num
  705. if num == 1:
  706. tex += r"%s %s" % (diff_symbol, self._print(x))
  707. else:
  708. tex += r"%s %s^{%s}" % (diff_symbol,
  709. self.parenthesize_super(self._print(x)),
  710. self._print(num))
  711. if dim == 1:
  712. tex = r"\frac{%s}{%s}" % (diff_symbol, tex)
  713. else:
  714. tex = r"\frac{%s^{%s}}{%s}" % (diff_symbol, self._print(dim), tex)
  715. if any(i.could_extract_minus_sign() for i in expr.args):
  716. return r"%s %s" % (tex, self.parenthesize(expr.expr,
  717. PRECEDENCE["Mul"],
  718. is_neg=True,
  719. strict=True))
  720. return r"%s %s" % (tex, self.parenthesize(expr.expr,
  721. PRECEDENCE["Mul"],
  722. is_neg=False,
  723. strict=True))
  724. def _print_Subs(self, subs):
  725. expr, old, new = subs.args
  726. latex_expr = self._print(expr)
  727. latex_old = (self._print(e) for e in old)
  728. latex_new = (self._print(e) for e in new)
  729. latex_subs = r'\\ '.join(
  730. e[0] + '=' + e[1] for e in zip(latex_old, latex_new))
  731. return r'\left. %s \right|_{\substack{ %s }}' % (latex_expr,
  732. latex_subs)
  733. def _print_Integral(self, expr):
  734. tex, symbols = "", []
  735. diff_symbol = self._settings["diff_operator_latex"]
  736. # Only up to \iiiint exists
  737. if len(expr.limits) <= 4 and all(len(lim) == 1 for lim in expr.limits):
  738. # Use len(expr.limits)-1 so that syntax highlighters don't think
  739. # \" is an escaped quote
  740. tex = r"\i" + "i"*(len(expr.limits) - 1) + "nt"
  741. symbols = [r"\, %s%s" % (diff_symbol, self._print(symbol[0]))
  742. for symbol in expr.limits]
  743. else:
  744. for lim in reversed(expr.limits):
  745. symbol = lim[0]
  746. tex += r"\int"
  747. if len(lim) > 1:
  748. if self._settings['mode'] != 'inline' \
  749. and not self._settings['itex']:
  750. tex += r"\limits"
  751. if len(lim) == 3:
  752. tex += "_{%s}^{%s}" % (self._print(lim[1]),
  753. self._print(lim[2]))
  754. if len(lim) == 2:
  755. tex += "^{%s}" % (self._print(lim[1]))
  756. symbols.insert(0, r"\, %s%s" % (diff_symbol, self._print(symbol)))
  757. return r"%s %s%s" % (tex, self.parenthesize(expr.function,
  758. PRECEDENCE["Mul"],
  759. is_neg=any(i.could_extract_minus_sign() for i in expr.args),
  760. strict=True),
  761. "".join(symbols))
  762. def _print_Limit(self, expr):
  763. e, z, z0, dir = expr.args
  764. tex = r"\lim_{%s \to " % self._print(z)
  765. if str(dir) == '+-' or z0 in (S.Infinity, S.NegativeInfinity):
  766. tex += r"%s}" % self._print(z0)
  767. else:
  768. tex += r"%s^%s}" % (self._print(z0), self._print(dir))
  769. if isinstance(e, AssocOp):
  770. return r"%s\left(%s\right)" % (tex, self._print(e))
  771. else:
  772. return r"%s %s" % (tex, self._print(e))
  773. def _hprint_Function(self, func: str) -> str:
  774. r'''
  775. Logic to decide how to render a function to latex
  776. - if it is a recognized latex name, use the appropriate latex command
  777. - if it is a single letter, excluding sub- and superscripts, just use that letter
  778. - if it is a longer name, then put \operatorname{} around it and be
  779. mindful of undercores in the name
  780. '''
  781. func = self._deal_with_super_sub(func)
  782. superscriptidx = func.find("^")
  783. subscriptidx = func.find("_")
  784. if func in accepted_latex_functions:
  785. name = r"\%s" % func
  786. elif len(func) == 1 or func.startswith('\\') or subscriptidx == 1 or superscriptidx == 1:
  787. name = func
  788. else:
  789. if superscriptidx > 0 and subscriptidx > 0:
  790. name = r"\operatorname{%s}%s" %(
  791. func[:min(subscriptidx,superscriptidx)],
  792. func[min(subscriptidx,superscriptidx):])
  793. elif superscriptidx > 0:
  794. name = r"\operatorname{%s}%s" %(
  795. func[:superscriptidx],
  796. func[superscriptidx:])
  797. elif subscriptidx > 0:
  798. name = r"\operatorname{%s}%s" %(
  799. func[:subscriptidx],
  800. func[subscriptidx:])
  801. else:
  802. name = r"\operatorname{%s}" % func
  803. return name
  804. def _print_Function(self, expr: Function, exp=None) -> str:
  805. r'''
  806. Render functions to LaTeX, handling functions that LaTeX knows about
  807. e.g., sin, cos, ... by using the proper LaTeX command (\sin, \cos, ...).
  808. For single-letter function names, render them as regular LaTeX math
  809. symbols. For multi-letter function names that LaTeX does not know
  810. about, (e.g., Li, sech) use \operatorname{} so that the function name
  811. is rendered in Roman font and LaTeX handles spacing properly.
  812. expr is the expression involving the function
  813. exp is an exponent
  814. '''
  815. func = expr.func.__name__
  816. if hasattr(self, '_print_' + func) and \
  817. not isinstance(expr, AppliedUndef):
  818. return getattr(self, '_print_' + func)(expr, exp)
  819. else:
  820. args = [str(self._print(arg)) for arg in expr.args]
  821. # How inverse trig functions should be displayed, formats are:
  822. # abbreviated: asin, full: arcsin, power: sin^-1
  823. inv_trig_style = self._settings['inv_trig_style']
  824. # If we are dealing with a power-style inverse trig function
  825. inv_trig_power_case = False
  826. # If it is applicable to fold the argument brackets
  827. can_fold_brackets = self._settings['fold_func_brackets'] and \
  828. len(args) == 1 and \
  829. not self._needs_function_brackets(expr.args[0])
  830. inv_trig_table = [
  831. "asin", "acos", "atan",
  832. "acsc", "asec", "acot",
  833. "asinh", "acosh", "atanh",
  834. "acsch", "asech", "acoth",
  835. ]
  836. # If the function is an inverse trig function, handle the style
  837. if func in inv_trig_table:
  838. if inv_trig_style == "abbreviated":
  839. pass
  840. elif inv_trig_style == "full":
  841. func = ("ar" if func[-1] == "h" else "arc") + func[1:]
  842. elif inv_trig_style == "power":
  843. func = func[1:]
  844. inv_trig_power_case = True
  845. # Can never fold brackets if we're raised to a power
  846. if exp is not None:
  847. can_fold_brackets = False
  848. if inv_trig_power_case:
  849. if func in accepted_latex_functions:
  850. name = r"\%s^{-1}" % func
  851. else:
  852. name = r"\operatorname{%s}^{-1}" % func
  853. elif exp is not None:
  854. func_tex = self._hprint_Function(func)
  855. func_tex = self.parenthesize_super(func_tex)
  856. name = r'%s^{%s}' % (func_tex, exp)
  857. else:
  858. name = self._hprint_Function(func)
  859. if can_fold_brackets:
  860. if func in accepted_latex_functions:
  861. # Wrap argument safely to avoid parse-time conflicts
  862. # with the function name itself
  863. name += r" {%s}"
  864. else:
  865. name += r"%s"
  866. else:
  867. name += r"{\left(%s \right)}"
  868. if inv_trig_power_case and exp is not None:
  869. name += r"^{%s}" % exp
  870. return name % ",".join(args)
  871. def _print_UndefinedFunction(self, expr):
  872. return self._hprint_Function(str(expr))
  873. def _print_ElementwiseApplyFunction(self, expr):
  874. return r"{%s}_{\circ}\left({%s}\right)" % (
  875. self._print(expr.function),
  876. self._print(expr.expr),
  877. )
  878. @property
  879. def _special_function_classes(self):
  880. from sympy.functions.special.tensor_functions import KroneckerDelta
  881. from sympy.functions.special.gamma_functions import gamma, lowergamma
  882. from sympy.functions.special.beta_functions import beta
  883. from sympy.functions.special.delta_functions import DiracDelta
  884. from sympy.functions.special.error_functions import Chi
  885. return {KroneckerDelta: r'\delta',
  886. gamma: r'\Gamma',
  887. lowergamma: r'\gamma',
  888. beta: r'\operatorname{B}',
  889. DiracDelta: r'\delta',
  890. Chi: r'\operatorname{Chi}'}
  891. def _print_FunctionClass(self, expr):
  892. for cls in self._special_function_classes:
  893. if issubclass(expr, cls) and expr.__name__ == cls.__name__:
  894. return self._special_function_classes[cls]
  895. return self._hprint_Function(str(expr))
  896. def _print_Lambda(self, expr):
  897. symbols, expr = expr.args
  898. if len(symbols) == 1:
  899. symbols = self._print(symbols[0])
  900. else:
  901. symbols = self._print(tuple(symbols))
  902. tex = r"\left( %s \mapsto %s \right)" % (symbols, self._print(expr))
  903. return tex
  904. def _print_IdentityFunction(self, expr):
  905. return r"\left( x \mapsto x \right)"
  906. def _hprint_variadic_function(self, expr, exp=None) -> str:
  907. args = sorted(expr.args, key=default_sort_key)
  908. texargs = [r"%s" % self._print(symbol) for symbol in args]
  909. tex = r"\%s\left(%s\right)" % (str(expr.func).lower(),
  910. ", ".join(texargs))
  911. if exp is not None:
  912. return r"%s^{%s}" % (tex, exp)
  913. else:
  914. return tex
  915. _print_Min = _print_Max = _hprint_variadic_function
  916. def _print_floor(self, expr, exp=None):
  917. tex = r"\left\lfloor{%s}\right\rfloor" % self._print(expr.args[0])
  918. if exp is not None:
  919. return r"%s^{%s}" % (tex, exp)
  920. else:
  921. return tex
  922. def _print_ceiling(self, expr, exp=None):
  923. tex = r"\left\lceil{%s}\right\rceil" % self._print(expr.args[0])
  924. if exp is not None:
  925. return r"%s^{%s}" % (tex, exp)
  926. else:
  927. return tex
  928. def _print_log(self, expr, exp=None):
  929. if not self._settings["ln_notation"]:
  930. tex = r"\log{\left(%s \right)}" % self._print(expr.args[0])
  931. else:
  932. tex = r"\ln{\left(%s \right)}" % self._print(expr.args[0])
  933. if exp is not None:
  934. return r"%s^{%s}" % (tex, exp)
  935. else:
  936. return tex
  937. def _print_Abs(self, expr, exp=None):
  938. tex = r"\left|{%s}\right|" % self._print(expr.args[0])
  939. if exp is not None:
  940. return r"%s^{%s}" % (tex, exp)
  941. else:
  942. return tex
  943. def _print_re(self, expr, exp=None):
  944. if self._settings['gothic_re_im']:
  945. tex = r"\Re{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom'])
  946. else:
  947. tex = r"\operatorname{{re}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom']))
  948. return self._do_exponent(tex, exp)
  949. def _print_im(self, expr, exp=None):
  950. if self._settings['gothic_re_im']:
  951. tex = r"\Im{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom'])
  952. else:
  953. tex = r"\operatorname{{im}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom']))
  954. return self._do_exponent(tex, exp)
  955. def _print_Not(self, e):
  956. from sympy.logic.boolalg import (Equivalent, Implies)
  957. if isinstance(e.args[0], Equivalent):
  958. return self._print_Equivalent(e.args[0], r"\not\Leftrightarrow")
  959. if isinstance(e.args[0], Implies):
  960. return self._print_Implies(e.args[0], r"\not\Rightarrow")
  961. if (e.args[0].is_Boolean):
  962. return r"\neg \left(%s\right)" % self._print(e.args[0])
  963. else:
  964. return r"\neg %s" % self._print(e.args[0])
  965. def _print_LogOp(self, args, char):
  966. arg = args[0]
  967. if arg.is_Boolean and not arg.is_Not:
  968. tex = r"\left(%s\right)" % self._print(arg)
  969. else:
  970. tex = r"%s" % self._print(arg)
  971. for arg in args[1:]:
  972. if arg.is_Boolean and not arg.is_Not:
  973. tex += r" %s \left(%s\right)" % (char, self._print(arg))
  974. else:
  975. tex += r" %s %s" % (char, self._print(arg))
  976. return tex
  977. def _print_And(self, e):
  978. args = sorted(e.args, key=default_sort_key)
  979. return self._print_LogOp(args, r"\wedge")
  980. def _print_Or(self, e):
  981. args = sorted(e.args, key=default_sort_key)
  982. return self._print_LogOp(args, r"\vee")
  983. def _print_Xor(self, e):
  984. args = sorted(e.args, key=default_sort_key)
  985. return self._print_LogOp(args, r"\veebar")
  986. def _print_Implies(self, e, altchar=None):
  987. return self._print_LogOp(e.args, altchar or r"\Rightarrow")
  988. def _print_Equivalent(self, e, altchar=None):
  989. args = sorted(e.args, key=default_sort_key)
  990. return self._print_LogOp(args, altchar or r"\Leftrightarrow")
  991. def _print_conjugate(self, expr, exp=None):
  992. tex = r"\overline{%s}" % self._print(expr.args[0])
  993. if exp is not None:
  994. return r"%s^{%s}" % (tex, exp)
  995. else:
  996. return tex
  997. def _print_polar_lift(self, expr, exp=None):
  998. func = r"\operatorname{polar\_lift}"
  999. arg = r"{\left(%s \right)}" % self._print(expr.args[0])
  1000. if exp is not None:
  1001. return r"%s^{%s}%s" % (func, exp, arg)
  1002. else:
  1003. return r"%s%s" % (func, arg)
  1004. def _print_ExpBase(self, expr, exp=None):
  1005. # TODO should exp_polar be printed differently?
  1006. # what about exp_polar(0), exp_polar(1)?
  1007. tex = r"e^{%s}" % self._print(expr.args[0])
  1008. return self._do_exponent(tex, exp)
  1009. def _print_Exp1(self, expr, exp=None):
  1010. return "e"
  1011. def _print_elliptic_k(self, expr, exp=None):
  1012. tex = r"\left(%s\right)" % self._print(expr.args[0])
  1013. if exp is not None:
  1014. return r"K^{%s}%s" % (exp, tex)
  1015. else:
  1016. return r"K%s" % tex
  1017. def _print_elliptic_f(self, expr, exp=None):
  1018. tex = r"\left(%s\middle| %s\right)" % \
  1019. (self._print(expr.args[0]), self._print(expr.args[1]))
  1020. if exp is not None:
  1021. return r"F^{%s}%s" % (exp, tex)
  1022. else:
  1023. return r"F%s" % tex
  1024. def _print_elliptic_e(self, expr, exp=None):
  1025. if len(expr.args) == 2:
  1026. tex = r"\left(%s\middle| %s\right)" % \
  1027. (self._print(expr.args[0]), self._print(expr.args[1]))
  1028. else:
  1029. tex = r"\left(%s\right)" % self._print(expr.args[0])
  1030. if exp is not None:
  1031. return r"E^{%s}%s" % (exp, tex)
  1032. else:
  1033. return r"E%s" % tex
  1034. def _print_elliptic_pi(self, expr, exp=None):
  1035. if len(expr.args) == 3:
  1036. tex = r"\left(%s; %s\middle| %s\right)" % \
  1037. (self._print(expr.args[0]), self._print(expr.args[1]),
  1038. self._print(expr.args[2]))
  1039. else:
  1040. tex = r"\left(%s\middle| %s\right)" % \
  1041. (self._print(expr.args[0]), self._print(expr.args[1]))
  1042. if exp is not None:
  1043. return r"\Pi^{%s}%s" % (exp, tex)
  1044. else:
  1045. return r"\Pi%s" % tex
  1046. def _print_beta(self, expr, exp=None):
  1047. x = expr.args[0]
  1048. # Deal with unevaluated single argument beta
  1049. y = expr.args[0] if len(expr.args) == 1 else expr.args[1]
  1050. tex = rf"\left({x}, {y}\right)"
  1051. if exp is not None:
  1052. return r"\operatorname{B}^{%s}%s" % (exp, tex)
  1053. else:
  1054. return r"\operatorname{B}%s" % tex
  1055. def _print_betainc(self, expr, exp=None, operator='B'):
  1056. largs = [self._print(arg) for arg in expr.args]
  1057. tex = r"\left(%s, %s\right)" % (largs[0], largs[1])
  1058. if exp is not None:
  1059. return r"\operatorname{%s}_{(%s, %s)}^{%s}%s" % (operator, largs[2], largs[3], exp, tex)
  1060. else:
  1061. return r"\operatorname{%s}_{(%s, %s)}%s" % (operator, largs[2], largs[3], tex)
  1062. def _print_betainc_regularized(self, expr, exp=None):
  1063. return self._print_betainc(expr, exp, operator='I')
  1064. def _print_uppergamma(self, expr, exp=None):
  1065. tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]),
  1066. self._print(expr.args[1]))
  1067. if exp is not None:
  1068. return r"\Gamma^{%s}%s" % (exp, tex)
  1069. else:
  1070. return r"\Gamma%s" % tex
  1071. def _print_lowergamma(self, expr, exp=None):
  1072. tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]),
  1073. self._print(expr.args[1]))
  1074. if exp is not None:
  1075. return r"\gamma^{%s}%s" % (exp, tex)
  1076. else:
  1077. return r"\gamma%s" % tex
  1078. def _hprint_one_arg_func(self, expr, exp=None) -> str:
  1079. tex = r"\left(%s\right)" % self._print(expr.args[0])
  1080. if exp is not None:
  1081. return r"%s^{%s}%s" % (self._print(expr.func), exp, tex)
  1082. else:
  1083. return r"%s%s" % (self._print(expr.func), tex)
  1084. _print_gamma = _hprint_one_arg_func
  1085. def _print_Chi(self, expr, exp=None):
  1086. tex = r"\left(%s\right)" % self._print(expr.args[0])
  1087. if exp is not None:
  1088. return r"\operatorname{Chi}^{%s}%s" % (exp, tex)
  1089. else:
  1090. return r"\operatorname{Chi}%s" % tex
  1091. def _print_expint(self, expr, exp=None):
  1092. tex = r"\left(%s\right)" % self._print(expr.args[1])
  1093. nu = self._print(expr.args[0])
  1094. if exp is not None:
  1095. return r"\operatorname{E}_{%s}^{%s}%s" % (nu, exp, tex)
  1096. else:
  1097. return r"\operatorname{E}_{%s}%s" % (nu, tex)
  1098. def _print_fresnels(self, expr, exp=None):
  1099. tex = r"\left(%s\right)" % self._print(expr.args[0])
  1100. if exp is not None:
  1101. return r"S^{%s}%s" % (exp, tex)
  1102. else:
  1103. return r"S%s" % tex
  1104. def _print_fresnelc(self, expr, exp=None):
  1105. tex = r"\left(%s\right)" % self._print(expr.args[0])
  1106. if exp is not None:
  1107. return r"C^{%s}%s" % (exp, tex)
  1108. else:
  1109. return r"C%s" % tex
  1110. def _print_subfactorial(self, expr, exp=None):
  1111. tex = r"!%s" % self.parenthesize(expr.args[0], PRECEDENCE["Func"])
  1112. if exp is not None:
  1113. return r"\left(%s\right)^{%s}" % (tex, exp)
  1114. else:
  1115. return tex
  1116. def _print_factorial(self, expr, exp=None):
  1117. tex = r"%s!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"])
  1118. if exp is not None:
  1119. return r"%s^{%s}" % (tex, exp)
  1120. else:
  1121. return tex
  1122. def _print_factorial2(self, expr, exp=None):
  1123. tex = r"%s!!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"])
  1124. if exp is not None:
  1125. return r"%s^{%s}" % (tex, exp)
  1126. else:
  1127. return tex
  1128. def _print_binomial(self, expr, exp=None):
  1129. tex = r"{\binom{%s}{%s}}" % (self._print(expr.args[0]),
  1130. self._print(expr.args[1]))
  1131. if exp is not None:
  1132. return r"%s^{%s}" % (tex, exp)
  1133. else:
  1134. return tex
  1135. def _print_RisingFactorial(self, expr, exp=None):
  1136. n, k = expr.args
  1137. base = r"%s" % self.parenthesize(n, PRECEDENCE['Func'])
  1138. tex = r"{%s}^{\left(%s\right)}" % (base, self._print(k))
  1139. return self._do_exponent(tex, exp)
  1140. def _print_FallingFactorial(self, expr, exp=None):
  1141. n, k = expr.args
  1142. sub = r"%s" % self.parenthesize(k, PRECEDENCE['Func'])
  1143. tex = r"{\left(%s\right)}_{%s}" % (self._print(n), sub)
  1144. return self._do_exponent(tex, exp)
  1145. def _hprint_BesselBase(self, expr, exp, sym: str) -> str:
  1146. tex = r"%s" % (sym)
  1147. need_exp = False
  1148. if exp is not None:
  1149. if tex.find('^') == -1:
  1150. tex = r"%s^{%s}" % (tex, exp)
  1151. else:
  1152. need_exp = True
  1153. tex = r"%s_{%s}\left(%s\right)" % (tex, self._print(expr.order),
  1154. self._print(expr.argument))
  1155. if need_exp:
  1156. tex = self._do_exponent(tex, exp)
  1157. return tex
  1158. def _hprint_vec(self, vec) -> str:
  1159. if not vec:
  1160. return ""
  1161. s = ""
  1162. for i in vec[:-1]:
  1163. s += "%s, " % self._print(i)
  1164. s += self._print(vec[-1])
  1165. return s
  1166. def _print_besselj(self, expr, exp=None):
  1167. return self._hprint_BesselBase(expr, exp, 'J')
  1168. def _print_besseli(self, expr, exp=None):
  1169. return self._hprint_BesselBase(expr, exp, 'I')
  1170. def _print_besselk(self, expr, exp=None):
  1171. return self._hprint_BesselBase(expr, exp, 'K')
  1172. def _print_bessely(self, expr, exp=None):
  1173. return self._hprint_BesselBase(expr, exp, 'Y')
  1174. def _print_yn(self, expr, exp=None):
  1175. return self._hprint_BesselBase(expr, exp, 'y')
  1176. def _print_jn(self, expr, exp=None):
  1177. return self._hprint_BesselBase(expr, exp, 'j')
  1178. def _print_hankel1(self, expr, exp=None):
  1179. return self._hprint_BesselBase(expr, exp, 'H^{(1)}')
  1180. def _print_hankel2(self, expr, exp=None):
  1181. return self._hprint_BesselBase(expr, exp, 'H^{(2)}')
  1182. def _print_hn1(self, expr, exp=None):
  1183. return self._hprint_BesselBase(expr, exp, 'h^{(1)}')
  1184. def _print_hn2(self, expr, exp=None):
  1185. return self._hprint_BesselBase(expr, exp, 'h^{(2)}')
  1186. def _hprint_airy(self, expr, exp=None, notation="") -> str:
  1187. tex = r"\left(%s\right)" % self._print(expr.args[0])
  1188. if exp is not None:
  1189. return r"%s^{%s}%s" % (notation, exp, tex)
  1190. else:
  1191. return r"%s%s" % (notation, tex)
  1192. def _hprint_airy_prime(self, expr, exp=None, notation="") -> str:
  1193. tex = r"\left(%s\right)" % self._print(expr.args[0])
  1194. if exp is not None:
  1195. return r"{%s^\prime}^{%s}%s" % (notation, exp, tex)
  1196. else:
  1197. return r"%s^\prime%s" % (notation, tex)
  1198. def _print_airyai(self, expr, exp=None):
  1199. return self._hprint_airy(expr, exp, 'Ai')
  1200. def _print_airybi(self, expr, exp=None):
  1201. return self._hprint_airy(expr, exp, 'Bi')
  1202. def _print_airyaiprime(self, expr, exp=None):
  1203. return self._hprint_airy_prime(expr, exp, 'Ai')
  1204. def _print_airybiprime(self, expr, exp=None):
  1205. return self._hprint_airy_prime(expr, exp, 'Bi')
  1206. def _print_hyper(self, expr, exp=None):
  1207. tex = r"{{}_{%s}F_{%s}\left(\begin{matrix} %s \\ %s \end{matrix}" \
  1208. r"\middle| {%s} \right)}" % \
  1209. (self._print(len(expr.ap)), self._print(len(expr.bq)),
  1210. self._hprint_vec(expr.ap), self._hprint_vec(expr.bq),
  1211. self._print(expr.argument))
  1212. if exp is not None:
  1213. tex = r"{%s}^{%s}" % (tex, exp)
  1214. return tex
  1215. def _print_meijerg(self, expr, exp=None):
  1216. tex = r"{G_{%s, %s}^{%s, %s}\left(\begin{matrix} %s & %s \\" \
  1217. r"%s & %s \end{matrix} \middle| {%s} \right)}" % \
  1218. (self._print(len(expr.ap)), self._print(len(expr.bq)),
  1219. self._print(len(expr.bm)), self._print(len(expr.an)),
  1220. self._hprint_vec(expr.an), self._hprint_vec(expr.aother),
  1221. self._hprint_vec(expr.bm), self._hprint_vec(expr.bother),
  1222. self._print(expr.argument))
  1223. if exp is not None:
  1224. tex = r"{%s}^{%s}" % (tex, exp)
  1225. return tex
  1226. def _print_dirichlet_eta(self, expr, exp=None):
  1227. tex = r"\left(%s\right)" % self._print(expr.args[0])
  1228. if exp is not None:
  1229. return r"\eta^{%s}%s" % (exp, tex)
  1230. return r"\eta%s" % tex
  1231. def _print_zeta(self, expr, exp=None):
  1232. if len(expr.args) == 2:
  1233. tex = r"\left(%s, %s\right)" % tuple(map(self._print, expr.args))
  1234. else:
  1235. tex = r"\left(%s\right)" % self._print(expr.args[0])
  1236. if exp is not None:
  1237. return r"\zeta^{%s}%s" % (exp, tex)
  1238. return r"\zeta%s" % tex
  1239. def _print_stieltjes(self, expr, exp=None):
  1240. if len(expr.args) == 2:
  1241. tex = r"_{%s}\left(%s\right)" % tuple(map(self._print, expr.args))
  1242. else:
  1243. tex = r"_{%s}" % self._print(expr.args[0])
  1244. if exp is not None:
  1245. return r"\gamma%s^{%s}" % (tex, exp)
  1246. return r"\gamma%s" % tex
  1247. def _print_lerchphi(self, expr, exp=None):
  1248. tex = r"\left(%s, %s, %s\right)" % tuple(map(self._print, expr.args))
  1249. if exp is None:
  1250. return r"\Phi%s" % tex
  1251. return r"\Phi^{%s}%s" % (exp, tex)
  1252. def _print_polylog(self, expr, exp=None):
  1253. s, z = map(self._print, expr.args)
  1254. tex = r"\left(%s\right)" % z
  1255. if exp is None:
  1256. return r"\operatorname{Li}_{%s}%s" % (s, tex)
  1257. return r"\operatorname{Li}_{%s}^{%s}%s" % (s, exp, tex)
  1258. def _print_jacobi(self, expr, exp=None):
  1259. n, a, b, x = map(self._print, expr.args)
  1260. tex = r"P_{%s}^{\left(%s,%s\right)}\left(%s\right)" % (n, a, b, x)
  1261. if exp is not None:
  1262. tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
  1263. return tex
  1264. def _print_gegenbauer(self, expr, exp=None):
  1265. n, a, x = map(self._print, expr.args)
  1266. tex = r"C_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)
  1267. if exp is not None:
  1268. tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
  1269. return tex
  1270. def _print_chebyshevt(self, expr, exp=None):
  1271. n, x = map(self._print, expr.args)
  1272. tex = r"T_{%s}\left(%s\right)" % (n, x)
  1273. if exp is not None:
  1274. tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
  1275. return tex
  1276. def _print_chebyshevu(self, expr, exp=None):
  1277. n, x = map(self._print, expr.args)
  1278. tex = r"U_{%s}\left(%s\right)" % (n, x)
  1279. if exp is not None:
  1280. tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
  1281. return tex
  1282. def _print_legendre(self, expr, exp=None):
  1283. n, x = map(self._print, expr.args)
  1284. tex = r"P_{%s}\left(%s\right)" % (n, x)
  1285. if exp is not None:
  1286. tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
  1287. return tex
  1288. def _print_assoc_legendre(self, expr, exp=None):
  1289. n, a, x = map(self._print, expr.args)
  1290. tex = r"P_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)
  1291. if exp is not None:
  1292. tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
  1293. return tex
  1294. def _print_hermite(self, expr, exp=None):
  1295. n, x = map(self._print, expr.args)
  1296. tex = r"H_{%s}\left(%s\right)" % (n, x)
  1297. if exp is not None:
  1298. tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
  1299. return tex
  1300. def _print_laguerre(self, expr, exp=None):
  1301. n, x = map(self._print, expr.args)
  1302. tex = r"L_{%s}\left(%s\right)" % (n, x)
  1303. if exp is not None:
  1304. tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
  1305. return tex
  1306. def _print_assoc_laguerre(self, expr, exp=None):
  1307. n, a, x = map(self._print, expr.args)
  1308. tex = r"L_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x)
  1309. if exp is not None:
  1310. tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
  1311. return tex
  1312. def _print_Ynm(self, expr, exp=None):
  1313. n, m, theta, phi = map(self._print, expr.args)
  1314. tex = r"Y_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi)
  1315. if exp is not None:
  1316. tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
  1317. return tex
  1318. def _print_Znm(self, expr, exp=None):
  1319. n, m, theta, phi = map(self._print, expr.args)
  1320. tex = r"Z_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi)
  1321. if exp is not None:
  1322. tex = r"\left(" + tex + r"\right)^{%s}" % (exp)
  1323. return tex
  1324. def __print_mathieu_functions(self, character, args, prime=False, exp=None):
  1325. a, q, z = map(self._print, args)
  1326. sup = r"^{\prime}" if prime else ""
  1327. exp = "" if not exp else "^{%s}" % exp
  1328. return r"%s%s\left(%s, %s, %s\right)%s" % (character, sup, a, q, z, exp)
  1329. def _print_mathieuc(self, expr, exp=None):
  1330. return self.__print_mathieu_functions("C", expr.args, exp=exp)
  1331. def _print_mathieus(self, expr, exp=None):
  1332. return self.__print_mathieu_functions("S", expr.args, exp=exp)
  1333. def _print_mathieucprime(self, expr, exp=None):
  1334. return self.__print_mathieu_functions("C", expr.args, prime=True, exp=exp)
  1335. def _print_mathieusprime(self, expr, exp=None):
  1336. return self.__print_mathieu_functions("S", expr.args, prime=True, exp=exp)
  1337. def _print_Rational(self, expr):
  1338. if expr.q != 1:
  1339. sign = ""
  1340. p = expr.p
  1341. if expr.p < 0:
  1342. sign = "- "
  1343. p = -p
  1344. if self._settings['fold_short_frac']:
  1345. return r"%s%d / %d" % (sign, p, expr.q)
  1346. return r"%s\frac{%d}{%d}" % (sign, p, expr.q)
  1347. else:
  1348. return self._print(expr.p)
  1349. def _print_Order(self, expr):
  1350. s = self._print(expr.expr)
  1351. if expr.point and any(p != S.Zero for p in expr.point) or \
  1352. len(expr.variables) > 1:
  1353. s += '; '
  1354. if len(expr.variables) > 1:
  1355. s += self._print(expr.variables)
  1356. elif expr.variables:
  1357. s += self._print(expr.variables[0])
  1358. s += r'\rightarrow '
  1359. if len(expr.point) > 1:
  1360. s += self._print(expr.point)
  1361. else:
  1362. s += self._print(expr.point[0])
  1363. return r"O\left(%s\right)" % s
  1364. def _print_Symbol(self, expr: Symbol, style='plain'):
  1365. name: str = self._settings['symbol_names'].get(expr)
  1366. if name is not None:
  1367. return name
  1368. return self._deal_with_super_sub(expr.name, style=style)
  1369. _print_RandomSymbol = _print_Symbol
  1370. def _deal_with_super_sub(self, string: str, style='plain') -> str:
  1371. if '{' in string:
  1372. name, supers, subs = string, [], []
  1373. else:
  1374. name, supers, subs = split_super_sub(string)
  1375. name = translate(name)
  1376. supers = [translate(sup) for sup in supers]
  1377. subs = [translate(sub) for sub in subs]
  1378. # apply the style only to the name
  1379. if style == 'bold':
  1380. name = "\\mathbf{{{}}}".format(name)
  1381. # glue all items together:
  1382. if supers:
  1383. name += "^{%s}" % " ".join(supers)
  1384. if subs:
  1385. name += "_{%s}" % " ".join(subs)
  1386. return name
  1387. def _print_Relational(self, expr):
  1388. if self._settings['itex']:
  1389. gt = r"\gt"
  1390. lt = r"\lt"
  1391. else:
  1392. gt = ">"
  1393. lt = "<"
  1394. charmap = {
  1395. "==": "=",
  1396. ">": gt,
  1397. "<": lt,
  1398. ">=": r"\geq",
  1399. "<=": r"\leq",
  1400. "!=": r"\neq",
  1401. }
  1402. return "%s %s %s" % (self._print(expr.lhs),
  1403. charmap[expr.rel_op], self._print(expr.rhs))
  1404. def _print_Piecewise(self, expr):
  1405. ecpairs = [r"%s & \text{for}\: %s" % (self._print(e), self._print(c))
  1406. for e, c in expr.args[:-1]]
  1407. if expr.args[-1].cond == true:
  1408. ecpairs.append(r"%s & \text{otherwise}" %
  1409. self._print(expr.args[-1].expr))
  1410. else:
  1411. ecpairs.append(r"%s & \text{for}\: %s" %
  1412. (self._print(expr.args[-1].expr),
  1413. self._print(expr.args[-1].cond)))
  1414. tex = r"\begin{cases} %s \end{cases}"
  1415. return tex % r" \\".join(ecpairs)
  1416. def _print_matrix_contents(self, expr):
  1417. lines = []
  1418. for line in range(expr.rows): # horrible, should be 'rows'
  1419. lines.append(" & ".join([self._print(i) for i in expr[line, :]]))
  1420. mat_str = self._settings['mat_str']
  1421. if mat_str is None:
  1422. if self._settings['mode'] == 'inline':
  1423. mat_str = 'smallmatrix'
  1424. else:
  1425. if (expr.cols <= 10) is True:
  1426. mat_str = 'matrix'
  1427. else:
  1428. mat_str = 'array'
  1429. out_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}'
  1430. out_str = out_str.replace('%MATSTR%', mat_str)
  1431. if mat_str == 'array':
  1432. out_str = out_str.replace('%s', '{' + 'c'*expr.cols + '}%s')
  1433. return out_str % r"\\".join(lines)
  1434. def _print_MatrixBase(self, expr):
  1435. out_str = self._print_matrix_contents(expr)
  1436. if self._settings['mat_delim']:
  1437. left_delim = self._settings['mat_delim']
  1438. right_delim = self._delim_dict[left_delim]
  1439. out_str = r'\left' + left_delim + out_str + \
  1440. r'\right' + right_delim
  1441. return out_str
  1442. def _print_MatrixElement(self, expr):
  1443. return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True)\
  1444. + '_{%s, %s}' % (self._print(expr.i), self._print(expr.j))
  1445. def _print_MatrixSlice(self, expr):
  1446. def latexslice(x, dim):
  1447. x = list(x)
  1448. if x[2] == 1:
  1449. del x[2]
  1450. if x[0] == 0:
  1451. x[0] = None
  1452. if x[1] == dim:
  1453. x[1] = None
  1454. return ':'.join(self._print(xi) if xi is not None else '' for xi in x)
  1455. return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + r'\left[' +
  1456. latexslice(expr.rowslice, expr.parent.rows) + ', ' +
  1457. latexslice(expr.colslice, expr.parent.cols) + r'\right]')
  1458. def _print_BlockMatrix(self, expr):
  1459. return self._print(expr.blocks)
  1460. def _print_Transpose(self, expr):
  1461. mat = expr.arg
  1462. from sympy.matrices import MatrixSymbol, BlockMatrix
  1463. if (not isinstance(mat, MatrixSymbol) and
  1464. not isinstance(mat, BlockMatrix) and mat.is_MatrixExpr):
  1465. return r"\left(%s\right)^{T}" % self._print(mat)
  1466. else:
  1467. s = self.parenthesize(mat, precedence_traditional(expr), True)
  1468. if '^' in s:
  1469. return r"\left(%s\right)^{T}" % s
  1470. else:
  1471. return "%s^{T}" % s
  1472. def _print_Trace(self, expr):
  1473. mat = expr.arg
  1474. return r"\operatorname{tr}\left(%s \right)" % self._print(mat)
  1475. def _print_Adjoint(self, expr):
  1476. mat = expr.arg
  1477. from sympy.matrices import MatrixSymbol, BlockMatrix
  1478. if (not isinstance(mat, MatrixSymbol) and
  1479. not isinstance(mat, BlockMatrix) and mat.is_MatrixExpr):
  1480. return r"\left(%s\right)^{\dagger}" % self._print(mat)
  1481. else:
  1482. s = self.parenthesize(mat, precedence_traditional(expr), True)
  1483. if '^' in s:
  1484. return r"\left(%s\right)^{\dagger}" % s
  1485. else:
  1486. return r"%s^{\dagger}" % s
  1487. def _print_MatMul(self, expr):
  1488. from sympy import MatMul
  1489. # Parenthesize nested MatMul but not other types of Mul objects:
  1490. parens = lambda x: self._print(x) if isinstance(x, Mul) and not isinstance(x, MatMul) else \
  1491. self.parenthesize(x, precedence_traditional(expr), False)
  1492. args = list(expr.args)
  1493. if expr.could_extract_minus_sign():
  1494. if args[0] == -1:
  1495. args = args[1:]
  1496. else:
  1497. args[0] = -args[0]
  1498. return '- ' + ' '.join(map(parens, args))
  1499. else:
  1500. return ' '.join(map(parens, args))
  1501. def _print_Determinant(self, expr):
  1502. mat = expr.arg
  1503. if mat.is_MatrixExpr:
  1504. from sympy.matrices.expressions.blockmatrix import BlockMatrix
  1505. if isinstance(mat, BlockMatrix):
  1506. return r"\left|{%s}\right|" % self._print_matrix_contents(mat.blocks)
  1507. return r"\left|{%s}\right|" % self._print(mat)
  1508. return r"\left|{%s}\right|" % self._print_matrix_contents(mat)
  1509. def _print_Mod(self, expr, exp=None):
  1510. if exp is not None:
  1511. return r'\left(%s \bmod %s\right)^{%s}' % \
  1512. (self.parenthesize(expr.args[0], PRECEDENCE['Mul'],
  1513. strict=True),
  1514. self.parenthesize(expr.args[1], PRECEDENCE['Mul'],
  1515. strict=True),
  1516. exp)
  1517. return r'%s \bmod %s' % (self.parenthesize(expr.args[0],
  1518. PRECEDENCE['Mul'],
  1519. strict=True),
  1520. self.parenthesize(expr.args[1],
  1521. PRECEDENCE['Mul'],
  1522. strict=True))
  1523. def _print_HadamardProduct(self, expr):
  1524. args = expr.args
  1525. prec = PRECEDENCE['Pow']
  1526. parens = self.parenthesize
  1527. return r' \circ '.join(
  1528. (parens(arg, prec, strict=True) for arg in args))
  1529. def _print_HadamardPower(self, expr):
  1530. if precedence_traditional(expr.exp) < PRECEDENCE["Mul"]:
  1531. template = r"%s^{\circ \left({%s}\right)}"
  1532. else:
  1533. template = r"%s^{\circ {%s}}"
  1534. return self._helper_print_standard_power(expr, template)
  1535. def _print_KroneckerProduct(self, expr):
  1536. args = expr.args
  1537. prec = PRECEDENCE['Pow']
  1538. parens = self.parenthesize
  1539. return r' \otimes '.join(
  1540. (parens(arg, prec, strict=True) for arg in args))
  1541. def _print_MatPow(self, expr):
  1542. base, exp = expr.base, expr.exp
  1543. from sympy.matrices import MatrixSymbol
  1544. if not isinstance(base, MatrixSymbol) and base.is_MatrixExpr:
  1545. return "\\left(%s\\right)^{%s}" % (self._print(base),
  1546. self._print(exp))
  1547. else:
  1548. base_str = self._print(base)
  1549. if '^' in base_str:
  1550. return r"\left(%s\right)^{%s}" % (base_str, self._print(exp))
  1551. else:
  1552. return "%s^{%s}" % (base_str, self._print(exp))
  1553. def _print_MatrixSymbol(self, expr):
  1554. return self._print_Symbol(expr, style=self._settings[
  1555. 'mat_symbol_style'])
  1556. def _print_ZeroMatrix(self, Z):
  1557. return "0" if self._settings[
  1558. 'mat_symbol_style'] == 'plain' else r"\mathbf{0}"
  1559. def _print_OneMatrix(self, O):
  1560. return "1" if self._settings[
  1561. 'mat_symbol_style'] == 'plain' else r"\mathbf{1}"
  1562. def _print_Identity(self, I):
  1563. return r"\mathbb{I}" if self._settings[
  1564. 'mat_symbol_style'] == 'plain' else r"\mathbf{I}"
  1565. def _print_PermutationMatrix(self, P):
  1566. perm_str = self._print(P.args[0])
  1567. return "P_{%s}" % perm_str
  1568. def _print_NDimArray(self, expr: NDimArray):
  1569. if expr.rank() == 0:
  1570. return self._print(expr[()])
  1571. mat_str = self._settings['mat_str']
  1572. if mat_str is None:
  1573. if self._settings['mode'] == 'inline':
  1574. mat_str = 'smallmatrix'
  1575. else:
  1576. if (expr.rank() == 0) or (expr.shape[-1] <= 10):
  1577. mat_str = 'matrix'
  1578. else:
  1579. mat_str = 'array'
  1580. block_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}'
  1581. block_str = block_str.replace('%MATSTR%', mat_str)
  1582. if mat_str == 'array':
  1583. block_str= block_str.replace('%s','{}%s')
  1584. if self._settings['mat_delim']:
  1585. left_delim: str = self._settings['mat_delim']
  1586. right_delim = self._delim_dict[left_delim]
  1587. block_str = r'\left' + left_delim + block_str + \
  1588. r'\right' + right_delim
  1589. if expr.rank() == 0:
  1590. return block_str % ""
  1591. level_str: list[list[str]] = [[] for i in range(expr.rank() + 1)]
  1592. shape_ranges = [list(range(i)) for i in expr.shape]
  1593. for outer_i in itertools.product(*shape_ranges):
  1594. level_str[-1].append(self._print(expr[outer_i]))
  1595. even = True
  1596. for back_outer_i in range(expr.rank()-1, -1, -1):
  1597. if len(level_str[back_outer_i+1]) < expr.shape[back_outer_i]:
  1598. break
  1599. if even:
  1600. level_str[back_outer_i].append(
  1601. r" & ".join(level_str[back_outer_i+1]))
  1602. else:
  1603. level_str[back_outer_i].append(
  1604. block_str % (r"\\".join(level_str[back_outer_i+1])))
  1605. if len(level_str[back_outer_i+1]) == 1:
  1606. level_str[back_outer_i][-1] = r"\left[" + \
  1607. level_str[back_outer_i][-1] + r"\right]"
  1608. even = not even
  1609. level_str[back_outer_i+1] = []
  1610. out_str = level_str[0][0]
  1611. if expr.rank() % 2 == 1:
  1612. out_str = block_str % out_str
  1613. return out_str
  1614. def _printer_tensor_indices(self, name, indices, index_map: dict):
  1615. out_str = self._print(name)
  1616. last_valence = None
  1617. prev_map = None
  1618. for index in indices:
  1619. new_valence = index.is_up
  1620. if ((index in index_map) or prev_map) and \
  1621. last_valence == new_valence:
  1622. out_str += ","
  1623. if last_valence != new_valence:
  1624. if last_valence is not None:
  1625. out_str += "}"
  1626. if index.is_up:
  1627. out_str += "{}^{"
  1628. else:
  1629. out_str += "{}_{"
  1630. out_str += self._print(index.args[0])
  1631. if index in index_map:
  1632. out_str += "="
  1633. out_str += self._print(index_map[index])
  1634. prev_map = True
  1635. else:
  1636. prev_map = False
  1637. last_valence = new_valence
  1638. if last_valence is not None:
  1639. out_str += "}"
  1640. return out_str
  1641. def _print_Tensor(self, expr):
  1642. name = expr.args[0].args[0]
  1643. indices = expr.get_indices()
  1644. return self._printer_tensor_indices(name, indices, {})
  1645. def _print_TensorElement(self, expr):
  1646. name = expr.expr.args[0].args[0]
  1647. indices = expr.expr.get_indices()
  1648. index_map = expr.index_map
  1649. return self._printer_tensor_indices(name, indices, index_map)
  1650. def _print_TensMul(self, expr):
  1651. # prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)"
  1652. sign, args = expr._get_args_for_traditional_printer()
  1653. return sign + "".join(
  1654. [self.parenthesize(arg, precedence(expr)) for arg in args]
  1655. )
  1656. def _print_TensAdd(self, expr):
  1657. a = []
  1658. args = expr.args
  1659. for x in args:
  1660. a.append(self.parenthesize(x, precedence(expr)))
  1661. a.sort()
  1662. s = ' + '.join(a)
  1663. s = s.replace('+ -', '- ')
  1664. return s
  1665. def _print_TensorIndex(self, expr):
  1666. return "{}%s{%s}" % (
  1667. "^" if expr.is_up else "_",
  1668. self._print(expr.args[0])
  1669. )
  1670. def _print_PartialDerivative(self, expr):
  1671. if len(expr.variables) == 1:
  1672. return r"\frac{\partial}{\partial {%s}}{%s}" % (
  1673. self._print(expr.variables[0]),
  1674. self.parenthesize(expr.expr, PRECEDENCE["Mul"], False)
  1675. )
  1676. else:
  1677. return r"\frac{\partial^{%s}}{%s}{%s}" % (
  1678. len(expr.variables),
  1679. " ".join([r"\partial {%s}" % self._print(i) for i in expr.variables]),
  1680. self.parenthesize(expr.expr, PRECEDENCE["Mul"], False)
  1681. )
  1682. def _print_ArraySymbol(self, expr):
  1683. return self._print(expr.name)
  1684. def _print_ArrayElement(self, expr):
  1685. return "{{%s}_{%s}}" % (
  1686. self.parenthesize(expr.name, PRECEDENCE["Func"], True),
  1687. ", ".join([f"{self._print(i)}" for i in expr.indices]))
  1688. def _print_UniversalSet(self, expr):
  1689. return r"\mathbb{U}"
  1690. def _print_frac(self, expr, exp=None):
  1691. if exp is None:
  1692. return r"\operatorname{frac}{\left(%s\right)}" % self._print(expr.args[0])
  1693. else:
  1694. return r"\operatorname{frac}{\left(%s\right)}^{%s}" % (
  1695. self._print(expr.args[0]), exp)
  1696. def _print_tuple(self, expr):
  1697. if self._settings['decimal_separator'] == 'comma':
  1698. sep = ";"
  1699. elif self._settings['decimal_separator'] == 'period':
  1700. sep = ","
  1701. else:
  1702. raise ValueError('Unknown Decimal Separator')
  1703. if len(expr) == 1:
  1704. # 1-tuple needs a trailing separator
  1705. return self._add_parens_lspace(self._print(expr[0]) + sep)
  1706. else:
  1707. return self._add_parens_lspace(
  1708. (sep + r" \ ").join([self._print(i) for i in expr]))
  1709. def _print_TensorProduct(self, expr):
  1710. elements = [self._print(a) for a in expr.args]
  1711. return r' \otimes '.join(elements)
  1712. def _print_WedgeProduct(self, expr):
  1713. elements = [self._print(a) for a in expr.args]
  1714. return r' \wedge '.join(elements)
  1715. def _print_Tuple(self, expr):
  1716. return self._print_tuple(expr)
  1717. def _print_list(self, expr):
  1718. if self._settings['decimal_separator'] == 'comma':
  1719. return r"\left[ %s\right]" % \
  1720. r"; \ ".join([self._print(i) for i in expr])
  1721. elif self._settings['decimal_separator'] == 'period':
  1722. return r"\left[ %s\right]" % \
  1723. r", \ ".join([self._print(i) for i in expr])
  1724. else:
  1725. raise ValueError('Unknown Decimal Separator')
  1726. def _print_dict(self, d):
  1727. keys = sorted(d.keys(), key=default_sort_key)
  1728. items = []
  1729. for key in keys:
  1730. val = d[key]
  1731. items.append("%s : %s" % (self._print(key), self._print(val)))
  1732. return r"\left\{ %s\right\}" % r", \ ".join(items)
  1733. def _print_Dict(self, expr):
  1734. return self._print_dict(expr)
  1735. def _print_DiracDelta(self, expr, exp=None):
  1736. if len(expr.args) == 1 or expr.args[1] == 0:
  1737. tex = r"\delta\left(%s\right)" % self._print(expr.args[0])
  1738. else:
  1739. tex = r"\delta^{\left( %s \right)}\left( %s \right)" % (
  1740. self._print(expr.args[1]), self._print(expr.args[0]))
  1741. if exp:
  1742. tex = r"\left(%s\right)^{%s}" % (tex, exp)
  1743. return tex
  1744. def _print_SingularityFunction(self, expr, exp=None):
  1745. shift = self._print(expr.args[0] - expr.args[1])
  1746. power = self._print(expr.args[2])
  1747. tex = r"{\left\langle %s \right\rangle}^{%s}" % (shift, power)
  1748. if exp is not None:
  1749. tex = r"{\left({\langle %s \rangle}^{%s}\right)}^{%s}" % (shift, power, exp)
  1750. return tex
  1751. def _print_Heaviside(self, expr, exp=None):
  1752. pargs = ', '.join(self._print(arg) for arg in expr.pargs)
  1753. tex = r"\theta\left(%s\right)" % pargs
  1754. if exp:
  1755. tex = r"\left(%s\right)^{%s}" % (tex, exp)
  1756. return tex
  1757. def _print_KroneckerDelta(self, expr, exp=None):
  1758. i = self._print(expr.args[0])
  1759. j = self._print(expr.args[1])
  1760. if expr.args[0].is_Atom and expr.args[1].is_Atom:
  1761. tex = r'\delta_{%s %s}' % (i, j)
  1762. else:
  1763. tex = r'\delta_{%s, %s}' % (i, j)
  1764. if exp is not None:
  1765. tex = r'\left(%s\right)^{%s}' % (tex, exp)
  1766. return tex
  1767. def _print_LeviCivita(self, expr, exp=None):
  1768. indices = map(self._print, expr.args)
  1769. if all(x.is_Atom for x in expr.args):
  1770. tex = r'\varepsilon_{%s}' % " ".join(indices)
  1771. else:
  1772. tex = r'\varepsilon_{%s}' % ", ".join(indices)
  1773. if exp:
  1774. tex = r'\left(%s\right)^{%s}' % (tex, exp)
  1775. return tex
  1776. def _print_RandomDomain(self, d):
  1777. if hasattr(d, 'as_boolean'):
  1778. return '\\text{Domain: }' + self._print(d.as_boolean())
  1779. elif hasattr(d, 'set'):
  1780. return ('\\text{Domain: }' + self._print(d.symbols) + ' \\in ' +
  1781. self._print(d.set))
  1782. elif hasattr(d, 'symbols'):
  1783. return '\\text{Domain on }' + self._print(d.symbols)
  1784. else:
  1785. return self._print(None)
  1786. def _print_FiniteSet(self, s):
  1787. items = sorted(s.args, key=default_sort_key)
  1788. return self._print_set(items)
  1789. def _print_set(self, s):
  1790. items = sorted(s, key=default_sort_key)
  1791. if self._settings['decimal_separator'] == 'comma':
  1792. items = "; ".join(map(self._print, items))
  1793. elif self._settings['decimal_separator'] == 'period':
  1794. items = ", ".join(map(self._print, items))
  1795. else:
  1796. raise ValueError('Unknown Decimal Separator')
  1797. return r"\left\{%s\right\}" % items
  1798. _print_frozenset = _print_set
  1799. def _print_Range(self, s):
  1800. def _print_symbolic_range():
  1801. # Symbolic Range that cannot be resolved
  1802. if s.args[0] == 0:
  1803. if s.args[2] == 1:
  1804. cont = self._print(s.args[1])
  1805. else:
  1806. cont = ", ".join(self._print(arg) for arg in s.args)
  1807. else:
  1808. if s.args[2] == 1:
  1809. cont = ", ".join(self._print(arg) for arg in s.args[:2])
  1810. else:
  1811. cont = ", ".join(self._print(arg) for arg in s.args)
  1812. return(f"\\text{{Range}}\\left({cont}\\right)")
  1813. dots = object()
  1814. if s.start.is_infinite and s.stop.is_infinite:
  1815. if s.step.is_positive:
  1816. printset = dots, -1, 0, 1, dots
  1817. else:
  1818. printset = dots, 1, 0, -1, dots
  1819. elif s.start.is_infinite:
  1820. printset = dots, s[-1] - s.step, s[-1]
  1821. elif s.stop.is_infinite:
  1822. it = iter(s)
  1823. printset = next(it), next(it), dots
  1824. elif s.is_empty is not None:
  1825. if (s.size < 4) == True:
  1826. printset = tuple(s)
  1827. elif s.is_iterable:
  1828. it = iter(s)
  1829. printset = next(it), next(it), dots, s[-1]
  1830. else:
  1831. return _print_symbolic_range()
  1832. else:
  1833. return _print_symbolic_range()
  1834. return (r"\left\{" +
  1835. r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) +
  1836. r"\right\}")
  1837. def __print_number_polynomial(self, expr, letter, exp=None):
  1838. if len(expr.args) == 2:
  1839. if exp is not None:
  1840. return r"%s_{%s}^{%s}\left(%s\right)" % (letter,
  1841. self._print(expr.args[0]), exp,
  1842. self._print(expr.args[1]))
  1843. return r"%s_{%s}\left(%s\right)" % (letter,
  1844. self._print(expr.args[0]), self._print(expr.args[1]))
  1845. tex = r"%s_{%s}" % (letter, self._print(expr.args[0]))
  1846. if exp is not None:
  1847. tex = r"%s^{%s}" % (tex, exp)
  1848. return tex
  1849. def _print_bernoulli(self, expr, exp=None):
  1850. return self.__print_number_polynomial(expr, "B", exp)
  1851. def _print_genocchi(self, expr, exp=None):
  1852. return self.__print_number_polynomial(expr, "G", exp)
  1853. def _print_bell(self, expr, exp=None):
  1854. if len(expr.args) == 3:
  1855. tex1 = r"B_{%s, %s}" % (self._print(expr.args[0]),
  1856. self._print(expr.args[1]))
  1857. tex2 = r"\left(%s\right)" % r", ".join(self._print(el) for
  1858. el in expr.args[2])
  1859. if exp is not None:
  1860. tex = r"%s^{%s}%s" % (tex1, exp, tex2)
  1861. else:
  1862. tex = tex1 + tex2
  1863. return tex
  1864. return self.__print_number_polynomial(expr, "B", exp)
  1865. def _print_fibonacci(self, expr, exp=None):
  1866. return self.__print_number_polynomial(expr, "F", exp)
  1867. def _print_lucas(self, expr, exp=None):
  1868. tex = r"L_{%s}" % self._print(expr.args[0])
  1869. if exp is not None:
  1870. tex = r"%s^{%s}" % (tex, exp)
  1871. return tex
  1872. def _print_tribonacci(self, expr, exp=None):
  1873. return self.__print_number_polynomial(expr, "T", exp)
  1874. def _print_SeqFormula(self, s):
  1875. dots = object()
  1876. if len(s.start.free_symbols) > 0 or len(s.stop.free_symbols) > 0:
  1877. return r"\left\{%s\right\}_{%s=%s}^{%s}" % (
  1878. self._print(s.formula),
  1879. self._print(s.variables[0]),
  1880. self._print(s.start),
  1881. self._print(s.stop)
  1882. )
  1883. if s.start is S.NegativeInfinity:
  1884. stop = s.stop
  1885. printset = (dots, s.coeff(stop - 3), s.coeff(stop - 2),
  1886. s.coeff(stop - 1), s.coeff(stop))
  1887. elif s.stop is S.Infinity or s.length > 4:
  1888. printset = s[:4]
  1889. printset.append(dots)
  1890. else:
  1891. printset = tuple(s)
  1892. return (r"\left[" +
  1893. r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) +
  1894. r"\right]")
  1895. _print_SeqPer = _print_SeqFormula
  1896. _print_SeqAdd = _print_SeqFormula
  1897. _print_SeqMul = _print_SeqFormula
  1898. def _print_Interval(self, i):
  1899. if i.start == i.end:
  1900. return r"\left\{%s\right\}" % self._print(i.start)
  1901. else:
  1902. if i.left_open:
  1903. left = '('
  1904. else:
  1905. left = '['
  1906. if i.right_open:
  1907. right = ')'
  1908. else:
  1909. right = ']'
  1910. return r"\left%s%s, %s\right%s" % \
  1911. (left, self._print(i.start), self._print(i.end), right)
  1912. def _print_AccumulationBounds(self, i):
  1913. return r"\left\langle %s, %s\right\rangle" % \
  1914. (self._print(i.min), self._print(i.max))
  1915. def _print_Union(self, u):
  1916. prec = precedence_traditional(u)
  1917. args_str = [self.parenthesize(i, prec) for i in u.args]
  1918. return r" \cup ".join(args_str)
  1919. def _print_Complement(self, u):
  1920. prec = precedence_traditional(u)
  1921. args_str = [self.parenthesize(i, prec) for i in u.args]
  1922. return r" \setminus ".join(args_str)
  1923. def _print_Intersection(self, u):
  1924. prec = precedence_traditional(u)
  1925. args_str = [self.parenthesize(i, prec) for i in u.args]
  1926. return r" \cap ".join(args_str)
  1927. def _print_SymmetricDifference(self, u):
  1928. prec = precedence_traditional(u)
  1929. args_str = [self.parenthesize(i, prec) for i in u.args]
  1930. return r" \triangle ".join(args_str)
  1931. def _print_ProductSet(self, p):
  1932. prec = precedence_traditional(p)
  1933. if len(p.sets) >= 1 and not has_variety(p.sets):
  1934. return self.parenthesize(p.sets[0], prec) + "^{%d}" % len(p.sets)
  1935. return r" \times ".join(
  1936. self.parenthesize(set, prec) for set in p.sets)
  1937. def _print_EmptySet(self, e):
  1938. return r"\emptyset"
  1939. def _print_Naturals(self, n):
  1940. return r"\mathbb{N}"
  1941. def _print_Naturals0(self, n):
  1942. return r"\mathbb{N}_0"
  1943. def _print_Integers(self, i):
  1944. return r"\mathbb{Z}"
  1945. def _print_Rationals(self, i):
  1946. return r"\mathbb{Q}"
  1947. def _print_Reals(self, i):
  1948. return r"\mathbb{R}"
  1949. def _print_Complexes(self, i):
  1950. return r"\mathbb{C}"
  1951. def _print_ImageSet(self, s):
  1952. expr = s.lamda.expr
  1953. sig = s.lamda.signature
  1954. xys = ((self._print(x), self._print(y)) for x, y in zip(sig, s.base_sets))
  1955. xinys = r", ".join(r"%s \in %s" % xy for xy in xys)
  1956. return r"\left\{%s\; \middle|\; %s\right\}" % (self._print(expr), xinys)
  1957. def _print_ConditionSet(self, s):
  1958. vars_print = ', '.join([self._print(var) for var in Tuple(s.sym)])
  1959. if s.base_set is S.UniversalSet:
  1960. return r"\left\{%s\; \middle|\; %s \right\}" % \
  1961. (vars_print, self._print(s.condition))
  1962. return r"\left\{%s\; \middle|\; %s \in %s \wedge %s \right\}" % (
  1963. vars_print,
  1964. vars_print,
  1965. self._print(s.base_set),
  1966. self._print(s.condition))
  1967. def _print_PowerSet(self, expr):
  1968. arg_print = self._print(expr.args[0])
  1969. return r"\mathcal{{P}}\left({}\right)".format(arg_print)
  1970. def _print_ComplexRegion(self, s):
  1971. vars_print = ', '.join([self._print(var) for var in s.variables])
  1972. return r"\left\{%s\; \middle|\; %s \in %s \right\}" % (
  1973. self._print(s.expr),
  1974. vars_print,
  1975. self._print(s.sets))
  1976. def _print_Contains(self, e):
  1977. return r"%s \in %s" % tuple(self._print(a) for a in e.args)
  1978. def _print_FourierSeries(self, s):
  1979. if s.an.formula is S.Zero and s.bn.formula is S.Zero:
  1980. return self._print(s.a0)
  1981. return self._print_Add(s.truncate()) + r' + \ldots'
  1982. def _print_FormalPowerSeries(self, s):
  1983. return self._print_Add(s.infinite)
  1984. def _print_FiniteField(self, expr):
  1985. return r"\mathbb{F}_{%s}" % expr.mod
  1986. def _print_IntegerRing(self, expr):
  1987. return r"\mathbb{Z}"
  1988. def _print_RationalField(self, expr):
  1989. return r"\mathbb{Q}"
  1990. def _print_RealField(self, expr):
  1991. return r"\mathbb{R}"
  1992. def _print_ComplexField(self, expr):
  1993. return r"\mathbb{C}"
  1994. def _print_PolynomialRing(self, expr):
  1995. domain = self._print(expr.domain)
  1996. symbols = ", ".join(map(self._print, expr.symbols))
  1997. return r"%s\left[%s\right]" % (domain, symbols)
  1998. def _print_FractionField(self, expr):
  1999. domain = self._print(expr.domain)
  2000. symbols = ", ".join(map(self._print, expr.symbols))
  2001. return r"%s\left(%s\right)" % (domain, symbols)
  2002. def _print_PolynomialRingBase(self, expr):
  2003. domain = self._print(expr.domain)
  2004. symbols = ", ".join(map(self._print, expr.symbols))
  2005. inv = ""
  2006. if not expr.is_Poly:
  2007. inv = r"S_<^{-1}"
  2008. return r"%s%s\left[%s\right]" % (inv, domain, symbols)
  2009. def _print_Poly(self, poly):
  2010. cls = poly.__class__.__name__
  2011. terms = []
  2012. for monom, coeff in poly.terms():
  2013. s_monom = ''
  2014. for i, exp in enumerate(monom):
  2015. if exp > 0:
  2016. if exp == 1:
  2017. s_monom += self._print(poly.gens[i])
  2018. else:
  2019. s_monom += self._print(pow(poly.gens[i], exp))
  2020. if coeff.is_Add:
  2021. if s_monom:
  2022. s_coeff = r"\left(%s\right)" % self._print(coeff)
  2023. else:
  2024. s_coeff = self._print(coeff)
  2025. else:
  2026. if s_monom:
  2027. if coeff is S.One:
  2028. terms.extend(['+', s_monom])
  2029. continue
  2030. if coeff is S.NegativeOne:
  2031. terms.extend(['-', s_monom])
  2032. continue
  2033. s_coeff = self._print(coeff)
  2034. if not s_monom:
  2035. s_term = s_coeff
  2036. else:
  2037. s_term = s_coeff + " " + s_monom
  2038. if s_term.startswith('-'):
  2039. terms.extend(['-', s_term[1:]])
  2040. else:
  2041. terms.extend(['+', s_term])
  2042. if terms[0] in ('-', '+'):
  2043. modifier = terms.pop(0)
  2044. if modifier == '-':
  2045. terms[0] = '-' + terms[0]
  2046. expr = ' '.join(terms)
  2047. gens = list(map(self._print, poly.gens))
  2048. domain = "domain=%s" % self._print(poly.get_domain())
  2049. args = ", ".join([expr] + gens + [domain])
  2050. if cls in accepted_latex_functions:
  2051. tex = r"\%s {\left(%s \right)}" % (cls, args)
  2052. else:
  2053. tex = r"\operatorname{%s}{\left( %s \right)}" % (cls, args)
  2054. return tex
  2055. def _print_ComplexRootOf(self, root):
  2056. cls = root.__class__.__name__
  2057. if cls == "ComplexRootOf":
  2058. cls = "CRootOf"
  2059. expr = self._print(root.expr)
  2060. index = root.index
  2061. if cls in accepted_latex_functions:
  2062. return r"\%s {\left(%s, %d\right)}" % (cls, expr, index)
  2063. else:
  2064. return r"\operatorname{%s} {\left(%s, %d\right)}" % (cls, expr,
  2065. index)
  2066. def _print_RootSum(self, expr):
  2067. cls = expr.__class__.__name__
  2068. args = [self._print(expr.expr)]
  2069. if expr.fun is not S.IdentityFunction:
  2070. args.append(self._print(expr.fun))
  2071. if cls in accepted_latex_functions:
  2072. return r"\%s {\left(%s\right)}" % (cls, ", ".join(args))
  2073. else:
  2074. return r"\operatorname{%s} {\left(%s\right)}" % (cls,
  2075. ", ".join(args))
  2076. def _print_OrdinalOmega(self, expr):
  2077. return r"\omega"
  2078. def _print_OmegaPower(self, expr):
  2079. exp, mul = expr.args
  2080. if mul != 1:
  2081. if exp != 1:
  2082. return r"{} \omega^{{{}}}".format(mul, exp)
  2083. else:
  2084. return r"{} \omega".format(mul)
  2085. else:
  2086. if exp != 1:
  2087. return r"\omega^{{{}}}".format(exp)
  2088. else:
  2089. return r"\omega"
  2090. def _print_Ordinal(self, expr):
  2091. return " + ".join([self._print(arg) for arg in expr.args])
  2092. def _print_PolyElement(self, poly):
  2093. mul_symbol = self._settings['mul_symbol_latex']
  2094. return poly.str(self, PRECEDENCE, "{%s}^{%d}", mul_symbol)
  2095. def _print_FracElement(self, frac):
  2096. if frac.denom == 1:
  2097. return self._print(frac.numer)
  2098. else:
  2099. numer = self._print(frac.numer)
  2100. denom = self._print(frac.denom)
  2101. return r"\frac{%s}{%s}" % (numer, denom)
  2102. def _print_euler(self, expr, exp=None):
  2103. m, x = (expr.args[0], None) if len(expr.args) == 1 else expr.args
  2104. tex = r"E_{%s}" % self._print(m)
  2105. if exp is not None:
  2106. tex = r"%s^{%s}" % (tex, exp)
  2107. if x is not None:
  2108. tex = r"%s\left(%s\right)" % (tex, self._print(x))
  2109. return tex
  2110. def _print_catalan(self, expr, exp=None):
  2111. tex = r"C_{%s}" % self._print(expr.args[0])
  2112. if exp is not None:
  2113. tex = r"%s^{%s}" % (tex, exp)
  2114. return tex
  2115. def _print_UnifiedTransform(self, expr, s, inverse=False):
  2116. return r"\mathcal{{{}}}{}_{{{}}}\left[{}\right]\left({}\right)".format(s, '^{-1}' if inverse else '', self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2]))
  2117. def _print_MellinTransform(self, expr):
  2118. return self._print_UnifiedTransform(expr, 'M')
  2119. def _print_InverseMellinTransform(self, expr):
  2120. return self._print_UnifiedTransform(expr, 'M', True)
  2121. def _print_LaplaceTransform(self, expr):
  2122. return self._print_UnifiedTransform(expr, 'L')
  2123. def _print_InverseLaplaceTransform(self, expr):
  2124. return self._print_UnifiedTransform(expr, 'L', True)
  2125. def _print_FourierTransform(self, expr):
  2126. return self._print_UnifiedTransform(expr, 'F')
  2127. def _print_InverseFourierTransform(self, expr):
  2128. return self._print_UnifiedTransform(expr, 'F', True)
  2129. def _print_SineTransform(self, expr):
  2130. return self._print_UnifiedTransform(expr, 'SIN')
  2131. def _print_InverseSineTransform(self, expr):
  2132. return self._print_UnifiedTransform(expr, 'SIN', True)
  2133. def _print_CosineTransform(self, expr):
  2134. return self._print_UnifiedTransform(expr, 'COS')
  2135. def _print_InverseCosineTransform(self, expr):
  2136. return self._print_UnifiedTransform(expr, 'COS', True)
  2137. def _print_DMP(self, p):
  2138. try:
  2139. if p.ring is not None:
  2140. # TODO incorporate order
  2141. return self._print(p.ring.to_sympy(p))
  2142. except SympifyError:
  2143. pass
  2144. return self._print(repr(p))
  2145. def _print_DMF(self, p):
  2146. return self._print_DMP(p)
  2147. def _print_Object(self, object):
  2148. return self._print(Symbol(object.name))
  2149. def _print_LambertW(self, expr, exp=None):
  2150. arg0 = self._print(expr.args[0])
  2151. exp = r"^{%s}" % (exp,) if exp is not None else ""
  2152. if len(expr.args) == 1:
  2153. result = r"W%s\left(%s\right)" % (exp, arg0)
  2154. else:
  2155. arg1 = self._print(expr.args[1])
  2156. result = "W{0}_{{{1}}}\\left({2}\\right)".format(exp, arg1, arg0)
  2157. return result
  2158. def _print_Expectation(self, expr):
  2159. return r"\operatorname{{E}}\left[{}\right]".format(self._print(expr.args[0]))
  2160. def _print_Variance(self, expr):
  2161. return r"\operatorname{{Var}}\left({}\right)".format(self._print(expr.args[0]))
  2162. def _print_Covariance(self, expr):
  2163. return r"\operatorname{{Cov}}\left({}\right)".format(", ".join(self._print(arg) for arg in expr.args))
  2164. def _print_Probability(self, expr):
  2165. return r"\operatorname{{P}}\left({}\right)".format(self._print(expr.args[0]))
  2166. def _print_Morphism(self, morphism):
  2167. domain = self._print(morphism.domain)
  2168. codomain = self._print(morphism.codomain)
  2169. return "%s\\rightarrow %s" % (domain, codomain)
  2170. def _print_TransferFunction(self, expr):
  2171. num, den = self._print(expr.num), self._print(expr.den)
  2172. return r"\frac{%s}{%s}" % (num, den)
  2173. def _print_Series(self, expr):
  2174. args = list(expr.args)
  2175. parens = lambda x: self.parenthesize(x, precedence_traditional(expr),
  2176. False)
  2177. return ' '.join(map(parens, args))
  2178. def _print_MIMOSeries(self, expr):
  2179. from sympy.physics.control.lti import MIMOParallel
  2180. args = list(expr.args)[::-1]
  2181. parens = lambda x: self.parenthesize(x, precedence_traditional(expr),
  2182. False) if isinstance(x, MIMOParallel) else self._print(x)
  2183. return r"\cdot".join(map(parens, args))
  2184. def _print_Parallel(self, expr):
  2185. return ' + '.join(map(self._print, expr.args))
  2186. def _print_MIMOParallel(self, expr):
  2187. return ' + '.join(map(self._print, expr.args))
  2188. def _print_Feedback(self, expr):
  2189. from sympy.physics.control import TransferFunction, Series
  2190. num, tf = expr.sys1, TransferFunction(1, 1, expr.var)
  2191. num_arg_list = list(num.args) if isinstance(num, Series) else [num]
  2192. den_arg_list = list(expr.sys2.args) if \
  2193. isinstance(expr.sys2, Series) else [expr.sys2]
  2194. den_term_1 = tf
  2195. if isinstance(num, Series) and isinstance(expr.sys2, Series):
  2196. den_term_2 = Series(*num_arg_list, *den_arg_list)
  2197. elif isinstance(num, Series) and isinstance(expr.sys2, TransferFunction):
  2198. if expr.sys2 == tf:
  2199. den_term_2 = Series(*num_arg_list)
  2200. else:
  2201. den_term_2 = tf, Series(*num_arg_list, expr.sys2)
  2202. elif isinstance(num, TransferFunction) and isinstance(expr.sys2, Series):
  2203. if num == tf:
  2204. den_term_2 = Series(*den_arg_list)
  2205. else:
  2206. den_term_2 = Series(num, *den_arg_list)
  2207. else:
  2208. if num == tf:
  2209. den_term_2 = Series(*den_arg_list)
  2210. elif expr.sys2 == tf:
  2211. den_term_2 = Series(*num_arg_list)
  2212. else:
  2213. den_term_2 = Series(*num_arg_list, *den_arg_list)
  2214. numer = self._print(num)
  2215. denom_1 = self._print(den_term_1)
  2216. denom_2 = self._print(den_term_2)
  2217. _sign = "+" if expr.sign == -1 else "-"
  2218. return r"\frac{%s}{%s %s %s}" % (numer, denom_1, _sign, denom_2)
  2219. def _print_MIMOFeedback(self, expr):
  2220. from sympy.physics.control import MIMOSeries
  2221. inv_mat = self._print(MIMOSeries(expr.sys2, expr.sys1))
  2222. sys1 = self._print(expr.sys1)
  2223. _sign = "+" if expr.sign == -1 else "-"
  2224. return r"\left(I_{\tau} %s %s\right)^{-1} \cdot %s" % (_sign, inv_mat, sys1)
  2225. def _print_TransferFunctionMatrix(self, expr):
  2226. mat = self._print(expr._expr_mat)
  2227. return r"%s_\tau" % mat
  2228. def _print_DFT(self, expr):
  2229. return r"\text{{{}}}_{{{}}}".format(expr.__class__.__name__, expr.n)
  2230. _print_IDFT = _print_DFT
  2231. def _print_NamedMorphism(self, morphism):
  2232. pretty_name = self._print(Symbol(morphism.name))
  2233. pretty_morphism = self._print_Morphism(morphism)
  2234. return "%s:%s" % (pretty_name, pretty_morphism)
  2235. def _print_IdentityMorphism(self, morphism):
  2236. from sympy.categories import NamedMorphism
  2237. return self._print_NamedMorphism(NamedMorphism(
  2238. morphism.domain, morphism.codomain, "id"))
  2239. def _print_CompositeMorphism(self, morphism):
  2240. # All components of the morphism have names and it is thus
  2241. # possible to build the name of the composite.
  2242. component_names_list = [self._print(Symbol(component.name)) for
  2243. component in morphism.components]
  2244. component_names_list.reverse()
  2245. component_names = "\\circ ".join(component_names_list) + ":"
  2246. pretty_morphism = self._print_Morphism(morphism)
  2247. return component_names + pretty_morphism
  2248. def _print_Category(self, morphism):
  2249. return r"\mathbf{{{}}}".format(self._print(Symbol(morphism.name)))
  2250. def _print_Diagram(self, diagram):
  2251. if not diagram.premises:
  2252. # This is an empty diagram.
  2253. return self._print(S.EmptySet)
  2254. latex_result = self._print(diagram.premises)
  2255. if diagram.conclusions:
  2256. latex_result += "\\Longrightarrow %s" % \
  2257. self._print(diagram.conclusions)
  2258. return latex_result
  2259. def _print_DiagramGrid(self, grid):
  2260. latex_result = "\\begin{array}{%s}\n" % ("c" * grid.width)
  2261. for i in range(grid.height):
  2262. for j in range(grid.width):
  2263. if grid[i, j]:
  2264. latex_result += latex(grid[i, j])
  2265. latex_result += " "
  2266. if j != grid.width - 1:
  2267. latex_result += "& "
  2268. if i != grid.height - 1:
  2269. latex_result += "\\\\"
  2270. latex_result += "\n"
  2271. latex_result += "\\end{array}\n"
  2272. return latex_result
  2273. def _print_FreeModule(self, M):
  2274. return '{{{}}}^{{{}}}'.format(self._print(M.ring), self._print(M.rank))
  2275. def _print_FreeModuleElement(self, m):
  2276. # Print as row vector for convenience, for now.
  2277. return r"\left[ {} \right]".format(",".join(
  2278. '{' + self._print(x) + '}' for x in m))
  2279. def _print_SubModule(self, m):
  2280. return r"\left\langle {} \right\rangle".format(",".join(
  2281. '{' + self._print(x) + '}' for x in m.gens))
  2282. def _print_ModuleImplementedIdeal(self, m):
  2283. return r"\left\langle {} \right\rangle".format(",".join(
  2284. '{' + self._print(x) + '}' for [x] in m._module.gens))
  2285. def _print_Quaternion(self, expr):
  2286. # TODO: This expression is potentially confusing,
  2287. # shall we print it as `Quaternion( ... )`?
  2288. s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True)
  2289. for i in expr.args]
  2290. a = [s[0]] + [i+" "+j for i, j in zip(s[1:], "ijk")]
  2291. return " + ".join(a)
  2292. def _print_QuotientRing(self, R):
  2293. # TODO nicer fractions for few generators...
  2294. return r"\frac{{{}}}{{{}}}".format(self._print(R.ring),
  2295. self._print(R.base_ideal))
  2296. def _print_QuotientRingElement(self, x):
  2297. return r"{{{}}} + {{{}}}".format(self._print(x.data),
  2298. self._print(x.ring.base_ideal))
  2299. def _print_QuotientModuleElement(self, m):
  2300. return r"{{{}}} + {{{}}}".format(self._print(m.data),
  2301. self._print(m.module.killed_module))
  2302. def _print_QuotientModule(self, M):
  2303. # TODO nicer fractions for few generators...
  2304. return r"\frac{{{}}}{{{}}}".format(self._print(M.base),
  2305. self._print(M.killed_module))
  2306. def _print_MatrixHomomorphism(self, h):
  2307. return r"{{{}}} : {{{}}} \to {{{}}}".format(self._print(h._sympy_matrix()),
  2308. self._print(h.domain), self._print(h.codomain))
  2309. def _print_Manifold(self, manifold):
  2310. string = manifold.name.name
  2311. if '{' in string:
  2312. name, supers, subs = string, [], []
  2313. else:
  2314. name, supers, subs = split_super_sub(string)
  2315. name = translate(name)
  2316. supers = [translate(sup) for sup in supers]
  2317. subs = [translate(sub) for sub in subs]
  2318. name = r'\text{%s}' % name
  2319. if supers:
  2320. name += "^{%s}" % " ".join(supers)
  2321. if subs:
  2322. name += "_{%s}" % " ".join(subs)
  2323. return name
  2324. def _print_Patch(self, patch):
  2325. return r'\text{%s}_{%s}' % (self._print(patch.name), self._print(patch.manifold))
  2326. def _print_CoordSystem(self, coordsys):
  2327. return r'\text{%s}^{\text{%s}}_{%s}' % (
  2328. self._print(coordsys.name), self._print(coordsys.patch.name), self._print(coordsys.manifold)
  2329. )
  2330. def _print_CovarDerivativeOp(self, cvd):
  2331. return r'\mathbb{\nabla}_{%s}' % self._print(cvd._wrt)
  2332. def _print_BaseScalarField(self, field):
  2333. string = field._coord_sys.symbols[field._index].name
  2334. return r'\mathbf{{{}}}'.format(self._print(Symbol(string)))
  2335. def _print_BaseVectorField(self, field):
  2336. string = field._coord_sys.symbols[field._index].name
  2337. return r'\partial_{{{}}}'.format(self._print(Symbol(string)))
  2338. def _print_Differential(self, diff):
  2339. field = diff._form_field
  2340. if hasattr(field, '_coord_sys'):
  2341. string = field._coord_sys.symbols[field._index].name
  2342. return r'\operatorname{{d}}{}'.format(self._print(Symbol(string)))
  2343. else:
  2344. string = self._print(field)
  2345. return r'\operatorname{{d}}\left({}\right)'.format(string)
  2346. def _print_Tr(self, p):
  2347. # TODO: Handle indices
  2348. contents = self._print(p.args[0])
  2349. return r'\operatorname{{tr}}\left({}\right)'.format(contents)
  2350. def _print_totient(self, expr, exp=None):
  2351. if exp is not None:
  2352. return r'\left(\phi\left(%s\right)\right)^{%s}' % \
  2353. (self._print(expr.args[0]), exp)
  2354. return r'\phi\left(%s\right)' % self._print(expr.args[0])
  2355. def _print_reduced_totient(self, expr, exp=None):
  2356. if exp is not None:
  2357. return r'\left(\lambda\left(%s\right)\right)^{%s}' % \
  2358. (self._print(expr.args[0]), exp)
  2359. return r'\lambda\left(%s\right)' % self._print(expr.args[0])
  2360. def _print_divisor_sigma(self, expr, exp=None):
  2361. if len(expr.args) == 2:
  2362. tex = r"_%s\left(%s\right)" % tuple(map(self._print,
  2363. (expr.args[1], expr.args[0])))
  2364. else:
  2365. tex = r"\left(%s\right)" % self._print(expr.args[0])
  2366. if exp is not None:
  2367. return r"\sigma^{%s}%s" % (exp, tex)
  2368. return r"\sigma%s" % tex
  2369. def _print_udivisor_sigma(self, expr, exp=None):
  2370. if len(expr.args) == 2:
  2371. tex = r"_%s\left(%s\right)" % tuple(map(self._print,
  2372. (expr.args[1], expr.args[0])))
  2373. else:
  2374. tex = r"\left(%s\right)" % self._print(expr.args[0])
  2375. if exp is not None:
  2376. return r"\sigma^*^{%s}%s" % (exp, tex)
  2377. return r"\sigma^*%s" % tex
  2378. def _print_primenu(self, expr, exp=None):
  2379. if exp is not None:
  2380. return r'\left(\nu\left(%s\right)\right)^{%s}' % \
  2381. (self._print(expr.args[0]), exp)
  2382. return r'\nu\left(%s\right)' % self._print(expr.args[0])
  2383. def _print_primeomega(self, expr, exp=None):
  2384. if exp is not None:
  2385. return r'\left(\Omega\left(%s\right)\right)^{%s}' % \
  2386. (self._print(expr.args[0]), exp)
  2387. return r'\Omega\left(%s\right)' % self._print(expr.args[0])
  2388. def _print_Str(self, s):
  2389. return str(s.name)
  2390. def _print_float(self, expr):
  2391. return self._print(Float(expr))
  2392. def _print_int(self, expr):
  2393. return str(expr)
  2394. def _print_mpz(self, expr):
  2395. return str(expr)
  2396. def _print_mpq(self, expr):
  2397. return str(expr)
  2398. def _print_Predicate(self, expr):
  2399. return r"\operatorname{{Q}}_{{\text{{{}}}}}".format(latex_escape(str(expr.name)))
  2400. def _print_AppliedPredicate(self, expr):
  2401. pred = expr.function
  2402. args = expr.arguments
  2403. pred_latex = self._print(pred)
  2404. args_latex = ', '.join([self._print(a) for a in args])
  2405. return '%s(%s)' % (pred_latex, args_latex)
  2406. def emptyPrinter(self, expr):
  2407. # default to just printing as monospace, like would normally be shown
  2408. s = super().emptyPrinter(expr)
  2409. return r"\mathtt{\text{%s}}" % latex_escape(s)
  2410. def translate(s: str) -> str:
  2411. r'''
  2412. Check for a modifier ending the string. If present, convert the
  2413. modifier to latex and translate the rest recursively.
  2414. Given a description of a Greek letter or other special character,
  2415. return the appropriate latex.
  2416. Let everything else pass as given.
  2417. >>> from sympy.printing.latex import translate
  2418. >>> translate('alphahatdotprime')
  2419. "{\\dot{\\hat{\\alpha}}}'"
  2420. '''
  2421. # Process the rest
  2422. tex = tex_greek_dictionary.get(s)
  2423. if tex:
  2424. return tex
  2425. elif s.lower() in greek_letters_set:
  2426. return "\\" + s.lower()
  2427. elif s in other_symbols:
  2428. return "\\" + s
  2429. else:
  2430. # Process modifiers, if any, and recurse
  2431. for key in sorted(modifier_dict.keys(), key=len, reverse=True):
  2432. if s.lower().endswith(key) and len(s) > len(key):
  2433. return modifier_dict[key](translate(s[:-len(key)]))
  2434. return s
  2435. @print_function(LatexPrinter)
  2436. def latex(expr, **settings):
  2437. r"""Convert the given expression to LaTeX string representation.
  2438. Parameters
  2439. ==========
  2440. full_prec: boolean, optional
  2441. If set to True, a floating point number is printed with full precision.
  2442. fold_frac_powers : boolean, optional
  2443. Emit ``^{p/q}`` instead of ``^{\frac{p}{q}}`` for fractional powers.
  2444. fold_func_brackets : boolean, optional
  2445. Fold function brackets where applicable.
  2446. fold_short_frac : boolean, optional
  2447. Emit ``p / q`` instead of ``\frac{p}{q}`` when the denominator is
  2448. simple enough (at most two terms and no powers). The default value is
  2449. ``True`` for inline mode, ``False`` otherwise.
  2450. inv_trig_style : string, optional
  2451. How inverse trig functions should be displayed. Can be one of
  2452. ``'abbreviated'``, ``'full'``, or ``'power'``. Defaults to
  2453. ``'abbreviated'``.
  2454. itex : boolean, optional
  2455. Specifies if itex-specific syntax is used, including emitting
  2456. ``$$...$$``.
  2457. ln_notation : boolean, optional
  2458. If set to ``True``, ``\ln`` is used instead of default ``\log``.
  2459. long_frac_ratio : float or None, optional
  2460. The allowed ratio of the width of the numerator to the width of the
  2461. denominator before the printer breaks off long fractions. If ``None``
  2462. (the default value), long fractions are not broken up.
  2463. mat_delim : string, optional
  2464. The delimiter to wrap around matrices. Can be one of ``'['``, ``'('``,
  2465. or the empty string ``''``. Defaults to ``'['``.
  2466. mat_str : string, optional
  2467. Which matrix environment string to emit. ``'smallmatrix'``,
  2468. ``'matrix'``, ``'array'``, etc. Defaults to ``'smallmatrix'`` for
  2469. inline mode, ``'matrix'`` for matrices of no more than 10 columns, and
  2470. ``'array'`` otherwise.
  2471. mode: string, optional
  2472. Specifies how the generated code will be delimited. ``mode`` can be one
  2473. of ``'plain'``, ``'inline'``, ``'equation'`` or ``'equation*'``. If
  2474. ``mode`` is set to ``'plain'``, then the resulting code will not be
  2475. delimited at all (this is the default). If ``mode`` is set to
  2476. ``'inline'`` then inline LaTeX ``$...$`` will be used. If ``mode`` is
  2477. set to ``'equation'`` or ``'equation*'``, the resulting code will be
  2478. enclosed in the ``equation`` or ``equation*`` environment (remember to
  2479. import ``amsmath`` for ``equation*``), unless the ``itex`` option is
  2480. set. In the latter case, the ``$$...$$`` syntax is used.
  2481. mul_symbol : string or None, optional
  2482. The symbol to use for multiplication. Can be one of ``None``,
  2483. ``'ldot'``, ``'dot'``, or ``'times'``.
  2484. order: string, optional
  2485. Any of the supported monomial orderings (currently ``'lex'``,
  2486. ``'grlex'``, or ``'grevlex'``), ``'old'``, and ``'none'``. This
  2487. parameter does nothing for `~.Mul` objects. Setting order to ``'old'``
  2488. uses the compatibility ordering for ``~.Add`` defined in Printer. For
  2489. very large expressions, set the ``order`` keyword to ``'none'`` if
  2490. speed is a concern.
  2491. symbol_names : dictionary of strings mapped to symbols, optional
  2492. Dictionary of symbols and the custom strings they should be emitted as.
  2493. root_notation : boolean, optional
  2494. If set to ``False``, exponents of the form 1/n are printed in fractonal
  2495. form. Default is ``True``, to print exponent in root form.
  2496. mat_symbol_style : string, optional
  2497. Can be either ``'plain'`` (default) or ``'bold'``. If set to
  2498. ``'bold'``, a `~.MatrixSymbol` A will be printed as ``\mathbf{A}``,
  2499. otherwise as ``A``.
  2500. imaginary_unit : string, optional
  2501. String to use for the imaginary unit. Defined options are ``'i'``
  2502. (default) and ``'j'``. Adding ``r`` or ``t`` in front gives ``\mathrm``
  2503. or ``\text``, so ``'ri'`` leads to ``\mathrm{i}`` which gives
  2504. `\mathrm{i}`.
  2505. gothic_re_im : boolean, optional
  2506. If set to ``True``, `\Re` and `\Im` is used for ``re`` and ``im``, respectively.
  2507. The default is ``False`` leading to `\operatorname{re}` and `\operatorname{im}`.
  2508. decimal_separator : string, optional
  2509. Specifies what separator to use to separate the whole and fractional parts of a
  2510. floating point number as in `2.5` for the default, ``period`` or `2{,}5`
  2511. when ``comma`` is specified. Lists, sets, and tuple are printed with semicolon
  2512. separating the elements when ``comma`` is chosen. For example, [1; 2; 3] when
  2513. ``comma`` is chosen and [1,2,3] for when ``period`` is chosen.
  2514. parenthesize_super : boolean, optional
  2515. If set to ``False``, superscripted expressions will not be parenthesized when
  2516. powered. Default is ``True``, which parenthesizes the expression when powered.
  2517. min: Integer or None, optional
  2518. Sets the lower bound for the exponent to print floating point numbers in
  2519. fixed-point format.
  2520. max: Integer or None, optional
  2521. Sets the upper bound for the exponent to print floating point numbers in
  2522. fixed-point format.
  2523. diff_operator: string, optional
  2524. String to use for differential operator. Default is ``'d'``, to print in italic
  2525. form. ``'rd'``, ``'td'`` are shortcuts for ``\mathrm{d}`` and ``\text{d}``.
  2526. Notes
  2527. =====
  2528. Not using a print statement for printing, results in double backslashes for
  2529. latex commands since that's the way Python escapes backslashes in strings.
  2530. >>> from sympy import latex, Rational
  2531. >>> from sympy.abc import tau
  2532. >>> latex((2*tau)**Rational(7,2))
  2533. '8 \\sqrt{2} \\tau^{\\frac{7}{2}}'
  2534. >>> print(latex((2*tau)**Rational(7,2)))
  2535. 8 \sqrt{2} \tau^{\frac{7}{2}}
  2536. Examples
  2537. ========
  2538. >>> from sympy import latex, pi, sin, asin, Integral, Matrix, Rational, log
  2539. >>> from sympy.abc import x, y, mu, r, tau
  2540. Basic usage:
  2541. >>> print(latex((2*tau)**Rational(7,2)))
  2542. 8 \sqrt{2} \tau^{\frac{7}{2}}
  2543. ``mode`` and ``itex`` options:
  2544. >>> print(latex((2*mu)**Rational(7,2), mode='plain'))
  2545. 8 \sqrt{2} \mu^{\frac{7}{2}}
  2546. >>> print(latex((2*tau)**Rational(7,2), mode='inline'))
  2547. $8 \sqrt{2} \tau^{7 / 2}$
  2548. >>> print(latex((2*mu)**Rational(7,2), mode='equation*'))
  2549. \begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}
  2550. >>> print(latex((2*mu)**Rational(7,2), mode='equation'))
  2551. \begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation}
  2552. >>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True))
  2553. $$8 \sqrt{2} \mu^{\frac{7}{2}}$$
  2554. >>> print(latex((2*mu)**Rational(7,2), mode='plain'))
  2555. 8 \sqrt{2} \mu^{\frac{7}{2}}
  2556. >>> print(latex((2*tau)**Rational(7,2), mode='inline'))
  2557. $8 \sqrt{2} \tau^{7 / 2}$
  2558. >>> print(latex((2*mu)**Rational(7,2), mode='equation*'))
  2559. \begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}
  2560. >>> print(latex((2*mu)**Rational(7,2), mode='equation'))
  2561. \begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation}
  2562. >>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True))
  2563. $$8 \sqrt{2} \mu^{\frac{7}{2}}$$
  2564. Fraction options:
  2565. >>> print(latex((2*tau)**Rational(7,2), fold_frac_powers=True))
  2566. 8 \sqrt{2} \tau^{7/2}
  2567. >>> print(latex((2*tau)**sin(Rational(7,2))))
  2568. \left(2 \tau\right)^{\sin{\left(\frac{7}{2} \right)}}
  2569. >>> print(latex((2*tau)**sin(Rational(7,2)), fold_func_brackets=True))
  2570. \left(2 \tau\right)^{\sin {\frac{7}{2}}}
  2571. >>> print(latex(3*x**2/y))
  2572. \frac{3 x^{2}}{y}
  2573. >>> print(latex(3*x**2/y, fold_short_frac=True))
  2574. 3 x^{2} / y
  2575. >>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=2))
  2576. \frac{\int r\, dr}{2 \pi}
  2577. >>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=0))
  2578. \frac{1}{2 \pi} \int r\, dr
  2579. Multiplication options:
  2580. >>> print(latex((2*tau)**sin(Rational(7,2)), mul_symbol="times"))
  2581. \left(2 \times \tau\right)^{\sin{\left(\frac{7}{2} \right)}}
  2582. Trig options:
  2583. >>> print(latex(asin(Rational(7,2))))
  2584. \operatorname{asin}{\left(\frac{7}{2} \right)}
  2585. >>> print(latex(asin(Rational(7,2)), inv_trig_style="full"))
  2586. \arcsin{\left(\frac{7}{2} \right)}
  2587. >>> print(latex(asin(Rational(7,2)), inv_trig_style="power"))
  2588. \sin^{-1}{\left(\frac{7}{2} \right)}
  2589. Matrix options:
  2590. >>> print(latex(Matrix(2, 1, [x, y])))
  2591. \left[\begin{matrix}x\\y\end{matrix}\right]
  2592. >>> print(latex(Matrix(2, 1, [x, y]), mat_str = "array"))
  2593. \left[\begin{array}{c}x\\y\end{array}\right]
  2594. >>> print(latex(Matrix(2, 1, [x, y]), mat_delim="("))
  2595. \left(\begin{matrix}x\\y\end{matrix}\right)
  2596. Custom printing of symbols:
  2597. >>> print(latex(x**2, symbol_names={x: 'x_i'}))
  2598. x_i^{2}
  2599. Logarithms:
  2600. >>> print(latex(log(10)))
  2601. \log{\left(10 \right)}
  2602. >>> print(latex(log(10), ln_notation=True))
  2603. \ln{\left(10 \right)}
  2604. ``latex()`` also supports the builtin container types :class:`list`,
  2605. :class:`tuple`, and :class:`dict`:
  2606. >>> print(latex([2/x, y], mode='inline'))
  2607. $\left[ 2 / x, \ y\right]$
  2608. Unsupported types are rendered as monospaced plaintext:
  2609. >>> print(latex(int))
  2610. \mathtt{\text{<class 'int'>}}
  2611. >>> print(latex("plain % text"))
  2612. \mathtt{\text{plain \% text}}
  2613. See :ref:`printer_method_example` for an example of how to override
  2614. this behavior for your own types by implementing ``_latex``.
  2615. .. versionchanged:: 1.7.0
  2616. Unsupported types no longer have their ``str`` representation treated as valid latex.
  2617. """
  2618. return LatexPrinter(settings).doprint(expr)
  2619. def print_latex(expr, **settings):
  2620. """Prints LaTeX representation of the given expression. Takes the same
  2621. settings as ``latex()``."""
  2622. print(latex(expr, **settings))
  2623. def multiline_latex(lhs, rhs, terms_per_line=1, environment="align*", use_dots=False, **settings):
  2624. r"""
  2625. This function generates a LaTeX equation with a multiline right-hand side
  2626. in an ``align*``, ``eqnarray`` or ``IEEEeqnarray`` environment.
  2627. Parameters
  2628. ==========
  2629. lhs : Expr
  2630. Left-hand side of equation
  2631. rhs : Expr
  2632. Right-hand side of equation
  2633. terms_per_line : integer, optional
  2634. Number of terms per line to print. Default is 1.
  2635. environment : "string", optional
  2636. Which LaTeX wnvironment to use for the output. Options are "align*"
  2637. (default), "eqnarray", and "IEEEeqnarray".
  2638. use_dots : boolean, optional
  2639. If ``True``, ``\\dots`` is added to the end of each line. Default is ``False``.
  2640. Examples
  2641. ========
  2642. >>> from sympy import multiline_latex, symbols, sin, cos, exp, log, I
  2643. >>> x, y, alpha = symbols('x y alpha')
  2644. >>> expr = sin(alpha*y) + exp(I*alpha) - cos(log(y))
  2645. >>> print(multiline_latex(x, expr))
  2646. \begin{align*}
  2647. x = & e^{i \alpha} \\
  2648. & + \sin{\left(\alpha y \right)} \\
  2649. & - \cos{\left(\log{\left(y \right)} \right)}
  2650. \end{align*}
  2651. Using at most two terms per line:
  2652. >>> print(multiline_latex(x, expr, 2))
  2653. \begin{align*}
  2654. x = & e^{i \alpha} + \sin{\left(\alpha y \right)} \\
  2655. & - \cos{\left(\log{\left(y \right)} \right)}
  2656. \end{align*}
  2657. Using ``eqnarray`` and dots:
  2658. >>> print(multiline_latex(x, expr, terms_per_line=2, environment="eqnarray", use_dots=True))
  2659. \begin{eqnarray}
  2660. x & = & e^{i \alpha} + \sin{\left(\alpha y \right)} \dots\nonumber\\
  2661. & & - \cos{\left(\log{\left(y \right)} \right)}
  2662. \end{eqnarray}
  2663. Using ``IEEEeqnarray``:
  2664. >>> print(multiline_latex(x, expr, environment="IEEEeqnarray"))
  2665. \begin{IEEEeqnarray}{rCl}
  2666. x & = & e^{i \alpha} \nonumber\\
  2667. & & + \sin{\left(\alpha y \right)} \nonumber\\
  2668. & & - \cos{\left(\log{\left(y \right)} \right)}
  2669. \end{IEEEeqnarray}
  2670. Notes
  2671. =====
  2672. All optional parameters from ``latex`` can also be used.
  2673. """
  2674. # Based on code from https://github.com/sympy/sympy/issues/3001
  2675. l = LatexPrinter(**settings)
  2676. if environment == "eqnarray":
  2677. result = r'\begin{eqnarray}' + '\n'
  2678. first_term = '& = &'
  2679. nonumber = r'\nonumber'
  2680. end_term = '\n\\end{eqnarray}'
  2681. doubleet = True
  2682. elif environment == "IEEEeqnarray":
  2683. result = r'\begin{IEEEeqnarray}{rCl}' + '\n'
  2684. first_term = '& = &'
  2685. nonumber = r'\nonumber'
  2686. end_term = '\n\\end{IEEEeqnarray}'
  2687. doubleet = True
  2688. elif environment == "align*":
  2689. result = r'\begin{align*}' + '\n'
  2690. first_term = '= &'
  2691. nonumber = ''
  2692. end_term = '\n\\end{align*}'
  2693. doubleet = False
  2694. else:
  2695. raise ValueError("Unknown environment: {}".format(environment))
  2696. dots = ''
  2697. if use_dots:
  2698. dots=r'\dots'
  2699. terms = rhs.as_ordered_terms()
  2700. n_terms = len(terms)
  2701. term_count = 1
  2702. for i in range(n_terms):
  2703. term = terms[i]
  2704. term_start = ''
  2705. term_end = ''
  2706. sign = '+'
  2707. if term_count > terms_per_line:
  2708. if doubleet:
  2709. term_start = '& & '
  2710. else:
  2711. term_start = '& '
  2712. term_count = 1
  2713. if term_count == terms_per_line:
  2714. # End of line
  2715. if i < n_terms-1:
  2716. # There are terms remaining
  2717. term_end = dots + nonumber + r'\\' + '\n'
  2718. else:
  2719. term_end = ''
  2720. if term.as_ordered_factors()[0] == -1:
  2721. term = -1*term
  2722. sign = r'-'
  2723. if i == 0: # beginning
  2724. if sign == '+':
  2725. sign = ''
  2726. result += r'{:s} {:s}{:s} {:s} {:s}'.format(l.doprint(lhs),
  2727. first_term, sign, l.doprint(term), term_end)
  2728. else:
  2729. result += r'{:s}{:s} {:s} {:s}'.format(term_start, sign,
  2730. l.doprint(term), term_end)
  2731. term_count += 1
  2732. result += end_term
  2733. return result