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