rU-ShawJI-07 commited on
Commit
4c33e3f
·
verified ·
1 Parent(s): 464a2c2

Create polynomial.py

Browse files
Files changed (1) hide show
  1. polynomial.py +176 -0
polynomial.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #polynomial.py
2
+ import gradio as gr
3
+ import sympy as sp
4
+ import numpy as np
5
+ import matplotlib.pyplot as plt
6
+
7
+ # Define symbolic variable for polynomial operations
8
+ x = sp.symbols('x')
9
+
10
+ # Function to generate a LaTeX template for a polynomial based on its degree
11
+ def generate_polynomial_template(degree):
12
+ terms = [f"a_{{{i}}}x^{degree - i}" for i in range(degree)]
13
+ terms.append(f"a_{{{degree}}}")
14
+ return "$$" + " + ".join(terms) + " = 0$$"
15
+
16
+ # Function to load example coefficients for a given polynomial degree
17
+ def load_poly_example(degree):
18
+ examples = {
19
+ 1: "3 9",
20
+ 2: "1 -3 2",
21
+ 3: "1 -6 11 -6",
22
+ 4: "1 0 -5 0 4",
23
+ 5: "1 -9 3 8 1 8",
24
+ 6: "1 -9 3 8 1 8 3",
25
+ 7: "1 -9 3 8 1 8 6 2",
26
+ 8: "1 -9 3 8 1 8 2 3 7"
27
+ }
28
+ return examples.get(degree, "")
29
+
30
+ # Function to solve the polynomial equation and generate a graph
31
+ def solve_polynomial(degree, coeff_string, real_only):
32
+ try:
33
+ coeffs = list(map(float, coeff_string.strip().split()))
34
+ if len(coeffs) != degree + 1:
35
+ return f"⚠️ Please enter exactly {degree + 1} coefficients.", None, None
36
+
37
+ poly = sum([coeffs[i] * x**(degree - i) for i in range(degree + 1)])
38
+ simplified = sp.simplify(poly)
39
+ factored = sp.factor(simplified)
40
+ roots = sp.solve(sp.Eq(simplified, 0), x)
41
+
42
+ if real_only:
43
+ roots = [r for r in roots if sp.im(r) == 0]
44
+
45
+ roots_output = "$$\n" + "\\ ".join(
46
+ [f"r_{{{i}}} = {sp.latex(sp.nsimplify(r, rational=True))}" for i, r in enumerate(roots, 1)]
47
+ ) + "\n$$"
48
+
49
+ steps_output = f"""
50
+ ### 🧐 Polynomial Expression
51
+ $$ {sp.latex(poly)} = 0 $$
52
+ ### ✏️ Simplified
53
+ $$ {sp.latex(simplified)} = 0 $$
54
+ ### 🤩 Factored
55
+ $$ {sp.latex(factored)} = 0 $$
56
+ ### 🥮 Roots {'(Only Real)' if real_only else '(All Roots)'}
57
+ {roots_output}
58
+ """
59
+
60
+ x_vals = np.linspace(-10, 10, 400)
61
+ y_vals = np.polyval(coeffs, x_vals)
62
+
63
+ fig, ax = plt.subplots(figsize=(6, 4))
64
+ ax.plot(x_vals, y_vals, label="Polynomial", color="blue")
65
+ ax.axhline(0, color='black', linewidth=0.5)
66
+ ax.axvline(0, color='black', linewidth=0.5)
67
+ ax.grid(True)
68
+ ax.set_title(" Graph of the Polynomial")
69
+ ax.set_xlabel("x")
70
+ ax.set_ylabel("f(x)")
71
+ ax.legend()
72
+
73
+ return steps_output, fig, ""
74
+ except Exception as e:
75
+ return f"❌ Error: {e}", None, ""
76
+
77
+ # Function to create the Polynomial Solver tab with Gradio components
78
+ def polynomial_tab():
79
+ with gr.Tab("📐 Polynomial Solver"):
80
+ # Row for displaying the equation template and real roots checkbox
81
+ with gr.Row():
82
+ # Markdown component for displaying the polynomial template with increased height (200px)
83
+ # The 'height' parameter ensures the template is more readable
84
+ template_display = gr.Markdown(value=generate_polynomial_template(2))
85
+
86
+ # Checkbox to toggle between showing all roots or only real roots
87
+ real_checkbox = gr.Checkbox(label="Show Only Real Roots", value=False)
88
+
89
+ # Row for selecting the polynomial degree and entering coefficients
90
+ with gr.Row():
91
+ # Slider to select the degree of the polynomial (1 to 8)
92
+ degree_slider = gr.Slider(1, 8, value=2, step=1, label="Select Degree of Polynomial Equation")
93
+
94
+ # Textbox for user to input coefficients (space-separated)
95
+ coeff_input = gr.Textbox(label="✍️ Enter Coefficients (space-separated)", placeholder="e.g. 1 -3 2")
96
+
97
+ # Row for example and preview buttons
98
+ with gr.Row():
99
+ # Button to load an example set of coefficients
100
+ example_btn = gr.Button("🔁 Load Example")
101
+
102
+ # Button to preview the entered polynomial equation
103
+ preview_poly_button = gr.Button("🔍 Preview Equation")
104
+
105
+ # Row for displaying the confirmed equation (increased height for better visibility)
106
+ with gr.Row():
107
+ # Markdown component for displaying the confirmed equation with increased height (200px)
108
+ # The 'height' parameter makes the confirmed equation display larger
109
+ poly_equation_display = gr.Markdown()
110
+
111
+ # Row for confirm and cancel buttons
112
+ with gr.Row():
113
+ # Button to confirm and display the solution (initially hidden)
114
+ confirm_poly_btn = gr.Button("✅ Display Solution", visible=False)
115
+
116
+ # Button to cancel and edit the equation (initially hidden)
117
+ cancel_poly_btn = gr.Button("✏️ Make Changes in Equation", visible=False)
118
+
119
+ # Markdown component to display step-by-step solution
120
+ steps_md = gr.Markdown()
121
+
122
+ # Plot component to display the polynomial graph
123
+ plot_output = gr.Plot()
124
+
125
+ # Textbox to display errors (initially hidden)
126
+ error_box = gr.Textbox(visible=False)
127
+
128
+ # Function to preview the polynomial equation based on user input
129
+ def preview_polynomial(degree, coeff_string, real_only):
130
+ try:
131
+ coeffs = list(map(float, coeff_string.strip().split()))
132
+ if len(coeffs) != degree + 1:
133
+ return f"⚠️ Please enter exactly {degree + 1} coefficients.", gr.update(visible=False), gr.update(visible=False), "", None
134
+ poly = sum([coeffs[i] * x**(degree - i) for i in range(degree + 1)])
135
+ eq_latex = f"### ✅ Confirm Polynomial\n\n$$ {sp.latex(poly)} = 0 $$"
136
+ return eq_latex, gr.update(visible=True), gr.update(visible=True), "", None
137
+ except Exception as e:
138
+ return f"❌ Error parsing coefficients: {e}", gr.update(visible=False), gr.update(visible=False), "", None
139
+
140
+ # Event handler for preview button click
141
+ preview_poly_button.click(
142
+ fn=preview_polynomial,
143
+ inputs=[degree_slider, coeff_input, real_checkbox],
144
+ outputs=[poly_equation_display, confirm_poly_btn, cancel_poly_btn, steps_md, plot_output]
145
+ )
146
+
147
+ # Function to handle cancellation of the preview
148
+ def cancel_poly():
149
+ return gr.update(visible=False), gr.update(visible=False), "", "", None
150
+
151
+ # Event handler for cancel button click
152
+ cancel_poly_btn.click(
153
+ fn=cancel_poly,
154
+ inputs=[],
155
+ outputs=[confirm_poly_btn, cancel_poly_btn, poly_equation_display, steps_md, plot_output]
156
+ )
157
+
158
+ # Event handler for confirm button click to solve and display results
159
+ confirm_poly_btn.click(
160
+ fn=solve_polynomial,
161
+ inputs=[degree_slider, coeff_input, real_checkbox],
162
+ outputs=[steps_md, plot_output, error_box]
163
+ )
164
+
165
+ # Event handler to update the template when the degree slider changes
166
+ degree_slider.change(fn=generate_polynomial_template, inputs=degree_slider, outputs=template_display)
167
+
168
+ # Event handler to load an example when the example button is clicked
169
+ example_btn.click(fn=load_poly_example, inputs=degree_slider, outputs=coeff_input)
170
+
171
+ # Initialize the template display with the default degree (2) on load
172
+ template_display.value = generate_polynomial_template(2)
173
+
174
+ # Return all components (though not used directly in app.py, included for consistency)
175
+ return template_display, real_checkbox, degree_slider, coeff_input, example_btn, preview_poly_button, poly_equation_display, confirm_poly_btn, cancel_poly_btn, steps_md, plot_output, error_box
176
+