Example usage for com.google.common.collect RangeSet asRanges

List of usage examples for com.google.common.collect RangeSet asRanges

Introduction

In this page you can find the example usage for com.google.common.collect RangeSet asRanges.

Prototype

Set<Range<C>> asRanges();

Source Link

Document

Returns a view of the Range#isConnected disconnected ranges that make up this range set.

Usage

From source file:org.mskcc.shenkers.data.interval.RangeTools.java

public static RangeSet<Integer> asClosed(RangeSet<Integer> s) {
    RangeSet<Integer> closedIntervalSet = TreeRangeSet.create();
    for (Range<Integer> r : s.asRanges()) {
        closedIntervalSet.add(asClosed(r));
    }/*from w  ww . jav  a 2  s  .co m*/
    return closedIntervalSet;
}

From source file:io.v.todos.persistence.syncbase.DigitMappings.java

/**
 * Constructs a {@link DigitMapping} from a {@link RangeSet}, ordering the ranges in ascending
 * order (regardless of input order). If out-of-order ranges are desired, use the
 * {@link #fromRanges(Iterable)} factory method instead to provide explicit ordering.
 *//*from   ww w .ja  v  a2 s .  co m*/
public static DigitMapping fromRangeSet(RangeSet<Character> spec) {
    return fromRanges(
            Collections2.transform(spec.asRanges(), new Function<Range<Character>, ContiguousSet<Character>>() {
                @Override
                public ContiguousSet<Character> apply(Range<Character> input) {
                    return ContiguousSet.create(input, DOMAIN);
                }
            }));
}

From source file:io.druid.sql.calcite.filtration.RangeSets.java

public static List<Interval> toIntervals(final RangeSet<Long> rangeSet) {
    final List<Interval> retVal = Lists.newArrayList();

    for (Range<Long> range : rangeSet.asRanges()) {
        final long start;
        final long end;

        if (range.hasLowerBound()) {
            final long millis = range.lowerEndpoint();
            start = millis + (range.lowerBoundType() == BoundType.OPEN ? 1 : 0);
        } else {/* w ww  . j  a v  a  2 s.c o m*/
            start = Filtration.eternity().getStartMillis();
        }

        if (range.hasUpperBound()) {
            final long millis = range.upperEndpoint();
            end = millis + (range.upperBoundType() == BoundType.OPEN ? 0 : 1);
        } else {
            end = Filtration.eternity().getEndMillis();
        }

        retVal.add(Intervals.utc(start, end));
    }

    return retVal;
}

From source file:com.google.devtools.javatools.transform.StringUtil.java

/**
 * Strips the given ranges from {@code text}.
 *///from   w w  w  .j  a v a 2 s .c  o  m
public static final String stripRanges(String text, RangeSet<Integer> rangesToRemove) {
    StringBuilder contentBuilder = new StringBuilder(text);
    // Delete the ranges.  Go from last to first to avoid having to
    // compute the offsets.
    List<Range<Integer>> ranges = Lists.newArrayList(rangesToRemove.asRanges());
    Collections.reverse(ranges);
    for (Range<Integer> range : ranges) {
        contentBuilder.delete(range.lowerEndpoint(), range.upperEndpoint());
    }
    return contentBuilder.toString();
}

From source file:org.apache.james.imap.api.message.UidRange.java

private static LinkedList<Range<MessageUid>> mergeContiguousRanges(RangeSet<MessageUid> rangeSet) {
    LinkedList<Range<MessageUid>> mergedRanges = new LinkedList<Range<MessageUid>>();

    for (Range<MessageUid> range : rangeSet.asRanges()) {
        Range<MessageUid> previous = mergedRanges.peekLast();
        if (rangesShouldBeMerged(range, previous)) {
            replaceLastRange(mergedRanges, mergeRanges(range, previous));
        } else {/*from   w  w  w  .  j a  va2  s  . com*/
            mergedRanges.add(range);
        }
    }
    return mergedRanges;
}

From source file:com.jeffreybosboom.lyne.Effector.java

