Source code: infranet/CommonCache.java
1 /* Copyright (c) 2003, Massachusetts Institute of Technology
2 * All rights reserved.
3 *
4 * Permission to use, copy, modify and distribute this software and its
5 * documentation for any purpose, without fee, and without written agreement is
6 * hereby granted, provided that the above copyright notice and the following
7 * paragraph appears in all copies of this software.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
10 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
11 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
13 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
14 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
15 * IN THE SOFTWARE.
16 *
17 * Author: Winston Wang
18 *
19 */
20
21 package infranet;
22
23 import java.io.*;
24 import java.util.*;
25
26 public class CommonCache {
27
28 private static SortedMap map;
29
30 public static void init(String discreteFile) throws FileNotFoundException, IOException {
31 map = new TreeMap();
32 BufferedReader r = new BufferedReader(new FileReader(discreteFile));
33 int total = 0;
34 while(r.ready()) {
35 StringTokenizer st = new StringTokenizer(r.readLine());
36 if (st.hasMoreTokens()) {
37 int num = Integer.parseInt(st.nextToken());
38 String symbol = st.nextToken();
39 map.put(symbol, new Double(total));
40 total += num;
41 }
42 }
43 Iterator i = map.entrySet().iterator();
44 while (i.hasNext()) {
45 Map.Entry e = (Map.Entry)i.next();
46 Double newValue = new Double(((Double)e.getValue()).doubleValue() / total);
47 map.put(e.getKey(), newValue);
48 }
49 }
50
51 private SortedMap tempMap;
52
53 public double cdf(String s) {
54 if (s.length() == 0) return 0;
55
56 tempMap = map.tailMap(s);
57 if (tempMap.isEmpty()) return 1;
58 return ((Double)tempMap.values().iterator().next()).doubleValue();
59 }
60
61 public String bound() {
62 if (tempMap.isEmpty()) return UniformCdf.HIGHEST_STRING;
63 return (String)tempMap.firstKey();
64 }
65 }
66