Difference between revisions of "Introduction to MathObjects"

From WeBWorK_wiki
Jump to navigation Jump to search
 
(77 intermediate revisions by 6 users not shown)
Line 1: Line 1:
== What are MathObjects ==
+
== What are MathObjects? ==
   
MathObjects are a set of formal objects introduced to make manipulation of mathematical object in !WeBWorK problems more intuitive. They allow the definition of variables as common mathematical objects, e.g.,
+
MathObjects are a set of Perl objects that make the manipulation of mathematics within WeBWorK problems more intuitive. They make it possible to define variables in your problems that correspond to common mathematical objects, such as formulas, real number, complex numbers, intervals, vectors, points, and so on. For example:
   
$f = Formula("sin(x^2+6)");
+
$f = Formula("sin(x^2+6)");
$a = Real("sqrt(pi/6)");
+
$a = Real("sqrt(pi/6)");
$z = Complex("1 + 5i");
+
$z = Complex("1 + 5i");
   
These are useful (and powerful) because MathObjects "know" information about themselves: thus, we can add formulas to get new formulas, plug real objects into formulas to get formulas evaluated at those values, and calculate derivatives of formulas.
+
These are useful (and powerful) because MathObjects "know" information about themselves; thus, you can add formulas to get new formulas, plug real objects into formulas to get formulas evaluated at those values, calculate derivatives of formulas, add and subtract intervals to form unions and intersections, and much more.
   
For several reasons it
 
  +
For several reasons it is usually preferable to write the MathObjects above using the <code>Compute()</code> function rather than the individual constructors for the various MathObject types.
is usually preferable to write the MathObjects above using <code>Compute</code>
 
   
$f = Compute("sin(x^2+6)");
+
$f = Compute("sin(x^2+6)");
$a = Compute("sqrt(pi/6)");
+
$a = Compute("sqrt(pi/6)");
$z = Compute("1 + 5i");
+
$z = Compute("1 + 5i");
  +
  +
The <code>Compute()</code> function determines the kind of MathObject from the Context and from the syntax of its argument, which is usually a string value that is in the form that a student could type. The <code>Compute</code> function also sets the "correct answer" to be the exact string that it was given, so that if a student were asked to enter a number that matched <code>$a</code> from above and asked to see the correct answer (after the due date), then <code>sqrt(pi/6)</code> would be displayed rather than <code>0.723601</code>. This gives you more control over the format of correct answers that are shown to students.
   
<code>Compute</code> determines the kind of MathObject from the Context and from the syntax of its
 
argument which is always a string variable.
 
   
 
== Why use MathObjects? ==
 
== Why use MathObjects? ==
   
MathObjects are designed to be used in two ways. First, you can use it within your perl code
 
  +
MathObjects are designed to be used in two ways. First, you can use them within your Perl code when writing problems as a means of making it easier to handle formulas and other mathematical items, and in particular to be able to produce numeric values, TeX output, and answer strings from a single formula object. This avoids having to type a function three different ways (as a Perl function, as a TeX string, and as an answer string), making it much easier to maintain a problem, or duplicate and modify it to use a different formula. Since MathObjects also includes vectors, points, matrices, intervals, complex numbers, and a variety of other object types, it is easier to work with these kinds of values as well.
when writing problems as a means of making it easier to handle formulas, and in particular,
 
to be able to use a single object to produce numeric values, TeX output and answer strings from a single
 
formula entry. This avoids having to type a function three different ways
 
(which makes maintaining a problem much harder). Since MathObjects also included vector and complex arthimetic, it is easier to work with these types of values as well.
 
   
More importantly using MathObjects improves the processing of student input. This is accomplished through special answer checkers that are part of the Parser package (rather than the traditional WeBWorK answer checkers).
 
  +
More importantly, using MathObjects improves the processing of student input. This is accomplished through special answer checkers that are part of the MathObjects Parser package rather than the traditional WeBWorK answer checkers. Each of these checkers has error checking customized to the type of input expected from the student and can provide helpful feedback if the syntax of the student's entry is incorrect. Because the MathObject checkers are part of a unified library, students get consistent error messages regardless of the type of answer that is expected or that they provide. For example, if a student enters a formula in an answer blank where the correct answer is actually a number, she will receive a message indicating that what she typed was a formula but that a number was expected. Thus students are given guidance automatically about this type of semantic problem with their answers. Answer checkers for points and vectors can indicate that the number of coordinates are wrong, or can tell the student which coordinates are incorrect (at the problem-author's discretion).
Each of these checkers has error checking customized to the type of input expected from the student and can provide helpful feedback if the syntax of the student's entry is incorrect.
 
   
Checkers are available for each of the types of values that the parser can produce (numbers, complex numbers, infinities, points, vectors, intervals, unions, formulas, lists of numbers, lists of points, lists of intervals, lists of formulas returning numbers, lists of formulas returning points, and so on). They are typically invoked using the notation <code>$mathObject->cmp()</code>
 
   
MathObjects are useful (and powerful) because they "know" information about themselves:
 
  +
== MathObject Contexts ==
thus, we can add formulas to get new formulas, plug real objects
 
into formulas to get formulas evaluated at those values, and calculate derivatives of formulas.
 
   
== Contexts ==
 
  +
