File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.12: download - view: text, annotated - select for diffs
Thu Dec 20 22:36:35 2001 UTC (22 years, 4 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
filename changes mostly.

    1: # The LearningOnline Network with CAPA
    2: # Dynamic plot
    3: #
    4: # $Id: lonplot.pm,v 1.12 2001/12/20 22:36:35 matthew Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # 12/15/01 Matthew
   29: # 12/18 12/19 12/20 Matthew
   30: package Apache::lonplot;
   31: 
   32: use strict;
   33: use Apache::File;
   34: use Apache::response;
   35: use Apache::lonxml;
   36: 
   37: use Digest::MD5 qw(md5_base64);
   38: 
   39: sub BEGIN {
   40:   &Apache::lonxml::register('Apache::lonplot',('plot'));
   41: }
   42: 
   43: ## 
   44: ## Description of data structures:
   45: ##
   46: ##  %plot       %key    %axis
   47: ## --------------------------
   48: ##  height      title   color
   49: ##  width       box     xmin
   50: ##  bgcolor     pos     xmax
   51: ##  fgcolor             ymin
   52: ##  transparent         ymax
   53: ##  grid
   54: ##  border
   55: ##  font
   56: ##
   57: ##  @labels: $labels[$i] = \%label
   58: ##           %label: text, xpos, ypos, justify
   59: ## 
   60: ##  @curves: $curves[$i] = \%curve
   61: ##        %curve: name, linestyle, ( function | data )
   62: ##
   63: ##  $curves[$i]->{'data'} = [ [x1,x2,x3,x4],
   64: ##                            [y1,y2,y3,y4] ]
   65: ##
   66: ##------------------------------------------------------------
   67: ##
   68: ## Tests used in checking the validitity of input
   69: ##
   70: my $int_test       = sub {$_[0]=~s/\s+//g;$_[0]=~/^\d+$/};
   71: my $real_test      = sub {$_[0]=~s/\s+//g;$_[0]=~/^[+-]?\d*\.?\d*$/};
   72: my $color_test     = sub {$_[0]=~s/\s+//g;$_[0]=~/^x[\da-f]{6}$/};
   73: my $onoff_test     = sub {$_[0]=~/^(on|off)$/};
   74: my $key_pos_test   = sub {$_[0]=~/^(top|bottom|right|left|outside|below)+$/};
   75: my $sml_test       = sub {$_[0]=~/^(small|medium|large)$/};
   76: my $linestyle_test = sub {$_[0]=~/^(lines|linespoints|dots|points|steps)$/};
   77: my $words_test     = sub {$_[0]=~s/\s+/ /g;$_[0]=~/^(\w+ ?)+$/};
   78: ##
   79: ## Default values for attributes of elements
   80: ##
   81: my %plot_defaults = 
   82:     (
   83:      height       => {default => 200,       test => $int_test   },
   84:      width        => {default => 200,       test => $int_test   },
   85:      bgcolor      => {default => 'xffffff', test => $color_test },
   86:      fgcolor      => {default => 'x000000', test => $color_test },
   87:      transparent  => {default => 'off',     test => $onoff_test },
   88:      grid         => {default => 'off',     test => $onoff_test },
   89:      border       => {default => 'on',      test => $onoff_test },
   90:      font         => {default => 'medium',  test => $sml_test   }
   91:      );
   92: 
   93: my %key_defaults = 
   94:     (
   95:      title => { default => '',          test => $words_test   },
   96:      box   => { default => 'off',       test => $onoff_test   },
   97:      pos   => { default => 'top right', test => $key_pos_test }
   98:      );
   99: 
  100: my %label_defaults = 
  101:     (
  102:      xpos    => {default => 0,         test => $real_test     },
  103:      ypos    => {default => 0,         test => $real_test     },
  104:      justify => {default => 'left',    
  105:                  test => sub {$_[0]=~/^(left|right|center)$/} }
  106:      );
  107: 
  108: my %axis_defaults = 
  109:     (
  110:      color     => {default => 'x000000', test => $color_test},
  111:      xmin      => {default => '-10.0',   test => $real_test },
  112:      xmax      => {default => ' 10.0',   test => $real_test },
  113:      ymin      => {default => '-10.0',   test => $real_test },
  114:      ymax      => {default => ' 10.0',   test => $real_test }
  115:      );
  116: 
  117: my %curve_defaults = 
  118:     (
  119:      color     => {default => 'x000000', test => $color_test             },
  120:      name      => {default => 'x000000', test => sub {1} },#sub {$_[0]=~/^[\w ]*$/} },
  121:      linestyle => {default => 'lines',   test => $linestyle_test         }
  122:      );
  123: 
  124: ##
  125: ## End of defaults
  126: ##
  127: my (%plot,%key,%axis,$title,$xlabel,$ylabel,@labels,@curves);
  128: 
  129: sub start_plot {
  130:     %plot    = undef;   %key     = undef;   %axis   = undef; 
  131:     $title   = undef;   $xlabel  = undef;   $ylabel = undef;
  132:     $#labels = -1;      $#curves = -1;
  133:     #
  134:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  135:     my $result='';
  136:     &Apache::lonxml::register('Apache::lonplot',
  137: 	     ('title','xlabel','ylabel','key','axis','label','curve'));
  138:     push (@Apache::lonxml::namespace,'plot');
  139:     ## Always evaluate the insides of the <plot></plot> tags
  140:     my $inside = &Apache::lonxml::get_all_text("/plot",$$parser[-1]);
  141:     $inside=&Apache::run::evaluate($inside,$safeeval,$$parstack[-1]);
  142:     &Apache::lonxml::newparser($parser,\$inside);
  143:     ##-------------------------------------------------------
  144:     &get_attributes(\%plot,\%plot_defaults,$parstack,$safeeval,
  145: 		    $tagstack->[-1]);
  146:     if ($target eq 'web') {
  147:     }
  148:     return '';
  149: }
  150: 
  151: sub end_plot {
  152:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  153:     pop @Apache::lonxml::namespace;
  154:     &Apache::lonxml::deregister('Apache::lonplot',
  155: 	('title','xlabel','ylabel','key','axis','label','curve'));
  156:     my $result = '';
  157:     if ($target eq 'web') {
  158: 	## Determine filename -- Need to use the 'id' thingy that Gerd 
  159: 	## mentioned.
  160: 	my $tmpdir = '/home/httpd/perl/tmp/';
  161: 	my $filename = $ENV{'user.name'}.'_'.$ENV{'user.domain'}.
  162: 	    '_plot.data';
  163: 	## Write the plot description to the file
  164: 	my $fh=Apache::File->new(">$tmpdir$filename");
  165: 	$result .= '<pre>';
  166: 	$result .= $filename.$/;
  167: 	print $fh &write_gnuplot_file();
  168: 	$result .= '</pre>'.$/;
  169: 	## return image tag for the plot
  170: 	$result .= <<"ENDIMAGE";
  171: <img src = "/cgi-bin/plot.gif?$filename" 
  172:      alt = "/cgi-bin/plot.gif?$filename" />
  173: ENDIMAGE
  174:     }
  175:     return $result;
  176: }
  177: 
  178: ##----------------------------------------------------------------- key
  179: sub start_key {
  180:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  181:     my $result='';
  182:     &get_attributes(\%key,\%key_defaults,$parstack,$safeeval,
  183: 		    $tagstack->[-1]);
  184:     if ($target eq 'web') {
  185: 	# This routine should never return anything.
  186:     }
  187:     return $result;
  188: }
  189: 
  190: sub end_key {
  191:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  192:     my $result = '';
  193:     if ($target eq 'web') {
  194: 	# This routine should never return anything.
  195:     }
  196:     return $result;
  197: }
  198: ##------------------------------------------------------------------- title
  199: sub start_title {
  200:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  201:     $title = &Apache::lonxml::get_all_text("/title",$$parser[-1]);
  202:     my $result='';
  203:     if ($target eq 'web') {
  204: 	# This routine should never return anything.
  205:     }
  206:     return $result;
  207: }
  208: 
  209: sub end_title {
  210:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  211:     my $result = '';
  212:     if ($target eq 'web') {
  213: 	# This routine should never return anything.
  214:     }
  215:     return $result;
  216: }
  217: ##------------------------------------------------------------------- xlabel
  218: sub start_xlabel {
  219:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  220:     my $result='';
  221:     $xlabel = &Apache::lonxml::get_all_text("/xlabel",$$parser[-1]);
  222:     if ($target eq 'web') {
  223: 	# This routine should never return anything.
  224:     }
  225:     return $result;
  226: }
  227: 
  228: sub end_xlabel {
  229:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  230:     my $result = '';
  231:     if ($target eq 'web') {
  232: 	# This routine should never return anything.
  233:     }
  234:     return $result;
  235: }
  236: ##------------------------------------------------------------------- ylabel
  237: sub start_ylabel {
  238:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  239:     my $result='';
  240:     $ylabel = &Apache::lonxml::get_all_text("/ylabel",$$parser[-1]);
  241:     if ($target eq 'web') {
  242: 	# This routine should never return anything.
  243:     }
  244:     return $result;
  245: }
  246: 
  247: sub end_ylabel {
  248:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  249:     my $result = '';
  250:     if ($target eq 'web') {
  251: 	# This routine should never return anything.
  252:     }
  253:     return $result;
  254: }
  255: ##------------------------------------------------------------------- label
  256: sub start_label {
  257:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  258:     my $result='';
  259:     my %label;
  260:     &get_attributes(\%label,\%label_defaults,$parstack,$safeeval,
  261: 		    $tagstack->[-1]);
  262:     $label{'text'} = &Apache::lonxml::get_all_text("/label",$$parser[-1]);
  263:     if (! &$words_test($label{'text'})) {
  264: 	# I should probably warn about it, too.
  265: 	$label{'text'} = 'Illegal text';
  266:     }
  267:     push(@labels,\%label);
  268:     if ($target eq 'web') {
  269: 	# This routine should never return anything.
  270:     }
  271:     return $result;
  272: }
  273: 
  274: sub end_label {
  275:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  276:     my $result = '';
  277:     if ($target eq 'web') {
  278: 	# This routine should never return anything.
  279:     }
  280:     return $result;
  281: }
  282: 
  283: ##------------------------------------------------------------------- curve
  284: sub start_curve {
  285:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  286:     my $result='';
  287:     my %curve;
  288:     &get_attributes(\%curve,\%curve_defaults,$parstack,$safeeval,
  289: 		    $tagstack->[-1]);
  290:     push (@curves,\%curve);
  291:     &Apache::lonxml::register('Apache::lonplot',('function','data'));
  292:     push (@Apache::lonxml::namespace,'curve');
  293:     if ($target eq 'web') {
  294: 	# This routine should never return anything.
  295:     }
  296:     return $result;
  297: }
  298: 
  299: sub end_curve {
  300:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  301:     my $result = '';
  302:     pop @Apache::lonxml::namespace;
  303:     &Apache::lonxml::deregister('Apache::lonplot',('function','data'));
  304:     if ($target eq 'web') {
  305: 	# This routine should never return anything.
  306:     }
  307:     return $result;
  308: }
  309: ##------------------------------------------------------------ curve function
  310: sub start_function {
  311:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  312:     my $result='';
  313:     if (exists($curves[-1]->{'data'})) {
  314: 	&Apache::lonxml::warning('Use of <function> precludes use of <data>.  The <data> will be omitted in favor of the <function> declaration.');
  315: 	delete $curves[-1]->{'data'} ;
  316:     }
  317:     $curves[-1]->{'function'} = 
  318: 	&Apache::lonxml::get_all_text("/function",$$parser[-1]);
  319:     if ($target eq 'web') {
  320: 	# This routine should never return anything.
  321:     }
  322:     return $result;
  323: }
  324: 
  325: sub end_function {
  326:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  327:     my $result = '';
  328:     if ($target eq 'web') {
  329: 	# This routine should never return anything.
  330:     }
  331:     return $result;
  332: }
  333: ##------------------------------------------------------------ curve  data
  334: sub start_data {
  335:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  336:     my $result='';
  337:     if (exists($curves[-1]->{'function'})) {
  338: 	&Apache::lonxml::warning('Use of <data> precludes use of <function>.'.
  339:             '  The <function> will be omitted in favor of the <data>'.
  340:             ' declaration.');
  341: 	delete($curves[-1]->{'function'});
  342:     }
  343:     my $datatext = &Apache::lonxml::get_all_text("/data",$$parser[-1]);
  344:     $datatext =~ s/\s+//g;  # No whitespace, numbers must be seperated
  345:                             # by commas
  346:     if ($datatext !~ /^(([+-]?\d*\.?\d*)[, ]?)+$/) {
  347: 	&Apache::lonxml::warning('Malformed data: '.$datatext);
  348: 	$datatext = '';
  349:     }
  350:     # Need to do some error checking on the @data array - 
  351:     # make sure it's all numbers and make sure each array 
  352:     # is of the same length.
  353:     my @data = split /,/,$datatext;
  354:     for (my $i=0;$i<=$#data;$i++) {
  355: 	# Check that it's non-empty
  356: 	# Check that it's a number
  357: 	# Maybe I need a 'debug=on' switch to list the data set
  358: 	#    out in a warning?
  359:     }
  360:     push  @{$curves[-1]->{'data'}},\@data;
  361:     if ($target eq 'web') {
  362: 	# This routine should never return anything.
  363:     }
  364:     return $result;
  365: }
  366: 
  367: sub end_data {
  368:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  369:     my $result = '';
  370:     if ($target eq 'web') {
  371: 	# This routine should never return anything.
  372:     }
  373:     return $result;
  374: }
  375: 
  376: ##------------------------------------------------------------------- axis
  377: sub start_axis {
  378:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  379:     my $result='';
  380:     &get_attributes(\%axis,\%axis_defaults,$parstack,$safeeval,
  381: 		    $tagstack->[-1]);
  382:     if ($target eq 'web') {
  383: 	# This routine should never return anything.
  384:     }
  385:     return $result;
  386: }
  387: 
  388: sub end_axis {
  389:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  390:     my $result = '';
  391:     if ($target eq 'web') {
  392: 	# This routine should never return anything.
  393:     }
  394:     return $result;
  395: }
  396: 
  397: ##------------------------------------------------------------------- misc
  398: sub get_attributes{
  399:     my $values   = shift;
  400:     my $defaults = shift;
  401:     my $parstack = shift;
  402:     my $safeeval = shift;
  403:     my $tag      = shift;
  404:     my $attr;
  405:     foreach $attr (keys %{$defaults}) {
  406: 	$values->{$attr} = 
  407: 	             &Apache::lonxml::get_param($attr,$parstack,$safeeval);
  408: 	if ($values->{$attr} eq '' | !defined($values->{$attr})) {
  409: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
  410: 	    next;
  411: 	}
  412: 	my $test = $defaults->{$attr}->{'test'};
  413: 	if (! &$test($values->{$attr})) {
  414: 	    &Apache::lonxml::warning
  415: 		($tag.':'.$attr.': Bad value.'.'Replacing your value with : '
  416: 		 .$defaults->{$attr}->{'default'} );
  417: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
  418: 	}
  419:     }
  420:     return ;
  421: }
  422: 
  423: sub write_gnuplot_file {
  424:     my $gnuplot_input = '';
  425:     my $curve;
  426:     # Collect all the colors
  427:     my @Colors;
  428:     push @Colors, $plot{'bgcolor'};
  429:     push @Colors, $plot{'fgcolor'}; 
  430:     push @Colors, $axis{'color'};
  431:     push @Colors, $axis{'color'}; 
  432:     foreach $curve (@curves) {
  433: 	push @Colors, ($curve->{'color'} ne '' ? 
  434: 		       $curve->{'color'}       : 
  435: 		       $plot{'fgcolor'}      );
  436:     }
  437:     # set term
  438:     $gnuplot_input .= 'set term gif ';
  439:     $gnuplot_input .= 'transparent ' if ($plot{'transparent'} eq 'on');
  440:     $gnuplot_input .= $plot{'font'} . ' ';
  441:     $gnuplot_input .= 'size '.$plot{'width'}.','.$plot{'height'}.' ';
  442:     $gnuplot_input .= "@Colors\n";
  443:     # grid
  444:     $gnuplot_input .= 'set grid'.$/ if ($plot{'grid'} eq 'on');
  445:     # border
  446:     $gnuplot_input .= ($plot{'border'} eq 'on'?
  447: 		       'set border'.$/           :
  448: 		       'set noborder'.$/         );    # title, xlabel, ylabel
  449:     {
  450:     $gnuplot_input .= <<"ENDLABELS";
  451: set output 
  452: set title  "$title"
  453: set xlabel "$xlabel"
  454: set ylabel "$ylabel"
  455: set xrange \[$axis{'xmin'}:$axis{'xmax'}\]
  456: set yrange \[$axis{'ymin'}:$axis{'ymax'}\]
  457: ENDLABELS
  458:     }
  459:     # Key
  460:     if (defined($key{'pos'})) {
  461: 	$gnuplot_input .= 'set key '.$key{'pos'}.' ';
  462: 	if ($key{'title'} ne '') {
  463: 	    $gnuplot_input .= 'title "'.$key{'title'}.'" ';
  464: 	} 
  465: 	$gnuplot_input .= ($key{'box'} eq 'on' ? 'box ' : 'nobox ').$/;
  466:     } else {
  467: 	$gnuplot_input .= 'set nokey'.$/;
  468:     }    
  469:     # labels
  470:     my $label;
  471:     foreach $label (@labels) {
  472: 	$gnuplot_input .= 'set label "'.$label->{'text'}.'" at '.
  473: 	    $label->{'xpos'}.','.$label->{'ypos'}.' '.$label->{'justify'}.$/ ;
  474:     }
  475:     # curves
  476:     $gnuplot_input .= 'plot ';
  477:     my $datatext = '';
  478:     for (my $i = 0;$i<=$#curves;$i++) {
  479: 	$curve = $curves[$i];
  480: 	$gnuplot_input.= ', ' if ($i > 0);
  481: 	if (exists($curve->{'function'})) {
  482: 	    $gnuplot_input.= 
  483: 		$curve->{'function'}.' title "'.
  484: 		$curve->{'name'}.'" with '.
  485: 		$curve->{'linestyle'};
  486: 	} elsif (exists($curve->{'data'})) {
  487: 	    $gnuplot_input.= '\'-\' title "'.
  488: 		$curve->{'name'}.'" with '.
  489: 		$curve->{'linestyle'};
  490: 	    my @Data = @{$curve->{'data'}};
  491: 	    my @Data0 = @{$Data[0]};
  492: 	    for (my $i =0; $i<=$#Data0; $i++) {
  493: 		my $dataset;
  494: 		foreach $dataset (@Data) {
  495: 		    $datatext .= $dataset->[$i] . ' ';
  496: 		}
  497: 		$datatext .= $/;
  498: 	    }
  499: 	    $datatext .=$/;
  500: 	}
  501:     }
  502:     $gnuplot_input .= $/.$datatext;
  503:     return $gnuplot_input;
  504: }
  505: 
  506: 1;
  507: __END__
  508: 
  509: 
  510: 
  511: 
  512: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>