Aroy1997 commited on
Commit
ceba12d
ยท
verified ยท
1 Parent(s): 7da6559

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +155 -0
app.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ import sympy as sp
5
+
6
+ x, y = sp.symbols('x y')
7
+
8
+ # Generate polynomial template
9
+ def generate_polynomial_template(degree):
10
+ terms = [f"a{i}*x^{degree - i}" for i in range(degree)] + [f"a{degree}"]
11
+ return " + ".join(terms) + " = 0"
12
+
13
+ # Solve and plot polynomial
14
+ def solve_polynomial(degree, coeff_string):
15
+ try:
16
+ coeffs = [sp.sympify(s) for s in coeff_string.strip().split()]
17
+ if len(coeffs) != degree + 1:
18
+ return f"โš ๏ธ Please enter exactly {degree + 1} coefficients.", None, None
19
+
20
+ poly = sum([coeffs[i] * x**(degree - i) for i in range(degree + 1)])
21
+ simplified = sp.simplify(poly)
22
+
23
+ # Factor step-by-step
24
+ factored_steps = []
25
+ current_expr = simplified
26
+ while True:
27
+ factored = sp.factor(current_expr)
28
+ if factored == current_expr:
29
+ break
30
+ factored_steps.append(factored)
31
+ current_expr = factored
32
+
33
+ roots = sp.solve(sp.Eq(simplified, 0), x)
34
+ root_display = []
35
+ for i, r in enumerate(roots):
36
+ r_simplified = sp.nsimplify(r, rational=True)
37
+ root_display.append(f"r_{{{i+1}}} = {sp.latex(r_simplified)}")
38
+
39
+ steps_output = f"### ๐Ÿง Polynomial Expression\n\n$$ {sp.latex(poly)} = 0 $$\n\n"
40
+ steps_output += f"### โœ๏ธ Simplified\n\n$$ {sp.latex(simplified)} = 0 $$\n\n"
41
+
42
+ if factored_steps:
43
+ steps_output += f"### ๐Ÿชœ Step-by-Step Factorization\n\n"
44
+ for i, step in enumerate(factored_steps, 1):
45
+ steps_output += f"**Step {i}:** $$ {sp.latex(step)} = 0 $$\n\n"
46
+ else:
47
+ steps_output += f"### ๐Ÿคท No further factorization possible\n\n"
48
+
49
+ steps_output += "### ๐Ÿฅฎ Roots\n\n$$ " + " \\quad ".join(root_display) + " $$"
50
+
51
+ f_lambdified = sp.lambdify(x, simplified, modules=["numpy"])
52
+ x_vals = np.linspace(-10, 10, 400)
53
+ y_vals = f_lambdified(x_vals)
54
+
55
+ fig, ax = plt.subplots(figsize=(6, 4))
56
+ ax.plot(x_vals, y_vals, label="Polynomial")
57
+ ax.axhline(0, color='black', linewidth=0.5)
58
+ ax.axvline(0, color='black', linewidth=0.5)
59
+ ax.grid(True)
60
+ ax.set_title("๐Ÿ“ˆ Graph of the Polynomial")
61
+ ax.set_xlabel("x")
62
+ ax.set_ylabel("f(x)")
63
+
64
+ real_roots = [sp.N(r.evalf()) for r in roots if sp.im(r) == 0]
65
+ for r in real_roots:
66
+ ax.plot([float(r)], [0], 'ro', label="Real Root")
67
+
68
+ ax.legend()
69
+
70
+ return steps_output, fig, ""
71
+
72
+ except Exception as e:
73
+ return f"โŒ Error: {e}", None, ""
74
+
75
+ # Solve linear system
76
+ def solve_linear_system(eq1_str, eq2_str):
77
+ try:
78
+ eq1 = sp.sympify(eq1_str)
79
+ eq2 = sp.sympify(eq2_str)
80
+
81
+ sol = sp.solve((eq1, eq2), (x, y), dict=True)
82
+
83
+ steps = "### ๐Ÿ” Solving System\n\n"
84
+ steps += f"**Equation 1:** $$ {sp.latex(eq1)} $$\n\n"
85
+ steps += f"**Equation 2:** $$ {sp.latex(eq2)} $$\n\n"
86
+
87
+ if sol:
88
+ sol = sol[0]
89
+ steps += f"**Solution:** $$ x = {sp.latex(sol[x])}, \ y = {sp.latex(sol[y])} $$\n\n"
90
+ else:
91
+ steps += "**No unique solution or inconsistent system**\n"
92
+
93
+ x_vals = np.linspace(-10, 10, 400)
94
+ f1 = sp.solve(eq1, y)
95
+ f2 = sp.solve(eq2, y)
96
+
97
+ fig, ax = plt.subplots(figsize=(6, 4))
98
+ if f1 and f2:
99
+ y1 = sp.lambdify(x, f1[0], modules=['numpy'])(x_vals)
100
+ y2 = sp.lambdify(x, f2[0], modules=['numpy'])(x_vals)
101
+ ax.plot(x_vals, y1, label='Equation 1')
102
+ ax.plot(x_vals, y2, label='Equation 2')
103
+
104
+ if sol:
105
+ px = float(sp.N(sol[x]))
106
+ py = float(sp.N(sol[y]))
107
+ ax.plot(px, py, 'ro')
108
+ ax.annotate(f"({px:.2f}, {py:.2f})", (px, py), textcoords="offset points", xytext=(10, 5), ha='center', color='red')
109
+
110
+ ax.axhline(0, color='black', linewidth=0.5)
111
+ ax.axvline(0, color='black', linewidth=0.5)
112
+ ax.set_title("๐Ÿ“‰ Graph of the Linear System")
113
+ ax.set_xlabel("x")
114
+ ax.set_ylabel("y")
115
+ ax.grid(True)
116
+ ax.legend()
117
+
118
+ return steps, fig
119
+
120
+ except Exception as e:
121
+ return f"โŒ Error: {e}", None
122
+
123
+ # UI
124
+ with gr.Blocks() as demo:
125
+ gr.Markdown("## ๐Ÿ”ข Polynomial Solver with Step-by-Step Factorization and Graph")
126
+
127
+ with gr.Row():
128
+ degree_slider = gr.Slider(1, 8, value=3, step=1, label="Degree of Polynomial")
129
+ template_display = gr.Textbox(label="Polynomial Template (Fill in Coefficients)", interactive=False)
130
+
131
+ coeff_input = gr.Textbox(label="Enter Coefficients (space-separated, supports pi, e, sqrt(2), I)", placeholder="e.g. 1 -3 sqrt(2) -pi")
132
+
133
+ steps_md = gr.Markdown()
134
+ plot_output = gr.Plot()
135
+ error_box = gr.Textbox(visible=False)
136
+
137
+ with gr.Row():
138
+ solve_button = gr.Button("Plot Polynomial", variant="primary")
139
+
140
+ degree_slider.change(fn=generate_polynomial_template, inputs=degree_slider, outputs=template_display)
141
+ solve_button.click(fn=solve_polynomial, inputs=[degree_slider, coeff_input], outputs=[steps_md, plot_output, error_box])
142
+
143
+ gr.Markdown("## ๐Ÿ“ Solve Linear System (2 Equations, 2 Variables)")
144
+
145
+ eq1_input = gr.Textbox(label="Equation 1 (in x and y)", placeholder="e.g. 2*x + 3*y - 6")
146
+ eq2_input = gr.Textbox(label="Equation 2 (in x and y)", placeholder="e.g. -x + y - 2")
147
+ sys_steps = gr.Markdown()
148
+ sys_plot = gr.Plot()
149
+
150
+ with gr.Row():
151
+ solve_sys_button = gr.Button("Solve Linear System", variant="primary")
152
+
153
+ solve_sys_button.click(fn=solve_linear_system, inputs=[eq1_input, eq2_input], outputs=[sys_steps, sys_plot])
154
+
155
+ demo.launch()