File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.121: download - view: text, annotated - select for diffs
Tue Apr 19 13:59:34 2005 UTC (19 years, 2 months ago) by matthew
Branches: MAIN
CVS tags: version_2_0_X, version_2_0_2, version_2_0_1, version_2_0_0, version_1_99_3, version_1_99_2, version_1_99_1_tmcc, version_1_99_1, version_1_99_0, HEAD
Bug 2989: Need more submit buttons on problem selection pages.  Problem
analysis and submission time analysis now have submit buttons after each
sequence/folder.

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

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