12.6 webMathematica

 < Day Day Up > 



12.6 webMathematica

webMathematica is a Java-based application that provides interactive access to Mathematica computations over the Web. The underlying technology behind webMathematica is called Mathematica Server Pages (MSP), which is an application of Java servlet technology. Servlets are Java programs that run on a Web server, either directly or through a separate plug-in program called a servlet container. The details of installing and configuring webMathematica on a server can be somewhat complicated. However, once the initial installation is done, it is relatively easy to write Web pages that can interact with the server to produce live mathematical content.

The basic idea is that you can insert Mathematica commands into a standard HTML document in the form of special Mathlet tags. When a Web page enhanced in this way is submitted to a suitably configured Web server, each Mathlet tag is interpreted and its contents evaluated by a copy of Mathematica running on the server. The results of the evaluation are then inserted into the HTML document, replacing the original Mathlet tag. The new Web page is then returned back to the client and displayed in the browser.

webMathematica thus provides a simple way to integrate Mathematica input and output into a standard Web page. The Web server can run multiple Mathematica sessions simultaneously and can manage multiple requests, queuing and assigning evaluations as a new session becomes available. Users can purchase a license for any desired number of sessions, depending on the level of demand expected on the Web site. The configuration is scalable, and you can easily modify it for high levels of usage by increasing the number of Mathematica sessions available.

HTML documents enhanced by the addition of Mathlet tags are called MSP scripts. They must have the file extension .msp. A typical Mathlet tag has the following structure:

    <% Mathlet expr %> 

Here, expr can be any command or sequence of commands that is valid as input to Mathematica. In addition to ordinary Mathematica commands, Mathlet tags can contain a small set of commands, with the prefix MSP, that are defined exclusively for use in MSP scripts. These handle various details of the interaction between the Web page and Mathematica. Let's see look at a few examples of MSP scripts to illustrate how such pages work.

Integrating a Function

Example 12.11 shows a simple MSP script that sets up a Web page for calculating integrals. The page includes a text field and a button. A user can enter a function of one variable in the text field, and then click the "Integrate" button to see the result in the same Web page (Figure 12.16). The function must be entered using Mathematica's input syntax, which means that all function names must be capitalized and arguments must be enclosed in square brackets, as in Sqrt[x], Sin[x], or Log[x, 2].

Example 12.11: An HTML document for calculating the integral of a function using webMathematica.

start example
    <html>    <head><title>Integration</title></head>    <body bgcolor="white" >     <h1>Integrate a Function</h1>     <form method="post">      <p>Enter a function of one variable:     <input type="text" name="fn" align="left"      size="24" %>">     </p>    <p>      <input type="submit" name="inputButton"       value="Integrate"> </p>      <p><%Mathlet MSPBlock[{$$fn},       MSPFormat[Integrate[$$fn, x],TraditionalForm]] %>    </p>      </form>     </body>    </html> 
end example

click to expand
Figure 12.16: A Web page for calculating integrals using Mathematica.

This Web page contains two controls, a text field and a button, each represented by its own input element. The input elements are enclosed in a form element that has the attribute method="post". This attribute determines how the server processes the contents of the form.

The page also contains a single Mathlet tag. This tag contains the following command that will be passed to Mathematica for evaluation when the form is submitted:

    MSPBlock[{$$fn},       MSPFormat[Integrate[$$fn, x], TraditionalForm]] 

Here $$fn represents the value of the input element with the attribute name="fn". All variables that are to be sent to the Mathematica session must be prefaced with a $$ sign. The MSPBlock function checks the value of its first argument, namely $$fn. If this variable has a valid value-that is, if the user has entered a function in the text box-then the command given in the second argument is executed. Otherwise, MSPBlock returns a null string, which does not lead to any visible output in the Web page. The MSPBlock command is thus a way of ensuring that the evaluation proceeds only when a valid input is available. Otherwise, Mathematica will generate an error message that will be displayed in the Web page.

The second function in the Mathlet tag is MSPFormat, which formats the result obtained after evaluating its first argument and displays it in the Web page. By default, the result is displayed in StandardForm, which is a two-dimensional output format used by Mathematica for displaying mathematical expressions. You can specify a different display format by specifying the format as the second argument of MSPFormat. For example, to display an expression in traditional mathematical notation, you would use the command MSPFormat[expr, TraditionalForm]. See Section 11.2 for more information about the different display forms in Mathematica.

