Example usage for java.util BitSet get

List of usage examples for java.util BitSet get

Introduction

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

Prototype

public boolean get(int bitIndex) 

Source Link

Document

Returns the value of the bit with the specified index.

Usage

From source file:org.mycore.imagetiler.MCRImageTest.java

/**
 * Tests {@link MCRImage#tile()} with various images provided by {@link #setUp()}.
 * @throws Exception if tiling process fails
 *///  w w  w.  j av  a  2 s .c o m
@Test
public void testTiling() throws Exception {
    for (final Map.Entry<String, String> entry : pics.entrySet()) {
        final File file = new File(entry.getValue());
        final String derivateID = "derivateID";
        final String imagePath = "imagePath/" + FilenameUtils.getName(entry.getValue());
        final MCRImage image = new MCRMemSaveImage(file.toPath(), derivateID, imagePath);
        image.setTileDir(tileDir);
        final BitSet events = new BitSet(2);//pre and post event
        image.tile(new MCRTileEventHandler() {

            @Override
            public void preImageReaderCreated() {
                events.flip(0);
            }

            @Override
            public void postImageReaderCreated() {
                events.flip(1);
            }
        });
        assertTrue("preImageReaderCreated() was not called", events.get(0));
        assertTrue("postImageReaderCreated() was not called", events.get(1));
        assertTrue("Tile directory is not created.", Files.exists(tileDir));
        final Path iviewFile = MCRImage.getTiledFile(tileDir, derivateID, imagePath);
        assertTrue("IView File is not created:" + iviewFile, Files.exists(iviewFile));
        final MCRTiledPictureProps props = MCRTiledPictureProps.getInstanceFromFile(iviewFile);
        final int tilesCount;
        try (final ZipFile iviewImage = new ZipFile(iviewFile.toFile())) {
            tilesCount = iviewImage.size() - 1;
            ZipEntry imageInfoXML = iviewImage.getEntry(MCRTiledPictureProps.IMAGEINFO_XML);
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document imageInfo = documentBuilder.parse(iviewImage.getInputStream(imageInfoXML));
            String hAttr = Objects.requireNonNull(imageInfo.getDocumentElement().getAttribute("height"));
            String wAttr = Objects.requireNonNull(imageInfo.getDocumentElement().getAttribute("width"));
            String zAttr = Objects.requireNonNull(imageInfo.getDocumentElement().getAttribute("zoomLevel"));
            String tAttr = Objects.requireNonNull(imageInfo.getDocumentElement().getAttribute("tiles"));
            assertTrue("height must be positive: " + hAttr, Integer.parseInt(hAttr) > 0);
            assertTrue("width must be positive: " + wAttr, Integer.parseInt(wAttr) > 0);
            assertTrue("zoomLevel must be zero or positive: " + zAttr, Integer.parseInt(zAttr) >= 0);
            int iTiles = Integer.parseInt(tAttr);
            assertEquals(tilesCount, iTiles);

        }
        assertEquals(entry.getKey() + ": Metadata tile count does not match stored tile count.",
                props.getTilesCount(), tilesCount);
        final int x = props.width;
        final int y = props.height;
        assertEquals(entry.getKey() + ": Calculated tile count does not match stored tile count.",
                MCRImage.getTileCount(x, y), tilesCount);
    }
}

From source file:com.joliciel.jochre.graphics.features.InnerEmptyChupchikLowerLeftFeature.java

