File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.104: download - view: text, annotated - select for diffs
Wed Nov 10 21:23:10 2004 UTC (19 years, 7 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Finished time analysis for numerical responses.  Things seem to work but I
am seeing strange results.

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

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