When the user specifies a function in the text box and clicks the button, the contents of the text box are assigned to the variable $$fn and submitted to the server. Mathematica then evaluates the command Integrate[$$fn, x]. The result of the evaluation replaces the Mathlet tag in the original Web page. The result is displayed in the form of a GIF image that is stored in the browser's cache, and a link to the image is automatically inserted into the Web page. The MSPFormat function automatically handles these steps.

Plotting a Function

Example 12.12 shows an MSP for plotting functions. A user can enter a function along with a range, and then click a button to see a plot of the function over the specified range (Figure 12.17).

Example 12.12: An HTML document for plotting a function using webMathematica.

start example
    <html>      <head><title>Plot</title></head>      <body bgcolor="white" >        <h1>Plot a Function</h1>          <form method="post">            <p>Enter a function of one variable:            <input type="text" name="f" size="20" value=            "<%Mathlet MSPValue[ $$f, "Sin[x^2]"] %>"> </p>            <p>Enter the start of the range:            <input type="text" name="x1" size="10" value=            "<%Mathlet MSPValue[ $$x1, "0"] %>"> </p>            <p> Enter the end of the range:            <input type="text" name="x2" size="10" value=            "<%Mathlet MSPValue[ $$x2, "5"] %>"> </p>            <p><input type="submit" name="inputButton"             value="Plot"></p>            <%Mathlet MSPBlock[ {$$f, $$x1, $$x2},             MSPShow[ Plot[$$f, {x,$$x1,$$x2}]]] %>        </form>      </body>    </html> 
end example

click to expand
Figure 12.17: A Web page for plotting functions using Mathematica.

This page is a straightforward generalization of the page shown in Example 12.11. It contains a form element that contains four different controls: three text boxes and one button. Notice that each text box has its value attribute set to a Mathlet tag that contains the command MSPValue[$$name, value]. This command displays the variable contained in the first argument if that variable has been assigned a value. Otherwise, it displays the second argument. Specifying a second argument is thus a way to include a default value in the text box when the Web page is first displayed. When the page is first loaded, a default value of the function as well as the starting and ending values of the range are displayed in the corresponding text boxes.

