File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.142.2.5: download - view: text, annotated - select for diffs
Thu Nov 12 00:15:27 2020 UTC (3 years, 6 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_4_uiuc, version_2_11_4_msu, version_2_11_4, version_2_11_3_uiuc, version_2_11_3_msu, version_2_11_3
- For 2.11
  Backport 1.147

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

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