Difference between revisions of "Modifying Contexts (advanced)"

From WeBWorK_wiki
Jump to navigation Jump to search
m (moved Modifying contexts (advanced) to Modifying Contexts (advanced): Context (MathObjects) is capitalized)
(Reorganize the page, and lay out new sections, remove old material that is now elsewhere. Write first section on number formats with examples.)
Line 1: Line 1:
= Context Modification: How to Modify an Existing Context or Make Your Own Context =
 
  +
== Advanced Context Modifications ==
   
This document explains how to modify the current context and how to define your own context. You might want to do the latter if the problems you write/use always have certain nonstandard characteristics. For example, maybe your book always uses a certain parentheses type, etc.
 
  +
The [[Introduction to Contexts]] describes how to make basic modifications to a Context's [[Introduction to Contexts#Variables|variables]], [[Introduction to Contexts#Constants|constants]], [[Introduction to Contexts#Strings|strings]], [[Introduction to Contexts#Flags|flags]], [[Introduction to Contexts#Functions|functions]], [[Introduction to Contexts#Operators|operators]], and [[Introduction to Contexts#Reduction Rules|reduction rules]]. Here we will describe more advanced modifications and techniques involving the Context.
   
First we will describe common context modifications which you can make. The second part of the document will explain how to combine these changes into a file to define your own custom context.
 
  +
=== Number Formats ===
=== Part I. Modifying an Existing Context ===
 
   
What can you change? Here is a description of some of the basic changes you can make, what the options are, and how to change those values. You can do a lot of customization here, probably more than you need, but more advanced modifications can be made if you know how to program in Perl.
 
  +
Real numbers are stored using a format that retains about 16 or 17 significant digits, making computations very accurate in most situations. When a number is displayed, you probably don't want to see all 17 digits (that would make a vector in three-space take up around 35 characters, for example). To make answers easier to read, MathObjects usually display only 6 significant digits. You can change the format used, however, to suit your needs. The format is determined by the <code>Context()->{format}{number}</code>, which is a <code>printf</code>-style string indicating how real numbers should be formatted for display.
==== (1) Operators ====
 
   
The list of predefined operators includes stardard arithmetic operators:
 
  +
The format always should begin with <code>%</code> and end with one of <code>f</code>, <code>e</code>, or <code>g</code>, possibly followed by <code>#</code>. Here, <code>f</code> means fixed-point notation (e.g. <code>452.116</code>), <code>e</code> means exponential notation (e.g, <code>3.578E-5</code>), and <code>g</code> means use the form most appropriate for the magnitude of the number. Between the <code>%</code> and the letter you can (optionally) include <code>.<i>n</i></code> where <code><i>n</i></code> is the number of decimal digits to use for the number. If the format ends in <code>#</code>, then trailing zeros are removed after the number is formatted. (More sophisticated formats are possible, but this describes the basics.)
   
  +
Context()->{format}{number} = "%.2f"; # format numbers using 2-place decimals (e.g., for currency values).
  +
Context()->{format}{number} = "%.4f#"; # format numbers using 4-place decimals, but remove trailing zeros, if any.
   
* / + - ! >< U ^ **
 
  +
The default format is <code>"%g"</code>.
. ,
 
   
  +
