static {
    // variable names refer to RFC 2616, section 2.2
    BitSet ctl = new BitSet(128);
    for (int i = 0; i <= 31; i++) {
      ctl.set(i);
    }
    ctl.set(127);

    BitSet separators = new BitSet(128);
    separators.set('(');
    separators.set(')');
    separators.set('<');
    separators.set('>');
    separators.set('@');
    separators.set(',');
    separators.set(';');
    separators.set(':');
    separators.set('\\');
    separators.set('\"');
    separators.set('/');
    separators.set('[');
    separators.set(']');
    separators.set('?');
    separators.set('=');
    separators.set('{');
    separators.set('}');
    separators.set(' ');
    separators.set('\t');

    TOKEN = new BitSet(128);
    TOKEN.set(0, 128);
    TOKEN.andNot(ctl);
    TOKEN.andNot(separators);

    ALL = MediaType.valueOf(ALL_VALUE);
    APPLICATION_ATOM_XML = MediaType.valueOf(APPLICATION_ATOM_XML_VALUE);
    APPLICATION_RSS_XML = MediaType.valueOf(APPLICATION_RSS_XML_VALUE);
    APPLICATION_FORM_URLENCODED = MediaType.valueOf(APPLICATION_FORM_URLENCODED_VALUE);
    APPLICATION_JSON = MediaType.valueOf(APPLICATION_JSON_VALUE);
    APPLICATION_OCTET_STREAM = MediaType.valueOf(APPLICATION_OCTET_STREAM_VALUE);
    APPLICATION_XHTML_XML = MediaType.valueOf(APPLICATION_XHTML_XML_VALUE);
    APPLICATION_XML = MediaType.valueOf(APPLICATION_XML_VALUE);
    APPLICATION_WILDCARD_XML = MediaType.valueOf(APPLICATION_WILDCARD_XML_VALUE);
    IMAGE_GIF = MediaType.valueOf(IMAGE_GIF_VALUE);
    IMAGE_JPEG = MediaType.valueOf(IMAGE_JPEG_VALUE);
    IMAGE_PNG = MediaType.valueOf(IMAGE_PNG_VALUE);
    MULTIPART_FORM_DATA = MediaType.valueOf(MULTIPART_FORM_DATA_VALUE);
    TEXT_HTML = MediaType.valueOf(TEXT_HTML_VALUE);
    TEXT_PLAIN = MediaType.valueOf(TEXT_PLAIN_VALUE);
    TEXT_XML = MediaType.valueOf(TEXT_XML_VALUE);
  }
  static {
    // variable names refer to RFC 2616, section 2.2
    BitSet ctl = new BitSet(128);
    for (int i = 0; i <= 31; i++) {
      ctl.set(i);
    }
    ctl.set(127);

    BitSet separators = new BitSet(128);
    separators.set('(');
    separators.set(')');
    separators.set('<');
    separators.set('>');
    separators.set('@');
    separators.set(',');
    separators.set(';');
    separators.set(':');
    separators.set('\\');
    separators.set('\"');
    separators.set('/');
    separators.set('[');
    separators.set(']');
    separators.set('?');
    separators.set('=');
    separators.set('{');
    separators.set('}');
    separators.set(' ');
    separators.set('\t');

    TOKEN = new BitSet(128);
    TOKEN.set(0, 128);
    TOKEN.andNot(ctl);
    TOKEN.andNot(separators);

    ALL = new MediaType("*", "*");
    APPLICATION_ATOM_XML = new MediaType("application", "atom+xml");
    APPLICATION_RSS_XML = new MediaType("application", "rss+xml");
    APPLICATION_FORM_URLENCODED = new MediaType("application", "x-www-form-urlencoded");
    APPLICATION_JSON = new MediaType("application", "json");
    APPLICATION_OCTET_STREAM = new MediaType("application", "octet-stream");
    APPLICATION_XHTML_XML = new MediaType("application", "xhtml+xml");
    APPLICATION_XML = new MediaType("application", "xml");
    APPLICATION_WILDCARD_XML = new MediaType("application", "*+xml");
    IMAGE_GIF = new MediaType("image", "gif");
    IMAGE_JPEG = new MediaType("image", "jpeg");
    IMAGE_PNG = new MediaType("image", "png");
    MULTIPART_FORM_DATA = new MediaType("multipart", "form-data");
    TEXT_HTML = new MediaType("text", "html");
    TEXT_PLAIN = new MediaType("text", "plain");
    TEXT_XML = new MediaType("text", "xml");
  }
  /**
   * Converse of addRule. Since we know all the rules ever stored in this flowmap we simply retrieve
   * the rule using the id provided and remove each of its fields from the underlying structures.
   *
   * @param id - the id of the rule to remove
   * @throws FlowEntryNotFound - if this id is unknown. Could indicate that rule has already been
   *     removed.
   * @return
   */
  public void removeRule(int id) throws FlowEntryNotFound {
    ruleCount--;

    if (!rules.containsKey(id)) throw new FlowEntryNotFound(id);

    FlowEntry rule = rules.get(id);

    BitSet flowRuleSet = getFlowRuleSet(rule);

    remove(port, rule.getRuleMatch().getInputPort(), flowRuleSet);
    remove(dpids, rule.dpid, flowRuleSet);
    remove(vlan, (int) rule.getRuleMatch().getDataLayerVirtualLan(), flowRuleSet);
    remove(vlan, rule.getRuleMatch().getDataLayerVirtualLanPriorityCodePoint() << 16, flowRuleSet);
    remove(dl_type, rule.getRuleMatch().getDataLayerType(), flowRuleSet);

    remove(nw, (short) rule.getRuleMatch().getNetworkProtocol(), flowRuleSet);
    remove(nw, (short) (rule.getRuleMatch().getNetworkTypeOfService() << 8), flowRuleSet);

    remove(tp, (int) rule.getRuleMatch().getTransportSource(), flowRuleSet);
    remove(tp, rule.getRuleMatch().getTransportDestination() << 16, flowRuleSet);

    remove(dl_src, FVMatch.toLong(rule.getRuleMatch().getDataLayerSource()), flowRuleSet);
    remove(dl_dst, FVMatch.toLong(rule.getRuleMatch().getDataLayerDestination()), flowRuleSet);

    remove(prioSet, rule.getPriority(), flowRuleSet);

    vlan_ignore.clear(rule.getId());
    rules.remove(rule.getId());
    allRules.andNot(flowRuleSet);
  }