public static Pair<Puzzle, ImmutableMap<Node, Region.Point>> parseImage(BufferedImage image) {
    ImmutableSet<Region> regions = Region.connectedComponents(image, Colors.LYNE_COLORS);
    List<Region> nodeRegions = regions.stream().filter(r -> Colors.NODE_COLORS.keySet().contains(r.color()))
            .collect(Collectors.toList());
    //terminal markers and pips are inside node regions, so must be smaller
    int maxSize = nodeRegions.stream().mapToInt(r -> r.points().size()).max().getAsInt();
    List<Region> terminalRegions = regions.stream().filter(r -> r.points().size() < maxSize)
            .filter(r -> r.color() == Colors.TERMINAL_CENTER).collect(Collectors.toList());
    List<Region> pipRegions = regions.stream().filter(r -> r.points().size() < maxSize)
            .filter(r -> r.color() == Colors.PIP).collect(Collectors.toList());

    RangeSet<Integer> rowRanges = TreeRangeSet.create();
    nodeRegions.stream().map(Region::centroid).mapToInt(Region.Point::y)
            .mapToObj(i -> Range.closed(i - TOLERANCE, i + TOLERANCE)).forEachOrdered(rowRanges::add);
    List<Range<Integer>> rows = rowRanges.asRanges().stream().collect(Collectors.toList());
    RangeSet<Integer> colRanges = TreeRangeSet.create();
    nodeRegions.stream().map(Region::centroid).mapToInt(Region.Point::x)
            .mapToObj(i -> Range.closed(i - TOLERANCE, i + TOLERANCE)).forEachOrdered(colRanges::add);
    List<Range<Integer>> cols = colRanges.asRanges().stream().collect(Collectors.toList());

    Node[][] puzzle = new Node[rows.size()][cols.size()];
    ImmutableMap.Builder<Node, Region.Point> mapBuilder = ImmutableMap.builder();
    for (Region r : nodeRegions) {
        Region.Point c = r.centroid();
        Rectangle b = r.boundingBox();
        int row = rows.indexOf(rowRanges.rangeContaining(c.y()));
        int col = cols.indexOf(colRanges.rangeContaining(c.x()));
        Node.Kind kind = Colors.NODE_COLORS.get(r.color());
        Node node;//from w  w w  .j a  va2  s.c  o m
        if (kind == Node.Kind.OCTAGON) {
            int pips = (int) pipRegions.stream().filter(p -> b.contains(p.boundingBox())).count();
            node = Node.octagon(row, col, pips);
        } else {
            boolean terminal = terminalRegions.stream().anyMatch(t -> b.contains(t.boundingBox()));
            node = terminal ? Node.terminal(row, col, kind) : Node.nonterminal(row, col, kind);
        }
        puzzle[row][col] = node;
        mapBuilder.put(node, c);
    }
    return new Pair<>(new Puzzle(puzzle), mapBuilder.build());
}

From source file:com.rockhoppertech.music.examples.Guava.java

public static void goofaround() {
    MIDITrack track = MIDITrackBuilder.create().noteString("C D E").sequential().build();

    // http://docs.guava-libraries.googlecode.com/git-history/release12/javadoc/com/google/common/collect/FluentIterable.html#filter(com.google.common.base.Predicate)

    ImmutableList<MIDINote> notes = FluentIterable.from(track).transform(new AddFunction(1)).limit(10).toList();

    for (MIDINote note : notes) {
        logger.debug("{}", note);
    }/*from w  ww.ja  va  2 s  .  c o  m*/

    RangeSet<Double> rangeSet = TreeRangeSet.create();
    rangeSet.add(Range.closed(1d, 10d));
    rangeSet.add(Range.closed(11d, 20d));
    for (Range<Double> r : rangeSet.asRanges()) {
        logger.debug("{}", r);
    }
    logger.debug("span {}", rangeSet.span());
    logger.debug("contains {}", rangeSet.contains(20d));
    logger.debug("contains {}", rangeSet.contains(20.1));

}

From source file:org.dishevelled.bio.align.Alignments.java

/**
 * Return the sum of lengths of the specified ranges, after merging overlapping ranges.
 *
 * @param ranges ranges, must not be null, must not contain any null ranges, and all ranges must be [closed, open)
 * @return the sum of lengths of the specified ranges, after merging overlapping ranges
 *///from   w ww  .j  ava  2 s.  c o  m
public static long length(final Iterable<Range<Long>> ranges) {
    checkNotNull(ranges);
    RangeSet<Long> rangeSet = TreeRangeSet.create();
    for (Range<Long> range : ranges) {
        rangeSet.add(range);
    }
    long length = 0L;
    for (Range<Long> range : rangeSet.asRanges()) {
        length += length(range);
    }
    return length;
}

From source file:org.apache.druid.sql.calcite.filtration.CombineAndSimplifyBounds.java

/**
 * Simplify BoundDimFilters that are children of an OR or an AND.
 *
 * @param children    the filters/*from   ww w  .j  a  v  a  2 s.  co m*/
 * @param disjunction true for disjunction, false for conjunction
 *
 * @return simplified filters
 */
