
    "/a                         d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	m	Z	 ddl
mZ 	 dd	lmZ 	 e  G d
 de      Zy# e$ r	 dd	lmZ Y w xY w# e$ r eZY &w xY w)a  
intervaltree: A mutable, self-balancing interval tree for Python 2 and 3.
Queries may be by point, by range overlap, or by range envelopment.

Core logic.

Copyright 2013-2018 Chaim Leib Halbert
Modifications Copyright 2014 Konstantin Tretyakov

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
   Interval)Node    )Number)
SortedDictcopy)warn)
MutableSetc                      e Zd ZdZed        Zd8dZd Zd Zd Z	d Z
e
Zd8d	ZeZd
 Zd Zd8dZd Zd8dZd Zd Zd Zd Zd Zd Zd Zd8dZd Zd8dZd8dZd Zd Zd8dZ d Z!d Z"d Z#d9d Z$d:d!Z%d" Z&d# Z'd$ Z(d8d%Z)d8d&Z*d' Z+d( Z,d) Z-d* Z.d;d+Z/d, Z0d;d-Z1d. Z2d/ Z3d0 Z4d1 Z5d8d2Z6d3 Z7e7Z8d4 Z9d5 Z:d6 Z;e;Z<d7 Z=y)<IntervalTreea  
    A binary lookup tree of intervals.
    The intervals contained in the tree are represented using ``Interval(a, b, data)`` objects.
    Each such object represents a half-open interval ``[a, b)`` with optional data.

    Examples:
    ---------

    Initialize a blank tree::

        >>> tree = IntervalTree()
        >>> tree
        IntervalTree()

    Initialize a tree from an iterable set of Intervals in O(n * log n)::

        >>> tree = IntervalTree([Interval(-10, 10), Interval(-20.0, -10.0)])
        >>> tree
        IntervalTree([Interval(-20.0, -10.0), Interval(-10, 10)])
        >>> len(tree)
        2

    Note that this is a set, i.e. repeated intervals are ignored. However,
    Intervals with different data fields are regarded as different::

        >>> tree = IntervalTree([Interval(-10, 10), Interval(-10, 10), Interval(-10, 10, "x")])
        >>> tree
        IntervalTree([Interval(-10, 10), Interval(-10, 10, 'x')])
        >>> len(tree)
        2

    Insertions::
        >>> tree = IntervalTree()
        >>> tree[0:1] = "data"
        >>> tree.add(Interval(10, 20))
        >>> tree.addi(19.9, 20)
        >>> tree
        IntervalTree([Interval(0, 1, 'data'), Interval(10, 20), Interval(19.9, 20)])
        >>> tree.update([Interval(19.9, 20.1), Interval(20.1, 30)])
        >>> len(tree)
        5

        Inserting the same Interval twice does nothing::
            >>> tree = IntervalTree()
            >>> tree[-10:20] = "arbitrary data"
            >>> tree[-10:20] = None  # Note that this is also an insertion
            >>> tree
            IntervalTree([Interval(-10, 20), Interval(-10, 20, 'arbitrary data')])
            >>> tree[-10:20] = None  # This won't change anything
            >>> tree[-10:20] = "arbitrary data" # Neither will this
            >>> len(tree)
            2

    Deletions::
        >>> tree = IntervalTree(Interval(b, e) for b, e in [(-10, 10), (-20, -10), (10, 20)])
        >>> tree
        IntervalTree([Interval(-20, -10), Interval(-10, 10), Interval(10, 20)])
        >>> tree.remove(Interval(-10, 10))
        >>> tree
        IntervalTree([Interval(-20, -10), Interval(10, 20)])
        >>> tree.remove(Interval(-10, 10))
        Traceback (most recent call last):
        ...
        ValueError
        >>> tree.discard(Interval(-10, 10))  # Same as remove, but no exception on failure
        >>> tree
        IntervalTree([Interval(-20, -10), Interval(10, 20)])

    Delete intervals, overlapping a given point::

        >>> tree = IntervalTree([Interval(-1.1, 1.1), Interval(-0.5, 1.5), Interval(0.5, 1.7)])
        >>> tree.remove_overlap(1.1)
        >>> tree
        IntervalTree([Interval(-1.1, 1.1)])

    Delete intervals, overlapping an interval::

        >>> tree = IntervalTree([Interval(-1.1, 1.1), Interval(-0.5, 1.5), Interval(0.5, 1.7)])
        >>> tree.remove_overlap(0, 0.5)
        >>> tree
        IntervalTree([Interval(0.5, 1.7)])
        >>> tree.remove_overlap(1.7, 1.8)
        >>> tree
        IntervalTree([Interval(0.5, 1.7)])
        >>> tree.remove_overlap(1.6, 1.6)  # Null interval does nothing
        >>> tree
        IntervalTree([Interval(0.5, 1.7)])
        >>> tree.remove_overlap(1.6, 1.5)  # Ditto
        >>> tree
        IntervalTree([Interval(0.5, 1.7)])

    Delete intervals, enveloped in the range::

        >>> tree = IntervalTree([Interval(-1.1, 1.1), Interval(-0.5, 1.5), Interval(0.5, 1.7)])
        >>> tree.remove_envelop(-1.0, 1.5)
        >>> tree
        IntervalTree([Interval(-1.1, 1.1), Interval(0.5, 1.7)])
        >>> tree.remove_envelop(-1.1, 1.5)
        >>> tree
        IntervalTree([Interval(0.5, 1.7)])
        >>> tree.remove_envelop(0.5, 1.5)
        >>> tree
        IntervalTree([Interval(0.5, 1.7)])
        >>> tree.remove_envelop(0.5, 1.7)
        >>> tree
        IntervalTree()

    Point queries::

        >>> tree = IntervalTree([Interval(-1.1, 1.1), Interval(-0.5, 1.5), Interval(0.5, 1.7)])
        >>> assert tree[-1.1]   == set([Interval(-1.1, 1.1)])
        >>> assert tree.at(1.1) == set([Interval(-0.5, 1.5), Interval(0.5, 1.7)])   # Same as tree[1.1]
        >>> assert tree.at(1.5) == set([Interval(0.5, 1.7)])                        # Same as tree[1.5]

    Interval overlap queries

        >>> tree = IntervalTree([Interval(-1.1, 1.1), Interval(-0.5, 1.5), Interval(0.5, 1.7)])
        >>> assert tree.overlap(1.7, 1.8) == set()
        >>> assert tree.overlap(1.5, 1.8) == set([Interval(0.5, 1.7)])
        >>> assert tree[1.5:1.8] == set([Interval(0.5, 1.7)])                       # same as previous
        >>> assert tree.overlap(1.1, 1.8) == set([Interval(-0.5, 1.5), Interval(0.5, 1.7)])
        >>> assert tree[1.1:1.8] == set([Interval(-0.5, 1.5), Interval(0.5, 1.7)])  # same as previous

    Interval envelop queries::

        >>> tree = IntervalTree([Interval(-1.1, 1.1), Interval(-0.5, 1.5), Interval(0.5, 1.7)])
        >>> assert tree.envelop(-0.5, 0.5) == set()
        >>> assert tree.envelop(-0.5, 1.5) == set([Interval(-0.5, 1.5)])

    Membership queries::

        >>> tree = IntervalTree([Interval(-1.1, 1.1), Interval(-0.5, 1.5), Interval(0.5, 1.7)])
        >>> Interval(-0.5, 0.5) in tree
        False
        >>> Interval(-1.1, 1.1) in tree
        True
        >>> Interval(-1.1, 1.1, "x") in tree
        False
        >>> tree.overlaps(-1.1)
        True
        >>> tree.overlaps(1.7)
        False
        >>> tree.overlaps(1.7, 1.8)
        False
        >>> tree.overlaps(-1.2, -1.1)
        False
        >>> tree.overlaps(-1.2, -1.0)
        True

    Sizing::

        >>> tree = IntervalTree([Interval(-1.1, 1.1), Interval(-0.5, 1.5), Interval(0.5, 1.7)])
        >>> len(tree)
        3
        >>> tree.is_empty()
        False
        >>> IntervalTree().is_empty()
        True
        >>> not tree
        False
        >>> not IntervalTree()
        True
        >>> print(tree.begin())    # using print() because of floats in Python 2.6
        -1.1
        >>> print(tree.end())      # ditto
        1.7

    Iteration::

        >>> tree = IntervalTree([Interval(-11, 11), Interval(-5, 15), Interval(5, 17)])
        >>> [iv.begin for iv in sorted(tree)]
        [-11, -5, 5]
        >>> assert tree.items() == set([Interval(-5, 15), Interval(-11, 11), Interval(5, 17)])

    Copy- and typecasting, pickling::

        >>> tree0 = IntervalTree([Interval(0, 1, "x"), Interval(1, 2, ["x"])])
        >>> tree1 = IntervalTree(tree0)  # Shares Interval objects
        >>> tree2 = tree0.copy()         # Shallow copy (same as above, as Intervals are singletons)
        >>> import pickle
        >>> tree3 = pickle.loads(pickle.dumps(tree0))  # Deep copy
        >>> list(tree0[1])[0].data[0] = "y"  # affects shallow copies, but not deep copies
        >>> tree0
        IntervalTree([Interval(0, 1, 'x'), Interval(1, 2, ['y'])])
        >>> tree1
        IntervalTree([Interval(0, 1, 'x'), Interval(1, 2, ['y'])])
        >>> tree2
        IntervalTree([Interval(0, 1, 'x'), Interval(1, 2, ['y'])])
        >>> tree3
        IntervalTree([Interval(0, 1, 'x'), Interval(1, 2, ['x'])])

    Equality testing::

        >>> IntervalTree([Interval(0, 1)]) == IntervalTree([Interval(0, 1)])
        True
        >>> IntervalTree([Interval(0, 1)]) == IntervalTree([Interval(0, 1, "x")])
        False
    c                 L    |D cg c]
  }t        |  }}t        |      S c c}w )z
        Create a new IntervalTree from an iterable of 2- or 3-tuples,
         where the tuple lists begin, end, and optionally data.
        )r   r   )clstupstivss       9lib/python3.12/site-packages/intervaltree/intervaltree.pyfrom_tupleszIntervalTree.from_tuples   s,     &**Tx|T*C   +s   !Nc                 L   |t        |      n	t               }|D ],  }|j                         st        dj                  |             || _        t        j                  | j                        | _        t               | _	        | j                  D ]  }| j                  |        y)z
        Set up a tree. If intervals is provided, add all the intervals
        to the tree.

        Completes in O(n*log n) time.
        NDIntervalTree: Null Interval objects not allowed in IntervalTree: {0})setis_null