Beispiel #4
0
 void computeIn(LinkedList<Vertex> worklist) {
   int i;
   BitSet old;
   BitSet ne;
   Vertex v;
   ListIterator<Vertex> iter;
   iter = succ.listIterator();
   while (iter.hasNext()) {
     v = iter.next();
     out.or(v.in);
   }
   old = in;
   in = new BitSet();
   in.or(out);
   in.andNot(def);
   in.or(use);
   if (!in.equals(old)) {
     iter = pred.listIterator();
     while (iter.hasNext()) {
       v = iter.next();
       if (!v.listed) {
         worklist.addLast(v);
         v.listed = true;
       }
     }
   }
 }
  /**
   * Prob0 precomputation algorithm. i.e. determine the states of an STPG which, with min/max
   * probability 0, reach a state in {@code target}, while remaining in those in @{code remain}.
   * {@code min}=true gives Prob0E, {@code min}=false gives Prob0A.
   *
   * @param stpg The STPG
   * @param remain Remain in these states (optional: null means "all")
   * @param target Target states
   * @param min1 Min or max probabilities for player 1 (true=lower bound, false=upper bound)
   * @param min2 Min or max probabilities for player 2 (true=min, false=max)
   */
  public BitSet prob0(STPG stpg, BitSet remain, BitSet target, boolean min1, boolean min2) {
    int n, iters;
    BitSet u, soln, unknown;
    boolean u_done;
    long timer;

    // Start precomputation
    timer = System.currentTimeMillis();
    if (verbosity >= 1)
      mainLog.println(
          "Starting Prob0 (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")...");

    // Special case: no target states
    if (target.cardinality() == 0) {
      soln = new BitSet(stpg.getNumStates());
      soln.set(0, stpg.getNumStates());
      return soln;
    }

    // Initialise vectors
    n = stpg.getNumStates();
    u = new BitSet(n);
    soln = new BitSet(n);

    // Determine set of states actually need to perform computation for
    unknown = new BitSet();
    unknown.set(0, n);
    unknown.andNot(target);
    if (remain != null) unknown.and(remain);

    // Fixed point loop
    iters = 0;
    u_done = false;
    // Least fixed point - should start from 0 but we optimise by
    // starting from 'target', thus bypassing first iteration
    u.or(target);
    soln.or(target);
    while (!u_done) {
      iters++;
      // Single step of Prob0
      stpg.prob0step(unknown, u, min1, min2, soln);
      // Check termination
      u_done = soln.equals(u);
      // u = soln
      u.clear();
      u.or(soln);
    }

    // Negate
    u.flip(0, n);

    // Finished precomputation
    timer = System.currentTimeMillis() - timer;
    if (verbosity >= 1) {
      mainLog.print("Prob0 (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")");
      mainLog.println(" took " + iters + " iterations and " + timer / 1000.0 + " seconds.");
    }

    return u;
  }
Beispiel #6
0
 /**
  * checks whether all of the set voxels in voxelSelection are also set in this VoxelSelection
  *
  * @param voxelSelection the voxels to test against. must be the same size as 'this'.
  * @return true if all of the set voxels in voxelSelection are also set in this VoxelSelection
  */
 public boolean containsAllOfThisMask(VoxelSelection voxelSelection) {
   assert (voxelSelection.xSize == this.xSize
       && voxelSelection.ySize == this.ySize
       && voxelSelection.zSize == this.zSize);
   BitSet maskBitsNotInThis = (BitSet) voxelSelection.voxels.clone();
   maskBitsNotInThis.andNot(this.voxels);
   return maskBitsNotInThis.length() == 0;
 }
    void printBodyCoverage(MethodCoverage mc) {
      MethodInfo mi = mc.getMethodInfo();
      Instruction[] code = mi.getInstructions();
      BitSet cov = mc.getExecutedInsn();
      int i, start = -1;

      BitSet handlers = mc.getHandlers();

      if (excludeHandlers) {
        cov.andNot(handlers);
      }

      for (i = 0; i < code.length; i++) {
        if (!cov.get(i)) { // not covered
          if (start == -1) {
            start = i;
          }
        } else { // covered
          if (start != -1) {
            printSourceRange(code, handlers, start, i - 1, "");
            start = -1;
          }
        }
      }
      if (start != -1) {
        printSourceRange(code, handlers, start, i - 1, "");
      }

      // now print the missing branches
      BitSet branches = mc.getBranches();
      lastStart = -1; // reset in case condition and branch are in same line
      for (i = 0; i < code.length; i++) {
        if (branches.get(i)) {
          String prefix = "";
          BitSet bTrue = mc.branchTrue;
          BitSet bFalse = mc.branchFalse;
          if (bTrue != null) { // means we have condition bit sets
            boolean cTrue = bTrue.get(i);
            boolean cFalse = bFalse.get(i);
            if (cTrue) {
              prefix = cFalse ? "" : "F "; // covered or false missing
            } else {
              prefix = cFalse ? "T " : "N "; // true or both missing
            }
          } else {
            prefix = "N "; // not covered at all
          }

          if (prefix != null) {
            printSourceRange(code, handlers, i, i, prefix);
          }
        }
      }
    }
 /**
  * Update the piece availabilities for a given peer
  *
  * @param peerID String
  * @param has BitSet
  */
 public synchronized void peerAvailability(String peerID, BitSet has) {
   this.peerAvailabilies.put(peerID, has);
   BitSet interest = (BitSet) (has.clone());
   interest.andNot(this.isComplete);
   DownloadTask dt = this.task.get(peerID);
   if (dt != null) {
     if (interest.cardinality() > 0 && !dt.peer.isInteresting()) {
       dt.ms.addMessageToQueue(new Message_PP(PeerProtocol.INTERESTED, 2));
       dt.peer.setInteresting(true);
     }
   }
   dt = null;
 }
 @Override
 public final void filter(List<IRow> data, BitSet mask, BitSet mask_filteredOutInfluenceRanking) {
   if (!isFiltered()) return;
   if (!maskInvalid.isEmpty()) {
     BitSet todo = (BitSet) maskInvalid.clone();
     todo.and(mask);
     updateMask(todo, data, this.mask);
     maskInvalid.andNot(todo);
   }
   mask.and(this.mask);
   if (!isRankIndependentFilter) // mark that the masked out are persistent
   mask_filteredOutInfluenceRanking.and(this.mask);
 }
