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

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

Introduction

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

Prototype

public C upperEndpoint() 

Source Link

Document

Returns the upper endpoint of this range.

Usage

From source file:org.apache.calcite.adapter.druid.DruidDateTimeUtils.java

protected static List<LocalInterval> toInterval(List<Range<Calendar>> ranges) {
    List<LocalInterval> intervals = Lists.transform(ranges, new Function<Range<Calendar>, LocalInterval>() {
        public LocalInterval apply(Range<Calendar> range) {
            if (!range.hasLowerBound() && !range.hasUpperBound()) {
                return DruidTable.DEFAULT_INTERVAL;
            }/*w  w  w .ja  v a  2  s.  com*/
            long start = range.hasLowerBound() ? range.lowerEndpoint().getTime().getTime()
                    : DruidTable.DEFAULT_INTERVAL.getStartMillis();
            long end = range.hasUpperBound() ? range.upperEndpoint().getTime().getTime()
                    : DruidTable.DEFAULT_INTERVAL.getEndMillis();
            if (range.hasLowerBound() && range.lowerBoundType() == BoundType.OPEN) {
                start++;
            }
            if (range.hasUpperBound() && range.upperBoundType() == BoundType.CLOSED) {
                end++;
            }
            return LocalInterval.create(start, end);
        }
    });
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Converted time ranges " + ranges + " to interval " + intervals);
    }
    return intervals;
}

From source file:com.github.rinde.opt.localsearch.Swaps.java

static <C, T> Iterator<Swap<T>> oneItemSwapIterator(Schedule<C, T> schedule, IntList startIndices, T item,
        int fromRow) {
    final IntList indices = indices(schedule.routes.get(fromRow), item);
    final ImmutableList.Builder<Iterator<Swap<T>>> iteratorBuilder = ImmutableList.builder();

    Range<Integer> range;
    if (indices.size() == 1) {
        range = Range.closedOpen(fromRow, fromRow + 1);
    } else {//  w  ww .  j a  v  a2  s  .com
        range = Range.closedOpen(0, schedule.routes.size());
    }

    for (int i = range.lowerEndpoint(); i < range.upperEndpoint(); i++) {
        int rowSize = schedule.routes.get(i).size();
        if (fromRow == i) {
            rowSize -= indices.size();
        }
        Iterator<IntList> it = new InsertionIndexGenerator(indices.size(), rowSize, startIndices.getInt(i));
        // filter out swaps that have existing result
        if (fromRow == i) {
            it = Iterators.filter(it, Predicates.not(Predicates.equalTo(indices)));
        }
        iteratorBuilder.add(Iterators.transform(it, new IndexToSwapTransform<T>(item, fromRow, i)));
    }
    return Iterators.concat(iteratorBuilder.build().iterator());
}

From source file:org.pshdl.model.simulation.HDLSimulator.java

private static HDLRange createRange(Range<BigInteger> newRange) {
    if (newRange.lowerEndpoint().equals(newRange.upperEndpoint()))
        return new HDLRange().setTo(HDLLiteral.get(newRange.upperEndpoint()));
    return new HDLRange().setTo(HDLLiteral.get(newRange.lowerEndpoint()))
            .setFrom(HDLLiteral.get(newRange.upperEndpoint()));
}

From source file:org.apache.kylin.common.util.RangeUtil.java

public static String formatTsRange(Range<Long> tsRange) {
    if (tsRange == null)
        return null;

    StringBuilder sb = new StringBuilder();
    if (tsRange.hasLowerBound()) {
        if (tsRange.lowerBoundType() == BoundType.CLOSED) {
            sb.append("[");
        } else {/*from   ww w. ja  va  2 s . c  om*/
            sb.append("(");
        }
        sb.append(DateFormat.formatToTimeStr(tsRange.lowerEndpoint()));
    } else {
        sb.append("(-");
    }

    sb.append("~");

    if (tsRange.hasUpperBound()) {
        sb.append(DateFormat.formatToTimeStr(tsRange.upperEndpoint()));
        if (tsRange.upperBoundType() == BoundType.CLOSED) {
            sb.append("]");
        } else {
            sb.append(")");
        }
    } else {
        sb.append("+)");
    }
    return sb.toString();
}

