File:  [LON-CAPA] / loncom / interface / statistics / lonproblemstatistics.pm
Revision 1.112: download - view: text, annotated - select for diffs
Mon Jan 14 14:32:49 2008 UTC (16 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_7_0, version_2_6_X, version_2_6_99_1, version_2_6_99_0, version_2_6_3, version_2_6_2, version_2_6_1, HEAD
When using calls to &Apache::lonnet::EXT(), request a scalar explicitly, to avoid similar problems to those eencountered in bug 5578, following the change in lonnet.pm rev 1.927 which enabled EXT() to return the level a parameter is set at, if an array was requested.

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

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