Diff for /loncom/interface/statistics/lonproblemstatistics.pm between versions 1.2 and 1.46

version 1.2, 2002/07/25 19:29:23 version 1.46, 2003/03/26 21:55:18
Line 1 Line 1
 # The LearningOnline Network with CAPA  # The LearningOnline Network with CAPA
 # (Publication Handler  
 #  #
 # $Id$  # $Id$
 #  #
Line 26 Line 25
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
 # (Navigate problems for statistical reports  # (Navigate problems for statistical reports
 # YEAR=2001  
 # 5/5,7/9,7/25/1,8/11,9/13,9/26,10/5,10/9,10/22,10/26 Behrouz Minaei  
 # 11/1,11/4,11/16,12/14,12/16,12/18,12/20,12/31 Behrouz Minaei  
 # YEAR=2002  
 # 1/22,2/1,2/6,2/25,3/2,3/6,3/17,3/21,3/22,3/26,4/7,5/6 Behrouz Minaei  
 # 5/12,5/14,5/15,5/19,5/26,7/16,7/25  Behrouz Minaei  
 #  #
 ###  ###
   
 package Apache::lonproblemstatistics;   package Apache::lonproblemstatistics;
   
 use strict;  use strict;
 use Apache::lonnet();  use Apache::lonnet();
 use Apache::lonhtmlcommon;  use Apache::lonhtmlcommon;
 use Apache::loncoursedata;  use Apache::loncoursedata;
 use GDBM_File;  use Apache::lonstatistics;
   use Spreadsheet::WriteExcel;
   
 my %mapsort;  #######################################################
   #######################################################
   
 sub BuildProblemStatisticsPage {  sub CreateInterface {
     my ($cacheDB, $students, $courseID, $c, $r,%color)=@_;      my $Str = '';
     my %cache;      $Str .= '<table cellspacing="5">'."\n";
     #my %DoDiff;      $Str .= '<tr>';
     unless(tie(%cache,'GDBM_File',$cacheDB,&GDBM_READER,0640)) {      $Str .= '<td align="center"><b>Sections</b></td>';
         return '<html><body>Unable to tie database.</body></html>';      $Str .= '<td align="center"><b>Sequences and Folders</b></td>';
     }      $Str .= '<td align="center"><b>Output</b></td>';
       $Str .= '</tr>'."\n";
     my $Ptr = '';      #
     $Ptr .= '<table border="0"><tbody>';      $Str .= '<tr><td align="center">'."\n";
     $Ptr .= '<tr><td align="right"><b>Select Map</b></td>'."\n";      $Str .= &Apache::lonstatistics::SectionSelect('Section','multiple',5);
     $Ptr .= '<td align="left">';      $Str .= '</td><td align="center">';
     $Ptr .= &Apache::lonhtmlcommon::MapOptions(\%cache, 'ProblemStatistics');      #
     $Ptr .= '</td></tr>'."\n";      my $only_seq_with_assessments = sub { 
     $Ptr .= &AscendOrderOptions($cache{'Ascend'});          my $s=shift;
     $Ptr .= &ProblemStatisticsButtons($cache{'DisplayFormat'});          if ($s->{'num_assess'} < 1) { 
     $Ptr .= '</table>';              return 0;
           } else { 
     $Ptr .= &ProblemStatisticsLegend();              return 1;
   
     untie(%cache);  
     foreach (@$students) {  
         my $courseData =   
             &Apache::loncoursedata::DownloadCourseInformation($_, $courseID);  
         last if ($c->aborted());  
         if(tie(%cache,'GDBM_File',$cacheDB,&GDBM_WRCREAT,0640)) {  
             &Apache::loncoursedata::ProcessStudentData(\%cache,   
                                                        $courseData, $_);  
             untie(%cache);  
         }          }
     }      };
     if($c->aborted()) { return $Ptr; }      $Str .= &Apache::lonstatistics::MapSelect('Maps','multiple,all',5,
                                                 $only_seq_with_assessments);
     unless(tie(%cache,'GDBM_File',$cacheDB,&GDBM_READER,0640)) {      $Str .= '</td><td>'."\n";
         return '<html><body>Unable to tie database.</body></html>';      $Str .= &CreateAndParseOutputSelector();
     }      $Str .= '</td></tr>'."\n";
     my $discriminantFactor;      $Str .= '</table>'."\n";
     my @list=();      return $Str;
     my %Discuss=&Apache::loncoursedata::LoadDiscussion($courseID);  
     my $index=0;  
     foreach (@$students) {  
  #&Apache::lonstatistics::Update_PrgWin(++$index,$r);  
         $discriminantFactor = &ExtractStudentData(\%cache, $_, \@list,\%Discuss);  
     }  
     #&Apache::lonstatistics::Close_PrgWin($r);  
   
     return $Ptr;  
     my ($upper, $lower) = &Discriminant($discriminantFactor);  
     my %Header = (0,"Homework Sets Order",1,"#Stdnts",2,"Tries",3,"Mod",  
                   4,"Mean",5,"#YES",6,"#yes",7,"%Wrng",8,"DoDiff",  
                   9,"S.D.",10,"Skew.",11,"D.F.1st",12,"D.F.2nd", 13, "Disc.");  
   
     my %GraphDat= &BuildStatisticsTable(\%cache, $discriminantFactor, \@list,   
                                         \%Header, $students, $r, \%color);  
   
     untie(%cache);  
   
     return $Ptr;  
 }  }
   
 sub BuildDiffGraph {  #######################################################
     my ($r)=@_;  #######################################################
   
     my $graphData = &GetGraphData('DiffGraph', $r);  =pod
     return '<IMG src="/cgi-bin/graph.gif?'.$graphData.'" />';  
 }  
   
 sub BuildWrongGraph {  =item &CreateAndParseOutputSelector()
     my ($r)=@_;  
   
     my $graphData = &GetGraphData('WrongGraph', $r);  =cut
     return '<IMG src="/cgi-bin/graph.gif?'.$graphData.'" />';  
 }  
   
 #---- Activity log -------------------------------------------------------  #######################################################
   #######################################################
   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 LoadDoDiffFile {  sub OutputDescriptions {
     my $file="/home/minaeibi/183d.txt";      my $Str = '';
     open(FILEID, "<$file");      $Str .= "<h2>Output Modes</h2>\n";
     my $line=<FILEID>;      $Str .= "<dl>\n";
     my %DoDiff=();      foreach my $outputmode (@OutputOptions) {
     my @Act=split('&',$line);   $Str .="    <dt>".$outputmode->{'name'}."</dt>\n";
        $Str .="        <dd>".$outputmode->{'description'}."</dd>\n";
 #    $r->print('<br>'.$#Act);  
     for(my $n=0;$n<=$#Act;$n++){  
        my ($res,$Degree)=split('@',$Act[$n]);  
       $DoDiff{$res}=$Degree;  
     }      }
       $Str .= "</dl>\n";
     return \%DoDiff;      return $Str;
 }  }
   
 sub LoadClassFile {  sub CreateAndParseOutputSelector {
     my $file="/home/minaeibi/class.txt";      my $Str = '';
     open(FILEID, "<$file");      my $elementname = 'outputmode';
     my $line;      #
     my %Grade=();      # Format for output options is 'mode, restrictions';
     while ($line=<FILEID>) {      my $selected = 'html, with links';
         my ($id,$ex1,$ex2,$ex3,$ex4,$hw,$final,$grade)=split(' ',$line);      if (exists($ENV{'form.'.$elementname})) {
         $Grade{$id}=$grade;          if (ref($ENV{'form.'.$elementname} eq 'ARRAY')) {
               $selected = $ENV{'form.'.$elementname}->[0];
           } else {
               $selected = $ENV{'form.'.$elementname};
           }
     }      }
     return \%Grade;      #
 }      # Set package variables describing output mode
       $output_mode = 'html';
 #------- Classification        $show        = 'all';
 sub Classify {      foreach my $option (@OutputOptions) {
     my ($DiscFac, $students)=@_;          next if ($option->{'value'} ne $selected);
     my ($fileGrade) = &LoadClassFile();          $output_mode = $option->{'mode'};
     my $Count=0;          $show        = $option->{'show'};
     my @List=();      }
     my @LS=();      #
     my @LF=();      # Build the form element
     my @LM=();      $Str = qq/<select size="5" name="$elementname">/;
     my $cf=0;      foreach my $option (@OutputOptions) {
     my $cs=0;          $Str .= "\n".'    <option value="'.$option->{'value'}.'"';
     my $cm=0;          $Str .= " selected " if ($option->{'value'} eq $selected);
     foreach (keys(%$DiscFac)){            $Str .= ">".$option->{'name'}."<\/option>";
  my @l=split(/\:/,$_);  
  if (!($students->{$l[1]})) {next;}  
  my $Grade=$fileGrade->{$students->{$l[1]}};  
  if( $Grade > 3 ) {  
     $cs++;  
     push(@LS,("$l[6],$l[5],$l[4],$l[7],$l[8],$l[9],Successful"));  
  } elsif ( $Grade > 2 ) {  
     $cm++;  
     push(@LM,("$l[6],$l[5],$l[4],$l[7],$l[8],$l[9],Average"));  
  } else {  
     $cf++;  
     push(@LF,("$l[6],$l[5],$l[4],$l[7],$l[8],$l[9],Failed"));  
  }  
     }      }
     my $Str = '';      $Str .= "\n</select>";
     for(my $n=0;$n<$cs;$n++){$Str .= '<br>'.$LS[$n];}  
     for(my $n=0;$n<$cm;$n++){$Str .= '<br>'.$LM[$n];}    
     for(my $n=0;$n<$cf;$n++){$Str .= '<br>'.$LF[$n];}  
   
     return $Str;      return $Str;
 }   }
   
 sub ProcAct {  
     # return;  
     my ($Act,$Submit)=@_;  
     my @Act=split(/\@/,$Act);  
     @Act = sort(@Act);  
   
     ##$r->print('<br>'.$#Act);  
     ##for(my $n=0;$n<=$#Act;$n++){  
 ## $r->print('<br>n='.$n.')'.$Act[$n]);  
 ##    }  
   
 #    my $Beg=$Act[0];  
     my $Dif=$Submit-$Act[0];  
     $Dif = ($Dif>0) ? ($Dif/3600) : 0;   
   
 #    $r->print('<br>Access Number = '.$#Act.'<br>Submit Time='.$Submit.'<br>First Access='.$Act[0].'<br>Last Access='.$Act[$#Act].'<br> Submit - First = <b>'.$Dif.'</b>');  
   
   
 #time spent for solving the problem             ###############################################
 #    $r->print('<br>Def'.($Act[$#Act-1]-$Act[0]));  ###############################################
   
     return $Dif;  ###############################################
   ###############################################
   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();
 }  }
   
 sub LoadActivityLog {  ###############################################
 #    my $CacheDB = "/home/minaeibi/act183.log.cache";  ###############################################
     my $CacheDB = "/home/httpd/perl/tmp/act183.log.cache";  
   ###############################################
     my %Activity;  ###############################################
     if (-e "$CacheDB") {  sub BuildProblemStatisticsPage {
  if (tie(%Activity,'GDBM_File',"$CacheDB",&GDBM_READER,0640)) {      my ($r,$c)=@_;
     return;      #
         }      $output_mode = 'html';
         else {      $show = 'grouped';
 #    $r->print("Unable to tie log Cache hash to db file");      #
       $r->print(&CreateInterface());
       $r->print('<input type="hidden" name="statsfirstcall" value="no" />');
       $r->print('<input type="hidden" name="sortby" value="'.$ENV{'form.sortby'}.
                 '" />');
       if (! exists($ENV{'form.statsfirstcall'})) {
           return;
       }
       #
       &Gather_Student_Data($r);
       #
       #
       if ($output_mode eq 'html') {
           $r->print("<h2>".
                     $ENV{'course.'.$ENV{'request.course.id'}.'.description'}.
                     "</h2>\n");
           $r->print("<h3>".localtime(time)."</h3>");
           $r->rflush();
           if ($show eq 'grouped') {
               &output_html_grouped_by_sequence($r);
           } elsif ($show eq 'ungrouped') {
               &output_html_ungrouped($r);
         }          }
     }      } elsif ($output_mode eq 'excel') {
     else {          $r->print("<h2>Preparing Excel Spreadsheet</h2>");
  if (tie(%Activity,'GDBM_File',$CacheDB,&GDBM_WRCREAT,0640)) {          &output_excel($r);
     foreach (keys %Activity) {delete $Activity{$_};}      } elsif ($output_mode eq 'plot') {
     &Build_log(\%Activity);           if ($show eq 'deg of diff') {
  }              &plot_statistics($r,'DoDiff');
         else {          } elsif ($show eq 'per wrong') {
 #    $r->print("Unable to tie log Build hash to db file");              &plot_statistics($r,'%Wrng');
         }          }
       } else {
           $r->print("<h1>Not implemented</h1>");
     }      }
     return \%Activity;      return;
 }  }
   
 sub Build_log {  ###############################################
     my ($Activity)=@_;  ###############################################
     my $file="/home/minaeibi/act183.log";  
     open(FILEID, "<$file");  
     my $line;  
     my $count=0;  
     while ($line=<FILEID>) {  
  my ($time,$machine,$what)=split(':',$line);  
  $what=&Apache::lonnet::unescape($what);  
  my @accesses=split('&',$what);  
              
  foreach my $access (@accesses) {  
   
     $count++;  
   
     my ($date,$resource,$who,$domain,$post,@posts)=split(':',$access);  
     if (!$resource) { next; }  
     my $res=&Apache::lonnet::unescape($resource);  
     if (($res =~ /\.problem/)) {  
  $Activity->{$who.':'.$res}.=$date.'@';  
                 #$r->print('<br>'.$time.':'.$who.'---'.$res);  
  &Update_PrgInit($count);  
   
     }  ###############################################
  }  ###############################################
   sub output_html_grouped_by_sequence {
       my ($r) = @_;
       my $problem_num = 0;
       #$r->print(&ProblemStatisticsLegend());
       my @Header = ("Title","Part","#Stdnts","Tries","Mod",
                     "Mean","#YES","#yes","%Wrng","DoDiff",
                     "S.D.","Skew.");#,"D.F.1st","D.F.2nd");
       # #FFFFE6 #EEFFCC #DDFFFF FFDDDD #DDFFDD #FFDDFF
       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");
               }
           }
           $r->print("</table>\n");
           $r->print("</td></tr></table>\n");
           $r->rflush();
       }
       #
       return;
   }
   
   ###############################################
   ###############################################
   
   ###############################################
   ###############################################
   sub output_html_ungrouped {
       my ($r,$option) = @_;
       #
       my $problem_num = 0;
       my $show_container = 0;
       my $show_part = 0;
       #$r->print(&ProblemStatisticsLegend());
       my @Header = ("Title","Part","#Stdnts","Tries","Mod",
                     "Mean","#YES","#yes","%Wrng","DoDiff",
                     "S.D.","Skew");#,"D.F.1st","D.F.2nd");
       #
       my $sortby = undef;
       foreach (@Header) {
           if ($ENV{'form.sortby'} eq $_) {
               $sortby = $_;
           }
     }      }
       if (! defined($sortby) || $sortby eq '') {
 # my $c=1;          $sortby = 'Container';
 # foreach (sort keys %Activity) {  
 #     $r->print('<br>'.$c.')'.$_.' ... '.$Activity{$_});  
 #     $c++;  
 # }  
   
 }  
   
 sub Activity {  
     my $file="/home/minaeibi/activity.log";  
     my $userid='adamsde1';  
 #    $r->print("<br>Using $file");  
 #    $r->rflush();  
     open(FILEID, "<$file");  
     my $line;  
     my @allaccess;  
     my $Count=0;  
     while ($line=<FILEID>) {  
  my ($time,$machine,$what)=split(':',$line);  
  $what=&Apache::lonnet::unescape($what);  
  my @accesses=split('&',$what);  
  foreach my $access (@accesses) {  
     my ($date,$resource,$who,$domain,$post,@posts)=split(':',$access);  
     #if ($who ne $userid) { next; }  
     if (!$resource) { next; }  
     my $res=&Apache::lonnet::unescape($resource);  
     if (($res =~ /\.(sequence|problem|htm|html|page)/)) {  
      $Count++;  
 ###888 $r->print("<br>$Count) ".localtime($date).": $who --> $res");  
 #        if ($post) {   
 #    $Count++;  
 #    $r->print("<br><b>$Count) Sent data ".join(':',  
 #                              &Apache::lonnet::unescape(@posts)).'</b>');  
 # }  
 ###888 $r->rflush();  
     }  
     #push (@allaccess,unescape($access));  
     #print $machine;  
  }  
     }      }
 #    @allaccess=sort(@allaccess);      # If there is more than one sequence, list their titles
 #    $Count=0;      my @Sequences = &Apache::lonstatistics::Sequences_with_Assess();
 #    foreach my $access (@allaccess) {      if (@Sequences > 1) {
 # my ($date,$resource,$who,$domain,$post,@posts)=split(':',$access);          unshift(@Header,"Container");
 # $Count++;          $show_container = 1;
 # $r->print("<br>$Count) $date: $who --> $resource");      }
 # $r->rflush();      # 
 # if ($post) {       # If the option for showing the problem number is needed, push that
 #    $r->print("<br><b>Sent data ".join(':',unescape(@posts)).'</b>');      # on the list too
 # }      if (defined($option) && $option =~ /show probnum/) {
 #    }          unshift(@Header,"P#");
 }  
   
 #---- END Activity log ---------------------------------------------------  
   
 #---- Problem Statistics Web Page ---------------------------------------  
   
 #------- Processing upperlist and lowerlist according to each problem  
 sub ProcessDiscriminant {  
     my ($List) = @_;  
     my @sortedList = sort (@$List);  
     my $Count = scalar @sortedList;  
     my $Problem;  
     my @Dis;  
     my $Slvd=0;  
     my $tmp;  
     my $Sum1=0;  
     my $Sum2=0;  
     my $nIndex=0;  
     my $nStudent=0;  
     my %Proc=undef;  
     while ($nIndex<$Count) {  
  ($Problem,$tmp)=split(/\=/,$sortedList[$nIndex]);  
  @Dis=split(/\+/,$tmp);  
  my $Temp = $Problem;  
  do {  
     $nIndex++;  
     $nStudent++;  
     $Sum1 += $Dis[0];  
     $Sum2 += $Dis[1];  
     ($Problem,$tmp)=split(/\=/,$sortedList[$nIndex]);  
     @Dis=split(/\+/,$tmp);  
  } while ( $Problem eq $Temp && $nIndex < $Count );  
 # $Proc{$Temp}=($Sum1/$nStudent).':'.$nStudent;  
  $Proc{$Temp}=($Sum1/$nStudent).':'.($Sum2/$nStudent);  
 #       $r->print("$nIndex) $Temp --> ($nStudent) $Proc{$Temp} <br>");  
  $Sum1=0;  
  $Sum2=0;  
  $nStudent=0;  
     }      }
       #
     return %Proc;      $r->print('<table border="0"><tr><td bgcolor="#777777">'."\n");
 }      $r->rflush();
       #
 #------- Creating Discimination factor         # Compile the data
 sub Discriminant {      my @Statsarray;
     my ($discriminantFactor)=@_;      foreach my $sequence (@Sequences) {
     my @discriminantKeys=keys(%$discriminantFactor);          next if ($sequence->{'num_assess'}<1);
     my $Count = scalar @discriminantKeys;          foreach my $resource (@{$sequence->{'contents'}}) {
               next if ($resource->{'type'} ne 'assessment');
     my $UpCnt = int(0.27*$Count);              foreach my $part (@{$resource->{'parts'}}) {
     my $low=0;                  $problem_num++;
     my $up=$Count-$UpCnt;                  my ($num,$tries,$mod,$mean,$Solved,$solved,$DegOfDiff,$STD,
     my @UpList=();                      $SKEW) = &Apache::loncoursedata::get_problem_statistics
     my @LowList=();                          (undef,$resource->{'symb'},$part,
                            $ENV{'request.course.id'});
     $Count=0;                  #
     foreach my $key (sort(@discriminantKeys)) {                   $show_part = 1 if ($part ne '0');
  $Count++;                      $part = '&nbsp;' if ($part == 0);
  if($low < $UpCnt || $Count > $up) {                  #
             $low++;                  my $wrongpercent = 0;
             my $str=$discriminantFactor->{$key};                  if (defined($num) && $num > 0) {
             foreach(split(/\:/,$str)){                      $wrongpercent=int(10*100*($num-$Solved+$solved)/$num)/10;
                 if($_) {  
                     if($low<$UpCnt) { push(@LowList,$_); }  
                     else            { push(@UpList,$_);  }  
                 }                  }
                   push (@Statsarray,
                         { 'sequence' => $sequence,
                           'resource' => $resource,
                           'Title' => $resource->{'title'},
                           'Part'  => $part,
                           '#Stdnts' => $num,
                           'Tries' => $tries,
                           'Mod' => $mod,
                           'Mean' => $mean,
                           '#YES' => $Solved,
                           '#yes' => $solved,
                           '%Wrng' => $wrongpercent,
                           'DoDiff' => $DegOfDiff,
                           'S.D.' => $STD,
                           'Skew' => $SKEW,
                           'problem_num' => $problem_num,
                         });
             }              }
         }          }
     }      }
     my %DisUp =  &ProcessDiscriminant(\@UpList);      #
     my %DisLow = &ProcessDiscriminant(\@LowList);      # Table Headers
       $r->print('<table border="0" cellpadding="3">'."\n");
     return (\%DisUp, \%DisLow);      my $Str = '';
 }      foreach (@Header) {
           next if ($_ eq 'Part' && !$show_part);
              # Do not allow sorting on some fields
 sub NumericSort {                    if ($_ eq $sortby || /^(Part|P\#)$/) {  
     $a <=> $b;              $Str .= '<th>'.$_.'</th>';
 }          } else {
               $Str .= '<th>'.
        '<a href="javascript:document.Statistics.sortby.value='."'$_'".
            ';document.Statistics.submit();">'.
                $_.'</a></th>';
           }
       }
       $r->print('<tr bgcolor="#FFFFE6">'.$Str."</tr>\n");
       #
       # Sort the data
       my @OutputOrder;
       if ($sortby eq 'Container') {
           @OutputOrder = @Statsarray;
       } else {
           # $sortby is already defined, so we can charge ahead
           if ($sortby =~ /^(title|part)$/i) {
               # 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));
   
 sub CreateProblemStatisticsTableHeading {          $r->print("</tr>\n");
     my ($displayFormat,$sequenceSource,$sequenceTitle,$headings,$r)=@_;  
     if($displayFormat eq 'Display CSV Format') {  
         $r->print('<br>"'.$sequenceTitle.'","');  
         $r->print($sequenceSource.'"');  
  return;  
     }  
   
     $r->print('<br><a href="'.$sequenceSource.  
               '" target="_blank">'.$sequenceTitle.'</a>');  
   
     my $Result = "\n".'<table border=2><tr><th>P#</th>'."\n";  
     for(my $nIndex=0; $nIndex < (scalar (keys %$headings)); $nIndex++) {   
  $Result .= '<th>'.'<input type="submit" name="';  
         $Result .= 'ProblemStatisticsHeading" value="';  
         $Result .= $headings->{$nIndex}.'" />'.'</th>'."\n";  
     }      }
     $Result .= "\n".'</tr>'."\n";          $r->print("</table>\n");
     $r->print($Result);      $r->print("</td></tr></table>\n");
     $r->rflush();      $r->rflush();
       #
       return;
 }  }
   
 sub CloseTable {  
     my ($cache,$r)=@_;  
     if($cache->{'DisplayFormat'} eq 'Display CSV Format') {  
  return;  
     }      
     $r->print("\n".'</table>'."\n");  
     $r->rflush();  
 }  
   
   ###############################################
   ###############################################
   
    ###############################################
 # ------ Dump the Student's DB file and handling the data for statistics table   ###############################################
 sub ExtractStudentData {  sub output_excel {
     my ($cache,$name,$list,%Discuss)=@_;      my ($r) = @_;
     my %discriminantFactor;      my $filename = '/prtspool/'.
           $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
     my $totalTries = 0;              time.'_'.rand(1000000000).'.xls';
     my $totalAwarded = 0;      #
     my $tempProblemOrder=0;      my $excel_workbook = undef;
     my $spent=0;      my $excel_sheet = undef;
     my $spent_yes=0;      #
     my $TotDiscuss=0;      my $rows_output = 0;
     my $TotalOpend = 0;      my $cols_output = 0;
     my $ProbSolved = 0;      #
     my $ProbTot = 0;      # Create sheet
     my $TotFirst = 0;      $excel_workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
     my $TimeTot = 0;      #
     my $Discussed=0;      # Check for errors
       if (! defined($excel_workbook)) {
     foreach my $sequence (split(':', $cache->{'orderedSequences'})) {          $r->log_error("Error creating excel spreadsheet $filename: $!");
         if($cache->{'ProblemStatisticsMap'} ne 'All Maps'  &&          $r->print("Problems creating new Excel file.  ".
            $cache->{'ProblemStatisticsMap'} ne $cache->{$sequence.':title'}) {                    "This error has been logged.  ".
             next;                    "Please alert your LON-CAPA administrator");
           return ;
       }
       #
       # The excel spreadsheet stores temporary data in files, then put them
       # together.  If needed we should be able to disable this (memory only).
       # The temporary directory must be specified before calling 'addworksheet'.
       # File::Temp is used to determine the temporary directory.
       $excel_workbook->set_tempdir($Apache::lonnet::tmpdir);
       #
       # Add a worksheet
       my $sheetname = $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
       if (length($sheetname) > 31) {
           $sheetname = substr($sheetname,0,31);
       }
       $excel_sheet = $excel_workbook->addworksheet($sheetname);
       #
       # Put the course description in the header
       $excel_sheet->write($rows_output,$cols_output++,
                      $ENV{'course.'.$ENV{'request.course.id'}.'.description'});
       $cols_output += 3;
       #
       # Put a description of the sections listed
       my $sectionstring = '';
       my @Sections = @Apache::lonstatistics::SelectedSections;
       if (scalar(@Sections) > 1) {
           if (scalar(@Sections) > 2) {
               my $last = pop(@Sections);
               $sectionstring = "Sections ".join(', ',@Sections).', and '.$last;
           } else {
               $sectionstring = "Sections ".join(' and ',@Sections);
         }          }
       } else {
         my $Dis = '';          if ($Sections[0] eq 'all') {
         foreach my $problemID (split(':', $cache->{$sequence.':problems'})) {              $sectionstring = "All sections";
             my $problem = $cache->{$problemID.':problem'};          } else {
             my $LatestVersion = $cache->{$name.':version:'.$problem};              $sectionstring = "Section ".$Sections[0];
           }
             # Output dashes for all the parts of this problem if there      }
             # is no version information about the current problem.      $excel_sheet->write($rows_output,$cols_output++,$sectionstring);
             #if(!$LatestVersion) {      $cols_output += scalar(@Sections);
             #    foreach my $part (split(/\:/,$cache->{$sequence.':'.      #
             #                                          $problemID.      # Put the date in there too
             #                                          ':parts'})) {      $excel_sheet->write($rows_output,$cols_output++,
             #        $codes    .= "-,";                          'Compiled on '.localtime(time));
             #        $attempts .= "0,";       #
             #    }      $rows_output++; 
             #    next;      $cols_output=0;
             #}      #
       # Add the headers
             my %partData=undef;      my @Header = ("Container","Title","Part","#Stdnts","Tries","Mod",
             # Initialize part data, display skips correctly                    "Mean","#YES","#yes","%Wrng","DoDiff",
             # Skip refers to when a student made no submissions on that                    "S.D.","Skew.");#,"D.F.1st","D.F.2nd");
             # part/problem.      foreach (@Header) {
             foreach my $part (split(/\:/,$cache->{$sequence.':'.          $excel_sheet->write($rows_output,$cols_output++,$_);
                                                   $problemID.      }
                                                   ':parts'})) {      $rows_output++;
                 $partData{$part.':tries'}=0;      #
                 $partData{$part.':code'}='-';      # Write the data
             }      foreach my $sequence (&Apache::lonstatistics::Sequences_with_Assess()) {
           next if ($sequence->{'num_assess'}<1);
             # Looping through all the versions of each part, starting with the          foreach my $resource (@{$sequence->{'contents'}}) {
             # oldest version.  Basically, it gets the most recent               next if ($resource->{'type'} ne 'assessment');
             # set of grade data for each part.              foreach my $part (@{$resource->{'parts'}}) {
     for(my $Version=1; $Version<=$LatestVersion; $Version++) {                  $cols_output=0;
                 foreach my $part (split(/\:/,$cache->{$sequence.':'.                  my ($num,$tries,$mod,$mean,$Solved,$solved,$DegOfDiff,$STD,
                                                       $problemID.                      $SKEW) = &Apache::loncoursedata::get_problem_statistics
                                                       ':parts'})) {                          (undef,$resource->{'symb'},$part,
                            $ENV{'request.course.id'});
                     if(!defined($cache->{$name.":$Version:$problem".                  #
                                                ":resource.$part.solved"})) {                  if (!defined($part) || $part eq '') {
                         # No grade for this submission, so skip                      $part = ' ';
                         next;  
                     }  
   
                     my $tries=0;  
                     my $time=0;  
                     my $awarded=0;  
     $Discussed=0;  
                     my $code='U';  
   
                     $awarded = $cache->{$name.  
                                         "$Version:$problem:resource.".  
                                         "$part.awarded"};  
                     $partData{$part.':awarded'} = ($awarded) ? $awarded : 0;  
                     $totalAwarded += $awarded;  
   
                     $tries = $cache->{$name.":$Version:$problem".  
                                       ":resource.$part.tries"};  
                     $partData{$part.':tries'} = ($tries) ? $tries : 0;  
                     $partData{$part.':wrong'} = $partData{$part.':tries'};  
                     $totalTries += $tries;  
   
                     my $val = $cache->{$name.":$Version:$problem".  
                                        ":resource.$part.solved"};  
                     if    ($val eq 'correct_by_student')   {$code = 'C';}   
                     elsif ($val eq 'correct_by_override')  {$code = 'O';}  
                     elsif ($val eq 'incorrect_attempted')  {$code = 'I';}   
                     elsif ($val eq 'incorrect_by_override'){$code = 'I';}  
                     elsif ($val eq 'excused')              {$code = 'x';}  
                     $partData{$part.':code'}=$code;  
   
                     if($partData{$part.':wrong'} ne 0 &&   
                        ($code eq 'C' || $code eq 'O')) {  
                         $partData{$part.':wrong'}--;  
                     }  
                 }  
             }  
   
             # Loop through all the parts for the current problem in the   
             # correct order and prepare the output  
             foreach (split(/\:/,$cache->{$sequence.':'.$problemID.  
                                          ':parts'})) {  
                 my $Yes = 0;  
                 if($partData{$_.':code'} eq 'C' ||   
                    $partData{$_.':code'} eq 'O') {  
                     $Yes=1;  
                 }  
                 my $ptr = $tempProblemOrder.'&'.$problemID;  
   
                 if($_ > 1) {  
                     $ptr .= "*(part $_)";  
                     $Dis .= '&';  
                 }  
   
  my ($pr_no,$dod)=split('&',$ptr);  
 # my $DoDiff=$DoDiff->{$dod};  
 #               $r->print('<br>'.$name.'---'.$ptr.'==='.$DoDiff);  
   
                 my $Fac = ($partData{$_.':Tries'}) ?   
                     ($partData{$_.':awarded'}/$partData{$_.':tries'}) : 0;  
                 my $DisF;  
                 if($Fac > 0 &&  $Fac < 1) {   
                     $DisF = sprintf( "%.4f", $Fac );  
                 } else {  
                     $DisF = $Fac;  
                 }                  }
                   my $wrongpercent = 0;
                 if ($Discuss{"$name:$problem"}) {                  if (defined($num) && $num > 0) {
     $TotDiscuss++;                      $wrongpercent=int(10*100*($num-$Solved+$solved)/$num)/10;
                     $Discussed=1;  
                 }                  }
                 my $time = $cache->{"$name:$LatestVersion:$problem:timestamp"};                  foreach ($sequence->{'title'},$resource->{'title'},$part,
                 $Dis .= $tempProblemOrder.'='.$DisF.'+'.$Yes;                           $num,$tries,$mod,$mean,$Solved,$solved,$wrongpercent,
                 $ptr .= '&'.$partData{$_.'.Tries'}.                           $DegOfDiff,$STD,$SKEW) {
                         '&'.$partData{$_.'.Wrongs'}.                      $excel_sheet->write($rows_output,$cols_output++,$_);
                         '&'.$partData{$_.'.Code'};  
                 push (@$list, $ptr."&$Discussed");  
   
 #### if ($DoDiff>0.85) {  
   
                 $TimeTot += $time;  
   
                 if ($Yes==1 && $partData{$_.'.Tries'}==1) {  
     $TotFirst++;  
                 }                  }
 # my $Acts= $Activity->{$name.':'.$problem};                  $rows_output++;
 # if ($Acts) {  
 #    my $Pt=&ProcAct( $Acts, $time );  
     #my ($spe,$beg) = split(/\+/,$Pt);  
 #                    my $spe= $Pt;  
 #    if ($Yes==1) {$spent_yes += $spe;}  
 #    $spent += $spe;  
     #$Beg += $beg;  
 #                   $r->print('<br>'.$name.'---'.$problem.'---'.$spe);  
 # }  
  $TotalOpend++;  
  $ProbTot++;  
   
                 $tempProblemOrder++;  
             }              }
         }          }
  my $pstr;  
         if($totalTries) {  
     my $DisFac = ($totalAwarded/$totalTries);  
     my $DisFactor = sprintf( "%.4f", $DisFac );  
             my $TS = sprintf( "%.2f", $spent );  
             my $TS_yes = sprintf( "%.2f", $spent_yes );  
    # $DiscFac{$DisFactor}=$Dis;  
     $pstr=$DisFactor.':'.$name.':'.$ProbTot.':'.$TotalOpend.':'.  
                   $totalTries.':'.$ProbSolved.':'.$TotFirst.':'.  
                   $TS_yes.':'.$TS.':'.$TotDiscuss;  
     $discriminantFactor{$pstr}=$Dis;  
  }  
     }      }
       #
     return (\%discriminantFactor);      # Write the excel file
       $excel_workbook->close();
       # Tell the user where to get their excel file
       $r->print('<br />'.
                 '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
       $r->rflush();
       return;
 }  }
   
   ###############################################
   ###############################################
   
 =pod  ###############################################
 sub MySort {            ###############################################
     if ( $Pos > 0 ) {  sub statistics_html_table_data {
  if ($ENV{'form.order'} eq 'Descending') {$b <=> $a;}      my ($resource,$part,$num,$tries,$mod,$mean,$Solved,$solved,$wrongpercent,
  else { $a <=> $b; }          $DegOfDiff,$STD,$SKEW,$options) = @_;
     }      my $row = '';
     else {      $row .= '<td bgcolor="#FFFFE6">'.
  if ($ENV{'form.order'} eq 'Descending') {$b cmp $a;}          '<a href="'.$resource->{'src'}.'" target="_blank" >'.
  else { $a cmp $b; }              $resource->{'title'}.'</a>'.
                   '</td>';
       $row .= '<td bgcolor="#FFFFE6">'.$part.'</td>' if ($options !~ /no part/);
       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 plot_statistics {
       my ($r,$datafield) = @_;
       my @Data;
       #
       my %Fields = ('#Stdnts'=> 0,
                     'Tries'  => 1,
                     'Mod'    => 2,
                     'Mean'   => 3,
                     '#YES'   => 4,
                     '#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};
 =cut      #
       my $Max = 0;
 sub BuildStatisticsTable {      foreach my $sequence (&Apache::lonstatistics::Sequences_with_Assess()) {
     my ($cache,$discriminantFactor,$list,$headings,$students,$r,%color)=@_;          next if ($sequence->{'num_assess'}<1);
           foreach my $resource (@{$sequence->{'contents'}}) {
 #6666666              next if ($resource->{'type'} ne 'assessment');
 #    my $file="/home/httpd/perl/tmp/183d.txt";              foreach my $part (@{$resource->{'parts'}}) {
 #    open(OUT, ">$file");                  my @Results = &Apache::loncoursedata::get_problem_statistics
 #6666666                          (undef,$resource->{'symb'},$part,
 ##     &Apache::lonstatistics::Create_PrgWin($r);                           $ENV{'request.course.id'});
 ##777777                  my ($num,$Solved,$solved) = @Results[0,4,5];
 ##    my (%Activity) = &LoadActivityLog();                  my $wrongpercent = 0;
 ##    $r->print('<script>popwin.document.popremain.remaining.value="'.                  if (defined($num) && $num > 0) {
 ##              'Loading Discussion...";</script>');                      $wrongpercent=int(10*100*($num-$Solved+$solved)/$num)/10;
 ##    my ($doDiffFile) = &LoadDoDiffFile();                  }
                   push (@Results,$wrongpercent);
     my $p_count = 0;                  my $data = $Results[$fieldindex];
     my $nIndex = 0;                  $data = 0 if ($data eq 'nan');
     my $dummy;                  $Max = $data if ($Max<$data);
     my $p_val;                  push (@Data,$data);
     my $ResId;              }
     my %GraphDat;  
     my $NoElements = scalar @$list;  
   
     foreach my $sequence (split(':', $cache->{'orderedSequences'})) {  
         if($cache->{'ProblemStatisticsMap'} ne 'All Maps'  &&  
            $cache->{'ProblemStatisticsMap'} ne $cache->{$sequence.':title'}) {  
             next;  
         }          }
   
  &CreateProblemStatisticsTableHeading($cache->{'DisplayFormat'},  
                                              $cache->{$sequence.':source'},   
                                              $cache->{$sequence.':title'},  
                                              $headings,$r);  
   
 ##777777  
 ##    $Str .= &Classify($discriminantFactor, $students);  
   
   
  my ($Hid,$pr)=split(/\:/,$mapsort{$_});  
  my @lpr=split(/\&/,$pr);  
  for (my $i=1; $i<=$#lpr; $i++) {  
     my %storestats=();  
     my ($PrOrd,$Prob,$Tries,$Wrongs,$Code,$Disc)=split(/\&/,$list->[$nIndex]);  
     my $Temp = $Prob;  
     my $MxTries = 0;  
     my $TotalTries = 0;  
     my $YES = 0;  
     my $Incorrect = 0;  
     my $Override = 0;  
     my $StdNo = 0;  
     my $DiscNo=0;  
     my @StdLst;  
     while ( $PrOrd == $lpr[$i] )   
     {  
  $nIndex++;  
  $StdNo++;  
  $StdLst[ $StdNo ] = $Tries;  
  $TotalTries += $Tries;  
  if ( $MxTries < $Tries ) { $MxTries = $Tries; }   
  if ( $Code eq 'C' ){ $YES++; }  
  elsif( $Code eq 'I' ) { $Incorrect++; }  
  elsif( $Code eq 'O' ) { $Override++; }  
  elsif( $Code eq 'U' ) { $StdNo--; }  
  ($PrOrd,$Prob,$Tries,$Wrongs,$Code,$Disc)=split(/\&/,$list->[$nIndex]);  
     }  
   
     $p_count++;  
     my $Dummy;  
     ($ResId,$Dummy)=split(/\*/,$Temp);  
   
     $Temp = '<a href="'.$cache->{'src_'.$ResId}.  
                 '" target="_blank">'.$cache->{'title_'.$ResId}.$Dummy.'</a>';  
   
     my $res = &Apache::lonnet::declutter($cache->{'src_'.$ResId});  
     my $urlres=$res;  
   
     $ResId=~/(\d+)\.(\d+)/;  
     my $Map = &Apache::lonnet::declutter( $cache->{'map_id_'.$1} );  
     $urlres=$Map;  
    
     $res = '<a href="'.$cache->{'src_'.$ResId}.'">'.$res.'</a>';  
     #$Map = '<a href="'.$Map.'">'.$res.'</a>';  
   
 #------------------------ Compute the Average of Tries about one problem  
     my $Average = ($StdNo) ? $TotalTries/$StdNo : 0;  
   
     $storestats{$ENV{'request.course.id'}.'___'.$urlres.'___timestamp'}=time;         
     $storestats{$ENV{'request.course.id'}.'___'.$urlres.'___stdno'}=$StdNo;  
     $storestats{$ENV{'request.course.id'}.'___'.$urlres.'___avetries'}=$Average;  
      
 #-------------------------------- Compute percentage of Wrong tries  
     my $Wrong = ( $StdNo ) ? 100 * ( $Incorrect / $StdNo ) : 0;  
   
 #-------------------------------- Compute Standard Deviation  
     my $StdDev = 0;   
     if ( $StdNo > 1 ) {  
  for ( my $n = 0; $n < $StdNo; $n++ ) {  
     my $Dif = $StdLst[ $n ]-$Average;  
     $StdDev += $Dif*$Dif;  
  }   
  $StdDev /= ( $StdNo - 1 );  
  $StdDev = sqrt( $StdDev );  
     }  
   
 #-------------------------------- Compute Degree of Difficulty  
     my $DoDiff = 0;  
     if( $TotalTries > 0 ) {  
  $DoDiff = 1 - ( ( $YES + $Override ) / $TotalTries );  
 #    $DoDiff =  ($TotalTries)/($YES + $Override+ 0.1);      
     }  
          
     $storestats{$ENV{'request.course.id'}.'___'.$urlres.'___difficulty'}=$DoDiff;  
   
 #-------------------------------- Compute the Skewness  
     my $Skewness = 0;  
     my $Sum = 0;   
     if ( $StdNo > 0 && $StdDev > 0 ) {  
  for ( my $n = 0; $n < $StdNo; $n++ ) {  
     my $Dif = $StdLst[ $n ]-$Average;  
     $Skewness += $Dif*$Dif*$Dif;  
  }   
  $Skewness /= $StdNo;  
  $Skewness /= $StdDev*$StdDev*$StdDev;  
     }  
   
 #--------------------- Compute the Discrimination Factors  
             my ($Up1,$Up2)=split(/\:/,':');#jason$DisUp->{$lpr[$i]});  
     my ($Lw1,$Lw2)=split(/\:/,':');#jason$DisLow->{$lpr[$i]});  
     my $Dis1 = $Up1 - $Lw1;  
     my $Dis2 = $Up2 - $Lw2;  
     my $_D1 = sprintf("%.2f", $Dis1);  
     my $_D2 = sprintf("%.2f", $Dis2);  
   
 #-----------------  Some restition in presenting the float numbers  
     my $Avg = sprintf( "%.2f", $Average );  
     my $Wrng = sprintf( "%.1f", $Wrong );  
     my $SD = sprintf( "%.1f", $StdDev );  
     my $DoD = sprintf( "%.2f", $DoDiff );  
     my $Sk = sprintf( "%.1f", $Skewness );  
     my $join = $lpr[$i].'&'.$Temp.'&'.$StdNo.'&'.  
                        $TotalTries.'&'.$MxTries.'&'.$Avg.'&'.  
                        $YES.'&'.$Override.'&'.$Wrng.'&'.$DoD.'&'.  
        $SD.'&'.$Sk.'&'.$_D1.'&'.$_D2.'&'.  
                        $DiscNo.'&'.$Prob;  
 ##8888    $CachData{($p_count-1)}=$join;  
   
 #6666666  
 #    $r->print('<br>'.$out.'&'.$DoD);  
 #            print (OUT $out.'@'.$DoD.'&');  
 #6666666  
   
     $urlres=~/^(\w+)\/(\w+)/;  
     if ($StdNo) {   
  &Apache::lonnet::put('resevaldata',\%storestats,$1,$2);   
     }  
 #-------------------------------- Row of statistical table  
             &TableRow($cache,$join,$i,($p_count-1),$r,\%color,\%GraphDat);  
  }  
  &CloseTable($cache,$r);  
     }      }
     &Close_PrgWin();      #
 #666666      # Print out plot request
 #    close( OUT );      my $title = 'Percent Wrong';
 #666666      if ($field eq 'DoDiff') {
 }          $title = 'Degree of Difficulty';
       }
 =pod      my $yaxis = 'Percent';
 sub Cache_Statistics {      if ($field eq 'DoDiff') {
     my ($cache,$color)=@_;          $yaxis = '';
     my @list = ();      } elsif ($field ne '%Wrng') {
     my $Useful;          $yaxis = '';
     my $UnUseful;      }
 #    $r->print('<input type="hidden" name="show" value="excel" />'."\n");       #
     my %myHeader = reverse( %Header );      # Determine appropriate value for $Max
     $Pos = $myHeader{$ENV{'form.sort'}};      if ($field eq 'DoDiff') {
     if ($Pos > 0) {$Pos++;}          if ($Max > 0.5) {
     my $p_count = 0;              $Max = 1;
     foreach my $key( keys %CachData) {           } elsif ($Max > 0.2) {
  my @Temp=split(/\&/,$CachData{$key});              $Max = 0.5;
  if ( $Pos == 0 ) {          } elsif ($Max > 0.1) {
     ($UnUseful,$Useful)=split(/\>/,$Temp[$Pos]);              $Max = 0.2;
  }          }
  else {      } elsif ($field eq '%Wrng') {
     $Useful = $Temp[$Pos];          if ($Max > 50) {
  }                 $Max = 100;
  $list[$p_count]=$Useful.'@'.$CachData{$key};          } elsif ($Max > 25) {
         $p_count++;              $Max = 50;
     }          } elsif ($Max > 20) {
               $Max = 25;
     @list = sort MySort (@list);          } elsif ($Max > 10) {
               $Max = 20;
     my $nIndex=0;          } elsif ($Max > 5) {
               $Max = 10;
     if ( $Pos == 0 ) {          } else {
  foreach (sort keys %mapsort) {              $Max = 5;
     my ($Hid,$pr)=split(/\:/,$mapsort{$_});          }
     &CreateProblemStatisticsTableHeading($cache,1,$Hid);      }
     my @lpr=split(/\&/,$pr);      
     for (my $i=1; $i<=$#lpr; $i++) {      $r->print("<p>".&DrawGraph(\@Data,$title,'Problem Number',$yaxis,
  my($Pre, $Post) = split(/\@/,$list[$nIndex]);                                  $Max)."</p>\n");
  #$r->print('<br>'.$Pre.'---'.$Post);      #
  &TableRow($cache,$Post,$i,$nIndex,\%color,\%GraphDat);      # Print out the data
  $nIndex++;      $ENV{'form.sortby'} = 'Contents';
       &output_html_ungrouped($r,'show probnum');
       return;
   }
   
   ###############################################
   ###############################################
   
   ###############################################
   ###############################################
   sub DrawGraph {
       my ($values,$title,$xaxis,$yaxis,$Max)=@_;
       $title = '' if (! defined($title));    
       $xaxis = '' if (! defined($xaxis));
       $yaxis = '' if (! defined($yaxis));
       #
       my $sendValues = join(',', @$values);
       my $sendCount = scalar(@$values);
       if ( $Max > 1 ) {
    if ($Max % 10) {
               if ( int($Max) < $Max ) {
        $Max++;
    $Max = int($Max);
     }      }
     &CloseTable($cache);  
  }   }
       } else { 
           $Max = 1; 
     }      }
     else {      my @GData = ($title,$xaxis,$yaxis,$Max,$sendCount,$sendValues);
  &CreateProblemStatisticsTableHeading($cache,0);      return '<IMG src="/cgi-bin/graph.png?'.
  for ( my $nIndex = 0; $nIndex < $p_count; $nIndex++ ) {          (join('&', @GData)).'" border="1" />';
     my($Pre, $Post) = split(/\@/,$list[$nIndex]);   
     &TableRow($cache,$Post,$nIndex,$nIndex,\%color,\%GraphDat);  
  }   
  &CloseTable($cache);  
     }  
 }  
 =cut   
   
 sub TableRow {  
     my ($cache,$Str,$Idx,$RealIdx,$r,$color,$GraphDat)=@_;  
     my($PrOrd,$Temp,$StdNo,$TotalTries,$MxTries,$Avg,$YES,$Override,  
        $Wrng,$DoD,$SD,$Sk,$_D1,$_D2,$DiscNo,$Prob)=split(/\&/,$Str);  
     if ($ENV{'form.showcsv'}) {  
         my ($ResId,$Dummy)=split(/\*/,$Prob);  
         my $Ptr =  "\n".'<br>'.  
                "\n".'"'.($RealIdx+1).'",'.  
                "\n".'"'.$cache->{'title_'.$ResId}.$Dummy.'",'.  
                "\n".'"'.$cache->{'src_'.$ResId}.'",'.  
                "\n".'"'.$StdNo.'",'.  
                "\n".'"'.$TotalTries.'",'.  
                "\n".'"'.$MxTries.'",'.  
                "\n".'"'.$Avg.'",'.  
                "\n".'"'.$YES.'",'.  
                "\n".'"'.$Override.'",'.  
                "\n".'"'.$Wrng.'",'.  
                "\n".'"'.$DoD.'",'.  
                "\n".'"'.$SD.'",'.  
                "\n".'"'.$Sk.'",'.  
                "\n".'"'.$_D1.'",'.  
        "\n".'"'.$_D2.'"'.  
        "\n".'"'.$DiscNo.'"';  
   
         $r->print("\n".$Ptr);  
     }  
     else{  
         my $Ptr =  "\n".'<tr>'.  
                "\n".'<td>'.($RealIdx+1).'</td>'.  
           #     "\n".'<td>'.$PrOrd.$Temp.'</td>'.  
                "\n".'<td>'.$Temp.'</td>'.  
                "\n".'<td bgcolor='.$color->{"yellow"}.'> '.$StdNo.'</td>'.  
                "\n".'<td bgcolor='.$color->{"yellow"}.'>'.$TotalTries.'</td>'.  
                "\n".'<td bgcolor='.$color->{"yellow"}.'>'.$MxTries.'</td>'.  
                "\n".'<td bgcolor='.$color->{"gb"}.'>'.$Avg.'</td>'.  
                "\n".'<td bgcolor='.$color->{"gb"}.'> '.$YES.'</td>'.  
                "\n".'<td bgcolor='.$color->{"gb"}.'> '.$Override.'</td>'.  
                "\n".'<td bgcolor='.$color->{"red"}.'> '.$Wrng.'</td>'.  
                "\n".'<td bgcolor='.$color->{"red"}.'> '.$DoD.'</td>'.  
                "\n".'<td bgcolor='.$color->{"green"}.'> '.$SD.'</td>'.  
                "\n".'<td bgcolor='.$color->{"green"}.'> '.$Sk.'</td>'.  
                "\n".'<td bgcolor='.$color->{"purple"}.'> '.$_D1.'</td>'.  
        "\n".'<td bgcolor='.$color->{"purple"}.'> '.$_D2.'</td>'.  
                "\n".'<td bgcolor='.$color->{"yellow"}.'> '.$DiscNo.'</td>';  
         $r->print("\n".$Ptr.'</tr>' );  
     }  
     $GraphDat->{$RealIdx}=$DoD.':'.$Wrng;  
 }  
   
 sub StatusOptions {  
     my ($cache)=@_;  
   
     my $Status = $cache->{'Status'};  
     my $OpSel1 = '';  
     my $OpSel2 = '';  
     my $OpSel3 = '';  
   
     if($Status eq 'Any')         { $OpSel3 = ' selected'; }  
     elsif($Status eq 'Expired' ) { $OpSel2 = ' selected'; }  
     else                         { $OpSel1 = ' selected'; }  
   
     my $Ptr = '';  
     $Ptr .= '<tr><td align="right"><b>Student Status:</b></td>'."\n";  
     $Ptr .= '<td align="left"><select name="Status">';  
     $Ptr .= '<option'.$OpSel1.'>Active</option>'."\n";  
     $Ptr .= '<option'.$OpSel2.'>Expired</option>'."\n";  
     $Ptr .= '<option'.$OpSel3.'>Any</option>'."\n";  
     $Ptr .= '</select></td></tr>'."\n";  
   
     return $Ptr;  
 }  
   
 sub AscendOrderOptions {  
     my ($order)=@_;  
   
     my $OpSel1 = '';  
     my $OpSel2 = '';  
   
     if($order eq 'Ascending') {  
         $OpSel1 = ' selected';  
     } else {  
         $OpSel2 = ' selected';  
     }  
   
     my $Ptr = '';  
     $Ptr .= '<tr><td align="right"><b>Sorting Type:</b></td>'."\n";  
     $Ptr .= '<td align="left"><select name="Ascend">'."\n";  
     $Ptr .= '<option'.$OpSel1.'>Ascending</option>'."\n".  
     '<option'.$OpSel2.'>Descending</option>'."\n";  
     $Ptr .= '</select></td></tr>'."\n";  
   
     return $Ptr;  
 }  }
   
 sub ProblemStatisticsButtons {  ###############################################
     my ($displayFormat)=@_;  ###############################################
   
     my $Ptr = '<tr><td></td><td align="left">';  
     $Ptr .= '<input type=submit name="ProblemStatisticsRecalculate" ';  
     $Ptr .= 'value="Recalculate Statistics"/>'."\n";  
     $Ptr .= '&nbsp;&nbsp;&nbsp;';  
     $Ptr .= '<input type="submit" name="DoDiffGraph" ';  
     $Ptr .= 'value="DoDiff Graph" />'."\n";  
     $Ptr .= '&nbsp;&nbsp;&nbsp;';  
     $Ptr .= '<input type="submit" name="PercentWrongGraph" ';  
     $Ptr .= 'value="%Wrong Graph" />'."\n";  
     $Ptr .= '&nbsp;&nbsp;&nbsp;';  
     $Ptr .= '<input type="submit" name="DisplayCSVFormat" ';  
     if($displayFormat eq 'Display CSV Format') {  
         $Ptr .= 'value="Display CSV Format" />'."\n";  
     } else {  
         $Ptr .= 'value="Display Table Format" />'."\n";  
     }  
     $Ptr .= '</td></tr>';  
   
     return $Ptr;  
 }  
   
   ###############################################
   ###############################################
 sub ProblemStatisticsLegend {  sub ProblemStatisticsLegend {
     my $Ptr = '';      my $Ptr = '';
     $Ptr = '<table border="0">';      $Ptr = '<table border="0">';
     $Ptr .= '<tr><td>';      $Ptr .= '<tr><td>';
     $Ptr .= '<b>#Stdnts</b>:</td>';      $Ptr .= '<b>#Stdnts</b></td>';
     $Ptr .= '<td>Total Number of Students opened the problem.';      $Ptr .= '<td>Total number of students attempted the problem.';
     $Ptr .= '</td></tr><tr><td>';      $Ptr .= '</td></tr><tr><td>';
     $Ptr .= '<b>Tries</b>:</td>';      $Ptr .= '<b>Tries</b></td>';
     $Ptr .= '<td>Total Number of Tries for solving the problem.';      $Ptr .= '<td>Total number of tries for solving the problem.';
     $Ptr .= '</td></tr><tr><td>';      $Ptr .= '</td></tr><tr><td>';
     $Ptr .= '<b>Mod</b>:</td>';      $Ptr .= '<b>Mod</b></td>';
     $Ptr .= '<td>Maximunm Number of Tries for solving the problem.';      $Ptr .= '<td>Largest number of tries for solving the problem by a student.';
     $Ptr .= '</td></tr><tr><td>';      $Ptr .= '</td></tr><tr><td>';
     $Ptr .= '<b>Mean</b>:</td>';      $Ptr .= '<b>Mean</b></td>';
     $Ptr .= '<td>Average Number of the tries. [ Tries / #Stdnts ]';      $Ptr .= '<td>Average number of tries. [ Tries / #Stdnts ]';
     $Ptr .= '</td></tr><tr><td>';      $Ptr .= '</td></tr><tr><td>';
     $Ptr .= '<b>#YES</b>:</td>';      $Ptr .= '<b>#YES</b></td>';
     $Ptr .= '<td>Number of students solved the problem correctly.';      $Ptr .= '<td>Number of students solved the problem correctly.';
     $Ptr .= '</td></tr><tr><td>';      $Ptr .= '</td></tr><tr><td>';
     $Ptr .= '<b>#yes</b>:</td>';      $Ptr .= '<b>#yes</b></td>';
     $Ptr .= '<td>Number of students solved the problem by override.';      $Ptr .= '<td>Number of students solved the problem by override.';
     $Ptr .= '</td></tr><tr><td>';      $Ptr .= '</td></tr><tr><td>';
     $Ptr .= '<b>%Wrng</b>:</td>';      $Ptr .= '<b>%Wrong</b></td>';
     $Ptr .= '<td>Percentage of students tried to solve the problem ';      $Ptr .= '<td>Percentage of students who tried to solve the problem ';
     $Ptr .= 'but still incorrect. [ 100*((#Stdnts-(#YES+#yes))/#Stdnts) ]';      $Ptr .= 'but is still incorrect. [ 100*((#Stdnts-(#YES+#yes))/#Stdnts) ]';
     $Ptr .= '</td></tr><tr><td>';      $Ptr .= '</td></tr><tr><td>';
     $Ptr .= '<b>DoDiff</b>:</td>';      $Ptr .= '<b>DoDiff</b></td>';
     $Ptr .= '<td>Degree of Difficulty of the problem.  ';      $Ptr .= '<td>Degree of Difficulty of the problem.  ';
     $Ptr .= '[ 1 - ((#YES+#yes) / Tries) ]';      $Ptr .= '[ 1 - ((#YES+#yes) / Tries) ]';
     $Ptr .= '</td></tr><tr><td>';      $Ptr .= '</td></tr><tr><td>';
     $Ptr .= '<b>S.D.</b>:</td>';      $Ptr .= '<b>S.D.</b></td>';
     $Ptr .= '<td>Standard Deviation of the tries.  ';      $Ptr .= '<td>Standard Deviation of the tries.  ';
     $Ptr .= '[ sqrt(sum((Xi - Mean)^2)) / (#Stdnts-1) ';      $Ptr .= '[ sqrt(sum((Xi - Mean)^2)) / (#Stdnts-1) ';
     $Ptr .= 'where Xi denotes every student\'s tries ]';      $Ptr .= 'where Xi denotes every student\'s tries ]';
     $Ptr .= '</td></tr><tr><td>';      $Ptr .= '</td></tr><tr><td>';
     $Ptr .= '<b>Skew.</b>:</td>';      $Ptr .= '<b>Skew.</b></td>';
     $Ptr .= '<td>Skewness of the students tries.';      $Ptr .= '<td>Skewness of the students tries.';
     $Ptr .= '[(sqrt( sum((Xi - Mean)^3) / #Stdnts)) / (S.D.^3)]';      $Ptr .= '[(sqrt( sum((Xi - Mean)^3) / #Stdnts)) / (S.D.^3)]';
     $Ptr .= '</td></tr><tr><td>';      $Ptr .= '</td></tr><tr><td>';
     $Ptr .= '<b>Dis.F.</b>:</td>';      $Ptr .= '<b>Dis.F.</b></td>';
     $Ptr .= '<td>Discrimination Factor: A Standard for evaluating the ';      $Ptr .= '<td>Discrimination Factor: A Standard for evaluating the ';
     $Ptr .= 'problem according to a Criterion<br>';      $Ptr .= 'problem according to a Criterion<br>';
     $Ptr .= '<b>[Applied Criterion in %27 Upper Students - ';      $Ptr .= '<b>[Criterion to group students into %27 Upper Students - ';
     $Ptr .= 'Applied the same Criterion in %27 Lower Students]</b><br>';      $Ptr .= 'and %27 Lower Students]</b><br>';
     $Ptr .= '<b>1st Criterion</b> for Sorting the Students: ';      $Ptr .= '<b>1st Criterion</b> for Sorting the Students: ';
     $Ptr .= '<b>Sum of Partial Credit Awarded / Total Number of Tries</b><br>';      $Ptr .= '<b>Sum of Partial Credit Awarded / Total Number of Tries</b><br>';
     $Ptr .= '<b>2nd Criterion</b> for Sorting the Students: ';      $Ptr .= '<b>2nd Criterion</b> for Sorting the Students: ';
Line 1006  sub ProblemStatisticsLegend { Line 796  sub ProblemStatisticsLegend {
     $Ptr .= '<tr><td><b>Disc.</b></td>';      $Ptr .= '<tr><td><b>Disc.</b></td>';
     $Ptr .= '<td>Number of Students had at least one discussion.';      $Ptr .= '<td>Number of Students had at least one discussion.';
     $Ptr .= '</td></tr></table>';      $Ptr .= '</td></tr></table>';
   
     return $Ptr;      return $Ptr;
 }  }
   
 #---- END Problem Statistics Web Page ----------------------------------------  #---- END Problem Statistics Web Page ----------------------------------------
   
 #---- Problem Statistics Graph Web Page --------------------------------------  
   
 # ------------------------------------------- Prepare data for Graphical chart  
   
 sub GetGraphData {  
     my ($ylab,$r,%GraphDat)=@_;  
     my $Col;  
     my $data='';  
     my $count = 0;  
     my $Max = 0;  
     my $cid=$ENV{'request.course.id'};  
     my $GraphDB = "/home/httpd/perl/tmp/$ENV{'user.name'}".  
                   "_$ENV{'user.domain'}_$cid\_graph.db";  
     foreach (keys %GraphDat) {delete $GraphDat{$_};}  
     if (-e "$GraphDB") {  
  if (tie(%GraphDat,'GDBM_File',"$GraphDB",&GDBM_READER,0640)) {  
     if ( $ylab eq 'DoDiff Graph' ) {  
  $ylab = 'Degree-of-Difficulty';  
  $Col = 0;  
     }  
     else {  
  $ylab = 'Wrong-Percentage';  
  $Col = 1;  
     }  
     foreach (sort NumericSort keys %GraphDat) {   
  my @Temp=split(/\:/,$GraphDat{$_});  
                 my $inf = $Temp[$Col];   
  if ( $Max < $inf ) {$Max = $inf;}  
  $data .= $inf.',';  
  $count++;  
     }  
     if ( $Max > 1 ) {   
  $Max += (10 - $Max % 10);  
  $Max = int($Max);  
     }  
     else { $Max = 1; }  
             untie(%GraphDat);  
     my $Course = $ENV{'course.'.$cid.'.description'};  
     $Course =~ s/\ /"_"/eg;  
     my $GData=$Course.'&'.'Problems'.'&'.$ylab.'&'.$Max.'&'.$count.'&'.$data;  
  }  
  else {  
     $r->print("Unable to tie hash to db file");  
  }  
     }  
 }  
 1;  1;
 __END__  __END__

Removed from v.1.2  
changed lines
  Added in v.1.46


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