mathai 2.4.6__tar.gz → 2.4.7__tar.gz

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.
Files changed (43) hide show
  1. {mathai-2.4.6 → mathai-2.4.7}/PKG-INFO +1 -1
  2. {mathai-2.4.6 → mathai-2.4.7}/mathai/__init__.py +3 -1
  3. mathai-2.4.7/mathai/benchmark.py +312 -0
  4. {mathai-2.4.6 → mathai-2.4.7}/mathai/decision.py +15 -0
  5. {mathai-2.4.6 → mathai-2.4.7}/mathai.egg-info/PKG-INFO +1 -1
  6. {mathai-2.4.6 → mathai-2.4.7}/setup.py +1 -1
  7. mathai-2.4.6/mathai/benchmark.py +0 -63
  8. {mathai-2.4.6 → mathai-2.4.7}/README.md +0 -0
  9. {mathai-2.4.6 → mathai-2.4.7}/mathai/apart.py +0 -0
  10. {mathai-2.4.6 → mathai-2.4.7}/mathai/base.py +0 -0
  11. {mathai-2.4.6 → mathai-2.4.7}/mathai/diff.py +0 -0
  12. {mathai-2.4.6 → mathai-2.4.7}/mathai/electronic.py +0 -0
  13. {mathai-2.4.6 → mathai-2.4.7}/mathai/expand.py +0 -0
  14. {mathai-2.4.6 → mathai-2.4.7}/mathai/factor.py +0 -0
  15. {mathai-2.4.6 → mathai-2.4.7}/mathai/formula_applier.py +0 -0
  16. {mathai-2.4.6 → mathai-2.4.7}/mathai/formula_compiler.py +0 -0
  17. {mathai-2.4.6 → mathai-2.4.7}/mathai/fraction.py +0 -0
  18. {mathai-2.4.6 → mathai-2.4.7}/mathai/graphics.py +0 -0
  19. {mathai-2.4.6 → mathai-2.4.7}/mathai/integrate.py +0 -0
  20. {mathai-2.4.6 → mathai-2.4.7}/mathai/inverse.py +0 -0
  21. {mathai-2.4.6 → mathai-2.4.7}/mathai/lambda_calculus.py +0 -0
  22. {mathai-2.4.6 → mathai-2.4.7}/mathai/limit.py +0 -0
  23. {mathai-2.4.6 → mathai-2.4.7}/mathai/linear.py +0 -0
  24. {mathai-2.4.6 → mathai-2.4.7}/mathai/logic.py +0 -0
  25. {mathai-2.4.6 → mathai-2.4.7}/mathai/matrix.py +0 -0
  26. {mathai-2.4.6 → mathai-2.4.7}/mathai/ml.py +0 -0
  27. {mathai-2.4.6 → mathai-2.4.7}/mathai/mlscalar.py +0 -0
  28. {mathai-2.4.6 → mathai-2.4.7}/mathai/ncert_data.txt +0 -0
  29. {mathai-2.4.6 → mathai-2.4.7}/mathai/ode.py +0 -0
  30. {mathai-2.4.6 → mathai-2.4.7}/mathai/parser.py +0 -0
  31. {mathai-2.4.6 → mathai-2.4.7}/mathai/pde.py +0 -0
  32. {mathai-2.4.6 → mathai-2.4.7}/mathai/printeq.py +0 -0
  33. {mathai-2.4.6 → mathai-2.4.7}/mathai/qm.py +0 -0
  34. {mathai-2.4.6 → mathai-2.4.7}/mathai/simplify.py +0 -0
  35. {mathai-2.4.6 → mathai-2.4.7}/mathai/statistics.py +0 -0
  36. {mathai-2.4.6 → mathai-2.4.7}/mathai/test.py +0 -0
  37. {mathai-2.4.6 → mathai-2.4.7}/mathai/tool.py +0 -0
  38. {mathai-2.4.6 → mathai-2.4.7}/mathai/trig.py +0 -0
  39. {mathai-2.4.6 → mathai-2.4.7}/mathai/univariate_inequality.py +0 -0
  40. {mathai-2.4.6 → mathai-2.4.7}/mathai.egg-info/SOURCES.txt +0 -0
  41. {mathai-2.4.6 → mathai-2.4.7}/mathai.egg-info/dependency_links.txt +0 -0
  42. {mathai-2.4.6 → mathai-2.4.7}/mathai.egg-info/top_level.txt +0 -0
  43. {mathai-2.4.6 → mathai-2.4.7}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mathai
