File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.130: download - view: text, annotated - select for diffs
Thu Jan 4 02:44:07 2007 UTC (17 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: version_2_7_X, version_2_7_1, version_2_7_0, version_2_6_X, version_2_6_99_1, version_2_6_99_0, version_2_6_3, version_2_6_2, version_2_6_1, version_2_6_0, version_2_5_X, version_2_5_99_1, version_2_5_99_0, version_2_5_2, version_2_5_1, version_2_5_0, version_2_4_X, version_2_4_99_0, version_2_4_2, version_2_4_1, version_2_4_0, version_2_3_X, version_2_3_99_0, version_2_3_2, version_2_3_1, version_2_3_0, HEAD
- updating to work (simplely) with multiple correct answers

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: lonproblemanalysis.pm,v 1.130 2007/01/04 02:44:07 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: 	# pick one of the possible answers
  640: 	my $which = 'INTERNAL';
  641: 	if (!exists($analysis->{$key}{$which})) {
  642: 	    $which = (sort(keys(%{ $analysis->{$key} })))[0];
  643: 	}
  644:         foreach my $item ('answer','unit','ans_high','ans_low') {
  645: 	    if (ref($analysis->{$key.'.'.$item}) eq 'ARRAY') {
  646: 		$correct->{$sname.':'.$sdom}->{$item} = 
  647: 		    $analysis->{$key.'.'.$item}[0];
  648: 	    } else {
  649: 		$correct->{$sname.':'.$sdom}->{$item} = 
  650: 		    $analysis->{$key.'.'.$item}{$which}[0][0];
  651: 	    }
  652:         }
  653:         $answers{$correct->{$sname.':'.$sdom}{'answer'}}++;
  654:         &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
  655:                                                  &mt('last student'));
  656:     }
  657:     &Apache::lonstathelpers::write_analysis_cache();
  658:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  659:     return ($correct,\%answers);
  660: }
  661: 
  662: #
  663: # Inputs: $r, $width, $height, $data
  664: #         $n = number of students
  665: #         $data = hashref of $answer => $frequency pairs
  666: sub numerical_one_dimensional_plot {
  667:     my ($r,$width,$height,$data)=@_;
  668:     #
  669:     # Compute data -> image scaling factors
  670:     my $max_y = 0;
  671:     my $min_x = undef;
  672:     my $max_x = undef;
  673:     my $n = 0;
  674:     while (my ($answer,$count) = each(%$data)) {
  675:         $n+=$count;
  676:         $max_y = $count if ($max_y < $count);
  677:         if (! defined($min_x) || $answer < $min_x) {
  678:             $min_x = $answer;
  679:         }
  680:         if (! defined($max_x) || $answer > $max_x) {
  681:             $max_x = $answer;
  682:         }
  683:     }
  684:     #
  685:     my $min_max_difference = $max_x - $min_x;
  686:     if (! defined($min_max_difference) || $min_max_difference == 0) {
  687:         $min_max_difference = 1;
  688:     }
  689:     my $h_scale = ($width-10)/$min_max_difference;
  690:     #
  691:     my $ticscale = 5;
  692:     if ($max_y * $ticscale > $height/2) {
  693:         $ticscale = int($height/2/$max_y);
  694:         $ticscale = 1 if ($ticscale < 1);
  695:     }
  696:     #
  697:     # Create the plot
  698:     my $plot = 
  699:         qq{<drawimage width="$width" height="$height" bgcolor="transparent" >};
  700:     while (my ($answer,$count) = each(%$data)) {
  701:         my $xloc = 5+$h_scale*($answer - $min_x);
  702:         my $top    = $height/2-$count*$ticscale;
  703:         my $bottom = $height/2+$count*$ticscale;
  704:         $plot .= &line($xloc,$top,$xloc,$bottom,'888888',1);
  705:     }
  706:     #
  707:     # Put the scale on last to ensure it is on top of the data.
  708:     if ($min_x < 0 && $max_x > 0) {
  709:         my $circle_x = 5+$h_scale*abs($min_x);  # '0' in data coordinates
  710:         my $r = 4;
  711:         $plot .= &line(5,$height/2,$circle_x-$r,$height/2,'000000',1);
  712:         $plot .= &circle($circle_x,$height/2,$r+1,'000000');
  713:         $plot .= &line($circle_x+$r,$height/2,$width-5,$height/2,'000000',1);
  714:     } else {
  715:         $plot .= &line(5,$height/2,$width-5,$height/2,'000000',1);
  716:     }
  717:     $plot .= '</drawimage>';
  718:     my $plotresult =  &Apache::lonxml::xmlparse($r,'web',$plot);
  719:     my $result = '<table>'.
  720:         '<tr><td colspan="3" align="center">'.
  721:         '<font size="+2">'.&mt('Distribution of correct answers').'</font>'.
  722:         '<br />'.&mt('[_1] students, [_2] distinct correct answers',
  723:                      $n,scalar(keys(%$data))).
  724:         '<br />'.&mt('Maximum number of coinciding values: [_1]',$max_y).
  725:         '</td></tr>'.
  726:         '<tr>'.
  727:         '<td valign="center">'.$min_x.'</td>'.
  728:         '<td>'.$plotresult.'</td>'.
  729:         '<td valign="center">'.$max_x.'</td>'.
  730:         '</tr>'.
  731:         '</table>';
  732:     return $result;
  733: }
  734: 
  735: ##
  736: ## Helper subroutines for <drawimage>.  
  737: ## These should probably go somewhere more suitable soon.
  738: sub line {
  739:     my ($x1,$y1,$x2,$y2,$color,$thickness) = @_;
  740:     return qq{<line x1="$x1" y1="$y1" x2="$x2" y2="$y2" color="$color" thickness="$thickness" />};
  741: }
  742: 
  743: sub text {
  744:     my ($x,$y,$color,$text,$font,$direction) = @_;
  745:     if (! defined($font) || $font !~ /^(tiny|small|medium|large|giant)$/) {
  746:         $font = 'medium';
  747:     }
  748:     if (! defined($direction) || $direction ne 'vertical') {
  749:         $direction = '';
  750:     }
  751:     return qq{<text x="$x" y="$y" color="$color" font="$font" direction="$direction" >$text</text>};
  752: }
  753: 
  754: sub rectangle {
  755:     my ($x1,$y1,$x2,$y2,$color,$thickness,$filled) = @_;
  756:     return qq{<rectangle x1="$x1" y1="$y1" x2="$x2" y2="$y2" color="$color" thickness="$thickness" filled="$filled" />};
  757: }
  758: 
  759: sub arc {
  760:     my ($x,$y,$width,$height,$start,$end,$color,$thickness,$filled)=@_;
  761:     return qq{<arc x="$x" y="$y" width="$width" height="$height" start="$start" end="$end" color="$color" thickness="$thickness" filled="$filled" />};
  762: }
  763: 
  764: sub circle {
  765:     my ($x,$y,$radius,$color,$thickness,$filled)=@_;
  766:     return &arc($x,$y,$radius,$radius,0,360,$color,$thickness,$filled);
  767: }
  768: 
  769: #########################################################
  770: #########################################################
  771: ##
  772: ##      Radio Response Routines
  773: ##
  774: #########################################################
  775: #########################################################
  776: sub radio_response_analysis {
  777:     my ($r,$problem,$problem_analysis,$students) = @_;
  778:     #
  779:     if ($env{'form.AnalyzeOver'} !~ /^(tries|time)$/) {
  780:         $r->print('Bad request');
  781:     }
  782:     #
  783:     my ($resource,$partid,$respid) = ($problem->{'resource'},
  784:                                       $problem->{'part'},
  785:                                       $problem->{'respid'});
  786:     #
  787:     my $analysis_html;
  788:     my $foildata = $problem_analysis->{'_Foils'};
  789:     my ($table,$foils,$concepts) = &build_foil_index($problem_analysis);
  790:     if (! defined($concepts)) {
  791:         $concepts = [];
  792:     }
  793:     #
  794:     my %true_foils;
  795:     my $num_true = 0;
  796:     if (! $problem_analysis->{'answercomputed'}) {
  797:         foreach my $foil (@$foils) {
  798:             if ($foildata->{$foil}->{'value'} eq 'true') {
  799:                 $true_foils{$foil}++; 
  800:             }
  801:         }
  802:         $num_true = scalar(keys(%true_foils));
  803:     }
  804:     #
  805:     $analysis_html .= $table;
  806:     # Gather student data
  807:     my $response_data = &Apache::loncoursedata::get_response_data
  808:         ([&Apache::lonstatistics::get_selected_sections()],
  809:          [&Apache::lonstatistics::get_selected_groups()],
  810:          $Apache::lonstatistics::enrollment_status,
  811:          $resource->symb,$respid);
  812:     my $correct;   # either a hash reference or a scalar
  813:     if ($problem_analysis->{'answercomputed'} || scalar(@$concepts) > 1) {
  814:         # This takes a while for large classes...
  815:         &Apache::lonstathelpers::GetStudentAnswers($r,$problem,$students,
  816:                                                    'Statistics',
  817:                                                    'stats_status');
  818:         foreach my $student (@$students) {
  819:             my ($idx,@remainder) = split('&',$student->{'answer'});
  820:             my ($answer) = ($remainder[$idx]=~/^(.*)=([^=]*)$/);
  821:             $correct->{$student->{'username'}.':'.$student->{'domain'}}=
  822:                 &unescape($answer);
  823:         }
  824:     } else {
  825:         foreach my $foil (keys(%$foildata)) {
  826:             if ($foildata->{$foil}->{'value'} eq 'true') {
  827:                 $correct = $foildata->{$foil}->{'name'};
  828:             }
  829:         }
  830:     }
  831:     #
  832:     if (! defined($response_data) || ref($response_data) ne 'ARRAY' ) {
  833:         $analysis_html = '<h2>'.
  834:             &mt('There is no submission data for this resource').
  835:             '</h2>';
  836:         $r->print($analysis_html);
  837:         return;
  838:     }
  839:     #
  840:     $analysis_html.='<table>';
  841:     for (my $plot_num = 1;$plot_num<=$env{'form.NumPlots'};$plot_num++) {
  842:         # classify data ->correct foil -> selected foil
  843:         my ($restriction_function,
  844:             $correct_foil_title,$incorrect_foil_title,
  845:             $pre_graph_text,$post_graph_text,
  846:             $no_data_text,@extra_data);
  847:         if ($env{'form.AnalyzeOver'} eq 'tries') {
  848:             $restriction_function = sub {($_[0]->{'tries'} == $plot_num?1:0)};
  849:             $correct_foil_title = 'Attempt '.$plot_num;
  850:             $incorrect_foil_title = 'Attempt '.$plot_num;
  851:             $pre_graph_text = 
  852:                 'Attempt [_1], [_2] submissions, [_3] correct, [_4] incorrect';
  853:             $post_graph_text = '';
  854:             $no_data_text = 'No data exists for attempt [_1]';
  855:         } elsif ($env{'form.AnalyzeOver'} eq 'time') {
  856:             my $starttime = &Apache::lonhtmlcommon::get_date_from_form
  857:                 ('startdate_'.$plot_num);
  858:             my $endtime = &Apache::lonhtmlcommon::get_date_from_form
  859:                 ('enddate_'.$plot_num);
  860:             ($starttime,$endtime) = &ensure_start_end_times
  861:                 ($starttime,$endtime,
  862:                  &get_time_from_row($response_data->[0]),
  863:                  &get_time_from_row($response_data->[-1]),
  864:                  $plot_num);
  865:             $pre_graph_text = 
  866:                 'Data from [_6] to [_7]<br /> [_2] submissions from [_5] students, [_3] correct, [_4] incorrect';
  867:             $extra_data[0] = &Apache::lonlocal::locallocaltime($starttime);
  868:             $extra_data[1] = &Apache::lonlocal::locallocaltime($endtime);
  869:             #
  870:             $post_graph_text = 
  871:                 &mt('Start time: [_1]',
  872:                     &Apache::lonhtmlcommon::date_setter
  873:                     ('Statistics','startdate_'.$plot_num,$starttime)).
  874:                 '<br />'.
  875:                 &mt('End time: [_1]',
  876:                     &Apache::lonhtmlcommon::date_setter
  877:                     ('Statistics','enddate_'.$plot_num,$endtime));
  878:             $restriction_function = 
  879:                 sub { 
  880:                     my $t = $_[0]->{'timestamp'};
  881:                     if ($t >= $starttime && $t < $endtime) {
  882:                         return 1;
  883:                     } else { 
  884:                         return 0;
  885:                     }
  886:                 };
  887:             $no_data_text = 'No data for [_5] to [_6]';
  888:         }
  889:         my $foil_choice_data =
  890:             &classify_response_data($response_data,$correct,
  891:                                     $restriction_function);
  892:         # &Apache::lonstathelpers::log_hash_ref($foil_choice_data);
  893:         my $answers;
  894:         if (ref($correct)) {
  895:             my %tmp;
  896:             foreach my $foil (values(%$correct)) {
  897:                 $tmp{$foil}++;
  898:             }
  899:             $answers = [keys(%tmp)];
  900:         } else {
  901:             $answers = [$correct];
  902:         }
  903:         # Concept Plot
  904:         my $concept_plot = '';
  905:         if (scalar(@$concepts) > 1) {
  906:             $concept_plot = &RR_concept_plot($concepts,$foil_choice_data,
  907:                                              'Correct Concepts');
  908:         }
  909:         # % Choosing plot
  910:         my $choice_plot = &RR_create_percent_selected_plot
  911:             ($concepts,$foils,$foil_choice_data,$correct_foil_title);
  912:         # for each correct foil, how did they mark it? (stacked bar graph)
  913:         my ($stacked_plot,$count_by_foil);
  914:         if ($problem_analysis->{'answercomputed'} || $num_true > 1) {
  915:             ($stacked_plot,$count_by_foil) =
  916:                 &RR_create_stacked_selection_plot($foils,$foil_choice_data,
  917:                                                   $incorrect_foil_title,
  918:                                                   \%true_foils);
  919:         }
  920:         #
  921:         if ($concept_plot ne '' ||
  922:             $choice_plot  ne '' ||
  923:             $stacked_plot ne '') {
  924:             my $correct = $foil_choice_data->{'_correct'};
  925:             $correct |= 0;
  926:             my $incorrect = $foil_choice_data->{'_count'}-$correct;
  927:             $analysis_html.= '<tr><td colspan="4" align="center">'.
  928:                 '<font size="+1">'.
  929:                 &mt($pre_graph_text,
  930:                     $plot_num,$foil_choice_data->{'_count'},
  931:                     $correct,
  932:                     $incorrect,
  933:                     $foil_choice_data->{'_students'},
  934:                     @extra_data).
  935:                     '</td></tr>'.$/;
  936:             $analysis_html.=
  937:                 '<tr>'.
  938:                 '<td>'.$concept_plot.'</td>'.
  939:                 '<td>'.$choice_plot.'</td>';
  940:             if ($stacked_plot ne '') {
  941:                 $analysis_html .= 
  942:                     '<td>'.$stacked_plot.'</td>'.
  943:                     '<td>'.&build_foil_key($foils,$count_by_foil).'</td>';
  944:             } else {
  945:                 $analysis_html .= ('<td></td>'x2);
  946:             }
  947:             $analysis_html.='</tr>'.$/;
  948:             if (defined($post_graph_text)) {
  949:                 $analysis_html.= '<tr><td colspan="4" align="center">'.
  950:                     $post_graph_text.'</td></tr>'.$/;
  951:             }
  952:         } elsif ($no_data_text ne '') {
  953:             $analysis_html.='<tr><td colspan="4" align="center">'.
  954:                 &mt($no_data_text,
  955:                     $plot_num,$foil_choice_data->{'_count'},
  956:                     $correct,                    
  957:                     $foil_choice_data->{'_count'}-$correct,
  958:                     @extra_data);
  959:             if (defined($post_graph_text)) {
  960:                 $analysis_html.='<br />'.$post_graph_text;
  961:             }
  962:             $analysis_html.='</td></tr>'.$/;
  963:         }
  964:     } # end of loop for plots
  965:     $analysis_html.='</table>';
  966:     $r->print($analysis_html);
  967: }
  968: 
  969: sub ensure_start_end_times {
  970:     my ($start,$end,$first,$last,$plot_num) = @_;
  971:     if (! defined($start) || ! defined($end)) {
  972:         my $sec_in_day = 86400;
  973:         my ($sday,$smon,$syear) = 
  974:             (localtime($last - $sec_in_day*($plot_num-1)))[3..5];
  975:         $start = &Time::Local::timelocal(0,0,0,$sday,$smon,$syear);
  976:         $end   = $start + $sec_in_day;
  977:         if ($plot_num == $env{'form.NumPlots'}) {
  978:             $start = $first;
  979:         }
  980:     }
  981:     return ($start,$end);
  982: }
  983: 
  984: sub RR_concept_plot {
  985:     my ($concepts,$foil_data,$title) = @_;
  986:     #
  987:     my %correct_by_concept;
  988:     my %incorrect_by_concept;
  989:     my %true;
  990:     foreach my $concept (@$concepts) {
  991:         foreach my $foil (@{$concept->{'foils'}}) {
  992:             next if (! exists($foil_data->{$foil}));
  993:             foreach my $choice (keys(%{$foil_data->{$foil}})) {
  994:                 if ($choice eq $foil) {
  995:                     $correct_by_concept{$concept->{'name'}} +=
  996:                         $foil_data->{$foil}->{$choice};
  997:                 } else {
  998:                     $incorrect_by_concept{$concept->{'name'}} +=
  999:                         $foil_data->{$foil}->{$choice};
 1000:                 }
 1001:             }
 1002:         }
 1003:     }
 1004:     # 
 1005:     # need arrays for incorrect and correct because we want to use different
 1006:     # colors for them
 1007:     my @correct;
 1008:     #
 1009:     my $total =0;
 1010:     for (my $i=0;$i<scalar(@$concepts);$i++) {
 1011:         my $concept = $concepts->[$i];
 1012:         $correct[$i]   =   $correct_by_concept{$concept->{'name'}};
 1013:         $total += $correct_by_concept{$concept->{'name'}}+
 1014:             $incorrect_by_concept{$concept->{'name'}};
 1015:     }
 1016:     if ($total == 0) { return ''; };
 1017:     for (my $i=0;$i<=$#correct;$i++) { 
 1018:         $correct[$i] = sprintf('%0f',$correct[$i]/$total*100);
 1019:     }
 1020:     my $xlabel = 'concept';
 1021:     my $plot=  &Apache::loncommon::DrawBarGraph($title,
 1022:                                                 $xlabel,
 1023:                                                 'Percent Choosing',
 1024:                                                 100,
 1025:                                                 ['#33ff00','#ff3300'],
 1026:                                                 undef,
 1027:                                                 \@correct);
 1028:     return $plot;
 1029: }
 1030: 
 1031: sub RR_create_percent_selected_plot {
 1032:     my ($concepts,$foils,$foil_data,$title) = @_;
 1033:     #
 1034:     if ($foil_data->{'_count'} == 0) { return ''; };
 1035:     my %correct_selections;
 1036:     my %incorrect_selections;
 1037:     foreach my $foil (@$foils) {
 1038:         # foil_data has format $foil_data->{true_foil}->{selected foil}=count
 1039:         next if (! exists($foil_data->{$foil}));
 1040:         while (my ($f,$count)= each(%{$foil_data->{$foil}})) {
 1041:             if ($f eq $foil) {
 1042:                 $correct_selections{$foil} += $count;
 1043:             } else {
 1044:                 $incorrect_selections{$f} += $count;
 1045:             }
 1046:         }
 1047:     }
 1048:     # 
 1049:     # need arrays for incorrect and correct because we want to use different
 1050:     # colors for them
 1051:     my @correct;
 1052:     my @incorrect;
 1053:     #
 1054:     my $total = $foil_data->{'_count'};
 1055:     for (my $i=0;$i<scalar(@$foils);$i++) {
 1056:         my $foil = $foils->[$i];
 1057:         $correct[$i]   = $correct_selections{$foil};
 1058:         $incorrect[$i] = $incorrect_selections{$foil};
 1059:     }
 1060:     for (my $i=0;$i<=$#correct;$i++) { 
 1061:         $correct[$i] = sprintf('%2f',$correct[$i]/$total*100);
 1062:     }
 1063:     for (my $i=0;$i<=$#incorrect;$i++) {
 1064:         $incorrect[$i] = sprintf('%2f',$incorrect[$i]/$total*100);
 1065:     }
 1066:     #
 1067:     # Put a blank in the data sets between concepts, if there are concepts
 1068:     my @labels;
 1069:     if (defined($concepts) && scalar(@$concepts) > 1) {
 1070:         my @new_correct;
 1071:         my @new_incorrect;
 1072:         my $foil_count = 0;
 1073:         foreach my $concept (@$concepts) {
 1074:             foreach (@{$concept->{'foils'}}) {
 1075:                 push(@new_correct,  $correct[$foil_count]);
 1076:                 push(@new_incorrect,$incorrect[$foil_count]);
 1077:                 push(@labels,++$foil_count);
 1078:             }
 1079:             push(@new_correct,'');
 1080:             push(@new_incorrect,'');
 1081:             push(@labels,'');
 1082:         }
 1083:         @correct = @new_correct;
 1084:         @incorrect = @new_incorrect;
 1085:     } else {
 1086:         @labels = (1 .. scalar(@correct));
 1087:     }
 1088:     #
 1089:     my $xlabel = 'foil chosen';
 1090:     my $plot=  &Apache::loncommon::DrawBarGraph($title,
 1091:                                                 $xlabel,
 1092:                                                 'Percent Choosing',
 1093:                                                 100,
 1094:                                                 ['#33ff00','#ff3300'],
 1095:                                                 \@labels,
 1096:                                                 \@correct,
 1097:                                                 \@incorrect);
 1098:     return $plot;
 1099: }
 1100: 
 1101: sub RR_create_stacked_selection_plot {
 1102:     my ($foils,$foil_data,$title,$true_foils)=@_;
 1103:     #
 1104:     my @dataset; # array of array refs - multicolor rows $datasets[row]->[col]
 1105:     my @labels;
 1106:     my $count;
 1107:     my %column; # maps foil name to column in @datasets
 1108:     for (my $i=0;$i<scalar(@$foils);$i++) {
 1109:         my $foil = $foils->[$i];
 1110:         if (defined($true_foils) && scalar(keys(%$true_foils)) > 0 ) {
 1111:             next if (! $true_foils->{$foil} );
 1112:             push(@labels,$i+1);
 1113:         } else {
 1114:             next if (! exists($foil_data->{$foil}));
 1115:             push(@labels,$i+1);
 1116:         }
 1117:         next if (! exists($foil_data->{$foils->[$i]}));
 1118:         $column{$foil}= $count++;
 1119:         for (my $j=0;$j<scalar(@$foils);$j++) {
 1120:             my $value = 0;
 1121:             if ($i != $j ) {
 1122:                 $value += $foil_data->{$foil}->{$foils->[$j]};
 1123:             }
 1124:             $dataset[$j]->[$column{$foil}]=$value;
 1125:         }
 1126:     }
 1127:     #
 1128:     return '' if (! scalar(keys(%column)));
 1129:     #
 1130:     my $grand_total = 0;
 1131:     my %count_per_foil;
 1132:     while (my ($foil,$bar) = each (%column)) {
 1133:         my $bar_total = 0;
 1134:         for (my $j=0;$j<scalar(@dataset);$j++) {
 1135:             $bar_total += $dataset[$j]->[$bar];
 1136:         }
 1137:         next if ($bar_total == 0);
 1138:         for (my $j=0;$j<scalar(@dataset);$j++) {
 1139:             $dataset[$j]->[$bar] = 
 1140:                 sprintf('%2f',$dataset[$j]->[$bar]/$bar_total * 100);
 1141:         }
 1142:         $count_per_foil{$foil}=' ( '.$bar_total.' )';
 1143:         $grand_total += $bar_total;
 1144:     }
 1145:     if ($grand_total == 0) {
 1146:         return ('',undef);
 1147:     }
 1148:     my @empty_row = ();
 1149:     foreach (@{$dataset[0]}) {
 1150:         push(@empty_row,0);
 1151:     }
 1152:     #
 1153:     my $graph = &Apache::loncommon::DrawBarGraph
 1154:         ($title,'Correct Foil','foils chosen Incorrectly',
 1155:          100,$plotcolors,\@labels,\@empty_row,@dataset);
 1156:     return ($graph,\%count_per_foil);
 1157: }
 1158: 
 1159: 
 1160: #########################################################
 1161: #########################################################
 1162: ##
 1163: ##       Misc routines
 1164: ##
 1165: #########################################################
 1166: #########################################################
 1167: 
 1168: # if $correct is a hash ref, it is assumed to be indexed by student names.
 1169: #    the values are assumed to be hash refs with a key of 'answer'.
 1170: sub classify_response_data {
 1171:     my ($full_row_data,$correct,$function) = @_;
 1172:     my %submission_data;
 1173:     my %students;
 1174:     my $max=0;
 1175:     foreach my $row (@$full_row_data) {
 1176:         my %subm = &hashify_attempt($row);
 1177:         if (ref($correct) eq 'HASH') {
 1178:             $subm{'correct'} = $correct->{$subm{'student'}};
 1179:         } else {
 1180:             $subm{'correct'} = $correct;
 1181:         }
 1182:         $subm{'submission'} =~ s/=\d+\s*$//;
 1183:         if (&$function(\%subm)) {
 1184:             $students{$subm{'student'}}++;
 1185:             $submission_data{'_count'}++;
 1186:             if (&submission_is_correct($subm{'award'})) { 
 1187:                 $submission_data{'_correct'}++;
 1188:             }
 1189:             
 1190:             if($max<++$submission_data{$subm{'correct'}}->{$subm{'submission'}}) {
 1191:                 $max=$submission_data{$subm{'correct'}}->{$subm{'submission'}};
 1192:             }
 1193:         }
 1194:     }
 1195:     $submission_data{'_max'} = $max;
 1196:     $submission_data{'_students'}=scalar(keys(%students));
 1197:     return \%submission_data;
 1198: }
 1199: 
 1200: 
 1201: #########################################################
 1202: #########################################################
 1203: ##
 1204: ##      Option Response Routines
 1205: ##
 1206: #########################################################
 1207: #########################################################
 1208: sub OptionResponseAnalysis {
 1209:     my ($r,$problem,$problem_data,$Students) = @_;
 1210:     my ($resource,$respid) = ($problem->{'resource'},
 1211:                               $problem->{'respid'});
 1212:     # Note: part data is not needed.
 1213:     my $PerformanceData = &Apache::loncoursedata::get_response_data
 1214:         ([&Apache::lonstatistics::get_selected_sections()],
 1215:          [&Apache::lonstatistics::get_selected_groups()],
 1216:          $Apache::lonstatistics::enrollment_status,
 1217:          $resource->symb,$respid);
 1218:     if (! defined($PerformanceData) || 
 1219:         ref($PerformanceData) ne 'ARRAY' ) {
 1220:         $r->print('<h2>'.
 1221:                   &mt('There is no student data for this problem.').
 1222:                   '</h2>');
 1223:     }  else {
 1224:         $r->rflush();
 1225:         if ($env{'form.AnalyzeOver'} eq 'tries') {
 1226:             my $analysis_html = &OR_tries_analysis($r,
 1227:                                                    $PerformanceData,
 1228:                                                    $problem_data);
 1229:             $r->print($analysis_html);
 1230:             $r->rflush();
 1231:         } elsif ($env{'form.AnalyzeOver'} eq 'time') {
 1232:             my $analysis_html = &OR_time_analysis($PerformanceData,
 1233:                                                   $problem_data);
 1234:             $r->print($analysis_html);
 1235:             $r->rflush();
 1236:         } else {
 1237:             $r->print('<h2>'.
 1238:                       &mt('The analysis you have selected is '.
 1239:                           'not supported at this time').
 1240:                       '</h2>');
 1241:         }
 1242:     }
 1243: }
 1244: 
 1245: #########################################################
 1246: #
 1247: #       Option Response:  tries Analysis
 1248: #
 1249: #########################################################
 1250: sub OR_tries_analysis {
 1251:     my ($r,$PerformanceData,$ORdata) = @_;
 1252:     my $mintries = 1;
 1253:     my $maxtries = $env{'form.NumPlots'};
 1254:     my ($table,$Foils,$Concepts) = &build_foil_index($ORdata);
 1255:     if (! defined($Concepts)) {
 1256:         $Concepts = [];
 1257:     }
 1258:     my %response_data = &OR_analyze_by_tries($r,$PerformanceData,
 1259:                                                      $mintries,$maxtries);
 1260:     my $analysis = '';
 1261:     #
 1262:     # Compute the data necessary to make the plots
 1263:     my @foil_plot; 
 1264:     my @concept_data;
 1265:     for (my $j=0;$j<=scalar(@$Concepts);$j++) {
 1266:         my $concept = $Concepts->[$j];
 1267:         foreach my $foilid (@{$concept->{'foils'}}) {
 1268:             for (my $try=$mintries;$try<=$maxtries;$try++) {
 1269:                 # concept analysis data
 1270:                 $concept_data[$j]->[$try]->{'_correct'} +=
 1271:                     $response_data{$foilid}->[$try]->{'_correct'};
 1272:                 $concept_data[$j]->[$try]->{'_total'} +=
 1273:                     $response_data{$foilid}->[$try]->{'_total'};
 1274:                 #
 1275:                 # foil analysis data
 1276:                 if ($response_data{$foilid}->[$try]->{'_total'} == 0) {
 1277:                     push(@{$foil_plot[$try]->{'_correct'}},0);
 1278:                 } else {
 1279:                     push(@{$foil_plot[$try]->{'_correct'}},
 1280:                          100*$response_data{$foilid}->[$try]->{'_correct'}/
 1281:                          $response_data{$foilid}->[$try]->{'_total'});
 1282:                 }
 1283:                 foreach my $option (@{$ORdata->{'_Options'}}) {
 1284:                     push(@{$foil_plot[$try]->{'_total'}},
 1285:                          $response_data{$foilid}->[$try]->{'_total'});
 1286:                     if ($response_data{$foilid}->[$try]->{'_total'} == 0) {
 1287:                         push (@{$foil_plot[$try]->{$option}},0);
 1288:                     } else {
 1289:                         if ($response_data{$foilid}->[$try]->{'_total'} ==
 1290:                             $response_data{$foilid}->[$try]->{'_correct'}) {
 1291:                             push(@{$foil_plot[$try]->{$option}},0);
 1292:                         } else {
 1293:                             push (@{$foil_plot[$try]->{$option}},
 1294:                                   100 * 
 1295:                                   $response_data{$foilid}->[$try]->{$option} / 
 1296:                                   ($response_data{$foilid}->[$try]->{'_total'} 
 1297:                                    - 
 1298:                                    $response_data{$foilid}->[$try]->{'_correct'}
 1299:                                    ));
 1300:                         }
 1301:                     }
 1302:                 } # End of foreach my $option
 1303:             }
 1304:         } # End of foreach my $foilid
 1305:     } # End of concept loops
 1306:     # 
 1307:     # Build a table for the plots
 1308:     my $analysis_html = "<br /><table>\n";
 1309:     my $optionkey = &build_option_index($ORdata);
 1310:     my $num_concepts = 1;
 1311:     if (defined($Concepts)) { $num_concepts = scalar(@$Concepts); }
 1312:     #
 1313:     for (my $try=$mintries;$try<=$maxtries;$try++) {
 1314:         if (! defined($response_data{'_total'}->[$try]) ||
 1315:             $response_data{'_total'}->[$try] == 0) { 
 1316:             if ($try > 1) {
 1317:                 $analysis_html.= '<tr><td align="center" colspan="4"><b>'.
 1318:                     &mt('None of the selected students attempted the problem more than [_1] times.',$try-1).
 1319:                     '</b></td></tr>';
 1320:             } else {
 1321:                 $analysis_html.= '<tr><td colspan="4" align="center"><b>'.
 1322:                     &mt('None of the selected students have attempted the problem').'</b></td></tr>';
 1323:             }
 1324:             last;
 1325:         }
 1326:         my $concept_graph='';
 1327:         if ($num_concepts > 1) {
 1328:             #
 1329:             # Create concept plot
 1330:             my @concept_plot_data;
 1331:             for (my $j=0;$j<=$#concept_data;$j++) {
 1332:                 my $total = $concept_data[$j]->[$try]->{'_total'};
 1333:                 if ($total == 0) {
 1334:                     $concept_plot_data[$j] = 0;
 1335:                 } else {
 1336:                     $concept_plot_data[$j] = 100 * 
 1337:                         sprintf('%0.3f',
 1338:                                 $concept_data[$j]->[$try]->{'_correct'} / 
 1339:                                 $total);
 1340:                 }
 1341:             }
 1342:             #
 1343:             $concept_graph = &Apache::loncommon::DrawBarGraph
 1344:                 ('Correct Concepts','Concept Number','Percent Correct',
 1345:                  100,$plotcolors,undef,\@concept_plot_data,{xskip=>1});
 1346:         }
 1347:         #
 1348:         # Create Foil Plots
 1349:         my $data_count = $response_data{'_total'}->[$try];
 1350:         my $correct = $response_data{'_correct'}->[$try];
 1351:         $correct |= 0;
 1352:         my @Datasets;
 1353:         foreach my $option ('_correct',@{$ORdata->{'_Options'}}) {
 1354:             next if (! exists($foil_plot[$try]->{$option}));
 1355:             push(@Datasets,$foil_plot[$try]->{$option});
 1356:         }
 1357:         #
 1358:         # Put a blank in the data set between concepts
 1359:         for (my $set =0;$set<=$#Datasets;$set++) {
 1360:             my @Data = @{$Datasets[$set]};
 1361:             my $idx = 0;
 1362:             foreach my $concept (@{$Concepts}) {
 1363:                 foreach my $foilid (@{$concept->{'foils'}}) {
 1364:                     $Datasets[$set]->[$idx++]=shift(@Data);
 1365:                 }
 1366:                 if ($concept->{'name'} ne $Concepts->[-1]->{'name'}) {
 1367:                     $Datasets[$set]->[$idx++] = 0;
 1368:                 }
 1369:             }
 1370:         }
 1371:         #
 1372:         # Set up the labels needed for the bar graph
 1373:         my @Labels;
 1374:         my $idx = 1;
 1375:         foreach my $concept (@{$Concepts}) {
 1376:             foreach my $foilid (@{$concept->{'foils'}}) {
 1377:                 push(@Labels,$idx++);
 1378:             }
 1379:             push(@Labels,'');
 1380:         }
 1381:         #
 1382:         my $correct_graph = &Apache::loncommon::DrawBarGraph
 1383:             ('Correct Statements','Statement','% Answered Correct',
 1384:              100,$plotcolors,\@Labels,$Datasets[0],{xskip=>1});
 1385:         
 1386:         #
 1387:         #
 1388:         next if (! defined($Datasets[0]));
 1389:         for (my $i=0; $i< scalar(@{$Datasets[0]});$i++) {
 1390:             $Datasets[0]->[$i]=0;
 1391:         }
 1392:         my $count = $response_data{'_total'}->[$try] - 
 1393:                                            $response_data{'_correct'}->[$try];
 1394:         my $incorrect_graph = &Apache::loncommon::DrawBarGraph
 1395:             ('Incorrect Statements','Statement','% Chosen Incorrectly',
 1396:              100,$plotcolors,\@Labels,@Datasets,{xskip=>1});
 1397:         $analysis_html.= 
 1398:             '<tr><td colspan="4" align="center">'.
 1399:             '<font size="+1">'.
 1400:             &mt('Attempt [_1], [_2] submissions, [_3] correct, [_4] incorrect',
 1401:                 $try,$data_count,$correct,$data_count-$correct).
 1402:             '</font>'.'</td></tr>'.$/.                
 1403:             '<tr>'.
 1404:             '<td>'.$concept_graph.'</td>'.
 1405:             '<td>'.$correct_graph.'</td>'.
 1406:             '<td>'.$incorrect_graph.'</td>'.
 1407:             '<td>'.$optionkey.'<td>'.
 1408:             '</tr>'.$/;
 1409:     }
 1410:     $analysis_html .= "</table>\n";
 1411:     $table .= $analysis_html;
 1412:     return $table;
 1413: }
 1414: 
 1415: sub OR_analyze_by_tries {
 1416:     my ($r,$PerformanceData,$mintries,$maxtries) = @_;
 1417:     my %Trydata;
 1418:     $mintries = 1         if (! defined($mintries) || $mintries < 1);
 1419:     $maxtries = $mintries if (! defined($maxtries) || $maxtries < $mintries);
 1420:     my @students;
 1421:     foreach my $row (@$PerformanceData) {
 1422:         next if (! defined($row));
 1423:         my $tries = &get_tries_from_row($row);
 1424:         my %Row   = &Process_OR_Row($row);
 1425:         next if (! %Row);
 1426:         my $student_id = $row->[&Apache::loncoursedata::RD_student_id()];
 1427:         $students[$tries]->{$student_id}++;
 1428:         while (my ($foilid,$href) = each(%Row)) {
 1429:             if (! ref($href)) { 
 1430:                 $Trydata{$foilid}->[$tries] += $href;
 1431:                 next;
 1432:             }
 1433:             while (my ($option,$value) = each(%$href)) {
 1434:                 $Trydata{$foilid}->[$tries]->{$option}+=$value;
 1435:             }
 1436:         }
 1437:     }
 1438:     for (my $try=$mintries;$try<=$maxtries;$try++) {
 1439:         $Trydata{'_studentcount'}->[$try] = scalar(keys(%{$students[$try]}));
 1440:     }
 1441:     return %Trydata;
 1442: }
 1443: 
 1444: #########################################################
 1445: #
 1446: #     Option Response: Time Analysis
 1447: #
 1448: #########################################################
 1449: sub OR_time_analysis {
 1450:     my ($performance_data,$ORdata) = @_;
 1451:     my ($table,$Foils,$Concepts) = &build_foil_index($ORdata);
 1452:     my $foilkey = &build_option_index($ORdata);
 1453:     my $num_concepts = 1;
 1454:     if (defined($Concepts)) { $num_concepts = scalar(@$Concepts); }
 1455:     #
 1456:     if ($num_concepts < 2) {
 1457:         $table = '<h3>'.
 1458:             &mt('Not enough data for concept analysis.  '.
 1459:                 'Performing Foil Analysis').
 1460:                 '</h3>'.$table;
 1461:     }
 1462:     #
 1463:     my $num_plots = $env{'form.NumPlots'};
 1464:     my $num_data = scalar(@$performance_data)-1;
 1465:     #
 1466:     my $current_index;
 1467:     $table .= "<table>\n";
 1468:     for (my $i=0;$i<$num_plots;$i++) {
 1469:         ##
 1470:         my $starttime = &Apache::lonhtmlcommon::get_date_from_form
 1471:             ('startdate_'.$i);
 1472:         my $endtime = &Apache::lonhtmlcommon::get_date_from_form
 1473:             ('enddate_'.$i);
 1474:         if (! defined($starttime) || ! defined($endtime)) {
 1475:             my $sec_in_day = 86400;
 1476:             my $last_sub_time = &get_time_from_row($performance_data->[-1]);
 1477:             my ($sday,$smon,$syear) = 
 1478:                 (localtime($last_sub_time - $sec_in_day*$i))[3..5];
 1479:             $starttime = &Time::Local::timelocal(0,0,0,$sday,$smon,$syear);
 1480:             $endtime = $starttime + $sec_in_day;
 1481:             if ($i == ($num_plots -1 )) {
 1482:                 $starttime = &get_time_from_row($performance_data->[0]);
 1483:             }
 1484:         }
 1485:         $table .= '<tr><td colspan="4" align="center"><font size="+1">'.
 1486:             &mt('Data from [_1] to [_2]',
 1487:                 &Apache::lonlocal::locallocaltime($starttime),
 1488:                 &Apache::lonlocal::locallocaltime($endtime)).
 1489:                 '</font></td></tr>'.$/;
 1490:         my $startdateform = &Apache::lonhtmlcommon::date_setter
 1491:             ('Statistics','startdate_'.$i,$starttime);
 1492:         my $enddateform = &Apache::lonhtmlcommon::date_setter
 1493:             ('Statistics','enddate_'.$i,$endtime);
 1494:         #
 1495:         my $begin_index;
 1496:         my $end_index;
 1497:         my $j;
 1498:         while (++$j < scalar(@$performance_data)) {
 1499:             last if (&get_time_from_row($performance_data->[$j]) 
 1500:                                                               > $starttime);
 1501:         }
 1502:         $begin_index = $j;
 1503:         while ($j < scalar(@$performance_data)) {
 1504:             if (&get_time_from_row($performance_data->[$j]) > $endtime) {
 1505:                 last;
 1506:             } else {
 1507:                 $j++;
 1508:             }
 1509:         }
 1510:         $end_index = $j;
 1511:         ##
 1512:         my ($processed_time_data,$correct,$data_count,$student_count) =
 1513:             &OR_time_process_data($performance_data,$begin_index,$end_index);
 1514:         $correct |= 0;
 1515:         ##
 1516:         $table .= '<tr><td colspan="4" align="center"><font size="+1">'.
 1517:             &mt('[_1] submissions from [_2] students, [_3] correct, [_4] incorrect',
 1518:                 $data_count,$student_count,$correct,$data_count-$correct).
 1519:                 '</font></td></tr>'.$/;
 1520:         my $concept_correct_plot = '';
 1521:         if ($num_concepts > 1) {
 1522:             $concept_correct_plot = 
 1523:                 &OR_Concept_Time_Analysis($processed_time_data,
 1524:                                           $correct,$data_count,$student_count,
 1525:                                           $ORdata,$Concepts);
 1526:         }
 1527:         my ($foil_correct_plot,$foil_incorrect_plot) = 
 1528:             &OR_Foil_Time_Analysis($processed_time_data,
 1529:                                    $correct,$data_count,$student_count,
 1530:                                    $ORdata,$Foils,$Concepts);
 1531:         $table .= '<tr>'.
 1532:             '<td>'.$concept_correct_plot.'</td>'.
 1533:             '<td>'.$foil_correct_plot.'</td>'.
 1534:             '<td>'.$foil_incorrect_plot.'</td>'.
 1535:             '<td align="left" valign="top">'.$foilkey.'</td></tr>'.$/;
 1536:         $table .= '<tr><td colspan="4" align="center">'.
 1537:             &mt('Start time: [_1]',$startdateform).'<br />'.
 1538:             &mt('End time: [_1]',$enddateform).'</td></tr>'.$/;
 1539:         $table.= '<tr><td colspan="4">&nbsp</td></tr>'.$/;
 1540:     }
 1541:     $table .= '</table>';
 1542:     #
 1543:     return $table;
 1544: }
 1545: 
 1546: sub OR_Foil_Time_Analysis {
 1547:     my ($processed_time_data,$correct,$data_count,$student_count,
 1548:         $ORdata,$Foils,$Concepts) = @_;
 1549:     if ($data_count <= 0) {
 1550:         return ('<h2>'.&mt('There is no data to plot').'</h2>','');
 1551:     }
 1552:     my $analysis_html;
 1553:     my @plotdata;
 1554:     my @labels;
 1555:     foreach my $concept (@{$Concepts}) {
 1556:         foreach my $foil (@{$concept->{'foils'}}) {
 1557:             push(@labels,scalar(@labels)+1);
 1558:             my $total = $processed_time_data->{$foil}->{'_total'};
 1559:             if ($total == 0) {
 1560:                 push(@{$plotdata[0]},0);
 1561:             } else {
 1562:                 push(@{$plotdata[0]},
 1563:                      100 * $processed_time_data->{$foil}->{'_correct'} / $total);
 1564:             }
 1565:             my $total_incorrect = $total - $processed_time_data->{$foil}->{'_correct'};
 1566:             for (my $i=0;$i<scalar(@{$ORdata->{'_Options'}});$i++) {
 1567:                 my $option = $ORdata->{'_Options'}->[$i];
 1568:                 if ($total_incorrect == 0) {
 1569:                     push(@{$plotdata[$i+1]},0);
 1570:                 } else {
 1571:                     push(@{$plotdata[$i+1]},
 1572:                          100 * $processed_time_data->{$foil}->{$option} / $total_incorrect);
 1573:                 }
 1574:             }
 1575:         }
 1576:         # Put in a blank one
 1577:         push(@labels,'');
 1578:         push(@{$plotdata[0]},0);
 1579:         for (my $i=0;$i<scalar(@{$ORdata->{'_Options'}});$i++) {
 1580:             push(@{$plotdata[$i+1]},0);
 1581:         }
 1582:     }
 1583:     #
 1584:     # Create the plot
 1585:     my $correct_plot = &Apache::loncommon::DrawBarGraph('Correct Statements',
 1586:                                                         'Statement Number',
 1587:                                                         'Percent Correct',
 1588:                                                         100,
 1589:                                                         $plotcolors,
 1590:                                                         undef,
 1591:                                                         $plotdata[0],
 1592:                                                         {xskip=>1});
 1593:     for (my $j=0; $j< scalar(@{$plotdata[0]});$j++) {
 1594:         $plotdata[0]->[$j]=0;
 1595:     }
 1596:     my $incorrect_plot = 
 1597:         &Apache::loncommon::DrawBarGraph('Incorrect Statements',
 1598:                                          'Statement Number',
 1599:                                          'Incorrect Option Choice',
 1600:                                          100,
 1601:                                          $plotcolors,
 1602:                                          undef,
 1603:                                          @plotdata,{xskip=>1});
 1604:     return ($correct_plot,$incorrect_plot);
 1605: }
 1606: 
 1607: sub OR_Concept_Time_Analysis {
 1608:     my ($processed_time_data,$correct,$data_count,$student_count,
 1609:         $ORdata,$Concepts) = @_;
 1610:     return '' if ($data_count == 0);
 1611:     #
 1612:     # Put the data in plottable form
 1613:     my @plotdata;
 1614:     foreach my $concept (@$Concepts) {
 1615:         my ($total,$correct);
 1616:         foreach my $foil (@{$concept->{'foils'}}) {
 1617:             $total += $processed_time_data->{$foil}->{'_total'};
 1618:             $correct += $processed_time_data->{$foil}->{'_correct'};
 1619:         }
 1620:         if ($total == 0) {
 1621:             push(@plotdata,0);
 1622:         } else {
 1623:             push(@plotdata,100 * $correct / $total);
 1624:         }
 1625:     }
 1626:     #
 1627:     # Create the plot
 1628:     return &Apache::loncommon::DrawBarGraph('Correct Concepts',
 1629:                                             'Concept Number',
 1630:                                             'Percent Correct',
 1631:                                             100,
 1632:                                             $plotcolors,
 1633:                                             undef,
 1634:                                             \@plotdata,{xskip=>1});
 1635: }
 1636: 
 1637: sub OR_time_process_data {
 1638:     my ($performance_data,$begin_index,$end_index)=@_;
 1639:     my %processed_time_data;
 1640:     my %distinct_students;
 1641:     my ($correct,$data_count);
 1642:     if (($begin_index == $end_index) && 
 1643:         ($end_index != scalar(@$performance_data)-1)) { 
 1644:         return undef;
 1645:     }
 1646:     # Be sure we include the last one if we are asked for it.
 1647:     # That we have to correct here (and not when $end_index is 
 1648:     # given a value) should probably be considered a bug.
 1649:     if ($end_index == scalar(@$performance_data)-1) {
 1650:         $end_index++;
 1651:     }
 1652:     my $count;
 1653:     for (my $i=$begin_index;$i<$end_index;$i++) {
 1654:         my $attempt = $performance_data->[$i];
 1655:         $count++;
 1656:         next if (! defined($attempt));
 1657:         my %attempt = &Process_OR_Row($attempt);
 1658:         $data_count++;
 1659:         $correct += $attempt{'_correct'};
 1660:         $distinct_students{$attempt->[&Apache::loncoursedata::RD_student_id()]}++;
 1661:         while (my ($foilid,$href) = each(%attempt)) {
 1662:             if (! ref($href)) {
 1663:                 $processed_time_data{$foilid} += $href;
 1664:                 next;
 1665:             }
 1666:             while (my ($option,$value) = each(%$href)) {
 1667:                 $processed_time_data{$foilid}->{$option}+=$value;
 1668:             }
 1669:         }
 1670:     }
 1671:     return (\%processed_time_data,$correct,$data_count,
 1672:             scalar(keys(%distinct_students)));
 1673: }
 1674: 
 1675: sub build_foil_index {
 1676:     my ($ORdata) = @_;
 1677:     return if (! exists($ORdata->{'_Foils'}));
 1678:     my %Foildata = %{$ORdata->{'_Foils'}};
 1679:     my @Foils = sort(keys(%Foildata));
 1680:     my %Concepts;
 1681:     foreach my $foilid (@Foils) {
 1682:         push(@{$Concepts{$Foildata{$foilid}->{'_Concept'}}},
 1683:              $foilid);
 1684:     }
 1685:     undef(@Foils);
 1686:     # Having gathered the concept information in a hash, we now translate it
 1687:     # into an array because we need to be consistent about order.
 1688:     # Also put the foils in order, too.
 1689:     my $sortfunction = sub {
 1690:         my %Numbers = (one   => 1,
 1691:                        two   => 2,
 1692:                        three => 3,
 1693:                        four  => 4,
 1694:                        five  => 5,
 1695:                        six   => 6,
 1696:                        seven => 7,
 1697:                        eight => 8,
 1698:                        nine  => 9,
 1699:                        ten   => 10,);
 1700:         my $a1 = lc($a); 
 1701:         my $b1 = lc($b);
 1702:         if (exists($Numbers{$a1})) {
 1703:             $a1 = $Numbers{$a1};
 1704:         }
 1705:         if (exists($Numbers{$b1})) {
 1706:             $b1 = $Numbers{$b1};
 1707:         }
 1708:         if (($a1 =~/^\d+$/) && ($b1 =~/^\d+$/)) {
 1709:             return $a1 <=> $b1;
 1710:         } else {
 1711:             return $a1 cmp $b1;
 1712:         }
 1713:     };
 1714:     my @Concepts;
 1715:     foreach my $concept (sort $sortfunction (keys(%Concepts))) {
 1716:         if (! defined($Concepts{$concept})) {
 1717:             $Concepts{$concept}=[];
 1718: #            next;
 1719:         }
 1720:         push(@Concepts,{ name => $concept,
 1721:                         foils => [@{$Concepts{$concept}}]});
 1722:         push(@Foils,(@{$Concepts{$concept}}));
 1723:     }
 1724:     #
 1725:     # Build up the table of row labels.
 1726:     my $table = '<table border="1" >'."\n";
 1727:     if (@Concepts > 1) {
 1728:         $table .= '<tr>'.
 1729:             '<th>'.&mt('Concept Number').'</th>'.
 1730:             '<th>'.&mt('Concept').'</th>'.
 1731:             '<th>'.&mt('Foil Number').'</th>'.
 1732:             '<th>'.&mt('Foil Name').'</th>'.
 1733:             '<th>'.&mt('Foil Text').'</th>'.
 1734:             '<th>'.&mt('Correct Value').'</th>'.
 1735:             "</tr>\n";
 1736:     } else {
 1737:         $table .= '<tr>'.
 1738:             '<th>'.&mt('Foil Number').'</th>'.
 1739:             '<th>'.&mt('Foil Name').'</th>'.
 1740:             '<th>'.&mt('Foil Text').'</th>'.
 1741:             '<th>'.&mt('Correct Value').'</th>'.
 1742:             "</tr>\n";
 1743:     }        
 1744:     my $conceptindex = 1;
 1745:     my $foilindex = 1;
 1746:     foreach my $concept (@Concepts) {
 1747:         my @FoilsInConcept = @{$concept->{'foils'}};
 1748:         my $firstfoil = shift(@FoilsInConcept);
 1749:         if (@Concepts > 1) {
 1750:             $table .= '<tr>'.
 1751:                 '<td>'.$conceptindex.'</td>'.
 1752:                 '<td>'.&HTML::Entities::encode($concept->{'name'},'<>&"').'</td>'.
 1753:                 '<td>'.$foilindex++.'</td>'.
 1754:                 '<td>'.&HTML::Entities::encode($Foildata{$firstfoil}->{'name'},'<>&"').'</td>'.
 1755:                 '<td>'.$Foildata{$firstfoil}->{'text'}.'</td>'.
 1756:                 '<td>'.&HTML::Entities::encode($Foildata{$firstfoil}->{'value'},'<>&"').'</td>'.
 1757:                 "</tr>\n";
 1758:         } else {
 1759:             $table .= '<tr>'.
 1760:                 '<td>'.$foilindex++.'</td>'.
 1761:                 '<td>'.&HTML::Entities::encode($Foildata{$firstfoil}->{'name'},'<>&"').'</td>'.
 1762:                 '<td>'.$Foildata{$firstfoil}->{'text'}.'</td>'.
 1763:                 '<td>'.&HTML::Entities::encode($Foildata{$firstfoil}->{'value'},'<>&"').'</td>'.
 1764:                 "</tr>\n";
 1765:         }
 1766:         foreach my $foilid (@FoilsInConcept) {
 1767:             if (@Concepts > 1) {
 1768:                 $table .= '<tr>'.
 1769:                     '<td></td>'.
 1770:                     '<td></td>'.
 1771:                     '<td>'.$foilindex.'</td>'.
 1772:                     '<td>'.&HTML::Entities::encode($Foildata{$foilid}->{'name'},'<>&"').'</td>'.
 1773:                     '<td>'.$Foildata{$foilid}->{'text'}.'</td>'.
 1774:                     '<td>'.&HTML::Entities::encode($Foildata{$foilid}->{'value'},'<>&"').'</td>'.
 1775:                     "</tr>\n";
 1776:             } else {
 1777:                 $table .= '<tr>'.
 1778:                     '<td>'.$foilindex.'</td>'.
 1779:                     '<td>'.&HTML::Entities::encode($Foildata{$foilid}->{'name'},'<>&"').'</td>'.
 1780:                     '<td>'.$Foildata{$foilid}->{'text'}.'</td>'.
 1781:                     '<td>'.&HTML::Entities::encode($Foildata{$foilid}->{'value'},'<>&"').'</td>'.
 1782:                     "</tr>\n";
 1783:             }                
 1784:         } continue {
 1785:             $foilindex++;
 1786:         }
 1787:     } continue {
 1788:         $conceptindex++;
 1789:     }
 1790:     $table .= "</table>\n";
 1791:     #
 1792:     # Build option index with color stuff
 1793:     return ($table,\@Foils,\@Concepts);
 1794: }
 1795: 
 1796: sub build_option_index {
 1797:     my ($ORdata)= @_;
 1798:     my $table = "<table>\n";
 1799:     my $optionindex = 0;
 1800:     my @Rows;
 1801:     foreach my $option (&mt('correct option chosen'),@{$ORdata->{'_Options'}}) {
 1802:         my $color = $plotcolors->[$optionindex++];
 1803:         push (@Rows,
 1804:               '<tr>'.
 1805:               '<td bgcolor="'.$color.'">'.
 1806:               '<font color="'.$color.'">'.('*'x3).'</font>'.'</td>'.
 1807:               '<td>'.&HTML::Entities::encode($option,'<>&"').'</td>'.
 1808:               "</tr>\n");
 1809:     }
 1810:     shift(@Rows); # Throw away 'correct option chosen' color
 1811:     $table .= join('',reverse(@Rows));
 1812:     $table .= "</table>\n";
 1813: }
 1814: 
 1815: sub build_foil_key {
 1816:     my ($foils,$extra_data)= @_;
 1817:     if (! defined($extra_data)) { $extra_data = {}; }
 1818:     my $table = "<table>\n";
 1819:     my $foil_index = 0;
 1820:     my @rows;
 1821:     foreach my $foil (&mt('correct foil chosen'),@{$foils}) {
 1822:         my $color = $plotcolors->[$foil_index++];
 1823:         push (@rows,
 1824:               '<tr>'.
 1825:               '<td bgcolor="'.$color.'" class="key">'.
 1826:               '<font color="'.$color.'">'.('*'x4).'</font></td>'.
 1827:               '<td>'.&HTML::Entities::encode($foil,'<>&"').
 1828:               ('&nbsp;'x2).$extra_data->{$foil}.'</td>'.
 1829:               "</tr>\n");
 1830:     }
 1831:     shift(@rows); # Throw away 'correct foil chosen' color
 1832:     $table .= join('',reverse(@rows));
 1833:     $table .= "</table>\n";
 1834: }
 1835: 
 1836: #########################################################
 1837: #########################################################
 1838: ##
 1839: ##   Generic Interface Routines
 1840: ##
 1841: #########################################################
 1842: #########################################################
 1843: sub CreateInterface {
 1844:     ##
 1845:     ## Environment variable initialization
 1846:     if (! exists($env{'form.AnalyzeOver'})) {
 1847:         $env{'form.AnalyzeOver'} = 'tries';
 1848:     }
 1849:     ##
 1850:     ## Build the menu
 1851:     my $Str = '';
 1852:     $Str .= &Apache::lonhtmlcommon::breadcrumbs('Detailed Problem Analysis');
 1853:     $Str .= '<table cellspacing="5">'."\n";
 1854:     $Str .= '<tr>';
 1855:     $Str .= '<td align="center"><b>'.&mt('Sections').'</b></td>';
 1856:     $Str .= '<td align="center"><b>'.&mt('Groups').'</b></td>';
 1857:     $Str .= '<td align="center"><b>'.&mt('Access Status').'</b></td>';
 1858:     $Str .= '<td align="center">&nbsp;</td>';
 1859:     $Str .= '</tr>'."\n";
 1860:     ##
 1861:     ## 
 1862:     $Str .= '<tr><td align="center">'."\n";
 1863:     $Str .= &Apache::lonstatistics::SectionSelect('Section','multiple',5);
 1864:     $Str .= '</td>';
 1865:     #
 1866:     $Str .= '<td align="center">'."\n";
 1867:     $Str .= &Apache::lonstatistics::GroupSelect('Group','multiple',5);
 1868:     $Str .= '</td>';
 1869:     #
 1870:     $Str .= '<td align="center">';
 1871:     $Str .= &Apache::lonhtmlcommon::StatusOptions(undef,undef,5);
 1872:     $Str .= '</td>';
 1873:     #
 1874:     ##
 1875:     ##
 1876:     $Str .= '<td>';
 1877:     ##
 1878:     my $showprob_checkbox = 
 1879:         '<input type="checkbox" name="show_prob" value="true" ';
 1880:     if ($env{'form.show_prob'} eq 'true') {
 1881:         $showprob_checkbox .= 'checked ';
 1882:     }
 1883:     $showprob_checkbox.= ' />';
 1884:     $Str.= '<nobr><label>'.
 1885:         &mt('Show problem [_1]',$showprob_checkbox).
 1886:         '</label></nobr><br />';
 1887:     ##
 1888:     my $analyze_selector = '<select name="AnalyzeOver" >';
 1889:     $analyze_selector .= '<option value="tries" ';
 1890:     if (! exists($env{'form.AnalyzeOver'}) || 
 1891:         $env{'form.AnalyzeOver'} eq 'tries'){
 1892:         # Default to tries
 1893:         $analyze_selector .= ' selected ';
 1894:     }
 1895:     $analyze_selector .= '>'.&mt('Tries').'</option>';
 1896:     $analyze_selector .= '<option value="time" ';
 1897:     $analyze_selector .= ' selected ' if ($env{'form.AnalyzeOver'} eq 'time');
 1898:     $analyze_selector .= '>'.&mt('Time').'</option>';
 1899:     $analyze_selector .= '</select>';
 1900:     $Str .= '<nobr><label>'.
 1901:         &mt('Analyze Over [_1] [_2]',
 1902:             $analyze_selector,
 1903:             &Apache::loncommon::help_open_topic('Analysis_Analyze_Over')).
 1904:             '</label></nobr><br />'.$/;
 1905:     ##
 1906:     my $numplots_selector = '<select name="NumPlots">';
 1907:     if (! exists($env{'form.NumPlots'}) 
 1908:         || $env{'form.NumPlots'} < 1 
 1909:         || $env{'form.NumPlots'} > 20) {
 1910:         $env{'form.NumPlots'} = 5;
 1911:     }
 1912:     foreach my $i (1,2,3,4,5,6,7,8,10,15,20) {
 1913:         $numplots_selector .= '<option value="'.$i.'" ';
 1914:         if ($env{'form.NumPlots'} == $i) { $numplots_selector.=' selected '; }
 1915:         $numplots_selector .= '>'.$i.'</option>';
 1916:     }
 1917:     $numplots_selector .= '</select></nobr><br />';
 1918:     $Str .= '<nobr><label>'.&mt('Number of Plots [_1]',$numplots_selector).
 1919:         '</label></nobr>';
 1920:     ##
 1921:     $Str .= '<nobr><label>'.&mt('Status: [_1]',
 1922:                                  '<input type="text" '.
 1923:                                  'name="stats_status" size="60" value="" />'
 1924:                                  ).
 1925:                     '</label></nobr>';
 1926:     $Str .= '</td>';
 1927:     ##
 1928:     ##
 1929:     $Str .= '</tr>'."\n";
 1930:     $Str .= '</table>'."\n";
 1931:     return $Str;
 1932: }
 1933: 
 1934: #########################################################
 1935: #########################################################
 1936: ##
 1937: ##              Misc Option Response functions
 1938: ##
 1939: #########################################################
 1940: #########################################################
 1941: sub get_time_from_row {
 1942:     my ($row) = @_;
 1943:     if (ref($row)) {
 1944:         return $row->[&Apache::loncoursedata::RD_timestamp()];
 1945:     } 
 1946:     return undef;
 1947: }
 1948: 
 1949: sub get_tries_from_row {
 1950:     my ($row) = @_;
 1951:     if (ref($row)) {
 1952:         return $row->[&Apache::loncoursedata::RD_tries()];
 1953:     }
 1954:     return undef;
 1955: }
 1956: 
 1957: sub hashify_attempt {
 1958:     my ($row) = @_;
 1959:     my %attempt;
 1960:     $attempt{'student'}    = $row->[&Apache::loncoursedata::RD_sname()];
 1961:     $attempt{'tries'}      = $row->[&Apache::loncoursedata::RD_tries()];
 1962:     $attempt{'submission'} = &unescape($row->[&Apache::loncoursedata::RD_submission()]);
 1963:     $attempt{'award'}      = $row->[&Apache::loncoursedata::RD_awarddetail()];
 1964:     $attempt{'timestamp'}  = $row->[&Apache::loncoursedata::RD_timestamp()];
 1965:     return %attempt;
 1966: }
 1967: 
 1968: sub Process_OR_Row {
 1969:     my ($row) = @_;
 1970:     my %RowData;
 1971: #    my $student_id = $row->[&Apache::loncoursedata::RD_student_id()];
 1972:     my $award      = $row->[&Apache::loncoursedata::RD_awarddetail()];
 1973:     my $grading    = $row->[&Apache::loncoursedata::RD_response_eval()];
 1974:     my $submission = $row->[&Apache::loncoursedata::RD_submission()];
 1975:     my $time       = $row->[&Apache::loncoursedata::RD_timestamp()];
 1976: #    my $tries      = $row->[&Apache::loncoursedata::RD_tries()];
 1977:     return undef if ($award eq 'MISSING_ANSWER');
 1978:     if (&submission_is_correct($award)) {
 1979:         $RowData{'_correct'} = 1;
 1980:     }
 1981:     $RowData{'_total'} = 1;
 1982:     my @Foilgrades = split('&',$grading);
 1983:     my @Foilsubs   = split('&',$submission);
 1984:     for (my $j=0;$j<=$#Foilgrades;$j++) {
 1985:         my ($foilid,$correct)  = split('=',$Foilgrades[$j]);
 1986:         $foilid = &unescape($foilid);
 1987:         my (undef,$submission) = split('=',$Foilsubs[$j]);
 1988:         if ($correct) {
 1989:             $RowData{$foilid}->{'_correct'}++;
 1990:         } else {
 1991:             $submission = &unescape($submission);
 1992:             $RowData{$foilid}->{$submission}++;
 1993:         }
 1994:         $RowData{$foilid}->{'_total'}++;
 1995:     }
 1996:     return %RowData;
 1997: }
 1998: 
 1999: sub submission_is_correct {
 2000:     my ($award) = @_;
 2001:     if ($award =~ /(APPROX_ANS|EXACT_ANS)/) {
 2002:         return 1;
 2003:     } else {
 2004:         return 0;
 2005:     }
 2006: }
 2007: 
 2008: 1;
 2009: 
 2010: __END__

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