File:  [LON-CAPA] / loncom / interface / statistics / lonproblemanalysis.pm
Revision 1.86: download - view: text, annotated - select for diffs
Wed Jun 23 20:51:14 2004 UTC (20 years ago) by matthew
Branches: MAIN
CVS tags: HEAD
No need to tell the user there are no students in the selected section
before they have chosen a problem to analyze.

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

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