{"id":4,"date":"2005-11-17T08:25:58","date_gmt":"2005-11-17T16:25:58","guid":{"rendered":"http:\/\/www.viscerallogic.com\/programming\/blog\/2006\/11\/17\/variables-and-graphical-plots-in-java\/"},"modified":"2006-12-29T11:03:08","modified_gmt":"2006-12-29T19:03:08","slug":"variables-and-graphical-plots-in-java","status":"publish","type":"post","link":"https:\/\/www.viscerallogic.com\/programming\/blog\/variables-and-graphical-plots-in-java\/","title":{"rendered":"Variables and Graphical Plots in Java"},"content":{"rendered":"<p>This tutorial builds on the <a href=\"http:\/\/www.viscerallogic.com\/programming\/blog\/2005\/11\/12\/numerical-expression-solver-in-java\/\">Numerical Expression Solver<\/a> tutorial, adding textual variables such as &#8220;e&#8221; or &#8220;pi&#8221;, and custom ones. Then you will create an applet that takes advantage of this new functionality by creating a graphical representation of an arbitrary expression at each point in space. <!--more-->This applet is shown below.<\/p>\n<p>\n<applet codebase=\"http:\/\/www.viscerallogic.com\/programming\/expression2\" code=\"ExpressionApplet.class\" width=\"200\" height=\"200\"><br \/>\n<\/applet><\/p>\n<p>\nStarting with the <a href=\"http:\/\/www.viscerallogic.com\/programming\/expression1\/Expression.java\">Expression.java<\/a> file you created last time, add the following variable:<\/p>\n<blockquote>\n<pre><code>\r\n\t\/*\r\n\t* Used for getting variables\r\n\t*\/\r\n\tVariable get;\r\n<\/code><\/pre>\n<\/blockquote>\n<p>\nThis is an object of a type we haven&#8217;t defined yet, which will serve to return numerical values for variables.<\/p>\n<p>\nInsert the following <code>variable()<\/code> function:<\/p>\n<blockquote>\n<pre><code>\r\n\t\/*\r\n\t* Evaluates variable terms.\r\n\t*\/\r\n\tdouble variable(){\r\n\t\tdouble a;\r\n\t\tStringBuffer buf = new StringBuffer();\r\n\t\twhile( s.length() > 0 && Character.isLetter( s.charAt( 0 ) ) ){\r\n\t\t\tbuf.append( s.charAt( 0 ) );\r\n\t\t\ts = s.substring( 1 );\r\n\t\t}\r\n\t\tString v = buf.toString();\r\n\t\tif( v.compareTo( \"e\" ) == 0 ){\r\n\t\t\ta = Math.E;\r\n\t\t} else if( v.compareTo( \"pi\" ) == 0 ){\r\n\t\t\ta = Math.PI;\r\n\t\t} else {\r\n\t\t\ta = get.variable( v );\r\n\t\t}\r\n\t\treturn a;\r\n\t}\r\n<\/code><\/pre>\n<\/blockquote>\n<p>\nFor our purposes, a &#8220;variable&#8221; is defined as any contiguous sequence of alphabetic characters. This function firsts collects all the contiguous letters, and then checks to see if it recognizes them as one of its built-in constants, &#8220;e&#8221; or &#8220;pi&#8221;. If not, it makes a call to the <i>get<\/i> object, which hopefully will recognize the variable and return the appropriate value.<\/p>\n<p>\nThis function is not being called yet, so we need to modify the <code>term()<\/code> function as follows:<\/p>\n<blockquote>\n<pre><code>\r\n\tdouble term(){\r\n\t\tdouble ans = 0;\r\n\t\tStringBuffer temp = new StringBuffer();\r\n\r\n\t\tif( Character.isLetter( s.charAt( 0 ) ) ){\t\/\/ new lines\r\n\t\t\treturn variable();\t\t\t\/\/ ...\r\n\t\t}\t\t\t\t\t\t\/\/ end new lines\r\n\r\n\t\twhile( s.length() > 0 && Character.isDigit( s.charAt( 0 ) ) ){\r\n\t\t\ttemp.append(Integer.parseInt( \"\" + s.charAt( 0 ) ));\r\n\t\t\ts = s.substring( 1 );\r\n\t\t}\r\n\t\r\n\t\t...\r\n\t\r\n\t}\r\n<\/code><\/pre>\n<\/blockquote>\n<p>\nThese newly inserted lines check to see whether the term is a number or a variable. If it starts with a letter, we assume it is a variable and deal with it by calling <code>variable()<\/code>. Otherwise, we continue as we did before, assuming it is a number.<\/p>\n<p>\nNow we need to modify the constructor <code>Expression()<\/code> by changing the first couple lines:<\/p>\n<blockquote>\n<pre><code>\r\n\tpublic Expression( String s, Variable v ){\r\n\t\tget = v;\r\n\t\t\/\/ remove white space, assume only spaces or tabs\r\n\t\tStringBuffer b = new StringBuffer();\r\n\t\t\r\n\t\t...\r\n\r\n\t}\r\n<\/code><\/pre>\n<\/blockquote>\n<p>\nWe changed the declaration to accept a <i>Variable<\/i> object as an additional argument, and then assigned it to our variable <i>get<\/i>. If you know that your expression will contain know variables, you may pass <i>null<\/i> as the second argument.<\/p>\n<p>\nFinally, in order to run this from the command-line, you will have to change the <code>main()<\/code> function to pass <i>null<\/i> as a second argument to the <code>Expression()<\/code> constructor:<\/p>\n<blockquote>\n<pre><code>\r\n\tpublic static void main( String[] args ){\r\n\t\tExpression e = new Expression( args[0], null );\r\n\t\tSystem.out.println( e + \" = \" + e.evaluate() );\r\n\t}\r\n<\/code><\/pre>\n<\/blockquote>\n<p>\nThese are all the changes that we need to make to <i>Expression.java<\/i>. However, you can&#8217;t compile it until we create the interface declaration <i>Variable.java<\/i>, given below in its entirety:<\/p>\n<blockquote>\n<pre><code>\r\npublic interface Variable{\r\n\t\/*\r\n\t* Returns the value of given variable.\r\n\t*\/\r\n\tpublic double variable( String s );\r\n}\r\n<\/code><\/pre>\n<\/blockquote>\n<p>\nThis interface allows any object to respond to the <code>variable()<\/code> function called by an <i>Expression<\/i> instance when it encounters an unknown variable.<\/p>\n<p>\nYou can now compile and run <i>Expression.java<\/i> as before. You can now enter &#8220;e&#8221; for the number 2.718&#8230; or &#8220;pi&#8221; for 3.141&#8230; These two &#8220;variables&#8221; function as numbers now.<\/p>\n<p>\nNow let&#8217;s create the graphical plotter that uses this new functionality. Create the file <i>ExpressionApplet.java<\/i> as follows:<\/p>\n<blockquote>\n<pre><code>\r\nimport java.awt.*;\r\nimport java.awt.event.*;\r\nimport java.awt.image.*;\r\n\r\npublic class ExpressionApplet extends java.applet.Applet implements Variable{\r\n\tImage img;\t\t\t\t\/\/ image buffer used to draw plot\r\n\tExpression exp;\t\t\t\/\/ the Expression we wish to draw\r\n\tTextField input;\t\t\/\/ the user input field for the Expression\r\n\tdouble x, y;\t\t\t\/\/ the currently evaluated variables\r\n\tdouble left = -Math.PI, right = Math.PI, top = Math.PI, bottom = - Math.PI;\r\n\t\t\t\t\t\t\t\/\/ our bounds\r\n\t\r\n\t\/*\r\n\t* Set up the interface, create an initial Expression,\r\n\t* and draw it.\r\n\t*\/\r\n\tpublic void init(){\r\n\t\tinput = new TextField(\"x^2+y^2\",20);\r\n\t\tButton b = new Button( \"Draw\" );\r\n\t\tfinal Variable v = this;\r\n\t\tinput.addActionListener( new ActionListener(){\r\n\t\t\t\tpublic void actionPerformed( ActionEvent e ){\r\n\t\t\t\t\texp = new Expression( input.getText(), v );\r\n\t\t\t\t\timg = null;\r\n\t\t\t\t\trepaint();\r\n\t\t\t\t}\r\n\t\t\t} );\r\n\t\tb.addActionListener( new ActionListener(){\r\n\t\t\t\tpublic void actionPerformed( ActionEvent e ){\r\n\t\t\t\t\texp = new Expression( input.getText(), v );\r\n\t\t\t\t\timg = null;\r\n\t\t\t\t\trepaint();\r\n\t\t\t\t}\r\n\t\t\t} );\r\n\t\tadd( input );\r\n\t\tadd( b );\r\n\t\texp = new Expression(\"x^2+y^2\", this);\r\n\t\trepaint();\r\n\t}\r\n}\r\n<\/code><\/pre>\n<\/blockquote>\n<p>\nAs you can see, we have a good number of instance variables. The <code>init()<\/code> function takes care of setting things up for us, including creating an initial <i>Expression<\/i>, and calling <code>repaint()<\/code>, which draws the results of evaluating the <i>Expression<\/i>.<\/p>\n<p>\nIf you looked carefully at the above code, you would have noticed that the string passed to the <i>Expression<\/i> to evaluate includes &#8220;x&#8221; and &#8220;y&#8221;, which it can&#8217;t evaluate. This is where the <i>Variable<\/i> interface comes into play. <i>Expression<\/i> recognizes that &#8220;x&#8221; and &#8220;y&#8221; are variables, but doesn&#8217;t know what they are, so it calls its <code>get.variable()<\/code> function to evaluate them. As you might have guessed since the declaration of <i>ExpressionApplet<\/i> says that it implements the <i>Variable<\/i> interface, and in fact the applet is passed to the <i>Expression<\/i> constructor, we will implement that function here:<\/p>\n<blockquote>\n<pre><code>\r\n\t\/*\r\n\t* Looks for variables we define, and returns them\r\n\t* appropriately. Otherwise, returns NaN.\r\n\t*\/\r\n\tpublic double variable( String s ){\r\n\t\tif( s.compareTo( \"x\" ) == 0 || s.compareTo( \"X\" ) == 0 )\r\n\t\t\treturn x;\r\n\t\tif( s.compareTo( \"y\" ) == 0 || s.compareTo( \"Y\" ) == 0 )\r\n\t\t\treturn y;\r\n\t\treturn Math.log(-1);\r\n\t}\r\n<\/code><\/pre>\n<\/blockquote>\n<p>\nThis function is what makes the graphical element possible. In the <code>paint()<\/code> function which follows, we will go through every pixel, setting the instance variables <i>x<\/i> and <i>y<\/i> appropriately, and then evaluating the <i>Expression<\/i>. If it contains &#8220;x&#8221; or &#8220;y&#8221;, our <code>variable()<\/code> function will be called.<\/p>\n<p>\nNow add the <code>paint()<\/code> function, which does the actual evaluation and drawing of the <i>Expression<\/i>:<\/p>\n<blockquote>\n<pre><code>\r\n\t\/*\r\n\t* Evaluate and draw the Expression at every pixel.\r\n\t*\/\r\n\tpublic void paint( Graphics g ){\r\n\t\tdouble min = 0, max = 0;\r\n\t\tif( img != null ){\r\n\t\t\tg.drawImage( img, 0, 0, this );\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tfor( int y = 0; y < getSize().height; y++ ){\r\n\t\t\tfor( int x = 0; x < getSize().width; x++ ){\r\n\t\t\t\tmapToVirtual( x, y );\r\n\t\t\t\tdouble a = exp.evaluate();\r\n\t\t\t\tif( a > max )\r\n\t\t\t\t\tmax = a;\r\n\t\t\t\telse if( a < min )\r\n\t\t\t\t\tmin = a;\r\n\t\t\t}\r\n\t\t}\r\n\t\tint pix[] = new int[ getSize().width * getSize().height ];\r\n\t\tint index = 0;\r\n\t\tfor( int y = 0; y < getSize().height; y++ ){\r\n\t\t\tfor( int x = 0; x < getSize().width; x++ ){\r\n\t\t\t\tmapToVirtual( x, y );\r\n\t\t\t\tpix[ index++ ] = Color.getHSBColor( (float)(exp.evaluate()\/(max-min) - min\/(max-min)), 1, 1 ).getRGB();\r\n\t\t\t}\r\n\t\t}\r\n\t\timg  = createImage( new MemoryImageSource( getSize().width, getSize().height, pix, 0, getSize().width ) );\r\n\t\tg.drawImage( img, 0, 0, this );\r\n\t}\r\n<\/code><\/pre>\n<\/blockquote>\n<p>\nThe first thing to notice is that we check to see if the <i>img<\/i> variable is already defined before we do anything else. If it is defined, then <code>paint()<\/code> is being called simply because it was obscured, and now needs to be refreshed. If we didn't test for this case, we would have to re-evaluate the expression at every pixel every time something happened to require the applet to refresh. The reason this works is that when the user enters a new expression, we set the <i>img<\/i> variable to <i>null<\/i>.<\/p>\n<p>\nNext we run through every pixel in our applet, calling <code>mapToVirtual()<\/code>, which sets the instance variables <i>x<\/i> and <i>y<\/i> to the appropriate values to be returned to the <i>Expression<\/i>, since most of the time the pixel index won't correspond to the coordinate we want it to. We then evaluate the expression and find the minimum and maximum values.<\/p>\n<p>\nOnce we have done this, we create an array of integers to hold our pixel color information, and reiterate through the pixels, this time setting them to colors. We have also scaled them to values between 0 and 1 because that is what the function <code>Color.getHSBColor()<\/code> needs. Once we have filled the pixel array, we create a <i>MemoryImageSource<\/i> with it, and draw the image. The instance variable <i>img<\/i> is now non-null, so if the applet needs to refresh, it won't have to go through all that calculation again.<\/p>\n<p><p>\nNow we just need the function <code>mapToVirtual()<\/code>:<\/p>\n<blockquote>\n<pre><code>\r\n\t\/*\r\n\t* Map a pixel coordinate to a virtual coordinate.\r\n\t*\/\r\n\tpublic void mapToVirtual( int x, int y ){\r\n\t\tthis.x = ( (right-left)\/getSize().width )*x + left;\r\n\t\tthis.y = ( (bottom-top)\/getSize().height )*y + top;\r\n\t}\r\n<\/code><\/pre>\n<\/blockquote>\n<p>\nThis function simply maps pixels linearly from their actual coordinates to assumed coordinates, according to the <i>right, left, top, bottom<\/i> variables declared at the beginning of the class. It sets the instance variables <i>x, y<\/i> to the virtual coordinates, as required for the <code>variable()<\/code> function.<\/p>\n<p>\nYou can now compile <i>ExpressionApplet.java<\/i> and include it in an HTML page as I have done here. If you wish, you may add text fields to set the virtual boundaries, so that you can move around and zoom in and out, instead of being always confined to one view, as here.<\/p>\n<p>\nHere is the finished file <a href=\"http:\/\/www.viscerallogic.com\/programming\/expression2\/Expression.java\">Expression.java<\/a>.<br \/>\nHere is the finished file <a href=\"http:\/\/www.viscerallogic.com\/programming\/expression2\/Variable.java\">Variable.java<\/a>.<br \/>\nHere is the finished file <a href=\"http:\/\/www.viscerallogic.com\/programming\/expression2\/ExpressionApplet.java\">ExpressionApplet.java<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This tutorial builds on the Numerical Expression Solver tutorial, adding textual variables such as &#8220;e&#8221; or &#8220;pi&#8221;, and custom ones. Then you will create an applet that takes advantage of this new functionality by creating a graphical representation of an arbitrary expression at each point in space.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[4,2],"tags":[],"jetpack_featured_media_url":"","jetpack_publicize_connections":[],"jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p9npkn-4","jetpack_likes_enabled":true,"jetpack-related-posts":[{"id":3,"url":"https:\/\/www.viscerallogic.com\/programming\/blog\/numerical-expression-solver-in-java\/","url_meta":{"origin":4,"position":0},"title":"Numerical Expression Solver in Java","date":"November 12, 2005","format":false,"excerpt":"This tutorial will show you how to write a Java program that takes a string input such as \"3 + 4^2*7.5E-1*sin(22)\" and convert it into a numerical answer, 2.893784 in this case, which you can use for whatever purpose you like. This Java Applet utilizes the Expression class that you\u2026","rel":"","context":"In &quot;Java&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":90,"url":"https:\/\/www.viscerallogic.com\/programming\/blog\/basic-interpreter-part-iv\/","url_meta":{"origin":4,"position":1},"title":"BASIC Interpreter, Part IV","date":"September 7, 2018","format":false,"excerpt":"This is a continuation of Part III. This time we will add some mathematical operators, the ability to save and load programs, and support numerical variables. To enable mathematical operations, we will create a subclass of DoubleExpression that takes two DoubleExpressions as inputs, as well as a character code signifying\u2026","rel":"","context":"In &quot;BASIC&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":149,"url":"https:\/\/www.viscerallogic.com\/programming\/blog\/basic-interpreter-part-vii\/","url_meta":{"origin":4,"position":2},"title":"Basic Interpreter, Part VII","date":"September 7, 2018","format":false,"excerpt":"This is a continuation of Part VI. This time, we will be adding the FOR-NEXT loop and unary negation. The FOR-NEXT loop takes a couple forms: FOR <VAR> = <START> TO <STOP> ... NEXT <VAR> or FOR <VAR> = <START> TO <STOP> STEP <STEP> ... NEXT <VAR> In the former\u2026","rel":"","context":"In &quot;BASIC&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":131,"url":"https:\/\/www.viscerallogic.com\/programming\/blog\/basic-interpreter-part-vi\/","url_meta":{"origin":4,"position":3},"title":"BASIC Interpreter, Part VI","date":"September 7, 2018","format":false,"excerpt":"This is a continuation of Part V. In the previous section, we added support for the GOTO statement. Since we don't yet have any control logic, that is not very useful, but it does lay the infrastructure for one of the features we will add this time: IF-THEN. We will\u2026","rel":"","context":"In &quot;BASIC&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":5,"url":"https:\/\/www.viscerallogic.com\/programming\/blog\/guitar-chords-to-midi-in-objective-c\/","url_meta":{"origin":4,"position":4},"title":"Guitar Chords to MIDI in Objective-C","date":"December 3, 2005","format":false,"excerpt":"This tutorial will show you how to write a program that creates MIDI files of guitar chords by processing text files. Although I wrote this in Objective-C and the GUI is built using Cocoa, the MIDI algorithms could easily be applied to another language or platform. Essentially, this program scans\u2026","rel":"","context":"In &quot;Languages&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":72,"url":"https:\/\/www.viscerallogic.com\/programming\/blog\/basic-interpeter-part-iii\/","url_meta":{"origin":4,"position":5},"title":"BASIC Interpeter, Part III","date":"September 7, 2018","format":false,"excerpt":"This is a continuation of Part II. In this part, we will add support for numerical as well as string expressions, support multiple expression in a PRINT statement, and add functionality for deleting program lines. Let's start with the Basic class header file, basic.h. All we need to do here\u2026","rel":"","context":"In &quot;BASIC&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/www.viscerallogic.com\/programming\/blog\/wp-json\/wp\/v2\/posts\/4"}],"collection":[{"href":"https:\/\/www.viscerallogic.com\/programming\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.viscerallogic.com\/programming\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.viscerallogic.com\/programming\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.viscerallogic.com\/programming\/blog\/wp-json\/wp\/v2\/comments?post=4"}],"version-history":[{"count":0,"href":"https:\/\/www.viscerallogic.com\/programming\/blog\/wp-json\/wp\/v2\/posts\/4\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.viscerallogic.com\/programming\/blog\/wp-json\/wp\/v2\/media?parent=4"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.viscerallogic.com\/programming\/blog\/wp-json\/wp\/v2\/categories?post=4"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.viscerallogic.com\/programming\/blog\/wp-json\/wp\/v2\/tags?post=4"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}