home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: OtherApp / OtherApp.zip / entrand.zip / ent / ent.c < prev    next >
C/C++ Source or Header  |  1998-10-20  |  7KB  |  283 lines

  1. /*
  2.     ENT  --  Entropy calculation and analysis of putative
  3.          random sequences.
  4.  
  5.         Designed and implemented by John "Random" Walker in May 1985.
  6.  
  7.     Multiple analyses of random sequences added in December 1985.
  8.  
  9.     Bit stream analysis added in September 1997.
  10.  
  11.     Terse mode output, getopt() command line processing,
  12.     optional stdin input, and HTML documentation added in
  13.     October 1998.
  14.  
  15.     For additional information and the latest version,
  16.     see http://www.fourmilab.ch/random/
  17.  
  18. */
  19.  
  20. #include <stdio.h>
  21. #include <string.h>
  22. #include <ctype.h>
  23. #include <math.h>
  24. #ifndef _MSDOS
  25. #include <unistd.h>
  26. #endif
  27.  
  28. #include "iso8859.h"
  29. #include "randtest.h"
  30.  
  31. #define UPDATE  "October 20th, 1998"
  32.  
  33. #define FALSE 0
  34. #define TRUE  1
  35.  
  36. #ifdef M_PI
  37. #define PI     M_PI
  38. #else
  39. #define PI     3.14159265358979323846
  40. #endif
  41.  
  42. #define V (void)
  43.  
  44. /*  Table of chi-square Xp values versus corresponding probabilities  */
  45.  
  46. static double chsqt[2][10] = {
  47.     0.5,
  48.     0.25,
  49.     0.1,
  50.     0.05,
  51.     0.025,
  52.     0.01,
  53.     0.005,
  54.     0.001,
  55.     0.0005,
  56.     0.0001,
  57.  
  58.     0.0,
  59.     0.6745,
  60.     1.2816,
  61.     1.6449,
  62.     1.9600,
  63.     2.3263,
  64.     2.5758,
  65.     3.0902,
  66.     3.2905,
  67.     3.7190
  68.  
  69. };
  70.  
  71. /*  HELP  --  Print information on how to call    */
  72.  
  73. static void help()
  74. {
  75.         V printf("ent --  Calculate entropy of file.  Call");
  76.         V printf("\n        with ent [options] [input-file]");
  77.         V printf("\n");
  78.         V printf("\n        Options:   -b   Treat input as a stream of bits");
  79.         V printf("\n                   -c   Print occurrence counts");
  80.         V printf("\n                   -f   Fold upper to lower case letters");
  81.         V printf("\n                   -u   Print this message\n");
  82.         V printf("\nBy John Walker");
  83.         V printf("\n   http://www.fourmilab.ch/");
  84.         V printf("\n   %s\n", UPDATE);
  85. }
  86.  
  87. /*  GETOPT  --    Dumb version of getopt for brain-dead MS-DOS.  */
  88.  
  89. #ifdef _MSDOS    
  90. static int optind = 1;
  91.  
  92. static int getopt(int argc, char *argv[], char *opts)
  93. {
  94.     static char *opp = NULL;
  95.     int o;
  96.     
  97.     while (opp == NULL) {
  98.         if ((optind >= argc) || (*argv[optind] != '-')) {
  99.        return -1;
  100.     }
  101.     opp = argv[optind] + 1;
  102.     optind++;
  103.     if (*opp == 0) {
  104.         opp = NULL;
  105.     }    
  106.     }
  107.     o = *opp++;
  108.     if (*opp == 0) { 
  109.     opp = NULL;
  110.     }
  111.     return strchr(opts, o) == NULL ? '?' : o;
  112. }
  113. #endif
  114.  
  115. /*  Main program  */
  116.  
  117. int main(int argc, char *argv[])
  118. {
  119.     int i, oc, opt;
  120.     long ccount[256];          /* Bins to count occurrences of values */
  121.     long totalc = 0;          /* Total character count */
  122.     char *samp;
  123.     double a, montepi, chip,
  124.            scc, ent, mean, chisq;
  125.     FILE *fp = stdin;
  126.     int counts = FALSE,          /* Print character counts */
  127.         fold = FALSE,          /* Fold upper to lower */
  128.         binary = FALSE,          /* Treat input as a bitstream */
  129.         terse = FALSE;          /* Terse (CSV format) output */
  130.  
  131.         while ((opt = getopt(argc, argv, "bcftu?BCFTU")) != -1) {
  132.         switch (toISOlower(opt)) {
  133.                  case 'b':
  134.             binary = TRUE;
  135.             break;
  136.  
  137.                  case 'c':
  138.             counts = TRUE;
  139.             break;
  140.  
  141.                  case 'f':
  142.             fold = TRUE;
  143.             break;
  144.  
  145.                  case 't':
  146.             terse = TRUE;
  147.             break;
  148.  
  149.                  case '?':
  150.                  case 'u':
  151.             help();
  152.             return 0;
  153.         }
  154.     }
  155.     if (optind < argc) {
  156.        if (optind != (argc - 1)) {
  157.               V printf("Duplicate file name.\n");
  158.           help();
  159.           return 2;
  160.        }
  161.            if ((fp = fopen(argv[optind], "rb")) == NULL) {
  162.               V printf("Cannot open file %s\n", argv[optind]);
  163.           return 2;
  164.        }
  165.     }
  166.  
  167.         samp = binary ? "bit" : "byte";
  168.     memset(ccount, 0, sizeof ccount);
  169.  
  170.     /* Initialise for calculations */
  171.  
  172.     rt_init(binary);
  173.  
  174.     /* Scan input file and count character occurrences */
  175.  
  176.     while ((oc = fgetc(fp)) != EOF) {
  177.        unsigned char ocb;
  178.  
  179.        if (fold && isISOalpha(oc) && isISOupper(oc)) {
  180.           oc = toISOlower(oc);
  181.        }
  182.        ocb = (unsigned char) oc;
  183.        totalc += binary ? 8 : 1;
  184.        if (binary) {
  185.         int b;
  186.         unsigned char ob = ocb;
  187.  
  188.         for (b = 0; b < 8; b++) {
  189.         ccount[ob & 1]++;
  190.         ob >>= 1;
  191.         }
  192.        } else {
  193.            ccount[ocb]++;          /* Update counter for this bin */
  194.        }
  195.        rt_add(&ocb, 1);
  196.     }
  197.     V fclose(fp);
  198.  
  199.     /* Complete calculation and return sequence metrics */
  200.  
  201.     rt_end(&ent, &chisq, &mean, &montepi, &scc);
  202.  
  203.     if (terse) {
  204.            V printf("0,File-%ss,Entropy,Chi-square,Mean,Monte-Carlo-Pi,Serial-Correlation\n",
  205.               binary ? "bit" : "byte");
  206.            V printf("1,%ld,%f,%f,%f,%f,%f\n",
  207.           totalc, ent, chisq, mean, montepi, scc);
  208.     }
  209.  
  210.     /* Calculate probability of observed distribution occurring from
  211.        the results of the Chi-Square test */
  212.  
  213.     chip = sqrt(2.0 * chisq) - sqrt(2.0 * (binary ? 1 : 255.0) - 1.0);
  214.     a = fabs(chip);
  215.     for (i = 9; i >= 0; i--) {
  216.        if (chsqt[1][i] < a) {
  217.           break;
  218.        }
  219.     }
  220.     chip = (chip >= 0.0) ? chsqt[0][i] : 1.0 - chsqt[0][i];
  221.  
  222.     /* Print bin counts if requested */
  223.  
  224.     if (counts) {
  225.        if (terse) {
  226.               V printf("2,Value,Occurrences,Fraction\n");
  227.        } else {
  228.               V printf("Value Char Occurrences Fraction\n");
  229.        }
  230.        for (i = 0; i < (binary ? 2 : 256); i++) {
  231.           if (terse) {
  232.                  V printf("3,%d,%ld,%f\n", i,
  233.             ccount[i], ((double) ccount[i] / totalc));
  234.           } else {
  235.          if (ccount[i] > 0) {
  236.                     V printf("%3d   %c   %10ld   %f\n", i,
  237.                /* The following expression shows ISO 8859-1
  238.               Latin1 characters and blanks out other codes.
  239.               The test for ISO space replaces the ISO
  240.               non-blanking space (0xA0) with a regular
  241.                           ASCII space, guaranteeing it's rendered
  242.                           properly even when the font doesn't contain
  243.               that character, which is the case with many
  244.               X fonts. */
  245.                        (!isISOprint(i) || isISOspace(i)) ? ' ' : i,
  246.                ccount[i], ((double) ccount[i] / totalc));
  247.          }
  248.           }
  249.        }
  250.        if (!terse) {
  251.               V printf("\nTotal:    %10ld   %f\n\n", totalc, 1.0);
  252.        }
  253.     }
  254.  
  255.     /* Print calculated results */
  256.  
  257.     if (!terse) {
  258.            V printf("Entropy = %f bits per %s.\n", ent, samp);
  259.            V printf("\nOptimum compression would reduce the size\n");
  260.            V printf("of this %ld %s file by %d percent.\n\n", totalc, samp,
  261.             (short) ((100 * ((binary ? 1 : 8) - ent) /
  262.                   (binary ? 1.0 : 8.0))));
  263.        V printf(
  264.               "Chi square distribution for %ld samples is %1.2f, and randomly\n",
  265.           totalc, chisq);
  266.            V printf("would exceed this value %1.2f percent of the times.\n\n",
  267.           chip * 100);
  268.        V printf(
  269.               "Arithmetic mean value of data %ss is %1.4f (%.1f = random).\n",
  270.           samp, mean, binary ? 0.5 : 127.5);
  271.            V printf("Monte Carlo value for Pi is %1.9f (error %1.2f percent).\n",
  272.           montepi, 100.0 * (fabs(PI - montepi) / PI));
  273.            V printf("Serial correlation coefficient is ");
  274.        if (scc >= -99999) {
  275.               V printf("%1.6f (totally uncorrelated = 0.0).\n", scc);
  276.        } else {
  277.               V printf("undefined (all values equal!).\n");
  278.        }
  279.     }
  280.  
  281.     return 0;
  282. }
  283.