File size: 2,676 Bytes
5543e04
 
95151f6
5543e04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95151f6
 
 
 
 
 
 
 
 
db31576
 
95151f6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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"]],
)