|
| 1 | +package simulator; |
| 2 | + |
| 3 | + |
| 4 | +import common.iterable.Range; |
| 5 | +import parser.State; |
| 6 | +import parser.ast.LabelList; |
| 7 | +import prism.PrismException; |
| 8 | +import prism.PrismLangException; |
| 9 | + |
| 10 | +import java.util.BitSet; |
| 11 | +import java.util.HashMap; |
| 12 | +import java.util.List; |
| 13 | +import java.util.Map; |
| 14 | + |
| 15 | +public class LabelsCache |
| 16 | +{ |
| 17 | + // cache internal order of states |
| 18 | + Map<State, Integer> stateIndices = new HashMap<>(); |
| 19 | + Map<String, BitSet> labelValues = new HashMap<>(); |
| 20 | + LabelList labelList; |
| 21 | + |
| 22 | + LabelsCache(LabelList ll) |
| 23 | + { |
| 24 | + this.labelList = ll; |
| 25 | + for (String label : ll.getLabelNames()) { |
| 26 | + labelValues.put(label, new BitSet()); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + public boolean getLabelValue(State state, String label) |
| 31 | + { |
| 32 | + return labelValues.get(label).get(stateIndices.get(state)); |
| 33 | + } |
| 34 | + |
| 35 | + public Map<String, Boolean> getLabelValues(State state) throws PrismLangException |
| 36 | + { |
| 37 | + int index; |
| 38 | + Map<String, Boolean> stateLabelValues; |
| 39 | + |
| 40 | + if (stateIndices.containsKey(state)) { |
| 41 | + index = stateIndices.get(state); |
| 42 | + stateLabelValues = new HashMap<>(); |
| 43 | + labelValues.forEach((name, bitset) -> stateLabelValues.put(name, bitset.get(index))); |
| 44 | + } else { |
| 45 | + index = addState(state); |
| 46 | + stateLabelValues = labelList.getLabelValues(state); |
| 47 | + labelValues.forEach((name, bitset) -> bitset.set(index, stateLabelValues.get(name))); |
| 48 | + } |
| 49 | + return stateLabelValues; |
| 50 | + } |
| 51 | + |
| 52 | + private int addState(State state) |
| 53 | + { |
| 54 | + int nextIndex = stateIndices.size(); |
| 55 | + stateIndices.put(state, nextIndex); |
| 56 | + return nextIndex; |
| 57 | + } |
| 58 | + |
| 59 | + public BitSet getLabel(String name, List<State> statesList) throws PrismException |
| 60 | + { |
| 61 | + // check if all states have been evaluated |
| 62 | + for (State state : statesList) { |
| 63 | + if (!stateIndices.containsKey(state)) { |
| 64 | + throw new PrismException("Labels not evaluated for state: " + state); |
| 65 | + } |
| 66 | + } |
| 67 | + // assuming statesList has efficient indexed access, e.g., ArrayList |
| 68 | + BitSet values = labelValues.get(name); |
| 69 | + |
| 70 | + Range indices = new Range(statesList.size()).reversed(); // iterate in revese order to avoid multiple resizing of BitSet |
| 71 | + return indices.filter((int i) -> values.get(stateIndices.get(statesList.get(i)))).collect(new BitSet()); |
| 72 | + } |
| 73 | +} |
0 commit comments