Beispiel #10
0
 /** Change this SprayPattern to be (this & (!p)), showing what this has that p needs. */
 public SprayPattern andNot(SprayPattern p) {
   if (size != p.size) throw new IndexOutOfBoundsException();
   if (is(false)) ; // No change
   else if (is(true)) {
     set(p);
     not();
   } else if (p.is(false)) ; // No change
   else if (p.is(true)) set(false);
   else {
     array.andNot(p.array);
     update();
   }
   return this;
 }
    Coverage getCoveredInsn() {
      int nTotal = mi.getInstructions().length;

      if (excludeHandlers) {
        nTotal -= getHandlers().cardinality();
      }

      if (covered != null) {
        BitSet bExec = getExecutedInsn();
        if (excludeHandlers) {
          bExec.andNot(getHandlers());
        }
        return new Coverage(nTotal, bExec.cardinality());
      } else {
        return new Coverage(nTotal, 0);
      }
    }
    boolean getCoveredLines(BitSet executable, BitSet covered) {
      Instruction inst[] = mi.getInstructions();
      BitSet insn;
      int i, line;

      if (covered == null) {
        return false;
      }

      insn = getExecutedInsn();
      if (excludeHandlers) {
        insn.andNot(getHandlers());
      }

      if (branchTrue != null) {
        for (i = branchTrue.length() - 1; i >= 0; i--) {
          boolean cTrue = branchTrue.get(i);
          boolean cFalse = branchFalse.get(i);

          if ((!cTrue || !cFalse) && (inst[i] instanceof IfInstruction)) {
            insn.clear(i);
          }
        }
      }

      for (i = inst.length - 1; i >= 0; i--) {
        line = inst[i].getLineNumber();

        if (line > 0) {
          executable.set(line);
          covered.set(line);
        }
      }

      for (i = inst.length - 1; i >= 0; i--) {
        line = inst[i].getLineNumber();
        if ((!insn.get(i))
            && (line
                > 0)) { // TODO What do we do with instructions that don't have a line number.  Is
          // this even possible?
          covered.clear(line);
        }
      }

      return true;
    }
  public void rTest(final int N) {
    System.out.println("rtest N=" + N);
    for (int gap = 1; gap <= 65536; gap *= 2) {
      final BitSet bs1 = new BitSet();
      final RoaringBitmap rb1 = new RoaringBitmap();
      for (int x = 0; x <= N; ++x) {
        bs1.set(x);
        rb1.add(x);
      }
      if (bs1.cardinality() != rb1.getCardinality()) throw new RuntimeException("different card");
      if (!equals(bs1, rb1)) throw new RuntimeException("basic  bug");
      for (int offset = 1; offset <= gap; offset *= 2) {
        final BitSet bs2 = new BitSet();
        final RoaringBitmap rb2 = new RoaringBitmap();
        for (int x = 0; x <= N; ++x) {
          bs2.set(x + offset);
          rb2.add(x + offset);
        }
        if (bs2.cardinality() != rb2.getCardinality()) throw new RuntimeException("different card");
        if (!equals(bs2, rb2)) throw new RuntimeException("basic  bug");

        BitSet clonebs1;
        // testing AND
        clonebs1 = (BitSet) bs1.clone();
        clonebs1.and(bs2);
        if (!equals(clonebs1, RoaringBitmap.and(rb1, rb2))) throw new RuntimeException("bug and");
        {
          final RoaringBitmap t = rb1.clone();
          t.and(rb2);
          if (!equals(clonebs1, t)) throw new RuntimeException("bug inplace and");
          if (!t.equals(RoaringBitmap.and(rb1, rb2))) {
            System.out.println(
                t.highlowcontainer.getContainerAtIndex(0).getClass().getCanonicalName());
            System.out.println(
                RoaringBitmap.and(rb1, rb2)
                    .highlowcontainer
                    .getContainerAtIndex(0)
                    .getClass()
                    .getCanonicalName());

            throw new RuntimeException("bug inplace and");
          }
        }

        // testing OR
        clonebs1 = (BitSet) bs1.clone();
        clonebs1.or(bs2);

        if (!equals(clonebs1, RoaringBitmap.or(rb1, rb2))) throw new RuntimeException("bug or");
        {
          final RoaringBitmap t = rb1.clone();
          t.or(rb2);
          if (!equals(clonebs1, t)) throw new RuntimeException("bug or");
          if (!t.equals(RoaringBitmap.or(rb1, rb2))) throw new RuntimeException("bug or");
          if (!t.toString().equals(RoaringBitmap.or(rb1, rb2).toString()))
            throw new RuntimeException("bug or");
        }
        // testing XOR
        clonebs1 = (BitSet) bs1.clone();
        clonebs1.xor(bs2);
        if (!equals(clonebs1, RoaringBitmap.xor(rb1, rb2))) {
          throw new RuntimeException("bug xor");
        }
        {
          final RoaringBitmap t = rb1.clone();
          t.xor(rb2);
          if (!equals(clonebs1, t)) throw new RuntimeException("bug xor");
          if (!t.equals(RoaringBitmap.xor(rb1, rb2))) throw new RuntimeException("bug xor");
        }
        // testing NOTAND
        clonebs1 = (BitSet) bs1.clone();
        clonebs1.andNot(bs2);
        if (!equals(clonebs1, RoaringBitmap.andNot(rb1, rb2))) {
          throw new RuntimeException("bug andnot");
        }
        clonebs1 = (BitSet) bs2.clone();
        clonebs1.andNot(bs1);
        if (!equals(clonebs1, RoaringBitmap.andNot(rb2, rb1))) {
          throw new RuntimeException("bug andnot");
        }
        {
          final RoaringBitmap t = rb2.clone();
          t.andNot(rb1);
          if (!equals(clonebs1, t)) {
            throw new RuntimeException("bug inplace andnot");
          }
          final RoaringBitmap g = RoaringBitmap.andNot(rb2, rb1);
          if (!equals(clonebs1, g)) {
            throw new RuntimeException("bug andnot");
          }
          if (!t.equals(g)) throw new RuntimeException("bug");
        }
        clonebs1 = (BitSet) bs1.clone();
        clonebs1.andNot(bs2);
        if (!equals(clonebs1, RoaringBitmap.andNot(rb1, rb2))) {
          throw new RuntimeException("bug andnot");
        }
        {
          final RoaringBitmap t = rb1.clone();
          t.andNot(rb2);
          if (!equals(clonebs1, t)) {
            throw new RuntimeException("bug andnot");
          }
          final RoaringBitmap g = RoaringBitmap.andNot(rb1, rb2);
          if (!equals(clonebs1, g)) {
            throw new RuntimeException("bug andnot");
          }
          if (!t.equals(g)) throw new RuntimeException("bug");
        }
      }
    }
  }
