File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.137: download - view: text, annotated - select for diffs
Tue Apr 21 13:28:23 2009 UTC (15 years, 2 months ago) by bisitz
Branches: MAIN
CVS tags: version_2_8_99_0, bz5969, bz2851, HEAD, GCI_3, GCI_2, BZ5971-printing-apage, BZ5434-fox
Moved output options checkboxes from translation phrases to script code.
This ensures that
- the checkboxes are always properly displayed, independent from the translation phrases
- the place of the checkboxes is given by the script code to have a consistent screen layout, independent from the translation of the corresponding text

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

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