ValueErrorformatall_intervalsr   from_intervalstop_noder   boundary_table_add_boundariesself	intervalsivs      r   __init__zIntervalTree.__init__   s     '0&;C	N	Bzz| !6":   '++D,>,>?(l$$B  $ %    c                 &    t        d | D              S )z
        Construct a new IntervalTree using shallow copies of the
        intervals in the source tree.

        Completes in O(n*log n) time.
        :rtype: IntervalTree
        c              3   <   K   | ]  }|j                           y wNr	   ).0r$   s     r   	<genexpr>z$IntervalTree.copy.<locals>.<genexpr>  s     5"BGGIs   )r   r"   s    r   r
   zIntervalTree.copy  s     5555r&   c                    |j                   }|j                  }|| j                  v r| j                  |xx   dz  cc<   nd| j                  |<   || j                  v r| j                  |xx   dz  cc<   yd| j                  |<   y)zO
        Records the boundaries of the interval in the boundary table.
        r   Nbeginendr   r"   intervalr/   r0   s       r   r    zIntervalTree._add_boundaries  s~     llD'''&!+&)*D&$%%%$)$'(D$r&   c                    |j                   }|j                  }| j                  |   dk(  r| j                  |= n| j                  |xx   dz  cc<   | j                  |   dk(  r| j                  |= y| j                  |xx   dz  cc<   y)zQ
        Removes the boundaries of the interval from the boundary table.
        r   Nr.   r1   s       r   _remove_boundarieszIntervalTree._remove_boundaries*  s     llu%*##E*&!+&s#q(##C($)$r&   c                 H   || v ry|j                         rt        dj                  |            | j                  st	        j
                  |      | _        n | j                  j                  |      | _        | j                  j                  |       | j                  |       y)zl
        Adds an interval to the tree, if not already present.

        Completes in O(log n) time.
        Nr   )	r   r   r   r   r   from_intervaladdr   r    r"   r2   s     r   r7   zIntervalTree.add:  s     tvh' 
 }} ..x8DM MM--h7DMx(X&r&   c                 :    | j                  t        |||            S )zd
        Shortcut for add(Interval(begin, end, data)).

        Completes in O(log n) time.
        )r7   r   r"   r/   r0   datas       r   addizIntervalTree.addiQ  s     xxT233r&   c                 4    |D ]  }| j                  |        y)z
        Given an iterable of intervals, add them to the tree.

        Completes in O(m*log(n+m), where m = number of intervals to
        add.
        N)r7   r!   s      r   updatezIntervalTree.updateZ  s     BHHRL r&   c                     || vrt         | j                  j                  |      | _        | j                  j                  |       | j	                  |       y)z
        Removes an interval from the tree, if present. If not, raises
        ValueError.

        Completes in O(log n) time.
        N)r   r   remover   r4   r8   s     r   r@   zIntervalTree.removed  sJ     4,,X6!!(+)r&   c                 :    | j                  t        |||            S )zg
        Shortcut for remove(Interval(begin, end, data)).

        Completes in O(log n) time.
        )r@   r   r:   s       r   removeizIntervalTree.removeit  s     {{8E3566r&   c                     || vry| j                   j                  |       | j                  j                  |      | _        | j                  |       y)z
        Removes an interval from the tree, if present. If not, does
        nothing.

        Completes in O(log n) time.
        N)r   discardr   r4   r8   s     r   rD   zIntervalTree.discard|  sG     4""8,--h7)r&   c                 :    | j                  t        |||            S )zh
        Shortcut for discard(Interval(begin, end, data)).

        Completes in O(log n) time.
        )rD   r   r:   s       r   discardizIntervalTree.discardi  s     ||HUC677r&   c                 f    t               }| D ]  }||vs|j                  |        t        |      S )z`
        Returns a new tree, comprising all intervals in self but not
        in other.
        )r   r7   r   r"   otherr   r$   s       r   
differencezIntervalTree.difference  s4    
 eB  C  r&   c                 4    |D ]  }| j                  |        y)z;
        Removes all intervals in other from self.
        N)rD   )r"   rI   r$   s      r   difference_updatezIntervalTree.difference_update  s     BLL r&   c                 H    t        t        |       j                  |            S )z[
        Returns a new tree, comprising all intervals from self
        and other.
        )r   r   unionr"   rI   s     r   rN   zIntervalTree.union  s    
 CIOOE233r&   c                     t               }t        | |gt              \  }}|D ]  }||v s|j                  |        t	        |      S )z\
        Returns a new tree of all intervals common to both self and
        other.
        )key)r   sortedlenr7   r   )r"   rI   r   shorterlongerr$   s         r   intersectionzIntervalTree.intersection  sH    
 e $C8BV|  C  r&   c                 T    t        |       }|D ]  }||vs| j                  |        y)zN
        Removes intervals from self unless they also exist in other.
        N)listr@   rH   s       r   intersection_updatez IntervalTree.intersection_update  s)     4jBB r&   c                     t        |t              st        |      }t        |       }|j                  |      j                  |j                  |            }t	        |      S )zY
        Return a tree with elements only in self or other but not
        both.
        )
isinstancer   rJ   rN   r   )r"   rI   mer   s       r   symmetric_differencez!IntervalTree.symmetric_difference  sN    
 %%s5zuYmmE"(()9)9")=>C  r&   c                     t        |      }t        |       }|D ])  }||v s| j                  |       |j                  |       + | j                  |       y)z`
        Throws out all intervals except those only in self or other,
        not both.
        N)r   rX   r@   r>   rH   s       r   symmetric_difference_updatez(IntervalTree.symmetric_difference_update  sL    
 E
4jBU{BR   	Er&   c                 ~    || j                  |      n| j                  ||      }|D ]  }| j                  |        y)a  
        Removes all intervals overlapping the given point or range.

        Completes in O((r+m)*log n) time, where:
          * n = size of the tree
          * m = number of matches
          * r = size of the search range (this is 1 for a point)
        N)atoverlapr@   r"   r/   r0   hitlistr$   s        r   remove_overlapzIntervalTree.remove_overlap  s7     %(K$''%.T\\%5MBKKO r&   c                 X    | j                  ||      }|D ]  }| j                  |        y)z
        Removes all intervals completely enveloped in the given range.

        Completes in O((r+m)*log n) time, where:
          * n = size of the tree
          * m = number of matches
          * r = size of the search range
        N)envelopr@   rc   s        r   remove_envelopzIntervalTree.remove_envelop  s)     ,,uc*BKKO r&   c                     t               }| j                  |      D cg c]  }|j                  |k  s| }}| j                  |      D cg c]  }|j                  |kD  s| }}|ri|D ]/  }|j	                  t        |j                  | ||d                   1 |D ]/  }|j	                  t        ||j                   ||d                   1 nn|D ]2  }|j	                  t        |j                  ||j                               4 |D ]2  }|j	                  t        ||j                  |j                               4 | j                  ||       | j                  |       | j                  |       | j                  |       yc c}w c c}w )z
        Like remove_envelop(), but trims back Intervals hanging into
        the chopped area so that nothing overlaps.
        TFN)
