List of usage examples for java.util BitSet set
public void set(int fromIndex, int toIndex)
From source file:org.asoem.greyfish.utils.collect.BitString.java
/** * Create a random bit string of given {@code length} where each bit is set with probability {@code p}, and not set * with probability {@code 1-p}.// w w w. j a v a 2 s .co m * * @param length the length of the bit string * @param rng the random number generator to use * @param p the probability for each bit in the new bit string to hold the value 1 * @return a new bit string */ public static BitString random(final int length, final RandomGenerator rng, final double p) { checkNotNull(rng); checkArgument(p >= 0 && p <= 1); checkArgument(length >= 0); if (length == 0) { return emptyBitSequence(); } if (p == 0.5) { return random(length, rng); // faster } final int n; if (p == 0) { n = 0; } else if (p == 1) { n = length; } else { final BinomialDistribution binomialDistribution = new BinomialDistribution(rng, length, p); n = binomialDistribution.sample(); } assert n >= 0 && n <= length : n; if (n == 0) { return zeros(length); } else if (n == length) { return ones(length); } final ContiguousSet<Integer> indexRange = ContiguousSet.create(Range.closedOpen(0, length), DiscreteDomain.integers()); final Iterable<Integer> uniqueIndexSample = Samplings.random(rng).withoutReplacement().sample(indexRange, n); if ((double) n / length < 1.0 / 32) { // < 1 bit per word? return new IndexSetString(ImmutableSortedSet.copyOf(uniqueIndexSample), length); } else { final BitSet bs = new BitSet(length); for (Integer index : uniqueIndexSample) { bs.set(index, true); } return new BitSetString(bs, length); } }
From source file:org.osgp.adapter.protocol.dlms.domain.commands.ConfigurationObjectHelperService.java
/** * Calculate the byte array for the given list of ConfigurationFlagType * objects//from w w w .j ava 2 s. com * * @param configurationFlags * List of ConfigurationFlag objects * @return byte array with MSB in first element */ public byte[] toByteArray(final List<ConfigurationFlag> configurationFlags) { final BitSet bitSet = new BitSet(NUMBER_OF_FLAG_BITS); for (final ConfigurationFlag configurationFlag : configurationFlags) { if (configurationFlag.isEnabled()) { bitSet.set(this.toBitPosition(configurationFlag.getConfigurationFlagType()), true); } } final byte[] byteArray = bitSet.toByteArray(); // swap 0 and 1 final byte tmp = byteArray[1]; byteArray[1] = byteArray[0]; byteArray[0] = tmp; return byteArray; }
From source file:org.apache.metron.stellar.common.utils.hashing.tlsh.TLSHHasher.java
public Map<String, String> bin(String hash) throws DecoderException { Random r = new Random(0); byte[] h = Hex.decodeHex(hash.substring(2 * checksumOption.getChecksumLength()).toCharArray()); BitSet vector = BitSet.valueOf(h); int n = vector.length(); Map<String, String> ret = new HashMap<>(); boolean singleHash = hashes.size() == 1; for (int numHashes : hashes) { BitSet projection = new BitSet(); for (int i = 0; i < numHashes; ++i) { int index = r.nextInt(n); projection.set(i, vector.get(index)); }// w ww . j a v a2s . c o m String outputHash = numHashes + Hex.encodeHexString(projection.toByteArray()); if (singleHash) { ret.put(TLSH_BIN_KEY, outputHash); } else { ret.put(TLSH_BIN_KEY + "_" + numHashes, outputHash); } } return ret; }
From source file:com.joliciel.jochre.graphics.VectorizerImplTest.java
@Test public void testArrayListize(@NonStrict final Shape shape, @NonStrict final JochreImage image) { final int threshold = 100; final int whiteGapFillFactor = 5; new NonStrictExpectations() { {/*from w ww . j a v a 2 s. c o m*/ shape.getHeight(); returns(8); shape.getWidth(); returns(8); shape.getJochreImage(); returns(image); image.getBlackThreshold(); returns(threshold); int[] pixels = { 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0 }; for (int x = -1; x <= 8; x++) for (int y = -1; y <= 8; y++) { shape.isPixelBlack(x, y, threshold, whiteGapFillFactor); if (x >= 0 && x < 8 && y >= 0 && y < 8) returns(pixels[y * 8 + x] == 1); else returns(false); } int[] outlinePixels = { 0, 1, 1, 0, 0, 1, 1, 1, // row 0 0, 1, 0, 1, 0, 1, 0, 1, // row 1 0, 0, 1, 1, 0, 0, 1, 1, // row 2 0, 0, 1, 1, 0, 1, 1, 0, // row 3 0, 0, 0, 1, 1, 0, 1, 0, // row 4 0, 0, 0, 1, 0, 1, 0, 0, // row 5 0, 0, 1, 0, 1, 0, 0, 0, // row 6 1, 1, 1, 1, 1, 0, 0, 0, // row 7 }; BitSet outline = new BitSet(); for (int i = 0; i < 8 * 8; i++) outline.set(i, outlinePixels[i] == 1); shape.getOutline(threshold); returns(outline); } }; VectorizerImpl vectorizer = new VectorizerImpl(); GraphicsServiceInternal graphicsService = new GraphicsServiceImpl(); vectorizer.setGraphicsService(graphicsService); vectorizer.setWhiteGapFillFactor(whiteGapFillFactor); List<LineSegment> lines = vectorizer.vectorize(shape); int i = 0; for (LineSegment lineSegment : lines) { double slope = (double) (lineSegment.getEndY() - lineSegment.getStartY()) / (double) (lineSegment.getEndX() - lineSegment.getStartX()); LOG.debug("Line " + i++ + "(" + lineSegment.getStartX() + "," + lineSegment.getStartY() + ") " + "(" + lineSegment.getEndX() + "," + lineSegment.getEndY() + "). Length = " + lineSegment.getLength() + ", Slope = " + slope); } }
From source file:org.lockss.util.NumberUtil.java
/** * Increment an alphabetical string by the given delta, considering the string * to represent a value in base-26 using the characters a-z or A-Z - the * string is treated case-insensitively. For example, with a delta of 1: * <ul>/*from w w w . jav a 2 s.c o m*/ * <li>aaa to aab</li> * <li>aaz to aba</li> * <li>zzy to zzz</li> * <li>zyz to zza</li> * </ul> * <p> * Note that after 'z' comes 'ba', because 'a' corresponds to 0 and is so * every number is implicitly preceded by 'a'. This may not be what is desired * for some sequences, in which case this may need to be adapted. * <p> * The string is lower cased before the increment is applied, and then each * character position that was upper case in the original string is upper * cased before returning. An exception will be thrown if any character is * outside of a-z after lower casing. If the value limit for the string length * is reached, the returned string will be longer; the extra characters will * be lower cased, which may be unwanted. * * @param s a purely alphabetical string * @return a string incremented according to base-26 * @throws NumberFormatException if the string contains inappropriate characters or cannot be incremented */ public static String incrementBase26String(String s, int delta) throws NumberFormatException { // Track the case of each character, so we can reset them before returning BitSet cases = new BitSet(); for (int i = 0; i < s.length(); i++) { cases.set(i, Character.isUpperCase(s.charAt(i))); } // Convert, increment, convert back String res = toBase26(fromBase26(s.toLowerCase()) + delta); // Pad the string to the correct length with 'a' res = StringUtils.leftPad(res, s.length(), 'a'); // Re-case the chars - using an offset in case the new string is longer char[] carr = res.toCharArray(); int offset = carr.length - s.length(); for (int pos = 0; pos < s.length(); pos++) { if (cases.get(pos)) carr[offset + pos] = Character.toUpperCase(carr[offset + pos]); } return new String(carr); }
From source file:org.lockss.util.NumberUtil.java
/** * Construct an alphabetical (base-26) sequence by incrementing the first * string alphabetically until it reaches the second string. The start string * is incremented by the given delta; if the delta does not divide into the * Levenstein distance between the start and end strings, an exception is * thrown. The strings must also be the same length. * <p>//from w w w. ja v a 2 s . c o m * The string is lower cased before the increment is applied, and then each * character position that was upper case in the original string is upper * cased in the resulting string. It is assumed that the two strings are * capitalised in the same pattern. An exception will be thrown if any * character is outside of a-z after lower casing. * * @param start an alphabetical string (case-insensitive) * @param end an alphabetical string (case-insensitive) * @param delta the increment between strings in the sequence; can be negative * @return a list of strings representing a sequence from <tt>start</tt> to <tt>end</tt> * @throws IllegalArgumentException if the delta does not divide into the gap or the strings are different lengths */ public static List<String> constructAlphabeticSequence(final String start, final String end, int delta) throws IllegalArgumentException { // Ensure the delta is positive if (delta == 0) throw new IllegalArgumentException("Delta cannot be 0."); // If the strings are equal, the sequence will be the single string if (start.equals(end)) return new ArrayList<String>() { { add(start); } }; // Check the string lengths are the same if (start.length() != end.length()) throw new IllegalArgumentException( String.format("Start and end strings are different lengths: %s %s.", start, end)); // Find the integer distance int distance = Math.abs(fromBase26(start) - fromBase26(end)); //int distance = StringUtils.getLevenshteinDistance(start, end); // Check the delta divides into the gap if (distance % delta != 0) { throw new IllegalArgumentException(String.format( "The distance %s between start and end must be " + "divisible by delta %s.", distance, delta)); } // Track the case of each character, so we can reset them before returning BitSet cases = new BitSet(start.length()); for (int i = 0; i < start.length(); i++) { cases.set(i, Character.isUpperCase(start.charAt(i))); } // Increment alphabetically List<String> seq = new ArrayList<String>(); int[] nums = constructSequence(fromBase26(start), fromBase26(end), delta); for (int i = 0; i < nums.length; i++) { String s = toBase26(nums[i]); // Pad the string to the correct length with 'a' s = StringUtils.leftPad(s, start.length(), 'a'); // Re-case the chars char[] carr = s.toCharArray(); for (int pos = 0; pos < cases.length(); pos++) { if (cases.get(pos)) carr[pos] = Character.toUpperCase(carr[pos]); } seq.add(new String(carr)); } return seq; }
From source file:org.osgp.adapter.protocol.dlms.domain.commands.SetAlarmNotificationsCommandExecutor.java
public long alarmFilterLongValue(final AlarmNotifications alarmNotifications) { final BitSet bitSet = new BitSet(NUMBER_OF_BITS_IN_ALARM_FILTER); final Set<AlarmNotification> notifications = alarmNotifications.getAlarmNotifications(); for (final AlarmNotification alarmNotification : notifications) { bitSet.set(alarmRegisterBitIndexPerAlarmType.get(alarmNotification.getAlarmType()), alarmNotification.isEnabled()); }//w w w . j ava 2 s. co m return bitSet.toLongArray()[0]; }
From source file:com.opengamma.analytics.financial.model.volatility.smile.fitting.SABRNonLinearLeastSquareFitter.java
public LeastSquareResultsWithTransform getFitResult(final EuropeanVanillaOption[] options, final BlackFunctionData[] data, final double[] errors, final double[] initialFitParameters, final BitSet fixed, final double atmVol, final boolean recoverATMVol) { testData(options, data, errors, initialFitParameters, fixed, N_PARAMETERS); if (recoverATMVol) { Validate.isTrue(atmVol > 0.0, "ATM volatility must be > 0"); fixed.set(0, true); }/*w w w . j av a 2 s . c o m*/ final int n = options.length; final double[] strikes = new double[n]; final double[] blackVols = new double[n]; final double maturity = options[0].getTimeToExpiry(); final double forward = data[0].getForward(); strikes[0] = options[0].getStrike(); blackVols[0] = data[0].getBlackVolatility(); for (int i = 1; i < n; i++) { Validate.isTrue(CompareUtils.closeEquals(options[i].getTimeToExpiry(), maturity), "All options must have the same maturity " + maturity + "; have one with maturity " + options[i].getTimeToExpiry()); strikes[i] = options[i].getStrike(); blackVols[i] = data[i].getBlackVolatility(); } final UncoupledParameterTransforms transforms = new UncoupledParameterTransforms( new DoubleMatrix1D(initialFitParameters), TRANSFORMS, fixed); final EuropeanVanillaOption atmOption = new EuropeanVanillaOption(forward, maturity, true); final ParameterizedFunction<Double, DoubleMatrix1D, Double> function = new ParameterizedFunction<Double, DoubleMatrix1D, Double>() { @SuppressWarnings("synthetic-access") @Override public Double evaluate(final Double strike, final DoubleMatrix1D fp) { final DoubleMatrix1D mp = transforms.inverseTransform(fp); double alpha = mp.getEntry(0); final double beta = mp.getEntry(1); final double rho = mp.getEntry(2); final double nu = mp.getEntry(3); final SABRFormulaData sabrFormulaData; if (recoverATMVol) { alpha = _atmCalculator.calculate(new SABRFormulaData(alpha, beta, rho, nu), atmOption, forward, atmVol); sabrFormulaData = new SABRFormulaData(alpha, beta, rho, nu); } else { sabrFormulaData = new SABRFormulaData(alpha, beta, rho, nu); } final EuropeanVanillaOption option = new EuropeanVanillaOption(strike, maturity, true); return _formula.getVolatilityFunction(option, forward).evaluate(sabrFormulaData); } }; final DoubleMatrix1D fp = transforms.transform(new DoubleMatrix1D(initialFitParameters)); LeastSquareResults lsRes = errors == null ? SOLVER.solve(new DoubleMatrix1D(strikes), new DoubleMatrix1D(blackVols), function, fp) : SOLVER.solve(new DoubleMatrix1D(strikes), new DoubleMatrix1D(blackVols), new DoubleMatrix1D(errors), function, fp); final double[] mp = transforms.inverseTransform(lsRes.getFitParameters()).toArray(); if (recoverATMVol) { final double beta = mp[1]; final double nu = mp[2]; final double rho = mp[3]; final EuropeanVanillaOption option = new EuropeanVanillaOption(forward, maturity, true); final SABRFormulaData sabrFormulaData = new SABRFormulaData(mp[0], beta, rho, nu); final double value = _atmCalculator.calculate(sabrFormulaData, option, forward, atmVol); mp[0] = value; lsRes = new LeastSquareResults(lsRes.getChiSq(), new DoubleMatrix1D(mp), lsRes.getCovariance()); } return new LeastSquareResultsWithTransform(lsRes, transforms); //return new LeastSquareResults(lsRes.getChiSq(), new DoubleMatrix1D(mp), new DoubleMatrix2D(new double[N_PARAMETERS][N_PARAMETERS]), lsRes.getFittingParameterSensitivityToData()); }
From source file:com.indeed.lsmtree.core.TestStore.java
public void testStore(StorageType storageType, CompressionCodec codec) throws Exception { File indexDir = new File(tmpDir, "index"); indexDir.mkdirs();//from w ww . ja v a2 s. c o m File indexLink = new File(tmpDir, "indexlink"); PosixFileOperations.link(indexDir, indexLink); File storeDir = new File(indexLink, "store"); Store<Integer, Long> store = new StoreBuilder<Integer, Long>(storeDir, new IntSerializer(), new LongSerializer()).setMaxVolatileGenerationSize(8 * 1024 * 1024).setStorageType(storageType) .setCodec(codec).build(); final Random r = new Random(0); final int[] ints = new int[treeSize]; for (int i = 0; i < ints.length; i++) { ints[i] = r.nextInt(); } for (final int i : ints) { store.put(i, (long) i); assertTrue(store.get(i) == i); } for (final int i : ints) { assertTrue(store.get(i) == i); } store.close(); store.waitForCompactions(); store = new StoreBuilder<Integer, Long>(storeDir, new IntSerializer(), new LongSerializer()) .setMaxVolatileGenerationSize(8 * 1024 * 1024).setStorageType(storageType).setCodec(codec).build(); Arrays.sort(ints); Iterator<Store.Entry<Integer, Long>> iterator = store.iterator(); int index = 0; while (iterator.hasNext()) { Store.Entry<Integer, Long> next = iterator.next(); int current = ints[index]; assertTrue(next.getKey() == ints[index]); assertTrue(next.getValue() == ints[index]); while (index < ints.length && ints[index] == current) { index++; } } assertTrue(index == ints.length); final BitSet deleted = new BitSet(); for (int i = 0; i < ints.length / 10; i++) { int deletionIndex = r.nextInt(ints.length); deleted.set(deletionIndex, true); for (int j = deletionIndex - 1; j >= 0; j--) { if (ints[j] == ints[deletionIndex]) { deleted.set(j, true); } else { break; } } for (int j = deletionIndex + 1; j < ints.length; j++) { if (ints[j] == ints[deletionIndex]) { deleted.set(j, true); } else { break; } } store.delete(ints[deletionIndex]); assertNull(store.get(ints[deletionIndex])); } iterator = store.iterator(); index = 0; while (iterator.hasNext()) { Store.Entry<Integer, Long> next = iterator.next(); while (deleted.get(index)) index++; int current = ints[index]; assertTrue(next.getKey() == ints[index]); assertTrue(next.getValue() == ints[index]); while (index < ints.length && ints[index] == current) { index++; } } while (deleted.get(index)) index++; assertTrue(index == ints.length); final int max = ints[ints.length - 1]; final AtomicInteger done = new AtomicInteger(8); for (int i = 0; i < done.get(); i++) { final int thread = i; final Store<Integer, Long> finalStore = store; new Thread(new Runnable() { @Override public void run() { try { Random r = new Random(thread); for (int i = 0; i < treeSize; i++) { int rand = r.nextInt(); int insertionindex = Arrays.binarySearch(ints, rand); Store.Entry<Integer, Long> next = finalStore.ceil(rand); boolean found = next != null; if (insertionindex >= 0 && deleted.get(insertionindex)) { assertNull(finalStore.get(ints[insertionindex])); } else { assertTrue(found == (rand <= max)); if (found) { assertTrue(next.getKey() >= rand); assertTrue(next.getKey().longValue() == next.getValue()); if (insertionindex >= 0) { assertTrue(rand == ints[insertionindex]); assertTrue(next.getKey() == rand); Long result = finalStore.get(rand); assertTrue(result == rand); } else { int nextIndex = ~insertionindex; while (deleted.get(nextIndex) && nextIndex < ints.length) nextIndex++; if (nextIndex < ints.length) { if (insertionindex != -1) assertTrue(ints[(~insertionindex) - 1] < rand); assertTrue(ints[nextIndex] + " != " + next.getKey(), ints[nextIndex] == next.getKey()); } Long result = finalStore.get(rand); assertTrue(result == null); } } } } } catch (IOException e) { throw new RuntimeException(e); } finally { done.decrementAndGet(); } } }).start(); } while (done.get() > 0) { Thread.yield(); } store.close(); }
From source file:com.rockagen.commons.util.CommUtil.java
/** * Create a BitSet instance,start index is 0 * <p>//from w w w . jav a2 s .c om * example: * </p> * <pre> * byte: 50 * binary: 0b110010 * * +--------+---+---+---+---+---+---+---+---+ * | bits | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | * +--------+---+---+---+---+---+---+---+---+ * | bitset | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | * +--------+---+---+---+---+---+---+-------+ * * bitSet.toString(): {2, 3, 6} * </pre> * * @param bytes bytes * @return bitSet */ public static BitSet bitSet(byte[] bytes) { if (bytes == null) { return null; } BitSet bit = new BitSet(); int index = 0; for (byte aByte : bytes) { for (int j = 7; j >= 0; j--) { bit.set(index++, (aByte & (1 << j)) >>> j == 1); } } return bit; }