package yi.ds;

import java.util.*;
import yi.ds.DoubleArrayCumulator;
import yi.ds.hash.DoubleScoreHashMap;

/**
 * AccumulatorHashMap handles a hashmap with its value is a
 * DoubleArrayCumulator.  It can be used to accumulate double typed vectors.
 */
public class AccumulatorHashMap extends HashMap {
  public void accumulate(Object key, double[] value) {
    DoubleArrayCumulator accumulator = (DoubleArrayCumulator)get(key);
    if (accumulator == null) {  // if there is no corresponding accumulator yet
      accumulator = new DoubleArrayCumulator();
    }
    accumulator.add(value);
    put(key, accumulator);
  }

  public void accumulate(DoubleScoreHashMap scores) {
    for (Iterator i = scores.keySet().iterator(); i.hasNext(); ) {
      Object key = i.next();
      DoubleArrayCumulator accumulator = (DoubleArrayCumulator) get(key);
      if (accumulator == null) { // if there is no corresponding accumulator yet
        accumulator = new DoubleArrayCumulator();
      }
      accumulator.add(new double[]{scores.getScore(key)});
      put(key, accumulator);
    }
  }

  public int getCount(Object key) {
    DoubleArrayCumulator accumulator = (DoubleArrayCumulator)get(key);
    if (accumulator == null) {  // if there is no corresponding accumulator yet
      return 0;
    }
    return accumulator.getCount();
  }

  /**
   * Calculate the means of the accumulators
   * @param accumulators
   * @return A HashMap contains means indexed by the corresponding key.
   */
  public HashMap getMeans() {
    HashMap means = new HashMap();
    Iterator iter = keySet().iterator();
    while (iter.hasNext()) {
      String key = (String) iter.next();
      DoubleArrayCumulator accumulator = (DoubleArrayCumulator) get(key);
      means.put(key, accumulator.getMeans());
    }

    return means;
  }


}
