File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.113: download - view: text, annotated - select for diffs
Tue Feb 22 05:28:21 2005 UTC (19 years, 4 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
So the last commit of code for &numerical_plot_percent was stupid for
plotting percents, but much better in &numerical_plot_differences, which
now works well.

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

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