File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.126: download - view: text, annotated - select for diffs
Tue May 30 12:46:49 2006 UTC (18 years, 1 month ago) by www
Branches: MAIN
CVS tags: version_2_1_99_3, version_2_1_99_2, version_2_1_99_1, version_2_1_99_0, HEAD
&Apache::lonnet::unescape -> &unescape
&Apache::lonnet::escape -> &escape

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

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