/** * Created by rebeccamancy on 23/01/2014. */ import java.io.IOException; import java.io.PrintWriter; import java.util.*; public class QSD { Map M; private int totalClicks; /** * Construct an empty HashMap in order to store the sites */ public QSD() { M = new HashMap(); totalClicks = 0; } /** * Draws a value from the QSD representation proportional to relative time in each state (a hashtable with BitSet keys and counts) * @return an integer array (because this is how the rest of the code is built, rather than on BitSets) */ public int[] drawFromQSD(){ int[] draw; BitSet bitRepState = new BitSet(); double p = Math.random() * this.totalClicks; double clickCount = 0; Iterator it = M.entrySet().iterator(); // Loop over each entry in the hashtable until total count exceeds our random number while (it.hasNext()){ Map.Entry pairs = (Map.Entry)it.next(); StateCounter s = (StateCounter)pairs.getValue(); // cast it into a StateCounter to access counter clickCount = clickCount + (s.getCounter()); if (clickCount > p) { bitRepState = s.getState(); break; } } draw = Util.BitSet2bin(bitRepState); return draw; } public void add(BitSet key, int clicks){ // key is the system state represented as a bitset // Look in the hashmap to see if the represented state is already there StateCounter state = M.get(key); if (state != null) state.add(clicks); // if it is, then increment the counter by number of clicks else M.put(key,new StateCounter(key)); // else create a new state for it this.totalClicks = this.totalClicks + clicks; } public int getTotalClicks() { return totalClicks; } /*public void add(BitSet key, double time){ // key is the system state represented as a bitset // Look in the hashmap to see if the represented state is already there StateCounter state = M.get(key); if (state != null) state.add(time); // if it is, then increment the counter by number of clicks else M.put(key,new StateCounter(key)); // else create a new state for it }*/ /** * Writes out the QSD hashmap to a file (item-by-item to save memory) * @param f filename and path */ public void write(String f) { PrintWriter outputWriter = null; try { outputWriter = new PrintWriter(f); } // Catch file opening errors and close files catch (IOException e) { System.out.println("Error opening file: " + e); System.exit(1); } try { Iterator it = M.entrySet().iterator(); while (it.hasNext()){ Map.Entry pairs = (Map.Entry)it.next(); outputWriter.println(pairs.getValue()); } } catch (Exception e) { System.out.println("Error processing file: " + f + " Error: " + e); System.exit(1); } finally { if (outputWriter != null) outputWriter.close(); } System.out.println("Total states in QSD: " + M.size()); } }