File:  [LON-CAPA] / loncom / interface / statistics / lonproblemstatistics.pm
Revision 1.89: download - view: text, annotated - select for diffs
Wed Jun 16 16:22:52 2004 UTC (20 years ago) by matthew
Branches: MAIN
CVS tags: version_1_1_99_2, version_1_1_99_1, HEAD
Turn computing the degree of discrimination on by default.

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: lonproblemstatistics.pm,v 1.89 2004/06/16 16:22:52 matthew Exp $
    4: #
    5: # Copyright Michigan State University Board of Trustees
    6: #
    7: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    8: #
    9: # LON-CAPA is free software; you can redistribute it and/or modify
   10: # it under the terms of the GNU General Public License as published by
   11: # the Free Software Foundation; either version 2 of the License, or
   12: # (at your option) any later version.
   13: #
   14: # LON-CAPA is distributed in the hope that it will be useful,
   15: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   16: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   17: # GNU General Public License for more details.
   18: #
   19: # You should have received a copy of the GNU General Public License
   20: # along with LON-CAPA; if not, write to the Free Software
   21: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   22: #
   23: # /home/httpd/html/adm/gpl.txt
   24: #
   25: # http://www.lon-capa.org/
   26: #
   27: # (Navigate problems for statistical reports
   28: #
   29: ###############################################
   30: ###############################################
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: lonproblemstatistics
   37: 
   38: =head1 SYNOPSIS
   39: 
   40: Routines to present problem statistics to instructors via tables,
   41: Excel files, and plots.
   42: 
   43: =over 4
   44: 
   45: =cut
   46: 
   47: ###############################################
   48: ###############################################
   49: 
   50: package Apache::lonproblemstatistics;
   51: 
   52: use strict;
   53: use Apache::lonnet();
   54: use Apache::loncommon();
   55: use Apache::lonhtmlcommon;
   56: use Apache::loncoursedata;
   57: use Apache::lonstatistics;
   58: use LONCAPA::lonmetadata();
   59: use Apache::lonlocal;
   60: use Spreadsheet::WriteExcel;
   61: use Apache::lonstathelpers();
   62: use Time::HiRes;
   63: 
   64: my @StatsArray;
   65: my %SeqStat;    # keys are symbs, values are hash refs
   66: 
   67: ##
   68: ## Localization notes:
   69: ##
   70: ## in @Fields[0]->{'long_title'} is placed in Excel files and is used as the
   71: ## header for plots created with Graph.pm, both of which more than likely do
   72: ## not support localization.
   73: ##
   74: #
   75: #
   76: ##
   77: ## Description of Field attributes
   78: ##
   79: ## Attribute     Required   Value       Meaning or Use
   80: ##
   81: ## name            yes      any scalar  Used to uniquely identify field
   82: ## title           yes      any scalar  This is what the user sees to identify
   83: ##                                      the field.  Passed through &mt().
   84: ## long_title      yes      any scalar  Used as graph heading and in excel
   85: ##                                      output.  NOT translated
   86: ## align           no    (left|right|center)  HTML cell contents alignment
   87: ## color           yes      html color  HTML cell background color
   88: ##                                      used to visually group statistics
   89: ## special         no          (link)   Indicates a link, target is name.link
   90: ##                                      Currently set in &get_statistics()
   91: ## graphable       no      (yes|no)     Can a bar graph of the field be 
   92: ##                                      produced?
   93: ## sortable        no      (yes|no)     Should a sort link be put in the
   94: ##                                      column header?
   95: ## selectable      yes     (yes|no)     Can the column be removed from the
   96: ##                                      statistics display?
   97: ## selected        yes     (yes|no)     Is the column selected by default?
   98: ##
   99: ## format          no      sprintf format string
  100: ##
  101: ## excel_format    no      excel format type 
  102: ##                               (see &Apache::loncommon::define_excel_formats
  103: my @Fields = (
  104:            { name => 'problem_num',
  105:              title => 'P#',
  106:              align => 'right',
  107:              color => '#FFFFE6',
  108:              selectable => 'no',
  109:              defaultselected => 'yes',
  110:            },
  111:            { name   => 'container',
  112:              title  => 'Sequence or Folder',
  113:              align  => 'left',
  114:              color  => '#FFFFE6',
  115:              sortable => 'yes',
  116:              selectable => 'no',
  117:              defaultselected => 'yes',
  118:            },
  119:            { name   => 'title',
  120:              title  => 'Title',
  121:              align  => 'left',
  122:              color  => '#FFFFE6',
  123:              special  => 'link',
  124:              sortable => 'yes', 
  125:              selectable => 'no',
  126:              defaultselected => 'yes',
  127:            },
  128:            { name   => 'part', 
  129:              title  => 'Part',
  130:              align  => 'left',
  131:              color  => '#FFFFE6',
  132:              selectable => 'no',
  133:              defaultselected => 'yes',
  134:            },
  135:            { name   => 'num_students',
  136:              title  => '#Stdnts',
  137:              align  => 'right',
  138:              color  => '#EEFFCC',
  139:              format => '%d',
  140:              sortable  => 'yes',
  141:              graphable => 'yes',
  142:              long_title => 'Number of Students Attempting Problem',
  143:              selectable => 'yes',
  144:              defaultselected => 'yes',
  145:            },
  146:            { name   => 'tries',
  147:              title  => 'Tries',
  148:              align  => 'right',
  149:              color  => '#EEFFCC',
  150:              format => '%d',
  151:              sortable  => 'yes',
  152:              graphable => 'yes',
  153:              long_title => 'Total Number of Tries',
  154:              selectable => 'yes',
  155:              defaultselected => 'yes',
  156:            },
  157:            { name   => 'max_tries',
  158:              title  => 'Max Tries',
  159:              align  => 'right',
  160:              color  => '#DDFFFF',
  161:              format => '%d',
  162:              sortable  => 'yes',
  163:              graphable => 'yes',
  164:              long_title => 'Maximum Number of Tries',
  165:              selectable => 'yes',
  166:              defaultselected => 'yes',
  167:            },
  168:            { name   => 'min_tries',
  169:              title  => 'Min Tries',
  170:              align  => 'right',
  171:              color  => '#DDFFFF',
  172:              format => '%d',
  173:              sortable  => 'yes',
  174:              graphable => 'yes',
  175:              long_title => 'Minumum Number of Tries',
  176:              selectable => 'yes',
  177:              defaultselected => 'yes',
  178:            },
  179:            { name   => 'mean_tries',
  180:              title  => 'Mean Tries',
  181:              align  => 'right',
  182:              color  => '#DDFFFF',
  183:              format => '%5.2f',
  184:              sortable  => 'yes',
  185:              graphable => 'yes',
  186:              long_title => 'Average Number of Tries',
  187:              selectable => 'yes',
  188:              defaultselected => 'yes',
  189:            },
  190:            { name   => 'std_tries',
  191:              title  => 'S.D. tries',
  192:              align  => 'right',
  193:              color  => '#DDFFFF',
  194:              format => '%5.2f',
  195:              sortable  => 'yes',
  196:              graphable => 'yes',
  197:              long_title => 'Standard Deviation of Number of Tries',
  198:              selectable => 'yes',
  199:              defaultselected => 'yes',
  200:            },
  201:            { name   => 'skew_tries',
  202:              title  => 'Skew Tries',
  203:              align  => 'right',
  204:              color  => '#DDFFFF',
  205:              format => '%5.2f',
  206:              sortable  => 'yes',
  207:              graphable => 'yes',
  208:              long_title => 'Skew of Number of Tries',
  209:              selectable => 'yes',
  210:              defaultselected => 'no',
  211:            },
  212:            { name   => 'num_solved',
  213:              title  => '#YES',
  214:              align  => 'right',
  215:              color  => '#FFDDDD',
  216:              format => '%4.1f',#             format => '%d',
  217:              sortable  => 'yes',
  218:              graphable => 'yes',
  219:              long_title => 'Number of Students able to Solve',
  220:              selectable => 'yes',
  221:              defaultselected => 'yes',
  222:            },
  223:            { name   => 'num_override',
  224:              title  => '#yes',
  225:              align  => 'right',
  226:              color  => '#FFDDDD',
  227:              format => '%4.1f',#             format => '%d',
  228:              sortable  => 'yes',
  229:              graphable => 'yes',
  230:              long_title => 'Number of Students given Override',
  231:              selectable => 'yes',
  232:              defaultselected => 'yes',
  233:            },
  234:            { name   => 'num_wrong',
  235:              title  => '#Wrng',
  236:              align  => 'right',
  237:              color  => '#FFDDDD',
  238:              format => '%4.1f',
  239:              sortable  => 'yes',
  240:              graphable => 'yes',
  241:              long_title => 'Percent of students whose final answer is wrong',
  242:              selectable => 'yes',
  243:              defaultselected => 'yes',
  244:            },
  245:            { name   => 'deg_of_diff',
  246:              title  => 'DoDiff',
  247:              align  => 'right',
  248:              color  => '#FFFFE6',
  249:              format => '%5.2f',
  250:              sortable  => 'yes',
  251:              graphable => 'yes',
  252:              long_title => 'Degree of Difficulty'.
  253:                            '[ 1 - ((#YES+#yes) / Tries) ]',
  254:              selectable => 'yes',
  255:              defaultselected => 'yes',
  256:            },
  257:            { name   => 'deg_of_disc',
  258:              title  => 'DoDisc',
  259:              align  => 'right',
  260:              color  => '#FFFFE6',
  261:              format => '%4.2f',
  262:              sortable  => 'yes',
  263:              graphable => 'yes',
  264:              long_title => 'Degree of Discrimination',
  265:              selectable => 'yes',
  266:              defaultselected => 'yes',
  267:            },
  268: ##   duedate included for research purposes.  Commented out most of the time.
  269: #           { name => 'duedate',
  270: #             title => 'Due Date',
  271: #             align => 'left',
  272: #             color => '#FFFFFF',
  273: #             sortable => 'yes',
  274: #             graphable => 'no',
  275: #             long_title => 'Due date of resource for instructor',
  276: #             selectable => 'no',
  277: #             defaultselected => 'yes',
  278: #            },
  279: ##   opendate included for research purposes.  Commented out most of the time.
  280: #           { name => 'opendate',
  281: #             title => 'Open Date',
  282: #             align => 'left',
  283: #             color => '#FFFFFF',
  284: #             sortable => 'yes',
  285: #             graphable => 'no',
  286: #             long_title => 'date resource became answerable',
  287: #             selectable => 'no',
  288: #             defaultselected => 'yes',
  289: #            },
  290: ##   symb included for research purposes.  Commented out most of the time.
  291: #           { name => 'symb',
  292: #             title => 'Symb',
  293: #             align => 'left',
  294: #             color => '#FFFFFF',
  295: #             sortable => 'yes',
  296: #             graphable => 'no',
  297: #             long_title => 'Unique LON-CAPA identifier for problem',
  298: #             selectable => 'no',
  299: #             defaultselected => 'yes',
  300: #            },
  301: ##   resptypes included for research purposes.  Commented out most of the time.
  302: #           { name => 'resptypes',
  303: #             title => 'Response Types',
  304: #             align => 'left',
  305: #             color => '#FFFFFF',
  306: #             sortable => 'no',
  307: #             graphable => 'no',
  308: #             long_title => 'Response Types used in this problem',
  309: #             selectable => 'no',
  310: #             defaultselected => 'yes',
  311: #            },
  312: );
  313: 
  314: my @SeqFields = (
  315:            { name   => 'title',
  316:              title  => 'Sequence',
  317:              align  => 'left',
  318:              color  => '#FFFFE6',
  319:              special  => 'no',
  320:              sortable => 'no', 
  321:              selectable => 'yes',
  322:              defaultselected => 'no',
  323:            },
  324:            { name   => 'items',
  325:              title  => '#Items',
  326:              align  => 'right',
  327:              color  => '#FFFFE6',
  328:              format => '%4d',
  329:              sortable  => 'no',
  330:              graphable => 'no',
  331:              long_title => 'Number of Items in Sequence',
  332:              selectable => 'yes',
  333:              defaultselected => 'no',
  334:            },
  335:            { name   => 'scoremean',
  336:              title  => 'Score Mean',
  337:              align  => 'right',
  338:              color  => '#FFFFE6',
  339:              format => '%4.2f',
  340:              sortable  => 'no',
  341:              graphable => 'no',
  342:              long_title => 'Mean Sequence Score',
  343:              selectable => 'yes',
  344:              defaultselected => 'no',
  345:            },
  346:            { name   => 'scorestd',
  347:              title  => 'Score STD',
  348:              align  => 'right',
  349:              color  => '#FFFFE6',
  350:              format => '%4.2f',
  351:              sortable  => 'no',
  352:              graphable => 'no',
  353:              long_title => 'Standard Deviation of Sequence Scores',
  354:              selectable => 'yes',
  355:              defaultselected => 'no',
  356:            },
  357:            { name   => 'scoremax',
  358:              title  => 'Score Max',
  359:              align  => 'right',
  360:              color  => '#FFFFE6',
  361:              format => '%4.2f',
  362:              sortable  => 'no',
  363:              graphable => 'no',
  364:              long_title => 'Maximum Sequence Score',
  365:              selectable => 'yes',
  366:              defaultselected => 'no',
  367:            },
  368:            { name   => 'scoremin',
  369:              title  => 'Score Min',
  370:              align  => 'right',
  371:              color  => '#FFFFE6',
  372:              format => '%4.2f',
  373:              sortable  => 'no',
  374:              graphable => 'no',
  375:              long_title => 'Minumum Sequence Score',
  376:              selectable => 'yes',
  377:              defaultselected => 'no',
  378:            },
  379:            { name   => 'scorecount',
  380:              title  => 'Score N',
  381:              align  => 'right',
  382:              color  => '#FFFFE6',
  383:              format => '%4d',
  384:              sortable  => 'no',
  385:              graphable => 'no',
  386:              long_title => 'Number of Students in score computations',
  387:              selectable => 'yes',
  388:              defaultselected => 'no',
  389:            },
  390:            { name   => 'countmean',
  391:              title  => 'Count Mean',
  392:              align  => 'right',
  393:              color  => '#FFFFFF',
  394:              format => '%4.2f',
  395:              sortable  => 'no',
  396:              graphable => 'no',
  397:              long_title => 'Mean Sequence Score',
  398:              selectable => 'yes',
  399:              defaultselected => 'no',
  400:            },
  401:            { name   => 'countstd',
  402:              title  => 'Count STD',
  403:              align  => 'right',
  404:              color  => '#FFFFFF',
  405:              format => '%4.2f',
  406:              sortable  => 'no',
  407:              graphable => 'no',
  408:              long_title => 'Standard Deviation of Sequence Scores',
  409:              selectable => 'yes',
  410:              defaultselected => 'no',
  411:            },
  412:            { name   => 'countmax',
  413:              title  => 'Count Max',
  414:              align  => 'right',
  415:              color  => '#FFFFFF',
  416:              format => '%4.2f',
  417:              sortable  => 'no',
  418:              graphable => 'no',
  419:              long_title => 'Maximum Number of Correct Problems',
  420:              selectable => 'yes',
  421:              defaultselected => 'no',
  422:            },
  423:            { name   => 'countmin',
  424:              title  => 'Count Min',
  425:              align  => 'right',
  426:              color  => '#FFFFFF',
  427:              format => '%4.2f',
  428:              sortable  => 'no',
  429:              graphable => 'no',
  430:              long_title => 'Minumum Number of Correct Problems',
  431:              selectable => 'yes',
  432:              defaultselected => 'no',
  433:            },
  434:            { name   => 'count',
  435:              title  => 'Count N',
  436:              align  => 'right',
  437:              color  => '#FFFFFF',
  438:              format => '%4d',
  439:              sortable  => 'no',
  440:              graphable => 'no',
  441:              long_title => 'Number of Students in score computations',
  442:              selectable => 'yes',
  443:              defaultselected => 'no',
  444:            },
  445:            { name   => 'KR-21',
  446:              title  => 'KR-21',
  447:              align  => 'right',
  448:              color  => '#FFAAAA',
  449:              format => '%4.2f',
  450:              sortable  => 'no',
  451:              graphable => 'no',
  452:              long_title => 'KR-21 reliability statistic',
  453:              selectable => 'yes',
  454:              defaultselected => 'no',
  455:            },           
  456: );
  457: 
  458: my %SelectedFields;
  459: 
  460: sub parse_field_selection {
  461:     #
  462:     # Pull out the defaults
  463:     if (! defined($ENV{'form.fieldselections'})) {
  464:         $ENV{'form.fieldselections'} = [];
  465:         foreach my $field (@Fields) {
  466:             next if ($field->{'selectable'} ne 'yes');
  467:             if ($field->{'defaultselected'} eq 'yes') {
  468:                 push(@{$ENV{'form.fieldselections'}},$field->{'name'});
  469:             }
  470:         }
  471:     }
  472:     #
  473:     # Make sure the data we are plotting is there
  474:     my %NeededFields;
  475:     if (exists($ENV{'form.plot'}) && $ENV{'form.plot'} ne '' &&
  476:         $ENV{'form.plot'} ne 'none') {
  477:         if ($ENV{'form.plot'} eq 'degrees') {
  478:             $NeededFields{'deg_of_diff'}++;
  479:             $NeededFields{'deg_of_disc'}++;
  480:         } elsif ($ENV{'form.plot'} eq 'tries statistics') {
  481:             $NeededFields{'mean_tries'}++;
  482:             $NeededFields{'std_tries'}++;
  483:             $NeededFields{'problem_num'}++;
  484:         } else {
  485:             $NeededFields{$ENV{'form.plot'}}++;
  486:         }
  487:     }
  488:     #
  489:     # This should not happen, but in case it does...
  490:     if (ref($ENV{'form.fieldselections'}) ne 'ARRAY') {
  491:         $ENV{'form.fieldselections'} = [$ENV{'form.fieldselections'}];
  492:     }
  493:     #
  494:     # Set the field data and the selected fields (for easier checking)
  495:     undef(%SelectedFields);
  496:     foreach my $field (@Fields) {
  497:         if ($field->{'selectable'} ne 'yes') {
  498:             $field->{'selected'} = 'yes';
  499:         } else {
  500:             $field->{'selected'} = 'no';
  501:         }
  502:         if (exists($NeededFields{$field->{'name'}})) {
  503:             $field->{'selected'} = 'yes';
  504:             $SelectedFields{$field->{'name'}}++;
  505:         }
  506:         foreach my $selection (@{$ENV{'form.fieldselections'}}) {
  507:             if ($selection eq $field->{'name'} || $selection eq 'all') {
  508:                 $field->{'selected'} = 'yes';
  509:                 $SelectedFields{$field->{'name'}}++;
  510:             }
  511:         }
  512:     }
  513:     #
  514:     # Always show all the sequence statistics (for now)
  515:     foreach my $field (@SeqFields) {
  516:         $field->{'selected'} = 'yes';
  517:     }
  518:     return;
  519: }
  520: 
  521: sub field_selection_input {
  522:     my $Str = '<select name="fieldselections" multiple size="5">'."\n";
  523:     $Str .= '<option value="all">all</option>'."\n";
  524:     foreach my $field (@Fields) {
  525:         next if ($field->{'selectable'} ne 'yes');
  526:         $Str .= '    <option value="'.$field->{'name'}.'" ';
  527:         if ($field->{'selected'} eq 'yes') {
  528:             $Str .= 'selected ';
  529:         }
  530:         $Str .= '>'.$field->{'title'}.'</option>'."\n";
  531:     }
  532:     $Str .= "</select>\n";
  533: }
  534: 
  535: ###############################################
  536: ###############################################
  537: 
  538: =pod 
  539: 
  540: =item &CreateInterface()
  541: 
  542: Create the main intereface for the statistics page.  Allows the user to
  543: select sections, maps, and output.
  544: 
  545: =cut
  546: 
  547: ###############################################
  548: ###############################################
  549: sub CreateInterface {
  550:     my ($r) = @_;
  551:     #
  552:     &parse_field_selection();
  553:     #
  554:     my $Str = '';
  555:     $Str .= &Apache::lonhtmlcommon::breadcrumbs
  556:         (undef,'Overall Problem Statistics','Statistics_Overall_Key');
  557:     $Str .= '<table cellspacing="5">'."\n";
  558:     $Str .= '<tr>';
  559:     $Str .= '<td align="center"><b>'.&mt('Sections').'</b></td>';
  560:     $Str .= '<td align="center"><b>'.&mt('Enrollment Status').'</b></td>';
  561:     $Str .= '<td align="center"><b>'.&mt('Sequences and Folders').'</b></td>';
  562:     $Str .= '<td align="center"><b>'.&mt('Statistics').'</b></td>';
  563:     $Str .= '<td rowspan="2">'.
  564:         &Apache::lonstathelpers::limit_by_time_form().'</td>';
  565:     $Str .= '</tr>'."\n";
  566:     #
  567:     $Str .= '<tr><td align="center">'."\n";
  568:     $Str .= &Apache::lonstatistics::SectionSelect('Section','multiple',5);
  569:     $Str .= '</td><td align="center">';
  570:     $Str .= &Apache::lonhtmlcommon::StatusOptions(undef,undef,5);
  571:     $Str .= '</td><td align="center">';
  572:     #
  573:     my $only_seq_with_assessments = sub { 
  574:         my $s=shift;
  575:         if ($s->{'num_assess'} < 1) { 
  576:             return 0;
  577:         } else { 
  578:             return 1;
  579:         }
  580:     };
  581:     $Str .= &Apache::lonstatistics::MapSelect('Maps','multiple,all',5,
  582:                                               $only_seq_with_assessments);
  583:     $Str .= '</td><td>'.&field_selection_input();
  584:     $Str .= '</td></tr>'."\n";
  585:     $Str .= '</table>'."\n";
  586:     #
  587:     $Str .= '<p>'.&mt('Status: [_1]',
  588:                          '<input type="text" '.
  589:                          'name="stats_status" size="60" value="" />'
  590:                          ).
  591:                          '</nobr></p>';
  592:     #
  593:     $Str .= '<input type="submit" name="GenerateStatistics" value="'.
  594:         &mt('Generate Statistics').'" />';
  595:     $Str .= '&nbsp;'x5;
  596:     $Str .= 'Plot '.&plot_dropdown().('&nbsp;'x10);
  597:     #
  598:     return $Str;
  599: }
  600: 
  601: ###############################################
  602: ###############################################
  603: 
  604: =pod 
  605: 
  606: =item &BuildProblemStatisticsPage()
  607: 
  608: Main interface to problem statistics.
  609: 
  610: =cut
  611: 
  612: ###############################################
  613: ###############################################
  614: sub BuildProblemStatisticsPage {
  615:     my ($r,$c)=@_;
  616:     #
  617:     my %Saveable_Parameters = ('Status' => 'scalar',
  618:                                'statsoutputmode' => 'scalar',
  619:                                'Section' => 'array',
  620:                                'StudentData' => 'array',
  621:                                'Maps' => 'array',
  622:                                'fieldselections'=> 'array');
  623:     &Apache::loncommon::store_course_settings('statistics',
  624:                                               \%Saveable_Parameters);
  625:     &Apache::loncommon::restore_course_settings('statistics',
  626:                                                 \%Saveable_Parameters);
  627:     #
  628:     &Apache::lonstatistics::PrepareClasslist();
  629:     #
  630:     # Clear the package variables
  631:     undef(@StatsArray);
  632:     undef(%SeqStat);
  633:     #
  634:     # Finally let the user know we are here
  635:     my $interface = &CreateInterface($r);
  636:     $r->print($interface);
  637:     $r->print('<input type="hidden" name="sortby" value="'.$ENV{'form.sortby'}.
  638:               '" />');
  639:     #
  640:     my @CacheButtonHTML = 
  641:         &Apache::lonstathelpers::manage_caches($r,'Statistics','stats_status');
  642:     my $Str;
  643:     foreach my $html (@CacheButtonHTML) {
  644:         $Str.=$html.('&nbsp;'x5);
  645:     }
  646:     #
  647:     $r->print($Str);
  648:     if (! exists($ENV{'form.firstrun'})) {
  649:         $r->print('<h3>'.
  650:                   &mt('Press "Generate Statistics" when you are ready.').
  651:                   '</h3><p>'.
  652:                   &mt('It may take some time to update the student data '.
  653:                       'for the first analysis.  Future analysis this session '.
  654:                       ' will not have this delay.').
  655:                   '</p>');
  656:         return;
  657:     }
  658:     $r->rflush();
  659:     #
  660:     # This probably does not need to be done each time we are called, but
  661:     # it does not slow things down noticably.
  662:     &Apache::loncoursedata::populate_weight_table();
  663:     #
  664:     if (exists($ENV{'form.Excel'})) {
  665:         &Excel_output($r);
  666:     } else { 
  667:         $r->print('<input type="submit" name="Excel" value="'.
  668:                   &mt('Produce Excel Output').'" />'.'&nbsp;'x5);
  669:         $r->rflush();
  670:         my $count = 0;
  671:         foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
  672:             $count += $seq->{'num_assess_parts'};
  673:         }
  674:         if ($count > 10) {
  675:             $r->print('<h2>'.
  676:                       &mt('Compiling statistics for [_1] problems',$count).
  677:                       '</h2>');
  678:             if ($count > 30) {
  679:                 $r->print('<h3>'.&mt('This will take some time.').'</h3>');
  680:             }
  681:             $r->rflush();
  682:         }
  683:         #
  684:         my $sortby = $ENV{'form.sortby'};
  685:         $sortby = 'container' if (! defined($sortby) || $sortby =~ /^\s*$/);
  686:         my $plot = $ENV{'form.plot'};
  687:         if ($plot eq '' || $plot eq 'none') {
  688:             undef($plot);
  689:         }
  690:         if ($sortby eq 'container' && ! defined($plot)) {
  691:             &output_sequence_statistics($r);
  692:             &output_html_by_sequence($r);
  693:         } else {
  694:             if (defined($plot)) {
  695:                 &make_plot($r,$plot);
  696:             }
  697:             &output_html_stats($r);
  698:             &output_sequence_statistics($r);
  699:         }
  700:     }
  701:     return;
  702: }
  703: 
  704: sub output_sequence_statistics {
  705:     my ($r) = @_;
  706:     my $c=$r->connection();
  707:     $r->print('<h2>'.&mt('Sequence Statistics').'</h2>');
  708:     $r->print('<table border="0"><tr><td bgcolor="#777777">'."\n".
  709:               '<table border="0" cellpadding="3">'."\n".
  710:               '<tr bgcolor="#FFFFE6">');
  711:     $r->print(&sequence_html_header());
  712:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
  713:         last if ($c->aborted);
  714:         next if ($seq->{'num_assess'} < 1);
  715:         &compute_sequence_statistics($seq);
  716:         $r->print(&sequence_html_output($seq));
  717:     }
  718:     $r->print('</table>');
  719:     $r->print('</table>');
  720:     $r->rflush();
  721:     return;
  722: }
  723: 
  724: 
  725: ##########################################################
  726: ##########################################################
  727: ##
  728: ## HTML output routines
  729: ##
  730: ##########################################################
  731: ##########################################################
  732: sub output_html_by_sequence {
  733:     my ($r) = @_;
  734:     my $c = $r->connection();
  735:     $r->print(&html_preamble());
  736:     #
  737:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
  738:         last if ($c->aborted);
  739:         next if ($seq->{'num_assess'} < 1);
  740:         $r->print("<h3>".$seq->{'title'}."</h3>".
  741:                   '<table border="0"><tr><td bgcolor="#777777">'."\n".
  742:                   '<table border="0" cellpadding="3">'."\n".
  743:                   '<tr bgcolor="#FFFFE6">'.
  744:                   &statistics_table_header('no container')."</tr>\n");
  745:         my @Data = &compute_statistics_on_sequence($seq);
  746:         foreach my $data (@Data) {
  747:             $r->print('<tr>'.&statistics_html_table_data($data,
  748:                                                          'no container').
  749:                       "</tr>\n");
  750:         }
  751:         $r->print('</table>'."\n".'</table>'."\n");
  752:         $r->rflush();
  753:     }
  754:     return;
  755: }
  756: 
  757: sub output_html_stats {
  758:     my ($r)=@_;
  759:     &compute_all_statistics($r);
  760:     $r->print(&html_preamble());
  761:     &sort_data($ENV{'form.sortby'});
  762:     #
  763:     my $count=0;
  764:     foreach my $data (@StatsArray) {
  765:         if ($count++ % 50 == 0) {
  766:             $r->print("</table>\n</table>\n");
  767:             $r->print('<table border="0"><tr><td bgcolor="#777777">'."\n".
  768:                       '<table border="0" cellpadding="3">'."\n".
  769:                       '<tr bgcolor="#FFFFE6">'.
  770:                       '<tr bgcolor="#FFFFE6">'.
  771:                       &statistics_table_header().
  772:                       "</tr>\n");
  773:         }
  774:         $r->print('<tr>'.&statistics_html_table_data($data)."</tr>\n");
  775:     }
  776:     $r->print("</table>\n</table>\n");
  777:     return;
  778: }
  779: 
  780: sub html_preamble {
  781:     my $Str='';
  782:     $Str .= "<h2>".
  783:         $ENV{'course.'.$ENV{'request.course.id'}.'.description'}.
  784:         "</h2>\n";
  785:     my ($starttime,$endtime) = &Apache::lonstathelpers::get_time_limits();
  786:     if (defined($starttime) || defined($endtime)) {
  787:         # Inform the user what the time limits on the data are.
  788:         $Str .= '<h3>'.&mt('Statistics on submissions from [_1] to [_2]',
  789:                            &Apache::lonlocal::locallocaltime($starttime),
  790:                            &Apache::lonlocal::locallocaltime($endtime)
  791:                            ).'</h3>';
  792:     }
  793:     $Str .= "<h3>".&mt('Compiled on [_1]',
  794:                        &Apache::lonlocal::locallocaltime(time))."</h3>";
  795:     return $Str;
  796: }
  797: 
  798: 
  799: ###############################################
  800: ###############################################
  801: ##
  802: ## Misc HTML output routines
  803: ##
  804: ###############################################
  805: ###############################################
  806: sub statistics_html_table_data {
  807:     my ($data,$options) = @_;
  808:     my $row = '';
  809:     foreach my $field (@Fields) {
  810:         next if ($options =~ /no $field->{'name'}/);
  811:         next if ($field->{'selected'} ne 'yes');
  812:         $row .= '<td bgcolor="'.$field->{'color'}.'"';
  813:         if (exists($field->{'align'})) {
  814:             $row .= ' align="'.$field->{'align'}.'"';
  815:             }
  816:         $row .= '>';
  817:         if (exists($field->{'special'}) && $field->{'special'} eq 'link') {
  818:             $row .= '<a href="'.$data->{$field->{'name'}.'.link'}.'">';
  819:         }
  820:         if (exists($field->{'format'})) {
  821:             $row .= sprintf($field->{'format'},$data->{$field->{'name'}});
  822:         } else {
  823:             $row .= $data->{$field->{'name'}};
  824:         }
  825:         if (exists($field->{'special'}) && $field->{'special'} eq 'link') {
  826:             $row.= '</a>';
  827:         }
  828:         $row .= '</td>';
  829:     }
  830:     return $row;
  831: }
  832: 
  833: sub statistics_table_header {
  834:     my ($options) = @_;
  835:     my $header_row;
  836:     foreach my $field (@Fields) {
  837:         next if ($options =~ /no $field->{'name'}/);
  838:         next if ($field->{'selected'} ne 'yes');
  839:         $header_row .= '<th>';
  840:         if (exists($field->{'sortable'}) && $field->{'sortable'} eq 'yes') {
  841:             $header_row .= '<a href="javascript:'.
  842:                 'document.Statistics.sortby.value='."'".$field->{'name'}."'".
  843:                     ';document.Statistics.submit();">';
  844:         }
  845:         $header_row .= &mt($field->{'title'});
  846:         if ($options =~ /sortable/) {
  847:             $header_row.= '</a>';
  848:         }
  849:         if ($options !~ /no plots/        && 
  850:             exists($field->{'graphable'}) && 
  851:             $field->{'graphable'} eq 'yes') {
  852:             $header_row.=' (';
  853:             $header_row .= '<a href="javascript:'.
  854:                 "document.Statistics.plot.value='$field->{'name'}'".
  855:                     ';document.Statistics.submit();">';
  856:             $header_row .= &mt('plot').'</a>)';
  857:         }
  858:         $header_row .= '</th>';
  859:     }
  860:     return $header_row;
  861: }
  862: 
  863: sub sequence_html_header {
  864:     my $Str .= '<tr>';
  865:     foreach my $field (@SeqFields) {
  866: #        next if ($field->{'selected'} ne 'yes');
  867:         $Str .= '<th bgcolor="'.$field->{'color'}.'"';
  868:         $Str .= '>'.$field->{'title'}.'</th>';
  869:     }
  870:     $Str .= '</tr>';
  871:     return $Str;
  872: }
  873: 
  874: 
  875: sub sequence_html_output {
  876:     my ($seq) = @_;
  877:     my $data = $SeqStat{$seq->{'symb'}};
  878:     my $row = '<tr>';
  879:     foreach my $field (@SeqFields) {
  880:         next if ($field->{'selected'} ne 'yes');
  881:         $row .= '<td bgcolor="'.$field->{'color'}.'"';
  882:         if (exists($field->{'align'})) {
  883:             $row .= ' align="'.$field->{'align'}.'"';
  884:         }
  885:         $row .= '>';
  886:         if (exists($field->{'format'})) {
  887:             $row .= sprintf($field->{'format'},$data->{$field->{'name'}});
  888:         } else {
  889:             $row .= $data->{$field->{'name'}};
  890:         }
  891:         $row .= '</td>';
  892:     }
  893:     $row .= '</tr>'."\n";
  894:     return $row;
  895: }
  896: 
  897: ####################################################
  898: ####################################################
  899: ##
  900: ##    Plotting Routines
  901: ##
  902: ####################################################
  903: ####################################################
  904: sub make_plot {
  905:     my ($r,$plot) = @_;
  906:     &compute_all_statistics($r);
  907:     &sort_data($ENV{'form.sortby'});
  908:     if ($plot eq 'degrees') {
  909:         &degrees_plot($r);
  910:     } elsif ($plot eq 'tries statistics') {
  911:         &tries_data_plot($r);
  912:     } else {
  913:         &make_single_stat_plot($r,$plot);
  914:     }
  915:     return;
  916: }
  917: 
  918: sub make_single_stat_plot {
  919:     my ($r,$datafield) = @_;
  920:     #
  921:     my $title; my $yaxis;
  922:     foreach my $field (@Fields) {
  923:         next if ($field->{'name'} ne $datafield);
  924:         $title = $field->{'long_title'};
  925:         $yaxis = $field->{'title'};
  926:         last;
  927:     }
  928:     if ($title eq '' || $yaxis eq '') {
  929:         # datafield is something we do not know enough about to plot
  930:         $r->print('<h3>'.
  931:                   &mt('Unable to plot the requested statistic.').
  932:                   '</h3>');
  933:         return;
  934:     }
  935:     #
  936:     # Build up the data sets to plot
  937:     my @Labels; 
  938:     my @Data;
  939:     my $max = 1;
  940:     foreach my $data (@StatsArray) {
  941:         push(@Labels,$data->{'problem_num'});
  942:         push(@Data,$data->{$datafield});
  943:         if ($data->{$datafield}>$max) {
  944:             $max = $data->{$datafield};
  945:         }
  946:     }
  947:     foreach (1,2,3,4,5,10,15,20,25,40,50,75,100,150,200,250,300,500,600,750,
  948:              1000,1500,2000,2500,3000,3500,4000,5000,7500,10000,15000,20000) {
  949:         if ($max <= $_) {
  950:             $max = $_;
  951:             last;
  952:         }
  953:     }
  954:     if ($max > 20000) {
  955:         $max = 10000*(int($max/10000)+1);
  956:     }
  957:     #
  958:     $r->print("<p>".&Apache::loncommon::DrawBarGraph($title,
  959:                                                      'Problem Number',
  960:                                                      $yaxis,
  961:                                                      $max,
  962:                                                      undef, # colors
  963:                                                      \@Labels,
  964:                                                      \@Data)."</p>\n");
  965:     return;
  966: }
  967: 
  968: sub degrees_plot {
  969:     my ($r)=@_;
  970:     my $count = scalar(@StatsArray);
  971:     my $width = 50 + 10*$count;
  972:     $width = 300 if ($width < 300);
  973:     my $height = 300;
  974:     my $plot = '';
  975:     my $ymax = 0;
  976:     my $ymin = 0;
  977:     my @Disc; my @Diff; my @Labels;    
  978:     foreach my $data (@StatsArray) {
  979:         push(@Labels,$data->{'problem_num'});
  980:         my $disc = $data->{'deg_of_disc'};
  981:         my $diff = $data->{'deg_of_diff'};
  982:         push(@Disc,$disc);
  983:         push(@Diff,$diff);
  984:         #
  985:         $ymin = $disc if ($ymin > $disc);
  986:         $ymin = $diff if ($ymin > $diff);
  987:         $ymax = $disc if ($ymax < $disc);
  988:         $ymax = $diff if ($ymax < $diff);
  989:     }
  990:     #
  991:     # Make sure we show relevant information.
  992:     if ($ymin < 0) {
  993:         if (abs($ymin) < 0.05) {
  994:             $ymin = 0;
  995:         } else {
  996:             $ymin = -1;
  997:         }
  998:     }
  999:     if ($ymax > 0) {
 1000:         if (abs($ymax) < 0.05) {
 1001:             $ymax = 0;
 1002:         } else {
 1003:             $ymax = 1;
 1004:         }
 1005:     }
 1006:     #
 1007:     my $xmax = $Labels[-1];
 1008:     if ($xmax > 50) {
 1009:         if ($xmax % 10 != 0) {
 1010:             $xmax = 10 * (int($xmax/10)+1);
 1011:         }
 1012:     } else {
 1013:         if ($xmax % 5 != 0) {
 1014:             $xmax = 5 * (int($xmax/5)+1);
 1015:         }
 1016:     }
 1017:     #
 1018:     my $discdata .= '<data>'.join(',',@Labels).'</data>'.$/.
 1019:                     '<data>'.join(',',@Disc).'</data>'.$/;
 1020:     #
 1021:     my $diffdata .= '<data>'.join(',',@Labels).'</data>'.$/.
 1022:                     '<data>'.join(',',@Diff).'</data>'.$/;
 1023:     #
 1024:     my $title = 'Degree of Discrimination\nand Degree of Difficulty';
 1025:     if ($xmax > 50) {
 1026:         $title = 'Degree of Discrimination and Degree of Difficulty';
 1027:     }
 1028:     #
 1029:     $plot=<<"END";
 1030: <gnuplot 
 1031:     texfont="10"
 1032:     fgcolor="x000000"
 1033:     plottype="Cartesian"
 1034:     font="large"
 1035:     grid="on"
 1036:     align="center"
 1037:     border="on"
 1038:     transparent="on"
 1039:     alttag="Degree of Discrimination and Degree of Difficulty Plot"
 1040:     samples="100"
 1041:     bgcolor="xffffff"
 1042:     height="$height"
 1043:     width="$width">
 1044:     <key 
 1045:         pos="top right"
 1046:         title=""
 1047:         box="off" />
 1048:     <title>$title</title>
 1049:     <axis xmin="0" ymin="$ymin" xmax="$xmax" ymax="$ymax" color="x000000" />
 1050:     <xlabel>Problem Number</xlabel>
 1051:     <curve 
 1052:         linestyle="linespoints" 
 1053:         name="DoDisc" 
 1054:         pointtype="0" 
 1055:         color="x000000">
 1056:         $discdata
 1057:     </curve>
 1058:     <curve 
 1059:         linestyle="linespoints" 
 1060:         name="DoDiff" 
 1061:         pointtype="0" 
 1062:         color="xFF0000">
 1063:         $diffdata
 1064:     </curve>
 1065: </gnuplot>
 1066: END
 1067:     my $plotresult = 
 1068:         '<p>'.&Apache::lonxml::xmlparse($r,'web',$plot).'</p>'.$/;
 1069:     $r->print($plotresult);
 1070:     return;
 1071: }
 1072: 
 1073: sub tries_data_plot {
 1074:     my ($r)=@_;
 1075:     my $count = scalar(@StatsArray);
 1076:     my $width = 50 + 10*$count;
 1077:     $width = 300 if ($width < 300);
 1078:     my $height = 300;
 1079:     my $plot = '';
 1080:     my @STD;  my @Mean; my @Max; my @Min;
 1081:     my @Labels;
 1082:     my $ymax = 5;
 1083:     foreach my $data (@StatsArray) {
 1084:         my $max = $data->{'mean_tries'} + $data->{'std_tries'};
 1085:         $ymax = $max if ($ymax < $max);
 1086:         $ymax = $max if ($ymax < $max);
 1087:         push(@Labels,$data->{'problem_num'});
 1088:         push(@STD,$data->{'std_tries'});
 1089:         push(@Mean,$data->{'mean_tries'});
 1090:     }
 1091:     #
 1092:     # Make sure we show relevant information.
 1093:     my $xmax = $Labels[-1];
 1094:     if ($xmax > 50) {
 1095:         if ($xmax % 10 != 0) {
 1096:             $xmax = 10 * (int($xmax/10)+1);
 1097:         }
 1098:     } else {
 1099:         if ($xmax % 5 != 0) {
 1100:             $xmax = 5 * (int($xmax/5)+1);
 1101:         }
 1102:     }
 1103:     $ymax = int($ymax)+1+2;
 1104:     #
 1105:     my $std_data .= '<data>'.join(',',@Labels).'</data>'.$/.
 1106:                     '<data>'.join(',',@Mean).'</data>'.$/;
 1107:     #
 1108:     my $std_error_data .= '<data>'.join(',',@Labels).'</data>'.$/.
 1109:                           '<data>'.join(',',@Mean).'</data>'.$/.
 1110:                           '<data>'.join(',',@STD).'</data>'.$/;
 1111:     #
 1112:     my $title = 'Mean and S.D. of Tries';
 1113:     if ($xmax > 25) {
 1114:         $title = 'Mean and Standard Deviation of Tries';
 1115:     }
 1116:     #
 1117:     $plot=<<"END";
 1118: <gnuplot 
 1119:     texfont="10"
 1120:     fgcolor="x000000"
 1121:     plottype="Cartesian"
 1122:     font="large"
 1123:     grid="on"
 1124:     align="center"
 1125:     border="on"
 1126:     transparent="on"
 1127:     alttag="Mean and S.D of Tries Plot"
 1128:     samples="100"
 1129:     bgcolor="xffffff"
 1130:     height="$height"
 1131:     width="$width">
 1132:     <title>$title</title>
 1133:     <axis xmin="0" ymin="0" xmax="$xmax" ymax="$ymax" color="x000000" />
 1134:     <xlabel>Problem Number</xlabel>
 1135:     <ylabel>Number of Tries</ylabel>
 1136:     <curve 
 1137:         linestyle="yerrorbars"
 1138:         name="S.D. Tries" 
 1139:         pointtype="1" 
 1140:         color="x666666">
 1141:         $std_error_data
 1142:     </curve>
 1143:     <curve 
 1144:         linestyle="points"
 1145:         name="Mean Tries" 
 1146:         pointtype="1" 
 1147:         color="xCC4444">
 1148:         $std_data
 1149:     </curve>
 1150: </gnuplot>
 1151: END
 1152:     my $plotresult = 
 1153:         '<p>'.&Apache::lonxml::xmlparse($r,'web',$plot).'</p>'.$/;
 1154:     $r->print($plotresult);
 1155:     return;
 1156: }
 1157: 
 1158: sub plot_dropdown {
 1159:     my $current = '';
 1160:     #
 1161:     if (defined($ENV{'form.plot'})) {
 1162:         $current = $ENV{'form.plot'};
 1163:     }
 1164:     #
 1165:     my @Additional_Plots = (
 1166:                             { graphable=>'yes',
 1167:                               name => 'degrees',
 1168:                               title => 'Difficulty Indexes' },
 1169:                             { graphable=>'yes',
 1170:                               name => 'tries statistics',
 1171:                               title => 'Tries Statistics' });
 1172:     #
 1173:     my $Str= "\n".'<select name="plot" size="1">';
 1174:     $Str .= '<option name="none"></option>'."\n";
 1175:     $Str .= '<option name="none2">none</option>'."\n";
 1176:     foreach my $field (@Additional_Plots,@Fields) {
 1177:         if (! exists($field->{'graphable'}) ||
 1178:             $field->{'graphable'} ne 'yes') {
 1179:             next;
 1180:         }
 1181:         $Str .= '<option value="'.$field->{'name'}.'"';
 1182:         if ($field->{'name'} eq $current) {
 1183:             $Str .= ' selected ';
 1184:         }
 1185:         $Str.= '>'.&mt($field->{'title'}).'</option>'."\n";
 1186:     }
 1187:     $Str .= '</select>'."\n";
 1188:     return $Str;
 1189: }
 1190: 
 1191: ###############################################
 1192: ###############################################
 1193: ##
 1194: ## Excel output routines
 1195: ##
 1196: ###############################################
 1197: ###############################################
 1198: sub Excel_output {
 1199:     my ($r) = @_;
 1200:     $r->print('<h2>'.&mt('Preparing Excel Spreadsheet').'</h2>');
 1201:     ##
 1202:     ## Compute the statistics
 1203:     &compute_all_statistics($r);
 1204:     my $c = $r->connection;
 1205:     return if ($c->aborted());
 1206:     ##
 1207:     ## Create the excel workbook
 1208:     my $filename = '/prtspool/'.
 1209:         $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
 1210:         time.'_'.rand(1000000000).'.xls';
 1211:     my ($starttime,$endtime) = &Apache::lonstathelpers::get_time_limits();
 1212:     #
 1213:     # Create sheet
 1214:     my $excel_workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1215:     #
 1216:     # Check for errors
 1217:     if (! defined($excel_workbook)) {
 1218:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1219:         $r->print(&mt("Problems creating new Excel file.  ".
 1220:                   "This error has been logged.  ".
 1221:                   "Please alert your LON-CAPA administrator."));
 1222:         return 0;
 1223:     }
 1224:     #
 1225:     # The excel spreadsheet stores temporary data in files, then put them
 1226:     # together.  If needed we should be able to disable this (memory only).
 1227:     # The temporary directory must be specified before calling 'addworksheet'.
 1228:     # File::Temp is used to determine the temporary directory.
 1229:     $excel_workbook->set_tempdir($Apache::lonnet::tmpdir);
 1230:     #
 1231:     # Add a worksheet
 1232:     my $sheetname = $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
 1233:     if (length($sheetname) > 31) {
 1234:         $sheetname = substr($sheetname,0,31);
 1235:     }
 1236:     my $excel_sheet = $excel_workbook->addworksheet(
 1237:         &Apache::loncommon::clean_excel_name($sheetname));
 1238:     #
 1239:     my $format = &Apache::loncommon::define_excel_formats($excel_workbook);
 1240:     ##
 1241:     ## Begin creating excel sheet
 1242:     ##
 1243:     my ($rows_output,$cols_output) = (0,0);
 1244:     #
 1245:     # Put the course description in the header
 1246:     $excel_sheet->write($rows_output,$cols_output++,
 1247:                    $ENV{'course.'.$ENV{'request.course.id'}.'.description'},
 1248:                         $format->{'h1'});
 1249:     $cols_output += 3;
 1250:     #
 1251:     # Put a description of the sections listed
 1252:     my $sectionstring = '';
 1253:     $excel_sheet->write($rows_output,$cols_output++,
 1254:                         &Apache::lonstathelpers::sections_description
 1255:                             (@Apache::lonstatistics::SelectedSections),
 1256:                         $format->{'h3'});
 1257:     $cols_output += scalar(@Apache::lonstatistics::SelectedSections);
 1258:     #
 1259:     # Time restrictions
 1260:     my $time_string;
 1261:     if (defined($starttime)) {
 1262:         # call localtime but not lonlocal:locallocaltime because excel probably
 1263:         # cannot handle localized text.  Probably.
 1264:         $time_string .= 'Data collected from '.localtime($time_string);
 1265:         if (defined($endtime)) {
 1266:             $time_string .= ' to '.localtime($endtime);
 1267:         }
 1268:         $time_string .= '.';
 1269:     } elsif (defined($endtime)) {
 1270:         # See note above about lonlocal:locallocaltime
 1271:         $time_string .= 'Data collected before '.localtime($endtime).'.';
 1272:     }
 1273:     if (defined($time_string)) {
 1274:         $excel_sheet->write($rows_output,$cols_output++,$time_string);
 1275:         $cols_output+= 5;
 1276:     }
 1277:     #
 1278:     # Put the date in there too
 1279:     $excel_sheet->write($rows_output,$cols_output++,
 1280:                         'Compiled on '.localtime(time));
 1281:     #
 1282:     $rows_output++; 
 1283:     $cols_output=0;
 1284:     ##
 1285:     ## Sequence Statistics
 1286:     ## 
 1287:     &write_headers($excel_sheet,$format,\$rows_output,\$cols_output,
 1288:                    \@SeqFields);
 1289:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
 1290:         next if ($seq->{'num_assess'} < 1);
 1291:         my $data = $SeqStat{$seq->{'symb'}};
 1292:         $cols_output=0;
 1293:         foreach my $field (@SeqFields) {
 1294:             next if ($field->{'selected'} ne 'yes');
 1295:             my $fieldformat = undef;
 1296:             if (exists($field->{'excel_format'})) {
 1297:                 $fieldformat = $format->{$field->{'excel_format'}};
 1298:             }
 1299:             $excel_sheet->write($rows_output,$cols_output++,
 1300:                                 $data->{$field->{'name'}},$fieldformat);
 1301:         }
 1302:         $rows_output++;
 1303:         $cols_output=0;
 1304:     }
 1305:     ##
 1306:     ## Resource Statistics
 1307:     ##
 1308:     $rows_output++;
 1309:     $cols_output=0;
 1310:     &write_headers($excel_sheet,$format,\$rows_output,\$cols_output,
 1311:                    \@Fields);
 1312:     #
 1313:     foreach my $data (@StatsArray) {
 1314:         $cols_output=0;
 1315:         foreach my $field (@Fields) {
 1316:             next if ($field->{'selected'} ne 'yes');
 1317:             next if ($field->{'name'} eq 'problem_num');
 1318:             my $fieldformat = undef;
 1319:             if (exists($field->{'excel_format'})) {
 1320:                 $fieldformat = $format->{$field->{'excel_format'}};
 1321:             }
 1322:             $excel_sheet->write($rows_output,$cols_output++,
 1323:                                 $data->{$field->{'name'}},$fieldformat);
 1324:         }
 1325:         $rows_output++;
 1326:         $cols_output=0;
 1327:     }
 1328:     #
 1329:     $excel_workbook->close();
 1330:     #
 1331:     # Tell the user where to get their excel file
 1332:     $r->print('<br />'.
 1333:               '<a href="'.$filename.'">'.
 1334:               &mt('Your Excel Spreadsheet').'</a>'."\n");
 1335:     $r->rflush();
 1336:     return;
 1337: }
 1338: 
 1339: ##
 1340: ## &write_headers
 1341: ##
 1342: sub write_headers {
 1343:     my ($excel_sheet,$format,$rows_output,$cols_output,$Fields) = @_;
 1344:     ##
 1345:     ## First the long titles
 1346:     foreach my $field (@{$Fields}) {
 1347:         next if ($field->{'name'} eq 'problem_num');
 1348:         next if ($field->{'selected'} ne 'yes');
 1349:         if (exists($field->{'long_title'})) {
 1350:             $excel_sheet->write($$rows_output,${$cols_output},
 1351:                                 $field->{'long_title'},
 1352:                                 $format->{'bold'});
 1353:         } else {
 1354:             $excel_sheet->write($$rows_output,${$cols_output},'');
 1355:         }
 1356:         ${$cols_output}+= 1;
 1357:     }
 1358:     ${$cols_output} =0;
 1359:     ${$rows_output}+=1;
 1360:     ##
 1361:     ## Then the short titles
 1362:     foreach my $field (@{$Fields}) {
 1363:         next if ($field->{'selected'} ne 'yes');
 1364:         next if ($field->{'name'} eq 'problem_num');
 1365:         # Use english for excel as I am not sure how well excel handles 
 1366:         # other character sets....
 1367:         $excel_sheet->write($$rows_output,$$cols_output,
 1368:                             $field->{'title'},
 1369:                             $format->{'bold'});
 1370:         $$cols_output+=1;
 1371:     }
 1372:     ${$cols_output} =0;
 1373:     ${$rows_output}+=1;
 1374:     return;
 1375: }
 1376: 
 1377: ##################################################
 1378: ##################################################
 1379: ##
 1380: ## Statistics Gathering and Manipulation Routines
 1381: ##
 1382: ##################################################
 1383: ##################################################
 1384: sub compute_statistics_on_sequence {
 1385:     my ($seq) = @_;
 1386:     my @Data;
 1387:     foreach my $res (@{$seq->{'contents'}}) {
 1388:         next if ($res->{'type'} ne 'assessment');
 1389:         foreach my $part (@{$res->{'parts'}}) {
 1390:             next if ($res->{'partdata'}->{$part}->{'Survey'});
 1391:             #
 1392:             # This is where all the work happens
 1393:             my $data = &get_statistics($seq,$res,$part,scalar(@StatsArray)+1);
 1394:             push (@Data,$data);
 1395:             push (@StatsArray,$data);
 1396:         }
 1397:     }
 1398:     return @Data;
 1399: }
 1400: 
 1401: sub compute_all_statistics {
 1402:     my ($r) = @_;
 1403:     if (@StatsArray > 0) {
 1404:         # Assume we have already computed the statistics
 1405:         return;
 1406:     }
 1407:     my $c = $r->connection;
 1408:     foreach my $seq (&Apache::lonstatistics::Sequences_with_Assess()) {
 1409:         last if ($c->aborted);
 1410:         next if ($seq->{'num_assess'} < 1);
 1411:         &compute_sequence_statistics($seq);
 1412:         &compute_statistics_on_sequence($seq);
 1413:     }
 1414: }
 1415: 
 1416: sub sort_data {
 1417:     my ($sortkey) = @_;
 1418:     return if (! @StatsArray);
 1419:     #
 1420:     # Sort the data
 1421:     my $sortby = undef;
 1422:     foreach my $field (@Fields) {
 1423:         if ($sortkey eq $field->{'name'}) {
 1424:             $sortby = $field->{'name'};
 1425:         }
 1426:     }
 1427:     if (! defined($sortby) || $sortby eq '' || $sortby eq 'problem_num') {
 1428:         $sortby = 'container';
 1429:     }
 1430:     if ($sortby ne 'container') {
 1431:         # $sortby is already defined, so we can charge ahead
 1432:         if ($sortby =~ /^(title|part)$/i) {
 1433:             # Alpha comparison
 1434:             @StatsArray = sort {
 1435:                 lc($a->{$sortby}) cmp lc($b->{$sortby}) ||
 1436:                 lc($a->{'title'}) cmp lc($b->{'title'}) ||
 1437:                 lc($a->{'part'}) cmp lc($b->{'part'});
 1438:             } @StatsArray;
 1439:         } else {
 1440:             # Numerical comparison
 1441:             @StatsArray = sort {
 1442:                 my $retvalue = 0;
 1443:                 if ($b->{$sortby} eq 'nan') {
 1444:                     if ($a->{$sortby} ne 'nan') {
 1445:                         $retvalue = -1;
 1446:                     } else {
 1447:                         $retvalue = 0;
 1448:                     }
 1449:                 }
 1450:                 if ($a->{$sortby} eq 'nan') {
 1451:                     if ($b->{$sortby} ne 'nan') {
 1452:                         $retvalue = 1;
 1453:                     }
 1454:                 }
 1455:                 if ($retvalue eq '0') {
 1456:                     $retvalue = $b->{$sortby} <=> $a->{$sortby}     ||
 1457:                             lc($a->{'title'}) <=> lc($b->{'title'}) ||
 1458:                             lc($a->{'part'})  <=> lc($b->{'part'});
 1459:                 }
 1460:                 $retvalue;
 1461:             } @StatsArray;
 1462:         }
 1463:     }
 1464:     #
 1465:     # Renumber the data set
 1466:     my $count;
 1467:     foreach my $data (@StatsArray) {
 1468:         $data->{'problem_num'} = ++$count;
 1469:     }
 1470:     return;
 1471: }
 1472: 
 1473: ########################################################
 1474: ########################################################
 1475: 
 1476: =pod
 1477: 
 1478: =item &get_statistics()
 1479: 
 1480: Wrapper routine from the call to loncoursedata::get_problem_statistics.  
 1481: Calls lonstathelpers::get_time_limits() to limit the data set by time
 1482: and &compute_discrimination_factor
 1483: 
 1484: Inputs: $sequence, $resource, $part, $problem_num
 1485: 
 1486: Returns: Hash reference with statistics data from 
 1487: loncoursedata::get_problem_statistics.
 1488: 
 1489: =cut
 1490: 
 1491: ########################################################
 1492: ########################################################
 1493: sub get_statistics {
 1494:     my ($sequence,$resource,$part,$problem_num) = @_;
 1495:     #
 1496:     my ($starttime,$endtime) = &Apache::lonstathelpers::get_time_limits();
 1497:     my $symb = $resource->{'symb'};
 1498:     my $courseid = $ENV{'request.course.id'};
 1499:     #
 1500:     my $data = &Apache::loncoursedata::get_problem_statistics
 1501:                         (\@Apache::lonstatistics::SelectedSections,
 1502:                          $Apache::lonstatistics::enrollment_status,
 1503:                          $symb,$part,$courseid,$starttime,$endtime);
 1504:     $data->{'symb'}        = $symb;
 1505:     $data->{'part'}        = $part;
 1506:     $data->{'problem_num'} = $problem_num;
 1507:     $data->{'container'}   = $sequence->{'title'};
 1508:     $data->{'title'}       = $resource->{'title'};
 1509:     $data->{'title.link'}  = $resource->{'src'}.'?symb='.
 1510:         &Apache::lonnet::escape($resource->{'symb'});
 1511:     #
 1512:     if ($SelectedFields{'deg_of_disc'}) {
 1513:         $data->{'deg_of_disc'} = 
 1514:             &compute_discrimination_factor($resource,$part,$sequence);
 1515:     }
 1516:     #
 1517:     # Store in metadata if computations were done for all students
 1518:     if ($data->{'num_students'} > 1) {
 1519:         my @Sections = @Apache::lonstatistics::SelectedSections;
 1520:         my $sections = '"'.join(' ',@Sections).'"';
 1521:         $sections =~ s/&+/_/g;  # Ensure no special characters
 1522:         $data->{'sections'}=$sections;
 1523:         $data->{'course'} = $ENV{'request.course.id'};
 1524:         my $urlres=(&Apache::lonnet::decode_symb($resource->{'symb'}))[2];
 1525:         $data->{'urlres'}=$urlres;
 1526:         my %storestats = 
 1527:             &LONCAPA::lonmetadata::dynamic_metadata_storage($data);
 1528:         my ($dom,$user) = $urlres=~/^(\w+)\/(\w+)/; 
 1529:         &Apache::lonnet::put('nohist_resevaldata',\%storestats,$dom,$user);
 1530:     }
 1531:     #
 1532:     # Get the due date for research purposes (commented out most of the time)
 1533: #    $data->{'duedate'} = 
 1534: #        &Apache::lonnet::EXT('resource.'.$part.'.duedate',$symb);
 1535: #    $data->{'opendate'} = 
 1536: #        &Apache::lonnet::EXT('resource.'.$part.'.opendate',$symb);
 1537: #    $data->{'resptypes'} = join(',',@{$resource->{'partdata'}->{$part}->{'ResponseTypes'}});
 1538:     return $data;
 1539: }
 1540: 
 1541: ###############################################
 1542: ###############################################
 1543: 
 1544: =pod
 1545: 
 1546: =item &compute_discrimination_factor()
 1547: 
 1548: Inputs: $Resource, $Sequence
 1549: 
 1550: Returns: integer between -1 and 1
 1551: 
 1552: =cut
 1553: 
 1554: ###############################################
 1555: ###############################################
 1556: sub compute_discrimination_factor {
 1557:     my ($resource,$part,$sequence) = @_;
 1558:     my @Resources;
 1559:     foreach my $res (@{$sequence->{'contents'}}) {
 1560:         next if ($res->{'symb'} eq $resource->{'symb'});
 1561:         push (@Resources,$res->{'symb'});
 1562:     }
 1563:     #
 1564:     # rank
 1565:     my ($starttime,$endtime) = &Apache::lonstathelpers::get_time_limits();
 1566:     my $ranking = 
 1567:         &Apache::loncoursedata::rank_students_by_scores_on_resources
 1568:         (\@Resources,
 1569:          \@Apache::lonstatistics::SelectedSections,
 1570:          $Apache::lonstatistics::enrollment_status,undef,
 1571:          $starttime,$endtime);
 1572:     #
 1573:     # compute their percent scores on the problems in the sequence,
 1574:     my $number_to_grab = int(scalar(@{$ranking})/4);
 1575:     my $num_students = scalar(@{$ranking});
 1576:     my @BottomSet = map { $_->[&Apache::loncoursedata::RNK_student()]; 
 1577:                       } @{$ranking}[0..$number_to_grab];
 1578:     my @TopSet    = 
 1579:         map { 
 1580:             $_->[&Apache::loncoursedata::RNK_student()]; 
 1581:           } @{$ranking}[($num_students-$number_to_grab)..($num_students-1)];
 1582:     my ($bottom_sum,$bottom_max) = 
 1583:         &Apache::loncoursedata::get_sum_of_scores($resource,$part,\@BottomSet,
 1584:                                                   undef,$starttime,$endtime);
 1585:     my ($top_sum,$top_max) = 
 1586:         &Apache::loncoursedata::get_sum_of_scores($resource,$part,\@TopSet,
 1587:                                                   undef,$starttime,$endtime);
 1588:     my $deg_of_disc;
 1589:     if ($top_max == 0 || $bottom_max==0) {
 1590:         $deg_of_disc = 'nan';
 1591:     } else {
 1592:         $deg_of_disc = ($top_sum/$top_max) - ($bottom_sum/$bottom_max);
 1593:     }
 1594:     #&Apache::lonnet::logthis('    '.$top_sum.'/'.$top_max.
 1595:     #                         ' - '.$bottom_sum.'/'.$bottom_max);
 1596:     return $deg_of_disc;
 1597: }
 1598: 
 1599: ###############################################
 1600: ###############################################
 1601: ##
 1602: ## Compute KR-21
 1603: ##
 1604: ## To compute KR-21, you need the following information:
 1605: ##
 1606: ## K=the number of items in your test
 1607: ## M=the mean score on the test
 1608: ## s=the standard deviation of the scores on your test 
 1609: ##
 1610: ## then:
 1611: ## 
 1612: ## KR-21 rk= [K/(K-1)] * [1- (M*(K-M))/(K*s^2))]
 1613: ##
 1614: ###############################################
 1615: ###############################################
 1616: sub compute_sequence_statistics {
 1617:     my ($seq) = @_;
 1618:     my $symb = $seq->{'symb'};
 1619:     my @Resources;
 1620:     foreach my $res (@{$seq->{'contents'}}) {
 1621:         next if ($res->{'type'} ne 'assessment');
 1622:         push (@Resources,$res->{'symb'});
 1623:     }
 1624:     my ($starttime,$endtime) = &Apache::lonstathelpers::get_time_limits();
 1625:     #
 1626:     # First compute statistics based on student scores
 1627:     my ($smin,$smax,$sMean,$sSTD,$scount,$sMAX) = 
 1628:         &Apache::loncoursedata::score_stats
 1629:                     (\@Apache::lonstatistics::SelectedSections,
 1630:                      $Apache::lonstatistics::enrollment_status,
 1631:                      \@Resources,$starttime,$endtime,undef);
 1632:     $SeqStat{$symb}->{'title'}  = $seq->{'title'};
 1633:     $SeqStat{$symb}->{'scoremax'}  = $smax;
 1634:     $SeqStat{$symb}->{'scoremin'}  = $smin;
 1635:     $SeqStat{$symb}->{'scoremean'} = $sMean;
 1636:     $SeqStat{$symb}->{'scorestd'}  = $sSTD;
 1637:     $SeqStat{$symb}->{'scorecount'} = $scount;
 1638:     $SeqStat{$symb}->{'max_possible'} = $sMAX;
 1639:     #
 1640:     # Compute statistics based on the number of correct problems
 1641:     # 'correct' is taken to mean 
 1642:     my ($cmin,$cmax,$cMean,$cSTD,$ccount)=
 1643:         &Apache::loncoursedata::count_stats
 1644:         (\@Apache::lonstatistics::SelectedSections,
 1645:          $Apache::lonstatistics::enrollment_status,
 1646:          \@Resources,$starttime,$endtime,undef);
 1647:     my $K = $seq->{'num_assess_parts'};
 1648:     my $kr_21;
 1649:     if ($K > 1 && $cSTD > 0) {
 1650:         $kr_21 =  ($K/($K-1)) * (1 - $cMean*($K-$cMean)/($K*$cSTD**2));
 1651:     } else {
 1652:         $kr_21 = 'nan';
 1653:     }
 1654:     $SeqStat{$symb}->{'countmax'} = $cmax;
 1655:     $SeqStat{$symb}->{'countmin'} = $cmin;
 1656:     $SeqStat{$symb}->{'countstd'} = $cSTD;
 1657:     $SeqStat{$symb}->{'countmean'} = $cMean;
 1658:     $SeqStat{$symb}->{'count'} = $ccount;
 1659:     $SeqStat{$symb}->{'items'} = $K;
 1660:     $SeqStat{$symb}->{'KR-21'}=$kr_21;
 1661:     return;
 1662: }
 1663: 
 1664: 
 1665: 
 1666: =pod 
 1667: 
 1668: =item ProblemStatisticsLegend
 1669: 
 1670: =over 4
 1671: 
 1672: =item #Stdnts
 1673: Total number of students attempted the problem.
 1674: 
 1675: =item Tries
 1676: Total number of tries for solving the problem.
 1677: 
 1678: =item Max Tries
 1679: Largest number of tries for solving the problem by a student.
 1680: 
 1681: =item Mean
 1682: Average number of tries. [ Tries / #Stdnts ]
 1683: 
 1684: =item #YES
 1685: Number of students solved the problem correctly.
 1686: 
 1687: =item #yes
 1688: Number of students solved the problem by override.
 1689: 
 1690: =item %Wrong
 1691: Percentage of students who tried to solve the problem 
 1692: but is still incorrect. [ 100*((#Stdnts-(#YES+#yes))/#Stdnts) ]
 1693: 
 1694: =item DoDiff
 1695: Degree of Difficulty of the problem.  
 1696: [ 1 - ((#YES+#yes) / Tries) ]
 1697: 
 1698: =item S.D.
 1699: Standard Deviation of the tries.  
 1700: [ sqrt(sum((Xi - Mean)^2)) / (#Stdnts-1) 
 1701: where Xi denotes every student\'s tries ]
 1702: 
 1703: =item Skew.
 1704: Skewness of the students tries.
 1705: [(sqrt( sum((Xi - Mean)^3) / #Stdnts)) / (S.D.^3)]
 1706: 
 1707: =item Dis.F.
 1708: Discrimination Factor: A Standard for evaluating the 
 1709: problem according to a Criterion<br>
 1710: 
 1711: =item [Criterion to group students into %27 Upper Students - 
 1712: and %27 Lower Students]
 1713: 1st Criterion for Sorting the Students: 
 1714: Sum of Partial Credit Awarded / Total Number of Tries
 1715: 2nd Criterion for Sorting the Students: 
 1716: Total number of Correct Answers / Total Number of Tries
 1717: 
 1718: =item Disc.
 1719: Number of Students had at least one discussion.
 1720: 
 1721: =back
 1722: 
 1723: =cut
 1724: 
 1725: ############################################################
 1726: ############################################################
 1727: 
 1728: 1;
 1729: __END__

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