1: # The LearningOnline Network with CAPA
2: # Dynamic plot
3: #
4: # $Id: lonplot.pm,v 1.133 2007/12/14 06:34:59 albertel 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:
29: package Apache::lonplot;
30:
31: use strict;
32: use warnings FATAL=>'all';
33: no warnings 'uninitialized';
34: use Apache::File;
35: use Apache::response;
36: use Apache::lonxml;
37: use Apache::edit;
38: use Apache::lonnet;
39: use LONCAPA;
40:
41:
42: use vars qw/$weboutputformat $version/;
43:
44:
45:
46: BEGIN {
47: &Apache::lonxml::register('Apache::lonplot',('gnuplot'));
48: #
49: # Determine the version of GNUPLOT
50: $weboutputformat = 'gif';
51: my $versionstring = `gnuplot --version 2>/dev/null`;
52: ($version) = ($versionstring =~ /^gnuplot ([\d.]+)/);
53: if ($version >= 4) {
54: $weboutputformat = 'png';
55: }
56:
57: }
58:
59:
60: ##
61: ## Description of data structures:
62: ##
63: ## %plot %key %axis
64: ## --------------------------
65: ## height title color
66: ## width box xmin
67: ## bgcolor pos xmax
68: ## fgcolor ymin
69: ## transparent ymax
70: ## grid
71: ## border
72: ## font
73: ## align
74: ##
75: ## @labels: $labels[$i] = \%label
76: ## %label: text, xpos, ypos, justify
77: ##
78: ## @curves: $curves[$i] = \%curve
79: ## %curve: name, linestyle, ( function | data )
80: ##
81: ## $curves[$i]->{'data'} = [ [x1,x2,x3,x4],
82: ## [y1,y2,y3,y4] ]
83: ##
84:
85: ###################################################################
86: ## ##
87: ## Tests used in checking the validitity of input ##
88: ## ##
89: ###################################################################
90:
91: my $max_str_len = 50; # if a label, title, xlabel, or ylabel text
92: # is longer than this, it will be truncated.
93:
94: my %linestyles =
95: (
96: lines => 2, # Maybe this will be used in the future
97: linespoints => 2, # to check on whether or not they have
98: dots => 2, # supplied enough <data></data> fields
99: points => 2, # to use the given line style. But for
100: steps => 2, # now there are more important things
101: fsteps => 2, # for me to deal with.
102: histeps => 2,
103: errorbars => 3,
104: xerrorbars => [3,4],
105: yerrorbars => [3,4],
106: xyerrorbars => [4,6],
107: boxes => 3,
108: filledcurves => 2,
109: vector => 4
110: );
111:
112: my $int_test = sub {$_[0]=~s/\s+//g;$_[0]=~/^\d+$/};
113: my $real_test =
114: sub {$_[0]=~s/\s+//g;$_[0]=~/^[+-]?\d*\.?\d*([eE][+-]\d+)?$/};
115: my $pos_real_test =
116: sub {$_[0]=~s/\s+//g;$_[0]=~/^[+]?\d*\.?\d*([eE][+-]\d+)?$/};
117: my $color_test = sub {$_[0]=~s/\s+//g;$_[0]=~/^x[\da-fA-F]{6}$/};
118: my $onoff_test = sub {$_[0]=~/^(on|off)$/};
119: my $key_pos_test = sub {$_[0]=~/^(top|bottom|right|left|outside|below| )+$/};
120: my $sml_test = sub {$_[0]=~/^(\d+|small|medium|large)$/};
121: my $linestyle_test = sub {exists($linestyles{$_[0]})};
122: my $words_test = sub {$_[0]=~s/\s+/ /g;$_[0]=~/^([\w~!\@\#\$\%^&\*\(\)-=_\+\[\]\{\}:\;\'<>,\.\/\?\\]+ ?)+$/};
123:
124: ###################################################################
125: ## ##
126: ## Attribute metadata ##
127: ## ##
128: ###################################################################
129: my @gnuplot_edit_order =
130: qw/alttag bgcolor fgcolor height width texwidth fontface font texfont
131: transparent grid samples
132: border align plotcolor plottype gridtype lmargin rmargin
133: tmargin bmargin major_ticscale minor_ticscale boxwidth gridlayer fillstyle
134: pattern solid/;
135:
136: my $margin_choices = ['default',0..20];
137:
138: my %gnuplot_defaults =
139: (
140: alttag => {
141: default => 'dynamically generated plot',
142: test => $words_test,
143: description => 'Brief description of the plot',
144: edit_type => 'entry',
145: size => '40'
146: },
147: height => {
148: default => 300,
149: test => $int_test,
150: description => 'Height of image (pixels)',
151: edit_type => 'entry',
152: size => '10'
153: },
154: width => {
155: default => 400,
156: test => $int_test,
157: description => 'Width of image (pixels)',
158: edit_type => 'entry',
159: size => '10'
160: },
161: bgcolor => {
162: default => 'xffffff',
163: test => $color_test,
164: description => 'Background color of image (xffffff)',
165: edit_type => 'entry',
166: size => '10'
167: },
168: fgcolor => {
169: default => 'x000000',
170: test => $color_test,
171: description => 'Foreground color of image (x000000)',
172: edit_type => 'entry',
173: size => '10'
174: },
175: transparent => {
176: default => 'off',
177: test => $onoff_test,
178: description => 'Transparent image',
179: edit_type => 'onoff'
180: },
181: grid => {
182: default => 'on',
183: test => $onoff_test,
184: description => 'Display grid',
185: edit_type => 'onoff'
186: },
187: gridlayer => {
188: default => 'off',
189: test => $onoff_test,
190: description => 'Display grid front layer over filled boxes or filled curves',
191: edit_type => 'onoff'
192: },
193: box_border => {
194: default => 'noborder',
195: test => sub {$_[0]=~/^(noborder|border)$/},
196: description => 'Draw border for boxes',
197: edit_type => 'choice',
198: choices => ['border','noborder']
199: },
200: border => {
201: default => 'on',
202: test => $onoff_test,
203: description => 'Draw border around plot',
204: edit_type => 'onoff'
205: },
206: font => {
207: default => '9',
208: test => $sml_test,
209: description => 'Font size to use in web output (pts)',
210: edit_type => 'choice',
211: choices => [['5','5 (small)'],'6','7','8',['9','9 (medium)'],'10',['11','11 (large)'],'12','15']
212: },
213: fontface => {
214: default => 'sans-serif',
215: test => sub {$_[0]=~/^(sans-serif|serif|classic)$/},
216: description => 'Type of font to use',
217: edit_type => 'choice',
218: choices => ['sans-serif','serif', 'classic']
219: },
220: samples => {
221: default => '100',
222: test => $int_test,
223: description => 'Number of samples for non-data plots',
224: edit_type => 'choice',
225: choices => ['100','200','500','1000','2000','5000']
226: },
227: align => {
228: default => 'middle',
229: test => sub {$_[0]=~/^(left|right|middle|center)$/},
230: description => 'Alignment for image in HTML',
231: edit_type => 'choice',
232: choices => ['left','right','middle']
233: },
234: texwidth => {
235: default => '93',
236: test => $int_test,
237: description => 'Width of plot when printed (mm)',
238: edit_type => 'entry',
239: size => '5'
240: },
241: texfont => {
242: default => '22',
243: test => $int_test,
244: description => 'Font size to use in TeX output (pts):',
245: edit_type => 'choice',
246: choices => [qw/8 10 12 14 16 18 20 22 24 26 28 30 32 34 36/],
247: },
248: plotcolor => {
249: default => 'monochrome',
250: test => sub {$_[0]=~/^(monochrome|color|colour)$/},
251: description => 'Color setting for printing:',
252: edit_type => 'choice',
253: choices => [qw/monochrome color colour/],
254: },
255: pattern => {
256: default => '',
257: test => $int_test,
258: description => 'Pattern value for boxes:',
259: edit_type => 'choice',
260: choices => [0,1,2,3,4,5,6]
261: },
262: solid => {
263: default => 0,
264: test => $real_test,
265: description => 'The density of fill style for boxes',
266: edit_type => 'entry',
267: size => '5'
268: },
269: fillstyle => {
270: default => 'empty',
271: test => sub {$_[0]=~/^(empty|solid|pattern)$/},
272: description => 'Filled style for boxes:',
273: edit_type => 'choice',
274: choices => ['empty','solid','pattern']
275: },
276: plottype => {
277: default => 'Cartesian',
278: test => sub {$_[0]=~/^(Polar|Cartesian)$/},
279: description => 'Plot type:',
280: edit_type => 'choice',
281: choices => ['Cartesian','Polar']
282: },
283: gridtype => {
284: default => 'Cartesian',
285: test => sub {$_[0]=~/^(Polar|Cartesian|Linear-Log|Log-Linear|Log-Log)$/},
286: description => 'Grid type:',
287: edit_type => 'choice',
288: choices => ['Cartesian','Polar','Linear-Log','Log-Linear','Log-Log']
289: },
290: lmargin => {
291: default => 'default',
292: test => sub {$_[0]=~/^(default|\d+)$/},
293: description => 'Left margin width (pts):',
294: edit_type => 'choice',
295: choices => $margin_choices,
296: },
297: rmargin => {
298: default => 'default',
299: test => sub {$_[0]=~/^(default|\d+)$/},
300: description => 'Right margin width (pts):',
301: edit_type => 'choice',
302: choices => $margin_choices,
303: },
304: tmargin => {
305: default => 'default',
306: test => sub {$_[0]=~/^(default|\d+)$/},
307: description => 'Top margin width (pts):',
308: edit_type => 'choice',
309: choices => $margin_choices,
310: },
311: bmargin => {
312: default => 'default',
313: test => sub {$_[0]=~/^(default|\d+)$/},
314: description => 'Bottom margin width (pts):',
315: edit_type => 'choice',
316: choices => $margin_choices,
317: },
318: boxwidth => {
319: default => '',
320: test => $real_test,
321: description => 'Width of boxes, default is auto',
322: edit_type => 'entry',
323: size => '5'
324: },
325: major_ticscale => {
326: default => '1',
327: test => $real_test,
328: description => 'Size of major tic marks (plot coordinates)',
329: edit_type => 'entry',
330: size => '5'
331: },
332: minor_ticscale => {
333: default => '0.5',
334: test => $real_test,
335: description => 'Size of minor tic mark (plot coordinates)',
336: edit_type => 'entry',
337: size => '5'
338: },
339: );
340:
341: my %key_defaults =
342: (
343: title => {
344: default => '',
345: test => $words_test,
346: description => 'Title of key',
347: edit_type => 'entry',
348: size => '40'
349: },
350: box => {
351: default => 'off',
352: test => $onoff_test,
353: description => 'Draw a box around the key?',
354: edit_type => 'onoff'
355: },
356: pos => {
357: default => 'top right',
358: test => $key_pos_test,
359: description => 'Position of the key on the plot',
360: edit_type => 'choice',
361: choices => ['top left','top right','bottom left','bottom right',
362: 'outside','below']
363: }
364: );
365:
366: my %label_defaults =
367: (
368: xpos => {
369: default => 0,
370: test => $real_test,
371: description => 'X position of label (graph coordinates)',
372: edit_type => 'entry',
373: size => '10'
374: },
375: ypos => {
376: default => 0,
377: test => $real_test,
378: description => 'Y position of label (graph coordinates)',
379: edit_type => 'entry',
380: size => '10'
381: },
382: justify => {
383: default => 'left',
384: test => sub {$_[0]=~/^(left|right|center)$/},
385: description => 'justification of the label text on the plot',
386: edit_type => 'choice',
387: choices => ['left','right','center']
388: }
389: );
390:
391: my @tic_edit_order = ('location','mirror','start','increment','end',
392: 'minorfreq');
393: my %tic_defaults =
394: (
395: location => {
396: default => 'border',
397: test => sub {$_[0]=~/^(border|axis)$/},
398: description => 'Location of major tic marks',
399: edit_type => 'choice',
400: choices => ['border','axis']
401: },
402: mirror => {
403: default => 'on',
404: test => $onoff_test,
405: description => 'Mirror tics on opposite axis?',
406: edit_type => 'onoff'
407: },
408: start => {
409: default => '-10.0',
410: test => $real_test,
411: description => 'Start major tics at',
412: edit_type => 'entry',
413: size => '10'
414: },
415: increment => {
416: default => '1.0',
417: test => $real_test,
418: description => 'Place a major tic every',
419: edit_type => 'entry',
420: size => '10'
421: },
422: end => {
423: default => ' 10.0',
424: test => $real_test,
425: description => 'Stop major tics at ',
426: edit_type => 'entry',
427: size => '10'
428: },
429: minorfreq => {
430: default => '0',
431: test => $int_test,
432: description => 'Number of minor tics per major tic mark',
433: edit_type => 'entry',
434: size => '10'
435: },
436: );
437:
438: my @axis_edit_order = ('color','xmin','xmax','ymin','ymax','xformat', 'yformat');
439: my %axis_defaults =
440: (
441: color => {
442: default => 'x000000',
443: test => $color_test,
444: description => 'Color of grid lines (x000000)',
445: edit_type => 'entry',
446: size => '10'
447: },
448: xmin => {
449: default => '-10.0',
450: test => $real_test,
451: description => 'Minimum x-value shown in plot',
452: edit_type => 'entry',
453: size => '10'
454: },
455: xmax => {
456: default => ' 10.0',
457: test => $real_test,
458: description => 'Maximum x-value shown in plot',
459: edit_type => 'entry',
460: size => '10'
461: },
462: ymin => {
463: default => '-10.0',
464: test => $real_test,
465: description => 'Minimum y-value shown in plot',
466: edit_type => 'entry',
467: size => '10'
468: },
469: ymax => {
470: default => ' 10.0',
471: test => $real_test,
472: description => 'Maximum y-value shown in plot',
473: edit_type => 'entry',
474: size => '10'
475: },
476: xformat => {
477: default => 'on',
478: test => sub {$_[0]=~/^(on|off|\d+(f|F|e|E))$/},
479: description => 'X-axis number formatting',
480: edit_type => 'choice',
481: choices => ['on', 'off', '2e', '2f'],
482: },
483: yformat => {
484: default => 'on',
485: test => sub {$_[0]=~/^(on|off|\d+(f|F|e|E))$/},
486: description => 'X-axis number formatting',
487: edit_type => 'choice',
488: choices => ['on', 'off', '2e', '2f'],
489: },
490:
491: );
492:
493: my @curve_edit_order = ('color','name','linestyle','linewidth','pointtype','pointsize','limit');
494:
495: my %curve_defaults =
496: (
497: color => {
498: default => 'x000000',
499: test => $color_test,
500: description => 'Color of curve (x000000)',
501: edit_type => 'entry',
502: size => '10'
503: },
504: name => {
505: default => '',
506: test => $words_test,
507: description => 'Name of curve to appear in key',
508: edit_type => 'entry',
509: size => '20'
510: },
511: linestyle => {
512: default => 'lines',
513: test => $linestyle_test,
514: description => 'Line style',
515: edit_type => 'choice',
516: choices => [keys(%linestyles)]
517: },
518: linewidth => {
519: default => 1,
520: test => $int_test,
521: description => 'Line width (may not apply to all line styles)',
522: edit_type => 'choice',
523: choices => [1,2,3,4,5,6,7,8,9,10]
524: },
525: pointsize => {
526: default => 1,
527: test => $pos_real_test,
528: description => 'Point size (may not apply to all line styles)',
529: edit_type => 'entry',
530: size => '5'
531: },
532: pointtype => {
533: default => 1,
534: test => $int_test,
535: description => 'Point type (may not apply to all line styles)',
536: edit_type => 'choice',
537: choices => [0,1,2,3,4,5,6]
538: },
539: limit => {
540: default => 'closed',
541: test => sub {$_[0]=~/^(closed|x1|x2|y1|y2)$/},
542: description => 'Point to fill -- for filledcurves',
543: edit_type => 'choice',
544: choices => ['closed','x1','x2','y1','y2']
545: },
546: );
547:
548: ###################################################################
549: ## ##
550: ## parsing and edit rendering ##
551: ## ##
552: ###################################################################
553:
554: undef %Apache::lonplot::plot;
555: my (%key,%axis,$title,$xlabel,$ylabel,@labels,@curves,%xtics,%ytics);
556:
557: sub start_gnuplot {
558: undef(%Apache::lonplot::plot); undef(%key); undef(%axis);
559: undef($title); undef($xlabel); undef($ylabel);
560: undef(@labels); undef(@curves);
561: undef(%xtics); undef(%ytics);
562: #
563: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
564: my $result='';
565: &Apache::lonxml::register('Apache::lonplot',
566: ('title','xlabel','ylabel','key','axis','label','curve',
567: 'xtics','ytics'));
568: push (@Apache::lonxml::namespace,'lonplot');
569: if ($target eq 'web' || $target eq 'tex') {
570: &get_attributes(\%Apache::lonplot::plot,\%gnuplot_defaults,$parstack,$safeeval,
571: $tagstack->[-1]);
572: } elsif ($target eq 'edit') {
573: $result .= &Apache::edit::tag_start($target,$token,'GnuPlot');
574: $result .= &edit_attributes($target,$token,\%gnuplot_defaults,
575: \@gnuplot_edit_order)
576: .&Apache::edit::end_row()
577: .&Apache::edit::start_spanning_row();
578: } elsif ($target eq 'modified') {
579: my $constructtag=&Apache::edit::get_new_args
580: ($token,$parstack,$safeeval,keys(%gnuplot_defaults));
581: if ($constructtag) {
582: $result = &Apache::edit::rebuild_tag($token);
583: }
584: }
585: return $result;
586: }
587:
588: sub end_gnuplot {
589: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
590: pop @Apache::lonxml::namespace;
591: &Apache::lonxml::deregister('Apache::lonplot',
592: ('title','xlabel','ylabel','key','axis','label','curve'));
593: my $result = '';
594: my $randnumber;
595: # need to call rand everytime start_script would evaluate, as the
596: # safe space rand number generator and the global rand generator
597: # are not separate
598: if ($target eq 'web' || $target eq 'tex' || $target eq 'grade' ||
599: $target eq 'answer') {
600: $randnumber=int(rand(1000));
601: }
602: if ($target eq 'web' || $target eq 'tex') {
603: &check_inputs(); # Make sure we have all the data we need
604: ##
605: ## Determine filename
606: my $tmpdir = '/home/httpd/perl/tmp/';
607: my $filename = $env{'user.name'}.'_'.$env{'user.domain'}.
608: '_'.time.'_'.$$.$randnumber.'_plot';
609: ## Write the plot description to the file
610: &write_gnuplot_file($tmpdir,$filename,$target);
611: $filename = &escape($filename);
612: ## return image tag for the plot
613: if ($target eq 'web') {
614: $result .= <<"ENDIMAGE";
615: <img src = "/cgi-bin/plot.$weboutputformat?file=$filename.data"
616: width = "$Apache::lonplot::plot{'width'}"
617: height = "$Apache::lonplot::plot{'height'}"
618: align = "$Apache::lonplot::plot{'align'}"
619: alt = "$Apache::lonplot::plot{'alttag'}" />
620: ENDIMAGE
621: } elsif ($target eq 'tex') {
622: &Apache::lonxml::debug(" gnuplot wid = $Apache::lonplot::plot{'width'}");
623: &Apache::lonxml::debug(" gnuplot ht = $Apache::lonplot::plot{'height'}");
624: #might be inside the safe space, register the URL for later
625: &Apache::lonxml::register_ssi("/cgi-bin/plot.gif?file=$filename.data&output=eps");
626: $result = "%DYNAMICIMAGE:$Apache::lonplot::plot{'width'}:$Apache::lonplot::plot{'height'}:$Apache::lonplot::plot{'texwidth'}\n";
627: $result .= '\graphicspath{{/home/httpd/perl/tmp/}}'."\n";
628: $result .= '\includegraphics[width='.$Apache::lonplot::plot{'texwidth'}.' mm]{'.&unescape($filename).'.eps}';
629: }
630: } elsif ($target eq 'edit') {
631: $result.=&Apache::edit::tag_end($target,$token);
632: }
633: return $result;
634: }
635:
636:
637: ##--------------------------------------------------------------- xtics
638: sub start_xtics {
639: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
640: my $result='';
641: if ($target eq 'web' || $target eq 'tex') {
642: &get_attributes(\%xtics,\%tic_defaults,$parstack,$safeeval,
643: $tagstack->[-1]);
644: } elsif ($target eq 'edit') {
645: $result .= &Apache::edit::tag_start($target,$token,'xtics');
646: $result .= &edit_attributes($target,$token,\%tic_defaults,
647: \@tic_edit_order);
648: } elsif ($target eq 'modified') {
649: my $constructtag=&Apache::edit::get_new_args
650: ($token,$parstack,$safeeval,keys(%tic_defaults));
651: if ($constructtag) {
652: $result = &Apache::edit::rebuild_tag($token);
653: }
654: }
655: return $result;
656: }
657:
658: sub end_xtics {
659: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
660: my $result = '';
661: if ($target eq 'web' || $target eq 'tex') {
662: } elsif ($target eq 'edit') {
663: $result.=&Apache::edit::tag_end($target,$token);
664: }
665: return $result;
666: }
667:
668: ##--------------------------------------------------------------- ytics
669: sub start_ytics {
670: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
671: my $result='';
672: if ($target eq 'web' || $target eq 'tex') {
673: &get_attributes(\%ytics,\%tic_defaults,$parstack,$safeeval,
674: $tagstack->[-1]);
675: } elsif ($target eq 'edit') {
676: $result .= &Apache::edit::tag_start($target,$token,'ytics');
677: $result .= &edit_attributes($target,$token,\%tic_defaults,
678: \@tic_edit_order);
679: } elsif ($target eq 'modified') {
680: my $constructtag=&Apache::edit::get_new_args
681: ($token,$parstack,$safeeval,keys(%tic_defaults));
682: if ($constructtag) {
683: $result = &Apache::edit::rebuild_tag($token);
684: }
685: }
686: return $result;
687: }
688:
689: sub end_ytics {
690: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
691: my $result = '';
692: if ($target eq 'web' || $target eq 'tex') {
693: } elsif ($target eq 'edit') {
694: $result.=&Apache::edit::tag_end($target,$token);
695: }
696: return $result;
697: }
698:
699: ##-----------------------------------------------------------------font
700: my %font_properties =
701: (
702: 'classic' => {
703: face => 'classic',
704: file => 'DejaVuSansMono-Bold',
705: printname => 'Helvetica',
706: tex_no_file => 1,
707: },
708: 'sans-serif' => {
709: face => 'sans-serif',
710: file => 'DejaVuSans',
711: printname => 'DejaVuSans',
712: },
713: 'serif' => {
714: face => 'serif',
715: file => 'DejaVuSerif',
716: printname => 'DejaVuSerif',
717: },
718: );
719:
720: sub get_font {
721: my ($target) = @_;
722: my ($size, $selected_font);
723:
724: if ( $Apache::lonplot::plot{'font'} =~ /^(small|medium|large)/) {
725: $selected_font = $font_properties{'classic'};
726: if ( $Apache::lonplot::plot{'font'} eq 'small') {
727: $size = '5';
728: } elsif ( $Apache::lonplot::plot{'font'} eq 'medium') {
729: $size = '9';
730: } elsif ( $Apache::lonplot::plot{'font'} eq 'large') {
731: $size = '11';
732: } else {
733: $size = '9';
734: }
735: } else {
736: $size = $Apache::lonplot::plot{'font'};
737: $selected_font = $font_properties{$Apache::lonplot::plot{'fontface'}};
738: }
739: if ($target eq 'tex' && defined($Apache::lonplot::plot{'texfont'})) {
740: $size = $Apache::lonplot::plot{'texfont'};
741: }
742: return ($size, $selected_font);
743: }
744:
745: ##----------------------------------------------------------------- key
746: sub start_key {
747: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
748: my $result='';
749: if ($target eq 'web' || $target eq 'tex') {
750: &get_attributes(\%key,\%key_defaults,$parstack,$safeeval,
751: $tagstack->[-1]);
752: } elsif ($target eq 'edit') {
753: $result .= &Apache::edit::tag_start($target,$token,'Plot Key');
754: $result .= &edit_attributes($target,$token,\%key_defaults);
755: } elsif ($target eq 'modified') {
756: my $constructtag=&Apache::edit::get_new_args
757: ($token,$parstack,$safeeval,keys(%key_defaults));
758: if ($constructtag) {
759: $result = &Apache::edit::rebuild_tag($token);
760: }
761: }
762: return $result;
763: }
764:
765: sub end_key {
766: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
767: my $result = '';
768: if ($target eq 'web' || $target eq 'tex') {
769: } elsif ($target eq 'edit') {
770: $result.=&Apache::edit::tag_end($target,$token);
771: }
772: return $result;
773: }
774:
775: sub parse_label {
776: my ($target,$text) = @_;
777: my $parser=HTML::LCParser->new(\$text);
778: my $result;
779: while (my $token=$parser->get_token) {
780: if ($token->[0] eq 'S') {
781: if ($token->[1] eq 'sub') {
782: $result .= '_{';
783: } elsif ($token->[1] eq 'sup') {
784: $result .= '^{';
785: } else {
786: $result .= $token->[4];
787: }
788: } elsif ($token->[0] eq 'E') {
789: if ($token->[1] eq 'sub'
790: || $token->[1] eq 'sup') {
791: $result .= '}';
792: } else {
793: $result .= $token->[2];
794: }
795: } elsif ($token->[0] eq 'T') {
796: $result .= &replace_entities($target,$token->[1]);
797: }
798: }
799: return $result;
800: }
801:
802:
803: my %lookup =
804: ('(Alpha|#913)' => {'tex' => '{/Symbol A}', 'web' => "\x{391}"},
805: '(Beta|#914)' => {'tex' => '{/Symbol B}', 'web' => "\x{392}"},
806: '(Chi|#935)' => {'tex' => '{/Symbol C}', 'web' => "\x{3A7}"},
807: '(Delta|#916)' => {'tex' => '{/Symbol D}', 'web' => "\x{394}"},
808: '(Epsilon|#917)' => {'tex' => '{/Symbol E}', 'web' => "\x{395}"},
809: '(Phi|#934)' => {'tex' => '{/Symbol F}', 'web' => "\x{3A6}"},
810: '(Gamma|#915)' => {'tex' => '{/Symbol G}', 'web' => "\x{393}"},
811: '(Eta|#919)' => {'tex' => '{/Symbol H}', 'web' => "\x{397}"},
812: '(Iota|#921)' => {'tex' => '{/Symbol I}', 'web' => "\x{399}"},
813: '(Kappa|#922)' => {'tex' => '{/Symbol K}', 'web' => "\x{39A}"},
814: '(Lambda|#923)' => {'tex' => '{/Symbol L}', 'web' => "\x{39B}"},
815: '(Mu|#924)' => {'tex' => '{/Symbol M}', 'web' => "\x{39C}"},
816: '(Nu|#925)' => {'tex' => '{/Symbol N}', 'web' => "\x{39D}"},
817: '(Omicron|#927)' => {'tex' => '{/Symbol O}', 'web' => "\x{39F}"},
818: '(Pi|#928)' => {'tex' => '{/Symbol P}', 'web' => "\x{3A0}"},
819: '(Theta|#920)' => {'tex' => '{/Symbol Q}', 'web' => "\x{398}"},
820: '(Rho|#929)' => {'tex' => '{/Symbol R}', 'web' => "\x{3A1}"},
821: '(Sigma|#931)' => {'tex' => '{/Symbol S}', 'web' => "\x{3A3}"},
822: '(Tau|#932)' => {'tex' => '{/Symbol T}', 'web' => "\x{3A4}"},
823: '(Upsilon|#933)' => {'tex' => '{/Symbol U}', 'web' => "\x{3A5}"},
824: '(Omega|#937)' => {'tex' => '{/Symbol W}', 'web' => "\x{3A9}"},
825: '(Xi|#926)' => {'tex' => '{/Symbol X}', 'web' => "\x{39E}"},
826: '(Psi|#936)' => {'tex' => '{/Symbol Y}', 'web' => "\x{3A8}"},
827: '(Zeta|#918)' => {'tex' => '{/Symbol Z}', 'web' => "\x{396}"},
828: '(alpha|#945)' => {'tex' => '{/Symbol a}', 'web' => "\x{3B1}"},
829: '(beta|#946)' => {'tex' => '{/Symbol b}', 'web' => "\x{3B2}"},
830: '(chi|#967)' => {'tex' => '{/Symbol c}', 'web' => "\x{3C7}"},
831: '(delta|#948)' => {'tex' => '{/Symbol d}', 'web' => "\x{3B4}"},
832: '(epsilon|#949)' => {'tex' => '{/Symbol e}', 'web' => "\x{3B5}"},
833: '(phi|#966)' => {'tex' => '{/Symbol f}', 'web' => "\x{3C6}"},
834: '(gamma|#947)' => {'tex' => '{/Symbol g}', 'web' => "\x{3B3}"},
835: '(eta|#951)' => {'tex' => '{/Symbol h}', 'web' => "\x{3B7}"},
836: '(iota|#953)' => {'tex' => '{/Symbol i}', 'web' => "\x{3B9}"},
837: '(kappa|#954)' => {'tex' => '{/Symbol k}', 'web' => "\x{3BA}"},
838: '(lambda|#955)' => {'tex' => '{/Symbol k}', 'web' => "\x{3BB}"},
839: '(mu|#956)' => {'tex' => '{/Symbol m}', 'web' => "\x{3BC}"},
840: '(nu|#957)' => {'tex' => '{/Symbol n}', 'web' => "\x{3BD}"},
841: '(omicron|#959)' => {'tex' => '{/Symbol o}', 'web' => "\x{3BF}"},
842: '(pi|#960)' => {'tex' => '{/Symbol p}', 'web' => "\x{3C0}"},
843: '(theta|#952)' => {'tex' => '{/Symbol q}', 'web' => "\x{3B8}"},
844: '(rho|#961)' => {'tex' => '{/Symbol r}', 'web' => "\x{3C1}"},
845: '(sigma|#963)' => {'tex' => '{/Symbol s}', 'web' => "\x{3C3}"},
846: '(tau|#964)' => {'tex' => '{/Symbol t}', 'web' => "\x{3C4}"},
847: '(upsilon|#965)' => {'tex' => '{/Symbol u}', 'web' => "\x{3C5}"},
848: '(omega|#969)' => {'tex' => '{/Symbol w}', 'web' => "\x{3C9}"},
849: '(xi|#958)' => {'tex' => '{/Symbol x}', 'web' => "\x{3BE}"},
850: '(psi|#968)' => {'tex' => '{/Symbol y}', 'web' => "\x{3C8}"},
851: '(zeta|#950)' => {'tex' => '{/Symbol z}', 'web' => "\x{3B6}"},
852: );
853:
854:
855: sub replace_entities {
856: my ($target,$text) = @_;
857: $text =~ s{([_^~\{\}]|\\\\)}{\\\\$1}g;
858: while (my ($re, $replace) = each(%lookup)) {
859: $text =~ s/&$re;/$replace->{$target}/g;
860: }
861: $text =~ s{(&)}{\\\\$1}g;
862: return $text;
863: }
864:
865: ##------------------------------------------------------------------- title
866: sub start_title {
867: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
868: my $result='';
869: if ($target eq 'web' || $target eq 'tex') {
870: $title = &Apache::lonxml::get_all_text("/title",$parser,$style);
871: $title=&Apache::run::evaluate($title,$safeeval,$$parstack[-1]);
872: $title =~ s/\n/ /g;
873: if (length($title) > $max_str_len) {
874: $title = substr($title,0,$max_str_len);
875: }
876: $title = &parse_label($target,$title);
877: } elsif ($target eq 'edit') {
878: $result.=&Apache::edit::tag_start($target,$token,'Plot Title');
879: my $text=&Apache::lonxml::get_all_text("/title",$parser,$style);
880: $result.=&Apache::edit::editline('',$text,'',60);
881: } elsif ($target eq 'modified') {
882: $result.=&Apache::edit::rebuild_tag($token);
883: $result.=&Apache::edit::modifiedfield("/title",$parser);
884: }
885: return $result;
886: }
887:
888: sub end_title {
889: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
890: my $result = '';
891: if ($target eq 'web' || $target eq 'tex') {
892: } elsif ($target eq 'edit') {
893: $result.=&Apache::edit::tag_end($target,$token);
894: }
895: return $result;
896: }
897: ##------------------------------------------------------------------- xlabel
898: sub start_xlabel {
899: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
900: my $result='';
901: if ($target eq 'web' || $target eq 'tex') {
902: $xlabel = &Apache::lonxml::get_all_text("/xlabel",$parser,$style);
903: $xlabel=&Apache::run::evaluate($xlabel,$safeeval,$$parstack[-1]);
904: $xlabel =~ s/\n/ /g;
905: if (length($xlabel) > $max_str_len) {
906: $xlabel = substr($xlabel,0,$max_str_len);
907: }
908: $xlabel = &parse_label($target,$xlabel);
909: } elsif ($target eq 'edit') {
910: $result.=&Apache::edit::tag_start($target,$token,'Plot Xlabel');
911: my $text=&Apache::lonxml::get_all_text("/xlabel",$parser,$style);
912: $result.=&Apache::edit::editline('',$text,'',60);
913: } elsif ($target eq 'modified') {
914: $result.=&Apache::edit::rebuild_tag($token);
915: $result.=&Apache::edit::modifiedfield("/xlabel",$parser);
916: }
917: return $result;
918: }
919:
920: sub end_xlabel {
921: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
922: my $result = '';
923: if ($target eq 'web' || $target eq 'tex') {
924: } elsif ($target eq 'edit') {
925: $result.=&Apache::edit::tag_end($target,$token);
926: }
927: return $result;
928: }
929:
930: ##------------------------------------------------------------------- ylabel
931: sub start_ylabel {
932: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
933: my $result='';
934: if ($target eq 'web' || $target eq 'tex') {
935: $ylabel = &Apache::lonxml::get_all_text("/ylabel",$parser,$style);
936: $ylabel = &Apache::run::evaluate($ylabel,$safeeval,$$parstack[-1]);
937: $ylabel =~ s/\n/ /g;
938: if (length($ylabel) > $max_str_len) {
939: $ylabel = substr($ylabel,0,$max_str_len);
940: }
941: $ylabel = &parse_label($target,$ylabel);
942: } elsif ($target eq 'edit') {
943: $result .= &Apache::edit::tag_start($target,$token,'Plot Ylabel');
944: my $text = &Apache::lonxml::get_all_text("/ylabel",$parser,$style);
945: $result .= &Apache::edit::editline('',$text,'',60);
946: } elsif ($target eq 'modified') {
947: $result.=&Apache::edit::rebuild_tag($token);
948: $result.=&Apache::edit::modifiedfield("/ylabel",$parser);
949: }
950: return $result;
951: }
952:
953: sub end_ylabel {
954: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
955: my $result = '';
956: if ($target eq 'web' || $target eq 'tex') {
957: } elsif ($target eq 'edit') {
958: $result.=&Apache::edit::tag_end($target,$token);
959: }
960: return $result;
961: }
962:
963: ##------------------------------------------------------------------- label
964: sub start_label {
965: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
966: my $result='';
967: if ($target eq 'web' || $target eq 'tex') {
968: my %label;
969: &get_attributes(\%label,\%label_defaults,$parstack,$safeeval,
970: $tagstack->[-1]);
971: my $text = &Apache::lonxml::get_all_text("/label",$parser,$style);
972: $text = &Apache::run::evaluate($text,$safeeval,$$parstack[-1]);
973: $text =~ s/\n/ /g;
974: $text = substr($text,0,$max_str_len) if (length($text) > $max_str_len);
975: $label{'text'} = &parse_label($target,$text);
976: push(@labels,\%label);
977: } elsif ($target eq 'edit') {
978: $result .= &Apache::edit::tag_start($target,$token,'Plot Label');
979: $result .= &edit_attributes($target,$token,\%label_defaults);
980: my $text = &Apache::lonxml::get_all_text("/label",$parser,$style);
981: $result .= &Apache::edit::end_row().
982: &Apache::edit::start_spanning_row().
983: &Apache::edit::editline('',$text,'',60);
984: } elsif ($target eq 'modified') {
985: &Apache::edit::get_new_args
986: ($token,$parstack,$safeeval,keys(%label_defaults));
987: $result.=&Apache::edit::rebuild_tag($token);
988: $result.=&Apache::edit::modifiedfield("/label",$parser);
989: }
990: return $result;
991: }
992:
993: sub end_label {
994: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
995: my $result = '';
996: if ($target eq 'web' || $target eq 'tex') {
997: } elsif ($target eq 'edit') {
998: $result.=&Apache::edit::tag_end($target,$token);
999: }
1000: return $result;
1001: }
1002:
1003: ##------------------------------------------------------------------- curve
1004: sub start_curve {
1005: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1006: my $result='';
1007: &Apache::lonxml::register('Apache::lonplot',('function','data'));
1008: push (@Apache::lonxml::namespace,'curve');
1009: if ($target eq 'web' || $target eq 'tex') {
1010: my %curve;
1011: &get_attributes(\%curve,\%curve_defaults,$parstack,$safeeval,
1012: $tagstack->[-1]);
1013: push (@curves,\%curve);
1014: } elsif ($target eq 'edit') {
1015: $result .= &Apache::edit::tag_start($target,$token,'Curve');
1016: $result .= &edit_attributes($target,$token,\%curve_defaults,
1017: \@curve_edit_order)
1018: .&Apache::edit::end_row()
1019: .&Apache::edit::start_spanning_row();
1020:
1021: } elsif ($target eq 'modified') {
1022: my $constructtag=&Apache::edit::get_new_args
1023: ($token,$parstack,$safeeval,keys(%curve_defaults));
1024: if ($constructtag) {
1025: $result = &Apache::edit::rebuild_tag($token);
1026: }
1027: }
1028: return $result;
1029: }
1030:
1031: sub end_curve {
1032: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1033: my $result = '';
1034: pop @Apache::lonxml::namespace;
1035: &Apache::lonxml::deregister('Apache::lonplot',('function','data'));
1036: if ($target eq 'web' || $target eq 'tex') {
1037: } elsif ($target eq 'edit') {
1038: $result.=&Apache::edit::tag_end($target,$token);
1039: }
1040: return $result;
1041: }
1042:
1043: ##------------------------------------------------------------ curve function
1044: sub start_function {
1045: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1046: my $result='';
1047: if ($target eq 'web' || $target eq 'tex') {
1048: if (exists($curves[-1]->{'data'})) {
1049: &Apache::lonxml::warning
1050: ('Use of the <b>curve function</b> tag precludes use of '.
1051: ' the <b>curve data</b> tag. '.
1052: 'The curve data tag will be omitted in favor of the '.
1053: 'curve function declaration.');
1054: delete $curves[-1]->{'data'} ;
1055: }
1056: my $function = &Apache::lonxml::get_all_text("/function",$parser,
1057: $style);
1058: $function = &Apache::run::evaluate($function,$safeeval,$$parstack[-1]);
1059: $curves[-1]->{'function'} = $function;
1060: } elsif ($target eq 'edit') {
1061: $result .= &Apache::edit::tag_start($target,$token,'Gnuplot compatible curve function');
1062: my $text = &Apache::lonxml::get_all_text("/function",$parser,$style);
1063: $result .= &Apache::edit::editline('',$text,'',60);
1064: } elsif ($target eq 'modified') {
1065: $result.=&Apache::edit::rebuild_tag($token);
1066: $result.=&Apache::edit::modifiedfield("/function",$parser);
1067: }
1068: return $result;
1069: }
1070:
1071: sub end_function {
1072: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1073: my $result = '';
1074: if ($target eq 'web' || $target eq 'tex') {
1075: } elsif ($target eq 'edit') {
1076: $result .= &Apache::edit::end_table();
1077: }
1078: return $result;
1079: }
1080:
1081: ##------------------------------------------------------------ curve data
1082: sub start_data {
1083: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1084: my $result='';
1085: if ($target eq 'web' || $target eq 'tex') {
1086: if (exists($curves[-1]->{'function'})) {
1087: &Apache::lonxml::warning
1088: ('Use of the <b>curve function</b> tag precludes use of '.
1089: ' the <b>curve data</b> tag. '.
1090: 'The curve function tag will be omitted in favor of the '.
1091: 'curve data declaration.');
1092: delete($curves[-1]->{'function'});
1093: }
1094: my $datatext = &Apache::lonxml::get_all_text("/data",$parser,$style);
1095: $datatext=&Apache::run::evaluate($datatext,$safeeval,$$parstack[-1]);
1096: # Deal with cases where we're given an array...
1097: if ($datatext =~ /^\@/) {
1098: $datatext = &Apache::run::run('return "'.$datatext.'"',
1099: $safeeval,1);
1100: }
1101: $datatext =~ s/\s+/ /g;
1102: # Need to do some error checking on the @data array -
1103: # make sure it's all numbers and make sure each array
1104: # is of the same length.
1105: my @data;
1106: if ($datatext =~ /,/) { # comma deliminated
1107: @data = split /,/,$datatext;
1108: } else { # Assume it's space separated.
1109: @data = split / /,$datatext;
1110: }
1111: for (my $i=0;$i<=$#data;$i++) {
1112: # Check that it's non-empty
1113: if (! defined($data[$i])) {
1114: &Apache::lonxml::warning(
1115: 'undefined curve data value. Replacing with '.
1116: ' pi/e = 1.15572734979092');
1117: $data[$i] = 1.15572734979092;
1118: }
1119: # Check that it's a number
1120: if (! &$real_test($data[$i]) & ! &$int_test($data[$i])) {
1121: &Apache::lonxml::warning(
1122: 'Bad curve data value of '.$data[$i].' Replacing with '.
1123: ' pi/e = 1.15572734979092');
1124: $data[$i] = 1.15572734979092;
1125: }
1126: }
1127: # complain if the number of data points is not the same as
1128: # in previous sets of data.
1129: if (($curves[-1]->{'data'}) && ($#data != $#{@{$curves[-1]->{'data'}->[0]}})){
1130: &Apache::lonxml::warning
1131: ('Number of data points is not consistent with previous '.
1132: 'number of data points');
1133: }
1134: push @{$curves[-1]->{'data'}},\@data;
1135: } elsif ($target eq 'edit') {
1136: $result .= &Apache::edit::tag_start($target,$token,'Comma or space deliminated curve data');
1137: my $text = &Apache::lonxml::get_all_text("/data",$parser,$style);
1138: $result .= &Apache::edit::editline('',$text,'',60);
1139: } elsif ($target eq 'modified') {
1140: $result.=&Apache::edit::rebuild_tag($token);
1141: $result.=&Apache::edit::modifiedfield("/data",$parser);
1142: }
1143: return $result;
1144: }
1145:
1146: sub end_data {
1147: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1148: my $result = '';
1149: if ($target eq 'web' || $target eq 'tex') {
1150: } elsif ($target eq 'edit') {
1151: $result .= &Apache::edit::end_table();
1152: }
1153: return $result;
1154: }
1155:
1156: ##------------------------------------------------------------------- axis
1157: sub start_axis {
1158: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1159: my $result='';
1160: if ($target eq 'web' || $target eq 'tex') {
1161: &get_attributes(\%axis,\%axis_defaults,$parstack,$safeeval,
1162: $tagstack->[-1]);
1163: } elsif ($target eq 'edit') {
1164: $result .= &Apache::edit::tag_start($target,$token,'Plot Axes');
1165: $result .= &edit_attributes($target,$token,\%axis_defaults,
1166: \@axis_edit_order);
1167: } elsif ($target eq 'modified') {
1168: my $constructtag=&Apache::edit::get_new_args
1169: ($token,$parstack,$safeeval,keys(%axis_defaults));
1170: if ($constructtag) {
1171: $result = &Apache::edit::rebuild_tag($token);
1172: }
1173: }
1174: return $result;
1175: }
1176:
1177: sub end_axis {
1178: my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1179: my $result = '';
1180: if ($target eq 'web' || $target eq 'tex') {
1181: } elsif ($target eq 'edit') {
1182: $result.=&Apache::edit::tag_end($target,$token);
1183: } elsif ($target eq 'modified') {
1184: }
1185: return $result;
1186: }
1187:
1188: ###################################################################
1189: ## ##
1190: ## Utility Functions ##
1191: ## ##
1192: ###################################################################
1193:
1194: ##----------------------------------------------------------- set_defaults
1195: sub set_defaults {
1196: my ($var,$defaults) = @_;
1197: my $key;
1198: foreach $key (keys(%$defaults)) {
1199: $var->{$key} = $defaults->{$key}->{'default'};
1200: }
1201: }
1202:
1203: ##------------------------------------------------------------------- misc
1204: sub get_attributes{
1205: my ($values,$defaults,$parstack,$safeeval,$tag) = @_;
1206: foreach my $attr (keys(%{$defaults})) {
1207: if ($attr eq 'texwidth' || $attr eq 'texfont') {
1208: $values->{$attr} =
1209: &Apache::lonxml::get_param($attr,$parstack,$safeeval,undef,1);
1210: } else {
1211: $values->{$attr} =
1212: &Apache::lonxml::get_param($attr,$parstack,$safeeval);
1213: }
1214: if ($values->{$attr} eq '' | !defined($values->{$attr})) {
1215: $values->{$attr} = $defaults->{$attr}->{'default'};
1216: next;
1217: }
1218: my $test = $defaults->{$attr}->{'test'};
1219: if (! &$test($values->{$attr})) {
1220: &Apache::lonxml::warning
1221: ($tag.':'.$attr.': Bad value.'.'Replacing your value with : '
1222: .$defaults->{$attr}->{'default'} );
1223: $values->{$attr} = $defaults->{$attr}->{'default'};
1224: }
1225: }
1226: return ;
1227: }
1228:
1229: ##------------------------------------------------------- write_gnuplot_file
1230: sub write_gnuplot_file {
1231: my ($tmpdir,$filename,$target)= @_;
1232: my ($fontsize, $font_properties) = &get_font($target);
1233: my $gnuplot_input = '';
1234: my $curve;
1235: #
1236: # Check to be sure we do not have any empty curves
1237: my @curvescopy;
1238: foreach my $curve (@curves) {
1239: if (exists($curve->{'function'})) {
1240: if ($curve->{'function'} !~ /^\s*$/) {
1241: push(@curvescopy,$curve);
1242: }
1243: } elsif (exists($curve->{'data'})) {
1244: foreach my $data (@{$curve->{'data'}}) {
1245: if (scalar(@$data) > 0) {
1246: push(@curvescopy,$curve);
1247: last;
1248: }
1249: }
1250: }
1251: }
1252: @curves = @curvescopy;
1253: # Collect all the colors
1254: my @Colors;
1255: push @Colors, $Apache::lonplot::plot{'bgcolor'};
1256: push @Colors, $Apache::lonplot::plot{'fgcolor'};
1257: push @Colors, (defined($axis{'color'})?$axis{'color'}:$Apache::lonplot::plot{'fgcolor'});
1258: foreach $curve (@curves) {
1259: push @Colors, ($curve->{'color'} ne '' ?
1260: $curve->{'color'} :
1261: $Apache::lonplot::plot{'fgcolor'} );
1262: }
1263: # set term
1264: if ($target eq 'web') {
1265: $gnuplot_input .= 'set terminal png enhanced nocrop ';
1266: $gnuplot_input .= 'transparent ' if ($Apache::lonplot::plot{'transparent'} eq 'on');
1267: $gnuplot_input .= 'font "'.$Apache::lonnet::perlvar{'lonFontsDir'}.
1268: '/'.$font_properties->{'file'}.'.ttf" ';
1269: $gnuplot_input .= $fontsize;
1270: $gnuplot_input .= ' size '.$Apache::lonplot::plot{'width'}.','.$Apache::lonplot::plot{'height'}.' ';
1271: $gnuplot_input .= "@Colors\n";
1272: # set output
1273: $gnuplot_input .= "set output\n";
1274: } elsif ($target eq 'tex') {
1275: $gnuplot_input .= "set term postscript eps enhanced $Apache::lonplot::plot{'plotcolor'} solid ";
1276: if (!$font_properties->{'tex_no_file'}) {
1277: $gnuplot_input .=
1278: 'fontfile "'.$Apache::lonnet::perlvar{'lonFontsDir'}.
1279: '/'.$font_properties->{'file'}.'.pfb" ';
1280: }
1281: $gnuplot_input .= ' "'.$font_properties->{'printname'}.'" ';
1282: $gnuplot_input .= $fontsize;
1283: $gnuplot_input .= "\nset output \"/home/httpd/perl/tmp/".
1284: &unescape($filename).".eps\"\n";
1285: }
1286: # cartesian or polar plot?
1287: if (lc($Apache::lonplot::plot{'plottype'}) eq 'polar') {
1288: $gnuplot_input .= 'set polar'.$/;
1289: } else {
1290: # Assume Cartesian
1291: }
1292: # cartesian or polar grid?
1293: if (lc($Apache::lonplot::plot{'gridtype'}) eq 'polar') {
1294: $gnuplot_input .= 'set grid polar'.$/;
1295: } elsif (lc($Apache::lonplot::plot{'gridtype'}) eq 'linear-log') {
1296: $gnuplot_input .= 'set logscale x'.$/;
1297: } elsif (lc($Apache::lonplot::plot{'gridtype'}) eq 'log-linear') {
1298: $gnuplot_input .= 'set logscale y'.$/;
1299: } elsif (lc($Apache::lonplot::plot{'gridtype'}) eq 'log-log') {
1300: $gnuplot_input .= 'set logscale x'.$/;
1301: $gnuplot_input .= 'set logscale y'.$/;
1302: } else {
1303: # Assume Cartesian
1304: }
1305: # solid or pattern for boxes?
1306: if (lc($Apache::lonplot::plot{'fillstyle'}) eq 'solid') {
1307: $gnuplot_input .= 'set style fill solid '.
1308: $Apache::lonplot::plot{'solid'}.$Apache::lonplot::plot{'box_border'}.$/;
1309: } elsif (lc($Apache::lonplot::plot{'fillstyle'}) eq 'pattern') {
1310: $gnuplot_input .= 'set style fill pattern '.$Apache::lonplot::plot{'pattern'}.$Apache::lonplot::plot{'box_border'}.$/;
1311: } elsif (lc($Apache::lonplot::plot{'fillstyle'}) eq 'empty') {
1312: }
1313: # margin
1314: if (lc($Apache::lonplot::plot{'lmargin'}) ne 'default') {
1315: $gnuplot_input .= 'set lmargin '.$Apache::lonplot::plot{'lmargin'}.$/;
1316: }
1317: if (lc($Apache::lonplot::plot{'rmargin'}) ne 'default') {
1318: $gnuplot_input .= 'set rmargin '.$Apache::lonplot::plot{'rmargin'}.$/;
1319: }
1320: if (lc($Apache::lonplot::plot{'tmargin'}) ne 'default') {
1321: $gnuplot_input .= 'set tmargin '.$Apache::lonplot::plot{'tmargin'}.$/;
1322: }
1323: if (lc($Apache::lonplot::plot{'bmargin'}) ne 'default') {
1324: $gnuplot_input .= 'set bmargin '.$Apache::lonplot::plot{'bmargin'}.$/;
1325: }
1326:
1327: # tic scales
1328: if ($version > 4) {
1329: $gnuplot_input .= 'set tics scale '.
1330: $Apache::lonplot::plot{'major_ticscale'}.', '.$Apache::lonplot::plot{'minor_ticscale'}.$/;
1331: } else {
1332: $gnuplot_input .= 'set ticscale '.
1333: $Apache::lonplot::plot{'major_ticscale'}.' '.$Apache::lonplot::plot{'minor_ticscale'}.$/;
1334: }
1335: #boxwidth
1336: if (lc($Apache::lonplot::plot{'boxwidth'}) ne '') {
1337: $gnuplot_input .= 'set boxwidth '.$Apache::lonplot::plot{'boxwidth'}.$/;
1338: }
1339: # gridlayer
1340: $gnuplot_input .= 'set grid noxtics noytics front '.$/
1341: if ($Apache::lonplot::plot{'gridlayer'} eq 'on');
1342:
1343: # grid
1344: $gnuplot_input .= 'set grid'.$/ if ($Apache::lonplot::plot{'grid'} eq 'on');
1345: # border
1346: $gnuplot_input .= ($Apache::lonplot::plot{'border'} eq 'on'?
1347: 'set border'.$/ :
1348: 'set noborder'.$/ );
1349: # sampling rate for non-data curves
1350: $gnuplot_input .= "set samples $Apache::lonplot::plot{'samples'}\n";
1351: # title, xlabel, ylabel
1352: # titles
1353: my $extra_space_x = ($xtics{'location'} eq 'axis') ? ' 0, -0.5 ' : '';
1354: my $extra_space_y = ($ytics{'location'} eq 'axis') ? ' -0.5, 0 ' : '';
1355:
1356: if ($target eq 'tex') {
1357: $gnuplot_input .= "set title \"$title\" font \"".$font_properties->{'printname'}.",".$fontsize."pt\"\n" if (defined($title)) ;
1358: $gnuplot_input .= "set xlabel \"$xlabel\" $extra_space_x font \"".$font_properties->{'printname'}.",".$fontsize."pt\"\n" if (defined($xlabel));
1359: $gnuplot_input .= "set ylabel \"$ylabel\" $extra_space_y font \"".$font_properties->{'printname'}.",".$fontsize."pt\"\n" if (defined($ylabel));
1360: } else {
1361: $gnuplot_input .= "set title \"$title\" \n" if (defined($title)) ;
1362: $gnuplot_input .= "set xlabel \"$xlabel\" $extra_space_x \n" if (defined($xlabel));
1363: $gnuplot_input .= "set ylabel \"$ylabel\" $extra_space_y \n" if (defined($ylabel));
1364: }
1365: # tics
1366: if (%xtics) {
1367: $gnuplot_input .= "set xtics $xtics{'location'} ";
1368: $gnuplot_input .= ( $xtics{'mirror'} eq 'on'?"mirror ":"nomirror ");
1369: $gnuplot_input .= "$xtics{'start'}, ";
1370: $gnuplot_input .= "$xtics{'increment'}, ";
1371: $gnuplot_input .= "$xtics{'end'}\n";
1372: if ($xtics{'minorfreq'} != 0) {
1373: $gnuplot_input .= "set mxtics ".$xtics{'minorfreq'}."\n";
1374: }
1375: }
1376: if (%ytics) {
1377: $gnuplot_input .= "set ytics $ytics{'location'} ";
1378: $gnuplot_input .= ( $ytics{'mirror'} eq 'on'?"mirror ":"nomirror ");
1379: $gnuplot_input .= "$ytics{'start'}, ";
1380: $gnuplot_input .= "$ytics{'increment'}, ";
1381: $gnuplot_input .= "$ytics{'end'}\n";
1382: if ($ytics{'minorfreq'} != 0) {
1383: $gnuplot_input .= "set mytics ".$ytics{'minorfreq'}."\n";
1384: }
1385: }
1386: # axis
1387: if (%axis) {
1388: if ($axis{'xformat'} ne 'on') {
1389: $gnuplot_input .= "set format x ";
1390: if ($axis{'xformat'} eq 'off') {
1391: $gnuplot_input .= "\"\"\n";
1392: } else {
1393: $gnuplot_input .= "\"\%.".$axis{'xformat'}."\"\n";
1394: }
1395: }
1396: if ($axis{'yformat'} ne 'on') {
1397: $gnuplot_input .= "set format y ";
1398: if ($axis{'yformat'} eq 'off') {
1399: $gnuplot_input .= "\"\"\n";
1400: } else {
1401: $gnuplot_input .= "\"\%.".$axis{'yformat'}."\"\n";
1402: }
1403: }
1404: $gnuplot_input .= "set xrange \[$axis{'xmin'}:$axis{'xmax'}\]\n";
1405: $gnuplot_input .= "set yrange \[$axis{'ymin'}:$axis{'ymax'}\]\n";
1406: }
1407: # Key
1408: if (%key) {
1409: $gnuplot_input .= 'set key '.$key{'pos'}.' ';
1410: if ($key{'title'} ne '') {
1411: $gnuplot_input .= 'title "'.$key{'title'}.'" ';
1412: }
1413: $gnuplot_input .= ($key{'box'} eq 'on' ? 'box ' : 'nobox ').$/;
1414: } else {
1415: $gnuplot_input .= 'set nokey'.$/;
1416: }
1417: # labels
1418: my $label;
1419: foreach $label (@labels) {
1420: $gnuplot_input .= 'set label "'.$label->{'text'}.'" at '.
1421: $label->{'xpos'}.','.$label->{'ypos'}.' '.$label->{'justify'};
1422: if ($target eq 'tex') {
1423: $gnuplot_input .=' font "'.$font_properties->{'printname'}.','.$fontsize.'pt"' ;
1424: }
1425: $gnuplot_input .= $/;
1426: }
1427: if ($target eq 'tex') {
1428: $gnuplot_input .="set size 1,".$Apache::lonplot::plot{'height'}/$Apache::lonplot::plot{'width'}*1.38;
1429: $gnuplot_input .="\n";
1430: }
1431: # curves
1432: $gnuplot_input .= 'plot ';
1433: for (my $i = 0;$i<=$#curves;$i++) {
1434: $curve = $curves[$i];
1435: $gnuplot_input.= ', ' if ($i > 0);
1436: if ($target eq 'tex') {
1437: $curve->{'linewidth'} *= 2;
1438: }
1439: if (exists($curve->{'function'})) {
1440: $gnuplot_input.=
1441: $curve->{'function'}.' title "'.
1442: $curve->{'name'}.'" with '.
1443: $curve->{'linestyle'};
1444:
1445: if (($curve->{'linestyle'} eq 'points') ||
1446: ($curve->{'linestyle'} eq 'linespoints') ||
1447: ($curve->{'linestyle'} eq 'errorbars') ||
1448: ($curve->{'linestyle'} eq 'xerrorbars') ||
1449: ($curve->{'linestyle'} eq 'yerrorbars') ||
1450: ($curve->{'linestyle'} eq 'xyerrorbars')) {
1451: $gnuplot_input.=' pointtype '.$curve->{'pointtype'};
1452: $gnuplot_input.=' pointsize '.$curve->{'pointsize'};
1453: } elsif ($curve->{'linestyle'} eq 'filledcurves') {
1454: $gnuplot_input.= ' '.$curve->{'limit'};
1455: }
1456: $gnuplot_input.= ' linewidth '.$curve->{'linewidth'};
1457:
1458: } elsif (exists($curve->{'data'})) {
1459: # Store data values in $datatext
1460: my $datatext = '';
1461: # get new filename
1462: my $datafilename = "$tmpdir/$filename.data.$i";
1463: my $fh=Apache::File->new(">$datafilename");
1464: # Compile data
1465: my @Data = @{$curve->{'data'}};
1466: my @Data0 = @{$Data[0]};
1467: for (my $i =0; $i<=$#Data0; $i++) {
1468: my $dataset;
1469: foreach $dataset (@Data) {
1470: $datatext .= $dataset->[$i] . ' ';
1471: }
1472: $datatext .= $/;
1473: }
1474: # write file
1475: print $fh $datatext;
1476: close($fh);
1477: # generate gnuplot text
1478: $gnuplot_input.= '"'.$datafilename.'" title "'.
1479: $curve->{'name'}.'" with '.
1480: $curve->{'linestyle'};
1481: if (($curve->{'linestyle'} eq 'points') ||
1482: ($curve->{'linestyle'} eq 'linespoints') ||
1483: ($curve->{'linestyle'} eq 'errorbars') ||
1484: ($curve->{'linestyle'} eq 'xerrorbars') ||
1485: ($curve->{'linestyle'} eq 'yerrorbars') ||
1486: ($curve->{'linestyle'} eq 'xyerrorbars')) {
1487: $gnuplot_input.=' pointtype '.$curve->{'pointtype'};
1488: $gnuplot_input.=' pointsize '.$curve->{'pointsize'};
1489: } elsif ($curve->{'linestyle'} eq 'filledcurves') {
1490: $gnuplot_input.= ' '.$curve->{'limit'};
1491: }
1492: $gnuplot_input.= ' linewidth '.$curve->{'linewidth'};
1493: }
1494: }
1495: # Write the output to a file.
1496: open (my $fh,">$tmpdir$filename.data");
1497: binmode($fh, ":utf8");
1498: print $fh $gnuplot_input;
1499: close($fh);
1500: # That's all folks.
1501: return ;
1502: }
1503:
1504: #---------------------------------------------- check_inputs
1505: sub check_inputs {
1506: ## Note: no inputs, no outputs - this acts only on global variables.
1507: ## Make sure we have all the input we need:
1508: if (! %Apache::lonplot::plot) { &set_defaults(\%Apache::lonplot::plot,\%gnuplot_defaults); }
1509: if (! %key ) {} # No key for this plot, thats okay
1510: # if (! %axis) { &set_defaults(\%axis,\%axis_defaults); }
1511: if (! defined($title )) {} # No title for this plot, thats okay
1512: if (! defined($xlabel)) {} # No xlabel for this plot, thats okay
1513: if (! defined($ylabel)) {} # No ylabel for this plot, thats okay
1514: if ($#labels < 0) { } # No labels for this plot, thats okay
1515: if ($#curves < 0) {
1516: &Apache::lonxml::warning("No curves specified for plot!!!!");
1517: return '';
1518: }
1519: my $curve;
1520: foreach $curve (@curves) {
1521: if (!defined($curve->{'function'})&&!defined($curve->{'data'})){
1522: &Apache::lonxml::warning("One of the curves specified did not contain any curve data or curve function declarations\n");
1523: return '';
1524: }
1525: }
1526: }
1527:
1528: #------------------------------------------------ make_edit
1529: sub edit_attributes {
1530: my ($target,$token,$defaults,$keys) = @_;
1531: my ($result,@keys);
1532: if ($keys && ref($keys) eq 'ARRAY') {
1533: @keys = @$keys;
1534: } else {
1535: @keys = sort(keys(%$defaults));
1536: }
1537: foreach my $attr (@keys) {
1538: # append a ' ' to the description if it doesn't have one already.
1539: my $description = $defaults->{$attr}->{'description'};
1540: $description .= ' ' if ($description !~ / $/);
1541: if ($defaults->{$attr}->{'edit_type'} eq 'entry') {
1542: $result .= &Apache::edit::text_arg
1543: ($description,$attr,$token,
1544: $defaults->{$attr}->{'size'});
1545: } elsif ($defaults->{$attr}->{'edit_type'} eq 'choice') {
1546: $result .= &Apache::edit::select_or_text_arg
1547: ($description,$attr,$defaults->{$attr}->{'choices'},$token);
1548: } elsif ($defaults->{$attr}->{'edit_type'} eq 'onoff') {
1549: $result .= &Apache::edit::select_or_text_arg
1550: ($description,$attr,['on','off'],$token);
1551: }
1552: $result .= '<br />';
1553: }
1554: return $result;
1555: }
1556:
1557:
1558: ###################################################################
1559: ## ##
1560: ## Insertion functions for editing plots ##
1561: ## ##
1562: ###################################################################
1563:
1564: sub insert_gnuplot {
1565: my $result = '';
1566: # plot attributes
1567: $result .= "\n<gnuplot ";
1568: foreach my $attr (keys(%gnuplot_defaults)) {
1569: $result .= "\n $attr=\"$gnuplot_defaults{$attr}->{'default'}\"";
1570: }
1571: $result .= ">";
1572: # Add the components (most are commented out for simplicity)
1573: # $result .= &insert_key();
1574: # $result .= &insert_axis();
1575: # $result .= &insert_title();
1576: # $result .= &insert_xlabel();
1577: # $result .= &insert_ylabel();
1578: $result .= &insert_curve();
1579: # close up the <gnuplot>
1580: $result .= "\n</gnuplot>";
1581: return $result;
1582: }
1583:
1584: sub insert_tics {
1585: my $result;
1586: $result .= &insert_xtics() . &insert_ytics;
1587: return $result;
1588: }
1589:
1590: sub insert_xtics {
1591: my $result;
1592: $result .= "\n <xtics ";
1593: foreach my $attr (keys(%tic_defaults)) {
1594: $result .= "\n $attr=\"$tic_defaults{$attr}->{'default'}\" ";
1595: }
1596: $result .= "/>";
1597: return $result;
1598: }
1599:
1600: sub insert_ytics {
1601: my $result;
1602: $result .= "\n <ytics ";
1603: foreach my $attr (keys(%tic_defaults)) {
1604: $result .= "\n $attr=\"$tic_defaults{$attr}->{'default'}\" ";
1605: }
1606: $result .= "/>";
1607: return $result;
1608: }
1609:
1610: sub insert_key {
1611: my $result;
1612: $result .= "\n <key ";
1613: foreach my $attr (keys(%key_defaults)) {
1614: $result .= "\n $attr=\"$key_defaults{$attr}->{'default'}\"";
1615: }
1616: $result .= " />";
1617: return $result;
1618: }
1619:
1620: sub insert_axis{
1621: my $result;
1622: $result .= "\n <axis ";
1623: foreach my $attr (keys(%axis_defaults)) {
1624: $result .= "\n $attr=\"$axis_defaults{$attr}->{'default'}\"";
1625: }
1626: $result .= " />";
1627: return $result;
1628: }
1629:
1630: sub insert_title { return "\n <title></title>"; }
1631: sub insert_xlabel { return "\n <xlabel></xlabel>"; }
1632: sub insert_ylabel { return "\n <ylabel></ylabel>"; }
1633:
1634: sub insert_label {
1635: my $result;
1636: $result .= "\n <label ";
1637: foreach my $attr (keys(%label_defaults)) {
1638: $result .= "\n $attr=\"".
1639: $label_defaults{$attr}->{'default'}."\"";
1640: }
1641: $result .= "></label>";
1642: return $result;
1643: }
1644:
1645: sub insert_curve {
1646: my $result;
1647: $result .= "\n <curve ";
1648: foreach my $attr (keys(%curve_defaults)) {
1649: $result .= "\n $attr=\"".
1650: $curve_defaults{$attr}->{'default'}."\"";
1651: }
1652: $result .= " >";
1653: $result .= &insert_data().&insert_data()."\n </curve>";
1654: }
1655:
1656: sub insert_function {
1657: my $result;
1658: $result .= "\n <function></function>";
1659: return $result;
1660: }
1661:
1662: sub insert_data {
1663: my $result;
1664: $result .= "\n <data></data>";
1665: return $result;
1666: }
1667:
1668: ##----------------------------------------------------------------------
1669: 1;
1670: __END__
1671:
1672:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>