Maxima: Piecewise function differentiation and simplification.




I have a piecewise function returned by penalty.mac (see blelow).

I am then calling penalty.mac with specific arguments:

(%i69) vpen : penalty(u1^2*sin(x3)^2+u1^2*cos(x3)^2,0,vsqmax);

(%o69) if u1^2*sin(x3)^2+u1^2*cos(x3)^2 > vmax
           then (u1^2*sin(x3)^2+u1^2*cos(x3)^2-vmax)^2
           elseif u1^2*sin(x3)^2+u1^2*cos(x3)^2 < 0
           then (u1^2*sin(x3)^2+u1^2*cos(x3)^2)^2 else 0

I want to differentiate vpen wrt u1 and then wrt x3 directly, dvpendu1 : 
diff(vpen,u1), dvpendx3 : diff(vpen,x3), but could not do this correctly. 

Also, is it possible to somehow apply Maxima simplification functions to such 
piecewise functions, eg. factor(vpen), ratsimp(vpen), etc.

(I prefer not to use a separate function diffpenalty.mac (below) to do the 
differentiation manually).

Any assistance would be much appreciated.

Regards,

C. Frangos.



penalty(fx,amin,amax) := block(

[pen],

'if (fx > amax) then
pen : (fx - amax)^2
elseif (fx < amin) then 
pen : (fx - amin)^2
else
pen : 0);



diffpenalty(fx,amin,amax,x) := block(

[pen],

'if (fx > amax) then
pen : 2*(fx - amax)*diff(fx,x)
elseif (fx < amin) then 
pen : 2*(fx - amin)*diff(fx,x)
else
pen : 0);