Example usage for java.util BitSet nextSetBit

List of usage examples for java.util BitSet nextSetBit

Introduction

In this page you can find the example usage for java.util BitSet nextSetBit.

Prototype

public int nextSetBit(int fromIndex) 

Source Link

Document

Returns the index of the first bit that is set to true that occurs on or after the specified starting index.

Usage

From source file:dendroscope.autumn.hybridnumber.ComputeHybridNumber.java

/**
 * run the algorithm. This can be reentered by rerootings of the same two trees
 *
 * @param tree1// ww w.  j  a  v a2  s  .com
 * @param tree2
 * @return reduced trees
 */
int run(PhyloTree tree1, PhyloTree tree2, Taxa allTaxa) throws IOException, CanceledException {
    if (!initialized) {
        initialized = true;
        progressListener.setMaximum(20);
        progressListener.setProgress(0);
        startTime = System.currentTimeMillis();
        nextTime = this.startTime + waitTime;
    }

    if (bestScore.get() == LARGE) { // no upper bound given, use cluster network
        System.err.print("Computing upper bound using cluster network: ");
        int upperBound = Utilities.getNumberOfReticulationsInClusterNetwork(tree1, tree2, progressListener);
        System.err.println(upperBound);
        bestScore.set(upperBound);
    }

    Pair<Root, Root> roots = PreProcess.apply(tree1, tree2, allTaxa);
    Root root1 = roots.getFirst();
    Root root2 = roots.getSecond();

    BitSet onlyTree1 = Cluster.setminus(root1.getTaxa(), root2.getTaxa());
    BitSet onlyTree2 = Cluster.setminus(root2.getTaxa(), root1.getTaxa());

    if (root1.getTaxa().cardinality() == onlyTree1.cardinality())
        throw new IOException("None of the taxa in tree2 are contained in tree1");
    if (root2.getTaxa().cardinality() == onlyTree2.cardinality())
        throw new IOException("None of the taxa in tree1 are contained in tree2");

    if (onlyTree1.cardinality() > 0) {
        if (!silent)
            System.err.println("Killing all taxa only present in tree1: " + onlyTree1.cardinality());
        for (int t = onlyTree1.nextSetBit(0); t != -1; t = onlyTree1.nextSetBit(t + 1)) {
            BitSet one = new BitSet();
            one.set(t);
            root1 = CopyWithTaxaRemoved.apply(root1, one);
        }
    }

    if (onlyTree2.cardinality() > 0) {
        if (!silent)
            System.err.println("Killing all taxa only present in tree2: " + onlyTree2.cardinality());
        for (int t = onlyTree2.nextSetBit(0); t != -1; t = onlyTree2.nextSetBit(t + 1)) {
            BitSet one = new BitSet();
            one.set(t);
            root2 = CopyWithTaxaRemoved.apply(root2, one);
        }
    }

    if (!root1.getTaxa().equals(root2.getTaxa()))
        throw new IOException("Trees have unequal taxon sets (even after killing)");

    // run the refine algorithm
    if (!silent)
        System.err.println("Computing common refinement of both trees");
    Refine.apply(root1, root2);

    if (true) {
        System.err.println(root1.toStringTree());
        System.err.println(root2.toStringTree());
    }

    if (tree1.getRoot() == null || tree2.getRoot() == null) {
        throw new IOException("Can't compute hybrid number, at least one of the trees is empty or unrooted");
    }

    // we maintain both trees in lexicographic order for ease of comparison
    root1.reorderSubTree();
    root2.reorderSubTree();

    if (!silent)
        System.err.println("Computing hybridization number using Autumn algorithm...");
    if (!silent)
        System.err.println("(Number of worker threads: " + (additionalThreads + 1) + ")");

    int result = computeHybridNumberRec(root1, root2, false, null, null, true, 0, new ValuesList());
    if (!silent)
        System.err.println("(Result: " + result + ")");
    if (!silent)
        System.err.println("Hybridization number: " + bestScore.get());
    if (bestScore.get() > result)
        throw new IOException("bestScore > result: " + bestScore.get() + " " + result);

    return bestScore.get();
}

From source file:model.DecomposableModel.java

/**
 * @return the number of parameters of the models
 *//*w  w  w  . j a v a  2 s  .  c o  m*/