r   ra   r/   r0   r7   r   r;   rh   rL   r>   )r"   r/   r0   datafunc
insertionsr$   
begin_hitsend_hitss           r   chopzIntervalTree.chop  sB   
 U
#'775>F>RRXX5Eb>
F!%>2#B> x%"d9KLM !xRVVXb%5HIJ  !x%AB !xRVVRWW=>  	E3'z*x(J# G>s   FFF!Fc                 :   t        fd| j                        D              }t               }|rb|D ]\  }|j                  t        |j                   ||d                   |j                  t        |j
                   ||d                   ^ ng|D ]b  }|j                  t        |j                  |j                               |j                  t        |j
                  |j                               d | j                  |       | j                  |       y)aX  
        Split Intervals that overlap point into two new Intervals. if
        specified, uses datafunc(interval, islower=True/False) to
        set the data field of the new Intervals.
        :param point: where to slice
        :param datafunc(interval, isupper): callable returning a new
        value for the interval's data field
        c              3   B   K   | ]  }|j                   k  s|  y wr)   )r/   )r*   r$   points     r   r+   z%IntervalTree.slice.<locals>.<genexpr>  s     F>RRXX5Eb>s   TFN)	r   ra   r7   r   r/   r0   r;   rL   r>   )r"   rq   rj   rd   rk   r$   s    `    r   slicezIntervalTree.slice	  s     F4775>FFU
