File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.141: download - view: text, annotated - select for diffs
Wed Dec 21 21:25:51 2011 UTC (12 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD, BZ4492-merge, BZ4492-feature_horizontal_radioresponse
Bug 6455 - Progress Indicator now jQuery. Still need to test across browsers.

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

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