public long getNbParameters() {
    if (nbParameters == -1) {
        List<BitSet> cliques = graph.getCliquesBFS();
        List<BitSet> separators = graph.getSeparatorsBFS();
        nbParameters = 0;

        for (BitSet clique : cliques) {
            int tmpNBDF = 1;
            for (int var = clique.nextSetBit(0); var >= 0; var = clique.nextSetBit(var + 1)) {
                tmpNBDF *= dimensionsForVariables[var];
            }
            tmpNBDF = tmpNBDF - 1;
            nbParameters += tmpNBDF;
        }

        for (BitSet separator : separators) {
            int tmpNBDF = 1;
            for (int var = separator.nextSetBit(0); var >= 0; var = separator.nextSetBit(var + 1)) {
                tmpNBDF *= dimensionsForVariables[var];
            }
            tmpNBDF = tmpNBDF - 1;
            nbParameters -= tmpNBDF;
        }

    }

    return nbParameters;

}

From source file:com.bittorrent.mpetazzoni.client.SharedTorrent.java

/**
 * Bit field availability handler./*w  w w .  j  av a2s.  c  o  m*/
 *
 * <p>
 * Handle updates in piece availability from a peer's BITFIELD message.
 * When this happens, we need to mark in all the pieces the peer has that
 * they can be reached through this peer, thus augmenting the global
 * availability of pieces.
 * </p>
 *
 * @param peer The peer we got the update from.
 * @param availablePieces The pieces availability bit field of the peer.
 */
@Override
public synchronized void handleBitfieldAvailability(SharingPeer peer, BitSet availablePieces) {
    // Determine if the peer is interesting for us or not, and notify it.
    BitSet interesting = (BitSet) availablePieces.clone();
    interesting.andNot(this.completedPieces);
    interesting.andNot(this.requestedPieces);

    if (interesting.cardinality() == 0) {
        peer.notInteresting();
    } else {
        peer.interesting();
    }

    // Record that the peer has all the pieces it told us it had.
    for (int i = availablePieces.nextSetBit(0); i >= 0; i = availablePieces.nextSetBit(i + 1)) {
        this.rarest.remove(this.pieces[i]);
        this.pieces[i].seenAt(peer);
        this.rarest.add(this.pieces[i]);
    }

    logger.trace("Peer {} contributes {} piece(s) ({} interesting) " + "[completed={}; available={}/{}].",
            new Object[] { peer, availablePieces.cardinality(), interesting.cardinality(),
                    this.completedPieces.cardinality(), this.getAvailablePieces().cardinality(),
                    this.pieces.length });
}

From source file:dendroscope.autumn.hybridnetwork.ComputeHybridizationNetwork.java

/**
 * run the algorithm//from   w w w  .  j  av  a2  s .  c o  m
 *
 * @param tree1
 * @param tree2
 * @param hybridizationNumber
 * @return reduced trees
 */
