/
latex.py
1774 lines (1422 loc) · 61.6 KB
/
latex.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""A Printer which converts an expression into its LaTeX equivalent."""
import itertools
import re
import mpmath.libmp as mlib
from mpmath.libmp import prec_to_dps
from ..core import Add, Integer, Mod, oo
from ..core.alphabets import greeks
from ..core.function import _coeff_isneg
from ..core.operations import AssocOp
from ..core.relational import Relational
from ..sets import Reals
from ..utilities import default_sort_key, has_variety
from .conventions import requires_partial, split_super_sub
from .precedence import PRECEDENCE, precedence
from .printer import Printer
# Hand-picked functions which can be used directly in both LaTeX and MathJax
# Complete list at http://www.mathjax.org/docs/1.1/tex.html#supported-latex-commands
# This variable only contains those functions which diofant uses.
accepted_latex_functions = ['arcsin', 'arccos', 'arctan', 'sin', 'cos', 'tan',
'sinh', 'cosh', 'tanh', 'sqrt', 'ln', 'log', 'sec',
'csc', 'cot', 'coth', 're', 'im', 'frac', 'root',
'arg']
tex_greek_dictionary = {
'Alpha': 'A',
'Beta': 'B',
'Gamma': r'\Gamma',
'Delta': r'\Delta',
'Epsilon': 'E',
'Zeta': 'Z',
'Eta': 'H',
'Theta': r'\Theta',
'Iota': 'I',
'Kappa': 'K',
'Lambda': r'\Lambda',
'Mu': 'M',
'Nu': 'N',
'Xi': r'\Xi',
'omicron': 'o',
'Omicron': 'O',
'Pi': r'\Pi',
'Rho': 'P',
'Sigma': r'\Sigma',
'Tau': 'T',
'Upsilon': r'\Upsilon',
'Phi': r'\Phi',
'Chi': 'X',
'Psi': r'\Psi',
'Omega': r'\Omega',
'lamda': r'\lambda',
'Lamda': r'\Lambda',
'khi': r'\chi',
'Khi': r'X',
'varepsilon': r'\varepsilon',
'varkappa': r'\varkappa',
'varphi': r'\varphi',
'varpi': r'\varpi',
'varrho': r'\varrho',
'varsigma': r'\varsigma',
'vartheta': r'\vartheta',
}
other_symbols = {'aleph', 'beth', 'daleth', 'gimel', 'ell', 'eth', 'hbar',
'hslash', 'mho', 'wp', }
# Variable name modifiers
modifier_dict = {
# Accents
'mathring': lambda s: r'\mathring{'+s+r'}',
'ddddot': lambda s: r'\ddddot{'+s+r'}',
'dddot': lambda s: r'\dddot{'+s+r'}',
'ddot': lambda s: r'\ddot{'+s+r'}',
'dot': lambda s: r'\dot{'+s+r'}',
'check': lambda s: r'\check{'+s+r'}',
'breve': lambda s: r'\breve{'+s+r'}',
'acute': lambda s: r'\acute{'+s+r'}',
'grave': lambda s: r'\grave{'+s+r'}',
'tilde': lambda s: r'\tilde{'+s+r'}',
'hat': lambda s: r'\hat{'+s+r'}',
'bar': lambda s: r'\bar{'+s+r'}',
'vec': lambda s: r'\vec{'+s+r'}',
'prime': lambda s: '{'+s+"}'",
'prm': lambda s: '{'+s+"}'",
# Faces
'bold': lambda s: r'\boldsymbol{'+s+r'}',
'bm': lambda s: r'\boldsymbol{'+s+r'}',
# Brackets
'norm': lambda s: r'\left\|{'+s+r'}\right\|',
'avg': lambda s: r'\left\langle{'+s+r'}\right\rangle',
'abs': lambda s: r'\left|{'+s+r'}\right|',
'mag': lambda s: r'\left|{'+s+r'}\right|',
}
greek_letters_set = frozenset(greeks)
_between_two_numbers_p = (
re.compile(r'[0-9][} ]*$'), # search
re.compile(r'[{ ]*[-+0-9]'), # match
)
class LatexPrinter(Printer):
"""LaTex printer."""
printmethod = '_latex'
_default_settings = {
'order': None,
'mode': 'plain',
'itex': False,
'fold_frac_powers': False,
'fold_func_brackets': False,
'fold_short_frac': None,
'long_frac_ratio': 2,
'mul_symbol': None,
'inv_trig_style': 'abbreviated',
'mat_str': None,
'mat_delim': '[',
'symbol_names': {},
}
def __init__(self, settings=None):
"""Initialize self."""
Printer.__init__(self, settings)
valid_modes = ['inline', 'plain', 'equation', 'equation*']
if self._settings['mode'] not in valid_modes:
raise ValueError("'mode' must be one of 'inline', 'plain', "
"'equation' or 'equation*'")
if self._settings['inv_trig_style'] not in ['power', 'full',
'abbreviated']:
raise ValueError("'inv_trig_style' must be one of 'power', 'full'"
"or 'abbreviated'")
if self._settings['fold_short_frac'] is None and \
self._settings['mode'] == 'inline':
self._settings['fold_short_frac'] = True
mul_symbol_table = {
None: r' ',
'ldot': r' \,.\, ',
'dot': r' \cdot ',
'times': r' \times '
}
self._settings['mul_symbol_latex'] = \
mul_symbol_table[self._settings['mul_symbol']]
self._settings['mul_symbol_latex_numbers'] = \
mul_symbol_table[self._settings['mul_symbol'] or 'dot']
self._delim_dict = {'(': ')', '[': ']'}
def parenthesize(self, item, level):
if precedence(item) <= level:
return r'\left(%s\right)' % self._print(item)
return self._print(item)
def doprint(self, expr):
tex = Printer.doprint(self, expr)
if self._settings['mode'] == 'plain':
return tex
if self._settings['mode'] == 'inline':
return r'$%s$' % tex
if self._settings['itex']:
return r'$$%s$$' % tex
env_str = self._settings['mode']
return r'\begin{%s}%s\end{%s}' % (env_str, tex, env_str)
def _needs_mul_brackets(self, expr, first=False, last=False):
"""
Returns True if the expression needs to be wrapped in brackets when
printed as part of a Mul, False otherwise. This is True for Add,
but also for some container objects that would not need brackets
when appearing last in a Mul, e.g. an Integral. ``last=True``
specifies that this expr is the last to appear in a Mul.
``first=True`` specifies that this expr is the first to appear in a Mul.
"""
from ..concrete import Product, Sum
from ..integrals import Integral
if expr.is_Add:
return True
if expr.is_Relational:
return True
if expr.is_Mul:
if not first and _coeff_isneg(expr):
return True
if expr.is_Piecewise:
return True
if expr.has(Mod):
return True
if not last and any(expr.has(x) for x in (Integral, Product, Sum)):
return True
return False
def _needs_add_brackets(self, expr):
"""
Returns True if the expression needs to be wrapped in brackets when
printed as part of an Add, False otherwise. This is False for most
things.
"""
if expr.is_Relational:
return True
if expr.has(Mod):
return True
return False
def _do_exponent(self, expr, exp):
if exp is not None:
return r'\left(%s\right)^{%s}' % (expr, exp)
return expr
def _print_bool(self, e):
return r'\mathrm{%s}' % e
_print_BooleanTrue = _print_bool
_print_BooleanFalse = _print_bool
def _print_NoneType(self, e):
return r'\mathrm{%s}' % e
def _print_Add(self, expr, order=None):
if self.order == 'none':
terms = list(expr.args)
else:
terms = expr.as_ordered_terms(order=order or self.order)
tex = ''
for i, term in enumerate(terms):
if i == 0:
pass
elif _coeff_isneg(term):
tex += ' - '
term = -term
else:
tex += ' + '
term_tex = self._print(term)
if self._needs_add_brackets(term):
term_tex = r'\left(%s\right)' % term_tex
tex += term_tex
return tex
def _print_Cycle(self, expr):
from ..combinatorics import Permutation
if not expr or (isinstance(expr, Permutation) and not expr.list()):
return r'\left( \right)'
expr = Permutation(expr)
expr_perm = expr.cyclic_form
siz = expr.size
if expr.array_form[-1] == siz - 1:
expr_perm = expr_perm + [[siz - 1]]
term_tex = ''
for i in expr_perm:
term_tex += str(i).replace(',', r'\;')
term_tex = term_tex.replace('[', r'\left( ')
term_tex = term_tex.replace(']', r'\right)')
return term_tex
_print_Permutation = _print_Cycle
def _print_Float(self, expr):
# Based off of that in StrPrinter
dps = prec_to_dps(expr._prec)
str_real = mlib.to_str(expr._mpf_, dps, strip_zeros=True)
# Must always have a mul symbol (as 2.5 10^{20} just looks odd)
# thus we use the number separator
separator = self._settings['mul_symbol_latex_numbers']
if 'e' in str_real:
(mant, exp) = str_real.split('e')
if exp[0] == '+':
exp = exp[1:]
return r'%s%s10^{%s}' % (mant, separator, exp)
if str_real == '+inf':
return r'\infty'
if str_real == '-inf':
return r'- \infty'
return str_real
def _print_Mul(self, expr):
include_parens = False
if _coeff_isneg(expr):
expr = -expr
tex = '- '
if expr.is_Add:
tex += '('
include_parens = True
else:
tex = ''
from ..simplify import fraction
numer, denom = fraction(expr, exact=True)
separator = self._settings['mul_symbol_latex']
numbersep = self._settings['mul_symbol_latex_numbers']
def convert(expr):
if not expr.is_Mul:
return str(self._print(expr))
_tex = last_term_tex = ''
if self.order != 'none':
args = expr.as_ordered_factors()
else:
args = expr.args
for i, term in enumerate(args):
term_tex = self._print(term)
if self._needs_mul_brackets(term, i == 0, i == len(args) - 1):
term_tex = r'\left(%s\right)' % term_tex
if _between_two_numbers_p[0].search(last_term_tex) and \
_between_two_numbers_p[1].match(term_tex):
# between two numbers
_tex += numbersep
elif _tex:
_tex += separator
_tex += term_tex
last_term_tex = term_tex
return _tex
if denom == 1:
# use the original expression here, since fraction() may have
# altered it when producing numer and denom
tex += convert(expr)
else:
snumer = convert(numer)
sdenom = convert(denom)
ldenom = len(sdenom.split())
ratio = self._settings['long_frac_ratio']
if self._settings['fold_short_frac'] \
and ldenom <= 2 and '^' not in sdenom:
# handle short fractions
if self._needs_mul_brackets(numer, last=False):
tex += r'\left(%s\right) / %s' % (snumer, sdenom)
else:
tex += r'%s / %s' % (snumer, sdenom)
elif len(snumer.split()) > ratio*ldenom:
# handle long fractions
if self._needs_mul_brackets(numer, last=True):
tex += r'\frac{1}{%s}%s\left(%s\right)' \
% (sdenom, separator, snumer)
elif numer.is_Mul:
# split a long numerator
a = Integer(1)
b = Integer(1)
for x in numer.args:
if self._needs_mul_brackets(x, last=False) or \
len(convert(a*x).split()) > ratio*ldenom or \
(b.is_commutative is x.is_commutative is False):
b *= x
else:
a *= x
if self._needs_mul_brackets(b, last=True):
tex += r'\frac{%s}{%s}%s\left(%s\right)' \
% (convert(a), sdenom, separator, convert(b))
else:
tex += r'\frac{%s}{%s}%s%s' \
% (convert(a), sdenom, separator, convert(b))
else:
tex += r'\frac{1}{%s}%s%s' % (sdenom, separator, snumer)
else:
tex += r'\frac{%s}{%s}' % (snumer, sdenom)
if include_parens:
tex += ')'
return tex
def _print_Pow(self, expr):
from ..integrals import Integral
# Treat root(x, n) as special case
if expr.exp.is_Rational and abs(expr.exp.numerator) == 1 and expr.exp.denominator != 1:
base = self._print(expr.base)
expq = expr.exp.denominator
if expq == 2:
tex = r'\sqrt{%s}' % base
elif self._settings['itex']:
tex = r'\root{%d}{%s}' % (expq, base)
else:
tex = r'\sqrt[%d]{%s}' % (expq, base)
if expr.exp.is_negative:
return r'\frac{1}{%s}' % tex
return tex
if self._settings['fold_frac_powers'] \
and expr.exp.is_Rational \
and expr.exp.denominator != 1:
base, p, q = self.parenthesize(expr.base, PRECEDENCE['Pow']), expr.exp.numerator, expr.exp.denominator
if expr.base.is_Function:
return self._print(expr.base, f'{p}/{q}')
return r'%s^{%s/%s}' % (base, p, q)
if expr.exp.is_Rational and expr.exp.is_negative and expr.base.is_commutative:
# Things like 1/x
return self._print_Mul(expr)
if expr.base.is_Function:
return self._print(expr.base, self._print(expr.exp))
tex = r'%s^{%s}'
if expr.base.is_Float or isinstance(expr.base, Integral):
tex = r'\left(%s\right)^{%s}'
return tex % (self.parenthesize(expr.base, PRECEDENCE['Pow']),
self._print(expr.exp))
def _print_Sum(self, expr):
if len(expr.limits) == 1:
tex = r'\sum_{%s=%s}^{%s} ' % \
tuple(self._print(i) for i in expr.limits[0])
else:
def _format_ineq(l):
return r'%s \leq %s \leq %s' % \
tuple(self._print(s) for s in (l[1], l[0], l[2]))
tex = r'\sum_{\substack{%s}} ' % \
str.join('\\\\', [_format_ineq(l) for l in expr.limits])
if isinstance(expr.function, Add):
tex += r'\left(%s\right)' % self._print(expr.function)
else:
tex += self._print(expr.function)
return tex
def _print_Product(self, expr):
if len(expr.limits) == 1:
tex = r'\prod_{%s=%s}^{%s} ' % \
tuple(self._print(i) for i in expr.limits[0])
else:
def _format_ineq(l):
return r'%s \leq %s \leq %s' % \
tuple(self._print(s) for s in (l[1], l[0], l[2]))
tex = r'\prod_{\substack{%s}} ' % \
str.join('\\\\', [_format_ineq(l) for l in expr.limits])
if isinstance(expr.function, Add):
tex += r'\left(%s\right)' % self._print(expr.function)
else:
tex += self._print(expr.function)
return tex
def _print_Indexed(self, expr):
tex = self._print(expr.base)+'_{%s}' % ','.join(
map(self._print, expr.indices))
return tex
def _print_IndexedBase(self, expr):
return self._print(expr.label)
def _print_Derivative(self, expr):
dim = len(expr.variables)
if requires_partial(expr):
diff_symbol = r'\partial'
else:
diff_symbol = r'd'
if dim == 1:
tex = r'\frac{%s}{%s %s}' % (diff_symbol, diff_symbol,
self._print(expr.variables[0]))
else:
multiplicity, i, tex = [], 1, ''
current = expr.variables[0]
for symbol in expr.variables[1:]:
if symbol == current:
i = i + 1
else:
multiplicity.append((current, i))
current, i = symbol, 1
multiplicity.append((current, i))
for x, i in multiplicity:
if i == 1:
tex += r'%s %s' % (diff_symbol, self._print(x))
else:
tex += r'%s %s^{%s}' % (diff_symbol, self._print(x), i)
tex = r'\frac{%s^{%s}}{%s} ' % (diff_symbol, dim, tex)
if isinstance(expr.expr, AssocOp):
return r'%s\left(%s\right)' % (tex, self._print(expr.expr))
return r'%s %s' % (tex, self._print(expr.expr))
def _print_Subs(self, subs):
expr, old, new = subs.expr, subs.variables, subs.point
latex_expr = self._print(expr)
latex_old = (self._print(e) for e in old)
latex_new = (self._print(e) for e in new) # pragma: no branch
latex_subs = r'\\ '.join(
e[0] + '=' + e[1] for e in zip(latex_old, latex_new))
return r'\left. %s \right|_{\substack{ %s }}' % (latex_expr, latex_subs)
def _print_Integral(self, expr):
tex, symbols = '', []
# Only up to \iiiint exists
if len(expr.limits) <= 4 and all(len(lim) == 1 for lim in expr.limits):
# Use len(expr.limits)-1 so that syntax highlighters don't think
# \" is an escaped quote
tex = r'\i' + 'i'*(len(expr.limits) - 1) + 'nt'
symbols = [r'\, d%s' % self._print(symbol[0])
for symbol in expr.limits]
else:
for lim in reversed(expr.limits):
symbol = lim[0]
tex += r'\int'
if len(lim) > 1:
if self._settings['mode'] in ['equation', 'equation*'] \
and not self._settings['itex']:
tex += r'\limits'
if len(lim) == 3:
tex += '_{%s}^{%s}' % (self._print(lim[1]),
self._print(lim[2]))
if len(lim) == 2:
tex += '^{%s}' % (self._print(lim[1]))
symbols.insert(0, r'\, d%s' % self._print(symbol))
tmpl = r'%s \left(%s\right)%s' if expr.function.is_Add else r'%s %s%s'
return tmpl % (tex, str(self._print(expr.function)), ''.join(symbols))
def _print_Limit(self, expr):
e, z, z0, dir = expr.args
if dir not in [Reals, 1, -1]:
e = e.subs({z: z0 - dir*z})
z0 = 0
dir = -1
tex = r'\lim_{%s \to ' % self._print(z)
if dir == Reals or z0 in (oo, -oo):
tex += r'%s}' % self._print(z0)
elif dir in [1, -1]:
tex += r'%s^%s}' % (self._print(z0), self._print('+' if dir == -1 else '-'))
else:
raise NotImplementedError
if isinstance(e, (AssocOp, Relational)):
return r'%s\left(%s\right)' % (tex, self._print(e))
return r'%s %s' % (tex, self._print(e))
def _hprint_Function(self, func):
r"""
Logic to decide how to render a function to latex
- if it is a recognized latex name, use the appropriate latex command
- if it is a single letter, just use that letter
- if it is a longer name, then put \operatorname{} around it and be
mindful of undercores in the name
"""
func = self._deal_with_super_sub(func)
if func in accepted_latex_functions:
name = r'\%s' % func
elif len(func) == 1 or func.startswith('\\'):
name = func
else:
name = r'\operatorname{%s}' % func
return name
def _print_Function(self, expr, exp=None):
r"""
Render functions to LaTeX, handling functions that LaTeX knows about
e.g., sin, cos, ... by using the proper LaTeX command (\sin, \cos, ...).
For single-letter function names, render them as regular LaTeX math
symbols. For multi-letter function names that LaTeX does not know
about, (e.g., Li, sech) use \operatorname{} so that the function name
is rendered in Roman font and LaTeX handles spacing properly.
expr is the expression involving the function
exp is an exponent
"""
func = expr.func.__name__
args = [str(self._print(arg)) for arg in expr.args]
# How inverse trig functions should be displayed, formats are:
# abbreviated: asin, full: arcsin, power: sin^-1
inv_trig_style = self._settings['inv_trig_style']
# If we are dealing with a power-style inverse trig function
inv_trig_power_case = False
# If it is applicable to fold the argument brackets
can_fold_brackets = (self._settings['fold_func_brackets'] and
len(args) == 1)
inv_trig_table = ['asin', 'acos', 'atan', 'acot']
# If the function is an inverse trig function, handle the style
if func in inv_trig_table:
if inv_trig_style == 'abbreviated':
pass
elif inv_trig_style == 'full':
func = 'arc' + func[1:]
else: # inv_trig_style == 'power':
func = func[1:]
inv_trig_power_case = True
# Can never fold brackets if we're raised to a power
if exp is not None:
can_fold_brackets = False
if inv_trig_power_case:
name = r'\%s^{-1}' % func
elif exp is not None:
name = r'%s^{%s}' % (self._hprint_Function(func), exp)
else:
name = self._hprint_Function(func)
if can_fold_brackets:
if func in accepted_latex_functions:
# Wrap argument safely to avoid parse-time conflicts
# with the function name itself
name += r' {%s}'
else:
name += r'%s'
else:
name += r'{\left (%s \right )}'
if inv_trig_power_case and exp is not None:
name += r'^{%s}' % exp
return name % ','.join(args)
def _print_UndefinedFunction(self, expr):
return self._hprint_Function(str(expr))
def _print_FunctionClass(self, expr):
if hasattr(expr, '_latex_no_arg'):
return expr._latex_no_arg(self)
return self._hprint_Function(str(expr))
def _print_Lambda(self, expr):
symbols, expr = expr.args
if len(symbols) == 1:
symbols = self._print(symbols[0])
else:
symbols = self._print(tuple(symbols))
tex = r'\left( %s \mapsto %s \right)' % (symbols, self._print(expr))
return tex
def _print_Min(self, expr, exp=None):
args = sorted(expr.args, key=default_sort_key)
texargs = [r'%s' % self._print(symbol) for symbol in args]
tex = r'\min\left(%s\right)' % ', '.join(texargs)
if exp is not None:
return r'%s^{%s}' % (tex, exp)
return tex
def _print_Max(self, expr, exp=None):
args = sorted(expr.args, key=default_sort_key)
texargs = [r'%s' % self._print(symbol) for symbol in args]
tex = r'\max\left(%s\right)' % ', '.join(texargs)
if exp is not None:
return r'%s^{%s}' % (tex, exp)
return tex
def _print_floor(self, expr, exp=None):
tex = r'\lfloor{%s}\rfloor' % self._print(expr.args[0])
if exp is not None:
return r'%s^{%s}' % (tex, exp)
return tex
def _print_ceiling(self, expr, exp=None):
tex = r'\lceil{%s}\rceil' % self._print(expr.args[0])
if exp is not None:
return r'%s^{%s}' % (tex, exp)
return tex
def _print_Abs(self, expr, exp=None):
tex = r'\left|{%s}\right|' % self._print(expr.args[0])
if exp is not None:
return r'%s^{%s}' % (tex, exp)
return tex
_print_Determinant = _print_Abs
def _print_re(self, expr, exp=None):
tex = r'\Re{%s}' % self.parenthesize(expr.args[0], PRECEDENCE['Func'])
return self._do_exponent(tex, exp)
def _print_im(self, expr, exp=None):
tex = r'\Im{%s}' % self.parenthesize(expr.args[0], PRECEDENCE['Func'])
return self._do_exponent(tex, exp)
def _print_Not(self, e):
from ..logic import Equivalent, Implies
if isinstance(e.args[0], Equivalent):
return self._print_Equivalent(e.args[0], r'\not\equiv')
if isinstance(e.args[0], Implies):
return self._print_Implies(e.args[0], r'\not\Rightarrow')
if e.args[0].is_Boolean:
return r'\neg (%s)' % self._print(e.args[0])
return r'\neg %s' % self._print(e.args[0])
def _print_LogOp(self, args, char):
arg = args[0]
if arg.is_Boolean and (not arg.is_Not and not arg.is_Atom):
tex = r'\left(%s\right)' % self._print(arg)
else:
tex = r'%s' % self._print(arg)
for arg in args[1:]:
if arg.is_Boolean and (not arg.is_Not and not arg.is_Atom):
tex += r' %s \left(%s\right)' % (char, self._print(arg))
else:
tex += r' %s %s' % (char, self._print(arg))
return tex
def _print_And(self, e):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, r'\wedge')
def _print_Or(self, e):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, r'\vee')
def _print_Xor(self, e):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, r'\veebar')
def _print_Implies(self, e, altchar=None):
return self._print_LogOp(e.args, altchar or r'\Rightarrow')
def _print_Equivalent(self, e, altchar=None):
args = sorted(e.args, key=default_sort_key)
return self._print_LogOp(args, altchar or r'\equiv')
def _print_conjugate(self, expr, exp=None):
tex = r'\overline{%s}' % self._print(expr.args[0])
if exp is not None:
return r'%s^{%s}' % (tex, exp)
return tex
def _print_polar_lift(self, expr, exp=None):
func = r'\operatorname{polar\_lift}'
arg = r'{\left (%s \right )}' % self._print(expr.args[0])
if exp is not None:
return r'%s^{%s}%s' % (func, exp, arg)
return r'%s%s' % (func, arg)
def _print_elliptic_k(self, expr, exp=None):
tex = r'\left(%s\right)' % self._print(expr.args[0])
if exp is not None:
return r'K^{%s}%s' % (exp, tex)
return r'K%s' % tex
def _print_elliptic_f(self, expr, exp=None):
tex = r'\left(%s\middle| %s\right)' % \
(self._print(expr.args[0]), self._print(expr.args[1]))
if exp is not None:
return r'F^{%s}%s' % (exp, tex)
return r'F%s' % tex
def _print_elliptic_e(self, expr, exp=None):
if len(expr.args) == 2:
tex = r'\left(%s\middle| %s\right)' % \
(self._print(expr.args[0]), self._print(expr.args[1]))
else:
tex = r'\left(%s\right)' % self._print(expr.args[0])
if exp is not None:
return r'E^{%s}%s' % (exp, tex)
return r'E%s' % tex
def _print_elliptic_pi(self, expr, exp=None):
if len(expr.args) == 3:
tex = r'\left(%s; %s\middle| %s\right)' % \
(self._print(expr.args[0]), self._print(expr.args[1]),
self._print(expr.args[2]))
else:
tex = r'\left(%s\middle| %s\right)' % \
(self._print(expr.args[0]), self._print(expr.args[1]))
if exp is not None:
return r'\Pi^{%s}%s' % (exp, tex)
return r'\Pi%s' % tex
def _print_uppergamma(self, expr, exp=None):
tex = r'\left(%s, %s\right)' % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r'\Gamma^{%s}%s' % (exp, tex)
return r'\Gamma%s' % tex
def _print_lowergamma(self, expr, exp=None):
tex = r'\left(%s, %s\right)' % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r'\gamma^{%s}%s' % (exp, tex)
return r'\gamma%s' % tex
def _print_expint(self, expr, exp=None):
tex = r'\left(%s\right)' % self._print(expr.args[1])
nu = self._print(expr.args[0])
if exp is not None:
return r'\operatorname{E}_{%s}^{%s}%s' % (nu, exp, tex)
return r'\operatorname{E}_{%s}%s' % (nu, tex)
def _print_fresnels(self, expr, exp=None):
tex = r'\left(%s\right)' % self._print(expr.args[0])
if exp is not None:
return r'S^{%s}%s' % (exp, tex)
return r'S%s' % tex
def _print_fresnelc(self, expr, exp=None):
tex = r'\left(%s\right)' % self._print(expr.args[0])
if exp is not None:
return r'C^{%s}%s' % (exp, tex)
return r'C%s' % tex
def _print_subfactorial(self, expr, exp=None):
tex = r'!%s' % self.parenthesize(expr.args[0], PRECEDENCE['Func'])
if exp is not None:
return r'%s^{%s}' % (tex, exp)
return tex
def _print_factorial(self, expr, exp=None):
tex = r'%s!' % self.parenthesize(expr.args[0], PRECEDENCE['Func'])
if exp is not None:
return r'%s^{%s}' % (tex, exp)
return tex
def _print_factorial2(self, expr, exp=None):
tex = r'%s!!' % self.parenthesize(expr.args[0], PRECEDENCE['Func'])
if exp is not None:
return r'%s^{%s}' % (tex, exp)
return tex
def _print_binomial(self, expr, exp=None):
tex = r'{\binom{%s}{%s}}' % (self._print(expr.args[0]),
self._print(expr.args[1]))
if exp is not None:
return r'%s^{%s}' % (tex, exp)
return tex
def _print_RisingFactorial(self, expr, exp=None):
n, k = expr.args
base = r'%s' % self.parenthesize(n, PRECEDENCE['Func'])
tex = r'{%s}^{\left(%s\right)}' % (base, self._print(k))
return self._do_exponent(tex, exp)
def _print_FallingFactorial(self, expr, exp=None):
n, k = expr.args
sub = r'%s' % self.parenthesize(k, PRECEDENCE['Func'])
tex = r'{\left(%s\right)}_{%s}' % (self._print(n), sub)
return self._do_exponent(tex, exp)
def _hprint_BesselBase(self, expr, exp, sym):
tex = r'%s' % sym
need_exp = False
if exp is not None:
if tex.find('^') == -1:
tex = r'%s^{%s}' % (tex, self._print(exp))
else:
need_exp = True
tex = r'%s_{%s}\left(%s\right)' % (tex, self._print(expr.order),
self._print(expr.argument))
if need_exp:
tex = self._do_exponent(tex, exp)
return tex
def _hprint_vec(self, vec):
if len(vec) == 0:
return ''
s = ''
for i in vec[:-1]:
s += '%s, ' % self._print(i)
s += self._print(vec[-1])
return s
def _print_besselj(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'J')
def _print_besseli(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'I')
def _print_besselk(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'K')
def _print_bessely(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'Y')
def _print_yn(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'y')
def _print_jn(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'j')
def _print_hankel1(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'H^{(1)}')
def _print_hankel2(self, expr, exp=None):
return self._hprint_BesselBase(expr, exp, 'H^{(2)}')
def _hprint_airy(self, expr, exp=None, notation=''):
tex = r'\left(%s\right)' % self._print(expr.args[0])
if exp is not None:
return r'%s^{%s}%s' % (notation, exp, tex)
return r'%s%s' % (notation, tex)
def _hprint_airy_prime(self, expr, exp=None, notation=''):
tex = r'\left(%s\right)' % self._print(expr.args[0])
if exp is not None:
return r'{%s^\prime}^{%s}%s' % (notation, exp, tex)
return r'%s^\prime%s' % (notation, tex)
def _print_airyai(self, expr, exp=None):
return self._hprint_airy(expr, exp, 'Ai')
def _print_airybi(self, expr, exp=None):
return self._hprint_airy(expr, exp, 'Bi')
def _print_airyaiprime(self, expr, exp=None):
return self._hprint_airy_prime(expr, exp, 'Ai')
def _print_airybiprime(self, expr, exp=None):
return self._hprint_airy_prime(expr, exp, 'Bi')
def _print_hyper(self, expr, exp=None):
tex = r'{{}_{%s}F_{%s}\left(\begin{matrix} %s \\ %s \end{matrix}' \
r'\middle| {%s} \right)}' % \
(self._print(len(expr.ap)), self._print(len(expr.bq)),
self._hprint_vec(expr.ap), self._hprint_vec(expr.bq),
self._print(expr.argument))
if exp is not None:
tex = r'{%s}^{%s}' % (tex, self._print(exp))
return tex
def _print_meijerg(self, expr, exp=None):
tex = r'{G_{%s, %s}^{%s, %s}\left(\begin{matrix} %s & %s \\' \
r'%s & %s \end{matrix} \middle| {%s} \right)}' % \
(self._print(len(expr.ap)), self._print(len(expr.bq)),
self._print(len(expr.bm)), self._print(len(expr.an)),
self._hprint_vec(expr.an), self._hprint_vec(expr.aother),
self._hprint_vec(expr.bm), self._hprint_vec(expr.bother),
self._print(expr.argument))
if exp is not None:
tex = r'{%s}^{%s}' % (tex, self._print(exp))
return tex
def _print_dirichlet_eta(self, expr, exp=None):
tex = r'\left(%s\right)' % self._print(expr.args[0])
if exp is not None:
return r'\eta^{%s}%s' % (self._print(exp), tex)
return r'\eta%s' % tex
def _print_zeta(self, expr, exp=None):