Although a problem may include several answer blanks, the problem generally has a collection of variables that it defines, values that it uses, and so on; these form the "context" of the problem. For example, if the problem is concerned with a function of <math>x</math> and <math>y</math> and its partial derivatives, then the context of the problem includes variables <math>x</math> and <math>y</math>, and so all the answer blanks within the problem should recognize that <code>x</code> and <code>y</code> have meaning within the problem, even if the answer blank is only asking for a number. Suppose a student is asked to enter the value of a partial derivative at a particular point and, rather than giving a number, enters the formula for the derivative (not evaluated at the point). He should not be told "x is undefined", as would have been the case with WeBWorK's traditional answer checkers, since <math>x</math> actually <i>is</i> defined as part of the problem. Such messages serve to confuse the student rather than help him resolve the problem.
   
Each problem is considered in a given context. The context determines what various symbols represent.
 
  +
MathObjects solves this issue by using a Context object to maintain the context of a problem. That way, all the answer blanks will know about all the variables and values defined within the problem, and can issue appropriate warning messages when a student uses them inappropriately. For example, in the situation described above where the student entered the unevaluated derivative where the value at a point was requested, he will get the message "Your answer is not a number (it seems to be a formula returning a number)", which should help him figure out what he has done wrong.
For example in "Interval" context <code> (4,5)</code> means the interval
 
between 4 and 5 while in "Point" context it means a single
 
point in the x-y plane.
 
Among other things the context will determine which student responses
 
will be considered "legitimate", although perhaps incorrect, and which will be considered not
 
legitimate and will trigger a syntax error message.
 
   
* For example in a "Vector" context <code> <5,6,7></code> makes sense and the < is interpreted as an angle brackect.
 
  +
Thus one of the main purposes for the Context is to maintain the set of variables and values that are part of the problem as a whole. Another key function of the Context is to tell the answer checkers what functions and operations are available within a student answer, and what the various symbols the student can type will mean. For example, if you are asking a student to compute the value of 6 / 3, then you may want to restrict what the student can type so that she can't enter <code>/</code> in her answer, and must type an actual number (not an expression that is evaluated to a number). Or if you are asking a student to determine the value of <code>sin(pi/6)</code>, you might want to restrict his answer so that he can't include <code>sin()</code>, but you do allow arithmetic operations. Such restrictions are also part of the context of the problem, and so are maintained by MathObjects as part of the Context.
In the "Numeric" context it would trigger an error.
 
* In the "Inequality" context <code> 5 < 6</code> the < is interpreted as a "less than" sign.
 
* We've already noted that <code> (4,5)</code> means two different things in different contexts.
 
   
  +
In a similar way, some symbols mean different things in different problems. For example in a problem dealing with intervals, <code>(4,5)</code> means the interval between 4 and 5, while in a multi-variable calculus setting, it might mean a single point in the <math>xy</math>-plane. Or in a problem on complex numbers, the value <math>i</math> means <math>\sqrt{-1}</math>, while in vector calculus, it would mean the coordinate unit vector along the <math>x</math>-axis. Or in a problem on inequalities, <code>5 &lt; x</code> would use <code>&lt;</code> as the "less-than" sign, while in a vector calculus problem, <code>&lt;5,6,7&gt;</code> would mean the vector with coordinates 5, 6, and 7. The Context determines how these symbols will be interpreted by the MathObjects library.
   
The default Context is
 
  +
