def __init__(self, arg, shapein=None, shapeout=None, dtype=None, **keywords): if sp.issparse(arg): self.__class__ = pyoperators.linear.SparseOperator self.__init__(arg, dtype=None, **keywords) return if not isinstance( arg, (FSCMatrix, FSRMatrix, FSCBlockMatrix, FSRBlockMatrix, FSCRotation2dMatrix, FSRRotation2dMatrix, FSCRotation3dMatrix, FSRRotation3dMatrix)): raise TypeError('The input sparse matrix type is not recognised.') if isinstance(arg, (FSCMatrix, FSRMatrix)): if shapein is None: bshapein = keywords.pop('broadcastable_shapein', (arg.shape[1], )) else: shapein = tointtuple(shapein) test = np.cumprod(shapein) == arg.shape[1] try: bshapein = shapein[:ilast(test, lambda x: x) + 1] except ValueError: bshapein = (arg.shape[1], ) self.broadcastable_shapein = bshapein if shapeout is None: bshapeout = keywords.pop('broadcastable_shapeout', (arg.shape[0], )) else: shapeout = tointtuple(shapeout) test = np.cumprod(shapeout) == arg.shape[0] try: bshapeout = shapeout[:ilast(test, lambda x: x) + 1] except ValueError: bshapeout = (arg.shape[0], ) self.broadcastable_shapeout = bshapeout else: bs = arg.block_shape if shapein is None: if bs[1] == 1: shapein = arg.shape[1] else: shapein = arg.shape[1] // bs[1], bs[1] if shapeout is None: if bs[0] == 1: shapeout = arg.shape[0] else: shapeout = arg.shape[0] // bs[0], bs[0] pyoperators.linear.SparseBase.__init__(self, arg, dtype=dtype, shapein=shapein, shapeout=shapeout, **keywords) self.set_rule('T', self._rule_transpose) self.set_rule(('T', '.'), self._rule_pTp, CompositionOperator)
def __init__(self, arg, shapein=None, shapeout=None, dtype=None, **keywords): if sp.issparse(arg): self.__class__ = pyoperators.linear.SparseOperator self.__init__(arg, dtype=None, **keywords) return if not isinstance(arg, (FSCMatrix, FSRMatrix, FSCBlockMatrix, FSRBlockMatrix, FSCRotation2dMatrix, FSRRotation2dMatrix, FSCRotation3dMatrix, FSRRotation3dMatrix)): raise TypeError('The input sparse matrix type is not recognised.') if isinstance(arg, (FSCMatrix, FSRMatrix)): if shapein is None: bshapein = keywords.pop('broadcastable_shapein', (arg.shape[1],)) else: shapein = tointtuple(shapein) test = np.cumprod(shapein) == arg.shape[1] try: bshapein = shapein[:ilast(test, lambda x: x) + 1] except ValueError: bshapein = (arg.shape[1],) self.broadcastable_shapein = bshapein if shapeout is None: bshapeout = keywords.pop('broadcastable_shapeout', (arg.shape[0],)) else: shapeout = tointtuple(shapeout) test = np.cumprod(shapeout) == arg.shape[0] try: bshapeout = shapeout[:ilast(test, lambda x: x) + 1] except ValueError: bshapeout = (arg.shape[0],) self.broadcastable_shapeout = bshapeout else: bs = arg.block_shape if shapein is None: if bs[1] == 1: shapein = arg.shape[1] else: shapein = arg.shape[1] // bs[1], bs[1] if shapeout is None: if bs[0] == 1: shapeout = arg.shape[0] else: shapeout = arg.shape[0] // bs[0], bs[0] pyoperators.linear.SparseBase.__init__( self, arg, dtype=dtype, shapein=shapein, shapeout=shapeout, **keywords) self.set_rule('T', self._rule_transpose) self.set_rule(('T', '.'), self._rule_pTp, CompositionOperator)
def __init__(self, *args, **keywords): """ ptg = SamplingSpherical(n) ptg = SamplingSpherical(precession=, nutation=, intrinsic_rotation=) ptg = SamplingSpherical(precession, nutation, intrinsic_rotation) Parameters ---------- n : integer The number of samples. names : tuple of 3 strings The names of the 3 rotation angles. They are stored as Layout special attributes. By default, these are the proper Euler angles: precession, nutation and intrinsic rotation. degrees : boolean, optional If true, the input spherical coordinates are assumed to be in degrees. """ names = keywords.pop('names', ('precession', 'nutation', 'intrinsic_rotation')) degrees = keywords.pop('degrees', False) if len(names) != 3: raise ValueError('The 3 pointing angles are not named.') if len(args) <= 1: if names[0] in keywords and names[1] not in keywords or \ names[1] in keywords and names[0] not in keywords: raise ValueError('The pointing is not specified.') if names[0] not in keywords: keywords[names[0]] = None if names[1] not in keywords: keywords[names[1]] = None if names[2] not in keywords: keywords[names[2]] = 0 elif len(args) <= 3: keywords[names[0]] = args[0] keywords[names[1]] = args[1] keywords[names[2]] = args[2] if len(args) == 3 else 0 else: raise ValueError('Invalid number of arguments.') if len(args) == 1: if not isscalarlike(args[0]): raise ValueError('Invalid number of arguments.') shape = tointtuple(args[0]) else: shape = np.broadcast(*([keywords[_] for _ in names] + [keywords.get('time', None)])).shape if len(shape) == 0: shape = (1, ) elif len(shape) != 1: raise ValueError('Invalid dimension for the pointing.') Sampling.__init__(self, shape, cartesian=None, spherical=None, velocity=None, **keywords) self.names = names self.degrees = bool(degrees)
def __init__(self, flib_id, shape, block_shape, nrowmax, sparse_axis, dtype, dtype_index, data, verbose): if data is None: if block_shape is None: raise TypeError('The block shape is not specified.') block_shape = tointtuple(block_shape) if len(block_shape) != 2: raise ValueError( "The number of dimensions of the blocks is not 2.") if block_shape == (1, 1): raise ValueError( 'For block size of (1, 1), use the {}Matrix format.'.format( flib_id[:3].upper())) if any(_ not in (1, 2, 3) for _ in block_shape): raise NotImplementedError( "The sparse format {}BlockMatrix is not implemented for block" "s of shape '{}.'".format(flib_id[:3].upper(), block_shape)) _FSMatrix.__init__(self, flib_id, shape, block_shape, nrowmax, sparse_axis, dtype=dtype, dtype_index=dtype_index, data=data, verbose=verbose)
def distance(shape, center=None, scale=1, dtype=float, out=None): """ Returns an array whose values are the distances to a given center. Parameters ---------- shape : tuple of integer dimensions of the output array. For a 2d array, the first integer is for the Y-axis and the second one for the X-axis. center : array-like, optional The coordinates (x0, y0, ...) of the point from which the distance is calculated, assuming a zero-based coordinate indexing. Default value is the array center. scale : float or array-like, optional Inter-pixel distance (dx, dy, ...). If scale is a Quantity, its unit will be carried over to the returned distance array dtype : np.dtype, optional The output data type. Example ------- nx, ny = 3, 3 print(distance((ny,nx))) [[ 1.41421356 1. 1.41421356] [ 1. 0. 1. ] [ 1.41421356 1. 1.41421356]] """ shape = tointtuple(shape) dtype = np.dtype(dtype) unit = getattr(scale, '_unit', None) if out is None: out = np.empty(shape, dtype) ndim = out.ndim dtype = float_intrinsic_dtype(out.dtype) if ndim in (1, 2) and dtype != out.dtype: out_ = np.empty(shape, dtype) else: out_ = out if center is None: center = (np.array(shape[::-1]) - 1) / 2 else: center = np.ascontiguousarray(center, dtype) if isscalarlike(scale): scale = np.resize(scale, out.ndim) scale = np.ascontiguousarray(scale, dtype) if ndim in (1, 2): fname = 'distance_{0}d_r{1}'.format(ndim, dtype.itemsize) func = getattr(flib.datautils, fname) if ndim == 1: func(out_, center[0], scale[0]) else: func(out_.T, center, scale) if not isalias(out, out_): out[...] = out_ else: _distance_slow(shape, center, scale, dtype, out) return Map(out, copy=False, unit=unit)
def __init__(self, *args, **keywords): """ ptg = SamplingSpherical(n) ptg = SamplingSpherical(precession=, nutation=, intrinsic_rotation=) ptg = SamplingSpherical(precession, nutation, intrinsic_rotation) Parameters ---------- n : integer The number of samples. names : tuple of 3 strings The names of the 3 rotation angles. They are stored as Layout special attributes. By default, these are the proper Euler angles: precession, nutation and intrinsic rotation. degrees : boolean, optional If true, the input spherical coordinates are assumed to be in degrees. """ names = keywords.pop('names', ('precession', 'nutation', 'intrinsic_rotation')) degrees = keywords.pop('degrees', False) if len(names) != 3: raise ValueError('The 3 pointing angles are not named.') if len(args) <= 1: if names[0] in keywords and names[1] not in keywords or \ names[1] in keywords and names[0] not in keywords: raise ValueError('The pointing is not specified.') if names[0] not in keywords: keywords[names[0]] = None if names[1] not in keywords: keywords[names[1]] = None if names[2] not in keywords: keywords[names[2]] = 0 elif len(args) <= 3: keywords[names[0]] = args[0] keywords[names[1]] = args[1] keywords[names[2]] = args[2] if len(args) == 3 else 0 else: raise ValueError('Invalid number of arguments.') if len(args) == 1: if not isscalarlike(args[0]): raise ValueError('Invalid number of arguments.') shape = tointtuple(args[0]) else: shape = np.broadcast(*([keywords[_] for _ in names] + [keywords.get('time', None)])).shape if len(shape) == 0: shape = (1,) elif len(shape) != 1: raise ValueError('Invalid dimension for the pointing.') Sampling.__init__(self, shape, cartesian=None, spherical=None, velocity=None, **keywords) self.names = names self.degrees = bool(degrees)
def gaussian(shape, sigma=None, fwhm=None, center=None, dtype=float): """ Returns an array whose values are the distances to a given center. Parameters ---------- shape : tuple of integer dimensions of the output array. For a 2d array, the first integer is for the Y-axis and the second one for the X-axis. fwhm : array-like The Full Width Half Maximum of the gaussian (fwhm_x, fwhm_y, ...). sigma : array-like The sigma parameter (sigma_x, sigma_y, ...) in pixel units. center : array-like, optional Center (x0, y0, ...) of the gaussian, in pixel units. By convention, the coordinates of the center of the pixel [0, 0] are (0, 0). Default is the image center. dtype : np.dtype, optional The output data type. """ if sigma is None and fwhm is None: raise ValueError('The shape of the gaussian is not specified.') shape = tointtuple(shape) n = len(shape) if sigma is None: sigma = fwhm / np.sqrt(8 * np.log(2)) if center is None: center = (np.array(shape[::-1], dtype) - 1) / 2 else: center = np.ascontiguousarray(center, dtype) if isscalarlike(sigma): sigma = np.resize(sigma, n).astype(dtype) else: sigma = np.ascontiguousarray(sigma, dtype) dtype = np.dtype(dtype) if n == 2 and dtype in (np.float32, np.float64): out = np.empty(shape, dtype) func = getattr(flib.datautils, 'gaussian_2d_r{0}'.format(dtype.itemsize)) func(out.T, center, sigma) else: scale = 1 / (np.sqrt(2) * sigma[::-1]) axes = np.ogrid[[ slice(-o * sc, (sh - 1 - o) * sc, complex(sh)) for o, sh, sc in zip(center[::-1], shape, scale) ]] out = 1 / ((2 * np.pi)**(n / 2) * product(sigma)) for a in axes: out = out * np.exp(-a**2) return out
def gaussian(shape, sigma=None, fwhm=None, center=None, dtype=float): """ Returns an array whose values are the distances to a given center. Parameters ---------- shape : tuple of integer dimensions of the output array. For a 2d array, the first integer is for the Y-axis and the second one for the X-axis. fwhm : array-like The Full Width Half Maximum of the gaussian (fwhm_x, fwhm_y, ...). sigma : array-like The sigma parameter (sigma_x, sigma_y, ...) in pixel units. center : array-like, optional Center (x0, y0, ...) of the gaussian, in pixel units. By convention, the coordinates of the center of the pixel [0, 0] are (0, 0). Default is the image center. dtype : np.dtype, optional The output data type. """ if sigma is None and fwhm is None: raise ValueError('The shape of the gaussian is not specified.') shape = tointtuple(shape) n = len(shape) if sigma is None: sigma = fwhm / np.sqrt(8 * np.log(2)) if center is None: center = (np.array(shape[::-1], dtype) - 1) / 2 else: center = np.ascontiguousarray(center, dtype) if isscalarlike(sigma): sigma = np.resize(sigma, n).astype(dtype) else: sigma = np.ascontiguousarray(sigma, dtype) dtype = np.dtype(dtype) if n == 2 and dtype in (np.float32, np.float64): out = np.empty(shape, dtype) func = getattr(flib.datautils, 'gaussian_2d_r{0}'.format(dtype.itemsize)) func(out.T, center, sigma) else: scale = 1 / (np.sqrt(2) * sigma[::-1]) axes = np.ogrid[[slice(-o * sc, (sh - 1 - o) * sc, complex(sh)) for o, sh, sc in zip(center[::-1], shape, scale)]] out = 1 / ((2*np.pi)**(n / 2) * product(sigma)) for a in axes: out = out * np.exp(-a**2) return out
def __init__(self, shape, selection=None, ordering=None, ndim=None, **keywords): """ shape : tuple of int The shape of the unpacked table attributes. For 2-dimensional attributes, the shape would be (nrows, ncolumns). ndim : int, optional The number of splittable (indexable) dimensions. It is the actual number of dimensions of the layout. It can be lower than that specified by the layout shape, in which case the extra dimensions are instructed not to be split. selection : array-like of bool or int, slices, optional The slices or the integer or boolean selection that specifies the selected components (and reject those that are not physically present or those not handled by the current MPI process when the table is distributed in a parallel processing). ordering : array-like of int, optional The values in this array specify an ordering of the components. It is used to define the 1-dimensional indexing of the packed components. A negative value means that the component is removed. """ shape = tointtuple(shape) if ndim is None: ndim = len(shape) elif ndim < 1 or ndim > len(shape): raise ValueError("Invalid ndim value '{0}'.".format(ndim)) object.__setattr__(self, 'shape', shape) object.__setattr__(self, 'ndim', ndim) object.__setattr__(self, 'comm', MPI.COMM_SELF) self._dtype_index = np.int64 self._index = self._get_index(selection, ordering) for k, v in keywords.items(): self._special_attributes += (k, ) if v is None and isclassattr(k, type(self)): continue if not isinstance(v, collections.Callable): v = self.pack(v, copy=True) setattr(self, k, v)
def __init__(self, flib_id, shape, block_shape, nrowmax, sparse_axis, dtype, dtype_index, data, verbose): if data is None: if block_shape is None: raise TypeError('The block shape is not specified.') block_shape = tointtuple(block_shape) if len(block_shape) != 2: raise ValueError( "The number of dimensions of the blocks is not 2.") if block_shape == (1, 1): raise ValueError( 'For block size of (1, 1), use the {}Matrix format.' .format(flib_id[:3].upper())) if any(_ not in (1, 2, 3) for _ in block_shape): raise NotImplementedError( "The sparse format {}BlockMatrix is not implemented for block" "s of shape '{}.'".format(flib_id[:3].upper(), block_shape)) _FSMatrix.__init__(self, flib_id, shape, block_shape, nrowmax, sparse_axis, dtype=dtype, dtype_index=dtype_index, data=data, verbose=verbose)
def __init__(self, shape, selection=None, ordering=None, ndim=None, **keywords): """ shape : tuple of int The shape of the unpacked table attributes. For 2-dimensional attributes, the shape would be (nrows, ncolumns). ndim : int, optional The number of splittable (indexable) dimensions. It is the actual number of dimensions of the layout. It can be lower than that specified by the layout shape, in which case the extra dimensions are instructed not to be split. selection : array-like of bool or int, slices, optional The slices or the integer or boolean selection that specifies the selected components (and reject those that are not physically present or those not handled by the current MPI process when the table is distributed in a parallel processing). ordering : array-like of int, optional The values in this array specify an ordering of the components. It is used to define the 1-dimensional indexing of the packed components. A negative value means that the component is removed. """ shape = tointtuple(shape) if ndim is None: ndim = len(shape) elif ndim < 1 or ndim > len(shape): raise ValueError("Invalid ndim value '{0}'.".format(ndim)) object.__setattr__(self, 'shape', shape) object.__setattr__(self, 'ndim', ndim) object.__setattr__(self, 'comm', MPI.COMM_SELF) self._dtype_index = np.int64 self._index = self._get_index(selection, ordering) for k, v in keywords.items(): self._special_attributes += (k,) if v is None and isclassattr(k, type(self)): continue if not isinstance(v, collections.Callable): v = self.pack(v, copy=True) setattr(self, k, v)
def func(v, s, d): assert_equal(v.shape, tointtuple(s)) assert_equal(v.dtype, d) assert_aligned(v) assert_contiguous(v)