@Override
public FeatureResult<Boolean> checkInternal(ShapeWrapper shapeWrapper, RuntimeEnvironment env) {
    Shape shape = shapeWrapper.getShape();
    BitSet bitset = shape.getBlackAndWhiteBitSet(shape.getJochreImage().getBlackThreshold());
    boolean[][] grid = new boolean[shape.getWidth()][shape.getHeight()];
    for (int i = 0; i < shape.getWidth(); i++) {
        for (int j = 0; j < shape.getHeight(); j++) {
            if (bitset.get(j * shape.getWidth() + i))
                grid[i][j] = true;/*w  ww .  j a  va 2s  .c om*/
        }
    }
    int startX = shape.getWidth() / 2;
    int startY = shape.getHeight() / 2;
    while (startY < shape.getHeight() && grid[startX][startY]) {
        startY += 1;
    }

    WritableImageGrid mirror = this.graphicsService.getEmptyMirror(shape);

    boolean foundChupchikOrOpening = false;
    if (startY < shape.getHeight()) {
        Stack<HorizontalLineSegment> whiteLineStack = new Stack<HorizontalLineSegment>();
        Set<HorizontalLineSegment> whiteLineSet = new TreeSet<HorizontalLineSegment>();
        HorizontalLineSegment startLine = new HorizontalLineSegment(startX, startY);
        whiteLineStack.push(startLine);
        while (!whiteLineStack.empty()) {
            HorizontalLineSegment line = whiteLineStack.pop();
            if (line.y == shape.getHeight() - 1) {
                // found opening to the outside world
                if (LOG.isTraceEnabled())
                    LOG.trace("Reached edge: found opening");
                foundChupchikOrOpening = true;
                break;
            }
            if (mirror.getPixel(line.xLeft, line.y) == 1)
                continue;

            // extend this line to the right and left
            for (int i = line.xLeft; i >= 0; i--) {
                if (!grid[i][line.y])
                    line.xLeft = i;
                else
                    break;
            }
            for (int i = line.xRight; i <= startX; i++) {
                if (!grid[i][line.y])
                    line.xRight = i;
                else
                    break;
            }
            if (LOG.isTraceEnabled())
                LOG.trace(line.toString());
            whiteLineSet.add(line);

            for (int i = line.xLeft; i <= line.xRight; i++) {
                mirror.setPixel(i, line.y, 1);
            }

            // find lines below and to the left
            if (line.y < shape.getHeight() - 1) {
                boolean inLine = false;
                int row = line.y + 1;
                int xLeft = 0;
                for (int i = line.xLeft; i <= line.xRight; i++) {
                    if (!inLine && !grid[i][row]) {
                        inLine = true;
                        xLeft = i;
                    } else if (inLine && grid[i][row]) {
                        HorizontalLineSegment newLine = new HorizontalLineSegment(xLeft, row);
                        newLine.xRight = i - 1;
                        whiteLineStack.push(newLine);
                        inLine = false;
                    }
                }
                if (inLine) {
                    HorizontalLineSegment newLine = new HorizontalLineSegment(xLeft, row);
                    newLine.xRight = line.xRight;
                    whiteLineStack.push(newLine);
                }
            }
        }

        if (!foundChupchikOrOpening) {
            //            if (LOG.isDebugEnabled()) {
            //               LOG.trace("List of lines");
            //               for (HorizontalLineSegment line : whiteLineSet) {
            //                  LOG.trace(line.toString());
            //               }
            //            }
            Iterator<HorizontalLineSegment> iLines = whiteLineSet.iterator();
            HorizontalLineSegment bottomLeftLine = iLines.next();
            double threshold = shape.getWidth() / 8;
            if (LOG.isTraceEnabled())
                LOG.trace("Length threshold: " + threshold);
            HorizontalLineSegment nextLine = null;
            List<HorizontalLineSegment> firstFewLines = new ArrayList<HorizontalLineSegment>();
            firstFewLines.add(bottomLeftLine);
            HorizontalLineSegment currentLine = bottomLeftLine;
            while (iLines.hasNext() && firstFewLines.size() < 3) {
                nextLine = iLines.next();
                if (nextLine.y != currentLine.y) {
                    firstFewLines.add(nextLine);
                    currentLine = nextLine;
                }
            }
            boolean mightHaveChupchik = true;
            HorizontalLineSegment prevLine = null;
            for (HorizontalLineSegment line : firstFewLines) {
                if (LOG.isTraceEnabled())
                    LOG.trace("Next line left, " + bottomLeftLine.xLeft + ", length: " + bottomLeftLine.length()
                            + ", threshold: " + threshold);
                if (line.length() > threshold) {
                    mightHaveChupchik = false;
                    break;
                }
                if (prevLine != null) {
                    if (line.xLeft + 2 < prevLine.xLeft) {
                        mightHaveChupchik = false;
                        break;
                    }
                    if (line.length() + 1 < prevLine.length()) {
                        mightHaveChupchik = false;
                        break;
                    }
                }
                prevLine = line;
                threshold = threshold * 1.2;
            }
            if (mightHaveChupchik)
                foundChupchikOrOpening = true;
        }
    }

    FeatureResult<Boolean> outcome = this.generateResult(foundChupchikOrOpening);
    return outcome;
}

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

