File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.147: download - view: text, annotated - select for diffs
Tue Nov 10 19:28:32 2020 UTC (3 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Load CSS file(s) for resource when using (a) Student Submission Reports
  (only one problem selected), or and (b)Detailed Problem Analysis when
  "Show problem" is checked, or when using Submission Time Plots.

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

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