private TreeData[] run(TreeData tree1, TreeData tree2, int upperBound, Single<Integer> hybridizationNumber)
        throws IOException, CanceledException {
    verbose = ProgramProperties.get("verbose-HL", false);
    Taxa allTaxa = new Taxa();
    Pair<Root, Root> roots = PreProcess.apply(tree1, tree2, allTaxa);
    Root root1 = roots.getFirst();
    Root root2 = roots.getSecond();

    if (root1.getOutDegree() == 1 && root1.getFirstOutEdge().getTarget().getOutDegree() > 0) {
        Root tmp = (Root) root1.getFirstOutEdge().getTarget();
        root1.deleteNode();
        root1 = tmp;
    }

    if (root2.getOutDegree() == 1 && root2.getFirstOutEdge().getTarget().getOutDegree() > 0) {
        Root tmp = (Root) root2.getFirstOutEdge().getTarget();
        root2.deleteNode();
        root2 = tmp;
    }

    BitSet onlyTree1 = Cluster.setminus(root1.getTaxa(), root2.getTaxa());
    BitSet onlyTree2 = Cluster.setminus(root2.getTaxa(), root1.getTaxa());

    if (root1.getTaxa().cardinality() == onlyTree1.cardinality())
        throw new IOException("None of the taxa in second tree are contained in first tree");
    if (root2.getTaxa().cardinality() == onlyTree2.cardinality())
        throw new IOException("None of the taxa in first tree are contained in second tree");

    if (onlyTree1.cardinality() > 0) {
        System.err.println("Killing all taxa only present in first tree: " + onlyTree1.cardinality());
        for (int t = onlyTree1.nextSetBit(0); t != -1; t = onlyTree1.nextSetBit(t + 1)) {
            RemoveTaxon.apply(root1, 1, t);
        }
    }

    if (onlyTree2.cardinality() > 0) {
        System.err.println("Killing all taxa only present in second tree: " + onlyTree2.cardinality());
        for (int t = onlyTree2.nextSetBit(0); t != -1; t = onlyTree2.nextSetBit(t + 1)) {
            RemoveTaxon.apply(root2, 2, t);
        }
    }

    // run the refine algorithm
    System.err.println("Computing common refinement of both trees");
    Refine.apply(root1, root2);

    if (tree1.getRoot() == null || tree2.getRoot() == null) {
        throw new IOException(
                "Can't compute hybridization networks, at least one of the trees is empty or unrooted");
    }

    // we maintain both trees in lexicographic order for ease of comparison
    root1.reorderSubTree();
    root2.reorderSubTree();

    System.err.println(
            "Computing hybridization networks using Autumn algorithm (Autumn algorithm, Huson and Linz, 2016)...");
    progressListener.setTasks("Computing hybridization networks", "(Unknown how long this will really take)");
    progressListener.setMaximum(20);
    progressListener.setProgress(0);
    long startTime = System.currentTimeMillis();
    nextTime = startTime + waitTime;
    Set<Root> result = new TreeSet<>(new NetworkComparator());
    int h = computeRec(root1, root2, false, getAllAliveTaxa(root1, root2), upperBound, result, ">");

    fixOrdering(result);

    if (false) {
        Collection<Root> maafs = MAAFUtils.computeAllMAAFs(result);
        System.err.println("MAAFs before:");
        for (Root root : maafs) {
            System.err.println(root.toStringNetworkFull());
        }
    }
    int numberOfDuplicatesRemoved = MAAFUtils.removeDuplicateMAAFs(result, false);
    if (numberOfDuplicatesRemoved > 0)
        System.err.println("MAAF duplicates removed: " + numberOfDuplicatesRemoved);
    if (false) {
        Collection<Root> maafs = MAAFUtils.computeAllMAAFs(result);
        System.err.println("MAAFs after:");
        for (Root root : maafs) {
            System.err.println(root.toStringNetworkFull());
        }
    }

    fixOrdering(result);

    BitSet missingTaxa = Cluster.union(onlyTree1, onlyTree2);
    if (missingTaxa.cardinality() > 0) {
        System.err.println("Reattaching killed taxa: " + missingTaxa.cardinality());
        for (Root r : result) {
            for (int t = missingTaxa.nextSetBit(0); t != -1; t = missingTaxa.nextSetBit(t + 1)) {
                RemoveTaxon.unapply(r, t);
            }
        }
    }

    System.err.println("Hybridization number: " + h);
    hybridizationNumber.set(h);
    System.err.println("Total networks: " + result.size());
    System.err.println("Time: " + ((System.currentTimeMillis() - startTime) / 1000) + " secs");

    System.err.println(
            "(Size lookup table: " + lookupTable.size() + ", number of times used: " + numberOfLookups + ")");
    lookupTable.clear();
    System.gc();

    if (false) {
        System.err.println("Networks:");
        for (Root root : result) {
            System.err.println(root.toStringNetworkFull());
        }
    }

    System.gc();

    List<TreeData> list = PostProcess.apply(result.toArray(new Root[result.size()]), allTaxa, false);
    return list.toArray(new TreeData[list.size()]);
}

From source file:org.jahia.ajax.gwt.helper.NodeHelper.java