@Test
public void testTrace(@NonStrict final Shape shape) {
    LineDefinitionImpl lineDef = new LineDefinitionImpl(0, 0);
    List<Integer> steps = new ArrayList<Integer>();
    steps.add(2);//from   ww w .ja  va 2 s .co m
    steps.add(3);
    lineDef.setSteps(steps);

    new NonStrictExpectations() {
        {
            shape.getHeight();
            returns(8);
            shape.getWidth();
            returns(8);
        }
    };
    BitSet bitset = new BitSet(shape.getHeight() * shape.getWidth());
    lineDef.trace(bitset, shape, 5, 2, 8, 0);

    int[] bitsetPixels = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1,
            0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0 };

    for (int x = 0; x < 8; x++)
        for (int y = 0; y < 8; y++) {
            assertEquals(bitsetPixels[y * 8 + x] == 1, bitset.get(y * 8 + x));
        }

    bitset = new BitSet(shape.getHeight() * shape.getWidth());
    lineDef.trace(bitset, shape, 1, 1, 4, 2);

    int[] bitsetPixels2 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
            0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0 };

    for (int x = 0; x < 8; x++)
        for (int y = 0; y < 8; y++) {
            assertEquals("failure at x=" + x + ",y=" + y, bitsetPixels2[y * 8 + x] == 1, bitset.get(y * 8 + x));
        }
}

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

@Test
public void testGetEnclosingRectangle(@NonStrict final Shape shape) {
    LineDefinitionImpl lineDef = new LineDefinitionImpl(0, 0);
    List<Integer> steps = new ArrayList<Integer>();
    steps.add(2);// w w w.  j av a  2 s .  c  om
    steps.add(3);
    lineDef.setSteps(steps);

    new NonStrictExpectations() {
        {
            shape.getHeight();
            returns(8);
            shape.getWidth();
            returns(8);
        }
    };

    LineSegmentImpl lineSegment = new LineSegmentImpl(shape, lineDef, 5, 2, 1, 3);
    lineSegment.setLength(4);

    BitSet rectangle = lineSegment.getEnclosingRectangle(1);

    int[] bitsetPixels = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1,
            1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0 };

    for (int x = 0; x < 8; x++)
        for (int y = 0; y < 8; y++) {
            assertEquals("x = " + x + ", y = " + y, bitsetPixels[y * 8 + x] == 1, rectangle.get(y * 8 + x));
        }

    assertEquals(3 * (lineSegment.getLength() + 1), rectangle.cardinality());
}

From source file:org.apache.hadoop.mapred.TestCombineTextInputFormat.java

@Test(timeout = 10000)
public void testFormat() throws Exception {
    JobConf job = new JobConf(defaultConf);

    Random random = new Random();
    long seed = random.nextLong();
    LOG.info("seed = " + seed);
    random.setSeed(seed);/*ww w .  ja v a2  s  . co m*/

    localFs.delete(workDir, true);
    FileInputFormat.setInputPaths(job, workDir);

    final int length = 10000;
    final int numFiles = 10;

    createFiles(length, numFiles, random);

    // create a combined split for the files
    CombineTextInputFormat format = new CombineTextInputFormat();
    LongWritable key = new LongWritable();
    Text value = new Text();
    for (int i = 0; i < 3; i++) {
        int numSplits = random.nextInt(length / 20) + 1;
        LOG.info("splitting: requesting = " + numSplits);
        InputSplit[] splits = format.getSplits(job, numSplits);
        LOG.info("splitting: got =        " + splits.length);

        // we should have a single split as the length is comfortably smaller than
        // the block size
        assertEquals("We got more than one splits!", 1, splits.length);
        InputSplit split = splits[0];
        assertEquals("It should be CombineFileSplit", CombineFileSplit.class, split.getClass());

        // check the split
        BitSet bits = new BitSet(length);
        LOG.debug("split= " + split);
        RecordReader<LongWritable, Text> reader = format.getRecordReader(split, job, voidReporter);
        try {
            int count = 0;
            while (reader.next(key, value)) {
                int v = Integer.parseInt(value.toString());
                LOG.debug("read " + v);
                if (bits.get(v)) {
                    LOG.warn("conflict with " + v + " at position " + reader.getPos());
                }
                assertFalse("Key in multiple partitions.", bits.get(v));
                bits.set(v);
                count++;
            }
            LOG.info("splits=" + split + " count=" + count);
        } finally {
            reader.close();
        }
        assertEquals("Some keys in no partition.", length, bits.cardinality());
    }
}

