Example usage for java.util BitSet cardinality

List of usage examples for java.util BitSet cardinality

Introduction

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

Prototype

public int cardinality() 

Source Link

Document

Returns the number of bits set to true in this BitSet .

Usage

From source file:Main.java

public static void main(String[] args) {

    BitSet bitset1 = new BitSet(8);
    BitSet bitset2 = new BitSet(8);

    // assign values to bitset1
    bitset1.set(0);//from   ww  w .j av a 2  s  . c  o  m
    bitset1.set(1);
    bitset1.set(2);

    // assign values to bitset2
    bitset2.set(2);
    bitset2.set(4);

    // print the sets
    System.out.println("Bitset1:" + bitset1);
    System.out.println("Bitset2:" + bitset2);

    // print cardinality for bitset1
    System.out.println(bitset1.cardinality());

    // print cardinality for bitset2
    System.out.println(bitset2.cardinality());

}

From source file:com.textocat.textokit.postagger.DictionaryComplianceChecker.java

private static int calcDistance(final BitSet xArg, final BitSet yArg) {
    BitSet x = (BitSet) xArg.clone();
    x.xor(yArg);// w  w  w  .  ja  v a 2s.c o m
    return x.cardinality();
}

From source file:com.cloudera.oryx.kmeans.computation.cluster.KSketchIndex.java

private static int hammingDistance(BitSet q, BitSet idx) {
    BitSet x = new BitSet(q.size());
    x.or(q);//from  w  w  w.  j av  a 2 s. com
    x.xor(idx);
    return x.cardinality();
}

From source file:info.rmarcus.birkhoffvonneumann.MatrixUtils.java

public static double permanent(double[][] input) {
    int n = input.length;

    double collector = 0.0;
    Iterator<BitSet> i = bitStringsOfSize(n);
    while (i.hasNext()) {
        BitSet nxt = NullUtils.orThrow(i.next(), () -> new BVNRuntimeException("Iterator returned null!"));
        if (nxt.cardinality() == 0)
            continue;

        int mult = (int) Math.pow(-1, nxt.cardinality());
        double accum = 1.0;

        for (int row = 0; row < n; row++) {
            double x = 0;
            for (int col = 0; col < n; col++) {
                if (!nxt.get(col))
                    continue;

                x += input[row][col];/*from   w ww. ja  v a2  s  .  c om*/
            }

            accum *= x;
        }

        collector += mult * accum;
    }

    int mult = (int) Math.pow(-1, n);
    return mult * collector;

}

From source file:org.caleydo.core.util.impute.KNNImpute.java

private static Pair<List<Gene>, List<Gene>> split(List<Gene> neighborhood, BitSet partOf_a) {
    final int a_n = partOf_a.cardinality();
    final int b_n = neighborhood.size() - a_n;

    final List<Gene> a = new ArrayList<>(a_n);
    final List<Gene> b = new ArrayList<>(b_n);

    for (int i = 0; i < neighborhood.size(); ++i) {
        if (partOf_a.get(i))
            a.add(neighborhood.get(i));//www.  ja  v  a  2 s . c o  m
        else
            b.add(neighborhood.get(i));
    }
    return Pair.make(a, b);
}

From source file:org.apache.hadoop.hive.ql.optimizer.optiq.stats.HiveRelMdRowCount.java

private static Pair<Integer, Integer> canHandleJoin(JoinRelBase joinRel, List<RexNode> leftFilters,
        List<RexNode> rightFilters, List<RexNode> joinFilters) {

    /*//from  www  . j ava2 s.  co  m
     * If after classifying filters there is more than 1 joining predicate, we
     * don't handle this. Return null.
     */
    if (joinFilters.size() != 1) {
        return null;
    }

    RexNode joinCond = joinFilters.get(0);

    int leftColIdx;
    int rightColIdx;

    if (!(joinCond instanceof RexCall)) {
        return null;
    }

    if (((RexCall) joinCond).getOperator() != SqlStdOperatorTable.EQUALS) {
        return null;
    }

    BitSet leftCols = RelOptUtil.InputFinder.bits(((RexCall) joinCond).getOperands().get(0));
    BitSet rightCols = RelOptUtil.InputFinder.bits(((RexCall) joinCond).getOperands().get(1));

    if (leftCols.cardinality() != 1 || rightCols.cardinality() != 1) {
        return null;
    }

    int nFieldsLeft = joinRel.getLeft().getRowType().getFieldList().size();
    int nFieldsRight = joinRel.getRight().getRowType().getFieldList().size();
    int nSysFields = joinRel.getSystemFieldList().size();
    BitSet rightFieldsBitSet = BitSets.range(nSysFields + nFieldsLeft, nSysFields + nFieldsLeft + nFieldsRight);
    /*
     * flip column references if join condition specified in reverse order to
     * join sources.
     */
    if (BitSets.contains(rightFieldsBitSet, leftCols)) {
        BitSet t = leftCols;
        leftCols = rightCols;
        rightCols = t;
    }

    leftColIdx = leftCols.nextSetBit(0) - nSysFields;
    rightColIdx = rightCols.nextSetBit(0) - (nSysFields + nFieldsLeft);

    return new Pair<Integer, Integer>(leftColIdx, rightColIdx);
}