x%"d9KLMxrvvxE7JKL  x%ABxrvvrww?@  	w'Jr&   c                 $    | j                          y)zD
        Empties the tree.

        Completes in O(1) tine.
        N)r%   r,   s    r   clearzIntervalTree.clear  s     	r&   c                     i fd}t        | j                  t        j                  d      }t	        |      D ]  \  }||dz   d D ]	   |          S )z
        Returns a dictionary mapping parent intervals to sets of
        intervals overlapped by and contained in the parent.

        Completes in O(n^2) time.
        :rtype: dict of [Interval, set of Interval]
        c                  t    j                         r&vrt               <      j                          y y r)   )contains_intervalr   r7   )childparentresults   r   add_if_nestedz/IntervalTree.find_nested.<locals>.add_if_nested1  s;    ''.'%(UF6Nv""5) /r&   T)rQ   reverser   N)rR   r   r   length	enumerate)r"   r{   long_ivsirx   ry   rz   s       @@@r   find_nestedzIntervalTree.find_nested'  s]     	* $,,(//4P"8,IAv!!a%&) * - r&   c                     || j                  ||      S t        |t              r| j                  |      S | j                  |j                  |j
                        S )z
        Returns whether some interval in the tree overlaps the given
        point or range.

        Completes in O(r*log n) time, where r is the size of the
        search range.
        :rtype: bool
        )overlaps_ranger[   r   overlaps_pointr/   r0   r"   r/   r0   s      r   overlapszIntervalTree.overlaps=  sR     ?&&uc22v&&&u--&&u{{EII>>r&   c                 l    | j                         ryt        | j                  j                  |            S )z
        Returns whether some interval in the tree overlaps p.

        Completes in O(log n) time.
        :rtype: bool
        F)is_emptyboolr   contains_point)r"   ps     r   r   zIntervalTree.overlaps_pointM  s*     ==?DMM00344r&   c                       j                         ryk\  ry j                        ryt         fd j                  D              S )a  
        Returns whether some interval in the tree overlaps the given
        range. Returns False if given a null interval over which to
        test.

        Completes in O(r*log n) time, where r is the range length and n
        is the table size.
        :rtype: bool
        FTc              3   \   K   | ]#  }|cxk  rk  rn nj                  |       % y wr)   )r   )r*   boundr/   r0   r"   s     r   r+   z.IntervalTree.overlaps_range.<locals>.<genexpr>h  s1      
