File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.140: download - view: text, annotated - select for diffs
Mon Jan 17 00:19:41 2011 UTC (13 years, 4 months ago) by www
Branches: MAIN
CVS tags: language_hyphenation_merge, language_hyphenation, HEAD
Add statistics and reports under "grading"

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

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