File: evaluateMath.java

package info (click to toggle)
libsbml 5.20.4%2Bdfsg-0.1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 116,352 kB
  • sloc: cpp: 466,192; xml: 357,499; ansic: 53,961; python: 12,540; makefile: 9,755; sh: 9,245; cs: 8,586; java: 8,151; perl: 6,133; ruby: 4,760; javascript: 1,605; php: 202; csh: 3
file content (593 lines) | stat: -rw-r--r-- 19,023 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
/**
 * @file    evaluateMath.java
 * @brief   Evaluates and outputs infix expressions
 * @author  Nicolas Rodriguez (translated from the libSBML C example)
 * @author  Rainer Machne (author of original libSBML C example)
 * @author  Michael Hucka
 *
 * <!--------------------------------------------------------------------------
 * This sample program is distributed under a different license than the rest
 * of libSBML.  This program uses the open-source MIT license, as follows:
 *
 * Copyright (c) 2013-2018 by the California Institute of Technology
 * (California, USA), the European Bioinformatics Institute (EMBL-EBI, UK)
 * and the University of Heidelberg (Germany), with support from the National
 * Institutes of Health (USA) under grant R01GM070923.  All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 * Neither the name of the California Institute of Technology (Caltech), nor
 * of the European Bioinformatics Institute (EMBL-EBI), nor of the University
 * of Heidelberg, nor the names of any contributors, may be used to endorse
 * or promote products derived from this software without specific prior
 * written permission.
 * ------------------------------------------------------------------------ -->
 */

import java.io.IOException;

import org.sbml.libsbml.ASTNode;
import org.sbml.libsbml.libsbml;
import org.sbml.libsbml.libsbmlConstants;


/**
 * This program asks the user to enter an infix formula, translates it to
 * an Abstract Syntax tree using the function:
 *
 *   ASTNode libsbml.parseFormula(String)
 *
 * evaluates the formula and returns the result.  See comments for double
 * evalAST(ASTNode n) for further information.
 */
public class evaluateMath
{
  public static void main (String[] args)
  {
    println( "This program evaluates infix formulas." );
    println( "Typing return triggers evaluation." );
    println( "\n" );


    long start, stop, size;

    int  i = 0;
    char c;

    String  mathStr = new String();
    ASTNode nodes;

    try
    {
      // Hit Enter to quit the loop
      while (i != 10)
      {
        // Read a character from keyboard
        i  = System.in.read();
        // 1 byte character is returned in int.
        // So cast to char
        c = (char) i;
        mathStr += c;
      }
    }
    catch (IOException ioe)
    {
      println( "IO error:" + ioe );
    }

    nodes = libsbml.parseFormula(mathStr);

    start = System.currentTimeMillis();
    double result = evalAST(nodes);
    stop  = System.currentTimeMillis();


    println("\n" + libsbml.formulaToString(nodes) + "\n= " + result + "\n");
    println("evaluation time: " + (stop - start) + " ms\n\n");
  }


