Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Try this :

def param_form(eqns, unkns, params=None):
    ## Variables involved in the system of equations
    L1=reduce(union, [[s for s in E.variables()] for E in eqns], {})
    ## Solve in a dictionary (eliminates special-case handling of
    ## unique solutions or unique unknowns...)
    Sol=solve(eqns, unkns, solution_dict=True)
    ## Variables involved in solutions
    L2=set(s for s in reduce(union,
                            [set(Sol[0].get(k).variables())
                             for k in Sol[0].keys()], {}))
    ## "New" variables introduced by solve
    D=L2.difference(L1)
    if params is None:
        ## Default behaviour : declare them globally
        var(", ".join([repr(s) for s in D]))
    else:
        ## Peruse an option list of parameter names
        ## Create local symbolic variables
        LD=SR.var(", ".join([repr(s) for s in D]))
        ## Again a single-variable special case. Grrrr...
        if len(LD)==0:
            LD=(LD,)
        ## Substitution dictionnary.
        SD=dict(zip(LD, params))
        ## Too few parameter names ? Declare them globally.
        ## (We might alternatively raise an error)
        RD=set(LD)-set(SD.keys())
        if len(RD)>0:
            var(", ".join([repr(s) for s in RD]))
        ## Substitute our params in the solution.
        for S in Sol:
            for k in S.keys():
                    S.update({k:S.get(k).subs(SD)})
    return Sol

Test that (very quick and rough) :

sage: reset()
sage: load('/tmp/sage_shell_modepFOyEq/sage_shell_mode_temp.sage') # Load code above...
sage: x,y,z=var('x y z')
sage: eqns = [x + y + 2*z - 25 == 0,  -x + y - 25 == 0]
sage: param_form(eqns, [x,y,z])
[{z: r16, y: -r16 + 25, x: -r16}]

Test that a symbolic variable r16 has been correctly created globally

sage: r16
r16

We wish to name our parameter name t. We have to create it first:

sage: t=var("t")
sage: param_form(eqns, [x,y,z],[t])
[{z: t, y: -t + 25, x: -t}]

Seems to work as advertised...

HTH,