Beispiel #14
0
  private BlockNode processSwitch(
      IRegion currentRegion, BlockNode block, SwitchNode insn, RegionStack stack) {
    SwitchRegion sw = new SwitchRegion(currentRegion, block);
    currentRegion.getSubBlocks().add(sw);

    int len = insn.getTargets().length;
    // sort by target
    Map<Integer, List<Object>> casesMap = new LinkedHashMap<Integer, List<Object>>(len);
    for (int i = 0; i < len; i++) {
      Object key = insn.getKeys()[i];
      int targ = insn.getTargets()[i];
      List<Object> keys = casesMap.get(targ);
      if (keys == null) {
        keys = new ArrayList<Object>(2);
        casesMap.put(targ, keys);
      }
      keys.add(key);
    }

    Map<BlockNode, List<Object>> blocksMap = new LinkedHashMap<BlockNode, List<Object>>(len);
    for (Map.Entry<Integer, List<Object>> entry : casesMap.entrySet()) {
      BlockNode c = getBlockByOffset(entry.getKey(), block.getSuccessors());
      assert c != null;
      blocksMap.put(c, entry.getValue());
    }
    BlockNode defCase = getBlockByOffset(insn.getDefaultCaseOffset(), block.getSuccessors());
    if (defCase != null) {
      blocksMap.remove(defCase);
    }
    LoopInfo loop = mth.getLoopForBlock(block);

    Map<BlockNode, BlockNode> fallThroughCases = new LinkedHashMap<BlockNode, BlockNode>();

    List<BlockNode> basicBlocks = mth.getBasicBlocks();
    BitSet outs = new BitSet(basicBlocks.size());
    outs.or(block.getDomFrontier());
    for (BlockNode s : block.getCleanSuccessors()) {
      BitSet df = s.getDomFrontier();
      // fall through case block
      if (df.cardinality() > 1) {
        if (df.cardinality() > 2) {
          LOG.debug("Unexpected case pattern, block: {}, mth: {}", s, mth);
        } else {
          BlockNode first = basicBlocks.get(df.nextSetBit(0));
          BlockNode second = basicBlocks.get(df.nextSetBit(first.getId() + 1));
          if (second.getDomFrontier().get(first.getId())) {
            fallThroughCases.put(s, second);
            df = new BitSet(df.size());
            df.set(first.getId());
          } else if (first.getDomFrontier().get(second.getId())) {
            fallThroughCases.put(s, first);
            df = new BitSet(df.size());
            df.set(second.getId());
          }
        }
      }
      outs.or(df);
    }
    outs.clear(block.getId());
    if (loop != null) {
      outs.clear(loop.getStart().getId());
    }

    stack.push(sw);
    stack.addExits(BlockUtils.bitSetToBlocks(mth, outs));

    // check cases order if fall through case exists
    if (!fallThroughCases.isEmpty()) {
      if (isBadCasesOrder(blocksMap, fallThroughCases)) {
        LOG.debug("Fixing incorrect switch cases order, method: {}", mth);
        blocksMap = reOrderSwitchCases(blocksMap, fallThroughCases);
        if (isBadCasesOrder(blocksMap, fallThroughCases)) {
          LOG.error("Can't fix incorrect switch cases order, method: {}", mth);
          mth.add(AFlag.INCONSISTENT_CODE);
        }
      }
    }

    // filter 'out' block
    if (outs.cardinality() > 1) {
      // remove exception handlers
      BlockUtils.cleanBitSet(mth, outs);
    }
    if (outs.cardinality() > 1) {
      // filter loop start and successors of other blocks
      for (int i = outs.nextSetBit(0); i >= 0; i = outs.nextSetBit(i + 1)) {
        BlockNode b = basicBlocks.get(i);
        outs.andNot(b.getDomFrontier());
        if (b.contains(AFlag.LOOP_START)) {
          outs.clear(b.getId());
        } else {
          for (BlockNode s : b.getCleanSuccessors()) {
            outs.clear(s.getId());
          }
        }
      }
    }

    if (loop != null && outs.cardinality() > 1) {
      outs.clear(loop.getEnd().getId());
    }
    if (outs.cardinality() == 0) {
      // one or several case blocks are empty,
      // run expensive algorithm for find 'out' block
      for (BlockNode maybeOut : block.getSuccessors()) {
        boolean allReached = true;
        for (BlockNode s : block.getSuccessors()) {
          if (!isPathExists(s, maybeOut)) {
            allReached = false;
            break;
          }
        }
        if (allReached) {
          outs.set(maybeOut.getId());
          break;
        }
      }
    }
    BlockNode out = null;
    if (outs.cardinality() == 1) {
      out = basicBlocks.get(outs.nextSetBit(0));
      stack.addExit(out);
    } else if (loop == null && outs.cardinality() > 1) {
      LOG.warn("Can't detect out node for switch block: {} in {}", block, mth);
    }
    if (loop != null) {
      // check if 'continue' must be inserted
      BlockNode end = loop.getEnd();
      if (out != end && out != null) {
        insertContinueInSwitch(block, out, end);
      }
    }

    if (!stack.containsExit(defCase)) {
      sw.setDefaultCase(makeRegion(defCase, stack));
    }
    for (Entry<BlockNode, List<Object>> entry : blocksMap.entrySet()) {
      BlockNode caseBlock = entry.getKey();
      if (stack.containsExit(caseBlock)) {
        // empty case block
        sw.addCase(entry.getValue(), new Region(stack.peekRegion()));
      } else {
        BlockNode next = fallThroughCases.get(caseBlock);
        stack.addExit(next);
        Region caseRegion = makeRegion(caseBlock, stack);
        stack.removeExit(next);
        if (next != null) {
          next.add(AFlag.FALL_THROUGH);
          caseRegion.add(AFlag.FALL_THROUGH);
        }
        sw.addCase(entry.getValue(), caseRegion);
        // 'break' instruction will be inserted in RegionMakerVisitor.PostRegionVisitor
      }
    }

    stack.pop();
    return out;
  }
