File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.13: download - view: text, annotated - select for diffs
Fri Dec 21 15:27:29 2001 UTC (22 years, 4 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Now should handle missing information relatively cleanly.  I hope.

    1: # The LearningOnline Network with CAPA
    2: # Dynamic plot
    3: #
    4: # $Id: lonplot.pm,v 1.13 2001/12/21 15:27:29 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 => '',        test => $words_test     },
  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: 	##
  159: 	## Make sure we have all the input we need:
  160: 	if (! defined(%plot  )) { &set_defaults(\%plot,\%plot_defaults); }
  161: 	if (! defined(%key   )) {} # No key for this plot 
  162: 	if (! defined(%axis  )) { &set_defaults(\%axis,\%axis_defaults); }
  163: 	if (! defined($title )) {} # No title for this plot 
  164: 	if (! defined($xlabel)) {} # No xlabel for this plot 
  165: 	if (! defined($ylabel)) {} # No ylabel for this plot 
  166: 	if ($#labels < 0) { } # No labels for this plot
  167: 	if ($#curves < 0) { } # This is an error
  168: 	##
  169: 	## Determine filename
  170: 	my $tmpdir = '/home/httpd/perl/tmp/';
  171: 	my $filename = $ENV{'user.name'}.'_'.$ENV{'user.domain'}.
  172: 	    '_'.time.'_'.$$.'_plot.data';
  173: 	## Write the plot description to the file
  174: 	my $fh=Apache::File->new(">$tmpdir$filename");
  175: 	$result .= '<pre>';
  176: 	$result .= $filename.$/;
  177: 	print $fh &write_gnuplot_file();
  178: 	$result .= '</pre>'.$/;
  179: 	## return image tag for the plot
  180: 	$result .= <<"ENDIMAGE";
  181: <img src = "/cgi-bin/plot.gif?$filename" 
  182:      alt = "/cgi-bin/plot.gif?$filename" />
  183: ENDIMAGE
  184:     }
  185:     return $result;
  186: }
  187: 
  188: ##----------------------------------------------------------------- key
  189: sub start_key {
  190:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  191:     my $result='';
  192:     &get_attributes(\%key,\%key_defaults,$parstack,$safeeval,
  193: 		    $tagstack->[-1]);
  194:     if ($target eq 'web') {
  195: 	# This routine should never return anything.
  196:     }
  197:     return $result;
  198: }
  199: 
  200: sub end_key {
  201:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  202:     my $result = '';
  203:     if ($target eq 'web') {
  204: 	# This routine should never return anything.
  205:     }
  206:     return $result;
  207: }
  208: ##------------------------------------------------------------------- title
  209: sub start_title {
  210:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  211:     $title = &Apache::lonxml::get_all_text("/title",$$parser[-1]);
  212:     my $result='';
  213:     if ($target eq 'web') {
  214: 	# This routine should never return anything.
  215:     }
  216:     return $result;
  217: }
  218: 
  219: sub end_title {
  220:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  221:     my $result = '';
  222:     if ($target eq 'web') {
  223: 	# This routine should never return anything.
  224:     }
  225:     return $result;
  226: }
  227: ##------------------------------------------------------------------- xlabel
  228: sub start_xlabel {
  229:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  230:     my $result='';
  231:     $xlabel = &Apache::lonxml::get_all_text("/xlabel",$$parser[-1]);
  232:     if ($target eq 'web') {
  233: 	# This routine should never return anything.
  234:     }
  235:     return $result;
  236: }
  237: 
  238: sub end_xlabel {
  239:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  240:     my $result = '';
  241:     if ($target eq 'web') {
  242: 	# This routine should never return anything.
  243:     }
  244:     return $result;
  245: }
  246: ##------------------------------------------------------------------- ylabel
  247: sub start_ylabel {
  248:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  249:     my $result='';
  250:     $ylabel = &Apache::lonxml::get_all_text("/ylabel",$$parser[-1]);
  251:     if ($target eq 'web') {
  252: 	# This routine should never return anything.
  253:     }
  254:     return $result;
  255: }
  256: 
  257: sub end_ylabel {
  258:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  259:     my $result = '';
  260:     if ($target eq 'web') {
  261: 	# This routine should never return anything.
  262:     }
  263:     return $result;
  264: }
  265: ##------------------------------------------------------------------- label
  266: sub start_label {
  267:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  268:     my $result='';
  269:     my %label;
  270:     &get_attributes(\%label,\%label_defaults,$parstack,$safeeval,
  271: 		    $tagstack->[-1]);
  272:     $label{'text'} = &Apache::lonxml::get_all_text("/label",$$parser[-1]);
  273:     if (! &$words_test($label{'text'})) {
  274: 	# I should probably warn about it, too.
  275: 	$label{'text'} = 'Illegal text';
  276:     }
  277:     push(@labels,\%label);
  278:     if ($target eq 'web') {
  279: 	# This routine should never return anything.
  280:     }
  281:     return $result;
  282: }
  283: 
  284: sub end_label {
  285:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  286:     my $result = '';
  287:     if ($target eq 'web') {
  288: 	# This routine should never return anything.
  289:     }
  290:     return $result;
  291: }
  292: 
  293: ##------------------------------------------------------------------- curve
  294: sub start_curve {
  295:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  296:     my $result='';
  297:     my %curve;
  298:     &get_attributes(\%curve,\%curve_defaults,$parstack,$safeeval,
  299: 		    $tagstack->[-1]);
  300:     push (@curves,\%curve);
  301:     &Apache::lonxml::register('Apache::lonplot',('function','data'));
  302:     push (@Apache::lonxml::namespace,'curve');
  303:     if ($target eq 'web') {
  304: 	# This routine should never return anything.
  305:     }
  306:     return $result;
  307: }
  308: 
  309: sub end_curve {
  310:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  311:     my $result = '';
  312:     pop @Apache::lonxml::namespace;
  313:     &Apache::lonxml::deregister('Apache::lonplot',('function','data'));
  314:     if ($target eq 'web') {
  315: 	# This routine should never return anything.
  316:     }
  317:     return $result;
  318: }
  319: ##------------------------------------------------------------ curve function
  320: sub start_function {
  321:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  322:     my $result='';
  323:     if (exists($curves[-1]->{'data'})) {
  324: 	&Apache::lonxml::warning('Use of <function> precludes use of <data>.  The <data> will be omitted in favor of the <function> declaration.');
  325: 	delete $curves[-1]->{'data'} ;
  326:     }
  327:     $curves[-1]->{'function'} = 
  328: 	&Apache::lonxml::get_all_text("/function",$$parser[-1]);
  329:     if ($target eq 'web') {
  330: 	# This routine should never return anything.
  331:     }
  332:     return $result;
  333: }
  334: 
  335: sub end_function {
  336:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  337:     my $result = '';
  338:     if ($target eq 'web') {
  339: 	# This routine should never return anything.
  340:     }
  341:     return $result;
  342: }
  343: ##------------------------------------------------------------ curve  data
  344: sub start_data {
  345:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  346:     my $result='';
  347:     if (exists($curves[-1]->{'function'})) {
  348: 	&Apache::lonxml::warning('Use of <data> precludes use of <function>.'.
  349:             '  The <function> will be omitted in favor of the <data>'.
  350:             ' declaration.');
  351: 	delete($curves[-1]->{'function'});
  352:     }
  353:     my $datatext = &Apache::lonxml::get_all_text("/data",$$parser[-1]);
  354:     $datatext =~ s/\s+//g;  # No whitespace, numbers must be seperated
  355:                             # by commas
  356:     if ($datatext !~ /^(([+-]?\d*\.?\d*)[, ]?)+$/) {
  357: 	&Apache::lonxml::warning('Malformed data: '.$datatext);
  358: 	$datatext = '';
  359:     }
  360:     # Need to do some error checking on the @data array - 
  361:     # make sure it's all numbers and make sure each array 
  362:     # is of the same length.
  363:     my @data = split /,/,$datatext;
  364:     for (my $i=0;$i<=$#data;$i++) {
  365: 	# Check that it's non-empty
  366: 	# Check that it's a number
  367: 	# Maybe I need a 'debug=on' switch to list the data set
  368: 	#    out in a warning?
  369:     }
  370:     push  @{$curves[-1]->{'data'}},\@data;
  371:     if ($target eq 'web') {
  372: 	# This routine should never return anything.
  373:     }
  374:     return $result;
  375: }
  376: 
  377: sub end_data {
  378:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  379:     my $result = '';
  380:     if ($target eq 'web') {
  381: 	# This routine should never return anything.
  382:     }
  383:     return $result;
  384: }
  385: 
  386: ##------------------------------------------------------------------- axis
  387: sub start_axis {
  388:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  389:     my $result='';
  390:     &get_attributes(\%axis,\%axis_defaults,$parstack,$safeeval,
  391: 		    $tagstack->[-1]);
  392:     if ($target eq 'web') {
  393: 	# This routine should never return anything.
  394:     }
  395:     return $result;
  396: }
  397: 
  398: sub end_axis {
  399:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  400:     my $result = '';
  401:     if ($target eq 'web') {
  402: 	# This routine should never return anything.
  403:     }
  404:     return $result;
  405: }
  406: 
  407: ##----------------------------------------------------------- set_defaults
  408: sub set_defaults {
  409:     my $var      = shift;
  410:     my $defaults = shift;
  411:     my $key;
  412:     foreach $key (keys %$defaults) {
  413: 	$var->{$key} = $defaults->{$key}->{'default'};
  414:     }
  415: }
  416: 
  417: ##------------------------------------------------------------------- misc
  418: sub get_attributes{
  419:     my $values   = shift;
  420:     my $defaults = shift;
  421:     my $parstack = shift;
  422:     my $safeeval = shift;
  423:     my $tag      = shift;
  424:     my $attr;
  425:     foreach $attr (keys %{$defaults}) {
  426: 	$values->{$attr} = 
  427: 	             &Apache::lonxml::get_param($attr,$parstack,$safeeval);
  428: 	if ($values->{$attr} eq '' | !defined($values->{$attr})) {
  429: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
  430: 	    next;
  431: 	}
  432: 	my $test = $defaults->{$attr}->{'test'};
  433: 	if (! &$test($values->{$attr})) {
  434: 	    &Apache::lonxml::warning
  435: 		($tag.':'.$attr.': Bad value.'.'Replacing your value with : '
  436: 		 .$defaults->{$attr}->{'default'} );
  437: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
  438: 	}
  439:     }
  440:     return ;
  441: }
  442: 
  443: sub write_gnuplot_file {
  444:     my $gnuplot_input = '';
  445:     my $curve;
  446:     # Collect all the colors
  447:     my @Colors;
  448:     push @Colors, $plot{'bgcolor'};
  449:     push @Colors, $plot{'fgcolor'}; 
  450:     push @Colors, (defined($axis{'color'})?$axis{'color'}:$plot{'fgcolor'});
  451:     push @Colors, $Colors[-1];  # Redundancy
  452:     foreach $curve (@curves) {
  453: 	push @Colors, ($curve->{'color'} ne '' ? 
  454: 		       $curve->{'color'}       : 
  455: 		       $plot{'fgcolor'}        );
  456:     }
  457:     # set term
  458:     $gnuplot_input .= 'set term gif ';
  459:     $gnuplot_input .= 'transparent ' if ($plot{'transparent'} eq 'on');
  460:     $gnuplot_input .= $plot{'font'} . ' ';
  461:     $gnuplot_input .= 'size '.$plot{'width'}.','.$plot{'height'}.' ';
  462:     $gnuplot_input .= "@Colors\n";
  463:     # grid
  464:     $gnuplot_input .= 'set grid'.$/ if ($plot{'grid'} eq 'on');
  465:     # border
  466:     $gnuplot_input .= ($plot{'border'} eq 'on'?
  467: 		       'set border'.$/           :
  468: 		       'set noborder'.$/         );    # title, xlabel, ylabel
  469:     $gnuplot_input .= "set output\n";
  470:     $gnuplot_input .= "set title  \"$title\"\n"  if (defined($title)) ;
  471:     $gnuplot_input .= "set xlabel \"$xlabel\"\n" if (defined($xlabel));
  472:     $gnuplot_input .= "set ylabel \"$ylabel\"\n" if (defined($ylabel));
  473:     if (defined(%axis)) {
  474: 	$gnuplot_input .= "set xrange \[$axis{'xmin'}:$axis{'xmax'}\]\n";
  475: 	$gnuplot_input .= "set yrange \[$axis{'ymin'}:$axis{'ymax'}\]\n";
  476:     }
  477:     # Key
  478:     if (defined(%key)) {
  479: 	$gnuplot_input .= 'set key '.$key{'pos'}.' ';
  480: 	if ($key{'title'} ne '') {
  481: 	    $gnuplot_input .= 'title "'.$key{'title'}.'" ';
  482: 	} 
  483: 	$gnuplot_input .= ($key{'box'} eq 'on' ? 'box ' : 'nobox ').$/;
  484:     } else {
  485: 	$gnuplot_input .= 'set nokey'.$/;
  486:     }
  487:     # labels
  488:     my $label;
  489:     foreach $label (@labels) {
  490: 	$gnuplot_input .= 'set label "'.$label->{'text'}.'" at '.
  491: 	    $label->{'xpos'}.','.$label->{'ypos'}.' '.$label->{'justify'}.$/ ;
  492:     }
  493:     # curves
  494:     $gnuplot_input .= 'plot ';
  495:     my $datatext = '';
  496:     for (my $i = 0;$i<=$#curves;$i++) {
  497: 	$curve = $curves[$i];
  498: 	$gnuplot_input.= ', ' if ($i > 0);
  499: 	if (exists($curve->{'function'})) {
  500: 	    $gnuplot_input.= 
  501: 		$curve->{'function'}.' title "'.
  502: 		$curve->{'name'}.'" with '.
  503: 		$curve->{'linestyle'};
  504: 	} elsif (exists($curve->{'data'})) {
  505: 	    $gnuplot_input.= '\'-\' title "'.
  506: 		$curve->{'name'}.'" with '.
  507: 		$curve->{'linestyle'};
  508: 	    my @Data = @{$curve->{'data'}};
  509: 	    my @Data0 = @{$Data[0]};
  510: 	    for (my $i =0; $i<=$#Data0; $i++) {
  511: 		my $dataset;
  512: 		foreach $dataset (@Data) {
  513: 		    $datatext .= $dataset->[$i] . ' ';
  514: 		}
  515: 		$datatext .= $/;
  516: 	    }
  517: 	    $datatext .=$/;
  518: 	}
  519:     }
  520:     $gnuplot_input .= $/.$datatext;
  521:     return $gnuplot_input;
  522: }
  523: 
  524: 1;
  525: __END__
  526: 
  527: 
  528: 
  529: 
  530: 

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