mathai 0.7.8__py3-none-any.whl → 0.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mathai/expand.py CHANGED
@@ -3,21 +3,12 @@ from .simplify import simplify
3
3
  import itertools
4
4
 
5
5
  def expand_nc(expr, label="f_mul"):
6
- """
7
- Expand expression where:
8
- - f_add is commutative
9
- - label (@) is NON-commutative
10
- """
11
- # --- base cases ---
6
+
12
7
  if expr.name not in {"f_add", label, "f_pow"}:
13
8
  return expr
14
9
 
15
- # --- expand children first ---
16
10
  expr.children = [expand_nc(c, label) for c in expr.children]
17
11
 
18
- # ==========================================================
19
- # POWER: (A + B)^n only if n is positive integer
20
- # ==========================================================
21
12
  if expr.name == "f_pow":
22
13
  base, exp = expr.children
23
14
  n = frac(exp)
@@ -26,9 +17,6 @@ def expand_nc(expr, label="f_mul"):
26
17
  return expand_nc(TreeNode(label, factors), label)
27
18
  return expr
28
19
 
29
- # ==========================================================
30
- # ADDITION (commutative)
31
- # ==========================================================
32
20
  if expr.name == "f_add":
33
21
  out = []
34
22
  for c in expr.children:
@@ -38,20 +26,15 @@ def expand_nc(expr, label="f_mul"):
38
26
  out.append(c)
39
27
  return TreeNode("f_add", out)
40
28
 
41
- # ==========================================================
42
- # NON-COMMUTATIVE MULTIPLICATION (@)
43
- # ==========================================================
44
29
  if expr.name == label:
45
30
  factors = []
46
31
 
47
- # flatten only (NO reordering)
48
32
  for c in expr.children:
49
33
  if c.name == label:
50
34
  factors.extend(c.children)
51
35
  else:
52
36
  factors.append(c)
53
37
 
54
- # find first additive factor
55
38
  for i, f in enumerate(factors):
56
39
  if f.name == "f_add":
57
40
  left = factors[:i]
@@ -66,13 +49,12 @@ def expand_nc(expr, label="f_mul"):
66
49
 
67
50
  return TreeNode("f_add", terms)
68
51
 
69
- # no addition inside → return as-is
70
52
  return TreeNode(label, factors)
71
53
 
72
-
73
54
  def expand2(eq, over="*"):
74
55
  over = {"@": "f_wmul", ".":"f_dot", "*":"f_mul"}[over]
75
56
  return expand_nc(eq, over)
76
57
  def expand(eq, over="*"):
77
58
  eq = expand2(eq, over)
78
59
  return TreeNode(eq.name, [expand(child, over) for child in eq.children])
60
+
mathai/fraction.py CHANGED
@@ -2,102 +2,86 @@ from .base import *
2
2
  from .simplify import simplify
3
3
  from .expand import expand
4
4
 