From source file:org.apache.hadoop.hive.ql.optimizer.calcite.druid.DruidIntervalUtils.java

protected static List<Interval> toInterval(List<Range> ranges) {
    List<Interval> intervals = Lists.transform(ranges, new Function<Range, Interval>() {
        @Override//from www  .  ja v  a2 s . co  m
        public Interval apply(Range range) {
            if (!range.hasLowerBound() && !range.hasUpperBound()) {
                return DruidTable.DEFAULT_INTERVAL;
            }
            long start = range.hasLowerBound() ? toLong(range.lowerEndpoint())
                    : DruidTable.DEFAULT_INTERVAL.getStartMillis();
            long end = range.hasUpperBound() ? toLong(range.upperEndpoint())
                    : DruidTable.DEFAULT_INTERVAL.getEndMillis();
            if (range.hasLowerBound() && range.lowerBoundType() == BoundType.OPEN) {
                start++;
            }
            if (range.hasUpperBound() && range.upperBoundType() == BoundType.CLOSED) {
                end++;
            }
            return new Interval(start, end);
        }
    });
    LOG.info("Converted time ranges " + ranges + " to interval " + intervals);
    return intervals;
}

From source file:net.sf.mzmine.util.ScanUtils.java

/**
 * This method bins values on x-axis. Each bin is assigned biggest y-value
 * of all values in the same bin./* ww w  .j a va2s  .c o m*/
 * 
 * @param x
 *            X-coordinates of the data
 * @param y
 *            Y-coordinates of the data
 * @param firstBinStart
 *            Value at the "left"-edge of the first bin
 * @param lastBinStop
 *            Value at the "right"-edge of the last bin
 * @param numberOfBins
 *            Number of bins
 * @param interpolate
 *            If true, then empty bins will be filled with interpolation
 *            using other bins
 * @param binningType
 *            Type of binning (sum of all 'y' within a bin, max of 'y', min
 *            of 'y', avg of 'y')
 * @return Values for each bin
 */