  /**
   * The function evalAST(ASTNode) evaluates the formula of an Abstract
   * Syntax Tree by simple recursion and returns the result as a double
   * value.
   *
   * If variables (ASTNodeType_t AST_NAME) occur in the formula the user is
   * asked to provide a numerical value.  When evaluating ASTs within an
   * SBML document or simulating an SBML model this node type includes
   * parameters and variables of the model.  Parameters should be retrieved
   * from the SBML file, time and variables from current values of the
   * simulation.
   *
   * Not implemented:
   *
   *   - PIECEWISE, LAMBDA, and the SBML model specific functions DELAY and
   *     TIME and user-defined functions.
   *
   *   - Complex numbers and/or checking for domains of trigonometric and
   *     root functions.
   *
   *   - Checking for precision and rounding errors.
   *
   * The Nodetypes AST_TIME, AST_DELAY and AST_PIECEWISE default to 0.  The
   * SBML DELAY function and unknown functions (SBML user-defined
   * functions) use the value of the left child (first argument to
   * function) or 0 if the node has no children.
   */
  private static double evalAST (ASTNode n)
  {
    int    i;
    double result = 0;
    int    astNodeType;

    String msg;

    int       childnum = (int) n.getNumChildren();
    ASTNode[] child    = new ASTNode[childnum];


    for(i = 0; i < childnum; i++)
    {
      child[i] = n.getChild(i);
    }

    astNodeType = n.getType();

    switch (astNodeType)
    {
      case libsbmlConstants.AST_INTEGER: 
        result = (double) n.getInteger();
        break;

      case libsbmlConstants.AST_REAL:
        result = n.getReal();
        break;

      case libsbmlConstants.AST_REAL_E:
        result = n.getReal();
        break;

      case libsbmlConstants.AST_RATIONAL:
        result = n.getReal();
        break;


      case libsbmlConstants.AST_NAME:
        msg =
          "\n--------- MESSAGE FROM EVALUATION FUNCTION ----------\n\n" +
          "Please enter a number for the variable!\n" +
          "If you do not enter a valid number (empty or characters), the \n" +
          "evaluation will proceed with a current internal value and the \n" +
          "result will make no sense.\n" +
          n.getName() + " = ";

        println(msg);
        
        String l = new String();
        double var;

        try
        {
          int input = 0;
          while (input != 10)
          {
            // Read a character from keyboard
            input  = System.in.read();
            // 1 byte character is returned in int.
            // So cast to char
            l += (char) input;
          }

          var = Double.valueOf(l).doubleValue();
          println(n.getName() + " = " + var + "\n");
          result = var;
        }
        catch (IOException e)
        {
        }

        println("\n--------- END MESSAGE ----------\n\n");
        break;


      case libsbmlConstants.AST_FUNCTION_DELAY:
        msg =
          "\n--------- MESSAGE FROM EVALUATION FUNCTION ----------\n\n"      +
          "Delays can only be evaluated during a time series simulation.\n"  +
          "The value of the first child (ie. the first argument to the"      +
          "function)\nis used for this evaluation. If the function node has" +
          "no children the\nvalue defaults to 0.\n" +
          "\n--------- END MESSAGE ----------\n\n";

        println(msg);

        if (i > 0)
        {
          result = evalAST(child[0]);
        }
        else
        {
          result = 0.0;
        }
        break;

      case libsbmlConstants.AST_NAME_TIME:
        msg =
          "\n--------- MESSAGE FROM EVALUATION FUNCTION ----------\n\n"       +
          "The time can only be evaluated during a time series simulation.\n" +
          "The value of defaults to 0\n" +
          "\n--------- END MESSAGE ----------\n\n";
        println(msg);

        result = 0.0;
        break;


      case libsbmlConstants.AST_CONSTANT_E:
        /* exp(1) is used to adjust exponentiale to machine precision */
        result = Math.exp(1);
        break;

      case libsbmlConstants.AST_CONSTANT_FALSE:
        result = 0.0;
        break;

      case libsbmlConstants.AST_CONSTANT_PI:
        /* pi = 4 * atan 1  is used to adjust Pi to machine precision */
        result = 4 * Math.atan(1.);
        break;

      case libsbmlConstants.AST_CONSTANT_TRUE:
        result = 1.0;
        break;

      case libsbmlConstants.AST_PLUS:
        result = evalAST(child[0]) + evalAST(child[1]);
        break;


      case libsbmlConstants.AST_MINUS:
        if (childnum == 1)
        {
          result = - (evalAST(child[0]));
        }
        else
        {
          result = evalAST(child[0]) - evalAST(child[1]);
        }
        break;


      case libsbmlConstants.AST_TIMES:
        result = evalAST(child[0]) * evalAST(child[1]) ;
        break;

      case libsbmlConstants.AST_DIVIDE:
        result = evalAST(child[0]) / evalAST(child[1]);
        break;

      case libsbmlConstants.AST_POWER:
        result = Math.pow(evalAST(child[0]),evalAST(child[1]));
        break;

      case libsbmlConstants.AST_LAMBDA:
        msg =
          "\n--------- MESSAGE FROM EVALUATION FUNCTION ----------\n\n" +
          "This function is not implemented yet.\n"                     +
          "The value defaults to 0.\n"                                  +
          "\n--------- END MESSAGE ----------\n\n";
        println(msg);

        result = 0.0;
        break;

      case libsbmlConstants.AST_FUNCTION:
        msg =
          "\n--------- MESSAGE FROM EVALUATION FUNCTION ----------\n\n"        +
          "This function is not known.\n"                                      +
          "Within an SBML document new functions can be defined by the user\n" +
          "or application. The value of the first child (ie. the first\n"      +
          "argument to the function) is used for this evaluation. If the\n"    +
          "function node has no children the value defaults to 0.\n"           +
          "\n--------- END MESSAGE ----------\n\n";
        println(msg);

        if (childnum > 0)
        {
          result = evalAST(child[0]);
        }
        else
        {
          result = 0.0;
        }
        break;

        case libsbmlConstants.AST_FUNCTION_ABS:
          result = Math.abs(evalAST(child[0]));
          break;

        case libsbmlConstants.AST_FUNCTION_ARCCOS:
          result = Math.acos(evalAST(child[0]));
          break;

        case libsbmlConstants.AST_FUNCTION_ARCCOSH:
          result = Math.acos(evalAST(child[0])); // TODO : fix to have acosh
          break;

        case libsbmlConstants.AST_FUNCTION_ARCCOT:
          /* arccot x =  arctan (1 / x) */
          result = Math.atan(1. / evalAST(child[0]));
          break;

        case libsbmlConstants.AST_FUNCTION_ARCCOTH:
          /* arccoth x = 1/2 * ln((x+1)/(x-1)) */
          result = ((1. / 2.) *
                    Math.log((evalAST(child[0]) + 1.) /
                             (evalAST(child[0]) - 1.) ));
          break;

        case libsbmlConstants.AST_FUNCTION_ARCCSC:
          /* arccsc(x) = Arctan(1 / sqrt((x - 1)(x + 1))) */
          result = Math.atan(1. / Math.sqrt((evalAST(child[0]) - 1.) *
                                            (evalAST(child[0]) + 1.) ));
          break;

        case libsbmlConstants.AST_FUNCTION_ARCCSCH:
          /* arccsch(x) = ln((1 + sqrt(1 + x^2)) / x) */
          result = Math.log((1. +
                             Math.pow(1 + Math.pow(evalAST(child[0]), 2), 2))
                            / evalAST(child[0]));
          break;

      case libsbmlConstants.AST_FUNCTION_ARCSEC:
        /* arcsec(x) = arctan(sqrt((x - 1)(x + 1))) */
        result = Math.atan(Math.sqrt((evalAST(child[0]) - 1.) *
                                     (evalAST(child[0]) + 1.) ));
        break;

      case libsbmlConstants.AST_FUNCTION_ARCSECH:
        /* arcsech(x) = ln((1 + sqrt(1 - x^2)) / x) */
        result = Math.log((1. + Math.pow(1 -
                                         Math.pow(evalAST(child[0]), 2), 0.5))
                          / evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_ARCSIN:
        result = Math.asin(evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_ARCSINH:
        result = Math.asin(evalAST(child[0])); // TODO : fix to have asinh
        break;

      case libsbmlConstants.AST_FUNCTION_ARCTAN:
        result = Math.atan(evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_ARCTANH:
        result = Math.atan(evalAST(child[0])); // TODO : fix to have atanh
        break;

      case libsbmlConstants.AST_FUNCTION_CEILING:
        result = Math.ceil(evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_COS:
        result = Math.cos(evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_COSH:
        result = Math.cosh(evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_COT:
        /* cot x = 1 / tan x */
        result = 1. / Math.tan(evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_COTH:
        /* coth x = cosh x / sinh x */
        result = Math.cosh(evalAST(child[0])) / Math.sinh(evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_CSC:
        /* csc x = 1 / sin x */
        result = (1. / Math.sin(evalAST(child[0])));
        break;

      case libsbmlConstants.AST_FUNCTION_CSCH:
        /* csch x = 1 / cosh x  */
        result = (1. / Math.cosh(evalAST(child[0])));
        break;

      case libsbmlConstants.AST_FUNCTION_EXP:
        result = Math.exp(evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_FACTORIAL:
        msg =
          "\n--------- MESSAGE FROM EVALUATION FUNCTION ----------\n\n"    +
          "The factorial is only implemented for integer values. If a\n"   +
          "floating point number is passed, the floor value is used for\n" +
          "calculation!\n" +
          "\n--------- END MESSAGE ----------\n\n";
        println(msg);

        double dbl = Math.floor(evalAST(child[0]));
        for(result = 1; dbl > 1; --dbl)
        {
          result *= i;
        }
        break;

      case libsbmlConstants.AST_FUNCTION_FLOOR:
        result = Math.floor(evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_LN:
        result = Math.log(evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_LOG:
        result = Math.log10(evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_PIECEWISE:
        msg =
          "\n--------- MESSAGE FROM EVALUATION FUNCTION ----------\n\n" +
          "This function is not implemented yet.\n" +
          "The value defaults to 0.\n"              +
          "\n--------- END MESSAGE ----------\n\n";
        println(msg);

        result = 0.0;
        break;

      case libsbmlConstants.AST_FUNCTION_POWER:
        result = Math.pow(evalAST(child[0]), evalAST(child[1]));
        break;

      case libsbmlConstants.AST_FUNCTION_ROOT:
        result = Math.pow(evalAST(child[1]), 1. / evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_SEC:
        /* sec x = 1 / cos x */
        result = 1. / Math.cos(evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_SECH:
        /* sech x = 1 / sinh x */
        result = 1. / Math.sinh(evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_SIN:
        result = Math.sin(evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_SINH:
        result = Math.sinh(evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_TAN:
        result = Math.tan(evalAST(child[0]));
        break;

      case libsbmlConstants.AST_FUNCTION_TANH:
        result = Math.tanh(evalAST(child[0]));
        break;
/*
      case libsbmlConstants.AST_LOGICAL_AND:
        result = (double) (evalAST(child[0]) & evalAST(child[1]));
        break;

      case libsbmlConstants.AST_LOGICAL_NOT:
        result = (double) (!(evalAST(child[0])));
        break;

      case libsbmlConstants.AST_LOGICAL_OR:
        result = (double) ((evalAST(child[0])) || (evalAST(child[1])));
        break;

      case libsbmlConstants.AST_LOGICAL_XOR:
        result = (double) ((!(evalAST(child[0])) && (evalAST(child[1])))
                           || ((evalAST(child[0])) &&  !(evalAST(child[1]))));
        break;

      case libsbmlConstants.AST_RELATIONAL_EQ:
        result = (double) ((evalAST(child[0])) == (evalAST(child[1])));
        break;

      case libsbmlConstants.AST_RELATIONAL_GEQ:
        result = (double) ((evalAST(child[0])) >= (evalAST(child[1])));
        break;

      case libsbmlConstants.AST_RELATIONAL_GT:
        result = (double) ((evalAST(child[0])) > (evalAST(child[1])));
        break;

      case libsbmlConstants.AST_RELATIONAL_LEQ:
        result = (double) ((evalAST(child[0])) <= (evalAST(child[1])));
        break;

      case libsbmlConstants.AST_RELATIONAL_LT:
        result = (double) ((evalAST(child[0])) < (evalAST(child[1])));
        break;
*/
      default:
        result = 0;
        break;
    }

    return result;
  }
    

  static void println (String msg)
  {
    System.out.println(msg);
  }


  /**
   * Loads the SWIG-generated libSBML Java module when this class is
   * loaded, or reports a sensible diagnostic message about why it failed.
   */
  static
  {
    try
    {
      System.loadLibrary("sbmlj");
      // For extra safety, check that the jar file is in the classpath.
      Class.forName("org.sbml.libsbml.libsbml");
    }
    catch (UnsatisfiedLinkError e)
    {
      System.err.println("Error encountered while attempting to load libSBML:");
      System.err.println("Please check the value of your "
                         + (System.getProperty("os.name").startsWith("Mac OS")
                            ? "DYLD_LIBRARY_PATH" : "LD_LIBRARY_PATH") +
                         " environment variable and/or your" +
                         " 'java.library.path' system property (depending on" +
                         " which one you are using) to make sure it list the" +
                         " directories needed to find the " +
                         System.mapLibraryName("sbmlj") + " library file and" +
                         " libraries it depends upon (e.g., the XML parser).");
      System.exit(1);
    }
    catch (ClassNotFoundException e)
    {
      System.err.println("Error: unable to load the file 'libsbmlj.jar'." +
                         " It is likely that your -classpath command line " +
                         " setting or your CLASSPATH environment variable " +
                         " do not include the file 'libsbmlj.jar'.");
      e.printStackTrace();

      System.exit(1);
    }
    catch (SecurityException e)
    {
      System.err.println("Error encountered while attempting to load libSBML:");
      e.printStackTrace();
      System.err.println("Could not load the libSBML library files due to a"+
                         " security exception.\n");
      System.exit(1);
    }
  }
}