joshuarauh commited on
Commit
5e14f9b
·
verified ·
1 Parent(s): 165edf2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -44
app.py CHANGED
@@ -73,7 +73,75 @@ When writing SymPy code to verify solutions:
73
  - Use Float() for sequence terms
74
  - Convert sums to float() before printing
75
  - For series calculations, print intermediate terms
76
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
 
79
 
@@ -470,7 +538,6 @@ STRICT REQUIREMENTS:
470
  def extract_and_run_sympy_code_simple(response_text):
471
  """
472
  Extract SymPy code from the response and execute it.
473
- Handles SymPy expression printing safely and ensures proper symbol definition.
474
  """
475
  try:
476
  # Extract code
@@ -490,7 +557,7 @@ def extract_and_run_sympy_code_simple(response_text):
490
 
491
  # Create globals dict with all SymPy functions
492
  globals_dict = {}
493
- globals_dict.update(vars(sympy)) # This adds all SymPy functions
494
  globals_dict.update({
495
  'print': print,
496
  'float': float,
@@ -502,6 +569,7 @@ def extract_and_run_sympy_code_simple(response_text):
502
  'diff': sympy.diff,
503
  'integrate': sympy.integrate,
504
  'simplify': sympy.simplify,
 
505
  })
506
 
507
  # Remove the sympy import line from the code if present
@@ -514,58 +582,37 @@ def extract_and_run_sympy_code_simple(response_text):
514
  from contextlib import redirect_stdout
515
 
516
  output_buffer = io.StringIO()
517
- try:
518
- with redirect_stdout(output_buffer):
519
- exec(modified_code, globals_dict)
520
- return output_buffer.getvalue().strip() or "No output produced"
521
- except NonInvertibleMatrixError:
522
- return "ERROR_NONINVERTIBLE_MATRIX: The system of equations has either no solution or infinitely many solutions. Matrix is singular (determinant = 0)."
523
- except Exception as e:
524
- if "det == 0" in str(e) or "not invertible" in str(e):
525
- return "ERROR_NONINVERTIBLE_MATRIX: The system of equations has either no solution or infinitely many solutions. Matrix is singular (determinant = 0)."
526
- return f"Error executing SymPy code: {str(e)}"
527
 
528
  except Exception as e:
529
- return f"Error in code extraction: {str(e)}"
530
-
531
  def check_and_resolve_discrepancy(initial_response, sympy_output):
532
  """
533
  Compare the SymPy output with the initial response and resolve any discrepancies.
534
- Now handles singular matrix cases specifically.
535
  """
536
  try:
537
- if "ERROR_NONINVERTIBLE_MATRIX" in sympy_output:
538
- resolution_prompt = f"""The original solution claims to solve a system of linear equations, but SymPy indicates the coefficient matrix is not invertible (singular). This means:
539
- 1. The system has either no solution or infinitely many solutions
540
- 2. The vectors are linearly dependent
541
- 3. The solution given cannot be unique
542
-
543
- Please:
544
- 1. Verify if the system has no solutions or infinitely many solutions
545
- 2. If solutions exist, express them in parametric form
546
- 3. Provide a complete revised solution that correctly addresses this case
 
547
 
548
  Original solution:
549
  {initial_response}
550
 
551
- Please maintain the same LaTeX formatting as the original solution and include correct SymPy code that uses row reduction instead of matrix inversion."""
552
- else:
553
- resolution_prompt = f"""Here is a mathematics question with two answers.
554
- The first, called Original solution, is a complete solution.
555
- The second, called SymPy Verification, will only provide the final answer.
556
-
557
- If the SymPy Verification answer is consistent with the final answer Original solution,
558
- then please say that they are consistent and briefly explain why.
559
-
560
- If the two answers are inconsistent with each other then please:
561
- 1. Identify which solution is correct
562
- 2. Explain the error in the incorrect solution
563
- 3. Provide a revised complete solution that fixes any errors and does not mention SymPy
564
- Original solution:
565
- {initial_response}
566
- SymPy Verification Results:
567
- {sympy_output}
568
- Please maintain the same LaTeX formatting as the original solution."""
569
 
570
  # Make API call for resolution
