File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.127: download - view: text, annotated - select for diffs
Sun Jan 22 21:11:59 2006 UTC (18 years, 5 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Towards fixing bug 4508: Instead of just putting in a
SUM(start:end)
for the Total column, put in
IF(COUNT(start:end),SUM(start:end),"")

This will sum the scores up if there are any scores, but put a blank
string into the sum if there were no attempts at all. If the professor
then averages that column, this will much more closely match the
LON-CAPA-claimed average for the sequence.

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: lonstudentassessment.pm,v 1.127 2006/01/22 21:11:59 bowersj2 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::loncommon();
   56: use Apache::loncoursedata;
   57: use Apache::lonnet; # for logging porpoises
   58: use Apache::lonlocal;
   59: use Time::HiRes;
   60: use Spreadsheet::WriteExcel;
   61: use Spreadsheet::WriteExcel::Utility();
   62: 
   63: #######################################################
   64: #######################################################
   65: =pod
   66: 
   67: =item Package Variables
   68: 
   69: =over 4
   70: 
   71: =item $Statistics Hash ref to store student data.  Indexed by symb,
   72:       contains hashes with keys 'score' and 'max'.
   73: 
   74: =cut
   75: 
   76: #######################################################
   77: #######################################################
   78: 
   79: my $Statistics;
   80: 
   81: #######################################################
   82: #######################################################
   83: 
   84: =pod
   85: 
   86: =item $show_links 'yes' or 'no' for linking to student performance data
   87: 
   88: =item $output_mode 'html', 'excel', or 'csv' for output mode
   89: 
   90: =item $show 'all', 'totals', or 'scores' determines how much data is output
   91: 
   92: =item $single_student_mode evaluates to true if we are showing only one
   93: student.
   94: 
   95: =cut
   96: 
   97: #######################################################
   98: #######################################################
   99: my $show_links;
  100: my $output_mode;
  101: my $chosen_output;
  102: my $single_student_mode;
  103: 
  104: #######################################################
  105: #######################################################
  106: # End of package variable declarations
  107: 
  108: =pod
  109: 
  110: =back
  111: 
  112: =cut
  113: 
  114: #######################################################
  115: #######################################################
  116: 
  117: =pod
  118: 
  119: =item &BuildStudentAssessmentPage()
  120: 
  121: Inputs: 
  122: 
  123: =over 4
  124: 
  125: =item $r Apache Request
  126: 
  127: =item $c Apache Connection 
  128: 
  129: =back
  130: 
  131: =cut
  132: 
  133: #######################################################
  134: #######################################################
  135: sub BuildStudentAssessmentPage {
  136:     my ($r,$c)=@_;
  137:     #
  138:     undef($Statistics);
  139:     undef($show_links);
  140:     undef($output_mode);
  141:     undef($chosen_output);
  142:     undef($single_student_mode);
  143:     #
  144:     my %Saveable_Parameters = ('Status' => 'scalar',
  145:                                'chartoutputmode' => 'scalar',
  146:                                'chartoutputdata' => 'scalar',
  147:                                'Section' => 'array',
  148:                                'StudentData' => 'array',
  149:                                'Maps' => 'array');
  150:     &Apache::loncommon::store_course_settings('chart',\%Saveable_Parameters);
  151:     &Apache::loncommon::restore_course_settings('chart',\%Saveable_Parameters);
  152:     #
  153:     &Apache::lonstatistics::PrepareClasslist();
  154:     #
  155:     $single_student_mode = 0;
  156:     $single_student_mode = 1 if ($env{'form.SelectedStudent'});
  157:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  158:                                             ['selectstudent']);
  159:     if ($env{'form.selectstudent'}) {
  160:         &Apache::lonstatistics::DisplayClasslist($r);
  161:         return;
  162:     }
  163:     #
  164:     # Print out the HTML headers for the interface
  165:     #    This also parses the output mode selector
  166:     #    This step must *always* be done.
  167:     $r->print(&CreateInterface());
  168:     $r->print('<input type="hidden" name="notfirstrun" value="true" />');
  169:     $r->print('<input type="hidden" name="sort" value="'.
  170:               $env{'form.sort'}.'" />');
  171:     $r->rflush();
  172:     #
  173:     if (! exists($env{'form.notfirstrun'}) && ! $single_student_mode) {
  174:         return;
  175:     }
  176:     $r->print('<h4>'.
  177:               &Apache::lonstatistics::section_and_enrollment_description().
  178:               '</h4>');
  179:     #
  180:     my $initialize     = \&html_initialize;
  181:     my $output_student = \&html_outputstudent;
  182:     my $finish         = \&html_finish;
  183:     #
  184:     if ($output_mode eq 'excel') {
  185:         $initialize     = \&excel_initialize;
  186:         $output_student = \&excel_outputstudent;
  187:         $finish         = \&excel_finish;
  188:     } elsif ($output_mode eq 'csv') {
  189:         $initialize     = \&csv_initialize;
  190:         $output_student = \&csv_outputstudent;
  191:         $finish         = \&csv_finish;
  192:     }
  193:     #
  194:     if($c->aborted()) {  return ; }
  195:     #
  196:     # Determine which students we want to look at
  197:     my @Students;
  198:     if ($single_student_mode) {
  199:         @Students = (&Apache::lonstatistics::current_student());
  200:         $r->print(&next_and_previous_buttons());
  201:         $r->rflush();
  202:     } else {
  203:         @Students = @Apache::lonstatistics::Students;
  204:     }
  205:     #
  206:     # Perform generic initialization tasks
  207:     #       Since we use lonnet::EXT to retrieve problem weights,
  208:     #       to ensure current data we must clear the caches out.
  209:     #       This makes sure that parameter changes at the student level
  210:     #       are immediately reflected in the chart.
  211:     &Apache::lonnet::clear_EXT_cache_status();
  212:     #
  213:     # Clean out loncoursedata's package data, just to be safe.
  214:     &Apache::loncoursedata::clear_internal_caches();
  215:     #
  216:     # Call the initialize routine selected above
  217:     $initialize->($r);
  218:     foreach my $student (@Students) {
  219:         if($c->aborted()) { 
  220:             $finish->($r);
  221:             return ; 
  222:         }
  223:         # Call the output_student routine selected above
  224:         $output_student->($r,$student);
  225:     }
  226:     # Call the "finish" routine selected above
  227:     $finish->($r);
  228:     #
  229:     return;
  230: }
  231: 
  232: #######################################################
  233: #######################################################
  234: sub next_and_previous_buttons {
  235:     my $Str = '';
  236:     $Str .= '<input type="hidden" name="SelectedStudent" value="'.
  237:         $env{'form.SelectedStudent'}.'" />';
  238:     #
  239:     # Build the previous student link
  240:     my $previous = &Apache::lonstatistics::previous_student();
  241:     my $previousbutton = '';
  242:     if (defined($previous)) {
  243:         my $sname = $previous->{'username'}.':'.$previous->{'domain'};
  244:         $previousbutton .= '<input type="button" value="'.
  245:             'Previous Student ('.
  246:             $previous->{'username'}.'@'.$previous->{'domain'}.')'.
  247:             '" onclick="document.Statistics.SelectedStudent.value='.
  248:             "'".$sname."'".';'.
  249:             'document.Statistics.submit();" />';
  250:     } else {
  251:         $previousbutton .= '<input type="button" value="'.
  252:             'Previous student (none)'.'" />';
  253:     }
  254:     #
  255:     # Build the next student link
  256:     my $next = &Apache::lonstatistics::next_student();
  257:     my $nextbutton = '';
  258:     if (defined($next)) {
  259:         my $sname = $next->{'username'}.':'.$next->{'domain'};
  260:         $nextbutton .= '<input type="button" value="'.
  261:             'Next Student ('.
  262:             $next->{'username'}.'@'.$next->{'domain'}.')'.
  263:             '" onclick="document.Statistics.SelectedStudent.value='.
  264:             "'".$sname."'".';'.
  265:             'document.Statistics.submit();" />';
  266:     } else {
  267:         $nextbutton .= '<input type="button" value="'.
  268:             'Next student (none)'.'" />';
  269:     }
  270:     #
  271:     # Build the 'all students' button
  272:     my $all = '';
  273:     $all .= '<input type="button" value="All Students" '.
  274:             '" onclick="document.Statistics.SelectedStudent.value='.
  275:             "''".';'.'document.Statistics.submit();" />';
  276:     $Str .= $previousbutton.('&nbsp;'x5).$all.('&nbsp;'x5).$nextbutton;
  277:     return $Str;
  278: }
  279: 
  280: #######################################################
  281: #######################################################
  282: 
  283: sub get_student_fields_to_show {
  284:     my @to_show = @Apache::lonstatistics::SelectedStudentData;
  285:     foreach (@to_show) {
  286:         if ($_ eq 'all') {
  287:             @to_show = @Apache::lonstatistics::StudentDataOrder;
  288:             last;
  289:         }
  290:     }
  291:     return @to_show;
  292: }
  293: 
  294: #######################################################
  295: #######################################################
  296: 
  297: =pod
  298: 
  299: =item &CreateInterface()
  300: 
  301: Called by &BuildStudentAssessmentPage to create the top part of the
  302: page which displays the chart.
  303: 
  304: Inputs: None
  305: 
  306: Returns:  A string containing the HTML for the headers and top table for 
  307: the chart page.
  308: 
  309: =cut
  310: 
  311: #######################################################
  312: #######################################################
  313: sub CreateInterface {
  314:     my $Str = '';
  315:     $Str .= &Apache::lonhtmlcommon::breadcrumbs(undef,'Chart');
  316: #    $Str .= &CreateLegend();
  317:     $Str .= '<table cellspacing="5">'."\n";
  318:     $Str .= '<tr>';
  319:     $Str .= '<td align="center"><b>'.&mt('Sections').'</b></td>';
  320:     $Str .= '<td align="center"><b>'.&mt('Student Data</b>').'</td>';
  321:     $Str .= '<td align="center"><b>'.&mt('Enrollment Status').'</b></td>';
  322:     $Str .= '<td align="center"><b>'.&mt('Sequences and Folders').'</b></td>';
  323:     $Str .= '<td align="center"><b>'.&mt('Output Format').'</b>'.
  324:         &Apache::loncommon::help_open_topic("Chart_Output_Formats").
  325:         '</td>';
  326:     $Str .= '<td align="center"><b>'.&mt('Output Data').'</b>'.
  327:         &Apache::loncommon::help_open_topic("Chart_Output_Data").
  328:         '</td>';
  329:     $Str .= '</tr>'."\n";
  330:     #
  331:     $Str .= '<tr><td align="center">'."\n";
  332:     $Str .= &Apache::lonstatistics::SectionSelect('Section','multiple',5);
  333:     $Str .= '</td><td align="center">';
  334:     $Str .= &Apache::lonstatistics::StudentDataSelect('StudentData','multiple',
  335:                                                       5,undef);
  336:     $Str .= '</td><td>'."\n";
  337:     $Str .= &Apache::lonhtmlcommon::StatusOptions(undef,undef,5);
  338:     $Str .= '</td><td>'."\n";
  339:     $Str .= &Apache::lonstatistics::map_select('Maps','multiple,all',5);
  340:     $Str .= '</td><td>'."\n";
  341:     $Str .= &CreateAndParseOutputSelector();
  342:     $Str .= '</td><td>'."\n";
  343:     $Str .= &CreateAndParseOutputDataSelector();
  344:     $Str .= '</td></tr>'."\n";
  345:     $Str .= '</table>'."\n";
  346:     $Str .= '<input type="submit" name="Generate Chart" value="'.
  347:         &mt('Generate Chart').'" />';
  348:     $Str .= '&nbsp;'x5;
  349:     $Str .= '<input type="submit" name="selectstudent" value="'.
  350:         &mt('Select One Student').'" />';
  351:     $Str .= '&nbsp;'x5;
  352:     $Str .= '<input type="submit" name="ClearCache" value="'.
  353:         &mt('Clear Caches').'" />';
  354:     $Str .= '&nbsp;'x5;
  355:     $Str .= 
  356:         &mt('Status [_1]',
  357:             '<input type="text" name="stats_status" size="60" value="" />');
  358:     $Str .= '<br />';
  359:     return $Str;
  360: }
  361: 
  362: #######################################################
  363: #######################################################
  364: 
  365: =pod
  366: 
  367: =item &CreateAndParseOutputSelector()
  368: 
  369: =cut
  370: 
  371: #######################################################
  372: #######################################################
  373: my @OutputOptions = 
  374:     ({ name  => 'HTML, with links',
  375:        value => 'html, with links',
  376:        description => 'Output HTML with each symbol linked to the problem '.
  377: 	   'which generated it.',
  378:        mode => 'html',
  379:        show_links => 'yes',
  380:        },
  381:      { name  => 'HTML, with all links',
  382:        value => 'html, with all links',
  383:        description => 'Output HTML with each symbol linked to the problem '.
  384: 	   'which generated it.  '.
  385:            'This includes links for unattempted problems.',
  386:        mode => 'html',
  387:        show_links => 'all',
  388:        },
  389:      { name  => 'HTML, without links',
  390:        value => 'html, without links',
  391:        description => 'Output HTML.  By not including links, the size of the'.
  392: 	   ' web page is greatly reduced.  If your browser crashes on the '.
  393: 	   'full display, try this.',
  394:        mode => 'html',
  395:        show_links => 'no',
  396:            },
  397:      { name  => 'Excel',
  398:        value => 'excel',
  399:        description => 'Output an Excel file (compatable with Excel 95).',
  400:        mode => 'excel',
  401:        show_links => 'no',
  402:    },
  403:      { name  => 'CSV',
  404:        value => 'csv',
  405:        description => 'Output a comma separated values file suitable for '.
  406:            'import into a spreadsheet program.  Using this method as opposed '.
  407:            'to Excel output allows you to organize your data before importing'.
  408:            ' it into a spreadsheet program.',
  409:        mode => 'csv',
  410:        show_links => 'no',
  411:            },
  412:      );
  413: 
  414: sub OutputDescriptions {
  415:     my $Str = '';
  416:     $Str .= "<h2>Output Formats</h2>\n";
  417:     $Str .= "<dl>\n";
  418:     foreach my $outputmode (@OutputOptions) {
  419: 	$Str .="    <dt>".$outputmode->{'name'}."</dt>\n";
  420: 	$Str .="        <dd>".$outputmode->{'description'}."</dd>\n";
  421:     }
  422:     $Str .= "</dl>\n";
  423:     return $Str;
  424: }
  425: 
  426: sub CreateAndParseOutputSelector {
  427:     my $Str = '';
  428:     my $elementname = 'chartoutputmode';
  429:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  430:                                             [$elementname]);
  431:     #
  432:     # Format for output options is 'mode, restrictions';
  433:     my $selected = (&Apache::loncommon::get_env_multiple('form.'.$elementname))[0];
  434:     $selected = 'html, without links' if (!$selected);
  435: 
  436:     #
  437:     # Set package variables describing output mode
  438:     $show_links  = 'no';
  439:     $output_mode = 'html';
  440:     foreach my $option (@OutputOptions) {
  441:         next if ($option->{'value'} ne $selected);
  442:         $output_mode = $option->{'mode'};
  443:         $show_links  = $option->{'show_links'};
  444:     }
  445: 
  446:     #
  447:     # Build the form element
  448:     $Str = qq/<select size="5" name="$elementname">/;
  449:     foreach my $option (@OutputOptions) {
  450:         $Str .= "\n".'    <option value="'.$option->{'value'}.'"';
  451:         $Str .= " selected " if ($option->{'value'} eq $selected);
  452:         $Str .= ">".&mt($option->{'name'})."<\/option>";
  453:     }
  454:     $Str .= "\n</select>";
  455:     return $Str;
  456: }
  457: 
  458: ##
  459: ## Data selector stuff
  460: ##
  461: my @OutputDataOptions =
  462:     (
  463:      { name  => 'Scores Summary',
  464:        base  => 'scores',
  465:        value => 'sum and total',
  466:        scores => 1,
  467:        tries  => 0,
  468:        every_problem => 0,
  469:        sequence_sum => 1,
  470:        sequence_max => 1,
  471:        grand_total => 1,
  472:        grand_maximum => 1,
  473:        summary_table => 1,
  474:        maximum_row => 1,
  475:        shortdesc => 'Total Score and Maximum Possible for each '.
  476:            'Sequence or Folder',
  477:        longdesc => 'The score of each student as well as the '.
  478:            ' maximum possible on each Sequence or Folder.',
  479:        },
  480:      { name  => 'Scores Per Problem',
  481:        base  => 'scores',
  482:        value => 'scores',
  483:        scores => 1,
  484:        tries  => 0,
  485:        correct => 0,
  486:        every_problem => 1,
  487:        sequence_sum => 1,
  488:        sequence_max => 1,
  489:        grand_total => 1,
  490:        grand_maximum => 1,
  491:        summary_table => 1,
  492:        maximum_row => 1,
  493:        shortdesc => 'Score on each Problem Part',
  494:        longdesc =>'The students score on each problem part, computed as'.
  495:            'the part weight * part awarded',
  496:        },
  497:      { name  =>'Tries',
  498:        base  =>'tries',
  499:        value => 'tries',
  500:        scores => 0,
  501:        tries  => 1,
  502:        correct => 0,
  503:        every_problem => 1,
  504:        sequence_sum => 0,
  505:        sequence_max => 0,
  506:        grand_total => 0,
  507:        grand_maximum => 0,
  508:        summary_table => 0,
  509:        maximum_row => 0,
  510:        shortdesc => 'Number of Tries before success on each Problem Part',
  511:        longdesc =>'The number of tries before success on each problem part.',
  512:        non_html_notes => 'negative values indicate an incorrect problem',
  513:        },
  514:      { name  =>'Parts Correct',
  515:        base  =>'tries',
  516:        value => 'parts correct total',
  517:        scores => 0,
  518:        tries  => 0,
  519:        correct => 1,
  520:        every_problem => 1,
  521:        sequence_sum => 1,
  522:        sequence_max => 1,
  523:        grand_total => 1,
  524:        grand_maximum => 1,
  525:        summary_table => 1,
  526:        maximum_row => 0,
  527:        shortdesc => 'Number of Problem Parts completed successfully.',
  528:        longdesc => 'The Number of Problem Parts completed successfully and '.
  529:            'the maximum possible for each student',
  530:        },
  531:      );
  532: 
  533: sub HTMLifyOutputDataDescriptions {
  534:     my $Str = '';
  535:     $Str .= "<h2>Output Data</h2>\n";
  536:     $Str .= "<dl>\n";
  537:     foreach my $option (@OutputDataOptions) {
  538:         $Str .= '    <dt>'.$option->{'name'}.'</dt>';
  539:         $Str .= '<dd>'.$option->{'longdesc'}.'</dd>'."\n";
  540:     }
  541:     $Str .= "</dl>\n";
  542:     return $Str;
  543: }
  544: 
  545: sub CreateAndParseOutputDataSelector {
  546:     my $Str = '';
  547:     my $elementname = 'chartoutputdata';
  548:     #
  549:     my $selected = (&Apache::loncommon::get_env_multiple('form.'.$elementname))[0];
  550:     $selected = 'scores' if (!$selected);
  551: 
  552:     #
  553:     $chosen_output = $OutputDataOptions[0];
  554:     foreach my $option (@OutputDataOptions) {
  555:         if ($option->{'value'} eq $selected) {
  556:             $chosen_output = $option;
  557:         }
  558:     }
  559:     #
  560:     # Build the form element
  561:     $Str = qq/<select size="5" name="$elementname">/;
  562:     foreach my $option (@OutputDataOptions) {
  563:         $Str .= "\n".'    <option value="'.$option->{'value'}.'"';
  564:         $Str .= " selected " if ($option->{'value'} eq $chosen_output->{'value'});
  565:         $Str .= ">".&mt($option->{'name'})."<\/option>";
  566:     }
  567:     $Str .= "\n</select>";
  568:     return $Str;
  569: 
  570: }
  571: 
  572: #######################################################
  573: #######################################################
  574: sub count_parts {
  575:     my ($navmap,$sequence) = @_;
  576:     my @resources = &get_resources($navmap,$sequence);
  577:     my $count = 0;
  578:     foreach my $res (@resources) {
  579:         $count += scalar(@{$res->parts});
  580:     }
  581:     return $count;
  582: }
  583: 
  584: sub get_resources {
  585:     my ($navmap,$sequence) = @_;
  586:     my @resources = $navmap->retrieveResources($sequence,
  587:                                                sub { shift->is_problem(); },
  588:                                                0,0,0);
  589:     return @resources;
  590: }
  591: 
  592: #######################################################
  593: #######################################################
  594: 
  595: =pod
  596: 
  597: =head2 HTML output routines
  598: 
  599: =item &html_initialize($r)
  600: 
  601: Create labels for the columns of student data to show.
  602: 
  603: =item &html_outputstudent($r,$student)
  604: 
  605: Return a line of the chart for a student.
  606: 
  607: =item &html_finish($r)
  608: 
  609: =cut
  610: 
  611: #######################################################
  612: #######################################################
  613: {
  614:     my $padding;
  615:     my $count;
  616: 
  617:     my $nodata_count; # The number of students for which there is no data
  618:     my %prog_state;   # progress state used by loncommon PrgWin routines
  619:     my $total_sum_width;
  620: 
  621:     my %width; # Holds sequence width information
  622:     my @sequences;
  623:     my $navmap; # Have to keep this around since weakref is a bit zealous
  624: 
  625: sub html_cleanup {
  626:     undef(%prog_state);
  627:     undef(%width);
  628:     #
  629:     undef($navmap);
  630:     undef(@sequences);
  631: }
  632: 
  633: sub html_initialize {
  634:     my ($r) = @_;
  635:     #
  636:     $padding = ' 'x3;
  637:     $count = 0;
  638:     $nodata_count = 0;
  639:     &html_cleanup();
  640:     ($navmap,@sequences) = 
  641:         &Apache::lonstatistics::selected_sequences_with_assessments();
  642:     if (! ref($navmap)) {
  643:         # Unable to get data, so bail out
  644:         $r->print("<h3>".
  645:                   &mt('Unable to retrieve course information.').
  646:                   '</h3>');
  647:     }
  648:     #
  649:     $r->print("<h3>".$env{'course.'.$env{'request.course.id'}.'.description'}.
  650:               "&nbsp;&nbsp;".localtime(time)."</h3>");
  651:     #
  652:     if ($chosen_output->{'base'} !~ /^final table/) {
  653:         $r->print("<h3>".$chosen_output->{'shortdesc'}."</h3>");        
  654:     }
  655:     my $Str = "<pre>\n";
  656:     # First, the @StudentData fields need to be listed
  657:     my @to_show = &get_student_fields_to_show();
  658:     foreach my $field (@to_show) {
  659:         my $title=$Apache::lonstatistics::StudentData{$field}->{'title'};
  660:         my $base =$Apache::lonstatistics::StudentData{$field}->{'base_width'};
  661:         my $width=$Apache::lonstatistics::StudentData{$field}->{'width'};
  662:         $Str .= $title.' 'x($width-$base).$padding;
  663:     }
  664:     #
  665:     # Compute the column widths and output the sequence titles
  666:     my $total_count;
  667:     #
  668:     # Compute sequence widths
  669:     my $starttime = Time::HiRes::time;
  670:     foreach my $seq (@sequences) {
  671:         my $symb = $seq->symb;
  672:         my $title = $seq->compTitle;
  673:         $width{$symb}->{'width_sum'} = 0;
  674:         # Compute width of sum
  675:         if ($chosen_output->{'sequence_sum'}) {
  676:             if ($chosen_output->{'every_problem'}) {
  677:                 # Use 1 digit for a space
  678:                 $width{$symb}->{'width_sum'} += 1;            
  679:             }
  680: 	    $total_count += &count_parts($navmap,$seq);
  681:             # Use 3 digits for the sum
  682:             $width{$symb}->{'width_sum'} += 3;
  683:         }
  684:         # Compute width of maximum
  685:         if ($chosen_output->{'sequence_max'}) {
  686:             if ($width{$symb}->{'width_sum'}>0) {
  687:                 # One digit for the '/'
  688:                 $width{$symb}->{'width_sum'} +=1;
  689:             }
  690:             # Use 3 digits for the total
  691:             $width{$symb}->{'width_sum'}+=3;
  692:         }
  693: 	#
  694:         if ($chosen_output->{'every_problem'}) {
  695:             # one problem per digit
  696:             $width{$symb}->{'width_parts'}= &count_parts($navmap,$seq);
  697:             $width{$symb}->{'width_problem'} += $width{$symb}->{'width_parts'};
  698:         } else {
  699:             $width{$symb}->{'width_problem'} = 0;
  700:         }
  701:         $width{$symb}->{'width_total'} = $width{$symb}->{'width_problem'} + 
  702:                                      $width{$symb}->{'width_sum'};
  703:         if ($width{$symb}->{'width_total'} < length(&HTML::Entities::decode($title))) {
  704:             $width{$symb}->{'width_total'} = length(&HTML::Entities::decode($title));
  705:         }
  706:         #
  707:         # Output the sequence titles
  708:         $Str .= $title.(' 'x($width{$symb}->{'width_total'}-
  709:                             length($title)
  710:                             )).$padding;
  711:     }
  712:     $total_sum_width = length($total_count)+1;
  713:     $Str .= "    total</pre>\n";
  714:     $Str .= "<pre>";
  715:     $r->print($Str);
  716:     $r->rflush();
  717:     #
  718:     # Let the user know what we are doing
  719:     my $studentcount = scalar(@Apache::lonstatistics::Students); 
  720:     if ($env{'form.SelectedStudent'}) {
  721:         $studentcount = '1';
  722:     }
  723:     #
  724:     # Initialize progress window
  725:     %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
  726:         ($r,'HTML Chart Status',
  727:          'HTML Chart Progress', $studentcount,
  728:          'inline',undef,'Statistics','stats_status');
  729:     #
  730:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
  731:                                           'Processing first student');
  732:     return;
  733: }
  734: 
  735: sub html_outputstudent {
  736:     my ($r,$student) = @_;
  737:     my $Str = '';
  738:     return if (! defined($navmap));
  739:     #
  740:     if($count++ % 5 == 0 && $count > 0) {
  741:         $r->print("</pre><pre>");
  742:     }
  743:     # First, the @StudentData fields need to be listed
  744:     my @to_show = &get_student_fields_to_show();
  745:     foreach my $field (@to_show) {
  746:         my $title=$student->{$field};
  747:         # Deal with 'comments' - how I love special cases
  748:         if ($field eq 'comments') {
  749:             $title = '<a href="/adm/'.$student->{'domain'}.'/'.$student->{'username'}.'/'.'aboutme#coursecomment">'.&mt('Comments').'</a>';
  750:         }
  751:         my $base = length($title);
  752:         my $width=$Apache::lonstatistics::StudentData{$field}->{'width'};
  753:         $Str .= $title.' 'x($width-$base).$padding;
  754:     }
  755:     # Get ALL the students data
  756:     my %StudentsData;
  757:     my @tmp = &Apache::loncoursedata::get_current_state
  758:         ($student->{'username'},$student->{'domain'},undef,
  759:          $env{'request.course.id'});
  760:     if ((scalar @tmp > 0) && ($tmp[0] !~ /^error:/)) {
  761:         %StudentsData = @tmp;
  762:     }
  763:     if (scalar(@tmp) < 1) {
  764:         $nodata_count++;
  765:         $Str .= '<font color="blue">No Course Data</font>'."\n";
  766:         $r->print($Str);
  767:         $r->rflush();
  768:         return;
  769:     }
  770:     #
  771:     # By sequence build up the data
  772:     my $studentstats;
  773:     my $PerformanceStr = '';
  774:     foreach my $seq (@sequences) {
  775:         my $symb = $seq->symb;
  776:         my ($performance,$performance_length,$score,$seq_max,$rawdata);
  777:         if ($chosen_output->{'tries'}) {
  778:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
  779:                 &student_tries_on_sequence($student,\%StudentsData,
  780:                                            $navmap,$seq,$show_links);
  781:         } else {
  782:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
  783:                 &student_performance_on_sequence($student,\%StudentsData,
  784:                                                  $navmap,$seq,$show_links);
  785:         }
  786:         my $ratio='';
  787:         if ($chosen_output->{'every_problem'} && 
  788:             $chosen_output->{'sequence_sum'}) {
  789:             $ratio .= ' ';
  790:         }
  791:         if ($chosen_output->{'sequence_sum'} && $score ne ' ') {
  792:             my $score .= sprintf("%3.0f",$score);
  793:             $ratio .= (' 'x(3-length($score))).$score;
  794:         } elsif($chosen_output->{'sequence_sum'}) {
  795:             $ratio .= ' 'x3;
  796:         }
  797:         if ($chosen_output->{'sequence_max'}) {
  798:             if ($chosen_output->{'sequence_sum'}) {
  799:                 $ratio .= '/';
  800:             }
  801:             $ratio .= sprintf("%3.0f",$seq_max);
  802:         }
  803:         #
  804:         if (! $chosen_output->{'every_problem'}) {
  805:             $performance = '';
  806: 	    $performance_length=0;
  807:         }
  808:         $performance .= ' 'x($width{$symb}->{'width_total'} -
  809:                              $performance_length -
  810:                              $width{$symb}->{'width_sum'}).
  811:             $ratio;
  812:         #
  813:         $Str .= $performance.$padding;
  814:         #
  815:         $studentstats->{$symb}->{'score'}= $score;
  816:         $studentstats->{$symb}->{'max'}  = $seq_max;
  817:     }
  818:     #
  819:     # Total it up and store the statistics info.
  820:     my ($score,$max);
  821:     while (my ($symb,$seq_stats) = each (%{$studentstats})) {
  822:         $Statistics->{$symb}->{'score'} += $seq_stats->{'score'};
  823:         if ($Statistics->{$symb}->{'max'} < $seq_stats->{'max'}) {
  824:             $Statistics->{$symb}->{'max'} = $seq_stats->{'max'};
  825:         }
  826:         if ($seq_stats->{'score'} ne ' ') {
  827:             $score += $seq_stats->{'score'};
  828:             $Statistics->{$symb}->{'num_students'}++;
  829:         }
  830:         $max   += $seq_stats->{'max'};
  831:     }
  832:     if (! defined($score)) {
  833:         $score = ' ' x $total_sum_width;
  834:     } else {
  835:         $score = sprintf("%.0f",$score);
  836:         $score = (' 'x(3-length($score))).$score;
  837:     }
  838:     $Str .= ' '.' 'x($total_sum_width-length($score)).$score.' / '.$max;
  839:     $Str .= " \n";
  840:     #
  841:     $r->print($Str);
  842:     #
  843:     $r->rflush();
  844:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
  845:     return;
  846: }    
  847: 
  848: sub html_finish {
  849:     my ($r) = @_;
  850:     return if (! defined($navmap));
  851:     #
  852:     # Check for suppressed output and close the progress window if so
  853:     $r->print("</pre>\n"); 
  854:     if ($chosen_output->{'summary_table'}) {
  855:         if ($single_student_mode) {
  856:             $r->print(&SingleStudentTotal());
  857:         } else {
  858:             $r->print(&StudentAverageTotal());
  859:         }
  860:     }
  861:     $r->rflush();
  862:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  863:     &html_cleanup();
  864:     return;
  865: }
  866: 
  867: sub StudentAverageTotal {
  868:     my $Str = '<h3>'.&mt('Summary Tables').'</h3>'.$/;
  869:     $Str .= '<table border=2 cellspacing="1">'."\n";
  870:     $Str .= '<tr>'.
  871:         '<th>'.&mt('Title').'</th>'.
  872:         '<th>'.&mt('Average').'</th>'.
  873:         '<th>'.&mt('Maximum').'</th>'.
  874:         '</tr>'.$/;
  875:     foreach my $seq (@sequences) {
  876:         my $symb = $seq->symb;
  877:         my $ave;
  878:         my $num_students = $Statistics->{$symb}->{'num_students'};
  879:         if ($num_students > 0) {
  880:             $ave = int(100*
  881:                        ($Statistics->{$symb}->{'score'}/$num_students)
  882:                        )/100;
  883:         } else {
  884:             $ave = 0;
  885:         }
  886:         my $max = $Statistics->{$symb}->{'max'};
  887:         $ave = sprintf("%.2f",$ave);
  888:         $Str .= '<tr><td>'.$seq->compTitle.'</td>'.
  889:             '<td align="right">'.$ave.'&nbsp;</td>'.
  890:             '<td align="right">'.$max.'&nbsp;'.'</td></tr>'."\n";
  891:     }
  892:     $Str .= "</table>\n";
  893:     return $Str;
  894: }
  895: 
  896: sub SingleStudentTotal {
  897:     return if (! defined($navmap));
  898:     my $student = &Apache::lonstatistics::current_student();
  899:     my $Str = '<h3>'.&mt('Summary table for [_1] ([_2]@[_3])',
  900:                          $student->{'fullname'},
  901:                          $student->{'username'},$student->{'domain'}).'</h3>';
  902:     $Str .= $/;
  903:     $Str .= '<table border=2 cellspacing="1">'."\n";
  904:     $Str .= 
  905:         '<tr>'.
  906:         '<th>'.&mt('Sequence or Folder').'</th>';
  907:     if ($chosen_output->{'base'} eq 'tries') {
  908:         $Str .= '<th>'.&mt('Parts Correct').'</th>';
  909:     } else {
  910:         $Str .= '<th>'.&mt('Score').'</th>';
  911:     }
  912:     $Str .= '<th>'.&mt('Maximum').'</th>'."</tr>\n";
  913:     my $total = 0;
  914:     my $total_max = 0;
  915:     foreach my $seq (@sequences) {
  916:         my $value = $Statistics->{$seq->symb}->{'score'};
  917:         my $max = $Statistics->{$seq->symb}->{'max'};
  918:         $Str .= '<tr><td>'.&HTML::Entities::encode($seq->compTitle).'</td>'.
  919:             '<td align="right">'.$value.'</td>'.
  920:                 '<td align="right">'.$max.'</td></tr>'."\n";
  921:         $total += $value;
  922:         $total_max +=$max;
  923:     }
  924:     $Str .= '<tr><td><b>'.&mt('Total').'</b></td>'.
  925:         '<td align="right">'.$total.'</td>'.
  926:         '<td align="right">'.$total_max."</td></tr>\n";
  927:     $Str .= "</table>\n";
  928:     return $Str;
  929: }
  930: 
  931: }
  932: 
  933: #######################################################
  934: #######################################################
  935: 
  936: =pod
  937: 
  938: =head2 EXCEL subroutines
  939: 
  940: =item &excel_initialize($r)
  941: 
  942: =item &excel_outputstudent($r,$student)
  943: 
  944: =item &excel_finish($r)
  945: 
  946: =cut
  947: 
  948: #######################################################
  949: #######################################################
  950: {
  951: 
  952: my $excel_sheet;
  953: my $excel_workbook;
  954: my $format;
  955: 
  956: my $filename;
  957: my $rows_output;
  958: my $cols_output;
  959: 
  960: my %prog_state; # progress window state
  961: my $request_aborted;
  962: 
  963: my $total_formula;
  964: my $maximum_formula;
  965: my %formula_data;
  966: 
  967: my $navmap;
  968: my @sequences;
  969: 
  970: sub excel_cleanup {
  971:     #
  972:     undef ($excel_sheet);
  973:     undef ($excel_workbook);
  974:     undef ($filename);
  975:     undef ($rows_output);
  976:     undef ($cols_output);
  977:     undef (%prog_state);
  978:     undef ($request_aborted);
  979:     undef ($total_formula);
  980:     undef ($maximum_formula);
  981:     #
  982:     undef(%formula_data);
  983:     #
  984:     undef($navmap);
  985:     undef(@sequences);
  986: }
  987: 
  988: sub excel_initialize {
  989:     my ($r) = @_;
  990: 
  991:     &excel_cleanup();
  992:     ($navmap,@sequences) = 
  993:         &Apache::lonstatistics::selected_sequences_with_assessments();
  994:     if (! ref($navmap)) {
  995:         # Unable to get data, so bail out
  996:         $r->print("<h3>".
  997:                   &mt('Unable to retrieve course information.').
  998:                   '</h3>');
  999:     }
 1000:     #
 1001:     my $total_columns = scalar(&get_student_fields_to_show());
 1002:     my $num_students = scalar(@Apache::lonstatistics::Students);
 1003:     #
 1004:     foreach my $seq (@sequences) {
 1005:         if ($chosen_output->{'every_problem'}) {
 1006:             $total_columns+=&count_parts($navmap,$seq);
 1007:         }
 1008:         # Add 2 because we need a 'sequence_sum' and 'total' column for each
 1009:         $total_columns += 2;
 1010:     }
 1011:     my $too_many_cols_error_message = 
 1012:         '<h2>'.&mt('Unable to Complete Request').'</h2>'.$/.
 1013:         '<p>'.&mt('LON-CAPA is unable to produce your Excel spreadsheet because your selections will result in more than 255 columns.  Excel allows only 255 columns in a spreadsheet.').'</p>'.$/.
 1014:         '<p>'.&mt('You may consider reducing the number of <b>Sequences or Folders</b> you have selected.').'</p>'.$/.
 1015:         '<p>'.&mt('LON-CAPA can produce <b>CSV</b> files of this data or Excel files of the <b>Scores Summary</b> data.').'</p>'.$/;
 1016:     if ($chosen_output->{'base'} eq 'tries' && $total_columns > 255) {
 1017:         $r->print($too_many_cols_error_message);
 1018:         $request_aborted = 1;
 1019:     }
 1020:     if ($chosen_output->{'base'} eq 'scores' && $total_columns > 255) {
 1021:         $r->print($too_many_cols_error_message);
 1022:         $request_aborted = 1;
 1023:     }
 1024:     return if ($request_aborted);
 1025:     #
 1026:     #
 1027:     $excel_workbook = undef;
 1028:     $excel_sheet = undef;
 1029:     #
 1030:     $rows_output = 0;
 1031:     $cols_output = 0;
 1032:     #
 1033:     # Determine rows 
 1034:     my $header_row = $rows_output++;
 1035:     my $description_row = $rows_output++;
 1036:     my $notes_row = $rows_output++;
 1037:     $rows_output++;        # blank row
 1038:     my $summary_header_row;
 1039:     if ($chosen_output->{'summary_table'}) {
 1040:         $summary_header_row = $rows_output++;
 1041:         $rows_output+= scalar(@sequences);
 1042:         $rows_output++;
 1043:     }
 1044:     my $sequence_name_row = $rows_output++;
 1045:     my $resource_name_row = $rows_output++;
 1046:     my $maximum_data_row = $rows_output++;
 1047:     if (! $chosen_output->{'maximum_row'}) {
 1048:         $rows_output--;
 1049:     }
 1050:     my $first_data_row = $rows_output++;
 1051:     #
 1052:     # Create sheet
 1053:     ($excel_workbook,$filename,$format)=
 1054:         &Apache::loncommon::create_workbook($r);
 1055:     return if (! defined($excel_workbook));
 1056:     #
 1057:     # Add a worksheet
 1058:     my $sheetname = $env{'course.'.$env{'request.course.id'}.'.description'};
 1059:     $sheetname = &Apache::loncommon::clean_excel_name($sheetname);
 1060:     $excel_sheet = $excel_workbook->addworksheet($sheetname);
 1061:     #
 1062:     # Put the course description in the header
 1063:     $excel_sheet->write($header_row,$cols_output++,
 1064:                    $env{'course.'.$env{'request.course.id'}.'.description'},
 1065:                         $format->{'h1'});
 1066:     $cols_output += 3;
 1067:     #
 1068:     # Put a description of the sections listed
 1069:     my $sectionstring = '';
 1070:     my @Sections = &Apache::lonstatistics::get_selected_sections();
 1071:     $excel_sheet->write($header_row,$cols_output++,
 1072:                         &Apache::lonstatistics::section_and_enrollment_description('plaintext'),
 1073:                         $format->{'h3'});
 1074:     #
 1075:     # Put the date in there too
 1076:     $excel_sheet->write($header_row,$cols_output++,
 1077:                         'Compiled on '.localtime(time),$format->{'h3'});
 1078:     #
 1079:     $cols_output = 0;
 1080:     $excel_sheet->write($description_row,$cols_output++,
 1081:                         $chosen_output->{'shortdesc'},
 1082:                         $format->{'b'});
 1083:     #
 1084:     $cols_output = 0;
 1085:     $excel_sheet->write($notes_row,$cols_output++,
 1086:                         $chosen_output->{'non_html_notes'},
 1087:                         $format->{'i'});
 1088:     
 1089:     ##############################################
 1090:     # Output headings for the raw data
 1091:     ##############################################
 1092:     #
 1093:     # Add the student headers
 1094:     $cols_output = 0;
 1095:     foreach my $field (&get_student_fields_to_show()) {
 1096:         $excel_sheet->write($resource_name_row,$cols_output++,$field,
 1097:                             $format->{'bold'});
 1098:     }
 1099:     #
 1100:     # Add the remaining column headers
 1101:     my $total_formula_string = '=0';
 1102:     my $maximum_formula_string = '=0';
 1103:     foreach my $seq (@sequences) {
 1104:         my $symb = $seq->symb;
 1105:         $excel_sheet->write($sequence_name_row,,
 1106:                             $cols_output,$seq->compTitle,$format->{'bold'});
 1107:         # Determine starting cell
 1108:         $formula_data{$symb}->{'Excel:startcell'}=
 1109:             &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1110:             ($first_data_row,$cols_output);
 1111:         $formula_data{$symb}->{'Excel:startcol'}=$cols_output;
 1112:         my $count = 0;
 1113:         if ($chosen_output->{'every_problem'}) {
 1114:             # Put the names of the problems and parts into the sheet
 1115:             foreach my $res (&get_resources($navmap,$seq)) {
 1116:                 if (scalar(@{$res->parts}) > 1) {
 1117:                     foreach my $part (@{$res->parts}) {
 1118:                         $excel_sheet->write($resource_name_row,
 1119:                                             $cols_output++,
 1120:                                             $res->compTitle.' part '.$res->part_display($part),
 1121:                                             $format->{'bold'});
 1122:                         $count++;
 1123:                     }
 1124:                 } else {
 1125:                     $excel_sheet->write($resource_name_row,
 1126:                                         $cols_output++,
 1127:                                         $res->compTitle,$format->{'bold'});
 1128:                     $count++;
 1129:                 }
 1130:             }
 1131:         }
 1132:         # Determine ending cell
 1133:         if ($count <= 1) {
 1134:             $formula_data{$symb}->{'Excel:endcell'} = $formula_data{$symb}->{'Excel:startcell'};
 1135:             $formula_data{$symb}->{'Excel:endcol'}  = $formula_data{$symb}->{'Excel:startcol'};
 1136:         } else {
 1137:             $formula_data{$symb}->{'Excel:endcell'} = 
 1138:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1139:                 ($first_data_row,$cols_output-1);
 1140:             $formula_data{$symb}->{'Excel:endcol'} = $cols_output-1;
 1141:         }
 1142:         # Create the formula for summing up this sequence
 1143:         if (! exists($formula_data{$symb}->{'Excel:endcell'}) ||
 1144:             ! defined($formula_data{$symb}->{'Excel:endcell'})) {
 1145:             $formula_data{$symb}->{'Excel:endcell'} = $formula_data{$symb}->{'Excel:startcell'};
 1146:         }
 1147:         # =IF(COUNT(B31:L31);SUM(B31:L31);"")
 1148:         my $start = $formula_data{$symb}->{'Excel:startcell'};
 1149:         my $end = $formula_data{$symb}->{'Excel:endcell'};
 1150:         $formula_data{$symb}->{'Excel:sum'}= $excel_sheet->store_formula
 1151:             ("=IF(COUNT($start\:$end),SUM($start\:$end),\"\")");
 1152:         # Determine cell the score is held in
 1153:         $formula_data{$symb}->{'Excel:scorecell'} = 
 1154:             &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1155:             ($first_data_row,$cols_output);
 1156:         $formula_data{$symb}->{'Excel:scorecol'}=$cols_output;
 1157:         if ($chosen_output->{'base'} eq 'parts correct total') {
 1158:             $excel_sheet->write($resource_name_row,$cols_output++,
 1159:                                 'parts correct',
 1160:                                 $format->{'bold'});
 1161:         } elsif ($chosen_output->{'sequence_sum'}) {
 1162:             if ($chosen_output->{'correct'}) {
 1163:                 # Only reporting the number correct, so do not call it score
 1164:                 $excel_sheet->write($resource_name_row,$cols_output++,
 1165:                                     'sum',
 1166:                                     $format->{'bold'});
 1167:             } else {
 1168:                 $excel_sheet->write($resource_name_row,$cols_output++,
 1169:                                     'score',
 1170:                                     $format->{'bold'});
 1171:             }
 1172:         }
 1173:         #
 1174:         $total_formula_string.='+'.
 1175:             &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1176:             ($first_data_row,$cols_output-1);
 1177:         if ($chosen_output->{'sequence_max'}) {
 1178:             $excel_sheet->write($resource_name_row,$cols_output,
 1179:                                 'maximum',
 1180:                                 $format->{'bold'});
 1181:             $formula_data{$symb}->{'Excel:maxcell'} = 
 1182:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1183:                 ($first_data_row,$cols_output);
 1184:             $formula_data{$symb}->{'Excel:maxcol'}=$cols_output;
 1185:             $maximum_formula_string.='+'.
 1186:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1187:                 ($first_data_row,$cols_output);
 1188:             $cols_output++;
 1189: 
 1190:         }
 1191:     }
 1192:     if ($chosen_output->{'grand_total'}) {
 1193:         $excel_sheet->write($resource_name_row,$cols_output++,'Total',
 1194:                             $format->{'bold'});
 1195:     }
 1196:     if ($chosen_output->{'grand_maximum'}) {
 1197:         $excel_sheet->write($resource_name_row,$cols_output++,'Max. Total',
 1198:                             $format->{'bold'});
 1199:     }
 1200:     $total_formula = $excel_sheet->store_formula($total_formula_string);
 1201:     $maximum_formula = $excel_sheet->store_formula($maximum_formula_string);
 1202:     ##############################################
 1203:     # Output a row for MAX, if appropriate
 1204:     ##############################################
 1205:     if ($chosen_output->{'maximum_row'}) {
 1206:         $cols_output = 0;
 1207:         foreach my $field (&get_student_fields_to_show()) {
 1208:             if ($field eq 'username' || $field eq 'fullname' || 
 1209:                 $field eq 'id') {
 1210:                 $excel_sheet->write($maximum_data_row,$cols_output++,'Maximum',
 1211:                                     $format->{'bold'});
 1212:             } else {
 1213:                 $excel_sheet->write($maximum_data_row,$cols_output++,'');
 1214:             }
 1215:         }
 1216:         #
 1217:         # Add the maximums for each sequence or assessment
 1218:         my %total_cell_translation;
 1219:         my %maximum_cell_translation;
 1220:         foreach my $seq (@sequences) {
 1221:             my $symb = $seq->symb;
 1222:             $cols_output=$formula_data{$symb}->{'Excel:startcol'};
 1223:             $total_cell_translation{$formula_data{$symb}->{'Excel:scorecell'}}=
 1224:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1225:                 ($maximum_data_row,$formula_data{$symb}->{'Excel:scorecol'});
 1226:             $maximum_cell_translation{$formula_data{$symb}->{'Excel:maxcell'}}=
 1227:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1228:                 ($maximum_data_row,$formula_data{$symb}->{'Excel:maxcol'});
 1229:             my $weight;
 1230:             my $max = 0;
 1231:             foreach my $resource (&get_resources($navmap,$seq)) {
 1232:                 foreach my $part (@{$resource->parts}){
 1233:                     $weight = 1;
 1234:                     if ($chosen_output->{'scores'}) {
 1235:                         $weight = &Apache::lonnet::EXT
 1236:                             ('resource.'.$part.'.weight',$resource->{'symb'},
 1237:                              undef,undef,undef);
 1238:                         if (!defined($weight) || ($weight eq '')) { 
 1239:                             $weight=1;
 1240:                         }
 1241:                     }
 1242:                     if ($chosen_output->{'scores'} &&
 1243:                         $chosen_output->{'every_problem'}) {
 1244:                         $excel_sheet->write($maximum_data_row,$cols_output++,
 1245:                                             $weight);
 1246:                     }
 1247:                     $max += $weight;
 1248:                 }
 1249:             } 
 1250:             #
 1251:             if ($chosen_output->{'sequence_sum'} && 
 1252:                 $chosen_output->{'every_problem'}) {
 1253: 		my %replaceCells=
 1254: 		    ('^'.$formula_data{$symb}->{'Excel:startcell'}.':'.
 1255: 		         $formula_data{$symb}->{'Excel:endcell'}.'$' =>
 1256: 		     &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell($maximum_data_row,$formula_data{$symb}->{'Excel:startcol'}).':'.
 1257: 		     &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell($maximum_data_row,$formula_data{$symb}->{'Excel:endcol'}));
 1258:                 $excel_sheet->repeat_formula($maximum_data_row,$cols_output++,
 1259:                                              $formula_data{$symb}->{'Excel:sum'},undef,
 1260: 					     %replaceCells, %replaceCells);
 1261: 			
 1262:             } elsif ($chosen_output->{'sequence_sum'}) {
 1263:                 $excel_sheet->write($maximum_data_row,$cols_output++,$max);
 1264:             }
 1265:             if ($chosen_output->{'sequence_max'}) {
 1266:                 $excel_sheet->write($maximum_data_row,$cols_output++,$max);
 1267:             }
 1268:             #
 1269:         }
 1270:         if ($chosen_output->{'grand_total'}) {
 1271:             $excel_sheet->repeat_formula($maximum_data_row,$cols_output++,
 1272:                                          $total_formula,undef,
 1273:                                          %total_cell_translation);
 1274:         }
 1275:         if ($chosen_output->{'grand_maximum'}) {
 1276:             $excel_sheet->repeat_formula($maximum_data_row,$cols_output++,
 1277:                                          $maximum_formula,undef,
 1278:                                          %maximum_cell_translation);
 1279:         }
 1280:     } # End of MAXIMUM row output  if ($chosen_output->{'maximum_row'}) {
 1281:     $rows_output = $first_data_row;
 1282:     ##############################################
 1283:     # Output summary table, which actually is above the sequence name row.
 1284:     ##############################################
 1285:     if ($chosen_output->{'summary_table'}) {
 1286:         $cols_output = 0;
 1287:         $excel_sheet->write($summary_header_row,$cols_output++,
 1288:                             'Summary Table',$format->{'bold'});
 1289:         if ($chosen_output->{'maximum_row'}) {
 1290:             $excel_sheet->write($summary_header_row,$cols_output++,
 1291:                                 'Maximum',$format->{'bold'});
 1292:         }
 1293:         $excel_sheet->write($summary_header_row,$cols_output++,
 1294:                             'Average',$format->{'bold'});
 1295:         $excel_sheet->write($summary_header_row,$cols_output++,
 1296:                             'Median',$format->{'bold'});
 1297:         $excel_sheet->write($summary_header_row,$cols_output++,
 1298:                             'Std Dev',$format->{'bold'});
 1299:         my $row = $summary_header_row+1;
 1300:         foreach my $seq (@sequences) {
 1301:             my $symb = $seq->symb;
 1302:             $cols_output = 0;
 1303:             $excel_sheet->write($row,$cols_output++,
 1304:                                 $seq->compTitle,
 1305:                                 $format->{'bold'});
 1306:             if ($chosen_output->{'maximum_row'}) {
 1307:                 $excel_sheet->write
 1308:                     ($row,$cols_output++,
 1309:                      '='.
 1310:                      &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1311:                      ($maximum_data_row,$formula_data{$symb}->{'Excel:scorecol'})
 1312:                      );
 1313:             }
 1314:             my $range = 
 1315:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1316:                 ($first_data_row,$formula_data{$symb}->{'Excel:scorecol'}).
 1317:                 ':'.
 1318:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1319:                 ($first_data_row+$num_students-1,$formula_data{$symb}->{'Excel:scorecol'});
 1320:             $excel_sheet->write($row,$cols_output++,
 1321:                                 '=AVERAGE('.$range.')');
 1322:             $excel_sheet->write($row,$cols_output++,
 1323:                                 '=MEDIAN('.$range.')');
 1324:             $excel_sheet->write($row,$cols_output++,
 1325:                                 '=STDEV('.$range.')');
 1326:             $row++;
 1327:         }
 1328:     }
 1329:     ##############################################
 1330:     #   Take care of non-excel initialization
 1331:     ##############################################
 1332:     #
 1333:     # Let the user know what we are doing
 1334:     my $studentcount = scalar(@Apache::lonstatistics::Students); 
 1335:     if ($env{'form.SelectedStudent'}) {
 1336:         $studentcount = '1';
 1337:     }
 1338:     if ($studentcount > 1) {
 1339:         $r->print('<h1>'.&mt('Compiling Excel spreadsheet for [_1] students',
 1340:                              $studentcount)."</h1>\n");
 1341:     } else {
 1342:         $r->print('<h1>'.
 1343:                   &mt('Compiling Excel spreadsheet for 1 student').
 1344:                   "</h1>\n");
 1345:     }
 1346:     $r->rflush();
 1347:     #
 1348:     # Initialize progress window
 1349:     %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
 1350:         ($r,'Excel File Compilation Status',
 1351:          'Excel File Compilation Progress', $studentcount,
 1352:          'inline',undef,'Statistics','stats_status');
 1353:     #
 1354:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 1355:                                           'Processing first student');
 1356:     return;
 1357: }
 1358: 
 1359: sub excel_outputstudent {
 1360:     my ($r,$student) = @_;
 1361:     if ($request_aborted || ! defined($navmap) || ! defined($excel_sheet)) {
 1362:         return;
 1363:     }
 1364:     $cols_output=0;
 1365:     #
 1366:     # Write out student data
 1367:     my @to_show = &get_student_fields_to_show();
 1368:     foreach my $field (@to_show) {
 1369:         my $value = $student->{$field};
 1370:         if ($field eq 'comments') {
 1371:             $value = &Apache::lonmsg::retrieve_instructor_comments
 1372:                 ($student->{'username'},$student->{'domain'});
 1373:         }
 1374:         $excel_sheet->write($rows_output,$cols_output++,$value);
 1375:     }
 1376:     #
 1377:     # Get student assessment data
 1378:     my %StudentsData;
 1379:     my @tmp = &Apache::loncoursedata::get_current_state($student->{'username'},
 1380:                                                         $student->{'domain'},
 1381:                                                         undef,
 1382:                                                    $env{'request.course.id'});
 1383:     if ((scalar @tmp > 0) && ($tmp[0] !~ /^error:/)) {
 1384:         %StudentsData = @tmp;
 1385:     }
 1386:     #
 1387:     # Write out sequence scores and totals data
 1388:     my %total_cell_translation;
 1389:     my %maximum_cell_translation;
 1390:     foreach my $seq (@sequences) {
 1391:         my $symb = $seq->symb;
 1392:         $cols_output = $formula_data{$symb}->{'Excel:startcol'};
 1393:         # Keep track of cells to translate in total cell
 1394:         $total_cell_translation{$formula_data{$symb}->{'Excel:scorecell'}} = 
 1395:             &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1396:                         ($rows_output,$formula_data{$symb}->{'Excel:scorecol'});
 1397:         # and maximum cell
 1398:         $maximum_cell_translation{$formula_data{$symb}->{'Excel:maxcell'}} = 
 1399:             &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1400:             ($rows_output,$formula_data{$symb}->{'Excel:maxcol'});
 1401:         #
 1402:         my ($performance,$performance_length,$score,$seq_max,$rawdata);
 1403:         if ($chosen_output->{'tries'} || $chosen_output->{'correct'}){
 1404:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
 1405:                 &student_tries_on_sequence($student,\%StudentsData,
 1406:                                            $navmap,$seq,'no');
 1407:         } else {
 1408:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
 1409:                 &student_performance_on_sequence($student,\%StudentsData,
 1410:                                                  $navmap,$seq,'no');
 1411:         } 
 1412:         if ($chosen_output->{'every_problem'}) {
 1413:             if ($chosen_output->{'correct'}) {
 1414:                 # only indiciate if each item is correct or not
 1415:                 foreach my $value (@$rawdata) {
 1416:                     # positive means correct, 0 or negative means
 1417:                     # incorrect
 1418:                     $value = $value > 0 ? 1 : 0;
 1419:                     $excel_sheet->write($rows_output,$cols_output++,$value);
 1420:                 }
 1421:             } else {
 1422:                 foreach my $value (@$rawdata) {
 1423:                     if ($score eq ' ' || !defined($value)) {
 1424:                         $cols_output++;
 1425:                     } else {                        
 1426:                         $excel_sheet->write($rows_output,$cols_output++,
 1427:                                             $value);
 1428:                     }
 1429:                 }
 1430:             }
 1431:         }
 1432:         if ($chosen_output->{'sequence_sum'} && 
 1433:             $chosen_output->{'every_problem'}) {
 1434:             # Write a formula for the sum of this sequence
 1435:             my %replaceCells=
 1436: 		('^'.$formula_data{$symb}->{'Excel:startcell'}.':'.$formula_data{$symb}->{'Excel:endcell'}.'$'
 1437: 		 => 
 1438: 		 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell($rows_output,$formula_data{$symb}->{'Excel:startcol'}).':'.
 1439: 		 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell($rows_output,$formula_data{$symb}->{'Excel:endcol'})
 1440: 		 );
 1441:             # The undef is for the format	    
 1442: 	    $excel_sheet->repeat_formula($rows_output,$cols_output++,
 1443: 					 $formula_data{$symb}->{'Excel:sum'},undef,
 1444: 					 %replaceCells, %replaceCells);
 1445:         } elsif ($chosen_output->{'sequence_sum'}) {
 1446:             if ($score eq ' ') {
 1447:                 $cols_output++;
 1448:             } else {
 1449:                 $excel_sheet->write($rows_output,$cols_output++,$score);
 1450:             }
 1451:         }
 1452:         if ($chosen_output->{'sequence_max'}) {
 1453:             $excel_sheet->write($rows_output,$cols_output++,$seq_max);
 1454:         }
 1455:     }
 1456:     #
 1457:     if ($chosen_output->{'grand_total'}) {
 1458:         $excel_sheet->repeat_formula($rows_output,$cols_output++,
 1459:                                      $total_formula,undef,
 1460:                                      %total_cell_translation);
 1461:     }
 1462:     if ($chosen_output->{'grand_maximum'}) {
 1463:         $excel_sheet->repeat_formula($rows_output,$cols_output++,
 1464:                                      $maximum_formula,undef,
 1465:                                      %maximum_cell_translation);
 1466:     }
 1467:     #
 1468:     # Bookkeeping
 1469:     $rows_output++; 
 1470:     $cols_output=0;
 1471:     #
 1472:     # Update the progress window
 1473:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 1474:     return;
 1475: }
 1476: 
 1477: sub excel_finish {
 1478:     my ($r) = @_;
 1479:     if ($request_aborted || ! defined($navmap) || ! defined($excel_sheet)) {
 1480: 	&excel_cleanup();
 1481:         return;
 1482:     }
 1483:     #
 1484:     # Write the excel file
 1485:     $excel_workbook->close();
 1486:     #
 1487:     # Close the progress window
 1488:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 1489:     #
 1490:     # Tell the user where to get their excel file
 1491:     $r->print('<br />'.
 1492:               '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
 1493:     $r->rflush();
 1494:     &excel_cleanup();
 1495:     return;
 1496: }
 1497: 
 1498: }
 1499: #######################################################
 1500: #######################################################
 1501: 
 1502: =pod
 1503: 
 1504: =head2 CSV output routines
 1505: 
 1506: =item &csv_initialize($r)
 1507: 
 1508: =item &csv_outputstudent($r,$student)
 1509: 
 1510: =item &csv_finish($r)
 1511: 
 1512: =cut
 1513: 
 1514: #######################################################
 1515: #######################################################
 1516: {
 1517: 
 1518: my $outputfile;
 1519: my $filename;
 1520: my $request_aborted;
 1521: my %prog_state; # progress window state
 1522: my $navmap;
 1523: my @sequences;
 1524: 
 1525: sub csv_cleanup {
 1526:     undef($outputfile);
 1527:     undef($filename);
 1528:     undef($request_aborted);
 1529:     undef(%prog_state);
 1530:     #
 1531:     undef($navmap);
 1532:     undef(@sequences);
 1533: }
 1534: 
 1535: sub csv_initialize{
 1536:     my ($r) = @_;
 1537: 
 1538:     &csv_cleanup();
 1539:     ($navmap,@sequences) = 
 1540:         &Apache::lonstatistics::selected_sequences_with_assessments();
 1541:     if (! ref($navmap)) {
 1542:         # Unable to get data, so bail out
 1543:         $r->print("<h3>".
 1544:                   &mt('Unable to retrieve course information.').
 1545:                   '</h3>');
 1546:     }
 1547:     #
 1548:     # Deal with unimplemented requests
 1549:     $request_aborted = undef;
 1550:     if ($chosen_output->{'base'} =~ /final table/) {
 1551:         $r->print(<<END);
 1552: <h2>Unable to Complete Request</h2>
 1553: <p>
 1554: The <b>Summary Table (Scores)</b> option is not available for non-HTML output.
 1555: </p>
 1556: END
 1557:        $request_aborted = 1;
 1558:     }
 1559:     return if ($request_aborted);
 1560:     #
 1561:     # Initialize progress window
 1562:     my $studentcount = scalar(@Apache::lonstatistics::Students);
 1563:     %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
 1564:         ($r,'CSV File Compilation Status',
 1565:          'CSV File Compilation Progress', $studentcount,
 1566:          'inline',undef,'Statistics','stats_status');
 1567:     #
 1568:     # Open a file
 1569:     ($outputfile,$filename) = &Apache::loncommon::create_text_file($r,'csv');
 1570:     if (! defined($outputfile)) { return ''; }
 1571:     #
 1572:     # Datestamp
 1573:     my $description = $env{'course.'.$env{'request.course.id'}.'.description'};
 1574:     print $outputfile '"'.&Apache::loncommon::csv_translate($description).'",'.
 1575:         '"'.&Apache::loncommon::csv_translate(scalar(localtime(time))).'"'.
 1576:             "\n";
 1577:     print $outputfile '"'.
 1578:         &Apache::loncommon::csv_translate
 1579:         (&Apache::lonstatistics::section_and_enrollment_description()).
 1580:         '"'."\n";
 1581:     foreach my $item ('shortdesc','non_html_notes') {
 1582:         next if (! exists($chosen_output->{$item}));
 1583:         print $outputfile 
 1584:             '"'.&Apache::loncommon::csv_translate($chosen_output->{$item}).'"'.
 1585:             "\n";
 1586:     }
 1587:     #
 1588:     # Print out the headings
 1589:     my $sequence_row = '';
 1590:     my $resource_row = undef;
 1591:     foreach my $field (&get_student_fields_to_show()) {
 1592:         $sequence_row .='"",';
 1593:         $resource_row .= '"'.&Apache::loncommon::csv_translate($field).'",';
 1594:     }
 1595:     foreach my $seq (@sequences) {
 1596:         $sequence_row .= '"'.
 1597:             &Apache::loncommon::csv_translate($seq->compTitle).'",';
 1598:         my $count = 0;
 1599:         if ($chosen_output->{'every_problem'}) {
 1600:             foreach my $res (&get_resources($navmap,$seq)) {
 1601:                 if (scalar(@{$res->parts}) < 1) {
 1602:                     next;
 1603:                 }
 1604:                 foreach my $part (@{$res->parts}) {
 1605:                     $resource_row .= '"'.
 1606:                         &Apache::loncommon::csv_translate
 1607:                         ($res->compTitle.', Part '.$res->part_display($part)).'",';
 1608:                     $count++;
 1609:                 }
 1610:             }
 1611:         }
 1612:         $sequence_row.='"",'x$count;
 1613:         if ($chosen_output->{'sequence_sum'}) {
 1614:             if($chosen_output->{'correct'}) {
 1615:                 $resource_row .= '"sum",';
 1616:             } else {
 1617:                 $resource_row .= '"score",';
 1618:             }
 1619:         }
 1620:         if ($chosen_output->{'sequence_max'}) {
 1621:             $sequence_row.= '"",';
 1622:             $resource_row .= '"maximum possible",';
 1623:         }
 1624:     }
 1625:     if ($chosen_output->{'grand_total'}) {
 1626:         $sequence_row.= '"",';
 1627:         $resource_row.= '"Total",';
 1628:     } 
 1629:     if ($chosen_output->{'grand_maximum'}) {
 1630:         $sequence_row.= '"",';
 1631:         $resource_row.= '"Maximum",';
 1632:     } 
 1633:     chomp($sequence_row);
 1634:     chomp($resource_row);
 1635:     print $outputfile $sequence_row."\n";
 1636:     print $outputfile $resource_row."\n";
 1637:     return;
 1638: }
 1639: 
 1640: sub csv_outputstudent {
 1641:     my ($r,$student) = @_;
 1642:     if ($request_aborted || ! defined($navmap) || ! defined($outputfile)) {
 1643:         return;
 1644:     }
 1645:     my $Str = '';
 1646:     #
 1647:     # Output student fields
 1648:     my @to_show = &get_student_fields_to_show();
 1649:     foreach my $field (@to_show) {
 1650:         my $value = $student->{$field};
 1651:         if ($field eq 'comments') {
 1652:             $value = &Apache::lonmsg::retrieve_instructor_comments
 1653:                 ($student->{'username'},$student->{'domain'});
 1654:         }        
 1655:         $Str .= '"'.&Apache::loncommon::csv_translate($value).'",';
 1656:     }
 1657:     #
 1658:     # Get student assessment data
 1659:     my %StudentsData;
 1660:     my @tmp = &Apache::loncoursedata::get_current_state($student->{'username'},
 1661:                                                         $student->{'domain'},
 1662:                                                         undef,
 1663:                                                    $env{'request.course.id'});
 1664:     if ((scalar @tmp > 0) && ($tmp[0] !~ /^error:/)) {
 1665:         %StudentsData = @tmp;
 1666:     }
 1667:     #
 1668:     # Output performance data
 1669:     my $total = 0;
 1670:     my $maximum = 0;
 1671:     foreach my $seq (@sequences) {
 1672:         my ($performance,$performance_length,$score,$seq_max,$rawdata);
 1673:         if ($chosen_output->{'tries'}){
 1674:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
 1675:                 &student_tries_on_sequence($student,\%StudentsData,
 1676:                                            $navmap,$seq,'no');
 1677:         } else {
 1678:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
 1679:                 &student_performance_on_sequence($student,\%StudentsData,
 1680:                                                  $navmap,$seq,'no');
 1681:         }
 1682:         if ($chosen_output->{'every_problem'}) {
 1683:             if ($chosen_output->{'correct'}) {
 1684:                 $score = 0;
 1685:                 # Deal with number of parts correct data
 1686:                 $Str .= '"'.join('","',( map { if ($_>0) { 
 1687:                                                    $score += 1;
 1688:                                                    1; 
 1689:                                                } else { 
 1690:                                                    0; 
 1691:                                                }
 1692:                                              } @$rawdata)).'",';
 1693:             } else {
 1694:                 $Str .= '"'.join('","',(@$rawdata)).'",';
 1695:             }
 1696:         }
 1697:         if ($chosen_output->{'sequence_sum'}) {
 1698:             $Str .= '"'.$score.'",';
 1699:         } 
 1700:         if ($chosen_output->{'sequence_max'}) {
 1701:             $Str .= '"'.$seq_max.'",';
 1702:         }
 1703:         $total+=$score;
 1704:         $maximum += $seq_max;
 1705:     }
 1706:     if ($chosen_output->{'grand_total'}) {
 1707:         $Str .= '"'.$total.'",';
 1708:     }
 1709:     if ($chosen_output->{'grand_maximum'}) {
 1710:         $Str .= '"'.$maximum.'",';
 1711:     }
 1712:     chop($Str);
 1713:     $Str .= "\n";
 1714:     print $outputfile $Str;
 1715:     #
 1716:     # Update the progress window
 1717:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 1718:     return;
 1719: }
 1720: 
 1721: sub csv_finish {
 1722:     my ($r) = @_;
 1723:     if ($request_aborted || ! defined($navmap) || ! defined($outputfile)) {
 1724: 	&csv_cleanup();
 1725:         return;
 1726:     }
 1727:     close($outputfile);
 1728:     #
 1729:     # Close the progress window
 1730:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 1731:     #
 1732:     # Tell the user where to get their csv file
 1733:     $r->print('<br />'.
 1734:               '<a href="'.$filename.'">'.&mt('Your csv file.').'</a>'."\n");
 1735:     $r->rflush();
 1736:     &csv_cleanup();
 1737:     return;
 1738:     
 1739: }
 1740: 
 1741: }
 1742: 
 1743: #######################################################
 1744: #######################################################
 1745: 
 1746: =pod
 1747: 
 1748: =item &StudentTriesOnSequence()
 1749: 
 1750: Inputs:
 1751: 
 1752: =over 4
 1753: 
 1754: =item $student
 1755: 
 1756: =item $studentdata Hash ref to all student data
 1757: 
 1758: =item $seq Hash ref, the sequence we are working on
 1759: 
 1760: =item $links if defined we will output links to each resource.
 1761: 
 1762: =back
 1763: 
 1764: =cut
 1765: 
 1766: #######################################################
 1767: #######################################################
 1768: sub student_tries_on_sequence {
 1769:     my ($student,$studentdata,$navmap,$seq,$links) = @_;
 1770:     $links = 'no' if (! defined($links));
 1771:     my $Str = '';
 1772:     my ($sum,$max) = (0,0);
 1773:     my $performance_length = 0;
 1774:     my @TriesData = ();
 1775:     my $tries;
 1776:     my $hasdata = 0; # flag - true if the student has any data on the sequence
 1777:     foreach my $resource (&get_resources($navmap,$seq)) {
 1778:         my $resource_data = $studentdata->{$resource->symb};
 1779:         my $value = '';
 1780:         foreach my $partnum (@{$resource->parts()}) {
 1781:             $tries = undef;
 1782:             $max++;
 1783:             $performance_length++;
 1784:             my $symbol = ' '; # default to space
 1785:             #
 1786:             my $awarded = 0;
 1787:             if (exists($resource_data->{'resource.'.$partnum.'.awarded'})) {
 1788:                 $awarded = $resource_data->{'resource.'.$partnum.'.awarded'};
 1789:                 $awarded = 0 if (! $awarded);
 1790:             }
 1791:             #
 1792:             my $status = '';
 1793:             if (exists($resource_data->{'resource.'.$partnum.'.solved'})) {
 1794:                 $status = $resource_data->{'resource.'.$partnum.'.solved'};
 1795:             }
 1796:             #
 1797:             my $tries = 0;
 1798:             if(exists($resource_data->{'resource.'.$partnum.'.tries'})) {
 1799:                 $tries = $resource_data->{'resource.'.$partnum.'.tries'};
 1800:                 $hasdata =1;
 1801:             }
 1802:             #
 1803:             if ($awarded > 0) {
 1804:                 # The student has gotten the problem correct to some degree
 1805:                 if ($status eq 'excused') {
 1806:                     $symbol = 'x';
 1807:                     $max--;
 1808:                 } elsif ($status eq 'correct_by_override') {
 1809:                     $symbol = '+';
 1810:                     $sum++;
 1811:                 } elsif ($tries > 0) {
 1812:                     if ($tries > 9) {
 1813:                         $symbol = '*';
 1814:                     } else {
 1815:                         $symbol = $tries;
 1816:                     }
 1817:                     $sum++;
 1818:                 } else {
 1819:                     $symbol = '+';
 1820:                     $sum++;
 1821:                 }
 1822:             } else {
 1823:                 # The student has the problem incorrect or it is ungraded
 1824:                 if ($status eq 'excused') {
 1825:                     $symbol = 'x';
 1826:                     $max--;
 1827:                 } elsif ($status eq 'incorrect_by_override') {
 1828:                     $symbol = '-';
 1829:                 } elsif ($status eq 'ungraded_attempted') {
 1830:                     $symbol = 'u';
 1831:                 } elsif ($status eq 'incorrect_attempted' ||
 1832:                          $tries > 0)  {
 1833:                     $symbol = '.';
 1834:                 } else {
 1835:                     # Problem is wrong and has not been attempted.
 1836:                     $symbol=' ';
 1837:                 }
 1838:             }
 1839:             #
 1840:             if (! defined($tries)) {
 1841:                 $tries = 0;
 1842:             }
 1843:             if ($status =~ /^(incorrect|ungraded)/) {
 1844:                 # Bug 3390: show '-' for tries on incorrect problems 
 1845:                 # (csv & excel only)
 1846:                 push(@TriesData,-$tries);
 1847:             } else {
 1848:                 push (@TriesData,$tries);
 1849:             }
 1850:             #
 1851:             if ( ($links eq 'yes' && $symbol ne ' ') ||
 1852:                  ($links eq 'all')) {
 1853:                 if (length($symbol) > 1) {
 1854:                     &Apache::lonnet::logthis('length of symbol "'.$symbol.'" > 1');
 1855:                 }
 1856:                 $symbol = '<a href="/adm/grades'.
 1857:                     '?symb='.&Apache::lonnet::escape($resource->symb).
 1858:                         '&student='.$student->{'username'}.
 1859:                             '&userdom='.$student->{'domain'}.
 1860:                                 '&command=submission">'.$symbol.'</a>';
 1861:             }
 1862:             $value .= $symbol;
 1863:         }
 1864:         $Str .= $value;
 1865:     }
 1866:     if ($seq->randompick()) {
 1867:         $max = $seq->randompick();
 1868:     }
 1869:     if (! $hasdata && $sum == 0) {
 1870:         $sum = ' ';
 1871:     }
 1872:     return ($Str,$performance_length,$sum,$max,\@TriesData);
 1873: }
 1874: 
 1875: #######################################################
 1876: #######################################################
 1877: 
 1878: =pod
 1879: 
 1880: =item &student_performance_on_sequence
 1881: 
 1882: Inputs:
 1883: 
 1884: =over 4
 1885: 
 1886: =item $student
 1887: 
 1888: =item $studentdata Hash ref to all student data
 1889: 
 1890: =item $seq Hash ref, the sequence we are working on
 1891: 
 1892: =item $links if defined we will output links to each resource.
 1893: 
 1894: =back
 1895: 
 1896: =cut
 1897: 
 1898: #######################################################
 1899: #######################################################
 1900: sub student_performance_on_sequence {
 1901:     my ($student,$studentdata,$navmap,$seq,$links) = @_;
 1902:     $links = 'no' if (! defined($links));
 1903:     my $Str = ''; # final result string
 1904:     my ($score,$max) = (0,0);
 1905:     my $performance_length = 0;
 1906:     my $symbol;
 1907:     my @ScoreData = ();
 1908:     my $partscore;
 1909:     my $hasdata = 0; # flag, 0 if there were no submissions on the sequence
 1910:     foreach my $resource (&get_resources($navmap,$seq)) {
 1911:         my $symb = $resource->symb;
 1912:         my $resource_data = $studentdata->{$symb};
 1913:         foreach my $part (@{$resource->parts()}) {
 1914:             $partscore = undef;
 1915:             my $weight = &Apache::lonnet::EXT('resource.'.$part.'.weight',
 1916:                                               $symb,
 1917:                                               $student->{'domain'},
 1918:                                               $student->{'username'},
 1919:                                               $student->{'section'});
 1920:             if (!defined($weight) || ($weight eq '')) { 
 1921:                 $weight=1;
 1922:             }
 1923:             #
 1924:             $max += $weight; # see the 'excused' branch below...
 1925:             $performance_length++; # one character per part
 1926:             $symbol = ' '; # default to space
 1927:             #
 1928:             my $awarded;
 1929:             if (exists($resource_data->{'resource.'.$part.'.awarded'})) {
 1930:                 $awarded = $resource_data->{'resource.'.$part.'.awarded'};
 1931:                 $awarded = 0 if (! $awarded);
 1932:                 $hasdata = 1;
 1933:             }
 1934:             #
 1935:             $partscore = $weight*$awarded;
 1936:             if (! defined($awarded)) {
 1937:                 $partscore = undef;
 1938:             }
 1939:             $score += $partscore;
 1940:             $symbol = $partscore; 
 1941:             if (abs($symbol - sprintf("%.0f",$symbol)) < 0.001) {
 1942:                 $symbol = sprintf("%.0f",$symbol);
 1943:             }
 1944:             if (length($symbol) > 1) {
 1945:                 $symbol = '*';
 1946:             }
 1947:             if (exists($resource_data->{'resource.'.$part.'.solved'}) &&
 1948:                 $resource_data->{'resource.'.$part.'.solved'} ne '') {
 1949:                 my $status = $resource_data->{'resource.'.$part.'.solved'};
 1950:                 if ($status eq 'excused') {
 1951:                     $symbol = 'x';
 1952:                     $max -= $weight; # Do not count 'excused' problems.
 1953:                 } elsif ($status eq 'ungraded_attempted') {
 1954:                     $symbol = 'u';
 1955:                 }
 1956:                 $hasdata = 1;
 1957:             } elsif ($resource_data->{'resource.'.$part.'.award'} eq 'DRAFT') {
 1958:                 $symbol = 'd';
 1959:                 $hasdata = 1;
 1960:             } elsif (!exists($resource_data->{'resource.'.$part.'.awarded'})){
 1961:                 # Unsolved.  Did they try?
 1962:                 if (exists($resource_data->{'resource.'.$part.'.tries'})){
 1963:                     $symbol = '.';
 1964:                     $hasdata = 1;
 1965:                 } else {
 1966:                     $symbol = ' ';
 1967:                 }
 1968:             }
 1969:             #
 1970:             if (! defined($partscore)) {
 1971:                 $partscore = $symbol;
 1972:             }
 1973:             push (@ScoreData,$partscore);
 1974:             #
 1975:             if ( ($links eq 'yes' && $symbol ne ' ') || ($links eq 'all')) {
 1976:                 $symbol = '<a href="/adm/grades'.
 1977:                     '?symb='.&Apache::lonnet::escape($symb).
 1978:                     '&student='.$student->{'username'}.
 1979:                     '&userdom='.$student->{'domain'}.
 1980:                     '&command=submission">'.$symbol.'</a>';
 1981:             }
 1982:             $Str .= $symbol;
 1983:         }
 1984:     }
 1985:     if (! $hasdata && $score == 0) {
 1986:         $score = ' ';
 1987:     }
 1988:     return ($Str,$performance_length,$score,$max,\@ScoreData);
 1989: }
 1990: 
 1991: #######################################################
 1992: #######################################################
 1993: 
 1994: =pod
 1995: 
 1996: =item &CreateLegend()
 1997: 
 1998: This function returns a formatted string containing the legend for the
 1999: chart.  The legend describes the symbols used to represent grades for
 2000: problems.
 2001: 
 2002: =cut
 2003: 
 2004: #######################################################
 2005: #######################################################
 2006: sub CreateLegend {
 2007:     my $Str = "<p><pre>".
 2008:               " digit score or number of tries to get correct ".
 2009:               "   *  correct by student in more than 9 tries\n".
 2010: 	      "   +  correct by hand grading or override\n".
 2011:               "   -  incorrect by override\n".
 2012: 	      "   .  incorrect attempted\n".
 2013: 	      "   u  ungraded attempted\n".
 2014:               "   d  draft answer saved but not submitted\n".
 2015:               "      not attempted (blank field)\n".
 2016: 	      "   x  excused".
 2017:               "</pre><p>";
 2018:     return $Str;
 2019: }
 2020: 
 2021: #######################################################
 2022: #######################################################
 2023: 
 2024: =pod 
 2025: 
 2026: =back
 2027: 
 2028: =cut
 2029: 
 2030: #######################################################
 2031: #######################################################
 2032: 
 2033: 1;
 2034: 
 2035: __END__

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