001import org.apache.commons.math3.analysis.MultivariateFunction;
002
003/** Wrapper used to pass a method definition to <a target="_blank" href="http://commons.apache.org/math">Commons Math</a> algorithms.
004  * Computes a command given as a String.<br/>
005  * <br/>
006  * See <a target="_top" href="../0_CommonsMath_README.html#examples">JxnMultivariateFunction_Optimization~Demo.jxn</a>
007  * for an example.  
008  */
009public class JxnMultivariateFunction implements MultivariateFunction
010{
011   String cmd;
012   KmgFormelInterpreter fi;
013   static final boolean skipInputLogEnabled = true;
014
015   /** Constructs a {@link org.apache.commons.math3.analysis.MultivariateFunction}
016     * instance to be used by <a target="_blank" href="http://commons.apache.org/math">Commons Math</a> algorithms.<br/>
017     * Example:
018     * <pre>
019     *    mvf = @JxnMultivariateFunction( $this, "( $x[0]^2 + 2.5 $x[1]^2 - $x[1] ) * Math.exp( 1 - $x[0]^2 - $x[1]^2 );" )</pre>
020     * @param fi an internal copy of {@code fi} is used to execute {@code cmd}
021     * @param cmd one or more statements separated by '{@code ;}'. The command {@code cmd} must use the
022     * array {@code double[] $x}
023     * to compute a result of type double. If {@code cmd} ends with '{@code ;}', log output of intermediate steps is suppressed.
024     */
025   public JxnMultivariateFunction( KmgFormelInterpreter fi, String cmd )
026   {
027      this.cmd = cmd;
028      this.fi = new KmgFormelInterpreter( fi );
029   }
030   
031   /** @deprecated replaced by {@link #JxnMultivariateFunction(KmgFormelInterpreter, String)} */
032   public JxnMultivariateFunction( String cmd, KmgFormelInterpreter fi )
033   {
034      this.cmd = cmd;
035      this.fi = new KmgFormelInterpreter( fi );
036   }
037   
038   /** Internally called by Commons Math algorithms: Computes the function value using the given argument {@code x}. */
039   public double value( double [] x )
040   {
041      fi.put( "$x", x );
042      return KmgFormelInterpreter.doubleValue( fi.execute( cmd, skipInputLogEnabled ) );
043   }
044
045   /** Returns the command {@code cmd} passed to the constructor. */
046   public String toString()
047   {
048      return cmd;
049   }
050}