File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.123: download - view: text, annotated - select for diffs
Sun Jan 22 04:10:04 2006 UTC (18 years, 5 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Pending implementation of the "Detailed Problem Analysis" output into
CSV and Excel, remove the selection box for Excel & CSV so we aren't
promising what we can't deliver.

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