File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.103: download - view: text, annotated - select for diffs
Wed Nov 10 16:56:39 2004 UTC (19 years, 7 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Numerical response analysis works for attempts, but not time analysis.
Shows histogram of correct answers each time, which is dumb.

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: lonproblemanalysis.pm,v 1.103 2004/11/10 16:56:39 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: #
    9: # LON-CAPA is free software; you can redistribute it and/or modify
   10: # it under the terms of the GNU General Public License as published by
   11: # the Free Software Foundation; either version 2 of the License, or
   12: # (at your option) any later version.
   13: #
   14: # LON-CAPA is distributed in the hope that it will be useful,
   15: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   16: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   17: # GNU General Public License for more details.
   18: #
   19: # You should have received a copy of the GNU General Public License
   20: # along with LON-CAPA; if not, write to the Free Software
   21: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   22: #
   23: # /home/httpd/html/adm/gpl.txt
   24: #
   25: # http://www.lon-capa.org/
   26: #
   27: package Apache::lonproblemanalysis;
   28: 
   29: use strict;
   30: use Apache::lonnet();
   31: use Apache::loncommon();
   32: use Apache::lonhtmlcommon();
   33: use Apache::loncoursedata();
   34: use Apache::lonstatistics;
   35: use Apache::lonlocal;
   36: use Apache::lonstathelpers();
   37: use Apache::lonstudentsubmissions();
   38: use HTML::Entities();
   39: use Time::Local();
   40: use Spreadsheet::WriteExcel();
   41: 
   42: my $plotcolors = ['#33ff00', 
   43:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
   44:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
   45:                   ]; 
   46: 
   47: my @SubmitButtons = ({ name => 'PrevProblemAnalysis',
   48:                        text => 'Previous Problem' },
   49:                      { name => 'ProblemAnalysis',
   50:                        text => 'Analyze Problem Again' },
   51:                      { name => 'NextProblemAnalysis',
   52:                        text => 'Next Problem' },
   53:                      { name => 'break'},
   54:                      { name => 'SelectAnother',
   55:                        text => 'Choose a different Problem' },
   56:                      { name => 'ExcelOutput',
   57:                        text => 'Produce Excel Output' });
   58: 
   59: sub BuildProblemAnalysisPage {
   60:     my ($r,$c)=@_;
   61:     #
   62:     my %Saveable_Parameters = ('Status' => 'scalar',
   63:                                'Section' => 'array',
   64:                                'NumPlots' => 'scalar',
   65:                                'AnalyzeOver' => 'scalar',
   66:                                );
   67:     &Apache::loncommon::store_course_settings('problem_analysis',
   68:                                               \%Saveable_Parameters);
   69:     &Apache::loncommon::restore_course_settings('problem_analysis',
   70:                                                 \%Saveable_Parameters);
   71:     #
   72:     &Apache::lonstatistics::PrepareClasslist();
   73:     #
   74:     $r->print(&CreateInterface());
   75:     #
   76:     my @Students = @Apache::lonstatistics::Students;
   77:     #
   78:     if (@Students < 1 && exists($ENV{'form.firstrun'})) {
   79:         $r->print('<h2>There are no students in the sections selected</h2>');
   80:     }
   81:     #
   82:     my @CacheButtonHTML = 
   83:         &Apache::lonstathelpers::manage_caches($r,'Statistics','stats_status');
   84:     $r->rflush();
   85:     #
   86:     # Support for numerical and radio response isn't complete enough to
   87:     # include in 1.2 release.
   88:     # my $problem_types = '(option|radiobutton|numerical)';
   89:     my $problem_types = '.';#(option)';
   90:     if (exists($ENV{'form.problemchoice'}) && 
   91:         ! exists($ENV{'form.SelectAnother'})) {
   92:         foreach my $button (@SubmitButtons) {
   93:             if ($button->{'name'} eq 'break') {
   94:                 $r->print("<br />\n");
   95:             } else {
   96:                 $r->print('<input type="submit" name="'.$button->{'name'}.'" '.
   97:                           'value="'.&mt($button->{'text'}).'" />');
   98:                 $r->print('&nbsp;'x5);
   99:             }
  100:         }
  101:         foreach my $html (@CacheButtonHTML) {
  102:             $r->print($html.('&nbsp;'x5));
  103:         }
  104:         #
  105:         $r->print('<hr />');
  106:         $r->rflush();
  107:         #
  108:         # Determine which problem we are to analyze
  109:         my $current_problem = &Apache::lonstathelpers::get_target_from_id
  110:             ($ENV{'form.problemchoice'});
  111:         #
  112:         my ($prev,$curr,$next) = 
  113:             &Apache::lonstathelpers::get_prev_curr_next($current_problem,
  114:                                                         $problem_types,
  115:                                                         'response',
  116:                                                         );
  117:         if (exists($ENV{'form.PrevProblemAnalysis'}) && defined($prev)) {
  118:             $current_problem = $prev;
  119:         } elsif (exists($ENV{'form.NextProblemAnalysis'}) && defined($next)) {
  120:             $current_problem = $next;
  121:         } else {
  122:             $current_problem = $curr;
  123:         }
  124:         #
  125:         # Store the current problem choice and send it out in the form
  126:         $ENV{'form.problemchoice'} = 
  127:             &Apache::lonstathelpers::make_target_id($current_problem);
  128:         $r->print('<input type="hidden" name="problemchoice" value="'.
  129:                   $ENV{'form.problemchoice'}.'" />');
  130:         #
  131:         if (! defined($current_problem->{'resource'})) {
  132:             $r->print('resource is undefined');
  133:         } else {
  134:             my $resource = $current_problem->{'resource'};
  135:             $r->print('<h1>'.$resource->{'title'}.'</h1>');
  136:             $r->print('<h3>'.$resource->{'src'}.'</h3>');
  137:             if ($ENV{'form.show_prob'} eq 'true') {
  138:                 $r->print(&Apache::lonstathelpers::render_resource($resource));
  139:             }
  140:             $r->rflush();
  141:             my %Data = &Apache::lonstathelpers::get_problem_data
  142:                 ($resource->{'src'});
  143:             my $problem_data = $Data{$current_problem->{'part'}.
  144:                                     '.'.
  145:                                     $current_problem->{'respid'}};
  146:             if ($current_problem->{'resptype'} eq 'option') {
  147:                 &OptionResponseAnalysis($r,$current_problem,
  148:                                         $problem_data,
  149:                                         \@Students);
  150:             } elsif ($current_problem->{'resptype'} eq 'radiobutton') {
  151:                 &radio_response_analysis($r,$current_problem,
  152:                                          $problem_data,
  153:                                          \@Students);
  154:             } elsif ($current_problem->{'resptype'} eq 'numerical') {
  155:                 &numerical_response_analysis($r,$current_problem,
  156:                                              $problem_data,\@Students);
  157:             } else {
  158:                 $r->print('<h2>Analysis of '.$current_problem->{'resptype'}.' is not supported</h2>');
  159:             }
  160:         }
  161:         $r->print('<hr />');
  162:     } else {
  163:         $r->print('<input type="submit" name="ProblemAnalysis" value="'.
  164:                   &mt('Analyze Problem').'" />');
  165:         $r->print('&nbsp;'x5);
  166:         $r->print('<h3>'.&mt('Please select a problem to analyze').'</h3>');
  167:         $r->print(&Apache::lonstathelpers::ProblemSelector
  168:                   ($problem_types));
  169:     }
  170: }
  171: 
  172: #########################################################
  173: #########################################################
  174: ##
  175: ##      Numerical Response Routines
  176: ##
  177: #########################################################
  178: #########################################################
  179: sub numerical_response_analysis {
  180:     my ($r,$problem,$problem_analysis,$students) = @_;
  181:     my $c = $r->connection();
  182:     #
  183:     if ($ENV{'form.AnalyzeOver'} !~ /^(tries|time)$/) {
  184:         $r->print('Bad request');
  185:     }
  186:     #
  187:     my ($resource,$partid,$respid) = ($problem->{'resource'},
  188:                                       $problem->{'part'},
  189:                                       $problem->{'respid'});
  190:     # Gather student data
  191:     my $response_data = &Apache::loncoursedata::get_response_data
  192:         (\@Apache::lonstatistics::SelectedSections,
  193:          $Apache::lonstatistics::enrollment_status,
  194:          $resource->{'symb'},$respid);
  195:     #
  196:     for (my $plot_num = 1;$plot_num<=$ENV{'form.NumPlots'};$plot_num++) {
  197:         my $restriction_function;
  198:         $restriction_function = sub {($_[0]->{'tries'} == $plot_num?1:0)};
  199:         #
  200:         my ($correct,$intervals,$answers) = 
  201:             &numerical_response_determine_intervals($r,$resource,$partid,
  202:                                                     $respid,$students);
  203:         if ($c->aborted()) { return; };
  204:         #
  205:         my $responses = &classify_response_data($response_data,
  206:                                                 $correct,
  207:                                                 $restriction_function);
  208:         my $student_count = $responses->{'_students'};
  209:         my $correct_count = $responses->{'_correct'};
  210:         my $total_count   = $responses->{'_count'};
  211:         my $max           = $responses->{'_max'};
  212:         #
  213:         my $analysis_html = '<h2>'.&mt('Attempt [_1]',$plot_num).'</h2>';
  214:         $analysis_html.= &numerical_one_dimensional_plot($r,600,150,
  215:                                                          scalar(@$students),
  216:                                                          $answers);
  217:         $analysis_html.= '<table><tr>'.
  218:             '<td valign="top" align="center">'.
  219:             &numerical_plot_percent($r,$responses).'</td>'.
  220:             '<td align="center" valign="top">'.
  221:             &numerical_plot_differences($r,$responses).'</td>'.
  222:             '</tr>'.$/.'</table>';
  223:         $r->print($analysis_html);
  224:     }
  225:     #
  226:     return;
  227: }
  228: 
  229: sub numerical_plot_percent {
  230:     my ($r,$responses) = @_;
  231:     #
  232:     my $total = $responses->{'_count'};
  233:     return '' if ($total == 0);
  234:     my $minbin = 0.5;
  235:     while (my ($interval,$submissions) = each(%$responses)) {
  236:         next if ($interval =~ /^_/);
  237:         my ($ans,$ans_low,$ans_high) = split(" ",$interval);
  238:         my $low_percent  = abs(($ans-$ans_low)/$ans);
  239:         my $high_percent = abs(($ans_high-$ans)/$ans);
  240:         if ($minbin > $high_percent) { $minbin = $high_percent; }
  241:         if ($minbin > $low_percent) { $minbin = $low_percent; }
  242:     }    
  243:     #
  244:     my @bins;
  245:     if ($minbin < 1) {
  246:         @bins = (0.1, ".5",1,1.5,2,2.5,3,4,5,10,20,50,100);        
  247:     } elsif ($minbin < 2) {
  248:         @bins = (0.5,1,1.5,2,2.5,3,4,5,10,20,50,100);
  249:     } elsif ($minbin < 5) {
  250:         @bins = (1,2,3,4,5,10,25,50,75,100,200);
  251:     } elsif ($minbin < 10) {
  252:         @bins = (2,4,6,8,10,12,15,20,25,30,50,75,100,200);
  253:     } else {
  254:         @bins = (5,10,15,20,25,30,50,75,100,200);
  255:     }
  256:     my @labels = (1..scalar(@bins));
  257:     #
  258:     my @correct;
  259:     my @incorrect;
  260:     while (my ($interval,$submissions) = each(%$responses)) {
  261:         next if ($interval =~ /^_/);
  262:         my ($ans,$ans_low,$ans_high) = split(" ",$interval);
  263:         while (my ($submission,$count) = each(%$submissions)) {
  264:             my $scaled_value = abs(($submission-$ans)/$ans);
  265:             my $bin=0;
  266:             for ($bin=0;$bin<$#bins;$bin++) { # not <= for a reason
  267:                 last if ($bins[$bin]>$scaled_value);
  268:             }
  269:             if (($submission <= $ans_high) && ($submission >= $ans_low)) {
  270:                 $correct[$bin]+=$count;
  271:             } else {
  272:                 $incorrect[$bin]+=$count;
  273:             }
  274:         }
  275:     }
  276:     #
  277:     for (my $i=0;$i<=$#bins;$i++) {
  278:         if (! defined(  $correct[$i])) {   $correct[$i]=0;}
  279:         if (! defined($incorrect[$i])) { $incorrect[$i]=0;}
  280:         $correct[$i]*=100/$total;
  281:         $incorrect[$i]*=100/$total;
  282:     }
  283:     my $title = &mt('Distribution by Percent');
  284:     my $graph = &Apache::loncommon::DrawBarGraph
  285:         ($title,'Percent difference from correct','Number of answers',
  286:          100,['#33FF00','#FF3300'],\@labels,\@correct,\@incorrect,
  287:          {xskip=>1});
  288:     #
  289:     my $table = $graph.'<table><tr><th>'.&mt('Bar').'</th>'.
  290:         '<th colspan="3">'.&mt('Range').'</th>';
  291:     for (my $i=0;$i<=$#bins;$i++) {
  292:         my $lownum;
  293:         if ($i == 0) {
  294:             $lownum = 0;
  295:         } else {
  296:             $lownum = $bins[$i-1];
  297:         }
  298:         my $highnum = $bins[$i];
  299:         $table .= 
  300:             '<tr>'.
  301:             '<td>'.$labels[$i].'</td>'.
  302:             '<td align="right">'.$lownum.'</td>'.
  303:             '<td>&nbsp;-&nbsp;</td>'.
  304:             '<td align="right">'.$highnum.'</td>'.'</tr>'.$/;
  305:     }
  306:     $table.= '</table>'.$/;
  307:     return $table;
  308: }
  309: 
  310: sub numerical_plot_differences {
  311:     my ($r,$responses) = @_;
  312:     #
  313:     my $total = $responses->{'_count'};
  314:     return '' if ($total == 0);
  315:     my $minbin = undef;
  316:     my $maxbin = undef;
  317:     while (my ($interval,$submissions) = each(%$responses)) {
  318:         next if ($interval =~ /^_/);
  319:         my ($ans,$ans_low,$ans_high) = split(" ",$interval);
  320:         my $low_diff  = abs($ans-$ans_low);
  321:         my $high_diff = abs($ans_high-$ans);
  322:         if (! defined($maxbin)) { $maxbin = $low_diff;}
  323:         if (! defined($minbin)) { $minbin = $low_diff;}
  324:         #
  325:         if ($minbin > $high_diff) { $minbin = $high_diff; }
  326:         if ($minbin > $low_diff ) { $minbin = $low_diff; }
  327:         #
  328:         if ($maxbin < $high_diff) { $maxbin = $high_diff; }
  329:         if ($maxbin < $low_diff ) { $maxbin = $low_diff; }
  330:     }    
  331:     #
  332:     my @bins;
  333:     my @labels;
  334:     # Hmmmm, should switch to absolute difference
  335:     for (my $i=1;$i<=20;$i++) {
  336:         push(@bins,$i*$minbin/2);
  337:         push(@labels,$i);
  338:     }
  339:     #
  340:     my @correct;
  341:     my @incorrect;
  342:     while (my ($interval,$submissions) = each(%$responses)) {
  343:         next if ($interval =~ /^_/);
  344:         my ($ans,$ans_low,$ans_high) = split(" ",$interval);
  345:         while (my ($submission,$count) = each(%$submissions)) {
  346:             my $value = abs($submission-$ans);
  347:             my $bin=0;
  348:             for ($bin=0;$bin<$#bins;$bin++) { # not <= for a reason
  349:                 last if ($bins[$bin]>$value);
  350:             }
  351:             if (($submission <= $ans_high) && ($submission >= $ans_low)) {
  352:                 $correct[$bin]+=$count;
  353:             } else {
  354:                 $incorrect[$bin]+=$count;
  355:             }
  356:         }
  357:     }
  358:     #
  359:     for (my $i=0;$i<=$#bins;$i++) {
  360:         if (! defined(  $correct[$i])) {   $correct[$i]=0;}
  361:         if (! defined($incorrect[$i])) { $incorrect[$i]=0;}
  362:         $correct[$i]*=100/$total;
  363:         $incorrect[$i]*=100/$total;
  364:     }
  365:     my $title = &mt('Distribution by Magnitude');
  366:     my $graph = &Apache::loncommon::DrawBarGraph
  367:         ($title,'magnitude difference from correct','Number of answers',
  368:          100,['#33FF00','#FF3300'],\@labels,\@correct,\@incorrect,{xskip=>1});
  369:     #
  370:     my $table = $graph.'<table><tr><th>'.&mt('Bar').'</th>'.
  371:         '<th colspan="3">'.&mt('Range').'</th>';
  372:     for (my $i=0;$i<=$#bins;$i++) {
  373:         my $lownum;
  374:         if ($i == 0) {
  375:             $lownum = 0;
  376:         } else {
  377:             $lownum = $bins[$i-1];
  378:         }
  379:         my $highnum = $bins[$i];
  380:         $table .= 
  381:             '<tr>'.
  382:             '<td>'.$labels[$i].'</td>'.
  383:             '<td align="right">'.$lownum.'</td>'.
  384:             '<td>&nbsp;-&nbsp;</td>'.
  385:             '<td align="right">'.$highnum.'</td>'.'</tr>'.$/;
  386:     }
  387:     $table.= '</table>'.$/;
  388:     return $table;
  389: }
  390: 
  391: sub numerical_response_determine_intervals {
  392:     my ($r,$resource,$partid,$respid,$students)=@_;
  393:     my $c = $r->connection();
  394:     #
  395:     # FIX ME: Need progress dialog updates
  396:     #
  397:     # Read in the cache (if it exists) before we start timing things.
  398:     &Apache::lonstathelpers::ensure_proper_cache($resource->{'symb'});
  399:     #
  400:     my $correct;
  401:     # %intervals differs from %answers because it may be possible for two
  402:     # students to have the same correct answer but different intervals.
  403:     my %intervals; 
  404:     my %answers;
  405:     foreach my $student (@$students) {
  406:         last if ($c->aborted());
  407:         my $sname = $student->{'username'};
  408:         my $sdom = $student->{'domain'};
  409:         # analyze problem
  410:         my $analysis = 
  411:             &Apache::lonstathelpers::analyze_problem_as_student($resource,
  412:                                                                 $sname,
  413:                                                                 $sdom);
  414:         # make the key
  415:         my $key = $partid.'.'.$respid;
  416:         my $interval = join(' ',($analysis->{$key.'.answer'}->[0],
  417:                                  $analysis->{$key.'.ans_low'}->[0],
  418:                                  $analysis->{$key.'.ans_high'}->[0]));
  419:         $correct->{$sname.':'.$sdom} = $interval;
  420:         $intervals{$interval}++;
  421:         $answers{$analysis->{$key.'.answer'}->[0]}++;
  422:     }
  423:     &Apache::lonstathelpers::write_analysis_cache();
  424:     return ($correct,\%intervals,\%answers);
  425: }
  426: 
  427: sub numerical_one_dimensional_plot {
  428:     my ($r,$width,$height,$n,$data)=@_;
  429:     #
  430:     # Compute data -> image scaling factors
  431:     my $max_y = 0;
  432:     my $min_x = undef;
  433:     my $max_x = undef;
  434:     while (my ($answer,$count) = each(%$data)) {
  435:         $max_y = $count if ($max_y < $count);
  436:         if (! defined($min_x) || $answer < $min_x) {
  437:             $min_x = $answer;
  438:         }
  439:         if (! defined($max_x) || $answer > $max_x) {
  440:             $max_x = $answer;
  441:         }
  442:     }
  443:     #
  444:     my $h_scale = ($width-10)/($max_x-$min_x);
  445:     #
  446:     my $ticscale = 5;
  447:     if ($max_y * $ticscale > $height/2) {
  448:         $ticscale = int($height/2/$max_y);
  449:         $ticscale = 1 if ($ticscale < 1);
  450:     }
  451:     #
  452:     # Create the plot
  453:     my $plot = 
  454:         qq{<drawimage width="$width" height="$height" bgcolor="transparent" >};
  455:     while (my ($answer,$count) = each(%$data)) {
  456:         my $xloc = 5+$h_scale*($answer - $min_x);
  457:         my $top    = $height/2-$count*$ticscale;
  458:         my $bottom = $height/2+$count*$ticscale;
  459:         $plot .= &line($xloc,$top,$xloc,$bottom,'888888',1);
  460:     }
  461:     #
  462:     # Put the scale on last to ensure it is on top of the data.
  463:     if ($min_x < 0 && $max_x > 0) {
  464:         my $circle_x = 5+$h_scale*abs($min_x);  # '0' in data coordinates
  465:         my $r = 4;
  466:         $plot .= &line(5,$height/2,$circle_x-$r,$height/2,'000000',1);
  467:         $plot .= &circle($circle_x,$height/2,$r+1,'000000');
  468:         $plot .= &line($circle_x+$r,$height/2,$width-5,$height/2,'000000',1);
  469:     } else {
  470:         $plot .= &line(5,$height/2,$width-5,$height/2,'000000',1);
  471:     }
  472:     $plot .= '</drawimage>';
  473:     my $plotresult =  &Apache::lonxml::xmlparse($r,'web',$plot);
  474:     
  475:     my $result = '<table>'.
  476:         '<tr><td colspan="3" align="center">'.
  477:         '<font size="+2">'.&mt('Distribution of correct answers').'</font>'.
  478:         '<br />'.&mt('[_1] students, [_2] distinct correct answers',
  479:                      $n,scalar(keys(%$data))).
  480:         '<br />'.&mt('Maximum number of coinciding values: [_1]',$max_y).
  481:         '</td></tr>'.
  482:         '<tr>'.
  483:         '<td valign="center">'.$min_x.'</td>'.
  484:         '<td>'.$plotresult.'</td>'.
  485:         '<td valign="center">'.$max_x.'</td>'.
  486:         '</tr>'.
  487:         '</table>';
  488:     return $result;
  489: }
  490: 
  491: ##
  492: ## Helper subroutines for <drawimage>.  
  493: ## These should probably go somewhere more suitable soon.
  494: sub line {
  495:     my ($x1,$y1,$x2,$y2,$color,$thickness) = @_;
  496:     return qq{<line x1="$x1" y1="$y1" x2="$x2" y2="$y2" color="$color" thickness="$thickness" />};
  497: }
  498: 
  499: sub text {
  500:     my ($x,$y,$color,$text,$font,$direction) = @_;
  501:     if (! defined($font) || $font !~ /^(tiny|small|medium|large|giant)$/) {
  502:         $font = 'medium';
  503:     }
  504:     if (! defined($direction) || $direction ne 'vertical') {
  505:         $direction = '';
  506:     }
  507:     return qq{<text x="$x" y="$y" color="$color" font="$font" direction="$direction" >$text</text>};
  508: }
  509: 
  510: sub rectangle {
  511:     my ($x1,$y1,$x2,$y2,$color,$thickness,$filled) = @_;
  512:     return qq{<rectangle x1="$x1" y1="$y1" x2="$x2" y2="$y2" color="$color" thickness="$thickness" filled="$filled" />};
  513: }
  514: 
  515: sub arc {
  516:     my ($x,$y,$width,$height,$start,$end,$color,$thickness,$filled)=@_;
  517:     return qq{<arc x="$x" y="$y" width="$width" height="$height" start="$start" end="$end" color="$color" thickness="$thickness" filled="$filled" />};
  518: }
  519: 
  520: sub circle {
  521:     my ($x,$y,$radius,$color,$thickness,$filled)=@_;
  522:     return &arc($x,$y,$radius,$radius,0,360,$color,$thickness,$filled);
  523: }
  524: 
  525: sub build_student_data_worksheet {
  526:     my ($workbook,$format) = @_;
  527:     my $rows_output = 3;
  528:     my $cols_output = 0;
  529:     my $worksheet  = $workbook->addworksheet('Student Data');
  530:     $worksheet->write($rows_output++,0,'Student Data',$format->{'h3'});
  531:     my @Headers = ('full name','username','domain','section',
  532:                    "student\nnumber",'identifier');
  533:     $worksheet->write_row($rows_output++,0,\@Headers,$format->{'header'});
  534:     my @Students = @Apache::lonstatistics::Students;
  535:     my $studentrows = &Apache::loncoursedata::get_student_data(\@Students);
  536:     my %ids;
  537:     foreach my $row (@$studentrows) {
  538:         my ($mysqlid,$student) = @$row;
  539:         $ids{$student}=$mysqlid;
  540:     }
  541:     foreach my $student (@Students) {
  542:         my $name_domain = $student->{'username'}.':'.$student->{'domain'};
  543:         $worksheet->write_row($rows_output++,0,
  544:                           [$student->{'fullname'},
  545:                            $student->{'username'},$student->{'domain'},
  546:                            $student->{'section'},$student->{'id'},
  547:                            $ids{$name_domain}]);
  548:     }
  549:     return $worksheet;
  550: }
  551: 
  552: #########################################################
  553: #########################################################
  554: ##
  555: ##      Radio Response Routines
  556: ##
  557: #########################################################
  558: #########################################################
  559: sub radio_response_analysis {
  560:     my ($r,$problem,$problem_analysis,$students) = @_;
  561:     #
  562:     if ($ENV{'form.AnalyzeOver'} !~ /^(tries|time)$/) {
  563:         $r->print('Bad request');
  564:     }
  565:     #
  566:     my ($resource,$partid,$respid) = ($problem->{'resource'},
  567:                                       $problem->{'part'},
  568:                                       $problem->{'respid'});
  569:     #
  570:     my $analysis_html;
  571:     my $foildata = $problem_analysis->{'_Foils'};
  572:     my ($table,$foils,$concepts) = &build_foil_index($problem_analysis);
  573:     #
  574:     my %true_foils;
  575:     my $num_true = 0;
  576:     if (! $problem_analysis->{'answercomputed'}) {
  577:         foreach my $foil (@$foils) {
  578:             if ($foildata->{$foil}->{'value'} eq 'true') {
  579:                 $true_foils{$foil}++; 
  580:             }
  581:         }
  582:         $num_true = scalar(keys(%true_foils));
  583:     }
  584:     #
  585:     $analysis_html .= $table;
  586:     # Gather student data
  587:     my $response_data = &Apache::loncoursedata::get_response_data
  588:         (\@Apache::lonstatistics::SelectedSections,
  589:          $Apache::lonstatistics::enrollment_status,
  590:          $resource->{'symb'},$respid);
  591:     my $correct;   # either a hash reference or a scalar
  592:     if ($problem_analysis->{'answercomputed'} || scalar(@$concepts) > 1) {
  593:         # This takes a while for large classes...
  594:         &Apache::lonstathelpers::GetStudentAnswers($r,$problem,$students,
  595:                                                    'Statistics',
  596:                                                    'stats_status');
  597:         foreach my $student (@$students) {
  598:             my ($idx,@remainder) = split('&',$student->{'answer'});
  599:             my ($answer) = ($remainder[$idx]=~/^(.*)=([^=]*)$/);
  600:             $correct->{$student->{'username'}.':'.$student->{'domain'}}=
  601:                 &Apache::lonnet::unescape($answer);
  602:         }
  603:     } else {
  604:         foreach my $foil (keys(%$foildata)) {
  605:             if ($foildata->{$foil}->{'value'} eq 'true') {
  606:                 $correct = $foildata->{$foil}->{'name'};
  607:             }
  608:         }
  609:     }
  610:     #
  611:     if (! defined($response_data) || ref($response_data) ne 'ARRAY' ) {
  612:         $analysis_html = '<h2>'.
  613:             &mt('There is no submission data for this resource').
  614:             '</h2>';
  615:         $r->print($analysis_html);
  616:         return;
  617:     }
  618:     #
  619:     $analysis_html.='<table>';
  620:     for (my $plot_num = 1;$plot_num<=$ENV{'form.NumPlots'};$plot_num++) {
  621:         # classify data ->correct foil -> selected foil
  622:         my ($restriction_function,
  623:             $correct_foil_title,$incorrect_foil_title,
  624:             $pre_graph_text,$post_graph_text,
  625:             $no_data_text,@extra_data);
  626:         if ($ENV{'form.AnalyzeOver'} eq 'tries') {
  627:             $restriction_function = sub {($_[0]->{'tries'} == $plot_num?1:0)};
  628:             $correct_foil_title = 'Attempt '.$plot_num;
  629:             $incorrect_foil_title = 'Attempt '.$plot_num;
  630:             $pre_graph_text = 
  631:                 'Attempt [_1], [_2] submissions, [_3] correct, [_4] incorrect';
  632:             $post_graph_text = '';
  633:             $no_data_text = 'No data exists for attempt [_1]';
  634:         } elsif ($ENV{'form.AnalyzeOver'} eq 'time') {
  635:             my $starttime = &Apache::lonhtmlcommon::get_date_from_form
  636:                 ('startdate_'.$plot_num);
  637:             my $endtime = &Apache::lonhtmlcommon::get_date_from_form
  638:                 ('enddate_'.$plot_num);
  639:             ($starttime,$endtime) = &ensure_start_end_times
  640:                 ($starttime,$endtime,
  641:                  &get_time_from_row($response_data->[0]),
  642:                  &get_time_from_row($response_data->[-1]),
  643:                  $plot_num);
  644:             $pre_graph_text = 
  645:                 'Data from [_6] to [_7]<br /> [_2] submissions from [_5] students, [_3] correct, [_4] incorrect';
  646:             $extra_data[0] = &Apache::lonlocal::locallocaltime($starttime);
  647:             $extra_data[1] = &Apache::lonlocal::locallocaltime($endtime);
  648:             #
  649:             $post_graph_text = 
  650:                 &mt('Start time: [_1]',
  651:                     &Apache::lonhtmlcommon::date_setter
  652:                     ('Statistics','startdate_'.$plot_num,$starttime)).
  653:                 '<br />'.
  654:                 &mt('End time: [_1]',
  655:                     &Apache::lonhtmlcommon::date_setter
  656:                     ('Statistics','enddate_'.$plot_num,$endtime));
  657:             $restriction_function = 
  658:                 sub { 
  659:                     my $t = $_[0]->{'timestamp'};
  660:                     if ($t >= $starttime && $t < $endtime) {
  661:                         return 1;
  662:                     } else { 
  663:                         return 0;
  664:                     }
  665:                 };
  666:             $no_data_text = 'No data for [_5] to [_6]';
  667:         }
  668:         my $foil_choice_data =
  669:             &classify_response_data($response_data,$correct,
  670:                                     $restriction_function);
  671:         # &Apache::lonstathelpers::log_hash_ref($foil_choice_data);
  672:         my $answers;
  673:         if (ref($correct)) {
  674:             my %tmp;
  675:             foreach my $foil (values(%$correct)) {
  676:                 $tmp{$foil}++;
  677:             }
  678:             $answers = [keys(%tmp)];
  679:         } else {
  680:             $answers = [$correct];
  681:         }
  682:         # Concept Plot
  683:         my $concept_plot = '';
  684:         if (scalar(@$concepts) > 1) {
  685:             $concept_plot = &RR_concept_plot($concepts,$foil_choice_data,
  686:                                              'Correct Concepts');
  687:         }
  688:         # % Choosing plot
  689:         my $choice_plot = &RR_create_percent_selected_plot
  690:             ($concepts,$foils,$foil_choice_data,$correct_foil_title);
  691:         # for each correct foil, how did they mark it? (stacked bar graph)
  692:         my ($stacked_plot,$count_by_foil);
  693:         if ($problem_analysis->{'answercomputed'} || $num_true > 1) {
  694:             ($stacked_plot,$count_by_foil) =
  695:                 &RR_create_stacked_selection_plot($foils,$foil_choice_data,
  696:                                                   $incorrect_foil_title,
  697:                                                   \%true_foils);
  698:         }
  699:         #
  700:         if ($concept_plot ne '' ||
  701:             $choice_plot  ne '' ||
  702:             $stacked_plot ne '') {
  703:             my $correct = $foil_choice_data->{'_correct'};
  704:             if (! defined($correct) || $correct eq '') {
  705:                 $correct = 0;
  706:             }
  707:             my $incorrect = 
  708:             $analysis_html.= '<tr><td colspan="4" align="center">'.
  709:                 '<font size="+1">'.
  710:                 &mt($pre_graph_text,
  711:                     $plot_num,$foil_choice_data->{'_count'},
  712:                     $correct,
  713:                     $foil_choice_data->{'_count'}-$correct,
  714:                     $foil_choice_data->{'_students'},
  715:                     @extra_data).
  716:                     '</td></tr>'.$/;
  717:             $analysis_html.=
  718:                 '<tr>'.
  719:                 '<td>'.$concept_plot.'</td>'.
  720:                 '<td>'.$choice_plot.'</td>';
  721:             if ($stacked_plot ne '') {
  722:                 $analysis_html .= 
  723:                     '<td>'.$stacked_plot.'</td>'.
  724:                     '<td>'.&build_foil_key($foils,$count_by_foil).'</td>';
  725:             } else {
  726:                 $analysis_html .= ('<td></td>'x2);
  727:             }
  728:             $analysis_html.='</tr>'.$/;
  729:             if (defined($post_graph_text)) {
  730:                 $analysis_html.= '<tr><td colspan="4" align="center">'.
  731:                     $post_graph_text.'</td></tr>'.$/;
  732:             }
  733:         } elsif ($no_data_text ne '') {
  734:             $analysis_html.='<tr><td colspan="4" align="center">'.
  735:                 &mt($no_data_text,
  736:                     $plot_num,$foil_choice_data->{'_count'},
  737:                     $correct,                    
  738:                     $foil_choice_data->{'_count'}-$correct,
  739:                     @extra_data);
  740:             if (defined($post_graph_text)) {
  741:                 $analysis_html.='<br />'.$post_graph_text;
  742:             }
  743:             $analysis_html.='</td></tr>'.$/;
  744:         }
  745:     } # end of loop for plots
  746:     $analysis_html.='</table>';
  747:     $r->print($analysis_html);
  748: }
  749: 
  750: sub ensure_start_end_times {
  751:     my ($start,$end,$first,$last,$plot_num) = @_;
  752:     if (! defined($start) || ! defined($end)) {
  753:         my $sec_in_day = 86400;
  754:         my ($sday,$smon,$syear) = 
  755:             (localtime($last - $sec_in_day*($plot_num-1)))[3..5];
  756:         $start = &Time::Local::timelocal(0,0,0,$sday,$smon,$syear);
  757:         $end   = $start + $sec_in_day;
  758:         if ($plot_num == $ENV{'form.NumPlots'}) {
  759:             $start = $first;
  760:         }
  761:     }
  762:     return ($start,$end);
  763: }
  764: 
  765: sub RR_concept_plot {
  766:     my ($concepts,$foil_data,$title) = @_;
  767:     #
  768:     my %correct_by_concept;
  769:     my %incorrect_by_concept;
  770:     my %true;
  771:     foreach my $concept (@$concepts) {
  772:         foreach my $foil (@{$concept->{'foils'}}) {
  773:             next if (! exists($foil_data->{$foil}));
  774:             foreach my $choice (keys(%{$foil_data->{$foil}})) {
  775:                 if ($choice eq $foil) {
  776:                     $correct_by_concept{$concept->{'name'}} +=
  777:                         $foil_data->{$foil}->{$choice};
  778:                 } else {
  779:                     $incorrect_by_concept{$concept->{'name'}} +=
  780:                         $foil_data->{$foil}->{$choice};
  781:                     
  782:                 }
  783:             }
  784:         }
  785:     }
  786:     # 
  787:     # need arrays for incorrect and correct because we want to use different
  788:     # colors for them
  789:     my @correct;
  790:     #
  791:     my $total =0;
  792:     for (my $i=0;$i<scalar(@$concepts);$i++) {
  793:         my $concept = $concepts->[$i];
  794:         $correct[$i]   =   $correct_by_concept{$concept->{'name'}};
  795:         $total += $correct_by_concept{$concept->{'name'}}+
  796:             $incorrect_by_concept{$concept->{'name'}};
  797:     }
  798:     if ($total == 0) { return ''; };
  799:     for (my $i=0;$i<=$#correct;$i++) { 
  800:         $correct[$i] = sprintf('%0f',$correct[$i]/$total*100);
  801:     }
  802:     my $xlabel = 'concept';
  803:     my $plot=  &Apache::loncommon::DrawBarGraph($title,
  804:                                                 $xlabel,
  805:                                                 'Percent Choosing',
  806:                                                 100,
  807:                                                 ['#33ff00','#ff3300'],
  808:                                                 undef,
  809:                                                 \@correct);
  810:     return $plot;
  811: }
  812: 
  813: sub RR_create_percent_selected_plot {
  814:     my ($concepts,$foils,$foil_data,$title) = @_;
  815:     #
  816:     if ($foil_data->{'_count'} == 0) { return ''; };
  817:     my %correct_selections;
  818:     my %incorrect_selections;
  819:     foreach my $foil (@$foils) {
  820:         # foil_data has format $foil_data->{true_foil}->{selected foil}=count
  821:         next if (! exists($foil_data->{$foil}));
  822:         while (my ($f,$count)= each(%{$foil_data->{$foil}})) {
  823:             if ($f eq $foil) {
  824:                 $correct_selections{$foil} += $count;
  825:             } else {
  826:                 $incorrect_selections{$f} += $count;
  827:             }
  828:         }
  829:     }
  830:     # 
  831:     # need arrays for incorrect and correct because we want to use different
  832:     # colors for them
  833:     my @correct;
  834:     my @incorrect;
  835:     #
  836:     my $total = $foil_data->{'_count'};
  837:     for (my $i=0;$i<scalar(@$foils);$i++) {
  838:         my $foil = $foils->[$i];
  839:         $correct[$i]   = $correct_selections{$foil};
  840:         $incorrect[$i] = $incorrect_selections{$foil};
  841:     }
  842:     for (my $i=0;$i<=$#correct;$i++) { 
  843:         $correct[$i] = sprintf('%2f',$correct[$i]/$total*100);
  844:     }
  845:     for (my $i=0;$i<=$#incorrect;$i++) {
  846:         $incorrect[$i] = sprintf('%2f',$incorrect[$i]/$total*100);
  847:     }
  848:     #
  849:     # Put a blank in the data sets between concepts, if there are concepts
  850:     my @labels;
  851:     if (defined($concepts) && scalar(@$concepts) > 1) {
  852:         my @new_correct;
  853:         my @new_incorrect;
  854:         my $foil_count = 0;
  855:         foreach my $concept (@$concepts) {
  856:             foreach (@{$concept->{'foils'}}) {
  857:                 push(@new_correct,  $correct[$foil_count]);
  858:                 push(@new_incorrect,$incorrect[$foil_count]);
  859:                 push(@labels,++$foil_count);
  860:             }
  861:             push(@new_correct,'');
  862:             push(@new_incorrect,'');
  863:             push(@labels,'');
  864:         }
  865:         @correct = @new_correct;
  866:         @incorrect = @new_incorrect;
  867:     } else {
  868:         @labels = (1 .. scalar(@correct));
  869:     }
  870:     #
  871:     my $xlabel = 'foil chosen';
  872:     my $plot=  &Apache::loncommon::DrawBarGraph($title,
  873:                                                 $xlabel,
  874:                                                 'Percent Choosing',
  875:                                                 100,
  876:                                                 ['#33ff00','#ff3300'],
  877:                                                 \@labels,
  878:                                                 \@correct,
  879:                                                 \@incorrect);
  880:     return $plot;
  881: }
  882: 
  883: sub RR_create_stacked_selection_plot {
  884:     my ($foils,$foil_data,$title,$true_foils)=@_;
  885:     #
  886:     my @dataset; # array of array refs - multicolor rows $datasets[row]->[col]
  887:     my @labels;
  888:     my $count;
  889:     my %column; # maps foil name to column in @datasets
  890:     for (my $i=0;$i<scalar(@$foils);$i++) {
  891:         my $foil = $foils->[$i];
  892:         if (defined($true_foils) && scalar(keys(%$true_foils)) > 0 ) {
  893:             next if (! $true_foils->{$foil} );
  894:             push(@labels,$i+1);
  895:         } else {
  896:             next if (! exists($foil_data->{$foil}));
  897:             push(@labels,$i+1);
  898:         }
  899:         next if (! exists($foil_data->{$foils->[$i]}));
  900:         $column{$foil}= $count++;
  901:         for (my $j=0;$j<scalar(@$foils);$j++) {
  902:             my $value = 0;
  903:             if ($i != $j ) {
  904:                 $value += $foil_data->{$foil}->{$foils->[$j]};
  905:             }
  906:             $dataset[$j]->[$column{$foil}]=$value;
  907:         }
  908:     }
  909:     #
  910:     return '' if (! scalar(keys(%column)));
  911:     #
  912:     my $grand_total = 0;
  913:     my %count_per_foil;
  914:     while (my ($foil,$bar) = each (%column)) {
  915:         my $bar_total = 0;
  916:         for (my $j=0;$j<scalar(@dataset);$j++) {
  917:             $bar_total += $dataset[$j]->[$bar];
  918:         }
  919:         next if ($bar_total == 0);
  920:         for (my $j=0;$j<scalar(@dataset);$j++) {
  921:             $dataset[$j]->[$bar] = 
  922:                 sprintf('%2f',$dataset[$j]->[$bar]/$bar_total * 100);
  923:         }
  924:         $count_per_foil{$foil}=' ( '.$bar_total.' )';
  925:         $grand_total += $bar_total;
  926:     }
  927:     if ($grand_total == 0) {
  928:         return ('',undef);
  929:     }
  930:     my @empty_row = ();
  931:     foreach (@{$dataset[0]}) {
  932:         push(@empty_row,0);
  933:     }
  934:     #
  935:     my $graph = &Apache::loncommon::DrawBarGraph
  936:         ($title,'Correct Foil','foils chosen Incorrectly',
  937:          100,$plotcolors,\@labels,\@empty_row,@dataset);
  938:     return ($graph,\%count_per_foil);
  939: }
  940: 
  941: 
  942: #########################################################
  943: #########################################################
  944: ##
  945: ##       Misc routines
  946: ##
  947: #########################################################
  948: #########################################################
  949: 
  950: # if $correct is a hash ref, it is assumed to be indexed by student names.
  951: #    the values are assumed to be hash refs with a key of 'answer'.
  952: sub classify_response_data {
  953:     my ($full_row_data,$correct,$function) = @_;
  954:     my %submission_data;
  955:     my %students;
  956:     my $max=0;
  957:     foreach my $row (@$full_row_data) {
  958:         my %subm = &hashify_attempt($row);
  959:         if (ref($correct) eq 'HASH') {
  960:             $subm{'correct'} = $correct->{$subm{'student'}};
  961:         } else {
  962:             $subm{'correct'} = $correct;
  963:         }
  964:         $subm{'submission'} =~ s/=\d+\s*$//;
  965:         if (&$function(\%subm)) {
  966:             $students{$subm{'student'}}++;
  967:             $submission_data{'_count'}++;
  968:             
  969:             if (&submission_is_correct($subm{'award'})) { 
  970:                 $submission_data{'_correct'}++;
  971:             }
  972:             
  973:             if($max<++$submission_data{$subm{'correct'}}->{$subm{'submission'}}) {
  974:                 $max=$submission_data{$subm{'correct'}}->{$subm{'submission'}};
  975:             }
  976:         }
  977:     }
  978:     $submission_data{'_max'} = $max;
  979:     $submission_data{'_students'}=scalar(keys(%students));
  980:     return \%submission_data;
  981: }
  982: 
  983: 
  984: #########################################################
  985: #########################################################
  986: ##
  987: ##      Option Response Routines
  988: ##
  989: #########################################################
  990: #########################################################
  991: sub OptionResponseAnalysis {
  992:     my ($r,$problem,$problem_data,$Students) = @_;
  993:     my ($resource,$respid) = ($problem->{'resource'},
  994:                               $problem->{'respid'});
  995:     # Note: part data is not needed.
  996:     my $PerformanceData = &Apache::loncoursedata::get_response_data
  997:         (\@Apache::lonstatistics::SelectedSections,
  998:          $Apache::lonstatistics::enrollment_status,
  999:          $resource->{'symb'},$respid);
 1000:     if (! defined($PerformanceData) || 
 1001:         ref($PerformanceData) ne 'ARRAY' ) {
 1002:         $r->print('<h2>'.
 1003:                   &mt('There is no student data for this problem.').
 1004:                   '</h2>');
 1005:     }  else {
 1006:         $r->rflush();
 1007:         if (exists($ENV{'form.ExcelOutput'})) {
 1008:             my $result = &OR_excel_sheet($r,$resource,
 1009:                                          $PerformanceData,
 1010:                                          $problem_data);
 1011:             $r->print($result);
 1012:             $r->rflush();
 1013:         } else {
 1014:             if ($ENV{'form.AnalyzeOver'} eq 'tries') {
 1015:                 my $analysis_html = &OR_tries_analysis($r,
 1016:                                                     $PerformanceData,
 1017:                                                     $problem_data);
 1018:                 $r->print($analysis_html);
 1019:                 $r->rflush();
 1020:             } elsif ($ENV{'form.AnalyzeOver'} eq 'time') {
 1021:                 my $analysis_html = &OR_time_analysis($PerformanceData,
 1022:                                                    $problem_data);
 1023:                 $r->print($analysis_html);
 1024:                 $r->rflush();
 1025:             } else {
 1026:                 $r->print('<h2>'.
 1027:                           &mt('The analysis you have selected is '.
 1028:                               'not supported at this time').
 1029:                           '</h2>');
 1030:             }
 1031:         }
 1032:     }
 1033: }
 1034: 
 1035: #########################################################
 1036: #
 1037: #       Option Response:  tries Analysis
 1038: #
 1039: #########################################################
 1040: sub OR_tries_analysis {
 1041:     my ($r,$PerformanceData,$ORdata) = @_;
 1042:     my $mintries = 1;
 1043:     my $maxtries = $ENV{'form.NumPlots'};
 1044:     my ($table,$Foils,$Concepts) = &build_foil_index($ORdata);
 1045:     my %response_data = &OR_analyze_by_tries($r,$PerformanceData,
 1046:                                                      $mintries,$maxtries);
 1047:     my $analysis = '';
 1048:     #
 1049:     # Compute the data necessary to make the plots
 1050:     my @foil_plot; 
 1051:     my @concept_data;
 1052:     for (my $j=0;$j<=scalar(@$Concepts);$j++) {
 1053:         my $concept = $Concepts->[$j];
 1054:         foreach my $foilid (@{$concept->{'foils'}}) {
 1055:             for (my $try=$mintries;$try<=$maxtries;$try++) {
 1056:                 # concept analysis data
 1057:                 $concept_data[$j]->[$try]->{'_correct'} +=
 1058:                     $response_data{$foilid}->[$try]->{'_correct'};
 1059:                 $concept_data[$j]->[$try]->{'_total'} +=
 1060:                     $response_data{$foilid}->[$try]->{'_total'};
 1061:                 #
 1062:                 # foil analysis data
 1063:                 if ($response_data{$foilid}->[$try]->{'_total'} == 0) {
 1064:                     push(@{$foil_plot[$try]->{'_correct'}},0);
 1065:                 } else {
 1066:                     push(@{$foil_plot[$try]->{'_correct'}},
 1067:                          100*$response_data{$foilid}->[$try]->{'_correct'}/
 1068:                          $response_data{$foilid}->[$try]->{'_total'});
 1069:                 }
 1070:                 foreach my $option (@{$ORdata->{'_Options'}}) {
 1071:                     push(@{$foil_plot[$try]->{'_total'}},
 1072:                          $response_data{$foilid}->[$try]->{'_total'});
 1073:                     if ($response_data{$foilid}->[$try]->{'_total'} == 0) {
 1074:                         push (@{$foil_plot[$try]->{$option}},0);
 1075:                     } else {
 1076:                         if ($response_data{$foilid}->[$try]->{'_total'} ==
 1077:                             $response_data{$foilid}->[$try]->{'_correct'}) {
 1078:                             push(@{$foil_plot[$try]->{$option}},0);
 1079:                         } else {
 1080:                             push (@{$foil_plot[$try]->{$option}},
 1081:                                   100 * 
 1082:                                   $response_data{$foilid}->[$try]->{$option} / 
 1083:                                   ($response_data{$foilid}->[$try]->{'_total'} 
 1084:                                    - 
 1085:                                    $response_data{$foilid}->[$try]->{'_correct'}
 1086:                                    ));
 1087:                         }
 1088:                     }
 1089:                 } # End of foreach my $option
 1090:             }
 1091:         } # End of foreach my $foilid
 1092:     } # End of concept loops
 1093:     # 
 1094:     # Build a table for the plots
 1095:     my $analysis_html = "<br /><table>\n";
 1096:     my $optionkey = &build_option_index($ORdata);
 1097:     my $num_concepts = 1;
 1098:     if (defined($Concepts)) { $num_concepts = scalar(@$Concepts); }
 1099:     #
 1100:     for (my $try=$mintries;$try<=$maxtries;$try++) {
 1101:         if (! defined($response_data{'_total'}->[$try]) ||
 1102:             $response_data{'_total'}->[$try] == 0) { 
 1103:             if ($try > 1) {
 1104:                 $analysis_html.= '<tr><td align="center" colspan="4"><b>'.
 1105:                     &mt('None of the selected students attempted the problem more than [_1] times.',$try-1).
 1106:                     '</b></td></tr>';
 1107:             } else {
 1108:                 $analysis_html.= '<tr><td colspan="4" align="center"><b>'.
 1109:                     &mt('None of the selected students have attempted the problem').'</b></td></tr>';
 1110:             }
 1111:             last;
 1112:         }
 1113:         my $concept_graph='';
 1114:         if ($num_concepts > 1) {
 1115:             #
 1116:             # Create concept plot
 1117:             my @concept_plot_data;
 1118:             for (my $j=0;$j<=$#concept_data;$j++) {
 1119:                 my $total = $concept_data[$j]->[$try]->{'_total'};
 1120:                 if ($total == 0) {
 1121:                     $concept_plot_data[$j] = 0;
 1122:                 } else {
 1123:                     $concept_plot_data[$j] = 100 * 
 1124:                         sprintf('%0.3f',
 1125:                                 $concept_data[$j]->[$try]->{'_correct'} / 
 1126:                                 $total);
 1127:                 }
 1128:             }
 1129:             #
 1130:             $concept_graph = &Apache::loncommon::DrawBarGraph
 1131:                 ('Correct Concepts','Concept Number','Percent Correct',
 1132:                  100,$plotcolors,undef,\@concept_plot_data);
 1133:         }
 1134:         #
 1135:         # Create Foil Plots
 1136:         my $data_count = $response_data{'_total'}->[$try];
 1137:         my $correct = $response_data{'_correct'}->[$try];
 1138:         my @Datasets;
 1139:         foreach my $option ('_correct',@{$ORdata->{'_Options'}}) {
 1140:             next if (! exists($foil_plot[$try]->{$option}));
 1141:             push(@Datasets,$foil_plot[$try]->{$option});
 1142:         }
 1143:         #
 1144:         # Put a blank in the data set between concepts
 1145:         for (my $set =0;$set<=$#Datasets;$set++) {
 1146:             my @Data = @{$Datasets[$set]};
 1147:             my $idx = 0;
 1148:             foreach my $concept (@{$Concepts}) {
 1149:                 foreach my $foilid (@{$concept->{'foils'}}) {
 1150:                     $Datasets[$set]->[$idx++]=shift(@Data);
 1151:                 }
 1152:                 if ($concept->{'name'} ne $Concepts->[-1]->{'name'}) {
 1153:                     $Datasets[$set]->[$idx++] = 0;
 1154:                 }
 1155:             }
 1156:         }
 1157:         #
 1158:         # Set up the labels needed for the bar graph
 1159:         my @Labels;
 1160:         my $idx = 1;
 1161:         foreach my $concept (@{$Concepts}) {
 1162:             foreach my $foilid (@{$concept->{'foils'}}) {
 1163:                 push(@Labels,$idx++);
 1164:             }
 1165:             push(@Labels,'');
 1166:         }
 1167:         #
 1168:         my $correct_graph = &Apache::loncommon::DrawBarGraph
 1169:             ('Correct Statements','Statement','% Answered Correct',
 1170:              100,$plotcolors,\@Labels,$Datasets[0]);
 1171:         
 1172:         #
 1173:         #
 1174:         next if (! defined($Datasets[0]));
 1175:         for (my $i=0; $i< scalar(@{$Datasets[0]});$i++) {
 1176:             $Datasets[0]->[$i]=0;
 1177:         }
 1178:         my $count = $response_data{'_total'}->[$try] - 
 1179:                                            $response_data{'_correct'}->[$try];
 1180:         my $incorrect_graph = &Apache::loncommon::DrawBarGraph
 1181:             ('Incorrect Statements','Statement','% Chosen Incorrectly',
 1182:              100,$plotcolors,\@Labels,@Datasets);
 1183:         $analysis_html.= 
 1184:             '<tr><td colspan="4" align="center">'.
 1185:             '<font size="+1">'.
 1186:             &mt('Attempt [_1], [_2] submissions, [_3] correct, [_4] incorrect',
 1187:                 $try,$data_count,$correct,$data_count-$correct).
 1188:             '</font>'.'</td></tr>'.$/.                
 1189:             '<tr>'.
 1190:             '<td>'.$concept_graph.'</td>'.
 1191:             '<td>'.$correct_graph.'</td>'.
 1192:             '<td>'.$incorrect_graph.'</td>'.
 1193:             '<td>'.$optionkey.'<td>'.
 1194:             '</tr>'.$/;
 1195:     }
 1196:     $analysis_html .= "</table>\n";
 1197:     $table .= $analysis_html;
 1198:     return $table;
 1199: }
 1200: 
 1201: sub OR_analyze_by_tries {
 1202:     my ($r,$PerformanceData,$mintries,$maxtries) = @_;
 1203:     my %Trydata;
 1204:     $mintries = 1         if (! defined($mintries) || $mintries < 1);
 1205:     $maxtries = $mintries if (! defined($maxtries) || $maxtries < $mintries);
 1206:     my @students;
 1207:     foreach my $row (@$PerformanceData) {
 1208:         next if (! defined($row));
 1209:         my $tries = &get_tries_from_row($row);
 1210:         my %Row   = &Process_OR_Row($row);
 1211:         next if (! %Row);
 1212:         my $student_id = $row->[&Apache::loncoursedata::RD_student_id()];
 1213:         $students[$tries]->{$student_id}++;
 1214:         while (my ($foilid,$href) = each(%Row)) {
 1215:             if (! ref($href)) { 
 1216:                 $Trydata{$foilid}->[$tries] += $href;
 1217:                 next;
 1218:             }
 1219:             while (my ($option,$value) = each(%$href)) {
 1220:                 $Trydata{$foilid}->[$tries]->{$option}+=$value;
 1221:             }
 1222:         }
 1223:     }
 1224:     for (my $try=$mintries;$try<=$maxtries;$try++) {
 1225:         $Trydata{'_studentcount'}->[$try] = scalar(keys(%{$students[$try]}));
 1226:     }
 1227:     return %Trydata;
 1228: }
 1229: 
 1230: #########################################################
 1231: #
 1232: #     Option Response: Time Analysis
 1233: #
 1234: #########################################################
 1235: sub OR_time_analysis {
 1236:     my ($performance_data,$ORdata) = @_;
 1237:     my ($table,$Foils,$Concepts) = &build_foil_index($ORdata);
 1238:     my $foilkey = &build_option_index($ORdata);
 1239:     my $num_concepts = 1;
 1240:     if (defined($Concepts)) { $num_concepts = scalar(@$Concepts); }
 1241:     #
 1242:     if ($num_concepts < 2) {
 1243:         $table = '<h3>'.
 1244:             &mt('Not enough data for concept analysis.  '.
 1245:                 'Performing Foil Analysis').
 1246:                 '</h3>'.$table;
 1247:     }
 1248:     #
 1249:     my $num_plots = $ENV{'form.NumPlots'};
 1250:     my $num_data = scalar(@$performance_data)-1;
 1251:     #
 1252:     my $current_index;
 1253:     $table .= "<table>\n";
 1254:     for (my $i=0;$i<$num_plots;$i++) {
 1255:         ##
 1256:         my $starttime = &Apache::lonhtmlcommon::get_date_from_form
 1257:             ('startdate_'.$i);
 1258:         my $endtime = &Apache::lonhtmlcommon::get_date_from_form
 1259:             ('enddate_'.$i);
 1260:         if (! defined($starttime) || ! defined($endtime)) {
 1261:             my $sec_in_day = 86400;
 1262:             my $last_sub_time = &get_time_from_row($performance_data->[-1]);
 1263:             my ($sday,$smon,$syear) = 
 1264:                 (localtime($last_sub_time - $sec_in_day*$i))[3..5];
 1265:             $starttime = &Time::Local::timelocal(0,0,0,$sday,$smon,$syear);
 1266:             $endtime = $starttime + $sec_in_day;
 1267:             if ($i == ($num_plots -1 )) {
 1268:                 $starttime = &get_time_from_row($performance_data->[0]);
 1269:             }
 1270:         }
 1271:         $table .= '<tr><td colspan="4" align="center"><font size="+1">'.
 1272:             &mt('Data from [_1] to [_2]',
 1273:                 &Apache::lonlocal::locallocaltime($starttime),
 1274:                 &Apache::lonlocal::locallocaltime($endtime)).
 1275:                 '</font></td></tr>'.$/;
 1276:         my $startdateform = &Apache::lonhtmlcommon::date_setter
 1277:             ('Statistics','startdate_'.$i,$starttime);
 1278:         my $enddateform = &Apache::lonhtmlcommon::date_setter
 1279:             ('Statistics','enddate_'.$i,$endtime);
 1280:         #
 1281:         my $begin_index;
 1282:         my $end_index;
 1283:         my $j;
 1284:         while (++$j < scalar(@$performance_data)) {
 1285:             last if (&get_time_from_row($performance_data->[$j]) 
 1286:                                                               > $starttime);
 1287:         }
 1288:         $begin_index = $j;
 1289:         while ($j < scalar(@$performance_data)) {
 1290:             if (&get_time_from_row($performance_data->[$j]) > $endtime) {
 1291:                 last;
 1292:             } else {
 1293:                 $j++;
 1294:             }
 1295:         }
 1296:         $end_index = $j;
 1297:         ##
 1298:         my ($processed_time_data,$correct,$data_count,$student_count) =
 1299:             &OR_time_process_data($performance_data,$begin_index,$end_index);
 1300:         ##
 1301:         $table .= '<tr><td colspan="4" align="center"><font size="+1">'.
 1302:             &mt('[_1] submissions from [_2] students, [_3] correct, [_4] incorrect',
 1303:                 $data_count,$student_count,$correct,$data_count-$correct).
 1304:                 '</font></td></tr>'.$/;
 1305:         my $concept_correct_plot = '';
 1306:         if ($num_concepts > 1) {
 1307:             $concept_correct_plot = 
 1308:                 &OR_Concept_Time_Analysis($processed_time_data,
 1309:                                           $correct,$data_count,$student_count,
 1310:                                           $ORdata,$Concepts);
 1311:         }
 1312:         my ($foil_correct_plot,$foil_incorrect_plot) = 
 1313:             &OR_Foil_Time_Analysis($processed_time_data,
 1314:                                    $correct,$data_count,$student_count,
 1315:                                    $ORdata,$Foils,$Concepts);
 1316:         $table .= '<tr>'.
 1317:             '<td>'.$concept_correct_plot.'</td>'.
 1318:             '<td>'.$foil_correct_plot.'</td>'.
 1319:             '<td>'.$foil_incorrect_plot.'</td>'.
 1320:             '<td align="left" valign="top">'.$foilkey.'</td></tr>'.$/;
 1321:         $table .= '<tr><td colspan="4" align="center">'.
 1322:             &mt('Start time: [_1]',$startdateform).'<br />'.
 1323:             &mt('End time: [_1]',$enddateform).'</td></tr>'.$/;
 1324:         $table.= '<tr><td colspan="4">&nbsp</td></tr>'.$/;
 1325:     }
 1326:     $table .= '</table>';
 1327:     #
 1328:     return $table;
 1329: }
 1330: 
 1331: sub OR_Foil_Time_Analysis {
 1332:     my ($processed_time_data,$correct,$data_count,$student_count,
 1333:         $ORdata,$Foils,$Concepts) = @_;
 1334:     if ($data_count <= 0) {
 1335:         return ('<h2>'.&mt('There is no data to plot').'</h2>','');
 1336:     }
 1337:     my $analysis_html;
 1338:     my @plotdata;
 1339:     my @labels;
 1340:     foreach my $concept (@{$Concepts}) {
 1341:         foreach my $foil (@{$concept->{'foils'}}) {
 1342:             push(@labels,scalar(@labels)+1);
 1343:             my $total = $processed_time_data->{$foil}->{'_total'};
 1344:             if ($total == 0) {
 1345:                 push(@{$plotdata[0]},0);
 1346:             } else {
 1347:                 push(@{$plotdata[0]},
 1348:                      100 * $processed_time_data->{$foil}->{'_correct'} / $total);
 1349:             }
 1350:             my $total_incorrect = $total - $processed_time_data->{$foil}->{'_correct'};
 1351:             for (my $i=0;$i<scalar(@{$ORdata->{'_Options'}});$i++) {
 1352:                 my $option = $ORdata->{'_Options'}->[$i];
 1353:                 if ($total_incorrect == 0) {
 1354:                     push(@{$plotdata[$i+1]},0);
 1355:                 } else {
 1356:                     push(@{$plotdata[$i+1]},
 1357:                          100 * $processed_time_data->{$foil}->{$option} / $total_incorrect);
 1358:                 }
 1359:             }
 1360:         }
 1361:         # Put in a blank one
 1362:         push(@labels,'');
 1363:         push(@{$plotdata[0]},0);
 1364:         for (my $i=0;$i<scalar(@{$ORdata->{'_Options'}});$i++) {
 1365:             push(@{$plotdata[$i+1]},0);
 1366:         }
 1367:     }
 1368:     #
 1369:     # Create the plot
 1370:     my $correct_plot = &Apache::loncommon::DrawBarGraph('Correct Statements',
 1371:                                                         'Statement Number',
 1372:                                                         'Percent Correct',
 1373:                                                         100,
 1374:                                                         $plotcolors,
 1375:                                                         undef,
 1376:                                                         $plotdata[0]);
 1377:     for (my $j=0; $j< scalar(@{$plotdata[0]});$j++) {
 1378:         $plotdata[0]->[$j]=0;
 1379:     }
 1380:     my $incorrect_plot = 
 1381:         &Apache::loncommon::DrawBarGraph('Incorrect Statements',
 1382:                                          'Statement Number',
 1383:                                          'Incorrect Option Choice',
 1384:                                          100,
 1385:                                          $plotcolors,
 1386:                                          undef,
 1387:                                          @plotdata);
 1388:     return ($correct_plot,$incorrect_plot);
 1389: }
 1390: 
 1391: sub OR_Concept_Time_Analysis {
 1392:     my ($processed_time_data,$correct,$data_count,$student_count,
 1393:         $ORdata,$Concepts) = @_;
 1394:     return '' if ($data_count == 0);
 1395:     #
 1396:     # Put the data in plottable form
 1397:     my @plotdata;
 1398:     foreach my $concept (@$Concepts) {
 1399:         my ($total,$correct);
 1400:         foreach my $foil (@{$concept->{'foils'}}) {
 1401:             $total += $processed_time_data->{$foil}->{'_total'};
 1402:             $correct += $processed_time_data->{$foil}->{'_correct'};
 1403:         }
 1404:         if ($total == 0) {
 1405:             push(@plotdata,0);
 1406:         } else {
 1407:             push(@plotdata,100 * $correct / $total);
 1408:         }
 1409:     }
 1410:     #
 1411:     # Create the plot
 1412:     return &Apache::loncommon::DrawBarGraph('Correct Concepts',
 1413:                                             'Concept Number',
 1414:                                             'Percent Correct',
 1415:                                             100,
 1416:                                             $plotcolors,
 1417:                                             undef,
 1418:                                             \@plotdata);
 1419: }
 1420: 
 1421: sub OR_time_process_data {
 1422:     my ($performance_data,$begin_index,$end_index)=@_;
 1423:     my %processed_time_data;
 1424:     my %distinct_students;
 1425:     my ($correct,$data_count);
 1426:     if (($begin_index == $end_index) && 
 1427:         ($end_index != scalar(@$performance_data)-1)) { 
 1428:         return undef;
 1429:     }
 1430:     # Be sure we include the last one if we are asked for it.
 1431:     # That we have to correct here (and not when $end_index is 
 1432:     # given a value) should probably be considered a bug.
 1433:     if ($end_index == scalar(@$performance_data)-1) {
 1434:         $end_index++;
 1435:     }
 1436:     my $count;
 1437:     for (my $i=$begin_index;$i<$end_index;$i++) {
 1438:         my $attempt = $performance_data->[$i];
 1439:         $count++;
 1440:         next if (! defined($attempt));
 1441:         my %attempt = &Process_OR_Row($attempt);
 1442:         $data_count++;
 1443:         $correct += $attempt{'_correct'};
 1444:         $distinct_students{$attempt->[&Apache::loncoursedata::RD_student_id()]}++;
 1445:         while (my ($foilid,$href) = each(%attempt)) {
 1446:             if (! ref($href)) {
 1447:                 $processed_time_data{$foilid} += $href;
 1448:                 next;
 1449:             }
 1450:             while (my ($option,$value) = each(%$href)) {
 1451:                 $processed_time_data{$foilid}->{$option}+=$value;
 1452:             }
 1453:         }
 1454:     }
 1455:     return (\%processed_time_data,$correct,$data_count,
 1456:             scalar(keys(%distinct_students)));
 1457: }
 1458: 
 1459: #########################################################
 1460: #########################################################
 1461: ##
 1462: ##             Excel output 
 1463: ##
 1464: #########################################################
 1465: #########################################################
 1466: sub OR_excel_sheet {
 1467:     my ($r,$resource,$performance_data,$ORdata) = @_;
 1468:     my $response = '';
 1469:     my (undef,$Foils,$Concepts) = &build_foil_index($ORdata);
 1470:     #
 1471:     # Create excel worksheet
 1472:     my $filename = '/prtspool/'.
 1473:         $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
 1474:         time.'_'.rand(1000000000).'.xls';
 1475:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1476:     if (! defined($workbook)) {
 1477:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1478:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1479:                             "This error has been logged.  ".
 1480:                             "Please alert your LON-CAPA administrator").
 1481:                   '</p>');
 1482:         return undef;
 1483:     }
 1484:     #
 1485:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1486:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1487:     #
 1488:     # Create and populate main worksheets
 1489:     my $problem_data_sheet  = $workbook->addworksheet('Problem Data');
 1490:     my $student_data_sheet = &build_student_data_worksheet($workbook,$format);
 1491:     my $response_data_sheet = $workbook->addworksheet('Response Data');
 1492:     foreach my $sheet ($problem_data_sheet,$student_data_sheet,
 1493:                        $response_data_sheet) {
 1494:         $sheet->write(0,0,$resource->{'title'},$format->{'h2'});
 1495:         $sheet->write(1,0,$resource->{'src'},$format->{'h3'});
 1496:     }
 1497:     #
 1498:     my $result;
 1499:     $result = &OR_build_problem_data_worksheet($problem_data_sheet,$format,
 1500:                                             $Concepts,$ORdata);
 1501:     if ($result ne 'okay') {
 1502:         # Do something useful
 1503:     }
 1504:     $result = &OR_build_response_data_worksheet($response_data_sheet,$format,
 1505:                                              $performance_data,$Foils,
 1506:                                              $ORdata);
 1507:     if ($result ne 'okay') {
 1508:         # Do something useful
 1509:     }
 1510:     $response_data_sheet->activate();
 1511:     #
 1512:     # Close the excel file
 1513:     $workbook->close();
 1514:     #
 1515:     # Write a link to allow them to download it
 1516:     $result .= '<h2>'.&mt('Excel Raw Data Output').'</h2>'.
 1517:               '<p><a href="'.$filename.'">'.
 1518:               &mt('Your Excel spreadsheet.').
 1519:               '</a></p>'."\n";
 1520:     return $result;
 1521: }
 1522: 
 1523: sub OR_build_problem_data_worksheet {
 1524:     my ($worksheet,$format,$Concepts,$ORdata) = @_;
 1525:     my $rows_output = 3;
 1526:     my $cols_output = 0;
 1527:     $worksheet->write($rows_output++,0,'Problem Structure',$format->{'h3'});
 1528:     ##
 1529:     ##
 1530:     my @Headers;
 1531:     if (@$Concepts > 1) {
 1532:         @Headers = ("Concept\nNumber",'Concept',"Foil\nNumber",
 1533:                     'Foil Name','Foil Text','Correct value');
 1534:     } else {
 1535:         @Headers = ('Foil Number','FoilName','Foil Text','Correct value');
 1536:     }
 1537:     $worksheet->write_row($rows_output++,0,\@Headers,$format->{'header'});
 1538:     my %Foildata = %{$ORdata->{'_Foils'}};
 1539:     my $conceptindex = 1;
 1540:     my $foilindex = 1;
 1541:     foreach my $concept (@$Concepts) {
 1542:         my @FoilsInConcept = @{$concept->{'foils'}};
 1543:         my $firstfoil = shift(@FoilsInConcept);
 1544:         if (@$Concepts > 1) {
 1545:             $worksheet->write_row($rows_output++,0,
 1546:                                   [$conceptindex,
 1547:                                    $concept->{'name'},
 1548:                                    $foilindex++,
 1549:                                    $Foildata{$firstfoil}->{'name'},
 1550:                                    $Foildata{$firstfoil}->{'text'},
 1551:                                    $Foildata{$firstfoil}->{'value'},]);
 1552:         } else {
 1553:             $worksheet->write_row($rows_output++,0,
 1554:                                   [ $foilindex++,
 1555:                                     $Foildata{$firstfoil}->{'name'},
 1556:                                     $Foildata{$firstfoil}->{'text'},
 1557:                                     $Foildata{$firstfoil}->{'value'},]);
 1558:         }
 1559:         foreach my $foilid (@FoilsInConcept) {
 1560:             if (@$Concepts > 1) {
 1561:                 $worksheet->write_row($rows_output++,0,
 1562:                                       ['',
 1563:                                        '',
 1564:                                        $foilindex,
 1565:                                        $Foildata{$foilid}->{'name'},
 1566:                                        $Foildata{$foilid}->{'text'},
 1567:                                        $Foildata{$foilid}->{'value'},]);
 1568:             } else {
 1569:                 $worksheet->write_row($rows_output++,0,                
 1570:                                       [$foilindex,
 1571:                                        $Foildata{$foilid}->{'name'},
 1572:                                        $Foildata{$foilid}->{'text'},
 1573:                                        $Foildata{$foilid}->{'value'},]);
 1574:             }                
 1575:         } continue {
 1576:             $foilindex++;
 1577:         }
 1578:     } continue {
 1579:         $conceptindex++;
 1580:     }
 1581:     $rows_output++;
 1582:     $rows_output++;
 1583:     ##
 1584:     ## Option data output
 1585:     $worksheet->write($rows_output++,0,'Options',$format->{'header'});
 1586:     foreach my $string (@{$ORdata->{'_Options'}}) {
 1587:         $worksheet->write($rows_output++,0,$string);
 1588:     }
 1589:     return 'okay';
 1590: }
 1591: 
 1592: sub OR_build_response_data_worksheet {
 1593:     my ($worksheet,$format,$performance_data,$Foils,$ORdata)=@_;
 1594:     my $rows_output = 3;
 1595:     my $cols_output = 0;
 1596:     $worksheet->write($rows_output++,0,'Response Data',$format->{'h3'});
 1597:     $worksheet->set_column(1,1,20);
 1598:     $worksheet->set_column(2,2,13);
 1599:     my @Headers = ('identifier','time','award detail','attempt');
 1600:     foreach my $foil (@$Foils) {
 1601:         push (@Headers,$foil.' submission');
 1602:         push (@Headers,$foil.' grading');
 1603:     }
 1604:     $worksheet->write_row($rows_output++,0,\@Headers,$format->{'header'});
 1605:     #
 1606:     foreach my $row (@$performance_data) {
 1607:         next if (! defined($row));
 1608:         my ($student,$award,$grading,$submission,$time,$tries) = @$row;
 1609:         my @Foilgrades = split('&',$grading);
 1610:         my @Foilsubs   = split('&',$submission);
 1611:         my %response_data;
 1612:         for (my $j=0;$j<=$#Foilgrades;$j++) {
 1613:             my ($foilid,$correct)  = split('=',$Foilgrades[$j]);
 1614:             my (undef,$submission) = split('=',$Foilsubs[$j]);
 1615:             $submission = &Apache::lonnet::unescape($submission);
 1616:             $response_data{$foilid.' submission'}=$submission;
 1617:             $response_data{$foilid.' award'}=$correct;
 1618:         }
 1619:         $worksheet->write($rows_output,$cols_output++,$student);
 1620:         $worksheet->write($rows_output,$cols_output++,
 1621:              &Apache::lonstathelpers::calc_serial($time),$format->{'date'});
 1622:         $worksheet->write($rows_output,$cols_output++,$award);
 1623:         $worksheet->write($rows_output,$cols_output++,$tries);
 1624:         foreach my $foilid (@$Foils) {
 1625:             $worksheet->write($rows_output,$cols_output++,
 1626:                               $response_data{$foilid.' submission'});
 1627:             $worksheet->write($rows_output,$cols_output++,
 1628:                               $response_data{$foilid.' award'});
 1629:         }
 1630:         $rows_output++;
 1631:         $cols_output = 0;
 1632:     }
 1633:     return;
 1634: }
 1635: 
 1636: sub build_foil_index {
 1637:     my ($ORdata) = @_;
 1638:     return if (! exists($ORdata->{'_Foils'}));
 1639:     my %Foildata = %{$ORdata->{'_Foils'}};
 1640:     my @Foils = sort(keys(%Foildata));
 1641:     my %Concepts;
 1642:     foreach my $foilid (@Foils) {
 1643:         push(@{$Concepts{$Foildata{$foilid}->{'_Concept'}}},
 1644:              $foilid);
 1645:     }
 1646:     undef(@Foils);
 1647:     # Having gathered the concept information in a hash, we now translate it
 1648:     # into an array because we need to be consistent about order.
 1649:     # Also put the foils in order, too.
 1650:     my $sortfunction = sub {
 1651:         my %Numbers = (one   => 1,
 1652:                        two   => 2,
 1653:                        three => 3,
 1654:                        four  => 4,
 1655:                        five  => 5,
 1656:                        six   => 6,
 1657:                        seven => 7,
 1658:                        eight => 8,
 1659:                        nine  => 9,
 1660:                        ten   => 10,);
 1661:         my $a1 = lc($a); 
 1662:         my $b1 = lc($b);
 1663:         if (exists($Numbers{$a1})) {
 1664:             $a1 = $Numbers{$a1};
 1665:         }
 1666:         if (exists($Numbers{$b1})) {
 1667:             $b1 = $Numbers{$b1};
 1668:         }
 1669:         if (($a1 =~/^\d+$/) && ($b1 =~/^\d+$/)) {
 1670:             return $a1 <=> $b1;
 1671:         } else {
 1672:             return $a1 cmp $b1;
 1673:         }
 1674:     };
 1675:     my @Concepts;
 1676:     foreach my $concept (sort $sortfunction (keys(%Concepts))) {
 1677:         if (! defined($Concepts{$concept})) {
 1678:             $Concepts{$concept}=[];
 1679: #            next;
 1680:         }
 1681:         push(@Concepts,{ name => $concept,
 1682:                         foils => [@{$Concepts{$concept}}]});
 1683:         push(@Foils,(@{$Concepts{$concept}}));
 1684:     }
 1685:     #
 1686:     # Build up the table of row labels.
 1687:     my $table = '<table border="1" >'."\n";
 1688:     if (@Concepts > 1) {
 1689:         $table .= '<tr>'.
 1690:             '<th>'.&mt('Concept Number').'</th>'.
 1691:             '<th>'.&mt('Concept').'</th>'.
 1692:             '<th>'.&mt('Foil Number').'</th>'.
 1693:             '<th>'.&mt('Foil Name').'</th>'.
 1694:             '<th>'.&mt('Foil Text').'</th>'.
 1695:             '<th>'.&mt('Correct Value').'</th>'.
 1696:             "</tr>\n";
 1697:     } else {
 1698:         $table .= '<tr>'.
 1699:             '<th>'.&mt('Foil Number').'</th>'.
 1700:             '<th>'.&mt('Foil Name').'</th>'.
 1701:             '<th>'.&mt('Foil Text').'</th>'.
 1702:             '<th>'.&mt('Correct Value').'</th>'.
 1703:             "</tr>\n";
 1704:     }        
 1705:     my $conceptindex = 1;
 1706:     my $foilindex = 1;
 1707:     foreach my $concept (@Concepts) {
 1708:         my @FoilsInConcept = @{$concept->{'foils'}};
 1709:         my $firstfoil = shift(@FoilsInConcept);
 1710:         if (@Concepts > 1) {
 1711:             $table .= '<tr>'.
 1712:                 '<td>'.$conceptindex.'</td>'.
 1713:                 '<td>'.&HTML::Entities::encode($concept->{'name'},'<>&"').'</td>'.
 1714:                 '<td>'.$foilindex++.'</td>'.
 1715:                 '<td>'.&HTML::Entities::encode($Foildata{$firstfoil}->{'name'},'<>&"').'</td>'.
 1716:                 '<td>'.$Foildata{$firstfoil}->{'text'}.'</td>'.
 1717:                 '<td>'.&HTML::Entities::encode($Foildata{$firstfoil}->{'value'},'<>&"').'</td>'.
 1718:                 "</tr>\n";
 1719:         } else {
 1720:             $table .= '<tr>'.
 1721:                 '<td>'.$foilindex++.'</td>'.
 1722:                 '<td>'.&HTML::Entities::encode($Foildata{$firstfoil}->{'name'},'<>&"').'</td>'.
 1723:                 '<td>'.$Foildata{$firstfoil}->{'text'}.'</td>'.
 1724:                 '<td>'.&HTML::Entities::encode($Foildata{$firstfoil}->{'value'},'<>&"').'</td>'.
 1725:                 "</tr>\n";
 1726:         }
 1727:         foreach my $foilid (@FoilsInConcept) {
 1728:             if (@Concepts > 1) {
 1729:                 $table .= '<tr>'.
 1730:                     '<td></td>'.
 1731:                     '<td></td>'.
 1732:                     '<td>'.$foilindex.'</td>'.
 1733:                     '<td>'.&HTML::Entities::encode($Foildata{$foilid}->{'name'},'<>&"').'</td>'.
 1734:                     '<td>'.$Foildata{$foilid}->{'text'}.'</td>'.
 1735:                     '<td>'.&HTML::Entities::encode($Foildata{$foilid}->{'value'},'<>&"').'</td>'.
 1736:                     "</tr>\n";
 1737:             } else {
 1738:                 $table .= '<tr>'.
 1739:                     '<td>'.$foilindex.'</td>'.
 1740:                     '<td>'.&HTML::Entities::encode($Foildata{$foilid}->{'name'},'<>&"').'</td>'.
 1741:                     '<td>'.$Foildata{$foilid}->{'text'}.'</td>'.
 1742:                     '<td>'.&HTML::Entities::encode($Foildata{$foilid}->{'value'},'<>&"').'</td>'.
 1743:                     "</tr>\n";
 1744:             }                
 1745:         } continue {
 1746:             $foilindex++;
 1747:         }
 1748:     } continue {
 1749:         $conceptindex++;
 1750:     }
 1751:     $table .= "</table>\n";
 1752:     #
 1753:     # Build option index with color stuff
 1754:     return ($table,\@Foils,\@Concepts);
 1755: }
 1756: 
 1757: sub build_option_index {
 1758:     my ($ORdata)= @_;
 1759:     my $table = "<table>\n";
 1760:     my $optionindex = 0;
 1761:     my @Rows;
 1762:     foreach my $option (&mt('correct option chosen'),@{$ORdata->{'_Options'}}) {
 1763:         my $color = $plotcolors->[$optionindex++];
 1764:         push (@Rows,
 1765:               '<tr>'.
 1766:               '<td bgcolor="'.$color.'">'.
 1767:               '<font color="'.$color.'">'.('*'x3).'</font>'.'</td>'.
 1768:               '<td>'.&HTML::Entities::encode($option,'<>&"').'</td>'.
 1769:               "</tr>\n");
 1770:     }
 1771:     shift(@Rows); # Throw away 'correct option chosen' color
 1772:     $table .= join('',reverse(@Rows));
 1773:     $table .= "</table>\n";
 1774: }
 1775: 
 1776: sub build_foil_key {
 1777:     my ($foils,$extra_data)= @_;
 1778:     if (! defined($extra_data)) { $extra_data = {}; }
 1779:     my $table = "<table>\n";
 1780:     my $foil_index = 0;
 1781:     my @rows;
 1782:     foreach my $foil (&mt('correct foil chosen'),@{$foils}) {
 1783:         my $color = $plotcolors->[$foil_index++];
 1784:         push (@rows,
 1785:               '<tr>'.
 1786:               '<td bgcolor="'.$color.'" class="key">'.
 1787:               '<font color="'.$color.'">'.('*'x4).'</font></td>'.
 1788:               '<td>'.&HTML::Entities::encode($foil,'<>&"').
 1789:               ('&nbsp;'x2).$extra_data->{$foil}.'</td>'.
 1790:               "</tr>\n");
 1791:     }
 1792:     shift(@rows); # Throw away 'correct foil chosen' color
 1793:     $table .= join('',reverse(@rows));
 1794:     $table .= "</table>\n";
 1795: }
 1796: 
 1797: #########################################################
 1798: #########################################################
 1799: ##
 1800: ##   Generic Interface Routines
 1801: ##
 1802: #########################################################
 1803: #########################################################
 1804: sub CreateInterface {
 1805:     ##
 1806:     ## Environment variable initialization
 1807:     if (! exists$ENV{'form.AnalyzeOver'}) {
 1808:         $ENV{'form.AnalyzeOver'} = 'tries';
 1809:     }
 1810:     ##
 1811:     ## Build the menu
 1812:     my $Str = '';
 1813:     $Str .= &Apache::lonhtmlcommon::breadcrumbs
 1814:         (undef,'Detailed Problem Analysis');
 1815:     $Str .= '<table cellspacing="5">'."\n";
 1816:     $Str .= '<tr>';
 1817:     $Str .= '<td align="center"><b>'.&mt('Sections').'</b></td>';
 1818:     $Str .= '<td align="center"><b>'.&mt('Enrollment Status').'</b></td>';
 1819: #    $Str .= '<td align="center"><b>'.&mt('Sequences and Folders').'</b></td>';
 1820:     $Str .= '<td align="center">&nbsp;</td>';
 1821:     $Str .= '</tr>'."\n";
 1822:     ##
 1823:     ## 
 1824:     $Str .= '<tr><td align="center">'."\n";
 1825:     $Str .= &Apache::lonstatistics::SectionSelect('Section','multiple',5);
 1826:     $Str .= '</td>';
 1827:     #
 1828:     $Str .= '<td align="center">';
 1829:     $Str .= &Apache::lonhtmlcommon::StatusOptions(undef,undef,5);
 1830:     $Str .= '</td>';
 1831:     #
 1832: #    $Str .= '<td align="center">';
 1833:     my $only_seq_with_assessments = sub { 
 1834:         my $s=shift;
 1835:         if ($s->{'num_assess'} < 1) { 
 1836:             return 0;
 1837:         } else { 
 1838:             return 1;
 1839:         }
 1840:     };
 1841:     &Apache::lonstatistics::MapSelect('Maps','multiple,all',5,
 1842:                                               $only_seq_with_assessments);
 1843:     ##
 1844:     ##
 1845:     $Str .= '<td>';
 1846:     ##
 1847:     my $showprob_checkbox = 
 1848:         '<input type="checkbox" name="show_prob" value="true" ';
 1849:     if ($ENV{'form.show_prob'} eq 'true') {
 1850:         $showprob_checkbox .= 'checked ';
 1851:     }
 1852:     $showprob_checkbox.= ' />';
 1853:     $Str.= '<nobr><label>'.
 1854:         &mt('Show problem [_1]',$showprob_checkbox).
 1855:         '</label></nobr><br />';
 1856:     ##
 1857:     my $analyze_selector = '<select name="AnalyzeOver" >';
 1858:     $analyze_selector .= '<option value="tries" ';
 1859:     if (! exists($ENV{'form.AnalyzeOver'}) || 
 1860:         $ENV{'form.AnalyzeOver'} eq 'tries'){
 1861:         # Default to tries
 1862:         $analyze_selector .= ' selected ';
 1863:     }
 1864:     $analyze_selector .= '>'.&mt('Tries').'</option>';
 1865:     $analyze_selector .= '<option value="time" ';
 1866:     $analyze_selector .= ' selected ' if ($ENV{'form.AnalyzeOver'} eq 'time');
 1867:     $analyze_selector .= '>'.&mt('Time').'</option>';
 1868:     $analyze_selector .= '</select>';
 1869:     $Str .= '<nobr><label>'.
 1870:         &mt('Analyze Over [_1] [_2]',
 1871:             $analyze_selector,
 1872:             &Apache::loncommon::help_open_topic('Analysis_Analyze_Over')).
 1873:             '</label></nobr><br />'.$/;
 1874:     ##
 1875:     my $numplots_selector = '<select name="NumPlots">';
 1876:     if (! exists($ENV{'form.NumPlots'}) 
 1877:         || $ENV{'form.NumPlots'} < 1 
 1878:         || $ENV{'form.NumPlots'} > 20) {
 1879:         $ENV{'form.NumPlots'} = 5;
 1880:     }
 1881:     foreach my $i (1,2,3,4,5,6,7,8,10,15,20) {
 1882:         $numplots_selector .= '<option value="'.$i.'" ';
 1883:         if ($ENV{'form.NumPlots'} == $i) { $numplots_selector.=' selected '; }
 1884:         $numplots_selector .= '>'.$i.'</option>';
 1885:     }
 1886:     $numplots_selector .= '</select></nobr><br />';
 1887:     $Str .= '<nobr><label>'.&mt('Number of Plots [_1]',$numplots_selector).
 1888:         '</label></nobr>';
 1889:     ##
 1890:     $Str .= '<nobr><label>'.&mt('Status: [_1]',
 1891:                                  '<input type="text" '.
 1892:                                  'name="stats_status" size="60" value="" />'
 1893:                                  ).
 1894:                     '</label></nobr>';
 1895:     $Str .= '</td>';
 1896:     ##
 1897:     ##
 1898:     $Str .= '</tr>'."\n";
 1899:     $Str .= '</table>'."\n";
 1900:     return $Str;
 1901: }
 1902: 
 1903: #########################################################
 1904: #########################################################
 1905: ##
 1906: ##              Misc Option Response functions
 1907: ##
 1908: #########################################################
 1909: #########################################################
 1910: sub get_time_from_row {
 1911:     my ($row) = @_;
 1912:     if (ref($row)) {
 1913:         return $row->[&Apache::loncoursedata::RD_timestamp()];
 1914:     } 
 1915:     return undef;
 1916: }
 1917: 
 1918: sub get_tries_from_row {
 1919:     my ($row) = @_;
 1920:     if (ref($row)) {
 1921:         return $row->[&Apache::loncoursedata::RD_tries()];
 1922:     }
 1923:     return undef;
 1924: }
 1925: 
 1926: sub hashify_attempt {
 1927:     my ($row) = @_;
 1928:     my %attempt;
 1929:     $attempt{'student'}    = $row->[&Apache::loncoursedata::RD_sname()];
 1930:     $attempt{'tries'}      = $row->[&Apache::loncoursedata::RD_tries()];
 1931:     $attempt{'submission'} = &Apache::lonnet::unescape($row->[&Apache::loncoursedata::RD_submission()]);
 1932:     $attempt{'award'}      = $row->[&Apache::loncoursedata::RD_awarddetail()];
 1933:     $attempt{'timestamp'}  = $row->[&Apache::loncoursedata::RD_timestamp()];
 1934:     return %attempt;
 1935: }
 1936: 
 1937: sub Process_OR_Row {
 1938:     my ($row) = @_;
 1939:     my %RowData;
 1940: #    my $student_id = $row->[&Apache::loncoursedata::RD_student_id()];
 1941:     my $award      = $row->[&Apache::loncoursedata::RD_awarddetail()];
 1942:     my $grading    = $row->[&Apache::loncoursedata::RD_response_eval()];
 1943:     my $submission = $row->[&Apache::loncoursedata::RD_submission()];
 1944:     my $time       = $row->[&Apache::loncoursedata::RD_timestamp()];
 1945: #    my $tries      = $row->[&Apache::loncoursedata::RD_tries()];
 1946:     return undef if ($award eq 'MISSING_ANSWER');
 1947:     if (&submission_is_correct($award)) {
 1948:         $RowData{'_correct'} = 1;
 1949:     }
 1950:     $RowData{'_total'} = 1;
 1951:     my @Foilgrades = split('&',$grading);
 1952:     my @Foilsubs   = split('&',$submission);
 1953:     for (my $j=0;$j<=$#Foilgrades;$j++) {
 1954:         my ($foilid,$correct)  = split('=',$Foilgrades[$j]);
 1955:         $foilid = &Apache::lonnet::unescape($foilid);
 1956:         my (undef,$submission) = split('=',$Foilsubs[$j]);
 1957:         if ($correct) {
 1958:             $RowData{$foilid}->{'_correct'}++;
 1959:         } else {
 1960:             $submission = &Apache::lonnet::unescape($submission);
 1961:             $RowData{$foilid}->{$submission}++;
 1962:         }
 1963:         $RowData{$foilid}->{'_total'}++;
 1964:     }
 1965:     return %RowData;
 1966: }
 1967: 
 1968: sub submission_is_correct {
 1969:     my ($award) = @_;
 1970:     if ($award =~ /(APPROX_ANS|EXACT_ANS)/) {
 1971:         return 1;
 1972:     } else {
 1973:         return 0;
 1974:     }
 1975: }
 1976: 
 1977: 1;
 1978: 
 1979: __END__

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