3
- Version: 2.4.6
3
+ Version: 2.4.7
4
4
  Summary: Mathematics solving Ai tailored to NCERT
5
5
  Home-page: https://github.com/infinity390/mathai
6
6
  Requires-Python: >=3.7
@@ -1,3 +1,5 @@
1
+ from .benchmark import load_sequences, strategy_tree, execute_parallel
2
+
1
3
  from .ode import diffsolve as ode_solve
2
4
  from .ode import diffsolve_sep as ode_shift_term
3
5
 
@@ -20,7 +22,7 @@ from .linear import linear_solve
20
22
 
21
23
  from .test import test
22
24
 
23
- from .decision import god
25
+ from .decision import god, god2
24
26
 
25
27
  from .expand import expand
26
28
 
@@ -0,0 +1,312 @@
1
+ import atexit
2
+ import copy
3
+ import multiprocessing
4
+ from pathlib import Path
5
+
6
+ from .simplify import simplify
7
+ from .expand import expand
8
+ from .parser import parse
9
+ from .fraction import fraction
10
+ from .apart import apart
11
+ from .integrate import (
12
+ integrate_formula,
13
+ integrate_trig_formula,
14
+ integrate_fraction,
15
+ integrate_subs_main as integrate_subs,
16
+ solve_integrate as integrate_clean,
17
+ )
18
+ from .factor import factor2
19
+ from .trig import trig0, trig1, trig4, trig6
20
+ from .univariate_inequality import simple_wavycurvy, absolute
21
+ from .limit import limit1
22
+ from .logic import logic0
23
+ from .base import *
24
+
25
+
26
+ fx_list = [
27
+ lambda x: dowhile(x, absolute),
28
+ logic0,
29
+ limit1,
30
+ simple_wavycurvy,
31
+ simplify,
32
+ expand,
33
+ fraction,
34
+ integrate_formula,
35
+ integrate_subs,
36
+ integrate_trig_formula,
37
+ integrate_clean,
38
+ apart,
39
+ trig0,
40
+ trig1,
41
+ trig4,
42
+ integrate_fraction,
43
+ factor2,
44
+ trig6,
45
+ ]
46
+
47
+ name_list = """
48
+ absolute logic0 limit1 simple_wavycurvy simplify expand fraction
49
+ integrate_formula integrate_subs integrate_trig_formula
50
+ integrate_clean apart trig0 trig1 trig4 integrate_fraction factor2 trig6
51
+ """.split()
52
+
53
+ # O(1) name -> function lookup
54
+ FUNCS = dict(zip(name_list, fx_list))
55
+
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # Benchmark
59
+ # ---------------------------------------------------------------------------
60
+
61
+
62
+ def benchmark(s="ncert_data"):
63
+ data_path = Path(__file__).parent / f"{s}.txt"
64
+ output_path = Path(__file__).parent / f"{s}_optimized.txt"
65
+
66
+ optimized_lines = []
67
+
68
+ with open(data_path, "r", encoding="utf-8") as file:
69
+ for count, line in enumerate(file, 1):
70
+ parts = line.split()
71
+
72
+ if not parts:
73
+ continue
74
+
75
+ expr_str, *function_names = parts
76
+ eq = simplify(parse(expr_str))
77
+ effective_steps = [expr_str]
78
+
79
+ for func_name in function_names:
80
+ func = FUNCS[func_name]
81
+ prev_eq = copy.deepcopy(eq)
82
+ eq = func(eq)
83
+
84
+ if eq != prev_eq:
85
+ effective_steps.append(func_name)
86
+
87
+ print(f"{count}. {expr_str} => {eq}")
88
+ optimized_lines.append(" ".join(effective_steps))
89
+
90
+ with open(output_path, "w", encoding="utf-8") as file:
91
+ file.write("\n".join(optimized_lines) + "\n")
92
+
93
+ print(f"\nOptimized dataset successfully written to: {output_path}")
94
+
95
+
96
+ # ---------------------------------------------------------------------------
97
+ # Strategy tree
98
+ # ---------------------------------------------------------------------------
99
+
100
+
101
+ class Node:
102
+ def __init__(self, value):
103
+ self.value = value
104
+ self.children = {} # Dictionary for O(1) child lookup
105
+
106
+ def add_child(self, value):
107
+ if value not in self.children:
108
+ self.children[value] = Node(value)
109
+ return self.children[value]
110
+
111
+ def execute(self, equation, sequence=None, terminal_condition=None):
112
+ if sequence is None:
113
+ sequence = []
114
+
115
+ if self.value != "ROOT":
116
+ func = FUNCS[self.value]
117
+
118
+ # Track previous state to detect and prune no-ops
119
+ prev_eq = copy.deepcopy(equation)
120
+ equation = func(equation)
121
+
122
+ # PRUNING: if the function didn't change the equation, halt this branch
123
+ if equation == prev_eq:
124
+ return []
125
+
126
+ sequence = sequence + [self.value]
127
+
128
+ # Check terminal condition after applying the function
129
+ if terminal_condition is not None and terminal_condition(equation):
130
+ return [(equation, sequence)]
131
+
132
+ if not self.children:
133
+ return [(equation, sequence)]
134
+
135
+ results = []
136
+ for child in self.children.values():
137
+ results.extend(
138
+ child.execute(copy.deepcopy(equation), sequence, terminal_condition)
139
+ )
140
+
141
+ return results
142
+
143
+
144
+ def strategy_tree(sequences):
145
+ root = Node("ROOT")
146
+
147
+ for sequence in sequences:
148
+ node = root
149
+
150
+ for function_name in sequence:
151
+ node = node.add_child(function_name)
152
+
153
+ return root
154
+
155
+
156
+ def load_sequences(s="ncert_data"):
157
+ data_path = Path(__file__).parent / f"{s}.txt"
158
+ sequences = []
159
+
160
+ with open(data_path, "r", encoding="utf-8") as file:
161
+ for line in file:
162
+ parts = line.split()
163
+
164
+ if parts:
165
+ sequences.append(parts[1:])
166
+
167
+ return sequences
168
+
169
+
170
+ def print_tree(node, depth=0):
171
+ print(" " * depth + str(node.value))
172
+
173
+ for child in node.children.values():
174
+ print_tree(child, depth + 1)
175
+
176
+
177
+ # ---------------------------------------------------------------------------
178
+ # Parallel execution
179
+ #
180
+ # Design: nothing heavy is pickled per call.
181
+ # - Each worker builds the tree once, from the dataset name, at pool start.
182
+ # - Terminal conditions are looked up by name in TERMINAL_CONDITIONS, so no
183
+ # function object is ever sent to a worker.
184
+ # - Pools persist across calls, so spawn/import cost is paid once.
185
+ # - Per task, only (branch index, equation, condition name, generation)
186
+ # is sent.
187
+ # ---------------------------------------------------------------------------
188
+
189
+ # Register terminal conditions here. Workers re-import this module and find
190
+ # them by name.
191
+ TERMINAL_CONDITIONS = {
192
+ "no_integrate": lambda eq: not contain2(eq, "f_integrate"),
193
+ }
194
+
195
+ _TREES = {} # data_name -> root Node (cached per process)
196
+ _POOLS = {} # (data_name, n_cores) -> (pool, generation counter)
197
+
198
+ # Worker-process globals, set once by _init_worker
199
+ _W_BRANCHES = None
200
+ _W_GEN = None
201
+
202
+
203
+ def _get_tree(data_name):
204
+ if data_name not in _TREES:
205
+ _TREES[data_name] = strategy_tree(load_sequences(data_name))
206
+ return _TREES[data_name]
207
+
208
+
209
+ def _init_worker(data_name, gen):
210
+ global _W_BRANCHES, _W_GEN
211
+ _W_BRANCHES = list(_get_tree(data_name).children.values())
212
+ _W_GEN = gen
213
+
214
+
215
+ def _worker(task):
216
+ idx, equation, cond_name, my_gen = task
217
+
218
+ # Stale task left over from a call that already finished: skip it.
219
+ if _W_GEN.value != my_gen:
220
+ return []
221
+
222
+ cond = TERMINAL_CONDITIONS[cond_name] if cond_name else None
223
+ try:
224
+ return _W_BRANCHES[idx].execute(equation, [], cond)
225
+ except Exception:
226
+ # A failing branch must not discard results from other branches.
227
+ return []
228
+
229
+
230
+ def _first_match(results, cond):
231
+ for eq, seq in results:
232
+ if cond is None or cond(eq):
233
+ return [(eq, seq)]
234
+ return None
235
+
236
+
237
+ def _execute_sequential(data_name, equation, cond_name):
238
+ cond = TERMINAL_CONDITIONS[cond_name] if cond_name else None
239
+
240
+ for child in _get_tree(data_name).children.values():
241
+ try:
242
+ results = child.execute(copy.deepcopy(equation), [], cond)
243
+ except Exception:
244
+ continue # same semantics as the workers
245
+
246
+ match = _first_match(results, cond)
247
+ if match is not None:
248
+ return match
249
+
250
+ return []
251
+
252
+
253
+ def _get_pool(data_name, n_cores):
254
+ key = (data_name, n_cores)
255
+
256
+ if key not in _POOLS:
257
+ gen = multiprocessing.Value("i", 0, lock=False)
258
+ pool = multiprocessing.Pool(
259
+ n_cores, initializer=_init_worker, initargs=(data_name, gen)
260
+ )
261
+ _POOLS[key] = (pool, gen)
262
+
263
+ return _POOLS[key]
264
+
265
+
266
+ def shutdown_pools():
267
+ for pool, _ in _POOLS.values():
268
+ pool.terminate()
269
+ pool.join()
270
+ _POOLS.clear()
271
+
272
+
273
+ atexit.register(shutdown_pools)
274
+
275
+
276
+ def execute_parallel(data_name, equation, n_cores=None, condition_name=None):
277
+ """
278
+ Run the strategy tree for `data_name` against `equation` and return at
279
+ most one result as a one-item list [(equation, sequence)].
280
+
281
+ condition_name: key into TERMINAL_CONDITIONS, or None.
282
+
283
+ On Windows/macOS (spawn start method) callers using n_cores > 1 must be
284
+ guarded by ``if __name__ == "__main__":``.
285
+ """
286
+ n_branches = len(_get_tree(data_name).children)
287
+ if n_branches == 0:
288
+ return []
289
+
290
+ if n_cores is None:
291
+ n_cores = multiprocessing.cpu_count()
292
+ # Never more processes than branches, never fewer than one
293
+ n_cores = max(1, min(n_cores, n_branches))
294
+
295
+ if n_cores == 1:
296
+ return _execute_sequential(data_name, equation, condition_name)
297
+
298
+ cond = TERMINAL_CONDITIONS[condition_name] if condition_name else None
299
+ pool, gen = _get_pool(data_name, n_cores)
300
+
301
+ my_gen = gen.value + 1
302
+ gen.value = my_gen
303
+ tasks = [(i, equation, condition_name, my_gen) for i in range(n_branches)]
304
+
305
+ try:
306
+ for branch_results in pool.imap_unordered(_worker, tasks):
307
+ match = _first_match(branch_results, cond)
308
+ if match is not None:
309
+ return match
310
+ return []
311
+ finally:
312
+ gen.value = my_gen + 1 # cancels any still-queued tasks
@@ -15,6 +15,7 @@ from .factor import factor2, factor
15
15
  from .limit import limit1, limit5
