Diff for /loncom/interface/statistics/lonproblemstatistics.pm between versions 1.45 and 1.73

version 1.45, 2003/03/26 21:47:47 version 1.73, 2004/03/26 22:04:22
Line 26 Line 26
 #  #
 # (Navigate problems for statistical reports  # (Navigate problems for statistical reports
 #  #
 ###  ###############################################
   ###############################################
   
   =pod
   
   =head1 NAME
   
   lonproblemstatistics
   
   =head1 SYNOPSIS
   
   Routines to present problem statistics to instructors via tables,
   Excel files, and plots.
   
   =over 4
   
   =cut
   
   ###############################################
   ###############################################
   
 package Apache::lonproblemstatistics;  package Apache::lonproblemstatistics;
   
 use strict;  use strict;
 use Apache::lonnet();  use Apache::lonnet();
   use Apache::loncommon();
 use Apache::lonhtmlcommon;  use Apache::lonhtmlcommon;
 use Apache::loncoursedata;  use Apache::loncoursedata;
 use Apache::lonstatistics;  use Apache::lonstatistics;
   use Apache::lonlocal;
 use Spreadsheet::WriteExcel;  use Spreadsheet::WriteExcel;
   use Apache::lonstathelpers();
   use Time::HiRes;
   
   my @StatsArray;
   
   ##
   ## Localization notes:
   ##
   ## in @Fields[0]->{'long_title'} is placed in Excel files and is used as the
   ## header for plots created with Graph.pm, both of which more than likely do
   ## not support localization.
   ##
   my @Fields = (
              { name => 'problem_num',
                title => 'P#',
                align => 'right',
                color => '#FFFFE6' },
              { name   => 'container',
                title  => 'Sequence or Folder',
                align  => 'left',
                color  => '#FFFFE6',
                sortable => 'yes' },
              { name   => 'title',
                title  => 'Title',
                align  => 'left',
                color  => '#FFFFE6',
                special  => 'link',
                sortable => 'yes', },
              { name   => 'part', 
                title  => 'Part',
                align  => 'left',
                color  => '#FFFFE6',
                },
              { name   => 'num_students',
                title  => '#Stdnts',
                align  => 'right',
                color  => '#EEFFCC',
                format => '%d',
                sortable  => 'yes',
                graphable => 'yes',
                long_title => 'Number of Students Attempting Problem' },
              { name   => 'tries',
                title  => 'Tries',
                align  => 'right',
                color  => '#EEFFCC',
                format => '%d',
                sortable  => 'yes',
                graphable => 'yes',
                long_title => 'Total Number of Tries' },
              { name   => 'max_tries',
                title  => 'Max Tries',
                align  => 'right',
                color  => '#DDFFFF',
                format => '%d',
                sortable  => 'yes',
                graphable => 'yes',
                long_title => 'Maximum Number of Tries' },
              { name   => 'min_tries',
                title  => 'Min Tries',
                align  => 'right',
                color  => '#DDFFFF',
                format => '%d',
                sortable  => 'yes',
                graphable => 'yes',
                long_title => 'Minumum Number of Tries' },
              { name   => 'mean_tries',
                title  => 'Mean Tries',
                align  => 'right',
                color  => '#DDFFFF',
                format => '%5.2f',
                sortable  => 'yes',
                graphable => 'yes',
                long_title => 'Average Number of Tries' },
              { name   => 'std_tries',
                title  => 'S.D. tries',
                align  => 'right',
                color  => '#DDFFFF',
                format => '%5.2f',
                sortable  => 'yes',
                graphable => 'yes',
                long_title => 'Standard Deviation of Number of Tries' },
              { name   => 'skew_tries',
                title  => 'Skew Tries',
                align  => 'right',
                color  => '#DDFFFF',
                format => '%5.2f',
                sortable  => 'yes',
                graphable => 'yes',
                long_title => 'Skew of Number of Tries' },
              { name   => 'num_solved',
                title  => '#YES',
                align  => 'right',
                color  => '#FFDDDD',
                format => '%4.1f',#             format => '%d',
                sortable  => 'yes',
                graphable => 'yes',
                long_title => 'Number of Students able to Solve' },
              { name   => 'num_override',
                title  => '#yes',
                align  => 'right',
                color  => '#FFDDDD',
                format => '%4.1f',#             format => '%d',
                sortable  => 'yes',
                graphable => 'yes',
                long_title => 'Number of Students given Override' },
              { name   => 'num_wrong',
                title  => '#Wrng',
                align  => 'right',
                color  => '#FFDDDD',
                format => '%4.1f',
                sortable  => 'yes',
                graphable => 'yes',
                long_title => 'Percent of students whose final answer is wrong' },
              { name   => 'deg_of_diff',
                title  => 'DoDiff',
                align  => 'right',
                color  => '#FFFFE6',
                format => '%5.2f',
                sortable  => 'yes',
                graphable => 'yes',
                long_title => 'Degree of Difficulty'.
                              '[ 1 - ((#YES+#yes) / Tries) ]'},
              { name   => 'deg_of_disc',
                title  => 'DoDisc',
                align  => 'right',
                color  => '#FFFFE6',
                format => '%4.2f',
                sortable  => 'yes',
                graphable => 'yes',
                long_title => 'Degree of Discrimination' },
   );
   
   ###############################################
   ###############################################
   
   =pod 
   
 #######################################################  =item &CreateInterface()
 #######################################################  
   
   Create the main intereface for the statistics page.  Allows the user to
   select sections, maps, and output.
   
   =cut
   
   ###############################################
   ###############################################
 sub CreateInterface {  sub CreateInterface {
     my $Str = '';      my $Str = '';
       $Str .= &Apache::lonhtmlcommon::breadcrumbs
           (undef,'Overall Problem Statistics','Statistics_Overall_Key');
     $Str .= '<table cellspacing="5">'."\n";      $Str .= '<table cellspacing="5">'."\n";
     $Str .= '<tr>';      $Str .= '<tr>';
     $Str .= '<td align="center"><b>Sections</b></td>';      $Str .= '<td align="center"><b>'.&mt('Sections').'</b></td>';
     $Str .= '<td align="center"><b>Sequences and Folders</b></td>';      $Str .= '<td align="center"><b>'.&mt('Enrollment Status').'</b></td>';
     $Str .= '<td align="center"><b>Output</b></td>';      $Str .= '<td align="center"><b>'.&mt('Sequences and Folders').'</b></td>';
       $Str .= '<td rowspan="2">'.
           &Apache::lonstathelpers::limit_by_time_form().'</td>';
     $Str .= '</tr>'."\n";      $Str .= '</tr>'."\n";
     #      #
     $Str .= '<tr><td align="center">'."\n";      $Str .= '<tr><td align="center">'."\n";
     $Str .= &Apache::lonstatistics::SectionSelect('Section','multiple',5);      $Str .= &Apache::lonstatistics::SectionSelect('Section','multiple',5);
     $Str .= '</td><td align="center">';      $Str .= '</td><td align="center">';
       $Str .= &Apache::lonhtmlcommon::StatusOptions(undef,undef,5);
       $Str .= '</td><td align="center">';
     #      #
     my $only_seq_with_assessments = sub {       my $only_seq_with_assessments = sub { 
         my $s=shift;          my $s=shift;
Line 63  sub CreateInterface { Line 232  sub CreateInterface {
     };      };
     $Str .= &Apache::lonstatistics::MapSelect('Maps','multiple,all',5,      $Str .= &Apache::lonstatistics::MapSelect('Maps','multiple,all',5,
                                               $only_seq_with_assessments);                                                $only_seq_with_assessments);
     $Str .= '</td><td>'."\n";  
     $Str .= &CreateAndParseOutputSelector();  
     $Str .= '</td></tr>'."\n";      $Str .= '</td></tr>'."\n";
     $Str .= '</table>'."\n";      $Str .= '</table>'."\n";
     return $Str;      $Str .= '<input type="submit" name="GenerateStatistics" value="'.
 }          &mt('Generate Statistics').'" />';
       $Str .= '&nbsp;'x5;
 #######################################################      $Str .= 'Plot '.&plot_dropdown().('&nbsp;'x10);
 #######################################################      $Str .= '<input type="submit" name="ClearCache" value="'.
           &mt('Clear Caches').'" />';
 =pod      $Str .= '&nbsp;'x5;
       $Str .= '<input type="submit" name="UpdateCache" value="'.
 =item &CreateAndParseOutputSelector()          &mt('Update Student Data').'" />';
       $Str .= '&nbsp;'x5;
 =cut      $Str .= '<input type="submit" name="Excel" value="'.
           &mt('Produce Excel Output').'" />';
 #######################################################      $Str .= '&nbsp;'x5;
 #######################################################  
 my $output_mode;  
 my $show;  
   
 my @OutputOptions =   
     (  
      { name  => 'problem statistics grouped by sequence',  
        value => 'HTML problem statistics grouped',  
        description => 'Output statistics for the problem parts.',  
        mode => 'html',  
        show => 'grouped',  
      },  
      { name  => 'problem statistics ungrouped',  
        value => 'HTML problem statistics ungrouped',  
        description => 'Output statistics for the problem parts.',  
        mode => 'html',  
        show => 'ungrouped',  
      },  
      { name  => 'problem statistics, Excel',  
        value => 'Excel problem statistics',  
        description => 'Output statistics for the problem parts '.  
            'in an Excel workbook',  
        mode => 'excel',  
        show => 'all',  
      },  
      { name  => 'Degree of Difficulty Plot',  
        value => 'plot deg diff',  
        description => 'Generate a plot of the degree of difficulty of each '.  
            'problem part.',  
        mode => 'plot',  
        show => 'deg of diff',  
      },  
      { name  => 'Percent Wrong Plot',  
        value => 'plot per wrong',  
        description => 'Generate a plot showing the percent of students who '.  
            'were unable to complete each problem part',  
        mode => 'plot',  
        show => 'per wrong',  
      },  
      );  
   
 sub OutputDescriptions {  
     my $Str = '';  
     $Str .= "<h2>Output Modes</h2>\n";  
     $Str .= "<dl>\n";  
     foreach my $outputmode (@OutputOptions) {  
  $Str .="    <dt>".$outputmode->{'name'}."</dt>\n";  
  $Str .="        <dd>".$outputmode->{'description'}."</dd>\n";  
     }  
     $Str .= "</dl>\n";  
     return $Str;  
 }  
   
 sub CreateAndParseOutputSelector {  
     my $Str = '';  
     my $elementname = 'outputmode';  
     #  
     # Format for output options is 'mode, restrictions';  
     my $selected = 'html, with links';  
     if (exists($ENV{'form.'.$elementname})) {  
         if (ref($ENV{'form.'.$elementname} eq 'ARRAY')) {  
             $selected = $ENV{'form.'.$elementname}->[0];  
         } else {  
             $selected = $ENV{'form.'.$elementname};  
         }  
     }  
     #  
     # Set package variables describing output mode  
     $output_mode = 'html';  
     $show        = 'all';  
     foreach my $option (@OutputOptions) {  
         next if ($option->{'value'} ne $selected);  
         $output_mode = $option->{'mode'};  
         $show        = $option->{'show'};  
     }  
     #  
     # Build the form element  
     $Str = qq/<select size="5" name="$elementname">/;  
     foreach my $option (@OutputOptions) {  
         $Str .= "\n".'    <option value="'.$option->{'value'}.'"';  
         $Str .= " selected " if ($option->{'value'} eq $selected);  
         $Str .= ">".$option->{'name'}."<\/option>";  
     }  
     $Str .= "\n</select>";  
     return $Str;      return $Str;
 }  }
   
 ###############################################  ###############################################
 ###############################################  ###############################################
   
 ###############################################  =pod 
 ###############################################  
 sub Gather_Student_Data {  
     my ($r) = @_;  
     my $c = $r->connection();  
     #  
     my @Sequences = &Apache::lonstatistics::Sequences_with_Assess();  
     #  
     my @Students = @Apache::lonstatistics::Students;  
     #  
     # Open the progress window  
     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin  
         ($r,'Statistics Compilation Status',  
          'Statistics Compilation Progress', scalar(@Students));  
     #  
     while (my $student = shift @Students) {  
         return if ($c->aborted());  
         my ($status,undef) = &Apache::loncoursedata::ensure_current_data  
             ($student->{'username'},$student->{'domain'},  
              $ENV{'request.course.id'});  
         &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,  
                                                  'last student');  
     }  
     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);  
     $r->rflush();  
 }  
   
 ###############################################  =item &BuildProblemStatisticsPage()
 ###############################################  
   Main interface to problem statistics.
   
   =cut
   
 ###############################################  ###############################################
 ###############################################  ###############################################
 sub BuildProblemStatisticsPage {  sub BuildProblemStatisticsPage {
     my ($r,$c)=@_;      my ($r,$c)=@_;
     #      #
     $output_mode = 'html';      my %Saveable_Parameters = ('Status' => 'scalar',
     $show = 'grouped';                                 'statsoutputmode' => 'scalar',
     #                                 'Section' => 'array',
     $r->print(&CreateInterface());                                 'StudentData' => 'array',
     $r->print('<input type="hidden" name="statsfirstcall" value="no" />');                                 'Maps' => 'array');
       &Apache::loncommon::store_course_settings('statistics',
                                                 \%Saveable_Parameters);
       &Apache::loncommon::restore_course_settings('statistics',
                                                   \%Saveable_Parameters);
       #
       &Apache::lonstatistics::PrepareClasslist();
       #
       # Clear the package variables
       undef(@StatsArray);
       #
       # Finally let the user know we are here
       my $interface = &CreateInterface();
       $r->print($interface);
     $r->print('<input type="hidden" name="sortby" value="'.$ENV{'form.sortby'}.      $r->print('<input type="hidden" name="sortby" value="'.$ENV{'form.sortby'}.
               '" />');                '" />');
       #
     if (! exists($ENV{'form.statsfirstcall'})) {      if (! exists($ENV{'form.statsfirstcall'})) {
           $r->print('<input type="hidden" name="statsfirstcall" value="yes" />');
           $r->print('<h3>'.
                     &mt('Press "Generate Statistics" when you are ready.').
                     '</h3><p>'.
                     &mt('It may take some time to update the student data '.
                         'for the first analysis.  Future analysis this session '.
                         ' will not have this delay.').
                     '</p>');
         return;          return;
       } elsif ($ENV{'form.statsfirstcall'} eq 'yes' || 
                exists($ENV{'form.UpdateCache'}) ||
                exists($ENV{'form.ClearCache'}) ) {
           $r->print('<input type="hidden" name="statsfirstcall" value="no" />');
           &Apache::lonstatistics::Gather_Student_Data($r);
       } else {
           $r->print('<input type="hidden" name="statsfirstcall" value="no" />');
     }      }
       $r->rflush();
     #      #
     &Gather_Student_Data($r);      # This probably does not need to be done each time we are called, but
     #      # it does not slow things down noticably.
       &Apache::loncoursedata::populate_weight_table();
       if (exists($ENV{'form.Excel'})) {
           &Excel_output($r);
       } else {
           my $sortby = $ENV{'form.sortby'};
           $sortby = 'container' if (! defined($sortby) || $sortby =~ /^\s*$/);
           my $plot = $ENV{'form.plot'};
           &Apache::lonnet::logthis('form.plot = '.$plot);
           if ($sortby eq 'container' && ! defined($plot)) {
               &output_html_by_sequence($r);
           } else {
               if (defined($plot)) {
                   &Apache::lonnet::logthis('calling plot routine');
                   &make_plot($r,$plot);
               }
               &output_html_stats($r);
           }
       }
       return;
   }
   
   ##########################################################
   ##########################################################
   ##
   ## HTML output routines
   ##
   ##########################################################
   ##########################################################
   sub output_html_by_sequence {
       my ($r) = @_;
       my $c = $r->connection();
       $r->print(&html_preamble());
     #      #
     if ($output_mode eq 'html') {      foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
         $r->print("<h2>".          last if ($c->aborted);
                   $ENV{'course.'.$ENV{'request.course.id'}.'.description'}.          next if ($seq->{'num_assess'} < 1);
                   "</h2>\n");          $r->print("<h3>".$seq->{'title'}."</h3>".
         $r->print("<h3>".localtime(time)."</h3>");                    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                     '<table border="0" cellpadding="3">'."\n".
                     '<tr bgcolor="#FFFFE6">'.
                     &statistics_table_header('no container')."</tr>\n");
           my @Data = &compute_statistics_on_sequence($seq);
           foreach my $data (@Data) {
               $r->print('<tr>'.&statistics_html_table_data($data,
                                                            'no container').
                         "</tr>\n");
           }
           $r->print('</table>'."\n".'</table>'."\n");
         $r->rflush();          $r->rflush();
         if ($show eq 'grouped') {      }
             &output_html_grouped_by_sequence($r);      return;
         } elsif ($show eq 'ungrouped') {  }
             &output_html_ungrouped($r);  
         }  sub output_html_stats {
     } elsif ($output_mode eq 'excel') {      my ($r)=@_;
         $r->print("<h2>Preparing Excel Spreadsheet</h2>");      &compute_all_statistics($r);
         &output_excel($r);      $r->print(&html_preamble());
     } elsif ($output_mode eq 'plot') {      &sort_data($ENV{'form.sortby'});
         if ($show eq 'deg of diff') {      #
             &plot_statistics($r,'DoDiff');      my $count=0;
         } elsif ($show eq 'per wrong') {      foreach my $data (@StatsArray) {
             &plot_statistics($r,'%Wrng');          if ($count++ % 50 == 0) {
               $r->print("</table>\n</table>\n");
               $r->print('<table border="0"><tr><td bgcolor="#777777">'."\n".
                         '<table border="0" cellpadding="3">'."\n".
                         '<tr bgcolor="#FFFFE6">'.
                         '<tr bgcolor="#FFFFE6">'.
                         &statistics_table_header().
                         "</tr>\n");
         }          }
     } else {          $r->print('<tr>'.&statistics_html_table_data($data)."</tr>\n");
         $r->print("<h1>Not implemented</h1>");  
     }      }
       $r->print("</table>\n</table>\n");
     return;      return;
 }  }
   
   
   sub html_preamble {
       my $Str='';
       $Str .= "<h2>".
           $ENV{'course.'.$ENV{'request.course.id'}.'.description'}.
           "</h2>\n";
       my ($starttime,$endtime) = &Apache::lonstathelpers::get_time_limits();
       if (defined($starttime) || defined($endtime)) {
           # Inform the user what the time limits on the data are.
           $Str .= '<h3>'.&mt('Statistics on submissions from [_1] to [_2]',
                              &Apache::lonlocal::locallocaltime($starttime),
                              &Apache::lonlocal::locallocaltime($endtime)
                              ).'</h3>';
       }
       $Str .= "<h3>".&mt('Compiled on [_1]',
                          &Apache::lonlocal::locallocaltime(time))."</h3>";
       return $Str;
   }
   
   
 ###############################################  ###############################################
 ###############################################  ###############################################
   ##
   ## Misc HTML output routines
   ##
 ###############################################  ###############################################
 ###############################################  ###############################################
 sub output_html_grouped_by_sequence {  sub statistics_html_table_data {
     my ($r) = @_;      my ($data,$options) = @_;
     my $problem_num = 0;      my $row = '';
     #$r->print(&ProblemStatisticsLegend());      foreach my $field (@Fields) {
     my @Header = ("Title","Part","#Stdnts","Tries","Mod",          next if ($options =~ /no $field->{'name'}/);
                   "Mean","#YES","#yes","%Wrng","DoDiff",          $row .= '<td bgcolor="'.$field->{'color'}.'"';
                   "S.D.","Skew.");#,"D.F.1st","D.F.2nd");          if (exists($field->{'align'})) {
     # #FFFFE6 #EEFFCC #DDFFFF FFDDDD #DDFFDD #FFDDFF              $row .= ' align="'.$field->{'align'}.'"';
     foreach my $sequence (&Apache::lonstatistics::Sequences_with_Assess()) {  
         my $show_part = 0;  
         next if ($sequence->{'num_assess'}<1);  
         $r->print("<h3>".$sequence->{'title'}."</h3>");  
         $r->print('<table border="0"><tr><td bgcolor="#777777">'."\n");  
         $r->print('<table border="0" cellpadding="3">'."\n");  
         $r->print('<tr bgcolor="#FFFFE6"><th>'.  
                   join("</th><th>",@Header)."</th></tr>\n");  
         foreach my $resource (@{$sequence->{'contents'}}) {  
             next if ($resource->{'type'} ne 'assessment');  
             foreach my $part (@{$resource->{'parts'}}) {  
                 $problem_num++;  
                 my ($num,$tries,$mod,$mean,$Solved,$solved,$DegOfDiff,$STD,  
                     $SKEW) = &Apache::loncoursedata::get_problem_statistics  
                         (undef,$resource->{'symb'},$part,  
                          $ENV{'request.course.id'});  
                 #  
                 $show_part = 1 if ($part ne '0');  
                 $part = '&nbsp;' if ($part == 0);  
                 #  
                 my $wrongpercent = 0;  
                 if (defined($num) && $num > 0) {  
                     $wrongpercent=int(10*100*($num-$Solved+$solved)/$num)/10;  
                 }  
                 my $option = '';  
                 $option .= 'no part' if (! $show_part);  
                 $r->print('<tr>'.&statistics_html_table_data  
                           ($resource,$part,$num,$tries,$mod,$mean,$Solved,  
                            $solved,$wrongpercent,$DegOfDiff,$STD,$SKEW,  
                            $option).  
                           "</tr>\n");  
             }              }
           $row .= '>';
           if (exists($field->{'special'}) && $field->{'special'} eq 'link') {
               $row .= '<a href="'.$data->{$field->{'name'}.'.link'}.'">';
         }          }
         $r->print("</table>\n");          if (exists($field->{'format'})) {
         $r->print("</td></tr></table>\n");              $row .= sprintf($field->{'format'},$data->{$field->{'name'}});
         $r->rflush();          } else {
               $row .= $data->{$field->{'name'}};
           }
           if (exists($field->{'special'}) && $field->{'special'} eq 'link') {
               $row.= '</a>';
           }
           $row .= '</td>';
     }      }
     #      return $row;
     return;  
 }  }
   
 ###############################################  sub statistics_table_header {
 ###############################################      my ($options) = @_;
       my $header_row;
       foreach my $field (@Fields) {
           next if ($options =~ /no $field->{'name'}/);
           $header_row .= '<th>';
           if (exists($field->{'sortable'}) && $field->{'sortable'} eq 'yes') {
               $header_row .= '<a href="javascript:'.
                   'document.Statistics.sortby.value='."'".$field->{'name'}."'".
                       ';document.Statistics.submit();">';
           }
           $header_row .= &mt($field->{'title'});
           if ($options =~ /sortable/) {
               $header_row.= '</a>';
           }
           if ($options !~ /no plots/        && 
               exists($field->{'graphable'}) && 
               $field->{'graphable'} eq 'yes') {
               $header_row.=' (';
               $header_row .= '<a href="javascript:'.
                   "document.Statistics.plot.value='$field->{'name'}'".
                       ';document.Statistics.submit();">';
               $header_row .= &mt('plot').'</a>)';
           }
           $header_row .= '</th>';
       }
       return $header_row;
   }
   
 ###############################################  ####################################################
 ###############################################  ####################################################
 sub output_html_ungrouped {  ##
     my ($r,$option) = @_;  ##    Plotting Routines
   ##
   ####################################################
   ####################################################
   sub make_plot {
       my ($r,$plot) = @_;
       &compute_all_statistics($r);
       &sort_data($ENV{'form.sortby'});
       if ($plot eq 'degrees') {
           &degrees_plot($r);
       } else {
           &make_single_stat_plot($r,$plot);
       }
       return;
   }
   
   sub make_single_stat_plot {
       my ($r,$datafield) = @_;
     #      #
     my $problem_num = 0;      my $title; my $yaxis;
     my $show_container = 0;      foreach my $field (@Fields) {
     my $show_part = 0;          next if ($field->{'name'} ne $datafield);
     #$r->print(&ProblemStatisticsLegend());          $title = $field->{'long_title'};
     my @Header = ("Title","Part","#Stdnts","Tries","Mod",          $yaxis = $field->{'title'};
                   "Mean","#YES","#yes","%Wrng","DoDiff",          last;
                   "S.D.","Skew");#,"D.F.1st","D.F.2nd");      }
       if ($title eq '' || $yaxis eq '') {
           # datafield is something we do not know enough about to plot
           $r->print('<h3>'.
                     &mt('Unable to plot the requested statistic.').
                     '</h3>');
           return;
       }
     #      #
     my $sortby = undef;      # Build up the data sets to plot
     foreach (@Header) {      my @Labels; 
         if ($ENV{'form.sortby'} eq $_) {      my @Data;
             $sortby = $_;      my $max = 1;
       foreach my $data (@StatsArray) {
           push(@Labels,$data->{'problem_num'});
           push(@Data,$data->{$datafield});
           if ($data->{$datafield}>$max) {
               $max = $data->{$datafield};
         }          }
     }      }
     if (! defined($sortby) || $sortby eq '') {      foreach (1,2,3,4,5,10,15,20,25,40,50,75,100,150,200,250,300,500,600,750,
         $sortby = 'Container';               1000,1500,2000,2500,3000,3500,4000,5000,7500,10000,15000,20000) {
     }          if ($max <= $_) {
     # If there is more than one sequence, list their titles              $max = $_;
     my @Sequences = &Apache::lonstatistics::Sequences_with_Assess();              last;
     if (@Sequences > 1) {          }
         unshift(@Header,"Container");  
         $show_container = 1;  
     }      }
     #       if ($max > 20000) {
     # If the option for showing the problem number is needed, push that          $max = 10000*(int($max/10000)+1);
     # on the list too  
     if (defined($option) && $option =~ /show probnum/) {  
         unshift(@Header,"P#");  
     }      }
     #      #
     $r->print('<table border="0"><tr><td bgcolor="#777777">'."\n");      $r->print("<p>".&Apache::loncommon::DrawBarGraph($title,
     $r->rflush();                                                       'Problem Number',
     #                                                       $yaxis,
     # Compile the data                                                       $max,
     my @Statsarray;                                                       undef, # colors
     foreach my $sequence (@Sequences) {                                                       \@Labels,
         next if ($sequence->{'num_assess'}<1);                                                       \@Data)."</p>\n");
         foreach my $resource (@{$sequence->{'contents'}}) {      return;
             next if ($resource->{'type'} ne 'assessment');  }
             foreach my $part (@{$resource->{'parts'}}) {  
                 $problem_num++;  sub degrees_plot {
                 my ($num,$tries,$mod,$mean,$Solved,$solved,$DegOfDiff,$STD,      my ($r)=@_;
                     $SKEW) = &Apache::loncoursedata::get_problem_statistics      my $count = scalar(@StatsArray);
                         (undef,$resource->{'symb'},$part,      my $width = 50 + 10*$count;
                          $ENV{'request.course.id'});      $width = 300 if ($width < 300);
                 #      my $height = 300;
                 $show_part = 1 if ($part ne '0');      my $plot = '';
                 $part = '&nbsp;' if ($part == 0);      my $ymax = 0;
                 #      my $ymin = 0;
                 my $wrongpercent = 0;      my @Disc; my @Diff; my @Labels;    
                 if (defined($num) && $num > 0) {      foreach my $data (@StatsArray) {
                     $wrongpercent=int(10*100*($num-$Solved+$solved)/$num)/10;          push(@Labels,$data->{'problem_num'});
                 }          my $disc = $data->{'deg_of_disc'};
                 push (@Statsarray,          my $diff = $data->{'deg_of_diff'};
                       { 'sequence' => $sequence,          push(@Disc,$disc);
                         'resource' => $resource,          push(@Diff,$diff);
                         'Title' => $resource->{'title'},          #
                         'Part'  => $part,          $ymin = $disc if ($ymin > $disc);
                         '#Stdnts' => $num,          $ymin = $diff if ($ymin > $diff);
                         'Tries' => $tries,          $ymax = $disc if ($ymax < $disc);
                         'Mod' => $mod,          $ymax = $diff if ($ymax < $diff);
                         'Mean' => $mean,      }
                         '#YES' => $Solved,      #
                         '#yes' => $solved,      # Make sure we show relevant information.
                         '%Wrng' => $wrongpercent,      if ($ymin < 0) {
                         'DoDiff' => $DegOfDiff,          if (abs($ymin) < 0.05) {
                         'S.D.' => $STD,              $ymin = 0;
                         'Skew' => $SKEW,          } else {
                         'problem_num' => $problem_num,              $ymin = -1;
                       });  
             }  
         }          }
     }      }
     #      if ($ymax > 0) {
     # Table Headers          if (abs($ymax) < 0.05) {
     $r->print('<table border="0" cellpadding="3">'."\n");              $ymax = 0;
     my $Str = '';  
     foreach (@Header) {  
         next if ($_ eq 'Part' && !$show_part);  
         # Do not allow sorting on some fields  
         if ($_ eq $sortby || /^(Part|P\#)$/) {    
             $Str .= '<th>'.$_.'</th>';  
         } else {          } else {
             $Str .= '<th>'.              $ymax = 1;
      '<a href="javascript:document.Statistics.sortby.value='."'$_'".  
          ';document.Statistics.submit();">'.  
              $_.'</a></th>';  
         }          }
     }      }
     $r->print('<tr bgcolor="#FFFFE6">'.$Str."</tr>\n");  
     #      #
     # Sort the data      my $xmax = $Labels[-1];
     my @OutputOrder;      if ($xmax > 50) {
     if ($sortby eq 'Container') {          if ($xmax % 10 != 0) {
         @OutputOrder = @Statsarray;              $xmax = 10 * (int($xmax/10)+1);
           }
     } else {      } else {
         # $sortby is already defined, so we can charge ahead          if ($xmax % 5 != 0) {
         if ($sortby =~ /^(title|part)$/i) {              $xmax = 5 * (int($xmax/5)+1);
             # Alpha comparison  
             @OutputOrder = sort {  
                 lc($a->{$sortby}) cmp lc($b->{$sortby}) ||  
                     lc($a->{'Title'}) cmp lc($b->{'Title'}) ||  
                         lc($a->{'Part'}) cmp lc($b->{'Part'});  
             } @Statsarray;  
         } else {  
             # Numerical comparison  
             @OutputOrder = sort {  
                 my $retvalue = 0;  
                 if ($b->{$sortby} eq 'nan') {  
                     if ($a->{$sortby} ne 'nan') {  
                         $retvalue = -1;  
                     } else {  
                         $retvalue = 0;  
                     }  
                 }  
                 if ($a->{$sortby} eq 'nan') {  
                     if ($b->{$sortby} ne 'nan') {  
                         $retvalue = 1;  
                     }  
                 }  
                 if ($retvalue eq '0') {  
                     $retvalue = $b->{$sortby} <=> $a->{$sortby} ||  
                                 lc($a->{'Title'}) <=> lc($b->{'Title'}) ||  
                                 lc($a->{'Part'})  <=> lc($b->{'Part'});  
                 }  
                 $retvalue;  
             } @Statsarray;  
         }          }
     }      }
     $option .= ',no part' if (! $show_part);  
     foreach my $row (@OutputOrder) {  
         $r->print('<tr>');  
         if (defined($option) && $option =~ /show probnum/) {  
             $r->print('<td bgcolor="#FFFFE6">'.$row->{'problem_num'}.'</td>');  
         }  
         if ($show_container) {  
             $r->print('<td bgcolor="#FFFFE6">'  
                       .$row->{'sequence'}->{'title'}.'</td>');  
         }  
         $r->print(&statistics_html_table_data  
                   ($row->{'resource'},$row->{'Part'},$row->{'#Stdnts'},  
                    $row->{'Tries'},$row->{'Mod'},$row->{'Mean'},  
                    $row->{'#YES'},$row->{'#yes'},$row->{"\%Wrng"},  
                    $row->{'DoDiff'},$row->{'S.D.'},$row->{'Skew'},  
                    $option));  
   
         $r->print("</tr>\n");  
     }  
     $r->print("</table>\n");  
     $r->print("</td></tr></table>\n");  
     $r->rflush();  
     #      #
       my $discdata .= '<data>'.join(',',@Labels).'</data>'.$/.
                       '<data>'.join(',',@Disc).'</data>'.$/;
       #
       my $diffdata .= '<data>'.join(',',@Labels).'</data>'.$/.
                       '<data>'.join(',',@Diff).'</data>'.$/;
       #
       $plot=<<"END";
   <gnuplot 
       texfont="10"
       fgcolor="x000000"
       plottype="Cartesian"
       font="large"
       grid="on"
       align="center"
       border="on"
       transparent="on"
       alttag="Sample Plot"
       samples="100"
       bgcolor="xffffff"
       height="$height"
       width="$width">
       <key 
           pos="top right"
           title=""
           box="off" />
       <title>Degree of Discrmination and Degree of Difficulty</title>
       <axis xmin="0" ymin="$ymin" xmax="$xmax" ymax="$ymax" color="x000000" />
       <xlabel>Problem Number</xlabel>
       <curve 
           linestyle="linespoints" 
           name="DoDisc" 
           pointtype="0" 
           color="x000000">
           $discdata
       </curve>
       <curve 
           linestyle="linespoints" 
           name="DoDiff" 
           pointtype="0" 
           color="xFF0000">
           $diffdata
       </curve>
   </gnuplot>
   END
       my $plotresult = 
           '<p>'.&Apache::lonxml::xmlparse($r,'web',$plot).'</p>'.$/;
       $r->print($plotresult);
     return;      return;
 }  }
   
   sub plot_dropdown {
       my $current = '';
       #
       if (defined($ENV{'form.plot'})) {
           $current = $ENV{'form.plot'};
       }
       #
       my @Additional_Plots = (
                               { graphable=>'yes',
                                 name => 'degrees',
                                 title => 'DoDisc and DoDiff' });
       #
       my $Str= "\n".'<select name="plot" size="1">';
       $Str .= '<option name="none"></option>'."\n";
       $Str .= '<option name="none2">none</option>'."\n";
       foreach my $field (@Fields,@Additional_Plots) {
           if (! exists($field->{'graphable'}) ||
               $field->{'graphable'} ne 'yes') {
               next;
           }
           $Str .= '<option value="'.$field->{'name'}.'"';
           if ($field->{'name'} eq $current) {
               $Str .= ' selected ';
           }
           $Str.= '>'.&mt($field->{'title'}).'</option>'."\n";
       }
       $Str .= '</select>'."\n";
       return $Str;
   }
   
 ###############################################  ###############################################
 ###############################################  ###############################################
   ##
   ## Excel output routines
   ##
 ###############################################  ###############################################
 ###############################################  ###############################################
 sub output_excel {  sub Excel_output {
     my ($r) = @_;      my ($r) = @_;
       $r->print('<h2>'.&mt('Preparing Excel Spreadsheet').'</h2>');
       ##
       ## Compute the statistics
       &compute_all_statistics($r);
       my $c = $r->connection;
       return if ($c->aborted());
       ##
       ## Create the excel workbook
     my $filename = '/prtspool/'.      my $filename = '/prtspool/'.
         $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.          $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
             time.'_'.rand(1000000000).'.xls';          time.'_'.rand(1000000000).'.xls';
     #      my ($starttime,$endtime) = &Apache::lonstathelpers::get_time_limits();
     my $excel_workbook = undef;  
     my $excel_sheet = undef;  
     #  
     my $rows_output = 0;  
     my $cols_output = 0;  
     #      #
     # Create sheet      # Create sheet
     $excel_workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);      my $excel_workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
     #      #
     # Check for errors      # Check for errors
     if (! defined($excel_workbook)) {      if (! defined($excel_workbook)) {
         $r->log_error("Error creating excel spreadsheet $filename: $!");          $r->log_error("Error creating excel spreadsheet $filename: $!");
         $r->print("Problems creating new Excel file.  ".          $r->print(&mt("Problems creating new Excel file.  ".
                   "This error has been logged.  ".                    "This error has been logged.  ".
                   "Please alert your LON-CAPA administrator");                    "Please alert your LON-CAPA administrator."));
         return ;          return 0;
     }      }
     #      #
     # The excel spreadsheet stores temporary data in files, then put them      # The excel spreadsheet stores temporary data in files, then put them
Line 503  sub output_excel { Line 711  sub output_excel {
     if (length($sheetname) > 31) {      if (length($sheetname) > 31) {
         $sheetname = substr($sheetname,0,31);          $sheetname = substr($sheetname,0,31);
     }      }
     $excel_sheet = $excel_workbook->addworksheet($sheetname);      my $excel_sheet = $excel_workbook->addworksheet(
           &Apache::loncommon::clean_excel_name($sheetname));
       ##
       ## Begin creating excel sheet
       ##
       my ($rows_output,$cols_output) = (0,0);
     #      #
     # Put the course description in the header      # Put the course description in the header
     $excel_sheet->write($rows_output,$cols_output++,      $excel_sheet->write($rows_output,$cols_output++,
Line 530  sub output_excel { Line 743  sub output_excel {
     $excel_sheet->write($rows_output,$cols_output++,$sectionstring);      $excel_sheet->write($rows_output,$cols_output++,$sectionstring);
     $cols_output += scalar(@Sections);      $cols_output += scalar(@Sections);
     #      #
       # Time restrictions
       my $time_string;
       if (defined($starttime)) {
           # call localtime but not lonlocal:locallocaltime because excel probably
           # cannot handle localized text.  Probably.
           $time_string .= 'Data collected from '.localtime($time_string);
           if (defined($endtime)) {
               $time_string .= ' to '.localtime($endtime);
           }
           $time_string .= '.';
       } elsif (defined($endtime)) {
           # See note above about lonlocal:locallocaltime
           $time_string .= 'Data collected before '.localtime($endtime).'.';
       }
       #
     # Put the date in there too      # Put the date in there too
     $excel_sheet->write($rows_output,$cols_output++,      $excel_sheet->write($rows_output,$cols_output++,
                         'Compiled on '.localtime(time));                          'Compiled on '.localtime(time));
Line 537  sub output_excel { Line 765  sub output_excel {
     $rows_output++;       $rows_output++; 
     $cols_output=0;      $cols_output=0;
     #      #
     # Add the headers      # Long Headers
     my @Header = ("Container","Title","Part","#Stdnts","Tries","Mod",      foreach my $field (@Fields) {
                   "Mean","#YES","#yes","%Wrng","DoDiff",          next if ($field->{'name'} eq 'problem_num');
                   "S.D.","Skew.");#,"D.F.1st","D.F.2nd");          if (exists($field->{'long_title'})) {
     foreach (@Header) {              $excel_sheet->write($rows_output,$cols_output++,
         $excel_sheet->write($rows_output,$cols_output++,$_);                                  $field->{'long_title'});
           } else {
               $excel_sheet->write($rows_output,$cols_output++,'');
           }
     }      }
     $rows_output++;      $rows_output++;
     #      $cols_output=0;
     # Write the data      # Brief headers
     foreach my $sequence (&Apache::lonstatistics::Sequences_with_Assess()) {      foreach my $field (@Fields) {
         next if ($sequence->{'num_assess'}<1);          next if ($field->{'name'} eq 'problem_num');
         foreach my $resource (@{$sequence->{'contents'}}) {          # Use english for excel as I am not sure how well excel handles 
             next if ($resource->{'type'} ne 'assessment');          # other character sets....
             foreach my $part (@{$resource->{'parts'}}) {          $excel_sheet->write($rows_output,$cols_output++,$field->{'title'});
                 $cols_output=0;      }
                 my ($num,$tries,$mod,$mean,$Solved,$solved,$DegOfDiff,$STD,      $rows_output++;
                     $SKEW) = &Apache::loncoursedata::get_problem_statistics      foreach my $data (@StatsArray) {
                         (undef,$resource->{'symb'},$part,          $cols_output=0;
                          $ENV{'request.course.id'});          foreach my $field (@Fields) {
                 #              next if ($field->{'name'} eq 'problem_num');
                 if (!defined($part) || $part eq '') {              $excel_sheet->write($rows_output,$cols_output++,
                     $part = ' ';                                  $data->{$field->{'name'}});
                 }  
                 my $wrongpercent = 0;  
                 if (defined($num) && $num > 0) {  
                     $wrongpercent=int(10*100*($num-$Solved+$solved)/$num)/10;  
                 }  
                 foreach ($sequence->{'title'},$resource->{'title'},$part,  
                          $num,$tries,$mod,$mean,$Solved,$solved,$wrongpercent,  
                          $DegOfDiff,$STD,$SKEW) {  
                     $excel_sheet->write($rows_output,$cols_output++,$_);  
                 }  
                 $rows_output++;  
             }  
         }          }
           $rows_output++;
     }      }
     #      #
     # Write the excel file  
     $excel_workbook->close();      $excel_workbook->close();
       #
     # Tell the user where to get their excel file      # Tell the user where to get their excel file
     $r->print('<br />'.      $r->print('<br />'.
               '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");                '<a href="'.$filename.'">'.
                 &mt('Your Excel Spreadsheet').'</a>'."\n");
     $r->rflush();      $r->rflush();
     return;      return;
 }  }
   
 ###############################################  ##################################################
 ###############################################  ##################################################
   ##
   ## Statistics Gathering and Manipulation Routines
   ##
   ##################################################
   ##################################################
   sub compute_statistics_on_sequence {
       my ($seq) = @_;
       my @Data;
       foreach my $res (@{$seq->{'contents'}}) {
           next if ($res->{'type'} ne 'assessment');
           foreach my $part (@{$res->{'parts'}}) {
               #
               # This is where all the work happens
               my $data = &get_statistics($seq,$res,$part,scalar(@StatsArray)+1);
               push (@Data,$data);
               push (@StatsArray,$data);
           }
       }
       return @Data;
   }
   
 ###############################################  sub compute_all_statistics {
 ###############################################      my ($r) = @_;
 sub statistics_html_table_data {      if (@StatsArray > 0) {
     my ($resource,$part,$num,$tries,$mod,$mean,$Solved,$solved,$wrongpercent,          # Assume we have already computed the statistics
         $DegOfDiff,$STD,$SKEW,$options) = @_;          return;
     my $row = '';      }
     $row .= '<td bgcolor="#FFFFE6">'.      my $c = $r->connection;
         '<a href="'.$resource->{'src'}.'" target="_blank" >'.      foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
             $resource->{'title'}.'</a>'.          last if ($c->aborted);
                 '</td>';          next if ($seq->{'num_assess'} < 1);
     $row .= '<td bgcolor="#FFFFE6">'.$part.'</td>' if ($options !~ /no part/);          &compute_statistics_on_sequence($seq);
     foreach ($num,$tries) {  
         $row .= '<td bgcolor="#EEFFCC" align="right">'.$_.'</td>';  
     }  
     foreach ($mod,$mean) {  
         $row .= '<td bgcolor="#DDFFFF" align="right">'.  
                   sprintf("%5.2f",$_).'</td>';  
     }  
     foreach ($Solved,$solved) {  
         $row .= '<td bgcolor="#DDFFFF" align="right">'.$_.'</td>';  
     }  
     foreach ($wrongpercent) {  
         $row .= '<td bgcolor="#DDFFFF" align="right">'.  
                   sprintf("%5.1f",$_).'</td>';  
     }  
     foreach ($DegOfDiff,$STD,$SKEW) {  
         $row .= '<td bgcolor="#FFDDDD" align="right">'.  
                   sprintf("%5.2f",$_).'</td>';  
     }      }
     return $row;  
 }  }
   
 ###############################################  sub sort_data {
 ###############################################      my ($sortkey) = @_;
 sub plot_statistics {      return if (! @StatsArray);
     my ($r,$datafield) = @_;  
     my @Data;  
     #      #
     my %Fields = ('#Stdnts'=> 0,      # Sort the data
                   'Tries'  => 1,      my $sortby = undef;
                   'Mod'    => 2,      foreach my $field (@Fields) {
                   'Mean'   => 3,          if ($sortkey eq $field->{'name'}) {
                   '#YES'   => 4,              $sortby = $field->{'name'};
                   '#yes'   => 5,  
                   '%Wrng'  => 9,  
                   'DoDiff' => 6,  
                   'S.D.'   => 7,  
                   'Skew'   => 8,);  
     #  
     my $field = '%Wrng';  
     foreach (keys(%Fields)) {  
         $field = $_ if ($datafield eq $_);  
     }  
     my $fieldindex = $Fields{$field};  
     #  
     my $Max = 0;  
     foreach my $sequence (&Apache::lonstatistics::Sequences_with_Assess()) {  
         next if ($sequence->{'num_assess'}<1);  
         foreach my $resource (@{$sequence->{'contents'}}) {  
             next if ($resource->{'type'} ne 'assessment');  
             foreach my $part (@{$resource->{'parts'}}) {  
                 my @Results = &Apache::loncoursedata::get_problem_statistics  
                         (undef,$resource->{'symb'},$part,  
                          $ENV{'request.course.id'});  
                 my ($num,$Solved,$solved) = @Results[0,4,5];  
                 my $wrongpercent = 0;  
                 if (defined($num) && $num > 0) {  
                     $wrongpercent=int(10*100*($num-$Solved+$solved)/$num)/10;  
                 }  
                 push (@Results,$wrongpercent);  
                 my $data = $Results[$fieldindex];  
                 $Max = $data if ($Max<$data);  
                 push (@Data,$data);  
             }  
         }          }
     }      }
     #      if (! defined($sortby) || $sortby eq '' || $sortby eq 'problem_num') {
     # Print out plot request          $sortby = 'container';
     my $title = 'Percent Wrong';      }
     if ($field eq 'DoDiff') {      if ($sortby ne 'container') {
         $title = 'Degree of Difficulty';          # $sortby is already defined, so we can charge ahead
     }          if ($sortby =~ /^(title|part)$/i) {
     my $yaxis = 'Percent';              # Alpha comparison
     if ($field eq 'DoDiff') {              @StatsArray = sort {
         $yaxis = '';                  lc($a->{$sortby}) cmp lc($b->{$sortby}) ||
     } elsif ($field ne '%Wrng') {                  lc($a->{'title'}) cmp lc($b->{'title'}) ||
         $yaxis = '';                  lc($a->{'part'}) cmp lc($b->{'part'});
     }              } @StatsArray;
     #  
     # Determine appropriate value for $Max  
     if ($field eq 'DoDiff') {  
         if ($Max > 0.5) {  
             $Max = 1;  
         } elsif ($Max > 0.2) {  
             $Max = 0.5;  
         } elsif ($Max > 0.1) {  
             $Max = 0.2;  
         }  
     } elsif ($field eq '%Wrng') {  
         if ($Max > 50) {  
             $Max = 100;  
         } elsif ($Max > 25) {  
             $Max = 50;  
         } elsif ($Max > 20) {  
             $Max = 25;  
         } elsif ($Max > 10) {  
             $Max = 20;  
         } elsif ($Max > 5) {  
             $Max = 10;  
         } else {          } else {
             $Max = 5;              # Numerical comparison
               @StatsArray = sort {
                   my $retvalue = 0;
                   if ($b->{$sortby} eq 'nan') {
                       if ($a->{$sortby} ne 'nan') {
                           $retvalue = -1;
                       } else {
                           $retvalue = 0;
                       }
                   }
                   if ($a->{$sortby} eq 'nan') {
                       if ($b->{$sortby} ne 'nan') {
                           $retvalue = 1;
                       }
                   }
                   if ($retvalue eq '0') {
                       $retvalue = $b->{$sortby} <=> $a->{$sortby}     ||
                               lc($a->{'title'}) <=> lc($b->{'title'}) ||
                               lc($a->{'part'})  <=> lc($b->{'part'});
                   }
                   $retvalue;
               } @StatsArray;
         }          }
     }      }
       
     $r->print("<p>".&DrawGraph(\@Data,$title,'Problem Number',$yaxis,  
                                $Max)."</p>\n");  
     #      #
     # Print out the data      # Renumber the data set
     $ENV{'form.sortby'} = 'Contents';      my $count;
     &output_html_ungrouped($r,'show probnum');      foreach my $data (@StatsArray) {
           $data->{'problem_num'} = ++$count;
       }
     return;      return;
 }  }
   
   ########################################################
   ########################################################
   
   =pod
   
   =item &get_statistics()
   
   Wrapper routine from the call to loncoursedata::get_problem_statistics.  
   Calls lonstathelpers::get_time_limits() to limit the data set by time
   and &compute_discrimination_factor
   
   Inputs: $sequence, $resource, $part, $problem_num
   
   Returns: Hash reference with statistics data from 
   loncoursedata::get_problem_statistics.
   
   =cut
   
   ########################################################
   ########################################################
   sub get_statistics {
       my ($sequence,$resource,$part,$problem_num) = @_;
       #
       my ($starttime,$endtime) = &Apache::lonstathelpers::get_time_limits();
       my $symb = $resource->{'symb'};
       my $courseid = $ENV{'request.course.id'};
       #
       my $data = &Apache::loncoursedata::get_problem_statistics
                           (\@Apache::lonstatistics::SelectedSections,
                            $Apache::lonstatistics::enrollment_status,
                            $symb,$part,$courseid,$starttime,$endtime);
       $data->{'part'}        = $part;
       $data->{'problem_num'} = $problem_num;
       $data->{'container'}   = $sequence->{'title'};
       $data->{'title'}       = $resource->{'title'};
       $data->{'title.link'}  = $resource->{'src'}.'?symb='.
           &Apache::lonnet::escape($resource->{'symb'});
       #
       $data->{'deg_of_disc'} = &compute_discrimination_factor($resource,$part,$sequence);
       return $data;
   }
   
   
 ###############################################  ###############################################
 ###############################################  ###############################################
   
   =pod
   
   =item &compute_discrimination_factor()
   
   Inputs: $Resource, $Sequence
   
   Returns: integer between -1 and 1
   
   =cut
   
 ###############################################  ###############################################
 ###############################################  ###############################################
 sub DrawGraph {  sub compute_discrimination_factor {
     my ($values,$title,$xaxis,$yaxis,$Max)=@_;      my ($resource,$part,$sequence) = @_;
     $title = '' if (! defined($title));          my @Resources;
     $xaxis = '' if (! defined($xaxis));      foreach my $res (@{$sequence->{'contents'}}) {
     $yaxis = '' if (! defined($yaxis));          next if ($res->{'symb'} eq $resource->{'symb'});
     #          push (@Resources,$res->{'symb'});
     my $sendValues = join(',', @$values);      }
     my $sendCount = scalar(@$values);      #
     if ( $Max > 1 ) {      # rank
  if ($Max % 10) {      my $ranking = 
             if ( int($Max) < $Max ) {          &Apache::loncoursedata::rank_students_by_scores_on_resources
      $Max++;          (\@Resources,
  $Max = int($Max);           \@Apache::lonstatistics::SelectedSections,
     }           $Apache::lonstatistics::enrollment_status,undef);
  }      #
     } else {       # compute their percent scores on the problems in the sequence,
         $Max = 1;       my $number_to_grab = int(scalar(@{$ranking})/4);
     }      my $num_students = scalar(@{$ranking});
     my @GData = ($title,$xaxis,$yaxis,$Max,$sendCount,$sendValues);      my @BottomSet = map { $_->[&Apache::loncoursedata::RNK_student()]; 
     return '<IMG src="/cgi-bin/graph.png?'.                        } @{$ranking}[0..$number_to_grab];
         (join('&', @GData)).'" border="1" />';      my @TopSet    = 
           map { 
               $_->[&Apache::loncoursedata::RNK_student()]; 
             } @{$ranking}[($num_students-$number_to_grab)..($num_students-1)];
       my ($bottom_sum,$bottom_max) = 
           &Apache::loncoursedata::get_sum_of_scores($resource,$part,\@BottomSet);
       my ($top_sum,$top_max) = 
           &Apache::loncoursedata::get_sum_of_scores($resource,$part,\@TopSet);
       my $deg_of_disc;
       if ($top_max == 0 || $bottom_max==0) {
           $deg_of_disc = 'nan';
       } else {
           $deg_of_disc = ($top_sum/$top_max) - ($bottom_sum/$bottom_max);
       }
       #&Apache::lonnet::logthis('    '.$top_sum.'/'.$top_max.
       #                         ' - '.$bottom_sum.'/'.$bottom_max);
       return $deg_of_disc;
 }  }
   
 ###############################################  ###############################################
 ###############################################  ###############################################
   
 ###############################################  =pod 
 ###############################################  
 sub ProblemStatisticsLegend {  =item ProblemStatisticsLegend
     my $Ptr = '';  
     $Ptr = '<table border="0">';  =over 4
     $Ptr .= '<tr><td>';  
     $Ptr .= '<b>#Stdnts</b></td>';  =item #Stdnts
     $Ptr .= '<td>Total number of students attempted the problem.';  Total number of students attempted the problem.
     $Ptr .= '</td></tr><tr><td>';  
     $Ptr .= '<b>Tries</b></td>';  =item Tries
     $Ptr .= '<td>Total number of tries for solving the problem.';  Total number of tries for solving the problem.
     $Ptr .= '</td></tr><tr><td>';  
     $Ptr .= '<b>Mod</b></td>';  =item Max Tries
     $Ptr .= '<td>Largest number of tries for solving the problem by a student.';  Largest number of tries for solving the problem by a student.
     $Ptr .= '</td></tr><tr><td>';  
     $Ptr .= '<b>Mean</b></td>';  =item Mean
     $Ptr .= '<td>Average number of tries. [ Tries / #Stdnts ]';  Average number of tries. [ Tries / #Stdnts ]
     $Ptr .= '</td></tr><tr><td>';  
     $Ptr .= '<b>#YES</b></td>';  =item #YES
     $Ptr .= '<td>Number of students solved the problem correctly.';  Number of students solved the problem correctly.
     $Ptr .= '</td></tr><tr><td>';  
     $Ptr .= '<b>#yes</b></td>';  =item #yes
     $Ptr .= '<td>Number of students solved the problem by override.';  Number of students solved the problem by override.
     $Ptr .= '</td></tr><tr><td>';  
     $Ptr .= '<b>%Wrong</b></td>';  =item %Wrong
     $Ptr .= '<td>Percentage of students who tried to solve the problem ';  Percentage of students who tried to solve the problem 
     $Ptr .= 'but is still incorrect. [ 100*((#Stdnts-(#YES+#yes))/#Stdnts) ]';  but is still incorrect. [ 100*((#Stdnts-(#YES+#yes))/#Stdnts) ]
     $Ptr .= '</td></tr><tr><td>';  
     $Ptr .= '<b>DoDiff</b></td>';  =item DoDiff
     $Ptr .= '<td>Degree of Difficulty of the problem.  ';  Degree of Difficulty of the problem.  
     $Ptr .= '[ 1 - ((#YES+#yes) / Tries) ]';  [ 1 - ((#YES+#yes) / Tries) ]
     $Ptr .= '</td></tr><tr><td>';  
     $Ptr .= '<b>S.D.</b></td>';  =item S.D.
     $Ptr .= '<td>Standard Deviation of the tries.  ';  Standard Deviation of the tries.  
     $Ptr .= '[ sqrt(sum((Xi - Mean)^2)) / (#Stdnts-1) ';  [ sqrt(sum((Xi - Mean)^2)) / (#Stdnts-1) 
     $Ptr .= 'where Xi denotes every student\'s tries ]';  where Xi denotes every student\'s tries ]
     $Ptr .= '</td></tr><tr><td>';  
     $Ptr .= '<b>Skew.</b></td>';  =item Skew.
     $Ptr .= '<td>Skewness of the students tries.';  Skewness of the students tries.
     $Ptr .= '[(sqrt( sum((Xi - Mean)^3) / #Stdnts)) / (S.D.^3)]';  [(sqrt( sum((Xi - Mean)^3) / #Stdnts)) / (S.D.^3)]
     $Ptr .= '</td></tr><tr><td>';  
     $Ptr .= '<b>Dis.F.</b></td>';  =item Dis.F.
     $Ptr .= '<td>Discrimination Factor: A Standard for evaluating the ';  Discrimination Factor: A Standard for evaluating the 
     $Ptr .= 'problem according to a Criterion<br>';  problem according to a Criterion<br>
     $Ptr .= '<b>[Criterion to group students into %27 Upper Students - ';  
     $Ptr .= 'and %27 Lower Students]</b><br>';  =item [Criterion to group students into %27 Upper Students - 
     $Ptr .= '<b>1st Criterion</b> for Sorting the Students: ';  and %27 Lower Students]
     $Ptr .= '<b>Sum of Partial Credit Awarded / Total Number of Tries</b><br>';  1st Criterion for Sorting the Students: 
     $Ptr .= '<b>2nd Criterion</b> for Sorting the Students: ';  Sum of Partial Credit Awarded / Total Number of Tries
     $Ptr .= '<b>Total number of Correct Answers / Total Number of Tries</b>';  2nd Criterion for Sorting the Students: 
     $Ptr .= '</td></tr>';  Total number of Correct Answers / Total Number of Tries
     $Ptr .= '<tr><td><b>Disc.</b></td>';  
     $Ptr .= '<td>Number of Students had at least one discussion.';  =item Disc.
     $Ptr .= '</td></tr></table>';  Number of Students had at least one discussion.
     return $Ptr;  
   =back
   
   =cut
   
   
   ############################################################
   ############################################################
   ##
   ##  How this all works:
   ##     Statistics are computed by calling &get_statistics with the sequence,
   ##     resource, and part id to run statistics on.  At various places within
   ##     the loops which compute the statistics, as well as before and after 
   ##     the entire process, subroutines can be called.  The subroutines are
   ##     registered to the following hooks:
   ##
   ##         hook          subroutine inputs
   ##     ----------------------------------------------------------
   ##         pre           $r,$count
   ##         pre_seq       $r,$count,$seq
   ##         pre_res       $r,$count,$seq,$res
   ##         calc          $r,$count,$seq,$res,$data
   ##         post_res      $r,$count,$seq,$res
   ##         post_seq      $r,$count,$seq
   ##         post          $r,$count
   ##
   ##         abort         $r
   ##
   ##     subroutines will be called in the order in which they are registered.
   ##   
   ############################################################
   ############################################################
   {
   
   my %hooks;
   my $aborted = 0;
   
   sub abort_computation {
       $aborted = 1;
 }  }
   
 #---- END Problem Statistics Web Page ----------------------------------------  sub clear_hooks {
       $aborted = 0;
       undef(%hooks);
   }
   
   sub register_hook {
       my ($hookname,$subref)=@_;
       if ($hookname !~ /^(pre|pre_seq|pre_res|post|post_seq|post_res|calc)$/){
           return;
       }
       if (ref($subref) ne 'CODE') {
           &Apache::lonnet::logthis('attempt to register hook to non-code: '.
                                    $hookname,' = '.$subref);
       } else {
           if (exists($hooks{$hookname})) {
               push(@{$hooks{$hookname}},$subref);
           } else {
               $hooks{$hookname} = [$subref];
           }
       }
       return;
   }
   
   sub run_hooks {
       my $context = shift();
       foreach my $hook (@{$hooks{$context}}) { 
           if ($aborted && $context ne 'abort') {
               last;
           }
           my $retvalue = $hook->(@_);
           if (defined($retvalue) && $retvalue eq '0') {
               $aborted = 1 if (! $aborted);
           }
       }
   }
   
   sub run_statistics {
       my ($r) = @_;
       my $count = 0;
       &run_hooks('pre',$r,$count);
       foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
           last if ($aborted);
           next if ($seq->{'num_assess'}<1);
           &run_hooks('pre_seq',$r,$count,$seq);
           foreach my $res (@{$seq->{'contents'}}) {
               last if ($aborted);
               next if ($res->{'type'} ne 'assessment');
               &run_hooks('pre_res',$r,$count,$seq,$res);            
               foreach my $part (@{$res->{'parts'}}) {
                   last if ($aborted);
                   #
                   # This is where all the work happens
                   my $data = &get_statistics($seq,$res,$part,++$count);
                   &run_hooks('calc',$r,$count,$seq,$res,$part,$data); 
               }
               &run_hooks('post_res',$r,$count,$seq,$res);
           }
           &run_hooks('post_seq',$r,$count,$seq);
       }
       if ($aborted) {
           &run_hooks('abort',$r);
       } else {
           &run_hooks('post',$r,$count);
       }
       return;
   }
   
   } # End of %hooks scope
   
   ############################################################
   ############################################################
   
 1;  1;
 __END__  __END__

Removed from v.1.45  
changed lines
  Added in v.1.73


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