KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*****************************************************************************
2
3 JEP - Java Math Expression Parser 2.24
4       December 30 2002
5       (c) Copyright 2002, Nathan Funk
6       See LICENSE.txt for license information.
7
8 *****************************************************************************/

9
10 /**
11  * Console - JEP Example Applet
12  * Copyright (c) 2000 Nathan Funk
13  *
14  * @author Richard Morris
15  */

16
17 package org.lsmp.djepExamples;
18 import org.nfunk.jep.*;
19 import org.lsmp.djep.djep.*;
20 import org.lsmp.djep.matrixJep.*;
21 import java.io.*;
22
23 /**
24 * This class implements a simple command line utility for evaluating
25 * mathematical expressions.
26 *
27 * Usage: java org.lsmp.djep.matrixParser.MatrixParserConsole [expression]
28 *
29 * If an argument is passed, it is interpreted as an expression
30 * and evaluated. Otherwise, a prompt is printed, and the user can enter
31 * expressions to be evaluated. To exit from the command prompt a 'q' must
32 * be entered.
33 * typing
34 * <pre>diff(x^2,x)</pre>
35 * will differentiate x^2 wrt 2. And
36 * <pre>eval(x^2,x,3)</pre>
37 * will calculate x^2 at x=3.
38 * Expresions like
39 * <pre>eval(diff(diff(x^2+y^3,x),y),x,3,y,4)</pre>
40 * are also allowed.
41 */

42 public class MatrixConsole {
43     /** Main JEP object */
44     MatrixJep j;
45     
46     /** The prompt string */
47     private String JavaDoc prompt;
48     
49     /** The input reader */
50     private BufferedReader br;
51
52     /** Constructor */
53     public MatrixConsole() {
54         prompt = "dJEPdx > ";
55         br = new BufferedReader(new InputStreamReader(System.in));
56
57     }
58
59     /** Creates a new Console object and calls run() */
60     public static void main(String JavaDoc args[]) throws IOException {
61         MatrixConsole c = new MatrixConsole();
62         c.run(args);
63     }
64     
65     /** sets up all the needed objects. */
66     void initialise()
67     {
68         j = new MatrixJep();
69         j.addStandardConstants();
70         j.addStandardFunctions();
71         j.addComplex();
72         j.setAllowUndeclared(true);
73         j.setImplicitMul(true);
74         j.setAllowAssignment(true);
75         j.addStandardDiffRules();
76         // dv.addDiffRule(new MProductDiffRule(dv,MatrixOperatorSet.M_HAT));
77
}
78     
79     /** performs the operations specified by the node tree and prints results. */
80     void processEquation(Node node)
81     {
82         if(node==null) return;
83         try
84         {
85             System.out.print("fun:\t\t");
86             j.println(node);
87             Node matEqn = j.preprocess(node);
88             j.println(matEqn);
89             Object JavaDoc res = j.evaluate(matEqn);
90             System.out.println("Res: "+res);
91             System.out.println("Variables");
92             ((DSymbolTable)j.getSymbolTable()).print(j.getPrintVisitor());
93         }
94         catch(ParseException e1) { System.out.println("Parse Error: "+e1.getMessage()); }
95         catch(IllegalArgumentException JavaDoc e2) { System.out.println(e2.getMessage()); }
96         catch(Exception JavaDoc e3) { System.out.println("Exception "+e3.getMessage()); e3.printStackTrace(); }
97     }
98
99     /** The input loop */
100     public void run(String JavaDoc args[]) throws IOException {
101         String JavaDoc command="";
102         initialise();
103          
104         if (args.length>0) {
105             // evaluate the expression passed as arguments
106
String JavaDoc temp = args[0];
107             for (int i=1; i<args.length; i++) temp += " " + args[i];
108             j.parseExpression(temp);
109             if (j.hasError())
110                 System.out.println(j.getErrorInfo());
111             else
112             {
113                 processEquation(j.getTopNode());
114             }
115
116         } else {
117             // no arguments - interactive mode
118

119             System.out.println("dJEPdx - Enter q to quit");
120             System.out.println("\tdiff(x^2,x) to differentiate");
121             System.out.println("\teval(x^y,x,2,y,3) to evaluate");
122             System.out.println("\trules to print operators and differentation rules.");
123             System.out.println("\tinvalidate to make all variables as having invalid values, used to force evaluation.");
124             System.out.println("\t[1,2].[3,4] for dot product.");
125             System.out.println("\t[1,2,3]^[3,4,5] for vector product (2^3 still works).");
126             System.out.println("\t[[1,2],[3,4]] for matricies.");
127                         
128             System.out.print(prompt);
129
130             while ((command = getCommand()) != null) {
131                 //j.parseExpression(command);
132
Node topNode=null;
133                 try
134                 {
135                     topNode = j.parse(command);
136         
137                 } catch (ParseException e) { System.out.println(e.getMessage()); }
138                 
139 // if (j.hasError()) {
140
// System.out.println(j.getErrorInfo());
141
// } else {
142
// expression is OK, get the value
143
//processEquation(Node j.getTopNode());
144
processEquation(topNode);
145                     // did error occur during evaluation?
146
// if (j.hasError()) {
147
// System.out.println(j.getErrorInfo());
148
// }
149
// }
150
System.out.print(prompt);
151             }
152         }
153     }
154     
155     /**
156      * Get a command from the input.
157      * @return null if an error occures, or if the user enters a terminating
158      * command
159      */

160     private String JavaDoc getCommand() throws IOException {
161         String JavaDoc s;
162         
163         if (br == null)
164             return null;
165
166         if ( (s = br.readLine()) == null)
167             return null;
168
169         if( s.equals("rules"))
170         {
171             j.getDifferentationVisitor().printDiffRules();
172
173             System.out.println("Operators:");
174             j.getOperatorSet().printOperators();
175
176 // 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");
177
System.out.print(prompt);
178             return getCommand();
179         }
180         if( s.equals("invalidate"))
181         {
182             this.j.getSymbolTable().clearValues();
183             ((DSymbolTable)j.getSymbolTable()).print(j.getPrintVisitor());
184             System.out.print(prompt);
185             return getCommand();
186         }
187
188         if (s.equals("q")
189             || s.equals("quit")
190             || s.equals("exit"))
191             return null;
192         
193         return s;
194     }
195 }
196
Popular Tags