Example usage for com.google.common.collect Range closedOpen

List of usage examples for com.google.common.collect Range closedOpen

Introduction

In this page you can find the example usage for com.google.common.collect Range closedOpen.

Prototype

public static <C extends Comparable<?>> Range<C> closedOpen(C lower, C upper) 

Source Link

Document

Returns a range that contains all values greater than or equal to lower and strictly less than upper .

Usage

From source file:com.google.googlejavaformat.java.Formatter.java

/**
 * Converts zero-indexed, [closed, open) line ranges in the given source file to character ranges.
 *//*from ww w  .j a v a 2s  . c  om*/
public static RangeSet<Integer> lineRangesToCharRanges(String input, RangeSet<Integer> lineRanges) {
    List<Integer> lines = new ArrayList<>();
    Iterators.addAll(lines, Newlines.lineOffsetIterator(input));
    lines.add(input.length() + 1);

    final RangeSet<Integer> characterRanges = TreeRangeSet.create();
    for (Range<Integer> lineRange : lineRanges.subRangeSet(Range.closedOpen(0, lines.size() - 1)).asRanges()) {
        int lineStart = lines.get(lineRange.lowerEndpoint());
        // Exclude the trailing newline. This isn't strictly necessary, but handling blank lines
        // as empty ranges is convenient.
        int lineEnd = lines.get(lineRange.upperEndpoint()) - 1;
        Range<Integer> range = Range.closedOpen(lineStart, lineEnd);
        characterRanges.add(range);
    }
    return characterRanges;
}

From source file:it.units.malelab.ege.ge.mapper.HierarchicalMapper.java

public Node<T> mapRecursively(T symbol, Range<Integer> range, BitsGenotype genotype, int[] bitUsages)
        throws MappingException {
    Node<T> node = new Node<>(symbol);
    if (grammar.getRules().keySet().contains(symbol)) {
        //a non-terminal node
        //update usage
        for (int i = range.lowerEndpoint(); i < range.upperEndpoint(); i++) {
            bitUsages[i] = bitUsages[i] + 1;
        }//from   ww w. ja va 2 s. c  om
        List<List<T>> options = grammar.getRules().get(symbol);
        //get option
        List<T> symbols;
        if ((range.upperEndpoint() - range.lowerEndpoint()) < options.size()) {
            int count = (range.upperEndpoint() - range.lowerEndpoint() > 0) ? genotype.slice(range).count()
                    : genotype.count();
            int index = shortestOptionIndexesMap.get(symbol)
                    .get(count % shortestOptionIndexesMap.get(symbol).size());
            symbols = options.get(index);
        } else {
            symbols = chooseOption(genotype, range, options);
            for (int i = range.lowerEndpoint(); i < range.upperEndpoint(); i++) {
                bitUsages[i] = bitUsages[i] + 1;
            }
        }
        //add children
        List<Range<Integer>> childRanges = getChildrenSlices(range, symbols);
        for (int i = 0; i < symbols.size(); i++) {
            Range<Integer> childRange = childRanges.get(i);
            if (childRanges.get(i).equals(range)
                    && (childRange.upperEndpoint() - childRange.lowerEndpoint() > 0)) {
                childRange = Range.closedOpen(range.lowerEndpoint(), range.upperEndpoint() - 1);
                childRanges.set(i, childRange);
            }
        }
        for (int i = 0; i < symbols.size(); i++) {
            node.getChildren().add(mapRecursively(symbols.get(i), childRanges.get(i), genotype, bitUsages));
        }
    }
    return node;
}

From source file:com.google.cloud.genomics.dataflow.pipelines.AnnotateVariants.java

