MasteredUltraInstinct commited on
Commit
8cf80cb
Β·
verified Β·
1 Parent(s): e736389

Create linear.py

Browse files
Files changed (1) hide show
  1. linear.py +134 -0
linear.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import sympy as sp
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import random
6
+
7
+ x, y = sp.symbols('x y')
8
+
9
+ def generate_linear_template():
10
+ return "$$ a_1x + b_1y = c_1 \\ a_2x + b_2y = c_2 $$"
11
+
12
+ def load_linear_example():
13
+ examples = [
14
+ ("1 -4 -2", "5 1 9"),
15
+ ("2 1 8", "1 -1 2"),
16
+ ("3 2 12", "1 1 5"),
17
+ ("4 -1 3", "2 3 6"),
18
+ ("1 2 10", "3 -1 5")
19
+ ]
20
+ return random.choice(examples)
21
+
22
+ def solve_linear_system_from_coeffs(eq1_str, eq2_str):
23
+ try:
24
+ coeffs1 = list(map(float, eq1_str.strip().split()))
25
+ coeffs2 = list(map(float, eq2_str.strip().split()))
26
+
27
+ if len(coeffs1) != 3 or len(coeffs2) != 3:
28
+ return "⚠️ Please enter exactly 3 coefficients for each equation.", None, None, None
29
+
30
+ a1, b1, c1 = coeffs1
31
+ a2, b2, c2 = coeffs2
32
+
33
+ eq1 = sp.Eq(a1 * x + b1 * y, c1)
34
+ eq2 = sp.Eq(a2 * x + b2 * y, c2)
35
+
36
+ sol = sp.solve([eq1, eq2], (x, y), dict=True)
37
+ if not sol:
38
+ return "❌ No unique solution.", None, None, None
39
+
40
+ solution = sol[0]
41
+ eq_latex = f"$$ {sp.latex(eq1)} \\ {sp.latex(eq2)} $$"
42
+
43
+ steps = rf"""
44
+ ### Step-by-step Solution
45
+ 1. **Original Equations:**
46
+ $$ {sp.latex(eq1)} $$
47
+ $$ {sp.latex(eq2)} $$
48
+ 2. **Standard Form:** Already provided.
49
+ 3. **Solve using SymPy `solve`:** Internally applies substitution/elimination.
50
+ 4. **Solve for `x` and `y`:**
51
+ $$ x = {sp.latex(solution[x])}, \quad y = {sp.latex(solution[y])} $$
52
+ 5. **Verification:** Substitute back into both equations."""
53
+
54
+ x_vals = np.linspace(-10, 10, 400)
55
+ f1 = sp.solve(eq1, y)
56
+ f2 = sp.solve(eq2, y)
57
+
58
+ fig, ax = plt.subplots()
59
+ if f1:
60
+ f1_func = sp.lambdify(x, f1[0], modules='numpy')
61
+ ax.plot(x_vals, f1_func(x_vals), label=sp.latex(eq1))
62
+ if f2:
63
+ f2_func = sp.lambdify(x, f2[0], modules='numpy')
64
+ ax.plot(x_vals, f2_func(x_vals), label=sp.latex(eq2))
65
+
66
+ ax.plot(solution[x], solution[y], 'ro', label=f"Solution ({solution[x]}, {solution[y]})")
67
+ ax.axhline(0, color='black', linewidth=0.5)
68
+ ax.axvline(0, color='black', linewidth=0.5)
69
+ ax.legend()
70
+ ax.set_title("Graph of the Linear System")
71
+ ax.grid(True)
72
+
73
+ return eq_latex, steps, fig, ""
74
+ except Exception as e:
75
+ return f"❌ Error: {e}", None, None, None
76
+
77
+ def linear_tab():
78
+ with gr.Tab("Linear System Solver"):
79
+ gr.Markdown("## Solve 2x2 Linear System")
80
+ linear_template = gr.Markdown(value=generate_linear_template())
81
+
82
+ with gr.Row():
83
+ linear_eq1_input = gr.Textbox(label="Equation 1 Coefficients (a1 b1 c1)", placeholder="e.g. 2 1 8")
84
+ linear_eq2_input = gr.Textbox(label="Equation 2 Coefficients (a2 b2 c2)", placeholder="e.g. 1 -1 2")
85
+
86
+ linear_example_btn = gr.Button("Load Example")
87
+ preview_button = gr.Button("Preview Equations")
88
+
89
+ linear_equation_display = gr.Markdown()
90
+ with gr.Row():
91
+ confirm_btn = gr.Button("Display Solution", visible=False)
92
+ cancel_btn = gr.Button("Make Changes in Equation", visible=False)
93
+
94
+ linear_steps_md = gr.Markdown()
95
+ linear_plot = gr.Plot()
96
+ linear_error = gr.Textbox(visible=False)
97
+
98
+ def update_example():
99
+ eq1, eq2 = load_linear_example()
100
+ return eq1, eq2
101
+
102
+ linear_example_btn.click(fn=update_example, inputs=[], outputs=[linear_eq1_input, linear_eq2_input])
103
+
104
+ def preview_equations(eq1_str, eq2_str):
105
+ try:
106
+ coeffs1 = list(map(float, eq1_str.strip().split()))
107
+ coeffs2 = list(map(float, eq2_str.strip().split()))
108
+ if len(coeffs1) != 3 or len(coeffs2) != 3:
109
+ return "⚠️ Please enter exactly 3 coefficients for each equation.", gr.update(visible=False), gr.update(visible=False)
110
+ a1, b1, c1 = coeffs1
111
+ a2, b2, c2 = coeffs2
112
+ eq1 = sp.Eq(a1 * x + b1 * y, c1)
113
+ eq2 = sp.Eq(a2 * x + b2 * y, c2)
114
+ eq_latex = f"### βœ… Confirm Equations\n\n$$ {sp.latex(eq1)} \\\\ {sp.latex(eq2)} $$"
115
+ return eq_latex, gr.update(visible=True), gr.update(visible=True)
116
+ except Exception as e:
117
+ return f"❌ Error parsing equations: {e}", gr.update(visible=False), gr.update(visible=False)
118
+
119
+ preview_button.click(
120
+ fn=preview_equations,
121
+ inputs=[linear_eq1_input, linear_eq2_input],
122
+ outputs=[linear_equation_display, confirm_btn, cancel_btn]
123
+ )
124
+
125
+ cancel_btn.click(
126
+ fn=lambda: (gr.update(visible=False), gr.update(visible=False), "", None, None),
127
+ outputs=[confirm_btn, cancel_btn, linear_equation_display, linear_steps_md, linear_plot]
128
+ )
129
+
130
+ confirm_btn.click(
131
+ fn=solve_linear_system_from_coeffs,
132
+ inputs=[linear_eq1_input, linear_eq2_input],
133
+ outputs=[linear_equation_display, linear_steps_md, linear_plot, linear_error]
134
+ )