File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.112: download - view: text, annotated - select for diffs
Tue Feb 22 04:32:46 2005 UTC (19 years, 4 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
half way through rewrite of numerical response analysis.
Added progress window to student answer computation.
&numerical_plot_percent is mostly done.
&numerical_classify_response gathers more statistics and passes them back
    in a seperate hash.
Minor code cleanups elsewhere.

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

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