File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.122: download - view: text, annotated - select for diffs
Mon Nov 7 22:09:00 2005 UTC (18 years, 7 months ago) by albertel
Branches: MAIN
CVS tags: version_2_1_2, version_2_1_1, version_2_1_0, version_2_0_99_1, HEAD
- BUG#4445

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

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