private void populatePermissions(GWTJahiaNode n, JCRNodeWrapper node) {
    BitSet bs = node.getPermissionsAsBitSet();
    if (bs != null) {
        GWTBitSet gwtBs = new GWTBitSet(bs.size());
        gwtBs.setReferenceHashCode(JahiaPrivilegeRegistry.getRegisteredPrivilegeNames().hashCode());

        for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
            gwtBs.set(i);/*  w  w w  .j  ava 2 s .  c  o  m*/
        }

        n.setPermissions(gwtBs);

        try {
            boolean hasAcl = node.hasNode("j:acl") && node.getNode("j:acl").hasNodes();
            n.setHasAcl(hasAcl);
        } catch (RepositoryException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:model.DecomposableModel.java

public long nbParametersDiffIfAdding(Integer a, Integer b) {
    // System.out.println("computing actual entropy");
    BitSet Sab = graph.getSeparator(a, b);
    BitSet Sabua = (BitSet) Sab.clone();
    BitSet Sabub = (BitSet) Sab.clone();
    BitSet Sabuaub = (BitSet) Sab.clone();
    Sabua.set(a);//  w  w  w  .  j  av a 2s .  co  m
    Sabub.set(b);
    Sabuaub.set(a);
    Sabuaub.set(b);

    long diffNbParameters = 0;

    // Sab
    int tmpNBDF = 1;
    for (int var = Sab.nextSetBit(0); var >= 0; var = Sab.nextSetBit(var + 1)) {
        tmpNBDF *= dimensionsForVariables[var];
    }
    tmpNBDF = tmpNBDF - 1;
    diffNbParameters += tmpNBDF;

    // Sab + a
    tmpNBDF = 1;
    for (int var = Sabua.nextSetBit(0); var >= 0; var = Sabua.nextSetBit(var + 1)) {
        tmpNBDF *= dimensionsForVariables[var];
    }
    tmpNBDF = tmpNBDF - 1;
    diffNbParameters -= tmpNBDF;

    // Sab + a + b
    tmpNBDF = 1;
    for (int var = Sabuaub.nextSetBit(0); var >= 0; var = Sabuaub.nextSetBit(var + 1)) {
        tmpNBDF *= dimensionsForVariables[var];
    }
    tmpNBDF = tmpNBDF - 1;
    diffNbParameters += tmpNBDF;

    // Sab + b
    tmpNBDF = 1;
    for (int var = Sabub.nextSetBit(0); var >= 0; var = Sabub.nextSetBit(var + 1)) {
        tmpNBDF *= dimensionsForVariables[var];
    }
    tmpNBDF = tmpNBDF - 1;
    diffNbParameters -= tmpNBDF;

    return diffNbParameters;
}

From source file:org.apache.carbondata.core.scan.filter.FilterUtil.java

/**
 * This method will compare the selected data against null values and
 * flip the bitSet if any null value is found
 *
 * @param dimensionColumnPage//from   ww w. j  a v  a 2  s .co  m
 * @param bitSet
 */
public static void removeNullValues(DimensionColumnPage dimensionColumnPage, BitSet bitSet,
        byte[] defaultValue) {
    if (!bitSet.isEmpty()) {
        if (null != dimensionColumnPage.getNullBits()) {
            if (!dimensionColumnPage.getNullBits().isEmpty()) {
                for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet.nextSetBit(i + 1)) {
                    if (dimensionColumnPage.getNullBits().get(i)) {
                        bitSet.flip(i);
                    }
                }
            }
        } else {
            for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet.nextSetBit(i + 1)) {
                if (dimensionColumnPage.compareTo(i, defaultValue) == 0) {
                    bitSet.flip(i);
                }
            }
        }
    }
}

From source file:model.DecomposableModel.java

public long nbParametersDiffIfAdding(Integer a, Integer b, BitSet Sab) {
    // System.out.println("computing actual entropy");
    BitSet Sabua = (BitSet) Sab.clone();
    BitSet Sabub = (BitSet) Sab.clone();
    BitSet Sabuaub = (BitSet) Sab.clone();
    Sabua.set(a);/*from  w w  w.j a  v  a 2s .c  o  m*/
    Sabub.set(b);
    Sabuaub.set(a);
    Sabuaub.set(b);

    long diffNbParameters = 0;

    // Sab
    int tmpNBDF = 1;
    for (int var = Sab.nextSetBit(0); var >= 0; var = Sab.nextSetBit(var + 1)) {
        tmpNBDF *= dimensionsForVariables[var];
    }
    tmpNBDF = tmpNBDF - 1;
    diffNbParameters += tmpNBDF;

    // Sab + a
    tmpNBDF = 1;
    for (int var = Sabua.nextSetBit(0); var >= 0; var = Sabua.nextSetBit(var + 1)) {
        tmpNBDF *= dimensionsForVariables[var];
    }
    tmpNBDF = tmpNBDF - 1;
    diffNbParameters -= tmpNBDF;

    // Sab + a + b
    tmpNBDF = 1;
    for (int var = Sabuaub.nextSetBit(0); var >= 0; var = Sabuaub.nextSetBit(var + 1)) {
        tmpNBDF *= dimensionsForVariables[var];
    }
    tmpNBDF = tmpNBDF - 1;
    diffNbParameters += tmpNBDF;

    // Sab + b
    tmpNBDF = 1;
    for (int var = Sabub.nextSetBit(0); var >= 0; var = Sabub.nextSetBit(var + 1)) {
        tmpNBDF *= dimensionsForVariables[var];
    }
    tmpNBDF = tmpNBDF - 1;
    diffNbParameters -= tmpNBDF;

    return diffNbParameters;
}

