File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.129: download - view: text, annotated - select for diffs
Thu Dec 21 19:52:28 2006 UTC (17 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: version_2_2_99_1, HEAD
- bug5095 - handle case of no students and no spread in provided answers
            more correctly (rather than infinite loop)

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

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