[system] / trunk / pg / lib / Value.pm Repository:
ViewVC logotype

View of /trunk/pg/lib/Value.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2669 - (download) (as text) (annotate)
Sun Aug 22 15:42:50 2004 UTC (15 years, 5 months ago) by dpvc
File size: 14534 byte(s)
Made the granularity of the test-point intervals be a parameter that
can be set on a global or variable-by-variable basis, so this is now
controlable from the .pg file.  For example:

            Context("Numeric")->variables->are(
              k=>{limits=>[1,10], resolution=>1},
              x=>{limits=>[-2,2], granularity=>1000},
            );

will make k be a variable that will only take on integer values
between 1 and 10, and x a variable that will take on one of 1000
different values evenly spaced between -2 and 2 (so resolution is
4/1000 in this case).

These parameters can also be set for an individual formula:

           $f = Formula("k^2-1");
           $f->{resolution} = 1;
           $f->{limits} = [0,10];

    1 package Value;
    2 my $pkg = 'Value';
    3 use vars qw($context $defaultContext %Type);
    4 use strict;
    5 
    6 #############################################################
    7 #
    8 #  Initialize the context
    9 #
   10 
   11 use Value::Context;
   12 
   13 $defaultContext = Value::Context->new(
   14   lists => {
   15     'Point'  => {open => '(', close => ')'},
   16     'Vector' => {open => '<', close => '>'},
   17     'Matrix' => {open => '[', close => ']'},
   18     'List'   => {open => '(', close => ')'},
   19   },
   20   flags => {
   21     #
   22     #  For vectors:
   23     #
   24     ijk => 0,  # print vectors as <...>
   25     #
   26     #  word to use for infinity
   27     #
   28     infiniteWord => 'infinity',
   29     #
   30     #  For fuzzy reals:
   31     #
   32     useFuzzyReals => 1,
   33     tolerance    => 1E-4,
   34     tolType      => 'relative',
   35     zeroLevel    => 1E-14,
   36     zeroLevelTol => 1E-12,
   37     #
   38     #  For functions
   39     #
   40     limits      => [-2,2],
   41     num_points  => 5,
   42     granularity => 1/1000,
   43     resolution  => undef,
   44   },
   45 );
   46 
   47 $context = \$defaultContext;
   48 
   49 
   50 #
   51 #  Precedence of the various types
   52 #    (They will be promoted upward automatically when needed)
   53 #
   54 $$context->{precedence} = {
   55    'Number'   =>  0,
   56    'Real'     =>  1,
   57    'Infinity' =>  2,
   58    'Complex'  =>  3,
   59    'Point'    =>  4,
   60    'Vector'   =>  5,
   61    'Matrix'   =>  6,
   62    'List'     =>  7,
   63    'Interval' =>  8,
   64    'Union'    =>  9,
   65    'String'   => 10,
   66    'Formula'  => 11,
   67    'special'  => 12,
   68 };
   69 
   70 #
   71 #  Binding of perl operator to class method
   72 #
   73 $$context->{method} = {
   74    '+'   => 'add',
   75    '-'   => 'sub',
   76    '*'   => 'mult',
   77    '/'   => 'div',
   78    '**'  => 'power',
   79    '.'   => '_dot',  # see _dot below
   80    'x'   => 'cross',
   81    '<=>' => 'compare',
   82    'cmp' => 'cmp',
   83 };
   84 
   85 $$context->{pattern}{infinite} = '[-+]?inf(?:inity)?';
   86 $$context->{pattern}{infinity} = '\+?inf(?:inity)?';
   87 $$context->{pattern}{-infinity} = '-inf(?:inity)?';
   88 
   89 push(@{$$context->{data}{values}},'method','precedence');
   90 
   91 #############################################################
   92 
   93 #
   94 #  Check if a value is a number, complex, etc.
   95 #
   96 sub matchNumber   {my $n = shift; $n =~ m/^$$context->{pattern}{signedNumber}$/i}
   97 sub matchInfinite {my $n = shift; $n =~ m/^$$context->{pattern}{infinite}$/i}
   98 sub isReal    {class(shift) eq 'Real'}
   99 sub isComplex {class(shift) eq 'Complex'}
  100 sub isFormula {
  101   my $v = shift;
  102   return class($v) eq 'Formula' ||
  103          (ref($v) && ref($v) ne 'ARRAY' && $v->{isFormula});
  104 }
  105 sub isValue   {
  106   my $v = shift;
  107   return (ref($v) || $v) =~ m/^Value::/ ||
  108          (ref($v) && ref($v) ne 'ARRAY' && $v->{isValue});
  109 }
  110 
  111 sub isNumber {
  112   my $n = shift;
  113   return $n->{tree}->isNumber if isFormula($n);
  114   return isReal($n) || isComplex($n) || matchNumber($n);
  115 }
  116 
  117 sub isRealNumber {
  118   my $n = shift;
  119   return $n->{tree}->isRealNumber if isFormula($n);
  120   return isReal($n) || matchNumber($n);
  121 }
  122 
  123 #
  124 #  Convert non-Value objects to Values, if possible
  125 #
  126 sub makeValue {
  127   my $x = shift;
  128   return $x if ref($x);
  129   return Value::Real->make($x) if matchNumber($x);
  130   if (matchInfinite($x)) {
  131     my $I = Value::Infinity->new();
  132     $I = $I->neg if $x =~ m/^$$Value::context->{pattern}{-infinity}$/;
  133     return $I;
  134   }
  135   if ($Parser::installed) {return $x unless $$Value::context->{strings}{$x}}
  136   return Value::String->make($x);
  137 }
  138 
  139 #
  140 #  Get a printable version of the class of an object
  141 #
  142 sub showClass {
  143   my $value = makeValue(shift);
  144   return "'".$value."'" unless Value::isValue($value);
  145   my $class = class($value);
  146   return showType($value) if ($class eq 'List');
  147   $class .= ' Number' if $class =~ m/^(Real|Complex)$/;
  148   $class .= ' of Intervals' if $class eq 'Union';
  149   $class = 'Word' if $class eq 'String';
  150   return 'a Formula that returns '.showType($value->{tree}) if ($class eq 'Formula');
  151   return 'an '.$class if $class =~ m/^[aeio]/i;
  152   return 'a '.$class;
  153 }
  154 
  155 #
  156 #  Get a printable version of the type of an object
  157 #
  158 sub showType {
  159   my $value = shift;
  160   my $type = $value->type;
  161   if ($type eq 'List') {
  162     my $ltype = $value->typeRef->{entryType}{name};
  163     if ($ltype && $ltype ne 'unknown') {
  164       $ltype =~ s/y$/ie/;
  165       $type .= ' of '.$ltype.'s';
  166     }
  167   }
  168   return 'a Word' if $type eq 'String';
  169   return 'a Complex Number' if $value->isComplex;
  170   return 'an '.$type if $type =~ m/^[aeio]/i;
  171   return 'a '.$type;
  172 }
  173 
  174 #
  175 #  Return a string describing a value's type
  176 #
  177 sub getType {
  178   my $equation = shift; my $value = shift;
  179   my $strings = $equation->{context}{strings};
  180   if (ref($value) eq 'ARRAY') {
  181     return 'Interval' if ($value->[0] =~ m/^[(\[]$/ && $value->[-1] =~ m/^[)\]]$/);
  182     my ($type,$ltype);
  183     foreach my $x (@{$value}) {
  184       $type = getType($equation,$x);
  185       if ($type eq 'value') {
  186         $type = $x->type if $x->class eq 'Formula';
  187         $type = 'Number' if $x->class eq 'Complex' || $type eq 'Complex';
  188       }
  189       $ltype = $type if $ltype eq '';
  190       return 'List' if $type ne $ltype;
  191     }
  192     return 'Point' if $ltype eq 'Number';
  193     return 'Matrix' if $ltype =~ m/Point|Matrix/;
  194     return 'List';
  195   }
  196   elsif (Value::isFormula($value)) {return 'Formula'}
  197   elsif (Value::class($value) eq 'Infinity') {return 'Infinity'}
  198   elsif (Value::isReal($value)) {return 'Number'}
  199   elsif (Value::isValue($value)) {return 'value'}
  200   elsif (ref($value)) {return 'unknown'}
  201   elsif (defined($strings->{$value})) {return 'String'}
  202   elsif (Value::isNumber($value)) {return 'Number'}
  203   return 'unknown';
  204 }
  205 
  206 #
  207 #  Get a string describing a value's type,
  208 #    and convert the value to a Value object (if needed)
  209 #
  210 sub getValueType {
  211   my $equation = shift; my $value = shift;
  212   my $type = Value::getType($equation,$value);
  213   if ($type eq 'String') {$type = $Value::Type{string}}
  214   elsif ($type eq 'Number') {$type = $Value::Type{number}}
  215   elsif ($type eq 'Infinity') {$type = $Value::Type{infinity}}
  216   elsif ($type eq 'value' || $type eq 'Formula') {$type = $value->typeRef}
  217   elsif ($type eq 'unknown') {
  218     $equation->Error("Can't convert ".Value::showClass($value)." to a constant");
  219   } else {
  220     $type = 'Value::'.$type, $value = $type->new(@{$value});
  221     $type = $value->typeRef;
  222   }
  223   return ($value,$type);
  224 }
  225 
  226 #
  227 #  Convert a list of values to a list of formulas (called by Parser::Value)
  228 #
  229 sub toFormula {
  230   my $formula = shift;
  231   my $processed = 0;
  232   my @f = (); my $vars = {};
  233   foreach my $x (@_) {
  234     if (isFormula($x)) {
  235       $formula->{context} = $x->{context}, $processed = 1 unless $processed;
  236       $formula->{variables} = {%{$formula->{variables}},%{$x->{variables}}};
  237       push(@f,$x->{tree}->copy($formula));
  238     } else {
  239       push(@f,Parser::Value->new($formula,$x));
  240     }
  241   }
  242   return (@f);
  243 }
  244 
  245 #
  246 #  Convert a list of values (and open and close parens)
  247 #    to a formula whose type is the list type associated with
  248 #    the parens.  If the formula is constant, evaluate it.
  249 #
  250 sub formula {
  251   my $self = shift; my $values = shift;
  252   my $class = $self->class;
  253   my $list = $$context->lists->get($class);
  254   my $open = $list->{'open'};
  255   my $close = $list->{'close'};
  256   my $paren = $open; $paren = 'list' if $class eq 'List';
  257   my $formula = Value::Formula->blank;
  258   my @coords = Value::toFormula($formula,@{$values});
  259   $formula->{tree} = Parser::List->new($formula,[@coords],0,
  260      $formula->{context}{parens}{$paren},$coords[0]->typeRef,$open,$close);
  261   $formula->{autoFormula} = 1;  # mark that this was generated automatically
  262 #   return $formula->eval if scalar(%{$formula->{variables}}) == 0;
  263   return $formula;
  264 }
  265 
  266 #
  267 #  A shortcut for new() that creates an instance of the object,
  268 #    but doesn't do the error checking.  We assume the data are already
  269 #    known to be good.
  270 #
  271 sub make {
  272   my $self = shift; my $class = ref($self) || $self;
  273   bless {data => [@_]}, $class;
  274 }
  275 
  276 #
  277 #  Return a type structure for the item
  278 #    (includes name, length of vectors, and so on)
  279 #
  280 sub Type {
  281   my $name = shift; my $length = shift; my $entryType = shift;
  282   $length = 1 unless defined $length;
  283   return {name => $name, length => $length, entryType => $entryType,
  284           list => (defined $entryType), @_};
  285 }
  286 
  287 #
  288 #  Some predefined types
  289 #
  290 %Type = (
  291   number   => Value::Type('Number',1),
  292   complex  => Value::Type('Number',2),
  293   string   => Value::Type('String',1),
  294   infinity => Value::Type('Infinity',1),
  295   unknown  => Value::Type('unknown',0,undef,list => 1)
  296 );
  297 
  298 #
  299 #  Return various information about the object
  300 #
  301 sub value {return @{(shift)->{data}}}                  # the value of the object (as an array)
  302 sub data {return (shift)->{data}}                      # the reference to the value
  303 sub length {return (shift)->typeRef->{length}}         # the number of coordinates
  304 sub type {return (shift)->typeRef->{name}}             # the object type
  305 sub entryType {return (shift)->typeRef->{entryType}}   # the coordinate type
  306 #
  307 #  The the full type-hash for the item
  308 #
  309 sub typeRef {
  310   my $self = shift;
  311   return Value::Type($self->class, $self->length, $Value::Type{number});
  312 }
  313 #
  314 #  The Value.pm object class
  315 #
  316 sub class {
  317   my $self = shift; my $class = ref($self) || $self;
  318   $class =~ s/Value:://;
  319   return $class;
  320 }
  321 
  322 #
  323 #  Get an element from a point, vector, matrix, or list
  324 #
  325 sub extract {
  326   my $M = shift; my $i;
  327   while (scalar(@_) > 0) {
  328     return unless Value::isValue($M);
  329     $i = shift; $i-- if $i > 0;
  330     Value::Error("Can't extract element number '$i' (index must be an integer)")
  331       unless $i =~ m/^-?\d+$/;
  332     $M = $M->data->[$i];
  333   }
  334   return $M;
  335 }
  336 
  337 
  338 #
  339 #  Promote an operand to the same precedence as the current object
  340 #
  341 sub promotePrecedence {
  342   my $self = shift; my $other = shift;
  343   my $sprec = $$context->{precedence}{class($self)};
  344   my $oprec = $$context->{precedence}{class($other)};
  345   return (defined($oprec) && $sprec < $oprec) ||
  346     ($sprec > $oprec && $sprec >= $$context->{precedence}{special});
  347 }
  348 
  349 sub promote {shift}
  350 
  351 #
  352 #  Default stub to call when no function is defined for an operation
  353 #
  354 sub nomethod {
  355   my ($l,$r,$flag,$op) = @_;
  356   my $call = $$context->{method}{$op};
  357   if (defined($call) && $l->promotePrecedence($r)) {return $r->$call($l,!$flag)}
  358   my $error = "Can't use '$op' with ".$l->class."-valued operands";
  359   $error .= " (use '**' for exponentiation)" if $op eq '^';
  360   Value::Error($error);
  361 }
  362 
  363 #
  364 #  Stubs for the sub-classes
  365 #
  366 sub add   {nomethod(@_,'+')}
  367 sub sub   {nomethod(@_,'-')}
  368 sub mult  {nomethod(@_,'*')}
  369 sub div   {nomethod(@_,'/')}
  370 sub power {nomethod(@_,'**')}
  371 sub cross {nomethod(@_,'x')}
  372 
  373 #
  374 #  If the right operand is higher precedence, we switch the order.
  375 #
  376 #  If the right operand is also a Value object, we do the object's
  377 #  dot method to combine the two objects of the same class.
  378 #
  379 #  Otherwise, since . is used for string concatenation, we want to retain
  380 #  that.  Since the resulting string is often used in Formula and will be
  381 #  parsed again, we put parentheses around the values to guarantee that
  382 #  the values will be treated as one mathematical unit.  For example, if
  383 #  $f = Formula("1+x") and $g = Formula("y") then Formula("$f/$g") will be
  384 #  (1+x)/y not 1+(x/y), as it would be without the implicit parentheses.
  385 #
  386 sub _dot {
  387   my ($l,$r,$flag) = @_;
  388   return Value::_dot($r,$l,!$flag) if ($l->promotePrecedence($r));
  389   return $l->dot($r,$flag) if (Value::isValue($r));
  390   $l = $l->stringify; $l = '('.$l.')' unless $$Value::context->flag('StringifyAsTeX');
  391   return ($flag)? ($r.$l): ($l.$r);
  392 }
  393 #
  394 #  Some classes override this
  395 #
  396 sub dot {
  397   my ($l,$r,$flag) = @_;
  398   my $tex = $$Value::context->flag('StringifyAsTeX');
  399   $l = $l->stringify; $l = '('.$l.')' if $tex;
  400   if (ref($r)) {$r = $r->stringify; $r = '('.$l.')' if $tex}
  401   return ($flag)? ($r.$l): ($l.$r);
  402 }
  403 
  404 #
  405 #  Compare the values of the objects
  406 #    (list classes should replace this)
  407 #
  408 sub compare {
  409   my ($l,$r,$flag) = @_;
  410   if ($l->promotePrecedence($r)) {return $r->compare($l,!$flag)}
  411   return $l->value <=> $r->value;
  412 }
  413 
  414 #
  415 #  Compare the values as strings
  416 #
  417 sub cmp {
  418   my ($l,$r,$flag) = @_;
  419   if ($l->promotePrecedence($r)) {return $r->compare($l,!$flag)}
  420   $l = $l->stringify; $r = $r->stringify if Value::isValue($r);
  421   if ($flag) {my $tmp = $l; $l = $r; $r = $tmp}
  422   return $l cmp $r;
  423 }
  424 
  425 #
  426 #  Generate the various output formats
  427 #  (can be replaced by sub-classes)
  428 #
  429 sub stringify {
  430   my $self = shift;
  431   return $self->TeX() if $$Value::context->flag('StringifyAsTeX');
  432   $self->string;
  433 }
  434 sub string {shift->value}
  435 sub TeX {shift->string(@_)}
  436 #
  437 #  For perl, call the appropriate constructor around the objects data
  438 #
  439 sub perl {
  440   my $self = shift; my $parens = shift; my $matrix = shift;
  441   my $class = $self->class; my $mtype = $class eq 'Matrix';
  442   my $perl; my @p = ();
  443   foreach my $x (@{$self->data}) {
  444     if (Value::isValue($x)) {push(@p,$x->perl(0,$mtype))} else {push(@p,$x)}
  445   }
  446   @p = ("'".$self->{open}."'",@p,"'".$self->{close}."'") if $class eq 'Interval';
  447   if ($matrix) {
  448     $perl = '['.join(',',@p).']';
  449   } else {
  450     $perl = $class.'('.join(',',@p).')';
  451     $perl = '('.$perl.')' if $parens == 1;
  452   }
  453   return $perl;
  454 }
  455 
  456 #
  457 #  Stubs for when called by Parser
  458 #
  459 sub eval {shift}
  460 sub reduce {shift}
  461 
  462 sub ijk {
  463   Value::Error("Can't use method 'ijk' with objects of type '".(shift)->class."'");
  464 }
  465 
  466 #
  467 #  Report an error
  468 #
  469 sub Error {
  470   my $message = shift;
  471   $$context->setError($message,'');
  472   die $message . traceback() if $$context->{debug};
  473   die $message . getCaller();
  474 }
  475 
  476 #
  477 #  Try to locate the line and file where the error occurred
  478 #
  479 sub getCaller {
  480   my $frame = 2;
  481   while (my ($pkg,$file,$line,$subname) = caller($frame++)) {
  482     return " at line $line of $file\n"
  483       unless $pkg =~ /^(Value|Parser)/ ||
  484              $subname =~ m/^(Value|Parser).*(new|call)$/;
  485   }
  486   return "";
  487 }
  488 
  489 #
  490 #  For debugging
  491 #
  492 sub traceback {
  493   my $frame = 2;
  494   my $trace = '';
  495   while (my ($pkg,$file,$line,$subname) = caller($frame++))
  496     {$trace .= " in $subname at line $line of $file\n"}
  497   return $trace;
  498 }
  499 
  500 ###########################################################################
  501 #
  502 #  Load the sub-classes.
  503 #
  504 
  505 use Value::Real;
  506 use Value::Complex;
  507 use Value::Infinity;
  508 use Value::Point;
  509 use Value::Vector;
  510 use Value::Matrix;
  511 use Value::List;
  512 use Value::Interval;
  513 use Value::Union;
  514 use Value::String;
  515 use Value::Formula;
  516 
  517 use Value::WeBWorK;  # stuff specific to WeBWorK
  518 
  519 ###########################################################################
  520 
  521 use vars qw($installed);
  522 $Value::installed = 1;
  523 
  524 ###########################################################################
  525 ###########################################################################
  526 #
  527 #    To Do:
  528 #
  529 #  Make Complex class include more of Complex1.pm
  530 #  Make better interval comparison
  531 #
  532 ###########################################################################
  533 
  534 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9