File:  [LON-CAPA] / loncom / interface / statistics / lonproblemstatistics.pm
Revision 1.120: download - view: text, annotated - select for diffs
Wed Dec 21 21:25:51 2011 UTC (12 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD, BZ4492-merge, BZ4492-feature_horizontal_radioresponse
Bug 6455 - Progress Indicator now jQuery. Still need to test across browsers.

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

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