The Context also includes information about what should count as a number when an answer is parsed. There are two patterns for this, a signed number and an unsigned number. The latter is what is used in parsing numbers (and the sign is treated as unary minus); former is used in the <code>[[Common MathObject Methods#Value::matchNumber|Value::matchNumber()]]</code> function. These are stored in the <code>Context()->{pattern}</code> hash; the default values are:
   
Where ! is the factorial operator, both ^ and ** give exponentiation, . is a dot product, and , is a list operation used to create lists.
 
  +
Context()->{pattern}{number} = '(?:\d+(?:\.\d*)?|\.\d+)(?:E[-+]?\d+)?';
  +
Context()->{pattern}{signedNumber} = '[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:E[-+]?\d+)?';
   
You may also find the operators u+, u-, and fn, but these are internal operators and should not be modified.
 
  +
These are fairly complicated regular expressions that match the usual fixe-point and exponential notation for numbers in WeBWorK. It is possible to change these patterns to handle things like commas instead of decimals for European usage, or to allow commas every three digits. Note, however, that you would need to include a <code>[[Context flags#NumberCheck|NumberCheck]]</code> routine that would translate the special format into the required internal format. For example, this allows you to enter numbers as hexadecimal values:
   
Here you will most often want to undefine some operators. The following example undefines cross product and dot product:
 
  +
#
  +
# Numbers in hexadecimal
  +
#
  +
Context()->{pattern}{number} = '[0-9A-F]+';
  +
Context()->{pattern}{signedNumber = '[-+]?[0-9A-F]+';
  +
Context()->flags->set(NumberCheck => sub {
  +
my $self = shift; # the Number object
  +
$self->{value} = hex($self->{value_string}); # convert hex to decimal via perl hex() function
  +
$self->{isOne} = ($self->{value} == 1); # set marker indicating if the value is 1
  +
$self->{isZero} = ($self->{value} == 0); # set marker indicating if the value is 0
  +
});
  +
Context()->update;
   
  +
Note that after changing the <code>pattern</code> you must call <code>Context()->update</code> to remake the tokenization patterns used by the Context.
   
Context()->operators->undefine('><','.');
 
  +
Here is an example that lets you use commas in your numbers:
   
  +
#
  +
# Allow commas every three digits in numbers
  +
#
  +
Context()->{pattern}{number} = '(:?(:?\d{1,3}(:?\,\d{3})+|\d+)(?:\.\d*)?|\.\d+)(?:E[-+]?\d+)?';
  +
Context()->{pattern}{signedNumber} = '[-+]?(:?(:?\d{1,3}(:?\,\d{3})+|\d+)(?:\.\d*)?|\.\d+)(?:E[-+]?\d+)?';
  +
Context()->flags->set(NumberCheck => sub {
  +
my $self = shift; # the Number object
  +
my $value = $self->{value_string}; # the original string
  +
$value =~ s/,//g; # remove commas
  +
$self->{value} = $value + 0; # make sure it is converted to a number
  +
$self->{isOne} = ($self->{value} == 1); # set marker indicating if the value is 1
  +
$self->{isZero} = ($self->{value} == 0); # set marker indicating if the value is 0
  +
});
  +
Context()->update;
   
You can also redefine an operator which was previously undefined.
 
  +
If you want to make the numbers display with commas, then you will need to subclass the <code>Value::Real</code> object and override the <code>string()</code> and <code>TeX()</code> methods to insert the commas again, and then tie your new class into the <code>Context()->{value}{Real}</code> value. For example, in addition to the changes above, you might do
   
Context()->operators->redefine('><','.');
 
  +
#
  +
# Subclass the Value::Real class and override its string() and TeX()
  +
# methods to insert commas back into the output
  +
#
  +
package my::Real;
  +
our @ISA = ('Value::Real'); # subclass of this Value::Real
  +
  +
sub string {
  +
my $self = shift; my $x = $self->SUPER::string(@_); # get the original string output
  +
my ($n,@rest) = split(/([.E])/,$x,1); # break it into the integer part and the rest
  +
while ($n =~ m/[0-9]{4}(,|$)/) # add commas as needed
  +
{$n =~ s/([0-9])([0-9]{3})(,|$)/$1,$2$3/}
  +
return join("",$n,@rest); # return the final string
  +
}
  +
  +
sub TeX {
  +
my $self = shift;
  +
my $n = $self->SUPER::TeX(@_); # original TeX uses string(), so commas are already there
  +
$n =~ s/,/{,}/g; # just make sure they have the correct spacing
  +
return $n;
  +
}
  +
  +
package main; # end of package my::Real;
  +
  +
Context()->{value}{Real} = "my::Real"; # make the Context use my::Real rather then Value::Real
  +
Context()->{format}{number} = "%f#"; # format using "f" rather than "g", so no exponential notation
   
To get rid of an operator you could also use
 
  +
This could be put into a separate macro file that you could load into your problems whenever it is needed. See [[Creating Custom Contexts]] for details.
   
Context()->operators->remove('><','.');
 
   
but this is not recommended, as undefine makes the operator unavailable (but still recognized), while after remove WebWork will not recognize the operator at all. Thus if an operator is undefined, students will get sensible error messages indicating that the operator is not available in the context of the problem.
 
  +
=== Lists and Delimiters ===
==== (2) Functions ====
 
 
The list of predefined functions is
 
 
sin, cos, tan, sec, csc, cot, asin, acos, atan, asec,
 
acsc, acot, sinh, cosh, tanh, sech, csch, coth, asinh,
 
acosh, atanh, asech, acsch, acoth, ln, log, log10, exp,
 
sqrt, abs, int, sgn, atan2, norm, unit, arg, mod,
 
Re, Im, conj
 
 
Here the most common need is to make some functions unavailable in the context of a problem. The following example makes functions needed only for complex variables unavailable:
 
 
Context()->functions->undefine('norm','unit','arg','mod','Re','Im','conj');
 
 
You can also undefine entire collections of functions with disable, e.g.,
 
 
Context()->functions->disable("Trig");
 
 
The categories of functions are: SimpleTrig (with sin, cos, tan, sec, csc, and cot), InverseTrig (with asin, acos, atan, asec, acsc, acot and atan2), SimpleHyperbolic (with sinh, cosh, tanh, sech, csch, and coth), InverseHyperbolic (with asinh, acosh, atanh, asech, acsch, acoth), Numeric (with ln, log, log10, exp, sqrt, abs, int, sgn), Vector (with norm and unit) and Complex (with arg, mod, Re, Im, conj).
 
 
There is also
 
 
Trig
 
(SimpleTrig together with InverseTrig), Hyperbolic (with SimpleHyperbolic and InverseHyperbolic), and All.
 
 
==== (3) Constants ====
 
 
The list of predefined constants is e, pi, i, j, k. The constant i denotes sqrt(-1) in Context("Complex"), denotes the vector <1,0> in Context("Vector2D"), and denotes the vector <1,0,0> in Context("Vector"), Context("Matrix"), and Context("Point"). The constant i is undefined outside of those contexts. The constants j and k are <0,1,0> and <0,0,1>, respectively, in Context("Vector") and Context("Matrix"). The constant j is <0,1> in Context("Vector2D"), and k is undefined there. The constants i, j and k are undefined outside of the contexts described above.
 
 
Context()->constants->set(i => {TeX=>'\boldsymbol{i}', perl=>'i'});
 
Context()->constants->remove("k");
 
Context()->constants->set(R => {TeX => '{\bf R}'});
 
 
 
==== (4) Variables ====
 
 
The default context Context("Numeric") recognizes a single real variable x. You can set variables in your context like this:
 
 
 
Context()->variables->are(z=>'Complex');
 
Context()->variables->are(x=>'Real',y=>'Real',z=>'Real');
 
 
 
Note that declaring variables this way with 'are' indicates to the context that these are the only variables in the context. You can add variables to a context while preserving already defined variables by doing:
 
 
Context()->variables->add(x=>'Real',y=>'Real',z=>'Real');
 
 
You can add any number of real or complex variables in this manner, just be careful that your variable names don't interfere with names of other defined objects. You may also create vector-valued variables, or variables of nearly any MathObject? type. For example:
 
 
Context()->variables->set(r=>'Vector3D');
 
Context()->variables->set(r=>Vector(1,2,3,4));
 
 
You can set variable limits like this:
 
 
Context()->variables->set(x=>{limits=>[-1,1]});
 
 
The limits can also be set at the time the variable is created, as follows:
 
 
Context()->variables->add(x => ~['Real',limits=>[-1,1]]);
 
 
which creates a real variable x with limits from -1 to 1.
 
 
==== (5) Strings ====
 
 
The list of predefined strings is:
 
* infinity,
 
* inf,
 
* NONE,
 
* DNE.
 
 
The strings listed in a context indicate allowed responses by students even though
 
the responses might not be correct.
 
If a string is in the context then entering the string will not trigger an error (even if it
 
is not the correct answer). However the student enters a string such as 'undefined' which is not
 
listed in the context then an error message: " 'undefined' is not defined in this context" is returned.
 
 
You can add strings to your context as follows:
 
 
The following command adds string 'True', and makes 'T' and alias for 'True'.
 
 
Context()->strings->add(True=>{},T=>{alias=>'True'});
 
 
The following line defines the string 'Continuous' in the current context:
 
 
Context()->strings("Continuous"=>{});
 
 
This sort of thing is useful for writing problems in which the student must enter text. Be sure here to provide sensible aliases for equivalent terms which students may use. Another good practice is to define strings for incorrect answers which students are likely to enter.
 
 
Another option for use on strings allows you to specify whether or not WebWork should be sensitive to uppercase/lowercase letters. By default WebWork is case insensitive with respect to any string which it recognizes.
 
 
To change this for a String, the caseSensitive flag must be specified when the String is added to the Context:
 
 
Context()->strings->add(True=>{caseSensitive=>1});
 
 
 
==== (6) Lists ====
 
   
 
This section and the next section 'Parens' are closely related.
 
This section and the next section 'Parens' are closely related.
Line 155: Line 110:
   
 
Next we'll discuss how to modify the type of parentheses used with the various objects.
 
Next we'll discuss how to modify the type of parentheses used with the various objects.
 
==== (7) Parens ====
 
   
 
WebWork recognizes the full range of parentheses types, as explained above (e.g., (, <, [, { ). But by default their meanings are dependent on the context. You can change how this works.
 
WebWork recognizes the full range of parentheses types, as explained above (e.g., (, <, [, { ). But by default their meanings are dependent on the context. You can change how this works.
Line 164: Line 117:
 
Context()->parens->set('('=>{type=>'Vector'});
 
Context()->parens->set('('=>{type=>'Vector'});
   
  +
=== More about Variables ===
   
==== (8) Flags ====
+
=== More about Constants ===
   
A discussion of the context flags can be found under [[ContextFlags]]. The point to emphasize here is that to change the context flags in your context do, e.g.,
 
  +
The list of predefined constants is e, pi, i, j, k. The constant i denotes sqrt(-1) in Context("Complex"), denotes the vector <1,0> in Context("Vector2D"), and denotes the vector <1,0,0> in Context("Vector"), Context("Matrix"), and Context("Point"). The constant i is undefined outside of those contexts. The constants j and k are <0,1,0> and <0,0,1>, respectively, in Context("Vector") and Context("Matrix"). The constant j is <0,1> in Context("Vector2D"), and k is undefined there. The constants i, j and k are undefined outside of the contexts described above.
   
Context()->flags->set(
+
Context()->constants->set(i => {TeX=>'\boldsymbol{i}', perl=>'i'});
tolerance => 0.0001,
+
Context()->constants->remove("k");
tolType => 'absolute',
+
Context()->constants->set(R => {TeX => '{\bf R}'});
);
+
  +
=== Adding New Functions ===
  +
  +
=== Adding New Operators ===
   
There are other ways to manipulate the context as well. For example, some function calls change the context:
 
  +
=== Error Messages ===
   
Parser::Number::NoDecimals(Context());
 
  +
=== Course-Wide Customization ===
   
Also, some macro files provide methods for changing the context:
 
   
loadMacros("contextLimitedPowers.pl");
 
Context()->operators->set(@LimitedPowers::OnlyIntegers);
 
   
  +
<!--
 
=== Part II. Create Your Own Context ===
 
=== Part II. Create Your Own Context ===
   
Line 228: Line 180:
   
 
Note that when it comes to answer checking (discussed elsewhere), context checked is the one where the object was created, not the currently active one (when they differ). This means you can create an object, change the context, then create another one in order to get answer checkers from two different contexts.
 
Note that when it comes to answer checking (discussed elsewhere), context checked is the one where the object was created, not the currently active one (when they differ). This means you can create an object, change the context, then create another one in order to get answer checkers from two different contexts.
  +
-->
   
 
===See also===
 
===See also===
   
[[IntroductionToContexts]]
 
  +
* [[Introduction to Contexts]]
  +
* [[Context flags]]
  +
* [[Reduction rules for MathObject Formulas]]
  +
* [[Context Operator Table]]
  +
* [[Common Contexts]]
   
[[ModifyingContexts]]
 
  +
<br>
   
 
[[Category:Contexts]]
 
[[Category:Contexts]]

Revision as of 13:16, 12 August 2012

Advanced Context Modifications

The Introduction to Contexts describes how to make basic modifications to a Context's variables, constants, strings, flags, functions, operators, and reduction rules. Here we will describe more advanced modifications and techniques involving the Context.

Number Formats

Real numbers are stored using a format that retains about 16 or 17 significant digits, making computations very accurate in most situations. When a number is displayed, you probably don't want to see all 17 digits (that would make a vector in three-space take up around 35 characters, for example). To make answers easier to read, MathObjects usually display only 6 significant digits. You can change the format used, however, to suit your needs. The format is determined by the Context()->{format}{number}, which is a printf-style string indicating how real numbers should be formatted for display.

The format always should begin with % and end with one of f, e, or g, possibly followed by #. Here, f means fixed-point notation (e.g. 452.116), e means exponential notation (e.g, 3.578E-5), and g means use the form most appropriate for the magnitude of the number. Between the % and the letter you can (optionally) include .n where n is the number of decimal digits to use for the number. If the format ends in #, then trailing zeros are removed after the number is formatted. (More sophisticated formats are possible, but this describes the basics.)

   Context()->{format}{number} = "%.2f";    # format numbers using 2-place decimals (e.g., for currency values).
   Context()->{format}{number} = "%.4f#";   # format numbers using 4-place decimals, but remove trailing zeros, if any.

The default format is "%g".

The Context also includes information about what should count as a number when an answer is parsed. There are two patterns for this, a signed number and an unsigned number. The latter is what is used in parsing numbers (and the sign is treated as unary minus); former is used in the Value::matchNumber() function. These are stored in the Context()->{pattern} hash; the default values are:

     Context()->{pattern}{number} = '(?:\d+(?:\.\d*)?|\.\d+)(?:E[-+]?\d+)?';
     Context()->{pattern}{signedNumber} = '[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:E[-+]?\d+)?';

These are fairly complicated regular expressions that match the usual fixe-point and exponential notation for numbers in WeBWorK. It is possible to change these patterns to handle things like commas instead of decimals for European usage, or to allow commas every three digits. Note, however, that you would need to include a NumberCheck routine that would translate the special format into the required internal format. For example, this allows you to enter numbers as hexadecimal values:

   #
   #  Numbers in hexadecimal
   #
   Context()->{pattern}{number} = '[0-9A-F]+'; 
   Context()->{pattern}{signedNumber = '[-+]?[0-9A-F]+';
   Context()->flags->set(NumberCheck => sub {
     my $self = shift;                              # the Number object
     $self->{value} = hex($self->{value_string});   # convert hex to decimal via perl hex() function
     $self->{isOne} = ($self->{value} == 1);        # set marker indicating if the value is 1
     $self->{isZero} = ($self->{value} == 0);       # set marker indicating if the value is 0
   });
   Context()->update;

Note that after changing the pattern you must call Context()->update to remake the tokenization patterns used by the Context.

Here is an example that lets you use commas in your numbers:

   #
   # Allow commas every three digits in numbers
   #
   Context()->{pattern}{number} = '(:?(:?\d{1,3}(:?\,\d{3})+|\d+)(?:\.\d*)?|\.\d+)(?:E[-+]?\d+)?';
   Context()->{pattern}{signedNumber} = '[-+]?(:?(:?\d{1,3}(:?\,\d{3})+|\d+)(?:\.\d*)?|\.\d+)(?:E[-+]?\d+)?';
   Context()->flags->set(NumberCheck => sub {
     my $self = shift;                              # the Number object
     my $value = $self->{value_string};             # the original string
     $value =~ s/,//g;                              # remove commas
     $self->{value} = $value + 0;                   # make sure it is converted to a number
     $self->{isOne} = ($self->{value} == 1);        # set marker indicating if the value is 1
     $self->{isZero} = ($self->{value} == 0);       # set marker indicating if the value is 0
   });
   Context()->update;

If you want to make the numbers display with commas, then you will need to subclass the Value::Real object and override the string() and TeX() methods to insert the commas again, and then tie your new class into the Context()->{value}{Real} value. For example, in addition to the changes above, you might do

   #
   #  Subclass the Value::Real class and override its string() and TeX()
   #  methods to insert commas back into the output
   #
   package my::Real;
   our @ISA = ('Value::Real');    # subclass of this Value::Real
   
   sub string {
     my $self = shift; my $x = $self->SUPER::string(@_);  # get the original string output
     my ($n,@rest) = split(/([.E])/,$x,1);                # break it into the integer part and the rest
     while ($n =~ m/[0-9]{4}(,|$)/)                       # add commas as needed
       {$n =~ s/([0-9])([0-9]{3})(,|$)/$1,$2$3/}
     return join("",$n,@rest);                            # return the final string
   }
   
   sub TeX {
     my $self = shift;
     my $n = $self->SUPER::TeX(@_);     # original TeX uses string(), so commas are already there
     $n =~ s/,/{,}/g;                   # just make sure they have the correct spacing
     return $n;
   }
   
   package main;    # end of package my::Real;
   
   Context()->{value}{Real} = "my::Real";    # make the Context use my::Real rather then Value::Real
   Context()->{format}{number} = "%f#";      # format using "f" rather than "g", so no exponential notation

This could be put into a separate macro file that you could load into your problems whenever it is needed. See Creating Custom Contexts for details.


Lists and Delimiters

This section and the next section 'Parens' are closely related. WebWork considers the following objects to be types of lists:

  • Point,
  • Vector,
  • Matrix,
  • List,
  • Interval,
  • Set,
  • Union,
  • AbsoluteValue.

The most common modification made to lists are to which type of parentheses is used to enclose them. The purpose of the following description is meant to make you aware of how the various parenthesis types are used by default.

  • Points by default look like e.g. (3,4).
  • Vectors by default look like e.g., <3,4,5>.
  • Matrix objects by default look like ~[[2,3],[2,3]].
  • A list by default looks like 3, 4, 5. An interval by default looks like (0,9), 0,9), etc.
  • A set by default looks like {3,4,5}.
  • A union by default looks like (-infinity,0? U (5,7].
  • Absolute value by default looks like |-5|.

Next we'll discuss how to modify the type of parentheses used with the various objects.

WebWork recognizes the full range of parentheses types, as explained above (e.g., (, <, [, { ). But by default their meanings are dependent on the context. You can change how this works.

For example, this command will cause Vector objects to look like (3,4,5) instead of <3,4,5>:

Context()->parens->set('('=>{type=>'Vector'});

More about Variables

More about Constants

The list of predefined constants is e, pi, i, j, k. The constant i denotes sqrt(-1) in Context("Complex"), denotes the vector <1,0> in Context("Vector2D"), and denotes the vector <1,0,0> in Context("Vector"), Context("Matrix"), and Context("Point"). The constant i is undefined outside of those contexts. The constants j and k are <0,1,0> and <0,0,1>, respectively, in Context("Vector") and Context("Matrix"). The constant j is <0,1> in Context("Vector2D"), and k is undefined there. The constants i, j and k are undefined outside of the contexts described above.

Context()->constants->set(i => {TeX=>'\boldsymbol{i}', perl=>'i'});
Context()->constants->remove("k");
Context()->constants->set(R => {TeX => '{\bf R}'});

Adding New Functions

Adding New Operators

Error Messages

Course-Wide Customization

See also