package yi.iu.imgdb.learn.absrgn;

import java.util.*;
import yi.iu.imgdb.learn.*;
import yi.util.io.output.*;

/**
 * AbsRgnProbMap contains a list of abstract regions which can be those of one
 * cluster.  Each abstract region has a score (probability) attached with it.
 *
 * For example, in an image, there may be several regions can be classified
 * as "green-regions".  They can be put into this structure with different
 * probabilities.
 */

public class AbsRgnProbMap extends HashMap{
  public double put(AbstractRegion region, double prob) {
    Double old_prob = (Double)super.put(region, new Double(prob));
    if (old_prob == null) return 0;
    else return old_prob.doubleValue();
  }

  public double getProbability(AbstractRegion region) {
    Object rst = this.get(region);
    if (rst == null) return Double.NEGATIVE_INFINITY;
    else return ((Double)rst).doubleValue();
  }

  public double getMaxProbability() {
    double max = Double.NEGATIVE_INFINITY;
    for (Iterator v = values().iterator(); v.hasNext(); ) {
      double p = ((Double)v.next()).doubleValue();
      if (p > max) max = p;
    }
    return max;
  }

  /**
   * Calculate the overlap of the two cluster candidates.  Each region in "this"
   * class will be intersect with any one in the given class.  If a pair of
   * regions are overlapped, then the overlapped region will be added into
   * a new list.  Its probability is simply the product of those two regions
   * @param arcc2
   * @return
   */
  public AbsRgnProbMap intersect(AbsRgnProbMap arcc2) {
    AbsRgnProbMap overlapped = new AbsRgnProbMap();
    for (Iterator i=keySet().iterator(); i.hasNext(); ) {
      AbstractRegion ar1 = (AbstractRegion)i.next();
      double prob1 = getProbability(ar1);
      for (Iterator j=arcc2.keySet().iterator(); j.hasNext(); ) {
        AbstractRegion ar2 = (AbstractRegion)j.next();
        double prob2 = arcc2.getProbability(ar2);
        AbstractRegion ar3 = ar1.intersect(ar2);
        if (ar3 != null && ar3.size() > 0) {
          overlapped.put(ar3, prob1 * prob2);
        }
      }
    }
    return overlapped;
  }

  public void drawRegions(int[] pixels, int width, int height, int color) {
    for (Iterator i=keySet().iterator(); i.hasNext(); ) {
      AbstractRegion ar = (AbstractRegion) i.next();
      ar.drawRegion(pixels, width, height, color);
    }
  }

}