下面列出了java.util.BitSet#and ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Determine if this set is an (improper) superset of another.
*
* @param source the set we are testing for.
* @param destination the set we are testing against.
* @return source is a superset of destination, yes then return true else
* false
* @throws CDKException
*/
public static boolean isSuperSet(BitSet source, BitSet destination) throws CDKException {
boolean flag = false;
if (source.cardinality() >= destination.cardinality()) {
not_null(source);
/* make a copy of the source set */
BitSet copy_other = (BitSet) source.clone();
/* and or in */
copy_other.and(destination);
/* if it hasn't changed, we were a subset */
flag = copy_other.equals(destination);
// flag = copy_other.equals(destination);
}
return flag;
}
/**
*
* @param Molecule1
* @param Molecule2
* @return
* @throws Exception
*/
public static double getNormalizedHammingDistance(BitSet Molecule1, BitSet Molecule2) throws Exception {
A = (BitSet) Molecule1.clone();
B = (BitSet) Molecule2.clone();
float _bitset1_cardinality = A.cardinality();
float _bitset2_cardinality = B.cardinality();
if (A.size() != B.size()) {
throw new Exception("Bisets must have the same bit length");
}
BitSet one_and_two = (BitSet) A.clone();
one_and_two.and(B);
float _common_bit_count = one_and_two.cardinality();
double Val = (_bitset1_cardinality + _bitset2_cardinality - _common_bit_count) - _common_bit_count;
float N1 = (_bitset1_cardinality + _bitset2_cardinality - _common_bit_count);
float N2 = (1 - _bitset1_cardinality - _bitset2_cardinality + _common_bit_count);
float N = N1 + N2;
return Val / N;
}
public de.metanome.algorithms.cfdfinder.structures.FDTreeElement addFunctionalDependencyIfNotInvalid(BitSet lhs, BitSet rhs) {
de.metanome.algorithms.cfdfinder.structures.FDTreeElement currentNode = this;
currentNode.addRhsAttributes(rhs);
BitSet invalidFds = (BitSet) currentNode.rhsAttributes.clone();
int lhsLength = 0;
for (int i = lhs.nextSetBit(0); i >= 0; i = lhs.nextSetBit(i + 1)) {
lhsLength++;
if (currentNode.getChildren() == null) {
currentNode.setChildren(new de.metanome.algorithms.cfdfinder.structures.FDTreeElement[this.numAttributes]);
currentNode.getChildren()[i] = new de.metanome.algorithms.cfdfinder.structures.FDTreeElement(this.numAttributes);
}
else if (currentNode.getChildren()[i] == null) {
currentNode.getChildren()[i] = new de.metanome.algorithms.cfdfinder.structures.FDTreeElement(this.numAttributes);
}
currentNode = currentNode.getChildren()[i];
invalidFds.and(currentNode.rhsFds);
currentNode.addRhsAttributes(rhs);
}
rhs.andNot(invalidFds);
currentNode.markFds(rhs);
rhs.or(invalidFds);
this.depth = Math.max(this.depth, lhsLength);
return currentNode;
}
public static void main(String[] args) throws Exception {
BitSet a = new BitSet();
BitSet b = new BitSet();
a.set(0);
a.set(70);
b.set(40);
a.and(b);
if (a.length() != 0)
throw new RuntimeException("Incorrect length after and().");
}
public static void main(String[] args) throws Exception {
BitSet a = new BitSet();
BitSet b = new BitSet();
a.set(0);
a.set(70);
b.set(40);
a.and(b);
if (a.length() != 0)
throw new RuntimeException("Incorrect length after and().");
}
public void removeAcl(OzoneAcl acl) throws OMException {
Objects.requireNonNull(acl, "Acl should not be null.");
if (acl.getAclScope().equals(OzoneAcl.AclScope.DEFAULT)) {
defaultAclList.remove(OzoneAcl.toProtobuf(acl));
return;
}
OzoneAclType aclType = OzoneAclType.valueOf(acl.getType().name());
if (getAccessAclMap(aclType).containsKey(acl.getName())) {
BitSet aclRights = getAccessAclMap(aclType).get(acl.getName());
BitSet bits = (BitSet) acl.getAclBitSet().clone();
bits.and(aclRights);
if (bits.equals(ZERO_BITSET)) {
// throw exception if acl doesn't exist.
throw new OMException("Acl [" + acl + "] doesn't exist.",
INVALID_REQUEST);
}
acl.getAclBitSet().and(aclRights);
aclRights.xor(acl.getAclBitSet());
// Remove the acl as all rights are already set to 0.
if (aclRights.equals(ZERO_BITSET)) {
getAccessAclMap(aclType).remove(acl.getName());
}
} else {
// throw exception if acl doesn't exist.
throw new OMException("Acl [" + acl + "] doesn't exist.",
INVALID_REQUEST);
}
}
public boolean hasAccess(OzoneAclInfo acl) {
if (acl == null) {
return false;
}
BitSet aclBitSet = getAcl(acl.getType(), acl.getName());
if (aclBitSet == null) {
return false;
}
BitSet result = BitSet.valueOf(acl.getRights().toByteArray());
result.and(aclBitSet);
return (!result.equals(ZERO_BITSET) || aclBitSet.get(ALL.ordinal()))
&& !aclBitSet.get(NONE.ordinal());
}
public static void main(String[] args) throws Exception {
BitSet a = new BitSet();
BitSet b = new BitSet();
a.set(0);
a.set(70);
b.set(40);
a.and(b);
if (a.length() != 0)
throw new RuntimeException("Incorrect length after and().");
}
public BitSet jointMembersCode( Collection<H> vals ) {
BitSet x = new BitSet( this.size() );
boolean first = true;
for ( H val : vals ) {
if ( first ) {
first = false;
x.or( getNode( val ).getBitMask() );
} else {
x.and( getNode( val ).getBitMask() );
}
}
return x;
}
BitSet singleBitDiff( BitSet x, BitSet y ) {
BitSet t = new BitSet( x.length() );
t.or( x );
t.flip(0, t.size());
t.and( y );
switch ( t.cardinality() ) {
case 0 : return t;
case 1 : return t;
default: return new BitSet();
}
}
@Nullable
private static BlockNode calcPostDomOut(MethodNode mth, BlockNode block, List<BlockNode> exits) {
if (exits.size() == 1 && mth.getExitBlocks().equals(exits)) {
// simple case: for only one exit which is equal to method exit block
return BlockUtils.calcImmediatePostDominator(mth, block);
}
// fast search: union of blocks dominance frontier
// work if no fallthrough cases and no returns inside switch
BitSet outs = BlockUtils.copyBlocksBitSet(mth, block.getDomFrontier());
for (BlockNode s : block.getCleanSuccessors()) {
outs.or(s.getDomFrontier());
}
outs.clear(block.getId());
if (outs.cardinality() != 1) {
// slow search: calculate partial post-dominance for every exit node
BitSet ipdoms = BlockUtils.newBlocksBitSet(mth);
for (BlockNode exitBlock : exits) {
if (BlockUtils.isAnyPathExists(block, exitBlock)) {
Set<BlockNode> pathBlocks = BlockUtils.getAllPathsBlocks(block, exitBlock);
BlockNode ipdom = BlockUtils.calcPartialImmediatePostDominator(mth, block, pathBlocks, exitBlock);
if (ipdom != null) {
ipdoms.set(ipdom.getId());
}
}
}
outs.and(ipdoms);
}
return BlockUtils.bitSetToOneBlock(mth, outs);
}
/**
* Calculates the intersection of a set of lists containing relation
* IDs
*
* @param indexLists the list to be intersected.
* @return the list of relations contained in all the supplied index
* lists.
*/
protected Collection<Relation> intersection(BitSet... indexLists) {
Set<Relation> res = new HashSet<Relation>();
BitSet relIds = new BitSet(maxID + 1);
relIds.set(0, maxID + 1);
boolean found = false;
for(BitSet aList : indexLists) {
if(aList != null) {
found = true;
relIds.and(aList);
// if there is no intersection then return the empty list
if(relIds.isEmpty()) return res;
}
}
if(!found) return res;
for(int relIdx = 0; relIdx < (maxID + 1); relIdx++) {
if(relIds.get(relIdx)) {
res.add(indexById.get(relIdx));
}
}
return res;
}
public synchronized void commit() {
Object[] o = observers.toArray();
for(int i = 0; i < o.length; i++) {
BitSet tmp = (BitSet)changeMap.clone();
ObserverEntry oe = (ObserverEntry)o[i];
tmp.and(oe.ids);
if(tmp.length() != 0)
oe.observer.update(this, oe.tag);
}
}
@Override
void setBits(BitSet table) {
BitSet tmp1 = new BitSet();
first.setBits(tmp1);
BitSet tmp2 = new BitSet();
second.setBits(tmp2);
tmp1.and(tmp2);
table.or(tmp1);
}
public static Tuple<Float, Float> countTrianglesTriplets(final GraphReadMethods graph) {
final int vxCount = graph.getVertexCount();
BitSet[] allNeighbours = new BitSet[vxCount];
BitSet update = new BitSet(vxCount);
Float triangles = 0f;
Float triplets = 0f;
// initialise variables
for (int vxPosition = 0; vxPosition < vxCount; vxPosition++) {
allNeighbours[vxPosition] = new BitSet(vxCount);
// get the vertex ID at this position
final int vxId = graph.getVertex(vxPosition);
// collect neighbours
BitSet neighbours = new BitSet(vxCount);
for (int neighbourPosition = 0; neighbourPosition < graph.getVertexNeighbourCount(vxId); neighbourPosition++) {
final int nxId = graph.getVertexNeighbour(vxId, neighbourPosition);
final int nxPosition = graph.getVertexPosition(nxId);
neighbours.set(nxPosition, true);
}
//not interested in neighbours to themselves
neighbours.set(vxPosition, false);
allNeighbours[vxPosition].or(neighbours);
update.set(vxPosition, true);
}
// checking for triangles
for (int one = update.nextSetBit(0); one >= 0; one = update.nextSetBit(one + 1)) {
for (int two = update.nextSetBit(one); two >= one; two = update.nextSetBit(two + 1)) {
// are these two vertices connected?
if (allNeighbours[one].get(two) && allNeighbours[two].get(one)) {
// determine common neighbours between them, each one is a triangle
BitSet intersection = new BitSet(vxCount);
intersection.or(allNeighbours[one]);
intersection.and(allNeighbours[two]);
for (int three = intersection.nextSetBit(two); three >= two; three = intersection.nextSetBit(three + 1)) {
triangles += 1;
}
BitSet union = new BitSet(vxCount);
union.or(allNeighbours[one]);
union.or(allNeighbours[two]);
union.set(one, false);
union.set(two, false);
for (int three = union.nextSetBit(two); three >= two; three = union.nextSetBit(three + 1)) {
triplets += 1;
}
}
}
}
return new Tuple<>(triangles, triplets);
}
/**
* Computes the dependencies for the current level (level1).
*
* @throws AlgorithmExecutionException
*/
private void computeDependencies() throws AlgorithmExecutionException {
initializeCplusForLevel();
// iterate through the combinations of the level
for (BitSet X : level1.keySet()) {
if (level1.get(X).isValid()) {
// Build the intersection between X and C_plus(X)
BitSet C_plus = level1.get(X).getRhsCandidates();
BitSet intersection = (BitSet) X.clone();
intersection.and(C_plus);
// clone of X for usage in the following loop
BitSet Xclone = (BitSet) X.clone();
// iterate through all elements (A) of the intersection
for (int A = intersection.nextSetBit(0); A >= 0; A = intersection.nextSetBit(A + 1)) {
Xclone.clear(A);
// check if X\A -> A is valid
StrippedPartition spXwithoutA = level0.get(Xclone).getPartition();
StrippedPartition spX = level1.get(X).getPartition();
if (spX.getError() == spXwithoutA.getError()) {
// found Dependency
BitSet XwithoutA = (BitSet) Xclone.clone();
processFunctionalDependency(XwithoutA, A);
// remove A from C_plus(X)
level1.get(X).getRhsCandidates().clear(A);
// remove all B in R\X from C_plus(X)
BitSet RwithoutX = new BitSet();
// set to R
RwithoutX.set(1, numberAttributes + 1);
// remove X
RwithoutX.andNot(X);
for (int i = RwithoutX.nextSetBit(0); i >= 0; i = RwithoutX.nextSetBit(i + 1)) {
level1.get(X).getRhsCandidates().clear(i);
}
}
Xclone.set(A);
}
}
}
}
@Override
public void edit(final GraphWriteMethods graph, final PluginInteraction interaction, final PluginParameters parameters) throws InterruptedException, PluginException {
final boolean includeConnectionsIn = parameters.getBooleanValue(INCLUDE_CONNECTIONS_IN_PARAMETER_ID);
final boolean includeConnectionsOut = parameters.getBooleanValue(INCLUDE_CONNECTIONS_OUT_PARAMETER_ID);
final boolean treatUndirectedBidirectional = parameters.getBooleanValue(TREAT_UNDIRECTED_BIDIRECTIONAL_PARAMETER_ID);
final int minCommonFeatures = parameters.getParameters().get(MINIMUM_COMMON_FEATURES_PARAMETER_ID).getIntegerValue();
final boolean selectedOnly = parameters.getBooleanValue(SELECTED_ONLY_PARAMETER_ID);
final int vertexSelectedAttributeId = VisualConcept.VertexAttribute.SELECTED.get(graph);
// map each vertex to its neighbour count
final int vertexCount = graph.getVertexCount();
final int[][] neighbourWeights = new int[vertexCount][vertexCount];
final BitSet[] neighbours = new BitSet[vertexCount];
final BitSet update = new BitSet(vertexCount);
final BitSet selected = new BitSet(vertexCount);
for (int vertexPosition = 0; vertexPosition < vertexCount; vertexPosition++) {
final int vertexId = graph.getVertex(vertexPosition);
neighbours[vertexPosition] = new BitSet(vertexCount);
for (int vertexNeighbourPosition = 0; vertexNeighbourPosition < graph.getVertexNeighbourCount(vertexId); vertexNeighbourPosition++) {
final int neighbourId = graph.getVertexNeighbour(vertexId, vertexNeighbourPosition);
final int neighbourPosition = graph.getVertexPosition(neighbourId);
if (vertexPosition == neighbourPosition) {
continue;
}
final int linkId = graph.getLink(vertexId, neighbourId);
for (int linkEdgePosition = 0; linkEdgePosition < graph.getLinkEdgeCount(linkId); linkEdgePosition++) {
final int edgeId = graph.getLinkEdge(linkId, linkEdgePosition);
final int edgeDirection = graph.getEdgeDirection(edgeId);
final boolean isRequestedDirection = (treatUndirectedBidirectional && edgeDirection == GraphConstants.UNDIRECTED
|| includeConnectionsIn && graph.getEdgeDestinationVertex(edgeId) == neighbourId
|| includeConnectionsOut && graph.getEdgeSourceVertex(edgeId) == neighbourId);
if (isRequestedDirection) {
neighbourWeights[vertexPosition][neighbourPosition] += graph.getEdgeTransactionCount(edgeId);
neighbourWeights[vertexPosition][neighbourPosition] -= SimilarityUtilities.countEdgeSimilarityTransactions(graph, edgeId);
neighbours[vertexPosition].set(neighbourPosition, true);
update.set(vertexPosition, true);
}
}
}
final boolean vertexSelected = graph.getBooleanValue(vertexSelectedAttributeId, vertexId);
selected.set(vertexPosition, vertexSelected);
}
// calculate cosine similarity for every pair of vertices on the graph
final Map<Tuple<Integer, Integer>, Float> cosineSimilarities = new HashMap<>();
for (int vertexOnePosition = update.nextSetBit(0); vertexOnePosition >= 0; vertexOnePosition = update.nextSetBit(vertexOnePosition + 1)) {
for (int vertexTwoPosition = update.nextSetBit(0); vertexTwoPosition >= 0; vertexTwoPosition = update.nextSetBit(vertexTwoPosition + 1)) {
if (!selectedOnly || (selected.get(vertexOnePosition) || selected.get(vertexTwoPosition))) {
if (vertexOnePosition >= vertexTwoPosition) {
continue;
}
final BitSet intersection = (BitSet) neighbours[vertexOnePosition].clone();
intersection.and(neighbours[vertexTwoPosition]);
if (intersection.cardinality() < minCommonFeatures) {
continue;
}
final int vertexOneId = graph.getVertex(vertexOnePosition);
final int[] neighboursOne = neighbourWeights[vertexOnePosition];
final int vertexTwoId = graph.getVertex(vertexTwoPosition);
final int[] neighboursTwo = neighbourWeights[vertexTwoPosition];
final float neighbourDotProduct = dot(neighboursOne, neighboursTwo);
final float neighboursMagnitude = magnitude(neighboursOne) * magnitude(neighboursTwo);
final float cosineSimilarity = neighboursMagnitude == 0 ? 0 : neighbourDotProduct / neighboursMagnitude;
cosineSimilarities.put(Tuple.create(vertexOneId, vertexTwoId), cosineSimilarity);
}
}
}
// update the graph with cosine similarity values
SimilarityUtilities.addScoresToGraph(graph, cosineSimilarities, COSINE_SIMILARITY_ATTRIBUTE);
// complete with schema
PluginExecution.withPlugin(VisualSchemaPluginRegistry.COMPLETE_SCHEMA).executeNow(graph);
}
@Override
public void edit(final GraphWriteMethods graph, final PluginInteraction interaction, final PluginParameters parameters) throws InterruptedException, PluginException {
final boolean includeConnectionsIn = parameters.getBooleanValue(INCLUDE_CONNECTIONS_IN_PARAMETER_ID);
final boolean includeConnectionsOut = parameters.getBooleanValue(INCLUDE_CONNECTIONS_OUT_PARAMETER_ID);
final boolean treatUndirectedBidirectional = parameters.getBooleanValue(TREAT_UNDIRECTED_BIDIRECTIONAL_PARAMETER_ID);
final int minCommonFeatures = parameters.getParameters().get(MINIMUM_COMMON_FEATURES_PARAMETER_ID).getIntegerValue();
final boolean selectedOnly = parameters.getBooleanValue(SELECTED_ONLY_PARAMETER_ID);
final boolean community = parameters.getBooleanValue(COMMUNITY_PARAMETER_ID);
final int vertexSelectedAttributeId = VisualConcept.VertexAttribute.SELECTED.get(graph);
// map each vertex to its neighbour count
final int vertexCount = graph.getVertexCount();
final BitSet[] neighbours = new BitSet[vertexCount];
final BitSet update = new BitSet(vertexCount);
final BitSet selected = new BitSet(vertexCount);
for (int vertexPosition = 0; vertexPosition < vertexCount; vertexPosition++) {
final int vertexId = graph.getVertex(vertexPosition);
neighbours[vertexPosition] = new BitSet(vertexCount);
for (int vertexNeighbourPosition = 0; vertexNeighbourPosition < graph.getVertexNeighbourCount(vertexId); vertexNeighbourPosition++) {
final int neighbourId = graph.getVertexNeighbour(vertexId, vertexNeighbourPosition);
final int neighbourPosition = graph.getVertexPosition(neighbourId);
if (vertexPosition == neighbourPosition) {
continue;
}
final int linkId = graph.getLink(vertexId, neighbourId);
for (int linkEdgePosition = 0; linkEdgePosition < graph.getLinkEdgeCount(linkId); linkEdgePosition++) {
final int edgeId = graph.getLinkEdge(linkId, linkEdgePosition);
final int edgeDirection = graph.getEdgeDirection(edgeId);
final boolean isRequestedDirection = (treatUndirectedBidirectional && edgeDirection == GraphConstants.UNDIRECTED
|| includeConnectionsIn && graph.getEdgeDestinationVertex(edgeId) == neighbourId
|| includeConnectionsOut && graph.getEdgeSourceVertex(edgeId) == neighbourId);
if (isRequestedDirection) {
if (!SimilarityUtilities.checkEdgeTypes(graph, edgeId)) {
continue;
}
neighbours[vertexPosition].set(neighbourPosition, true);
update.set(vertexPosition, true);
}
}
}
final boolean vertexSelected = graph.getBooleanValue(vertexSelectedAttributeId, vertexId);
selected.set(vertexPosition, vertexSelected);
}
// calculate resource allocation index for every pair of vertices on the graph
final Map<Tuple<Integer, Integer>, Float> raiScores = new HashMap<>();
for (int vertexOnePosition = update.nextSetBit(0); vertexOnePosition >= 0; vertexOnePosition = update.nextSetBit(vertexOnePosition + 1)) {
for (int vertexTwoPosition = update.nextSetBit(0); vertexTwoPosition >= 0; vertexTwoPosition = update.nextSetBit(vertexTwoPosition + 1)) {
if (!selectedOnly || (selected.get(vertexOnePosition) || selected.get(vertexTwoPosition))) {
if (vertexOnePosition >= vertexTwoPosition) {
continue;
}
if (community && (!selected.get(vertexOnePosition) || !selected.get(vertexTwoPosition))) {
continue;
}
final BitSet intersection = (BitSet) neighbours[vertexOnePosition].clone();
intersection.and(neighbours[vertexTwoPosition]);
intersection.set(vertexOnePosition, false);
intersection.set(vertexTwoPosition, false);
if (intersection.cardinality() < minCommonFeatures) {
continue;
}
final int vertexOneId = graph.getVertex(vertexOnePosition);
final int vertexTwoId = graph.getVertex(vertexTwoPosition);
float sum = 0f;
for (int commonNeighbour = intersection.nextSetBit(0); commonNeighbour >= 0; commonNeighbour = intersection.nextSetBit(commonNeighbour + 1)) {
sum += (1f / graph.getVertexNeighbourCount(graph.getVertex(commonNeighbour)));
}
raiScores.put(Tuple.create(vertexOneId, vertexTwoId), sum);
}
}
}
// update the graph with resource allocation index values
SimilarityUtilities.addScoresToGraph(graph, raiScores, RESOURCE_ALLOCATION_INDEX_ATTRIBUTE);
// complete with schema
PluginExecution.withPlugin(VisualSchemaPluginRegistry.COMPLETE_SCHEMA).executeNow(graph);
}
public Set<Integer> getMatchingSlices(ByteString data, int start_slice, int end_slice)
{
long t1=System.nanoTime();
while(start_slice % 8 != 0) start_slice--;
while(end_slice % 8 != 0) end_slice++;
end_slice = Math.min(end_slice, slices);
Set<Integer> hashes = getHashIndexes(data);
BitSet matches = null;
Set<Integer> match_set = new HashSet<Integer>();
int count = end_slice - start_slice;
byte[] b = new byte[count / 8];
for(int x : hashes)
{
long pos = ((long)slices * (long)x + start_slice) / 8L;
long t1_read = System.nanoTime();
long_map.getBytes(pos, b);
TimeRecord.record(t1_read, "bloom_read");
long t1_bits = System.nanoTime();
BitSet bs = BitSet.valueOf(b);
if (matches == null)
{
matches = bs;
}
else
{
matches.and(bs);
}
TimeRecord.record(t1_bits, "bloom_bitkelp");
if (matches.isEmpty())
{
TimeRecord.record(t1,"bloom_getmatch_short");
return match_set;
}
}
long t1_list=System.nanoTime();
/*
* Reading one bit at a time is slow (it was actually taking measurable clock time on a pi 2).
* So splitting the bitset into longs and on a non-zero checking all those bits. Quite a bit faster.
*/
long[] vals = matches.toLongArray();
for(int idx = 0; idx<vals.length; idx++)
{
if (vals[idx] != 0)
{
int end = Math.min((idx+1) * 64, slices);
for(int i= idx * 64; i<end; i++)
{
if (matches.get(i)) match_set.add(i + start_slice);
}
}
}
/*for(int i=0; i<slices; i++)
{
if (matches.get(i)) match_set.add(i + start_slice);
}*/
TimeRecord.record(t1_list, "bloom_list");
TimeRecord.record(t1_list, "bloom_slices", slices);
TimeRecord.record(t1,"bloom_getmatch");
return match_set;
}
public int intersection(BitSet a, BitSet b) {
BitSet c = (BitSet)a.clone();
c.and(b);
return c.cardinality();
}