Union of intervals

    :param S: list of pairs (low, high) defining intervals [low, high)
    :returns: ordered list of disjoint intervals with the same union as S
    :complexity: O(n log n)
423153
def intervals_union(S):
    
    E = [(low, -1) for (low, high) in S]
    E += [(high, +1) for (low, high) in S]
    nb_open = 0
    last = None
    retval = []
    for x, _dir in sorted(E):
        if _dir == -1:
            if nb_open == 0:
                last = x
            nb_open += 1
        else:
            nb_open -= 1
            if nb_open == 0:
                retval.append((last, x))
    return retval
1087380
def union(self, other):
        
        return Interval(min(self.low, other.low), max(self.high, other.high))
485820
def intersection(*args):
    
    if not args:
        return []

    # remove duplicates from first list whilst preserving order
    base = list(OrderedDict.fromkeys(args[0]))

    if len(args) == 1:
        return base
    else:
        others = set(args[1]).intersection(*args[2:])
        return [e for e in base if e in others]
1004658
def canonicalize(interval, lower_inc=True, upper_inc=False):
    
    if not interval.discrete:
        raise TypeError('Only discrete ranges can be canonicalized')

    if interval.empty:
        return interval

    lower, lower_inc = canonicalize_lower(interval, lower_inc)
    upper, upper_inc = canonicalize_upper(interval, upper_inc)

    return interval.__class__(
        [lower, upper],
        lower_inc=lower_inc,
        upper_inc=upper_inc,
    )
970608
def union(input, **params):
    
    res = []
    for col in input:
        res.extend(input[col])
    return res
490882
public static List<Range> union(List<Range> ranges){
        ranges = new ArrayList<Range>(ranges);
        Collections.sort(ranges, new Comparator<Range>(){
            @Override
            public int compare(Range r1, Range r2){
                return r1.min-r2.min;
            }
        });
        List<Range> union = new ArrayList<Range>();
        for(Range r: ranges){
            if(union.isEmpty())
                union.add(r);
            else
                CollectionUtil.addAll(union, union.remove(union.size() - 1).union(r));
        }
        return union;
    }
35024
def union(*argv):
        
        res = OrderedSet()
        for ods in argv:
            res = res | ods
        return res
256094
def union(self, b):
        

        if not allow_dsis:
            return StridedInterval.least_upper_bound(self, b)

        else:
            if self.cardinality > discrete_strided_interval_set.DEFAULT_MAX_CARDINALITY_WITHOUT_COLLAPSING or \
                    b.cardinality > discrete_strided_interval_set.DEFAULT_MAX_CARDINALITY_WITHOUT_COLLAPSING:
                return StridedInterval.least_upper_bound(self, b)

            else:
                dsis = DiscreteStridedIntervalSet(bits=self._bits, si_set={ self })
                return dsis.union(b)
1134295
def pairwise_iou(boxlist1, boxlist2):
    
    intersections = pairwise_intersection(boxlist1, boxlist2)
    areas1 = area(boxlist1)
    areas2 = area(boxlist2)
    unions = (
        tf.expand_dims(areas1, 1) + tf.expand_dims(areas2, 0) - intersections)
    return tf.where(
        tf.equal(intersections, 0.0),
        tf.zeros_like(intersections), tf.truediv(intersections, unions))
