def __init__(self, flags, values, description=None): self._description = description if isscalarlike(flags): if isinstance(flags, str): flags = flags.split(',') else: flags = [flags] flags = [_.strip() for _ in flags] if isscalarlike(values): if isinstance(values, str): values = values.split(',') else: values = [values] values = [_.strip().lower() for _ in values] if len(flags) != len(values): raise ValueError('The number of policy flags is different from the' ' number of policies.') self._policy = [] for flag, value in zip(flags, values): if flag[0] == '_': raise ValueError('A policy flag should not start with an under' 'score.') choices = 'keep', 'mask', 'remove' if value not in choices: raise KeyError('Invalid policy {}={!r}. Expected values are {}' '.'.format(flag, value, strenum(choices))) setattr(self, flag, value) self._flags = flags
def func(s, v): layout = PackedTable((6, 6), key=v) assert 'key' in layout._special_attributes assert isscalarlike(layout.key) assert_eq(layout.key, v) assert_eq(layout.key.shape, ()) assert_same(layout.all.key, v, broadcasting=True) assert_same(layout.all.key.shape, layout.shape) s(layout, 'key', v) assert isscalarlike(layout.key) assert_eq(layout.key, v) assert_eq(layout.key.shape, ()) assert_same(layout.all.key, v, broadcasting=True) assert_same(layout.all.key.shape, layout.shape)
def __rmul__(self, other): if isscalarlike(other): return self * other other = np.asarray(other) if other.ndim == 1: return self._transpose() * other return NotImplemented
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 __rmul__(self, other): if isscalarlike(other): return self * other other = np.asarray(other) if other.ndim == 1: return self._transpose() * other return NotImplemented
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 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 __mul__(self, other): if isscalarlike(other): data = self.data.copy() data.value *= other return type(self)(self.shape, data=data) other = np.asarray(other) if other.ndim == 1: return self._matvec(other) return NotImplemented
def func1(fmt, ra): args, keywords = fmt(ra) if len(args) > 0 and isscalarlike(args[0]): p = SamplingEquatorial(*args, **keywords) assert_is_none(p.ra) assert_is_none(p.dec) assert_equal(p.pa, 0) return assert_raises(ValueError, SamplingEquatorial, *args, **keywords)
def __mul__(self, other): if isscalarlike(other): data = self.data.copy() data.value *= other return type(self)(self.shape, data=data) other = np.asarray(other) if other.ndim == 1: return self._matvec(other) return NotImplemented
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 _format_sphconv(a, b, date_obs=None, time=None): incoords = np.empty(np.broadcast(a, b).shape + (2,)) incoords[..., 0] = a incoords[..., 1] = b if date_obs is None: return incoords import astropy if astropy.__version__ < "1": time = Time(date_obs if isscalarlike(time) else [date_obs], scale='utc') + \ TimeDelta(time, format='sec') else: time = Time(date_obs, scale='utc') + TimeDelta(time, format='sec') return incoords, time
def _format_sphconv(a, b, date_obs=None, time=None): incoords = np.empty(np.broadcast(a, b).shape + (2, )) incoords[..., 0] = a incoords[..., 1] = b if date_obs is None: return incoords import astropy if astropy.__version__ < "1": time = Time(date_obs if isscalarlike(time) else [date_obs], scale='utc') + \ TimeDelta(time, format='sec') else: time = Time(date_obs, scale='utc') + TimeDelta(time, format='sec') return incoords, time
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 get_center(self): """ Return the average pointing direction. """ if isscalarlike(self.masked) and self.masked: n = 0 coords = np.zeros((1, 3)) else: coords = self.cartesian if not isscalarlike(self.masked): valid = 1 - self.masked coords *= valid[:, None] n = np.sum(valid) else: n = len(self) n = np.asarray(n) center = np.sum(coords, axis=0) self.comm.Allreduce(MPI.IN_PLACE, as_mpi(n)) self.comm.Allreduce(MPI.IN_PLACE, as_mpi(center)) if n == 0: raise ValueError('There is no valid pointing.') center /= n return self.cartesian2spherical(center)
def get_center(self): """ Return the average pointing direction. """ if isscalarlike(self.masked) and self.masked: n = 0 coords = np.zeros((1, 3)) else: coords = self.cartesian if not isscalarlike(self.masked): valid = 1 - self.masked coords *= valid[:, None] n = np.sum(valid) else: n = len(self) n = np.asarray(n) center = np.sum(coords, axis=0) self.comm.Allreduce(MPI.IN_PLACE, as_mpi(n)) self.comm.Allreduce(MPI.IN_PLACE, as_mpi(center)) if n == 0: raise ValueError('There is no valid pointing.') center /= n return self.cartesian2spherical(center)
def func(cls, v, k): n1 = 1 if isscalarlike(v) else len(v) n2 = 1 if isscalarlike(k) else len(k) nn = max(n1, n2) if not isscalarlike(v) and not isscalarlike(k) and n1 != n2: # the partitioned arguments do not have the same length assert_raises(ValueError, lambda: cls(arg1, v, arg3, mykey=k)) return op = cls(arg1, v, arg3, mykey=k) if nn == 1: v = v if isscalarlike(v) else v[0] k = k if isscalarlike(k) else k[0] func2(cls, op, v, k) else: assert op.__class__ is BlockDiagonalOperator assert len(op.operands) == nn v = nn * [v] if isscalarlike(v) else v k = nn * [k] if isscalarlike(k) else k for op_, v_, k_ in zip(op.operands, v, k): func2(cls, op_, v_, k_) input = np.ones(nn) output = op(input) assert_equal(output, v)
def func(cls, v, k): n1 = 1 if isscalarlike(v) else len(v) n2 = 1 if isscalarlike(k) else len(k) nn = max(n1, n2) if not isscalarlike(v) and not isscalarlike(k) and n1 != n2: # the partitioned arguments do not have the same length assert_raises(ValueError, lambda: cls(arg1, v, arg3, mykey=k)) return op = cls(arg1, v, arg3, mykey=k) if nn == 1: v = v if isscalarlike(v) else v[0] k = k if isscalarlike(k) else k[0] func2(cls, op, v, k) else: assert op.__class__ is BlockDiagonalOperator assert len(op.operands) == nn v = nn * [v] if isscalarlike(v) else v k = nn * [k] if isscalarlike(k) else k for op_, v_, k_ in zip(op.operands, v, k): func2(cls, op_, v_, k_) input = np.ones(nn) output = op(input) assert_equal(output, v)
def _normalize_selection(self, selection, shape): # return the selection as an array of int or bool, a slice, an Ellipsis # or a tuple. if isinstance(selection, list) and len(selection) == 0: return np.array([], self._dtype_index) if selection is None or selection is Ellipsis or \ isinstance(selection, tuple) and len(selection) == 0: return Ellipsis if isscalarlike(selection): return np.asarray([selection], self._dtype_index) if isinstance(selection, slice): return self._normalize_slice(selection, product(shape)) if isinstance(selection, (list, tuple)): selection_ = np.asarray(selection) if selection_.dtype == object: if len(selection) > len(shape): raise ValueError('Invalid selection dimensions.') selection = tuple( self._normalize_slice(_, s) if isinstance(_, slice) else _ for _, s in zip(selection, shape)) try: return selection[:ilast_is_not(selection, Ellipsis) + 1] except ValueError: return Ellipsis else: selection = selection_ elif not isinstance(selection, np.ndarray): raise TypeError('Invalid selection.') if selection.dtype not in (bool, int): raise TypeError('Invalid selection.') if selection.dtype == int: if selection.ndim != 1: raise ValueError('Index selection is not 1-dimensional.') elif selection.shape != shape: raise ValueError('Invalid boolean selection dimensions.') return selection
def _normalize_selection(self, selection, shape): # return the selection as an array of int or bool, a slice, an Ellipsis # or a tuple. if isinstance(selection, list) and len(selection) == 0: return np.array([], self._dtype_index) if selection is None or selection is Ellipsis or \ isinstance(selection, tuple) and len(selection) == 0: return Ellipsis if isscalarlike(selection): return np.asarray([selection], self._dtype_index) if isinstance(selection, slice): return self._normalize_slice(selection, product(shape)) if isinstance(selection, (list, tuple)): selection_ = np.asarray(selection) if selection_.dtype == object: if len(selection) > len(shape): raise ValueError('Invalid selection dimensions.') selection = tuple(self._normalize_slice(_, s) if isinstance(_, slice) else _ for _, s in zip(selection, shape)) try: return selection[:ilast_is_not(selection, Ellipsis)+1] except ValueError: return Ellipsis else: selection = selection_ elif not isinstance(selection, np.ndarray): raise TypeError('Invalid selection.') if selection.dtype not in (bool, int): raise TypeError('Invalid selection.') if selection.dtype == int: if selection.ndim != 1: raise ValueError('Index selection is not 1-dimensional.') elif selection.shape != shape: raise ValueError('Invalid boolean selection dimensions.') return selection
def imshow(self, mask=None, new_figure=True, title=None, xlabel='', ylabel='', interpolation='nearest', colorbar=True, percentile=0, **keywords): """ A graphical display method specialising matplotlib's imshow. mask : array-like, optional Data mask. True means masked. new_figure : boolean, optional If True, a new figure if created. Default is True. title : str, optional The plot title. xlabel : str, optional Plot X label. ylabel : str, optional Plot Y label. interpolation : str, optional Acceptable values are None, 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos' Default is 'nearest'. colorbar : boolean, optional If True, plot an intensity color bar next to the display. Default is True. percentile : float, tuple of two floats in range [0,100] As a float, percentile of values to be discarded, otherwise, percentile of the minimum and maximum values to be displayed. **keywords : additional are keywords passed to matplotlib's imshow. """ import matplotlib.pyplot as mp if np.iscomplexobj(self): data = abs(self.magnitude) else: data = self.magnitude.copy() if isscalarlike(percentile): percentile = percentile / 2, 100 - percentile / 2 unfinite = ~np.isfinite(self.magnitude) if mask is None: mask = unfinite else: mask = np.logical_or(mask, unfinite) data_valid = data[~mask] minval = scipy.stats.scoreatpercentile(data_valid, percentile[0]) maxval = scipy.stats.scoreatpercentile(data_valid, percentile[1]) data[data < minval] = minval data[data > maxval] = maxval data[mask] = np.nan if new_figure: fig = mp.figure() else: fig = mp.gcf() fontsize = 12. * fig.get_figheight() / 6.125 image = mp.imshow(data, interpolation=interpolation, **keywords) image.set_clim(minval, maxval) ax = mp.gca() ax.set_xlabel(xlabel, fontsize=fontsize) ax.set_ylabel(ylabel, fontsize=fontsize) for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) if title is not None: mp.title(title, fontsize=fontsize) if colorbar: colorbar = mp.colorbar() for tick in colorbar.ax.get_yticklabels(): tick.set_fontsize(fontsize) mp.draw() return image
def create_fitsheader(naxes=None, dtype=None, fromdata=None, extname=None, crval=(0, 0), crpix=None, cunit='deg', ctype=('RA---TAN', 'DEC--TAN'), cd=None, cdelt=None, pa=None, radesys='ICRS', equinox=None): """ Helper to create a FITS header. Parameters ---------- naxes : array, optional (NAXIS1,NAXIS2,...) tuple, which specifies the data dimensions. Note that the dimensions in FITS and ndarrays are reversed. dtype : data-type, optional Desired data type for the data stored in the FITS file extname : None or string if a string is specified ('' can be used), the returned header type will be an Image HDU (otherwise a Primary HDU). crval : 2 element array, optional Reference pixel values (FITS convention). crpix : 2 element array, optional Reference pixel (FITS convention). ctype : 2 element string array, optional Projection types. cunit : string or 2 element string array Units of the CD matrix (default is degrees/pixel). cd : 2 x 2 array FITS parameters CD1_1 CD1_2 CD2_1 CD2_2 cdelt : float or 2 element array Physical increment at the reference pixel. pa : float Position angle of the Y=AXIS2 axis (=-CROTA2). radesys : string Coordinate reference frame for the RA and DEC axis columns. Default is 'ICRS'. equinox : float, optional Reference equinox (for non-ICRS reference frame). Example ------- >>> from pysimulators import Map >>> map = Map.ones((10, 100), unit='Jy/pixel') >>> ny, nx = map.shape >>> map.header = create_fitsheader((nx, ny), cd=[[-1,0], [0,1]]) """ if naxes is not None and fromdata is not None or naxes is None and \ fromdata is None: raise ValueError( "Either keyword 'naxes' or 'fromdata' must be specified.") if fromdata is None: naxes = np.array(naxes, dtype=int, ndmin=1) naxes = tuple(naxes) if len(naxes) > 8: raise ValueError('First argument is naxes=(NAXIS1,NAXIS2,...)') if dtype is not None: dtype = np.dtype(dtype) typename = dtype.name else: typename = 'float64' else: print("The keyword 'from_data' in create_fitsheader is deprecated and " "will be removed in an upcoming release. Use the function create" "_fitsheader_for instead.") array = np.array(fromdata, copy=False) naxes = tuple(reversed(array.shape)) if dtype is not None: array = array.astype(dtype) if array.dtype.itemsize == 1: typename = 'uint8' elif array.dtype.names is not None: typename = None else: typename = array.dtype.name numaxis = len(naxes) header = pyfits.Header() if extname is None: header['simple'] = True # primary header else: header['xtension'] = ('IMAGE', 'Image extension') if typename is not None: header['bitpix'] = (pyfits.DTYPE2BITPIX[typename], 'Array data type') header['naxis'] = (numaxis, 'Number of array dimensions') for dim in range(numaxis): header['naxis' + str(dim + 1)] = naxes[dim] if extname is None: header['extend'] = True else: header['pcount'] = (0, 'Number of parameters') header['gcount'] = (1, 'Number of groups') header['extname'] = extname if cd is not None: cd = np.asarray(cd, dtype=float) if cd.shape != (2, 2): raise ValueError('The CD matrix is not a 2x2 matrix.') else: if cdelt is None: return header cdelt = np.array(cdelt, float) if isscalarlike(cdelt): if ctype is None or len(ctype) == 2 and ctype[0] == 'RA---TAN' and\ ctype[1] == 'DEC--TAN': cdelt = (-cdelt, cdelt) else: cdelt = (cdelt, cdelt) if pa is None: pa = 0. theta = np.deg2rad(-pa) cd = np.diag(cdelt).dot( np.array([[np.cos(theta), np.sin(theta)], [-np.sin(theta), np.cos(theta)]])) crval = np.asarray(crval, float) if crval.size != 2: raise ValueError('CRVAL does not have two elements.') if crpix is None: crpix = (np.array(naxes) + 1) / 2 else: crpix = np.asarray(crpix, float) if crpix.size != 2: raise ValueError('CRPIX does not have two elements.') if len(ctype) != 2: raise ValueError('CTYPE does not have two elements.') if isscalarlike(cunit): cunit = (cunit, cunit) if len(cunit) != 2: raise ValueError('CUNIT does not have two elements.') header['crval1'] = crval[0] header['crval2'] = crval[1] header['crpix1'] = crpix[0] header['crpix2'] = crpix[1] header['cd1_1'] = cd[0, 0] header['cd2_1'] = cd[1, 0] header['cd1_2'] = cd[0, 1] header['cd2_2'] = cd[1, 1] header['ctype1'] = ctype[0] header['ctype2'] = ctype[1] header['cunit1'] = cunit[0] header['cunit2'] = cunit[1] if ctype[0][:3] == 'RA-' and ctype[1][:3] == 'DEC': header['radesys'] = radesys.upper() if equinox is not None: header['equinox'] = float(equinox) return header
def create_fitsheader(naxes=None, dtype=None, fromdata=None, extname=None, crval=(0, 0), crpix=None, cunit='deg', ctype=('RA---TAN', 'DEC--TAN'), cd=None, cdelt=None, pa=None, radesys='ICRS', equinox=None): """ Helper to create a FITS header. Parameters ---------- naxes : array, optional (NAXIS1,NAXIS2,...) tuple, which specifies the data dimensions. Note that the dimensions in FITS and ndarrays are reversed. dtype : data-type, optional Desired data type for the data stored in the FITS file extname : None or string if a string is specified ('' can be used), the returned header type will be an Image HDU (otherwise a Primary HDU). crval : 2 element array, optional Reference pixel values (FITS convention). crpix : 2 element array, optional Reference pixel (FITS convention). ctype : 2 element string array, optional Projection types. cunit : string or 2 element string array Units of the CD matrix (default is degrees/pixel). cd : 2 x 2 array FITS parameters CD1_1 CD1_2 CD2_1 CD2_2 cdelt : float or 2 element array Physical increment at the reference pixel. pa : float Position angle of the Y=AXIS2 axis (=-CROTA2). radesys : string Coordinate reference frame for the RA and DEC axis columns. Default is 'ICRS'. equinox : float, optional Reference equinox (for non-ICRS reference frame). Example ------- >>> from pysimulators import Map >>> map = Map.ones((10, 100), unit='Jy/pixel') >>> ny, nx = map.shape >>> map.header = create_fitsheader((nx, ny), cd=[[-1,0], [0,1]]) """ if naxes is not None and fromdata is not None or naxes is None and \ fromdata is None: raise ValueError( "Either keyword 'naxes' or 'fromdata' must be specified.") if fromdata is None: naxes = np.array(naxes, dtype=int, ndmin=1) naxes = tuple(naxes) if len(naxes) > 8: raise ValueError('First argument is naxes=(NAXIS1,NAXIS2,...)') if dtype is not None: dtype = np.dtype(dtype) typename = dtype.name else: typename = 'float64' else: print("The keyword 'from_data' in create_fitsheader is deprecated and " "will be removed in an upcoming release. Use the function create" "_fitsheader_for instead.") array = np.array(fromdata, copy=False) naxes = tuple(reversed(array.shape)) if dtype is not None: array = array.astype(dtype) if array.dtype.itemsize == 1: typename = 'uint8' elif array.dtype.names is not None: typename = None else: typename = array.dtype.name numaxis = len(naxes) header = pyfits.Header() if extname is None: header['simple'] = True # primary header else: header['xtension'] = ('IMAGE', 'Image extension') if typename is not None: header['bitpix'] = (pyfits.PrimaryHDU.ImgCode[typename], 'Array data type') header['naxis'] = (numaxis, 'Number of array dimensions') for dim in range(numaxis): header['naxis' + str(dim+1)] = naxes[dim] if extname is None: header['extend'] = True else: header['pcount'] = (0, 'Number of parameters') header['gcount'] = (1, 'Number of groups') header['extname'] = extname if cd is not None: cd = np.asarray(cd, dtype=float) if cd.shape != (2, 2): raise ValueError('The CD matrix is not a 2x2 matrix.') else: if cdelt is None: return header cdelt = np.array(cdelt, float) if isscalarlike(cdelt): if ctype is None or len(ctype) == 2 and ctype[0] == 'RA---TAN' and\ ctype[1] == 'DEC--TAN': cdelt = (-cdelt, cdelt) else: cdelt = (cdelt, cdelt) if pa is None: pa = 0. theta = np.deg2rad(-pa) cd = np.diag(cdelt).dot(np.array([[np.cos(theta), np.sin(theta)], [-np.sin(theta), np.cos(theta)]])) crval = np.asarray(crval, float) if crval.size != 2: raise ValueError('CRVAL does not have two elements.') if crpix is None: crpix = (np.array(naxes) + 1) / 2 else: crpix = np.asarray(crpix, float) if crpix.size != 2: raise ValueError('CRPIX does not have two elements.') if len(ctype) != 2: raise ValueError('CTYPE does not have two elements.') if isscalarlike(cunit): cunit = (cunit, cunit) if len(cunit) != 2: raise ValueError('CUNIT does not have two elements.') header['crval1'] = crval[0] header['crval2'] = crval[1] header['crpix1'] = crpix[0] header['crpix2'] = crpix[1] header['cd1_1'] = cd[0, 0] header['cd2_1'] = cd[1, 0] header['cd1_2'] = cd[0, 1] header['cd2_2'] = cd[1, 1] header['ctype1'] = ctype[0] header['ctype2'] = ctype[1] header['cunit1'] = cunit[0] header['cunit2'] = cunit[1] if ctype[0][:3] == 'RA-' and ctype[1][:3] == 'DEC': header['radesys'] = radesys.upper() if equinox is not None: header['equinox'] = float(equinox) return header
def func(cls, n, v, k): n1 = 1 if isscalarlike(v) else len(v) n2 = 1 if isscalarlike(k) else len(k) nn = max(n1, n2) if n is None else 1 if isscalarlike(n) else len(n) if not isscalarlike(v) and not isscalarlike(k) and n1 != n2: # the partitioned arguments do not have the same length assert_raises(ValueError, lambda: cls(arg1, v, arg3, mykey=k, partitionin=n)) return if nn != max(n1, n2) and (not isscalarlike(v) or not isscalarlike(k)): # the partition is incompatible with the partitioned arguments return #XXX test assert_raises(ValueError) op = cls(arg1, v, arg3, mykey=k, partitionin=n) if nn == 1: v = v if isscalarlike(v) else v[0] k = k if isscalarlike(k) else k[0] func2(cls, op, v, k) else: assert op.__class__ is BlockDiagonalOperator assert len(op.operands) == nn if n is None: assert op.partitionin == nn * (None,) assert op.partitionout == nn * (None,) return v = nn * [v] if isscalarlike(v) else v k = nn * [k] if isscalarlike(k) else k for op_, v_, k_ in zip(op.operands, v, k): func2(cls, op_, v_, k_) expected = np.hstack(n_*[v_] for n_, v_ in zip(n, v)) input = np.ones(np.sum(n)) output = op(input) assert_equal(output, expected)
def func(x): assert not isscalarlike(x)
def plot(self, map=None, header=None, title=None, new_figure=True, linewidth=2, percentile=0.01, **kw): """ Plot the pointings' celestial coordinates. Parameters ---------- map : ndarray of dim 2 An optional map to be displayed as background. header : pyfits.Header The optional map's FITS header. title : str The figure's title. new_figure : boolean If true, the display will be done in a new window. linewidth : float The scan line width. percentile : float, tuple of two floats As a float, percentile of values to be discarded, otherwise, percentile of the minimum and maximum values to be displayed. """ import kapteyn.maputils as km import matplotlib.pyplot as mp if isscalarlike(self.masked) and self.masked or np.all(self.masked): if new_figure: raise ValueError('There is no valid coordinates.') return if not isscalarlike(self.masked): ra = self.ra.copy() dec = self.dec.copy() ra[self.masked] = np.nan dec[self.masked] = np.nan else: ra = self.ra dec = self.dec if header is None: header = getattr(map, 'header', None) elif map is not None: map = Map(map, header=header, copy=False) if isinstance(map, Map) and map.has_wcs(): image = map.imshow(title=title, new_figure=new_figure, percentile=percentile, **kw) else: if header is None: header = self.get_map_header(naxis=1) fitsobj = km.FITSimage(externalheader=dict(header)) if new_figure: fig = mp.figure() frame = fig.add_axes((0.1, 0.1, 0.8, 0.8)) else: frame = mp.gca() if title is not None: frame.set_title(title) image = fitsobj.Annotatedimage(frame, blankcolor='w') image.Graticule() image.plot() image.interact_toolbarinfo() image.interact_writepos() mp.show() _plot_scan(image, ra, dec, linewidth=linewidth, **kw) return image
def imshow(self, mask=None, new_figure=True, title=None, xlabel='X', ylabel='Y', interpolation='nearest', origin=None, colorbar=True, percentile=0, **keywords): try: import kapteyn.maputils as km except ImportError: km = None import matplotlib.pyplot as mp if mask is None and self.coverage is not None: mask = self.coverage <= 0 if origin is None: origin = self.origin # check if the map has no astrometry information if not self.has_wcs() or km is None: image = super(Map, self).imshow(mask=mask, new_figure=new_figure, title=title, xlabel=xlabel, ylabel=ylabel, origin=origin, colorbar=colorbar, percentile=percentile, **keywords) return image if np.iscomplexobj(self): data = abs(self.magnitude) else: data = self.magnitude.copy() if isscalarlike(percentile): percentile = percentile / 2, 100 - percentile / 2 unfinite = ~np.isfinite(self.magnitude) if mask is None: mask = unfinite else: mask = np.logical_or(mask, unfinite) data_valid = data[~mask] minval = scipy.stats.scoreatpercentile(data_valid, percentile[0]) maxval = scipy.stats.scoreatpercentile(data_valid, percentile[1]) data[data < minval] = minval data[data > maxval] = maxval data[mask] = np.nan #XXX FIX ME colorbar = False fitsobj = km.FITSimage(externaldata=data, externalheader=dict(self.header)) if new_figure: fig = mp.figure() frame = fig.add_axes((0.1, 0.1, 0.8, 0.8)) else: frame = mp.gca() fontsize = 12. * fig.get_figheight() / 6.125 for tick in frame.xaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) for tick in frame.yaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) if title is not None: frame.set_title(title) if colorbar: colorbar = mp.colorbar() for tick in colorbar.ax.get_yticklabels(): tick.set_fontsize(fontsize) annim = fitsobj.Annotatedimage(frame, blankcolor='w') annim.Image(interpolation=interpolation) grat = annim.Graticule() grat.setp_gratline(visible=False) annim.plot() annim.interact_imagecolors() annim.interact_toolbarinfo() annim.interact_writepos() if colorbar: annim.Colorbar() mp.show() return annim
def imshow(self, mask=None, new_figure=True, title=None, xlabel='', ylabel='', interpolation='nearest', colorbar=True, percentile=0, **keywords): """ A graphical display method specialising matplotlib's imshow. mask : array-like, optional Data mask. True means masked. new_figure : boolean, optional If True, a new figure if created. Default is True. title : str, optional The plot title. xlabel : str, optional Plot X label. ylabel : str, optional Plot Y label. interpolation : str, optional Acceptable values are None, 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos' Default is 'nearest'. colorbar : boolean, optional If True, plot an intensity color bar next to the display. Default is True. percentile : float, tuple of two floats in range [0,100] As a float, percentile of values to be discarded, otherwise, percentile of the minimum and maximum values to be displayed. **keywords : additional are keywords passed to matplotlib's imshow. """ import matplotlib.pyplot as mp if np.iscomplexobj(self): data = abs(self.magnitude) else: data = self.magnitude.copy() if isscalarlike(percentile): percentile = percentile / 2, 100 - percentile / 2 unfinite = ~np.isfinite(self.magnitude) if mask is None: mask = unfinite else: mask = np.logical_or(mask, unfinite) data_valid = data[~mask] minval = scipy.stats.scoreatpercentile(data_valid, percentile[0]) maxval = scipy.stats.scoreatpercentile(data_valid, percentile[1]) data[data < minval] = minval data[data > maxval] = maxval data[mask] = np.nan if new_figure: fig = mp.figure() else: fig = mp.gcf() fontsize = 12. * fig.get_figheight() / 6.125 image = mp.imshow(data, interpolation=interpolation, **keywords) image.set_clim(minval, maxval) ax = mp.gca() ax.set_xlabel(xlabel, fontsize=fontsize) ax.set_ylabel(ylabel, fontsize=fontsize) for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) if title is not None: mp.title(title, fontsize=fontsize) if colorbar: colorbar = mp.colorbar() for tick in colorbar.ax.get_yticklabels(): tick.set_fontsize(fontsize) mp.draw() return image
def plot(self, map=None, header=None, title=None, new_figure=True, linewidth=2, percentile=0.01, **kw): """ Plot the pointings' celestial coordinates. Parameters ---------- map : ndarray of dim 2 An optional map to be displayed as background. header : pyfits.Header The optional map's FITS header. title : str The figure's title. new_figure : boolean If true, the display will be done in a new window. linewidth : float The scan line width. percentile : float, tuple of two floats As a float, percentile of values to be discarded, otherwise, percentile of the minimum and maximum values to be displayed. """ import kapteyn.maputils as km import matplotlib.pyplot as mp if isscalarlike(self.masked) and self.masked or np.all(self.masked): if new_figure: raise ValueError('There is no valid coordinates.') return if not isscalarlike(self.masked): ra = self.ra.copy() dec = self.dec.copy() ra[self.masked] = np.nan dec[self.masked] = np.nan else: ra = self.ra dec = self.dec if header is None: header = getattr(map, 'header', None) elif map is not None: map = Map(map, header=header, copy=False) if isinstance(map, Map) and map.has_wcs(): image = map.imshow(title=title, new_figure=new_figure, percentile=percentile, **kw) else: if header is None: header = self.get_map_header(naxis=1) fitsobj = km.FITSimage(externalheader=dict(header)) if new_figure: fig = mp.figure() frame = fig.add_axes((0.1, 0.1, 0.8, 0.8)) else: frame = mp.gca() if title is not None: frame.set_title(title) image = fitsobj.Annotatedimage(frame, blankcolor='w') image.Graticule() image.plot() image.interact_toolbarinfo() image.interact_writepos() mp.show() _plot_scan(image, ra, dec, linewidth=linewidth, **kw) return image
def func(x): assert not isscalarlike(x)
def imshow(self, mask=None, new_figure=True, title=None, xlabel='X', ylabel='Y', interpolation='nearest', origin=None, colorbar=True, percentile=0, **keywords): try: import kapteyn.maputils as km except ImportError: km = None import matplotlib.pyplot as mp if mask is None and self.coverage is not None: mask = self.coverage <= 0 if origin is None: origin = self.origin # check if the map has no astrometry information if not self.has_wcs() or km is None: image = super(Map, self).imshow( mask=mask, new_figure=new_figure, title=title, xlabel=xlabel, ylabel=ylabel, origin=origin, colorbar=colorbar, percentile=percentile, **keywords) return image if np.iscomplexobj(self): data = abs(self.magnitude) else: data = self.magnitude.copy() if isscalarlike(percentile): percentile = percentile / 2, 100 - percentile / 2 unfinite = ~np.isfinite(self.magnitude) if mask is None: mask = unfinite else: mask = np.logical_or(mask, unfinite) data_valid = data[~mask] minval = scipy.stats.scoreatpercentile(data_valid, percentile[0]) maxval = scipy.stats.scoreatpercentile(data_valid, percentile[1]) data[data < minval] = minval data[data > maxval] = maxval data[mask] = np.nan #XXX FIX ME colorbar = False fitsobj = km.FITSimage(externaldata=data, externalheader=dict(self.header)) if new_figure: fig = mp.figure() frame = fig.add_axes((0.1, 0.1, 0.8, 0.8)) else: frame = mp.gca() fontsize = 12. * fig.get_figheight() / 6.125 for tick in frame.xaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) for tick in frame.yaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) if title is not None: frame.set_title(title) if colorbar: colorbar = mp.colorbar() for tick in colorbar.ax.get_yticklabels(): tick.set_fontsize(fontsize) annim = fitsobj.Annotatedimage(frame, blankcolor='w') annim.Image(interpolation=interpolation) grat = annim.Graticule() grat.setp_gratline(visible=False) annim.plot() annim.interact_imagecolors() annim.interact_toolbarinfo() annim.interact_writepos() if colorbar: annim.Colorbar() mp.show() return annim
def func(cls, n, v, k): n1 = 1 if isscalarlike(v) else len(v) n2 = 1 if isscalarlike(k) else len(k) nn = max(n1, n2) if n is None else 1 if isscalarlike(n) else len(n) if not isscalarlike(v) and not isscalarlike(k) and n1 != n2: # the partitioned arguments do not have the same length assert_raises(ValueError, lambda: cls(arg1, v, arg3, mykey=k, partitionin=n)) return if nn != max(n1, n2) and (not isscalarlike(v) or not isscalarlike(k)): # the partition is incompatible with the partitioned arguments return #XXX test assert_raises(ValueError) op = cls(arg1, v, arg3, mykey=k, partitionin=n) if nn == 1: v = v if isscalarlike(v) else v[0] k = k if isscalarlike(k) else k[0] func2(cls, op, v, k) else: assert op.__class__ is BlockDiagonalOperator assert len(op.operands) == nn if n is None: assert op.partitionin == nn * (None, ) assert op.partitionout == nn * (None, ) return v = nn * [v] if isscalarlike(v) else v k = nn * [k] if isscalarlike(k) else k for op_, v_, k_ in zip(op.operands, v, k): func2(cls, op_, v_, k_) expected = np.hstack(n_ * [v_] for n_, v_ in zip(n, v)) input = np.ones(np.sum(n)) output = op(input) assert_equal(output, expected)