File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.84: download - view: text, annotated - select for diffs
Thu Apr 1 15:32:06 2004 UTC (20 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- missed and encode fixup

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: lonproblemanalysis.pm,v 1.84 2004/04/01 15:32:06 albertel Exp $
    4: #
    5: # Copyright Michigan State University Board of Trustees
    6: #
    7: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    8: #
    9: # LON-CAPA is free software; you can redistribute it and/or modify
   10: # it under the terms of the GNU General Public License as published by
   11: # the Free Software Foundation; either version 2 of the License, or
   12: # (at your option) any later version.
   13: #
   14: # LON-CAPA is distributed in the hope that it will be useful,
   15: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   16: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   17: # GNU General Public License for more details.
   18: #
   19: # You should have received a copy of the GNU General Public License
   20: # along with LON-CAPA; if not, write to the Free Software
   21: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   22: #
   23: # /home/httpd/html/adm/gpl.txt
   24: #
   25: # http://www.lon-capa.org/
   26: #
   27: package Apache::lonproblemanalysis;
   28: 
   29: use strict;
   30: use Apache::lonnet();
   31: use Apache::loncommon();
   32: use Apache::lonhtmlcommon();
   33: use Apache::loncoursedata();
   34: use Apache::lonstatistics;
   35: use Apache::lonlocal;
   36: use Apache::lonstathelpers();
   37: use Apache::lonstudentsubmissions();
   38: use HTML::Entities();
   39: use Time::Local();
   40: use 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 => 'ClearCache',
   55:                        text => 'Clear Caches' },
   56:                      { name => 'updatecaches',
   57:                        text => 'Update Student Data' },
   58:                      { name => 'SelectAnother',
   59:                        text => 'Choose a different Problem' },
   60:                      { name => 'ExcelOutput',
   61:                        text => 'Produce Excel Output' });
   62: 
   63: 
   64: sub BuildProblemAnalysisPage {
   65:     my ($r,$c)=@_;
   66:     #
   67:     my %Saveable_Parameters = ('Status' => 'scalar',
   68:                                'Section' => 'array',
   69:                                'NumPlots' => 'scalar',
   70:                                'AnalyzeAs' => 'scalar',
   71:                                'AnalyzeOver' => 'scalar',
   72:                                );
   73:     &Apache::loncommon::store_course_settings('problem_analysis',
   74:                                               \%Saveable_Parameters);
   75:     &Apache::loncommon::restore_course_settings('problem_analysis',
   76:                                                 \%Saveable_Parameters);
   77:     #
   78:     &Apache::lonstatistics::PrepareClasslist();
   79:     #
   80:     $r->print(&CreateInterface());
   81:     #
   82:     my @Students = @Apache::lonstatistics::Students;
   83:     #
   84:     if (@Students < 1) {
   85:         $r->print('<h2>There are no students in the sections selected</h2>');
   86:     }
   87:     #
   88:     &Apache::loncoursedata::clear_internal_caches();
   89:     if (exists($ENV{'form.ClearCache'}) || 
   90:         exists($ENV{'form.updatecaches'}) ||
   91:         (exists($ENV{'form.firstanalysis'}) &&
   92:          $ENV{'form.firstanalysis'} ne 'no')) {
   93:         &Apache::lonstatistics::Gather_Full_Student_Data($r);
   94:     }
   95:     if (! exists($ENV{'form.firstanalysis'})) {
   96:         $r->print('<input type="hidden" name="firstanalysis" value="yes" />');
   97:     } else {
   98:         $r->print('<input type="hidden" name="firstanalysis" value="no" />');
   99:     }
  100:     $r->rflush();
  101:     #
  102:     my $problem_types = '(option|radiobutton|numerical)';
  103:     if (exists($ENV{'form.problemchoice'}) && 
  104:         ! exists($ENV{'form.SelectAnother'})) {
  105:         foreach my $button (@SubmitButtons) {
  106:             if ($button->{'name'} eq 'break') {
  107:                 $r->print("<br />\n");
  108:             } else {
  109:                 $r->print('<input type="submit" name="'.$button->{'name'}.'" '.
  110:                           'value="'.&mt($button->{'text'}).'" />');
  111:                 $r->print('&nbsp;'x5);
  112:             }
  113:         }
  114:         #
  115:         $r->print('<hr />');
  116:         $r->rflush();
  117:         #
  118:         # Determine which problem we are to analyze
  119:         my $current_problem = &Apache::lonstathelpers::get_target_from_id
  120:             ($ENV{'form.problemchoice'});
  121:         #
  122:         my ($prev,$curr,$next) = 
  123:             &Apache::lonstathelpers::get_prev_curr_next($current_problem,
  124:                                                         $problem_types,
  125:                                                         'response',
  126:                                                         );
  127:         if (exists($ENV{'form.PrevProblemAnalysis'}) && defined($prev)) {
  128:             $current_problem = $prev;
  129:         } elsif (exists($ENV{'form.NextProblemAnalysis'}) && defined($next)) {
  130:             $current_problem = $next;
  131:         } else {
  132:             $current_problem = $curr;
  133:         }
  134:         #
  135:         # Store the current problem choice and send it out in the form
  136:         $ENV{'form.problemchoice'} = 
  137:             &Apache::lonstathelpers::make_target_id($current_problem);
  138:         $r->print('<input type="hidden" name="problemchoice" value="'.
  139:                   $ENV{'form.problemchoice'}.'" />');
  140:         #
  141:         if (! defined($current_problem->{'resource'})) {
  142:             $r->print('resource is undefined');
  143:         } else {
  144:             my $resource = $current_problem->{'resource'};
  145:             $r->print('<h1>'.$resource->{'title'}.'</h1>');
  146:             $r->print('<h3>'.$resource->{'src'}.'</h3>');
  147:             $r->print(&Apache::lonstathelpers::render_resource($resource));
  148:             $r->rflush();
  149:             my %Data = &Apache::lonstathelpers::get_problem_data
  150:                 ($resource->{'src'});
  151:             my $ProblemData = $Data{$current_problem->{'part'}.
  152:                                     '.'.
  153:                                     $current_problem->{'respid'}};
  154:             if ($current_problem->{'resptype'} eq 'option') {
  155:                 &OptionResponseAnalysis($r,$current_problem,
  156:                                         $ProblemData,
  157:                                         \@Students);
  158:             } elsif ($current_problem->{'resptype'} eq 'radiobutton') {
  159:                 &RadioResponseAnalysis($r,$current_problem,
  160:                                        $ProblemData,
  161:                                        \@Students);
  162:             } elsif ($current_problem->{'resptype'} eq 'numerical') {
  163:                 ## 
  164:                 ## analyze all responses of a problem at once
  165:                 my $res = $current_problem->{'resource'};
  166:                 foreach my $partid (@{$res->{'parts'}}) {
  167:                     $current_problem->{'part'} = $partid;
  168:                     foreach my $respid (@{$res->{'partdata'}->{$partid}->{'ResponseIds'}}) {
  169:                         $current_problem->{'respid'}=$respid;
  170:                         &NumericalResponseAnalysis($r,$current_problem,
  171:                                                    $ProblemData,\@Students);
  172:                     }
  173:                 }
  174:             } else {
  175:                 $r->print('<h2>This analysis is not supported</h2>');
  176:             }
  177:         }
  178:         $r->print('<hr />');
  179:     } else {
  180:         $r->print('<input type="submit" name="ProblemAnalysis" value="'.
  181:                   &mt('Analyze Problem').'" />');
  182:         $r->print('&nbsp;'x5);
  183:         $r->print('<h3>'.&mt('Please select a problem to analyze').'</h3>');
  184:         $r->print(&Apache::lonstathelpers::ProblemSelector
  185:                   ($problem_types));
  186:     }
  187: }
  188: 
  189: 
  190: #########################################################
  191: #########################################################
  192: ##
  193: ##      Numerical Response Routines
  194: ##
  195: #########################################################
  196: #########################################################
  197: sub NumericalResponseAnalysis {
  198:     my ($r,$problem,$ProblemData,$Students) = @_;
  199:     my $c = $r->connection();
  200:     my ($resource,$partid,$respid) = ($problem->{'resource'},
  201:                                       $problem->{'part'},
  202:                                       $problem->{'respid'});
  203:     #
  204:     if (scalar(@{$resource->{'parts'}})>1) {
  205:         if (@{$resource->{'partdata'}->{$partid}->{'ResponseIds'}}>1) {
  206:             $r->print('<h3>'.
  207:                       &mt('Part [_1], response [_2].',$partid,$respid).
  208:                       '</h3>');
  209:         } else { 
  210:             $r->print('<h3>'.
  211:                       &mt('Part [_1]',$partid,$respid).
  212:                       '</h3>');
  213:         }
  214:     } elsif (@{$resource->{'partdata'}->{$partid}->{'ResponseIds'}}>1) {
  215:         $r->print('<h3>'.&mt('Response [_1]',$respid).'</h3>');
  216:     }
  217:     #
  218:     my $analysis_html;
  219:     my $PerformanceData = &Apache::loncoursedata::get_response_data
  220:         (\@Apache::lonstatistics::SelectedSections,
  221:          $Apache::lonstatistics::enrollment_status,
  222:          $resource->{'symb'},$respid);
  223:     if (! defined($PerformanceData) || 
  224:         ref($PerformanceData) ne 'ARRAY' ) {
  225:         $analysis_html = '<h2>'.
  226:             &mt('There is no submission data for this resource').
  227:             '</h2>';
  228:         $r->print($analysis_html);
  229:         return;
  230:     }
  231:     #
  232:     # This next call causes all the waiting around that people complain about
  233:     my ($max,$min) = &Apache::lonstathelpers::GetStudentAnswers($r,$problem,
  234:                                                                 $Students);
  235:     return if ($c->aborted());
  236:     #
  237:     # Collate the data
  238:     my %Data;
  239:     foreach my $student (@$Students) {
  240:         my $answer = $student->{'answer'};
  241:         $Data{$answer}++;
  242:     }
  243:     my @Labels = sort {$a <=> $b } keys(%Data);
  244:     my @PlotData = @Data{@Labels};
  245:     #
  246:     my $width  = 500; 
  247:     my $height = 100;
  248:     my $plot = &one_dimensional_plot($r,500,100,scalar(@$Students),
  249:                                      \@Labels,\@PlotData);
  250:     $r->print($plot);
  251:     return;
  252: }
  253: 
  254: sub one_dimensional_plot {
  255:     my ($r,$width,$height,$N,$Labels,$Data)=@_;
  256:     #
  257:     # Compute data -> image scaling factors
  258:     my $min = $Labels->[0];
  259:     my $max = $Labels->[-1];
  260:     if ($max == $min) {
  261:         $max =$min+1;
  262:     }
  263:     my $h_scale = ($width-10)/($max-$min);
  264:     #
  265:     my $max_y = 0;
  266:     foreach (@$Data) {
  267:         $max_y = $_ if ($max_y < $_);
  268:     }
  269:     my $ticscale = 5;
  270:     if ($max_y * $ticscale > $height/2) {
  271:         $ticscale = int($height/2/$max_y);
  272:         $ticscale = 1 if ($ticscale < 1);
  273:     }
  274:     #
  275:     # Create the plot
  276:     my $plot = 
  277:         qq{<drawimage width="$width" height="$height" bgcolor="transparent" >};
  278:     for (my $idx=0;$idx<scalar(@$Labels);$idx++) {
  279:         my $xloc = 5+$h_scale*($Labels->[$idx] - $min);
  280:         my $top    = $height/2-$Data->[$idx]*$ticscale;
  281:         my $bottom = $height/2+$Data->[$idx]*$ticscale;
  282:         $plot .= 
  283:             &line($xloc,$top,$xloc,$bottom,'888888',1);
  284:     }
  285:     #
  286:     # Put the scale on last to ensure it is on top of the data.
  287:     if ($min < 0 && $max > 0) {
  288:         my $circle_x = 5+$h_scale*abs($min);  # '0' in data coordinates
  289:         my $r = 4;
  290:         $plot .= &line(5,$height/2,$circle_x-$r,$height/2,'000000',1);
  291:         $plot .= &circle($circle_x,$height/2,$r+1,'000000');
  292:         $plot .= &line($circle_x+$r,$height/2,$width-5,$height/2,'000000',1);
  293:     } else {
  294:         $plot .= &line(5,$height/2,$width-5,$height/2,'000000',1);
  295:     }
  296:     $plot .= '</drawimage>';
  297:     my $plotresult =  &Apache::lonxml::xmlparse($r,'web',$plot);
  298:     
  299:     my $title = 'Distribution of correct answers';
  300:     my $result = '<table>'.
  301:         '<tr><td colspan="3" align="center">'.
  302:         '<font size="+2">'.$title.' (N='.$N.')'.
  303:         '</font>'.
  304:         '</td></tr>'.
  305:         '<tr>'.
  306:         '<td valign="center">'.$min.'</td>'.
  307:         '<td>'.$plotresult.'</td>'.
  308:         '<td valign="center">'.$max.'</td>'.
  309:         '</tr>'.
  310:         '<tr><td colspan="3" align="center">'.
  311:         'Maximum Number of Coinciding Values: '.$max_y.
  312:         '</td></tr>'.
  313:         '</table>';
  314:     return $result;
  315: }
  316: 
  317: ##
  318: ## Helper subroutines for <drawimage>.  
  319: ## These should probably go somewhere more suitable soon.
  320: sub line {
  321:     my ($x1,$y1,$x2,$y2,$color,$thickness) = @_;
  322:     return qq{<line x1="$x1" y1="$y1" x2="$x2" y2="$y2" color="$color" thickness="$thickness" />$/};
  323: }
  324: 
  325: sub text {
  326:     my ($x,$y,$color,$text,$font,$direction) = @_;
  327:     if (! defined($font) || $font !~ /^(tiny|small|medium|large|giant)$/) {
  328:         $font = 'medium';
  329:     }
  330:     if (! defined($direction) || $direction ne 'vertical') {
  331:         $direction = '';
  332:     }
  333:     return qq{<text x="$x" y="$y" color="$color" font="$font" direction="$direction" >$text</text>};
  334: }
  335: 
  336: sub rectangle {
  337:     my ($x1,$y1,$x2,$y2,$color,$thickness,$filled) = @_;
  338:     return qq{<rectangle x1="$x1" y1="$y1" x2="$x2" y2="$y2" color="$color" thickness="$thickness" filled="$filled" />};
  339: }
  340: 
  341: sub arc {
  342:     my ($x,$y,$width,$height,$start,$end,$color,$thickness,$filled)=@_;
  343:     return qq{<arc x="$x" y="$y" width="$width" height="$height" start="$start" end="$end" color="$color" thickness="$thickness" filled="$filled" />};
  344: }
  345: 
  346: sub circle {
  347:     my ($x,$y,$radius,$color,$thickness,$filled)=@_;
  348:     return &arc($x,$y,$radius,$radius,0,360,$color,$thickness,$filled);
  349: }
  350: 
  351: sub build_student_data_worksheet {
  352:     my ($workbook,$format) = @_;
  353:     my $rows_output = 3;
  354:     my $cols_output = 0;
  355:     my $worksheet  = $workbook->addworksheet('Student Data');
  356:     $worksheet->write($rows_output++,0,'Student Data',$format->{'h3'});
  357:     my @Headers = ('full name','username','domain','section',
  358:                    "student\nnumber",'identifier');
  359:     $worksheet->write_row($rows_output++,0,\@Headers,$format->{'header'});
  360:     my @Students = @Apache::lonstatistics::Students;
  361:     my $studentrows = &Apache::loncoursedata::get_student_data(\@Students);
  362:     my %ids;
  363:     foreach my $row (@$studentrows) {
  364:         my ($mysqlid,$student) = @$row;
  365:         $ids{$student}=$mysqlid;
  366:     }
  367:     foreach my $student (@Students) {
  368:         my $name_domain = $student->{'username'}.':'.$student->{'domain'};
  369:         $worksheet->write_row($rows_output++,0,
  370:                           [$student->{'fullname'},
  371:                            $student->{'username'},$student->{'domain'},
  372:                            $student->{'section'},$student->{'id'},
  373:                            $ids{$name_domain}]);
  374:     }
  375:     return $worksheet;
  376: }
  377: 
  378: #########################################################
  379: #########################################################
  380: ##
  381: ##      Radio Response Routines
  382: ##
  383: #########################################################
  384: #########################################################
  385: sub RadioResponseAnalysis {
  386:     my ($r,$problem,$ProblemData,$Students) = @_;
  387:     my ($resource,$respid) = ($problem->{'resource'},
  388:                               $problem->{'respid'});
  389:     my $analysis_html;
  390:     my $PerformanceData = &Apache::loncoursedata::get_response_data
  391:         (\@Apache::lonstatistics::SelectedSections,
  392:          $Apache::lonstatistics::enrollment_status,
  393:          $resource->{'symb'},$respid);
  394:     if (! defined($PerformanceData) || 
  395:         ref($PerformanceData) ne 'ARRAY' ) {
  396:         $analysis_html = '<h2>'.
  397:             &mt('There is no submission data for this resource').
  398:             '</h2>';
  399:         $r->print($analysis_html);
  400:         return;
  401:     }
  402:     if (exists($ENV{'form.ExcelOutput'})) {
  403:         $analysis_html .= &RR_Excel_output($r,$problem->{'resource'},
  404:                                            $PerformanceData,$ProblemData);
  405:     } elsif ($ENV{'form.AnalyzeOver'} eq 'Tries') {
  406:         $analysis_html .= &RR_Tries_Analysis($r,$problem->{'resource'},
  407:                                              $PerformanceData,$ProblemData);
  408:     } elsif ($ENV{'form.AnalyzeOver'} eq 'Time') {
  409:         $analysis_html .= &RR_Time_Analysis($r,$problem->{'resource'},
  410:                                             $PerformanceData,$ProblemData);
  411:     } else {
  412:         $analysis_html .= '<h2>'.
  413:            &mt('The analysis you have selected is not supported at this time').
  414:            '</h2>';
  415:     }
  416:     $r->print($analysis_html);
  417: }
  418: 
  419: sub RR_Excel_output   { 
  420:     my ($r,$PerformanceData,$ProblemData) = @_;
  421:     return '<h1>No!</h1>';
  422: }
  423: 
  424: sub RR_Tries_Analysis { 
  425:     my ($r,$resource,$PerformanceData,$ProblemData) = @_;
  426:     my $analysis_html;
  427:     my $mintries = 1;
  428:     my $maxtries = $ENV{'form.NumPlots'};
  429:     my ($table,$Foils,$Concepts) = &build_foil_index($ProblemData);
  430:     if ((! defined($Concepts)) || ((@$Concepts < 2) && 
  431:                                    ($ENV{'form.AnalyzeAs'} ne 'Foils'))) {
  432:         $table = '<h3>'.
  433:             &mt('Not enough data for concept analysis.  '.
  434:                 'Performing Foil Analysis').
  435:             '</h3>'.$table;
  436:         $ENV{'form.AnalyzeAs'} = 'Foils';
  437:     }
  438:     $analysis_html .= $table;
  439:     my @TryData = &RR_tries_data_analysis($r,$PerformanceData);
  440: #    if ($ENV{'form.AnalyzeAs'} eq 'Foils') {
  441:         $analysis_html .= &RR_Tries_Foil_Analysis($mintries,$maxtries,$Foils,
  442:                                                  \@TryData,$ProblemData);
  443: #    } else {
  444: #        $analysis_html = &RR_Tries_Concept_Analysis($mintries,$maxtries,
  445: #                                                    $Concepts,
  446: #                                                    \@TryData,
  447: #                                                    $ProblemData);
  448: #    }
  449:     return $analysis_html;
  450: }
  451: 
  452: sub RR_tries_data_analysis {
  453:     my ($r,$Attempt_data) = @_;
  454:     my @TryData;
  455:     foreach my $attempt (@$Attempt_data) {
  456:         my %Attempt = &hashify_attempt($attempt);
  457:         my ($answer,undef) = split('=',$Attempt{'submission'});
  458:         $TryData[$Attempt{'tries'}]->{$answer}++;
  459:     }
  460:     return @TryData;
  461: }
  462: 
  463: sub RR_Time_Analysis  { 
  464:     my ($r,$PerformanceData,$ProblemData) = @_;
  465:     my $html;
  466:     return $html;
  467: }
  468: 
  469: sub RR_Tries_Foil_Analysis {
  470:     my ($min,$max,$Foils,$TryData,$ProblemData) = @_;
  471:     my $html;
  472:     #
  473:     # Compute the data neccessary to make the plots
  474:     for (my $try=$min;$try<=$max;$try++) {
  475:         my @PlotData_Correct; 
  476:         my @PlotData_Incorrect;
  477:         next if ($try > scalar(@{$TryData}));
  478:         next if (! defined($TryData->[$try]));
  479:         my %DataSet = %{$TryData->[$try]};
  480:         my $total = 0;
  481:         foreach my $foilid (@$Foils) {
  482:             $total += $DataSet{$foilid};
  483:         }
  484:         foreach my $foilid (@$Foils) {
  485:             if ($total == 0) {
  486:                 push (@PlotData_Correct,0);
  487:                 push (@PlotData_Incorrect,0);
  488:             } else {
  489:                 if ($ProblemData->{'_Foils'}->{$foilid}->{'value'} eq 'true') {
  490:                     push (@PlotData_Correct,
  491:                           int(100*$DataSet{$foilid}/$total));
  492:                     push (@PlotData_Incorrect,0);
  493:                 } else {
  494:                     push (@PlotData_Correct,0);
  495:                     push (@PlotData_Incorrect,
  496:                           int(100*$DataSet{$foilid}/$total));
  497:                 }
  498:             }
  499:         }
  500:         my $title='Attempt '.$try;
  501:         my $xlabel = $total.' Submissions';
  502:         $html.=  &Apache::loncommon::DrawBarGraph($title,
  503:                                                   $xlabel,
  504:                                                   'Percent Choosing',
  505:                                                   100,
  506:                                                   ['#33ff00','#ff3300'],
  507:                                                   undef,
  508:                                                   \@PlotData_Correct,
  509:                                                   \@PlotData_Incorrect);
  510:     }
  511:     return $html;
  512: }
  513: 
  514: sub RR_Tries_Concept_Analysis {
  515:     my ($min,$max,$Concepts,$ResponseData,$ProblemData) = @_;
  516:     my $html;
  517:     return $html;
  518: }
  519: 
  520: sub RR_Time_Foil_Analysis {
  521:     my ($min,$max,$Foils,$ResponseData,$ProblemData) = @_;
  522:     my $html;
  523:     return $html;
  524: }
  525: 
  526: sub RR_Time_Concept_Analysis {
  527:     my ($min,$max,$Concepts,$ResponseData,$ProblemData) = @_;
  528:     my $html;
  529:     return $html;
  530: }
  531: 
  532: 
  533: sub get_Radio_problem_data {
  534:     my ($url) = @_;
  535:     my $Answ=&Apache::lonnet::ssi($url,('grade_target' => 'analyze'));
  536:     (my $garbage,$Answ)=split('_HASH_REF__',$Answ,2);
  537:     my %Answer = &Apache::lonnet::str2hash($Answ);
  538:     my %Partdata;
  539:     foreach my $part (@{$Answer{'parts'}}) {
  540:         while (my($key,$value) = each(%Answer)) {
  541: #            if (ref($value) eq 'ARRAY') {
  542: #                &Apache::lonnet::logthis('is ref part:'.$part.' '.$key.'='.join(',',@$value));
  543: #            } else {
  544: #                &Apache::lonnet::logthis('notref part:'.$part.' '.$key.'='.$value);
  545: #            }                
  546:             next if ($key !~ /^$part/);
  547:             $key =~ s/^$part\.//;
  548:             if ($key eq 'foils') {
  549:                 $Partdata{$part}->{'_Foils'}=$value;
  550:             } elsif ($key eq 'options') {
  551:                 $Partdata{$part}->{'_Options'}=$value;
  552:             } elsif ($key eq 'shown') {
  553:                 $Partdata{$part}->{'_Shown'}=$value;
  554:             } elsif ($key =~ /^foil.value.(.*)$/) {
  555:                 $Partdata{$part}->{$1}->{'value'}=$value;
  556:             } elsif ($key =~ /^foil.text.(.*)$/) {
  557:                 $Partdata{$part}->{$1}->{'text'}=$value;
  558:             }
  559:         }
  560:     }
  561:     return %Partdata;
  562: }
  563: 
  564: #########################################################
  565: #########################################################
  566: ##
  567: ##      Option Response Routines
  568: ##
  569: #########################################################
  570: #########################################################
  571: sub OptionResponseAnalysis {
  572:     my ($r,$problem,$ProblemData,$Students) = @_;
  573:     my ($resource,$respid) = ($problem->{'resource'},
  574:                               $problem->{'respid'});
  575:     # Note: part data is not needed.
  576:     my $PerformanceData = &Apache::loncoursedata::get_response_data
  577:         (\@Apache::lonstatistics::SelectedSections,
  578:          $Apache::lonstatistics::enrollment_status,
  579:          $resource->{'symb'},$respid);
  580:     if (! defined($PerformanceData) || 
  581:         ref($PerformanceData) ne 'ARRAY' ) {
  582:         $r->print('<h2>'.
  583:                   &mt('There is no student data for this problem.').
  584:                   '</h2>');
  585:     }  else {
  586:         $r->rflush();
  587:         if (exists($ENV{'form.ExcelOutput'})) {
  588:             my $result = &OR_excel_sheet($r,$resource,
  589:                                          $PerformanceData,
  590:                                          $ProblemData);
  591:             $r->print($result);
  592:             $r->rflush();
  593:         } else {
  594:             if ($ENV{'form.AnalyzeOver'} eq 'Tries') {
  595:                 my $analysis_html = &OR_tries_analysis($r,
  596:                                                     $PerformanceData,
  597:                                                     $ProblemData);
  598:                 $r->print($analysis_html);
  599:                 $r->rflush();
  600:             } elsif ($ENV{'form.AnalyzeOver'} eq 'Time') {
  601:                 my $analysis_html = &OR_time_analysis($PerformanceData,
  602:                                                    $ProblemData);
  603:                 $r->print($analysis_html);
  604:                 $r->rflush();
  605:             } else {
  606:                 $r->print('<h2>'.
  607:                           &mt('The analysis you have selected is '.
  608:                               'not supported at this time').
  609:                           '</h2>');
  610:             }
  611:         }
  612:     }
  613: }
  614: 
  615: #########################################################
  616: #
  617: #       Option Response:  Tries Analysis
  618: #
  619: #########################################################
  620: sub OR_tries_analysis {
  621:     my ($r,$PerformanceData,$ORdata) = @_;
  622:     my $mintries = 1;
  623:     my $maxtries = $ENV{'form.NumPlots'};
  624:     my ($table,$Foils,$Concepts) = &build_foil_index($ORdata);
  625:     if (! defined($Concepts) || 
  626:         ((@$Concepts < 2) && ($ENV{'form.AnalyzeAs'} ne 'Foils'))) {
  627:         $table = '<h3>'.
  628:             &mt('Not enough data for concept analysis.  '.
  629:                 'Performing Foil Analysis').
  630:             '</h3>'.$table;
  631:         $ENV{'form.AnalyzeAs'} = 'Foils';
  632:     }
  633:     my %ResponseData = &OR_analyze_by_tries($r,$PerformanceData,
  634:                                                      $mintries,$maxtries);
  635:     my $analysis = '';
  636:     if ($ENV{'form.AnalyzeAs'} eq 'Foils') {
  637:         $analysis = &OR_Tries_Foil_Analysis($mintries,$maxtries,$Concepts,
  638:                                          \%ResponseData,$ORdata);
  639:     } else {
  640:         $analysis = &OR_Tries_Concept_Analysis($mintries,$maxtries,
  641:                                             $Concepts,\%ResponseData,$ORdata);
  642:     }
  643:     $table .= $analysis;
  644:     return $table;
  645: }
  646: 
  647: sub OR_Tries_Foil_Analysis {
  648:     my ($mintries,$maxtries,$Concepts,$respdat,$ORdata) = @_;
  649:     my %ResponseData = %$respdat;
  650:     #
  651:     # Compute the data neccessary to make the plots
  652:     my @PlotData; 
  653:     foreach my $concept (@$Concepts) {
  654:         foreach my $foilid (@{$concept->{'foils'}}) {
  655:             for (my $try=$mintries;$try<=$maxtries;$try++) {
  656:                 if ($ResponseData{$foilid}->[$try]->{'_total'} == 0) {
  657:                     push(@{$PlotData[$try]->{'_correct'}},0);
  658:                 } else {
  659:                     push(@{$PlotData[$try]->{'_correct'}},
  660:                          100*$ResponseData{$foilid}->[$try]->{'_correct'}/
  661:                          $ResponseData{$foilid}->[$try]->{'_total'});
  662:                 }
  663:                 foreach my $option (@{$ORdata->{'_Options'}}) {
  664:                     push(@{$PlotData[$try]->{'_total'}},
  665:                          $ResponseData{$foilid}->[$try]->{'_total'});
  666:                     if ($ResponseData{$foilid}->[$try]->{'_total'} == 0) {
  667:                         push (@{$PlotData[$try]->{$option}},0);
  668:                     } else {
  669:                         if ($ResponseData{$foilid}->[$try]->{'_total'} ==
  670:                             $ResponseData{$foilid}->[$try]->{'_correct'}) {
  671:                             push(@{$PlotData[$try]->{$option}},0);
  672:                         } else {
  673:                             push (@{$PlotData[$try]->{$option}},
  674:                                   100 * 
  675:                                   $ResponseData{$foilid}->[$try]->{$option} / 
  676:                                   ($ResponseData{$foilid}->[$try]->{'_total'} 
  677:                                    - 
  678:                                    $ResponseData{$foilid}->[$try]->{'_correct'}
  679:                                    ));
  680:                         }
  681:                     }
  682:                 } # End of foreach my $option
  683:             }
  684:         } # End of foreach my $foilid
  685:     } # End of foreach my $concept
  686:     # 
  687:     # Build a table for the plots
  688:     my $analysis_html = "<table>\n";
  689:     my $optionkey = &build_option_index($ORdata);
  690:     for (my $try=$mintries;$try<=$maxtries;$try++) {
  691:         my $count = $ResponseData{'_total'}->[$try];
  692:         my $title = 'Submission '.$try.' (N='.$count.')';
  693:         my @Datasets;
  694:         foreach my $option ('_correct',@{$ORdata->{'_Options'}}) {
  695:             next if (! exists($PlotData[$try]->{$option}));
  696:             push(@Datasets,$PlotData[$try]->{$option});
  697:         }
  698:         #
  699:         # Put a blank in the data set between concepts
  700:         for (my $set =0;$set<=$#Datasets;$set++) {
  701:             my @Data = @{$Datasets[$set]};
  702:             my $idx = 0;
  703:             foreach my $concept (@{$Concepts}) {
  704:                 foreach my $foilid (@{$concept->{'foils'}}) {
  705:                     $Datasets[$set]->[$idx++]=shift(@Data);
  706:                 }
  707:                 if ($concept->{'name'} ne $Concepts->[-1]->{'name'}) {
  708:                     $Datasets[$set]->[$idx++] = 0;
  709:                 }
  710:             }
  711:         }
  712:         #
  713:         # Set up the labels needed for the bar graph
  714:         my @Labels;
  715:         my $idx = 1;
  716:         foreach my $concept (@{$Concepts}) {
  717:             foreach my $foilid (@{$concept->{'foils'}}) {
  718:                 push(@Labels,$idx++);
  719:             }
  720:             push(@Labels,'');
  721:         }
  722:         #
  723:         my $correctgraph = &Apache::loncommon::DrawBarGraph
  724:             ($title,'Foil Number','Percent Correct',
  725:              100,$plotcolors,\@Labels,$Datasets[0]);
  726:         $analysis_html.= '<tr><td>'.$correctgraph.'</td>';
  727:         
  728:         #
  729:         #
  730:         next if (! defined($Datasets[0]));
  731:         for (my $i=0; $i< scalar(@{$Datasets[0]});$i++) {
  732:             $Datasets[0]->[$i]=0;
  733:         }
  734:         $count = $ResponseData{'_total'}->[$try] - 
  735:                                            $ResponseData{'_correct'}->[$try];
  736:         $title = 'Submission '.$try.' (N='.$count.')';
  737:         my $incorrectgraph = &Apache::loncommon::DrawBarGraph
  738:             ($title,'Foil Number','% Option Chosen Incorrectly',
  739:              100,$plotcolors,\@Labels,@Datasets);
  740:         $analysis_html.= '<td>'.$incorrectgraph.'</td>';
  741:         $analysis_html.= '<td>'.$optionkey."<td></tr>\n";
  742:     }
  743:     $analysis_html .= "</table>\n";
  744:     return $analysis_html;
  745: }
  746: 
  747: sub OR_Tries_Concept_Analysis {
  748:     my ($mintries,$maxtries,$Concepts,$respdat,$ORdata) = @_;
  749:     my %ResponseData = %$respdat;
  750:     my $analysis_html = "<table>\n";
  751:     #
  752:     # Compute the data neccessary to make the plots
  753:     my @PlotData;
  754:     # Concept analysis
  755:     #
  756:     # Note: we do not bother with characterizing the students incorrect
  757:     # answers at the concept level because an incorrect answer for one foil
  758:     # may be a correct answer for another foil.
  759:     my %ConceptData;
  760:     foreach my $concept (@{$Concepts}) {
  761:         for (my $i=$mintries;$i<=$maxtries;$i++) {
  762:             #
  763:             # Gather the per-attempt data
  764:             my $cdata = $ConceptData{$concept}->[$i];
  765:             foreach my $foilid (@{$concept->{'foils'}}) {
  766:                 $cdata->{'_correct'} += 
  767:                     $ResponseData{$foilid}->[$i]->{'_correct'};
  768:                 $cdata->{'_total'}   += 
  769:                     $ResponseData{$foilid}->[$i]->{'_total'};
  770:             }
  771:             push (@{$PlotData[$i]->{'_total'}},$cdata->{'_total'});
  772:             if ($cdata->{'_total'} == 0) {
  773:                 push (@{$PlotData[$i]->{'_correct'}},0);
  774:             } else {
  775:                 push (@{$PlotData[$i]->{'_correct'}},
  776:                       100*$cdata->{'_correct'}/$cdata->{'_total'});
  777:                 }
  778:         }
  779:     }
  780:     # Build a table for the plots
  781:     for (my $i=$mintries;$i<=$maxtries;$i++) {
  782:         my $minstu = $PlotData[$i]->{'_total'}->[0];
  783:         my $maxstu = $PlotData[$i]->{'_total'}->[0];
  784:         foreach my $count (@{$PlotData[$i]->{'_total'}}) {
  785:             if ($minstu > $count) {
  786:                 $minstu = $count;
  787:             }
  788:             if ($maxstu < $count) {
  789:                 $maxstu = $count;
  790:             }
  791:         }
  792:         $maxstu = 0 if (! defined($maxstu));
  793:         $minstu = 0 if (! defined($minstu));
  794:         my $title;
  795:         my $count = $ResponseData{'_total'}->[$i];
  796:         if ($count == 0) {
  797:             $count = 'no submissions';
  798:         } elsif ($count == 1) {
  799:             $count = '1 submission';
  800:         } else {
  801:             $count = $count.' submissions';
  802:         }
  803:         $title = 'Attempt '.$i.', '.$count;
  804:         my $graphlink = &Apache::loncommon::DrawBarGraph
  805:             ($title,'Concept Number','Percent Correct',
  806:              100,$plotcolors,undef,$PlotData[$i]->{'_correct'});
  807:         $analysis_html.= '<tr><td>'.$graphlink."</td></tr>\n";
  808:     }
  809:     $analysis_html .= "</table>\n";
  810:     return $analysis_html;
  811: }
  812: 
  813: sub OR_analyze_by_tries {
  814:     my ($r,$PerformanceData,$mintries,$maxtries) = @_;
  815:     my %Trydata;
  816:     $mintries = 1         if (! defined($mintries) || $mintries < 1);
  817:     $maxtries = $mintries if (! defined($maxtries) || $maxtries < $mintries);
  818:     foreach my $row (@$PerformanceData) {
  819:         next if (! defined($row));
  820:         my $tries = &get_tries_from_row($row);
  821:         my %Row   = &Process_OR_Row($row);
  822:         next if (! %Row);
  823:         while (my ($foilid,$href) = each(%Row)) {
  824:             if (! ref($href)) { 
  825:                 $Trydata{$foilid}->[$tries] += $href;
  826:                 next;
  827:             }
  828:             while (my ($option,$value) = each(%$href)) {
  829:                 $Trydata{$foilid}->[$tries]->{$option}+=$value;
  830:             }
  831:         }
  832:     }
  833:     return %Trydata;
  834: }
  835: 
  836: #########################################################
  837: #
  838: #     Option Response: Time Analysis
  839: #
  840: #########################################################
  841: sub OR_time_analysis {
  842:     my ($PerformanceData,$ORdata) = @_;
  843:     my ($table,$Foils,$Concepts) = &build_foil_index($ORdata);
  844:     if ((@$Concepts < 2) && ($ENV{'form.AnalyzeAs'} ne 'Foils')) {
  845:         $table = '<h3>'.
  846:             &mt('Not enough data for concept analysis.  '.
  847:                 'Performing Foil Analysis').
  848:             '</h3>'.$table;
  849:         $ENV{'form.AnalyzeAs'} = 'Foils';
  850:     }
  851:     my $num_plots = $ENV{'form.NumPlots'};
  852:     my $num_data = scalar(@$PerformanceData)-1;
  853:     my $percent = sprintf('%2f',100/$num_plots);
  854:     #
  855:     $table .= "<table>\n";
  856:     for (my $i=0;$i<$num_plots;$i++) {
  857:         ##
  858:         my $starttime = &Apache::lonhtmlcommon::get_date_from_form
  859:             ('startdate_'.$i);
  860:         my $endtime = &Apache::lonhtmlcommon::get_date_from_form
  861:             ('enddate_'.$i);
  862:         if (! defined($starttime) || ! defined($endtime)) {
  863:             my $sec_in_day = 86400;
  864:             my $last_sub_time = &get_time_from_row($PerformanceData->[-1]);
  865:             my ($sday,$smon,$syear);
  866:             (undef,undef,undef,$sday,$smon,$syear) = 
  867:                 localtime($last_sub_time - $sec_in_day*$i);
  868:             $starttime = &Time::Local::timelocal(0,0,0,$sday,$smon,$syear);
  869:             $endtime = $starttime + $sec_in_day;
  870:             if ($i == ($num_plots -1 )) {
  871:                 $starttime = &get_time_from_row($PerformanceData->[0]);
  872:             }
  873:         }
  874:         my $startdateform = &Apache::lonhtmlcommon::date_setter
  875:             ('Statistics','startdate_'.$i,$starttime);
  876:         my $enddateform = &Apache::lonhtmlcommon::date_setter
  877:             ('Statistics','enddate_'.$i,$endtime);
  878:         #
  879:         my $begin_index;
  880:         my $end_index;
  881:         my $j;
  882:         while (++$j < scalar(@$PerformanceData)) {
  883:             last if (&get_time_from_row($PerformanceData->[$j]) 
  884:                                                               > $starttime);
  885:         }
  886:         $begin_index = $j;
  887:         while (++$j < scalar(@$PerformanceData)) {
  888:             last if (&get_time_from_row($PerformanceData->[$j]) > $endtime);
  889:         }
  890:         $end_index = $j;
  891:         ##
  892:         my $interval = {
  893:             begin_index => $begin_index,
  894:             end_index   => $end_index,
  895:             startdateform => $startdateform,
  896:             enddateform   => $enddateform,
  897:         };
  898:         if ($ENV{'form.AnalyzeAs'} eq 'Foils') {
  899:             $table .= &OR_Foil_Time_Analysis($PerformanceData,$ORdata,$Foils,
  900:                                           $interval);
  901:         } else {
  902:             $table .= &OR_Concept_Time_Analysis($PerformanceData,$ORdata,
  903:                                              $Concepts,$interval);
  904:         }
  905:     }
  906:     #
  907:     return $table;
  908: }
  909: 
  910: sub OR_Foil_Time_Analysis {
  911:     my ($PerformanceData,$ORdata,$Foils,$interval) = @_;
  912:     my $analysis_html;
  913:     my $foilkey = &build_option_index($ORdata);
  914:     my ($begin_index,$end_index) = ($interval->{'begin_index'},
  915:                                     $interval->{'end_index'});
  916:     my %TimeData;
  917:     #
  918:     # Compute the number getting the foils correct or incorrects
  919:     for (my $j=$begin_index;$j<=$end_index;$j++) {
  920:         my $row = $PerformanceData->[$j];
  921:         next if (! defined($row));
  922:         my %Row = &Process_OR_Row($row);
  923:         while (my ($foilid,$href) = each(%Row)) {
  924:             if (! ref($href)) {
  925:                 $TimeData{$foilid} += $href;
  926:                 next;
  927:             }
  928:             while (my ($option,$value) = each(%$href)) {
  929:                 $TimeData{$foilid}->{$option}+=$value;
  930:             }
  931:         }
  932:     }
  933:     my @Plotdata;
  934:     foreach my $foil (@$Foils) {
  935:         my $total = $TimeData{$foil}->{'_total'};
  936:         if ($total == 0) {
  937:             push(@{$Plotdata[0]},0);
  938:         } else {
  939:             push(@{$Plotdata[0]},
  940:                  100 * $TimeData{$foil}->{'_correct'} / $total);
  941:         }
  942:         my $total_incorrect = $total - $TimeData{$foil}->{'_correct'};
  943:         my $optionidx = 1;
  944:         foreach my $option (@{$ORdata->{'_Options'}}) {
  945:             if ($total_incorrect == 0) {
  946:                 push(@{$Plotdata[$optionidx]},0);
  947:             } else {
  948:                 push(@{$Plotdata[$optionidx]},
  949:                      100 * $TimeData{$foil}->{$option} / $total_incorrect);
  950:             }
  951:         } continue {
  952:             $optionidx++;
  953:         }
  954:     }
  955:     #
  956:     # Create the plot
  957:     my $count = $end_index-$begin_index;
  958:     my $title;
  959:     if ($count == 0) {
  960:         $title = 'no submissions';
  961:     } elsif ($count == 1) {
  962:         $title = 'one submission';
  963:     } else {
  964:         $title = $count.' submissions';
  965:     }
  966:     my $correctplot = &Apache::loncommon::DrawBarGraph($title,
  967:                                                        'Foil Number',
  968:                                                        'Percent Correct',
  969:                                                        100,
  970:                                                        $plotcolors,
  971:                                                        undef,
  972:                                                        $Plotdata[0]);
  973:     for (my $j=0; $j< scalar(@{$Plotdata[0]});$j++) {
  974:         $Plotdata[0]->[$j]=0;
  975:     }
  976:     $count = $end_index-$begin_index-$TimeData{'_correct'};
  977:     if ($count == 0) {
  978:         $title = 'no submissions';
  979:     } elsif ($count == 1) {
  980:         $title = 'one submission';
  981:     } else {
  982:         $title = $count.' submissions';
  983:     }
  984:     my $incorrectplot = &Apache::loncommon::DrawBarGraph($title,
  985:                                                  'Foil Number',
  986:                                                  'Incorrect Option Choice',
  987:                                                  100,
  988:                                                  $plotcolors,
  989:                                                  undef,
  990:                                                  @Plotdata);        
  991:     $analysis_html.='<tr>'.
  992:         '<td>'.$correctplot.'</td>'.
  993:         '<td>'.$incorrectplot.'</td>'.
  994:         '<td align="left" valign="top">'.$foilkey.'</td>'."</tr>\n";
  995:     $analysis_html.= '<tr>'.'<td colspan="3">'.
  996:         '<b>Start Time</b>:'.
  997:         ' &nbsp;'.$interval->{'startdateform'}.'<br />'.
  998:         '<b>End Time</b>&nbsp;&nbsp;: '.
  999:         '&nbsp;'.$interval->{'enddateform'}.'<br />'.
 1000: #        '<b>Plot Title</b>&nbsp;&nbsp;:'.
 1001: #        ("&nbsp;"x3).$interval->{'titleform'}.
 1002:         '</td>'.
 1003:         "</tr>\n";
 1004:     return $analysis_html;
 1005: }
 1006: 
 1007: sub OR_Concept_Time_Analysis {
 1008:     my ($PerformanceData,$ORdata,$Concepts,$interval) = @_;
 1009:     my $analysis_html;
 1010:     ##
 1011:     ## Determine starttime, endtime, startindex, endindex
 1012:     my ($begin_index,$end_index) = ($interval->{'begin_index'},
 1013:                                     $interval->{'end_index'});
 1014:     my %TimeData;
 1015:     #
 1016:     # Compute the number getting the foils correct or incorrects
 1017:     for (my $j=$begin_index;$j<=$end_index;$j++) {
 1018:         my $row = $PerformanceData->[$j];
 1019:         next if (! defined($row));
 1020:         my %Row = &Process_OR_Row($row);
 1021:         while (my ($foilid,$href) = each(%Row)) {
 1022:             if (! ref($href)) {
 1023:                 $TimeData{$foilid} += $href;
 1024:                 next;
 1025:             }
 1026:             while (my ($option,$value) = each(%$href)) {
 1027:                 $TimeData{$foilid}->{$option}+=$value;
 1028:             }
 1029:         }
 1030:     }
 1031:     #
 1032:     # Put the data in plottable form
 1033:     my @Plotdata;
 1034:     foreach my $concept (@$Concepts) {
 1035:         my ($total,$correct);
 1036:         foreach my $foil (@{$concept->{'foils'}}) {
 1037:             $total += $TimeData{$foil}->{'_total'};
 1038:             $correct += $TimeData{$foil}->{'_correct'};
 1039:         }
 1040:         if ($total == 0) {
 1041:             push(@Plotdata,0);
 1042:         } else {
 1043:             push(@Plotdata,100 * $correct / $total);
 1044:         }
 1045:     }
 1046:     #
 1047:     # Create the plot
 1048:     my $title = ($end_index - $begin_index).' submissions';
 1049:     my $correctplot = &Apache::loncommon::DrawBarGraph($title,
 1050:                                                     'Concept Number',
 1051:                                                     'Percent Correct',
 1052:                                                     100,
 1053:                                                     $plotcolors,
 1054:                                                     undef,
 1055:                                                     \@Plotdata);
 1056:     $analysis_html.='<tr>'.
 1057:         '<td>'.$correctplot.'</td>'.
 1058:         '<td align="left" valign="top">'.
 1059:         '<b>Start Time</b>: &nbsp;'.$interval->{'startdateform'}.'<br />'.
 1060:         '<b>End Time</b>&nbsp;&nbsp;: '.
 1061:            '&nbsp;'.$interval->{'enddateform'}.'<br />'.
 1062: #        '<b>Plot Title</b>&nbsp;&nbsp;:'.("&nbsp;"x3).
 1063: #            $interval->{'titleform'}.
 1064:         '</td>'.
 1065:         "</tr>\n";
 1066:     return $analysis_html;
 1067: }
 1068: 
 1069: #########################################################
 1070: #########################################################
 1071: ##
 1072: ##             Excel output 
 1073: ##
 1074: #########################################################
 1075: #########################################################
 1076: sub OR_excel_sheet {
 1077:     my ($r,$resource,$PerformanceData,$ORdata) = @_;
 1078:     my $response = '';
 1079:     my (undef,$Foils,$Concepts) = &build_foil_index($ORdata);
 1080:     #
 1081:     # Create excel worksheet
 1082:     my $filename = '/prtspool/'.
 1083:         $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
 1084:         time.'_'.rand(1000000000).'.xls';
 1085:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1086:     if (! defined($workbook)) {
 1087:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1088:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1089:                             "This error has been logged.  ".
 1090:                             "Please alert your LON-CAPA administrator").
 1091:                   '</p>');
 1092:         return undef;
 1093:     }
 1094:     #
 1095:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1096:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1097:     #
 1098:     # Create and populate main worksheets
 1099:     my $problem_data_sheet  = $workbook->addworksheet('Problem Data');
 1100:     my $student_data_sheet = &build_student_data_worksheet($workbook,$format);
 1101:     my $response_data_sheet = $workbook->addworksheet('Response Data');
 1102:     foreach my $sheet ($problem_data_sheet,$student_data_sheet,
 1103:                        $response_data_sheet) {
 1104:         $sheet->write(0,0,$resource->{'title'},$format->{'h2'});
 1105:         $sheet->write(1,0,$resource->{'src'},$format->{'h3'});
 1106:     }
 1107:     #
 1108:     my $result;
 1109:     $result = &OR_build_problem_data_worksheet($problem_data_sheet,$format,
 1110:                                             $Concepts,$ORdata);
 1111:     if ($result ne 'okay') {
 1112:         # Do something useful
 1113:     }
 1114:     $result = &OR_build_response_data_worksheet($response_data_sheet,$format,
 1115:                                              $PerformanceData,$Foils,
 1116:                                              $ORdata);
 1117:     if ($result ne 'okay') {
 1118:         # Do something useful
 1119:     }
 1120:     $response_data_sheet->activate();
 1121:     #
 1122:     # Close the excel file
 1123:     $workbook->close();
 1124:     #
 1125:     # Write a link to allow them to download it
 1126:     $result .= '<h2>'.&mt('Excel Raw Data Output').'</h2>'.
 1127:               '<p><a href="'.$filename.'">'.
 1128:               &mt('Your Excel spreadsheet.').
 1129:               '</a></p>'."\n";
 1130:     return $result;
 1131: }
 1132: 
 1133: sub OR_build_problem_data_worksheet {
 1134:     my ($worksheet,$format,$Concepts,$ORdata) = @_;
 1135:     my $rows_output = 3;
 1136:     my $cols_output = 0;
 1137:     $worksheet->write($rows_output++,0,'Problem Structure',$format->{'h3'});
 1138:     ##
 1139:     ##
 1140:     my @Headers;
 1141:     if (@$Concepts > 1) {
 1142:         @Headers = ("Concept\nNumber",'Concept',"Foil\nNumber",
 1143:                     'Foil Name','Foil Text','Correct value');
 1144:     } else {
 1145:         @Headers = ('Foil Number','FoilName','Foil Text','Correct value');
 1146:     }
 1147:     $worksheet->write_row($rows_output++,0,\@Headers,$format->{'header'});
 1148:     my %Foildata = %{$ORdata->{'_Foils'}};
 1149:     my $conceptindex = 1;
 1150:     my $foilindex = 1;
 1151:     foreach my $concept (@$Concepts) {
 1152:         my @FoilsInConcept = @{$concept->{'foils'}};
 1153:         my $firstfoil = shift(@FoilsInConcept);
 1154:         if (@$Concepts > 1) {
 1155:             $worksheet->write_row($rows_output++,0,
 1156:                                   [$conceptindex,
 1157:                                    $concept->{'name'},
 1158:                                    $foilindex++,
 1159:                                    $Foildata{$firstfoil}->{'name'},
 1160:                                    $Foildata{$firstfoil}->{'text'},
 1161:                                    $Foildata{$firstfoil}->{'value'},]);
 1162:         } else {
 1163:             $worksheet->write_row($rows_output++,0,
 1164:                                   [ $foilindex++,
 1165:                                     $Foildata{$firstfoil}->{'name'},
 1166:                                     $Foildata{$firstfoil}->{'text'},
 1167:                                     $Foildata{$firstfoil}->{'value'},]);
 1168:         }
 1169:         foreach my $foilid (@FoilsInConcept) {
 1170:             if (@$Concepts > 1) {
 1171:                 $worksheet->write_row($rows_output++,0,
 1172:                                       ['',
 1173:                                        '',
 1174:                                        $foilindex,
 1175:                                        $Foildata{$foilid}->{'name'},
 1176:                                        $Foildata{$foilid}->{'text'},
 1177:                                        $Foildata{$foilid}->{'value'},]);
 1178:             } else {
 1179:                 $worksheet->write_row($rows_output++,0,                
 1180:                                       [$foilindex,
 1181:                                        $Foildata{$foilid}->{'name'},
 1182:                                        $Foildata{$foilid}->{'text'},
 1183:                                        $Foildata{$foilid}->{'value'},]);
 1184:             }                
 1185:         } continue {
 1186:             $foilindex++;
 1187:         }
 1188:     } continue {
 1189:         $conceptindex++;
 1190:     }
 1191:     $rows_output++;
 1192:     $rows_output++;
 1193:     ##
 1194:     ## Option data output
 1195:     $worksheet->write($rows_output++,0,'Options',$format->{'header'});
 1196:     foreach my $string (@{$ORdata->{'_Options'}}) {
 1197:         $worksheet->write($rows_output++,0,$string);
 1198:     }
 1199:     return 'okay';
 1200: }
 1201: 
 1202: sub OR_build_response_data_worksheet {
 1203:     my ($worksheet,$format,$PerformanceData,$Foils,$ORdata)=@_;
 1204:     my $rows_output = 3;
 1205:     my $cols_output = 0;
 1206:     $worksheet->write($rows_output++,0,'Response Data',$format->{'h3'});
 1207:     $worksheet->set_column(1,1,20);
 1208:     $worksheet->set_column(2,2,13);
 1209:     my @Headers = ('identifier','time','award detail','attempt');
 1210:     foreach my $foil (@$Foils) {
 1211:         push (@Headers,$foil.' submission');
 1212:         push (@Headers,$foil.' grading');
 1213:     }
 1214:     $worksheet->write_row($rows_output++,0,\@Headers,$format->{'header'});
 1215:     #
 1216:     foreach my $row (@$PerformanceData) {
 1217:         next if (! defined($row));
 1218:         my ($student,$award,$grading,$submission,$time,$tries) = @$row;
 1219:         my @Foilgrades = split('&',$grading);
 1220:         my @Foilsubs   = split('&',$submission);
 1221:         my %ResponseData;
 1222:         for (my $j=0;$j<=$#Foilgrades;$j++) {
 1223:             my ($foilid,$correct)  = split('=',$Foilgrades[$j]);
 1224:             my (undef,$submission) = split('=',$Foilsubs[$j]);
 1225:             $submission = &Apache::lonnet::unescape($submission);
 1226:             $ResponseData{$foilid.' submission'}=$submission;
 1227:             $ResponseData{$foilid.' award'}=$correct;
 1228:         }
 1229:         $worksheet->write($rows_output,$cols_output++,$student);
 1230:         $worksheet->write($rows_output,$cols_output++,
 1231:              &Apache::lonstathelpers::calc_serial($time),$format->{'date'});
 1232:         $worksheet->write($rows_output,$cols_output++,$award);
 1233:         $worksheet->write($rows_output,$cols_output++,$tries);
 1234:         foreach my $foilid (@$Foils) {
 1235:             $worksheet->write($rows_output,$cols_output++,
 1236:                               $ResponseData{$foilid.' submission'});
 1237:             $worksheet->write($rows_output,$cols_output++,
 1238:                               $ResponseData{$foilid.' award'});
 1239:         }
 1240:         $rows_output++;
 1241:         $cols_output = 0;
 1242:     }
 1243:     return;
 1244: }
 1245: 
 1246: sub build_foil_index {
 1247:     my ($ORdata) = @_;
 1248:     return if (! exists($ORdata->{'_Foils'}));
 1249:     my %Foildata = %{$ORdata->{'_Foils'}};
 1250:     my @Foils = sort(keys(%Foildata));
 1251:     my %Concepts;
 1252:     foreach my $foilid (@Foils) {
 1253:         push(@{$Concepts{$Foildata{$foilid}->{'_Concept'}}},
 1254:              $foilid);
 1255:     }
 1256:     undef(@Foils);
 1257:     # Having gathered the concept information in a hash, we now translate it
 1258:     # into an array because we need to be consistent about order.
 1259:     # Also put the foils in order, too.
 1260:     my $sortfunction = sub {
 1261:         my %Numbers = (one   => 1,
 1262:                        two   => 2,
 1263:                        three => 3,
 1264:                        four  => 4,
 1265:                        five  => 5,
 1266:                        six   => 6,
 1267:                        seven => 7,
 1268:                        eight => 8,
 1269:                        nine  => 9,
 1270:                        ten   => 10,);
 1271:         my $a1 = lc($a); 
 1272:         my $b1 = lc($b);
 1273:         if (exists($Numbers{$a1})) {
 1274:             $a1 = $Numbers{$a1};
 1275:         }
 1276:         if (exists($Numbers{$b1})) {
 1277:             $b1 = $Numbers{$b1};
 1278:         }
 1279:         if (($a1 =~/^\d+$/) && ($b1 =~/^\d+$/)) {
 1280:             return $a1 <=> $b1;
 1281:         } else {
 1282:             return $a1 cmp $b1;
 1283:         }
 1284:     };
 1285:     my @Concepts;
 1286:     foreach my $concept (sort $sortfunction (keys(%Concepts))) {
 1287:         if (! defined($Concepts{$concept})) {
 1288:             $Concepts{$concept}=[];
 1289: #            next;
 1290:         }
 1291:         push(@Concepts,{ name => $concept,
 1292:                         foils => [@{$Concepts{$concept}}]});
 1293:         push(@Foils,(@{$Concepts{$concept}}));
 1294:     }
 1295:     #
 1296:     # Build up the table of row labels.
 1297:     my $table = '<table border="1" >'."\n";
 1298:     if (@Concepts > 1) {
 1299:         $table .= '<tr>'.
 1300:             '<th>'.&mt('Concept Number').'</th>'.
 1301:             '<th>'.&mt('Concept').'</th>'.
 1302:             '<th>'.&mt('Foil Number').'</th>'.
 1303:             '<th>'.&mt('Foil Name').'</th>'.
 1304:             '<th>'.&mt('Foil Text').'</th>'.
 1305:             '<th>'.&mt('Correct Value').'</th>'.
 1306:             "</tr>\n";
 1307:     } else {
 1308:         $table .= '<tr>'.
 1309:             '<th>'.&mt('Foil Number').'</th>'.
 1310:             '<th>'.&mt('Foil Name').'</th>'.
 1311:             '<th>'.&mt('Foil Text').'</th>'.
 1312:             '<th>'.&mt('Correct Value').'</th>'.
 1313:             "</tr>\n";
 1314:     }        
 1315:     my $conceptindex = 1;
 1316:     my $foilindex = 1;
 1317:     foreach my $concept (@Concepts) {
 1318:         my @FoilsInConcept = @{$concept->{'foils'}};
 1319:         my $firstfoil = shift(@FoilsInConcept);
 1320:         if (@Concepts > 1) {
 1321:             $table .= '<tr>'.
 1322:                 '<td>'.$conceptindex.'</td>'.
 1323:                 '<td>'.&HTML::Entities::encode($concept->{'name'},'<>&"').'</td>'.
 1324:                 '<td>'.$foilindex++.'</td>'.
 1325:                 '<td>'.&HTML::Entities::encode($Foildata{$firstfoil}->{'name'},'<>&"').'</td>'.
 1326:                 '<td>'.$Foildata{$firstfoil}->{'text'}.'</td>'.
 1327:                 '<td>'.&HTML::Entities::encode($Foildata{$firstfoil}->{'value'},'<>&"').'</td>'.
 1328:                 "</tr>\n";
 1329:         } else {
 1330:             $table .= '<tr>'.
 1331:                 '<td>'.$foilindex++.'</td>'.
 1332:                 '<td>'.&HTML::Entities::encode($Foildata{$firstfoil}->{'name'},'<>&"').'</td>'.
 1333:                 '<td>'.$Foildata{$firstfoil}->{'text'}.'</td>'.
 1334:                 '<td>'.&HTML::Entities::encode($Foildata{$firstfoil}->{'value'},'<>&"').'</td>'.
 1335:                 "</tr>\n";
 1336:         }
 1337:         foreach my $foilid (@FoilsInConcept) {
 1338:             if (@Concepts > 1) {
 1339:                 $table .= '<tr>'.
 1340:                     '<td></td>'.
 1341:                     '<td></td>'.
 1342:                     '<td>'.$foilindex.'</td>'.
 1343:                     '<td>'.&HTML::Entities::encode($Foildata{$foilid}->{'name'},'<>&"').'</td>'.
 1344:                     '<td>'.$Foildata{$foilid}->{'text'}.'</td>'.
 1345:                     '<td>'.&HTML::Entities::encode($Foildata{$foilid}->{'value'},'<>&"').'</td>'.
 1346:                     "</tr>\n";
 1347:             } else {
 1348:                 $table .= '<tr>'.
 1349:                     '<td>'.$foilindex.'</td>'.
 1350:                     '<td>'.&HTML::Entities::encode($Foildata{$foilid}->{'name'},'<>&"').'</td>'.
 1351:                     '<td>'.$Foildata{$foilid}->{'text'}.'</td>'.
 1352:                     '<td>'.&HTML::Entities::encode($Foildata{$foilid}->{'value'},'<>&"').'</td>'.
 1353:                     "</tr>\n";
 1354:             }                
 1355:         } continue {
 1356:             $foilindex++;
 1357:         }
 1358:     } continue {
 1359:         $conceptindex++;
 1360:     }
 1361:     $table .= "</table>\n";
 1362:     #
 1363:     # Build option index with color stuff
 1364:     return ($table,\@Foils,\@Concepts);
 1365: }
 1366: 
 1367: sub build_option_index {
 1368:     my ($ORdata)= @_;
 1369:     my $table = "<table>\n";
 1370:     my $optionindex = 0;
 1371:     my @Rows;
 1372:     foreach my $option (&mt('correct option chosen'),@{$ORdata->{'_Options'}}) {
 1373:         push (@Rows,
 1374:               '<tr>'.
 1375:               '<td bgcolor="'.$plotcolors->[$optionindex++].'">'.
 1376:               ('&nbsp;'x4).'</td>'.
 1377:               '<td>'.&HTML::Entities::encode($option,'<>&"').'</td>'.
 1378:               "</tr>\n");
 1379:     }
 1380:     shift(@Rows); # Throw away 'correct option chosen' color
 1381:     $table .= join('',reverse(@Rows));
 1382:     $table .= "</table>\n";
 1383: }
 1384: 
 1385: #########################################################
 1386: #########################################################
 1387: ##
 1388: ##   Generic Interface Routines
 1389: ##
 1390: #########################################################
 1391: #########################################################
 1392: sub CreateInterface {
 1393:     ##
 1394:     ## Environment variable initialization
 1395:     if (! exists$ENV{'form.AnalyzeOver'}) {
 1396:         $ENV{'form.AnalyzeOver'} = 'Tries';
 1397:     }
 1398:     ##
 1399:     ## Build the menu
 1400:     my $Str = '';
 1401:     $Str .= &Apache::lonhtmlcommon::breadcrumbs
 1402:         (undef,'Detailed Problem Analysis');
 1403:     $Str .= '<table cellspacing="5">'."\n";
 1404:     $Str .= '<tr>';
 1405:     $Str .= '<td align="center"><b>'.&mt('Sections').'</b></td>';
 1406:     $Str .= '<td align="center"><b>'.&mt('Enrollment Status').'</b></td>';
 1407: #    $Str .= '<td align="center"><b>'.&mt('Sequences and Folders').'</b></td>';
 1408:     $Str .= '<td align="center">&nbsp;</td>';
 1409:     $Str .= '</tr>'."\n";
 1410:     ##
 1411:     ## 
 1412:     $Str .= '<tr><td align="center">'."\n";
 1413:     $Str .= &Apache::lonstatistics::SectionSelect('Section','multiple',5);
 1414:     $Str .= '</td>';
 1415:     #
 1416:     $Str .= '<td align="center">';
 1417:     $Str .= &Apache::lonhtmlcommon::StatusOptions(undef,undef,5);
 1418:     $Str .= '</td>';
 1419:     #
 1420: #    $Str .= '<td align="center">';
 1421:     my $only_seq_with_assessments = sub { 
 1422:         my $s=shift;
 1423:         if ($s->{'num_assess'} < 1) { 
 1424:             return 0;
 1425:         } else { 
 1426:             return 1;
 1427:         }
 1428:     };
 1429:     &Apache::lonstatistics::MapSelect('Maps','multiple,all',5,
 1430:                                               $only_seq_with_assessments);
 1431:     ##
 1432:     ##
 1433:     $Str .= '<td>';
 1434:     { # These braces are here to organize the code, not scope it.
 1435:         {
 1436:             $Str .= '<nobr>'.&mt('Analyze Over ');
 1437:             $Str .= &Apache::loncommon::help_open_topic
 1438:                                                   ('Analysis_Analyze_Over');
 1439:             $Str .='<select name="AnalyzeOver" >';
 1440:             $Str .= '<option value="Tries" ';
 1441:             if (! exists($ENV{'form.AnalyzeOver'}) || 
 1442:                 $ENV{'form.AnalyzeOver'} eq 'Tries'){
 1443:                 # Default to Tries
 1444:                 $Str .= ' selected ';
 1445:             }
 1446:             $Str .= '>'.&mt('Tries').'</option>';
 1447:             $Str .= '<option value="Time" ';
 1448:             $Str .= ' selected ' if ($ENV{'form.AnalyzeOver'} eq 'Time');
 1449:             $Str .= '>'.&mt('Time').'</option>';
 1450:             $Str .= '</select>';
 1451:             $Str .= '</nobr><br />';
 1452:         }
 1453:         {
 1454:             $Str .= '<nobr>'.&mt('Analyze as ');
 1455:             $Str .= &Apache::loncommon::help_open_topic
 1456:                                                   ('Analysis_Analyze_as');
 1457:             $Str .='<select name="AnalyzeAs" >';
 1458:             $Str .= '<option value="Concepts" ';
 1459:             if (! exists($ENV{'form.AnalyzeAs'}) || 
 1460:                 $ENV{'form.AnalyzeAs'} eq 'Concepts'){
 1461:                 # Default to Concepts
 1462:                 $Str .= ' selected ';
 1463:             }
 1464:             $Str .= '>'.&mt('Concepts').'</option>';
 1465:             $Str .= '<option value="Foils" ';
 1466:             $Str .= ' selected ' if ($ENV{'form.AnalyzeAs'} eq 'Foils');
 1467:             $Str .= '>'.&mt('Foils').'</option>';
 1468:             $Str .= '</select></nobr><br />';
 1469:         }
 1470:         {
 1471:             $Str .= '<br /><nobr>'.&mt('Number of Plots:');
 1472:             $Str .= &Apache::loncommon::help_open_topic
 1473:                                                   ('Analysis_num_plots');
 1474:             $Str .= '<select name="NumPlots">';
 1475:             if (! exists($ENV{'form.NumPlots'}) 
 1476:                 || $ENV{'form.NumPlots'} < 1 
 1477:                 || $ENV{'form.NumPlots'} > 20) {
 1478:                 $ENV{'form.NumPlots'} = 5;
 1479:             }
 1480:             foreach my $i (1,2,3,4,5,6,7,8,10,15,20) {
 1481:                 $Str .= '<option value="'.$i.'" ';
 1482:                 if ($ENV{'form.NumPlots'} == $i) { $Str.=' selected '; }
 1483:                 $Str .= '>'.$i.'</option>';
 1484:             }
 1485:             $Str .= '</select></nobr>';
 1486:         }
 1487:     }
 1488:     $Str .= '</td>';
 1489:     ##
 1490:     ##
 1491:     $Str .= '</tr>'."\n";
 1492:     $Str .= '</table>'."\n";
 1493:     return $Str;
 1494: }
 1495: 
 1496: #########################################################
 1497: #########################################################
 1498: ##
 1499: ##              Misc Option Response functions
 1500: ##
 1501: #########################################################
 1502: #########################################################
 1503: sub get_time_from_row {
 1504:     my ($row) = @_;
 1505:     if (ref($row)) {
 1506:         return $row->[&Apache::loncoursedata::RD_timestamp()];
 1507:     } 
 1508:     return undef;
 1509: }
 1510: 
 1511: sub get_tries_from_row {
 1512:     my ($row) = @_;
 1513:     if (ref($row)) {
 1514:         return $row->[&Apache::loncoursedata::RD_tries()];
 1515:     }
 1516:     return undef;
 1517: }
 1518: 
 1519: sub hashify_attempt {
 1520:     my ($row) = @_;
 1521:     my %attempt;
 1522:     $attempt{'tries'}      = $row->[&Apache::loncoursedata::RD_tries()];
 1523:     $attempt{'submission'} = $row->[&Apache::loncoursedata::RD_submission()];
 1524:     $attempt{'award'}      = $row->[&Apache::loncoursedata::RD_awarddetail()];
 1525:     $attempt{'timestamp'}  = $row->[&Apache::loncoursedata::RD_timestamp()];
 1526:     return %attempt;
 1527: }
 1528: 
 1529: sub Process_OR_Row {
 1530:     my ($row) = @_;
 1531:     my %RowData;
 1532:     my $student_id = $row->[&Apache::loncoursedata::RD_student_id()];
 1533:     my $award      = $row->[&Apache::loncoursedata::RD_awarddetail()];
 1534:     my $grading    = $row->[&Apache::loncoursedata::RD_response_eval()];
 1535:     my $submission = $row->[&Apache::loncoursedata::RD_submission()];
 1536:     my $time       = $row->[&Apache::loncoursedata::RD_timestamp()];
 1537:     my $tries      = $row->[&Apache::loncoursedata::RD_tries()];
 1538:     return undef if ($award eq 'MISSING_ANSWER');
 1539:     if ($award =~ /(APPROX_ANS|EXACT_ANS)/) {
 1540:         $RowData{'_correct'} = 1;
 1541:     }
 1542:     $RowData{'_total'} = 1;
 1543:     my @Foilgrades = split('&',$grading);
 1544:     my @Foilsubs   = split('&',$submission);
 1545:     for (my $j=0;$j<=$#Foilgrades;$j++) {
 1546:         my ($foilid,$correct)  = split('=',$Foilgrades[$j]);
 1547:         $foilid = &Apache::lonnet::unescape($foilid);
 1548:         my (undef,$submission) = split('=',$Foilsubs[$j]);
 1549:         if ($correct) {
 1550:             $RowData{$foilid}->{'_correct'}++;
 1551:         } else {
 1552:             $submission = &Apache::lonnet::unescape($submission);
 1553:             $RowData{$foilid}->{$submission}++;
 1554:         }
 1555:         $RowData{$foilid}->{'_total'}++;
 1556:     }
 1557:     return %RowData;
 1558: }
 1559: 
 1560: 1;
 1561: 
 1562: __END__

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