717933
public static <T extends Comparable<T>> Partition<T> union(Partition<T> p1, Partition<T> p2) throws MIDDException {

        if (p1.size() == 0) {
            return p2;
        }
        if (p2.size() == 0) {
            return p1;
        }

        Set<EndPoint<T>> boundSet = new HashSet<EndPoint<T>>();

        //collect all bounds and remove duplicated items
        for (Interval<T> interval : p1.getIntervals()) {
            boundSet.add(interval.getLowerBound());
            boundSet.add(interval.getUpperBound());
        }
        for (Interval<T> interval : p2.getIntervals()) {
            boundSet.add(interval.getLowerBound());
            boundSet.add(interval.getUpperBound());
        }
        if (boundSet.size() == 0) {
            throw new RuntimeException("no bounds");
        }
        //sorting the bounds
        List<EndPoint<T>> sortedBounds = new ArrayList<EndPoint<T>>(boundSet);
        Collections.sort(sortedBounds);

        List<Interval<T>> tempPartition = new ArrayList<Interval<T>>();

        // Generate new intervals
        for (int i = 0; i < sortedBounds.size() - 1; i++) {
            EndPoint<T> lowBound = sortedBounds.get(i);
            EndPoint<T> upBound = sortedBounds.get(i + 1);
            tempPartition.add(new Interval<T>(lowBound));
            tempPartition.add(new Interval<T>(lowBound, upBound));
        }
        // add the last end-point
        if (sortedBounds.size() > 0) {
            EndPoint<T> lastBound = sortedBounds.get(sortedBounds.size() - 1);
            tempPartition.add(new Interval<T>(lastBound));
        } else {
            log.warn("Empty sortedBound");
        }
        // combine adjacent intervals which belong to the same type
        List<Interval<T>> outputPartition = new ArrayList<Interval<T>>();

        Interval<T> newInterval = null;
        Interval<T> superOfNewIntervalP1 = null;
        Interval<T> superOfNewIntervalP2 = null;
//		int newIntervalType = 0;
/**
 * New version, updated at 2:00PM, 09/19/2012		
 */
        for (int i = 0; i < tempPartition.size(); i++) {
            Interval<T> tempInterval = tempPartition.get(i);
            Interval<T> superOfTempIntervalP1 = p1.getSuperInterval(tempInterval);
            Interval<T> superOfTempIntervalP2 = p2.getSuperInterval(tempInterval);

            if (superOfTempIntervalP1 == null && superOfTempIntervalP2 == null) // not belong to any partitions, ignore it
            {
                continue;
            }

            if (newInterval == null) {
                newInterval = tempInterval;
                superOfNewIntervalP1 = superOfTempIntervalP1;
                superOfNewIntervalP2 = superOfTempIntervalP2;
                continue;
            }

            if (superOfNewIntervalP1 == superOfTempIntervalP1 && superOfNewIntervalP2 == superOfTempIntervalP2) {
                newInterval.includeBound(tempInterval);
            } else {
                outputPartition.add(newInterval);
                newInterval = tempInterval;
                superOfNewIntervalP1 = superOfTempIntervalP1;
                superOfNewIntervalP2 = superOfTempIntervalP2;
            }

        }
        if (newInterval != null) {
            outputPartition.add(newInterval);
        }
        return new Partition<T>(outputPartition);
    }
566796
def intersect_4(self, second, third, fourth):
    
    self.intersection(second)
    self.intersection(third)
    self.intersection(fourth)
    self.coalesce()
    return len(self)
1100287
def union_elements(elements):
    

    if len(elements) < 2: return elements
    assert set( [e[3] for e in elements] ) == set( [elements[0][3]] ), "more than one id"
    el_id = elements[0][3]

    unioned_elements = []
    for ch, chgrp in groupby(elements, key=itemgetter(0)):
        for (s, e) in elem_u( np.array([itemgetter(1, 2)(_) for _ in chgrp], dtype=np.uint) ):
            if (s < e):
                unioned_elements.append( (ch, s, e, el_id) )
    assert len(unioned_elements) <= len(elements)
    return unioned_elements
1220113
def difference(self, other):
        
        ivs = set()
        for iv in self:
            if iv not in other:
                ivs.add(iv)
        return IntervalTree(ivs)
407687
def merge_range_pairs(prs):
    ''''''
    new_prs = []
    sprs = [sorted(p) for p in prs]
    sprs = sorted(sprs)
    merged = False
    x = 0
    while x < len(sprs):
        newx = x + 1
        new_pair = list(sprs[x])
        for y in range(x + 1, len(sprs)):
            if new_pair[0] <= sprs[y][0] - 1 <= new_pair[1]:
                new_pair[0] = min(new_pair[0], sprs[y][0])
                new_pair[1] = max(new_pair[1], sprs[y][1])
                newx = y + 1
        if new_pair not in new_prs:
            new_prs.append(new_pair)
        x = newx
    return new_prs
816157
def union(lst1, lst2):
    '''
    
    '''
    if isinstance(lst1, collections.Hashable) and isinstance(lst2, collections.Hashable):
        return set(lst1) | set(lst2)
    return unique(lst1 + lst2)
348217
def symmetric_difference(self, other):
        
        if not isinstance(other, set): other = set(other)
        me = set(self)
        ivs = me.difference(other).union(other.difference(me))
        return IntervalTree(ivs)
84184
def interval_cover(I):
    
    S = []
    for start, end in sorted(I, key=lambda v: v[1]):
        if not S or S[-1] < start:
            S.append(end)
    return S