Search is not available for this dataset
text stringlengths 75 104k |
|---|
def AdditivePoissonNoise(lam=0, per_channel=False, name=None, deterministic=False, random_state=None):
"""
Create an augmenter to add poisson noise to images.
Poisson noise is comparable to gaussian noise as in ``AdditiveGaussianNoise``, but the values are sampled from
a poisson distribution instead of... |
def Dropout(p=0, per_channel=False, name=None, deterministic=False, random_state=None):
"""
Augmenter that sets a certain fraction of pixels in images to zero.
dtype support::
See ``imgaug.augmenters.arithmetic.MultiplyElementwise``.
Parameters
----------
p : float or tuple of float o... |
def CoarseDropout(p=0, size_px=None, size_percent=None, per_channel=False, min_size=4, name=None, deterministic=False,
random_state=None):
"""
Augmenter that sets rectangular areas within images to zero.
In contrast to Dropout, these areas can have larger sizes.
(E.g. you might end up... |
def ImpulseNoise(p=0, name=None, deterministic=False, random_state=None):
"""
Creates an augmenter to apply impulse noise to an image.
This is identical to ``SaltAndPepper``, except that per_channel is always set to True.
dtype support::
See ``imgaug.augmenters.arithmetic.SaltAndPepper``.
... |
def SaltAndPepper(p=0, per_channel=False, name=None, deterministic=False, random_state=None):
"""
Adds salt and pepper noise to an image, i.e. some white-ish and black-ish pixels.
dtype support::
See ``imgaug.augmenters.arithmetic.ReplaceElementwise``.
Parameters
----------
p : float ... |
def Pepper(p=0, per_channel=False, name=None, deterministic=False, random_state=None):
"""
Adds pepper noise to an image, i.e. black-ish pixels.
This is similar to dropout, but slower and the black pixels are not uniformly black.
dtype support::
See ``imgaug.augmenters.arithmetic.ReplaceEleme... |
def CoarsePepper(p=0, size_px=None, size_percent=None, per_channel=False, min_size=4, name=None, deterministic=False,
random_state=None):
"""
Adds coarse pepper noise to an image, i.e. rectangles that contain noisy black-ish pixels.
dtype support::
See ``imgaug.augmenters.arithmet... |
def ContrastNormalization(alpha=1.0, per_channel=False, name=None, deterministic=False, random_state=None):
"""
Augmenter that changes the contrast of images.
dtype support:
See ``imgaug.augmenters.contrast.LinearContrast``.
Parameters
----------
alpha : number or tuple of number or l... |
def is_single_float(val):
"""
Checks whether a variable is a float.
Parameters
----------
val
The variable to check.
Returns
-------
bool
True if the variable is a float. Otherwise False.
"""
return isinstance(val, numbers.Real) and not is_single_integer(val) a... |
def is_integer_array(val):
"""
Checks whether a variable is a numpy integer array.
Parameters
----------
val
The variable to check.
Returns
-------
bool
True if the variable is a numpy integer array. Otherwise False.
"""
return is_np_array(val) and issubclass(v... |
def is_float_array(val):
"""
Checks whether a variable is a numpy float array.
Parameters
----------
val
The variable to check.
Returns
-------
bool
True if the variable is a numpy float array. Otherwise False.
"""
return is_np_array(val) and issubclass(val.dty... |
def is_callable(val):
"""
Checks whether a variable is a callable, e.g. a function.
Parameters
----------
val
The variable to check.
Returns
-------
bool
True if the variable is a callable. Otherwise False.
"""
# python 3.x with x <= 2 does not support callable... |
def flatten(nested_iterable):
"""
Flattens arbitrarily nested lists/tuples.
Code partially taken from https://stackoverflow.com/a/10824420.
Parameters
----------
nested_iterable
A list or tuple of arbitrarily nested values.
Yields
------
any
Non-list and non-tuple ... |
def new_random_state(seed=None, fully_random=False):
"""
Returns a new random state.
Parameters
----------
seed : None or int, optional
Optional seed value to use.
The same datatypes are allowed as for ``numpy.random.RandomState(seed)``.
fully_random : bool, optional
Wh... |
def copy_random_state(random_state, force_copy=False):
"""
Creates a copy of a random state.
Parameters
----------
random_state : numpy.random.RandomState
The random state to copy.
force_copy : bool, optional
If True, this function will always create a copy of every random
... |
def derive_random_states(random_state, n=1):
"""
Create N new random states based on an existing random state or seed.
Parameters
----------
random_state : numpy.random.RandomState
Random state or seed from which to derive new random states.
n : int, optional
Number of random s... |
def _quokka_normalize_extract(extract):
"""
Generate a normalized rectangle to be extract from the standard quokka image.
Parameters
----------
extract : 'square' or tuple of number or imgaug.BoundingBox or imgaug.BoundingBoxesOnImage
Unnormalized representation of the image subarea to be e... |
def _compute_resized_shape(from_shape, to_shape):
"""
Computes the intended new shape of an image-like array after resizing.
Parameters
----------
from_shape : tuple or ndarray
Old shape of the array. Usually expected to be a tuple of form ``(H, W)`` or ``(H, W, C)`` or
alternativel... |
def quokka(size=None, extract=None):
"""
Returns an image of a quokka as a numpy array.
Parameters
----------
size : None or float or tuple of int, optional
Size of the output image. Input into :func:`imgaug.imgaug.imresize_single_image`.
Usually expected to be a tuple ``(H, W)``, w... |
def quokka_heatmap(size=None, extract=None):
"""
Returns a heatmap (here: depth map) for the standard example quokka image.
Parameters
----------
size : None or float or tuple of int, optional
See :func:`imgaug.quokka`.
extract : None or 'square' or tuple of number or imgaug.BoundingBo... |
def quokka_segmentation_map(size=None, extract=None):
"""
Returns a segmentation map for the standard example quokka image.
Parameters
----------
size : None or float or tuple of int, optional
See :func:`imgaug.quokka`.
extract : None or 'square' or tuple of number or imgaug.BoundingBo... |
def quokka_keypoints(size=None, extract=None):
"""
Returns example keypoints on the standard example quokke image.
The keypoints cover the eyes, ears, nose and paws.
Parameters
----------
size : None or float or tuple of int or tuple of float, optional
Size of the output image on which... |
def quokka_bounding_boxes(size=None, extract=None):
"""
Returns example bounding boxes on the standard example quokke image.
Currently only a single bounding box is returned that covers the quokka.
Parameters
----------
size : None or float or tuple of int or tuple of float, optional
S... |
def quokka_polygons(size=None, extract=None):
"""
Returns example polygons on the standard example quokke image.
The result contains one polygon, covering the quokka's outline.
Parameters
----------
size : None or float or tuple of int or tuple of float, optional
Size of the output ima... |
def angle_between_vectors(v1, v2):
"""
Returns the angle in radians between vectors `v1` and `v2`.
From http://stackoverflow.com/questions/2827393/angles-between-two-n-dimensional-vectors-in-python
Parameters
----------
v1 : (N,) ndarray
First vector.
v2 : (N,) ndarray
Sec... |
def compute_line_intersection_point(x1, y1, x2, y2, x3, y3, x4, y4):
"""
Compute the intersection point of two lines.
Taken from https://stackoverflow.com/a/20679579 .
Parameters
----------
x1 : number
x coordinate of the first point on line 1. (The lines extends beyond this point.)
... |
def draw_text(img, y, x, text, color=(0, 255, 0), size=25):
"""
Draw text on an image.
This uses by default DejaVuSans as its font, which is included in this library.
dtype support::
* ``uint8``: yes; fully tested
* ``uint16``: no
* ``uint32``: no
* ``uint64``: no
... |
def imresize_many_images(images, sizes=None, interpolation=None):
"""
Resize many images to a specified size.
dtype support::
* ``uint8``: yes; fully tested
* ``uint16``: yes; tested
* ``uint32``: no (1)
* ``uint64``: no (2)
* ``int8``: yes; tested (3)
* ``i... |
def imresize_single_image(image, sizes, interpolation=None):
"""
Resizes a single image.
dtype support::
See :func:`imgaug.imgaug.imresize_many_images`.
Parameters
----------
image : (H,W,C) ndarray or (H,W) ndarray
Array of the image to resize.
Usually recommended to... |
def pad(arr, top=0, right=0, bottom=0, left=0, mode="constant", cval=0):
"""
Pad an image-like array on its top/right/bottom/left side.
This function is a wrapper around :func:`numpy.pad`.
dtype support::
* ``uint8``: yes; fully tested (1)
* ``uint16``: yes; fully tested (1)
*... |
def compute_paddings_for_aspect_ratio(arr, aspect_ratio):
"""
Compute the amount of pixels by which an array has to be padded to fulfill an aspect ratio.
The aspect ratio is given as width/height.
Depending on which dimension is smaller (height or width), only the corresponding
sides (left/right or... |
def pad_to_aspect_ratio(arr, aspect_ratio, mode="constant", cval=0, return_pad_amounts=False):
"""
Pad an image-like array on its sides so that it matches a target aspect ratio.
Depending on which dimension is smaller (height or width), only the corresponding
sides (left/right or top/bottom) will be pa... |
def pool(arr, block_size, func, cval=0, preserve_dtype=True):
"""
Resize an array by pooling values within blocks.
dtype support::
* ``uint8``: yes; fully tested
* ``uint16``: yes; tested
* ``uint32``: yes; tested (2)
* ``uint64``: no (1)
* ``int8``: yes; tested
... |
def avg_pool(arr, block_size, cval=0, preserve_dtype=True):
"""
Resize an array using average pooling.
dtype support::
See :func:`imgaug.imgaug.pool`.
Parameters
----------
arr : (H,W) ndarray or (H,W,C) ndarray
Image-like array to pool. See :func:`imgaug.pool` for details.
... |
def max_pool(arr, block_size, cval=0, preserve_dtype=True):
"""
Resize an array using max-pooling.
dtype support::
See :func:`imgaug.imgaug.pool`.
Parameters
----------
arr : (H,W) ndarray or (H,W,C) ndarray
Image-like array to pool. See :func:`imgaug.pool` for details.
b... |
def draw_grid(images, rows=None, cols=None):
"""
Converts multiple input images into a single image showing them in a grid.
dtype support::
* ``uint8``: yes; fully tested
* ``uint16``: yes; fully tested
* ``uint32``: yes; fully tested
* ``uint64``: yes; fully tested
... |
def show_grid(images, rows=None, cols=None):
"""
Converts the input images to a grid image and shows it in a new window.
dtype support::
minimum of (
:func:`imgaug.imgaug.draw_grid`,
:func:`imgaug.imgaug.imshow`
)
Parameters
----------
images : (N,H,W,3... |
def imshow(image, backend=IMSHOW_BACKEND_DEFAULT):
"""
Shows an image in a window.
dtype support::
* ``uint8``: yes; not tested
* ``uint16``: ?
* ``uint32``: ?
* ``uint64``: ?
* ``int8``: ?
* ``int16``: ?
* ``int32``: ?
* ``int64``: ?
... |
def warn_deprecated(msg, stacklevel=2):
"""Generate a non-silent deprecation warning with stacktrace.
The used warning is ``imgaug.imgaug.DeprecationWarning``.
Parameters
----------
msg : str
The message of the warning.
stacklevel : int, optional
How many steps above this func... |
def is_activated(self, images, augmenter, parents, default):
"""
Returns whether an augmenter may be executed.
Returns
-------
bool
If True, the augmenter may be executed. If False, it may not be executed.
"""
if self.activator is None:
r... |
def is_propagating(self, images, augmenter, parents, default):
"""
Returns whether an augmenter may call its children to augment an
image. This is independent of the augmenter itself possible changing
the image, without calling its children. (Most (all?) augmenters with
children ... |
def preprocess(self, images, augmenter, parents):
"""
A function to be called before the augmentation of images starts (per augmenter).
Returns
-------
(N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray
The input images, optional... |
def postprocess(self, images, augmenter, parents):
"""
A function to be called after the augmentation of images was
performed.
Returns
-------
(N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray
The input images, optionall... |
def pool(self):
"""Return the multiprocessing.Pool instance or create it if not done yet.
Returns
-------
multiprocessing.Pool
The multiprocessing.Pool used internally by this imgaug.multicore.Pool.
"""
if self._pool is None:
processes = self.pro... |
def map_batches(self, batches, chunksize=None):
"""
Augment batches.
Parameters
----------
batches : list of imgaug.augmentables.batches.Batch
The batches to augment.
chunksize : None or int, optional
Rough indicator of how many tasks should be s... |
def map_batches_async(self, batches, chunksize=None, callback=None, error_callback=None):
"""
Augment batches asynchonously.
Parameters
----------
batches : list of imgaug.augmentables.batches.Batch
The batches to augment.
chunksize : None or int, optional
... |
def imap_batches(self, batches, chunksize=1):
"""
Augment batches from a generator.
Parameters
----------
batches : generator of imgaug.augmentables.batches.Batch
The batches to augment, provided as a generator. Each call to the generator should yield exactly one
... |
def imap_batches_unordered(self, batches, chunksize=1):
"""
Augment batches from a generator in a way that does not guarantee to preserve order.
Parameters
----------
batches : generator of imgaug.augmentables.batches.Batch
The batches to augment, provided as a gener... |
def terminate(self):
"""Terminate the pool immediately."""
if self._pool is not None:
self._pool.terminate()
self._pool.join()
self._pool = None |
def terminate(self):
"""Stop all workers."""
if not self.join_signal.is_set():
self.join_signal.set()
# give minimal time to put generated batches in queue and gracefully shut down
time.sleep(0.01)
if self.main_worker_thread.is_alive():
self.main_worker_t... |
def get_batch(self):
"""
Returns a batch from the queue of augmented batches.
If workers are still running and there are no batches in the queue,
it will automatically wait for the next batch.
Returns
-------
out : None or imgaug.Batch
One batch or N... |
def _augment_images_worker(self, augseq, queue_source, queue_result, seedval):
"""
Augment endlessly images in the source queue.
This is a worker function for that endlessly queries the source queue (input batches),
augments batches in it and sends the result to the output queue.
... |
def terminate(self):
"""
Terminates all background processes immediately.
This will also free their RAM.
"""
for worker in self.workers:
if worker.is_alive():
worker.terminate()
self.nb_workers_finished = len(self.workers)
if not sel... |
def to_normalized_batch(self):
"""Convert this unnormalized batch to an instance of Batch.
As this method is intended to be called before augmentation, it
assumes that none of the ``*_aug`` attributes is yet set.
It will produce an AssertionError otherwise.
The newly created Ba... |
def fill_from_augmented_normalized_batch(self, batch_aug_norm):
"""
Fill this batch with (normalized) augmentation results.
This method receives a (normalized) Batch instance, takes all
``*_aug`` attributes out if it and assigns them to this
batch *in unnormalized form*. Hence, ... |
def Positive(other_param, mode="invert", reroll_count_max=2):
"""
Converts another parameter's results to positive values.
Parameters
----------
other_param : imgaug.parameters.StochasticParameter
Other parameter which's sampled values are to be
modified.
mode : {'invert', 'rer... |
def Negative(other_param, mode="invert", reroll_count_max=2):
"""
Converts another parameter's results to negative values.
Parameters
----------
other_param : imgaug.parameters.StochasticParameter
Other parameter which's sampled values are to be
modified.
mode : {'invert', 'rer... |
def create_for_noise(other_param, threshold=(-10, 10), activated=True):
"""
Creates a Sigmoid that is adjusted to be used with noise parameters,
i.e. with parameters which's output values are in the range [0.0, 1.0].
Parameters
----------
other_param : imgaug.parameters.... |
def area(self):
"""
Estimate the area of the polygon.
Returns
-------
number
Area of the polygon.
"""
if len(self.exterior) < 3:
raise Exception("Cannot compute the polygon's area because it contains less than three points.")
poly... |
def project(self, from_shape, to_shape):
"""
Project the polygon onto an image with different shape.
The relative coordinates of all points remain the same.
E.g. a point at (x=20, y=20) on an image (width=100, height=200) will be
projected on a new image (width=200, height=100) ... |
def find_closest_point_index(self, x, y, return_distance=False):
"""
Find the index of the point within the exterior that is closest to the given coordinates.
"Closeness" is here defined based on euclidean distance.
This method will raise an AssertionError if the exterior contains no po... |
def is_fully_within_image(self, image):
"""
Estimate whether the polygon is fully inside the image area.
Parameters
----------
image : (H,W,...) ndarray or tuple of int
Image dimensions to use.
If an ndarray, its shape will be used.
If a tuple... |
def is_partly_within_image(self, image):
"""
Estimate whether the polygon is at least partially inside the image area.
Parameters
----------
image : (H,W,...) ndarray or tuple of int
Image dimensions to use.
If an ndarray, its shape will be used.
... |
def is_out_of_image(self, image, fully=True, partly=False):
"""
Estimate whether the polygon is partially or fully outside of the image area.
Parameters
----------
image : (H,W,...) ndarray or tuple of int
Image dimensions to use.
If an ndarray, its shape... |
def clip_out_of_image(self, image):
"""
Cut off all parts of the polygon that are outside of the image.
This operation may lead to new points being created.
As a single polygon may be split into multiple new polygons, the result
is always a list, which may contain more than one ... |
def shift(self, top=None, right=None, bottom=None, left=None):
"""
Shift the polygon from one or more image sides, i.e. move it on the x/y-axis.
Parameters
----------
top : None or int, optional
Amount of pixels by which to shift the polygon from the top.
ri... |
def draw_on_image(self,
image,
color=(0, 255, 0), color_face=None,
color_lines=None, color_points=None,
alpha=1.0, alpha_face=None,
alpha_lines=None, alpha_points=None,
size=1, size_lines=... |
def extract_from_image(self, image):
"""
Extract the image pixels within the polygon.
This function will zero-pad the image if the polygon is partially/fully outside of
the image.
Parameters
----------
image : (H,W) ndarray or (H,W,C) ndarray
The ima... |
def change_first_point_by_coords(self, x, y, max_distance=1e-4,
raise_if_too_far_away=True):
"""
Set the first point of the exterior to the given point based on its coordinates.
If multiple points are found, the closest one will be picked.
If no matc... |
def change_first_point_by_index(self, point_idx):
"""
Set the first point of the exterior to the given point based on its index.
Note: This method does *not* work in-place.
Parameters
----------
point_idx : int
Index of the desired starting point.
R... |
def to_shapely_polygon(self):
"""
Convert this polygon to a Shapely polygon.
Returns
-------
shapely.geometry.Polygon
The Shapely polygon matching this polygon's exterior.
"""
# load shapely lazily, which makes the dependency more optional
im... |
def to_shapely_line_string(self, closed=False, interpolate=0):
"""
Convert this polygon to a Shapely LineString object.
Parameters
----------
closed : bool, optional
Whether to return the line string with the last point being identical to the first point.
in... |
def to_bounding_box(self):
"""
Convert this polygon to a bounding box tightly containing the whole polygon.
Returns
-------
imgaug.BoundingBox
Tight bounding box around the polygon.
"""
# TODO get rid of this deferred import
from imgaug.augme... |
def to_keypoints(self):
"""
Convert this polygon's `exterior` to ``Keypoint`` instances.
Returns
-------
list of imgaug.Keypoint
Exterior vertices as ``Keypoint`` instances.
"""
# TODO get rid of this deferred import
from imgaug.augmentables.... |
def to_line_string(self, closed=True):
"""
Convert this polygon's `exterior` to a ``LineString`` instance.
Parameters
----------
closed : bool, optional
Whether to close the line string, i.e. to add the first point of
the `exterior` also as the last point... |
def from_shapely(polygon_shapely, label=None):
"""
Create a polygon from a Shapely polygon.
Note: This will remove any holes in the Shapely polygon.
Parameters
----------
polygon_shapely : shapely.geometry.Polygon
The shapely polygon.
label : None ... |
def exterior_almost_equals(self, other, max_distance=1e-6, points_per_edge=8):
"""
Estimate if this and other polygon's exterior are almost identical.
The two exteriors can have different numbers of points, but any point
randomly sampled on the exterior of one polygon should be close to... |
def almost_equals(self, other, max_distance=1e-6, points_per_edge=8):
"""
Estimate if this polygon's and another's geometry/labels are similar.
This is the same as :func:`imgaug.Polygon.exterior_almost_equals` but
additionally compares the labels.
Parameters
----------
... |
def copy(self, exterior=None, label=None):
"""
Create a shallow copy of the Polygon object.
Parameters
----------
exterior : list of imgaug.Keypoint or list of tuple or (N,2) ndarray, optional
List of points defining the polygon. See :func:`imgaug.Polygon.__init__` f... |
def deepcopy(self, exterior=None, label=None):
"""
Create a deep copy of the Polygon object.
Parameters
----------
exterior : list of Keypoint or list of tuple or (N,2) ndarray, optional
List of points defining the polygon. See `imgaug.Polygon.__init__` for details.
... |
def on(self, image):
"""
Project polygons from one image to a new one.
Parameters
----------
image : ndarray or tuple of int
New image onto which the polygons are to be projected.
May also simply be that new image's shape tuple.
Returns
-... |
def draw_on_image(self,
image,
color=(0, 255, 0), color_face=None,
color_lines=None, color_points=None,
alpha=1.0, alpha_face=None,
alpha_lines=None, alpha_points=None,
size=1, size_lines=... |
def remove_out_of_image(self, fully=True, partly=False):
"""
Remove all polygons that are fully or partially outside of the image.
Parameters
----------
fully : bool, optional
Whether to remove polygons that are fully outside of the image.
partly : bool, opt... |
def clip_out_of_image(self):
"""
Clip off all parts from all polygons that are outside of the image.
NOTE: The result can contain less polygons than the input did. That
happens when a polygon is fully outside of the image plane.
NOTE: The result can also contain *more* polygons... |
def shift(self, top=None, right=None, bottom=None, left=None):
"""
Shift all polygons from one or more image sides, i.e. move them on the x/y-axis.
Parameters
----------
top : None or int, optional
Amount of pixels by which to shift all polygons from the top.
... |
def deepcopy(self):
"""
Create a deep copy of the PolygonsOnImage object.
Returns
-------
imgaug.PolygonsOnImage
Deep copy.
"""
# Manual copy is far faster than deepcopy for PolygonsOnImage,
# so use manual copy here too
polys = [poly... |
def from_shapely(geometry, label=None):
"""
Create a MultiPolygon from a Shapely MultiPolygon, a Shapely Polygon or a Shapely GeometryCollection.
This also creates all necessary Polygons contained by this MultiPolygon.
Parameters
----------
geometry : shapely.geometry.M... |
def Pad(px=None, percent=None, pad_mode="constant", pad_cval=0, keep_size=True, sample_independently=True,
name=None, deterministic=False, random_state=None):
"""
Augmenter that pads images, i.e. adds columns/rows to them.
dtype support::
See ``imgaug.augmenters.size.CropAndPad``.
Par... |
def Crop(px=None, percent=None, keep_size=True, sample_independently=True,
name=None, deterministic=False, random_state=None):
"""
Augmenter that crops/cuts away pixels at the sides of the image.
That allows to cut out subimages from given (full) input images.
The number of pixels to cut off m... |
def isect_segments__naive(segments):
"""
Brute force O(n2) version of ``isect_segments`` for test validation.
"""
isect = []
# order points left -> right
if Real is float:
segments = [
(s[0], s[1]) if s[0][X] <= s[1][X] else
(s[1], s[0])
for s in segm... |
def isect_polygon__naive(points):
"""
Brute force O(n2) version of ``isect_polygon`` for test validation.
"""
isect = []
n = len(points)
if Real is float:
pass
else:
points = [(Real(p[0]), Real(p[1])) for p in points]
for i in range(n):
a0, a1 = points[i], poi... |
def get_intersections(self):
"""
Return a list of unordered intersection points.
"""
if Real is float:
return list(self.intersections.keys())
else:
return [(float(p[0]), float(p[1])) for p in self.intersections.keys()] |
def get_intersections_with_segments(self):
"""
Return a list of unordered intersection '(point, segment)' pairs,
where segments may contain 2 or more values.
"""
if Real is float:
return [
(p, [event.segment for event in event_set])
for... |
def poll(self):
"""
Get, and remove, the first (lowest) item from this queue.
:return: the first (lowest) item from this queue.
:rtype: Point, Event pair.
"""
assert(len(self.events_scan) != 0)
p, events_current = self.events_scan.pop_min()
return p, even... |
def clear(self):
"""T.clear() -> None. Remove all items from T."""
def _clear(node):
if node is not None:
_clear(node.left)
_clear(node.right)
node.free()
_clear(self._root)
self._count = 0
self._root = None |
def pop_item(self):
"""T.pop_item() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if T is empty.
"""
if self.is_empty():
raise KeyError("pop_item(): tree is empty")
node = self._root
while True:
if node.left i... |
def min_item(self):
"""Get item with min key of tree, raises ValueError if tree is empty."""
if self.is_empty():
raise ValueError("Tree is empty")
node = self._root
while node.left is not None:
node = node.left
return node.key, node.value |
def max_item(self):
"""Get item with max key of tree, raises ValueError if tree is empty."""
if self.is_empty():
raise ValueError("Tree is empty")
node = self._root
while node.right is not None:
node = node.right
return node.key, node.value |
def succ_item(self, key, default=_sentinel):
"""Get successor (k,v) pair of key, raises KeyError if key is max key
or key does not exist. optimized for pypy.
"""
# removed graingets version, because it was little slower on CPython and much slower on pypy
# this version runs about... |
def prev_item(self, key, default=_sentinel):
"""Get predecessor (k,v) pair of key, raises KeyError if key is min key
or key does not exist. optimized for pypy.
"""
# removed graingets version, because it was little slower on CPython and much slower on pypy
# this version runs abo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.