private ListMultimap<Range<Long>, Annotation> retrieveVariantAnnotations(Genomics genomics,
        StreamVariantsRequest request) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    ListMultimap<Range<Long>, Annotation> annotationMap = ArrayListMultimap.create();
    Iterable<Annotation> annotationIter = Paginator.Annotations
            .create(genomics, ShardBoundary.Requirement.OVERLAPS)
            .search(new SearchAnnotationsRequest().setAnnotationSetIds(variantAnnotationSetIds)
                    .setReferenceName(canonicalizeRefName(request.getReferenceName()))
                    .setStart(request.getStart()).setEnd(request.getEnd()));
    for (Annotation annotation : annotationIter) {
        long start = 0;
        if (annotation.getStart() != null) {
            start = annotation.getStart();
        }/*w ww  .j a va2 s  .  c  o m*/
        annotationMap.put(Range.closedOpen(start, annotation.getEnd()), annotation);
    }
    LOG.info(String.format("read %d variant annotations in %s (%.2f / s)", annotationMap.size(), stopwatch,
            (double) annotationMap.size() / stopwatch.elapsed(TimeUnit.SECONDS)));
    return annotationMap;
}

From source file:edu.mit.streamjit.impl.compiler2.Storage.java

/**
 * Returns a range spanning the indices read from this storage during an
 * execution of the given schedule. (Note that, as a span, not every
 * contained index will be read.) The returned range will be
 * {@link Range#canonical(com.google.common.collect.DiscreteDomain) canonical}.
 * The range is not cached so as to be responsive to changes in input index
 * functions.//from   w  ww  .ja va2 s  .  c o m
 * @param externalSchedule the schedule
 * @return a range spanning the indices read during the given schedule under
 * the current index functions
 * @see #readIndices(java.util.Map)
 */
public Range<Integer> readIndexSpan(Map<ActorGroup, Integer> externalSchedule) {
    int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
    for (Actor a : downstream()) {
        int maxIteration = a.group().schedule().get(a) * externalSchedule.get(a.group()) - 1;
        if (maxIteration >= 0)
            for (int input = 0; input < a.inputs().size(); ++input)
                if (a.inputs().get(input).equals(this) && (a.peek(input).max() > 0 || a.pop(input).max() > 0)) {
                    min = Math.min(min, a.translateInputIndex(input, a.peeks(input, 0).first()));
                    max = Math.max(max, a.translateInputIndex(input, a.peeks(input, maxIteration).last()));
                }
    }
    Range<Integer> range = (min != Integer.MAX_VALUE ? Range.closed(min, max) : Range.closedOpen(0, 0));
    return range.canonical(DiscreteDomain.integers());
}

From source file:edu.mit.streamjit.impl.compiler2.Actor.java

/**
 * Returns the logical indices pushed to the given output during the given
 * iterations./*  w w w  .ja  v a2  s.  c  o  m*/
 * @param output the output index
 * @param iterations the iteration numbers
 * @return the logical indices pushed to the given input during the given
 * iterations
 */
public ContiguousSet<Integer> pushes(int output, ContiguousSet<Integer> iterations) {
    if (iterations.isEmpty())
        return ContiguousSet.create(Range.closedOpen(0, 0), DiscreteDomain.integers());
    return ContiguousSet.create(Range.closedOpen(iterations.first() * push(output).max(),
            (iterations.last() + 1) * push(output).max()), DiscreteDomain.integers());
}

From source file:it.units.malelab.ege.util.Utils.java

public static List<Range<Integer>> slices(Range<Integer> range, List<Integer> sizes) {
    int length = range.upperEndpoint() - range.lowerEndpoint();
    int sumOfSizes = 0;
    for (int size : sizes) {
        sumOfSizes = sumOfSizes + size;//  w  w w .j a v a 2 s  . c  o m
    }
    if (sumOfSizes > length) {
        List<Integer> originalSizes = new ArrayList<>(sizes);
        sizes = new ArrayList<>(sizes.size());
        int oldSumOfSizes = sumOfSizes;
        sumOfSizes = 0;
        for (int originalSize : originalSizes) {
            int newSize = (int) Math.round((double) originalSize / (double) oldSumOfSizes);
            sizes.add(newSize);
            sumOfSizes = sumOfSizes + newSize;
        }
    }
    int minSize = (int) Math.floor((double) length / (double) sumOfSizes);
    int missing = length - minSize * sumOfSizes;
    int[] rangeSize = new int[sizes.size()];
    for (int i = 0; i < rangeSize.length; i++) {
        rangeSize[i] = minSize * sizes.get(i);
    }
    int c = 0;
    while (missing > 0) {
        rangeSize[c % rangeSize.length] = rangeSize[c % rangeSize.length] + 1;
        c = c + 1;
        missing = missing - 1;
    }
    List<Range<Integer>> ranges = new ArrayList<>(sizes.size());
    int offset = range.lowerEndpoint();
    for (int i = 0; i < rangeSize.length; i++) {
        ranges.add(Range.closedOpen(offset, offset + rangeSize[i]));
        offset = offset + rangeSize[i];
    }
    return ranges;
}

