-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsym.py
2120 lines (1604 loc) · 87.6 KB
/
sym.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
# Convert between internal AST and SymPy expressions and write out LaTeX, native shorthand and Python code.
# Here be dragons! MUST REFACTOR AT SOME POINT FOR THE LOVE OF ALL THAT IS GOOD AND PURE!
from ast import literal_eval
from collections import OrderedDict
from functools import reduce
import re
import sympy as sp
from sympy.core.cache import clear_cache
from sympy.core.function import AppliedUndef as sp_AppliedUndef
from sast import AST # AUTO_REMOVE_IN_SINGLE_SCRIPT
import sxlat # AUTO_REMOVE_IN_SINGLE_SCRIPT
_SYM_MARK_PY_ASS_EQ = False # for testing to write extra information into python text representation of Eq() if is assignment
_TEX_SPACE = '\\ ' # explicit LaTeX space
_SYM_ASSUM_REDUCE = {(): ()} # cache to reduce extended lists of assumptions to single or a few assumptions which generated them
_SYM_USER_VARS = {} # flattened user vars {name: ast, ...}
_SYM_USER_FUNCS = set () # set of user funcs present {name, ...} - including hidden N and gamma and the like
_SYM_USER_ALL = {} # all funcs and vars dict, user funcs not in vars stored as AST.Null
_POST_SIMPLIFY = False # post-evaluation simplification
_PYS = True # Python S() escaping
_DOIT = True # expression doit()
_MUL_RATIONAL = False # products should lead with a rational fraction if one is present instead of absorbing into it
_STRICT_TEX = False # strict LaTeX formatting to assure copy-in ability of generated tex
_QUICK_MODE = False # quick input mode affects variable spacing in products
_None = object () # unique non-None None sentinel
class AST_Text (AST): # for displaying elements we do not know how to handle, only returned from SymPy processing, not passed in
op, is_text = '-text', True
def _init (self, tex = None, nat = None, py = None, spt = None):
self.tex, self.nat, self.py, self.spt = tex, nat, py, spt
AST.register_AST (AST_Text)
class EqAss (sp.Eq): pass # explicit assignment instead of equality comparison
class EqCmp (sp.Eq): pass # explicit equality comparison instead of assignment
class IdLambda (sp.Lambda): # identity lambda - having SymPy remap Lambda (y, y) to Lambda (_x, _x) is really annoying
def __new__ (cls, a, l, **kw):
self = sp.Expr.__new__(cls, sp.Tuple (l), l) # skip Lambda.__new__ to avoid creating identity function
return self
class NoEval (sp.Expr): # prevent any kind of evaluation on AST on instantiation or doit, args = (str (AST), sp.S.One)
is_number = False
free_symbols = set ()
def __new__ (cls, ast):
self = sp.Expr.__new__ (cls, str (ast))
self._ast = ast
return self
def doit (self, *args, **kw):
return self
def ast (self):
return AST (*literal_eval (self._ast)) if isinstance (self._ast, str) else self._ast # SymPy might have re-create this object using string argument
class Callable: # for wrapping SymPy concrete functions mapped to variables
def __init__ (self, ast, callable_):
self.ast = ast
self.callable_ = callable_
def __call__ (self, *args, **kw):
return self.callable_ (*args, **kw)
def _raise (exc):
raise exc
def _sympify (spt, sympify = sp.sympify, fallback = None): # try to sympify argument with optional fallback conversion function
try:
return sympify (spt)
except:
if fallback is True: # True for return original value
return spt
elif fallback is None:
raise
else:
try:
return fallback (spt)
except Exception as e:
raise e from None
def _free_symbols (spt): # extend sympy .free_symbols into standard python containers
if isinstance (spt, (None.__class__, bool, int, float, complex, str)):
pass # nop
elif isinstance (spt, (tuple, list, set, frozenset)):
return set ().union (*(_free_symbols (s) for s in spt))
elif isinstance (spt, slice):
return _free_symbols (spt.start).union (_free_symbols (spt.stop), _free_symbols (spt.step))
elif isinstance (spt, dict):
return set ().union (*(_free_symbols (s) for s in sum (spt.items (), ())))
else:
return getattr (spt, 'free_symbols', set ())
return set ()
def _simplify (spt): # extend sympy simplification into standard python containers
if isinstance (spt, (None.__class__, bool, int, float, complex, str)):
return spt
elif isinstance (spt, (tuple, list, set, frozenset)):
return spt.__class__ (_simplify (a) for a in spt)
elif isinstance (spt, slice):
return slice (_simplify (spt.start), _simplify (spt.stop), _simplify (spt.step))
elif isinstance (spt, dict):
return dict ((_simplify (k), _simplify (v)) for k, v in spt.items ())
if not isinstance (spt, (sp.Naturals.__class__, sp.Integers.__class__)): # these break on count_ops()
try:
spt2 = sp.simplify (spt)
if sp.count_ops (spt2) <= sp.count_ops (spt): # sometimes simplify doesn't
spt = spt2
except:
pass
return spt
def _doit (spt): # extend sympy .doit() into standard python containers
if isinstance (spt, (None.__class__, bool, int, float, complex, str)):
return spt
elif isinstance (spt, (tuple, list, set, frozenset)):
return spt.__class__ (_doit (a) for a in spt)
elif isinstance (spt, slice):
return slice (_doit (spt.start), _doit (spt.stop), _doit (spt.step))
elif isinstance (spt, dict):
return dict ((_doit (k), _doit (v)) for k, v in spt.items ())
try:
return spt.doit (deep = True)
except:
pass
return spt
def _subs (spt, subs): # extend sympy .subs() into standard python containers, subs = [(s1, d1), (s2, d2), ...]
if not subs:
return spt
if isinstance (spt, (tuple, list, set, frozenset, slice, dict)):
for i, (s, d) in enumerate (subs):
if s == spt:
return _subs (d, subs [:i] + subs [i + 1:])
if isinstance (spt, slice):
return slice (_subs (spt.start, subs), _subs (spt.stop, subs), _subs (spt.step, subs))
elif isinstance (spt, dict):
return dict ((_subs (k, subs), _subs (v, subs)) for k, v in spt.items ())
else: # isinstance (spt, (tuple, list, set, frozenset)):
return spt.__class__ (_subs (a, subs) for a in spt)
elif isinstance (spt, sp.Derivative) and isinstance (spt.args [0], sp_AppliedUndef): # do not subs derivative of appliedundef (d/dx (f (x, y))) to preserve info about variables
vars = set (spt.args [0].args)
spt = sp.Subs (spt, *zip (*filter (lambda sd: sd [0] in vars, subs)))
spt.doit = lambda self = spt, *args, **kw: self # disable doit because loses information
else:
try:
if isinstance (spt, (bool, int, float, complex)):
return sp.sympify (spt).subs (subs)
else:
return spt.subs (subs)
except:
pass
return spt
def _Mul (*args):
itr = iter (args)
res = next (itr)
for arg in itr:
try:
res = res * arg
except:
res = sp.sympify (res) * sp.sympify (arg)
return res
def _Pow (base, exp): # fix inconsistent sympy Pow (..., evaluate = True)
return base**exp
def _bool_or_None (v):
return None if v is None else bool (v)
def _fltoint (num):
return int (num) if isinstance (num, int) or num.is_integer () else num
def _trail_comma (obj):
return ',' if len (obj) == 1 else ''
def _spt_assumptions (spt):
return tuple (filter (lambda kv: kv [1] is not None and kv != ('commutative', True), sorted (spt._assumptions.items ())))
def _ast_is_neg (ast):
return ast.is_minus or ast.is_num_neg or (ast.is_mul and _ast_is_neg (ast.mul [0]))
def _ast_is_neg_nominus (ast):
return ast.is_num_neg or (ast.is_mul and _ast_is_neg (ast.mul [0]))
def _ast_is_top_ass_lhs (self, ast):
return (self.parent.is_ass and ast is self.parent.lhs and self.parents [-2].op in {None, ';'}) or \
(self.parent.is_comma and self.parents [-2].is_ass and self.parent is self.parents [-2].lhs and self.parents [-3].op in {None, ';'})
def _ast_eqcmp2ass (ast, parent = AST.Null):
if not isinstance (ast, AST):
return ast
if ast.is_cmp and not ast.is_cmp_explicit and ast.cmp.len == 1 and ast.cmp [0] [0] == '==' and (
parent.op in {None, ';', '<>', ',', '(', '[', '-', '!', '+', '*', '/', '^', '-log', '-sqrt', '-diff', '-diffp', '-mat', '-lamb', '-idx', '-set', '||', '^^', '&&', '-subs'} or
parent.is_attr_var or
(parent.is_attr_func and (ast is parent.obj or not ast.lhs.as_identifier)) or
(parent.op in {'-lim', '-sum', '-intg'} and ast is parent [1]) or
(parent.is_func and not ast.lhs.as_identifier)):
return AST ('=', _ast_eqcmp2ass (ast.lhs, ast), _ast_eqcmp2ass (ast.cmp [0] [1], ast))
return AST (*(_ast_eqcmp2ass (a, ast) for a in ast))
def _ast_slice_bounds (ast, None_ = AST.VarNull, allow1 = False):
if allow1 and not ast.start and not ast.step:
return (ast.stop or None_,)
return tuple (a or None_ for a in ((ast.start, ast.stop) if ast.step is None else (ast.start, ast.stop, ast.step)))
def _ast_followed_by_slice (ast, seq):
for i in range (len (seq)):
if seq [i] is ast:
for i in range (i + 1, len (seq)):
if seq [i].is_slice:
return True
elif not seq [i].is_var:
break
break
return False
def _ast_func_call (func, args, _ast2spt = None):
if _ast2spt is None:
_ast2spt = ast2spt
pyargs, pykw = AST.args2kwargs (args, _ast2spt)
return func (*pyargs, **pykw)
def _ast_has_open_differential (ast, istex):
if ast.is_differential or (not istex and
((ast.is_diff_d and (not ast.is_diff_dvdv and ast.dvs [-1] [-1] == 1)) or
(ast.is_subs_diff_d_ufunc and (not ast.expr.is_diff_dvdv and ast.expr.dvs [-1] [-1] == 1)))):
return True
elif istex and ast.is_div or ast.op in {'[', '|', '-log', '-sqrt', '-func', '-diff', '-intg', '-mat', '-set', '-dict', '-ufunc', '-subs'}: # specifically not checking '(' because that might be added by ast2tex/nat in subexpressions
return False
elif ast.op in {'.', '^', '-log', '-sqrt', '-lim', '-sum', '-diffp', '-lamb', '-idx'}:
return _ast_has_open_differential (ast [1], istex = istex)
return any (_ast_has_open_differential (a, istex = istex) if isinstance (a, AST) else False for a in (ast if ast.op is None else ast [1:]))
def _ast_subs2func (ast): # ast is '-subs'
func = ast.expr
if func.op in {'-diff', '-diffp'}:
func = func [1]
func = _SYM_USER_VARS.get (func.var, func)
if func.is_lamb:
vars = ast.subs [:func.vars.len]
if tuple (s.var for s, _ in vars) == func.vars:
return [AST ('=', s, d) for s, d in ast.subs [func.vars.len:]], tuple (d for _, d in vars)
elif func.is_ufunc_applied:
subs = []
vars = OrderedDict ((v, v) for v in func.vars)
for s, d in ast.subs:
if s.is_var_nonconst and vars.get (s) == s:
vars [s] = d
else:
subs.append (AST ('=', s, d))
vars = vars.values ()
if func.apply_argskw ((vars, ())):
return subs, vars
return [AST ('=', s, d) for s, d in ast.subs], None
#...............................................................................................
class ast2tex: # abstract syntax tree -> LaTeX text
def __init__ (self): self.parent = self.ast = None # pylint medication
def __new__ (cls, ast, retxlat = False):
def func_call (func, args):
return spt2ast (_ast_func_call (getattr (sp, func), args))
self = super ().__new__ (cls)
self.parents = [None]
self.parent = self.ast = AST.Null
astx = sxlat.xlat_funcs2asts (ast, sxlat.XLAT_FUNC2AST_TEX, func_call = func_call)
tex = self._ast2tex (astx)
return tex if not retxlat else (tex, (astx if astx != ast else None))
def _ast2tex (self, ast):
self.parents.append (self.ast)
self.parent = self.ast
self.ast = ast
tex = self._ast2tex_funcs [ast.op] (self, ast)
del self.parents [-1]
self.ast = self.parent
self.parent = self.parents [-1]
return tex
def _ast2tex_wrap (self, obj, curly = None, paren = None):
paren = (obj.op in paren) if isinstance (paren, set) else paren
curly = (obj.op in curly) if isinstance (curly, set) else curly
s = self._ast2tex (obj if not obj.is_slice or paren or not curly or obj.step is not None else AST ('-slice', obj.start, obj.stop, False)) if isinstance (obj, AST) else str (obj)
return f'\\left({s} \\right)' if paren else f'{{{s}}}' if curly else s
def _ast2tex_cmp (self, ast):
return f'{self._ast2tex_cmp_hs (ast.lhs)} {" ".join (f"{AST.Cmp.PY2TEX.get (r, r)} {self._ast2tex_cmp_hs (e)}" for r, e in ast.cmp)}'
def _ast2tex_curly (self, ast):
if ast.is_single_unit:
return f'{self._ast2tex (ast)}'
elif ast.op not in {',', '-slice'}:
return f'{{{self._ast2tex (ast)}}}'
else:
return f'{{\\left({self._ast2tex (ast)} \\right)}}'
def _ast2tex_paren (self, ast, ops = {}):
return self._ast2tex_wrap (ast, 0, not (ast.op in {'(', '-lamb'} or (ops and ast.op not in ops)))
def _ast2tex_paren_mul_exp (self, ast, ret_has = False, also = {'=', '<>', '+', '-slice', '||', '^^', '&&', '-or', '-and', '-not'}):
if ast.is_mul:
s, has = self._ast2tex_mul (ast, True)
else:
s, has = self._ast2tex (ast), ast.op in also
s = self._ast2tex_wrap (s, 0, has)
return (s, has) if ret_has else s
def _ast2tex_ass_hs (self, hs, lhs = True):
return self._ast2tex_wrap (hs, 0, hs.is_ass or hs.is_slice or
(lhs and (hs.is_piece or (hs.is_comma and (self.parent and not self.parent.is_scolon)))))
def _ast2tex_cmp_hs (self, hs):
return self._ast2tex_wrap (hs, 0, {'=', '<>', '-piece', '-slice', '-or', '-and', '-not'})
def _ast2tex_num (self, ast):
m, e = ast.num_mant_and_exp
return f'{m}{{e}}{{{e}}}' if e else m
def _ast2tex_var (self, ast):
if ast.is_var_null:
return '\\{' if self.parent.op in {None, ';'} else '{}'
texmulti = AST.Var.PY2TEXMULTI.get (ast.var)
if texmulti: # for stuff like "Naturals0"
return texmulti [0]
n, s = ast.text_and_tail_num
n = n.replace ('_', '\\_')
t = AST.Var.PY2TEX.get (n)
if s:
s = f'_{{{s}}}'
return \
f'{t or n}{s}' if not ast.diff_or_part_type else \
f'd{t or n}{s}' if ast.is_diff_any else \
f'\\partial' if ast.is_part_solo else \
f'\\partial{t}{s}' if t else \
f'\\partial {n}{s}' if n else \
f'\\partial'
def _ast2tex_attr (self, ast):
tex = sxlat.xlat_attr2tex (ast, self._ast2tex)
if tex is not None:
return tex
a = ast.attr.replace ('_', '\\_')
if ast.is_attr_func:
a = f'\\operatorname{{{a}}}\\left({self._ast2tex (AST.tuple2argskw (ast.args))} \\right)'
return f'{self._ast2tex_wrap (ast.obj, ast.obj.is_pow or ast.obj.is_subs_diff_ufunc, {"=", "<>", "#", ",", "-", "+", "*", "/", "-lim", "-sum", "-diff", "-intg", "-piece", "-slice", "||", "^^", "&&", "-or", "-and", "-not"})}.{a}'
def _ast2tex_minus (self, ast):
s = self._ast2tex_wrap (ast.minus, ast.minus.is_mul, {"=", "<>", "+", "-slice", "||", "^^", "&&", "-or", "-and", "-not"})
return f'-{{{s}}}' if s [:6] != '\\left(' and ast.minus.strip_fdpi.is_num_pos else f'-{s}'
def _ast2tex_add (self, ast):
terms = []
for n in ast.add:
not_first = n is not ast.add [0]
not_last = n is not ast.add [-1]
op = ' + '
if n.is_minus and not_first: # and n.minus.is_num_pos
op, n = ' - ', n.minus
s = self._ast2tex (n)
terms.extend ([op, self._ast2tex_wrap (s,
n.is_piece or (not_first and _ast_is_neg_nominus (n)) or (not_last and s [-1:] != ')' and (n.strip_mmls.is_intg or (n.is_mul and n.mul [-1].strip_mmls.is_intg))),
(n.is_piece and not_last) or n.op in {'=', '<>', '+', '-slice', '||', '^^', '&&', '-or', '-and', '-not'})]) # , '-subs'})])
return ''.join (terms [1:]).replace (' + -', ' - ')
def _ast2tex_mul (self, ast, ret_has = False):
t = []
p = None
has = False
for i, n in enumerate (ast.mul):
s = self._ast2tex_wrap (n, (p and _ast_is_neg (n)),
n.op in {'=', '<>', '+', '-slice', '||', '^^', '&&', '-or', '-and', '-not'} or (n.is_piece and n is not ast.mul [-1]))
if ((p and n.op in {'/', '-diff'} and p.op in {'#', '/'} and n.op != p.op) or
(n.strip_mmls.is_intg and n is not ast.mul [-1] and s [-1:] not in {'}', ')', ']'})):
s = f'{{{s}}}'
is_exp = i in ast.exp
paren_after_var = p and (s.startswith ('\\left(') and (p.tail_mul.is_var or p.tail_mul.is_attr_var))
if paren_after_var or (p and (
t [-1].endswith ('.') or
s [:1].isdigit () or
s.startswith ('\\left[') or
_ast_is_neg (n) or
n.is_var_null or
n.op in {'#', '-mat'} or
(s.startswith ('\\left(') and (
is_exp or
p.is_ufunc or
(p.strip_paren.is_lamb and n.is_paren_isolated) or
(p.is_diff_any_ufunc and not p.diff_any.apply_argskw (n.strip_paren1.as_ufunc_argskw)))) or
(t [-1] [-1:] not in {'}', ')', ']'} and p.tail_mul.is_sym_unqualified) or
p.strip_minus.op in {'-lim', '-sum', '-diff', '-intg', '-mat'} or
(p.tail_mul.is_var and (p.tail_mul.var == '_' or p.tail_mul.var in _SYM_USER_FUNCS)) or
(n.is_div and p.is_div) or
(n.is_attr and n.strip_attr.strip_paren.is_comma) or
(n.is_pow and (n.base.is_num_pos or n.base.strip_paren.is_comma)) or
(n.is_idx and (n.obj.is_idx or n.obj.strip_paren.is_comma)))):
v = p.tail_mul
a = _SYM_USER_VARS.get (v.var, AST.Null)
if paren_after_var and not (
is_exp or
(v.is_var and (
AST.UFunc.valid_implicit_args (n.strip_paren1.as_ufunc_argskw [0])) or
(n.is_diffp and n.diffp.is_paren and AST.UFunc.valid_implicit_args (n.diffp.paren.as_ufunc_argskw [0])) or
(a.is_ufunc and a.apply_argskw (n.strip_paren1.as_ufunc_argskw)))):
t.append (s)
if not t [-2].startswith ('{'):
t [-2] = f'{{{t [-2]}}}'
elif paren_after_var and not is_exp and n.is_paren_free and a.is_diff_any_ufunc and a.diff_any.apply_argskw (n.strip_paren1.as_ufunc_argskw):
t.append (s)
else:
t.extend ([' \\cdot ', s])
has = True
elif p and (
p.is_sqrt or
p.num_exp or
(_QUICK_MODE and p.is_attr_var and not s.startswith ('\\left(')) or
p.strip_minus.is_diff_or_part_any or
(not _QUICK_MODE and (
n.is_sym or
n.strip_pseudo.is_diff_or_part_any or
(not s.startswith ('{') and (
(not s.startswith ('\\left(') and
(p.tail_mul.strip_pseudo.is_var or p.tail_mul.is_attr_var) and
(n.strip_afpdpi.op in {'@', '-ufunc'} or (n.is_subs and n.expr.strip_afpdpi.op in {'@', '-ufunc'}))) or
(s [:6] not in {'\\left(', '\\left['} and (
p.is_var_long or
n.is_func_pseudo or
(n.strip_afpdpi.is_var_long and t [-1] [-7:] not in {'\\right)', '\\right]'})))))))):
t.extend ([_TEX_SPACE, s])
elif p:
t.extend ([' ', s])
else:
t.append (s)
p = n
return (''.join (t), has) if ret_has else ''.join (t)
def _ast2tex_div (self, ast):
false_diff = (ast.numer.base.is_diff_or_part_solo and ast.numer.exp.is_num_pos_int) if ast.numer.is_pow else \
(ast.numer.mul.len == 2 and ast.numer.mul [1].is_var and ast.numer.mul [0].is_pow and ast.numer.mul [0].base.is_diff_or_part_solo and ast.numer.mul [0].exp.strip_curly.is_num_pos_int) if ast.numer.is_mul else \
ast.numer.is_diff_or_part_solo
return f'\\frac{{{self._ast2tex_wrap (ast.numer, 0, ast.numer.is_slice or false_diff)}}}{{{self._ast2tex_wrap (ast.denom, 0, {"-slice"})}}}'
def _ast2tex_pow (self, ast, trighpow = True):
b = self._ast2tex_wrap (ast.base, {'-mat'}, not (ast.base.op in {'@', '.', '"', '(', '[', '|', '-log', '-func', '-mat', '-lamb', '-idx', '-set', '-dict', '-ufunc'} or ast.base.is_num_pos))
p = self._ast2tex_curly (ast.exp)
if trighpow and ast.base.is_func_trigh_noninv and ast.exp.is_num and ast.exp.num != '-1': # and ast.exp.is_single_unit
i = len (ast.base.func) + (15 if ast.base.func in {'sech', 'csch'} else 1)
return f'{b [:i]}^{p}{b [i:]}'
return f'{b}^{p}'
def _ast2tex_log (self, ast):
if ast.base is None:
return f'\\ln{{\\left({self._ast2tex (ast.log)} \\right)}}'
else:
return f'\\log_{self._ast2tex_curly (ast.base)}{{\\left({self._ast2tex (ast.log)} \\right)}}'
_rec_tailnum = re.compile (r'^(.+)(?<![\d_])(\d*)$')
def _ast2tex_func (self, ast):
if ast.is_func_trigh:
if ast.func [0] != 'a':
n = f'\\operatorname{{{ast.func}}}' if ast.func in {'sech', 'csch'} else f'\\{ast.func}'
elif ast.func in {'asech', 'acsch'}:
n = f'\\operatorname{{{ast.func [1:]}}}^{{-1}}'
else:
n = f'\\{ast.func [1:]}^{{-1}}'
return f'{n}{{\\left({self._ast2tex (AST.tuple2argskw (ast.args))} \\right)}}'
tex = sxlat.xlat_func2tex (ast, self._ast2tex)
if tex is not None:
return tex
if ast.func in AST.Func.TEX:
func = f'\\{ast.func}'
elif ast.func in {AST.Func.NOREMAP, AST.Func.NOEVAL}:
func = ast.func.replace (AST.Func.NOEVAL, '\\%')
if ast.args [0].op in {'#', '@', '(', '[', '|', '-func', '-mat', '-lamb', '-set', '-dict'}:
return f'{func}{self._ast2tex (AST.tuple2argskw (ast.args))}'
elif ast.func not in AST.Func.PY:
m = self._rec_tailnum.match (ast.func)
func, sub = m.groups () if m else (ast.func, None)
func = func.replace ('_', '\\_')
func = f'\\operatorname{{{func}_{{{sub}}}}}' if sub else f'\\operatorname{{{func}}}'
else:
func = ast.func.replace ('_', '\\_')
func = f'\\operatorname{{{AST.Var.GREEK2TEX.get (ast.func, func)}}}'
return f'{func}{{\\left({self._ast2tex (AST.tuple2argskw (ast.args))} \\right)}}'
def _ast2tex_lim (self, ast):
s = self._ast2tex_wrap (ast.to, False, ast.to.is_slice) if ast.dir is None else (self._ast2tex_pow (AST ('^', ast.to, AST.Zero), trighpow = False) [:-1] + ast.dir)
return f'\\lim_{{{self._ast2tex (ast.lvar)} \\to {s}}} {self._ast2tex_paren_mul_exp (ast.lim)}'
def _ast2tex_sum (self, ast):
return f'\\sum_{{{self._ast2tex (ast.svar)} = {self._ast2tex (ast.from_)}}}^{self._ast2tex_curly (ast.to)} {self._ast2tex_paren_mul_exp (ast.sum)}' \
def _ast2tex_diff (self, ast):
if ast.diff.is_var and not ast.diff.is_diff_or_part:
top = self._ast2tex (ast.diff)
topp = f' {top}'
side = ''
else:
top = topp = ''
side = self._ast2tex_wrap (ast.diff, 0, ast.diff.op not in {'(', '-lamb'})
ds = set ()
dp = 0
for v, p in ast.dvs:
ds.add (v)
dp += p
if not ds:
return f'\\frac{{d{top}}}{{}}{side}'
is_d = len (ds) <= 1 and ast.is_diff_d
if is_d:
diff = _SYM_USER_VARS.get (ast.diff.var, ast.diff)
if diff.is_lamb:
diff = diff.lamb
is_d = len (diff.free_vars) <= 1
if is_d:
dvs = " ".join (self._ast2tex (AST ('@', f'd{v}') if p == 1 else AST ('^', AST ('@', f'd{v}'), AST ('#', p))) for v, p in ast.dvs)
return f'\\frac{{d{top if dp == 1 else f"^{dp}{topp}"}}}{{{dvs}}}{side}'
else:
dvs = " ".join (self._ast2tex (AST ('@', f'partial{v}') if p == 1 else AST ('^', AST ('@', f'partial{v}'), AST ('#', p))) for v, p in ast.dvs)
return f'\\frac{{\\partial{topp if dp == 1 else f"^{dp}{topp}"}}}{{{dvs}}}{side}'
def _ast2tex_intg (self, ast):
if ast.intg is None:
intg = ' '
else:
curly = ast.intg.op in {"-diff", "-slice", "||", "^^", "&&", "-or", "-and", "-not"} or ast.intg.tail_mul.op in {"-lim", "-sum"}
intg = self._ast2tex_wrap (ast.intg, curly, {"=", "<>"})
intg = f' {{{intg}}} ' if not curly and _ast_has_open_differential (ast.intg, istex = True) else f' {intg} '
if ast.from_ is None:
return f'\\int{intg}\\ {self._ast2tex (ast.dv)}'
else:
return f'\\int_{self._ast2tex_curly (ast.from_)}^{self._ast2tex_curly (ast.to)}{intg}\\ {self._ast2tex (ast.dv)}'
def _ast2tex_idx (self, ast):
obj = self._ast2tex_wrap (ast.obj,
ast.obj.op in {"^", "-slice"} or ast.obj.is_subs_diff_ufunc or (ast.obj.is_var and ast.obj.var in _SYM_USER_FUNCS),
ast.obj.is_num_neg or ast.obj.op in {"=", "<>", ",", "-", "+", "*", "/", "-lim", "-sum", "-diff", "-intg", "-piece", "||", "^^", "&&", "-or", "-and", "-not"})
idx = '[' if ast.idx.len and ast.idx [0].is_var_null else f'\\left[{self._ast2tex (AST.tuple2ast (ast.idx))} \\right]'
return f'{obj}{idx}'
def _ast2tex_ufunc (self, ast):
user = _SYM_USER_ALL.get (ast.ufunc)
is_top_ass = _ast_is_top_ass_lhs (self, ast)
if (not ast.ufunc or
(_STRICT_TEX and
((ast.is_ufunc_explicit and is_top_ass) or
((user and (not user.is_ufunc or not user.apply_argskw ((ast.vars, ast.kw))) or
(not user and not AST.UFunc.valid_implicit_args (ast.vars))) and
not is_top_ass)))):
pre = '?'
else:
pre = ''
name = self._ast2tex (AST ("@", ast.ufunc)) if ast.ufunc else ""
args = ", ".join (tuple (self._ast2tex (v) for v in ast.vars) + tuple (" = ".join ((k.replace ("_", "\\_"), self._ast2tex_wrap (a, 0, a.is_comma))) for k, a in ast.kw))
return f'{pre}{name}\\left({args} \\right)'
def _ast2tex_subs (self, ast):
subs, vars = _ast_subs2func (ast)
if len (subs) == ast.subs.len:
expr = self._ast2tex (ast.expr)
else:
expr = f'{self._ast2tex (ast.expr)}\\left({", ".join (self._ast2tex (v) for v in vars)} \\right)'
if not subs:
return expr
if len (subs) == 1:
subs = self._ast2tex (subs [0])
else:
subs = '\\substack{' + ' \\\\ '.join (self._ast2tex (s) for s in subs) + '}'
return f'\\left. {expr} \\right|_{{{subs}}}'
_ast2tex_funcs = {
';' : lambda self, ast: ';\\: '.join (self._ast2tex (a) for a in ast.scolon),
'=' : lambda self, ast: f'{self._ast2tex_ass_hs (ast.lhs)} = {self._ast2tex_ass_hs (ast.rhs, False)}',
'<>' : _ast2tex_cmp,
'#' : _ast2tex_num,
'@' : _ast2tex_var,
'.' : _ast2tex_attr,
'"' : lambda self, ast: '\\text{' + repr (ast.str_).replace ('}', '\\}') + '}',
',' : lambda self, ast: f'{", ".join (self._ast2tex (c) for c in ast.comma)}{_trail_comma (ast.comma)}',
'(' : lambda self, ast: '(' if ast.paren.is_var_null else self._ast2tex_wrap (ast.paren, 0, 1), # not ast.paren.is_lamb),
'[' : lambda self, ast: '[' if ast.brack.len == 1 and ast.brack [0].is_var_null else f'\\left[{", ".join (self._ast2tex (b) for b in ast.brack)} \\right]',
'|' : lambda self, ast: '|' if ast.abs.is_var_null else f'\\left|{self._ast2tex (ast.abs)} \\right|',
'-' : _ast2tex_minus,
'!' : lambda self, ast: self._ast2tex_wrap (ast.fact, {'^'}, (ast.fact.op not in {'#', '@', '.', '"', '(', '[', '|', '!', '^', '-func', '-mat', '-idx', '-set', '-dict', '-sym'} or ast.fact.is_num_neg)) + '!',
'+' : _ast2tex_add,
'*' : _ast2tex_mul,
'/' : _ast2tex_div,
'^' : _ast2tex_pow,
'-log' : _ast2tex_log,
'-sqrt' : lambda self, ast: f'\\sqrt{{{self._ast2tex_wrap (ast.rad, 0, {",", "-slice"})}}}' if ast.idx is None else f'\\sqrt[{self._ast2tex (ast.idx)}]{{{self._ast2tex_wrap (ast.rad, 0, {",", "-slice"})}}}',
'-func' : _ast2tex_func,
'-lim' : _ast2tex_lim,
'-sum' : _ast2tex_sum,
'-diff' : _ast2tex_diff,
'-diffp': lambda self, ast: self._ast2tex_wrap (ast.diffp, ast.diffp.is_subs_diff_any_ufunc, ast.diffp.is_num_neg or ast.diffp.op in {"=", "<>", "-", "+", "*", "/", "^", "-sqrt", "-lim", "-sum", "-diff", "-intg", "-piece", "-slice", "||", "^^", "&&", "-or", "-and", "-not"}) + "'" * ast.count,
'-intg' : _ast2tex_intg,
'-mat' : lambda self, ast: '\\begin{bmatrix} ' + r' \\ '.join (' & '.join (self._ast2tex_wrap (e, 0, e.is_slice) for e in row) for row in ast.mat) + f'{" " if ast.mat else ""}\\end{{bmatrix}}',
'-piece': lambda self, ast: '\\begin{cases} ' + r' \\ '.join (f'{self._ast2tex_wrap (p [0], 0, {"=", "<>", ",", "-slice"})} & \\text{{otherwise}}' if p [1] is True else f'{self._ast2tex_wrap (p [0], 0, {"=", "<>", ",", "-slice"})} & \\text{{for}}\\: {self._ast2tex_wrap (p [1], 0, {"-slice"})}' for p in ast.piece) + ' \\end{cases}',
'-lamb' : lambda self, ast: f'\\left({self._ast2tex (AST ("@", ast.vars [0]) if ast.vars.len == 1 else AST ("(", (",", tuple (("@", v) for v in ast.vars))))} \\mapsto {self._ast2tex (ast.lamb)} \\right)',
'-idx' : _ast2tex_idx,
'-slice': lambda self, ast: self._ast2tex_wrap ('{:}'.join (self._ast2tex_wrap (a, a and _ast_is_neg (a), a and a.op in {'=', ',', '-slice'}) for a in _ast_slice_bounds (ast, '')), 0, not ast.start and self.parent.is_comma and ast is self.parent.comma [0] and self.parents [-2].is_ass and self.parent is self.parents [-2].rhs),
'-set' : lambda self, ast: f'\\left\\{{{", ".join (self._ast2tex_wrap (c, 0, c.is_slice) for c in ast.set)} \\right\\}}' if ast.set else '\\emptyset',
'-dict' : lambda self, ast: f'\\left\\{{{", ".join (f"{self._ast2tex_wrap (k, 0, k.is_slice)}{{:}} {self._ast2tex_wrap (v, 0, v.is_slice)}" for k, v in ast.dict)} \\right\\}}',
'||' : lambda self, ast: ' \\cup '.join (self._ast2tex_wrap (a, 0, a.op in {'=', '<>', ',', '-slice', '-or', '-and', '-not'} or (a.is_piece and a is not ast.union [-1])) for a in ast.union),
'^^' : lambda self, ast: ' \\ominus '.join (self._ast2tex_wrap (a, 0, a.op in {'=', '<>', ',', '-slice', '||', '-or', '-and', '-not'} or (a.is_piece and a is not ast.sdiff [-1])) for a in ast.sdiff),
'&&' : lambda self, ast: ' \\cap '.join (self._ast2tex_wrap (a, 0, a.op in {'=', '<>', ',', '-slice', '||', '^^', '-or', '-and', '-not'} or (a.is_piece and a is not ast.xsect [-1])) for a in ast.xsect),
'-or' : lambda self, ast: ' \\vee '.join (self._ast2tex_wrap (a, 0, a.op in {'=', ',', '-slice'} or (a.is_piece and a is not ast.or_ [-1])) for a in ast.or_),
'-and' : lambda self, ast: ' \\wedge '.join (self._ast2tex_wrap (a, 0, a.op in {'=', ',', '-slice', '-or'} or (a.is_piece and a is not ast.and_ [-1])) for a in ast.and_),
'-not' : lambda self, ast: f'\\neg\\ {self._ast2tex_wrap (ast.not_, 0, ast.not_.op in {"=", ",", "-slice", "-or", "-and"})}',
'-ufunc': _ast2tex_ufunc,
'-subs' : _ast2tex_subs,
'-sym' : lambda self, ast: f'\\${self._ast2tex (AST ("@", ast.sym)) if ast.sym else ""}' + ('' if ast.is_sym_unqualified else f'\\left({", ".join (tuple (f"{k} = {self._ast2tex_wrap (a, 0, a.is_comma)}" for k, a in ast.kw))} \\right)'),
'-text' : lambda self, ast: ast.tex,
}
#...............................................................................................
class ast2nat: # abstract syntax tree -> native text
def __init__ (self): self.parent = self.ast = None # pylint droppings
def __new__ (cls, ast, retxlat = False):
self = super ().__new__ (cls)
self.parents = [None]
self.parent = self.ast = AST.Null
astx = sxlat.xlat_funcs2asts (ast, sxlat.XLAT_FUNC2AST_NAT)
nat = self._ast2nat (astx)
return nat if not retxlat else (nat, (astx if astx != ast else None))
def _ast2nat (self, ast):
self.parents.append (self.ast)
self.parent = self.ast
self.ast = ast
nat = self._ast2nat_funcs [ast.op] (self, ast)
del self.parents [-1]
self.ast = self.parent
self.parent = self.parents [-1]
return nat
def _ast2nat_wrap (self, obj, curly = None, paren = None):
isast = isinstance (obj, AST)
paren = (obj.op in paren) if isinstance (paren, set) else paren
curly = ((obj.op in curly) if isinstance (curly, set) else curly) and not (isast and obj.is_abs)
s = self._ast2nat (obj if not obj.is_slice or paren or not curly or obj.step is not None else AST ('-slice', obj.start, obj.stop, False)) if isast else str (obj)
return f'({s})' if paren else f'{{{s}}}' if curly else s
def _ast2nat_curly (self, ast, ops = {}):
if ast.is_slice:
ast = AST ('(', ast)
return self._ast2nat_wrap (ast, ops if ops else (ast.is_div or not ast.is_single_unit or (ast.is_var and ast.var in AST.Var.PY2TEX)))
def _ast2nat_paren (self, ast, ops = {}):
return self._ast2nat_wrap (ast, 0, not (ast.is_paren or (ops and ast.op not in ops)))
def _ast2nat_curly_mul_exp (self, ast, ret_has = False, also = {}):
if ast.is_mul:
s, has = self._ast2nat_mul (ast, True)
else:
s, has = self._ast2nat (ast), False
has = has or ((ast.op in also) if isinstance (also, set) else also)
s = self._ast2nat_wrap (s, has, ast.is_slice)
return (s, has) if ret_has else s
def _ast2nat_ass_hs (self, hs, lhs = True):
return self._ast2nat_wrap (hs, 0, hs.is_ass or hs.is_slice or (lhs and (hs.op in {'-piece', '-lamb'}) or (hs.is_comma and (self.parent and not self.parent.is_scolon))) or \
(not lhs and hs.is_lamb and self.parent.op in {'-set', '-dict'}))
def _ast2nat_cmp_hs (self, hs):
return self._ast2nat_wrap (hs, 0, {'=', '<>', '-piece', '-lamb', '-slice', '-or', '-and', '-not'})
def _ast2nat_cmp (self, ast):
return f'{self._ast2nat_cmp_hs (ast.lhs)} {" ".join (f"{AST.Cmp.PYFMT.get (r, r)} {self._ast2nat_cmp_hs (e)}" for r, e in ast.cmp)}'
def _ast2nat_attr (self, ast):
obj = self._ast2nat_wrap (ast.obj, ast.obj.is_pow or ast.obj.is_subs_diff_ufunc, {"=", "<>", "#", ",", "-", "+", "*", "/", "-lim", "-sum", "-diff", "-intg", "-piece", "-lamb", "-slice", "||", "^^", "&&", "-or", "-and", "-not"})
if ast.is_attr_var:
return f'{obj}.{ast.attr}'
else:
return f'{obj}.{ast.attr}({self._ast2nat (AST.tuple2argskw (ast.args))})'
def _ast2nat_minus (self, ast):
s = self._ast2nat_wrap (ast.minus, ast.minus.op in {"*", "-diff", "-piece", "||", "^^", "&&", "-or", "-and"}, {"=", "<>", "+", "-lamb", "-slice", "-not"})
return f'-{{{s}}}' if s [:1] not in {'{', '('} and ast.minus.strip_fdpi.is_num_pos else f'-{s}'
def _ast2nat_str (self, ast):
s = repr (ast.str_)
return s if s [0] != "'" else f' {s}'
def _ast2nat_add (self, ast):
terms = []
for n in ast.add:
not_first = n is not ast.add [0]
not_last = n is not ast.add [-1]
op = ' + '
if n.is_minus and not_first: # and n.minus.is_num_pos
op, n = ' - ', n.minus
terms.extend ([op, self._ast2nat_wrap (n,
n.is_piece or (not_first and _ast_is_neg_nominus (n)) or ((n.strip_mmls.is_intg or (n.is_mul and n.mul [-1].strip_mmls.is_intg)) and not_last),
(n.op in ('-piece', '-lamb') and not_last) or n.op in {'=', '<>', '+', '-lamb', '-slice', '||', '^^', '&&', '-or', '-and', '-not'})])
return ''.join (terms [1:]).replace (' + -', ' - ')
def _ast2nat_mul (self, ast, ret_has = False):
t = []
p = None
has = False
for i, n in enumerate (ast.mul):
s = self._ast2nat_wrap (n,
n.op in {'+', '-piece', '-lamb', '-slice', '||', '^^', '&&', '-or', '-and', '-not'} or
(p and (
_ast_is_neg (n) or
(p.is_div and (p.denom.is_intg or (p.denom.is_mul and p.denom.mul [-1].is_intg)) and n.is_diff and n.diff.is_var and n.dvs [-1] [1] == 1))),
n.op in {'=', '<>'})
if n.strip_mmls.is_intg and n is not ast.mul [-1] and s [-1:] not in {'}', ')', ']'}:
s = f'{{{s}}}'
is_exp = i in ast.exp
paren_after_var = p and (s.startswith ('(') and (p.tail_mul.is_var or p.tail_mul.is_attr_var))
if paren_after_var or (p and (
s.startswith ('[') or
s [:1].isdigit () or
t [-1] [-1:] == '.' or
n.is_num or
n.is_var_null or
n.op in {'/', '-diff'} or
(s.startswith ('(') and (
is_exp or
p.is_ufunc or
(p.strip_paren.is_lamb and n.is_paren_isolated) or
(p.is_diff_any_ufunc and not p.diff_any.apply_argskw (n.strip_paren1.as_ufunc_argskw)))) or
n.strip_attrdp.is_subs_diff_ufunc or
(t [-1] [-1:] not in {'}', ')', ']'} and p.tail_mul.is_sym_unqualified) or
p.strip_minus.op in {'/', '-lim', '-sum', '-diff', '-intg'} or
(n.is_pow and (n.base.strip_paren.is_comma or n.base.is_num_pos)) or
(n.is_attr and n.strip_attr.strip_paren.is_comma) or
(n.is_idx and (n.obj.is_idx or n.obj.strip_paren.is_comma)) or
(p.has_tail_lambda and n is ast.mul [-1] and t [-1] [-6:] == 'lambda') or
(p.tail_mul.is_var and p.tail_mul.var in _SYM_USER_FUNCS) or
s [:1] in {'e', 'E'} and t [-1] [-1].isdigit ())):
v = p.tail_mul
a = _SYM_USER_VARS.get (v.var, AST.Null)
if paren_after_var and not (
is_exp or
(v.is_var and (
AST.UFunc.valid_implicit_args (n.strip_paren1.as_ufunc_argskw [0])) or
(n.is_diffp and n.diffp.is_paren and AST.UFunc.valid_implicit_args (n.diffp.paren.as_ufunc_argskw [0])) or
(a.is_ufunc and a.apply_argskw (n.strip_paren1.as_ufunc_argskw)))):
t.append (f'{{{s}}}')
elif paren_after_var and not is_exp and n.is_paren_free and a.is_diff_any_ufunc and a.diff_any.apply_argskw (n.strip_paren1.as_ufunc_argskw):
t.append (s)
else:
t.extend ([' * ', s])
has = True
elif p and (
p.is_diff_or_part_solo or
n.op not in {'#', '|', '^'} or
p.op not in {'#', '|'}):
t.extend ([' ', s])
else:
t.append (s)
p = n
return (''.join (t), has) if ret_has else ''.join (t)
def _ast2nat_div (self, ast):
false_diff = (ast.numer.base.is_diff_or_part_solo and ast.numer.exp.is_num_pos_int) if ast.numer.is_pow else \
(ast.numer.mul.len == 2 and ast.numer.mul [1].is_var and ast.numer.mul [0].is_pow and ast.numer.mul [0].base.is_diff_or_part_solo and ast.numer.mul [0].exp.strip_curly.is_num_pos_int) if ast.numer.is_mul else \
ast.numer.is_diff_or_part_solo
n, ns = (self._ast2nat_wrap (ast.numer, 1), True) if _ast_is_neg (ast.numer) or (ast.numer.is_mul and ast.numer.mul [-1].op in {'-lim', '-sum'}) else \
(self._ast2nat_wrap (ast.numer, 0, 1), True) if (ast.numer.is_slice or false_diff) else \
self._ast2nat_curly_mul_exp (ast.numer, True, {'=', '<>', '+', '/', '-lim', '-sum', '-diff', '-intg', '-piece', '-lamb', '||', '^^', '&&', '-or', '-and', '-not'})
d, ds = (self._ast2nat_wrap (ast.denom, 1), True) if ((_ast_is_neg (ast.denom) and ast.denom.strip_minus.is_div) or ast.denom.strip_minus.is_subs_diff_ufunc or (ast.denom.is_mul and ast.denom.mul [0].is_subs_diff_ufunc)) else \
(self._ast2nat_wrap (ast.denom, 0, 1), True) if ast.denom.is_slice else \
self._ast2nat_curly_mul_exp (ast.denom, True, {'=', '<>', '+', '/', '-lim', '-sum', '-diff', '-intg', '-piece', '-lamb', '||', '^^', '&&', '-or', '-and', '-not'})
s = ns or ds or ast.numer.strip_minus.op not in {'#', '@'} or ast.denom.strip_minus.op not in {'#', '@'}
return f'{n}{" / " if s else "/"}{d}'
def _ast2nat_pow (self, ast, trighpow = True):
b = self._ast2nat_wrap (ast.base, 0, not (ast.base.op in {'@', '.', '"', '(', '[', '|', '-func', '-mat', '-idx', '-set', '-dict', '-ufunc'} or ast.base.is_num_pos))
p = self._ast2nat_wrap (ast.exp,
ast.exp.op in {'<>', '=', '+', '-lamb', '-slice', '-not'} or
ast.exp.strip_minus.op in {'*', '/', '-lim', '-sum', '-diff', '-intg', '-piece', '||', '^^', '&&', '-or', '-and'} or
ast.exp.strip_minus.is_subs_diff_ufunc,
{","})
if trighpow and ast.base.is_func_trigh_noninv and ast.exp.is_num and ast.exp.num != '-1': # and ast.exp.is_single_unit
i = len (ast.base.func)
return f'{b [:i]}**{p}{b [i:]}'
return f'{b}**{p}'
def _ast2nat_log (self, ast):
if ast.base is None:
return f'ln({self._ast2nat (ast.log)})'
else:
return f'\\log_{self._ast2nat_curly (ast.base)}({self._ast2nat (ast.log)})'
def _ast2nat_lim (self, ast):
s = self._ast2nat_wrap (ast.to, (ast.to.is_ass and ast.to.rhs.is_lamb) or ast.to.op in {'-lamb', '-piece'}, ast.to.is_slice) if ast.dir is None else (self._ast2nat_pow (AST ('^', ast.to, AST.Zero), trighpow = False) [:-1] + ast.dir)
return f'\\lim_{{{self._ast2nat (ast.lvar)} \\to {s}}} {self._ast2nat_curly_mul_exp (ast.lim, False, ast.lim.op in {"=", "<>", "+", "-piece", "-lamb", "-slice", "||", "^^", "&&", "-or", "-and", "-not"} or ast.lim.is_mul_has_abs)}'
def _ast2nat_sum (self, ast):
return f'\\sum_{{{self._ast2nat (ast.svar)} = {self._ast2nat_curly (ast.from_, {"-lamb", "-piece"})}}}^{self._ast2nat_curly (ast.to)} {self._ast2nat_curly_mul_exp (ast.sum, False, ast.sum.op in {"=", "<>", "+", "-piece", "-lamb", "-slice", "||", "^^", "&&", "-or", "-and", "-not"} or ast.sum.is_mul_has_abs)}'
def _ast2nat_diff (self, ast):
if ast.diff.is_var and not ast.diff.is_diff_or_part:
top = self._ast2nat (ast.diff)
topp = f' {top}'
side = ''
else:
top = topp = ''
side = f' {self._ast2nat_paren (ast.diff)}'
dp = sum (dv [1] for dv in ast.dvs)
dv = (lambda v: AST ('@', f'd{v}')) if ast.is_diff_d else (lambda v: AST ('@', f'partial{v}'))
dvs = " ".join (self._ast2nat (dv (v) if p == 1 else AST ('^', dv (v), AST ('#', p))) for v, p in ast.dvs)
return f'{ast.d}{top if dp == 1 else f"**{dp}{topp}"} / {dvs}{side}'
def _ast2nat_intg (self, ast):
if ast.intg is None:
intg = ' '
else:
curly = (ast.intg.op in {"-piece", "-lamb", "-slice", "||", "^^", "&&", "-or", "-and", "-not"} or
ast.intg.is_mul_has_abs or
ast.intg.tail_mul.op in {"-lim", "-sum"} or
(ast.intg.tail_mul.is_var and ast.intg.tail_mul.var in _SYM_USER_FUNCS))
intg = self._ast2nat_wrap (ast.intg, curly, {"=", "<>"})
intg = f' {{{intg}}} ' if not curly and _ast_has_open_differential (ast.intg, istex = False) else f' {intg} '
if ast.from_ is None:
return f'\\int{intg}{self._ast2nat (ast.dv)}'
else:
return f'\\int_{self._ast2nat_curly (ast.from_)}^{self._ast2nat_curly (ast.to)}{intg}{self._ast2nat (ast.dv)}'
def _ast2nat_mat (self, ast):
if not ast.rows:
return '\\[]'
elif ast.is_mat_column and not any (r [0].is_brack for r in ast.mat): # (ast.rows > 1 or not ast.mat [0] [0].is_brack):
return f"\\[{', '.join (self._ast2nat (row [0]) for row in ast.mat)}]"
else:
return f"""\\[{', '.join (f'[{", ".join (self._ast2nat (e) for e in row)}]' for row in ast.mat)}]"""
def _ast2nat_idx (self, ast):
obj = self._ast2nat_wrap (ast.obj,