File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.42: download - view: text, annotated - select for diffs
Wed Mar 12 20:53:53 2003 UTC (21 years, 3 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
If none of the students have any data, we get a division by zero when we
compute the average.  This is now detected and everything is right with
the world.

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: lonstudentassessment.pm,v 1.42 2003/03/12 20:53:53 matthew Exp $
    4: #
    5: # Copyright Michigan State University Board of Trustees
    6: #
    7: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    8: # LON-CAPA is free software; you can redistribute it and/or modify
    9: # it under the terms of the GNU General Public License as published by
   10: # the Free Software Foundation; either version 2 of the License, or
   11: # (at your option) any later version.
   12: #
   13: # LON-CAPA is distributed in the hope that it will be useful,
   14: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   15: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   16: # GNU General Public License for more details.
   17: #
   18: # You should have received a copy of the GNU General Public License
   19: # along with LON-CAPA; if not, write to the Free Software
   20: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   21: #
   22: # /home/httpd/html/adm/gpl.txt
   23: #
   24: # http://www.lon-capa.org/
   25: #
   26: # (Navigate problems for statistical reports
   27: #
   28: #######################################################
   29: #######################################################
   30: 
   31: =pod
   32: 
   33: =head1 NAME
   34: 
   35: lonstudentassessment
   36: 
   37: =head1 SYNOPSIS
   38: 
   39: Presents assessment data about a student or a group of students.
   40: 
   41: =head1 Subroutines
   42: 
   43: =over 4 
   44: 
   45: =cut
   46: 
   47: #######################################################
   48: #######################################################
   49: 
   50: package Apache::lonstudentassessment;
   51: 
   52: use strict;
   53: use Apache::lonstatistics;
   54: use Apache::lonhtmlcommon;
   55: use Apache::loncoursedata;
   56: use Apache::lonnet; # for logging porpoises
   57: use Spreadsheet::WriteExcel;
   58: 
   59: #######################################################
   60: #######################################################
   61: =pod
   62: 
   63: =item Package Variables
   64: 
   65: =over 4
   66: 
   67: =item $Statistics Hash ref to store student data.  Indexed by symb,
   68:       contains hashes with keys 'score' and 'max'.
   69: 
   70: =cut
   71: 
   72: #######################################################
   73: #######################################################
   74: 
   75: my $Statistics;
   76: 
   77: #######################################################
   78: #######################################################
   79: 
   80: =pod
   81: 
   82: =item $show_links 'yes' or 'no' for linking to student performance data
   83: 
   84: =item $output_mode 'html', 'excel', or 'csv' for output mode
   85: 
   86: =item $show 'all', 'totals', or 'scores' determines how much data is output
   87: 
   88: =cut
   89: 
   90: #######################################################
   91: #######################################################
   92: my $show_links;
   93: my $output_mode;
   94: my $show;
   95: 
   96: #######################################################
   97: #######################################################
   98: # End of package variable declarations
   99: 
  100: =pod
  101: 
  102: =back
  103: 
  104: =cut
  105: 
  106: #######################################################
  107: #######################################################
  108: 
  109: =pod
  110: 
  111: =item &BuildStudentAssessmentPage()
  112: 
  113: Inputs: 
  114: 
  115: =over 4
  116: 
  117: =item $r Apache Request
  118: 
  119: =item $c Apache Connection 
  120: 
  121: =back
  122: 
  123: =cut
  124: 
  125: #######################################################
  126: #######################################################
  127: sub BuildStudentAssessmentPage {
  128:     my ($r,$c)=@_;
  129:     undef($Statistics);
  130:     #
  131:     # Print out the HTML headers for the interface
  132:     #    This also parses the output mode selector
  133:     #    This step must always be done.
  134:     $r->print(&CreateInterface());
  135:     $r->print('<input type="hidden" name="notfirstrun" value="true" />');
  136:     $r->rflush();
  137:     if (! exists($ENV{'form.notfirstrun'})) {
  138:         $r->print(<<ENDMSG);
  139: <p>
  140: <font size="+1">
  141: Please make your selections in the boxes above and hit 
  142: the button marked &quot;Update&nbsp;Display&quot;.
  143: </font>
  144: </p>
  145: ENDMSG
  146: #        $r->print(&OutputDescriptions());
  147:         return;
  148:     }
  149:     #
  150:     #
  151:     my $initialize     = \&html_initialize;
  152:     my $output_student = \&html_outputstudent;
  153:     my $finish         = \&html_finish;
  154:     #
  155:     if ($output_mode eq 'excel') {
  156:         $initialize     = \&excel_initialize;
  157:         $output_student = \&excel_outputstudent;
  158:         $finish         = \&excel_finish;
  159:     } elsif ($output_mode eq 'multi-sheet excel') {
  160:         $initialize     = \&multi_sheet_excel_initialize;
  161:         $output_student = \&multi_sheet_excel_outputstudent;
  162:         $finish         = \&multi_sheet_excel_finish;
  163:     } elsif ($output_mode eq 'csv') {
  164:         $initialize     = \&csv_initialize;
  165:         $output_student = \&csv_outputstudent;
  166:         $finish         = \&csv_finish;
  167:     }
  168:     #
  169:     if($c->aborted()) {  return ; }
  170:     #
  171:     # Call the initialize routine selected above
  172:     $initialize->($r);
  173:     foreach my $student (@Apache::lonstatistics::Students) {
  174:         if($c->aborted()) { 
  175:             $finish->($r);
  176:             return ; 
  177:         }
  178:         # Call the output_student routine selected above
  179:         $output_student->($r,$student);
  180:     }
  181:     # Call the "finish" routine selected above
  182:     $finish->($r);
  183:     #
  184:     return;
  185: }
  186: 
  187: #######################################################
  188: #######################################################
  189: 
  190: sub get_student_fields_to_show {
  191:     my @to_show = @Apache::lonstatistics::SelectedStudentData;
  192:     foreach (@to_show) {
  193:         if ($_ eq 'all') {
  194:             @to_show = @Apache::lonstatistics::StudentDataOrder;
  195:             last;
  196:         }
  197:     }
  198:     return @to_show;
  199: }
  200: 
  201: #######################################################
  202: #######################################################
  203: 
  204: =pod
  205: 
  206: =item &CreateInterface()
  207: 
  208: Called by &BuildStudentAssessmentPage to create the top part of the
  209: page which displays the chart.
  210: 
  211: Inputs: None
  212: 
  213: Returns:  A string containing the HTML for the headers and top table for 
  214: the chart page.
  215: 
  216: =cut
  217: 
  218: #######################################################
  219: #######################################################
  220: sub CreateInterface {
  221:     my $Str = '';
  222: #    $Str .= &CreateLegend();
  223:     $Str .= '<table cellspacing="5">'."\n";
  224:     $Str .= '<tr>';
  225:     $Str .= '<td align="center"><b>Sections</b></td>';
  226:     $Str .= '<td align="center"><b>Student Data</b></td>';
  227:     $Str .= '<td align="center"><b>Sequences and Folders</b></td>';
  228:     $Str .= '<td align="center"><b>Output Format</b></td>';
  229:     $Str .= '</tr>'."\n";
  230:     #
  231:     $Str .= '<tr><td align="center">'."\n";
  232:     $Str .= &Apache::lonstatistics::SectionSelect('Section','multiple',5);
  233:     $Str .= '</td><td align="center">';
  234:     my $only_seq_with_assessments = sub { 
  235:         my $s=shift;
  236:         if ($s->{'num_assess'} < 1) { 
  237:             return 0;
  238:         } else { 
  239:             return 1;
  240:         }
  241:     };
  242:     $Str .= &Apache::lonstatistics::StudentDataSelect('StudentData','multiple',
  243:                                                       5,undef);
  244:     $Str .= '</td><td>'."\n";
  245:     $Str .= &Apache::lonstatistics::MapSelect('Maps','multiple,all',5,
  246:                                               $only_seq_with_assessments);
  247:     $Str .= '</td><td>'."\n";
  248:     $Str .= &CreateAndParseOutputSelector();
  249:     $Str .= '</td></tr>'."\n";
  250:     $Str .= '</table>'."\n";
  251:     return $Str;
  252: }
  253: 
  254: #######################################################
  255: #######################################################
  256: 
  257: =pod
  258: 
  259: =item &CreateAndParseOutputSelector()
  260: 
  261: =cut
  262: 
  263: #######################################################
  264: #######################################################
  265: my @OutputOptions = 
  266:     ({ name  => 'HTML, with links',
  267:        value => 'html, with links',
  268:        description => 'Output HTML with each symbol linked to the problem '.
  269: 	   'which generated it.',
  270:        mode => 'html',
  271:        show => 'all',
  272:        show_links => 'yes',
  273:        },
  274:      { name  => 'HTML, without links',
  275:        value => 'html, without links',
  276:        description => 'Output HTML.  By not including links, the size of the'.
  277: 	   ' web page is greatly reduced.  If your browser crashes on the '.
  278: 	   'full display, try this.',
  279:        mode => 'html',
  280:        show => 'all',
  281:        show_links => 'no',
  282:            },
  283:      { name  => 'HTML, scores only',
  284:        value => 'html, scores only',
  285:        description => 'Output HTML, only showing the total number of correct'.
  286: 	   ' problems (or problem parts) and not the maximum possible for '.
  287: 	   'each student',
  288:        mode => 'html',
  289:        show => 'scores',
  290:        show_links => 'no',
  291:            },
  292:      { name  => 'HTML, totals',
  293:        value => 'html, totals',
  294:        description => 'Output HTML, but only the summary statistics for each'.
  295: 	   ' sequence selected for each student.',
  296:        mode => 'html',
  297:        show => 'totals',
  298:        show_links => 'no',
  299:        },
  300:      { name  => 'HTML, summary table only',
  301:        value => 'html summary table only',
  302:        description => 'Output HTML, but only the final summary table for '.
  303:            'all students across all sequences.',
  304:        mode => 'html',
  305:        show => 'final table',
  306:        show_links => 'no',
  307:        },
  308:      { name  => 'Excel, scores only',
  309:        value => 'excel, scores only',
  310:        description => 'Output an Excel file (compatable with Excel 95), '.
  311: 	   'with a single column for each sequence showing the students '.
  312: 	   'score.',
  313:        mode => 'excel',
  314:        show => 'scores',
  315:        show_links => 'no',
  316:            },
  317:      { name  => 'Excel, totals',
  318:        value => 'excel, totals',
  319:        description => 'Output an Excel file (compatable with Excel 95), '.
  320: 	   'with two columns for each sequence, the students score on the '.
  321: 	   'sequence and the students maximum possible on the sequence',
  322:        mode => 'excel',
  323:        show => 'totals',
  324:        show_links => 'no',
  325:            },
  326:      { name  => 'multi-sheet Excel',
  327:        value => 'multi-sheet excel',
  328:        description => 'Output an Excel file (compatable with Excel 95), '.
  329: 	   'with a seperate worksheet for each sequence you have selected '.
  330:            'the data for each problem part '.
  331:            '(number of tries, status, points awarded) will be listed.',
  332:        mode => 'multi-sheet excel',
  333:        show => 'totals',
  334:        show_links => 'no',
  335:            },
  336:      { name  => 'multi-sheet Excel, by section',
  337:        value => 'multi-sheet excel, by section',
  338:        description => 'Output an Excel file (compatable with Excel 95), '.
  339: 	   'with a seperate worksheet for each sequence you have selected '.
  340:            'the data for each problem part '.
  341:            '(number of tries, status, points awarded) will be listed.  '.
  342:            'There will be one Excel workbook for each section selected.',
  343:        mode => 'multi-sheet excel',
  344:        show => 'by section',
  345:        show_links => 'no',
  346:            },
  347:      { name  => 'CSV, everything',
  348:        value => 'csv, everything',
  349:        description => '',
  350:        mode => 'csv',
  351:        show => 'all',
  352:        show_links => 'no',
  353:            },
  354:      { name  => 'CSV, scores only',
  355:        value => 'csv, scores only',
  356:        description => '',
  357:        mode => 'csv',
  358:        show => 'scores',
  359:        show_links => 'no',
  360:            },
  361:      { name  => 'CSV, totals',
  362:        value => 'csv, totals',
  363:        description => '',
  364:        mode => 'csv',
  365:        show => 'totals',
  366:        show_links => 'no',
  367:            },
  368:      );
  369: 
  370: sub OutputDescriptions {
  371:     my $Str = '';
  372:     $Str .= "<h2>Output Modes</h2>\n";
  373:     $Str .= "<dl>\n";
  374:     foreach my $outputmode (@OutputOptions) {
  375: 	$Str .="    <dt>".$outputmode->{'name'}."</dt>\n";
  376: 	$Str .="        <dd>".$outputmode->{'description'}."</dd>\n";
  377:     }
  378:     $Str .= "</dl>\n";
  379:     return $Str;
  380: }
  381: 
  382: sub CreateAndParseOutputSelector {
  383:     my $Str = '';
  384:     my $elementname = 'outputmode';
  385:     #
  386:     # Format for output options is 'mode, restrictions';
  387:     my $selected = 'html, with links';
  388:     if (exists($ENV{'form.'.$elementname})) {
  389:         if (ref($ENV{'form.'.$elementname} eq 'ARRAY')) {
  390:             $selected = $ENV{'form.'.$elementname}->[0];
  391:         } else {
  392:             $selected = $ENV{'form.'.$elementname};
  393:         }
  394:     }
  395:     #
  396:     # Set package variables describing output mode
  397:     $show_links  = 'no';
  398:     $output_mode = 'html';
  399:     $show        = 'all';
  400:     foreach my $option (@OutputOptions) {
  401:         next if ($option->{'value'} ne $selected);
  402:         $output_mode = $option->{'mode'};
  403:         $show        = $option->{'show'};
  404:         $show_links  = $option->{'show_links'};
  405:     }
  406: 
  407:     #
  408:     # Build the form element
  409:     $Str = qq/<select size="5" name="$elementname">/;
  410:     foreach my $option (@OutputOptions) {
  411:         $Str .= "\n".'    <option value="'.$option->{'value'}.'"';
  412:         $Str .= " selected " if ($option->{'value'} eq $selected);
  413:         $Str .= ">".$option->{'name'}."<\/option>";
  414:     }
  415:     $Str .= "\n</select>";
  416:     return $Str;
  417: }
  418: 
  419: #######################################################
  420: #######################################################
  421: 
  422: =pod
  423: 
  424: =head2 HTML output routines
  425: 
  426: =item &html_initialize($r)
  427: 
  428: Create labels for the columns of student data to show.
  429: 
  430: =item &html_outputstudent($r,$student)
  431: 
  432: Return a line of the chart for a student.
  433: 
  434: =item &html_finish($r)
  435: 
  436: =cut
  437: 
  438: #######################################################
  439: #######################################################
  440: {
  441:     my $padding;
  442:     my $count;
  443: 
  444:     my $nodata_count; # The number of students for which there is no data
  445:     my %prog_state;   # progress state used by loncommon PrgWin routines
  446: 
  447: sub html_initialize {
  448:     my ($r) = @_;
  449:     #
  450:     $padding = ' 'x3;
  451:     $count = 0;
  452:     $nodata_count = 0;
  453:     #
  454:     $r->print("<h3>".$ENV{'course.'.$ENV{'request.course.id'}.'.description'}.
  455:               "&nbsp;&nbsp;".localtime(time)."</h3>");
  456: 
  457:     #
  458:     # Set up progress window for 'final table' display only
  459:     if ($show eq 'final table') {
  460:         my $studentcount = scalar(@Apache::lonstatistics::Students); 
  461:         %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
  462:             ($r,'Summary Table Status',
  463:              'Summary Table Compilation Progress', $studentcount);
  464:     }
  465:     my $Str = "<pre>\n";
  466:     # First, the @StudentData fields need to be listed
  467:     my @to_show = &get_student_fields_to_show();
  468:     foreach my $field (@to_show) {
  469:         my $title=$Apache::lonstatistics::StudentData{$field}->{'title'};
  470:         my $base =$Apache::lonstatistics::StudentData{$field}->{'base_width'};
  471:         my $width=$Apache::lonstatistics::StudentData{$field}->{'width'};
  472:         $Str .= $title.' 'x($width-$base).$padding;
  473:     }
  474:     # Now the selected sequences need to be listed
  475:     foreach my $sequence (&Apache::lonstatistics::Sequences_with_Assess()){
  476:         my $title = $sequence->{'title'};
  477:         my $base  = $sequence->{'base_width'};
  478:         my $width = $sequence->{'width'};
  479:         $Str .= $title.' 'x($width-$base).$padding;
  480:     }
  481:     $Str .= "total (of shown problems)</pre>\n";
  482:     $Str .= "<pre>";
  483:     #
  484:     # Check for suppression of output
  485:     if ($show eq 'final table') {
  486:         $Str = '';
  487:     }
  488:     $r->print($Str);
  489:     $r->rflush();
  490:     return;
  491: }
  492: 
  493: sub html_outputstudent {
  494:     my ($r,$student) = @_;
  495:     my $Str = '';
  496:     #
  497:     if($count++ % 5 == 0 && $count > 0) {
  498:         $r->print("</pre><pre>");
  499:     }
  500:     # First, the @StudentData fields need to be listed
  501:     my @to_show = &get_student_fields_to_show();
  502:     foreach my $field (@to_show) {
  503:         my $title=$student->{$field};
  504:         my $base = length($title);
  505:         my $width=$Apache::lonstatistics::StudentData{$field}->{'width'};
  506:         $Str .= $title.' 'x($width-$base).$padding;
  507:     }
  508:     # Get ALL the students data
  509:     my %StudentsData;
  510:     my @tmp = &Apache::loncoursedata::get_current_state
  511:         ($student->{'username'},$student->{'domain'},undef,
  512:          $ENV{'request.course.id'});
  513:     if ((scalar @tmp > 0) && ($tmp[0] !~ /^error:/)) {
  514:         %StudentsData = @tmp;
  515:     }
  516:     if (scalar(@tmp) < 1) {
  517:         $nodata_count++;
  518:         return if ($show eq 'final table');
  519:         $Str .= '<font color="blue">No Course Data</font>'."\n";
  520:         $r->print($Str);
  521:         $r->rflush();
  522:         return;
  523:     }
  524:     #
  525:     # By sequence build up the data
  526:     my $studentstats;
  527:     my $PerformanceStr = '';
  528:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
  529:         my ($performance,$score,$seq_max) =
  530:             &StudentPerformanceOnSequence($student,\%StudentsData,
  531:                                           $seq,$show_links);
  532:         my $ratio = $score.'/'.$seq_max;
  533:         #
  534:         if ($show eq 'totals') {
  535:             $performance = ' 'x(length($seq_max)-length($score)).$ratio;
  536:             $performance .= ' 'x($seq->{'width'}-length($performance));
  537:         } elsif ($show eq 'scores') {
  538:             $performance = $score;
  539:             $performance .= ' 'x($seq->{'width'}-length($performance));
  540:         } else {
  541:             # Pad with extra spaces
  542:             $performance .= ' 'x($seq->{'width'}-$seq_max-
  543:                                  length($ratio)
  544:                                  ).$ratio;
  545:         }
  546:         #
  547:         $Str .= $performance.$padding;
  548:         #
  549:         $studentstats->{$seq->{'symb'}}->{'score'}= $score;
  550:         $studentstats->{$seq->{'symb'}}->{'max'}  = $seq_max;
  551:     }
  552:     #
  553:     # Total it up and store the statistics info.
  554:     my ($score,$max) = (0,0);
  555:     while (my ($symb,$seq_stats) = each (%{$studentstats})) {
  556:         $Statistics->{$symb}->{'score'} += $seq_stats->{'score'};
  557:         $Statistics->{$symb}->{'max'}   += $seq_stats->{'max'};
  558:         $score += $seq_stats->{'score'};
  559:         $max   += $seq_stats->{'max'};
  560:     }
  561:     $Str .= ' '.' 'x(length($max)-length($score)).$score.'/'.$max;
  562:     $Str .= " \n";
  563:     #
  564:     # Check for suppressed output and update the progress window if so...
  565:     if ($show eq 'final table') {
  566:         $Str = '';
  567:         &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
  568:                                                  'last student');
  569:     }
  570:     #
  571:     $r->print($Str);
  572:     #
  573:     $r->rflush();
  574:     return;
  575: }    
  576: 
  577: sub html_finish {
  578:     my ($r) = @_;
  579:     #
  580:     # Check for suppressed output and close the progress window if so
  581:     if ($show eq 'final table') {
  582:         &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  583:     } else {
  584:         $r->print("</pre>\n"); 
  585:     }
  586:     $r->print(&StudentAverageTotal());
  587:     $r->rflush();
  588:     return;
  589: }
  590: 
  591: sub StudentAverageTotal {
  592:     my $Str = "<h3>Summary Tables</h3>\n";
  593:     my $num_students = scalar(@Apache::lonstatistics::Students);
  594:     my $total_ave = 0;
  595:     my $total_max = 0;
  596:     $Str .= '<table border=2 cellspacing="1">'."\n";
  597:     $Str .= "<tr><th>Title</th><th>Average</th><th>Maximum</th></tr>\n";
  598:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
  599:         my $ave;
  600:         if ($num_students > $nodata_count) {
  601:             $ave = int(100*($Statistics->{$seq->{'symb'}}->{'score'}/
  602:                             ($num_students-$nodata_count)))/100;
  603:         } else {
  604:             $ave = 0;
  605:         }
  606:         $total_ave += $ave;
  607:         my $max = $seq->{'num_assess_parts'};
  608:         $total_max += $max;
  609:         if ($ave == 0) {
  610:             $ave = "0.00";
  611:         }
  612:         $ave .= '&nbsp;';
  613:         $max .= '&nbsp;&nbsp;&nbsp;';
  614:         $Str .= '<tr><td>'.$seq->{'title'}.'</td>'.
  615:             '<td align="right">'.$ave.'</td>'.
  616:                 '<td align="right">'.$max.'</td></tr>'."\n";
  617:     }
  618:     $total_ave = int(100*$total_ave)/100; # only two digit
  619:     $Str .= "</table>\n";
  620:     $Str .= '<table border=2 cellspacing="1">'."\n";
  621:     $Str .= '<tr><th>Number of Students</th><th>Average</th>'.
  622:         "<th>Maximum</th></tr>\n";
  623:     $Str .= '<tr><td>'.($num_students-$nodata_count).'</td>'.
  624:         '<td>'.$total_ave.'</td><td>'.$total_max.'</td>';
  625:     $Str .= "</table>\n";
  626:     return $Str;
  627: }
  628: 
  629: }
  630: 
  631: #######################################################
  632: #######################################################
  633: 
  634: =pod
  635: 
  636: =head2 Multi-Sheet EXCEL subroutines
  637: 
  638: =item &multi_sheet_excel_initialize($r)
  639: 
  640: =item &multi_sheet_excel_outputstudent($r,$student)
  641: 
  642: =item &multi_sheet_excel_finish($r)
  643: 
  644: =cut
  645: 
  646: #######################################################
  647: #######################################################
  648: {
  649: 
  650: sub multi_sheet_excel_initialize {
  651:     my ($r)=@_;
  652:     $r->print("<h1>Not yet implemented</h1>");
  653:     # 
  654:     # Estimate the size of the file.  We would like to have < 5 megs of data.
  655:     my $max_size = 5000000;
  656:     my $num_students  = scalar(@Apache::lonstatistics::Students);
  657:     my $num_sequences = 0;
  658:     my $num_data_per_part  = 2; # 'status' and 'numtries'
  659:     my $fields_per_student = scalar(&get_student_fields_to_show());
  660:     my $bytes_per_field    = 20; # Back of the envelope calculation
  661:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
  662:         $num_sequences++ if ($seq->{'num_assess'} > 0);
  663:         $fields_per_student += $num_data_per_part * $seq->{'num_assess_parts'};
  664:     }
  665:     my $size_estimate = $fields_per_student*$num_students*$bytes_per_field;
  666:     #
  667:     # Compute number of workbooks
  668:     my $num_workbooks = 1;
  669:     if ($size_estimate > $max_size) { # try to stay under 5 megs
  670:         $num_workbooks += int($size_estimate / $max_size);
  671:     }
  672:     if ($show eq 'by section') {
  673:         if (@Apache::lonstatistics::SelectedSections > 1 && 
  674:             $Apache::lonstatistics::SelectedSections[0] ne 'all') {
  675:             $num_workbooks = scalar(@Apache::lonstatistics::SelectedSections);
  676:         } else {
  677:             # @Apache::lonstatistics::Sections contains 'all' as well.
  678:             $num_workbooks = scalar(@Apache::lonstatistics::Sections) - 1;
  679:         }
  680:     }
  681:     
  682:     $r->print("Maximum allowed size: ".$max_size." bytes<br />");
  683:     $r->print("Number of students: ".$num_students."<br />");
  684:     $r->print("Number of fields per student: ".$fields_per_student."<br />");
  685:     $r->print("Total number of fields: ".($fields_per_student*$num_students).
  686:               "<br />");
  687:     $r->print("Bytes per field: ".$bytes_per_field." (estimated)"."<br />");
  688:     $r->print("Estimated size: ".$size_estimate." bytes<br />");
  689:     $r->print("Number of workbooks: ".$num_workbooks."<br />");
  690:     $r->rflush();
  691:     return;
  692: }
  693: 
  694: sub multi_sheet_excel_outputstudent {
  695:     my ($r,$student) = @_;
  696: }
  697: 
  698: sub multi_sheet_excel_finish {
  699:     my ($r) = @_;
  700: }
  701: 
  702: }
  703: #######################################################
  704: #######################################################
  705: 
  706: =pod
  707: 
  708: =head2 EXCEL subroutines
  709: 
  710: =item &excel_initialize($r)
  711: 
  712: =item &excel_outputstudent($r,$student)
  713: 
  714: =item &excel_finish($r)
  715: 
  716: =cut
  717: 
  718: #######################################################
  719: #######################################################
  720: {
  721: 
  722: my $excel_sheet;
  723: my $excel_workbook;
  724: 
  725: my $filename;
  726: my $rows_output;
  727: my $cols_output;
  728: 
  729: my %prog_state; # progress window state
  730: 
  731: sub excel_initialize {
  732:     my ($r) = @_;
  733:     #
  734:     $filename = '/prtspool/'.
  735:         $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
  736:             time.'_'.rand(1000000000).'.xls';
  737:     #
  738:     $excel_workbook = undef;
  739:     $excel_sheet = undef;
  740:     #
  741:     $rows_output = 0;
  742:     $cols_output = 0;
  743:     #
  744:     # Create sheet
  745:     $excel_workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
  746:     #
  747:     # Check for errors
  748:     if (! defined($excel_workbook)) {
  749:         $r->log_error("Error creating excel spreadsheet $filename: $!");
  750:         $r->print("Problems creating new Excel file.  ".
  751:                   "This error has been logged.  ".
  752:                   "Please alert your LON-CAPA administrator");
  753:         return ;
  754:     }
  755:     #
  756:     # The excel spreadsheet stores temporary data in files, then put them
  757:     # together.  If needed we should be able to disable this (memory only).
  758:     # The temporary directory must be specified before calling 'addworksheet'.
  759:     # File::Temp is used to determine the temporary directory.
  760:     $excel_workbook->set_tempdir($Apache::lonnet::tmpdir);
  761:     #
  762:     # Add a worksheet
  763:     my $sheetname = $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
  764:     if (length($sheetname) > 31) {
  765:         $sheetname = substr($sheetname,0,31);
  766:     }
  767:     $excel_sheet = $excel_workbook->addworksheet($sheetname);
  768:     #
  769:     # Put the course description in the header
  770:     $excel_sheet->write($rows_output,$cols_output++,
  771:                    $ENV{'course.'.$ENV{'request.course.id'}.'.description'});
  772:     $cols_output += 3;
  773:     #
  774:     # Put a description of the sections listed
  775:     my $sectionstring = '';
  776:     my @Sections = @Apache::lonstatistics::SelectedSections;
  777:     if (scalar(@Sections) > 1) {
  778:         if (scalar(@Sections) > 2) {
  779:             my $last = pop(@Sections);
  780:             $sectionstring = "Sections ".join(', ',@Sections).', and '.$last;
  781:         } else {
  782:             $sectionstring = "Sections ".join(' and ',@Sections);
  783:         }
  784:     } else {
  785:         if ($Sections[0] eq 'all') {
  786:             $sectionstring = "All sections";
  787:         } else {
  788:             $sectionstring = "Section ".$Sections[0];
  789:         }
  790:     }
  791:     $excel_sheet->write($rows_output,$cols_output++,$sectionstring);
  792:     $cols_output += scalar(@Sections);
  793:     #
  794:     # Put the date in there too
  795:     $excel_sheet->write($rows_output,$cols_output++,
  796:                         'Compiled on '.localtime(time));
  797:     #
  798:     $rows_output++;
  799:     #
  800:     # Add the student headers
  801:     $cols_output = 0;
  802:     foreach my $field (&get_student_fields_to_show()) {
  803:         $excel_sheet->write($rows_output,$cols_output++,$field);
  804:     }
  805:     #
  806:     # Add the Sequence Headers
  807:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
  808:         $excel_sheet->write($rows_output,$cols_output,$seq->{'title'});
  809:         if ($show eq 'totals') {
  810:             $excel_sheet->write($rows_output+1,$cols_output,'score');
  811:             $excel_sheet->write($rows_output+1,$cols_output+1,'maximum');
  812:             $cols_output += 2;
  813:         } else {
  814:             $cols_output++;
  815:         }
  816:     }
  817:     #
  818:     # Bookkeeping
  819:     if ($show eq 'totals') {
  820:         $rows_output += 2;
  821:     } else {
  822:         $rows_output += 1;
  823:     }
  824:     #
  825:     # Let the user know what we are doing
  826:     my $studentcount = scalar(@Apache::lonstatistics::Students); 
  827:     $r->print("<h1>Compiling Excel spreadsheet for ".
  828:               $studentcount.' student');
  829:     $r->print('s') if ($studentcount > 1);
  830:     $r->print("</h1>\n");
  831:     $r->rflush();
  832:     #
  833:     # Initialize progress window
  834:     %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
  835:         ($r,'Excel File Compilation Status',
  836:          'Excel File Compilation Progress', $studentcount);
  837:     #
  838:     return;
  839: }
  840: 
  841: sub excel_outputstudent {
  842:     my ($r,$student) = @_;
  843:     return if (! defined($excel_sheet));
  844:     $cols_output=0;
  845:     #
  846:     # Write out student data
  847:     my @to_show = &get_student_fields_to_show();
  848:     foreach my $field (@to_show) {
  849:         $excel_sheet->write($rows_output,$cols_output++,$student->{$field});
  850:     }
  851:     #
  852:     # Get student assessment data
  853:     my %StudentsData;
  854:     my @tmp = &Apache::loncoursedata::get_current_state($student->{'username'},
  855:                                                         $student->{'domain'},
  856:                                                         undef,
  857:                                                    $ENV{'request.course.id'});
  858:     if ((scalar @tmp > 0) && ($tmp[0] !~ /^error:/)) {
  859:         %StudentsData = @tmp;
  860:     }
  861:     #
  862:     # Write out sequence scores and totals data
  863:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
  864:         my ($performance,$score,$seq_max) =
  865:             &StudentPerformanceOnSequence($student,\%StudentsData,
  866:                                           $seq,'no');
  867:         if ($show eq 'totals' || $show eq 'scores') {
  868:             $excel_sheet->write($rows_output,$cols_output++,$score);
  869:         }
  870:         if ($show eq 'totals') {
  871:             $excel_sheet->write($rows_output,$cols_output++,$seq_max);
  872:         }
  873:     }
  874:     #
  875:     # Bookkeeping
  876:     $rows_output++; 
  877:     $cols_output=0;
  878:     #
  879:     # Update the progress window
  880:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
  881:     return;
  882: }
  883: 
  884: sub excel_finish {
  885:     my ($r) = @_;
  886:     return if (! defined($excel_sheet));
  887:     #
  888:     # Write the excel file
  889:     $excel_workbook->close();
  890:     my $c = $r->connection();
  891:     #
  892:     return if($c->aborted());
  893:     #
  894:     # Close the progress window
  895:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  896:     #
  897:     # Tell the user where to get their excel file
  898:     $r->print('<br />'.
  899:               '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
  900:     $r->rflush();
  901:     return;
  902: }
  903: 
  904: }
  905: #######################################################
  906: #######################################################
  907: 
  908: =pod
  909: 
  910: =head2 CSV output routines
  911: 
  912: =item &csv_initialize($r)
  913: 
  914: =item &csv_outputstudent($r,$student)
  915: 
  916: =item &csv_finish($r)
  917: 
  918: =cut
  919: 
  920: #######################################################
  921: #######################################################
  922: {
  923: 
  924: my $outputfile;
  925: my $filename;
  926: 
  927: my %prog_state; # progress window state
  928: 
  929: sub csv_initialize{
  930:     my ($r) = @_;
  931:     # 
  932:     # Clean up
  933:     $filename = undef;
  934:     $outputfile = undef;
  935:     undef(%prog_state);
  936:     #
  937:     # Open a file
  938:     $filename = '/prtspool/'.
  939:         $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
  940:             time.'_'.rand(1000000000).'.csv';
  941:     unless ($outputfile = Apache::File->new('>/home/httpd'.$filename)) {
  942:         $r->log_error("Couldn't open $filename for output $!");
  943:         $r->print("Problems occured in writing the csv file.  ".
  944:                   "This error has been logged.  ".
  945:                   "Please alert your LON-CAPA administrator.");
  946:         $outputfile = undef;
  947:     }
  948:     #
  949:     # Datestamp
  950:     my $description = $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
  951:     print $outputfile '"'.&Apache::loncommon::csv_translate($description).'",'.
  952:         '"'.&Apache::loncommon::csv_translate(scalar(localtime(time))).'"'.
  953:             "\n";
  954: 
  955:     #
  956:     # Print out the headings
  957:     my $Str = '';
  958:     my $Str2 = undef;
  959:     foreach my $field (&get_student_fields_to_show()) {
  960:         if ($show eq 'scores') {
  961:             $Str .= '"'.&Apache::loncommon::csv_translate($field).'",';
  962:         } elsif ($show eq 'totals') {
  963:             $Str .= '"",'; # first row empty on the student fields
  964:             $Str2 .= '"'.&Apache::loncommon::csv_translate($field).'",';
  965:         } elsif ($show eq 'all') {
  966:             $Str .= '"'.&Apache::loncommon::csv_translate($field).'",';
  967:         }
  968:     }
  969:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
  970:         if ($show eq 'scores') {
  971:             $Str .= '"'.&Apache::loncommon::csv_translate($seq->{'title'}).
  972:                 '",';
  973:         } elsif ($show eq 'totals') {
  974:             $Str  .= '"'.&Apache::loncommon::csv_translate($seq->{'title'}).
  975:                 '","",';
  976:             $Str2 .= '"score","total possible",';
  977:         } elsif ($show eq 'all') {
  978:             $Str  .= '"'.&Apache::loncommon::csv_translate($seq->{'title'}).
  979:                 '",';
  980:             $Str .= '"",'x($seq->{'num_assess_parts'}-1);
  981:             $Str .= '"score","total possible",';
  982:         }
  983:     }
  984:     chop($Str);
  985:     $Str .= "\n";
  986:     print $outputfile $Str;
  987:     if (defined($Str2)) {
  988:         chop($Str2);
  989:         $Str2 .= "\n";
  990:         print $outputfile $Str2;
  991:     }
  992:     #
  993:     # Initialize progress window
  994:     my $studentcount = scalar(@Apache::lonstatistics::Students);
  995:     %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
  996:         ($r,'CSV File Compilation Status',
  997:          'CSV File Compilation Progress', $studentcount);
  998:     return;
  999: }
 1000: 
 1001: sub csv_outputstudent {
 1002:     my ($r,$student) = @_;
 1003:     return if (! defined($outputfile));
 1004:     my $Str = '';
 1005:     #
 1006:     # Output student fields
 1007:     my @to_show = &get_student_fields_to_show();
 1008:     foreach my $field (@to_show) {
 1009:         $Str .= '"'.&Apache::loncommon::csv_translate($student->{$field}).'",';
 1010:     }
 1011:     #
 1012:     # Get student assessment data
 1013:     my %StudentsData;
 1014:     my @tmp = &Apache::loncoursedata::get_current_state($student->{'username'},
 1015:                                                         $student->{'domain'},
 1016:                                                         undef,
 1017:                                                    $ENV{'request.course.id'});
 1018:     if ((scalar @tmp > 0) && ($tmp[0] !~ /^error:/)) {
 1019:         %StudentsData = @tmp;
 1020:     }
 1021:     #
 1022:     # Output performance data
 1023:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
 1024:         my ($performance,$score,$seq_max) =
 1025:             &StudentPerformanceOnSequence($student,\%StudentsData,
 1026:                                           $seq,'no');
 1027:         if ($show eq 'scores') {
 1028:             $Str .= '"'.$score.'",';
 1029:         } elsif ($show eq 'totals') {
 1030:             $Str  .= '"'.$score.'","'.$seq_max.'",';
 1031:         } elsif ($show eq 'all') {
 1032:             $Str .= '"'.join('","',(split(//,$performance),$score,$seq_max)).
 1033:                 '",';
 1034:         }
 1035:     }
 1036:     chop($Str);
 1037:     $Str .= "\n";
 1038:     print $outputfile $Str;
 1039:     #
 1040:     # Update the progress window
 1041:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 1042:     return;
 1043: }
 1044: 
 1045: sub csv_finish {
 1046:     my ($r) = @_;
 1047:     return if (! defined($outputfile));
 1048:     close($outputfile);
 1049:     #
 1050:     my $c = $r->connection();
 1051:     return if ($c->aborted());
 1052:     #
 1053:     # Close the progress window
 1054:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 1055:     #
 1056:     # Tell the user where to get their csv file
 1057:     $r->print('<br />'.
 1058:               '<a href="'.$filename.'">Your csv file.</a>'."\n");
 1059:     $r->rflush();
 1060:     return;
 1061:     
 1062: }
 1063: 
 1064: }
 1065: 
 1066: #######################################################
 1067: #######################################################
 1068: 
 1069: =pod
 1070: 
 1071: =item &StudentPerformanceOnSequence()
 1072: 
 1073: Inputs:
 1074: 
 1075: =over 4
 1076: 
 1077: =item $student
 1078: 
 1079: =item $studentdata Hash ref to all student data
 1080: 
 1081: =item $seq Hash ref, the sequence we are working on
 1082: 
 1083: =item $links if defined we will output links to each resource.
 1084: 
 1085: =back
 1086: 
 1087: =cut
 1088: 
 1089: #######################################################
 1090: #######################################################
 1091: sub StudentPerformanceOnSequence {
 1092:     my ($student,$studentdata,$seq,$links) = @_;
 1093:     $links = 'no' if (! defined($links));
 1094:     my $Str = '';
 1095:     my ($sum,$max) = (0,0);
 1096:     foreach my $resource (@{$seq->{'contents'}}) {
 1097:         next if ($resource->{'type'} ne 'assessment');
 1098:         my $resource_data = $studentdata->{$resource->{'symb'}};
 1099:         my $value = '';
 1100:         foreach my $partnum (@{$resource->{'parts'}}) {
 1101:             $max++;
 1102:             my $symbol = ' '; # default to space
 1103:             #
 1104:             if (exists($resource_data->{'resource.'.$partnum.'.solved'})) {
 1105:                 my $status = $resource_data->{'resource.'.$partnum.'.solved'};
 1106:                 if ($status eq 'correct_by_override') {
 1107:                     $symbol = '+';
 1108:                     $sum++;
 1109:                 } elsif ($status eq 'incorrect_by_override') {
 1110:                     $symbol = '-';
 1111:                 } elsif ($status eq 'ungraded_attempted') {
 1112:                     $symbol = '#';
 1113:                 } elsif ($status eq 'incorrect_attempted')  {
 1114:                     $symbol = '.';
 1115:                 } elsif ($status eq 'excused') {
 1116:                     $symbol = 'x';
 1117:                     $max--;
 1118:                 } elsif ($status eq 'correct_by_student' &&
 1119:                     exists($resource_data->{'resource.'.$partnum.'.tries'})){
 1120:                     my $num = $resource_data->{'resource.'.$partnum.'.tries'};
 1121:                     if ($num > 9) {
 1122:                         $symbol = '*';
 1123:                     } elsif ($num > 0) {
 1124:                         $symbol = $num;
 1125:                     } else {
 1126:                         $symbol = ' ';
 1127:                     }
 1128:                     $sum++;
 1129:                 } else {
 1130:                     $symbol = ' ';
 1131:                 }
 1132:             } else {
 1133:                 # Unsolved.  Did they try?
 1134:                 if (exists($resource_data->{'resource.'.$partnum.'.tries'})){
 1135:                     $symbol = '.';
 1136:                 } else {
 1137:                     $symbol = ' ';
 1138:                 }
 1139:             }
 1140:             #
 1141:             if ($links eq 'yes' && $symbol ne ' ') {
 1142:                 $symbol = '<a href="/adm/grades'.
 1143:                     '?symb='.&Apache::lonnet::escape($resource->{'symb'}).
 1144:                         '&student='.$student->{'username'}.
 1145:                             '&domain='.$student->{'domain'}.
 1146:                                 '&command=submission">'.$symbol.'</a>';
 1147:             }
 1148:             $value .= $symbol;
 1149:         }
 1150:         $Str .= $value;
 1151:     }
 1152:     return ($Str,$sum,$max);
 1153: }
 1154: 
 1155: #######################################################
 1156: #######################################################
 1157: 
 1158: =pod
 1159: 
 1160: =item &CreateLegend()
 1161: 
 1162: This function returns a formatted string containing the legend for the
 1163: chart.  The legend describes the symbols used to represent grades for
 1164: problems.
 1165: 
 1166: =cut
 1167: 
 1168: #######################################################
 1169: #######################################################
 1170: sub CreateLegend {
 1171:     my $Str = "<p><pre>".
 1172:               "   1  correct by student in 1 try\n".
 1173:               "   7  correct by student in 7 tries\n".
 1174:               "   *  correct by student in more than 9 tries\n".
 1175: 	      "   +  correct by hand grading or override\n".
 1176:               "   -  incorrect by override\n".
 1177: 	      "   .  incorrect attempted\n".
 1178: 	      "   #  ungraded attempted\n".
 1179:               "      not attempted (blank field)\n".
 1180: 	      "   x  excused".
 1181:               "</pre><p>";
 1182:     return $Str;
 1183: }
 1184: 
 1185: #######################################################
 1186: #######################################################
 1187: 
 1188: =pod 
 1189: 
 1190: =back
 1191: 
 1192: =cut
 1193: 
 1194: #######################################################
 1195: #######################################################
 1196: 
 1197: 1;
 1198: 
 1199: __END__

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