Debian Codegraph @

lib/ClusterShell/RangeSet.py

raw symbols SCIP
1 #
2 # Copyright (C) 2012-2016 CEA/DAM
3 # Copyright (C) 2012-2016 Aurelien Degremont <[email protected]>
4 # Copyright (C) 2015-2017 Stephane Thiell <[email protected]>
5 #
6 # This file is part of ClusterShell.
7 #
8 # ClusterShell is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License, or (at your option) any later version.
12 #
13 # ClusterShell is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 # Lesser General Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with ClusterShell; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
22 """
23 Cluster range set module.
24
25 Instances of RangeSet provide similar operations than the builtin set type,
26 extended to support cluster ranges-like format and stepping support ("0-8/2").
27 """
28
29 from functools import reduce
30 from itertools import product
31 from operator import mul
32
33 # Python 3 compatibility
34 try:
35 basestring
36 except NameError:
37 basestring = str
38
39
40 def _normalized_index_bounds(length, start, stop):
41 """Return list.index()-like normalized start/stop bounds."""
42 if start < 0:
43 start = max(0, length + start)
44 if stop is None:
45 stop = length
46 elif stop < 0:
47 stop = max(0, length + stop)
48 return start, stop
49
50
51 __all__ = ['RangeSetException',
52 'RangeSetParseError',
53 'RangeSetPaddingError',
54 'RangeSet',
55 'RangeSetND',
56 'AUTOSTEP_DISABLED']
57
58 # Special constant used to force turn off autostep feature.
59 # Note: +inf is 1E400, but a bug in python 2.4 makes it impossible to be
60 # pickled, so we use less. Later, we could consider sys.maxint here.
61 AUTOSTEP_DISABLED = 1E100
62
63
64 class RangeSetException(Exception):
65 """Base RangeSet exception class."""
66
67 class RangeSetParseError(RangeSetException):
68 """Raised when RangeSet parsing cannot be done properly."""
69 def __init__(self, part, msg):
70 if part:
71 msg = "%s : \"%s\"" % (msg, part)
72 RangeSetException.__init__(self, msg)
73 # faulty subrange; this allows you to target the error
74 self.part = part
75
76 class RangeSetPaddingError(RangeSetParseError):
77 """Raised when a fatal padding incoherence occurs"""
78 def __init__(self, part, msg):
79 RangeSetParseError.__init__(self, part, "padding mismatch (%s)" % msg)
80
81
82 class RangeSet(set):
83 """
84 Mutable set of cluster node indexes featuring a fast range-based API.
85
86 This class aims to ease the management of potentially large cluster range
87 sets and is used by the :class:`.NodeSet` class.
88
89 RangeSet basic constructors:
90
91 >>> rset = RangeSet() # empty RangeSet
92 >>> rset = RangeSet("5,10-42") # contains '5', '10' to '42'
93 >>> rset = RangeSet("0-10/2") # contains '0', '2', '4', '6', '8', '10'
94 >>> rset = RangeSet("00-10/2") # contains '00', '02', '04', '06', '08', '10'
95
96 Also any iterable of integers can be specified as first argument:
97
98 >>> RangeSet([3, 6, 8, 7, 1])
99 1,3,6-8
100 >>> rset2 = RangeSet(rset)
101
102 Padding of ranges (eg. "003-009") is inferred from input arguments and
103 managed automatically. This is new in ClusterShell v1.9, where mixed lengths
104 zero padding is now supported within the same RangeSet. The instance
105 variable `padding` has become a property that can still be used to either
106 get the max padding length in the set, or force a fixed length zero-padding
107 on the set.
108
109 RangeSet is itself a set and as such, provides an iterator over its items
110 as strings (strings are used since v1.9). It is recommended to use the
111 explicit iterators :meth:`RangeSet.intiter` and :meth:`RangeSet.striter`
112 when iterating over a RangeSet.
113
114 RangeSet provides methods like :meth:`RangeSet.union`,
115 :meth:`RangeSet.intersection`, :meth:`RangeSet.difference`,
116 :meth:`RangeSet.symmetric_difference` and their in-place versions
117 :meth:`RangeSet.update`, :meth:`RangeSet.intersection_update`,
118 :meth:`RangeSet.difference_update`,
119 :meth:`RangeSet.symmetric_difference_update` which conform to the Python
120 Set API.
121 """
122 _VERSION = 4 # serial version number
123
124 def __init__(self, pattern=None, autostep=None):
125 """Initialize RangeSet object.
126
127 :param pattern: optional string pattern
128 :param autostep: optional autostep threshold
129 """
130 set.__init__(self)
131
132 if pattern is not None and not isinstance(pattern, basestring):
133 pattern = ",".join("%s" % i for i in pattern)
134
135 if isinstance(pattern, RangeSet):
136 self._autostep = pattern._autostep
137 else:
138 self._autostep = None
139 self.autostep = autostep #: autostep threshold public instance attribute
140
141 if isinstance(pattern, basestring):
142 self._parse(pattern)
143
144 def _parse(self, pattern):
145 """Parse string of comma-separated x-y/step -like ranges"""
146 # Comma separated ranges
147 for subrange in pattern.split(','):
148 subrange = subrange.strip() # ignore whitespaces
149 if subrange.find('/') < 0:
150 baserange, step = subrange, 1
151 else:
152 baserange, step = subrange.split('/', 1)
153
154 try:
155 step = int(step)
156 except ValueError:
157 raise RangeSetParseError(subrange,
158 "cannot convert string to integer")
159
160 begin_sign = end_sign = 1 # sign "scale factor"
161
162 if baserange.find('-') < 0:
163 if step != 1:
164 raise RangeSetParseError(subrange, "invalid step usage")
165 begin = end = baserange
166 else:
167 # ignore whitespaces in a range
168 try:
169 begin, end = (n.strip() for n in baserange.split('-'))
170 if not begin: # single negative number "-5"
171 begin = end
172 begin_sign = end_sign = -1
173 except ValueError:
174 try:
175 # -0-3
176 _, begin, end = (n.strip()
177 for n in baserange.split('-'))
178 begin_sign = -1
179 except ValueError:
180 # -8--4
181 _, begin, _, end = (n.strip()
182 for n in baserange.split('-'))
183 begin_sign = end_sign = -1
184
185 # compute padding and return node range info tuple
186 try:
187 pad = endpad = 0
188 if int(begin) != 0:
189 begins = begin.lstrip("0")
190 if len(begin) - len(begins) > 0:
191 pad = len(begin)
192 start = int(begins)
193 else:
194 if len(begin) > 1:
195 pad = len(begin)
196 start = 0
197 if int(end) != 0:
198 ends = end.lstrip("0")
199 else:
200 ends = end
201 # explicit padding for begin and end must match
202 if len(end) - len(ends) > 0:
203 endpad = len(end)
204 if (pad > 0 or endpad > 0) and len(begin) != len(end):
205 raise RangeSetParseError(subrange,
206 "padding length mismatch")
207
208 stop = int(ends)
209 except ValueError:
210 if len(subrange) == 0:
211 msg = "empty range"
212 else:
213 msg = "cannot convert string to integer"
214 raise RangeSetParseError(subrange, msg)
215
216 # check preconditions
217 if pad > 0 and begin_sign < 0:
218 errmsg = "padding not supported in negative ranges"
219 raise RangeSetParseError(subrange, errmsg)
220
221 if stop > 1e100 or start * begin_sign > stop * end_sign or step < 1:
222 raise RangeSetParseError(subrange, "invalid values in range")
223
224 self.add_range(start * begin_sign, stop * end_sign + 1, step, pad)
225
226 @classmethod
227 def fromlist(cls, rnglist, autostep=None):
228 """Class method that returns a new RangeSet with ranges from provided
229 list."""
230 inst = RangeSet(autostep=autostep)
231 inst.updaten(rnglist)
232 return inst
233
234 @classmethod
235 def fromone(cls, index, pad=0, autostep=None):
236 """
237 Class method that returns a new RangeSet of one single item or
238 a single range. Accepted input arguments can be:
239 - integer and padding length
240 - slice object and padding length
241 - string (1.9+) with padding automatically detected (pad is ignored)
242 """
243 inst = RangeSet(autostep=autostep)
244 # support slice object with duck-typing
245 try:
246 inst.add(index, pad)
247 except TypeError:
248 if not index.stop:
249 raise ValueError("Invalid range upper limit (%s)" % index.stop)
250 inst.add_range(index.start or 0, index.stop, index.step or 1, pad)
251 return inst
252
253 @property
254 def padding(self):
255 """Get largest padding value of whole set"""
256 result = None
257 for si in self:
258 idx, digitlen = int(si), len(si)
259 # explicitly padded?
260 if digitlen > 1 and si[0] == '0':
261 # result always grows bigger as we iterate over a sorted set
262 # with largest padded values at the end
263 result = digitlen
264 return result
265
266 @padding.setter
267 def padding(self, value):
268 """Force padding length on the whole set"""
269 if value is None:
270 value = 1
271 cpyset = set(self)
272 self.clear()
273 for i in cpyset:
274 self.add(int(i), pad=value)
275
276 def get_autostep(self):
277 """Get autostep value (property)"""
278 if self._autostep >= AUTOSTEP_DISABLED:
279 return None
280 else:
281 # +1 as user wants node count but it means real steps here
282 return self._autostep + 1
283
284 def set_autostep(self, val):
285 """Set autostep value (property)"""
286 if val is None:
287 # disabled by default for compat with other cluster tools
288 self._autostep = AUTOSTEP_DISABLED
289 else:
290 # - 1 because user means node count, but we mean real steps
291 # (this operation has no effect on AUTOSTEP_DISABLED value)
292 self._autostep = int(val) - 1
293
294 autostep = property(get_autostep, set_autostep)
295
296 def dim(self):
297 """Get the number of dimensions of this RangeSet object. Common
298 method with RangeSetND. Here, it will always return 1 unless
299 the object is empty, in that case it will return 0."""
300 return int(len(self) > 0)
301
302 @staticmethod
303 def _sortkey(elem):
304 """Sort key used to order RangeSet elements (mixed padding support):
305 sort by both string length and index."""
306 if elem.startswith('-'):
307 return (-len(elem), int(elem))
308 return (len(elem), elem)
309
310 def _sorted(self):
311 """Get sorted list from inner set."""
312 # For mixed padding support, sort by both string length and index
313 return sorted(set.__iter__(self), key=self._sortkey)
314
315 def __iter__(self):
316 """Iterate over each element in RangeSet, currently as integers, with
317 no padding information.
318 To guarantee future compatibility, please use the methods intiter()
319 or striter() instead."""
320 return iter(self._sorted())
321
322 def striter(self):
323 """Iterate over each element in RangeSet as strings with optional
324 zero-padding."""
325 return iter(self._sorted())
326
327 def intiter(self):
328 """Iterate over each element in RangeSet as integer.
329 Zero padding info is ignored."""
330 for e in self._sorted():
331 yield int(e)
332
333 def contiguous(self):
334 """Object-based iterator over contiguous range sets."""
335 for sli, pad in self._contiguous_slices():
336 yield RangeSet.fromone(slice(sli.start, sli.stop, sli.step), pad)
337
338 def __reduce__(self):
339 """Return state information for pickling."""
340 pattern = str(self) if self else None # RangeSet("") raises by design
341 return self.__class__, (pattern,), \
342 { 'padding': self.padding, \
343 '_autostep': self._autostep, \
344 '_version' : RangeSet._VERSION }
345
346 def __setstate__(self, dic):
347 """called upon unpickling"""
348 self.__dict__.update(dic)
349 if getattr(self, '_version', 0) < RangeSet._VERSION:
350 # unpickle from old version?
351 if getattr(self, '_version', 0) <= 1:
352 # v1 (no object versioning) - CSv1.3
353 setattr(self, '_ranges', [(slice(start, stop + 1, step), pad) \
354 for start, stop, step, pad in getattr(self, '_ranges')])
355 elif hasattr(self, '_ranges'):
356 # v2 - CSv1.4-1.5
357 self_ranges = getattr(self, '_ranges')
358 if self_ranges and not isinstance(self_ranges[0][0], slice):
359 # workaround for object pickled from Python < 2.5
360 setattr(self, '_ranges', [(slice(start, stop, step), pad) \
361 for (start, stop, step), pad in self_ranges])
362
363 if hasattr(self, '_ranges'):
364 # convert to v3
365 for sli, pad in getattr(self, '_ranges'):
366 self.add_range(sli.start, sli.stop, sli.step, pad)
367 delattr(self, '_ranges')
368 delattr(self, '_length')
369
370 if getattr(self, '_version', 0) == 3: # 1.6 - 1.8
371 padding = getattr(self, 'padding', 0)
372 # convert integer set to string set
373 cpyset = set(self)
374 self.clear()
375 for i in cpyset:
376 self.add(i, pad=padding) # automatic conversion
377
378 def _strslices(self):
379 """Stringify slices list (x-y/step format)"""
380 for sli, pad in self._folded_slices():
381 if sli.start + 1 == sli.stop:
382 yield "%0*d" % (pad, sli.start)
383 else:
384 assert sli.step >= 0, "Internal error: sli.step < 0"
385 if sli.step == 1:
386 yield "%0*d-%0*d" % (pad, sli.start, pad, sli.stop - 1)
387 else:
388 yield "%0*d-%0*d/%d" % (pad, sli.start, pad, sli.stop - 1, \
389 sli.step)
390
391 def __str__(self):
392 """Get comma-separated range-based string (x-y/step format)."""
393 return ','.join(self._strslices())
394
395 # __repr__ is the same as __str__ as it is a valid expression that
396 # could be used to recreate a RangeSet with the same value
397 __repr__ = __str__
398
399 def _slices_padding(self, autostep=AUTOSTEP_DISABLED):
400 """Iterator over (slices, padding).
401
402 Iterator over RangeSet slices, either a:b:1 slices if autostep
403 is disabled (default), or a:b:step slices if autostep is specified.
404 """
405 #
406 # Now support mixed lengths zero-padding (v1.9)
407 cur_pad = 0
408 cur_padded = False
409 cur_start = None
410 cur_step = None
411 last_idx = None
412
413 for si in self._sorted():
414
415 # numerical index and length of digits
416 idx, digitlen = int(si), len(si)
417
418 # is current digit zero-padded?
419 padded = (digitlen > 1 and si[0] == '0')
420
421 if cur_start is not None:
422 padding_mismatch = False
423 step_mismatch = False
424
425 # check conditions to yield
426 # - padding mismatch
427 # - step check (step=1 is just a special case if contiguous)
428
429 if cur_padded:
430 # currently strictly padded, our next item could be
431 # unpadded but with the same length
432 if digitlen != cur_pad:
433 padding_mismatch = True
434 else:
435 # current not padded, and because the set is sorted,
436 # it should stay that way
437 if padded:
438 padding_mismatch = True
439
440 if not padding_mismatch:
441 # does current range lead to broken step?
442 if cur_step is not None:
443 # only consider it if step is defined
444 if cur_step != idx - last_idx:
445 step_mismatch = True
446
447 if padding_mismatch or step_mismatch:
448 if cur_step is not None:
449 # stepped is True when autostep setting does apply
450 stepped = (cur_step == 1) or (last_idx - cur_start >= autostep * cur_step)
451 step = cur_step
452 else:
453 stepped = True
454 step = 1
455
456 if stepped:
457 yield slice(cur_start, last_idx + 1, step), cur_pad if cur_padded else 0
458 cur_start = idx
459 cur_padded = padded
460 cur_pad = digitlen
461 else:
462 if padding_mismatch:
463 stop = last_idx + 1
464 else:
465 stop = last_idx - step + 1
466
467 for j in range(cur_start, stop, step):
468 yield slice(j, j + 1, 1), cur_pad if cur_padded else 0
469
470 if padding_mismatch:
471 cur_start = idx
472 cur_padded = padded
473 cur_pad = digitlen
474 else:
475 cur_start = last_idx
476
477 cur_step = idx - last_idx if step_mismatch else None
478 last_idx = idx
479 continue
480
481 else:
482 # first index
483 cur_padded = padded
484 cur_pad = digitlen
485 cur_start = idx
486 cur_step = None
487 last_idx = idx
488 continue
489
490 cur_step = idx - last_idx
491 last_idx = idx
492
493 if cur_start is not None:
494 if cur_step is not None:
495 # stepped is True when autostep setting does apply
496 stepped = (last_idx - cur_start >= self._autostep * cur_step)
497 else:
498 stepped = True
499
500 if stepped or cur_step == 1:
501 yield slice(cur_start, last_idx + 1, cur_step), cur_pad if cur_padded else 0
502 else:
503 for j in range(cur_start, last_idx + 1, cur_step):
504 yield slice(j, j + 1, 1), cur_pad if cur_padded else 0
505
506 def _contiguous_slices(self):
507 """Internal iterator over contiguous slices in RangeSet."""
508 return self._slices_padding()
509
510 def _folded_slices(self):
511 """Internal generator over ranges organized by step."""
512 return self._slices_padding(self._autostep)
513
514 def slices(self):
515 """
516 Iterate over RangeSet ranges as Python slide objects.
517 NOTE: zero-padding info is not provided
518 """
519 for sli, pad in self._folded_slices():
520 yield sli
521
522 def __getitem__(self, index):
523 """
524 Return the element at index or a subrange when a slice is specified.
525 """
526 if isinstance(index, slice):
527 inst = RangeSet()
528 inst._autostep = self._autostep
529 inst.update(self._sorted()[index])
530 return inst
531 elif isinstance(index, int):
532 return self._sorted()[index]
533 else:
534 raise TypeError("%s indices must be integers" %
535 self.__class__.__name__)
536
537 def index(self, elem, start=0, stop=None):
538 """
539 Return the zero-based index of element in the sorted RangeSet.
540
541 This is the reverse operation of :meth:`RangeSet.__getitem__` and
542 behaves like the ``index()`` method of the ``list`` type. The element
543 may be given as a string (zero-padding is then significant) or as an
544 integer. The optional `start` and `stop` arguments restrict the search
545 to the matching subsequence, and may be negative (counted from the
546 end).
547
548 :raises ValueError: the element is not present in the RangeSet
549 """
550 if isinstance(elem, basestring):
551 key = elem
552 else:
553 key = str(elem)
554 # set membership is fast and padding-aware for strings
555 if not set.__contains__(self, key):
556 raise ValueError("%s is not in RangeSet" % (elem,))
557 # Compute the rank in a single O(n) pass (no full sort) by counting
558 # the elements that come before `elem` in iteration order.
559 tkey = self._sortkey(key)
560 found = sum(1 for idx in set.__iter__(self)
561 if self._sortkey(idx) < tkey)
562 if start != 0 or stop is not None:
563 start, stop = _normalized_index_bounds(len(self), start, stop)
564 if not start <= found < stop:
565 raise ValueError("%s is not in RangeSet" % (elem,))
566 return found
567
568 def split(self, nbr):
569 """
570 Split the rangeset into nbr sub-rangesets (at most). Each
571 sub-rangeset will have the same number of elements more or
572 less 1. Current rangeset remains unmodified. Returns an
573 iterator.
574
575 >>> RangeSet("1-5").split(3)
576 RangeSet("1-2")
577 RangeSet("3-4")
578 RangeSet("foo5")
579 """
580 assert(nbr > 0)
581
582 # We put the same number of element in each sub-nodeset.
583 slice_size = len(self) // int(nbr)
584 left = len(self) % nbr
585
586 begin = 0
587 for i in range(0, min(nbr, len(self))):
588 length = slice_size + int(i < left)
589 yield self[begin:begin + length]
590 begin += length
591
592 def add_range(self, start, stop, step=1, pad=0):
593 """
594 Add a range (start, stop, step and padding length) to RangeSet.
595 Like the Python built-in function *range()*, the last element
596 is the largest start + i * step less than stop.
597 """
598 assert start < stop, "please provide ordered node index ranges"
599 assert step > 0
600 assert pad >= 0
601 assert stop - start < 1e9, "range too large"
602
603 if pad == 0:
604 set.update(self, ("%d" % i for i in range(start, stop, step)))
605 else:
606 set.update(self, ("%0*d" % (pad, i) for i in range(start, stop, step)))
607
608 def copy(self):
609 """Return a shallow copy of a RangeSet."""
610 cpy = self.__class__()
611 cpy._autostep = self._autostep
612 cpy.update(self)
613 return cpy
614
615 __copy__ = copy # For the copy module
616
617 def __eq__(self, other):
618 """
619 RangeSet equality comparison.
620 """
621 # Return NotImplemented instead of raising TypeError, to
622 # indicate that the comparison is not implemented with respect
623 # to the other type (the other comparand then gets a chance to
624 # determine the result, then it falls back to object address
625 # comparison).
626 if not isinstance(other, RangeSet):
627 return NotImplemented
628 return len(self) == len(other) and self.issubset(other)
629
630 # Standard set operations: union, intersection, both differences.
631 # Each has an operator version (e.g. __or__, invoked with |) and a
632 # method version (e.g. union).
633 # Subtle: Each pair requires distinct code so that the outcome is
634 # correct when the type of other isn't suitable. For example, if
635 # we did "union = __or__" instead, then Set().union(3) would return
636 # NotImplemented instead of raising TypeError (albeit that *why* it
637 # raises TypeError as-is is also a bit subtle).
638
639 def __or__(self, other):
640 """Return the union of two RangeSets as a new RangeSet.
641
642 (I.e. all elements that are in either set.)
643 """
644 if not isinstance(other, set):
645 return NotImplemented
646 return self.union(other)
647
648 def union(self, other):
649 """Return the union of two RangeSets as a new RangeSet.
650
651 (I.e. all elements that are in either set.)
652 """
653 self_copy = self.copy()
654 self_copy.update(other)
655 return self_copy
656
657 def __and__(self, other):
658 """Return the intersection of two RangeSets as a new RangeSet.
659
660 (I.e. all elements that are in both sets.)
661 """
662 if not isinstance(other, set):
663 return NotImplemented
664 return self.intersection(other)
665
666 def intersection(self, other):
667 """Return the intersection of two RangeSets as a new RangeSet.
668
669 (I.e. all elements that are in both sets.)
670 """
671 self_copy = self.copy()
672 self_copy.intersection_update(other)
673 return self_copy
674
675 def __xor__(self, other):
676 """Return the symmetric difference of two RangeSets as a new RangeSet.
677
678 (I.e. all elements that are in exactly one of the sets.)
679 """
680 if not isinstance(other, set):
681 return NotImplemented
682 return self.symmetric_difference(other)
683
684 def symmetric_difference(self, other):
685 """Return the symmetric difference of two RangeSets as a new RangeSet.
686
687 (ie. all elements that are in exactly one of the sets.)
688 """
689 self_copy = self.copy()
690 self_copy.symmetric_difference_update(other)
691 return self_copy
692
693 def __sub__(self, other):
694 """Return the difference of two RangeSets as a new RangeSet.
695
696 (I.e. all elements that are in this set and not in the other.)
697 """
698 if not isinstance(other, set):
699 return NotImplemented
700 return self.difference(other)
701
702 def difference(self, other):
703 """Return the difference of two RangeSets as a new RangeSet.
704
705 (I.e. all elements that are in this set and not in the other.)
706 """
707 self_copy = self.copy()
708 self_copy.difference_update(other)
709 return self_copy
710
711 # Membership test
712
713 def __contains__(self, element):
714 """Report whether an element is a member of a RangeSet.
715 Element can be either another RangeSet object, a string or an
716 integer.
717
718 Called in response to the expression ``element in self``.
719 """
720 if isinstance(element, set):
721 return element.issubset(self)
722
723 return set.__contains__(self, str(element))
724
725 # Subset and superset test
726
727 def issubset(self, other):
728 """Report whether another set contains this RangeSet."""
729 self._binary_sanity_check(other)
730 return set.issubset(self, other)
731
732 def issuperset(self, other):
733 """Report whether this RangeSet contains another set."""
734 self._binary_sanity_check(other)
735 return set.issuperset(self, other)
736
737 # Inequality comparisons using the is-subset relation.
738 __le__ = issubset
739 __ge__ = issuperset
740
741 def __lt__(self, other):
742 self._binary_sanity_check(other)
743 return len(self) < len(other) and self.issubset(other)
744
745 def __gt__(self, other):
746 self._binary_sanity_check(other)
747 return len(self) > len(other) and self.issuperset(other)
748
749 # Assorted helpers
750
751 def _binary_sanity_check(self, other):
752 """Check that the other argument to a binary operation is also a set,
753 raising a TypeError otherwise."""
754 if not isinstance(other, set):
755 raise TypeError("Binary operation only permitted between sets")
756
757 # In-place union, intersection, differences.
758 # Subtle: The xyz_update() functions deliberately return None,
759 # as do all mutating operations on built-in container types.
760 # The __xyz__ spellings have to return self, though.
761
762 def __ior__(self, other):
763 """Update a RangeSet with the union of itself and another."""
764 self._binary_sanity_check(other)
765 set.__ior__(self, other)
766 return self
767
768 def union_update(self, other):
769 """Update a RangeSet with the union of itself and another."""
770 self.update(other)
771
772 def __iand__(self, other):
773 """Update a RangeSet with the intersection of itself and another."""
774 self._binary_sanity_check(other)
775 set.__iand__(self, other)
776 return self
777
778 def intersection_update(self, other):
779 """Update a RangeSet with the intersection of itself and another."""
780 set.intersection_update(self, other)
781
782 def __ixor__(self, other):
783 """Update a RangeSet with the symmetric difference of itself and
784 another."""
785 self._binary_sanity_check(other)
786 set.symmetric_difference_update(self, other)
787 return self
788
789 def symmetric_difference_update(self, other):
790 """Update a RangeSet with the symmetric difference of itself and
791 another."""
792 set.symmetric_difference_update(self, other)
793
794 def __isub__(self, other):
795 """Remove all elements of another set from this RangeSet."""
796 self._binary_sanity_check(other)
797 set.difference_update(self, other)
798 return self
799
800 def difference_update(self, other, strict=False):
801 """Remove all elements of another set from this RangeSet.
802
803 If strict is True, raise KeyError if an element cannot be removed.
804 (strict is a RangeSet addition)"""
805 if strict and other not in self:
806 raise KeyError(set.difference(other, self).pop())
807 set.difference_update(self, other)
808
809 # Python dict-like mass mutations: update, clear
810
811 def update(self, iterable):
812 """Add all indexes (as strings) from an iterable (such as a list)."""
813 assert not isinstance(iterable, basestring)
814 set.update(self, iterable)
815
816 def updaten(self, rangesets):
817 """
818 Update a rangeset with the union of itself and several others.
819 """
820 for rng in rangesets:
821 if isinstance(rng, set):
822 self.update(str(i) for i in rng) # 1.9+: force cast to str
823 else:
824 self.update(RangeSet(rng))
825
826 def clear(self):
827 """Remove all elements from this RangeSet."""
828 set.clear(self)
829
830 # Single-element mutations: add, remove, discard
831
832 def add(self, element, pad=0):
833 """Add an element to a RangeSet.
834 This has no effect if the element is already present.
835
836 ClusterShell 1.9+ uses strings instead of integers to better manage
837 zero-padded ranges with mixed lengths. This method supports either a
838 string or an integer with padding info.
839
840 :param element: the element to add (integer or string)
841 :param pad: zero padding length (integer); ignored if element is string
842 """
843 if isinstance(element, basestring):
844 set.add(self, element)
845 else:
846 set.add(self, "%0*d" % (pad, int(element)))
847
848 def remove(self, element, pad=0):
849 """Remove an element from a RangeSet.
850
851 ClusterShell 1.9+ uses strings instead of integers to better manage
852 zero-padded ranges with mixed lengths. This method supports either a
853 string or an integer with padding info.
854
855 :param element: the element to remove (integer or string)
856 :param pad: zero padding length (integer); ignored if element is string
857 :raises KeyError: element is not contained in RangeSet
858 :raises ValueError: element is not castable to integer
859 """
860 if isinstance(element, basestring):
861 set.remove(self, element)
862 else:
863 set.remove(self, "%0*d" % (pad, int(element)))
864
865 def discard(self, element, pad=0):
866 """Discard an element from a RangeSet if it is a member.
867
868 If the element is not a member, do nothing.
869
870 ClusterShell 1.9+ uses strings instead of integers to better manage
871 zero-padded ranges with mixed lengths. This method supports either a
872 string or an integer with padding info.
873
874 :param element: the element to remove (integer or string)
875 :param pad: zero padding length (integer); ignored if element is string
876 """
877 try:
878 if isinstance(element, basestring):
879 set.discard(self, element)
880 else:
881 set.discard(self, "%0*d" % (pad, int(element)))
882 except ValueError:
883 pass # ignore other object types
884
885
886 class RangeSetND(object):
887 """
888 Build a N-dimensional RangeSet object.
889
890 .. warning:: You don't usually need to use this class directly, use
891 :class:`.NodeSet` instead that has ND support.
892
893 Empty constructor::
894
895 RangeSetND()
896
897 Build from a list of list of :class:`RangeSet` objects::
898
899 RangeSetND([[rs1, rs2, rs3, ...], ...])
900
901 Strings are also supported::
902
903 RangeSetND([["0-3", "4-10", ...], ...])
904
905 Integers are also supported::
906
907 RangeSetND([(0, 4), (0, 5), (1, 4), (1, 5), ...]
908 """
909 def __init__(self, args=None, pads=None, autostep=None, copy_rangeset=True):
910 """RangeSetND initializer
911
912 All parameters are optional.
913
914 :param args: generic "list of list" input argument (default is None)
915 :param pads: list of 0-padding length (default is to not pad any
916 dimensions)
917 :param autostep: autostep threshold (use range/step notation if more
918 than #autostep items meet the condition) - default is
919 off (None)
920 :param copy_rangeset: (advanced) if set to False, do not copy RangeSet
921 objects from args (transfer ownership), which is
922 faster. In that case, you should not modify these
923 objects afterwards (default is True).
924 """
925 # RangeSetND are arranged as a list of N-dimensional RangeSet vectors
926 self._veclist = []
927 # Dirty flag to avoid doing veclist folding too often
928 self._dirty = True
929 # Initialize autostep through property
930 self._autostep = None
931 self.autostep = autostep #: autostep threshold public instance attribute
932 # Hint on whether several dimensions are varying or not
933 self._multivar_hint = False
934 if args is None:
935 return
936 for rgvec in args:
937 if rgvec:
938 if isinstance(rgvec[0], basestring):
939 self._veclist.append([RangeSet(rg, autostep=autostep) \
940 for rg in rgvec])
941 elif isinstance(rgvec[0], RangeSet):
942 if copy_rangeset:
943 self._veclist.append([rg.copy() for rg in rgvec])
944 else:
945 self._veclist.append(rgvec)
946 else:
947 if pads is None:
948 self._veclist.append( \
949 [RangeSet.fromone(rg, autostep=autostep) \
950 for rg in rgvec])
951 else:
952 self._veclist.append( \
953 [RangeSet.fromone(rg, pad, autostep) \
954 for rg, pad in zip(rgvec, pads)])
955
956 class precond_fold(object):
957 """Decorator to ease internal folding management"""
958 def __call__(self, func):
959 def inner(*args, **kwargs):
960 rgnd, fargs = args[0], args[1:]
961 if rgnd._dirty:
962 rgnd._fold()
963 return func(rgnd, *fargs, **kwargs)
964 # modify the decorator meta-data for pydoc
965 # Note: should be later replaced by @wraps (functools)
966 # as of Python 2.5
967 inner.__name__ = func.__name__
968 inner.__doc__ = func.__doc__
969 inner.__dict__ = func.__dict__
970 inner.__module__ = func.__module__
971 return inner
972
973 @precond_fold()
974 def copy(self):
975 """Return a new, mutable shallow copy of a RangeSetND."""
976 cpy = self.__class__()
977 # Shallow "to the extent possible" says the copy module, so here that
978 # means calling copy() on each sub-RangeSet to keep mutability.
979 cpy._veclist = [[rg.copy() for rg in rgvec] for rgvec in self._veclist]
980 cpy._dirty = self._dirty
981 return cpy
982
983 __copy__ = copy # For the copy module
984
985 def __eq__(self, other):
986 """RangeSetND equality comparison."""
987 # Return NotImplemented instead of raising TypeError, to
988 # indicate that the comparison is not implemented with respect
989 # to the other type (the other comparand then gets a change to
990 # determine the result, then it falls back to object address
991 # comparison).
992 if not isinstance(other, RangeSetND):
993 return NotImplemented
994 return len(self) == len(other) and self.issubset(other)
995
996 def __bool__(self):
997 return bool(self._veclist)
998
999 __nonzero__ = __bool__ # Python 2 compat
1000
1001 def __len__(self):
1002 """Count unique elements in N-dimensional rangeset."""
1003 return sum([reduce(mul, [len(rg) for rg in rgvec]) \
1004 for rgvec in self.veclist])
1005
1006 @precond_fold()
1007 def __str__(self):
1008 """String representation of N-dimensional RangeSet."""
1009 result = ""
1010 for rgvec in self._veclist:
1011 result += "; ".join([str(rg) for rg in rgvec])
1012 result += "\n"
1013 return result
1014
1015 @precond_fold()
1016 def __iter__(self):
1017 return self._iter()
1018
1019 def _iter(self):
1020 """Iterate through individual items as tuples."""
1021 for vec in self._veclist:
1022 for ivec in product(*vec):
1023 yield ivec
1024
1025 @precond_fold()
1026 def iter_padding(self):
1027 """Iterate through individual items as tuples with padding info.
1028 As of v1.9, this method returns the largest padding value of each
1029 items, as mixed length padding is allowed."""
1030 for vec in self._veclist:
1031 for ivec in product(*vec):
1032 yield ivec, [rg.padding for rg in vec]
1033
1034 @precond_fold()
1035 def _get_veclist(self):
1036 """Get folded veclist"""
1037 return self._veclist
1038
1039 def _set_veclist(self, val):
1040 """Set veclist and set dirty flag for deferred folding."""
1041 self._veclist = val
1042 self._dirty = True
1043
1044 veclist = property(_get_veclist, _set_veclist)
1045
1046 def vectors(self):
1047 """Get underlying :class:`RangeSet` vectors"""
1048 return iter(self.veclist)
1049
1050 def dim(self):
1051 """Get the current number of dimensions of this RangeSetND
1052 object. Return 0 when object is empty."""
1053 try:
1054 return len(self._veclist[0])
1055 except IndexError:
1056 return 0
1057
1058 def pads(self):
1059 """Get a tuple of padding length info for each dimension."""
1060 # return a tuple of max padding length for each axis
1061 pad_veclist = ((rg.padding or 0 for rg in vec) for vec in self._veclist)
1062 return tuple(max(pads) for pads in zip(*pad_veclist))
1063
1064 def get_autostep(self):
1065 """Get autostep value (property)"""
1066 if self._autostep >= AUTOSTEP_DISABLED:
1067 return None
1068 else:
1069 # +1 as user wants node count but _autostep means real steps here
1070 return self._autostep + 1
1071
1072 def set_autostep(self, val):
1073 """Set autostep value (property)"""
1074 # Must conform to RangeSet.autostep logic
1075 if val is None:
1076 self._autostep = AUTOSTEP_DISABLED
1077 else:
1078 # Like in RangeSet.set_autostep(): -1 because user means node count,
1079 # but we mean real steps (this operation has no effect on
1080 # AUTOSTEP_DISABLED value)
1081 self._autostep = int(val) - 1
1082
1083 # Update our RangeSet objects
1084 for rgvec in self._veclist:
1085 for rg in rgvec:
1086 rg._autostep = self._autostep
1087
1088 autostep = property(get_autostep, set_autostep)
1089
1090 @precond_fold()
1091 def __getitem__(self, index):
1092 """
1093 Return the element at index or a subrange when a slice is specified.
1094 """
1095 if isinstance(index, slice):
1096 iveclist = []
1097 for rgvec in self._veclist:
1098 iveclist += product(*rgvec)
1099 assert(len(iveclist) == len(self))
1100 rnd = RangeSetND(iveclist[index], autostep=self.autostep)
1101 return rnd
1102
1103 elif isinstance(index, int):
1104 # find a tuple of integer (multi-dimensional) at position index
1105 if index < 0:
1106 length = len(self)
1107 if index >= -length:
1108 index = length + index
1109 else:
1110 raise IndexError("%d out of range" % index)
1111 length = 0
1112 for rgvec in self._veclist:
1113 cnt = reduce(mul, [len(rg) for rg in rgvec])
1114 if length + cnt < index:
1115 length += cnt
1116 else:
1117 for ivec in product(*rgvec):
1118 if index == length:
1119 return ivec
1120 length += 1
1121 raise IndexError("%d out of range" % index)
1122 else:
1123 raise TypeError("%s indices must be integers" %
1124 self.__class__.__name__)
1125
1126 @precond_fold()
1127 def index(self, elem, start=0, stop=None):
1128 """
1129 Return the zero-based index of element in this RangeSetND, following
1130 iteration order. This is the reverse operation of
1131 :meth:`RangeSetND.__getitem__` and behaves like the ``index()`` method
1132 of the ``list`` type.
1133
1134 The element is a vector (tuple) of indexes, given as integers or
1135 strings (zero-padding is then significant). The optional `start` and
1136 `stop` arguments restrict the search to the matching subsequence, and
1137 may be negative (counted from the end).
1138
1139 :raises TypeError: the element is not a vector of indexes
1140 :raises ValueError: the element is not present in the RangeSetND
1141 """
1142 # a bare string or scalar is not a valid index vector: iterating over
1143 # a string would otherwise wrongly split it into per-character indexes
1144 # (basestring catches both str and Python 2 unicode strings)
1145 if isinstance(elem, basestring) or not hasattr(elem, '__iter__'):
1146 raise TypeError("%s.index() argument must be a vector of indexes"
1147 % self.__class__.__name__)
1148 target = tuple("%s" % e for e in elem)
1149 for pos, ivec in enumerate(self._iter()):
1150 if ivec == target:
1151 if start != 0 or stop is not None:
1152 start, stop = _normalized_index_bounds(len(self),
1153 start, stop)
1154 if not start <= pos < stop:
1155 break
1156 return pos
1157 raise ValueError("%s is not in RangeSetND" % (elem,))
1158
1159 @precond_fold()
1160 def contiguous(self):
1161 """Object-based iterator over contiguous range sets."""
1162 veclist = self._veclist
1163 try:
1164 dim = len(veclist[0])
1165 except IndexError:
1166 return
1167 for dimidx in range(dim):
1168 new_veclist = []
1169 for rgvec in veclist:
1170 for rgsli in rgvec[dimidx].contiguous():
1171 rgvec = list(rgvec)
1172 rgvec[dimidx] = rgsli
1173 new_veclist.append(rgvec)
1174 veclist = new_veclist
1175 for rgvec in veclist:
1176 yield RangeSetND([rgvec])
1177
1178 # Membership test
1179
1180 @precond_fold()
1181 def __contains__(self, element):
1182 """Report whether an element is a member of a RangeSetND.
1183 Element can be either another RangeSetND object, a string or
1184 an integer.
1185
1186 Called in response to the expression ``element in self``.
1187 """
1188 if isinstance(element, RangeSetND):
1189 rgnd_element = element
1190 else:
1191 rgnd_element = RangeSetND([[str(element)]])
1192 return rgnd_element.issubset(self)
1193
1194 # Subset and superset test
1195
1196 def issubset(self, other):
1197 """Report whether another set contains this RangeSetND."""
1198 self._binary_sanity_check(other)
1199 return other.issuperset(self)
1200
1201 @precond_fold()
1202 def issuperset(self, other):
1203 """Report whether this RangeSetND contains another RangeSetND."""
1204 self._binary_sanity_check(other)
1205 if self.dim() == 1 and other.dim() == 1:
1206 return self._veclist[0][0].issuperset(other._veclist[0][0])
1207 if not other._veclist:
1208 return True
1209 test = other.copy()
1210 test.difference_update(self)
1211 return not bool(test)
1212
1213 # Inequality comparisons using the is-subset relation.
1214 __le__ = issubset
1215 __ge__ = issuperset
1216
1217 def __lt__(self, other):
1218 self._binary_sanity_check(other)
1219 return len(self) < len(other) and self.issubset(other)
1220
1221 def __gt__(self, other):
1222 self._binary_sanity_check(other)
1223 return len(self) > len(other) and self.issuperset(other)
1224
1225 # Assorted helpers
1226
1227 def _binary_sanity_check(self, other):
1228 """Check that the other argument to a binary operation is also a
1229 RangeSetND, raising a TypeError otherwise."""
1230 if not isinstance(other, RangeSetND):
1231 msg = "Binary operation only permitted between RangeSetND"
1232 raise TypeError(msg)
1233
1234 def _sort(self):
1235 """N-dimensional sorting."""
1236 def rgveckeyfunc(rgvec):
1237 # key used for sorting purposes, based on the following
1238 # conditions:
1239 # (1) larger vector first (#elements)
1240 # (2) larger dim first (#elements)
1241 # (3) lower first index first
1242 # (4) lower last index first
1243 return (-reduce(mul, [len(rg) for rg in rgvec]), \
1244 tuple((-len(rg), rg[0], rg[-1]) for rg in rgvec))
1245 self._veclist.sort(key=rgveckeyfunc)
1246
1247 @precond_fold()
1248 def fold(self):
1249 """Explicit folding call. Please note that folding of RangeSetND
1250 nD vectors are automatically managed, so you should not have to
1251 call this method. It may be still useful in some extreme cases
1252 where the RangeSetND is heavily modified."""
1253 pass
1254
1255 def _fold(self):
1256 """In-place N-dimensional folding."""
1257 assert self._dirty
1258 if len(self._veclist) > 1:
1259 self._fold_univariate() or self._fold_multivariate()
1260 else:
1261 self._dirty = False
1262
1263 def _fold_univariate(self):
1264 """Univariate nD folding. Return True on success and False when
1265 a multivariate folding is required."""
1266 dim = self.dim()
1267 vardim = dimdiff = 0
1268 if dim > 1:
1269 # We got more than one dimension, see if only one is changing...
1270 for i in range(dim):
1271 # Are all rangesets on this dimension the same?
1272 slist = [vec[i] for vec in self._veclist]
1273 if slist.count(slist[0]) != len(slist):
1274 dimdiff += 1
1275 if dimdiff > 1:
1276 break
1277 vardim = i
1278 univar = (dim == 1 or dimdiff == 1)
1279 if univar:
1280 # Eligible for univariate folding (faster!)
1281 for vec in self._veclist[1:]:
1282 self._veclist[0][vardim].update(vec[vardim])
1283 del self._veclist[1:]
1284 self._dirty = False
1285 self._multivar_hint = not univar
1286 return univar
1287
1288 def _fold_multivariate(self):
1289 """Multivariate nD folding"""
1290 # PHASE 1: expand with respect to uniqueness
1291 self._fold_multivariate_expand()
1292 # PHASE 2: merge
1293 self._fold_multivariate_merge()
1294 self._dirty = False
1295
1296 def _fold_multivariate_expand(self):
1297 """Multivariate nD folding: expand [phase 1]"""
1298 self._veclist = [[RangeSet.fromone(i, autostep=self.autostep)
1299 for i in tvec]
1300 for tvec in set(self._iter())]
1301
1302 def _fold_multivariate_merge(self):
1303 """Multivariate nD folding: merge [phase 2]"""
1304 full = False # try easy O(n) passes first
1305 chg = True # new pass (eg. after change on veclist)
1306 while chg:
1307 chg = False
1308 self._sort() # sort veclist before new pass
1309 index1, index2 = 0, 1
1310 while (index1 + 1) < len(self._veclist):
1311 # use 2 references on iterator to compare items by couples
1312 item1 = self._veclist[index1]
1313 index2 = index1 + 1
1314 index1 += 1
1315 while index2 < len(self._veclist):
1316 item2 = self._veclist[index2]
1317 index2 += 1
1318 new_item = [None] * len(item1)
1319 nb_diff = 0
1320 # compare 2 rangeset vector, item by item, the idea being
1321 # to merge vectors if they differ only by one item
1322 for pos, (rg1, rg2) in enumerate(zip(item1, item2)):
1323 if rg1 == rg2:
1324 new_item[pos] = rg1
1325 elif not rg1 & rg2: # merge on disjoint ranges
1326 nb_diff += 1
1327 if nb_diff > 1:
1328 break
1329 new_item[pos] = rg1 | rg2
1330 # if fully contained, keep the largest one
1331 elif (rg1 > rg2 or rg1 < rg2): # and nb_diff == 0:
1332 nb_diff += 1
1333 if nb_diff > 1:
1334 break
1335 new_item[pos] = max(rg1, rg2)
1336 # otherwise, compute rangeset intersection and
1337 # keep the two disjoint part to be handled
1338 # later...
1339 else:
1340 # intersection but do nothing
1341 nb_diff = 2
1342 break
1343 # one change has been done: use this new item to compare
1344 # with other
1345 if nb_diff <= 1:
1346 chg = True
1347 item1 = self._veclist[index1 - 1] = new_item
1348 index2 -= 1
1349 self._veclist.pop(index2)
1350 elif not full:
1351 # easy pass so break to avoid scanning all
1352 # index2; advance with next index1 for now
1353 break
1354 if not chg and not full:
1355 # if no change was done during the last normal pass, we do a
1356 # full O(n^2) pass. This pass is done only at the end in the
1357 # hope that most vectors have already been merged by easy
1358 # O(n) passes.
1359 chg = full = True
1360
1361 def __or__(self, other):
1362 """Return the union of two RangeSetNDs as a new RangeSetND.
1363
1364 (I.e. all elements that are in either set.)
1365 """
1366 if not isinstance(other, RangeSetND):
1367 return NotImplemented
1368 return self.union(other)
1369
1370 def union(self, other):
1371 """Return the union of two RangeSetNDs as a new RangeSetND.
1372
1373 (I.e. all elements that are in either set.)
1374 """
1375 rgnd_copy = self.copy()
1376 rgnd_copy.update(other)
1377 return rgnd_copy
1378
1379 def update(self, other):
1380 """Add all RangeSetND elements to this RangeSetND."""
1381 if isinstance(other, RangeSetND):
1382 iterable = other._veclist
1383 else:
1384 iterable = other
1385 for vec in iterable:
1386 # copy rangesets and set custom autostep
1387 assert isinstance(vec[0], RangeSet)
1388 cpyvec = []
1389 for rg in vec:
1390 cpyrg = rg.copy()
1391 cpyrg.autostep = self.autostep
1392 cpyvec.append(cpyrg)
1393 self._veclist.append(cpyvec)
1394 self._dirty = True
1395 if not self._multivar_hint:
1396 self._fold_univariate()
1397
1398 union_update = update
1399
1400 def __ior__(self, other):
1401 """Update a RangeSetND with the union of itself and another."""
1402 self._binary_sanity_check(other)
1403 self.update(other)
1404 return self
1405
1406 def __isub__(self, other):
1407 """Remove all elements of another set from this RangeSetND."""
1408 self._binary_sanity_check(other)
1409 self.difference_update(other)
1410 return self
1411
1412 def difference_update(self, other, strict=False):
1413 """Remove all elements of another set from this RangeSetND.
1414
1415 If strict is True, raise KeyError if an element cannot be removed
1416 (strict is a RangeSet addition)"""
1417 if strict and not other in self:
1418 raise KeyError(other.difference(self)[0])
1419
1420 ergvx = other._veclist # read only
1421 rgnd_new = []
1422 index1 = 0
1423 while index1 < len(self._veclist):
1424 rgvec1 = self._veclist[index1]
1425 procvx1 = [ rgvec1 ]
1426 nextvx1 = []
1427 index2 = 0
1428 while index2 < len(ergvx):
1429 rgvec2 = ergvx[index2]
1430 while len(procvx1) > 0: # refine diff for each resulting vector
1431 rgproc1 = procvx1.pop(0)
1432 tmpvx = []
1433 for pos, (rg1, rg2) in enumerate(zip(rgproc1, rgvec2)):
1434 if rg1 == rg2 or rg1 < rg2: # issubset
1435 pass
1436 elif rg1 & rg2: # intersect
1437 tmpvec = list(rgproc1)
1438 tmpvec[pos] = rg1.difference(rg2)
1439 tmpvx.append(tmpvec)
1440 else: # disjoint
1441 tmpvx = [ rgproc1 ] # reset previous work
1442 break
1443 if tmpvx:
1444 nextvx1 += tmpvx
1445 if nextvx1:
1446 procvx1 = nextvx1
1447 nextvx1 = []
1448 index2 += 1
1449 if procvx1:
1450 rgnd_new += procvx1
1451 index1 += 1
1452 self.veclist = rgnd_new
1453
1454 def __sub__(self, other):
1455 """Return the difference of two RangeSetNDs as a new RangeSetND.
1456
1457 (I.e. all elements that are in this set and not in the other.)
1458 """
1459 if not isinstance(other, RangeSetND):
1460 return NotImplemented
1461 return self.difference(other)
1462
1463 def difference(self, other):
1464 """
1465 ``s.difference(t)`` returns a new object with elements in s
1466 but not in t.
1467 """
1468 self_copy = self.copy()
1469 self_copy.difference_update(other)
1470 return self_copy
1471
1472 def intersection(self, other):
1473 """
1474 ``s.intersection(t)`` returns a new object with elements common
1475 to s and t.
1476 """
1477 self_copy = self.copy()
1478 self_copy.intersection_update(other)
1479 return self_copy
1480
1481 def __and__(self, other):
1482 """
1483 Implements the & operator. So ``s & t`` returns a new object
1484 with elements common to s and t.
1485 """
1486 if not isinstance(other, RangeSetND):
1487 return NotImplemented
1488 return self.intersection(other)
1489
1490 def intersection_update(self, other):
1491 """
1492 ``s.intersection_update(t)`` returns nodeset s keeping only
1493 elements also found in t.
1494 """
1495 if other is self:
1496 return
1497
1498 tmp_rnd = RangeSetND()
1499
1500 empty_rset = RangeSet()
1501
1502 for rgvec in self._veclist:
1503 for ergvec in other._veclist:
1504 irgvec = [rg.intersection(erg) \
1505 for rg, erg in zip(rgvec, ergvec)]
1506 if not empty_rset in irgvec:
1507 tmp_rnd.update([irgvec])
1508 # substitute
1509 self.veclist = tmp_rnd.veclist
1510
1511 def __iand__(self, other):
1512 """
1513 Implements the &= operator. So ``s &= t`` returns object s
1514 keeping only elements also found in t (Python 2.5+ required).
1515 """
1516 self._binary_sanity_check(other)
1517 self.intersection_update(other)
1518 return self
1519
1520 def symmetric_difference(self, other):
1521 """
1522 ``s.symmetric_difference(t)`` returns the symmetric difference
1523 of two objects as a new RangeSetND.
1524
1525 (ie. all items that are in exactly one of the RangeSetND.)
1526 """
1527 self_copy = self.copy()
1528 self_copy.symmetric_difference_update(other)
1529 return self_copy
1530
1531 def __xor__(self, other):
1532 """
1533 Implement the ^ operator. So ``s ^ t`` returns a new RangeSetND
1534 with nodes that are in exactly one of the RangeSetND.
1535 """
1536 if not isinstance(other, RangeSetND):
1537 return NotImplemented
1538 return self.symmetric_difference(other)
1539
1540 def symmetric_difference_update(self, other):
1541 """
1542 ``s.symmetric_difference_update(t)`` returns RangeSetND s
1543 keeping all nodes that are in exactly one of the objects.
1544 """
1545 diff2 = other.difference(self)
1546 self.difference_update(other)
1547 self.update(diff2)
1548
1549 def __ixor__(self, other):
1550 """
1551 Implement the ^= operator. So ``s ^= t`` returns object s after
1552 keeping all items that are in exactly one of the RangeSetND
1553 (Python 2.5+ required).
1554 """
1555 self._binary_sanity_check(other)
1556 self.symmetric_difference_update(other)
1557 return self
1558