From source file:mastodon.algorithms.MHLinearAlgorithm.java

protected void tryPruning() {
    //choose the number of species in list to perturb based on a Poisson distributions with rate equal to variable "mean" above
    int numberToSet = 0;
    int numberToClear = 0;

    while (numberToSet < 1 || numberToSet > currPrunedSpeciesCount) {
        numberToSet = pd.sample() + 1;//from  w w w  .j a  v  a  2  s .  c o m
    }

    if (numberToSet > (bts.getTaxaCount() - currPrunedSpeciesCount)) {
        numberToSet = bts.getTaxaCount() - currPrunedSpeciesCount;
    }

    //if we are pruning by one more species now, clear one species less from the pruning list this time
    if (currPruning.cardinality() < currPrunedSpeciesCount) {
        numberToClear = numberToSet - 1;
    } else {
        numberToClear = numberToSet;
    }

    BitSet bitsToSet = new BitSet();
    BitSet bitsToClear = new BitSet();

    for (int e = 0; e < numberToSet; e++) {
        int choice = 0;
        while (true) {
            choice = (int) (Random.nextDouble() * bts.getTaxaCount());
            if (!currPruning.get(choice) && !bitsToSet.get(choice)) {
                break;
            }
        }
        bitsToSet.set(choice);
    }

    for (int e = 0; e < numberToClear; e++) {
        int choice = 0;
        while (true) {
            choice = (int) (Random.nextDouble() * bts.getTaxaCount());
            if (currPruning.get(choice) && !bitsToClear.get(choice)) {
                break;
            }
        }
        bitsToClear.set(choice);
    }

    currPruning.or(bitsToSet);
    currPruning.xor(bitsToClear);

    currScore = bts.pruneFast(currPruning);
    bts.unPrune();

}

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

@Test
public void testGetEnclosingRectangleDoubleDiagonal(@NonStrict final Shape shape) {
    LineDefinitionImpl lineDef = new LineDefinitionImpl(1, 0);
    List<Integer> steps = new ArrayList<Integer>();
    steps.add(2);/*  w w w .java  2s  . co  m*/
    lineDef.setSteps(steps);

    new NonStrictExpectations() {
        {
            shape.getHeight();
            returns(8);
            shape.getWidth();
            returns(8);
        }
    };

    LineSegmentImpl lineSegment = new LineSegmentImpl(shape, lineDef, 5, 2, 3, 6);

    lineSegment.setLength(4);

    BitSet rectangle = lineSegment.getEnclosingRectangle(1);

    int[] bitsetPixels = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1,
            1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0 };

    for (int x = 0; x < 8; x++)
        for (int y = 0; y < 8; y++) {
            assertEquals("failure at x=" + x + ",y=" + y, bitsetPixels[y * 8 + x] == 1,
                    rectangle.get(y * 8 + x));
        }
    assertEquals(3 * (lineSegment.getLength() + 1), rectangle.cardinality());
}

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

@Test
public void testGetEnclosingRectangleDiagonal(@NonStrict final Shape shape) {
    LineDefinitionImpl lineDef = new LineDefinitionImpl(0, 0);
    List<Integer> steps = new ArrayList<Integer>();
    steps.add(1);// w  w  w.  ja va2 s. c  o  m
    steps.add(2);
    lineDef.setSteps(steps);

    new NonStrictExpectations() {
        {
            shape.getHeight();
            returns(8);
            shape.getWidth();
            returns(8);
        }
    };

    LineSegmentImpl lineSegment = new LineSegmentImpl(shape, lineDef, 5, 2, 1, 5);
    lineSegment.setLength(4);

    BitSet rectangle = lineSegment.getEnclosingRectangle(1);

    int[] bitsetPixels = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1,
            1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0 };

    for (int y = 0; y < 8; y++) {
        for (int x = 0; x < 8; x++) {
            assertEquals("failure at x=" + x + ",y=" + y, bitsetPixels[y * 8 + x] == 1,
                    rectangle.get(y * 8 + x));
        }
    }
    assertEquals(3 * (lineSegment.getLength() + 1), rectangle.cardinality());
}

