counting / maths /calculus /partial_derivative.py
spagestic's picture
feat: simplify descriptions and examples in Gradio interfaces for arithmetic and calculus tools
db31576
import sympy
from typing import List
import gradio as gr
def partial_derivative(expression_str: str, variables_str: List[str]) -> str:
"""
Computes partial derivatives of an expression with respect to specified variables.
Example: expression_str="x**2*y**3", variables_str=["x", "y"] will compute d/dx then d/dy.
If you want d^2f/dx^2, use variables_str=["x", "x"].
Args:
expression_str: The mathematical expression (e.g., "x**2*y + y*z**2").
variables_str: A list of variable names (strings) to differentiate by, in order.
(e.g., ["x", "y"] for d/dy(d/dx(expr)) ).
Returns:
String representation of the partial derivative or an error message.
"""
try:
symbols_in_expr = {s.name: s for s in sympy.parse_expr(expression_str, transformations='all').free_symbols}
diff_vars_symbols = []
for var_name in variables_str:
if var_name in symbols_in_expr:
diff_vars_symbols.append(symbols_in_expr[var_name])
else:
diff_vars_symbols.append(sympy.Symbol(var_name))
if not diff_vars_symbols:
return "Error: No variables specified for differentiation."
expr = sympy.parse_expr(expression_str, local_dict=symbols_in_expr, transformations='all')
current_expr = expr
for var_sym in diff_vars_symbols:
current_expr = sympy.diff(current_expr, var_sym)
return str(current_expr)
except (sympy.SympifyError, TypeError, SyntaxError) as e:
return f"Error parsing expression or variables: {e}"
except Exception as e:
return f"An unexpected error occurred: {e}"
partial_derivative_interface = gr.Interface(
fn=lambda expr_str, vars_str: partial_derivative(expr_str, [v.strip() for v in vars_str.split(',') if v.strip()]),
inputs=[
gr.Textbox(label="Expression (e.g., x**2*y + z*sin(x))", value="x**2*y**3 + y*sin(z)"),
gr.Textbox(label="Variables to differentiate by (comma-separated, in order, e.g., x,y or x,x for d²f/dx²)", value="x,y")
],
outputs="text",
title="Partial Derivative Calculator",
description="Compute partial derivatives.\n\n**Description:**\nThis tool computes partial derivatives of an expression with respect to specified variables, in order. For d/dy(d/dx(f)), enter 'x,y'. For d²f/dx², enter 'x,x'.\n\n**Examples:**\n- Expression: x**2*y**3, Variables: x → Output: 2*x*y**3\n- Expression: x**2*y**3, Variables: y → Output: 3*x**2*y**2\n- Expression: x**2*y**3, Variables: x,y → Output: 6*x*y**2",
examples=[["x**2*y**3", "x"], ["x**2*y**3", "y"], ["x**2*y**3", "x,y"]],
)