SSJ API Documentation
Stochastic Simulation in Java
Loading...
Searching...
No Matches
Tally.java
1/*
2 * Class: Tally
3 * Description: statistical collector
4 * Environment: Java
5 * Software: SSJ
6 * Copyright (C) 2001--2018 Pierre L'Ecuyer and Universite de Montreal
7 * Organization: DIRO, Universite de Montreal
8 * @author
9 * @since
10 *
11 *
12 * Licensed under the Apache License, Version 2.0 (the "License");
13 * you may not use this file except in compliance with the License.
14 * You may obtain a copy of the License at
15 *
16 * http://www.apache.org/licenses/LICENSE-2.0
17 *
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
23 *
24 */
25package umontreal.ssj.stat;
26
27import umontreal.ssj.util.PrintfFormat;
28import umontreal.ssj.probdist.StudentDist;
29import umontreal.ssj.probdist.NormalDist;
30import umontreal.ssj.probdist.ChiSquareDist;
31import java.util.logging.Level;
32import java.util.logging.Logger;
33
47public class Tally extends StatProbe implements Cloneable {
48 protected int numObs;
49 // private double sumSquares;
50 private double curAverage; // The average of the first numObs observations
51 private double curSum2; // The sum (xi - average)^2 of the first numObs
52 // observations.
53 private Logger log = Logger.getLogger("umontreal.ssj.stat");
54
55 protected static enum CIType {
56 CI_NONE, CI_NORMAL, CI_STUDENT
57 };
58
59 protected CIType confidenceInterval = CIType.CI_NONE;
60 protected double level = 0.95;
61 protected int digits = 3;
62
66 public Tally() {
67 super();
68 init();
69 }
70
76 public Tally(String name) {
77 super();
78 this.name = name;
79 init();
80 }
81
87 public void setName(String name) {
88 this.name = name;
89 }
90
91 public void init() {
92 maxValue = Double.NEGATIVE_INFINITY;
93 minValue = Double.POSITIVE_INFINITY;
94 sumValue = 0.0;
95 // sumSquares = 0.0;
96 curAverage = 0.0;
97 curSum2 = 0.0;
98 numObs = 0;
99 }
100
109 public void add(double x) {
110 if (collect) {
111 if (x < minValue)
112 minValue = x;
113 if (x > maxValue)
114 maxValue = x;
115 numObs++;
116 // Algorithme dans Knuth ed. 3, p. 232; voir Wikipedia
117 // http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#cite_note-1
118 double y = x - curAverage;
119 curAverage += y / numObs;
120 curSum2 += y * (x - curAverage);
121 // On pourrait utiliser l'algorithme correcteur de Kahan pour une
122 // meilleure precision.
123 // (voir http://en.wikipedia.org/wiki/Kahan_summation_algorithm)
124 }
126 }
127
131 public void add(double[] x, int number) {
132 if (collect)
133 for (int i = 0; i < number; i++)
134 add(x[i]);
135 }
136
143 public int numberObs() {
144 return numObs;
145 }
146
147 @Override
148 public double sum() {
149 return numObs * curAverage;
150 }
151
155 public double average() {
156 if (numObs < 1) {
157 // System.err.println (
158 // "******* Tally " + name + ": calling average() with " + numObs +
159 // " Observation");
160 log.logp(Level.WARNING, "Tally", "average",
161 "Tally " + name + ": calling average() with " + numObs + " observation");
162 return Double.NaN;
163 }
164 return curAverage;
165 }
166
174 public double variance() {
175 // throws NumberObservationException {
176 // if (numObs < 2) throw NumberObservationException;
177 if (numObs < 2) {
178 // System.err.println (
179 // "******* Tally " + name + ": calling variance() with " + numObs +
180 // " Observation");
181 log.logp(Level.WARNING, "Tally", "variance",
182 "Tally " + name + ": calling variance() with " + numObs + " observation");
183 return Double.NaN;
184 }
185 return curSum2 / (numObs - 1);
186 }
187
195 public double standardDeviation() {
196 return Math.sqrt(variance());
197 }
198
221 public void confidenceIntervalNormal(double level, double[] centerAndRadius) {
222 // Must return an array object, cannot return 2 doubles directly
223 double z;
224 if (numObs < 2)
225 throw new RuntimeException("Tally " + name + ": Calling confidenceIntervalStudent with < 2 Observations");
226 centerAndRadius[0] = average();
227 z = NormalDist.inverseF01(0.5 * (level + 1.0));
228 centerAndRadius[1] = z * Math.sqrt(variance() / (double) numObs);
229 }
230
254 public void confidenceIntervalStudent(double level, double[] centerAndRadius) {
255 // Must return an array object, cannot return 2 doubles directly
256 double t;
257 if (numObs < 2)
258 throw new RuntimeException("Tally " + name + ": Calling confidenceIntervalStudent with < 2 Observations");
259 centerAndRadius[0] = average();
260 t = StudentDist.inverseF(numObs - 1, 0.5 * (level + 1.0));
261 centerAndRadius[1] = t * Math.sqrt(variance() / (double) numObs);
262 }
263
276 public String formatCINormal(double level, int d) {
277 PrintfFormat str = new PrintfFormat();
278 double ci[] = new double[2];
279 confidenceIntervalNormal(level, ci);
280 str.append(" " + (100 * level) + "%");
281 str.append(" conf. interval for the mean (normal approx.): (");
282 str.append(7 + d, d - 1, d, ci[0] - ci[1]).append(',');
283 str.append(7 + d, d - 1, d, ci[0] + ci[1]).append(" )" + PrintfFormat.NEWLINE);
284 return str.toString();
285 }
286
294 public String formatCINormal(double level) {
295 return formatCINormal(level, 3);
296 }
297
310 public String formatCIStudent(double level, int d) {
311 PrintfFormat str = new PrintfFormat();
312 double ci[] = new double[2];
313 confidenceIntervalStudent(level, ci);
314 str.append(" " + (100 * level) + "%");
315 str.append(" conf. interval for the mean (Student approx.): (");
316 str.append(7 + d, d, d - 1, ci[0] - ci[1]).append(',');
317 str.append(7 + d, d, d - 1, ci[0] + ci[1]).append(" )" + PrintfFormat.NEWLINE);
318 return str.toString();
319 }
320
328 public String formatCIStudent(double level) {
329 return formatCIStudent(level, 3);
330 }
331
357 public void confidenceIntervalVarianceChi2(double level, double[] interval) {
358 // Must return an array object, cannot return 2 doubles directly
359 if (numObs < 2)
360 throw new RuntimeException(
361 "Tally " + name + ": calling confidenceIntervalVarianceChi2 with < 2 observations");
362 double w = (numObs - 1) * variance();
363 double x2 = ChiSquareDist.inverseF(numObs - 1, 0.5 * (1.0 + level));
364 double x1 = ChiSquareDist.inverseF(numObs - 1, 0.5 * (1.0 - level));
365 interval[0] = w / x2;
366 interval[1] = w / x1;
367 }
368
381 public String formatCIVarianceChi2(double level, int d) {
382 PrintfFormat str = new PrintfFormat();
383 double ci[] = new double[2];
385 str.append(" " + (100 * level) + "%");
386 str.append(" conf. interval for the variance (chi2 approx.): (");
387 str.append(7 + d, d, d - 1, ci[0]).append(',');
388 str.append(7 + d, d, d - 1, ci[1]).append(" )" + PrintfFormat.NEWLINE);
389 return str.toString();
390 }
391
397 public String report() {
398 return report(level, digits);
399 }
400
410 public String report(double level, int d) {
411 PrintfFormat str = new PrintfFormat();
412 str.append("REPORT on Tally stat. collector ==> " + name);
413 str.append(
414 PrintfFormat.NEWLINE + " num. obs. min max average variance standard dev."
416 str.append(7 + d, (int) numObs);
417 str.append(" ");
418 str.append(9 + d, d, d - 1, (double) minValue);
419 str.append(" ");
420 str.append(9 + d, d, d - 1, (double) maxValue);
421 str.append(" ");
422 str.append(9 + d, d, d - 1, (double) average());
423 str.append(" ");
424 str.append(9 + d, d, d - 1, (double) variance());
425 str.append(" ");
426 str.append(9 + d, d, d - 1, standardDeviation());
428
429 switch (confidenceInterval) {
430 case CI_NORMAL:
431 str.append(formatCINormal(level, d));
432 break;
433 case CI_STUDENT:
434 str.append(formatCIStudent(level, d));
435 break;
436 case CI_NONE:
437 break;
438 }
439
440 return str.toString();
441 }
442
443 public String shortReportHeader() {
444 PrintfFormat pf = new PrintfFormat();
445 if (showNobs)
446 pf.append(-8, "num obs.").append(" ");
447 pf.append(-8, " min").append(" ");
448 pf.append(-8, " max").append(" ");
449 pf.append(-8, " average").append(" ");
450 pf.append(-8, " variance").append(" ");
451 pf.append(-8, " std. dev.");
452 if (confidenceInterval != CIType.CI_NONE)
453 pf.append(" ").append(-12, "conf. int.");
454
455 return pf.toString();
456 }
457
467 public String shortReport() {
468 PrintfFormat pf = new PrintfFormat();
469 if (showNobs)
470 pf.append(-8, numberObs());
471 pf.append(9, 3, 2, min()).append(" ");
472 pf.append(9, 3, 2, max()).append(" ");
473 pf.append(10, 3, 2, average()).append(" ");
474 if (numberObs() >= 2) {
475 pf.append(10, 3, 2, variance()).append(" ");
476 pf.append(11, 3, 2, standardDeviation());
477 } else
478 pf.append(21, "---");
479
480 if (confidenceInterval != CIType.CI_NONE) {
481 double[] ci = new double[2];
482 switch (confidenceInterval) {
483 case CI_NORMAL:
484 confidenceIntervalNormal(level, ci);
485 break;
486 case CI_STUDENT:
487 confidenceIntervalStudent(level, ci);
488 break;
489 case CI_NONE:
490 break;
491 }
492 pf.append(" ").append((100 * level) + "% (");
493 pf.append(9, 3, 2, ci[0] - ci[1]).append(',');
494 pf.append(9, 3, 2, ci[0] + ci[1]).append(")");
495 }
496 return pf.toString();
497 }
498
510 public String reportAndCIStudent(double level, int d) {
511 CIType oldCIType = confidenceInterval;
512
513 try {
514 confidenceInterval = CIType.CI_STUDENT;
515 return report(level, d);
516 } finally {
517 confidenceInterval = oldCIType;
518 }
519 }
520
529 public String reportAndCIStudent(double level) {
530 return reportAndCIStudent(level, 3);
531 }
532
540 public double getConfidenceLevel() {
541 return level;
542 }
543
551 public void setConfidenceLevel(double level) {
552 if (level < 0.0)
553 throw new IllegalArgumentException("level < 0");
554 if (level >= 1.0)
555 throw new IllegalArgumentException("level >= 1");
556 this.level = level;
557 }
558
565 confidenceInterval = CIType.CI_NONE;
566 }
567
574 confidenceInterval = CIType.CI_NORMAL;
575 }
576
583 confidenceInterval = CIType.CI_STUDENT;
584 }
585
592 public void setShowNumberObs(boolean showNumObs) {
593 showNobs = showNumObs;
594 }
595
599 public Tally clone() {
600 try {
601 return (Tally) super.clone();
602 } catch (CloneNotSupportedException e) {
603 throw new IllegalStateException("This Tally cannot be cloned");
604 }
605 }
606
607}
Extends the class ContinuousDistribution for the chi-square distribution with degrees of freedom,...
double inverseF(double u)
Returns the inverse distribution function .
Extends the class ContinuousDistribution for the normal distribution (e.g., tjoh95a  (page 80)).
static double inverseF01(double u)
Same as inverseF(0, 1, u).
Extends the class ContinuousDistribution for the Student.
double inverseF(double u)
Returns the inverse distribution function .
The objects of this class are statistical probes or collectors, which are elementary devices for coll...
void notifyListeners(double x)
Notifies the observation x to all registered observers if broadcasting is ON.
double min()
Returns the smallest value taken by the variable since the last initialization of this probe.
double max()
Returns the largest value taken by the variable since the last initialization of this probe.
double standardDeviation()
Returns the sample standard deviation of the observations since the last initialization.
Definition Tally.java:195
String reportAndCIStudent(double level, int d)
Returns a formatted string that contains a report on this probe (as in report ), followed by a confid...
Definition Tally.java:510
String formatCIStudent(double level)
Equivalent to formatCIStudent (level, 3).
Definition Tally.java:328
String formatCINormal(double level, int d)
Similar to confidenceIntervalNormal.
Definition Tally.java:276
double sum()
Returns the sum cumulated so far for this probe.
Definition Tally.java:148
double average()
Returns the average value of the observations since the last initialization.
Definition Tally.java:155
void setName(String name)
Set the name of this Tally to name.
Definition Tally.java:87
int numberObs()
Returns the number of observations given to this probe since its last initialization.
Definition Tally.java:143
void setConfidenceIntervalStudent()
Indicates that a confidence interval on the true mean, based on the normality assumption,...
Definition Tally.java:582
String formatCINormal(double level)
Equivalent to formatCINormal (level, 3).
Definition Tally.java:294
double variance()
Returns the sample variance of the observations since the last initialization.
Definition Tally.java:174
void init()
Initializes the statistical collector.
Definition Tally.java:91
String formatCIVarianceChi2(double level, int d)
Similar to confidenceIntervalVarianceChi2.
Definition Tally.java:381
String reportAndCIStudent(double level)
Same as reportAndCIStudent(level, 3).
Definition Tally.java:529
String shortReport()
Formats and returns a short statistical report for this tally.
Definition Tally.java:467
void confidenceIntervalStudent(double level, double[] centerAndRadius)
Computes a confidence interval on the mean.
Definition Tally.java:254
void setShowNumberObs(boolean showNumObs)
Determines if the number of observations must be displayed in reports.
Definition Tally.java:592
void setConfidenceLevel(double level)
Sets the level of confidence for the intervals on the mean displayed in reports.
Definition Tally.java:551
void add(double[] x, int number)
Adds the first number observations from the array x to this probe.
Definition Tally.java:131
Tally()
Constructs a new unnamed Tally statistical probe.
Definition Tally.java:66
void setConfidenceIntervalNormal()
Indicates that a confidence interval on the true mean, based on the central limit theorem,...
Definition Tally.java:573
Tally(String name)
Constructs a new Tally statistical probe with name name.
Definition Tally.java:76
String report(double level, int d)
Returns a formatted string that contains a report on this probe with a confidence interval level leve...
Definition Tally.java:410
void setConfidenceIntervalNone()
Indicates that no confidence interval needs to be printed in reports formatted by report,...
Definition Tally.java:564
void confidenceIntervalVarianceChi2(double level, double[] interval)
Computes a confidence interval on the variance.
Definition Tally.java:357
void confidenceIntervalNormal(double level, double[] centerAndRadius)
Computes a confidence interval on the mean.
Definition Tally.java:221
double getConfidenceLevel()
Returns the level of confidence for the intervals on the mean displayed in reports.
Definition Tally.java:540
Tally clone()
Clones this object.
Definition Tally.java:599
void add(double x)
Gives a new observation x to the statistical collector.
Definition Tally.java:109
String shortReportHeader()
Returns a string containing the name of the values returned in the report strings.
Definition Tally.java:443
String formatCIStudent(double level, int d)
Similar to confidenceIntervalStudent.
Definition Tally.java:310
String report()
Returns a formatted string that contains a report on this probe.
Definition Tally.java:397
This class acts like a StringBuffer which defines new types of append methods.
String toString()
Converts the buffer into a String.
PrintfFormat append(String str)
Appends str to the buffer.
static final String NEWLINE
End-of-line symbol or line separator.