source: branches/testFACT++branch/scripts/Hist1D.js@ 19688

Last change on this file since 19688 was 14763, checked in by neise, 12 years ago
initial include
File size: 2.1 KB
Line 
1/**
2 * @fileOverview A simple one dimensional histogram.
3 * @author <a href="mailto:thomas.bretz@epfl.ch">Thomas Bretz</a>
4 */
5'use strict';
6
7/**
8 *
9 * @constructor
10 *
11 * @param {Interger} nx
12 *
13 * @param {Number} xmin
14 *
15 * @param {Number} xmax
16 *
17 * @returns
18 * A sub-classed array with the Hist1D functions added as properties.
19 *
20 * @example
21 * var hist = Hist1D(10, -0.5, 1.5);
22 *
23 */
24function Hist1D(nx, xmin, xmax)
25{
26 /**
27 *
28 * Array
29 *
30 */
31 var arr = new Array(nx);
32
33 /**
34 *
35 * @exports arr.get as Hist1D.get
36 *
37 */
38 arr.get = function(x)
39 {
40 var ix = parseInt(nx*(x-xmin)/(xmax-xmin));
41
42 return arr[ix] ? arr[ix] : 0;
43 }
44
45 /**
46 *
47 * @exports arr.fill as Hist1D.fill
48 *
49 */
50 arr.fill = function(x, w)
51 {
52 if (!x || x===NaN)
53 return false;
54
55 var ix = parseInt(nx*(x-xmin)/(xmax-xmin));
56 if (ix<0 || ix>=nx)
57 return false;
58
59 if (!arr[ix])
60 arr[ix] = 0;
61
62 arr[ix] += w ? w : 1;
63
64 return true;
65 }
66
67 /**
68 *
69 * @exports arr.print as Hist1D.print
70 *
71 */
72 arr.print = function(len)
73 {
74 if (!len)
75 len = 40;
76 if (len<6)
77 len = 6;
78
79 var sum = arr.reduce(function(a,b){return a+b;}, 0);
80 var max = arr.reduce(function(a,b){return Math.max(a,b);}, 0);
81
82 console.out("");
83 for (var ix=nx-1; ix>=0; ix--)
84 {
85 var entry = arr[ix] ? arr[ix] : 0;
86
87 var line ="%3d [%3d%] ".$(ix, sum==0 ? 0 : 100*entry/sum);
88 if (arr[ix])
89 {
90 var val = parseInt(len*arr[ix]/max);
91 var entry = ("%"+val+"s").$("");
92 entry = entry.replace(/ /g, "*");
93 line += ("%-"+len+"s").$(entry)+" |";
94 }
95
96 console.out(line);
97 }
98
99 var entry = arr[ix] ? arr[ix] : 0;
100 console.out(" --------"+("%"+(len-5)+"s").$("")+"-------");
101
102 var line =" %9d ".$(sum);
103 line += ("%"+len+"d").$(max);
104 console.out(line);
105 console.out("");
106 }
107
108 return arr;
109}
Note: See TracBrowser for help on using the repository browser.