private static DimFilter doSimplify(final List<DimFilter> children, boolean disjunction) {
    // Copy children list
    final List<DimFilter> newChildren = Lists.newArrayList(children);

    // Group Bound filters by dimension, extractionFn, and comparator and compute a RangeSet for each one.
    final Map<BoundRefKey, List<BoundDimFilter>> bounds = Maps.newHashMap();

    final Iterator<DimFilter> iterator = newChildren.iterator();
    while (iterator.hasNext()) {
        final DimFilter child = iterator.next();

        if (child.equals(Filtration.matchNothing())) {
            // Child matches nothing, equivalent to FALSE
            // OR with FALSE => ignore
            // AND with FALSE => always false, short circuit
            if (disjunction) {
                iterator.remove();
            } else {
                return Filtration.matchNothing();
            }
        } else if (child.equals(Filtration.matchEverything())) {
            // Child matches everything, equivalent to TRUE
            // OR with TRUE => always true, short circuit
            // AND with TRUE => ignore
            if (disjunction) {
                return Filtration.matchEverything();
            } else {
                iterator.remove();
            }
        } else if (child instanceof BoundDimFilter) {
            final BoundDimFilter bound = (BoundDimFilter) child;
            final BoundRefKey boundRefKey = BoundRefKey.from(bound);
            List<BoundDimFilter> filterList = bounds.get(boundRefKey);
            if (filterList == null) {
                filterList = Lists.newArrayList();
                bounds.put(boundRefKey, filterList);
            }
            filterList.add(bound);
        }
    }

    // Try to simplify filters within each group.
    for (Map.Entry<BoundRefKey, List<BoundDimFilter>> entry : bounds.entrySet()) {
        final BoundRefKey boundRefKey = entry.getKey();
        final List<BoundDimFilter> filterList = entry.getValue();

        // Create a RangeSet for this group.
        final RangeSet<BoundValue> rangeSet = disjunction ? RangeSets.unionRanges(Bounds.toRanges(filterList))
                : RangeSets.intersectRanges(Bounds.toRanges(filterList));

        if (rangeSet.asRanges().size() < filterList.size()) {
            // We found a simplification. Remove the old filters and add new ones.
            for (final BoundDimFilter bound : filterList) {
                if (!newChildren.remove(bound)) {
                    throw new ISE("WTF?! Tried to remove bound but couldn't?");
                }
            }

            if (rangeSet.asRanges().isEmpty()) {
                // range set matches nothing, equivalent to FALSE
                // OR with FALSE => ignore
                // AND with FALSE => always false, short circuit
                if (disjunction) {
                    newChildren.add(Filtration.matchNothing());
                } else {
                    return Filtration.matchNothing();
                }
            }

            for (final Range<BoundValue> range : rangeSet.asRanges()) {
                if (!range.hasLowerBound() && !range.hasUpperBound()) {
                    // range matches all, equivalent to TRUE
                    // AND with TRUE => ignore
                    // OR with TRUE => always true; short circuit
                    if (disjunction) {
                        return Filtration.matchEverything();
                    } else {
                        newChildren.add(Filtration.matchEverything());
                    }
                } else {
                    newChildren.add(Bounds.toFilter(boundRefKey, range));
                }
            }
        }
    }

    Preconditions.checkState(newChildren.size() > 0, "newChildren.size > 0");
    if (newChildren.size() == 1) {
        return newChildren.get(0);
    } else {
        return disjunction ? new OrDimFilter(newChildren) : new AndDimFilter(newChildren);
    }
}

From source file:com.rockhoppertech.music.examples.Guava.java

public static void ranges() {
    RangeSet<Double> set = TreeRangeSet.create();
    //        for (double i = 1d; i < 4d; i++) {
    //            set.add(Range.closed(i, i + 1d));
    //        }/*  w  w w .  j  ava  2 s  . c om*/

    set.add(Range.closed(1d, 4d));
    logger.debug("the set {}", set);

    set.remove(Range.closed(2.5, 3d));
    logger.debug("after remove: set {}", set);
    RangeSet<Double> comp = set.complement();
    logger.debug("after remove: set comp {}", comp);

    Range<Double> first = Iterables.getFirst(set.asRanges(), null);
    logger.debug("first {}", first);

    //Iterables.

    for (Range<Double> r : set.asRanges()) {
        logger.debug("iterated range {}", r);
    }

    //lowerEndpoint();

    set.clear();
    set.add(Range.open(1d, 4d));
    comp = set.complement();
    logger.debug("open comp {}", comp);

}