File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.125: download - view: text, annotated - select for diffs
Mon May 1 19:29:13 2006 UTC (18 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- update statistics calls to bread crumbs

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

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