public static double[] binValues(double[] x, double[] y, Range<Double> binRange, int numberOfBins,
        boolean interpolate, BinningType binningType) {

    Double[] binValues = new Double[numberOfBins];
    double binWidth = (binRange.upperEndpoint() - binRange.lowerEndpoint()) / numberOfBins;

    double beforeX = Double.MIN_VALUE;
    double beforeY = 0.0f;
    double afterX = Double.MAX_VALUE;
    double afterY = 0.0f;

    double[] noOfEntries = null;

    // Binnings
    for (int valueIndex = 0; valueIndex < x.length; valueIndex++) {

        // Before first bin?
        if ((x[valueIndex] - binRange.lowerEndpoint()) < 0) {
            if (x[valueIndex] > beforeX) {
                beforeX = x[valueIndex];
                beforeY = y[valueIndex];
            }
            continue;
        }

        // After last bin?
        if ((binRange.upperEndpoint() - x[valueIndex]) < 0) {
            if (x[valueIndex] < afterX) {
                afterX = x[valueIndex];
                afterY = y[valueIndex];
            }
            continue;
        }

        int binIndex = (int) ((x[valueIndex] - binRange.lowerEndpoint()) / binWidth);

        // in case x[valueIndex] is exactly lastBinStop, we would overflow
        // the array
        if (binIndex == binValues.length)
            binIndex--;

        switch (binningType) {
        case MAX:
            if (binValues[binIndex] == null) {
                binValues[binIndex] = y[valueIndex];
            } else {
                if (binValues[binIndex] < y[valueIndex]) {
                    binValues[binIndex] = y[valueIndex];
                }
            }
            break;
        case MIN:
            if (binValues[binIndex] == null) {
                binValues[binIndex] = y[valueIndex];
            } else {
                if (binValues[binIndex] > y[valueIndex]) {
                    binValues[binIndex] = y[valueIndex];
                }
            }
            break;
        case AVG:
            if (noOfEntries == null) {
                noOfEntries = new double[binValues.length];
            }
            if (binValues[binIndex] == null) {
                noOfEntries[binIndex] = 1;
                binValues[binIndex] = y[valueIndex];
            } else {
                noOfEntries[binIndex]++;
                binValues[binIndex] += y[valueIndex];
            }
            break;

        case SUM:
        default:
            if (binValues[binIndex] == null) {
                binValues[binIndex] = y[valueIndex];
            } else {
                binValues[binIndex] += y[valueIndex];
            }
            break;

        }

    }

    // calculate the AVG
    if (binningType.equals(BinningType.AVG)) {
        assert noOfEntries != null;
        for (int binIndex = 0; binIndex < binValues.length; binIndex++) {
            if (binValues[binIndex] != null) {
                binValues[binIndex] /= noOfEntries[binIndex];
            }
        }
    }

    // Interpolation
    if (interpolate) {

        for (int binIndex = 0; binIndex < binValues.length; binIndex++) {
            if (binValues[binIndex] == null) {

                // Find exisiting left neighbour
                double leftNeighbourValue = beforeY;
                int leftNeighbourBinIndex = (int) Math.floor((beforeX - binRange.lowerEndpoint()) / binWidth);
                for (int anotherBinIndex = binIndex - 1; anotherBinIndex >= 0; anotherBinIndex--) {
                    if (binValues[anotherBinIndex] != null) {
                        leftNeighbourValue = binValues[anotherBinIndex];
                        leftNeighbourBinIndex = anotherBinIndex;
                        break;
                    }
                }

                // Find existing right neighbour
                double rightNeighbourValue = afterY;
                int rightNeighbourBinIndex = (binValues.length - 1)
                        + (int) Math.ceil((afterX - binRange.upperEndpoint()) / binWidth);
                for (int anotherBinIndex = binIndex
                        + 1; anotherBinIndex < binValues.length; anotherBinIndex++) {
                    if (binValues[anotherBinIndex] != null) {
                        rightNeighbourValue = binValues[anotherBinIndex];
                        rightNeighbourBinIndex = anotherBinIndex;
                        break;
                    }
                }

                double slope = (rightNeighbourValue - leftNeighbourValue)
                        / (rightNeighbourBinIndex - leftNeighbourBinIndex);
                binValues[binIndex] = new Double(
                        leftNeighbourValue + slope * (binIndex - leftNeighbourBinIndex));

            }

        }

    }

    double[] res = new double[binValues.length];
    for (int binIndex = 0; binIndex < binValues.length; binIndex++) {
        res[binIndex] = binValues[binIndex] == null ? 0 : binValues[binIndex];
    }
    return res;

}

From source file:org.kitesdk.data.spi.ConstraintsSerialization.java

/**
 * Serializes an {@link Range} into the specified {@code out} stream.
 *//*from  w w  w  .  j a v  a2s.  c o m*/
private static void writeRangePredicate(Schema fieldSchema, Range range, ObjectOutputStream out)
        throws IOException {
    if (range.hasLowerBound()) {
        //write out that there is a lower endpoint and the value.
        out.writeBoolean(true);
        out.writeBoolean(range.isLowerBoundOpen());
        writeValue(fieldSchema, range.lowerEndpoint(), out);
    } else {
        //Write that there is no lower bound
        out.writeBoolean(false);
    }

    if (range.hasUpperBound()) {
        out.writeBoolean(true);
        out.writeBoolean(range.isUpperBoundOpen());
        //write out that there is a lower endpoint and the value.
        writeValue(fieldSchema, range.upperEndpoint(), out);
    } else {
        //write out that there is not an upper bound
        out.writeBoolean(false);
    }
}

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 ww w  .java2 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:annis.visualizers.component.grid.EventExtractor.java