Beispiel #15
0
 /* (non-Javadoc)
  * @see java.util.BitSet#andNot(java.util.BitSet)
  */
 public void andNot(java.util.BitSet set) {
   super.andNot(set);
   makeDirty();
 }
 /**
  * Remove a given bitset from the a given data structure.
  *
  * @param map - the data structure to remove from.
  * @param key - the key for the said data structure.
  * @param value - the bitset to remove.
  * @return the remaining bitset at map.get(key)
  */
 private <K> BitSet remove(Map<K, BitSet> map, K key, BitSet value) {
   BitSet set = map.get(key);
   if (set == null) return null;
   set.andNot(value);
   return map.put(key, set);
 }
  /**
   * match is called when a switch sends a packet in to the controller. The goal is to find all flow
   * space rules which match the fields of the packet in.
   *
   * @param dpid - the datapath id of the switch which sent the packet in.
   * @param match - the packet in information
   * @return a list, sorted by priority, of flow space rules which match.
   */
  public List<FlowEntry> match(long dpid, FVMatch match) {
    BitSet set = new BitSet();
    LinkedList<FlowEntry> flowrules = new LinkedList<FlowEntry>();
    int wildcards = match.getWildcards();
    FVLog.log(LogLevel.DEBUG, null, "dpid: ", dpid, "match: ", match.toString());

    set.or(allRules);
    FVLog.log(LogLevel.DEBUG, null, "allRules: ", set.toString());

    try {

      testEmpty(set, dpids, dpid, FlowEntry.ALL_DPIDS, wildcards, 0);
      /*
       * Test every field and intersect the resulting bitset. If the bit
       * set is empty an exception is thrown to stop the search.
       */
      testEmpty(set, port, match.getInputPort(), ANY_IN_PORT, wildcards, FVMatch.OFPFW_IN_PORT);
      if (match.getDataLayerVirtualLan() != ANY_VLAN_ID) {
        testEmpty(
            set,
            vlan,
            (int) match.getDataLayerVirtualLan(),
            (int) ANY_VLAN_ID,
            wildcards,
            FVMatch.OFPFW_DL_VLAN);
        testEmpty(
            set,
            vlan,
            match.getDataLayerVirtualLanPriorityCodePoint() << 16,
            ANY_VLAN_PCP << 16,
            wildcards,
            FVMatch.OFPFW_DL_VLAN_PCP);
      } else {

        set.andNot(vlan_ignore);
      }

      testEmpty(
          set, dl_type, match.getDataLayerType(), ANY_ETHER, wildcards, FVMatch.OFPFW_DL_TYPE);

      testEmpty(
          set,
          nw,
          (short) match.getNetworkProtocol(),
          (short) ANY_NW_PROTO_TOS,
          wildcards,
          FVMatch.OFPFW_NW_PROTO);

      testEmpty(
          set,
          nw,
          (short) (match.getNetworkTypeOfService() << 8),
          (short) (ANY_NW_PROTO_TOS << 8),
          wildcards,
          FVMatch.OFPFW_NW_TOS);

      testEmpty(
          set, tp, (int) match.getTransportSource(), (int) ANY_TP, wildcards, FVMatch.OFPFW_TP_SRC);

      testEmpty(
          set,
          tp,
          match.getTransportDestination() << 16,
          ANY_TP << 16,
          wildcards,
          FVMatch.OFPFW_TP_DST);

      testEmpty(
          set,
          dl_src,
          FVMatch.toLong(match.getDataLayerSource()),
          ANY_MAC,
          wildcards,
          FVMatch.OFPFW_DL_SRC);

      testEmpty(
          set,
          dl_dst,
          FVMatch.toLong(match.getDataLayerDestination()),
          ANY_MAC,
          wildcards,
          FVMatch.OFPFW_DL_DST);

      for (int i = set.nextSetBit(0); i >= 0; i = set.nextSetBit(i + 1)) {
        FlowEntry fe = rules.get(i);
        FVMatch ruleMatch = fe.getRuleMatch();
        FlowIntersect inter;
        inter = new FlowIntersect(fe.clone());

        FVMatch interMatch = inter.getMatch();
        interMatch.setNetworkDestination(
            testIP(
                inter,
                FVMatch.OFPFW_NW_DST_SHIFT,
                match.getNetworkDestinationMaskLen(),
                ruleMatch.getNetworkDestinationMaskLen(),
                match.getNetworkDestination(),
                ruleMatch.getNetworkDestination()));
        if (inter.getMatchType() == MatchType.NONE) {
          set.clear(i);
          continue;
        }

        // test ip_src
        interMatch.setNetworkSource(
            testIP(
                inter,
                FVMatch.OFPFW_NW_SRC_SHIFT,
                match.getNetworkSourceMaskLen(),
                ruleMatch.getNetworkSourceMaskLen(),
                match.getNetworkSource(),
                ruleMatch.getNetworkSource()));
        if (inter.getMatchType() == MatchType.NONE) {
          set.clear(i);
          continue;
        }
      }

    } catch (NoMatch e) {
      FVLog.log(LogLevel.INFO, null, "No match for: ", match);
      return flowrules;
    }

    /*
     * If we got here we have a match. Now return a prioritized list of
     * matches.
     *
     * Higher numbers have higher priorities.
     */

    TreeSet<FlowEntry> entries = new TreeSet<FlowEntry>();
    for (int i = set.nextSetBit(0); i >= 0; i = set.nextSetBit(i + 1)) {
      entries.add(rules.get(i));
    }
    flowrules.addAll(entries);
    return flowrules;
  }
  /**
   * Compute expected reachability rewards using value iteration.
   *
   * @param stpg The STPG
   * @param rewards The rewards
   * @param target Target states
   * @param inf States for which reward is infinite
   * @param min1 Min or max rewards for player 1 (true=min, false=max)
   * @param min2 Min or max rewards for player 2 (true=min, false=max)
   * @param init Optionally, an initial solution vector (will be overwritten)
   * @param known Optionally, a set of states for which the exact answer is known Note: if 'known'
   *     is specified (i.e. is non-null, 'init' must also be given and is used for the exact values.
   */
  protected ModelCheckerResult computeReachRewardsValIter(
      STPG stpg,
      STPGRewards rewards,
      BitSet target,
      BitSet inf,
      boolean min1,
      boolean min2,
      double init[],
      BitSet known)
      throws PrismException {
    ModelCheckerResult res;
    BitSet unknown;
    int i, n, iters;
    double soln[], soln2[], tmpsoln[];
    boolean done;
    long timer;

    // Start value iteration
    timer = System.currentTimeMillis();
    if (verbosity >= 1)
      mainLog.println(
          "Starting value iteration (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")...");

    // Store num states
    n = stpg.getNumStates();

    // Create solution vector(s)
    soln = new double[n];
    soln2 = (init == null) ? new double[n] : init;

    // Initialise solution vectors. Use (where available) the following in order of preference:
    // (1) exact answer, if already known; (2) 0.0/infinity if in target/inf; (3) passed in initial
    // value; (4) 0.0
    if (init != null) {
      if (known != null) {
        for (i = 0; i < n; i++)
          soln[i] =
              soln2[i] =
                  known.get(i)
                      ? init[i]
                      : target.get(i) ? 0.0 : inf.get(i) ? Double.POSITIVE_INFINITY : init[i];
      } else {
        for (i = 0; i < n; i++)
          soln[i] =
              soln2[i] = target.get(i) ? 0.0 : inf.get(i) ? Double.POSITIVE_INFINITY : init[i];
      }
    } else {
      for (i = 0; i < n; i++)
        soln[i] = soln2[i] = target.get(i) ? 0.0 : inf.get(i) ? Double.POSITIVE_INFINITY : 0.0;
    }

    // Determine set of states actually need to compute values for
    unknown = new BitSet();
    unknown.set(0, n);
    unknown.andNot(target);
    unknown.andNot(inf);
    if (known != null) unknown.andNot(known);

    // Start iterations
    iters = 0;
    done = false;
    while (!done && iters < maxIters) {
      // mainLog.println(soln);
      iters++;
      // Matrix-vector multiply and min/max ops
      stpg.mvMultRewMinMax(soln, rewards, min1, min2, soln2, unknown, false, null);
      // Check termination
      done = PrismUtils.doublesAreClose(soln, soln2, termCritParam, termCrit == TermCrit.ABSOLUTE);
      // Swap vectors for next iter
      tmpsoln = soln;
      soln = soln2;
      soln2 = tmpsoln;
    }

    // Finished value iteration
    timer = System.currentTimeMillis() - timer;
    if (verbosity >= 1) {
      mainLog.print("Value iteration (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")");
      mainLog.println(" took " + iters + " iterations and " + timer / 1000.0 + " seconds.");
    }

    // Non-convergence is an error (usually)
    if (!done && errorOnNonConverge) {
      String msg = "Iterative method did not converge within " + iters + " iterations.";
      msg +=
          "\nConsider using a different numerical method or increasing the maximum number of iterations";
      throw new PrismException(msg);
    }

    // Return results
    res = new ModelCheckerResult();
    res.soln = soln;
    res.numIters = iters;
    res.timeTaken = timer / 1000.0;
    return res;
  }