From source file:edu.mit.streamjit.impl.compiler2.Storage.java

/**
 * Returns the indices written in this storage during an execution of the
 * given schedule.  The returned set is not cached so as to be responsive
 * to changes in output index functions.
 * @param externalSchedule the schedule/*from   www . j av a 2s .com*/
 * @return the indices written during the given schedule under the current
 * index functions
 * @see #writeIndexSpan(java.util.Map)
 */
public ImmutableSortedSet<Integer> writeIndices(Map<ActorGroup, Integer> externalSchedule) {
    ImmutableSortedSet.Builder<Integer> builder = ImmutableSortedSet.naturalOrder();
    for (Actor a : upstream())
        builder.addAll(a.writes(this,
                Range.closedOpen(0, a.group().schedule().get(a) * externalSchedule.get(a.group()))));
    return builder.build();
}

From source file:com.tinspx.util.io.callbacks.FileChannelCallback.java

/**
 * Normalizes lower bound to a closed bound type (if exists) and the
 * upper bound to an open bound type (if exists). Missing bounds remain
 * missing. Lower bound must be non-negative and upper bound must be
 * positive. The range cannot be empty./*from w ww. j  a v  a2 s .  c  o  m*/
 */
static Range<Long> checkAndNormalize(Range<Long> range) {
    checkArgument(!range.isEmpty(), "range %s is empty", range);
    boolean make = false;
    long lower = -1;
    long upper = -1;

    if (range.hasLowerBound()) {
        lower = range.lowerEndpoint();
        if (range.lowerBoundType() == BoundType.OPEN) {
            make = true;
            lower++;
        }
        checkArgument(lower >= 0, "closed lower bound (%s) may not be negative", lower);
    }
    if (range.hasUpperBound()) {
        upper = range.upperEndpoint();
        if (range.upperBoundType() == BoundType.CLOSED) {
            make = true;
            upper++;
        }
        checkArgument(upper > 0, "open upper bound (%s) must be positive", upper);
    }
    if (make) {
        if (lower >= 0) {
            if (upper > 0) {
                range = Range.closedOpen(lower, upper);
            } else {
                range = Range.atLeast(lower);
            }
        } else {
            assert upper > 0 : upper;
            range = Range.lessThan(upper);
        }
        checkArgument(!range.isEmpty(), "normalized range %s is empty", range);
    }
    return range;
}

From source file:com.github.fauu.helix.system.PlayerMovementSystem.java

private boolean coordsInsideArea(IntVector2 coords, Entity area) {
    IntVector2 areaDimensions = dimensionsMapper.get(area).get();

    return (Range.closedOpen(0, areaDimensions.x).contains(coords.x)
            && Range.closedOpen(0, areaDimensions.y).contains(coords.y));
}

From source file:com.noodlewiz.xjavab.core.Connection.java

/**
 * Allocates an XID (resource identifier) for a new object.
 * /*from  w  ww . jav a  2s.c o  m*/
 * @return An XID
 */
public long genXid() {
    synchronized (mXidsLock) {
        if (!mXids.hasNext()) {
            // Ask for more XIDs from XC_MISC.
            try {
                final GetXIDRangeReply reply = XCMisc.getXIDRange(this).getReply();
                final long start = reply.startId;
                final long end = start + reply.count;
                final Iterable<Long> ids = ContiguousSet.create(Range.closedOpen(start, end),
                        DiscreteDomain.longs());
                mXids = ids.iterator();
            } catch (final InterruptedException e) {
                mLogger.error("Interrupted while retrieving XIDs.", e);
                System.exit(1);
            } catch (final RuntimeException e) {
                mLogger.error("Unable to allocate more XID.");
                throw e;
            }
        }

        return mXids.next();
    }
}