,u"s" &,s   ),)r   r   anyr   r   s   ```r   r   zIntervalTree.overlaps_rangeX  sL     ==?c\  ' 
,,
 
 	
r&   c           	      0   | syt        | j                        dk(  ryt        | j                        }t               }t	        |dd |dd       D ]5  \  }}| |   D ](  }|j                  t        |||j                               * 7 | j                  |       y)a2  
        Finds all intervals with overlapping ranges and splits them
        along the range boundaries.

        Completes in worst-case O(n^2*log n) time (many interval
        boundaries are inside many intervals), best-case O(n*log n)
        time (small number of overlaps << n per interval).
        N   r   )	rS   r   rR   r   zipr7   r   r;   r%   )r"   boundsnew_ivslbounduboundr$   s         r   split_overlapszIntervalTree.split_overlapsn  s     t""#q(++,%!&"+vabz:NFF6lHVVRWW=> # ; 	gr&   c                   	
 | syt        | j                        }g 
dgd		
fd}|D ]  	
r
d   }	j                  |j                  k  s|sx	j                  |j                  k(  r_t	        |j                  	j                        } d   	j
                        d<   ndd<   t        |j                  |d         
d<    |         |         | j                  
       y)a  
        Finds all intervals with overlapping ranges and merges them
        into a single interval. If provided, uses data_reducer and
        data_initializer with similar semantics to Python's built-in
        reduce(reducer_func[, initializer]), as follows:

        If data_reducer is set to a function, combines the data
        fields of the Intervals with
            current_reduced_data = data_reducer(current_reduced_data, new_data)
        If data_reducer is None, the merged Interval's data
        field will be set to None, ignoring all the data fields
        of the merged Intervals.

        On encountering the first Interval to merge, if
        data_initializer is None (default), uses the first
        Interval's data field as the first value for
        current_reduced_data. If data_initializer is not None,
        current_reduced_data is set to a shallow copy of
        data_initializer created with copy.copy(data_initializer).

        If strict is True (default), intervals are only merged if
        their ranges actually overlap; adjacent, touching intervals
        will not be merged. If strict is False, intervals are merged
        even if they are only end-to-end adjacent.

        Completes in O(n*logn).
        Nc                      !j                    d<   j                         y t               d<     d   j                          d<   j                  t        j                  j
                   d                y Nr   r;   appendr
   r   r/   r0   current_reduceddata_initializerdata_reducerhighermergeds   r   
new_seriesz/IntervalTree.merge_overlaps.<locals>.new_series  s    '%+[["f%%)*:%;"%1/!2Dfkk%R"hv||VZZQRASTUr&   r   r   )rR   r   r/   r0   maxr;   r   r%   )r"   r   r   strictsorted_intervalsr   lowerupper_boundr   r   r   s    ``     @@@r   merge_overlapszIntervalTree.merge_overlaps  s    8 !$"4"45&	V 	V 'Fr
LL599,6<<599#<"%eii"<K#/-9/!:Lfkk-Z*-1*!)%++{OTUDV!WF2JL '  	fr&   c                   	 | syt        | j                        }g 	dgd	fd}|D ]  	r}	d   }j                  |      r_t        |j                  j                        } d   j
                        d<   ndd<   t        |j                  |d         	d<   z |         |         | j                  	       y)a  
        Finds all intervals with equal ranges and merges them
        into a single interval. If provided, uses data_reducer and
        data_initializer with similar semantics to Python's built-in
        reduce(reducer_func[, initializer]), as follows:

        If data_reducer is set to a function, combines the data
        fields of the Intervals with
            current_reduced_data = data_reducer(current_reduced_data, new_data)
        If data_reducer is None, the merged Interval's data
        field will be set to None, ignoring all the data fields
        of the merged Intervals.

        On encountering the first Interval to merge, if
        data_initializer is None (default), uses the first
        Interval's data field as the first value for
        current_reduced_data. If data_initializer is not None,
        current_reduced_data is set to a shallow copy of
        data_initiazer created with
            copy.copy(data_initializer).

        Completes in O(n*logn).
        Nc                      !j                    d<   j                         y t               d<     d   j                          d<   j                  t        j                  j
                   d                y r   r   r   s   r   r   z-IntervalTree.merge_equals.<locals>.new_series  r   r&   r   r   )	rR   r   range_matchesr   r0   r;   r   r/   r%   )
r"   r   r   r   r   r   r   r   r   r   s
    ``    @@@r   merge_equalszIntervalTree.merge_equals  s    0 !$"4"45&	V 	V 'Fr
''."%eii"<K#/-9/!:Lfkk-Z*-1*!)%++{OTUDV!WF2JL ' 	fr&   c                 ,    t        | j                        S )z
        Constructs and returns a set of all intervals in the tree.

        Completes in O(n) time.
        :rtype: set of Interval
        )r   r   r,   s    r   itemszIntervalTree.items       4%%&&r&   c                     dt        |       k(  S )zj
        Returns whether the tree is empty.

        Completes in O(1) time.
        :rtype: bool
        r   )rS   r,   s    r   r   zIntervalTree.is_empty  s     CI~r&   c                 f    | j                   }|s
t               S |j                  |t                     S )z
        Returns the set of all intervals that contain p.

        Completes in O(m + log n) time, where:
          * n = size of the tree
          * m = number of matches
        :rtype: set of Interval
        )r   r   search_point)r"   r   roots      r   ra   zIntervalTree.at  s,     }}5L  CE**r&   c           	         | j                   }|s
t               S (}| j                  |j                  |j                        S k\  r
t               S |j                  t                     }| j                  j                        }j                        }|j                  |j                  fdt        ||      D                     t        fd|D              }|S )a#  
        Returns the set of all intervals fully contained in the range
        [begin, end).

        Completes in O(m + k*log n) time, where:
          * n = size of the tree
          * m = number of matches
          * k = size of the search range
        :rtype: set of Interval
        c              3   D   K   | ]  }j                         |     y wr)   keysr*   indexr   s     r   r+   z'IntervalTree.envelop.<locals>.<genexpr>9  $      *
6TUN!%(6T    c              3   ^   K   | ]$  }|j                   k\  r|j                  k  r| & y wr)   )r/   r0   )r*   r$   r/   r0   s     r   r+   z'IntervalTree.envelop.<locals>.<genexpr>?  s.      
2xx5 RVVs] s   *-)r   r   rg   r/   r0   r   r   bisect_leftr>   search_overlapxrange	r"   r/   r0   r   r$   rz   bound_begin	bound_endr   s	    ``     @r   rg   zIntervalTree.envelop"  s     }}5L;B<<"&&11c\5L""5#%0,,$007"..s3	d)) *
6<[)6T*
 
 	  

 
 r&   c           	         | j                   }|s
t               S |(|}| j                  |j                  |j                        S ||k\  r
t               S |j                  |t                     }| j                  j                  |      }j                  |      }|j                  |j                  fdt        ||      D                     |S )a  
        Returns a set of all intervals overlapping the given range.

        Completes in O(m + k*log n) time, where:
          * n = size of the tree
          * m = number of matches
          * k = size of the search range
        :rtype: set of Interval
        c              3   D   K   | ]  }j                         |     y wr)   r   r   s     r   r+   z'IntervalTree.overlap.<locals>.<genexpr>[  r   r   )r   r   rb   r/   r0   r   r   r   r>   r   r   r   s	           @r   rb   zIntervalTree.overlapE  s     }}5L;B<<"&&11c\5L""5#%0,,$007"..s3	d)) *
6<[)6T*
 
 	 r&   c                 V    | j                   sy| j                   j                         d   S )zm
        Returns the lower bound of the first interval in the tree.

        Completes in O(1) time.
        r   r   r   r,   s    r   r/   zIntervalTree.begina  s*     """"'')!,,r&   c                 V    | j                   sy| j                   j                         d   S )zl
        Returns the upper bound of the last interval in the tree.

        Completes in O(1) time.
        r   r   r   r,   s    r   r0   zIntervalTree.endk  s*     """"'')"--r&   c                 R    t        | j                         | j                               S )z
        Returns a minimum-spanning Interval that encloses all the
        members of this IntervalTree. If the tree is empty, returns
        null Interval.
        :rtype: Interval
        )r   r/   r0   r,   s    r   rangezIntervalTree.rangeu  s     

dhhj11r&   c                 J    | sy| j                         | j                         z
  S )z
        Returns the length of the minimum-spanning Interval that
        encloses all the members of this IntervalTree. If the tree
        is empty, return 0.
        r   )r0   r/   r,   s    r   spanzIntervalTree.span~  s!     xxzDJJL((r&   c                 v    | j                   r| j                   j                  |      S d}|st        |       y|S )z
        ## FOR DEBUGGING ONLY ##
        Pretty-prints the structure of the tree.
        If tostring is true, prints nothing and returns a string.
        :rtype: None or str
        )tostringz<empty IntervalTree>N)r   print_structureprint)r"   r   rz   s      r   r   zIntervalTree.print_structure  s7     ====00(0CC+Ffr&   c                    | j                   r	 | j                  j                         | j                   k(  sJ 	 | D ](  }t        |t              rJ dj                  |              | D ](  }|j                         sJ dj                  |              i }| D ]l  }|j                  |v r||j                  xx   d	z  cc<   nd	||j                  <   |j                  |v r||j                  xx   d	z  cc<   ^d	||j                  <   n t        | j                  j                               t        |j                               k(  sJ d
       | j                  j!                         D ](  \  }}||   |k(  rJ dj                  |||   |              | j                  j#                  t                      y| j                  rJ d       | j                  J d       y# t        $ r}t	        d       t        | j                  j                               }t	        d       	  n# t        $ r	 ddlm} Y nw xY w ||| j                   z
         t	        d        || j                   |z
         |d}~ww xY w)zk
        ## FOR DEBUGGING ONLY ##
        Checks the table to ensure that the invariants are held.
        z7Error: the tree and the membership set are out of sync!z(top_node.all_children() - all_intervals:r   )pprintz(all_intervals - top_node.all_children():Nz9Error: Only Interval objects allowed in IntervalTree: {0}z=Error: Null Interval objects not allowed in IntervalTree: {0}r   zDError: boundary_table is out of sync with the intervals in the tree!z5Error: boundary_table[{0}] should be {1}, but is {2}!z&Error: boundary table should be empty!zError: top_node isn't None!)r   r   all_childrenAssertionErrorr   r   	NameErrorr   r[   r   r   r   r/   r0   r   r   r   verify)r"   etivsr   r$   bound_checkrQ   vals           r   r   zIntervalTree.verify  sl   
 }}113t7I7IIII" !"h/ !6":/  ::< !6":'  K88{*)Q.),-K)66[('1,'*+K'  t**//12c+:J:J:L6MM ---M !//557S"3'3. 4##)6[-s$44. 8 MM  ' ** 989*==( .-.(y " M 4==5578@A.  .-.td0001@At))D01s;   )G 	I1#9I,H I, H2/I,1H22:I,,I1c                 
   t        |       dk  ryt        |       | j                  j                         fd}| j                  j                         |       d}t	        |j                               }||d<   |r|S |S )z
        Returns a number between 0 and 1, indicating how suboptimal the tree
        is. The lower, the better. Roughly, this number represents the
        fraction of flawed Intervals in the tree.
        :rtype: float
        r   g        c                  4    z
  } dz
  }| t        |      z  S )z
            Returns a normalized score, indicating roughly how many times
            intervals share s_center with other intervals. Output is full-scale
            from 0 to 1.
            :rtype: float
            r   )float)rawmaximummns     r   s_center_scorez*IntervalTree.score.<locals>.s_center_score  s&     a%C!eGw''r&   )depths_center_cumulative)rS   r   count_nodesdepth_scorer   values)r"   full_reportr   report
cumulativer   r   s        @@r   scorezIntervalTree.score  s     t9>IMM%%'		( ]]..q!4&(
 )
 *}Mr&   c                     	 |j                   |j                  }}|| j                         }|t        |       S || j	                         }| j                  ||      S # t        $ r | j                  |      cY S w xY w)a7  
        Returns a set of all intervals overlapping the given index or
        slice.

        Completes in O(k * log(n) + m) time, where:
          * n = size of the tree
          * m = number of matches
          * k = size of the search range (this is 1 for a point)
        :rtype: set of Interval
        )startstopr/   r   r0   rb   AttributeErrorra   )r"   r   r   r   s       r   __getitem__zIntervalTree.__getitem__  su    
	"++uzz4E}

<t9$|xxz<<t,, 	"775>!	"s   6A #A A:9A:c                 R    | j                  |j                  |j                  |       y)a  
        Adds a new interval to the tree. A shortcut for
        add(Interval(index.start, index.stop, value)).

        If an identical Interval object with equal range and data
        already exists, does nothing.

        Completes in O(log n) time.
        N)r<   r   r   )r"   r   values      r   __setitem__zIntervalTree.__setitem__  s     			%++uzz51r&   c                 &    | j                  |       y)z5
        Delete all items overlapping point.
        N)re   )r"   rq   s     r   __delitem__zIntervalTree.__delitem__&  s     	E"r&   c                     || j                   v S )z
        Returns whether item exists as an Interval in the tree.
        This method only returns True for exact matches; for
        overlaps, see the overlaps() method.

        Completes in O(1) time.
        :rtype: bool
        )r   )r"   items     r   __contains__zIntervalTree.__contains__,  s     t))))r&   c                      t        |||      | v S )zz
        Shortcut for (Interval(begin, end, data) in tree).

        Completes in O(1) time.
        :rtype: bool
        r   r:   s       r   	containsizIntervalTree.containsi<  s     sD)T11r&   c                 6    | j                   j                         S )z
        Returns an iterator over all the intervals in the tree.

        Completes in O(1) time.
        :rtype: collections.Iterable[Interval]
        )r   __iter__r,   s    r   r   zIntervalTree.__iter__E  s     !!**,,r&   c                 ,    t        | j                        S )zr
        Returns how many intervals are in the tree.

        Completes in O(1) time.
        :rtype: int
        )rS   r   r,   s    r   __len__zIntervalTree.__len__O  r   r&   c                 X    t        |t              xr | j                  |j                  k(  S )z
        Whether two IntervalTrees are equal.

        Completes in O(n) time if sizes are equal; O(1) time otherwise.
        :rtype: bool
        )r[   r   r   rO   s     r   __eq__zIntervalTree.__eq__X  s,     ul+ 6%"5"55	
r&   c                 @    t        |       }|sydj                  |      S )z
        :rtype: str
        zIntervalTree()zIntervalTree({0}))rR   r   )r"   r   s     r   __repr__zIntervalTree.__repr__d  s$     Tl#&--c22r&   c                 :    t         t        | j                        ffS )z7
        For pickle-ing.
        :rtype: tuple
        )r   rR   r   r,   s    r   
__reduce__zIntervalTree.__reduce__p  s    
 fT%7%78:::r&   r)   )NNT)NN)F)>__name__
__module____qualname____doc__classmethodr   r%   r
   r    r4   r7   r   r<   appendir>   r@   rB   rD   rF   rJ   rL   rN   rV   rY   r]   r_   re   rh   rn   rr   rt   r   r   r   r   r   r   r   r   r   ra   rg   rb   r/   r0   r   r   r   r   r   r   r   r   r   r   r   iterr  r  r  __str__r   r&   r   r   r   ,   sC   EL ! !%(6) * '* F4 G* 7*8	!4
! ! 2 ,,? 	5
,.?B:x'+!F8-.2) F.P F".
2#* 2- D'

3 G;r&   r   N)r  r2   r   noder   numbersr   sortedcontainersr   r
   warningsr   collections.abcr   ImportErrorcollectionsr   r   r   r   r  r&   r   <module>r     se   *    '  '*
I;: I;  '&'
  Fs    = A A
AAA