= #JxnPortable\docs\programmer_examples\commons_math_examples\JxnMultivariateFunction_Optimization~Demo.jxn

slider = @JxnSliderPanel($this)
xp = slider.add( "x", 0., -2.5, 2.5 )
yp = slider.add( "y", 0., -2.5, 2.5 )

uv = @JxnUVGrid( -2.5, 2.5, 0.1, -2.5, 2.5, 0.1, 2 )
t = 0.25 x
phi = atan2( 0.6, 0.8 )
cs = cos phi
sn = sin phi

fz = @JxnFunction( $this, "( x, y ) -> $x = cs x - sn y; $y = sn x + cs y; ( $x^2 + 2.5 $y^2 - $y ) * exp( 1 - $x^2 - $y^2 );" );
! see ..\gnuplot_example.jxn
zpt = fz( xp, t )
ztp = fz( t, yp )
zpp = fz( xp, yp )
zuv = fz( uv.u(), uv.v() )

#JXN:include/P3dInclude.jxn
pf = plot( p3d, 1. ).add( uv.u(), uv.v(), zuv ).add( xp + 0t, t, zpt, B ).add( t, yp + 0t, ztp, B )
p3d.setXYZ( xp, yp, zpp )
pf.add( @JxnSymbolPainter( 0, p3d.getX(), p3d.getY(), 8 ).setColor B )
pf.add( @JxnTextPainter( "z(x,y) = " + format( zpp, 5 ), 2., 3.25 ) ).setFont( @java.awt.Font( "Dialog", 0, 18 ) )


#import org.apache.commons.math3.optim
#import org.apache.commons.math3.optim.nonlinear.scalar
#import org.apache.commons.math3.optim.nonlinear.scalar.noderiv
!
! AbstractSimplex:
! as = @MultiDirectionalSimplex( { 0.1, 0.1 } )
as = @MultiDirectionalSimplex( 2 );
! as = @NelderMeadSimplex( { 0.02, 0.02 } )
! as = @NelderMeadSimplex( 2 )
! as.build( { 0., 0. } )
! 
! MultivariateOptimizer:
! mo = @SimplexOptimizer( 0.0001, 0.0001 )
mo = @PowellOptimizer( 0.001, 0.001 );
! mo = @BOBYQAOptimizer( 5, 10., 0.001 )
!
!! cmd = "$x0 = cs $x[0] - sn $x[1]; $x1 = sn $x[0] + cs $x[1]; ( $x0^2 + 2.5 $x1^2 - $x1 ) * Math.exp( 1 - $x0^2 - $x1^2 )";
!! f1 = @JxnMultivariateFunction( $this, cmd + ";" )
f1 = @JxnMultivariateFunction( $this, "fz( $x[0], $x[1] );" )
!
optData = { @ObjectiveFunction f1, GoalType.MINIMIZE, as, @MaxEval( 5000 ), @InitialGuess({ 0., 0. }) };
rpv = mo.optimize( ArrayClassCast.cast( OptimizationData.class, optData ) )
rpv.getPoint()
rpv.getValue()
!
rpv = mo.optimize( ArrayClassCast.cast( OptimizationData.class, { @ObjectiveFunction f1, GoalType.MAXIMIZE } ) )
rpv.getPoint()
rpv.getValue()
! => MAXIMIZE doesn't work => MINIMIZE -fz
!
f2 = @JxnMultivariateFunction( $this, "-fz( $x[0], $x[1] );" )
rpv = mo.optimize( ArrayClassCast.cast( OptimizationData.class, { @ObjectiveFunction f2, GoalType.MINIMIZE } ) )
rpv.getPoint()
-rpv.getValue()