571
  message = anthropic.messages.create(
 
73
  - Use Float() for sequence terms
74
  - Convert sums to float() before printing
75
  - For series calculations, print intermediate terms
76
+
77
+ 6. Matrix Operations and Systems of Equations:
78
+ - For systems of equations that might be linearly dependent, use row reduction instead of matrix inversion
79
+ - Here's the template for handling such systems:
80
+
81
+ ```python
82
+ from sympy import Matrix, symbols, solve
83
+
84
+ def analyze_system(A, b):
85
+ """
86
+ Analyze a system Ax = b using row reduction.
87
+ Returns whether solution exists and if it's unique.
88
+ """
89
+ # Augmented matrix [A|b]
90
+ aug = Matrix(A.row_join(b))
91
+
92
+ # Get row echelon form
93
+ rref, pivots = aug.rref()
94
+
95
+ print("Row reduced augmented matrix:")
96
+ print(rref)
97
+ print("\\nPivot columns:", pivots)
98
+
99
+ # Get rank of coefficient matrix and augmented matrix
100
+ rank_A = Matrix(A).rank()
101
+ rank_aug = aug.rank()
102
+
103
+ print(f"\\nRank of coefficient matrix: {rank_A}")
104
+ print(f"Rank of augmented matrix: {rank_aug}")
105
+
106
+ if rank_aug > rank_A:
107
+ print("\\nNo solution exists")
108
+ return None
109
+ elif rank_A < A.cols:
110
+ print("\\nInfinitely many solutions exist")
111
+ return "infinite"
112
+ else:
113
+ print("\\nUnique solution exists")
114
+ return "unique"
115
+
116
+ # When solving a system Ax = b:
117
+ A = Matrix([[...], [...], [...]]) # coefficient matrix
118
+ b = Matrix([[...], [...], [...]]) # right-hand side
119
+
120
+ # Analyze system
121
+ result = analyze_system(A, b)
122
+
123
+ if result == "infinite":
124
+ # Get parametric form of solution
125
+ aug = Matrix(A.row_join(b))
126
+ rref, pivots = aug.rref()
127
+
128
+ # Get free variables
129
+ vars = symbols('x y z') # adjust variable names as needed
130
+ free_vars = [var for i, var in enumerate(vars) if i not in pivots]
131
+
132
+ print("\\nParametric solution (t is free parameter):")
133
+ for i, var in enumerate(vars):
134
+ if i in pivots:
135
+ row = pivots.index(i)
136
+ expr = rref[row, -1]
137
+ for j, free_var in enumerate(free_vars):
138
+ expr -= rref[row, pivots[-1] + 1 + j] * free_var
139
+ print(f"{var} = {expr}")
140
+ else:
141
+ print(f"{var} = t") # use different parameter names for multiple free variables
142
+ ```
143
+
144
+ Always use this template when working with systems of equations to handle potential linear dependence correctly. """
145
 
146
 
147
 
 
538
  def extract_and_run_sympy_code_simple(response_text):
539
  """
540
  Extract SymPy code from the response and execute it.
 
541
  """
542
  try:
543
  # Extract code
 
557
 
558
  # Create globals dict with all SymPy functions
559
  globals_dict = {}
560
+ globals_dict.update(vars(sympy))
561
  globals_dict.update({
562
  'print': print,
563
  'float': float,
 
569
  'diff': sympy.diff,
570
  'integrate': sympy.integrate,
571
  'simplify': sympy.simplify,
572
+ 'Matrix': sympy.Matrix
573
  })
574
 
575
  # Remove the sympy import line from the code if present
 
582
  from contextlib import redirect_stdout
583
 
584
  output_buffer = io.StringIO()
585
+ with redirect_stdout(output_buffer):
586
+ exec(modified_code, globals_dict)
587
+ return output_buffer.getvalue().strip() or "No output produced"
 
 
 
 
 
 
 
588
 
589
  except Exception as e:
590
+ return f"Error executing SymPy code: {str(e)}"
591
+
592
  def check_and_resolve_discrepancy(initial_response, sympy_output):
593
  """
594
  Compare the SymPy output with the initial response and resolve any discrepancies.
 
595
  """
596
  try:
597
+ resolution_prompt = f"""Here is a mathematics question with two answers.
598
+ The first, called Original solution, is a complete solution.
599
+ The second, called SymPy Verification, will only provide the final answer.
600
+
601
+ If the SymPy Verification answer is consistent with the final answer Original solution,
602
+ then please say that they are consistent and briefly explain why.
603
+
604
+ If the two answers are inconsistent with each other then please:
605
+ 1. Identify which solution is correct
606
+ 2. Explain the error in the incorrect solution
607
+ 3. Provide a revised complete solution that fixes any errors
608
 
609
  Original solution:
610
  {initial_response}
611
 
612
+ SymPy Verification Results:
613
+ {sympy_output}
614
+
615
+ Please maintain the same LaTeX formatting as the original solution."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
616
 
617
  # Make API call for resolution
618
  message = anthropic.messages.create(