16
16
  from .linear import linear_solve
17
17
  from .matrix import matrix_solve, matrix_formula
18
+ from .benchmark import load_sequences, strategy_tree, execute_parallel
18
19
 
19
20
  def vlist_2(eq):
20
21
  out = []
@@ -60,6 +61,20 @@ def solve_subs(q):
60
61
  if len(solution.keys()) == 0:
61
62
  return orig
62
63
  return operation("f_and", [item for item in lst if all(not contain(item, tree_form(key)) for key in solution.keys())] + [TreeNode("f_eq", [tree_form(key), item]) for key, item in solution.items()])
64
+
65
+
66
+ def god2(string, core=1):
67
+ out = execute_parallel(
68
+ "ncert_data", simplify(parse(string)), core, "no_integrate"
69
+ )
70
+
71
+ if len(out) >= 1:
72
+ print(string)
73
+ print("=>", out[0][0])
74
+ print(["parse", "simplify"] + out[0][1])
75
+
76
+ return out
77
+
63
78
  def god(string, debug=True):
64
79
  if debug:
65
80
  print(f"? {string}")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mathai
3
- Version: 2.4.6
3
+ Version: 2.4.7
4
4
  Summary: Mathematics solving Ai tailored to NCERT
5
5
  Home-page: https://github.com/infinity390/mathai
