File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.142.2.2: download - view: text, annotated - select for diffs
Mon Dec 17 03:52:30 2012 UTC (11 years, 6 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_0_RC1
- For 2.11
  - Backport 1.143.

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

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