1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 """
26 create a histogram from data
27 """
28
29 import numpy.oldnumeric as Numeric
30
31
33 """
34 Create a histogram.
35 Comes from Konrad Hinsen: Scientific Python
36
37 @param data: data list or array
38 @type data: [any]
39 @param nbins: number of bins
40 @type nbins: int
41 @param range: data range to create histogram from (min val, max val)
42 @type range: (float, float) OR None
43
44 @return: array (2 x len(data) ) with start of bin and witdh of bin.
45 @rtype: array
46 """
47 data = Numeric.array(data, Numeric.Float)
48 if range is None:
49 min = Numeric.minimum.reduce(data)
50 max = Numeric.maximum.reduce(data)
51 else:
52 min, max = range
53 data = Numeric.repeat(data,
54 Numeric.logical_and(Numeric.less_equal(data, max),
55 Numeric.greater_equal(data, min)))
56 bin_width = (max-min)/nbins
57 data = Numeric.floor((data - min)/bin_width).astype(Numeric.Int)
58 histo = Numeric.add.reduce(Numeric.equal(
59 Numeric.arange(nbins)[:,Numeric.NewAxis], data), -1)
60 histo[-1] = histo[-1] + Numeric.add.reduce(Numeric.equal(nbins, data))
61 bins = min + bin_width*(Numeric.arange(nbins)+0.5)
62 return Numeric.transpose(Numeric.array([bins, histo]))
63
64
65 -def density(x, nBins, range = None, steps = 1, hist = 0):
66 """
67 returns the normalized histogram of x::
68 density( data, nBins [,range=None, steps=1, hist=0|1] ) -> array
69
70 @param x: data list or array
71 @type x: [any]
72 @param nBins: number of bins
73 @type nBins: int
74 @param range: data range to create histogram from (min val, max val)
75 @type range: (float, float) OR None
76 @param steps: 1: histogram appears as a discrete graph (default 1)
77 @type steps: 1|0
78 @param hist: 0: normalize histogram (default 0)
79 @type hist: 1|0
80
81 @return: array (2 x len(data) ) with start of bin and witdh of bin.
82 @rtype: array
83 """
84 h = histogram(x, nBins, range)
85 binWidth = h[1,0] - h[0,0]
86
87 if not hist:
88 i = Numeric.sum(h)[1]*binWidth
89 h[:,1] = h[:,1]/i
90
91 if steps:
92 half = (h[1][0]-h[0][0])/2
93 l = [(h[0][0]-half,0)]
94
95 for row in h:
96 l.append((row[0]-half,row[1]))
97 l.append((row[0]+half,row[1]))
98
99 l.append((h[-1][0]+half,0))
100
101 h = l
102
103 return Numeric.array(h)
104
105
106
107
108
109 import Biskit.test as BT
110
111 -class Test(BT.BiskitTest):
112 """Test case"""
113
115 """hist test"""
116 self.x = Numeric.arange( 4, 12, 1.2 )
117 self.data = density( self.x, 3, hist=1 )
118
119 self.assert_( Numeric.all( self.data == self.EXPECT) )
120
121 EXPECT= Numeric.array([[ 4. , 0. ],
122 [ 4. , 2. ],
123 [ 6.4, 2. ],
124 [ 6.4, 2. ],
125 [ 8.8, 2. ],
126 [ 8.8, 3. ],
127 [ 11.2, 3. ],
128 [ 11.2, 0. ]])
129
130
131 if __name__ == '__main__':
132
133 BT.localTest()
134