Beispiel #19
0
  /** Force the failure, apply decisions to the last solution + cut => failure! */
  private void explainCut() {
    // Goal: force the failure to get the set of decisions related to the cut
    forceCft = false;
    // 1. make a backup
    mSolver.getEnvironment().worldPush();
    Decision d;
    try {

      Decision previous = mSolver.getSearchLoop().getLastDecision();
      assert previous == RootDecision.ROOT;
      // 2. apply the decisions
      mExplanationEngine.getSolver().getObjectiveManager().postDynamicCut();
      for (int i = 0; i < path.size(); i++) {
        d = path.get(i);
        d.setPrevious(previous);
        d.buildNext();
        if (refuted.get(i)) d.buildNext();
        d.apply();
        mSolver.propagate();
        previous = d;
      }
      // mSolver.propagate();
      assert false : "SHOULD FAIL!";
    } catch (ContradictionException cex) {
      if ((cex.v != null) || (cex.c != null)) { // contradiction on domain wipe out
        tmpDeductions.clear();
        tmpValueDeductions.clear();
        related2cut.clear();
        unrelated.clear();

        // 3. explain the failure
        Explanation expl = new Explanation();
        if (cex.v != null) {
          cex.v.explain(mExplanationEngine, VariableState.DOM, expl);
        } else {
          cex.c.explain(mExplanationEngine, null, expl);
        }
        Explanation complete = mExplanationEngine.flatten(expl);
        ExplanationToolbox.extractDecision(complete, tmpValueDeductions);
        tmpDeductions.addAll(tmpValueDeductions);

        if (tmpDeductions.isEmpty()) {
          //                    if (LOGGER.isErrorEnabled()) {
          //                        LOGGER.error("2 cases: (a) optimality proven or (b) bug in
          // explanation");
          //                    }
          //                    throw new SolverException("2 cases: (a) optimality proven or (b) bug
          // in explanation");
          isTerminated = true;
        }

        for (int i = 0; i < tmpDeductions.size(); i++) {
          int idx = path.indexOf(((BranchingDecision) tmpDeductions.get(i)).getDecision());
          related2cut.set(idx);
        }

        // 4. need to replace the duplicated decision with the correct one
        for (int i = 0; i < path.size(); i++) {
          Decision dec = path.get(i);
          boolean forceNext = !dec.hasNext();
          dec.rewind();
          if (forceNext) dec.buildNext();
          dec.setPrevious(null); // useless .. but ... you know
        }

      } else {
        throw new UnsupportedOperationException(
            this.getClass().getName() + ".onContradiction incoherent state");
      }
    }
    mSolver.getEnvironment().worldPop();
    mSolver.getEngine().flush();
    unrelated.andNot(related2cut);
    unrelated.andNot(refuted);
  }
  /**
   * Compute reachability probabilities using Gauss-Seidel.
   *
   * @param stpg The STPG
   * @param no Probability 0 states
   * @param yes Probability 1 states
   * @param min1 Min or max probabilities for player 1 (true=lower bound, false=upper bound)
   * @param min2 Min or max probabilities for player 2 (true=min, false=max)
   * @param init Optionally, an initial solution vector (will be overwritten)
   * @param known Optionally, a set of states for which the exact answer is known Note: if 'known'
   *     is specified (i.e. is non-null, 'init' must also be given and is used for the exact values.
   */
  protected ModelCheckerResult computeReachProbsGaussSeidel(
      STPG stpg, BitSet no, BitSet yes, boolean min1, boolean min2, double init[], BitSet known)
      throws PrismException {
    ModelCheckerResult res;
    BitSet unknown;
    int i, n, iters;
    double soln[], initVal, maxDiff;
    boolean done;
    long timer;

    // Start value iteration
    timer = System.currentTimeMillis();
    if (verbosity >= 1)
      mainLog.println(
          "Starting value iteration (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")...");

    // Store num states
    n = stpg.getNumStates();

    // Create solution vector
    soln = (init == null) ? new double[n] : init;

    // Initialise solution vector. Use (where available) the following in order of preference:
    // (1) exact answer, if already known; (2) 1.0/0.0 if in yes/no; (3) passed in initial value;
    // (4) initVal
    // where initVal is 0.0 or 1.0, depending on whether we converge from below/above.
    initVal = (valIterDir == ValIterDir.BELOW) ? 0.0 : 1.0;
    if (init != null) {
      if (known != null) {
        for (i = 0; i < n; i++)
          soln[i] = known.get(i) ? init[i] : yes.get(i) ? 1.0 : no.get(i) ? 0.0 : init[i];
      } else {
        for (i = 0; i < n; i++) soln[i] = yes.get(i) ? 1.0 : no.get(i) ? 0.0 : init[i];
      }
    } else {
      for (i = 0; i < n; i++) soln[i] = yes.get(i) ? 1.0 : no.get(i) ? 0.0 : initVal;
    }

    // Determine set of states actually need to compute values for
    unknown = new BitSet();
    unknown.set(0, n);
    unknown.andNot(yes);
    unknown.andNot(no);
    if (known != null) unknown.andNot(known);

    // Start iterations
    iters = 0;
    done = false;
    while (!done && iters < maxIters) {
      iters++;
      // Matrix-vector multiply and min/max ops
      maxDiff =
          stpg.mvMultGSMinMax(soln, min1, min2, unknown, false, termCrit == TermCrit.ABSOLUTE);
      // Check termination
      done = maxDiff < termCritParam;
    }

    // Finished Gauss-Seidel
    timer = System.currentTimeMillis() - timer;
    if (verbosity >= 1) {
      mainLog.print("Value iteration (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")");
      mainLog.println(" took " + iters + " iterations and " + timer / 1000.0 + " seconds.");
    }

    // Non-convergence is an error (usually)
    if (!done && errorOnNonConverge) {
      String msg = "Iterative method did not converge within " + iters + " iterations.";
      msg +=
          "\nConsider using a different numerical method or increasing the maximum number of iterations";
      throw new PrismException(msg);
    }

    // Return results
    res = new ModelCheckerResult();
    res.soln = soln;
    res.numIters = iters;
    res.timeTaken = timer / 1000.0;
    return res;
  }
  /**
   * Compute reachability probabilities using value iteration.
   *
   * @param stpg The STPG
   * @param no Probability 0 states
   * @param yes Probability 1 states
   * @param min1 Min or max probabilities for player 1 (true=lower bound, false=upper bound)
   * @param min2 Min or max probabilities for player 2 (true=min, false=max)
   * @param init Optionally, an initial solution vector (will be overwritten)
   * @param known Optionally, a set of states for which the exact answer is known Note: if 'known'
   *     is specified (i.e. is non-null, 'init' must also be given and is used for the exact values.
   */
  protected ModelCheckerResult computeReachProbsValIter(
      STPG stpg, BitSet no, BitSet yes, boolean min1, boolean min2, double init[], BitSet known)
      throws PrismException {
    ModelCheckerResult res = null;
    BitSet unknown;
    int i, n, iters;
    double soln[], soln2[], tmpsoln[], initVal;
    int adv[] = null;
    boolean genAdv, done;
    long timer;

    // Are we generating an optimal adversary?
    genAdv = exportAdv;

    // Start value iteration
    timer = System.currentTimeMillis();
    if (verbosity >= 1)
      mainLog.println(
          "Starting value iteration (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")...");

    // Store num states
    n = stpg.getNumStates();

    // Create solution vector(s)
    soln = new double[n];
    soln2 = (init == null) ? new double[n] : init;

    // Initialise solution vectors. Use (where available) the following in order of preference:
    // (1) exact answer, if already known; (2) 1.0/0.0 if in yes/no; (3) passed in initial value;
    // (4) initVal
    // where initVal is 0.0 or 1.0, depending on whether we converge from below/above.
    initVal = (valIterDir == ValIterDir.BELOW) ? 0.0 : 1.0;
    if (init != null) {
      if (known != null) {
        for (i = 0; i < n; i++)
          soln[i] =
              soln2[i] = known.get(i) ? init[i] : yes.get(i) ? 1.0 : no.get(i) ? 0.0 : init[i];
      } else {
        for (i = 0; i < n; i++) soln[i] = soln2[i] = yes.get(i) ? 1.0 : no.get(i) ? 0.0 : init[i];
      }
    } else {
      for (i = 0; i < n; i++) soln[i] = soln2[i] = yes.get(i) ? 1.0 : no.get(i) ? 0.0 : initVal;
    }

    // Determine set of states actually need to compute values for
    unknown = new BitSet();
    unknown.set(0, n);
    unknown.andNot(yes);
    unknown.andNot(no);
    if (known != null) unknown.andNot(known);

    // Create/initialise adversary storage
    if (genAdv) {
      adv = new int[n];
      for (i = 0; i < n; i++) {
        adv[i] = -1;
      }
    }

    // Start iterations
    iters = 0;
    done = false;
    while (!done && iters < maxIters) {
      iters++;
      // Matrix-vector multiply and min/max ops
      stpg.mvMultMinMax(soln, min1, min2, soln2, unknown, false, genAdv ? adv : null);
      // Check termination
      done = PrismUtils.doublesAreClose(soln, soln2, termCritParam, termCrit == TermCrit.ABSOLUTE);
      // Swap vectors for next iter
      tmpsoln = soln;
      soln = soln2;
      soln2 = tmpsoln;
    }

    // Finished value iteration
    timer = System.currentTimeMillis() - timer;
    if (verbosity >= 1) {
      mainLog.print("Value iteration (" + (min1 ? "min" : "max") + (min2 ? "min" : "max") + ")");
      mainLog.println(" took " + iters + " iterations and " + timer / 1000.0 + " seconds.");
    }

    // Non-convergence is an error (usually)
    if (!done && errorOnNonConverge) {
      String msg = "Iterative method did not converge within " + iters + " iterations.";
      msg +=
          "\nConsider using a different numerical method or increasing the maximum number of iterations";
      throw new PrismException(msg);
    }

    // Print adversary
    if (genAdv) {
      PrismLog out = new PrismFileLog(exportAdvFilename);
      for (i = 0; i < n; i++) {
        out.println(i + " " + (adv[i] != -1 ? stpg.getAction(i, adv[i]) : "-"));
      }
      out.println();
    }

    // Return results
    res = new ModelCheckerResult();
    res.soln = soln;
    res.numIters = iters;
    res.timeTaken = timer / 1000.0;
    return res;
  }