index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
57,069
nibabel.spm99analyze
Spm99AnalyzeHeader
Class for SPM99 variant of basic Analyze header SPM99 variant adds the following to basic Analyze format: * voxel origin; * slope scaling of data.
class Spm99AnalyzeHeader(SpmAnalyzeHeader): """Class for SPM99 variant of basic Analyze header SPM99 variant adds the following to basic Analyze format: * voxel origin; * slope scaling of data. """ def get_origin_affine(self): """Get affine from header, using SPM origin field if sensible The default translations are got from the ``origin`` field, if set, or from the center of the image otherwise. Examples -------- >>> hdr = Spm99AnalyzeHeader() >>> hdr.set_data_shape((3, 5, 7)) >>> hdr.set_zooms((3, 2, 1)) >>> hdr.default_x_flip True >>> hdr.get_origin_affine() # from center of image array([[-3., 0., 0., 3.], [ 0., 2., 0., -4.], [ 0., 0., 1., -3.], [ 0., 0., 0., 1.]]) >>> hdr['origin'][:3] = [3,4,5] >>> hdr.get_origin_affine() # using origin array([[-3., 0., 0., 6.], [ 0., 2., 0., -6.], [ 0., 0., 1., -4.], [ 0., 0., 0., 1.]]) >>> hdr['origin'] = 0 # unset origin >>> hdr.set_data_shape((3, 5, 7)) >>> hdr.get_origin_affine() # from center of image array([[-3., 0., 0., 3.], [ 0., 2., 0., -4.], [ 0., 0., 1., -3.], [ 0., 0., 0., 1.]]) """ hdr = self._structarr zooms = hdr['pixdim'][1:4].copy() if self.default_x_flip: zooms[0] *= -1 # Get translations from origin, or center of image # Remember that the origin is for matlab (1-based indexing) origin = hdr['origin'][:3] dims = hdr['dim'][1:4] if np.any(origin) and np.all(origin > -dims) and np.all(origin < dims * 2): origin = origin - 1 else: origin = (dims - 1) / 2.0 aff = np.eye(4) aff[:3, :3] = np.diag(zooms) aff[:3, -1] = -origin * zooms return aff get_best_affine = get_origin_affine def set_origin_from_affine(self, affine): """Set SPM origin to header from affine matrix. The ``origin`` field was read but not written by SPM99 and 2. It was used for storing a central voxel coordinate, that could be used in aligning the image to some standard position - a proxy for a full translation vector that was usually stored in a separate matlab .mat file. Nifti uses the space occupied by the SPM ``origin`` field for important other information (the transform codes), so writing the origin will make the header a confusing Nifti file. If you work with both Analyze and Nifti, you should probably avoid doing this. Parameters ---------- affine : array-like, shape (4,4) Affine matrix to set Returns ------- None Examples -------- >>> hdr = Spm99AnalyzeHeader() >>> hdr.set_data_shape((3, 5, 7)) >>> hdr.set_zooms((3,2,1)) >>> hdr.get_origin_affine() array([[-3., 0., 0., 3.], [ 0., 2., 0., -4.], [ 0., 0., 1., -3.], [ 0., 0., 0., 1.]]) >>> affine = np.diag([3,2,1,1]) >>> affine[:3,3] = [-6, -6, -4] >>> hdr.set_origin_from_affine(affine) >>> np.all(hdr['origin'][:3] == [3,4,5]) True >>> hdr.get_origin_affine() array([[-3., 0., 0., 6.], [ 0., 2., 0., -6.], [ 0., 0., 1., -4.], [ 0., 0., 0., 1.]]) """ if affine.shape != (4, 4): raise ValueError('Need 4x4 affine to set') hdr = self._structarr RZS = affine[:3, :3] Z = np.sqrt(np.sum(RZS * RZS, axis=0)) T = affine[:3, 3] # Remember that the origin is for matlab (1-based) indexing hdr['origin'][:3] = -T / Z + 1 @classmethod def _get_checks(klass): checks = super()._get_checks() return checks + (klass._chk_origin,) @staticmethod def _chk_origin(hdr, fix=False): rep = Report(HeaderDataError) origin = hdr['origin'][0:3] dims = hdr['dim'][1:4] if not np.any(origin) or (np.all(origin > -dims) and np.all(origin < dims * 2)): return hdr, rep rep.problem_level = 20 rep.problem_msg = 'very large origin values relative to dims' if fix: rep.fix_msg = 'leaving as set, ignoring for affine' return hdr, rep
(binaryblock=None, endianness=None, check=True)
57,094
nibabel.spm99analyze
get_slope_inter
Get scalefactor and intercept If scalefactor is 0.0 return None to indicate no scalefactor. Intercept is always None because SPM99 analyze cannot store intercepts.
def get_slope_inter(self): """Get scalefactor and intercept If scalefactor is 0.0 return None to indicate no scalefactor. Intercept is always None because SPM99 analyze cannot store intercepts. """ slope = self._structarr['scl_slope'] # Return invalid slopes as None if np.isnan(slope) or slope in (0, -np.inf, np.inf): return None, None return slope, None
(self)
57,108
nibabel.spm99analyze
Spm99AnalyzeImage
Class for SPM99 variant of basic Analyze image
class Spm99AnalyzeImage(analyze.AnalyzeImage): """Class for SPM99 variant of basic Analyze image""" header_class = Spm99AnalyzeHeader header: Spm99AnalyzeHeader files_types = (('image', '.img'), ('header', '.hdr'), ('mat', '.mat')) has_affine = True makeable = True rw = have_scipy @classmethod def from_file_map(klass, file_map, *, mmap=True, keep_file_open=None): """Class method to create image from mapping in ``file_map`` Parameters ---------- file_map : dict Mapping with (kay, value) pairs of (``file_type``, FileHolder instance giving file-likes for each file needed for this image type. mmap : {True, False, 'c', 'r'}, optional, keyword only `mmap` controls the use of numpy memory mapping for reading image array data. If False, do not try numpy ``memmap`` for data array. If one of {'c', 'r'}, try numpy memmap with ``mode=mmap``. A `mmap` value of True gives the same behavior as ``mmap='c'``. If image data file cannot be memory-mapped, ignore `mmap` value and read array from file. keep_file_open : { None, True, False }, optional, keyword only `keep_file_open` controls whether a new file handle is created every time the image is accessed, or a single file handle is created and used for the lifetime of this ``ArrayProxy``. If ``True``, a single file handle is created and used. If ``False``, a new file handle is created every time the image is accessed. If ``file_map`` refers to an open file handle, this setting has no effect. The default value (``None``) will result in the value of ``nibabel.arrayproxy.KEEP_FILE_OPEN_DEFAULT`` being used. Returns ------- img : Spm99AnalyzeImage instance """ ret = super().from_file_map(file_map, mmap=mmap, keep_file_open=keep_file_open) try: matf = file_map['mat'].get_prepare_fileobj() except OSError: return ret # Allow for possibility of empty file -> no update to affine with matf: contents = matf.read() if len(contents) == 0: return ret import scipy.io as sio # type: ignore mats = sio.loadmat(BytesIO(contents)) if 'mat' in mats: # this overrides a 'M', and includes any flip mat = mats['mat'] if mat.ndim > 2: warnings.warn('More than one affine in "mat" matrix, using first') mat = mat[:, :, 0] ret._affine = mat elif 'M' in mats: # the 'M' matrix does not include flips hdr = ret._header if hdr.default_x_flip: ret._affine = np.dot(np.diag([-1, 1, 1, 1]), mats['M']) else: ret._affine = mats['M'] else: raise ValueError('mat file found but no "mat" or "M" in it') # Adjust for matlab 1,1,1 voxel origin to_111 = np.eye(4) to_111[:3, 3] = 1 ret._affine = np.dot(ret._affine, to_111) return ret def to_file_map(self, file_map=None, dtype=None): """Write image to `file_map` or contained ``self.file_map`` Extends Analyze ``to_file_map`` method by writing ``mat`` file Parameters ---------- file_map : None or mapping, optional files mapping. If None (default) use object's ``file_map`` attribute instead """ if file_map is None: file_map = self.file_map super().to_file_map(file_map, dtype=dtype) mat = self._affine if mat is None: return import scipy.io as sio hdr = self._header if hdr.default_x_flip: M = np.dot(np.diag([-1, 1, 1, 1]), mat) else: M = mat # Adjust for matlab 1,1,1 voxel origin from_111 = np.eye(4) from_111[:3, 3] = -1 M = np.dot(M, from_111) mat = np.dot(mat, from_111) # use matlab 4 format to allow gzipped write without error with file_map['mat'].get_prepare_fileobj(mode='wb') as mfobj: sio.savemat(mfobj, {'M': M, 'mat': mat}, format='4')
(dataobj, affine, header=None, extra=None, file_map=None, dtype=None)
57,127
nibabel.pkg_info
get_pkg_info
Return dict describing the context of this package Parameters ---------- pkg_path : str path containing __init__.py for package Returns ------- context : dict with named parameters of interest
def get_pkg_info(pkg_path: str) -> dict[str, str]: """Return dict describing the context of this package Parameters ---------- pkg_path : str path containing __init__.py for package Returns ------- context : dict with named parameters of interest """ src, hsh = pkg_commit_hash(pkg_path) import numpy return dict( pkg_path=pkg_path, commit_source=src, commit_hash=hsh, sys_version=sys.version, sys_executable=sys.executable, sys_platform=sys.platform, np_version=numpy.__version__, )
(pkg_path: str) -> dict[str, str]
57,129
nibabel.orientations
aff2axcodes
axis direction codes for affine `aff` Parameters ---------- aff : (N,M) array-like affine transformation matrix labels : optional, None or sequence of (2,) sequences Labels for negative and positive ends of output axes of `aff`. See docstring for ``ornt2axcodes`` for more detail tol : None or float Tolerance for SVD of affine - see ``io_orientation`` for more detail. Returns ------- axcodes : (N,) tuple labels for positive end of voxel axes. Dropped axes get a label of None. Examples -------- >>> aff = [[0,1,0,10],[-1,0,0,20],[0,0,1,30],[0,0,0,1]] >>> aff2axcodes(aff, (('L','R'),('B','F'),('D','U'))) ('B', 'R', 'U')
def aff2axcodes(aff, labels=None, tol=None): """axis direction codes for affine `aff` Parameters ---------- aff : (N,M) array-like affine transformation matrix labels : optional, None or sequence of (2,) sequences Labels for negative and positive ends of output axes of `aff`. See docstring for ``ornt2axcodes`` for more detail tol : None or float Tolerance for SVD of affine - see ``io_orientation`` for more detail. Returns ------- axcodes : (N,) tuple labels for positive end of voxel axes. Dropped axes get a label of None. Examples -------- >>> aff = [[0,1,0,10],[-1,0,0,20],[0,0,1,30],[0,0,0,1]] >>> aff2axcodes(aff, (('L','R'),('B','F'),('D','U'))) ('B', 'R', 'U') """ ornt = io_orientation(aff, tol) return ornt2axcodes(ornt, labels)
(aff, labels=None, tol=None)
57,133
nibabel.orientations
apply_orientation
Apply transformations implied by `ornt` to the first n axes of the array `arr` Parameters ---------- arr : array-like of data with ndim >= n ornt : (n,2) orientation array orientation transform. ``ornt[N,1]` is flip of axis N of the array implied by `shape`, where 1 means no flip and -1 means flip. For example, if ``N==0`` and ``ornt[0,1] == -1``, and there's an array ``arr`` of shape `shape`, the flip would correspond to the effect of ``np.flipud(arr)``. ``ornt[:,0]`` is the transpose that needs to be done to the implied array, as in ``arr.transpose(ornt[:,0])`` Returns ------- t_arr : ndarray data array `arr` transformed according to ornt
def apply_orientation(arr, ornt): """Apply transformations implied by `ornt` to the first n axes of the array `arr` Parameters ---------- arr : array-like of data with ndim >= n ornt : (n,2) orientation array orientation transform. ``ornt[N,1]` is flip of axis N of the array implied by `shape`, where 1 means no flip and -1 means flip. For example, if ``N==0`` and ``ornt[0,1] == -1``, and there's an array ``arr`` of shape `shape`, the flip would correspond to the effect of ``np.flipud(arr)``. ``ornt[:,0]`` is the transpose that needs to be done to the implied array, as in ``arr.transpose(ornt[:,0])`` Returns ------- t_arr : ndarray data array `arr` transformed according to ornt """ t_arr = np.asarray(arr) ornt = np.asarray(ornt) n = ornt.shape[0] if t_arr.ndim < n: raise OrientationError('Data array has fewer dimensions than orientation') # no coordinates can be dropped for applying the orientations if np.any(np.isnan(ornt[:, 0])): raise OrientationError('Cannot drop coordinates when applying orientation to data') # apply ornt transformations for ax, flip in enumerate(ornt[:, 1]): if flip == -1: t_arr = np.flip(t_arr, axis=ax) full_transpose = np.arange(t_arr.ndim) # ornt indicates the transpose that has occurred - we reverse it full_transpose[:n] = np.argsort(ornt[:, 0]) t_arr = t_arr.transpose(full_transpose) return t_arr
(arr, ornt)
57,136
nibabel.funcs
as_closest_canonical
Return `img` with data reordered to be closest to canonical Canonical order is the ordering of the output axes. Parameters ---------- img : ``spatialimage`` enforce_diag : {False, True}, optional If True, before transforming image, check if the resulting image affine will be close to diagonal, and if not, raise an error Returns ------- canonical_img : ``spatialimage`` Version of `img` where the underlying array may have been reordered and / or flipped so that axes 0,1,2 are those axes in the input data that are, respectively, closest to the output axis orientation. We modify the affine accordingly. If `img` is already has the correct data ordering, we just return `img` unmodified.
def as_closest_canonical(img, enforce_diag=False): """Return `img` with data reordered to be closest to canonical Canonical order is the ordering of the output axes. Parameters ---------- img : ``spatialimage`` enforce_diag : {False, True}, optional If True, before transforming image, check if the resulting image affine will be close to diagonal, and if not, raise an error Returns ------- canonical_img : ``spatialimage`` Version of `img` where the underlying array may have been reordered and / or flipped so that axes 0,1,2 are those axes in the input data that are, respectively, closest to the output axis orientation. We modify the affine accordingly. If `img` is already has the correct data ordering, we just return `img` unmodified. """ # Get the image class to transform the data for us img = img.as_reoriented(io_orientation(img.affine)) # however, the affine may not be diagonal if enforce_diag and not _aff_is_diag(img.affine): raise OrientationError('Transformed affine is not diagonal') return img
(img, enforce_diag=False)
57,138
nibabel
bench
Run benchmarks for nibabel using pytest The protocol mimics the ``numpy.testing.NoseTester.bench()``. Not all features are currently implemented. Parameters ---------- label : None Unused. verbose: int, optional Verbosity value for test outputs. Positive values increase verbosity, and negative values decrease it. Default is 1. extra_argv : list, optional List with any extra arguments to pass to pytest. Returns ------- code : ExitCode Returns the result of running the tests as a ``pytest.ExitCode`` enum
def bench(label=None, verbose=1, extra_argv=None): """ Run benchmarks for nibabel using pytest The protocol mimics the ``numpy.testing.NoseTester.bench()``. Not all features are currently implemented. Parameters ---------- label : None Unused. verbose: int, optional Verbosity value for test outputs. Positive values increase verbosity, and negative values decrease it. Default is 1. extra_argv : list, optional List with any extra arguments to pass to pytest. Returns ------- code : ExitCode Returns the result of running the tests as a ``pytest.ExitCode`` enum """ try: from importlib.resources import as_file, files except ImportError: from importlib_resources import as_file, files args = [] if extra_argv is not None: args.extend(extra_argv) config_path = files('nibabel') / 'benchmarks/pytest.benchmark.ini' with as_file(config_path) as config: args.extend(['-c', str(config)]) return test(label, verbose, extra_argv=args)
(label=None, verbose=1, extra_argv=None)
57,143
nibabel.funcs
concat_images
Concatenate images in list to single image, along specified dimension Parameters ---------- images : sequence sequence of ``SpatialImage`` or filenames of the same dimensionality\s check_affines : {True, False}, optional If True, then check that all the affines for `images` are nearly the same, raising a ``ValueError`` otherwise. Default is True axis : None or int, optional If None, concatenates on a new dimension. This requires all images to be the same shape. If not None, concatenates on the specified dimension. This requires all images to be the same shape, except on the specified dimension. Returns ------- concat_img : ``SpatialImage`` New image resulting from concatenating `images` across last dimension
def concat_images(images, check_affines=True, axis=None): r"""Concatenate images in list to single image, along specified dimension Parameters ---------- images : sequence sequence of ``SpatialImage`` or filenames of the same dimensionality\s check_affines : {True, False}, optional If True, then check that all the affines for `images` are nearly the same, raising a ``ValueError`` otherwise. Default is True axis : None or int, optional If None, concatenates on a new dimension. This requires all images to be the same shape. If not None, concatenates on the specified dimension. This requires all images to be the same shape, except on the specified dimension. Returns ------- concat_img : ``SpatialImage`` New image resulting from concatenating `images` across last dimension """ images = [load(img) if not hasattr(img, 'get_data') else img for img in images] n_imgs = len(images) if n_imgs == 0: raise ValueError('Cannot concatenate an empty list of images.') img0 = images[0] affine = img0.affine header = img0.header klass = img0.__class__ shape0 = img0.shape n_dim = len(shape0) if axis is None: # collect images in output array for efficiency out_shape = (n_imgs,) + shape0 out_data = np.empty(out_shape) else: # collect images in list for use with np.concatenate out_data = [None] * n_imgs # Get part of shape we need to check inside loop idx_mask = np.ones((n_dim,), dtype=bool) if axis is not None: idx_mask[axis] = False masked_shape = np.array(shape0)[idx_mask] for i, img in enumerate(images): if len(img.shape) != n_dim: raise ValueError(f'Image {i} has {len(img.shape)} dimensions, image 0 has {n_dim}') if not np.all(np.array(img.shape)[idx_mask] == masked_shape): raise ValueError( f'shape {img.shape} for image {i} not compatible with ' f'first image shape {shape0} with axis == {axis}' ) if check_affines and not np.all(img.affine == affine): raise ValueError(f'Affine for image {i} does not match affine for first image') # Do not fill cache in image if it is empty out_data[i] = np.asanyarray(img.dataobj) if axis is None: out_data = np.rollaxis(out_data, 0, out_data.ndim) else: out_data = np.concatenate(out_data, axis=axis) return klass(out_data, affine, header)
(images, check_affines=True, axis=None)
57,154
nibabel.orientations
flip_axis
Flip contents of `axis` in array `arr` flip_axis is deprecated. Please use numpy.flip instead. * deprecated from version: 3.2 * Raises <class 'nibabel.deprecator.ExpiredDeprecationError'> as of version: 5.0
def inv_ornt_aff(ornt, shape): """Affine transform reversing transforms implied in `ornt` Imagine you have an array ``arr`` of shape `shape`, and you apply the transforms implied by `ornt` (more below), to get ``tarr``. ``tarr`` may have a different shape ``shape_prime``. This routine returns the affine that will take a array coordinate for ``tarr`` and give you the corresponding array coordinate in ``arr``. Parameters ---------- ornt : (p, 2) ndarray orientation transform. ``ornt[P, 1]` is flip of axis N of the array implied by `shape`, where 1 means no flip and -1 means flip. For example, if ``P==0`` and ``ornt[0, 1] == -1``, and there's an array ``arr`` of shape `shape`, the flip would correspond to the effect of ``np.flipud(arr)``. ``ornt[:,0]`` gives us the (reverse of the) transpose that has been done to ``arr``. If there are any NaNs in `ornt`, we raise an ``OrientationError`` (see notes) shape : length p sequence shape of array you may transform with `ornt` Returns ------- transform_affine : (p + 1, p + 1) ndarray An array ``arr`` (shape `shape`) might be transformed according to `ornt`, resulting in a transformed array ``tarr``. `transformed_affine` is the transform that takes you from array coordinates in ``tarr`` to array coordinates in ``arr``. Notes ----- If a row in `ornt` contains NaN, this means that the input row does not influence the output space, and is thus effectively dropped from the output space. In that case one ``tarr`` coordinate maps to many ``arr`` coordinates, we can't invert the transform, and we raise an error """ ornt = np.asarray(ornt) if np.any(np.isnan(ornt)): raise OrientationError('We cannot invert orientation transform') p = ornt.shape[0] shape = np.array(shape)[:p] # ornt implies a flip, followed by a transpose. We need the affine # that inverts these. Thus we need the affine that first undoes the # effect of the transpose, then undoes the effects of the flip. # ornt indicates the transpose that has occurred to get the current # ordering, relative to canonical, so we just use that. # undo_reorder is a row permutatation matrix axis_transpose = [int(v) for v in ornt[:, 0]] undo_reorder = np.eye(p + 1)[axis_transpose + [p], :] undo_flip = np.diag(list(ornt[:, 1]) + [1.0]) center_trans = -(shape - 1) / 2.0 undo_flip[:p, p] = (ornt[:, 1] * center_trans) - center_trans return np.dot(undo_flip, undo_reorder)
(arr, axis=0)
57,155
nibabel.funcs
four_to_three
Create 3D images from 4D image by slicing over last axis Parameters ---------- img : image 4D image instance of some class with methods ``get_data``, ``header`` and ``affine``, and a class constructor allowing klass(data, affine, header) Returns ------- imgs : list list of 3D images
def four_to_three(img): """Create 3D images from 4D image by slicing over last axis Parameters ---------- img : image 4D image instance of some class with methods ``get_data``, ``header`` and ``affine``, and a class constructor allowing klass(data, affine, header) Returns ------- imgs : list list of 3D images """ arr = np.asanyarray(img.dataobj) header = img.header affine = img.affine image_maker = img.__class__ if arr.ndim != 4: raise ValueError('Expecting four dimensions') imgs = [] for i in range(arr.shape[3]): arr3d = arr[..., i] img3d = image_maker(arr3d, affine, header) imgs.append(img3d) return imgs
(img)
57,158
nibabel
get_info
null
def get_info(): return _get_pkg_info(os.path.dirname(__file__))
()
57,164
nibabel.orientations
io_orientation
Orientation of input axes in terms of output axes for `affine` Valid for an affine transformation from ``p`` dimensions to ``q`` dimensions (``affine.shape == (q + 1, p + 1)``). The calculated orientations can be used to transform associated arrays to best match the output orientations. If ``p`` > ``q``, then some of the output axes should be considered dropped in this orientation. Parameters ---------- affine : (q+1, p+1) ndarray-like Transformation affine from ``p`` inputs to ``q`` outputs. Usually this will be a shape (4,4) matrix, transforming 3 inputs to 3 outputs, but the code also handles the more general case tol : {None, float}, optional threshold below which SVD values of the affine are considered zero. If `tol` is None, and ``S`` is an array with singular values for `affine`, and ``eps`` is the epsilon value for datatype of ``S``, then `tol` set to ``S.max() * max((q, p)) * eps`` Returns ------- orientations : (p, 2) ndarray one row per input axis, where the first value in each row is the closest corresponding output axis. The second value in each row is 1 if the input axis is in the same direction as the corresponding output axis and -1 if it is in the opposite direction. If a row is [np.nan, np.nan], which can happen when p > q, then this row should be considered dropped.
def io_orientation(affine, tol=None): """Orientation of input axes in terms of output axes for `affine` Valid for an affine transformation from ``p`` dimensions to ``q`` dimensions (``affine.shape == (q + 1, p + 1)``). The calculated orientations can be used to transform associated arrays to best match the output orientations. If ``p`` > ``q``, then some of the output axes should be considered dropped in this orientation. Parameters ---------- affine : (q+1, p+1) ndarray-like Transformation affine from ``p`` inputs to ``q`` outputs. Usually this will be a shape (4,4) matrix, transforming 3 inputs to 3 outputs, but the code also handles the more general case tol : {None, float}, optional threshold below which SVD values of the affine are considered zero. If `tol` is None, and ``S`` is an array with singular values for `affine`, and ``eps`` is the epsilon value for datatype of ``S``, then `tol` set to ``S.max() * max((q, p)) * eps`` Returns ------- orientations : (p, 2) ndarray one row per input axis, where the first value in each row is the closest corresponding output axis. The second value in each row is 1 if the input axis is in the same direction as the corresponding output axis and -1 if it is in the opposite direction. If a row is [np.nan, np.nan], which can happen when p > q, then this row should be considered dropped. """ affine = np.asarray(affine) q, p = affine.shape[0] - 1, affine.shape[1] - 1 # extract the underlying rotation, zoom, shear matrix RZS = affine[:q, :p] zooms = np.sqrt(np.sum(RZS * RZS, axis=0)) # Zooms can be zero, in which case all elements in the column are zero, and # we can leave them as they are zooms[zooms == 0] = 1 RS = RZS / zooms # Transform below is polar decomposition, returning the closest # shearless matrix R to RS P, S, Qs = npl.svd(RS, full_matrices=False) # Threshold the singular values to determine the rank. if tol is None: tol = S.max() * max(RS.shape) * np.finfo(S.dtype).eps keep = S > tol R = np.dot(P[:, keep], Qs[keep]) # the matrix R is such that np.dot(R,R.T) is projection onto the # columns of P[:,keep] and np.dot(R.T,R) is projection onto the rows # of Qs[keep]. R (== np.dot(R, np.eye(p))) gives rotation of the # unit input vectors to output coordinates. Therefore, the row # index of abs max R[:,N], is the output axis changing most as input # axis N changes. In case there are ties, we choose the axes # iteratively, removing used axes from consideration as we go ornt = np.ones((p, 2), dtype=np.int8) * np.nan for in_ax in range(p): col = R[:, in_ax] if not np.allclose(col, 0): out_ax = np.argmax(np.abs(col)) ornt[in_ax, 0] = out_ax assert col[out_ax] != 0 if col[out_ax] < 0: ornt[in_ax, 1] = -1 else: ornt[in_ax, 1] = 1 # remove the identified axis from further consideration, by # zeroing out the corresponding row in R R[out_ax, :] = 0 return ornt
(affine, tol=None)
57,165
nibabel.arrayproxy
is_proxy
Return True if `obj` is an array proxy
def is_proxy(obj): """Return True if `obj` is an array proxy""" try: return obj.is_proxy except AttributeError: return False
(obj)
57,166
nibabel.loadsave
load
Load file given filename, guessing at file type Parameters ---------- filename : str or os.PathLike specification of file to load \*\*kwargs : keyword arguments Keyword arguments to format-specific load Returns ------- img : ``SpatialImage`` Image of guessed type
def load(filename: FileSpec, **kwargs) -> FileBasedImage: r"""Load file given filename, guessing at file type Parameters ---------- filename : str or os.PathLike specification of file to load \*\*kwargs : keyword arguments Keyword arguments to format-specific load Returns ------- img : ``SpatialImage`` Image of guessed type """ filename = _stringify_path(filename) # Check file exists and is not empty try: stat_result = os.stat(filename) except OSError: raise FileNotFoundError(f"No such file or no access: '{filename}'") if stat_result.st_size <= 0: raise ImageFileError(f"Empty file: '{filename}'") sniff = None for image_klass in all_image_classes: is_valid, sniff = image_klass.path_maybe_image(filename, sniff) if is_valid: img = image_klass.from_filename(filename, **kwargs) return img matches, msg = _signature_matches_extension(filename) if not matches: raise ImageFileError(msg) raise ImageFileError(f'Cannot work out file type of "{filename}"')
(filename: 'FileSpec', **kwargs) -> 'FileBasedImage'
57,181
nibabel.loadsave
save
Save an image to file adapting format to `filename` Parameters ---------- img : ``SpatialImage`` image to save filename : str or os.PathLike filename (often implying filenames) to which to save `img`. \*\*kwargs : keyword arguments Keyword arguments to format-specific save Returns ------- None
def save(img: FileBasedImage, filename: FileSpec, **kwargs) -> None: r"""Save an image to file adapting format to `filename` Parameters ---------- img : ``SpatialImage`` image to save filename : str or os.PathLike filename (often implying filenames) to which to save `img`. \*\*kwargs : keyword arguments Keyword arguments to format-specific save Returns ------- None """ filename = _stringify_path(filename) # Save the type as expected try: img.to_filename(filename, **kwargs) except ImageFileError: pass else: return # Be nice to users by making common implicit conversions froot, ext, trailing = splitext_addext(filename, _compressed_suffixes) lext = ext.lower() # Special-case Nifti singles and Pairs # Inline imports, as this module really shouldn't reference any image type from .nifti1 import Nifti1Image, Nifti1Pair from .nifti2 import Nifti2Image, Nifti2Pair converted: FileBasedImage if type(img) == Nifti1Image and lext in ('.img', '.hdr'): converted = Nifti1Pair.from_image(img) elif type(img) == Nifti2Image and lext in ('.img', '.hdr'): converted = Nifti2Pair.from_image(img) elif type(img) == Nifti1Pair and lext == '.nii': converted = Nifti1Image.from_image(img) elif type(img) == Nifti2Pair and lext == '.nii': converted = Nifti2Image.from_image(img) else: # arbitrary conversion valid_klasses = [klass for klass in all_image_classes if lext in klass.valid_exts] if not valid_klasses: # if list is empty raise ImageFileError(f'Cannot work out file type of "{filename}"') # Got a list of valid extensions, but that's no guarantee # the file conversion will work. So, try each image # in order... for klass in valid_klasses: try: converted = klass.from_image(img) break except Exception as e: err = e else: raise err converted.to_filename(filename, **kwargs)
(img: 'FileBasedImage', filename: 'FileSpec', **kwargs) -> 'None'
57,187
nibabel.funcs
squeeze_image
Return image, remove axes length 1 at end of image shape For example, an image may have shape (10,20,30,1,1). In this case squeeze will result in an image with shape (10,20,30). See doctests for further description of behavior. Parameters ---------- img : ``SpatialImage`` Returns ------- squeezed_img : ``SpatialImage`` Copy of img, such that data, and data shape have been squeezed, for dimensions > 3rd, and at the end of the shape list Examples -------- >>> import nibabel as nf >>> shape = (10,20,30,1,1) >>> data = np.arange(np.prod(shape), dtype='int32').reshape(shape) >>> affine = np.eye(4) >>> img = nf.Nifti1Image(data, affine) >>> img.shape == (10, 20, 30, 1, 1) True >>> img2 = squeeze_image(img) >>> img2.shape == (10, 20, 30) True If the data are 3D then last dimensions of 1 are ignored >>> shape = (10,1,1) >>> data = np.arange(np.prod(shape), dtype='int32').reshape(shape) >>> img = nf.ni1.Nifti1Image(data, affine) >>> img.shape == (10, 1, 1) True >>> img2 = squeeze_image(img) >>> img2.shape == (10, 1, 1) True Only *final* dimensions of 1 are squeezed >>> shape = (1, 1, 5, 1, 2, 1, 1) >>> data = data.reshape(shape) >>> img = nf.ni1.Nifti1Image(data, affine) >>> img.shape == (1, 1, 5, 1, 2, 1, 1) True >>> img2 = squeeze_image(img) >>> img2.shape == (1, 1, 5, 1, 2) True
def squeeze_image(img): """Return image, remove axes length 1 at end of image shape For example, an image may have shape (10,20,30,1,1). In this case squeeze will result in an image with shape (10,20,30). See doctests for further description of behavior. Parameters ---------- img : ``SpatialImage`` Returns ------- squeezed_img : ``SpatialImage`` Copy of img, such that data, and data shape have been squeezed, for dimensions > 3rd, and at the end of the shape list Examples -------- >>> import nibabel as nf >>> shape = (10,20,30,1,1) >>> data = np.arange(np.prod(shape), dtype='int32').reshape(shape) >>> affine = np.eye(4) >>> img = nf.Nifti1Image(data, affine) >>> img.shape == (10, 20, 30, 1, 1) True >>> img2 = squeeze_image(img) >>> img2.shape == (10, 20, 30) True If the data are 3D then last dimensions of 1 are ignored >>> shape = (10,1,1) >>> data = np.arange(np.prod(shape), dtype='int32').reshape(shape) >>> img = nf.ni1.Nifti1Image(data, affine) >>> img.shape == (10, 1, 1) True >>> img2 = squeeze_image(img) >>> img2.shape == (10, 1, 1) True Only *final* dimensions of 1 are squeezed >>> shape = (1, 1, 5, 1, 2, 1, 1) >>> data = data.reshape(shape) >>> img = nf.ni1.Nifti1Image(data, affine) >>> img.shape == (1, 1, 5, 1, 2, 1, 1) True >>> img2 = squeeze_image(img) >>> img2.shape == (1, 1, 5, 1, 2) True """ klass = img.__class__ shape = img.shape slen = len(shape) if slen < 4: return klass.from_image(img) for bdim in shape[3::][::-1]: if bdim == 1: slen -= 1 else: break if slen == len(shape): return klass.from_image(img) shape = shape[:slen] data = np.asanyarray(img.dataobj).reshape(shape) return klass(data, img.affine, img.header, img.extra)
(img)
57,189
nibabel
test
Run tests for nibabel using pytest The protocol mimics the ``numpy.testing.NoseTester.test()``. Not all features are currently implemented. Parameters ---------- label : None Unused. verbose: int, optional Verbosity value for test outputs. Positive values increase verbosity, and negative values decrease it. Default is 1. extra_argv : list, optional List with any extra arguments to pass to pytest. doctests: bool, optional If True, run doctests in module. Default is False. coverage: bool, optional If True, report coverage of NumPy code. Default is False. (This requires the `coverage module <https://nedbatchelder.com/code/modules/coveragehtml>`_). raise_warnings : None Unused. timer : False Unused. Returns ------- code : ExitCode Returns the result of running the tests as a ``pytest.ExitCode`` enum
def test( label=None, verbose=1, extra_argv=None, doctests=False, coverage=False, raise_warnings=None, timer=False, ): """ Run tests for nibabel using pytest The protocol mimics the ``numpy.testing.NoseTester.test()``. Not all features are currently implemented. Parameters ---------- label : None Unused. verbose: int, optional Verbosity value for test outputs. Positive values increase verbosity, and negative values decrease it. Default is 1. extra_argv : list, optional List with any extra arguments to pass to pytest. doctests: bool, optional If True, run doctests in module. Default is False. coverage: bool, optional If True, report coverage of NumPy code. Default is False. (This requires the `coverage module <https://nedbatchelder.com/code/modules/coveragehtml>`_). raise_warnings : None Unused. timer : False Unused. Returns ------- code : ExitCode Returns the result of running the tests as a ``pytest.ExitCode`` enum """ import pytest args = [] if label is not None: raise NotImplementedError('Labels cannot be set at present') verbose = int(verbose) if verbose > 0: args.append('-' + 'v' * verbose) elif verbose < 0: args.append('-' + 'q' * -verbose) if extra_argv: args.extend(extra_argv) if doctests: args.append('--doctest-modules') if coverage: args.extend(['--cov', 'nibabel']) if raise_warnings is not None: raise NotImplementedError('Warning filters are not implemented') if timer: raise NotImplementedError('Timing is not implemented') args.extend(['--pyargs', 'nibabel']) return pytest.main(args=args)
(label=None, verbose=1, extra_argv=None, doctests=False, coverage=False, raise_warnings=None, timer=False)
57,195
scooby.report
AutoReport
Auto-generate a scooby.Report for a package. This will generate a report based on the distribution requirements of the package.
class AutoReport(Report): """Auto-generate a scooby.Report for a package. This will generate a report based on the distribution requirements of the package. """ def __init__(self, module, additional=None, ncol=3, text_width=80, sort=False): """Initialize.""" if not isinstance(module, (str, ModuleType)): raise TypeError("Cannot generate report for type " "({})".format(type(module))) if isinstance(module, ModuleType): module = module.__name__ # Autogenerate from distribution requirements core = [module, *get_distribution_dependencies(module)] Report.__init__( self, additional=additional, core=core, optional=[], ncol=ncol, text_width=text_width, sort=sort, )
(module, additional=None, ncol=3, text_width=80, sort=False)
57,196
scooby.report
__init__
Initialize.
def __init__(self, module, additional=None, ncol=3, text_width=80, sort=False): """Initialize.""" if not isinstance(module, (str, ModuleType)): raise TypeError("Cannot generate report for type " "({})".format(type(module))) if isinstance(module, ModuleType): module = module.__name__ # Autogenerate from distribution requirements core = [module, *get_distribution_dependencies(module)] Report.__init__( self, additional=additional, core=core, optional=[], ncol=ncol, text_width=text_width, sort=sort, )
(self, module, additional=None, ncol=3, text_width=80, sort=False)
57,197
scooby.report
__repr__
Return Plain-text version information.
def __repr__(self) -> str: """Return Plain-text version information.""" import textwrap # lazy-load see PR#85 # Width for text-version text = '\n' + self.text_width * '-' + '\n' # Date and time info as title date_text = ' Date: ' mult = 0 indent = len(date_text) for txt in textwrap.wrap(self.date, self.text_width - indent): date_text += ' ' * mult + txt + '\n' mult = indent text += date_text + '\n' # Get length of longest package: min of 18 and max of 40 if self._packages: row_width = min(40, max(18, len(max(self._packages.keys(), key=len)))) else: row_width = 18 # Platform/OS details repr_dict = self.to_dict() for key in ['OS', 'CPU(s)', 'Machine', 'Architecture', 'RAM', 'Environment', 'File system']: if key in repr_dict: text += f'{key:>{row_width}} : {repr_dict[key]}\n' for key, value in self._extra_meta: text += f'{key:>{row_width}} : {value}\n' # Python details text += '\n' for txt in textwrap.wrap('Python ' + self.sys_version, self.text_width - 4): text += ' ' + txt + '\n' if self._packages: text += '\n' # Loop over packages for name, version in self._packages.items(): text += f'{name:>{row_width}} : {version}\n' # MKL details if self.mkl_info: text += '\n' for txt in textwrap.wrap(self.mkl_info, self.text_width - 4): text += ' ' + txt + '\n' # Finish text += self.text_width * '-' return text
(self) -> str
57,198
scooby.report
_add_packages
Add all packages to list; optional ones only if available.
def _add_packages( self, packages: Optional[List[Union[str, ModuleType]]], optional: bool = False ): """Add all packages to list; optional ones only if available.""" # Ensure arguments are a list if isinstance(packages, (str, ModuleType)): pckgs: List[Union[str, ModuleType]] = [ packages, ] elif packages is None or len(packages) < 1: pckgs = list() else: pckgs = list(packages) # Loop over packages for pckg in pckgs: name, version = get_version(pckg) if not (version == MODULE_NOT_FOUND and optional): self._packages[name] = version
(self, packages: Optional[List[Union[str, module]]], optional: bool = False)
57,199
scooby.report
_repr_html_
Return HTML-rendered version information.
def _repr_html_(self) -> str: """Return HTML-rendered version information.""" # Define html-styles border = "border: 1px solid;'" def colspan(html: str, txt: str, ncol: int, nrow: int) -> str: r"""Print txt in a row spanning whole table.""" html += " <tr>\n" html += " <td style='" if ncol == 1: html += "text-align: left; " else: html += "text-align: center; " if nrow == 0: html += "font-weight: bold; font-size: 1.2em; " html += border + " colspan='" html += f"{2 * ncol}'>{txt}</td>\n" html += " </tr>\n" return html def cols(html: str, version: str, name: str, ncol: int, i: int) -> Tuple[str, int]: r"""Print package information in two cells.""" # Check if we have to start a new row if i > 0 and i % ncol == 0: html += " </tr>\n" html += " <tr>\n" align = "left" if ncol == 1 else "right" html += f" <td style='text-align: {align};" html += " " + border + ">%s</td>\n" % name html += " <td style='text-align: left; " html += border + ">%s</td>\n" % version return html, i + 1 # Start html-table html = "<table style='border: 1.5px solid;" if self.max_width: html += f" max-width: {self.max_width}px;" html += "'>\n" # Date and time info as title html = colspan(html, self.date, self.ncol, 0) # Platform/OS details html += " <tr>\n" repr_dict = self.to_dict() i = 0 for key in ['OS', 'CPU(s)', 'Machine', 'Architecture', 'RAM', 'Environment', "File system"]: if key in repr_dict: html, i = cols(html, repr_dict[key], key, self.ncol, i) for meta in self._extra_meta: html, i = cols(html, meta[1], meta[0], self.ncol, i) # Finish row html += " </tr>\n" # Python details html = colspan(html, 'Python ' + self.sys_version, self.ncol, 1) html += " <tr>\n" # Loop over packages i = 0 # Reset count for rows. for name, version in self.packages.items(): html, i = cols(html, version, name, self.ncol, i) # Fill up the row while i % self.ncol != 0: html += " <td style= " + border + "></td>\n" html += " <td style= " + border + "></td>\n" i += 1 # Finish row html += " </tr>\n" # MKL details if self.mkl_info: html = colspan(html, self.mkl_info, self.ncol, 2) # Finish html += "</table>" return html
(self) -> str
57,200
scooby.report
to_dict
Return report as dict for storage.
def to_dict(self) -> Dict[str, str]: """Return report as dict for storage.""" out: Dict[str, str] = {} # Date and time info out['Date'] = self.date # Platform/OS details out['OS'] = self.system out['CPU(s)'] = str(self.cpu_count) out['Machine'] = self.machine out['Architecture'] = self.architecture if self.filesystem: out['File system'] = self.filesystem if self.total_ram != 'unknown': out['RAM'] = self.total_ram out['Environment'] = self.python_environment for meta in self._extra_meta: out[meta[1]] = meta[0] # Python details out['Python'] = self.sys_version # Loop over packages for name, version in self._packages.items(): out[name] = version # MKL details if self.mkl_info: out['MKL'] = self.mkl_info return out
(self) -> Dict[str, str]
57,201
scooby.report
Report
Have Scooby report the active Python environment. Displays the system information when a ``__repr__`` method is called (through outputting or printing). Parameters ---------- additional : list(ModuleType), list(str) List of packages or package names to add to output information. core : list(ModuleType), list(str) The core packages to list first. optional : list(ModuleType), list(str) A list of packages to list if they are available. If not available, no warnings or error will be thrown. Defaults to ``['numpy', 'scipy', 'IPython', 'matplotlib', 'scooby']`` ncol : int, optional Number of package-columns in html table (no effect in text-version); Defaults to 3. text_width : int, optional The text width for non-HTML display modes. sort : bool, optional Sort the packages when the report is shown. extra_meta : tuple(tuple(str, str), ...), optional Additional two component pairs of meta information to display. max_width : int, optional Max-width of html-table. By default None.
class Report(PlatformInfo, PythonInfo): """Have Scooby report the active Python environment. Displays the system information when a ``__repr__`` method is called (through outputting or printing). Parameters ---------- additional : list(ModuleType), list(str) List of packages or package names to add to output information. core : list(ModuleType), list(str) The core packages to list first. optional : list(ModuleType), list(str) A list of packages to list if they are available. If not available, no warnings or error will be thrown. Defaults to ``['numpy', 'scipy', 'IPython', 'matplotlib', 'scooby']`` ncol : int, optional Number of package-columns in html table (no effect in text-version); Defaults to 3. text_width : int, optional The text width for non-HTML display modes. sort : bool, optional Sort the packages when the report is shown. extra_meta : tuple(tuple(str, str), ...), optional Additional two component pairs of meta information to display. max_width : int, optional Max-width of html-table. By default None. """ def __init__( self, additional: Optional[List[Union[str, ModuleType]]] = None, core: Optional[List[Union[str, ModuleType]]] = None, optional: Optional[List[Union[str, ModuleType]]] = None, ncol: int = 4, text_width: int = 80, sort: bool = False, extra_meta: Optional[Union[Tuple[Tuple[str, str], ...], List[Tuple[str, str]]]] = None, max_width: Optional[int] = None, ) -> None: """Initialize report.""" # Set default optional packages to investigate if optional is None: optional = ['numpy', 'scipy', 'IPython', 'matplotlib', 'scooby'] PythonInfo.__init__(self, additional=additional, core=core, optional=optional, sort=sort) self.ncol = int(ncol) self.text_width = int(text_width) self.max_width = max_width if extra_meta is not None: if not isinstance(extra_meta, (list, tuple)): raise TypeError("`extra_meta` must be a list/tuple of " "key-value pairs.") if len(extra_meta) == 2 and isinstance(extra_meta[0], str): extra_meta = [extra_meta] for meta in extra_meta: if not isinstance(meta, (list, tuple)) or len(meta) != 2: raise TypeError("Each chunk of meta info must have two values.") else: extra_meta = [] self._extra_meta = extra_meta def __repr__(self) -> str: """Return Plain-text version information.""" import textwrap # lazy-load see PR#85 # Width for text-version text = '\n' + self.text_width * '-' + '\n' # Date and time info as title date_text = ' Date: ' mult = 0 indent = len(date_text) for txt in textwrap.wrap(self.date, self.text_width - indent): date_text += ' ' * mult + txt + '\n' mult = indent text += date_text + '\n' # Get length of longest package: min of 18 and max of 40 if self._packages: row_width = min(40, max(18, len(max(self._packages.keys(), key=len)))) else: row_width = 18 # Platform/OS details repr_dict = self.to_dict() for key in ['OS', 'CPU(s)', 'Machine', 'Architecture', 'RAM', 'Environment', 'File system']: if key in repr_dict: text += f'{key:>{row_width}} : {repr_dict[key]}\n' for key, value in self._extra_meta: text += f'{key:>{row_width}} : {value}\n' # Python details text += '\n' for txt in textwrap.wrap('Python ' + self.sys_version, self.text_width - 4): text += ' ' + txt + '\n' if self._packages: text += '\n' # Loop over packages for name, version in self._packages.items(): text += f'{name:>{row_width}} : {version}\n' # MKL details if self.mkl_info: text += '\n' for txt in textwrap.wrap(self.mkl_info, self.text_width - 4): text += ' ' + txt + '\n' # Finish text += self.text_width * '-' return text def _repr_html_(self) -> str: """Return HTML-rendered version information.""" # Define html-styles border = "border: 1px solid;'" def colspan(html: str, txt: str, ncol: int, nrow: int) -> str: r"""Print txt in a row spanning whole table.""" html += " <tr>\n" html += " <td style='" if ncol == 1: html += "text-align: left; " else: html += "text-align: center; " if nrow == 0: html += "font-weight: bold; font-size: 1.2em; " html += border + " colspan='" html += f"{2 * ncol}'>{txt}</td>\n" html += " </tr>\n" return html def cols(html: str, version: str, name: str, ncol: int, i: int) -> Tuple[str, int]: r"""Print package information in two cells.""" # Check if we have to start a new row if i > 0 and i % ncol == 0: html += " </tr>\n" html += " <tr>\n" align = "left" if ncol == 1 else "right" html += f" <td style='text-align: {align};" html += " " + border + ">%s</td>\n" % name html += " <td style='text-align: left; " html += border + ">%s</td>\n" % version return html, i + 1 # Start html-table html = "<table style='border: 1.5px solid;" if self.max_width: html += f" max-width: {self.max_width}px;" html += "'>\n" # Date and time info as title html = colspan(html, self.date, self.ncol, 0) # Platform/OS details html += " <tr>\n" repr_dict = self.to_dict() i = 0 for key in ['OS', 'CPU(s)', 'Machine', 'Architecture', 'RAM', 'Environment', "File system"]: if key in repr_dict: html, i = cols(html, repr_dict[key], key, self.ncol, i) for meta in self._extra_meta: html, i = cols(html, meta[1], meta[0], self.ncol, i) # Finish row html += " </tr>\n" # Python details html = colspan(html, 'Python ' + self.sys_version, self.ncol, 1) html += " <tr>\n" # Loop over packages i = 0 # Reset count for rows. for name, version in self.packages.items(): html, i = cols(html, version, name, self.ncol, i) # Fill up the row while i % self.ncol != 0: html += " <td style= " + border + "></td>\n" html += " <td style= " + border + "></td>\n" i += 1 # Finish row html += " </tr>\n" # MKL details if self.mkl_info: html = colspan(html, self.mkl_info, self.ncol, 2) # Finish html += "</table>" return html def to_dict(self) -> Dict[str, str]: """Return report as dict for storage.""" out: Dict[str, str] = {} # Date and time info out['Date'] = self.date # Platform/OS details out['OS'] = self.system out['CPU(s)'] = str(self.cpu_count) out['Machine'] = self.machine out['Architecture'] = self.architecture if self.filesystem: out['File system'] = self.filesystem if self.total_ram != 'unknown': out['RAM'] = self.total_ram out['Environment'] = self.python_environment for meta in self._extra_meta: out[meta[1]] = meta[0] # Python details out['Python'] = self.sys_version # Loop over packages for name, version in self._packages.items(): out[name] = version # MKL details if self.mkl_info: out['MKL'] = self.mkl_info return out
(additional: Optional[List[Union[str, module]]] = None, core: Optional[List[Union[str, module]]] = None, optional: Optional[List[Union[str, module]]] = None, ncol: int = 4, text_width: int = 80, sort: bool = False, extra_meta: Union[Tuple[Tuple[str, str], ...], List[Tuple[str, str]], NoneType] = None, max_width: Optional[int] = None) -> None
57,202
scooby.report
__init__
Initialize report.
def __init__( self, additional: Optional[List[Union[str, ModuleType]]] = None, core: Optional[List[Union[str, ModuleType]]] = None, optional: Optional[List[Union[str, ModuleType]]] = None, ncol: int = 4, text_width: int = 80, sort: bool = False, extra_meta: Optional[Union[Tuple[Tuple[str, str], ...], List[Tuple[str, str]]]] = None, max_width: Optional[int] = None, ) -> None: """Initialize report.""" # Set default optional packages to investigate if optional is None: optional = ['numpy', 'scipy', 'IPython', 'matplotlib', 'scooby'] PythonInfo.__init__(self, additional=additional, core=core, optional=optional, sort=sort) self.ncol = int(ncol) self.text_width = int(text_width) self.max_width = max_width if extra_meta is not None: if not isinstance(extra_meta, (list, tuple)): raise TypeError("`extra_meta` must be a list/tuple of " "key-value pairs.") if len(extra_meta) == 2 and isinstance(extra_meta[0], str): extra_meta = [extra_meta] for meta in extra_meta: if not isinstance(meta, (list, tuple)) or len(meta) != 2: raise TypeError("Each chunk of meta info must have two values.") else: extra_meta = [] self._extra_meta = extra_meta
(self, additional: Optional[List[Union[str, module]]] = None, core: Optional[List[Union[str, module]]] = None, optional: Optional[List[Union[str, module]]] = None, ncol: int = 4, text_width: int = 80, sort: bool = False, extra_meta: Union[Tuple[Tuple[str, str], ...], List[Tuple[str, str]], NoneType] = None, max_width: Optional[int] = None) -> NoneType
57,207
scooby.tracker
TrackedReport
A class to inspect the active environment and generate a report. Generates a report based on all imported modules. Simply pass the ``globals()`` dictionary.
class TrackedReport(Report): """A class to inspect the active environment and generate a report. Generates a report based on all imported modules. Simply pass the ``globals()`` dictionary. """ def __init__( self, additional: Optional[List[Union[str, ModuleType]]] = None, ncol: int = 3, text_width: int = 80, sort: bool = False, ): """Initialize.""" if not TRACKING_SUPPORTED: raise RuntimeError(SUPPORT_MESSAGE) if len(TRACKED_IMPORTS) < 2: raise RuntimeError( "There are no tracked imports, please use " "`scooby.track_imports()` before running your " "code." ) Report.__init__( self, additional=additional, core=TRACKED_IMPORTS, ncol=ncol, text_width=text_width, sort=sort, optional=[], )
(additional: Optional[List[Union[str, module]]] = None, ncol: int = 3, text_width: int = 80, sort: bool = False)
57,208
scooby.tracker
__init__
Initialize.
def __init__( self, additional: Optional[List[Union[str, ModuleType]]] = None, ncol: int = 3, text_width: int = 80, sort: bool = False, ): """Initialize.""" if not TRACKING_SUPPORTED: raise RuntimeError(SUPPORT_MESSAGE) if len(TRACKED_IMPORTS) < 2: raise RuntimeError( "There are no tracked imports, please use " "`scooby.track_imports()` before running your " "code." ) Report.__init__( self, additional=additional, core=TRACKED_IMPORTS, ncol=ncol, text_width=text_width, sort=sort, optional=[], )
(self, additional: Optional[List[Union[str, module]]] = None, ncol: int = 3, text_width: int = 80, sort: bool = False)
57,219
scooby.knowledge
get_standard_lib_modules
Return a set of the names of all modules in the standard library.
def get_standard_lib_modules() -> Set[str]: """Return a set of the names of all modules in the standard library.""" site_path = sysconfig.get_path('stdlib') if getattr(sys, 'frozen', False): # within pyinstaller lib_path = os.path.join(site_path, '..') if os.path.isdir(lib_path): names = os.listdir(lib_path) else: names = [] stdlib_pkgs = {name[:-3] for name in names if name.endswith(".py")} else: names = os.listdir(site_path) stdlib_pkgs = set([name if not name.endswith(".py") else name[:-3] for name in names]) stdlib_pkgs = { "python", "sys", "__builtin__", "__builtins__", "builtins", "session", "math", "itertools", "binascii", "array", "atexit", "fcntl", "errno", "gc", "time", "unicodedata", "mmap", }.union(stdlib_pkgs) return stdlib_pkgs
() -> Set[str]
57,220
scooby.report
get_version
Get the version of ``module`` by passing the package or it's name. Parameters ---------- module : str or module Name of a module to import or the module itself. Returns ------- name : str Package name version : str or None Version of module.
def get_version(module: Union[str, ModuleType]) -> Tuple[str, Optional[str]]: """Get the version of ``module`` by passing the package or it's name. Parameters ---------- module : str or module Name of a module to import or the module itself. Returns ------- name : str Package name version : str or None Version of module. """ # module is (1) a module or (2) a string. if not isinstance(module, (str, ModuleType)): raise TypeError("Cannot fetch version from type " "({})".format(type(module))) # module is module; get name if isinstance(module, ModuleType): name = module.__name__ else: name = module module = None # Check aliased names if name in PACKAGE_ALIASES: name = PACKAGE_ALIASES[name] # try importlib.metadata before loading the module try: return name, importlib_version(name) except PackageNotFoundError: module = None # importlib could not find the package, try to load it if module is None: try: module = importlib.import_module(name) except ImportError: return name, MODULE_NOT_FOUND except Exception: return name, MODULE_TROUBLE # Try common version names on loaded module for v_string in ('__version__', 'version'): try: return name, getattr(module, v_string) except AttributeError: pass # Try the VERSION_ATTRIBUTES library try: attr = VERSION_ATTRIBUTES[name] return name, getattr(module, attr) except (KeyError, AttributeError): pass # Try the VERSION_METHODS library try: method = VERSION_METHODS[name] return name, method() except (KeyError, ImportError): pass # If still not found, return VERSION_NOT_FOUND return name, VERSION_NOT_FOUND
(module: Union[str, module]) -> Tuple[str, Optional[str]]
57,221
scooby.knowledge
in_ipykernel
Check if in a ipykernel (most likely Jupyter) environment. Warning ------- There is no way to tell if the code is being executed in a notebook (Jupyter Notebook or Jupyter Lab) or a kernel is used but executed in a QtConsole, or in an IPython console, or any other frontend GUI. However, if `in_ipykernel` returns True, you are most likely in a Jupyter Notebook/Lab, just keep it in mind that there are other possibilities. Returns ------- bool : True if using an ipykernel
def in_ipykernel() -> bool: """Check if in a ipykernel (most likely Jupyter) environment. Warning ------- There is no way to tell if the code is being executed in a notebook (Jupyter Notebook or Jupyter Lab) or a kernel is used but executed in a QtConsole, or in an IPython console, or any other frontend GUI. However, if `in_ipykernel` returns True, you are most likely in a Jupyter Notebook/Lab, just keep it in mind that there are other possibilities. Returns ------- bool : True if using an ipykernel """ ipykernel = False if in_ipython(): try: ipykernel: bool = type(get_ipython()).__module__.startswith('ipykernel.') except NameError: pass return ipykernel
() -> bool
57,222
scooby.knowledge
in_ipython
Check if we are in a IPython environment. Returns ------- bool : True ``True`` when in an IPython environment.
def in_ipython() -> bool: """Check if we are in a IPython environment. Returns ------- bool : True ``True`` when in an IPython environment. """ try: __IPYTHON__ return True except NameError: return False
() -> bool
57,224
scooby.knowledge
meets_version
Check if a version string meets a minimum version. This is a simplified way to compare version strings. For a more robust tool, please check out the ``packaging`` library: https://github.com/pypa/packaging Parameters ---------- version : str Version string. For example ``'0.25.1'``. meets : str Version string. For example ``'0.25.2'``. Returns ------- newer : bool True if version ``version`` is greater or equal to version ``meets``. Examples -------- >>> meets_version('0.25.1', '0.25.2') False >>> meets_version('0.26.0', '0.25.2') True
def meets_version(version: str, meets: str) -> bool: """Check if a version string meets a minimum version. This is a simplified way to compare version strings. For a more robust tool, please check out the ``packaging`` library: https://github.com/pypa/packaging Parameters ---------- version : str Version string. For example ``'0.25.1'``. meets : str Version string. For example ``'0.25.2'``. Returns ------- newer : bool True if version ``version`` is greater or equal to version ``meets``. Examples -------- >>> meets_version('0.25.1', '0.25.2') False >>> meets_version('0.26.0', '0.25.2') True """ va = version_tuple(version) vb = version_tuple(meets) if len(va) != len(vb): raise AssertionError("Versions are not comparable.") for i in range(len(va)): if va[i] > vb[i]: return True elif va[i] < vb[i]: return False # Arrived here if same version return True
(version: str, meets: str) -> bool
57,226
scooby.tracker
track_imports
Track all imported modules for the remainder of this session.
def track_imports() -> None: """Track all imported modules for the remainder of this session.""" if not TRACKING_SUPPORTED: raise RuntimeError(SUPPORT_MESSAGE) global STDLIB_PKGS STDLIB_PKGS = get_standard_lib_modules() builtins.__import__ = scooby_import return
() -> NoneType
57,228
scooby.tracker
untrack_imports
Stop tracking imports and return to the builtin import method. This will also clear the tracked imports.
def untrack_imports() -> None: """Stop tracking imports and return to the builtin import method. This will also clear the tracked imports. """ if not TRACKING_SUPPORTED: raise RuntimeError(SUPPORT_MESSAGE) builtins.__import__ = CLASSIC_IMPORT TRACKED_IMPORTS.clear() TRACKED_IMPORTS.append("scooby") return
() -> NoneType
57,230
scooby.knowledge
version_tuple
Convert a version string to a tuple containing ints. Non-numeric version strings will be converted to 0. For example: ``'0.28.0dev0'`` will be converted to ``'0.28.0'`` Returns ------- ver_tuple : tuple Length 3 tuple representing the major, minor, and patch version.
def version_tuple(v: str) -> Tuple[int, ...]: """Convert a version string to a tuple containing ints. Non-numeric version strings will be converted to 0. For example: ``'0.28.0dev0'`` will be converted to ``'0.28.0'`` Returns ------- ver_tuple : tuple Length 3 tuple representing the major, minor, and patch version. """ split_v = v.split(".") while len(split_v) < 3: split_v.append('0') if len(split_v) > 3: raise ValueError('Version strings containing more than three parts ' 'cannot be parsed') vals: List[int] = [] for item in split_v: if item.isnumeric(): vals.append(int(item)) else: vals.append(0) return tuple(vals)
(v: str) -> Tuple[int, ...]
57,231
estnltk_core.layer.annotation
Annotation
Mapping for Span attribute values. Annotation is the object that contains information about the attribute values. Annotations are tied to a Span which hold the information about the location of the annotation. The attributes of an Annotation are formatted as a dictionary and they can be passed as arguments to the Annotation. Once the Annotation has a Span, it can not be changed.
class Annotation(Mapping): """Mapping for Span attribute values. Annotation is the object that contains information about the attribute values. Annotations are tied to a Span which hold the information about the location of the annotation. The attributes of an Annotation are formatted as a dictionary and they can be passed as arguments to the Annotation. Once the Annotation has a Span, it can not be changed. """ __slots__ = ['__dict__', '_span'] def __init__(self, span: 'Span', attributes: Dict[str, Any]={}, **attributes_kwargs): """Initiates a new Annotation object tied to the given span. Note that there are two parameters for assigning attributes to the annotation: `attributes` and `attributes_kwargs`. `attributes` supports a dictionary-based assignment, for example: Annotation( span, {'attr1': ..., 'attr2': ...} ) `attributes_kwargs` supports keyword argument assignments, for example: Annotation( span, attr1=..., attr2=... ) While keyword arguments can only be valid Python keywords (excluding the keyword 'span'), using `attributes` dictionary enables to bypass these restrictions while making the attribute assignments. Note that you can use both `attributes` and `attributes_kwargs` simultaneously. In that case, if there are overlapping argument assignments, then keyword arguments will override dictionary-based assignments. """ self._span = span merged_attributes = { **attributes, **attributes_kwargs } self.__dict__ = merged_attributes def __deepcopy__(self, memo=None): """ Makes a deep copy of all annotation attributes but detaches annotation from span. RATIONALE: One copies an annotation only to attach the copy to a different span. Based on: https://github.com/estnltk/estnltk/blob/974c666b2da3e89dc42d570aad4b66ef060a6742/estnltk/layer/annotation.py#L44 """ memo = memo or {} result = self.__class__(span=None) # Add newly created valid mutable objects to memo memo[id(self)] = result # Perform deep copy with a valid memo dict result.__dict__ = deepcopy(self.__dict__, memo) return result @property def span(self): return self._span @property def start(self) -> int: if self._span: return self._span.start @property def end(self) -> int: if self._span: return self._span.end @property def layer(self): if self._span: return self._span.layer @property def legal_attribute_names(self) -> Sequence[str]: if self.layer is not None: return self.layer.attributes @property def text_object(self): if self._span is not None: return self._span.text_object @property def text(self): if self._span: return self._span.text def __setattr__(self, key, value): if key in self.__slots__: super().__setattr__(key, value) elif key == 'span': if self._span is None: super().__setattr__('_span', value) else: raise AttributeError('this Annotation object already has a span') else: self.__dict__[key] = value def __contains__(self, item): return item in self.__dict__ def __len__(self): return len(self.__dict__) def __setitem__(self, key, value): self.__dict__[key] = value def __getitem__(self, item): if isinstance(item, str): return self.__dict__[item] if isinstance(item, tuple): return tuple(self.__dict__[i] for i in item) raise TypeError(item) def __iter__(self): yield from self.__dict__ def __delitem__(self, key): del self.__dict__[key] def __delattr__(self, item): try: del self[item] except KeyError as key_error: raise AttributeError(key_error.args[0]) from key_error def __eq__(self, other: Any) -> bool: if isinstance(other, Annotation): self_dict = self.__dict__ other_dict = other.__dict__ if self.layer is not None and len(self.layer.secondary_attributes) > 0: # skip the comparison of the secondary attributes secondary_attributes = self.layer.secondary_attributes self_dict = {k:v for k,v in self_dict.items() if k not in secondary_attributes} other_dict = {k:v for k,v in other_dict.items() if k not in secondary_attributes} return self_dict == other_dict else: return False @recursive_repr() def __repr__(self): # Output key-value pairs in an ordered way # (to assure a consistent output, e.g. for automated testing) if self.legal_attribute_names is None: attribute_names = sorted(self.__dict__) else: attribute_names = self.legal_attribute_names attr_val_repr = _create_attr_val_repr( [(k, self.__dict__[k]) for k in attribute_names] ) return '{class_name}({text!r}, {attributes})'.format(class_name=self.__class__.__name__, text=self.text, attributes=attr_val_repr)
(span: 'Span', attributes: Dict[str, Any] = {}, **attributes_kwargs)
57,232
estnltk_core.layer.annotation
__contains__
null
def __contains__(self, item): return item in self.__dict__
(self, item)
57,233
estnltk_core.layer.annotation
__deepcopy__
Makes a deep copy of all annotation attributes but detaches annotation from span. RATIONALE: One copies an annotation only to attach the copy to a different span. Based on: https://github.com/estnltk/estnltk/blob/974c666b2da3e89dc42d570aad4b66ef060a6742/estnltk/layer/annotation.py#L44
def __deepcopy__(self, memo=None): """ Makes a deep copy of all annotation attributes but detaches annotation from span. RATIONALE: One copies an annotation only to attach the copy to a different span. Based on: https://github.com/estnltk/estnltk/blob/974c666b2da3e89dc42d570aad4b66ef060a6742/estnltk/layer/annotation.py#L44 """ memo = memo or {} result = self.__class__(span=None) # Add newly created valid mutable objects to memo memo[id(self)] = result # Perform deep copy with a valid memo dict result.__dict__ = deepcopy(self.__dict__, memo) return result
(self, memo=None)
57,234
estnltk_core.layer.annotation
__delattr__
null
def __delattr__(self, item): try: del self[item] except KeyError as key_error: raise AttributeError(key_error.args[0]) from key_error
(self, item)
57,235
estnltk_core.layer.annotation
__delitem__
null
def __delitem__(self, key): del self.__dict__[key]
(self, key)
57,236
estnltk_core.layer.annotation
__eq__
null
def __eq__(self, other: Any) -> bool: if isinstance(other, Annotation): self_dict = self.__dict__ other_dict = other.__dict__ if self.layer is not None and len(self.layer.secondary_attributes) > 0: # skip the comparison of the secondary attributes secondary_attributes = self.layer.secondary_attributes self_dict = {k:v for k,v in self_dict.items() if k not in secondary_attributes} other_dict = {k:v for k,v in other_dict.items() if k not in secondary_attributes} return self_dict == other_dict else: return False
(self, other: Any) -> bool
57,237
estnltk_core.layer.annotation
__getitem__
null
def __getitem__(self, item): if isinstance(item, str): return self.__dict__[item] if isinstance(item, tuple): return tuple(self.__dict__[i] for i in item) raise TypeError(item)
(self, item)
57,238
estnltk_core.layer.annotation
__init__
Initiates a new Annotation object tied to the given span. Note that there are two parameters for assigning attributes to the annotation: `attributes` and `attributes_kwargs`. `attributes` supports a dictionary-based assignment, for example: Annotation( span, {'attr1': ..., 'attr2': ...} ) `attributes_kwargs` supports keyword argument assignments, for example: Annotation( span, attr1=..., attr2=... ) While keyword arguments can only be valid Python keywords (excluding the keyword 'span'), using `attributes` dictionary enables to bypass these restrictions while making the attribute assignments. Note that you can use both `attributes` and `attributes_kwargs` simultaneously. In that case, if there are overlapping argument assignments, then keyword arguments will override dictionary-based assignments.
def __init__(self, span: 'Span', attributes: Dict[str, Any]={}, **attributes_kwargs): """Initiates a new Annotation object tied to the given span. Note that there are two parameters for assigning attributes to the annotation: `attributes` and `attributes_kwargs`. `attributes` supports a dictionary-based assignment, for example: Annotation( span, {'attr1': ..., 'attr2': ...} ) `attributes_kwargs` supports keyword argument assignments, for example: Annotation( span, attr1=..., attr2=... ) While keyword arguments can only be valid Python keywords (excluding the keyword 'span'), using `attributes` dictionary enables to bypass these restrictions while making the attribute assignments. Note that you can use both `attributes` and `attributes_kwargs` simultaneously. In that case, if there are overlapping argument assignments, then keyword arguments will override dictionary-based assignments. """ self._span = span merged_attributes = { **attributes, **attributes_kwargs } self.__dict__ = merged_attributes
(self, span: 'Span', attributes: Dict[str, Any] = {}, **attributes_kwargs)
57,239
estnltk_core.layer.annotation
__iter__
null
def __iter__(self): yield from self.__dict__
(self)
57,240
estnltk_core.layer.annotation
__len__
null
def __len__(self): return len(self.__dict__)
(self)
57,241
estnltk_core.layer.annotation
__repr__
null
from copy import deepcopy from reprlib import recursive_repr from typing import Any, Mapping, Sequence, Dict from estnltk_core.common import _create_attr_val_repr class Annotation(Mapping): """Mapping for Span attribute values. Annotation is the object that contains information about the attribute values. Annotations are tied to a Span which hold the information about the location of the annotation. The attributes of an Annotation are formatted as a dictionary and they can be passed as arguments to the Annotation. Once the Annotation has a Span, it can not be changed. """ __slots__ = ['__dict__', '_span'] def __init__(self, span: 'Span', attributes: Dict[str, Any]={}, **attributes_kwargs): """Initiates a new Annotation object tied to the given span. Note that there are two parameters for assigning attributes to the annotation: `attributes` and `attributes_kwargs`. `attributes` supports a dictionary-based assignment, for example: Annotation( span, {'attr1': ..., 'attr2': ...} ) `attributes_kwargs` supports keyword argument assignments, for example: Annotation( span, attr1=..., attr2=... ) While keyword arguments can only be valid Python keywords (excluding the keyword 'span'), using `attributes` dictionary enables to bypass these restrictions while making the attribute assignments. Note that you can use both `attributes` and `attributes_kwargs` simultaneously. In that case, if there are overlapping argument assignments, then keyword arguments will override dictionary-based assignments. """ self._span = span merged_attributes = { **attributes, **attributes_kwargs } self.__dict__ = merged_attributes def __deepcopy__(self, memo=None): """ Makes a deep copy of all annotation attributes but detaches annotation from span. RATIONALE: One copies an annotation only to attach the copy to a different span. Based on: https://github.com/estnltk/estnltk/blob/974c666b2da3e89dc42d570aad4b66ef060a6742/estnltk/layer/annotation.py#L44 """ memo = memo or {} result = self.__class__(span=None) # Add newly created valid mutable objects to memo memo[id(self)] = result # Perform deep copy with a valid memo dict result.__dict__ = deepcopy(self.__dict__, memo) return result @property def span(self): return self._span @property def start(self) -> int: if self._span: return self._span.start @property def end(self) -> int: if self._span: return self._span.end @property def layer(self): if self._span: return self._span.layer @property def legal_attribute_names(self) -> Sequence[str]: if self.layer is not None: return self.layer.attributes @property def text_object(self): if self._span is not None: return self._span.text_object @property def text(self): if self._span: return self._span.text def __setattr__(self, key, value): if key in self.__slots__: super().__setattr__(key, value) elif key == 'span': if self._span is None: super().__setattr__('_span', value) else: raise AttributeError('this Annotation object already has a span') else: self.__dict__[key] = value def __contains__(self, item): return item in self.__dict__ def __len__(self): return len(self.__dict__) def __setitem__(self, key, value): self.__dict__[key] = value def __getitem__(self, item): if isinstance(item, str): return self.__dict__[item] if isinstance(item, tuple): return tuple(self.__dict__[i] for i in item) raise TypeError(item) def __iter__(self): yield from self.__dict__ def __delitem__(self, key): del self.__dict__[key] def __delattr__(self, item): try: del self[item] except KeyError as key_error: raise AttributeError(key_error.args[0]) from key_error def __eq__(self, other: Any) -> bool: if isinstance(other, Annotation): self_dict = self.__dict__ other_dict = other.__dict__ if self.layer is not None and len(self.layer.secondary_attributes) > 0: # skip the comparison of the secondary attributes secondary_attributes = self.layer.secondary_attributes self_dict = {k:v for k,v in self_dict.items() if k not in secondary_attributes} other_dict = {k:v for k,v in other_dict.items() if k not in secondary_attributes} return self_dict == other_dict else: return False @recursive_repr() def __repr__(self): # Output key-value pairs in an ordered way # (to assure a consistent output, e.g. for automated testing) if self.legal_attribute_names is None: attribute_names = sorted(self.__dict__) else: attribute_names = self.legal_attribute_names attr_val_repr = _create_attr_val_repr( [(k, self.__dict__[k]) for k in attribute_names] ) return '{class_name}({text!r}, {attributes})'.format(class_name=self.__class__.__name__, text=self.text, attributes=attr_val_repr)
(self)
57,242
estnltk_core.layer.annotation
__setattr__
null
def __setattr__(self, key, value): if key in self.__slots__: super().__setattr__(key, value) elif key == 'span': if self._span is None: super().__setattr__('_span', value) else: raise AttributeError('this Annotation object already has a span') else: self.__dict__[key] = value
(self, key, value)
57,248
estnltk_core.layer.base_span
BaseSpan
BaseSpan is class that defines meta information about a Span and is used when creating a Span. A BaseSpan can be given a level, start and end of a Span which then make sure that the Span is in the right position in a Layer. Level of a BaseSpan determines its positional structure: whether it is a raw text position or is enveloping around sequences of smaller level text positions. *) ElementaryBaseSpan has level = 0, and it corresponds to a raw text position: (start, end); *) EnvelopingBaseSpan at level = 1 corresponds to a sequence of ElementaryBaseSpan-s: [(start_1, end_1), ..., (start_N, end_N)] *) EnvelopingBaseSpan at level = 2 corresponds to a sequence of level 1 EnvelopingBaseSpans: [((start_11, end_11), ... ), ... ((start_N1, end_N1), ...)] And so forth. Note #1: In case of layers in parent-child relation, a child span has the same level as the parent span. So, if the parent layer is made of level 0 spans (ElementaryBaseSpan-s), then the child layer also has level 0 spans. Note #2: BaseSpans are immutable: once initialized, they cannot be changed anymore.
class BaseSpan: ''' BaseSpan is class that defines meta information about a Span and is used when creating a Span. A BaseSpan can be given a level, start and end of a Span which then make sure that the Span is in the right position in a Layer. Level of a BaseSpan determines its positional structure: whether it is a raw text position or is enveloping around sequences of smaller level text positions. *) ElementaryBaseSpan has level = 0, and it corresponds to a raw text position: (start, end); *) EnvelopingBaseSpan at level = 1 corresponds to a sequence of ElementaryBaseSpan-s: [(start_1, end_1), ..., (start_N, end_N)] *) EnvelopingBaseSpan at level = 2 corresponds to a sequence of level 1 EnvelopingBaseSpans: [((start_11, end_11), ... ), ... ((start_N1, end_N1), ...)] And so forth. Note #1: In case of layers in parent-child relation, a child span has the same level as the parent span. So, if the parent layer is made of level 0 spans (ElementaryBaseSpan-s), then the child layer also has level 0 spans. Note #2: BaseSpans are immutable: once initialized, they cannot be changed anymore. ''' __slots__ = ['_raw', '_hash', 'start', 'end', 'level'] def __init__(self, raw, level: int, start: int, end: int): super().__setattr__('_raw', raw) super().__setattr__('_hash', hash(raw)) super().__setattr__('level', level) super().__setattr__('start', start) super().__setattr__('end', end) def __getstate__(self): return dict( _raw=self._raw, level=self.level, start=self.start, end=self.end ) def __setstate__(self, state): super().__setattr__('_raw', state['_raw']) super().__setattr__('_hash', hash(state['_raw'])) super().__setattr__('level', state['level']) super().__setattr__('start', state['start']) super().__setattr__('end', state['end']) def __setattr__(self, *ignored): raise AttributeError('Basespans are immutable') def __delattr__(self, *ignored): raise AttributeError('Basespans are immutable') def flatten(self): """Returns this basespan flattened to a tuple of raw text positions. For ElementaryBaseSpan, returns ((start, end),). For EnvelopingBaseSpan at any level, returns ((start1, end1), ..., (startN, endN)). """ raise NotImplementedError def reduce(self, level): """Returns this basespan reduced down to a tuple of basespans on a given level. A higher level basespan is a tree of lower-level basespans. This function returns all basespans in the requested level. Parameter `level` must be smaller than or equal to the level of this basespan. """ raise NotImplementedError def raw(self): return self._raw def __eq__(self, other): if self is other: return True if isinstance(other, self.__class__): return self.raw() == other.raw() return False def __lt__(self, other): if isinstance(other, self.__class__): return (self.start, self.end, self.raw()) < (other.start, other.end, other.raw()) raise TypeError('unorderable types: {}<={}'.format(type(self), type(other))) def __le__(self, other): return self == other or self < other
(raw, level: int, start: int, end: int)
57,249
estnltk_core.layer.base_span
__delattr__
null
def __delattr__(self, *ignored): raise AttributeError('Basespans are immutable')
(self, *ignored)
57,250
estnltk_core.layer.base_span
__eq__
null
def __eq__(self, other): if self is other: return True if isinstance(other, self.__class__): return self.raw() == other.raw() return False
(self, other)
57,251
estnltk_core.layer.base_span
__getstate__
null
def __getstate__(self): return dict( _raw=self._raw, level=self.level, start=self.start, end=self.end )
(self)
57,252
estnltk_core.layer.base_span
__init__
null
def __init__(self, raw, level: int, start: int, end: int): super().__setattr__('_raw', raw) super().__setattr__('_hash', hash(raw)) super().__setattr__('level', level) super().__setattr__('start', start) super().__setattr__('end', end)
(self, raw, level: int, start: int, end: int)
57,253
estnltk_core.layer.base_span
__le__
null
def __le__(self, other): return self == other or self < other
(self, other)
57,254
estnltk_core.layer.base_span
__lt__
null
def __lt__(self, other): if isinstance(other, self.__class__): return (self.start, self.end, self.raw()) < (other.start, other.end, other.raw()) raise TypeError('unorderable types: {}<={}'.format(type(self), type(other)))
(self, other)
57,255
estnltk_core.layer.base_span
__setattr__
null
def __setattr__(self, *ignored): raise AttributeError('Basespans are immutable')
(self, *ignored)
57,256
estnltk_core.layer.base_span
__setstate__
null
def __setstate__(self, state): super().__setattr__('_raw', state['_raw']) super().__setattr__('_hash', hash(state['_raw'])) super().__setattr__('level', state['level']) super().__setattr__('start', state['start']) super().__setattr__('end', state['end'])
(self, state)
57,257
estnltk_core.layer.base_span
flatten
Returns this basespan flattened to a tuple of raw text positions. For ElementaryBaseSpan, returns ((start, end),). For EnvelopingBaseSpan at any level, returns ((start1, end1), ..., (startN, endN)).
def flatten(self): """Returns this basespan flattened to a tuple of raw text positions. For ElementaryBaseSpan, returns ((start, end),). For EnvelopingBaseSpan at any level, returns ((start1, end1), ..., (startN, endN)). """ raise NotImplementedError
(self)
57,258
estnltk_core.layer.base_span
raw
null
def raw(self): return self._raw
(self)
57,259
estnltk_core.layer.base_span
reduce
Returns this basespan reduced down to a tuple of basespans on a given level. A higher level basespan is a tree of lower-level basespans. This function returns all basespans in the requested level. Parameter `level` must be smaller than or equal to the level of this basespan.
def reduce(self, level): """Returns this basespan reduced down to a tuple of basespans on a given level. A higher level basespan is a tree of lower-level basespans. This function returns all basespans in the requested level. Parameter `level` must be smaller than or equal to the level of this basespan. """ raise NotImplementedError
(self, level)
57,260
estnltk_core.layer.base_span
ElementaryBaseSpan
An ElementaryBaseSpan is a BaseSpan which has level 0. It corresponds to a raw text position: (start, end).
class ElementaryBaseSpan(BaseSpan): '''An ElementaryBaseSpan is a BaseSpan which has level 0. It corresponds to a raw text position: (start, end). ''' __slots__ = [] def __init__(self, start: int, end: int): if not isinstance(start, int): raise TypeError('expected int, got', type(start)) if not isinstance(end, int): raise TypeError('expected int, got', type(end)) if not 0 <= start <= end: raise ValueError('0 <= {} <= {} not satisfied'.format(start, end)) raw = (start, end) super().__init__(raw=raw, level=0, start=start, end=end) def flatten(self): return (self.start, self.end), def reduce(self, level): if level == 0: return self raise ValueError(level) def __len__(self): return self.end - self.start def __hash__(self): return self._hash def __repr__(self): return '{}{}'.format(self.__class__.__name__, (self.start, self.end))
(start: int, end: int)
57,264
estnltk_core.layer.base_span
__hash__
null
def __hash__(self): return self._hash
(self)
57,265
estnltk_core.layer.base_span
__init__
null
def __init__(self, start: int, end: int): if not isinstance(start, int): raise TypeError('expected int, got', type(start)) if not isinstance(end, int): raise TypeError('expected int, got', type(end)) if not 0 <= start <= end: raise ValueError('0 <= {} <= {} not satisfied'.format(start, end)) raw = (start, end) super().__init__(raw=raw, level=0, start=start, end=end)
(self, start: int, end: int)
57,267
estnltk_core.layer.base_span
__len__
null
def __len__(self): return self.end - self.start
(self)
57,269
estnltk_core.layer.base_span
__repr__
null
def __repr__(self): return '{}{}'.format(self.__class__.__name__, (self.start, self.end))
(self)
57,272
estnltk_core.layer.base_span
flatten
null
def flatten(self): return (self.start, self.end),
(self)
57,274
estnltk_core.layer.base_span
reduce
null
def reduce(self, level): if level == 0: return self raise ValueError(level)
(self, level)
57,275
estnltk_core.layer.base_span
EnvelopingBaseSpan
An EnvelopingBaseSpan is a BaseSpan that is made up of other BaseSpans. Its level determines the depth of its nested structure: *) EnvelopingBaseSpan at level = 1 corresponds to a sequence of ElementaryBaseSpan-s: [(start_1, end_1), ..., (start_N, end_N)] *) EnvelopingBaseSpan at level = 2 corresponds to a sequence of level 1 EnvelopingBaseSpans: [((start_11, end_11), ... ), ... ((start_N1, end_N1), ...)] And so on.
class EnvelopingBaseSpan(BaseSpan): '''An EnvelopingBaseSpan is a BaseSpan that is made up of other BaseSpans. Its level determines the depth of its nested structure: *) EnvelopingBaseSpan at level = 1 corresponds to a sequence of ElementaryBaseSpan-s: [(start_1, end_1), ..., (start_N, end_N)] *) EnvelopingBaseSpan at level = 2 corresponds to a sequence of level 1 EnvelopingBaseSpans: [((start_11, end_11), ... ), ... ((start_N1, end_N1), ...)] And so on. ''' __slots__ = ['_spans'] def __init__(self, spans: Iterable[BaseSpan]): spans = tuple(spans) if len(spans) == 0: raise ValueError('spans is empty') if not all(isinstance(span, BaseSpan) for span in spans): raise TypeError('spans must be of type BaseSpan') for i in range(len(spans) - 1): if spans[i].end > spans[i + 1].start: raise ValueError('enveloped components must be sorted and must not overlap: {}, {}'.format( spans[i], spans[i+1])) base_level = spans[0].level if any(span.level != base_level for span in spans): raise ValueError('enveloped components must have the same levels: {}'.format( [span.level for span in spans])) raw = tuple(span.raw() for span in spans) object.__setattr__(self, '_spans', spans) super().__init__(raw=raw, level=base_level+1, start=spans[0].start, end=spans[-1].end) def __getstate__(self): state = super().__getstate__() state['_spans'] = self._spans return state def __setstate__(self, state): object.__setattr__(self, '_spans', state['_spans']) super().__setstate__(state) def flatten(self): return tuple(sp for span in self._spans for sp in span.flatten()) def reduce(self, level): if self.level == level: return self if self.level == level + 1: return self._spans if self.level > level: return tuple(sp for span in self._spans for sp in span.reduce(level)) raise ValueError(level) def __len__(self): return len(self._spans) def __getitem__(self, item): return self._spans[item] def __iter__(self): return iter(self._spans) def __hash__(self): return self._hash def __repr__(self): return '{}({})'.format(self.__class__.__name__, self._spans)
(spans: Iterable[estnltk_core.layer.base_span.BaseSpan])
57,278
estnltk_core.layer.base_span
__getitem__
null
def __getitem__(self, item): return self._spans[item]
(self, item)
57,279
estnltk_core.layer.base_span
__getstate__
null
def __getstate__(self): state = super().__getstate__() state['_spans'] = self._spans return state
(self)
57,281
estnltk_core.layer.base_span
__init__
null
def __init__(self, spans: Iterable[BaseSpan]): spans = tuple(spans) if len(spans) == 0: raise ValueError('spans is empty') if not all(isinstance(span, BaseSpan) for span in spans): raise TypeError('spans must be of type BaseSpan') for i in range(len(spans) - 1): if spans[i].end > spans[i + 1].start: raise ValueError('enveloped components must be sorted and must not overlap: {}, {}'.format( spans[i], spans[i+1])) base_level = spans[0].level if any(span.level != base_level for span in spans): raise ValueError('enveloped components must have the same levels: {}'.format( [span.level for span in spans])) raw = tuple(span.raw() for span in spans) object.__setattr__(self, '_spans', spans) super().__init__(raw=raw, level=base_level+1, start=spans[0].start, end=spans[-1].end)
(self, spans: Iterable[estnltk_core.layer.base_span.BaseSpan])
57,282
estnltk_core.layer.base_span
__iter__
null
def __iter__(self): return iter(self._spans)
(self)
57,284
estnltk_core.layer.base_span
__len__
null
def __len__(self): return len(self._spans)
(self)
57,286
estnltk_core.layer.base_span
__repr__
null
def __repr__(self): return '{}({})'.format(self.__class__.__name__, self._spans)
(self)
57,288
estnltk_core.layer.base_span
__setstate__
null
def __setstate__(self, state): object.__setattr__(self, '_spans', state['_spans']) super().__setstate__(state)
(self, state)
57,289
estnltk_core.layer.base_span
flatten
null
def flatten(self): return tuple(sp for span in self._spans for sp in span.flatten())
(self)
57,291
estnltk_core.layer.base_span
reduce
null
def reduce(self, level): if self.level == level: return self if self.level == level + 1: return self._spans if self.level > level: return tuple(sp for span in self._spans for sp in span.reduce(level)) raise ValueError(level)
(self, level)
57,292
estnltk_core.layer.enveloping_span
EnvelopingSpan
EnvelopingSpan is a Span which envelops around lower level spans. It is used to convey text annotations that build upon other, lower level annotations. For instance, a sentence is an EnvelopingSpan built from word spans, and a paragraph is an EnvelopingSpan built from sentence spans.
class EnvelopingSpan(Span): ''' EnvelopingSpan is a Span which envelops around lower level spans. It is used to convey text annotations that build upon other, lower level annotations. For instance, a sentence is an EnvelopingSpan built from word spans, and a paragraph is an EnvelopingSpan built from sentence spans. ''' __slots__ = ['_spans'] def __init__(self, base_span: BaseSpan, layer): self._spans = None super().__init__(base_span, layer) @classmethod def from_spans(cls, spans: Iterable[Span], layer, records): span = cls(base_span=EnvelopingBaseSpan(s.base_span for s in spans), layer=layer) for record in records: span.add_annotation(Annotation(span, **record)) return span @property def spans(self): if self._spans is None: get_from_enveloped = self._layer.text_object[self._layer.enveloping].get self._spans = tuple(get_from_enveloped(base) for base in self._base_span) return self._spans @property def _html_text(self): rt = self.raw_text result = [] for a, b in zip(self.spans, self.spans[1:]): result.extend(('<b>', rt[a.start:a.end], '</b>', rt[a.end:b.start])) result.extend(('<b>', rt[self.spans[-1].start:self.spans[-1].end], '</b>')) return ''.join(result) def __iter__(self): yield from self.spans def __len__(self) -> int: return len(self._base_span) def __contains__(self, item: Any) -> bool: return item in self.spans def __setattr__(self, key, value): if key == '_spans': object.__setattr__(self, key, value) else: super().__setattr__(key, value) def resolve_attribute(self, item): """Resolves and returns values of foreign attribute `item`, or resolves and returns a foreign span from layer `item`. More specifically: 1) If `item` is a name of a foreign attribute which is listed in the mapping from attribute names to foreign layer names (`attribute_mapping_for_enveloping_layers`), attempts to find foreign span with the same base span as this span from the foreign layer & returns value(s) of the attribute `item` from that foreign span. (raises KeyError if base span is missing in the foreign layer); Note: this is only available when this span belongs to estnltk's `Text` object. The step will be skipped if the span belongs to `BaseText`; 2) If `item` is a layer attached to span's the text_object, and the layer has `span_level` equal to or lower than this enveloping span (meaning: spans of this layer could envelop around spans of the target layer), then attempts to get & return span or spans from the target layer that match the base span of this span (raises KeyError if base span is missing); """ if self.text_object is not None: if hasattr(self.text_object, 'attribute_mapping_for_enveloping_layers'): # Attempt to get the foreign attribute of # the same base span of a different attached # layer, based on the mapping of attributes-layers # (only available if we have estnltk.text.Text object) attribute_mapping = self.text_object.attribute_mapping_for_enveloping_layers if item in attribute_mapping: return self._layer.text_object[attribute_mapping[item]].get(self.base_span)[item] if item in self.text_object.layers: # Attempt to get spans with same base # span(s) from a different attached # layer that has appropriate span_level target_layer = self.text_object[item] if len(target_layer) == 0: return if target_layer.span_level >= self._base_span.level: raise AttributeError('target layer span_level {} should be lower than {}'.format( target_layer.span_level, self._base_span.level)) return target_layer.get(self.base_span) else: raise AttributeError(("Unable to resolve foreign attribute {!r}: "+\ "the layer is not attached to Text object.").format(item) ) raise AttributeError("Unable to resolve foreign attribute {!r}.".format(item)) def __getitem__(self, idx): if isinstance(idx, int): return self.spans[idx] return super().__getitem__(idx)
(base_span: estnltk_core.layer.base_span.BaseSpan, layer)
57,293
estnltk_core.layer.enveloping_span
__contains__
null
def __contains__(self, item: Any) -> bool: return item in self.spans
(self, item: Any) -> bool
57,294
estnltk_core.layer.span
__deepcopy__
Makes a deep copy from the span. Loosely based on: https://github.com/estnltk/estnltk/blob/5bacff50072f9415814aee4f369c28db0e8d7789/estnltk/layer/span.py#L60
def __deepcopy__(self, memo=None): """ Makes a deep copy from the span. Loosely based on: https://github.com/estnltk/estnltk/blob/5bacff50072f9415814aee4f369c28db0e8d7789/estnltk/layer/span.py#L60 """ memo = memo or {} # Create new valid instance # _base_span: Immutable result = self.__class__(base_span=self.base_span, \ layer=None) # Add self to memo memo[id(self)] = result # _annotations: List[Mutable] for annotation in self._annotations: deepcopy_annotation = deepcopy(annotation, memo) deepcopy_annotation.span = result result._annotations.append( deepcopy_annotation ) # _parent: Mutable result._parent = deepcopy(self._parent, memo) # _layer: Mutable result._layer = deepcopy(self._layer, memo) return result
(self, memo=None)
57,295
estnltk_core.layer.span
__eq__
null
def __eq__(self, other: Any) -> bool: return isinstance(other, Span) \ and self.base_span == other.base_span \ and len(self.annotations) == len(other.annotations) \ and all(s in other.annotations for s in self.annotations)
(self, other: Any) -> bool
57,296
estnltk_core.layer.span
__getattr__
null
def __getattr__(self, item): if item in self.__getattribute__('_layer').attributes: return self[item] try: return self.resolve_attribute(item) except KeyError as key_error: raise AttributeError(key_error.args[0]) from key_error
(self, item)
57,297
estnltk_core.layer.enveloping_span
__getitem__
null
def __getitem__(self, idx): if isinstance(idx, int): return self.spans[idx] return super().__getitem__(idx)
(self, idx)
57,298
estnltk_core.layer.enveloping_span
__init__
null
def __init__(self, base_span: BaseSpan, layer): self._spans = None super().__init__(base_span, layer)
(self, base_span: estnltk_core.layer.base_span.BaseSpan, layer)
57,299
estnltk_core.layer.enveloping_span
__iter__
null
def __iter__(self): yield from self.spans
(self)
57,300
estnltk_core.layer.enveloping_span
__len__
null
def __len__(self) -> int: return len(self._base_span)
(self) -> int
57,301
estnltk_core.layer.span
__lt__
null
def __lt__(self, other: Any) -> bool: return self.base_span < other.base_span
(self, other: Any) -> bool
57,302
estnltk_core.layer.span
__repr__
null
from copy import deepcopy from reprlib import recursive_repr from typing import Any, Sequence, Union, Dict from estnltk_core.common import _create_attr_val_repr from estnltk_core.layer.base_span import BaseSpan, ElementaryBaseSpan from estnltk_core.layer.annotation import Annotation from estnltk_core.layer import AttributeList, AttributeTupleList from .to_html import html_table class Span: """Basic element of an EstNLTK layer. A span is a container for a fragment of text that is meaningful in the analyzed context. There can be several spans in one layer and each span can have many annotations which contain the information about the span. However, if the layer is not ambiguous, a span can have only one annotation. When creating a span, it must be given two arguments: BaseSpan which defines the mandatory attributes for a span (the exact attributes depend which kind of BaseSpan is given but minimally these are start and end of the span) and the layer that the span is attached to. Each annotation can have only one span. Span can exist without annotations. It is the responsibility of a programmer to remove such spans. """ __slots__ = ['_base_span', '_layer', '_annotations', '_parent'] def __init__(self, base_span: BaseSpan, layer): assert isinstance(base_span, BaseSpan), base_span self._base_span = base_span self._layer = layer # type: Layer self._annotations = [] self._parent = None # type: Span def __deepcopy__(self, memo=None): """ Makes a deep copy from the span. Loosely based on: https://github.com/estnltk/estnltk/blob/5bacff50072f9415814aee4f369c28db0e8d7789/estnltk/layer/span.py#L60 """ memo = memo or {} # Create new valid instance # _base_span: Immutable result = self.__class__(base_span=self.base_span, \ layer=None) # Add self to memo memo[id(self)] = result # _annotations: List[Mutable] for annotation in self._annotations: deepcopy_annotation = deepcopy(annotation, memo) deepcopy_annotation.span = result result._annotations.append( deepcopy_annotation ) # _parent: Mutable result._parent = deepcopy(self._parent, memo) # _layer: Mutable result._layer = deepcopy(self._layer, memo) return result def add_annotation(self, annotation: Union[Dict[str, Any], Annotation]={}, **annotation_kwargs) -> Annotation: """Adds new annotation (from `annotation` / `annotation_kwargs`) to this span. `annotation` can be either an Annotation object initiated with this span. For example:: span.add_annotation(Annotation(span, {'attr1': ..., 'attr2': ...})) Or it can be a dictionary of attributes and values:: span.add_annotation( {'attr1': ..., 'attr2': ...} ) Missing attributes will be filled in with span layer's default_values (None values, if defaults have not been explicitly set). Redundant attributes (attributes not in `span.layer.attributes`) will be discarded. Optionally, you can leave `annotation` unspecified and pass keyword arguments to the method via `annotation_kwargs`, for example:: span.add_annotation( attr1=..., attr2=... ) Note that keyword arguments can only be valid Python keywords (excluding the keyword 'annotation'), and using `annotation` dictionary enables to bypass these restrictions. Note that you cannot pass Annotation object and keyword arguments simultaneously, this will result in TypeError. However, you can pass annotation dictionary and keyword arguments simultaneously. In that case, keyword arguments override annotation dictionary in case of an overlap in attributes. Overall, the priority order in setting value of an attribute is: `annotation_kwargs` > `annotation(dict)` > `default attributes`. The method returns added Annotation object. Note: you can add two or more annotations to this span only if the layer is ambiguous. """ if isinstance(annotation, Annotation): # Annotation object if annotation.span is not self: raise ValueError('the annotation has a different span {}'.format(annotation.span)) if set(annotation) != set(self.layer.attributes): raise ValueError('the annotation has unexpected or missing attributes {}!={}'.format( set(annotation), set(self.layer.attributes))) if len(annotation_kwargs.items()) > 0: # If Annotation object is already provided, cannot add additional keywords raise TypeError(('cannot add keyword arguments {!r} to an existing Annotation object.'+\ 'please pass keywords as a dict instead of Annotation object.').format(annotation_kwargs)) elif isinstance(annotation, dict): # annotation dict annotation_dict = {**self.layer.default_values, \ **{k: v for k, v in annotation.items() if k in self.layer.attributes}, \ **{k: v for k, v in annotation_kwargs.items() if k in self.layer.attributes}} annotation = Annotation(self, annotation_dict) else: raise TypeError('expected Annotation object or dict, but got {}'.format(type(annotation))) if annotation not in self._annotations: if self.layer.ambiguous or len(self._annotations) == 0: self._annotations.append(annotation) return annotation raise ValueError('The layer is not ambiguous and this span already has a different annotation.') def del_annotation(self, idx): """Deletes annotation by index `idx`. """ del self._annotations[idx] def clear_annotations(self): """Removes all annotations from this span. Warning: Span without any annotations is dysfunctional. It is the responsibility of a programmer to either add new annotations to span after clearing it, or to remove the span from the layer altogether. """ self._annotations.clear() @property def annotations(self): return self._annotations def __getitem__(self, item): if isinstance(item, str): if self._layer.ambiguous: return AttributeList(self, item, index_type='annotations') return self._annotations[0][item] if isinstance(item, tuple): if self._layer.ambiguous: return AttributeTupleList(self, item, index_type='annotations') return self._annotations[0][item] raise KeyError(item) @property def parent(self): if self._parent is None: if self._layer is None or self._layer.parent is None: return self._parent text_obj = self._layer.text_object if text_obj is None or self._layer.parent not in text_obj.layers: return self._parent self._parent = self._layer.text_object[self._layer.parent].get(self.base_span) return self._parent @property def layer(self): return self._layer @property def legal_attribute_names(self) -> Sequence[str]: return self._layer.attributes @property def start(self) -> int: return self._base_span.start @property def end(self) -> int: return self._base_span.end @property def base_span(self): return self._base_span @property def base_spans(self): return [(self.start, self.end)] @property def text(self): if self.text_object is None: return text = self.text_object.text base_span = self.base_span if isinstance(base_span, ElementaryBaseSpan): return text[base_span.start:base_span.end] return [text[start:end] for start, end in base_span.flatten()] @property def enclosing_text(self): if self.text_object is None: return return self._layer.text_object.text[self.start:self.end] @property def text_object(self): if self._layer is not None: return self._layer.text_object @property def raw_text(self): return self.text_object.text def __setattr__(self, key, value): if key in {'_base_span', '_layer', '_annotations', '_parent'}: super().__setattr__(key, value) elif key in self.legal_attribute_names: for annotation in self._annotations: setattr(annotation, key, value) else: raise AttributeError(key) def resolve_attribute(self, item): """Resolves and returns values of foreign attribute `item`, or resolves and returns a foreign span from layer `item`. More specifically: 1) If `item` is a name of a foreign attribute which is listed in the mapping from attribute names to foreign layer names (`attribute_mapping_for_elementary_layers`), attempts to find foreign span with the same base span as this span from the foreign layer & returns value(s) of the attribute `item` from that foreign span. (raises KeyError if base span is missing in the foreign layer); Note: this is only available when this span belongs to estnltk's `Text` object. The step will be skipped if the span belongs to `BaseText`; 2) If `item` is a layer attached to span's the text_object, attempts to get & return span with the same base span from that layer (raises KeyError if base span is missing); """ if self.text_object is not None: if hasattr(self.text_object, 'attribute_mapping_for_elementary_layers'): # Attempt to get the foreign attribute of # the same base span of a different attached # layer, based on the mapping of attributes-layers # (only available if we have estnltk.text.Text object) attribute_mapping = self.text_object.attribute_mapping_for_elementary_layers if item in attribute_mapping: return self._layer.text_object[attribute_mapping[item]].get(self.base_span)[item] if item in self.text_object.layers: # Attempt to get the same base span from # a different attached layer # (e.g parent or child span) return self.text_object[item].get(self.base_span) else: raise AttributeError(("Unable to resolve foreign attribute {!r}: "+\ "the layer is not attached to Text object.").format(item) ) raise AttributeError("Unable to resolve foreign attribute {!r}.".format(item)) def __getattr__(self, item): if item in self.__getattribute__('_layer').attributes: return self[item] try: return self.resolve_attribute(item) except KeyError as key_error: raise AttributeError(key_error.args[0]) from key_error def __lt__(self, other: Any) -> bool: return self.base_span < other.base_span def __eq__(self, other: Any) -> bool: return isinstance(other, Span) \ and self.base_span == other.base_span \ and len(self.annotations) == len(other.annotations) \ and all(s in other.annotations for s in self.annotations) @recursive_repr() def __repr__(self): try: text = self.text except: text = None try: attribute_names = self._layer.attributes annotation_strings = [] for annotation in self._annotations: attr_val_repr = _create_attr_val_repr( [(attr, annotation[attr]) for attr in attribute_names] ) annotation_strings.append( attr_val_repr ) annotations = '[{}]'.format(', '.join(annotation_strings)) except: annotations = None return '{class_name}({text!r}, {annotations})'.format(class_name=self.__class__.__name__, text=text, annotations=annotations) def _to_html(self, margin=0) -> str: return '<b>{}</b>\n{}'.format( self.__class__.__name__, html_table(spans=[self], attributes=self._layer.attributes, margin=margin, index=False)) def _repr_html_(self): return self._to_html()
(self)
57,303
estnltk_core.layer.enveloping_span
__setattr__
null
def __setattr__(self, key, value): if key == '_spans': object.__setattr__(self, key, value) else: super().__setattr__(key, value)
(self, key, value)
57,304
estnltk_core.layer.span
_repr_html_
null
def _repr_html_(self): return self._to_html()
(self)
57,305
estnltk_core.layer.span
_to_html
null
def _to_html(self, margin=0) -> str: return '<b>{}</b>\n{}'.format( self.__class__.__name__, html_table(spans=[self], attributes=self._layer.attributes, margin=margin, index=False))
(self, margin=0) -> str
57,306
estnltk_core.layer.span
add_annotation
Adds new annotation (from `annotation` / `annotation_kwargs`) to this span. `annotation` can be either an Annotation object initiated with this span. For example:: span.add_annotation(Annotation(span, {'attr1': ..., 'attr2': ...})) Or it can be a dictionary of attributes and values:: span.add_annotation( {'attr1': ..., 'attr2': ...} ) Missing attributes will be filled in with span layer's default_values (None values, if defaults have not been explicitly set). Redundant attributes (attributes not in `span.layer.attributes`) will be discarded. Optionally, you can leave `annotation` unspecified and pass keyword arguments to the method via `annotation_kwargs`, for example:: span.add_annotation( attr1=..., attr2=... ) Note that keyword arguments can only be valid Python keywords (excluding the keyword 'annotation'), and using `annotation` dictionary enables to bypass these restrictions. Note that you cannot pass Annotation object and keyword arguments simultaneously, this will result in TypeError. However, you can pass annotation dictionary and keyword arguments simultaneously. In that case, keyword arguments override annotation dictionary in case of an overlap in attributes. Overall, the priority order in setting value of an attribute is: `annotation_kwargs` > `annotation(dict)` > `default attributes`. The method returns added Annotation object. Note: you can add two or more annotations to this span only if the layer is ambiguous.
def add_annotation(self, annotation: Union[Dict[str, Any], Annotation]={}, **annotation_kwargs) -> Annotation: """Adds new annotation (from `annotation` / `annotation_kwargs`) to this span. `annotation` can be either an Annotation object initiated with this span. For example:: span.add_annotation(Annotation(span, {'attr1': ..., 'attr2': ...})) Or it can be a dictionary of attributes and values:: span.add_annotation( {'attr1': ..., 'attr2': ...} ) Missing attributes will be filled in with span layer's default_values (None values, if defaults have not been explicitly set). Redundant attributes (attributes not in `span.layer.attributes`) will be discarded. Optionally, you can leave `annotation` unspecified and pass keyword arguments to the method via `annotation_kwargs`, for example:: span.add_annotation( attr1=..., attr2=... ) Note that keyword arguments can only be valid Python keywords (excluding the keyword 'annotation'), and using `annotation` dictionary enables to bypass these restrictions. Note that you cannot pass Annotation object and keyword arguments simultaneously, this will result in TypeError. However, you can pass annotation dictionary and keyword arguments simultaneously. In that case, keyword arguments override annotation dictionary in case of an overlap in attributes. Overall, the priority order in setting value of an attribute is: `annotation_kwargs` > `annotation(dict)` > `default attributes`. The method returns added Annotation object. Note: you can add two or more annotations to this span only if the layer is ambiguous. """ if isinstance(annotation, Annotation): # Annotation object if annotation.span is not self: raise ValueError('the annotation has a different span {}'.format(annotation.span)) if set(annotation) != set(self.layer.attributes): raise ValueError('the annotation has unexpected or missing attributes {}!={}'.format( set(annotation), set(self.layer.attributes))) if len(annotation_kwargs.items()) > 0: # If Annotation object is already provided, cannot add additional keywords raise TypeError(('cannot add keyword arguments {!r} to an existing Annotation object.'+\ 'please pass keywords as a dict instead of Annotation object.').format(annotation_kwargs)) elif isinstance(annotation, dict): # annotation dict annotation_dict = {**self.layer.default_values, \ **{k: v for k, v in annotation.items() if k in self.layer.attributes}, \ **{k: v for k, v in annotation_kwargs.items() if k in self.layer.attributes}} annotation = Annotation(self, annotation_dict) else: raise TypeError('expected Annotation object or dict, but got {}'.format(type(annotation))) if annotation not in self._annotations: if self.layer.ambiguous or len(self._annotations) == 0: self._annotations.append(annotation) return annotation raise ValueError('The layer is not ambiguous and this span already has a different annotation.')
(self, annotation: Union[Dict[str, Any], estnltk_core.layer.annotation.Annotation] = {}, **annotation_kwargs) -> estnltk_core.layer.annotation.Annotation
57,307
estnltk_core.layer.span
clear_annotations
Removes all annotations from this span. Warning: Span without any annotations is dysfunctional. It is the responsibility of a programmer to either add new annotations to span after clearing it, or to remove the span from the layer altogether.
def clear_annotations(self): """Removes all annotations from this span. Warning: Span without any annotations is dysfunctional. It is the responsibility of a programmer to either add new annotations to span after clearing it, or to remove the span from the layer altogether. """ self._annotations.clear()
(self)
57,308
estnltk_core.layer.span
del_annotation
Deletes annotation by index `idx`.
def del_annotation(self, idx): """Deletes annotation by index `idx`. """ del self._annotations[idx]
(self, idx)
57,309
estnltk_core.layer.enveloping_span
resolve_attribute
Resolves and returns values of foreign attribute `item`, or resolves and returns a foreign span from layer `item`. More specifically: 1) If `item` is a name of a foreign attribute which is listed in the mapping from attribute names to foreign layer names (`attribute_mapping_for_enveloping_layers`), attempts to find foreign span with the same base span as this span from the foreign layer & returns value(s) of the attribute `item` from that foreign span. (raises KeyError if base span is missing in the foreign layer); Note: this is only available when this span belongs to estnltk's `Text` object. The step will be skipped if the span belongs to `BaseText`; 2) If `item` is a layer attached to span's the text_object, and the layer has `span_level` equal to or lower than this enveloping span (meaning: spans of this layer could envelop around spans of the target layer), then attempts to get & return span or spans from the target layer that match the base span of this span (raises KeyError if base span is missing);
def resolve_attribute(self, item): """Resolves and returns values of foreign attribute `item`, or resolves and returns a foreign span from layer `item`. More specifically: 1) If `item` is a name of a foreign attribute which is listed in the mapping from attribute names to foreign layer names (`attribute_mapping_for_enveloping_layers`), attempts to find foreign span with the same base span as this span from the foreign layer & returns value(s) of the attribute `item` from that foreign span. (raises KeyError if base span is missing in the foreign layer); Note: this is only available when this span belongs to estnltk's `Text` object. The step will be skipped if the span belongs to `BaseText`; 2) If `item` is a layer attached to span's the text_object, and the layer has `span_level` equal to or lower than this enveloping span (meaning: spans of this layer could envelop around spans of the target layer), then attempts to get & return span or spans from the target layer that match the base span of this span (raises KeyError if base span is missing); """ if self.text_object is not None: if hasattr(self.text_object, 'attribute_mapping_for_enveloping_layers'): # Attempt to get the foreign attribute of # the same base span of a different attached # layer, based on the mapping of attributes-layers # (only available if we have estnltk.text.Text object) attribute_mapping = self.text_object.attribute_mapping_for_enveloping_layers if item in attribute_mapping: return self._layer.text_object[attribute_mapping[item]].get(self.base_span)[item] if item in self.text_object.layers: # Attempt to get spans with same base # span(s) from a different attached # layer that has appropriate span_level target_layer = self.text_object[item] if len(target_layer) == 0: return if target_layer.span_level >= self._base_span.level: raise AttributeError('target layer span_level {} should be lower than {}'.format( target_layer.span_level, self._base_span.level)) return target_layer.get(self.base_span) else: raise AttributeError(("Unable to resolve foreign attribute {!r}: "+\ "the layer is not attached to Text object.").format(item) ) raise AttributeError("Unable to resolve foreign attribute {!r}.".format(item))
(self, item)
57,310
estnltk_core.layer.layer
Layer
Layer extends BaseLayer with attribute resolving functionality and adds layer operations. Available layer operations: * Find descendant / ancestor layers of the given layer; * Count attribute values; * group spans or annotations of the layer, either by attributes or by another layer; * get rolling window over spans (generate n-grams); * visualise markup in text (only available with the full estnltk);
class Layer(BaseLayer): """Layer extends BaseLayer with attribute resolving functionality and adds layer operations. Available layer operations: * Find descendant / ancestor layers of the given layer; * Count attribute values; * group spans or annotations of the layer, either by attributes or by another layer; * get rolling window over spans (generate n-grams); * visualise markup in text (only available with the full estnltk); """ def __setattr__(self, key, value): if key == 'attributes': # check attributes: add userwarnings in case of # problematic attribute names attributes = value if isinstance(attributes, (list, tuple)) and all([isinstance(attr,str) for attr in attributes]): # Warn if user wants to use non-identifiers as argument names nonidentifiers = [attr for attr in attributes if not attr.isidentifier()] if nonidentifiers: warnings.warn(('Attribute names {!r} are not valid Python identifiers. '+\ 'This can hinder setting and accessing attribute values.'+\ '').format(nonidentifiers)) # Warn if user wants to use 'text', 'start', 'end' as attribute names overlapping_props = [attr for attr in attributes if attr in ['text', 'start', 'end']] if overlapping_props: warnings.warn(('Attribute names {!r} overlap with Span/Annotation property names. '+\ 'This can hinder setting and accessing attribute values.'+\ '').format(overlapping_props)) super().__setattr__(key, value) def ancestor_layers(self) -> List[str]: """Finds all layers that given layer depends on (ancestor layers). Returns names of ancestor layers in alphabetical order. """ if self.text_object is None: raise Exception('(!) Cannot find ancestor layers: the layer is detached from Text object.') ancestors = find_layer_dependencies(self.text_object, self.name, reverse=False) return sorted(ancestors) def descendant_layers(self) -> List[str]: """Finds all layers that are depending on the given layer (descendant layers). Returns names of descendant layers in alphabetical order. """ if self.text_object is None: raise Exception('(!) Cannot find descendant layers: the layer is detached from Text object.') descendants = find_layer_dependencies(self.text_object, self.name, reverse=True) return sorted(descendants) def count_values(self, attribute: str) -> collections.Counter: """Counts attribute values and returns frequency table (collections.Counter). Note: you can also use 'text' as the attribute name to count corresponding surface text strings. """ if self.ambiguous: return collections.Counter(annotation[attribute] if attribute != 'text' else annotation.text \ for span in self.spans for annotation in span.annotations) return collections.Counter( span.annotations[0][attribute] if attribute != 'text' else span.text \ for span in self.spans) def groupby(self, by: Union[str, Sequence[str], 'Layer'], return_type: str = 'spans') -> GroupBy: """Groups layer by attribute values of annotations or by an enveloping layer. Parameters ----------- by: Union[str, Sequence[str], 'Layer'] specifies basis for grouping, which can be either matching attribute values or containment in an enveloping span. More specifically, the parameter `by` can be:: 1) name of an attribute of this layer, 2) list of attribute names of this layer, 3) name of a Layer enveloping around this layer, or 4) Layer object which is a layer enveloping around this layer. Note: you can also use 'text' as an attribute name; in that case, spans / annotations are grouped by their surface text strings. return_type: str (default: 'spans') specifies layer's units which will be grouped. Possible values: "spans" or "annotations". Returns -------- estnltk_core.layer_operations.GroupBy estnltk_core.layer_operations.GroupBy object. """ if isinstance(by, str): if by in self.attributes: # Group by a single attribute of this Layer return GroupBy(layer=self, by=[ by ], return_type=return_type) elif self.text_object is not None and by in self.text_object.layers: # Group by a Layer (using given layer name) return GroupBy(layer=self, by = self.text_object[by], return_type=return_type) raise ValueError(by) elif isinstance(by, Sequence) and all(isinstance(b, str) for b in by): # Group by multiple attributes of this Layer return GroupBy(layer=self, by=by, return_type=return_type) elif isinstance(by, Layer): # Group by a Layer return GroupBy(layer=self, by=by, return_type=return_type) raise ValueError( ('Unexpected grouping parameter by={!r}. The parameter '+\ 'should be either an enveloping Layer (layer name or object) '+\ 'or attribute(s) of this layer (a single attribute name '+\ 'or a list of names).').format(by) ) def rolling(self, window: int, min_periods: int = None, inside: str = None) -> Rolling: """Creates an iterable object yielding span sequences from a window rolling over the layer. Parameters ----------- window length of the window (in spans); min_periods the minimal length of the window for borderline cases; allows to shrink the window to meet this minimal length. If not specified, then `min_periods == window`, which means that the shrinking is not allowed, and contexts smaller than the `window` will be discarded. Note: `0 < min_periods <= window` must hold; inside an enveloping layer to be used for constraining the rolling window. The rolling window is applied on each span of the enveloping layer separately, thus ensuring that the window does not exceed boundaries of enveloping spans. For instance, if you create a rolling window over 'words', you can specify inside='sentences', ensuring that the generated word N-grams do not exceed sentence boundaries; Returns -------- estnltk_core.layer_operations.Rolling estnltk_core.layer_operations.Rolling object. """ return Rolling(self, window=window, min_periods=min_periods, inside=inside) def resolve_attribute(self, item) -> Union[AmbiguousAttributeList, AttributeList]: """Resolves and returns values of foreign attribute `item`. Values of the attribute will be sought from a foreign layer, which must either: a) share the same base spans with this layer (be a parent or a child), or b) share the same base spans with smaller span level, which means that this layer should envelop around the foreign layer. Note: this method relies on a mapping from attribute names to foreign layer names (`attribute_mapping_for_elementary_layers`), which is defined estnltk's `Text` object. If this layer is attached to estnltk-core's `BaseText` instead, then the method always raises AttributeError. """ if len(self) == 0: raise AttributeError(item, 'layer is empty') attribute_mapping = {} if self.text_object is not None: if hasattr(self.text_object, 'attribute_mapping_for_elementary_layers'): # Attribute mapping for elementary layers is only # defined in Text object, it is missing in BaseText if self.span_level == 0: attribute_mapping = self.text_object.attribute_mapping_for_elementary_layers else: attribute_mapping = self.text_object.attribute_mapping_for_enveloping_layers else: raise AttributeError(item, "Foreign attribute resolving is only available "+\ "if the layer is attached to estnltk.text.Text object.") else: raise AttributeError(item, \ "Unable to resolve foreign attribute: the layer is not attached to Text object." ) if item not in attribute_mapping: raise AttributeError(item, \ "Attribute not defined in attribute_mapping_for_elementary_layers.") target_layer = self.text_object[attribute_mapping[item]] if len(target_layer) == 0: return AttributeList([], item) result = [target_layer.get(span.base_span) for span in self] target_level = target_layer.span_level self_level = self.span_level if target_level > self_level: raise AttributeError(item, \ ("Unable to resolve foreign attribute: target layer {!r} has higher "+\ "span level than this layer.").format( target_layer.name ) ) if target_level == self_level and target_layer.ambiguous: assert all([isinstance(s, Span) for s in result]) return AmbiguousAttributeList(result, item) assert all([isinstance(l, BaseLayer) for l in result]) return AttributeList(result, item, index_type='layers') def __getattr__(self, item): if item in self.__getattribute__('attributes'): return self.__getitem__(item) return self.resolve_attribute(item) def display(self, **kwargs): if check_if_estnltk_is_available(): from estnltk.visualisation import DisplaySpans display_spans = DisplaySpans(**kwargs) display_spans(self) else: raise NotImplementedError("Layer display is not available in estnltk-core. Please use the full EstNLTK package for that.")
(name: str, attributes: Sequence[str] = (), secondary_attributes: Sequence[str] = (), text_object: Union[ForwardRef('BaseText'), ForwardRef('Text')] = None, parent: str = None, enveloping: str = None, ambiguous: bool = False, default_values: dict = None, serialisation_module=None) -> None
57,311
estnltk_core.layer.base_layer
__copy__
Creates a new Layer object with the same content. TODO: this functionality will be deprecated in the future. Normally, you won't need to copy the layer. If you want to use copying for safely deleting spans, copy layer.spans instead: for span in copy(layer.spans): layer.remove_span(span)
def __copy__(self): """ Creates a new Layer object with the same content. TODO: this functionality will be deprecated in the future. Normally, you won't need to copy the layer. If you want to use copying for safely deleting spans, copy layer.spans instead: for span in copy(layer.spans): layer.remove_span(span) """ result = self.__class__( name=self.name, attributes=self.attributes, secondary_attributes=self.secondary_attributes, text_object=self.text_object, parent=self.parent, enveloping=self.enveloping, ambiguous=self.ambiguous, default_values=self.default_values, serialisation_module=self.serialisation_module) result.meta = copy(self.meta) result._span_list = copy(self._span_list) # TODO: fix the span level ? return result
(self)
57,312
estnltk_core.layer.base_layer
__deepcopy__
Makes a deep copy from the layer. Essential for deep copying of Text objects. Layer's inner components -- spans and annotations -- are also deep-copied, along with the Text object of the layer.
def __deepcopy__(self, memo=None): """ Makes a deep copy from the layer. Essential for deep copying of Text objects. Layer's inner components -- spans and annotations -- are also deep-copied, along with the Text object of the layer. """ memo = memo or {} result = self.__class__( name=self.name, attributes=deepcopy(self.attributes, memo), secondary_attributes=deepcopy(self.secondary_attributes, memo), text_object=None, parent=self.parent, enveloping=self.enveloping, ambiguous=self.ambiguous, default_values=deepcopy(self.default_values, memo), serialisation_module=self.serialisation_module ) memo[id(self)] = result result.meta = deepcopy(self.meta, memo) for span in self: deepcopy_span = deepcopy( span, memo ) deepcopy_span._layer = result result._span_list.add_span( deepcopy_span ) result.text_object = deepcopy( self.text_object, memo ) return result
(self, memo=None)
57,313
estnltk_core.layer.base_layer
__delitem__
null
def __delitem__(self, key): self._span_list.remove_span(self[key])
(self, key)
57,314
estnltk_core.layer.base_layer
__eq__
null
def __eq__(self, other): return self.diff(other) is None
(self, other)