public static void removeEmptySpace(LinkedHashMap<String, ArrayList<Row>> rowsByAnnotation, Row tokenRow) {
    List<Range<Integer>> gaps = new LinkedList<>();

    BitSet totalOccupancyGrid = new BitSet();
    for (Map.Entry<String, ArrayList<Row>> layer : rowsByAnnotation.entrySet()) {
        for (Row r : layer.getValue()) {
            totalOccupancyGrid.or(r.getOccupancyGridCopy());
        }//from  w  w w.  j  av  a 2  s.  c om
    }
    // We always include the token row in the occupancy grid since it is not
    // a gap. Otherwise empty token would trigger gaps if the token list
    // is included in the visualizer output.
    // See https://github.com/korpling/ANNIS/issues/281 for the corresponding
    // bug report.
    if (tokenRow != null) {
        totalOccupancyGrid.or(tokenRow.getOccupancyGridCopy());
    }

    // The Range class can give us the next bit that is not set. Use this
    // to detect gaps. A gap starts from the next non-set bit and goes to
    // the next set bit.
    Range<Integer> gap = Range.closed(-1, totalOccupancyGrid.nextSetBit(0));
    while (true) {
        int gapStart = totalOccupancyGrid.nextClearBit(gap.upperEndpoint() + 1);
        int gapEnd = totalOccupancyGrid.nextSetBit(gapStart);
        if (gapEnd <= 0) {
            break;
        }
        gap = Range.closed(gapStart, gapEnd - 1);
        gaps.add(gap);

    }

    int gapID = 0;
    int totalOffset = 0;
    for (Range<Integer> gRaw : gaps) {
        // adjust the space range itself
        Range<Integer> g = Range.closed(gRaw.lowerEndpoint() - totalOffset, gRaw.upperEndpoint() - totalOffset);
        int offset = g.upperEndpoint() - g.lowerEndpoint();
        totalOffset += offset;

        for (Entry<String, ArrayList<Row>> rowEntry : rowsByAnnotation.entrySet()) {
            ArrayList<Row> rows = rowEntry.getValue();
            for (Row r : rows) {
                List<GridEvent> eventsCopy = new LinkedList<>(r.getEvents());
                for (GridEvent e : eventsCopy) {
                    if (e.getLeft() >= g.upperEndpoint()) {

                        r.removeEvent(e);
                        e.setLeft(e.getLeft() - offset);
                        e.setRight(e.getRight() - offset);
                        r.addEvent(e);
                    }
                }

                // add a special space event
                String spaceCaption = "";
                if ("tok".equalsIgnoreCase(rowEntry.getKey())) {
                    spaceCaption = "(...)";
                }
                GridEvent spaceEvent = new GridEvent("gap-" + gapID, g.lowerEndpoint(), g.lowerEndpoint(),
                        spaceCaption);
                spaceEvent.setSpace(true);
                r.addEvent(spaceEvent);
                gapID++;
            }
        }
    }
}

From source file:org.pshdl.model.simulation.HDLSimulator.java

