File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.142.2.3: download - view: text, annotated - select for diffs
Mon Dec 30 14:19:58 2013 UTC (10 years, 6 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_0_RC2
- For 2.11
  - Backport  1.144.

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

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