声振论坛

 找回密码
 我要加入

QQ登录

只需一步,快速开始

查看: 2194|回复: 7

[经典算法] 用JAVA实现mathematica调用

[复制链接]
发表于 2008-4-27 09:37 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?我要加入

x
如题,想用VJ++做个界面,可以通过调用mathematica的核直接调用他,谁能帮我编个程序,急啊
回复
分享到:

使用道具 举报

发表于 2008-4-30 10:37 | 显示全部楼层
记得好像需要安装一个插件 J/Link
http://www.wolfram.com/ 上好像就有
 楼主| 发表于 2008-5-11 10:54 | 显示全部楼层

用JAVA实现mathematica调用

这是在VJ里面建的applet上的代码,有错误,估计是路径或者语法的问题把,达人们帮我搞一下把,
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import com.wolfram.jlink.*;
import com.*;
/**
* This class reads PARAM tags from its HTML host page and sets
* the color and label properties of the applet. Program execution
* begins with the init() method.
*/
public class Applet1 extends Applet implements ActionListener
{
/**
  * The entry point for the applet.
  */
public void init()
{
  initForm();
  usePageParams();
  // TODO: Add any constructor code after initForm call.
}
private final String labelParam = "label";
private final String backgroundParam = "background";
private final String foregroundParam = "foreground";
/**
  * Reads parameters from the applet's HTML host and sets applet
  * properties.
  */
private void usePageParams()
{
  final String defaultLabel = "Default label";
  final String defaultBackground = "C0C0C0";
  final String defaultForeground = "000000";
  String labelValue;
  String backgroundValue;
  String foregroundValue;
  /**
   * Read the <PARAM NAME="label" VALUE="some string">,
   * <PARAM NAME="background" VALUE="rrggbb">,
   * and <PARAM NAME="foreground" VALUE="rrggbb"> tags from
   * the applet's HTML host.
   */
  labelValue = getParameter(labelParam);
  backgroundValue = getParameter(backgroundParam);
  foregroundValue = getParameter(foregroundParam);
  if ((labelValue == null) || (backgroundValue == null) ||
   (foregroundValue == null))
  {
   /**
    * There was something wrong with the HTML host tags.
    * Generate default values.
    */
   labelValue = defaultLabel;
   backgroundValue = defaultBackground;
   foregroundValue = defaultForeground;
  }
  /**
   * Set the applet's string label, background color, and
   * foreground colors.
   */
  label1.setText(labelValue);
  label1.setBackground(stringToColor(backgroundValue));
  label1.setForeground(stringToColor(foregroundValue));
  this.setBackground(stringToColor(backgroundValue));
  this.setForeground(stringToColor(foregroundValue));
  
}
/**
  * Converts a string formatted as "rrggbb" to an awt.Color object
  */
private Color stringToColor(String paramValue)
{
  int red;
  int green;
  int blue;
  red = (Integer.decode("0x" + paramValue.substring(0,2))).intValue();
  green = (Integer.decode("0x" + paramValue.substring(2,4))).intValue();
  blue = (Integer.decode("0x" + paramValue.substring(4,6))).intValue();
  return new Color(red,green,blue);
}
/**
  * External interface used by design tools to show properties of an applet.
  */
public String[][] getParameterInfo()
{
  String[][] info =
  {
   { labelParam, "String", "Label string to be displayed" },
   { backgroundParam, "String", "Background color, format \"rrggbb\"" },
   { foregroundParam, "String", "Foreground color, format \"rrggbb\"" },
  };
  return info;
}
Label label1 = new Label();
Label label2=new Label();
TextArea textarea=new TextArea("     ",5,10,TextArea.SCROLLBARS_HORIZONTAL_ONLY);
TextField text2=new TextField("     ");
Button button1=new Button("计算");
double result;
public void actionPerformed(ActionEvent e)
{
  GetAnswer();

  text2.setText("result");
}
/**
  * Intializes values for the applet and its components
  */
void initForm()
{
  this.setBackground(Color.lightGray);
  this.setForeground(Color.black);
  label1.setText("label1");
  this.setLayout(new FlowLayout());
  this.add(label2);
  label2.setText("算式为");
  this.add(textarea);
  button1.addActionListener(this);//将小程序注册为button1的动作事件监听者
  this.add(button1);
  this.add(text2);
  
  
}

private  void GetAnswer(String[] argv)
{
  KernelLink ml = null;
  try {
   //ml = MathLinkFactory.createKernelLink(argv);
                         ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname 'c:/program files/wolfram research/mathematica/5.0/mathkernel.exe'");
      }
  catch (MathLinkException e)
  {
   
   return;
  }
  try
  {
   // Get rid of the initial InputNamePacket the kernel will send
   // when it is launched.
   ml.discardAnswer();
   ml.evaluate("<<MyPackage.m");
   ml.discardAnswer();
   ml.evaluate("2+2");
   ml.waitForAnswer();
   double result;
     result = 0.0;
    result= ml.getInteger();
   //System.out.println("2 + 2 = " + result);
   
         ml.evaluate("NIntegrate[Sin[x],{x,0,1}]");
   ml.waitForAnswer();
   double result2=ml.getDouble();
   
   //System.out.println("integrate sin(x) = " + result2);
   // Here抯 how to send the same input, but not as a string:
   /*
   
   ml.putFunction("EvaluatePacket", 1);
   ml.putFunction("Plus", 2);
   ml.put(3);
   ml.put(3);
   ml.endPacket();
   ml.waitForAnswer();
   result = ml.getInteger();
   //System.out.println("3 + 3 = " + result);
   // If you want the result back as a string, use evaluateToInputForm or
   // evaluateToOutputForm. The second arg for either is the requested page
   // width for formatting the string. Pass 0 for PageWidth->Infinity.
   // These methods get the result in one step--no need to call waitForAnswer.
   String strResult = ml.evaluateToOutputForm("4+4", 0);
   //System.out.println("4 + 4 = " + strResult);*/
  }
  catch (MathLinkException e)
  {
   System.out.println("MathLinkException occurred: " + e.getMessage());
  }
  finally
  {
   ml.close();
  }

}
}
 楼主| 发表于 2008-5-11 10:55 | 显示全部楼层