private static HDLUnit createBitRanges(HDLEvaluationContext context, HDLUnit insulin) {
    final HDLVariableRef[] refs = insulin.getAllObjectsOf(HDLVariableRef.class, true);
    final Map<HDLQualifiedName, List<RangeVal>> ranges = new LinkedHashMap<HDLQualifiedName, List<RangeVal>>();
    final Map<HDLQualifiedName, Range<BigInteger>> fullRanges = new LinkedHashMap<HDLQualifiedName, Range<BigInteger>>();
    for (final HDLVariableRef ref : refs)
        if (ref.getContainer() instanceof HDLAssignment) {
            final HDLAssignment ass = (HDLAssignment) ref.getContainer();
            if (ass.getLeft() == ref) {
                final Optional<HDLVariable> resolved = ref.resolveVar();
                if (!resolved.isPresent())
                    throw new IllegalArgumentException("Can not resolve:" + ref.getVarRefName());
                final HDLVariable resolveVar = resolved.get();
                if (resolveVar.getDirection() != HDLDirection.IN) {
                    final HDLQualifiedName varRefName = ref.getVarRefName();
                    if (ref.getBits().size() > 0) {
                        List<RangeVal> set = ranges.get(varRefName);
                        if (set == null) {
                            set = new LinkedList<RangeVal>();
                            ranges.put(varRefName, set);
                        }/*from   w ww.  jav a 2s.com*/
                        for (final HDLRange r : ref.getBits()) {
                            final Optional<Range<BigInteger>> determineRange = RangeExtension.rangeOf(r,
                                    context);
                            if (!determineRange.isPresent())
                                throw new IllegalArgumentException("Can not determine Range for:" + r);
                            set.add(new RangeVal(determineRange.get().lowerEndpoint(), 1));
                            set.add(new RangeVal(determineRange.get().upperEndpoint(), -1));
                        }
                    } else {
                        final HDLExpression width = TypeExtension.getWidth(resolveVar);
                        if (width != null) {
                            final Optional<BigInteger> bWidth = ConstantEvaluate.valueOf(width, context);
                            if (!bWidth.isPresent())
                                throw new IllegalArgumentException("Given the context this should be constant");
                            fullRanges.put(varRefName, RangeTool.createRange(BigInteger.ZERO,
                                    bWidth.get().subtract(BigInteger.ONE)));
                        }
                    }
                }
            }
        }
    final ModificationSet ms = new ModificationSet();
    final Map<HDLQualifiedName, SortedSet<Range<BigInteger>>> splitRanges = new LinkedHashMap<HDLQualifiedName, SortedSet<Range<BigInteger>>>();
    for (final Map.Entry<HDLQualifiedName, List<RangeVal>> entry : ranges.entrySet()) {
        final List<RangeVal> value = entry.getValue();
        final HDLQualifiedName varName = entry.getKey();
        if (fullRanges.containsKey(varName)) {
            final Range<BigInteger> fullWidth = fullRanges.get(varName);
            value.add(new RangeVal(fullWidth.lowerEndpoint(), 1));
            value.add(new RangeVal(fullWidth.upperEndpoint(), -1));
        }
        final SortedSet<Range<BigInteger>> split = RangeTool.split(value);
        splitRanges.put(varName, split);
    }
    // Change bit access to broken down ranges
    for (final HDLVariableRef ref : refs) {
        final SortedSet<Range<BigInteger>> list = splitRanges.get(ref.getVarRefName());
        if (list != null) {
            final ArrayList<HDLRange> newRanges = new ArrayList<HDLRange>();
            if (!ref.getBits().isEmpty()) {
                for (final HDLRange bit : ref.getBits())
                    if (bit.getFrom() != null) { // Singular ranges don't do
                        // anything
                        final Optional<Range<BigInteger>> range = RangeExtension.rangeOf(bit, context);
                        if (!range.isPresent())
                            throw new IllegalArgumentException("Can not determine Range of:" + bit);
                        for (final Range<BigInteger> newRange : list)
                            if (range.get().isConnected(newRange)) {
                                newRanges.add(0, createRange(newRange));
                            }
                    } else {
                        newRanges.add(0, bit);
                    }
            } else {
                for (final Range<BigInteger> vRange : list) {
                    newRanges.add(0, createRange(vRange));
                }
            }
            if (newRanges.size() != 0) {
                ms.replace(ref, ref.setBits(newRanges));
            }
        }
    }
    final HDLUnit apply = ms.apply(insulin);
    return Insulin.handleMultiBitAccess(apply, context);
}