The MathObjects library comes with a collection of predefined Contexts that you can call on to set the meanings of symbols like these to be what you need for your problems. The default Context is the <code>Numeric</code> Context, which is sufficient for most first-semester calculus problems. There are Contexts for complex numbers, intervals, vectors, and so forth; see the [[Common Contexts]] list and the links at the bottom of this document for further information. The [https://github.com/openwebwork/pg/tree/master/macros pg/macros/] directory includes a number of specialized Contexts as well; the files beginning with <code>context</code> define these, and are described on the [[Specialized contexts]] page.
 
<code>Context("Numeric");</code>
 
   
and it will be sufficient to use the default context for most
 
  +
Use <code>$context = Context();</code> to obtain a reference to the current context. See the [[Introduction to contexts]] for information about how to use this to modify an existing context (e.g., to add variables to it, or to restrict the functions that can be used).
first semester calculus problems.
 
   
There is a [[#List_of_Basic_Contexts |list of basic contexts]] and links to further context information at the bottom of this document.
 
  +
It is possible to use more than one context within the same problem. This is discussed '''(link needed)'''.
   
There are cases where one needs to use two Contexts for a single problem -- but this is not
 
  +
<div style="font-weight:bold; font-size:125%; margin-top:1em">Further Reading</div>
as common -- and for now we'll assume that each problem takes place in one context.
 
  +
* [[Introduction to Contexts]]
  +
* [[Common Contexts]]
  +
* [[Specialized contexts]]
  +
* [https://github.com/openwebwork/pg/tree/master/macros pg/macros] -- files starting with <code>context</code> define new Contexts
   
 
The basic contexts are straight forward and natural to use. Modifying contexts allows one to
 
create completely new question types but it is a subtle matter to make these contexts behave
 
as "expected".
 
   
 
== How to create a MathObject ==
 
== How to create a MathObject ==
   
$a = Real(3.5); or
 
  +
In order to use MathObjects in a problem you are writing, include <code>MathObjects.pl</code> in your <code>loadMacros()</code> call. For example:
$a = Compute("3.5");
 
 
$b = Complex(3, 4); or
 
$b = Complex("3 +4i"); or
 
$b = Compute("3+4i");
 
 
$v = Vector(4,5,8);
 
$v = Compute("&lt;4,5,8&gt;");
 
   
$f = Formula("sin(x^2) + 6");
 
  +
loadMacros(
  +
"PGstandard.pl",
  +
"MathObjects.pl",
  +
"PGcourse.pl",
  +
);
   
<code>$a</code> represents a real number 3.5 and <code>$b</code> (defined by either method) represents a complex number.
 
  +
Once this is done, there are several ways to create MathObjects in your problem:
In general using the <code>Compute</code> variant is preferred because the input string also serves as a model for the
 
  +
* By calling a constructor function for the type of object you want (e.g., <code>Real(3.5)</code> or <code>Complex("3+4i")</code>)
correct answer expected from the student.
 
  +
* By calling <code>Compute()</code> to parse a string and return the resulting object (e.g., <code>Compute("3+4i")</code>)
  +
* By calling a method of an existing MathObject that returns another object (e.g., <code>Formula("sin(x)")->eval(x => pi/2)</code>)
  +
* By combining existing MathObjects via mathematical operations (e.g., <code>$x = Formula("x"); $f = $x**2 + 2*$x + 1</code>)
   
== Which MathObject types (classes) can be created? ==
 
  +
Some examples:
   
These classes are listed and made available for writing problems in <code>pg/macros/Value.pl</code>. It is loaded automatically when you load <code>MathObjects.pl</code>.
 
  +
$a = Real(3.5); or
  +
$a = Compute(3.5); or
  +
$a = Compute("3.5");
   
=== Standard types ===
 
  +
$b = Complex(3, 4); or
  +
$b = Complex("3 + 4i"); or
  +
$b = Compute("3 + 4i");
   
* Real: Behave like real numbers
 
  +
$v = Vector(4,5,8); or
* Infinity: The positive infinity of the extended reals. Can be negated, but can't be added to real numbers.
 
  +
$v = Vector([4,5,8]); or
* Complex: Behave like complex numbers. The interpretations of <code>+</code> and <code>*</code> are those standardly used for mathematical complex numbers.
 
  +
$v = Vector("&lt;4,5,8&gt;"); or
  +
$v = Compute("&lt;4,5,8&gt;");
   
=== List types ===
 
  +
$f = Formula("sin(x^2) + 6"); or
  +
$f = Compute("sin(x^2) + 6");
   
List objects are math objects whose description involves delimiters (parentheses) of some type. For example points <code>(4, 5)</code> or vectors <code>&lt;2,5&gt;</code> . Here are examples of the construction of the List Objects.
 
  +
Here, <code>$a</code> (defined any of the three ways) represents a real number and <code>$b</code> (defined by any of the three) represents a complex number; <code>$v</code> will be a vector, and <code>$f</code> is a formula.
   
* Point: <code>$a = Point("(4,5)");</code>
 
  +
In general, the <code>Compute()</code> variant is preferred because you enter what you want the student to type, and <code>Compute()</code> generates the proper MathObject to handle that (just as it will when it processes the student answer). Another important feature of <code>Compute()</code> is that the input string also serves as the correct answer when a student requests answers after the due date, which lets you put the correct answer in exactly the form you want it to appear. For example if you use
* Vector: <code>$b = Vector("&lt;3,5,6!&gt;");</code>
 
* Matrix: <code>$c = Matrix("[[1,0],[0,1]]");</code>
 
* List: <code>$d = List("3, 7, 3+2i");</code>
 
   
=== Types that represent some subset of the real numbers ===
 
  +
Compute("<cos(pi/6),sin(pi/6), pi/6>")->cmp
   
* Interval: <code>$I = Interval("[0,1)");</code>
 
  +
the correct answer will be presented to the student as <code>&lt;cos(pi/6),sin(pi/6), pi/6&gt;</code>, while
* Set (a finite collections of points): <code>$S = Set("{3,5,6,8}");</code>
 
* Union (of intervals and sets): <code>$U = Union(""I U J");</code> (I union J)
 
   
=== The <code>Compute</code> command ===
 
  +
Vector("<cos(pi/6),sin(pi/6), pi/6>")->cmp
* You can use the <code>Compute</code> command to create any of the objects above from a string
 
Compute("3,7,3+2i")
 
Compute( "[[1,0],[0,1]]" );
 
Compute("<cos(pi/6),sin(pi/6), pi/6>");
 
   
==== Why it is usually preferable to use the <code>Compute</code> syntax ====
 
  +
would show <code>&lt;0.866025,0.5,0.523599&gt;</code> as the correct answer.
Usually <code>Compute</code> is the preferred way to convert a string to a MathObject. It preserves the original string and uses it to display the correct answer
 
expected of the student in the most useful form.
 
   
For example here are the correct answers presented to the students in the two cases: using Compute or using Vector directly.
 
  +
In addition, <code>Compute()</code> can be used to compute the result of a formula at a given value of its inputs. For example,
   
Compute("<cos(pi/6),sin(pi/6), pi/6>")->cmp
 
  +
$a = Compute("x+3",x => 2);
Correct answer presented to student: <cos(pi/6),sin(pi/6), pi/6>
 
  +
$a = Compute("x^2+y^2",x => 1, y => 2);
Vector("<cos(pi/6),sin(pi/6), pi/6>")->cmp
 
Correct answer presented to student: <0.866025,0.5,0.523599>
 
   
=== The String type ===
 
  +
both are equivalent to <code>$a = Real(5)</code>.
   
String is a special purpose type which allows comparison to an arbitrary string. The string which is the correct answer must also be one of the "legitimate" strings in the [[IntroductionToContexts#Context_changes_for_Strings| Context]] being used.
 
  +
The MathObjects library defines classes for a variety of common mathematical concepts, including real numbers, complex numbers, intervals, points, vectors, matrices, and formulas. These are described in more detail in the [[:Category:MathObject_Classes| MathObject Class documentation]].
   
String("DNE")
 
  +
The [https://github.com/openwebwork/pg/tree/master/macros pg/macros] directory contains a number of extensions to MathObjects, including files that define specialized MathObject types. The ones that begin with <code>parser</code> typically define a new object class. For example, <code>parserParametricLine.pl</code> defines a constructor <code>ParametricLine()</code> for creating a special object that checks if a student's answer is a given parametric line or not, even if it is parameterized differently. These files usually contain documentation within them; see the [http://webwork.maa.org/pod/pg/ POD pages] for versions that you can read on line, and [[Specialized parsers]] for a list of most of the MathObject extensions.
   
=== The Formula type ===
 
  +
<div style="font-weight:bold; font-size:125%; margin-top:1em">Further Reading</div>
  +
* [[:Category:MathObject_Classes| MathObject Class documentation]]
  +
* [[Specialized parsers]]
  +
* [https://github.com/openwebwork/pg/tree/master/macros pg/macros] -- files starting with <code>parser</code> define new MathObejcts
   
A Formula object represents a function whose output is one of the MathObject types defined above. Every Formula contains a parse tree which allows you to calculate output values from given input values.
 
   
$f = Formula('2x^2+3x-5');
 
  +
== How to display a MathObject ==
   
== How to invoke a MathObject's method ==
 
  +
MathObject can be inserted into the text of your problem just as any other variable can be. When this is done, the MathObject will insert its string version (as generated by its <code>[[Common MathObject Methods#string|string()]]</code> method). Frequently, however, you want to include the MathObject within a mathematical expression, and would prefer to use its <math>\rm\TeX</math> form (as generated by its <code>[[Common MathObject Methods#TeX|TeX()]]</code> method). One way to do this is to call the <code>TeX()</code> method directly, as in
   
Use the standard Perl method call syntax:
 
  +
$f = Formula("(x+1)/(x-1)");
  +
BEGIN_TEXT
  +
\[f(x) = \{$f->TeX\}\]
  +
END_TEXT
   
$obj->method;
 
  +
but this requires <code>\{...\}</code> and the explicit use of <code>->TeX</code> to get the desired output. There is an easier way, however, that involves telling the Context to produce <math>\rm\TeX</math> format rather than string format via the <code>texStrings()</code> method of the Context object.
$obj->method($arg1,$arg2);
 
   
For example:
 
  +
$f = Formula("(x+1)/(x-1)");
  +
Context()->texStrings;
  +
BEGIN_TEXT
  +
\[f(x) = $f\]
  +
END_TEXT
  +
Context()->normalStrings;
   
ANS($a->cmp);
 
  +
In this case, you just use <code>$f</code> within the text of the problem, which is easier to type and easier to read, especially if you have several MathObjects to insert. It is good practice to return the setting to normal using <code>normalStrings()</code>, as is done here, so that if you use MathObjects withing strings later on (e.g., <code>$g = Compute("3*$f + 1")</code>), you will not be inserting <math>\rm\TeX</math> into those strings inadvertently.
   
This compares the student's answer with <code>$a</code>. If <code>$a</code> is Real then this comparison will be "fuzzy" which means that equality is checked to a tolerance defined by the current Context.
 
   
=== Examples of Using MathObjects ===
 
  +
== MathObject Answer Checkers ==
MathObjects are useful (and powerful) because they "know" information about themselves: how to add themselves to other MathObjects, take derivatives, substitute values, and to compare themselves with student answers, and even to alert students if their entries contain syntactical errors as opposed to substantiative ones.
 
   
  +
Each MathObject type has a corresponding answer checker that can be used to process student responses. You obtain the checker by using the <code>cmp()</code> method of the MathObject.
   
$f = Compute("sin(x^2+6)");
 
  +
ANS($mathObject->cmp);
$a = Compute("sqrt(pi/6)");
 
$z = Compute("1 + 5i");
 
$v = Compute("");
 
$M = Compute("[1,0,1],[1,1,0],[0,1,1]");
 
   
With the definitions given above all of these operations can be performed:
 
  +
There is no need to select the right kind of answer checker, as the MathObject library handles that for you.
   
$dfdx = $f->D();
 
  +
Many of the answer checkers include options that you can specify. For example, the tolerances to use, or the limits to use for the variables, or whether to provide certain kinds of hints to students as they enter incorrect answers. These are passed as <code>name=>value</code> to the <code>cmp()</code> method, separated by commas if there is more than one option to set, as in the following example:
$dfdx_at4 = $dfdx->eval(x=>4);
 
$g = $f + $dfdx;
 
$z1 = 5*$z;
 
$z2 = $a + $z;
 
$x = $M*$v;
 
   
The results are that $dfdx is the derivative of $f, $dfdx_at4 is f'(4), and so forth.
 
  +
ANS(Real(sqrt(2))->cmp(tolerance => .0001)); # requires answer with roughly four decimal places.
  +
ANS(Formula("sqrt(x-10)")->cmp(limits => [10,12])); # use x in the interval [10,12] so that the square root is defined.
   
Use the online calculators at [[PGLabs]] to experiment with MathObjects in order to quickly learn the syntax.
 
  +
See the [[Answer Checkers (MathObjects)| Answer Checkers in MathObjects]] page for details about the MathObject Answer checkers, and the [[Answer Checker Options (MathObjects)| Answer Checker Options]] page for more on the options you can set for the different MathObject classes.
   
=== Methods shared by all MathObjects ===
 
  +
<div style="font-weight:bold; font-size:125%; margin-top:1em">Further Reading</div>
  +
* [[Answer Checkers (MathObjects)| Answer Checkers in MathObjects]]
  +
* [[Answer Checker Options (MathObjects)| Answer Checker Options]]
  +
* [[Custom Answer Checkers]]
   
* <code>cmp</code>: Returns an answer checker for the Value. All of the answer checkers are defined in the file lib/Value/AnswerChecker.pm.
 
* <code>perl</code>: Returns a string which represents the object as Perl source code.
 
* <code>perlFunction</code>: Returns a Perl subroutine which represents the object. (Only available for Formula objects.)
 
* <code>value</code>: Returns the value of the object.
 
* <code>TeX</code>: Returns a string which represents the object as a TeX math expression.
 
* <code>string</code>: Returns a string similar to that used to create the object. May include extra parentheses.
 
* <code>stringify</code>: Produces the output of the object when inside quotes. Depending on context this is either a TeX string or a regular string. (This is called automatically by Perl when when an object is used in string context, and should not need to be called explicitly by the problem author.)
 
* <code>getFlag("flag name")</code>: Returns the value of one of the object's internal flags. For example: <code>$a->getFlag("tolerance");</code> (see [[ContextFlags]] for a partial list )
 
   
=== Additional methods for Formulas ===
 
  +
== MathObject Methods and Properties ==
   
Each <code>Formula</code> has a parsed version of its defining string attached.
 
  +
Since MathObjects are Perl objects, you call a method on a MathObject as you would a method for any Perl object, using the <code>-></code> operator with the MathObject on the left and the method name and its arguments (if any) on the right. E.g.,
This is created by the parser whose purpose is to parse a string representing a formula and turn it into a parse tree.
 
   
Additional <code>Formula</code> methods include:
 
  +
$mathObject->method; # when there are no arguments
  +
$mathObject->method($arg); # for one argument
  +
$mathObject->method($arg1,$arg2); # for two arguments
  +
# and so on
   
* <code>eval: $f_at32 = $f->eval(x=>32) </code> evaluates the function <code>$f</code> at <code>x=32</code>. The result is no longer a formula (the parse tree is lost) but has the type of f(32) i.e. the type of the range of $f.
 
  +
Similarly, you access the properties of an object just as you would for a Perl hash, via the <code>-></code> operator with the MathObject on the left and the property name in braces on the right. E.g.,
* <code>reduce: $f = $f->reduce </code> does some simplification of the function string --e.g. replace <code>1x^2</code> by <code>x^2</code>. The reduction rules are usually defined in the Context() and some of them are listed at [[List_of_parser_reduction_rules_for_MathObject_Formulas]]
 
* <code>substitute: $f = $f->substitute(x=>'y')</code> replaces all occurences of the variable <code>x</code> by the variable <code>y</code>. (One will also need to add the variable <code>y</code> as a legal variable to the context.) The result is a new formula. Using <code>substitute</code> instead of <code>eval</code> preserves the parse string enabling more insightful correct answer hints. (See [[FormattingCorrectAnswers]])
 
* <code>D $fp = $f->D</code> calculates the derivative of <code>f</code> however this will not be simplified.<code>$fp = $f->D->reduce</code> will perform easy simplifications, but will not completely simplify the formula.
 
   
  +
$mathObject->{property-name}
   
  +
There are a number of methods and properties that are common to all MathObjects, which are described in the documentation for [[Common MathObject Methods]] and [[Common MathObject Properties]]. Some classes have additional methods and properties, and many of these are described in the [[:Category:MathObject_Classes|MathObject Class documentation]] under the individual class links.
   
The parser which creates the parse tree <code>Formula</code> is defined in the file <code>pg/lib/Parser.pm</code> and the files in the <code>pg/lib/Parser</code> directory. Even though the subdirectory names under <code>pg/lib/Parser</code> are similar to those under <code>pg/lib/Value</code> they refer to different although related concepts. Under <code>pg/lib/Parser</code> the files refer to tokens in a string that is to be parsed, while the files under <code>pg/lib/Value</code> refer to MathObjects.
 
  +
<div style="font-weight:bold; font-size:125%; margin-top:1em">Further Reading</div>
  +
* [[Common MathObject Methods]]
  +
* [[Common MathObject Properties]]
  +
* [[:Category:MathObject_Classes|MathObject Classes]]
   
== List of Basic Contexts ==
 
   
This is essentially a table of values that provides default values for the MathObjects and for the Parser. As a quick example: in Numeric context the answer <code>(4,5)</code> is interpreted as a point in the two dimensional plane. in Interval context it is interpreted as the real values x satisfying <code>4 < x < 5</code>.
 
  +
== Experimenting with MathObejcts ==
   
* Define context using: <code>Context("Numeric");</code>
 
  +
One way to experiment with MathObjects is to use the [[PGLabs| on-line PG labs]] to write example code and see what it produces. You can copy any of the examples above (or elsewhere in the WIki) and paste them into the lab to check the results. This makes it easy to test code without having to write complete problem files and save them in a course. One lab lets you get the output from a line of PG code, while another lets you try out full problems to see how they work.
* To obtain the current context: <code>$context = Context();</code>
 
* Context names: defined in pg/lib/Parser/Context/Default.pm
 
** <code>Numeric</code>: no Matrix, Complex or Vectors (or intervals) are allowed.
 
** <code>Complex</code>: no Matrix or Vector, can't use "less than".
 
** <code>Point</code>: really the same as the Vector context below, but the angle bracket notation is not allowed.
 
** <code>Vector</code>: <code>i</code>, <code>j</code>, and <code>k</code> are defined as unit Vectors, no Complex numbers are allowed.
 
** <code>Vector2D</code>: <code>i</code> and <code>j</code> are defined as unit Vectors, no Complex numbers are allowed.
 
** <code>Matrix</code>: square brackets define Matrix instead of Point or Interval
 
** <code>Interval</code>: similar to Numeric context, but <code>(,)</code> and <code>[,]</code> create Real Intervals rather than Lists. <code>{,}</code> creates finite sets of Reals.
 
** <code>Full: For internal use. This context is used to seed the others.
 
*** <code>pi</code> is defined
 
*** <code>i</code> is square root of minus one, but <code>j</code> and <code>k</code> are unit Vectors
 
*** Matrix, Vector and Complex are all defined.
 
*** <code>x</code> is a variable
 
   
When first using MathObjects it's easiest to use the standard "Numeric" context, however as you
 
begin to search for better ways to ask questions and to evaluate student responses you will find
 
that customizing the context is a powerful way to proceed. There is more on this subject in the following
 
documents.
 
   
 
== See also ==
 
== See also ==
* [[IntroductionToContexts]]
 
  +
* [http://webwork.maa.org/pod/pg/doc/MathObjects/UsingMathObjects.html Using Math Objects] POD documentation
* [[ContextFlags]]
 
  +
<div style="margin-top:.75em">
* [[SpecializedContexts]]
 
  +
* [[:Category:MathObject_Classes| MathObject Classes]]
* [[SpecializedParsers]]
 
  +
* [[Common MathObject Methods]]
* [[ModifyingContexts(Advanced)]]
 
  +
* [[Common MathObject Properties]]
  +
</div>
  +
<div style="margin-top:.75em">
  +
* [[Answer Checkers (MathObjects)| Answer Checkers]]
  +
* [[Answer Checker Options (MathObjects)| Answer Checker Options]]
  +
* [[Custom Answer Checkers]]
  +
* [[Custom Answer Checkers for Lists]]
  +
</div>
  +
<div style="margin-top:.75em">
  +
* [[Introduction to contexts]]
  +
* [[Common Contexts]]
  +
* [[Context flags]]
  +
* [[Specialized contexts]]
  +
* [[Modifying contexts (advanced)]]
  +
</div>
  +
<div style="margin-top:.75em">
  +
* [[Specialized parsers]]
  +
</div>
   
 
[[Category:MathObjects]]
 
[[Category:MathObjects]]

Latest revision as of 16:14, 7 April 2021

What are MathObjects?

MathObjects are a set of Perl objects that make the manipulation of mathematics within WeBWorK problems more intuitive. They make it possible to define variables in your problems that correspond to common mathematical objects, such as formulas, real number, complex numbers, intervals, vectors, points, and so on. For example:

   $f = Formula("sin(x^2+6)");
   $a = Real("sqrt(pi/6)");
   $z = Complex("1 + 5i");

These are useful (and powerful) because MathObjects "know" information about themselves; thus, you can add formulas to get new formulas, plug real objects into formulas to get formulas evaluated at those values, calculate derivatives of formulas, add and subtract intervals to form unions and intersections, and much more.

For several reasons it is usually preferable to write the MathObjects above using the Compute() function rather than the individual constructors for the various MathObject types.

   $f = Compute("sin(x^2+6)");
   $a = Compute("sqrt(pi/6)");
   $z = Compute("1 + 5i");

The Compute() function determines the kind of MathObject from the Context and from the syntax of its argument, which is usually a string value that is in the form that a student could type. The Compute function also sets the "correct answer" to be the exact string that it was given, so that if a student were asked to enter a number that matched $a from above and asked to see the correct answer (after the due date), then sqrt(pi/6) would be displayed rather than 0.723601. This gives you more control over the format of correct answers that are shown to students.


Why use MathObjects?

MathObjects are designed to be used in two ways. First, you can use them within your Perl code when writing problems as a means of making it easier to handle formulas and other mathematical items, and in particular to be able to produce numeric values, TeX output, and answer strings from a single formula object. This avoids having to type a function three different ways (as a Perl function, as a TeX string, and as an answer string), making it much easier to maintain a problem, or duplicate and modify it to use a different formula. Since MathObjects also includes vectors, points, matrices, intervals, complex numbers, and a variety of other object types, it is easier to work with these kinds of values as well.

More importantly, using MathObjects improves the processing of student input. This is accomplished through special answer checkers that are part of the MathObjects Parser package rather than the traditional WeBWorK answer checkers. Each of these checkers has error checking customized to the type of input expected from the student and can provide helpful feedback if the syntax of the student's entry is incorrect. Because the MathObject checkers are part of a unified library, students get consistent error messages regardless of the type of answer that is expected or that they provide. For example, if a student enters a formula in an answer blank where the correct answer is actually a number, she will receive a message indicating that what she typed was a formula but that a number was expected. Thus students are given guidance automatically about this type of semantic problem with their answers. Answer checkers for points and vectors can indicate that the number of coordinates are wrong, or can tell the student which coordinates are incorrect (at the problem-author's discretion).


MathObject Contexts

Although a problem may include several answer blanks, the problem generally has a collection of variables that it defines, values that it uses, and so on; these form the "context" of the problem. For example, if the problem is concerned with a function of [math]x[/math] and [math]y[/math] and its partial derivatives, then the context of the problem includes variables [math]x[/math] and [math]y[/math], and so all the answer blanks within the problem should recognize that x and y have meaning within the problem, even if the answer blank is only asking for a number. Suppose a student is asked to enter the value of a partial derivative at a particular point and, rather than giving a number, enters the formula for the derivative (not evaluated at the point). He should not be told "x is undefined", as would have been the case with WeBWorK's traditional answer checkers, since [math]x[/math] actually is defined as part of the problem. Such messages serve to confuse the student rather than help him resolve the problem.

MathObjects solves this issue by using a Context object to maintain the context of a problem. That way, all the answer blanks will know about all the variables and values defined within the problem, and can issue appropriate warning messages when a student uses them inappropriately. For example, in the situation described above where the student entered the unevaluated derivative where the value at a point was requested, he will get the message "Your answer is not a number (it seems to be a formula returning a number)", which should help him figure out what he has done wrong.

Thus one of the main purposes for the Context is to maintain the set of variables and values that are part of the problem as a whole. Another key function of the Context is to tell the answer checkers what functions and operations are available within a student answer, and what the various symbols the student can type will mean. For example, if you are asking a student to compute the value of 6 / 3, then you may want to restrict what the student can type so that she can't enter / in her answer, and must type an actual number (not an expression that is evaluated to a number). Or if you are asking a student to determine the value of sin(pi/6), you might want to restrict his answer so that he can't include sin(), but you do allow arithmetic operations. Such restrictions are also part of the context of the problem, and so are maintained by MathObjects as part of the Context.

In a similar way, some symbols mean different things in different problems. For example in a problem dealing with intervals, (4,5) means the interval between 4 and 5, while in a multi-variable calculus setting, it might mean a single point in the [math]xy[/math]-plane. Or in a problem on complex numbers, the value [math]i[/math] means [math]\sqrt{-1}[/math], while in vector calculus, it would mean the coordinate unit vector along the [math]x[/math]-axis. Or in a problem on inequalities, 5 < x would use < as the "less-than" sign, while in a vector calculus problem, <5,6,7> would mean the vector with coordinates 5, 6, and 7. The Context determines how these symbols will be interpreted by the MathObjects library.

The MathObjects library comes with a collection of predefined Contexts that you can call on to set the meanings of symbols like these to be what you need for your problems. The default Context is the Numeric Context, which is sufficient for most first-semester calculus problems. There are Contexts for complex numbers, intervals, vectors, and so forth; see the Common Contexts list and the links at the bottom of this document for further information. The pg/macros/ directory includes a number of specialized Contexts as well; the files beginning with context define these, and are described on the Specialized contexts page.

Use $context = Context(); to obtain a reference to the current context. See the Introduction to contexts for information about how to use this to modify an existing context (e.g., to add variables to it, or to restrict the functions that can be used).

It is possible to use more than one context within the same problem. This is discussed (link needed).

Further Reading


How to create a MathObject

In order to use MathObjects in a problem you are writing, include MathObjects.pl in your loadMacros() call. For example:

   loadMacros(
     "PGstandard.pl",
     "MathObjects.pl",
     "PGcourse.pl",
   );

Once this is done, there are several ways to create MathObjects in your problem:

  • By calling a constructor function for the type of object you want (e.g., Real(3.5) or Complex("3+4i"))
  • By calling Compute() to parse a string and return the resulting object (e.g., Compute("3+4i"))
  • By calling a method of an existing MathObject that returns another object (e.g., Formula("sin(x)")->eval(x => pi/2))
  • By combining existing MathObjects via mathematical operations (e.g., $x = Formula("x"); $f = $x**2 + 2*$x + 1)

Some examples:

   $a = Real(3.5);   or
   $a = Compute(3.5);   or
   $a = Compute("3.5");
   $b = Complex(3, 4);   or
   $b = Complex("3 + 4i");   or 
   $b = Compute("3 + 4i");
   $v = Vector(4,5,8);   or
   $v = Vector([4,5,8]);   or
   $v = Vector("<4,5,8>");  or
   $v = Compute("<4,5,8>");
   $f = Formula("sin(x^2) + 6");  or
   $f = Compute("sin(x^2) + 6");

Here, $a (defined any of the three ways) represents a real number and $b (defined by any of the three) represents a complex number; $v will be a vector, and $f is a formula.

In general, the Compute() variant is preferred because you enter what you want the student to type, and Compute() generates the proper MathObject to handle that (just as it will when it processes the student answer). Another important feature of Compute() is that the input string also serves as the correct answer when a student requests answers after the due date, which lets you put the correct answer in exactly the form you want it to appear. For example if you use

   Compute("<cos(pi/6),sin(pi/6), pi/6>")->cmp

the correct answer will be presented to the student as <cos(pi/6),sin(pi/6), pi/6>, while

   Vector("<cos(pi/6),sin(pi/6), pi/6>")->cmp

would show <0.866025,0.5,0.523599> as the correct answer.

In addition, Compute() can be used to compute the result of a formula at a given value of its inputs. For example,

   $a = Compute("x+3",x => 2);
   $a = Compute("x^2+y^2",x => 1, y => 2);

both are equivalent to $a = Real(5).

The MathObjects library defines classes for a variety of common mathematical concepts, including real numbers, complex numbers, intervals, points, vectors, matrices, and formulas. These are described in more detail in the MathObject Class documentation.

The pg/macros directory contains a number of extensions to MathObjects, including files that define specialized MathObject types. The ones that begin with parser typically define a new object class. For example, parserParametricLine.pl defines a constructor ParametricLine() for creating a special object that checks if a student's answer is a given parametric line or not, even if it is parameterized differently. These files usually contain documentation within them; see the POD pages for versions that you can read on line, and Specialized parsers for a list of most of the MathObject extensions.

Further Reading


How to display a MathObject

MathObject can be inserted into the text of your problem just as any other variable can be. When this is done, the MathObject will insert its string version (as generated by its string() method). Frequently, however, you want to include the MathObject within a mathematical expression, and would prefer to use its [math]\rm\TeX[/math] form (as generated by its TeX() method). One way to do this is to call the TeX() method directly, as in

   $f = Formula("(x+1)/(x-1)");
   BEGIN_TEXT
     \[f(x) = \{$f->TeX\}\]
   END_TEXT

but this requires \{...\} and the explicit use of ->TeX to get the desired output. There is an easier way, however, that involves telling the Context to produce [math]\rm\TeX[/math] format rather than string format via the texStrings() method of the Context object.

   $f = Formula("(x+1)/(x-1)");
   Context()->texStrings;
   BEGIN_TEXT
     \[f(x) = $f\]
   END_TEXT
   Context()->normalStrings;

In this case, you just use $f within the text of the problem, which is easier to type and easier to read, especially if you have several MathObjects to insert. It is good practice to return the setting to normal using normalStrings(), as is done here, so that if you use MathObjects withing strings later on (e.g., $g = Compute("3*$f + 1")), you will not be inserting [math]\rm\TeX[/math] into those strings inadvertently.


MathObject Answer Checkers

Each MathObject type has a corresponding answer checker that can be used to process student responses. You obtain the checker by using the cmp() method of the MathObject.

   ANS($mathObject->cmp);

There is no need to select the right kind of answer checker, as the MathObject library handles that for you.

Many of the answer checkers include options that you can specify. For example, the tolerances to use, or the limits to use for the variables, or whether to provide certain kinds of hints to students as they enter incorrect answers. These are passed as name=>value to the cmp() method, separated by commas if there is more than one option to set, as in the following example:

   ANS(Real(sqrt(2))->cmp(tolerance => .0001));           # requires answer with roughly four decimal places.
   ANS(Formula("sqrt(x-10)")->cmp(limits => [10,12]));    # use x in the interval [10,12] so that the square root is defined.

See the Answer Checkers in MathObjects page for details about the MathObject Answer checkers, and the Answer Checker Options page for more on the options you can set for the different MathObject classes.

Further Reading


MathObject Methods and Properties

Since MathObjects are Perl objects, you call a method on a MathObject as you would a method for any Perl object, using the -> operator with the MathObject on the left and the method name and its arguments (if any) on the right. E.g.,

   $mathObject->method;              # when there are no arguments
   $mathObject->method($arg);        # for one argument
   $mathObject->method($arg1,$arg2); # for two arguments
   # and so on

Similarly, you access the properties of an object just as you would for a Perl hash, via the -> operator with the MathObject on the left and the property name in braces on the right. E.g.,

   $mathObject->{property-name}

There are a number of methods and properties that are common to all MathObjects, which are described in the documentation for Common MathObject Methods and Common MathObject Properties. Some classes have additional methods and properties, and many of these are described in the MathObject Class documentation under the individual class links.

Further Reading


Experimenting with MathObejcts

One way to experiment with MathObjects is to use the on-line PG labs to write example code and see what it produces. You can copy any of the examples above (or elsewhere in the WIki) and paste them into the lab to check the results. This makes it easy to test code without having to write complete problem files and save them in a course. One lab lets you get the output from a line of PG code, while another lets you try out full problems to see how they work.


See also