[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 2579 - (download) (as text) (annotate)
Mon Aug 9 21:38:01 2004 UTC (15 years, 6 months ago) by dpvc
File size: 11668 byte(s)
Significant update to new parser.

New features include:

  Better control over format of vector output (you can now
    specify ijk-format rather than <...> format)

  "Fuzzy" reals, where the relations like == return true when the
    two values are "close enough".  (This is controlable using
    parameters similar to those used in NUM_CMP).

  The fuzzy reals are now used in vectors/points/matrices/complexes/intervals
    and so on so that their relations will also be fuzzy.  E.g.,
    (1E-13,2) == (0,3) will be true, and norm(Vector(0,1E-13)) will
    equal 0.

  The two main portions of the parser (the Parser and Value packages)
    now share a common context object for configuration purposes.

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9