001    package org.jdmp.core.script.jdmp;
002    
003    import java.lang.reflect.Constructor;
004    import java.lang.reflect.Method;
005    import java.util.ArrayList;
006    import java.util.List;
007    import java.util.Map;
008    
009    import org.jdmp.core.algorithm.Algorithm;
010    import org.jdmp.core.algorithm.AlgorithmMapping;
011    import org.jdmp.core.dataset.DataSet;
012    import org.jdmp.core.dataset.DataSetFactory;
013    import org.jdmp.core.dataset.RegressionDataSet;
014    import org.jdmp.core.module.Module;
015    import org.jdmp.core.module.ModuleFactory;
016    import org.jdmp.core.sample.Sample;
017    import org.jdmp.core.sample.SampleFactory;
018    import org.jdmp.core.script.Result;
019    import org.jdmp.core.script.jdmp.analysis.DepthFirstAdapter;
020    import org.jdmp.core.script.jdmp.node.AAndLevel7;
021    import org.jdmp.core.script.jdmp.node.AArgumentListArgumentList;
022    import org.jdmp.core.script.jdmp.node.AArray;
023    import org.jdmp.core.script.jdmp.node.AArrayAssignment;
024    import org.jdmp.core.script.jdmp.node.AArrayMatrix;
025    import org.jdmp.core.script.jdmp.node.ABitComplementLevel2;
026    import org.jdmp.core.script.jdmp.node.ABooleanLiteral;
027    import org.jdmp.core.script.jdmp.node.AColumn;
028    import org.jdmp.core.script.jdmp.node.AColumnMatrix;
029    import org.jdmp.core.script.jdmp.node.ACommaValue;
030    import org.jdmp.core.script.jdmp.node.AComplementLevel2;
031    import org.jdmp.core.script.jdmp.node.ADotLdivLevel3;
032    import org.jdmp.core.script.jdmp.node.ADotMultLevel3;
033    import org.jdmp.core.script.jdmp.node.ADotPowerLevel1;
034    import org.jdmp.core.script.jdmp.node.ADotRdivLevel3;
035    import org.jdmp.core.script.jdmp.node.ADotTransposeLevel1;
036    import org.jdmp.core.script.jdmp.node.AEmptyFunction;
037    import org.jdmp.core.script.jdmp.node.AEmptyMatrix;
038    import org.jdmp.core.script.jdmp.node.AEqLevel6;
039    import org.jdmp.core.script.jdmp.node.AExpressionArgumentList;
040    import org.jdmp.core.script.jdmp.node.AExpressionLevel0;
041    import org.jdmp.core.script.jdmp.node.AFloatingPointLiteral;
042    import org.jdmp.core.script.jdmp.node.AFunctionLevel0;
043    import org.jdmp.core.script.jdmp.node.AGtLevel6;
044    import org.jdmp.core.script.jdmp.node.AGteqLevel6;
045    import org.jdmp.core.script.jdmp.node.AIdentifierAssignment;
046    import org.jdmp.core.script.jdmp.node.AIdentifierLevel0;
047    import org.jdmp.core.script.jdmp.node.AIntegerLiteral;
048    import org.jdmp.core.script.jdmp.node.ALdivLevel3;
049    import org.jdmp.core.script.jdmp.node.ALevel0Level1;
050    import org.jdmp.core.script.jdmp.node.ALevel10Expression;
051    import org.jdmp.core.script.jdmp.node.ALevel1Level2;
052    import org.jdmp.core.script.jdmp.node.ALevel2Level3;
053    import org.jdmp.core.script.jdmp.node.ALevel3Level4;
054    import org.jdmp.core.script.jdmp.node.ALevel4Level5;
055    import org.jdmp.core.script.jdmp.node.ALevel5Level6;
056    import org.jdmp.core.script.jdmp.node.ALevel6Level7;
057    import org.jdmp.core.script.jdmp.node.ALevel7Level8;
058    import org.jdmp.core.script.jdmp.node.ALevel8Level9;
059    import org.jdmp.core.script.jdmp.node.ALevel9Level10;
060    import org.jdmp.core.script.jdmp.node.ALiteralLevel0;
061    import org.jdmp.core.script.jdmp.node.ALogicalAndLevel9;
062    import org.jdmp.core.script.jdmp.node.ALogicalOrLevel10;
063    import org.jdmp.core.script.jdmp.node.ALtLevel6;
064    import org.jdmp.core.script.jdmp.node.ALteqLevel6;
065    import org.jdmp.core.script.jdmp.node.AMatrixLevel0;
066    import org.jdmp.core.script.jdmp.node.AMinusLevel2;
067    import org.jdmp.core.script.jdmp.node.AMinusLevel4;
068    import org.jdmp.core.script.jdmp.node.AMultLevel3;
069    import org.jdmp.core.script.jdmp.node.ANeqLevel6;
070    import org.jdmp.core.script.jdmp.node.AOrLevel8;
071    import org.jdmp.core.script.jdmp.node.AParameterFunction;
072    import org.jdmp.core.script.jdmp.node.APlusLevel2;
073    import org.jdmp.core.script.jdmp.node.APlusLevel4;
074    import org.jdmp.core.script.jdmp.node.APowerLevel1;
075    import org.jdmp.core.script.jdmp.node.AQualifiedName;
076    import org.jdmp.core.script.jdmp.node.ARangeLevel5;
077    import org.jdmp.core.script.jdmp.node.ARdivLevel3;
078    import org.jdmp.core.script.jdmp.node.ARow;
079    import org.jdmp.core.script.jdmp.node.ARowMatrix;
080    import org.jdmp.core.script.jdmp.node.ASemicolonRow;
081    import org.jdmp.core.script.jdmp.node.ASemicolonValue;
082    import org.jdmp.core.script.jdmp.node.ASimpleName;
083    import org.jdmp.core.script.jdmp.node.AStatement;
084    import org.jdmp.core.script.jdmp.node.AStringLiteral;
085    import org.jdmp.core.script.jdmp.node.ATransposeLevel1;
086    import org.jdmp.core.script.jdmp.node.AValueMatrix;
087    import org.jdmp.core.script.jdmp.node.Node;
088    import org.jdmp.core.script.jdmp.node.PArgumentList;
089    import org.jdmp.core.script.jdmp.node.PArray;
090    import org.jdmp.core.script.jdmp.node.PColumn;
091    import org.jdmp.core.script.jdmp.node.PCommaValue;
092    import org.jdmp.core.script.jdmp.node.PExpression;
093    import org.jdmp.core.script.jdmp.node.PFunction;
094    import org.jdmp.core.script.jdmp.node.PLevel0;
095    import org.jdmp.core.script.jdmp.node.PLevel1;
096    import org.jdmp.core.script.jdmp.node.PLevel10;
097    import org.jdmp.core.script.jdmp.node.PLevel2;
098    import org.jdmp.core.script.jdmp.node.PLevel3;
099    import org.jdmp.core.script.jdmp.node.PLevel4;
100    import org.jdmp.core.script.jdmp.node.PLevel5;
101    import org.jdmp.core.script.jdmp.node.PLevel6;
102    import org.jdmp.core.script.jdmp.node.PLevel7;
103    import org.jdmp.core.script.jdmp.node.PLevel8;
104    import org.jdmp.core.script.jdmp.node.PLevel9;
105    import org.jdmp.core.script.jdmp.node.PLiteral;
106    import org.jdmp.core.script.jdmp.node.PMatrix;
107    import org.jdmp.core.script.jdmp.node.PName;
108    import org.jdmp.core.script.jdmp.node.PRow;
109    import org.jdmp.core.script.jdmp.node.PSemicolonRow;
110    import org.jdmp.core.script.jdmp.node.PSemicolonValue;
111    import org.jdmp.core.variable.Variable;
112    import org.jdmp.core.variable.VariableFactory;
113    import org.ujmp.core.Matrix;
114    import org.ujmp.core.MatrixFactory;
115    import org.ujmp.core.calculation.Calculation.Ret;
116    import org.ujmp.core.enums.ValueType;
117    import org.ujmp.core.exceptions.MatrixException;
118    import org.ujmp.core.util.MathUtil;
119    import org.ujmp.core.util.StringUtil;
120    
121    public class Translation extends DepthFirstAdapter {
122    
123            public static final String ANS = "ans";
124    
125            private Module module = null;
126    
127            private Result result = null;
128    
129            private final boolean ignoreNaN = true;
130    
131            public Translation(Module module) {
132                    this.module = module;
133            }
134    
135            private Variable getVariable(PName identifier) {
136                    String label = identifier.toString().trim();
137                    Variable v = module.getVariables().get(label);
138                    if (v == null) {
139                            v = VariableFactory.labeledVariable(label);
140                            module.getVariables().put(label, v);
141                    }
142                    return v;
143            }
144    
145            private Matrix getMatrix(PArray array) throws Exception {
146                    AArray aArray = (AArray) array;
147    
148                    ARow aRow = (ARow) aArray.getRow();
149    
150                    int rows = aArray.getAdditionalRows().size() + 1;
151                    int columns = aRow.getAdditionalValues().size() + 1;
152    
153                    for (PSemicolonRow semicolonRow : aArray.getAdditionalRows()) {
154                            aRow = (ARow) ((ASemicolonRow) semicolonRow).getRow();
155                            columns = Math.max(columns, aRow.getAdditionalValues().size() + 1);
156                    }
157                    Matrix m = MatrixFactory.zeros(ValueType.OBJECT, rows, columns);
158    
159                    aRow = (ARow) aArray.getRow();
160                    PExpression expr = aRow.getExpression();
161                    m.setAsObject(getSingleValue(expr), 0, 0);
162                    int c = 1;
163                    for (PCommaValue commaValue : aRow.getAdditionalValues()) {
164                            ACommaValue aCommaValue = (ACommaValue) commaValue;
165                            expr = aCommaValue.getExpression();
166                            m.setAsObject(getSingleValue(expr), 0, c++);
167                    }
168    
169                    int r = 1;
170                    for (PSemicolonRow semicolonRow : aArray.getAdditionalRows()) {
171                            aRow = (ARow) ((ASemicolonRow) semicolonRow).getRow();
172                            expr = aRow.getExpression();
173                            m.setAsObject(getSingleValue(expr), r, 0);
174                            c = 1;
175                            for (PCommaValue commaValue : aRow.getAdditionalValues()) {
176                                    ACommaValue aCommaValue = (ACommaValue) commaValue;
177                                    expr = aCommaValue.getExpression();
178                                    m.setAsObject(getSingleValue(expr), r, c++);
179                            }
180                            r++;
181                    }
182    
183                    return m;
184            }
185    
186            private Matrix getMatrix(PRow row) throws Exception {
187                    ARow aRow = (ARow) row;
188                    int columns = aRow.getAdditionalValues().size() + 1;
189                    Matrix m = MatrixFactory.zeros(ValueType.OBJECT, 1, columns);
190                    m.setAsObject(getSingleValue(aRow.getExpression()), 0, 0);
191                    int i = 1;
192                    for (PCommaValue commaValue : aRow.getAdditionalValues()) {
193                            PExpression expr = ((ACommaValue) commaValue).getExpression();
194                            m.setAsObject(getSingleValue(expr), 0, i++);
195                    }
196                    return m;
197            }
198    
199            private Matrix getMatrix(PColumn column) throws Exception {
200                    AColumn aColumn = (AColumn) column;
201                    int rows = aColumn.getAdditionalValues().size() + 1;
202                    Matrix m = MatrixFactory.zeros(ValueType.OBJECT, rows, 1);
203                    m.setAsObject(getSingleValue(aColumn.getExpression()), 0, 0);
204                    int i = 1;
205                    for (PSemicolonValue semicolonValue : aColumn.getAdditionalValues()) {
206                            PExpression expr = ((ASemicolonValue) semicolonValue).getExpression();
207                            m.setAsObject(getSingleValue(expr), i++, 0);
208                    }
209                    return m;
210            }
211    
212            @Override
213            public void defaultOut(Node node) {
214                    System.out.println(node.getClass().getSimpleName() + ": " + node);
215            }
216    
217            public Result getResult() {
218                    return result;
219            }
220    
221            @Override
222            public void outAArrayAssignment(AArrayAssignment node) {
223                    Exception e = new MatrixException("array assignments are not supported yet.");
224                    result = new Result(e);
225                    e.printStackTrace();
226            }
227    
228            @Override
229            public void outAIdentifierAssignment(AIdentifierAssignment node) {
230                    try {
231                            String id = node.getName().toString().trim();
232                            Object o = getObject(node.getExpression());
233                            if (o instanceof Module) {
234                                    Module m = (Module) o;
235                                    if (!ANS.equals(id)) {
236                                            module.getModules().put(id, m);
237                                    }
238                                    result = new Result(id, m);
239                            } else if (o instanceof DataSet) {
240                                    DataSet ds = (DataSet) o;
241                                    if (!ANS.equals(id)) {
242                                            module.getDataSets().put(id, ds);
243                                    }
244                                    result = new Result(id, ds);
245                            } else if (o instanceof Sample) {
246                                    Sample s = (Sample) o;
247                                    if (!ANS.equals(id)) {
248                                            module.getSamples().put(id, s);
249                                    }
250                                    result = new Result(id, s);
251                            } else if (o instanceof Variable) {
252                                    Variable v = (Variable) o;
253                                    if (!ANS.equals(id)) {
254                                            module.getVariables().put(id, v);
255                                    }
256                                    result = new Result(id, v);
257                            } else if (o instanceof Algorithm) {
258                                    Algorithm a = (Algorithm) o;
259                                    if (!ANS.equals(id)) {
260                                            module.getAlgorithms().put(id, a);
261                                    }
262                                    result = new Result(id, a);
263                            } else {
264                                    Matrix m = MathUtil.getMatrix(o);
265                                    if (m != null) {
266                                            Variable v = getVariable(node.getName());
267                                            v.addMatrix(m);
268                                            result = new Result(v.getLabel(), m);
269                                            System.out.println(result.toString());
270                                    }
271                            }
272                    } catch (Exception e) {
273                            result = new Result(e);
274                            e.printStackTrace();
275                    }
276            }
277    
278            private Object getObject(PExpression expression) throws Exception {
279                    if (expression instanceof ALevel10Expression) {
280                            return getObject(((ALevel10Expression) expression).getLevel10());
281                    }
282                    MatrixException e = new MatrixException("Unknown expression type: "
283                                    + expression.getClass().getSimpleName());
284                    result = new Result(e);
285                    throw e;
286            }
287    
288            private Object getObject(PLevel10 expression) throws Exception {
289                    if (expression instanceof ALevel9Level10) {
290                            return getObject(((ALevel9Level10) expression).getLevel9());
291                    } else if (expression instanceof ALogicalOrLevel10) {
292                            ALogicalOrLevel10 exp = (ALogicalOrLevel10) expression;
293                            Matrix left = MathUtil.getMatrix(getObject(exp.getLeft()));
294                            Matrix right = MathUtil.getMatrix(getObject(exp.getRight()));
295                            return left.or(Ret.NEW, right);
296                    }
297                    MatrixException e = new MatrixException("Unknown expression type: "
298                                    + expression.getClass().getSimpleName());
299                    result = new Result(e);
300                    throw e;
301            }
302    
303            private Object getObject(PLevel9 expression) throws Exception {
304                    if (expression instanceof ALevel8Level9) {
305                            return getObject(((ALevel8Level9) expression).getLevel8());
306                    } else if (expression instanceof ALogicalAndLevel9) {
307                            ALogicalAndLevel9 exp = (ALogicalAndLevel9) expression;
308                            Matrix left = MathUtil.getMatrix(getObject(exp.getLeft()));
309                            Matrix right = MathUtil.getMatrix(getObject(exp.getRight()));
310                            return left.and(Ret.NEW, right);
311                    }
312                    MatrixException e = new MatrixException("Unknown expression type: "
313                                    + expression.getClass().getSimpleName());
314                    result = new Result(e);
315                    throw e;
316            }
317    
318            private Object getObject(PLevel8 expression) throws Exception {
319                    if (expression instanceof ALevel7Level8) {
320                            return getObject(((ALevel7Level8) expression).getLevel7());
321                    } else if (expression instanceof AOrLevel8) {
322                            // TODO
323                    }
324                    MatrixException e = new MatrixException("Unknown expression type: "
325                                    + expression.getClass().getSimpleName());
326                    result = new Result(e);
327                    throw e;
328            }
329    
330            private Object getObject(PLevel7 expression) throws Exception {
331                    if (expression instanceof ALevel6Level7) {
332                            return getObject(((ALevel6Level7) expression).getLevel6());
333                    } else if (expression instanceof AAndLevel7) {
334                            // TODO
335                    }
336                    MatrixException e = new MatrixException("Unknown expression type: "
337                                    + expression.getClass().getSimpleName());
338                    result = new Result(e);
339                    throw e;
340            }
341    
342            private Object getObject(PLevel6 expression) throws Exception {
343                    if (expression instanceof ALevel5Level6) {
344                            return getObject(((ALevel5Level6) expression).getLevel5());
345                    } else if (expression instanceof AEqLevel6) {
346                            AEqLevel6 exp = (AEqLevel6) expression;
347                            Matrix left = MathUtil.getMatrix(getObject(exp.getLeft()));
348                            Matrix right = MathUtil.getMatrix(getObject(exp.getRight()));
349                            return left.eq(Ret.NEW, right);
350                    } else if (expression instanceof ANeqLevel6) {
351                            ANeqLevel6 exp = (ANeqLevel6) expression;
352                            Matrix left = MathUtil.getMatrix(getObject(exp.getLeft()));
353                            Matrix right = MathUtil.getMatrix(getObject(exp.getRight()));
354                            return left.ne(Ret.NEW, right);
355                    } else if (expression instanceof AGtLevel6) {
356                            AGtLevel6 exp = (AGtLevel6) expression;
357                            Matrix left = MathUtil.getMatrix(getObject(exp.getLeft()));
358                            Matrix right = MathUtil.getMatrix(getObject(exp.getRight()));
359                            return left.gt(Ret.NEW, right);
360                    } else if (expression instanceof ALtLevel6) {
361                            ALtLevel6 exp = (ALtLevel6) expression;
362                            Matrix left = MathUtil.getMatrix(getObject(exp.getLeft()));
363                            Matrix right = MathUtil.getMatrix(getObject(exp.getRight()));
364                            return left.lt(Ret.NEW, right);
365                    } else if (expression instanceof AGteqLevel6) {
366                            AGteqLevel6 exp = (AGteqLevel6) expression;
367                            Matrix left = MathUtil.getMatrix(getObject(exp.getLeft()));
368                            Matrix right = MathUtil.getMatrix(getObject(exp.getRight()));
369                            return left.ge(Ret.NEW, right);
370                    } else if (expression instanceof ALteqLevel6) {
371                            ALteqLevel6 exp = (ALteqLevel6) expression;
372                            Matrix left = MathUtil.getMatrix(getObject(exp.getLeft()));
373                            Matrix right = MathUtil.getMatrix(getObject(exp.getRight()));
374                            return left.le(Ret.NEW, right);
375                    }
376                    MatrixException e = new MatrixException("Unknown expression type: "
377                                    + expression.getClass().getSimpleName());
378                    result = new Result(e);
379                    throw e;
380            }
381    
382            private Object getObject(PLevel5 expression) throws Exception {
383                    if (expression instanceof ALevel4Level5) {
384                            return getObject(((ALevel4Level5) expression).getLevel4());
385                    } else if (expression instanceof ARangeLevel5) {
386                            // TODO
387                    }
388                    MatrixException e = new MatrixException("Unknown expression type: "
389                                    + expression.getClass().getSimpleName());
390                    result = new Result(e);
391                    throw e;
392            }
393    
394            private Object getObject(PLevel4 calculation) throws Exception {
395                    if (calculation instanceof ALevel3Level4) {
396                            return getObject(((ALevel3Level4) calculation).getLevel3());
397                    } else if (calculation instanceof APlusLevel4) {
398                            APlusLevel4 op = (APlusLevel4) calculation;
399                            PLevel4 left = op.getLeft();
400                            PLevel3 right = op.getRight();
401                            Matrix leftM = MathUtil.getMatrix(getObject(left));
402                            Matrix rightM = MathUtil.getMatrix(getObject(right));
403                            return leftM.plus(Ret.NEW, ignoreNaN, rightM);
404                    } else if (calculation instanceof AMinusLevel4) {
405                            AMinusLevel4 op = (AMinusLevel4) calculation;
406                            PLevel4 left = op.getLeft();
407                            PLevel3 right = op.getRight();
408                            Matrix leftM = MathUtil.getMatrix(getObject(left));
409                            Matrix rightM = MathUtil.getMatrix(getObject(right));
410                            return leftM.minus(Ret.NEW, ignoreNaN, rightM);
411                    }
412                    MatrixException e = new MatrixException("Unknown expression type: "
413                                    + calculation.getClass().getSimpleName());
414                    result = new Result(e);
415                    throw e;
416            }
417    
418            private Object getObject(PLevel3 term) throws Exception {
419                    if (term instanceof ALevel2Level3) {
420                            return getObject(((ALevel2Level3) term).getLevel2());
421                    } else if (term instanceof AMultLevel3) {
422                            Matrix left = MathUtil.getMatrix(getObject(((AMultLevel3) term).getLeft()));
423                            Matrix right = MathUtil.getMatrix(getObject(((AMultLevel3) term).getRight()));
424                            return left.mtimes(Ret.NEW, ignoreNaN, right);
425                    } else if (term instanceof ADotMultLevel3) {
426                            Matrix left = MathUtil.getMatrix(getObject(((ADotMultLevel3) term).getLeft()));
427                            Matrix right = MathUtil.getMatrix(getObject(((ADotMultLevel3) term).getRight()));
428                            return left.times(Ret.NEW, ignoreNaN, right);
429                    } else if (term instanceof ARdivLevel3) {
430                            Matrix left = MathUtil.getMatrix(getObject(((ARdivLevel3) term).getLeft()));
431                            Matrix right = MathUtil.getMatrix(getObject(((ARdivLevel3) term).getRight()));
432                            return left.divide(Ret.NEW, ignoreNaN, right);
433                    } else if (term instanceof ADotRdivLevel3) {
434                            Matrix left = MathUtil.getMatrix(getObject(((ADotRdivLevel3) term).getLeft()));
435                            Matrix right = MathUtil.getMatrix(getObject(((ADotRdivLevel3) term).getRight()));
436                            return left.divide(Ret.NEW, ignoreNaN, right);
437                    } else if (term instanceof ALdivLevel3) {
438                            Matrix left = MathUtil.getMatrix(getObject(((ALdivLevel3) term).getLeft()));
439                            Matrix right = MathUtil.getMatrix(getObject(((ALdivLevel3) term).getRight()));
440                            // TODO
441                    } else if (term instanceof ADotLdivLevel3) {
442                            Matrix left = MathUtil.getMatrix(getObject(((ADotLdivLevel3) term).getLeft()));
443                            Matrix right = MathUtil.getMatrix(getObject(((ADotLdivLevel3) term).getRight()));
444                            // TODO
445                    }
446                    MatrixException e = new MatrixException("Unknown expression type: "
447                                    + term.getClass().getSimpleName());
448                    result = new Result(e);
449                    throw e;
450            }
451    
452            private Object getObject(PLevel0 factor) throws Exception {
453                    if (factor instanceof ALiteralLevel0) {
454                            return MatrixFactory.linkToValue(getValue(((ALiteralLevel0) factor).getLiteral()));
455                    } else if (factor instanceof AMatrixLevel0) {
456                            return getMatrix(((AMatrixLevel0) factor).getMatrix());
457                    } else if (factor instanceof AExpressionLevel0) {
458                            return getObject(((AExpressionLevel0) factor).getExpression());
459                    } else if (factor instanceof AFunctionLevel0) {
460                            return getObject(((AFunctionLevel0) factor).getFunction());
461                    } else if (factor instanceof AIdentifierLevel0) {
462                            String name = ((AIdentifierLevel0) factor).getName().toString().trim();
463    
464                            if (ANS.equals(name) && module.getVariables().get(ANS) == null) {
465                                    module.getVariables().put(ANS, VariableFactory.labeledVariable(ANS));
466                            }
467    
468                            Variable v = module.getVariables().get(name);
469                            if (v != null) {
470                                    return v.getMatrix();
471                            }
472    
473                            DataSet ds = module.getDataSets().get(name);
474                            if (ds != null) {
475                                    return ds;
476                            }
477    
478                            Module m = module.getModules().get(name);
479                            if (m != null) {
480                                    return m;
481                            }
482    
483                            Sample s = module.getSamples().get(name);
484                            if (s != null) {
485                                    return s;
486                            }
487    
488                            Algorithm a = module.getAlgorithms().get(name);
489                            if (a != null) {
490                                    return a;
491                            }
492    
493                            a = getAlgorithm(name);
494                            if (a != null) {
495                                    return executeAlgorithm(a, null);
496                            }
497    
498                            MatrixException e = new MatrixException("Unknown object or command: " + name);
499                            result = new Result(e);
500                            throw e;
501    
502                    }
503                    MatrixException e = new MatrixException("Unknown expression type: "
504                                    + factor.getClass().getSimpleName());
505                    result = new Result(e);
506                    throw e;
507            }
508    
509            private Object getObject(PLevel2 factor) throws Exception {
510                    if (factor instanceof ALevel1Level2) {
511                            return getObject(((ALevel1Level2) factor).getLevel1());
512                    } else if (factor instanceof AMinusLevel2) {
513                            Matrix m = MathUtil.getMatrix(getObject(((AMinusLevel2) factor).getLevel1()));
514                            return m.times(-1);
515                    } else if (factor instanceof APlusLevel2) {
516                            return getObject(((APlusLevel2) factor).getLevel1());
517                    } else if (factor instanceof AComplementLevel2) {
518                            Matrix m = MathUtil.getMatrix(getObject(((AComplementLevel2) factor).getLevel1()));
519                            return m.not(Ret.NEW);
520                    } else if (factor instanceof ABitComplementLevel2) {
521                            // TODO
522                    }
523                    MatrixException e = new MatrixException("Unknown expression type: "
524                                    + factor.getClass().getSimpleName());
525                    result = new Result(e);
526                    throw e;
527            }
528    
529            private Object getObject(PLevel1 factor) throws Exception {
530                    if (factor instanceof ALevel0Level1) {
531                            return getObject(((ALevel0Level1) factor).getLevel0());
532                    } else if (factor instanceof APowerLevel1) {
533                            Matrix left = MathUtil.getMatrix(getObject(((APowerLevel1) factor).getLeft()));
534                            Matrix right = MathUtil.getMatrix(getObject(((APowerLevel1) factor).getRight()));
535                            // TODO
536                    } else if (factor instanceof ADotPowerLevel1) {
537                            Matrix left = MathUtil.getMatrix(getObject(((ADotPowerLevel1) factor).getLeft()));
538                            Matrix right = MathUtil.getMatrix(getObject(((ADotPowerLevel1) factor).getRight()));
539                            return left.power(Ret.NEW, right);
540                    } else if (factor instanceof ATransposeLevel1) {
541                            Matrix m = MathUtil.getMatrix(getObject(((ATransposeLevel1) factor).getLevel0()));
542                            return m.transpose();
543                    } else if (factor instanceof ADotTransposeLevel1) {
544                            Matrix m = MathUtil.getMatrix(getObject(((ADotTransposeLevel1) factor).getLevel0()));
545                            return m.transpose();
546                    }
547                    MatrixException e = new MatrixException("Unknown expression type: "
548                                    + factor.getClass().getSimpleName());
549                    result = new Result(e);
550                    throw e;
551            }
552    
553            public Object executeFunction(PName name, PArgumentList arguments) throws Exception {
554                    if (name instanceof ASimpleName) {
555                            ASimpleName sn = (ASimpleName) name;
556                            String id = sn.getIdentifier().toString().trim();
557                            Algorithm algorithm = getAlgorithm(id);
558                            if (algorithm == null) {
559                                    MatrixException e = new MatrixException("Unknown algorithm: " + id);
560                                    result = new Result(e);
561                                    throw e;
562                            }
563                            return executeAlgorithm(algorithm, arguments);
564                    } else if (name instanceof AQualifiedName) {
565                            AQualifiedName qn = (AQualifiedName) name;
566                            String id = qn.getName().toString().trim();
567                            Object object = getObject(id);
568                            if (object == null) {
569    
570                                    // try other classes
571                                    String methodName = qn.getIdentifier().toString().trim();
572                                    Class<?> c = null;
573                                    if ("MatrixFactory".equals(id)) {
574                                            c = MatrixFactory.class;
575                                    } else if ("VariableFactory".equals(id)) {
576                                            c = VariableFactory.class;
577                                    } else if ("SampleFactory".equals(id)) {
578                                            c = SampleFactory.class;
579                                    } else if ("ModuleFactory".equals(id)) {
580                                            c = ModuleFactory.class;
581                                    } else if ("DataSetFactory".equals(id)) {
582                                            c = DataSetFactory.class;
583                                    }
584                                    if (c != null) {
585                                            return executeMethod(c, null, methodName, arguments);
586                                    }
587    
588                                    MatrixException e = new MatrixException("Unknown identifier: " + id);
589                                    result = new Result(e);
590                                    throw e;
591                            }
592                            return executeMethod(object.getClass(), object, qn.getIdentifier().toString().trim(),
593                                            arguments);
594                    }
595    
596                    MatrixException e = new MatrixException("Unknown function: "
597                                    + name.getClass().getSimpleName());
598                    result = new Result(e);
599                    throw e;
600            }
601    
602            private List<Object> getArgumentsAsObjects(PArgumentList arguments) throws Exception {
603                    List<Object> obj = new ArrayList<Object>();
604                    if (arguments == null) {
605                            return obj;
606                    }
607                    if (arguments instanceof AExpressionArgumentList) {
608                            PExpression expr = ((AExpressionArgumentList) arguments).getExpression();
609                            obj.add(getObject(expr));
610                            return obj;
611                    } else if (arguments instanceof AArgumentListArgumentList) {
612                            PExpression expr = ((AArgumentListArgumentList) arguments).getExpression();
613                            obj.addAll(getArgumentsAsObjects(((AArgumentListArgumentList) arguments)
614                                            .getArgumentList()));
615                            obj.add(getObject(expr));
616                            return obj;
617                    }
618                    MatrixException e = new MatrixException("Unknown arguments: "
619                                    + arguments.getClass().getSimpleName());
620                    result = new Result(e);
621                    throw e;
622            }
623    
624            private Object executeAlgorithm(Algorithm algorithm, PArgumentList arguments) throws Exception {
625                    List<Object> matrices = getArgumentsAsObjects(arguments);
626                    Map<Object, Object> ret = algorithm.calculateObjects(matrices);
627                    if (ret.isEmpty()) {
628                            return null;
629                    } else {
630                            return ret.values().iterator().next();
631                    }
632            }
633    
634            private Algorithm getAlgorithm(String id) throws Exception {
635                    Class<?> c = null;
636    
637                    String cname = AlgorithmMapping.get(id);
638                    if (cname != null) {
639                            try {
640                                    c = Class.forName(cname);
641                            } catch (Exception e) {
642                            }
643                    }
644    
645                    // no algorithm found, maybe its a module method
646                    if (c == null) {
647                            return null;
648                    }
649    
650                    Constructor<?> constr = c.getConstructor(Variable.VARIABLEARRAY);
651                    Algorithm algorithm = (Algorithm) constr.newInstance(new Object[] { new Variable[] {} });
652                    return algorithm;
653            }
654    
655            private Object executeMethod(Class<?> c, Object object, String name, PArgumentList argumentList)
656                            throws Exception {
657                    List<Object> matrices = getArgumentsAsObjects(argumentList);
658                    for (Method method : c.getMethods()) {
659                            if (method.getName().equals(name)
660                                            && method.getParameterTypes().length == matrices.size()) {
661                                    Object[] arguments = convertObjects(matrices, method.getParameterTypes());
662                                    Object o = method.invoke(object, arguments);
663                                    return o;
664                            }
665                    }
666                    MatrixException e = new MatrixException("Unknown method: " + name);
667                    result = new Result(e);
668                    throw e;
669            }
670    
671            private Object[] convertObjects(List<Object> matrices, Class<?>[] classes) {
672                    List<Object> objects = new ArrayList<Object>();
673                    for (int i = 0; i < classes.length; i++) {
674                            Class<?> c = classes[i];
675                            Object m = matrices.get(i);
676                            Object o = convertObject(m, c);
677                            objects.add(o);
678                    }
679                    return objects.toArray();
680            }
681    
682            private Object convertObject(Object m, Class<?> c) {
683                    if (c == Matrix.class) {
684                            return MathUtil.getMatrix(m);
685                    } else if (c == Object.class) {
686                            return m;
687                    } else if (c == Integer.TYPE) {
688                            return MathUtil.getInt(m);
689                    } else if (c == Double.TYPE) {
690                            return MathUtil.getDouble(m);
691                    } else if (c == Long.TYPE) {
692                            return MathUtil.getLong(m);
693                    } else if (c == Boolean.TYPE) {
694                            return MathUtil.getBoolean(m);
695                    } else if (c == String.class) {
696                            return StringUtil.convert(m);
697                    } else if (c == RegressionDataSet.class) {
698                            return m;
699                    }
700                    MatrixException e = new MatrixException("cannot convert to desired object type "
701                                    + c.getSimpleName());
702                    result = new Result(e);
703                    throw e;
704            }
705    
706            private Object getObject(String name) {
707                    Object o = module.getVariables().get(name);
708                    if (o != null) {
709                            return ((Variable) o).getMatrix();
710                    }
711                    o = module.getDataSets().get(name);
712                    if (o != null) {
713                            return o;
714                    }
715                    o = module.getAlgorithms().get(name);
716                    if (o != null) {
717                            return o;
718                    }
719                    o = module.getSamples().get(name);
720                    if (o != null) {
721                            return o;
722                    }
723                    o = module.getModules().get(name);
724                    if (o != null) {
725                            return o;
726                    }
727                    return o;
728            }
729    
730            private Object getObject(PFunction function) throws Exception {
731                    if (function instanceof AParameterFunction) {
732                            return executeFunction(((AParameterFunction) function).getName(),
733                                            ((AParameterFunction) function).getArgumentList());
734                    } else if (function instanceof AEmptyFunction) {
735                            return executeFunction(((AEmptyFunction) function).getName(), null);
736                    }
737                    MatrixException e = new MatrixException("Unknown function type: "
738                                    + function.getClass().getSimpleName());
739                    result = new Result(e);
740                    throw e;
741            }
742    
743            private Matrix getMatrix(PMatrix matrix) throws Exception {
744                    if (matrix instanceof AEmptyMatrix) {
745                            return MatrixFactory.emptyMatrix();
746                    } else if (matrix instanceof AValueMatrix) {
747                            return MatrixFactory.linkToValue(((AValueMatrix) matrix).getExpression());
748                    } else if (matrix instanceof ARowMatrix) {
749                            return getMatrix(((ARowMatrix) matrix).getRow());
750                    } else if (matrix instanceof AColumnMatrix) {
751                            return getMatrix(((AColumnMatrix) matrix).getColumn());
752                    } else if (matrix instanceof AArrayMatrix) {
753                            return getMatrix(((AArrayMatrix) matrix).getArray());
754                    }
755                    MatrixException e = new MatrixException("Unknown matrix type: "
756                                    + matrix.getClass().getSimpleName());
757                    result = new Result(e);
758                    throw e;
759            }
760    
761            private Object getSingleValue(PExpression expression) throws Exception {
762                    Matrix m = MathUtil.getMatrix(getObject(expression));
763                    if (m.isScalar()) {
764                            return m.getAsObject(0, 0);
765                    } else {
766                            return m.doubleValue();
767                    }
768            }
769    
770            private Object getValue(PLiteral literal) {
771                    if (literal instanceof AIntegerLiteral) {
772                            return Long.parseLong(literal.toString().trim());
773                    } else if (literal instanceof AFloatingPointLiteral) {
774                            String s = literal.toString().trim();
775                            if ("NaN".equalsIgnoreCase(s)) {
776                                    return Double.NaN;
777                            }
778                            if ("Inf".equalsIgnoreCase(s)) {
779                                    return Double.POSITIVE_INFINITY;
780                            }
781                            if ("-Inf".equalsIgnoreCase(s)) {
782                                    return Double.NEGATIVE_INFINITY;
783                            }
784                            return Double.parseDouble(s);
785                    } else if (literal instanceof ABooleanLiteral) {
786                            return Boolean.parseBoolean(literal.toString().trim());
787                    } else if (literal instanceof AStringLiteral) {
788                            String s = literal.toString().trim();
789                            return s.substring(1, s.length() - 1);
790                    }
791    
792                    MatrixException e = new MatrixException("Unknown literal type: "
793                                    + literal.getClass().getSimpleName());
794                    result = new Result(e);
795                    throw e;
796            }
797    
798            private String getLiteral(PExpression expr) {
799                    if (expr instanceof ALevel10Expression) {
800                            return getLiteral(((ALevel10Expression) expr).getLevel10());
801                    } else {
802                            return null;
803                    }
804            }
805    
806            private String getLiteral(PLevel10 expr) {
807                    if (expr instanceof ALevel9Level10) {
808                            return getLiteral(((ALevel9Level10) expr).getLevel9());
809                    } else {
810                            return null;
811                    }
812            }
813    
814            private String getLiteral(PLevel9 expr) {
815                    if (expr instanceof ALevel8Level9) {
816                            return getLiteral(((ALevel8Level9) expr).getLevel8());
817                    } else {
818                            return null;
819                    }
820            }
821    
822            private String getLiteral(PLevel8 expr) {
823                    if (expr instanceof ALevel7Level8) {
824                            return getLiteral(((ALevel7Level8) expr).getLevel7());
825                    } else {
826                            return null;
827                    }
828            }
829    
830            private String getLiteral(PLevel7 expr) {
831                    if (expr instanceof ALevel6Level7) {
832                            return getLiteral(((ALevel6Level7) expr).getLevel6());
833                    } else {
834                            return null;
835                    }
836            }
837    
838            private String getLiteral(PLevel6 expr) {
839                    if (expr instanceof ALevel5Level6) {
840                            return getLiteral(((ALevel5Level6) expr).getLevel5());
841                    } else {
842                            return null;
843                    }
844            }
845    
846            private String getLiteral(PLevel5 expr) {
847                    if (expr instanceof ALevel4Level5) {
848                            return getLiteral(((ALevel4Level5) expr).getLevel4());
849                    } else {
850                            return null;
851                    }
852            }
853    
854            private String getLiteral(PLevel4 expr) {
855                    if (expr instanceof ALevel3Level4) {
856                            return getLiteral(((ALevel3Level4) expr).getLevel3());
857                    } else {
858                            return null;
859                    }
860            }
861    
862            private String getLiteral(PLevel3 expr) {
863                    if (expr instanceof ALevel2Level3) {
864                            return getLiteral(((ALevel2Level3) expr).getLevel2());
865                    } else {
866                            return null;
867                    }
868            }
869    
870            private String getLiteral(PLevel2 expr) {
871                    if (expr instanceof ALevel1Level2) {
872                            return getLiteral(((ALevel1Level2) expr).getLevel1());
873                    } else {
874                            return null;
875                    }
876            }
877    
878            private String getLiteral(PLevel1 expr) {
879                    if (expr instanceof ALevel0Level1) {
880                            return getLiteral(((ALevel0Level1) expr).getLevel0());
881                    } else {
882                            return null;
883                    }
884            }
885    
886            private String getLiteral(PLevel0 expr) {
887                    if (expr instanceof ALiteralLevel0) {
888                            String s = expr.toString().trim();
889                            if ("true".equalsIgnoreCase(s)) {
890                                    return null;
891                            }
892                            if ("false".equalsIgnoreCase(s)) {
893                                    return null;
894                            }
895                            return s;
896                    } else if (expr instanceof AIdentifierLevel0) {
897                            String s = expr.toString().trim();
898                            if ("true".equalsIgnoreCase(s)) {
899                                    return null;
900                            }
901                            if ("false".equalsIgnoreCase(s)) {
902                                    return null;
903                            }
904                            return s;
905                    } else {
906                            return null;
907                    }
908            }
909    
910            @Override
911            public void outAStatement(AStatement node) {
912                    try {
913                            // handle already known objects
914                            String id = getLiteral(node.getExpression());
915                            if (id != null) {
916                                    Variable v = module.getVariables().get(id);
917                                    if (v != null) {
918                                            result = new Result(id, v.getMatrix());
919                                            return;
920                                    }
921                                    DataSet ds = module.getDataSets().get(id);
922                                    if (ds != null) {
923                                            result = new Result(id, ds);
924                                            return;
925                                    }
926                                    Algorithm a = module.getAlgorithms().get(id);
927                                    if (a != null) {
928                                            result = new Result(id, a);
929                                            return;
930                                    }
931                                    Sample s = module.getSamples().get(id);
932                                    if (s != null) {
933                                            result = new Result(id, s);
934                                            return;
935                                    }
936                                    Module m = module.getModules().get(id);
937                                    if (m != null) {
938                                            result = new Result(id, m);
939                                            return;
940                                    }
941                            }
942    
943                            // handle unknown objects or algorithms
944                            Object o = getObject(node.getExpression());
945    
946                            Variable v = module.getVariables().get(ANS);
947                            if (v == null) {
948                                    v = VariableFactory.labeledVariable(ANS);
949                                    module.getVariables().put(ANS, v);
950                            }
951                            v.addMatrix(MathUtil.getMatrix(o));
952    
953                            result = new Result(ANS, o);
954                            System.out.println(result);
955                    } catch (Exception e) {
956                            result = new Result(e);
957                            e.printStackTrace();
958                    }
959            }
960    
961    }