The page also contains a fourth Mathlet tag, which encloses the command for generating the plot, as shown here:

    MSPBlock[{$$f, $$x1, $$x2},     MSPShow[Plot[$$f, {x, $$x1, $$x2}] 

The MSPBlock command, as in Example 12.11, first checks to see that all three variables ($$f, $$x1, and $$x2) have valid values. Then, it executes its second argument, Plot[f, {x, a, b}]. This is the Mathematica command for plotting a function of x in the range from a and b. The MSPShow command saves an image of the resulting graphic on the server and returns a link to that image for insertion into the Web page.

Matrix Operations

Example 12.13 shows a slightly more complicated Web page that allows a user to do several different types of computations on a matrix. The page features a pull-down menu with a list of functions. The user enters a matrix in the text box using standard Mathematica syntax, and then chooses a particular function from the pull-down menu. Clicking the Evaluate button causes the result of the computation to be displayed in the Web page, as shown in Figure 12.18.

Example 12.13: An HTML document for doing matrix calculations using webMathematica.

start example
    <html>      <head><title>Matrix Operations</title></head>        <h1>Matrix Operations</h1>        <form method="post">        <p>Enter a matrix:        <input type="text" name="matrix" align="left"         size="24" value = "<%Mathlet MSPValue[$$matrix,        "{{1, 2}, {3, 4}}"] %>"></p>        <p>Choose an operation from the menu:        <%Mathlet MSPSetDefault[$$fn, "Transpose"]; %>        <select name="fn" size=1>          <option value="Transpose"          <%Mathlet If[$$fn=="Transpose", "selected"]%>>            Transpose </option>          <option value="Inverse"          <%Mathlet If[$$fn=="Transpose", "selected"]%>>            Transpose </option>          <option value="Determinant"          <%Mathlet If[$$fn=="Transpose", "selected"]%>>            Transpose </option>          <option value="Eigenvectors"          <%Mathlet If[$$fn=="Transpose", "selected"]%>>            Transpose </option>        <option value=" Eigenvectors "        <%Mathlet If[$$fn=="Eigenvectors", selected"]%>>          Eigenvectors </option>      </select></p>      <p><input type="submit" name="Submit"      value="Evaluate"> </p>      <p><%Mathlet MSPBlock[$$ matrix, MSPFormat[Which[          $$fn=="Inverse", Inverse[$$matrix],          $$fn=="Transpose", Transpose[$$matrix],          $$fn=="Determinant", Det[$$matrix],          $$fn =="Eigenvalues", Eigenvalues[$$matrix],          $$fn =="Eigenvectors", Eigenvectors[$$matrix],          True, $$matrix], TraditionalForm]]%>        </p>       </form>      </body>    </html> 
end example

click to expand
Figure 12.18: A Web page for doing matrix calculations.

The Web page shown in Figure 12.18 works as follows. It contains three different controls: a text box for entering input, a menu for choosing the type of computation to perform, and a button for submitting the information to the server. The pull-down menu is implemented using the standard HTML select element, with each item in the menu represented by an option element.

The page defines two variables, $$matrix and $$fn, which represent the matrix entered by the user in the text box and the function to be applied to the matrix, respectively. The MSPSetDefault function is used to assign a default value to the $$fn variable. Depending on the menu item selected, the corresponding function name is assigned to the variable $$fn. When the user clicks the Evaluate button, the value of $$fn and $$matrix are passed to the Which command, used in Mathematica for conditional processing. Depending on the value of $$fn, the corresponding computation is performed on $$matrix, and the result is displayed in the Web page using MSPFormat.

Converting Expressions to MathML

As we saw in Section 11.2, Mathematica includes many commands for working with MathML. In particular, you can convert expressions in Mathematica syntax into MathML and vice versa. Example 12.14 shows an MSP script that displays the MathML representation for any expression in Mathematica syntax. Figure 12.19 shows how this script looks when viewed in IE.

Example 12.14: An HTML document for converting an expression into MathML.

start example
    <html>    <head><title>Conversion to MathML</title></head>    <body bgcolor = "white">      <h1>Conversion to MathML</h1>        <form method="post">          Enter an expression:          <input type="text" name="input" align="left"          size="50" value =        "<%Mathlet MSPValue[ $$input, "Sqrt[x+1]"] %>">        <p><input type="submit" name="inputButton"        value="Convert"> </p>      <p><%Mathlet MSPBlock[{$$input}, MSPFormat[      XML`MathML`ExpressionToMathML[$$input]]] %></p>      </form>    </body>    </html> 
end example

click to expand
Figure 12.19: Translating mathematical expressions into MathML.

This script is similar to the previous ones in that it uses Mathlet tags along with the standard functions: MSPValue, MSPBlock, and MSPFormat. The Mathematica function XML‘MathML‘ExpressionToMathML is used to translate the expression entered by the user into MathML.

You can use the conversion options discussed in Section 11.2 to control various aspects of the MathML produced, such as the type of markup or the declarations added to it. For example, by default, XML‘MathML‘ExpressionToMathML yields both presentation markup and content markup encodings of its argument, enclosed in a semantics tag. However, you can modify the function to get either presentation markup or content markup alone by setting the option "Formats" to "PresentationMathML" or "ContentMathML", respectively. Other conversion options for customizing the form of the output include, for example:

  • Adding a namespace declaration and prefix to all the element and attribute names

  • Adding an XML declaration or DOCTYPE declaration at the start of the MathML expression

  • Changing the format of the output to be a continuous string without any additional indentation and linebreaking

See Section 11.2 for more information on available the conversion options.

Using MathML As Input

All the examples of MSP scripts shown so far require you to specify input in Mathematica syntax. However, you can also use webMathematica to perform computations on input specified as MathML. This allows you, for example, to copy a MathML expression from another application, paste it into a form in a Web page, and then perform some computation on it (such as differentiating the expression or generating a plot).

The basic procedure for doing this is to convert the MathML string supplied as input into the equivalent Mathematica expression. You can do this by using the function XML‘MathML‘MathMLToExpression, which is the converse of the XML‘MathML‘ExpressionToMathML‘ function used in Example 12.14. Once a Mathematica expression is obtained, you can perform a wide variety of computations on it by applying any of the Mathematica functions for algebra, calculus, graphics, and so on. Example 12.15 shows an MSP script for calculating the integral of a function of one variable. Figure 12.20 shows how this script looks when viewed in IE.

Example 12.15: An HTML document for integrating a function specified in MathML form.

start example
    <html>      <head>          <title>Integrating MathML</title>      </head>      <body>      <h1>Integrating a MathML Expression</h1>      <form method="post">    <p>Enter some MathML:</p>    <p><textarea name="input" rows="10" cols="50" >      <%Mathlet StringReplace[MSPValue[$$input,        "<math><msup><mi>x</mi><mn>2</mn></msup></math>"],        {"\n"->"","&" -> "&amp;", "<" -> "&lt;",          ">" -> "&gt;", "'"->"&#39;", "\""->"&quot;"}] %>      </textarea></p>      <input type="submit" name="inputButton"        value="Integrate">        <p><%Mathlet MSPFormat[Integrate[          XML`MathML`MathMLToExpression[$$input],x],          TraditionalForm] %></p>         </form>      </body>    </html> 
end example

click to expand
Figure 12.20: Calculating the integral of a function specified in MathML.

Example 12.15 works as follows. The user enters a MathML string in the text box provided and then clicks the Integrate button. The Mathematica function StringReplace is applied to the MathML string to remove linebreaks and replace various special characters with the corresponding entity references. This is to prevent these special characters from being automatically replaced in certain browsers. The MathML string obtained after these substitutions are made is then supplied as an argument to the XML‘MathML‘MathMLToExpression function, which translates the MathML into the corresponding Mathematica expression. Finally, the Integrate function is used to calculate the integral, and the MSPFormat function is used to display the result in TraditionalForm.

You can easily modify Example 12.15 for doing other types of computation on MathML input. Example 12.16 shows an MSP script for plotting a function of one variable specified as a MathML string. Figure 12.21 shows how this script looks when viewed in IE.

Example 12.16: An HTML document for plotting a function specified in MathML form.

start example
    <html>      <head>      <title>Plotting MathML</title>      </head>      <body>        <h1>Plotting a MathML Expression</h1>        <form method="post">          <p>Enter some MathML :</p>          <p><textarea name="input" rows="10" cols="50">          <%Mathlet StringReplace[MSPValue[$$input, "<math><apply><sin/><ci>x</ci></apply></math>"],            {"\n"->"","&" -> "&amp;", "<" -> "&lt;", ">" ->            "&gt;", "'"->"&#39;", "\""->"&quot;"}] %>             </textarea></p>               <p>Enter the start of the range:               <input type="text" name="x1" size="10" value =                 "<%Mathlet MSPValue[$$x1, "0"] %>"></p>                 <p> Enter the end of the range:                 <input type="text" name="x2" size="10" value =                 "<%Mathlet MSPValue[ $$x2, "10"] %>"></p>                 <input type="submit" name="inputButton"                 value="Plot">                 <p><%Mathlet MSPBlock[{$$x1,$$x2}, MSPShow[ Plot[XML`MathML`MathMLToExpression[$$input],                   {x,$$x1,$$x2}]]]%></p>             </form>        </body>    </html> 
end example

click to expand
Figure 12.21: Plotting a function specified in MathML.

This example is similar to Example 12.12. The only difference is that the function to be plotted is specified as a MathML string instead of a Mathematica expression. As in Example 12.14, the MathML string is processed and converted into a Mathematica expression. The Plot function then produces the plot, and the MSPShow function displays an image of the plot in the Web browser.

The examples given here can be readily extended to provide access to calculations of any degree of complexity directly from a Web page. All the details for sending input to Mathematica and returning output back to the Web page are handled automatically by webMathematica, so the user does not have to worry about the low-level implementation details. Also, since the Mathlet tags can be embedded directly in the HTML document in a fairly natural and seamless way, whoever is maintaining the Web site can choose the tools for generating and maintaining Web pages.



 < Day Day Up > 



The MathML Handbook
The MathML Handbook (Charles River Media Internet & Web Design)
ISBN: 1584502495
EAN: 2147483647
Year: 2003
Pages: 127
Authors: Pavi Sandhu

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net