From source file:uk.ac.ebi.orchem.search.SimilaritySearch.java

/**
 * Similarity score calculation between one database compound and a user's query compound.
 * @param userQuery  query structure in SMILES or MOL
 * @param queryType  MOL or SMILES/* w w  w .j av a  2  s . c o m*/
 * @param compoundId ID of database compound to calculate similarity with
 * @return tanimoto similarity score
 * @throws Exception
 */
public static float singleCompoundSimilarity(Clob userQuery, String queryType, String compoundId)
        throws Exception {

    OracleConnection conn = null;
    PreparedStatement pstmtFp = null;
    ResultSet resFp = null;
    float tanimotoCoeff = 0;

    try {
        //User query
        int clobLen = new Long(userQuery.length()).intValue();
        String query = (userQuery.getSubString(1, clobLen));
        IAtomContainer molecule = null;
        if (queryType.equals(Utils.QUERY_TYPE_MOL)) {
            molecule = MoleculeCreator.getMoleculeFromMolfile(query);
        } else if (queryType.equals(Utils.QUERY_TYPE_SMILES)) {
            SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance());
            molecule = sp.parseSmiles(query);
        } else
            throw new RuntimeException("Query type not recognized");
        BitSet queryFp = FingerPrinterAgent.FP.getExtendedFingerPrinter().getFingerprint(molecule);
        float queryBitCount = queryFp.cardinality();
        byte[] queryBytes = Utils.toByteArray(queryFp, extFpSize);

        //Database comound
        conn = (OracleConnection) new OracleDriver().defaultConnection();
        String compoundQuery = "select bit_count, fp from orchem_fingprint_simsearch s where id=?";
        pstmtFp = conn.prepareStatement(compoundQuery);
        pstmtFp.setFetchSize(1);
        pstmtFp.setString(1, compoundId);
        resFp = pstmtFp.executeQuery();

        if (resFp.next()) {
            byte[] dbByteArray = resFp.getBytes("fp");
            float compoundBitCount = resFp.getFloat("bit_count");
            tanimotoCoeff = calcTanimoto(queryBytes, queryBytes.length, dbByteArray, queryBitCount,
                    compoundBitCount);
        } else
            throw new RuntimeException("Compound " + compoundId + " not found in similarity table");

    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (resFp != null)
            resFp.close();
        if (pstmtFp != null)
            pstmtFp.close();
        if (conn != null)
            conn.close();
    }
    return tanimotoCoeff;
}

From source file:org.moeaframework.TestUtils.java

/**
 * Returns {@code true} if the two populations are equal; otherwise
 * {@code false}. Two populations are equal if all solutions contained
 * in one population are contained in the other population.
 * // w ww.ja  va  2s.co m
 * @param p1 the first population
 * @param p2 the second population
 * @return {@code true} if the two populations are equal; otherwise
 *         {@code false}
 */
public static boolean equals(Population p1, Population p2) {
    if (p1.size() != p2.size()) {
        return false;
    }

    BitSet matched1 = new BitSet(p1.size());
    BitSet matched2 = new BitSet(p2.size());

    for (int i = 0; i < p1.size(); i++) {
        for (int j = 0; j < p2.size(); j++) {
            if (equals(p1.get(i), p2.get(j))) {
                matched1.set(i);
                matched2.set(j);
            }
        }
    }

    return (matched1.cardinality() == p1.size()) && (matched2.cardinality() == p2.size());
}