用JAVA实现mathematica调用

我已经设置过路径了 ,不知道是不是设置错了.
发表于 2008-5-12 20:12 | 显示全部楼层

GetAnswer应该没有参数的

还有一个问题,你的代码点那个Button以后,啥也没有,只显示result,无敌了。。。。。。。。。。。。。。。
 楼主| 发表于 2008-5-13 16:22 | 显示全部楼层

我改了下程序 请大侠们帮忙啊

我的程序 现在是在不能在textarea1里调用 GetAnswer() 里面的result的值 ,可能是 GetAnswer() 这个函数错了 ,但是他是从mathematica里面直接粘的例子.能不能帮我把这里面的语句调能跟VJ适用.再三感谢啊
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import com.wolfram.jlink.*;
import com.*;
import java .math .*;
import java.text.*;
import java.awt.Graphics.*;
/**
* This class reads PARAM tags from its HTML host page and sets
* the color and label properties of the applet. Program execution
* begins with the init() method.
*/
public class Applet1 extends Applet implements ActionListener,ItemListener
{
        /**
         * The entry point for the applet.
         */
        public void init()
        {
                initForm();

                usePageParams();

                // TODO: Add any constructor code after initForm call.
        }

        private        final String labelParam = "label";
        private        final String backgroundParam = "background";
        private        final String foregroundParam = "foreground";

        /**
         * Reads parameters from the applet's HTML host and sets applet
         * properties.
         */
        private void usePageParams()
        {
                final String defaultLabel = "Default label";
                final String defaultBackground = "C0C0C0";
                final String defaultForeground = "000000";
                String labelValue;
                String backgroundValue;
                String foregroundValue;

                /**
                 * Read the <PARAM NAME="label" VALUE="some string">,
                 * <PARAM NAME="background" VALUE="rrggbb">,
                 * and <PARAM NAME="foreground" VALUE="rrggbb"> tags from
                 * the applet's HTML host.
                 */
                labelValue = getParameter(labelParam);
                backgroundValue = getParameter(backgroundParam);
                foregroundValue = getParameter(foregroundParam);

                if ((labelValue == null) || (backgroundValue == null) ||
                        (foregroundValue == null))
                {
                        /**
                         * There was something wrong with the HTML host tags.
                         * Generate default values.
                         */
                        labelValue = defaultLabel;
                        backgroundValue = defaultBackground;
                        foregroundValue = defaultForeground;
                }

                /**
                 * Set the applet's string label, background color, and
                 * foreground colors.
                 */
                label1.setText(labelValue);
                label1.setBackground(stringToColor(backgroundValue));
                label1.setForeground(stringToColor(foregroundValue));
                this.setBackground(stringToColor(backgroundValue));
                this.setForeground(stringToColor(foregroundValue));
               
        }