From source file:cascading.tap.hadoop.ZipInputFormatTest.java

public void testSplits() throws Exception {
    JobConf job = new JobConf();
    FileSystem currentFs = FileSystem.get(job);

    Path file = new Path(workDir, "test.zip");

    Reporter reporter = Reporter.NULL;/*  w w w. ja  v  a  2  s. c  o m*/

    int seed = new Random().nextInt();
    LOG.info("seed = " + seed);
    Random random = new Random(seed);
    FileInputFormat.setInputPaths(job, file);

    for (int entries = 1; entries < MAX_ENTRIES; entries += random.nextInt(MAX_ENTRIES / 10) + 1) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(byteArrayOutputStream);
        long length = 0;

        LOG.debug("creating; zip file with entries = " + entries);

        // for each entry in the zip file
        for (int entryCounter = 0; entryCounter < entries; entryCounter++) {
            // construct zip entries splitting MAX_LENGTH between entries
            long entryLength = MAX_LENGTH / entries;
            ZipEntry zipEntry = new ZipEntry("/entry" + entryCounter + ".txt");
            zipEntry.setMethod(ZipEntry.DEFLATED);
            zos.putNextEntry(zipEntry);

            for (length = entryCounter * entryLength; length < (entryCounter + 1) * entryLength; length++) {
                zos.write(Long.toString(length).getBytes());
                zos.write("\n".getBytes());
            }

            zos.flush();
            zos.closeEntry();
        }

        zos.flush();
        zos.close();

        currentFs.delete(file, true);

        OutputStream outputStream = currentFs.create(file);

        byteArrayOutputStream.writeTo(outputStream);
        outputStream.close();

        ZipInputFormat format = new ZipInputFormat();
        format.configure(job);
        LongWritable key = new LongWritable();
        Text value = new Text();
        InputSplit[] splits = format.getSplits(job, 100);

        BitSet bits = new BitSet((int) length);
        for (int j = 0; j < splits.length; j++) {
            LOG.debug("split[" + j + "]= " + splits[j]);
            RecordReader<LongWritable, Text> reader = format.getRecordReader(splits[j], job, reporter);

            try {
                int count = 0;

                while (reader.next(key, value)) {
                    int v = Integer.parseInt(value.toString());
                    LOG.debug("read " + v);

                    if (bits.get(v))
                        LOG.warn("conflict with " + v + " in split " + j + " at position " + reader.getPos());

                    assertFalse("key in multiple partitions.", bits.get(v));
                    bits.set(v);
                    count++;
                }

                LOG.debug("splits[" + j + "]=" + splits[j] + " count=" + count);
            } finally {
                reader.close();
            }
        }

        assertEquals("some keys in no partition.", length, bits.cardinality());
    }
}

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

@Test
public void testGetEnclosingRectangleIntersection(@NonStrict final Shape shape) {
    LineDefinitionImpl lineDef1 = new LineDefinitionImpl(0, 0);
    List<Integer> steps1 = new ArrayList<Integer>();
    steps1.add(2);//from   w  w  w  .j a v  a 2  s.  com
    steps1.add(3);
    lineDef1.setSteps(steps1);

    new NonStrictExpectations() {
        {
            shape.getHeight();
            returns(8);
            shape.getWidth();
            returns(8);
        }
    };

    LineSegmentImpl lineSegement1 = new LineSegmentImpl(shape, lineDef1, 5, 2, 1, 3);
    lineSegement1.setLength(4);

    LineDefinitionImpl lineDef2 = new LineDefinitionImpl(1, 0);
    List<Integer> steps2 = new ArrayList<Integer>();
    steps2.add(2);
    lineDef2.setSteps(steps2);

    LineSegmentImpl lineSegment2 = new LineSegmentImpl(shape, lineDef2, 5, 2, 3, 6);
    lineSegment2.setLength(4);

    BitSet intersection = lineSegement1.getEnclosingRectangleIntersection(lineSegment2, 1);

    int[] bitsetPixels = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1,
            1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0 };

    for (int x = 0; x < 8; x++)
        for (int y = 0; y < 8; y++) {
            assertEquals("failure at x=" + x + ",y=" + y, bitsetPixels[y * 8 + x] == 1,
                    intersection.get(y * 8 + x));
        }
}