From source file:com.joliciel.jochre.graphics.ShapeFillerImpl.java

@Override
public int getFillFactor(Shape shape, int threshold) {
    // Note, we get the fill factor based on a neighbour count of 5,
    // on the assumption that "holey" shapes will contain more white space
    // that's surrounded on all sides.
    BitSet bitset = shape.getBlackAndWhiteBitSet(threshold);
    int fillFactor = MAX_FILL_FACTOR;
    int startCardinality = bitset.cardinality();
    LOG.debug("startCardinality: " + startCardinality);
    int endCardinality = startCardinality;
    int lastCardinality = startCardinality;
    for (int i = 0; i < MAX_FILL_FACTOR; i++) {
        BitSet newBitSet = this.fillBitSet(shape, bitset, 5);
        endCardinality = newBitSet.cardinality();
        LOG.debug("endCardinality: " + endCardinality);
        double percentIncrease = ((double) endCardinality / (double) lastCardinality) * 100.0;
        LOG.debug("% increase: " + percentIncrease);
        // for NEIGHBOUR_COUNT_BIRTH = 5, we could check, or a growth percentage
        // if (newBitSet.cardinality()==bitset.cardinality()) {
        // for NEIGHBOUR_COUNT_BIRTH = 4, we need to go by a growth percentage
        // if (percentIncrease < 105) {
        if (percentIncrease < 105) {
            fillFactor = i;/*from ww w  .  j a va  2 s.  c o  m*/
            break;
        }
        bitset = newBitSet;
        lastCardinality = endCardinality;
    }
    LOG.debug("Fill factor: " + fillFactor);
    LOG.debug("Total % increase: " + (((double) endCardinality / (double) startCardinality) * 100.0));
    return fillFactor;
}

From source file:com.textocat.textokit.morph.ruscorpora.DictionaryAligningTagMapper2.java

@Override
public void mapFromRusCorpora(RusCorporaWordform srcWf, com.textocat.textokit.morph.fs.Wordform targetWf) {
    Word wordAnno = targetWf.getWord();//from w w w. j a  v a  2  s  .  c o  m
    delegate.mapFromRusCorpora(srcWf, targetWf);
    // first - check whether tag is in tagset
    final BitSet wfTag = toGramBits(gm, FSUtils.toList(targetWf.getGrammems()));
    // skip INIT as a whole new category
    if (wfTag.get(gm.getGrammemNumId(RNCMorphConstants.RNC_INIT))) {
        return;
    }
    if (wfTag.intersects(rncDistortionsMask)) {
        wfTag.andNot(rncDistortionsMask);
        if (!dict.containsGramSet(wfTag)) {
            onDistortedWordWithUnknownTag(wordAnno, wfTag);
        }
        return;
    }
    //
    // if there is no such tag in dictionary then look the word in it
    String wordStr = wordAnno.getCoveredText();
    List<Wordform> dictWfs = dict.getEntries(normalizeToDictionaryForm(wordStr));
    if (dictWfs == null || dictWfs.isEmpty()) {
        // wfTag.isEmpty => NON-LEX
        if (!wfTag.isEmpty() && !dict.containsGramSet(wfTag)) {
            onUnknownWordWithUnknownTag(wordAnno, wfTag);
        }
        return;
    }
    // retain only the gram categories that are represented in RNC tagset
    Set<BitSet> dictTags = rncTrimmer.trimAndMerge(Lists.transform(dictWfs, allGramBitsFunction(dict)));
    // search for a unique dictionary entry that has a tag extending the given one
    List<BitSet> wfExtensions = Lists.newLinkedList();
    for (BitSet dTag : dictTags) {
        if (contains(dTag, wfTag)) {
            wfExtensions.add(dTag);
        }
    }
    if (wfExtensions.isEmpty()) {
        onConflictingTag(wordAnno, wfTag);
    } else if (wfExtensions.size() > 1) {
        onAmbiguousWordform(wordAnno, wfTag);
    } else {
        BitSet newTag = wfExtensions.get(0);
        if (newTag.cardinality() > wfTag.cardinality()) {
            List<String> newTagStr = gm.toGramSet(newTag);
            targetWf.setGrammems(FSUtils.toStringArray(getCAS(targetWf), newTagStr));
            onTagExtended(wordAnno, wfTag, newTag);
        }
    }
}