5
- def fraction(eq):
6
- stack = [(eq, None)] # (current_node, parent_processed_children)
7
- result_map = {} # Map original nodes to their processed TreeNode
8
-
9
- while stack:
10
- node, parent_info = stack.pop()
11
-
12
- # If node already processed, continue
13
- if node in result_map:
14
- continue
15
-
16
- # Base case: leaf node
17
- if not node.children:
18
- result_map[node] = TreeNode(node.name, [])
19
- continue
20
-
21
- # Check if all children are processed
22
- all_children_done = all(child in result_map for child in node.children)
23
- if not all_children_done:
24
- # Push current node back to stack after children
25
- stack.append((node, parent_info))
26
- for child in reversed(node.children):
27
- if child not in result_map:
28
- stack.append((child, (node, node.children)))
29
- continue
30
-
31
- # Now all children are processed, handle this node
32
- if node.name == "f_eq":
33
- left = result_map[node.children[0]]
34
- right = result_map[node.children[1]]
35
- result_map[node] = TreeNode("f_eq", [left, right])
36
- continue
37
-
38
- elif node.name == "f_add":
39
- con = []
40
- for child in node.children:
41
- child_processed = result_map[child]
42
- if child_processed.name == "f_pow" and child_processed.children[1].name[:2] == "d_" and int(child_processed.children[1].name[2:]) < 0:
43
- den = []
44
- n = int(child_processed.children[1].name[2:])
45
- if n == -1:
46
- den.append(child_processed.children[0])
47
- else:
48
- den.append(TreeNode("f_pow", [child_processed.children[0], tree_form("d_" + str(-n))]))
49
- con.append([[], den])
50
- elif child_processed.name == "f_mul":
51
- num = []
52
- den = []
53
- for child2 in child_processed.children:
54
- if child2.name == "f_pow" and child2.children[1].name[:2] == "d_" and int(child2.children[1].name[2:]) < 0:
55
- n = int(child2.children[1].name[2:])
56
- if n == -1:
57
- den.append(child2.children[0])
58
- else:
59
- den.append(TreeNode("f_pow", [child2.children[0], tree_form("d_" + str(-n))]))
60
- else:
61
- num.append(child2)
62
- con.append([num, den])
63
- else:
64
- con.append([[child_processed], []])
65
-
66
- if len(con) > 1 and any(x[1] != [] for x in con):
67
- # Construct numerator
68
- a_children = []
69
- for i in range(len(con)):
70
- b_children = con[i][0].copy()
71
- for j in range(len(con)):
72
- if i == j:
73
- continue
74
- b_children += con[j][1]
75
- if len(b_children) == 0:
76
- b_children = [tree_form("d_1")]
77
- elif len(b_children) == 1:
78
- b_children = b_children
5
+ def fraction(expr):
6
+ if expr is None:
7
+ return None
8
+
9
+ expr = simplify(expr)
10
+
11
+ if expr.children == []:
12
+ return expr
13
+
14
+ children = [fraction(c) for c in expr.children]
15
+
16
+ if expr.name == "f_add":
17
+ terms = []
18
+
19
+ for c in children:
20
+
21
+ if c.name == "f_mul":
22
+ num = []
23
+ den = []
24
+ for f in c.children:
25
+ if (
26
+ f.name == "f_pow"
27
+ and f.children[1].name.startswith("d_")
28
+ and int(f.children[1].name[2:]) < 0
29
+ ):
30
+ n = int(f.children[1].name[2:])
31
+ den.append(
32
+ f.children[0]
33
+ if n == -1
34
+ else TreeNode("f_pow", [f.children[0], tree_form(f"d_{-n}")])
35
+ )
79
36
  else:
80
- b_children = [TreeNode("f_mul", b_children)]
81
- a_children += b_children if isinstance(b_children, list) else [b_children]
82
-
83
- a = TreeNode("f_add", a_children)
84
-
85
- # Construct denominator
86
- c_children = []
87
- for i in range(len(con)):
88
- c_children += con[i][1]
89
- if len(c_children) == 1:
90
- c = c_children[0]
91
- else:
92
- c = TreeNode("f_mul", c_children)
93
- c = TreeNode("f_pow", [c, tree_form("d_-1")])
94
-
95
- result_map[node] = TreeNode("f_mul", [simplify(expand(simplify(a))), c])
96
- continue
97
-
98
- # Default: just reconstruct node
99
- children_processed = [result_map[child] for child in node.children]
100
- result_map[node] = TreeNode(node.name, children_processed)
101
-
102
- # Final return
103
- return simplify(result_map[eq])
37
+ num.append(f)
38
+ terms.append((num, den))
39
+
40
+ elif (
41
+ c.name == "f_pow"
42
+ and c.children[1].name.startswith("d_")
43
+ and int(c.children[1].name[2:]) < 0
44
+ ):
45
+ n = int(c.children[1].name[2:])
46
+ terms.append(([], [
47
+ c.children[0]
48
+ if n == -1
49
+ else TreeNode("f_pow", [c.children[0], tree_form(f"d_{-n}")])
50
+ ]))
51
+
52
+ else:
53
+ terms.append(([c], []))
54
+
55
+ if not any(den for _, den in terms):
56
+ return TreeNode("f_add", children)
57
+
58
+ num_terms = []
59
+ for i, (num_i, _) in enumerate(terms):
60
+ acc = list(num_i)
61
+ for j, (_, den_j) in enumerate(terms):
62
+ if i != j:
63
+ acc += den_j
64
+ if not acc:
65
+ acc = [tree_form("d_1")]
66
+ num_terms.append(
67
+ acc[0] if len(acc) == 1 else TreeNode("f_mul", acc)
68
+ )
69
+
70
+ numerator = TreeNode("f_add", num_terms)
71
+
72
+ den_all = []
73
+ for _, den in terms:
74
+ den_all += den
75
+
76
+ denom = den_all[0] if len(den_all) == 1 else TreeNode("f_mul", den_all)
77
+ denom = TreeNode("f_pow", [denom, tree_form("d_-1")])
78
+
79
+ return simplify(
80
+ TreeNode(
81
+ "f_mul",
82
+ [simplify(expand(numerator)), denom],
83
+ )
84
+ )
85
+
86
+ return TreeNode(expr.name, children)
87
+
mathai/integrate.py CHANGED
@@ -97,6 +97,8 @@ def place_try2(eq):
97
97
  return eq.children[try_lst.pop(0)]
98
98
  return TreeNode(eq.name, [place_try2(child) for child in eq.children])
99
99
  def _solve_integrate(eq):
100
+ if eq is None:
101
+ return None
100
102
  if eq.name == "f_ref":
101
103
  return eq
102
104
  if eq.name == "f_subs":
@@ -153,6 +155,8 @@ def inteq(eq):
153
155
  else:
154
156
  return TreeNode(eq.name, [inteq(child) for child in eq.children])
155
157
  def rm(eq):
158
+ if eq is None:
159
+ return None
156
160
  if eq.name == "f_try":
157
161
  eq = TreeNode(eq.name, list(set(eq.children)))
158
162
  return TreeNode(eq.name, [rm(child) for child in eq.children if child is not None])
@@ -161,6 +165,8 @@ def solve_integrate(eq):
161
165
  eq2 = dowhile(eq, _solve_integrate)
162
166
  #eq2 = dowhile(eq2, handle_try)
163
167
  eq2 = rm(eq2)
168
+ if eq2 is None:
169
+ return None
164
170
  if eq2.name == "f_try":
165
171
  eq2.children = list(set(eq2.children))
166
172
  return eq2
@@ -409,8 +415,8 @@ def integration_formula_ex():
409
415
 
410
416
  formula_gen11 = integration_formula_ex()
411
417
  def rm_const(equation):
412
- if equation.name == "f_ref":
413
- return equation
418
+ if equation is None:
419
+ return None
414
420
  eq2 = equation
415
421
  if eq2.name == "f_integrate" and contain(eq2.children[0], eq2.children[1]):
416
422
  equation = eq2.children[0]
@@ -436,8 +442,8 @@ def shorten(eq):
436
442
  return tree_form("d_0")
437
443
  return TreeNode(eq.name, [shorten(child) for child in eq.children])
438
444
  def integrate_formula(equation):
439
- if equation.name == "f_ref":
440
- return equation.copy_tree()
445
+ if equation is None:
446
+ return None
441
447
  eq2 = equation.copy_tree()
442
448
  if eq2.name == "f_integrate":
443
449
  integrand = eq2.children[0]
mathai/linear.py CHANGED
@@ -39,11 +39,10 @@ def islinear(eq, fxconst):
39
39
  return False
40
40
  def linear(eqlist, fxconst):
41
41
  orig = [item.copy_tree() for item in eqlist]
42
- #eqlist = [eq for eq in eqlist if fxconst(eq)]
43
-
42
+
44
43
  if eqlist == [] or not all(islinear(eq, fxconst) for eq in eqlist):
45
44
  return None
46
- #return TreeNode("f_and", [TreeNode("f_eq", [x, tree_form("d_0")]) for x in orig])
45
+
47
46
  vl = []
48
47
  def varlist(eq, fxconst):
49
48
  nonlocal vl
@@ -54,7 +53,7 @@ def linear(eqlist, fxconst):
54
53
  for eq in eqlist:
55
54
  varlist(eq, fxconst)
56
55
  vl = list(set(vl))
57
-
56
+
58
57
  if len(vl) > len(eqlist):
59
58
  return TreeNode("f_and", [TreeNode("f_eq", [x, tree_form("d_0")]) for x in eqlist])
60
59
  m = []
@@ -71,11 +70,11 @@ def linear(eqlist, fxconst):
71
70
  m[i][j] = simplify(expand(m[i][j]))
72
71
 
73
72
  m = rref(m)
74
-
73
+
75
74
  for i in range(len(m)):
76
75
  for j in range(len(m[i])):
77
76
  m[i][j] = fraction(m[i][j])
78
-
77
+
79
78
  output = []
80
79
  for index, row in enumerate(m):
81
80
  if not all(item == 0 for item in row[:-1]):
@@ -88,26 +87,17 @@ def linear(eqlist, fxconst):
88
87
  return tree_form("s_false")
89
88
  return TreeNode("f_and", [TreeNode("f_eq", [x, tree_form("d_0")]) for x in output])
90
89
  def order_collinear_indices(points, idx):
91
- """
92
- Arrange a subset of collinear points (given by indices) along their line.
93
90
 
94
- points: list of (x, y) tuples
95
- idx: list of indices referring to points
96
- Returns: list of indices sorted along the line
97
- """
98
91
  if len(idx) <= 1:
99
92
  return idx[:]
100
-
101
- # Take first two points from the subset to define the line
93
+
102
94
  p0, p1 = points[idx[0]], points[idx[1]]
103
95
  dx, dy = p1[0] - p0[0], p1[1] - p0[1]
104
-
105
- # Projection factor for sorting
96
+
106
97
  def projection_factor(i):
107
98
  vx, vy = points[i][0] - p0[0], points[i][1] - p0[1]
108
99
  return compute((vx * dx + vy * dy) / (dx**2 + dy**2))
109
-
110
- # Sort indices by projection
100
+
111
101
  sorted_idx = sorted(idx, key=projection_factor)
112
102
  return list(sorted_idx)
113
103
  def linear_or(eq):
@@ -124,12 +114,12 @@ def linear_or(eq):
124
114
  for item in itertools.combinations(enumerate(eqlst), 2):
125
115
  x, y = item[0][0], item[1][0]
126
116
  item = [item[0][1], item[1][1]]
127
-
117
+
128
118
  out = linear_solve(TreeNode("f_and", list(item)))
129
119
 
130
120
  if out is None:
131
121
  return None
132
-
122
+
133
123
  if out.name == "f_and" and all(len(vlist(child)) == 1 for child in out.children) and set(vlist(out)) == set(v) and all(len(vlist(simplify(child))) >0 for child in out.children):
134
124
  t = {}
135
125
  for child in out.children:
@@ -151,7 +141,7 @@ def linear_solve(eq, lst=None):
151
141
  eq = simplify(eq)
152
142
  eqlist = []
153
143
  if eq.name =="f_and" and all(child.name == "f_eq" and child.children[1] == 0 for child in eq.children):
154
-
144
+
155
145
  eqlist = [child.children[0] for child in eq.children]
156
146
  else:
157
147
  return eq
@@ -163,3 +153,4 @@ def linear_solve(eq, lst=None):
163
153
  if out is None:
164
154
  return None
165
155
  return simplify(out)
156
+
mathai/logic.py CHANGED
@@ -108,7 +108,7 @@ def logic2(eq):
108
108
  if len(lst) == 1:
109
109
  return lst[0]
110
110
  return TreeNode(eq.name, lst)
111
-
111
+
112
112
  if eq.name in ["f_and", "f_or"] and any(child.children is not None and len(child.children)!=0 for child in eq.children):
113
113
  for i in range(len(eq.children),1,-1):
114
114
  for item in itertools.combinations(enumerate(eq.children), i):
@@ -159,7 +159,7 @@ def logic1(eq):
159
159
  A, B = dowhile(A, logic2), dowhile(B, logic2)
160
160
  return flatten_tree((A & B) | (A.fx("not") & B.fx("not")))
161
161
  if eq.name == "f_imply":
162
-
162
+
163
163
  A, B = eq.children
164
164
  A, B = logic1(A), logic1(B)
165
165
  A, B = dowhile(A, logic2), dowhile(B, logic2)
@@ -171,32 +171,28 @@ def logic1(eq):
171
171
  return eq
172
172
  eq = helper(eq)
173
173
  eq = flatten_tree(eq)
174
-
174
+
175
175
  if len(eq.children) > 2:
176
176
  lst = []
177
177
  l = len(eq.children)
178
178
 
179
- # Handle last odd child directly
180
179
  if l % 2 == 1:
181
180
  last_child = eq.children[-1]
182
- # expand/simplify only if needed
181
+
183
182
  if isinstance(last_child, TreeNode):
184
183
  last_child = dowhile(last_child, logic2)
185
184
  lst.append(last_child)
186
185
  l -= 1
187
186
 
188
- # Pairwise combine children
189
187
  for i in range(0, l, 2):
190
188
  left, right = eq.children[i], eq.children[i+1]
191
189
  pair = TreeNode(eq.name, [left, right])
192
190
  simplified = dowhile(logic1(pair), logic2)
193
191
  lst.append(simplified)
194
192
 
195
- # If only one element left, just return it instead of nesting
196
193
  if len(lst) == 1:
197
194
  return flatten_tree(lst[0])
198
195
 
199
- # Otherwise rewrap
200
196
  return flatten_tree(TreeNode(eq.name, lst))
201
197
 
202
198
  if eq.name == "f_and":
@@ -228,3 +224,4 @@ def logic1(eq):
228
224
  out = out.children[0]
229
225
  return flatten_tree(out)
230
226
  return TreeNode(eq.name, [logic1(child) for child in eq.children])
227
+
mathai/matrix.py CHANGED
@@ -3,7 +3,6 @@ import copy
3
3
  from .simplify import simplify
4
4
  import itertools
5
5
 
6
- # ---------- tree <-> python list ----------
7
6
  def tree_to_py(node):
8
7
  if node.name=="f_list":
9
8
  return [tree_to_py(c) for c in node.children]
@@ -14,16 +13,13 @@ def py_to_tree(obj):
14
13
  return TreeNode("f_list",[py_to_tree(x) for x in obj])
15
14
  return obj
16
15
 
17
- # ---------- shape detection ----------
18
16
  def is_vector(x):
19
17
  return isinstance(x,list) and all(isinstance(item,TreeNode) for item in x)
20
18
  def is_mat(x):
21
19
  return isinstance(x,list) and all(isinstance(item,list) for item in x)
22
20
  def is_matrix(x):
23
21
  return isinstance(x, list) and all(isinstance(item, list) and (is_mat(item) or is_vector(item)) for item in x)
24
-
25
22
 
26
- # ---------- algebra primitives ----------
27
23
  def dot(u,v):
28
24
  if len(u)!=len(v):
29
25
  raise ValueError("Vector size mismatch")
@@ -33,9 +29,7 @@ def dot(u,v):
33
29
  return s
34
30
 
35
31
  def matmul(A, B):
36
- # A: n × m
37
- # B: m × p
38
-
32
+
39
33
  n = len(A)
40
34
  m = len(A[0])
41
35
  p = len(B[0])
@@ -54,7 +48,6 @@ def matmul(A, B):
54
48
  )
55
49
  return C
56
50
 
57
- # ---------- promotion ----------
58
51
  def promote(node):
59
52
  if node.name=="f_list":
60
53
  return tree_to_py(node)
@@ -68,7 +61,7 @@ def contains_neg(node):
68
61
  if not contains_neg(child):
69
62
  return False
70
63
  return True
71
- # ---------- multiplication (fully simplified) ----------
64
+
72
65
  def multiply(left,right):
73
66
  if left == tree_form("d_1"):
74
67
  return right
@@ -83,17 +76,16 @@ def multiply(left,right):
83
76
  return simplify(left2.children[0]**(left2.children[1]+right2.children[1]))
84
77
  A,B = promote(left), promote(right)
85
78
 
86
- # vector · vector
87
79
  if is_vector(A) and is_vector(B):
88
80
  return dot(A,B)
89
- # matrix × matrix
81
+
90
82
  if is_matrix(A) and is_matrix(B):
91
83
  return py_to_tree(matmul(A,B))
92
- # scalar × vector
84
+
93
85
  for _ in range(2):
94
86
  if contains_neg(A) and is_vector(B):
95
87
  return py_to_tree([TreeNode("f_mul",[A,x]) for x in B])
96
- # scalar × matrix
88
+
97
89
  if contains_neg(A) and is_matrix(B):
98
90
  return py_to_tree([[TreeNode("f_mul",[A,x]) for x in row] for row in B])
99
91
  A, B = B, A
@@ -122,45 +114,16 @@ def matadd(A, B):
122
114
  ]
123
115
  def addition(left,right):
124
116
  A,B = promote(left), promote(right)
125
- # vector + vector
117
+
126
118
  if is_vector(A) and is_vector(B):
127
119
  return add_vec(A,B)
128
- # matrix + matrix
120
+
129
121
  if is_matrix(A) and is_matrix(B):
130
122
  return py_to_tree(matadd(A,B))
131
123
  return None
132
- '''
133
- def fold_wmul(eq):
134
- if eq.name == "f_pow" and eq.children[1].name.startswith("d_"):
135
- n = int(eq.children[1].name[2:])
136
- if n == 1:
137
- eq = eq.children[0]
138
- elif n > 1:
139
- tmp = promote(eq.children[0])
140
- if is_matrix(tmp):
141
- orig =tmp
142
- for i in range(n-1):
143
- tmp = matmul(orig, tmp)
144
- eq = py_to_tree(tmp)
145
- elif eq.name in ["f_wmul", "f_add"]:
146
- if len(eq.children) == 1:
147
- eq = eq.children[0]
148
- else:
149
- i = len(eq.children)-1
150
- while i>0:
151
- if eq.name == "f_wmul":
152
- out = multiply(eq.children[i-1], eq.children[i])
153
- else:
154
- out = addition(eq.children[i-1], eq.children[i])
155
- if out is not None:
156
- eq.children.pop(i)
157
- eq.children.pop(i-1)
158
- eq.children.insert(i-1,out)
159
- i = i-1
160
- return TreeNode(eq.name, [fold_wmul(child) for child in eq.children])
161
- '''
124
+
162
125
  def fold_wmul(root):
163
- # Post-order traversal using explicit stack
126
+
164
127
  stack = [(root, False)]
165
128
  newnode = {}
166
129
 
@@ -168,17 +131,15 @@ def fold_wmul(root):
168
131
  node, visited = stack.pop()
169
132
 
170
133
  if not visited:
171
- # First time: push back as visited, then children
134
+
172
135
  stack.append((node, True))
173
136
  for child in node.children:
174
137
  stack.append((child, False))
175
138
  else:
176
- # All children already processed
139
+
177
140
  children = [newnode[c] for c in node.children]
178
141
  eq = TreeNode(node.name, children)
179
142
 
180
- # ---- original rewrite logic ----
181
-
182
143
  if eq.name == "f_pow" and eq.children[1].name.startswith("d_"):
183
144
  n = int(eq.children[1].name[2:])
184
145
  if n == 1:
@@ -208,8 +169,6 @@ def fold_wmul(root):
208
169
  eq.children.insert(i - 1, out)
209
170
  i -= 1
210
171
 
211
- # --------------------------------
212
-
213
172
  newnode[node] = eq
214
173
 
215
174
  return newnode[root]
@@ -223,3 +182,4 @@ def _matrix_solve(eq):
223
182
  return eq
224
183
  def matrix_solve(eq):
225
184
  return _matrix_solve(eq)
185
+