        /**
         * Converts a string formatted as "rrggbb" to an awt.Color object
         */
        private Color stringToColor(String paramValue)
        {
                int red;
                int green;
                int blue;

                red = (Integer.decode("0x" + paramValue.substring(0,2))).intValue();
                green = (Integer.decode("0x" + paramValue.substring(2,4))).intValue();
                blue = (Integer.decode("0x" + paramValue.substring(4,6))).intValue();

                return new Color(red,green,blue);
        }

        /**
         * External interface used by design tools to show properties of an applet.
         */
        public String[][] getParameterInfo()
        {
                String[][] info =
                {
                        { labelParam, "String", "Label string to be displayed" },
                        { backgroundParam, "String", "Background color, format \"rrggbb\"" },
                        { foregroundParam, "String", "Foreground color, format \"rrggbb\"" },
                };
                return info;
        }
String name;
        Label label1 = new Label();
        Label label2=new Label();
        TextArea textarea=new TextArea("     ",5,10,TextArea.SCROLLBARS_HORIZONTAL_ONLY);
        //TextField text2=new TextField("     ");
        TextArea textarea1=new TextArea("     ",5,10,TextArea.SCROLLBARS_HORIZONTAL_ONLY);
        Button button1=new Button("计算");

        double result;

  public void itemStateChanged(ItemEvent e)
        {
                name=(String)e.getItem();
        }
       
  public void actionPerformed(ActionEvent e)
        {
                if(e.getActionCommand()=="计算")
                {textarea1.setText("result");//输出
                       
                        //GetAnswer();
       
                //text2.setText("rr=" + result);
               
       
               
                        //textarea1.setText("result");//输出
                        this.repaint();
                }
               
        }
        /**
         * Intializes values for the applet and its components
         */

        void initForm()
        {
                this.setBackground(Color.lightGray);
                this.setForeground(Color.black);
                label1.setText("label1");
                this.setLayout(new FlowLayout());
                this.add(label2);
                label2.setText("算式为");
                this.add(textarea);
                button1.addActionListener(this);//将小程序注册为button1的动作事件监听者
                this.add(button1);
                this.add(textarea1);
               


               
               

        }
       
       
        //private  void  GetAnswer(String[] argv)
        private static void  GetAnswer()
        {

                KernelLink ml = null;

                try {
                        //ml = MathLinkFactory.createKernelLink(argv);
                         ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname 'c:/program files/wolfram research/mathematica/5.0/mathkernel.exe'");

                    }
                catch (MathLinkException e)
                {
                       
                        return;
                }

                try
                {
                        // Get rid of the initial InputNamePacket the kernel will send
                        // when it is launched.
                        ml.discardAnswer();

                        ml.evaluate("<<MyPackage.m");
                        ml.discardAnswer();

                        ml.evaluate("2+2");
                        ml.waitForAnswer();
                        double result;
                                        //result = 0.0;
                                result= ml.getInteger();
                               
                               
                        //System.out.println("2 + 2 = " + result);
                       
                       /*   ml.evaluate("NIntegrate[Sin[x],{x,0,1}]");
                        ml.waitForAnswer();
                        double result2=ml.getDouble();
                       
                        //System.out.println("integrate sin(x) = " + result2);

                        // Here抯 how to send the same input, but not as a string:
               
                       
                        ml.putFunction("EvaluatePacket", 1);
                        ml.putFunction("Plus", 2);
                        ml.put(3);
                        ml.put(3);
                        ml.endPacket();
                        ml.waitForAnswer();
                        result = ml.getInteger();
                        //System.out.println("3 + 3 = " + result);

                        // If you want the result back as a string, use evaluateToInputForm or
                        // evaluateToOutputForm. The second arg for either is the requested page
                        // width for formatting the string. Pass 0 for PageWidth->Infinity.
                        // These methods get the result in one step--no need to call waitForAnswer.
                        String strResult = ml.evaluateToOutputForm("4+4", 0);*/
                        //System.out.println("4 + 4 = " + strResult);
       

                }
                catch (MathLinkException e)
                {
                        System.out.println("MathLinkException occurred: " + e.getMessage());
                }
                finally
                {
                        ml.close();
                }
       
        }
}
 楼主| 发表于 2008-5-13 16:24 | 显示全部楼层

补充

我单独运行textarea1是可以显示里面的东西.但是把他放到GetAnswer()后面, 就不行 .郁闷了
 楼主| 发表于 2008-5-17 11:40 | 显示全部楼层

用JAVA实现mathematica调用

莫非没有人能搞? 天要亡我啊
您需要登录后才可以回帖 登录 | 我要加入

本版积分规则

QQ|小黑屋|Archiver|手机版|联系我们|声振论坛

GMT+8, 2024-12-23 23:31 , Processed in 0.069990 second(s), 19 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表