From source file:model.DecomposableModel.java

/**
 * Export a dot file representing the graph
 * //from w  ww . j av  a 2s .com
 * @see {@linkplain http://www.graphviz.org/content/dot-language}
 * @param file
 *            the file to save the representation to
 * @param variableNames
 *            the names of the variables
 */
public void exportDOTCG(File file, String[] variableNames) {
    // String[] simplVar = Arrays.copyOf(variableNames,
    // variableNames.length);
    // for(int i=0;i<simplVar.length;i++){
    // simplVar[i] = simplVar[i].replaceAll("[%()]","");
    // }
    try {
        PrintWriter out = new PrintWriter(new FileOutputStream(file), true);
        out.println("graph G{");

        for (CliqueGraphEdge edge : graph.cg.edgeSet()) {
            BitSet source = graph.cg.getEdgeSource(edge);
            BitSet target = graph.cg.getEdgeTarget(edge);
            BitSet inter = (BitSet) source.clone();
            inter.and(target);
            if (variableNames == null) {
                out.println(graph.cg.getEdgeSource(edge) + "--" + graph.cg.getEdgeTarget(edge));
            } else {
                out.print("\"");
                for (int v = source.nextSetBit(0); v >= 0; v = source.nextSetBit(v + 1)) {
                    out.print(variableNames[v] + ";");
                }
                out.print("\"--\"");
                for (int v = target.nextSetBit(0); v >= 0; v = target.nextSetBit(v + 1)) {
                    out.print(variableNames[v] + ";");
                }
                out.print("\" [label = \"");
                for (int v = inter.nextSetBit(0); v >= 0; v = inter.nextSetBit(v + 1)) {
                    out.print(variableNames[v] + ";");
                }
                out.println("\"]");
            }
        }

        out.println("}");

        out.close();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }

}

From source file:org.apache.carbondata.core.scan.filter.FilterUtil.java

/**
 * Below method will used to get encoded filter values for range filter values
 * when local dictionary is present in blocklet for columns
 * If number of include filter is more than 60% of total dictionary size it will
 * convert include to exclude//from  ww w . jav a 2  s  . c o m
 * @param includeDictValues
 * include filter values
 * @param carbonDictionary
 * dictionary
 * @param useExclude
 * to check if using exclude will be more optimized
 * @return encoded filter values
 */
private static byte[][] getEncodedFilterValuesForRange(BitSet includeDictValues,
        CarbonDictionary carbonDictionary, boolean useExclude) {
    KeyGenerator keyGenerator = KeyGeneratorFactory
            .getKeyGenerator(new int[] { CarbonCommonConstants.LOCAL_DICTIONARY_MAX });
    List<byte[]> encodedFilterValues = new ArrayList<>();
    int[] dummy = new int[1];
    if (!useExclude) {
        try {
            for (int i = includeDictValues.nextSetBit(0); i >= 0; i = includeDictValues.nextSetBit(i + 1)) {
                dummy[0] = i;
                encodedFilterValues.add(keyGenerator.generateKey(dummy));
            }
        } catch (KeyGenException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return encodedFilterValues.toArray(new byte[encodedFilterValues.size()][]);
    } else {
        try {
            for (int i = 1; i < carbonDictionary.getDictionarySize(); i++) {
                if (!includeDictValues.get(i) && null != carbonDictionary.getDictionaryValue(i)) {
                    dummy[0] = i;
                    encodedFilterValues.add(keyGenerator.generateKey(dummy));
                }
            }
        } catch (KeyGenException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
    return getSortedEncodedFilters(encodedFilterValues);
}