Shalyt commited on
Commit
2f63916
·
verified ·
1 Parent(s): 672a413

Upload ASyMOB_Generation.py

Browse files
Files changed (1) hide show
  1. ASyMOB_Generation.py +348 -0
ASyMOB_Generation.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ import json
3
+ import sympy as sp
4
+ import re
5
+ import random
6
+ import itertools
7
+
8
+ # Load CSV file containing seed questions and maximal symbolic perturbations.
9
+ csv_file_path = 'Seed_and_Max_Symbolic_Perturbations.csv'
10
+
11
+ with open(csv_file_path, 'r', encoding='utf-8') as cf:
12
+ data = list(csv.DictReader(cf)) # Read CSV into list of dicts
13
+ cur_data_len = len(data)
14
+ print("Length of initial data: ", cur_data_len) # Print initial dataset size
15
+
16
+ # Define symbolic variables that appear in the symbolic perturbations - and will be replaced by various expressions during variant generation.
17
+ x, A, B, F, G, H, N = sp.symbols('x A B F G H N', real=True)
18
+ Q = sp.symbols('Q', real=True, positive=True)
19
+
20
+
21
+ # Define symbolic perturbation characters and their corresponding sympy symbols
22
+ symnoise_char_list = ['A', 'B', 'F', 'G', 'H']
23
+ symnoise_sym_list = [A, B, F, G, H]
24
+ local_sym_dict = {'x': x, 'A': A, 'B': B, 'F': F, 'G': G, 'H': H, 'N': N, 'Q': Q}
25
+
26
+ # These sources contain explicit hypergeometric functions, which are marked by 'F' - so 'F' is not treated as a symbolic perturbation character.
27
+ # The hg_ variables below represent this special treatment.
28
+ hypergeomatric_question_sources = ["ASyMOB\nHypergeometrics\nQ1", "ASyMOB\nHypergeometrics\nQ2", "ASyMOB\nHypergeometrics\nQ3", "ASyMOB\nHypergeometrics\nQ4"]
29
+ hg_symnoise_char_list = ['A', 'B', 'G', 'H']
30
+ hg_symnoise_sym_list = [A, B, G, H]
31
+ hg_local_sym_dict = {'x': x, 'A': A, 'B': B, 'G': G, 'H': H, 'N': N, 'Q': Q}
32
+
33
+
34
+ # List of easy equivalent forms (should simplify to 1)
35
+ equivalent_forms_easy = [
36
+ sp.sin(-Q*x)**2 + sp.cos(Q*x)**2,
37
+ -sp.sinh(Q*x)**2 + sp.cosh(Q*x)**2,
38
+ (sp.log(x) * sp.log(Q,x))/sp.log(Q),
39
+ Q * sp.Sum( x / (Q * 2**N) , (N, 1, sp.oo)) / x,
40
+ (sp.exp(sp.I * Q * x) - sp.exp(-sp.I * Q * x)) / (2 * sp.I * sp.sin(Q * x))
41
+ ]
42
+ # List of hard equivalent forms (should simplify to 1)
43
+ equivalent_forms_hard = [
44
+ (sp.tan((Q-1)*x) + sp.tan(x)) / ((1 - sp.tan((Q-1)*x) * sp.tan(x)) * sp.tan(Q*x)),
45
+ sp.sinh(sp.log(Q*x + sp.sqrt((Q*x)**2 + 1))) / (Q*x),
46
+ (sp.log(x / sp.E, Q) + sp.log(sp.E, Q))/ sp.log(x, Q),
47
+ Q * sp.Sum( (6 * x) / (Q * (N * sp.pi)**2) , (N, 1, sp.oo)) / x,
48
+ -((1 + sp.exp(4 * sp.I * Q * x)) / (1 - sp.exp(4 * sp.I * Q * x))) * (2 * sp.tan(Q*x) / ((1 - sp.tan(Q*x)**2)) * sp.I)
49
+ ]
50
+
51
+ # Test that all equivalent forms simplify to 1 and are numerically close to 1.
52
+ # Note that some expressions above do not simplify to 1 by sp.simplify - due to the CAS's limitations - but are evaluated correctly to 1 numerically.
53
+ # We still print the warning to raise user awareness.
54
+ equivalence_test_x = -2.5
55
+ equivalence_test_Q = 0.5
56
+ equivalence_test_margin = 1e-4
57
+ for form in (equivalent_forms_easy + equivalent_forms_hard):
58
+ # Check if the form is equivalent to 1
59
+ if sp.simplify(form) != 1 or (abs(form.subs(Q, equivalence_test_Q).subs(x, equivalence_test_x).evalf() - 1) > equivalence_test_margin):
60
+ print(f"Form {form} is not equivalent to 1")
61
+ print(f"{form} is simplified to {sp.simplify(form)}")
62
+ print("Form is numerically evaluated to: ", form.subs(Q, equivalence_test_Q).subs(x, equivalence_test_x).evalf())
63
+
64
+ # LaTeX representations of the easy and hard equivalent forms
65
+ eq_forms_latex_easy = [
66
+ r'\sin^{2}{\left(- Q x \right)} + \cos^{2}{\left(Q x \right)}',
67
+ r'- \sinh^{2}{\left(Q x \right)} + \cosh^{2}{\left(Q x \right)}',
68
+ r'\frac{\ln(x) \cdot \log_{x}(Q)}{\ln(Q)}',
69
+ r'\frac{Q \sum_{N=1}^{\infty} \frac{2^{- N} x}{Q}}{x}',
70
+ r'- \frac{i \left(e^{i Q x} - e^{- i Q x}\right)}{2 \sin{\left(Q x \right)}}']
71
+ eq_forms_latex_hard = [
72
+ r'\frac{\tan{\left(x \right)} + \tan{\left(x \left(Q - 1\right) \right)}}{\left(- \tan{\left(x \right)} \tan{\left(x \left(Q - 1\right) \right)} + 1\right) \tan{\left(Q x \right)}}',
73
+ r'\frac{\sinh{\left(\log{\left(Q x + \sqrt{Q^{2} x^{2} + 1} \right)} \right)}}{Q x}',
74
+ r'\frac{\log_Q\left(\frac{x}{e}\right) + \log_Q(e)}{\log_Q(x)}',
75
+ r'\frac{Q \sum_{N=1}^{\infty} \frac{6 x}{\pi^{2} N^{2} Q}}{x}',
76
+ r'- \frac{2 i \left(e^{4 i Q x} + 1\right) \tan{\left(Q x \right)}}{\left(1 - e^{4 i Q x}\right) \left(1 - \tan^{2}{\left(Q x \right)}\right)}']
77
+
78
+ def replace_in_dollars(s, old, new):
79
+ # Replace 'old' with 'new' inside all $...$ math substrings in s
80
+ def repl(match):
81
+ return match.group(0).replace(old, new)
82
+ return re.sub(r'\$(.*?)\$', repl, s)
83
+
84
+ def char_in_dollars(s, char):
85
+ """Return True if char appears inside any $...$ substring in s."""
86
+ matches = re.findall(r'\$(.*?)\$', s)
87
+ return any(char in match for match in matches)
88
+
89
+ def check_for_problematic_symbols(sp_ans):
90
+ """Check for problematic symbols in sp_ans, but allow infinities if they are only used as summation or integration limits."""
91
+ # Check for NaN or zoo anywhere
92
+ if sp_ans.has(sp.nan) or sp_ans.has(sp.zoo):
93
+ return True
94
+ # Check for oo or -oo not as summation/integration limits
95
+ def has_bad_infinity(expr):
96
+ # If it's a Sum or Integral, skip limits
97
+ if isinstance(expr, (sp.Sum, sp.Integral)):
98
+ # expr.limits is a tuple of tuples: (symbol, lower, upper)
99
+ # Only check the function part, not the limits
100
+ return has_bad_infinity(expr.function)
101
+ # If it's an infinity itself, it's problematic
102
+ if expr == sp.oo or expr == -sp.oo:
103
+ return True
104
+ # Recursively check args
105
+ return any(has_bad_infinity(arg) for arg in getattr(expr, 'args', []))
106
+ return has_bad_infinity(sp_ans)
107
+
108
+ # Generate symbolic and numeric variants for each item in the dataset
109
+ def generate_variants(items, symnoise_chars, symnoise_syms, sym_dict, cur_ind):
110
+ next_ind = cur_ind
111
+ new_items = []
112
+ for item in items:
113
+ latex_chall = item.get("Challenge")
114
+ sp_sym_ans = sp.sympify(item.get("Answer in Sympy"), locals = sym_dict)
115
+ source = item.get("Source")
116
+ chars_in_latex = []
117
+ syms_in_latex = []
118
+ # Find which symbolic perturbation characters are present in the LaTeX challenge
119
+ for i in range(len(symnoise_chars)):
120
+ if char_in_dollars(latex_chall, symnoise_chars[i]):
121
+ chars_in_latex.append(symnoise_chars[i])
122
+ syms_in_latex.append(symnoise_syms[i])
123
+ if len(chars_in_latex) == 0:
124
+ print("No symbolic parameters found inside math expressions in source: ",source)
125
+
126
+ item['Variation'] = f"Symbolic-{len(chars_in_latex)}"
127
+
128
+ # Replace all symbols in symnoise_sym_list by 1 for equivalence perturbation answers.
129
+ sp_sym_ans_ones = sp_sym_ans.subs(dict(zip(symnoise_syms, [1]*len(symnoise_syms))))
130
+ # Check for problematic symbols in sp_sym_ans_ones
131
+ if check_for_problematic_symbols(sp_sym_ans_ones):
132
+ print(f"Warning: sp_sym_ans_ones for {item} contains problematic symbol(s): {sp_sym_ans_ones}")
133
+
134
+ # Generate all permutations of easy/hard equivalent forms for all symbolic chars
135
+ ordered_sets = list(itertools.permutations(range(len(eq_forms_latex_easy)), len(chars_in_latex)))
136
+ for order in ordered_sets:
137
+ # Substitute easy forms
138
+ latex_chall_copy = latex_chall
139
+ for i in range(len(chars_in_latex)):
140
+ latex_chall_copy = replace_in_dollars(latex_chall_copy, chars_in_latex[i], r' \left(' + eq_forms_latex_easy[order[i]].replace('Q', chars_in_latex[i]) + r'\right) ' )
141
+ next_ind += 1
142
+ new_items.append({
143
+ "Index": str(next_ind),
144
+ "Challenge": latex_chall_copy,
145
+ "Answer in Sympy": str(sp_sym_ans_ones),
146
+ "Answer in Latex": "",
147
+ "Variation": "Equivalence-All-Easy",
148
+ "Source": source
149
+ })
150
+ # Substitute hard forms
151
+ latex_chall_copy = latex_chall
152
+ for i in range(len(chars_in_latex)):
153
+ latex_chall_copy = replace_in_dollars(latex_chall_copy, chars_in_latex[i], r' \left(' + eq_forms_latex_hard[order[i]].replace('Q', chars_in_latex[i]) + r'\right) ' )
154
+ next_ind += 1
155
+ new_items.append({
156
+ "Index": str(next_ind),
157
+ "Challenge": latex_chall_copy,
158
+ "Answer in Sympy": str(sp_sym_ans_ones),
159
+ "Answer in Latex": "",
160
+ "Variation": "Equivalence-All-Hard",
161
+ "Source": source
162
+ })
163
+
164
+ # Generate single-symbolic substitutions (easy/hard) and numeric perturbation variants
165
+ for i in range(len(chars_in_latex)):
166
+ chars_left_in_latex = chars_in_latex.copy()
167
+ chars_left_in_latex.pop(i)
168
+ for j in range(len(eq_forms_latex_easy)):
169
+ # Substitute one easy form
170
+ latex_chall_copy = latex_chall
171
+ replace_form = r' \left(' + eq_forms_latex_easy[j].replace('Q', chars_in_latex[i]) + r'\right) '
172
+ latex_chall_copy = replace_in_dollars(latex_chall_copy, chars_in_latex[i], replace_form )
173
+ for ch in chars_left_in_latex:
174
+ latex_chall_copy = replace_in_dollars(latex_chall_copy, ch, '')
175
+ next_ind += 1
176
+ new_items.append({
177
+ "Index": str(next_ind),
178
+ "Challenge": latex_chall_copy,
179
+ "Answer in Sympy": str(sp_sym_ans_ones),
180
+ "Answer in Latex": "",
181
+ "Variation": "Equivalence-One-Easy",
182
+ "Source": source
183
+ })
184
+ # Substitute one hard form
185
+ latex_chall_copy = latex_chall
186
+ replace_form = r' \left(' + eq_forms_latex_hard[j].replace('Q', chars_in_latex[i]) + r'\right) '
187
+ latex_chall_copy = replace_in_dollars(latex_chall_copy, chars_in_latex[i], replace_form)
188
+ for ch in chars_left_in_latex:
189
+ latex_chall_copy = replace_in_dollars(latex_chall_copy, ch, '')
190
+ next_ind += 1
191
+ new_items.append({
192
+ "Index": str(next_ind),
193
+ "Challenge": latex_chall_copy,
194
+ "Answer in Sympy": str(sp_sym_ans_ones),
195
+ "Answer in Latex": "",
196
+ "Variation": "Equivalence-One-Hard",
197
+ "Source": source
198
+ })
199
+
200
+ # Numeric perturbation: replace one symbol with a random integer of increasing digit length
201
+ for noise_digits in range(1, 11):
202
+ latex_chall_copy = latex_chall
203
+ sp_sym_ans_copy = sp_sym_ans
204
+ nn1 = random.randint(10**(noise_digits-1), 10**noise_digits - 1)
205
+ sp_sym_ans_copy = sp_sym_ans_copy.subs(syms_in_latex[i], sp.UnevaluatedExpr(nn1), evaluate=False)
206
+ while check_for_problematic_symbols(sp_sym_ans_copy):
207
+ print(f"Warning: Numeric-One noise for {item} contains problems: {sp_sym_ans_copy}. Retrying")
208
+ nn1 = random.randint(10**(noise_digits-1), 10**noise_digits - 1)
209
+ sp_sym_ans_copy = sp_sym_ans_copy.subs(syms_in_latex[i], sp.UnevaluatedExpr(nn1), evaluate=False)
210
+ replace_form = r' \left(' + str(nn1) + r'\right) '
211
+ latex_chall_copy = replace_in_dollars(latex_chall_copy, chars_in_latex[i], replace_form)
212
+ for ch in chars_left_in_latex:
213
+ latex_chall_copy = replace_in_dollars(latex_chall_copy, ch, '')
214
+ for sym in syms_in_latex:
215
+ sp_sym_ans_copy = sp_sym_ans_copy.subs(sym, 1)
216
+ latex_chall_copy = re.sub(r'Assume.*?\.', '', latex_chall_copy)
217
+ next_ind += 1
218
+ new_items.append({
219
+ "Index": str(next_ind),
220
+ "Challenge": latex_chall_copy,
221
+ "Answer in Sympy": str(sp_sym_ans_copy),
222
+ "Answer in Latex": "",
223
+ "Variation": f"Numeric-One-{noise_digits}",
224
+ "Source": source
225
+ })
226
+
227
+
228
+ # Numeric perturbation: replace all symbols with random integers of increasing digit length
229
+ for noise_digits in range(1, 11):
230
+ latex_chall_copy = latex_chall
231
+ sp_sym_ans_copy = sp_sym_ans
232
+ nn_lst = [random.randint(10**(noise_digits-1), 10**noise_digits - 1) for _ in range(len(chars_in_latex))]
233
+ for i in range(len(chars_in_latex)):
234
+ sp_sym_ans_copy = sp_sym_ans_copy.subs(syms_in_latex[i], sp.UnevaluatedExpr(nn_lst[i]), evaluate=False)
235
+ while check_for_problematic_symbols(sp_sym_ans_copy):
236
+ print(f"Warning: Numeric-All noise for {item} contains problems: {sp_sym_ans_copy}. Retrying")
237
+ nn_lst = [random.randint(10**(noise_digits-1), 10**noise_digits - 1) for _ in range(len(chars_in_latex))]
238
+ for i in range(len(chars_in_latex)):
239
+ sp_sym_ans_copy = sp_sym_ans_copy.subs(syms_in_latex[i], sp.UnevaluatedExpr(nn_lst[i]), evaluate=False)
240
+ for i in range(len(chars_in_latex)):
241
+ latex_chall_copy = replace_in_dollars(latex_chall_copy, chars_in_latex[i], r' \left(' + str(nn_lst[i]) + r'\right) ' )
242
+
243
+ # Remove "Assume ... ." clause from latex_chall if it exists
244
+ latex_chall_copy = re.sub(r'Assume.*?\.', '', latex_chall_copy)
245
+
246
+ # Add new item with rolling index
247
+ next_ind += 1
248
+ new_items.append({
249
+ "Index": str(next_ind),
250
+ "Challenge": latex_chall_copy,
251
+ "Answer in Sympy": str(sp_sym_ans_copy),
252
+ "Answer in Latex": "",
253
+ "Variation": f"Numeric-All-{noise_digits}",
254
+ "Source": source
255
+ })
256
+
257
+ # Generate variants with some symbols replaced by 1 (partial symbolic)
258
+ for i in range(1, len(chars_in_latex)):
259
+ oned_indexes = list(itertools.combinations(range(len(chars_in_latex)), i))
260
+ for oned_set in oned_indexes:
261
+ latex_chall_copy = latex_chall
262
+ sp_sym_ans_copy = sp_sym_ans
263
+ for ind in oned_set:
264
+ latex_chall_copy = replace_in_dollars(latex_chall_copy, chars_in_latex[ind], '')
265
+ sp_sym_ans_copy = sp_sym_ans_copy.subs(syms_in_latex[ind], 1)
266
+ next_ind += 1
267
+ new_items.append({
268
+ "Index": str(next_ind),
269
+ "Challenge": latex_chall_copy,
270
+ "Answer in Sympy": str(sp_sym_ans_copy),
271
+ "Answer in Latex": "",
272
+ "Variation": f"Symbolic-{len(chars_in_latex) - i}",
273
+ "Source": source
274
+ })
275
+ # Add new_items to data before writing output
276
+ data.extend(new_items)
277
+
278
+ # Generate 'Numeric-All-2-S' variants - the 'Variance' subset
279
+ def generate_NA2S(items, symnoise_chars, symnoise_syms, sym_dict, cur_ind, noise_digits, reps_num):
280
+ next_ind = cur_ind
281
+ new_items = []
282
+
283
+ for item in items:
284
+ latex_chall = item.get("Challenge")
285
+ sp_sym_ans = sp.sympify(item.get("Answer in Sympy"), locals = sym_dict)
286
+ source = item.get("Source")
287
+ chars_in_latex = []
288
+ syms_in_latex = []
289
+ # Find which symbolic noise characters are present in the LaTeX challenge
290
+ for i in range(len(symnoise_chars)):
291
+ if char_in_dollars(latex_chall, symnoise_chars[i]):
292
+ chars_in_latex.append(symnoise_chars[i])
293
+ syms_in_latex.append(symnoise_syms[i])
294
+ if len(chars_in_latex) == 0:
295
+ print("No symbolic parameters found inside math expressions in source: ",source)
296
+
297
+ for _ in range(reps_num):
298
+ latex_chall_copy = latex_chall
299
+ sp_sym_ans_copy = sp_sym_ans
300
+ # Generate random integer values for all symbolic chars
301
+ nn_lst = [random.randint(10**(noise_digits-1), 10**(noise_digits) - 1) for _ in range(len(chars_in_latex))]
302
+ for i in range(len(chars_in_latex)):
303
+ sp_sym_ans_copy = sp_sym_ans_copy.subs(syms_in_latex[i], sp.UnevaluatedExpr(nn_lst[i]), evaluate=False)
304
+
305
+ while check_for_problematic_symbols(sp_sym_ans_copy):
306
+ print(f"Warning: Numeric-All noise for {item} contains problems: {sp_sym_ans_copy}. Retrying")
307
+ nn_lst = [random.randint(10**(noise_digits-1), 10**noise_digits - 1) for _ in range(len(chars_in_latex))]
308
+ for i in range(len(chars_in_latex)):
309
+ sp_sym_ans_copy = sp_sym_ans_copy.subs(syms_in_latex[i], sp.UnevaluatedExpr(nn_lst[i]), evaluate=False)
310
+
311
+ for i in range(len(chars_in_latex)):
312
+ latex_chall_copy = replace_in_dollars(latex_chall_copy, chars_in_latex[i], r' \left(' + str(nn_lst[i]) + r'\right) ' )
313
+
314
+ # Remove "Assume ... ." clause from latex_chall if it exists
315
+ latex_chall_copy = re.sub(r'Assume.*?\.', '', latex_chall_copy)
316
+ next_ind += 1
317
+ new_items.append({
318
+ "Index": str(next_ind),
319
+ "Challenge": latex_chall_copy,
320
+ "Answer in Sympy": str(sp_sym_ans_copy),
321
+ "Answer in Latex": "",
322
+ "Variation": f"Numeric-All-{noise_digits}-S",
323
+ "Source": source
324
+ })
325
+ # Add new_items to data before writing output
326
+ data.extend(new_items)
327
+
328
+
329
+ # Split items into regular and hypergeometric symbolic questions
330
+ sym_var_items = [item for item in data if (item.get('Variation', '').strip() == 'Symbolic' and item.get('Source') not in hypergeomatric_question_sources)]
331
+ hypergeometric_sym_var_items = [item for item in data if (item.get('Variation', '').strip() == 'Symbolic' and item.get('Source') in hypergeomatric_question_sources)]
332
+
333
+ # Generate all variants for regular and hypergeometric items
334
+ generate_variants(sym_var_items, symnoise_char_list, symnoise_sym_list, local_sym_dict, cur_data_len)
335
+ cur_data_len = len(data)
336
+ generate_variants(hypergeometric_sym_var_items, hg_symnoise_char_list, hg_symnoise_sym_list, hg_local_sym_dict, cur_data_len)
337
+ cur_data_len = len(data)
338
+ generate_NA2S(sym_var_items, symnoise_char_list, symnoise_sym_list, local_sym_dict, cur_data_len, 2, 50)
339
+ cur_data_len = len(data)
340
+ generate_NA2S(hypergeometric_sym_var_items, hg_symnoise_char_list, hg_symnoise_sym_list, hg_local_sym_dict, cur_data_len, 2, 50)
341
+ cur_data_len = len(data)
342
+ print("Final size of the ASyMOB dataset is: " ,cur_data_len)
343
+
344
+ # Write the full dataset to a JSON file
345
+ output_json_path = 'Full_ASyMOB_Dataset.json'
346
+ with open(output_json_path, 'w', encoding='utf-8') as jf:
347
+ json.dump(data, jf, ensure_ascii=False, indent=2)
348
+