6
6
  Requires-Python: >=3.7
@@ -3,7 +3,7 @@ from setuptools import setup, find_packages
3
3
 
4
4
  setup(
5
5
  name="mathai",
6
- version="2.4.6",
6
+ version="2.4.7",
7
7
  description="Mathematics solving Ai tailored to NCERT",
8
8
  long_description=Path("README.md").read_text(encoding="utf-8"),
9
9
  long_description_content_type="text/markdown",
@@ -1,63 +0,0 @@
1
- import random
2
- import copy
3
- from pathlib import Path
4
- from .simplify import simplify
5
- from .expand import expand
6
- from .parser import parse
7
- from .fraction import fraction
8
- from .apart import apart
9
- from .integrate import integrate_formula, integrate_trig_formula, integrate_fraction
10
- from .integrate import integrate_subs_main as integrate_subs
11
- from .integrate import solve_integrate as integrate_clean
12
- from .factor import factor2
13
- from .trig import trig0, trig1, trig4, trig6
14
- from .univariate_inequality import simple_wavycurvy, absolute
15
- from .limit import limit1
16
- from .logic import logic0
17
- from .base import *
18
-
19
- fx_list = [lambda x: dowhile(x, absolute), logic0, limit1, simple_wavycurvy, simplify, expand, fraction, integrate_formula, integrate_subs, integrate_trig_formula, integrate_clean, apart, trig0, trig1, trig4, integrate_fraction, factor2, trig6]
20
- name_list = "absolute, logic0, limit1, simple_wavycurvy, simplify, expand, fraction, integrate_formula, integrate_subs, integrate_trig_formula, integrate_clean, apart, trig0, trig1, trig4, integrate_fraction, factor2, trig6".split(", ")
21
-
22
- def benchmark(s="ncert_data"):
23
- data_path = Path(__file__).parent / f"{s}.txt"
24
- output_path = Path(__file__).parent / f"{s}_optimized.txt"
25
-
26
- optimized_lines = []
27
-
28
- with open(data_path, "r", encoding="utf-8") as file:
29
- content = file.read().strip().split("\n")
30
- count = 0
31
- for item in content:
32
- count += 1
33
- item = item.strip()
34
- if not item:
35
- continue
36
- parts = item.split(" ")
37
- expr_str = parts[0]
38
- eq = simplify(parse(expr_str))
39
-
40
- effective_steps = [expr_str]
41
-
42
- for func_name in parts[1:]:
43
- func_idx = name_list.index(func_name)
44
- func = fx_list[func_idx]
45
-
46
- # Deepcopy to avoid in-place mutation reference traps
47
- prev_eq = copy.deepcopy(eq)
48
- eq = func(eq)
49
-
50
- # Check if the function changed the equation
51
- if eq == prev_eq:
52
- pass
53
- else:
54
- effective_steps.append(func_name)
55
-
56
- print(f"{count}. {expr_str} => {eq}")
57
- optimized_lines.append(" ".join(effective_steps))
58
-
59
- # Write out the optimized lines without non-changing functions
60
- with open(output_path, "w", encoding="utf-8") as outfile:
61
- outfile.write("\n".join(optimized_lines) + "\n")
62
-
63
- print(f"\nOptimized dataset successfully written to: {output_path}")
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes