KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lsmp > djepExamples > DJepConsole


1 /*
2  * Created on 16-Jun-2003 by Rich webmaster@pfaf.org
3  * www.comp.leeds.ac.uk/pfaf/lsmp
4  *
5  * This code is covered by a Creative Commons
6  * Attribution, Non Commercial, Share Alike license
7  * <a HREF="http://creativecommons.org/licenses/by-nc-sa/1.0">License</a>
8  *
9  * Adapted from :
10  */

11
12 /*****************************************************************************
13
14 JEP - Java Math Expression Parser 2.24
15       December 30 2002
16       (c) Copyright 2002, Nathan Funk
17       See LICENSE.txt for license information.
18
19 *****************************************************************************/

20
21 /**
22  * Console - JEP Example Applet
23  * Copyright (c) 2000 Nathan Funk
24  *
25  * @author Nathan Funk
26  */

27
28 package org.lsmp.djepExamples;
29 import org.lsmp.djep.djep.*;
30 import org.nfunk.jep.*;
31 import java.io.*;
32 import java.applet.*;
33 import java.awt.*;
34 import java.awt.event.ActionListener JavaDoc;
35 import java.awt.event.ActionEvent JavaDoc;
36
37 /**
38 * This class implements a simple command line utility for evaluating
39 * mathematical expressions.
40 *
41 * Usage: java org.lsmp.djep.DJepConsole [expression]
42 *
43 * If an argument is passed, it is interpreted as an expression
44 * and evaluated. Otherwise, a prompt is printed, and the user can enter
45 * expressions to be evaluated. To exit from the command prompt a 'q' must
46 * be entered.
47 * typing
48 * <pre>diff(x^2,x)</pre>
49 * will differentiate x^2 wrt 2. And
50 * <pre>eval(x^2,x,3)</pre>
51 * will calculate x^2 at x=3.
52 * Expresions like
53 * <pre>eval(diff(diff(x^2+y^3,x),y),x,3,y,4)</pre>
54 * are also allowed.
55 */

