forked from benruijl/symbolica
-
Notifications
You must be signed in to change notification settings - Fork 0
/
symbolica.pyi
3053 lines (2395 loc) · 108 KB
/
symbolica.pyi
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
"""
Symbolica Python API.
"""
from __future__ import annotations
from enum import Enum
from typing import Any, Callable, overload, Iterator, Optional, Sequence, Tuple, List
from decimal import Decimal
def get_version() -> str:
"""Get the current Symbolica version."""
def is_licensed() -> bool:
"""Check if the current Symbolica instance has a valid license key set."""
def set_license_key(key: str) -> None:
"""Set the Symbolica license key for this computer. Can only be called before calling any other Symbolica functions."""
def request_hobbyist_license(name: str, email: str) -> None:
"""Request a key for **non-professional** use for the user `name`, that will be sent to the e-mail address `email`."""
def request_trial_license(name: str, email: str, company: str) -> None:
"""Request a key for a trial license for the user `name` working at `company`, that will be sent to the e-mail address `email`."""
def request_sublicense(name: str, email: str, company: str, super_licence: str) -> None:
"""Request a sublicense key for the user `name` working at `company` that has the site-wide license `super_license`.
The key will be sent to the e-mail address `email`."""
def get_license_key(email: str) -> str:
"""Get the license key for the account registered with the provided email address."""
class AtomType(Enum):
"""Specifies the type of the atom."""
Num = 1
Var = 2
Fn = 3
Add = 4
Mul = 5
Pow = 6
class AtomTree:
"""
A Python representation of a Symbolica expression.
The type of the atom is provided in `atom_type`.
The `head` contains the string representation of:
- a number if the type is `Num`
- the variable if the type is `Var`
- the function name if the type is `Fn`
- otherwise it is `None`.
The tail contains the child atoms:
- the summand for type `Add`
- the factors for type `Mul`
- the base and exponent for type `Pow`
- the function arguments for type `Fn`
"""
atom_type: AtomType
""" The type of this atom."""
head: Optional[str]
"""The string data of this atom."""
tail: List[AtomTree]
"""The list of child atoms of this atom."""
class Expression:
"""
A Symbolica expression.
Supports standard arithmetic operations, such
as addition and multiplication.
Examples
--------
>>> x = Expression.symbol('x')
>>> e = x**2 + 2 - x + 1 / x**4
>>> print(e)
"""
E: Expression
"""Euler's number `e`."""
PI: Expression
"""The mathematical constant `π`."""
I: Expression
"""The mathematical constant `i`, where `i^2 = -1`."""
COEFF: Expression
"""The built-in function that convert a rational polynomials to a coefficient."""
COS: Expression
"""The built-in cosine function."""
SIN: Expression
"""The built-in sine function."""
EXP: Expression
"""The built-in exponential function."""
LOG: Expression
"""The built-in logarithm function."""
@classmethod
def symbol(_cls, name: str, is_symmetric: Optional[bool] = None, is_antisymmetric: Optional[bool] = None, is_linear: Optional[bool] = None) -> Expression:
"""
Create a new symbol from a `name`. Symbols carry information about their attributes.
The symbol can signal that it is symmetric if it is used as a function
using `is_symmetric=True`, antisymmetric using `is_antisymmetric=True`, and
multilinear using `is_linear=True`. If no attributes
are specified, the attributes are inherited from the symbol if it was already defined,
otherwise all attributes are set to `false`.
Once attributes are defined on a symbol, they cannot be redefined later.
Examples
--------
Define a regular symbol and use it as a variable:
>>> x = Expression.symbol('x')
>>> e = x**2 + 5
>>> print(e)
x**2 + 5
Define a regular symbol and use it as a function:
>>> f = Expression.symbol('f')
>>> e = f(1,2)
>>> print(e)
f(1,2)
Define a symmetric function:
>>> f = Expression.symbol('f', is_symmetric=True)
>>> e = f(2,1)
>>> print(e)
f(1,2)
Define a linear and symmetric function:
>>> p1, p2, p3, p4 = Expression.symbols('p1', 'p2', 'p3', 'p4')
>>> dot = Expression.symbol('dot', is_symmetric=True, is_linear=True)
>>> e = dot(p2+2*p3,p1+3*p2-p3)
dot(p1,p2)+2*dot(p1,p3)+3*dot(p2,p2)-dot(p2,p3)+6*dot(p2,p3)-2*dot(p3,p3)
"""
@classmethod
def symbols(_cls, *names: str, is_symmetric: Optional[bool] = None, is_antisymmetric: Optional[bool] = None, is_linear: Optional[bool] = None) -> Sequence[Expression]:
"""
Create a Symbolica symbol for every name in `*names`. See `Expression.symbol` for more information.
Examples
--------
>>> f, x = Expression.symbols('x', 'f')
>>> e = f(1,x)
>>> print(e)
f(1,x)
"""
@overload
def __call__(self, *args: Expression | int | float | Decimal) -> Expression:
"""
Create a Symbolica expression or transformer by calling the function with appropriate arguments.
Examples
-------
>>> x, f = Expression.symbols('x', 'f')
>>> e = f(3,x)
>>> print(e)
f(3,x)
"""
@overload
def __call__(self, *args: Transformer | Expression | int | float | Decimal) -> Transformer:
"""
Create a Symbolica expression or transformer by calling the function with appropriate arguments.
Examples
-------
>>> x, f = Expression.symbols('x', 'f')
>>> e = f(3,x)
>>> print(e)
f(3,x)
"""
@classmethod
def num(_cls, num: int | float | str | Decimal, relative_error: Optional[float] = None) -> Expression:
"""Create a new Symbolica number from an int, a float, or a string.
A floating point number is kept as a float with the same precision as the input,
but it can also be converted to the smallest rational number given a `relative_error`.
Examples
--------
>>> e = Expression.num(1) / 2
>>> print(e)
1/2
>>> print(Expression.num(1/3))
>>> print(Expression.num(0.33, 0.1))
>>> print(Expression.num('0.333`3'))
>>> print(Expression.num(Decimal('0.1234')))
3.3333333333333331e-1
1/3
3.33e-1
1.2340e-1
"""
@classmethod
def get_all_symbol_names(_cls) -> list[str]:
"""Return all defined symbol names (function names and variables)."""
@classmethod
def parse(_cls, input: str) -> Expression:
"""
Parse a Symbolica expression from a string.
Parameters
----------
input: str
An input string. UTF-8 character are allowed.
Examples
--------
>>> e = Expression.parse('x^2+y+y*4')
>>> print(e)
x^2+5*y
Raises
------
ValueError
If the input is not a valid Symbolica expression.
"""
def __new__(cls) -> Expression:
"""Create a new expression that represents 0."""
def __copy__(self) -> Expression:
"""
Copy the expression.
"""
def __str__(self) -> str:
"""
Convert the expression into a human-readable string.
"""
def get_byte_size(self) -> int:
""" Get the number of bytes that this expression takes up in memory."""
def pretty_str(
self,
terms_on_new_line: bool = False,
color_top_level_sum: bool = True,
color_builtin_symbols: bool = True,
print_finite_field: bool = True,
symmetric_representation_for_finite_field: bool = False,
explicit_rational_polynomial: bool = False,
number_thousands_separator: Optional[str] = None,
multiplication_operator: str = "*",
double_star_for_exponentiation: bool = False,
square_brackets_for_function: bool = False,
num_exp_as_superscript: bool = True,
latex: bool = False,
) -> str:
"""
Convert the expression into a human-readable string, with tunable settings.
Examples
--------
>>> a = Expression.parse('128378127123 z^(2/3)*w^2/x/y + y^4 + z^34 + x^(x+2)+3/5+f(x,x^2)')
>>> print(a.pretty_str(number_thousands_separator='_', multiplication_operator=' '))
Yields `z³⁴+x^(x+2)+y⁴+f(x,x²)+128_378_127_123 z^(2/3) w² x⁻¹ y⁻¹+3/5`.
"""
def to_latex(self) -> str:
"""
Convert the expression into a LaTeX string.
Examples
--------
>>> a = Expression.parse('128378127123 z^(2/3)*w^2/x/y + y^4 + z^34 + x^(x+2)+3/5+f(x,x^2)')
>>> print(a.to_latex())
Yields `$$z^{34}+x^{x+2}+y^{4}+f(x,x^{2})+128378127123 z^{\\frac{2}{3}} w^{2} \\frac{1}{x} \\frac{1}{y}+\\frac{3}{5}$$`.
"""
def to_sympy(self) -> str:
"""Convert the expression into a sympy-parsable string.
Examples
--------
>>> from sympy import *
>>> s = sympy.parse_expr(Expression.parse('x^2+f((1+x)^y)').to_sympy())
"""
def __hash__(self) -> str:
"""
Hash the expression.
"""
def get_type(self) -> AtomType:
"""Get the type of the atom."""
def to_atom_tree(self) -> AtomTree:
"""Convert the expression to a tree."""
def get_name(self) -> Optional[str]:
"""
Get the name of a variable or function if the current atom
is a variable or function.
"""
def __add__(self, other: Expression | int | float | Decimal) -> Expression:
"""
Add this expression to `other`, returning the result.
"""
def __radd__(self, other: Expression | int | float | Decimal) -> Expression:
"""
Add this expression to `other`, returning the result.
"""
def __sub__(self, other: Expression | int | float | Decimal) -> Expression:
"""
Subtract `other` from this expression, returning the result.
"""
def __rsub__(self, other: Expression | int | float | Decimal) -> Expression:
"""
Subtract this expression from `other`, returning the result.
"""
def __mul__(self, other: Expression | int | float | Decimal) -> Expression:
"""
Multiply this expression with `other`, returning the result.
"""
def __rmul__(self, other: Expression | int | float | Decimal) -> Expression:
"""
Multiply this expression with `other`, returning the result.
"""
def __truediv__(self, other: Expression | int | float | Decimal) -> Expression:
"""
Divide this expression by `other`, returning the result.
"""
def __rtruediv__(self, other: Expression | int | float | Decimal) -> Expression:
"""
Divide `other` by this expression, returning the result.
"""
def __pow__(self, exp: Expression | int | float | Decimal) -> Expression:
"""
Take `self` to power `exp`, returning the result.
"""
def __rpow__(self, base: Expression | int | float | Decimal) -> Expression:
"""
Take `base` to power `self`, returning the result.
"""
def __xor__(self, a: Any) -> Expression:
"""
Returns a warning that `**` should be used instead of `^` for taking a power.
"""
def __rxor__(self, a: Any) -> Expression:
"""
Returns a warning that `**` should be used instead of `^` for taking a power.
"""
def __neg__(self) -> Expression:
"""
Negate the current expression, returning the result.
"""
def __len__(self) -> int:
"""
Return the number of terms in this expression.
"""
def transform(self) -> Transformer:
"""
Convert the input to a transformer, on which subsequent
transformations can be applied.
"""
def coefficients_to_float(self, decimal_prec: int) -> Expression:
"""Convert all coefficients to floats with a given precision `decimal_prec`.
The precision of floating point coefficients in the input will be truncated to `decimal_prec`."""
def rationalize_coefficients(self, relative_error: float) -> Expression:
"""Map all floating point and rational coefficients to the best rational approximation
in the interval `[self*(1-relative_error),self*(1+relative_error)]`."""
def req_len(self, min_length: int, max_length: int | None) -> PatternRestriction:
"""
Create a pattern restriction based on the wildcard length before downcasting.
"""
def req_type(self, atom_type: AtomType) -> PatternRestriction:
"""
Create a pattern restriction that tests the type of the atom.
Examples
--------
>>> from symbolica import Expression, AtomType
>>> x, x_ = Expression.symbols('x', 'x_')
>>> f = Expression.symbol('f')
>>> e = f(x)*f(2)*f(f(3))
>>> e = e.replace_all(f(x_), 1, x_.req_type(AtomType.Num))
>>> print(e)
Yields `f(x)*f(1)`.
"""
def req_lit(self) -> PatternRestriction:
"""
Create a pattern restriction that treats the wildcard as a literal variable,
so that it only matches to itself.
"""
def req(
self,
filter_fn: Callable[[Expression], bool],
) -> PatternRestriction:
"""
Create a new pattern restriction that calls the function `filter_fn` with the matched
atom that should return a boolean. If true, the pattern matches.
Examples
--------
>>> from symbolica import Expression
>>> x_ = Expression.symbol('x_')
>>> f = Expression.symbol('f')
>>> e = f(1)*f(2)*f(3)
>>> e = e.replace_all(f(x_), 1, x_.req(lambda m: m == 2 or m == 3))
"""
def req_cmp(
self,
other: Expression | int | float | Decimal,
cmp_fn: Callable[[Expression, Expression], bool],
) -> PatternRestriction:
"""
Create a new pattern restriction that calls the function `cmp_fn` with another the matched
atom and the match atom of the `other` wildcard that should return a boolean. If true, the pattern matches.
Examples
--------
>>> from symbolica import Expression
>>> x_, y_ = Expression.symbols('x_', 'y_')
>>> f = Expression.symbol('f')
>>> e = f(1)*f(2)*f(3)
>>> e = e.replace_all(f(x_)*f(y_), 1, x_.req_cmp(y_, lambda m1, m2: m1 + m2 == 4))
"""
def req_lt(self, num: Expression | int | float | Decimal, cmp_any_atom=False) -> PatternRestriction:
"""Create a pattern restriction that passes when the wildcard is smaller than a number `num`.
If the matched wildcard is not a number, the pattern fails.
When the option `cmp_any_atom` is set to `True`, this function compares atoms
of any type. The result depends on the internal ordering and may change between
different Symbolica versions.
Examples
--------
>>> from symbolica import Expression
>>> x_ = Expression.symbol('x_')
>>> f = Expression.symbol('f')
>>> e = f(1)*f(2)*f(3)
>>> e = e.replace_all(f(x_), 1, x_.req_lt(2))
"""
def req_gt(self, num: Expression | int | float | Decimal, cmp_any_atom=False) -> PatternRestriction:
"""Create a pattern restriction that passes when the wildcard is greater than a number `num`.
If the matched wildcard is not a number, the pattern fails.
When the option `cmp_any_atom` is set to `True`, this function compares atoms
of any type. The result depends on the internal ordering and may change between
different Symbolica versions.
Examples
--------
>>> from symbolica import Expression
>>> x_ = Expression.symbol('x_')
>>> f = Expression.symbol('f')
>>> e = f(1)*f(2)*f(3)
>>> e = e.replace_all(f(x_), 1, x_.req_gt(2))
"""
def req_le(self, num: Expression | int | float | Decimal, cmp_any_atom=False) -> PatternRestriction:
"""Create a pattern restriction that passes when the wildcard is smaller than or equal to a number `num`.
If the matched wildcard is not a number, the pattern fails.
When the option `cmp_any_atom` is set to `True`, this function compares atoms
of any type. The result depends on the internal ordering and may change between
different Symbolica versions.
Examples
--------
>>> from symbolica import Expression
>>> x_ = Expression.symbol('x_')
>>> f = Expression.symbol('f')
>>> e = f(1)*f(2)*f(3)
>>> e = e.replace_all(f(x_), 1, x_.req_le(2))
"""
def req_ge(self, num: Expression | int | float | Decimal, cmp_any_atom=False) -> PatternRestriction:
"""Create a pattern restriction that passes when the wildcard is greater than or equal to a number `num`.
If the matched wildcard is not a number, the pattern fails.
When the option `cmp_any_atom` is set to `True`, this function compares atoms
of any type. The result depends on the internal ordering and may change between
different Symbolica versions.
Examples
--------
>>> from symbolica import Expression
>>> x_ = Expression.symbol('x_')
>>> f = Expression.symbol('f')
>>> e = f(1)*f(2)*f(3)
>>> e = e.replace_all(f(x_), 1, x_.req_ge(2))
"""
def req_cmp_lt(self, num: Expression, cmp_any_atom=False) -> PatternRestriction:
"""Create a pattern restriction that passes when the wildcard is smaller than another wildcard.
If the matched wildcards are not a numbers, the pattern fails.
When the option `cmp_any_atom` is set to `True`, this function compares atoms
of any type. The result depends on the internal ordering and may change between
different Symbolica versions.
Examples
--------
>>> from symbolica import Expression
>>> x_, y_ = Expression.symbol('x_', 'y_')
>>> f = Expression.symbol('f')
>>> e = f(1,2)
>>> e = e.replace_all(f(x_,y_), 1, x_.req_cmp_lt(y_))
"""
def req_cmp_gt(self, num: Expression, cmp_any_atom=False) -> PatternRestriction:
"""Create a pattern restriction that passes when the wildcard is greater than another wildcard.
If the matched wildcards are not a numbers, the pattern fails.
When the option `cmp_any_atom` is set to `True`, this function compares atoms
of any type. The result depends on the internal ordering and may change between
different Symbolica versions.
Examples
--------
>>> from symbolica import Expression
>>> x_, y_ = Expression.symbol('x_', 'y_')
>>> f = Expression.symbol('f')
>>> e = f(1,2)
>>> e = e.replace_all(f(x_,y_), 1, x_.req_cmp_gt(y_))
"""
def req_cmp_le(self, num: Expression, cmp_any_atom=False) -> PatternRestriction:
"""Create a pattern restriction that passes when the wildcard is smaller than or equal to another wildcard.
If the matched wildcards are not a numbers, the pattern fails.
When the option `cmp_any_atom` is set to `True`, this function compares atoms
of any type. The result depends on the internal ordering and may change between
different Symbolica versions.
Examples
--------
>>> from symbolica import Expression
>>> x_, y_ = Expression.symbol('x_', 'y_')
>>> f = Expression.symbol('f')
>>> e = f(1,2)
>>> e = e.replace_all(f(x_,y_), 1, x_.req_cmp_le(y_))
"""
def req_cmp_ge(self, num: Expression, cmp_any_atom=False) -> PatternRestriction:
"""Create a pattern restriction that passes when the wildcard is greater than or equal to another wildcard.
If the matched wildcards are not a numbers, the pattern fails.
When the option `cmp_any_atom` is set to `True`, this function compares atoms
of any type. The result depends on the internal ordering and may change between
different Symbolica versions.
Examples
--------
>>> from symbolica import Expression
>>> x_, y_ = Expression.symbol('x_', 'y_')
>>> f = Expression.symbol('f')
>>> e = f(1,2)
>>> e = e.replace_all(f(x_,y_), 1, x_.req_cmp_ge(y_))
"""
def __eq__(self, other: Expression | int | float | Decimal) -> bool:
"""
Compare two expressions.
"""
def __neq__(self, other: Expression | int | float | Decimal) -> bool:
"""
Compare two expressions.
"""
def __lt__(self, other: Expression | int | float | Decimal) -> bool:
"""
Compare two expressions. Both expressions must be a number.
"""
def __le__(self, other: Expression | int | float | Decimal) -> bool:
"""
Compare two expressions. Both expressions must be a number.
"""
def __gt__(self, other: Expression | int | float | Decimal) -> bool:
"""
Compare two expressions. Both expressions must be a number.
"""
def __ge__(self, other: Expression | int | float | Decimal) -> bool:
"""
Compare two expressions. Both expressions must be a number.
"""
def __iter__(self) -> Iterator[Expression]:
"""
Create an iterator over all atoms in the expression.
"""
def __getitem__(self, idx: int) -> Expression:
"""Get the `idx`th component of the expression."""
def map(
self,
transformations: Transformer,
n_cores: Optional[int] = 1,
) -> Expression:
"""
Map the transformations to every term in the expression.
The execution happens in parallel using `n_cores`.
Examples
--------
>>> x, x_ = Expression.symbols('x', 'x_')
>>> e = (1+x)**2
>>> r = e.map(Transformer().expand().replace_all(x, 6))
>>> print(r)
"""
def set_coefficient_ring(self, vars: Sequence[Expression]) -> Expression:
"""
Set the coefficient ring to contain the variables in the `vars` list.
This will move all variables into a rational polynomial function.
Parameters
----------
vars : Sequence[Expression]
A list of variables
"""
def expand(self, var: Optional[Expression] = None) -> Expression:
"""
Expand the expression. Optionally, expand in `var` only.
"""
def collect(
self,
x: Expression,
key_map: Optional[Callable[[Expression], Expression]] = None,
coeff_map: Optional[Callable[[Expression], Expression]] = None,
) -> Expression:
"""
Collect terms involving the same power of `x`, where `x` is a variable or function name.
Return the list of key-coefficient pairs and the remainder that matched no key.
Both the key (the quantity collected in) and its coefficient can be mapped using
`key_map` and `coeff_map` respectively.
Examples
--------
>>> from symbolica import Expression
>>> x, y = Expression.symbols('x', 'y')
>>> e = 5*x + x * y + x**2 + 5
>>>
>>> print(e.collect(x))
yields `x^2+x*(y+5)+5`.
>>> from symbolica import Expression
>>> x, y = Expression.symbols('x', 'y')
>>> var, coeff = Expression.funs('var', 'coeff')
>>> e = 5*x + x * y + x**2 + 5
>>>
>>> print(e.collect(x, key_map=lambda x: var(x), coeff_map=lambda x: coeff(x)))
yields `var(1)*coeff(5)+var(x)*coeff(y+5)+var(x^2)*coeff(1)`.
Parameters
----------
key_map: A function to be applied to the quantity collected in
coeff_map: A function to be applied to the coefficient
"""
def coefficient_list(
self, x: Expression
) -> Sequence[Tuple[Expression, Expression]]:
"""Collect terms involving the same power of `x`, where `x` is a variable or function name.
Return the list of key-coefficient pairs and the remainder that matched no key.
Examples
--------
>>> from symbolica import *
>>> x, y = Expression.symbols('x', 'y')
>>> e = 5*x + x * y + x**2 + 5
>>>
>>> for a in e.coefficient_list(x):
>>> print(a[0], a[1])
yields
```
x y+5
x^2 1
1 5
```
"""
def coefficient(self, x: Expression) -> Expression:
"""Collect terms involving the literal occurrence of `x`.
Examples
--------
>>> from symbolica import *
>>> x, y = Expression.symbols('x', 'y')
>>> e = 5*x + x * y + x**2 + y*x**2
>>> print(e.coefficient(x**2))
yields
```
y + 1
```
"""
def derivative(self, x: Expression) -> Expression:
"""Derive the expression w.r.t the variable `x`."""
def series(
self,
x: Expression,
expansion_point: Expression | int | float | Decimal,
depth: int,
depth_denom: int = 1,
depth_is_absolute: bool = True
) -> Series:
"""Series expand in `x` around `expansion_point` to depth `depth`."""
def apart(self, x: Expression) -> Expression:
"""Compute the partial fraction decomposition in `x`.
Examples
--------
>>> from symbolica import Expression
>>> x = Expression.symbol('x')
>>> p = Expression.parse('1/((x+y)*(x^2+x*y+1)(x+1))')
>>> print(p.apart(x))
"""
def together(self) -> Expression:
"""Write the expression over a common denominator.
Examples
--------
>>> from symbolica import Expression
>>> p = Expression.parse('v1^2/2+v1^3/v4*v2+v3/(1+v4)')
>>> print(p.together())
"""
def cancel(self) -> Expression:
"""Cancel common factors between numerators and denominators.
Any non-canceling parts of the expression will not be rewritten.
Examples
--------
>>> from symbolica import Expression
>>> p = Expression.parse('1+(y+1)^10*(x+1)/(x^2+2x+1)')
>>> print(p.cancel())
1+(y+1)**10/(x+1)
"""
def factor(self) -> Expression:
"""Factor the expression over the rationals.
Examples
--------
>>> from symbolica import Expression
>>> p = Expression.parse('(6 + x)/(7776 + 6480*x + 2160*x^2 + 360*x^3 + 30*x^4 + x^5)')
>>> print(p.factor())
(x+6)**-4
"""
@overload
def to_polynomial(self, vars: Optional[Sequence[Expression]] = None) -> Polynomial:
"""Convert the expression to a polynomial, optionally, with the variable ordering specified in `vars`.
All non-polynomial parts will be converted to new, independent variables.
"""
@overload
def to_polynomial(self, minimal_poly: Expression, vars: Optional[Sequence[Expression]] = None,
) -> NumberFieldPolynomial:
"""Convert the expression to a polynomial, optionally, with the variables and the ordering specified in `vars`.
All non-polynomial elements will be converted to new independent variables.
The coefficients will be converted to a number field with the minimal polynomial `minimal_poly`.
The minimal polynomial must be a monic, irreducible univariate polynomial.
"""
@overload
def to_polynomial(self,
modulus: int,
power: Optional[Tuple[int, Expression]] = None,
minimal_poly: Optional[Expression] = None,
vars: Optional[Sequence[Expression]] = None,
) -> FiniteFieldPolynomial:
"""Convert the expression to a polynomial, optionally, with the variables and the ordering specified in `vars`.
All non-polynomial elements will be converted to new independent variables.
The coefficients will be converted to finite field elements modulo `modulus`.
If on top an `extension` is provided, for example `(2, a)`, the polynomial will be converted to the Galois field
`GF(modulus^2)` where `a` is the variable of the minimal polynomial of the field.
If a `minimal_poly` is provided, the Galois field will be created with `minimal_poly` as the minimal polynomial.
"""
def to_rational_polynomial(
self,
vars: Optional[Sequence[Expression]] = None,
) -> RationalPolynomial:
"""
Convert the expression to a rational polynomial, optionally, with the variable ordering specified in `vars`.
The latter is useful if it is known in advance that more variables may be added in the future to the
rational polynomial through composition with other rational polynomials.
All non-rational polynomial parts are converted to new, independent variables.
Examples
--------
>>> a = Expression.parse('(1 + 3*x1 + 5*x2 + 7*x3 + 9*x4 + 11*x5 + 13*x6 + 15*x7)^2 - 1').to_rational_polynomial()
>>> print(a)
"""
def match(
self,
lhs: Transformer | Expression | int | float | Decimal,
cond: Optional[PatternRestriction] = None,
level_range: Optional[Tuple[int, Optional[int]]] = None,
level_is_tree_depth: Optional[bool] = False,
allow_new_wildcards_on_rhs: Optional[bool] = False,
) -> MatchIterator:
"""
Return an iterator over the pattern `self` matching to `lhs`.
Restrictions on the pattern can be supplied through `cond`.
The `level_range` specifies the `[min,max]` level at which the pattern is allowed to match.
The first level is 0 and the level is increased when going into a function or one level deeper in the expression tree,
depending on `level_is_tree_depth`.
Examples
--------
>>> x, x_ = Expression.symbols('x','x_')
>>> f = Expression.symbol('f')
>>> e = f(x)*f(1)*f(2)*f(3)
>>> for match in e.match(f(x_)):
>>> for map in match:
>>> print(map[0],'=', map[1])
"""
def matches(
self,
lhs: Transformer | Expression | int | float | Decimal,
cond: Optional[PatternRestriction] = None,
level_range: Optional[Tuple[int, Optional[int]]] = None,
level_is_tree_depth: Optional[bool] = False,
allow_new_wildcards_on_rhs: Optional[bool] = False,
) -> bool:
"""
Test whether the pattern is found in the expression.
Restrictions on the pattern can be supplied through `cond`.
Examples
--------
>>> f = Expression.symbol('f')
>>> if f(1).matches(f(2)):
>>> print('match')
"""
def replace(
self,
lhs: Transformer | Expression | int | float | Decimal,
rhs: Transformer | Expression | int | float | Decimal,
cond: Optional[PatternRestriction] = None,
level_range: Optional[Tuple[int, Optional[int]]] = None,
level_is_tree_depth: Optional[bool] = False,
allow_new_wildcards_on_rhs: Optional[bool] = False,
) -> ReplaceIterator:
"""
Return an iterator over the replacement of the pattern `self` on `lhs` by `rhs`.
Restrictions on pattern can be supplied through `cond`.
Examples
--------
>>> from symbolica import Expression
>>> x_ = Expression.symbol('x_')
>>> f = Expression.symbol('f')
>>> e = f(1)*f(2)*f(3)
>>> for r in e.replace(f(x_), f(x_ + 1)):
>>> print(r)
Yields:
```
f(2)*f(2)*f(3)
f(1)*f(3)*f(3)
f(1)*f(2)*f(4)
```
Parameters
----------
lhs: The pattern to match.
rhs: The right-hand side to replace the matched subexpression with.
cond: Conditions on the pattern.
level_range: Specifies the `[min,max]` level at which the pattern is allowed to match. The first level is 0 and the level is increased when going into a function or one level deeper in the expression tree, depending on `level_is_tree_depth`.
level_is_tree_depth: If set to `True`, the level is increased when going one level deeper in the expression tree.
allow_new_wildcards_on_rhs: If set to `True`, allow wildcards that do not appear in the pattern on the right-hand side.
"""
def replace_all(
self,
pattern: Transformer | Expression | int | float | Decimal,
rhs: Transformer | Expression | int | float | Decimal,
cond: Optional[PatternRestriction] = None,
non_greedy_wildcards: Optional[Sequence[Expression]] = None,
level_range: Optional[Tuple[int, Optional[int]]] = None,
level_is_tree_depth: Optional[bool] = False,
allow_new_wildcards_on_rhs: Optional[bool] = False,
repeat: Optional[bool] = False,
) -> Expression:
"""
Replace all subexpressions matching the pattern `pattern` by the right-hand side `rhs`.
Examples
--------
>>> x, w1_, w2_ = Expression.symbols('x','w1_','w2_')
>>> f = Expression.symbol('f')
>>> e = f(3,x)
>>> r = e.replace_all(f(w1_,w2_), f(w1_ - 1, w2_**2), (w1_ >= 1) & w2_.is_var())
>>> print(r)
Parameters
----------
self: The expression to match and replace on.
pattern: The pattern to match.
rhs: The right-hand side to replace the matched subexpression with.
cond: Conditions on the pattern.
non_greedy_wildcards: Wildcards that try to match as little as possible.
level_range: Specifies the `[min,max]` level at which the pattern is allowed to match. The first level is 0 and the level is increased when going into a function or one level deeper in the expression tree, depending on `level_is_tree_depth`.
level_is_tree_depth: If set to `True`, the level is increased when going one level deeper in the expression tree.
allow_new_wildcards_on_rhs: If set to `True`, allow wildcards that do not appear in the pattern on the right-hand side.
repeat: If set to `True`, the entire operation will be repeated until there are no more matches.
"""
def replace_all_multiple(self, replacements: Sequence[Replacement], repeat: Optional[bool] = False) -> Expression:
"""
Replace all atoms matching the patterns. See `replace_all` for more information.
The entire operation can be repeated until there are no more matches using `repeat=True`.
Examples
--------
>>> x, y, f = Expression.symbols('x', 'y', 'f')
>>> e = f(x,y)