00001 package edu.tum.cs.bayesnets.util; 00002 00003 import java.util.HashMap; 00004 import java.util.NoSuchElementException; 00005 import java.util.Random; 00006 import java.util.Vector; 00007 00008 import edu.ksu.cis.bnj.ver3.core.BeliefNode; 00009 00010 public class TopologicalOrdering implements Iterable<Integer> { 00014 Vector<Vector<Integer>> partialOrder; 00018 HashMap<BeliefNode, Integer> tierMap; 00019 00020 public TopologicalOrdering(Vector<Vector<Integer>> partialOrder, HashMap<BeliefNode, Integer> tierMap) { 00021 this.partialOrder = partialOrder; 00022 this.tierMap = tierMap; 00023 } 00024 00025 public java.util.Iterator<Integer> iterator() { 00026 return new Iterator(this); 00027 } 00028 00029 public static class Iterator implements java.util.Iterator<Integer> { 00030 00031 int idxCurrentLevel; 00032 Vector<Integer> currentLevel; 00033 Random random; 00034 TopologicalOrdering ordering; 00035 00036 public Iterator(TopologicalOrdering ordering) { 00037 this.ordering = ordering; 00038 idxCurrentLevel = 0; 00039 currentLevel = new Vector<Integer>(ordering.partialOrder.get(0)); 00040 random = new Random(); 00041 } 00042 00043 public boolean hasNext() { 00044 return currentLevel != null && !currentLevel.isEmpty(); 00045 } 00046 00047 public Integer next() { 00048 if(!hasNext()) 00049 throw new NoSuchElementException(); 00050 int idxNext = random.nextInt(currentLevel.size()); 00051 int nextElem = currentLevel.remove(idxNext); 00052 if(currentLevel.isEmpty()) { 00053 ++idxCurrentLevel; 00054 if(idxCurrentLevel < ordering.partialOrder.size()) 00055 currentLevel = new Vector<Integer>(ordering.partialOrder.get(idxCurrentLevel)); 00056 else 00057 currentLevel = null; 00058 } 00059 return nextElem; 00060 } 00061 00062 public void remove() { 00063 throw new RuntimeException("remove() is not supported by this constant iterator."); 00064 } 00065 00066 } 00067 00073 public int getTier(BeliefNode n) { 00074 if(tierMap == null) 00075 throw new RuntimeException("Topological ordering has no tier map!"); 00076 return tierMap.get(n); 00077 } 00078 00079 public int getNumTiers() { 00080 return partialOrder.size(); 00081 } 00082 00088 public Vector<Integer> getTier(int index) { 00089 return partialOrder.get(index); 00090 } 00091 00092 public Vector<Vector<Integer>> getTiers() { 00093 return partialOrder; 00094 } 00095 }