56 public class DJepConsole extends Applet implements ActionListener JavaDoc {
57     /** Main JEP object */
58     DJep j;
59     /** Input equation. */
60     TextField inputTF;
61     /** variable to differentiate wrt respect to. */
62     TextField varTF;
63     /** Output equation. */
64     TextField outputTF;
65     /** Button to perform differentiation. */
66     Button but;
67     
68     
69     /** The prompt string */
70     private String JavaDoc prompt;
71     
72     /** The input reader */
73     private BufferedReader br;
74     
75     
76     /** Constructor */
77     public DJepConsole() {
78         prompt = "DJep > ";
79         br = new BufferedReader(new InputStreamReader(System.in));
80
81     }
82
83     /** Applet initialisation */
84         
85     public void init()
86     {
87         initialise();
88         setLayout(new GridLayout(3,2));
89         inputTF = new TextField("sin(x^2)",50);
90         outputTF = new TextField(50);
91         outputTF.setEditable(false);
92         varTF = new TextField("x",5);
93         but = new Button("Calculate");
94         but.addActionListener(this);
95         inputTF.addActionListener(this);
96
97         Panel p1 = new Panel();
98         p1.add(new Label("Differentiate:"));
99         p1.add(inputTF);
100         add(p1);
101         
102         Panel p2 = new Panel();
103         p2.add(new Label("with respect to:"));
104         p2.add(varTF);
105         p2.add(but);
106         add(p2);
107         
108         Panel p3 = new Panel();
109         p3.add(new Label("Result:"));
110         p3.add(outputTF);
111         add(p3);
112     }
113     
114     /** Called when the Calculate button is pressed.
115      * Firsts differentiates the expresion in inputTF wrt variable in
116      * varTF, then simplifies it and puts results into outputTF.
117      */

118     public void actionPerformed(ActionEvent JavaDoc e)
119     {
120             String JavaDoc command = inputTF.getText();
121             j.parseExpression(command);
122             if (j.hasError())
123             {
124                 outputTF.setText(j.getErrorInfo());
125             }
126             else
127             {
128                 // expression is OK, get the value
129
try
130                 {
131                     Node diff = j.differentiate(j.getTopNode(),varTF.getText());
132                     Node simp = j.simplify(diff);
133                     if (j.hasError())
134                     {
135                         outputTF.setText(j.getErrorInfo());
136                     }
137                     else
138                         outputTF.setText(j.toString(simp));
139                 }
140                 catch(ParseException e1) { outputTF.setText("Parse Error: "+e1.getMessage()); }
141                 catch(IllegalArgumentException JavaDoc e2) { outputTF.setText(e2.getMessage()); }
142                 catch(Exception JavaDoc e3) { outputTF.setText(e3.getMessage()); }
143
144                 // did error occur during evaluation?
145
}
146         
147     }
148     
149     /** Creates a new Console object and calls run() */
150     public static void main(String JavaDoc args[]) throws IOException {
151         DJepConsole c = new DJepConsole();
152         c.run(args);
153     }
154     
155     /** sets up all the needed objects. */
156     public void initialise()
157     {
158         j = new DJep();
159         j.addStandardConstants();
160         j.addStandardFunctions();
161         j.addComplex();
162         j.setAllowUndeclared(true);
163         j.setAllowAssignment(true);
164         j.setImplicitMul(true);
165         j.addStandardDiffRules();
166         //j.setTraverse(true);
167
}
168     
169     /** performs the operations specified by the node tree and prints results. */
170     public void processEquation(Node node)
171     {
172         try
173         {
174             System.out.print("Parsed:\t\t");
175             j.println(node);
176             Node processed = j.preprocess(node);
177             System.out.print("Processed:\t");
178             j.println(processed);
179             
180             Node simp = j.simplify(processed);
181             System.out.print("Simplified:\t");
182             j.println(simp);
183             
184             System.out.print("Full Brackets, no variable expansion:\t");
185             j.getPrintVisitor().setMode(DPrintVisitor.FULL_BRACKET,true);
186             j.getPrintVisitor().setMode(DPrintVisitor.PRINT_PARTIAL_EQNS,false);
187             j.println(simp);
188             j.getPrintVisitor().setMode(DPrintVisitor.PRINT_PARTIAL_EQNS,true);
189             j.getPrintVisitor().setMode(DPrintVisitor.FULL_BRACKET,false);
190
191             try
192             {
193                 Object JavaDoc res = j.evaluate(simp);
194                 System.out.println("Value:\t"+res.toString());
195             }
196             catch(Exception JavaDoc e2)
197             {
198                 System.out.println("Value:\tnull "+e2.getMessage());
199             }
200             
201         // Node diff = dv.differentiate(simp,"x");
202
// System.out.print("dfun/dx:\t");
203
// bpv.println(diff);
204
// simp = sv.simplify(diff);
205
// System.out.print("Simplified:\t");
206
// bpv.println(simp);
207

208             System.out.println("Variables");
209             ((DSymbolTable) j.getSymbolTable()).print(j.getPrintVisitor());
210         }
211         catch(ParseException e1) { System.out.println("Parse Error: "+e1.getMessage()); }
212         catch(IllegalArgumentException JavaDoc e2) { System.out.println(e2.getMessage()); }
213         catch(Exception JavaDoc e3) { System.out.println(e3.getMessage()); }
214     }
215     
216     
217
218     /** The input loop */
219     public void run(String JavaDoc args[]) throws IOException {
220         String JavaDoc command="";
221         initialise();
222          
223         if (args.length>0) {
224             // evaluate the expression passed as arguments
225
String JavaDoc temp = args[0];
226             for (int i=1; i<args.length; i++) temp += " " + args[i];
227             j.parseExpression(temp);
228             if (j.hasError())
229                 System.out.println(j.getErrorInfo());
230             else
231             {
232                 processEquation(j.getTopNode());
233             }
234
235         } else {
236             // no arguments - interactive mode
237

238             System.out.println("dJEPdx - Enter q to quit, rules to print the differentation rules,\ndiff(x^2,x) to differentiate,\neval(x^y,x,2,y,3) to evaluate");
239             System.out.print(prompt);
240
241             while ((command = getCommand()) != null) {
242                 j.parseExpression(command);
243                 
244                 if (j.hasError()) {
245                     System.out.println(j.getErrorInfo());
246                 } else {
247                         // expression is OK, get the value
248
processEquation(j.getTopNode());
249                     // did error occur during evaluation?
250
if (j.hasError()) {
251                         System.out.println(j.getErrorInfo());
252                     }
253                 }
254                 System.out.print(prompt);
255             }
256         }
257     }
258     
259     /**
260      * Get a command from the input.
261      * @return null if an error occures, or if the user enters a terminating
262      * command
263      */

264     private String JavaDoc getCommand() throws IOException {
265         String JavaDoc s;
266         
267         if (br == null)
268             return null;
269
270         if ( (s = br.readLine()) == null)
271             return null;
272
273         if( s.equals("rules"))
274         {
275             j.getDifferentationVisitor().printDiffRules();
276             System.out.println("dJEPdx - Enter q to quit, rules to print the differentation rules,\ndiff(x^2,x) to differentiate,\neval(x^y,x,2,y,3) to evaluate");
277             System.out.print(prompt);
278             return getCommand();
279         }
280         if (s.equals("q")
281             || s.equals("quit")
282             || s.equals("exit"))
283             return null;
284         
285         return s;
286     }
287 }
288
Popular Tags