Migrated from GitHub
Browse files- data/zipf.c +295 -0
- data/zipf.java +343 -0
- data/zipf.py +237 -0
data/zipf.c
ADDED
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2003-2009 Bill Manaris, Dana Hughes, J.R. Armstrong, Thomas Zalonis, Luca Pellicoro,
|
2 |
+
// Chris Wagner, Chuck McCormick
|
3 |
+
//
|
4 |
+
// This program is free software: you can redistribute it and/or modify
|
5 |
+
// it under the terms of the GNU General Public License as published by
|
6 |
+
// the Free Software Foundation, either version 3 of the License, or
|
7 |
+
// (at your option) any later version.
|
8 |
+
//
|
9 |
+
// This program is distributed in the hope that it will be useful,
|
10 |
+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
11 |
+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
12 |
+
// GNU General Public License for more details.
|
13 |
+
//
|
14 |
+
// You should have received a copy of the GNU General Public License
|
15 |
+
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
16 |
+
//
|
17 |
+
|
18 |
+
/* zipf.c Version 1.5 24-Dec-2009
|
19 |
+
*
|
20 |
+
* This module encapsulates functions that may be used to calculate
|
21 |
+
* the slope and r2 (fit) of a trendline
|
22 |
+
* of a Zipf distribution (byRank or bySize).
|
23 |
+
*
|
24 |
+
* The byRank distribution plots the values (y-axis)
|
25 |
+
* against the ranks of the values from largest to smallest
|
26 |
+
* (x-axis) in log-log scale. The ranks are generated automatically.
|
27 |
+
*
|
28 |
+
* The bySize distribution plots the values (y-axis)
|
29 |
+
* against the supplised keys (x-axis) in log-log scale.
|
30 |
+
*
|
31 |
+
* Usage: Call bySize(int *ranks, int numRanks, double *counts, int numCounts) and.or
|
32 |
+
* byRank(double *counts, int numCounts) functions.
|
33 |
+
*
|
34 |
+
* Output: slope and R2
|
35 |
+
*
|
36 |
+
* WARNING: If an error occurs the current code will NOT raise an exception;
|
37 |
+
* it will only print an error message (for ShedSkin compatibility).
|
38 |
+
* This may cause problems, if the error messages go undetected
|
39 |
+
* (e.g., this code is run in batch mode).
|
40 |
+
*
|
41 |
+
* Authors: Chris Wagner and Bill Manaris (based on VB code by Chuck McCormick and Bill Manaris)
|
42 |
+
*
|
43 |
+
* Thomas Zalonis - translate to C.
|
44 |
+
*
|
45 |
+
* version 1.5 (December 24, 2008) J.R. Armstrong and Bill Manaris
|
46 |
+
* - Now we are differentiating between monotonous and random phenomena (vertical vs. horizontal trendlines).
|
47 |
+
* In the first case, we return slope = 0 and r2 = 0.
|
48 |
+
* In the second case, we return slope = 0 and r2 = 1.
|
49 |
+
* Also, some variable names have been updated.
|
50 |
+
*
|
51 |
+
* version 1.4 (October 1, 2008) Bill Manaris
|
52 |
+
* - Added more unit-testing code (i.e., if __name__=='__main__') for Shed Skin Python-to-C++ conversion to work.
|
53 |
+
* - Updated some variable names for usability/readability
|
54 |
+
*
|
55 |
+
* version 1.3 (March 23, 2007) Thomas Zalonis
|
56 |
+
* - Added code to the getSlopeR2() function that calculates the y-intercept for the trendline.
|
57 |
+
* - getSlopeR2() now returns 3 values, slope, r2 and the trendline y-intercept
|
58 |
+
*
|
59 |
+
* version 1.2 (Feb 03, 2007) Luca Pellicoro
|
60 |
+
* -Translation from Java to Python
|
61 |
+
* -Raise exceptions with erroneous user inputs (such as zero keys or values)
|
62 |
+
*
|
63 |
+
* version 1.1 (July 30, 2005)
|
64 |
+
*
|
65 |
+
* version 1.0 (May 10, 2003)
|
66 |
+
*
|
67 |
+
*
|
68 |
+
* Calculates slope and R^2 values of a collection of numbers.
|
69 |
+
*
|
70 |
+
* Libraries needed:
|
71 |
+
* -----------------
|
72 |
+
* stdlib for qsort
|
73 |
+
*
|
74 |
+
*/
|
75 |
+
|
76 |
+
#include <stdlib.h>
|
77 |
+
#include <math.h>
|
78 |
+
#include <unistd.h>
|
79 |
+
#include <sys/stat.h>
|
80 |
+
#include <sys/types.h>
|
81 |
+
#include <sys/mman.h>
|
82 |
+
#include <fcntl.h>
|
83 |
+
#include <string.h>
|
84 |
+
|
85 |
+
#define FALSE 0
|
86 |
+
#define TRUE 1
|
87 |
+
|
88 |
+
//*****************************************************************************
|
89 |
+
// This struct is used to return multiple values from byRank()
|
90 |
+
// ****************************************************************************
|
91 |
+
struct ZipfValues
|
92 |
+
{
|
93 |
+
float slope;
|
94 |
+
float r2;
|
95 |
+
float yint;
|
96 |
+
};
|
97 |
+
|
98 |
+
|
99 |
+
// zipf related
|
100 |
+
struct ZipfValues *getSlopeR2(int *, int, double *, int);
|
101 |
+
int checkRanksAndCounts(int *, int, double *, int);
|
102 |
+
struct ZipfValues *bySize(int *, int, double *, int);
|
103 |
+
int compare(const void *, const void *);
|
104 |
+
struct ZipfValues *byRank(double *, int);
|
105 |
+
|
106 |
+
|
107 |
+
//*****************************************************************************
|
108 |
+
// The byRank distribution plots the values (y-axis)
|
109 |
+
// against the ranks of the values from largest to smallest
|
110 |
+
// (x-axis) in log-log scale. The ranks are generated automatically.
|
111 |
+
//*****************************************************************************
|
112 |
+
struct ZipfValues *byRank(double *counts, int numCounts)
|
113 |
+
{
|
114 |
+
double *newCounts = (double *)malloc(sizeof(double) * numCounts);
|
115 |
+
int *newRanks = (int *)malloc(sizeof(int) * numCounts);
|
116 |
+
|
117 |
+
int index;
|
118 |
+
for(index=0;index<numCounts;index++)
|
119 |
+
{
|
120 |
+
newCounts[index] = counts[index];
|
121 |
+
newRanks[index] = numCounts - index;
|
122 |
+
}
|
123 |
+
|
124 |
+
qsort((void *)newCounts, numCounts, sizeof(double), compare);
|
125 |
+
|
126 |
+
checkRanksAndCounts(newRanks, numCounts, newCounts, numCounts);
|
127 |
+
|
128 |
+
return getSlopeR2(newRanks, numCounts, newCounts, numCounts);
|
129 |
+
}
|
130 |
+
|
131 |
+
//*****************************************************************************
|
132 |
+
// 'Double' comparison function needed for sorting. This function
|
133 |
+
// is passed in as a parameter to qsort() in the byRank() function.
|
134 |
+
//*****************************************************************************
|
135 |
+
int compare(const void *a, const void *b)
|
136 |
+
{
|
137 |
+
double d = *( (double *) a) - *( (double *) b );
|
138 |
+
|
139 |
+
if(d > 0.0)
|
140 |
+
{
|
141 |
+
return 1;
|
142 |
+
}
|
143 |
+
else if (d < 0.0)
|
144 |
+
{
|
145 |
+
return -1;
|
146 |
+
}
|
147 |
+
else
|
148 |
+
{
|
149 |
+
return 0;
|
150 |
+
}
|
151 |
+
}
|
152 |
+
|
153 |
+
//*****************************************************************************
|
154 |
+
// The bySize distribution plots the values (y-axis)
|
155 |
+
// against the supplised keys (x-axis) in log-log scale.
|
156 |
+
//*****************************************************************************
|
157 |
+
struct ZipfValues *bySize(int *sizes, int numSizes, double *counts, int numCounts)
|
158 |
+
{
|
159 |
+
checkRanksAndCounts(sizes, numSizes, counts, numCounts);
|
160 |
+
return getSlopeR2(sizes, numSizes, counts, numCounts);
|
161 |
+
}
|
162 |
+
|
163 |
+
//*****************************************************************************
|
164 |
+
// Supporting function for bySize() and byRank(). Checks the passed values
|
165 |
+
// for correctness.
|
166 |
+
//*****************************************************************************
|
167 |
+
int checkRanksAndCounts(int *ranks, int numRanks, double *counts, int numCounts)
|
168 |
+
{
|
169 |
+
if(numCounts == 0)
|
170 |
+
{
|
171 |
+
fprintf(stderr, "Counts should contain at least one element.\n");
|
172 |
+
exit(0);
|
173 |
+
}
|
174 |
+
|
175 |
+
if(numRanks == 0)
|
176 |
+
{
|
177 |
+
fprintf(stderr, "Ranks should contain at least one element.\n");
|
178 |
+
exit(0);
|
179 |
+
}
|
180 |
+
|
181 |
+
if(numRanks != numCounts)
|
182 |
+
{
|
183 |
+
fprintf(stderr, "Ranks (%d) and counts (%d) should have the same size.\n", numRanks, numCounts);
|
184 |
+
exit(0);
|
185 |
+
}
|
186 |
+
|
187 |
+
int i;
|
188 |
+
for(i=0;i<numRanks;i++)
|
189 |
+
{
|
190 |
+
if(ranks[i] <= 0.0)
|
191 |
+
{
|
192 |
+
fprintf(stderr, "Ranks should be strictly positive.\n");
|
193 |
+
exit(0);
|
194 |
+
}
|
195 |
+
|
196 |
+
if(counts[i] <= 0.0)
|
197 |
+
{
|
198 |
+
fprintf(stderr, "Counts and values should be strictly positive.\n");
|
199 |
+
exit(0);
|
200 |
+
}
|
201 |
+
}
|
202 |
+
|
203 |
+
return 0;
|
204 |
+
}
|
205 |
+
|
206 |
+
//*****************************************************************************
|
207 |
+
// Supporting function for byRank() and bySize(). The actual zipf values
|
208 |
+
// (slope, R2 and yint) are calculated in this function and returned
|
209 |
+
// as a struct.
|
210 |
+
//*****************************************************************************
|
211 |
+
struct ZipfValues *getSlopeR2(int *ranks, int numRanks, double *counts, int numCounts)
|
212 |
+
{
|
213 |
+
struct ZipfValues *results = (struct ZipfValues *)malloc(sizeof(struct ZipfValues));
|
214 |
+
double sumX, sumY, sumXY, sumX2, sumY2,slope, r2, yint;
|
215 |
+
int index;
|
216 |
+
|
217 |
+
sumX = sumY = sumXY = sumX2 = sumY2 = 0.0;
|
218 |
+
|
219 |
+
// one exterme case:
|
220 |
+
// if the phenomenon is monotonous (only one type of event, e.g., ['a', 'a', 'a']),
|
221 |
+
// then the slope is negative infinity (cannot draw a line with only one data point),
|
222 |
+
// so indicate this with slope = 0 AND r2 = 0
|
223 |
+
if(numRanks == 1)
|
224 |
+
{
|
225 |
+
slope = 0.0;
|
226 |
+
r2 = 0.0;
|
227 |
+
}
|
228 |
+
else
|
229 |
+
{
|
230 |
+
//the other extreme case:
|
231 |
+
//if the phenomenon is uniformly distributed (several types of events,
|
232 |
+
//but all having the same number of instances, e.g., ['a', 'b', 'a', 'b', 'a', 'b']),
|
233 |
+
//then the slope = 0 and r2 = 1 (a horizontal line).
|
234 |
+
|
235 |
+
//check if all counts are equal
|
236 |
+
|
237 |
+
int allCountsEqual = 1;
|
238 |
+
for(index=0;(index < numRanks - 1) && allCountsEqual;index++)
|
239 |
+
{
|
240 |
+
if(counts[index] != counts[index + 1])
|
241 |
+
allCountsEqual = 0;
|
242 |
+
}
|
243 |
+
|
244 |
+
if(allCountsEqual)
|
245 |
+
{
|
246 |
+
slope = 0.0;
|
247 |
+
r2 = 1.0;
|
248 |
+
}
|
249 |
+
else // general case, so calculate actual slope and r2 values
|
250 |
+
{
|
251 |
+
double tmp1,tmp2;
|
252 |
+
for(index=0;index<numRanks;index++)
|
253 |
+
{
|
254 |
+
// only calculating the follow log()s once for efficiency
|
255 |
+
tmp1 = log10(ranks[index]);
|
256 |
+
tmp2 = log10(counts[index]);
|
257 |
+
|
258 |
+
sumX += tmp1;
|
259 |
+
sumY += tmp2;
|
260 |
+
sumXY += tmp1 * tmp2;
|
261 |
+
sumX2 += pow(tmp1, 2);
|
262 |
+
sumY2 += pow(tmp2, 2);
|
263 |
+
}
|
264 |
+
|
265 |
+
// calculate slope
|
266 |
+
if((numRanks*sumX2 - sumX*sumX) == 0.0)
|
267 |
+
slope = 0.0;
|
268 |
+
else
|
269 |
+
slope = ((numRanks*sumXY - sumX*sumY) / (numRanks*sumX2 - sumX*sumX));
|
270 |
+
|
271 |
+
// calculate r2
|
272 |
+
if(sqrt((numRanks*sumX2 - sumX*sumX) * (numRanks*sumY2 - sumY*sumY)) == 0.0)
|
273 |
+
{
|
274 |
+
r2 = 0.0;
|
275 |
+
}
|
276 |
+
else
|
277 |
+
{
|
278 |
+
r2 = (numRanks*sumXY - sumX*sumY)/(sqrt(numRanks*sumX2 - sumX*sumX)*sqrt(numRanks*sumY2 - sumY*sumY));
|
279 |
+
r2 = r2 * r2;
|
280 |
+
}
|
281 |
+
}
|
282 |
+
}
|
283 |
+
|
284 |
+
// calculate y-intercept
|
285 |
+
yint = (sumY - slope * sumX) / numRanks;
|
286 |
+
|
287 |
+
// packing slope, r2 and yint into a ZipfValues struct
|
288 |
+
// so that all three can be returned at once.
|
289 |
+
results->slope = slope;
|
290 |
+
results->r2 = r2;
|
291 |
+
results->yint = yint;
|
292 |
+
|
293 |
+
return results;
|
294 |
+
}
|
295 |
+
|
data/zipf.java
ADDED
@@ -0,0 +1,343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2003-2009 Bill Manaris, Dana Hughes, J.R. Armstrong, Thomas Zalonis, Luca Pellicoro,
|
2 |
+
// Chris Wagner, Chuck McCormick
|
3 |
+
//
|
4 |
+
// This program is free software: you can redistribute it and/or modify
|
5 |
+
// it under the terms of the GNU General Public License as published by
|
6 |
+
// the Free Software Foundation, either version 3 of the License, or
|
7 |
+
// (at your option) any later version.
|
8 |
+
//
|
9 |
+
// This program is distributed in the hope that it will be useful,
|
10 |
+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
11 |
+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
12 |
+
// GNU General Public License for more details.
|
13 |
+
//
|
14 |
+
// You should have received a copy of the GNU General Public License
|
15 |
+
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
16 |
+
//
|
17 |
+
|
18 |
+
|
19 |
+
package nevmuse.utilities;
|
20 |
+
|
21 |
+
import java.util.Arrays;
|
22 |
+
import java.util.Hashtable;
|
23 |
+
import java.util.Enumeration;
|
24 |
+
|
25 |
+
/**
|
26 |
+
* This class contains static methods that calculate the slope and R^2 of a trendline
|
27 |
+
* of a Zipf distribution (byRank or bySize).
|
28 |
+
* <br>
|
29 |
+
* <br>The byRank distribution plots the values (y-axis) against the ranks of the values from largest to smallest
|
30 |
+
* (x-axis) in log-log scale. The ranks are generated automatically.
|
31 |
+
* <br>
|
32 |
+
* <br>The bySize distribution plots the values (y-axis) against the supplied keys (x-axis) in log-log scale.
|
33 |
+
* <br>
|
34 |
+
* <br>
|
35 |
+
* <b>NOTE: </b> The provided methods are static, so call them as Zipf.byRank(values) or Zipf.bySize(keys, values).
|
36 |
+
* <br>
|
37 |
+
* <br>
|
38 |
+
* @author Luca Pellicoro, Chris Wagner, Bill Manaris (based on VB code by Chuck McCormick and Bill Manaris )
|
39 |
+
*
|
40 |
+
* @version 1.6 (October 19, 2009) Dana Hughes
|
41 |
+
* - Replaced IllegalArgumentException when no values are passed with slope = 0 and r2 = 0.
|
42 |
+
* This allows for batch processes to continue without exiting due to this exception.
|
43 |
+
* Also, numeric values may be more meaningful.
|
44 |
+
* @version 1.5 (November 3, 2009) Thomas Zalonis
|
45 |
+
* - Translated the latest zipf.py update (see zipf.py update message below) to Zipf.java
|
46 |
+
* zipf.py version 1.5 (December 24, 2008) J.R. Armstrong and Bill Manaris
|
47 |
+
* - Now we are differentiating between monotonous and random phenomena (vertical vs. horizontal trendlines).
|
48 |
+
* In the first case, we return slope = 0 and r2 = 0.
|
49 |
+
* In the second case, we return slope = 0 and r2 = 1.
|
50 |
+
* Also, some variable names have been updated.
|
51 |
+
*
|
52 |
+
* @version 1.2 (Jan 2007) Luca Pellicoro
|
53 |
+
* - Static Methods only (no more class instantiation)
|
54 |
+
* - Raising exceptions intead of Assert statements
|
55 |
+
* - Zero values and zero keys are considered erroneous input (raise IllegalArgumentException)
|
56 |
+
* @version 1.1 (July 30, 2005)
|
57 |
+
* @version 1.0 (May 10, 2003)
|
58 |
+
*/
|
59 |
+
|
60 |
+
public class Zipf
|
61 |
+
{
|
62 |
+
/*
|
63 |
+
public static void main(String[] args)
|
64 |
+
{
|
65 |
+
// numbers can be entered from the command line as "java Zipf 1 2 2 3 3 3 3" or
|
66 |
+
// any other sequence of numbers by uncommenting the code below.
|
67 |
+
|
68 |
+
//double[] phen = new double[args.length];
|
69 |
+
//for(int i = 0;i < args.length;i++)
|
70 |
+
//{
|
71 |
+
// phen[i] = (int)Double.parseDouble(args[i]);
|
72 |
+
//}
|
73 |
+
|
74 |
+
//double[] phen = {1, 1, 1}; // check monotonous
|
75 |
+
//double[] phen = {2, 2, 2, 3, 3, 3}; // check uniformly distributed (white noise)
|
76 |
+
//double[] phen = {1, 1, 2}; // check truly zipfian (pink noise)
|
77 |
+
//double[] phen = {1, 1, 1, 1, 2}; // check brown noise
|
78 |
+
double[] phen = {1, 2, 2, 3, 3, 3, 3}; // check general case
|
79 |
+
|
80 |
+
System.out.print("Given the sequence: ");
|
81 |
+
for(int i = 0;i < phen.length;i++)
|
82 |
+
{
|
83 |
+
System.out.print(phen[i] + ", ");
|
84 |
+
}
|
85 |
+
System.out.println();
|
86 |
+
|
87 |
+
// calculate frequency of occurrence of each symbol
|
88 |
+
Hashtable histogram = new Hashtable();
|
89 |
+
|
90 |
+
for(int i = 0;i < phen.length;i++)
|
91 |
+
{
|
92 |
+
if(histogram.containsKey(phen[i]))
|
93 |
+
{
|
94 |
+
int currentValue = ((Integer)histogram.get(phen[i])).intValue();
|
95 |
+
|
96 |
+
histogram.put(phen[i], new Integer(currentValue + 1));
|
97 |
+
}
|
98 |
+
else
|
99 |
+
{
|
100 |
+
histogram.put(phen[i], new Integer(1));
|
101 |
+
}
|
102 |
+
}
|
103 |
+
|
104 |
+
// next, extract the counts and calculate their rank-frequency (Zipfian) distribution
|
105 |
+
double[] counts = new double[histogram.size()];
|
106 |
+
int i = 0;
|
107 |
+
for (Enumeration e = histogram.keys(); e.hasMoreElements();)
|
108 |
+
{
|
109 |
+
counts[i] = (double)((Integer)histogram.get(e.nextElement())).intValue();
|
110 |
+
i++;
|
111 |
+
}
|
112 |
+
|
113 |
+
double[] result = byRank(counts);
|
114 |
+
double slope = result[0];
|
115 |
+
double r2 = result[1];
|
116 |
+
|
117 |
+
System.out.println("The byRank slope is " + slope + " and the R2 is " + r2);
|
118 |
+
|
119 |
+
// now, extract the sizes calculate their side-frequency (Zipfian) distribution
|
120 |
+
double[] sizes = new double[histogram.size()];
|
121 |
+
i = 0;
|
122 |
+
for (Enumeration e = histogram.keys(); e.hasMoreElements();)
|
123 |
+
{
|
124 |
+
sizes[i] = ((Double)e.nextElement()).doubleValue();
|
125 |
+
i++;
|
126 |
+
}
|
127 |
+
|
128 |
+
result = bySize(sizes, counts);
|
129 |
+
slope = result[0];
|
130 |
+
r2 = result[1];
|
131 |
+
|
132 |
+
System.out.println("The bySize slope is " + slope + " and the R2 is " + r2);
|
133 |
+
}
|
134 |
+
*/
|
135 |
+
|
136 |
+
/**
|
137 |
+
*
|
138 |
+
* Calculate the slope and R^2 of the rank-frequency distribution of the provided frequencies.
|
139 |
+
* Ranks will be automatically generated.
|
140 |
+
* <br>
|
141 |
+
* <br>
|
142 |
+
* '''NOTE:''' Caller does not need to sort the frequencies.
|
143 |
+
* <br>
|
144 |
+
* <br>
|
145 |
+
* @param frequencies The values whose rank-frequency distribution to calculate (y-axis).
|
146 |
+
*
|
147 |
+
* @return A double array containing slope (at index 0) and R^2 (at index 1).
|
148 |
+
*/
|
149 |
+
public static double[] byRank(double[] frequencies)
|
150 |
+
{
|
151 |
+
|
152 |
+
int numberOfValues = frequencies.length;
|
153 |
+
|
154 |
+
// Step 1 and 2: Sort the vals and create keys
|
155 |
+
// Copy vals so sort doesn't alter it.
|
156 |
+
double[] newValues = new double[numberOfValues];
|
157 |
+
double[] keys = new double[numberOfValues];
|
158 |
+
for(int i = 0; i < numberOfValues; i++)
|
159 |
+
{
|
160 |
+
keys[i] = numberOfValues - i;
|
161 |
+
newValues[i] = frequencies[i];
|
162 |
+
}
|
163 |
+
|
164 |
+
Arrays.sort(newValues);
|
165 |
+
|
166 |
+
checkKeysAndValues(keys, newValues);
|
167 |
+
|
168 |
+
// Step 3: Get Zipf Slope and R2 of keys/values.
|
169 |
+
return calculateSlopeR2(keys, newValues);
|
170 |
+
}
|
171 |
+
|
172 |
+
/**
|
173 |
+
* Calculate the slope and R^2 of the size-frequency distribution of the provided sizes and frequencies.
|
174 |
+
* <br>
|
175 |
+
* <br>
|
176 |
+
* '''NOTE:''' Caller does not need to sort the sizes or frequencies provided.
|
177 |
+
* <br>
|
178 |
+
* <br>
|
179 |
+
* @param sizes The sizes (x-axis).
|
180 |
+
* @param frequencies The frequencies (y-axis).
|
181 |
+
*
|
182 |
+
* @return An double array containing slope (at index 0) and R^2 (at index 1).
|
183 |
+
*/
|
184 |
+
public static double[] bySize(double[] sizes, double[] frequencies)
|
185 |
+
{
|
186 |
+
|
187 |
+
checkKeysAndValues(sizes, frequencies);
|
188 |
+
// NOTE: There is no need to sort the parallel arrays of keys and vals, since
|
189 |
+
// getSlopeR2() does not care if the keys are sorted in any particular order;
|
190 |
+
// it cares only that the association between keys[i] and vals[i] is correct.
|
191 |
+
|
192 |
+
return calculateSlopeR2(sizes, frequencies);
|
193 |
+
}
|
194 |
+
|
195 |
+
|
196 |
+
|
197 |
+
/*******************************
|
198 |
+
* SUPPORTING METHODS
|
199 |
+
*******************************/
|
200 |
+
|
201 |
+
/**
|
202 |
+
* Checks if provided data is relatively error free. In particular, it will raise exceptions if
|
203 |
+
* - a data array is empty
|
204 |
+
* - keys and values do not contain the same number of elements
|
205 |
+
* - a data array contains negative or zero elements
|
206 |
+
*/
|
207 |
+
private static void checkKeysAndValues(double[] keys, double[] values)
|
208 |
+
{
|
209 |
+
// NOTE: The first exception (keys or values contain no elements) has been replaced with
|
210 |
+
// setting the slope and r2 values to 0. This allows for batch operations to be
|
211 |
+
// performed without generating an Exception, or requiring the use of NaN's.
|
212 |
+
|
213 |
+
// if (keys.length == 0 || values.length == 0)
|
214 |
+
// throw new IllegalArgumentException ("Data (values and keys) must contain at least one element.");
|
215 |
+
|
216 |
+
if (keys.length != values.length)
|
217 |
+
throw new IllegalArgumentException("Keys and values must have the same length (keys length was " + keys.length + " and values length was " + values.length + ").");
|
218 |
+
|
219 |
+
for (int i = 0; i < values.length; i++)
|
220 |
+
if (keys[i] <= 0.0 || values[i] <= 0.0)
|
221 |
+
throw new IllegalArgumentException ("Data must be positive: keys[" + i + "] was " + keys[i] + " and values[" + i + "] was " + values[i] );
|
222 |
+
}
|
223 |
+
|
224 |
+
|
225 |
+
/**
|
226 |
+
* Calculates the linear regression (slope and R^2 (fit)) of a set of keys and values.
|
227 |
+
* If slope and/or R^2 cannot be calculated, zero is returned.
|
228 |
+
*
|
229 |
+
* @param keys The keys for the set
|
230 |
+
* @param vals The values for the set
|
231 |
+
*
|
232 |
+
* @return An array of doubles (slope is stored in index 0 and R^2 (fit) in index 1).
|
233 |
+
*/
|
234 |
+
private static double[] calculateSlopeR2(double[] keys, double[] vals)
|
235 |
+
{
|
236 |
+
|
237 |
+
// Log10(keys) is mapped to the X axis.
|
238 |
+
// Log10(vals) is mapped to the Y axis.
|
239 |
+
double sumX = 0; // holds the sum of X values.
|
240 |
+
double sumY = 0; // holds the sum of Y values.
|
241 |
+
double sumXY = 0; // holds the sum of X*Y values.
|
242 |
+
double sumX2 = 0; // holds the sum of X*X values.
|
243 |
+
double sumY2 = 0; // holds the sum of Y*Y values.
|
244 |
+
double[] sr2 = new double[2]; // holds the slope and r2 to be returned (slope is stored in index 0 and R^2 in index 1)
|
245 |
+
|
246 |
+
// one exterme case:
|
247 |
+
// if the phenomenon is monotonous (only one type of event, e.g., ['a', 'a', 'a']),
|
248 |
+
// then the slope is negative infinity (cannot draw a line with only one data point),
|
249 |
+
// so indicate this with slope = 0 AND r2 = 0
|
250 |
+
if (keys.length == 1)
|
251 |
+
{
|
252 |
+
sr2[0] = 0.0;
|
253 |
+
sr2[1] = 0.0;
|
254 |
+
}
|
255 |
+
// another extreme case (added 10/20/10):
|
256 |
+
// if the phenomenon contains no information (i.e., no statistical data exists),
|
257 |
+
// then the slope is undefined. Rather than causing an Exception, indicate this
|
258 |
+
// with a slope = 0 AND r2 = 0. Classes utilizing Zipf can always override this
|
259 |
+
// prior to calling and set these values to NaN, if desired.
|
260 |
+
else if (keys.length == 0)
|
261 |
+
{
|
262 |
+
sr2[0] = 0.0;
|
263 |
+
sr2[1] = 0.0;
|
264 |
+
}
|
265 |
+
|
266 |
+
else
|
267 |
+
{
|
268 |
+
// the other extreme case:
|
269 |
+
// if the phenomenon is uniformly distributed (several types of events,
|
270 |
+
// but all having the same number of instances, e.g., ['a', 'b', 'a', 'b', 'a', 'b']),
|
271 |
+
// then the slope = 0 and r2 = 1 (a horizontal line).
|
272 |
+
|
273 |
+
// check if all counts are equal
|
274 |
+
int i = 0;
|
275 |
+
boolean allCountsEqual = true; // assume they are all equal
|
276 |
+
while(allCountsEqual && i < (keys.length - 1))
|
277 |
+
{
|
278 |
+
allCountsEqual = (vals[i] == vals[i + 1]); // update hypothesis
|
279 |
+
i = i + 1;
|
280 |
+
}
|
281 |
+
|
282 |
+
if (allCountsEqual) // is phenomenon uniformly distributed?
|
283 |
+
{
|
284 |
+
sr2[0] = 0.0;
|
285 |
+
sr2[1] = 1.0;
|
286 |
+
}
|
287 |
+
else // general case, so caluclate actual slope and r2 values
|
288 |
+
{
|
289 |
+
|
290 |
+
// Sum up the values for the calculations.
|
291 |
+
for (i = 0; i < keys.length; i++)
|
292 |
+
{
|
293 |
+
//System.out.print(" " + i + " ");
|
294 |
+
sumX += log10(keys[i]);
|
295 |
+
sumY += log10(vals[i]);
|
296 |
+
sumXY += log10(keys[i]) * log10(vals[i]);
|
297 |
+
sumX2 += log10(keys[i]) * log10(keys[i]);
|
298 |
+
sumY2 += log10(vals[i]) * log10(vals[i]);
|
299 |
+
}
|
300 |
+
|
301 |
+
// calculate the slope
|
302 |
+
if ((keys.length * sumX2 - sumX * sumX) == 0) // check for division by zero (below)
|
303 |
+
sr2[0] = 0;
|
304 |
+
else
|
305 |
+
sr2[0] = ((keys.length * sumXY - sumX * sumY) / (keys.length * sumX2 - sumX * sumX));
|
306 |
+
|
307 |
+
// If you want to create the line: y = mx + b
|
308 |
+
// m = slope
|
309 |
+
// This calculates b.
|
310 |
+
// double b = (sumY - sr2[0] * sumX) / keys.length;
|
311 |
+
|
312 |
+
// calculate the R^2
|
313 |
+
if (Math.sqrt((keys.length * sumX2 - sumX * sumX) * (keys.length * sumY2 - sumY * sumY)) == 0) // check for division by zero (below)
|
314 |
+
sr2[1] = 0;
|
315 |
+
else
|
316 |
+
sr2[1] = (keys.length * sumXY - sumX * sumY) / Math.sqrt((keys.length * sumX2 - sumX * sumX) * (keys.length * sumY2 - sumY * sumY));
|
317 |
+
sr2[1] = sr2[1] * sr2[1]; // get the square
|
318 |
+
}
|
319 |
+
}
|
320 |
+
|
321 |
+
// return the result (slope is stored in index 0 and R^2 in index 1)
|
322 |
+
return sr2;
|
323 |
+
}
|
324 |
+
|
325 |
+
/**
|
326 |
+
* The natural log of 10
|
327 |
+
*/
|
328 |
+
private static final double LN_10 = 2.3025850929940456840179914546844;
|
329 |
+
|
330 |
+
/**
|
331 |
+
* Calculate the Log base 10 of a number.
|
332 |
+
* This is required because Math.log is not Log(10) but Ln (natural Log).
|
333 |
+
*
|
334 |
+
* Note: Log(b) n = Ln n / Ln b.
|
335 |
+
*
|
336 |
+
* @param n The original number.
|
337 |
+
*
|
338 |
+
* @return Log(10) n
|
339 |
+
*/
|
340 |
+
private static double log10(double n) {
|
341 |
+
return Math.log(n)/LN_10;
|
342 |
+
}
|
343 |
+
}
|
data/zipf.py
ADDED
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2003-2009 Bill Manaris, Dana Hughes, J.R. Armstrong, Thomas Zalonis, Luca Pellicoro,
|
2 |
+
# Chris Wagner, Chuck McCormick
|
3 |
+
#
|
4 |
+
# This program is free software: you can redistribute it and/or modify
|
5 |
+
# it under the terms of the GNU General Public License as published by
|
6 |
+
# the Free Software Foundation, either version 3 of the License, or
|
7 |
+
# (at your option) any later version.
|
8 |
+
#
|
9 |
+
# This program is distributed in the hope that it will be useful,
|
10 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
11 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
12 |
+
# GNU General Public License for more details.
|
13 |
+
#
|
14 |
+
# You should have received a copy of the GNU General Public License
|
15 |
+
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
16 |
+
#
|
17 |
+
|
18 |
+
# zipf.py Version 1.5 24-Dec-2008
|
19 |
+
#
|
20 |
+
# This module encapsulates functions that may be used to calculate
|
21 |
+
# the slope and r2 (fit) of a trendline
|
22 |
+
# of a Zipf distribution (byRank or bySize).
|
23 |
+
#
|
24 |
+
# The byRank distribution plots the values (y-axis)
|
25 |
+
# against the ranks of the values from largest to smallest
|
26 |
+
# (x-axis) in log-log scale. The ranks are generated automatically.
|
27 |
+
#
|
28 |
+
# The bySize distribution plots the values (y-axis)
|
29 |
+
# against the supplied keys (x-axis) in log-log scale.
|
30 |
+
#
|
31 |
+
# Usage: Call bySize(sizes, counts) and/or byRank(counts) functions
|
32 |
+
# Output: slope and R2
|
33 |
+
#
|
34 |
+
# WARNING: If an error occurs the current code will NOT raise an exception;
|
35 |
+
# it will only print an error message (for ShedSkin compatibility).
|
36 |
+
# This may cause problems, if the error messages go undetected
|
37 |
+
# (e.g., this code is run in batch mode).
|
38 |
+
#
|
39 |
+
# Authors: Chris Wagner and Bill Manaris (based on VB code by Chuck McCormick and Bill Manaris)
|
40 |
+
#
|
41 |
+
# version 1.5 (December 24, 2008) J.R. Armstrong and Bill Manaris
|
42 |
+
# - Now we are differentiating between monotonous and random phenomena (vertical vs. horizontal trendlines).
|
43 |
+
# In the first case, we return slope = 0 and r2 = 0.
|
44 |
+
# In the second case, we return slope = 0 and r2 = 1.
|
45 |
+
# Also, some variable names have been updated.
|
46 |
+
#
|
47 |
+
# version 1.4 (October 1, 2008) Bill Manaris
|
48 |
+
# - Added more unit-testing code (i.e., if __name__=='__main__') for Shed Skin Python-to-C++ conversion to work.
|
49 |
+
# - Updated some variable names for usability/readability
|
50 |
+
#
|
51 |
+
# version 1.3 (March 23, 2007) Thomas Zalonis
|
52 |
+
# - Added code to the getSlopeR2() function that calculates the y-intercept for the trendline.
|
53 |
+
# - getSlopeR2() now returns 3 values, slope, r2 and the trendline y-intercept
|
54 |
+
#
|
55 |
+
# version 1.2 (Feb 03, 2007) Luca Pellicoro
|
56 |
+
# -Translation from Java to Python
|
57 |
+
# -Raise exceptions with erroneous user inputs (such as zero keys or values)
|
58 |
+
#
|
59 |
+
# version 1.1 (July 30, 2005)
|
60 |
+
#
|
61 |
+
# version 1.0 (May 10, 2003)
|
62 |
+
#
|
63 |
+
|
64 |
+
# for logarithmic calculations
|
65 |
+
from math import *
|
66 |
+
|
67 |
+
|
68 |
+
def byRank(counts):
|
69 |
+
'''
|
70 |
+
Calculate the slope and R^2 of the counts.
|
71 |
+
Sorting the counts in descending order.
|
72 |
+
'''
|
73 |
+
|
74 |
+
|
75 |
+
newCounts = [] # to hold the deep copy
|
76 |
+
newRanks = [] # the newly created ranks
|
77 |
+
numberOfCounts = len(counts)
|
78 |
+
for index in range(numberOfCounts):
|
79 |
+
newCounts.append(counts[index]) # deep copy the counts
|
80 |
+
newRanks.append(numberOfCounts - index) # create the ranks: highest frequency has smallest rank
|
81 |
+
|
82 |
+
|
83 |
+
|
84 |
+
newCounts.sort()
|
85 |
+
|
86 |
+
checkRanksAndCounts(newRanks, newCounts)
|
87 |
+
|
88 |
+
return getSlopeR2(newRanks, newCounts)
|
89 |
+
|
90 |
+
def bySize(sizes, counts):
|
91 |
+
'''
|
92 |
+
Calculate the slope and r2 of the counts without ordering the ranks.
|
93 |
+
Keys contains the desired ranking.
|
94 |
+
'''
|
95 |
+
|
96 |
+
|
97 |
+
checkRanksAndCounts(sizes,counts)
|
98 |
+
|
99 |
+
|
100 |
+
return getSlopeR2(sizes, counts)
|
101 |
+
|
102 |
+
|
103 |
+
######################################
|
104 |
+
######### SUPPORTING METHODS #########
|
105 |
+
######################################
|
106 |
+
|
107 |
+
def checkRanksAndCounts(ranks, counts):
|
108 |
+
'''
|
109 |
+
Verify that:
|
110 |
+
- ranks and counts contain at least one element
|
111 |
+
- ranks and counts have the same length
|
112 |
+
- both ranks and counts do not contain any negative or zero element
|
113 |
+
'''
|
114 |
+
|
115 |
+
if len(counts) == 0: raise ValueError, 'Counts should contain at least one element'
|
116 |
+
if min(counts) <= 0.0: raise ValueError, 'Counts should be strictly positive: %f' % (min(counts))
|
117 |
+
|
118 |
+
if len(ranks) == 0: raise ValueError, 'Ranks should contain at least one element'
|
119 |
+
if min(ranks) <= 0.0 : raise ValueError, 'Ranks should be strictly positive: %f' % (min(ranks))
|
120 |
+
|
121 |
+
|
122 |
+
if len(ranks) != len(counts):
|
123 |
+
raise ValueError,'Ranks (length: %d) and counts (length: %d) should have the same size.' % (len(ranks), len(counts))
|
124 |
+
|
125 |
+
## # Comment the above exception code, and uncomment the code below,
|
126 |
+
## # for ShedSkin compatibility.
|
127 |
+
|
128 |
+
## if len(counts) == 0: print "Zipf ValueError: ", 'Counts should contain at least one element'
|
129 |
+
## if min(counts) <= 0.0: print "Zipf ValueError: ", 'Counts should be strictly positive: %f' % (min(counts))
|
130 |
+
##
|
131 |
+
## if len(ranks) == 0: print "Zipf ValueError: ", 'Ranks should contain at least one element'
|
132 |
+
## if min(ranks) <= 0.0 : print "Zipf ValueError: ", 'Ranks should be strictly positive: %f' % (min(ranks))
|
133 |
+
##
|
134 |
+
## if len(ranks) != len(counts):
|
135 |
+
## print "Zipf ValueError: ",'Ranks (length: %d) and counts (length: %d) should have the same size.' % (len(ranks), len(values))
|
136 |
+
|
137 |
+
|
138 |
+
def getSlopeR2(ranks, counts):
|
139 |
+
'''
|
140 |
+
Calculates the Zipf Slope and R^2(fit) of a
|
141 |
+
set of ranks and counts.
|
142 |
+
If slope and/or R^2 cannot be calculated, a zero is returned.
|
143 |
+
'''
|
144 |
+
|
145 |
+
assert len(ranks) == len(counts) , 'Ranks and counts must have the same length.'
|
146 |
+
|
147 |
+
sumX = sumY = sumXY = sumX2 = sumY2 = 0.0
|
148 |
+
|
149 |
+
numberOfRanks = len(ranks)
|
150 |
+
|
151 |
+
# one exterme case:
|
152 |
+
# if the phenomenon is monotonous (only one type of event, e.g., ['a', 'a', 'a']),
|
153 |
+
# then the slope is negative infinity (cannot draw a line with only one data point),
|
154 |
+
# so indicate this with slope = 0 AND r2 = 0
|
155 |
+
if numberOfRanks == 1:
|
156 |
+
slope = 0.0
|
157 |
+
r2 = 0.0
|
158 |
+
|
159 |
+
else:
|
160 |
+
# the other extreme case:
|
161 |
+
# if the phenomenon is uniformly distributed (several types of events,
|
162 |
+
# but all having the same number of instances, e.g., ['a', 'b', 'a', 'b', 'a', 'b']),
|
163 |
+
# then the slope = 0 and r2 = 1 (a horizontal line).
|
164 |
+
|
165 |
+
# check if all counts are equal
|
166 |
+
i = 0
|
167 |
+
allCountsEqual = True # assume they are all equal
|
168 |
+
while allCountsEqual and i < numberOfRanks-1:
|
169 |
+
allCountsEqual = (counts[i] == counts[i + 1]) # update hypothesis
|
170 |
+
i = i + 1
|
171 |
+
|
172 |
+
if allCountsEqual: # is phenomenon uniformly distributed?
|
173 |
+
slope = 0.0
|
174 |
+
r2 = 1.0
|
175 |
+
|
176 |
+
# general case, so calculate actual slope and r2 values
|
177 |
+
else:
|
178 |
+
|
179 |
+
# Sum up the values for the calculations
|
180 |
+
for index in range(numberOfRanks):
|
181 |
+
sumX += log(ranks[index],10)
|
182 |
+
sumY += log(counts[index],10)
|
183 |
+
sumXY += log(ranks[index],10) * log(counts[index],10)
|
184 |
+
sumX2 += log(ranks[index],10)**2
|
185 |
+
sumY2 += log(counts[index],10)**2
|
186 |
+
|
187 |
+
# calculate the slope
|
188 |
+
if ((numberOfRanks * sumX2 - sumX * sumX) == 0.0):
|
189 |
+
slope = 0.0
|
190 |
+
else:
|
191 |
+
slope = ((numberOfRanks * sumXY - sumX * sumY) / (numberOfRanks * sumX2 - sumX * sumX))
|
192 |
+
|
193 |
+
# calculate the r2
|
194 |
+
if(sqrt((numberOfRanks * sumX2 - sumX * sumX) * (numberOfRanks * sumY2 - sumY * sumY)) == 0.0):
|
195 |
+
r2 = 0.0
|
196 |
+
else:
|
197 |
+
r = (numberOfRanks * sumXY - sumX * sumY) / sqrt((numberOfRanks * sumX2 - sumX * sumX) * (numberOfRanks * sumY2 - sumY * sumY))
|
198 |
+
r2 = r * r
|
199 |
+
|
200 |
+
# calulate y-intercept
|
201 |
+
yint = (sumY - slope * sumX) / len(ranks)
|
202 |
+
|
203 |
+
return slope, r2, yint
|
204 |
+
|
205 |
+
if __name__ == '__main__':
|
206 |
+
#print "Enter sequence of numbers to calculate its Zipfian distribution."
|
207 |
+
#print "The rank-frequency distribution is calculated based on how many times each number appears."
|
208 |
+
#print "The size-frequency distribution is calculated based on how many times each number appears; also the actual number is treated as if it represents 'size'."
|
209 |
+
#phenomenon = input("Enter sequence of numbers (e.g., [50, 100, 50]): ")
|
210 |
+
|
211 |
+
#phenomenon = [1, 1, 1] # check monotonous
|
212 |
+
#phenomenon = [2, 2, 2, 3, 3, 3] # check uniformly distributed (white noise)
|
213 |
+
#phenomenon = [1, 1, 2] # check truly zipfian (pink noise)
|
214 |
+
#phenomenon = [1, 1, 1, 1, 2] # check brown noise
|
215 |
+
phenomenon = [1, 2, 2, 3, 3, 3, 3] # check general case
|
216 |
+
print "Given the sequence", phenomenon
|
217 |
+
|
218 |
+
# calculate frequency of occurrence of each symbol
|
219 |
+
histogram = {}
|
220 |
+
for event in phenomenon:
|
221 |
+
histogram[event] = histogram.get(event, 0) + 1
|
222 |
+
# now, the histogram contains the frequencies
|
223 |
+
|
224 |
+
# next, extract the counts and calculate their rank-frequency (Zipfian) distribution
|
225 |
+
counts = histogram.values()
|
226 |
+
slope, r2, yint = byRank(counts)
|
227 |
+
print "The byRank slope is", slope, "and the R^2 is", r2
|
228 |
+
|
229 |
+
# now, extract the sizes calculate their side-frequency (Zipfian) distribution
|
230 |
+
sizes = histogram.keys()
|
231 |
+
slope, r2, yint = bySize(sizes, counts)
|
232 |
+
print "The bySize slope is", slope, "and the R^2 is", r2
|
233 |
+
|
234 |
+
|
235 |
+
|
236 |
+
|
237 |
+
|