body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
5f76fffd49f07232339a9dd4552029f0d3a34d5578de17d33a93b8d159c0a2a3
def test_promote_user(self): 'Test error raised when accessing nonexisting user' response = self.app.put('/api/v2/auth/users/{}'.format(User.query.order_by(User.created_at).first().id), content_type='application/json', headers={'x-access-token': self.admintoken}) self.assertEqual(response.status_code, 200) response_msg = json.loads(response.data.decode('UTF-8')) self.assertIn('admin', response_msg['Message'])
Test error raised when accessing nonexisting user
tests/v2/test_user.py
test_promote_user
ThaDeveloper/weConnect
1
python
def test_promote_user(self): response = self.app.put('/api/v2/auth/users/{}'.format(User.query.order_by(User.created_at).first().id), content_type='application/json', headers={'x-access-token': self.admintoken}) self.assertEqual(response.status_code, 200) response_msg = json.loads(response.data.decode('UTF-8')) self.assertIn('admin', response_msg['Message'])
def test_promote_user(self): response = self.app.put('/api/v2/auth/users/{}'.format(User.query.order_by(User.created_at).first().id), content_type='application/json', headers={'x-access-token': self.admintoken}) self.assertEqual(response.status_code, 200) response_msg = json.loads(response.data.decode('UTF-8')) self.assertIn('admin', response_msg['Message'])<|docstring|>Test error raised when accessing nonexisting user<|endoftext|>
342b88b2a63b3702545dd32606570c61f0e1dd15fa85c977f86a2a163eeb478d
def test_unauthorized_promote_user(self): 'Test error raised for unauthorized user promotion' response = self.app.put('/api/v2/auth/users/{}'.format(User.query.order_by(User.created_at).first().id), content_type='application/json', headers={'x-access-token': self.token}) self.assertEqual(response.status_code, 401) response_msg = json.loads(response.data.decode('UTF-8')) self.assertIn('Cannot perform', response_msg['Message'])
Test error raised for unauthorized user promotion
tests/v2/test_user.py
test_unauthorized_promote_user
ThaDeveloper/weConnect
1
python
def test_unauthorized_promote_user(self): response = self.app.put('/api/v2/auth/users/{}'.format(User.query.order_by(User.created_at).first().id), content_type='application/json', headers={'x-access-token': self.token}) self.assertEqual(response.status_code, 401) response_msg = json.loads(response.data.decode('UTF-8')) self.assertIn('Cannot perform', response_msg['Message'])
def test_unauthorized_promote_user(self): response = self.app.put('/api/v2/auth/users/{}'.format(User.query.order_by(User.created_at).first().id), content_type='application/json', headers={'x-access-token': self.token}) self.assertEqual(response.status_code, 401) response_msg = json.loads(response.data.decode('UTF-8')) self.assertIn('Cannot perform', response_msg['Message'])<|docstring|>Test error raised for unauthorized user promotion<|endoftext|>
dd5159a04267a132b314da2dc584564c53cde638a94c24ff1756b91f4359c0bf
def test_delete_user(self): 'Tests deleting user from db' response = self.app.delete('/api/v2/auth/users/{}'.format(User.query.order_by(User.created_at).first().id), content_type='application/json', headers={'x-access-token': self.admintoken}) self.assertEqual(response.status_code, 200) response_msg = json.loads(response.data.decode('UTF-8')) self.assertIn('deleted', response_msg['Message'])
Tests deleting user from db
tests/v2/test_user.py
test_delete_user
ThaDeveloper/weConnect
1
python
def test_delete_user(self): response = self.app.delete('/api/v2/auth/users/{}'.format(User.query.order_by(User.created_at).first().id), content_type='application/json', headers={'x-access-token': self.admintoken}) self.assertEqual(response.status_code, 200) response_msg = json.loads(response.data.decode('UTF-8')) self.assertIn('deleted', response_msg['Message'])
def test_delete_user(self): response = self.app.delete('/api/v2/auth/users/{}'.format(User.query.order_by(User.created_at).first().id), content_type='application/json', headers={'x-access-token': self.admintoken}) self.assertEqual(response.status_code, 200) response_msg = json.loads(response.data.decode('UTF-8')) self.assertIn('deleted', response_msg['Message'])<|docstring|>Tests deleting user from db<|endoftext|>
53d8cd2e50cc03d5039c54a3e6149fc8d117b74b7afde366202fc1d1394c923a
def test_unauthorized_user_delete(self): 'Tests error raised for unauthorized user delete from db' response = self.app.delete('/api/v2/auth/users/{}'.format(User.query.order_by(User.created_at).first().id), content_type='application/json', headers={'x-access-token': self.token}) self.assertEqual(response.status_code, 401) response_msg = json.loads(response.data.decode('UTF-8')) self.assertIn('Cannot perform', response_msg['Message'])
Tests error raised for unauthorized user delete from db
tests/v2/test_user.py
test_unauthorized_user_delete
ThaDeveloper/weConnect
1
python
def test_unauthorized_user_delete(self): response = self.app.delete('/api/v2/auth/users/{}'.format(User.query.order_by(User.created_at).first().id), content_type='application/json', headers={'x-access-token': self.token}) self.assertEqual(response.status_code, 401) response_msg = json.loads(response.data.decode('UTF-8')) self.assertIn('Cannot perform', response_msg['Message'])
def test_unauthorized_user_delete(self): response = self.app.delete('/api/v2/auth/users/{}'.format(User.query.order_by(User.created_at).first().id), content_type='application/json', headers={'x-access-token': self.token}) self.assertEqual(response.status_code, 401) response_msg = json.loads(response.data.decode('UTF-8')) self.assertIn('Cannot perform', response_msg['Message'])<|docstring|>Tests error raised for unauthorized user delete from db<|endoftext|>
56f6aa568a433e646d4a9703cb9a81d057eff5cbfb3ed7604e658a4d4c64bf67
def test_read_user_businesses(self): 'Tests user can read the businesses of a particular user' response = self.app.get('/api/v2/auth/users/{}/businesses'.format(User.query.order_by(User.created_at).first().id), content_type='application/json') self.assertEqual(response.status_code, 200)
Tests user can read the businesses of a particular user
tests/v2/test_user.py
test_read_user_businesses
ThaDeveloper/weConnect
1
python
def test_read_user_businesses(self): response = self.app.get('/api/v2/auth/users/{}/businesses'.format(User.query.order_by(User.created_at).first().id), content_type='application/json') self.assertEqual(response.status_code, 200)
def test_read_user_businesses(self): response = self.app.get('/api/v2/auth/users/{}/businesses'.format(User.query.order_by(User.created_at).first().id), content_type='application/json') self.assertEqual(response.status_code, 200)<|docstring|>Tests user can read the businesses of a particular user<|endoftext|>
6c83967a47408d57f8dd08a65b7de29663ed40d614607a8cf2164b170cd0f60d
def gauss_image(shape=(101, 101), wcs=None, factor=1, gauss=None, center=None, flux=1.0, fwhm=(1.0, 1.0), peak=False, rot=0.0, cont=0, unit_center=u.deg, unit_fwhm=u.arcsec, unit=u.dimensionless_unscaled): 'Create a new image from a 2D gaussian.\n\n Parameters\n ----------\n shape : int or (int,int)\n Lengths of the image in Y and X with python notation: (ny,nx).\n (101,101) by default. If wcs object contains dimensions, shape is\n ignored and wcs dimensions are used.\n wcs : `mpdaf.obj.WCS`\n World coordinates.\n factor : int\n If factor<=1, gaussian value is computed in the center of each pixel.\n If factor>1, for each pixel, gaussian value is the sum of the gaussian\n values on the factor*factor pixels divided by the pixel area.\n gauss : `mpdaf.obj.Gauss2D`\n Object that contains all Gaussian parameters. If it is present, the\n following parameters are not used.\n center : (float,float)\n Gaussian center (y_peak, x_peak). If None the center of the image is\n used. The unit is given by the unit_center parameter (degrees by\n default).\n flux : float\n Integrated gaussian flux or gaussian peak value if peak is True.\n fwhm : (float,float)\n Gaussian fwhm (fwhm_y,fwhm_x).\n The unit is given by the unit_fwhm parameter (arcseconds by default).\n peak : bool\n If true, flux contains a gaussian peak value.\n rot : float\n Angle position in degree.\n cont : float\n Continuum value. 0 by default.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_fwhm : `astropy.units.Unit`\n FWHM unit. Arcseconds by default (use None for radius in pixels)\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' if is_int(shape): shape = (shape, shape) shape = np.array(shape) wcs = (wcs or WCS()) if ((wcs.naxis1 == 1.0) and (wcs.naxis2 == 1.0)): wcs.naxis1 = shape[1] wcs.naxis2 = shape[0] elif ((wcs.naxis1 != 0.0) or (wcs.naxis2 != 0.0)): shape[1] = wcs.naxis1 shape[0] = wcs.naxis2 if (gauss is not None): center = gauss.center flux = gauss.flux fwhm = gauss.fwhm peak = False rot = gauss.rot cont = gauss.cont if (center is None): center = ((np.array(shape) - 1) / 2.0) elif (unit_center is not None): center = wcs.sky2pix(center, unit=unit_center)[0] if (unit_fwhm is not None): fwhm = (np.array(fwhm) / wcs.get_step(unit=unit_fwhm)) if ((fwhm[1] == 0) or (fwhm[0] == 0)): raise ValueError('fwhm equal to 0') p_width = (fwhm[0] * gaussian_fwhm_to_sigma) q_width = (fwhm[1] * gaussian_fwhm_to_sigma) theta = ((np.pi * rot) / 180.0) if (peak is True): norm = ((((flux * 2) * np.pi) * p_width) * q_width) else: norm = flux def gauss(p, q): cost = np.cos(theta) sint = np.sin(theta) xdiff = (p - center[0]) ydiff = (q - center[1]) return (((norm / (((2 * np.pi) * p_width) * q_width)) * np.exp(((- (((xdiff * cost) - (ydiff * sint)) ** 2)) / (2 * (p_width ** 2))))) * np.exp(((- (((xdiff * sint) + (ydiff * cost)) ** 2)) / (2 * (q_width ** 2))))) if (factor > 1): if (rot == 0): from scipy import special (X, Y) = np.meshgrid(range(shape[0]), range(shape[1])) pixcrd_min = (np.array(list(zip(X.ravel(), Y.ravel()))) - 0.5) xmin = (((pixcrd_min[(:, 1)] - center[1]) / np.sqrt(2.0)) / q_width) ymin = (((pixcrd_min[(:, 0)] - center[0]) / np.sqrt(2.0)) / p_width) pixcrd_max = (np.array(list(zip(X.ravel(), Y.ravel()))) + 0.5) xmax = (((pixcrd_max[(:, 1)] - center[1]) / np.sqrt(2.0)) / q_width) ymax = (((pixcrd_max[(:, 0)] - center[0]) / np.sqrt(2.0)) / p_width) dx = (pixcrd_max[(:, 1)] - pixcrd_min[(:, 1)]) dy = (pixcrd_max[(:, 0)] - pixcrd_min[(:, 0)]) data = (((((norm * 0.25) / dx) / dy) * (special.erf(xmax) - special.erf(xmin))) * (special.erf(ymax) - special.erf(ymin))) data = np.reshape(data, (shape[1], shape[0])).T else: (yy, xx) = (np.mgrid[(:(shape[0] * factor), :(shape[1] * factor))] / factor) data = gauss(yy, xx) data = data.reshape(shape[0], 2, shape[1], 2).sum(axis=(1, 3)) data /= (factor ** 2) else: (yy, xx) = np.mgrid[(:shape[0], :shape[1])] data = gauss(yy, xx) return Image(data=(data + cont), wcs=wcs, unit=unit, copy=False, dtype=None)
Create a new image from a 2D gaussian. Parameters ---------- shape : int or (int,int) Lengths of the image in Y and X with python notation: (ny,nx). (101,101) by default. If wcs object contains dimensions, shape is ignored and wcs dimensions are used. wcs : `mpdaf.obj.WCS` World coordinates. factor : int If factor<=1, gaussian value is computed in the center of each pixel. If factor>1, for each pixel, gaussian value is the sum of the gaussian values on the factor*factor pixels divided by the pixel area. gauss : `mpdaf.obj.Gauss2D` Object that contains all Gaussian parameters. If it is present, the following parameters are not used. center : (float,float) Gaussian center (y_peak, x_peak). If None the center of the image is used. The unit is given by the unit_center parameter (degrees by default). flux : float Integrated gaussian flux or gaussian peak value if peak is True. fwhm : (float,float) Gaussian fwhm (fwhm_y,fwhm_x). The unit is given by the unit_fwhm parameter (arcseconds by default). peak : bool If true, flux contains a gaussian peak value. rot : float Angle position in degree. cont : float Continuum value. 0 by default. unit_center : `astropy.units.Unit` type of the center and position coordinates. Degrees by default (use None for coordinates in pixels). unit_fwhm : `astropy.units.Unit` FWHM unit. Arcseconds by default (use None for radius in pixels) Returns ------- out : `~mpdaf.obj.Image`
lib/mpdaf/obj/image.py
gauss_image
musevlt/mpdaf
4
python
def gauss_image(shape=(101, 101), wcs=None, factor=1, gauss=None, center=None, flux=1.0, fwhm=(1.0, 1.0), peak=False, rot=0.0, cont=0, unit_center=u.deg, unit_fwhm=u.arcsec, unit=u.dimensionless_unscaled): 'Create a new image from a 2D gaussian.\n\n Parameters\n ----------\n shape : int or (int,int)\n Lengths of the image in Y and X with python notation: (ny,nx).\n (101,101) by default. If wcs object contains dimensions, shape is\n ignored and wcs dimensions are used.\n wcs : `mpdaf.obj.WCS`\n World coordinates.\n factor : int\n If factor<=1, gaussian value is computed in the center of each pixel.\n If factor>1, for each pixel, gaussian value is the sum of the gaussian\n values on the factor*factor pixels divided by the pixel area.\n gauss : `mpdaf.obj.Gauss2D`\n Object that contains all Gaussian parameters. If it is present, the\n following parameters are not used.\n center : (float,float)\n Gaussian center (y_peak, x_peak). If None the center of the image is\n used. The unit is given by the unit_center parameter (degrees by\n default).\n flux : float\n Integrated gaussian flux or gaussian peak value if peak is True.\n fwhm : (float,float)\n Gaussian fwhm (fwhm_y,fwhm_x).\n The unit is given by the unit_fwhm parameter (arcseconds by default).\n peak : bool\n If true, flux contains a gaussian peak value.\n rot : float\n Angle position in degree.\n cont : float\n Continuum value. 0 by default.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_fwhm : `astropy.units.Unit`\n FWHM unit. Arcseconds by default (use None for radius in pixels)\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' if is_int(shape): shape = (shape, shape) shape = np.array(shape) wcs = (wcs or WCS()) if ((wcs.naxis1 == 1.0) and (wcs.naxis2 == 1.0)): wcs.naxis1 = shape[1] wcs.naxis2 = shape[0] elif ((wcs.naxis1 != 0.0) or (wcs.naxis2 != 0.0)): shape[1] = wcs.naxis1 shape[0] = wcs.naxis2 if (gauss is not None): center = gauss.center flux = gauss.flux fwhm = gauss.fwhm peak = False rot = gauss.rot cont = gauss.cont if (center is None): center = ((np.array(shape) - 1) / 2.0) elif (unit_center is not None): center = wcs.sky2pix(center, unit=unit_center)[0] if (unit_fwhm is not None): fwhm = (np.array(fwhm) / wcs.get_step(unit=unit_fwhm)) if ((fwhm[1] == 0) or (fwhm[0] == 0)): raise ValueError('fwhm equal to 0') p_width = (fwhm[0] * gaussian_fwhm_to_sigma) q_width = (fwhm[1] * gaussian_fwhm_to_sigma) theta = ((np.pi * rot) / 180.0) if (peak is True): norm = ((((flux * 2) * np.pi) * p_width) * q_width) else: norm = flux def gauss(p, q): cost = np.cos(theta) sint = np.sin(theta) xdiff = (p - center[0]) ydiff = (q - center[1]) return (((norm / (((2 * np.pi) * p_width) * q_width)) * np.exp(((- (((xdiff * cost) - (ydiff * sint)) ** 2)) / (2 * (p_width ** 2))))) * np.exp(((- (((xdiff * sint) + (ydiff * cost)) ** 2)) / (2 * (q_width ** 2))))) if (factor > 1): if (rot == 0): from scipy import special (X, Y) = np.meshgrid(range(shape[0]), range(shape[1])) pixcrd_min = (np.array(list(zip(X.ravel(), Y.ravel()))) - 0.5) xmin = (((pixcrd_min[(:, 1)] - center[1]) / np.sqrt(2.0)) / q_width) ymin = (((pixcrd_min[(:, 0)] - center[0]) / np.sqrt(2.0)) / p_width) pixcrd_max = (np.array(list(zip(X.ravel(), Y.ravel()))) + 0.5) xmax = (((pixcrd_max[(:, 1)] - center[1]) / np.sqrt(2.0)) / q_width) ymax = (((pixcrd_max[(:, 0)] - center[0]) / np.sqrt(2.0)) / p_width) dx = (pixcrd_max[(:, 1)] - pixcrd_min[(:, 1)]) dy = (pixcrd_max[(:, 0)] - pixcrd_min[(:, 0)]) data = (((((norm * 0.25) / dx) / dy) * (special.erf(xmax) - special.erf(xmin))) * (special.erf(ymax) - special.erf(ymin))) data = np.reshape(data, (shape[1], shape[0])).T else: (yy, xx) = (np.mgrid[(:(shape[0] * factor), :(shape[1] * factor))] / factor) data = gauss(yy, xx) data = data.reshape(shape[0], 2, shape[1], 2).sum(axis=(1, 3)) data /= (factor ** 2) else: (yy, xx) = np.mgrid[(:shape[0], :shape[1])] data = gauss(yy, xx) return Image(data=(data + cont), wcs=wcs, unit=unit, copy=False, dtype=None)
def gauss_image(shape=(101, 101), wcs=None, factor=1, gauss=None, center=None, flux=1.0, fwhm=(1.0, 1.0), peak=False, rot=0.0, cont=0, unit_center=u.deg, unit_fwhm=u.arcsec, unit=u.dimensionless_unscaled): 'Create a new image from a 2D gaussian.\n\n Parameters\n ----------\n shape : int or (int,int)\n Lengths of the image in Y and X with python notation: (ny,nx).\n (101,101) by default. If wcs object contains dimensions, shape is\n ignored and wcs dimensions are used.\n wcs : `mpdaf.obj.WCS`\n World coordinates.\n factor : int\n If factor<=1, gaussian value is computed in the center of each pixel.\n If factor>1, for each pixel, gaussian value is the sum of the gaussian\n values on the factor*factor pixels divided by the pixel area.\n gauss : `mpdaf.obj.Gauss2D`\n Object that contains all Gaussian parameters. If it is present, the\n following parameters are not used.\n center : (float,float)\n Gaussian center (y_peak, x_peak). If None the center of the image is\n used. The unit is given by the unit_center parameter (degrees by\n default).\n flux : float\n Integrated gaussian flux or gaussian peak value if peak is True.\n fwhm : (float,float)\n Gaussian fwhm (fwhm_y,fwhm_x).\n The unit is given by the unit_fwhm parameter (arcseconds by default).\n peak : bool\n If true, flux contains a gaussian peak value.\n rot : float\n Angle position in degree.\n cont : float\n Continuum value. 0 by default.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_fwhm : `astropy.units.Unit`\n FWHM unit. Arcseconds by default (use None for radius in pixels)\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' if is_int(shape): shape = (shape, shape) shape = np.array(shape) wcs = (wcs or WCS()) if ((wcs.naxis1 == 1.0) and (wcs.naxis2 == 1.0)): wcs.naxis1 = shape[1] wcs.naxis2 = shape[0] elif ((wcs.naxis1 != 0.0) or (wcs.naxis2 != 0.0)): shape[1] = wcs.naxis1 shape[0] = wcs.naxis2 if (gauss is not None): center = gauss.center flux = gauss.flux fwhm = gauss.fwhm peak = False rot = gauss.rot cont = gauss.cont if (center is None): center = ((np.array(shape) - 1) / 2.0) elif (unit_center is not None): center = wcs.sky2pix(center, unit=unit_center)[0] if (unit_fwhm is not None): fwhm = (np.array(fwhm) / wcs.get_step(unit=unit_fwhm)) if ((fwhm[1] == 0) or (fwhm[0] == 0)): raise ValueError('fwhm equal to 0') p_width = (fwhm[0] * gaussian_fwhm_to_sigma) q_width = (fwhm[1] * gaussian_fwhm_to_sigma) theta = ((np.pi * rot) / 180.0) if (peak is True): norm = ((((flux * 2) * np.pi) * p_width) * q_width) else: norm = flux def gauss(p, q): cost = np.cos(theta) sint = np.sin(theta) xdiff = (p - center[0]) ydiff = (q - center[1]) return (((norm / (((2 * np.pi) * p_width) * q_width)) * np.exp(((- (((xdiff * cost) - (ydiff * sint)) ** 2)) / (2 * (p_width ** 2))))) * np.exp(((- (((xdiff * sint) + (ydiff * cost)) ** 2)) / (2 * (q_width ** 2))))) if (factor > 1): if (rot == 0): from scipy import special (X, Y) = np.meshgrid(range(shape[0]), range(shape[1])) pixcrd_min = (np.array(list(zip(X.ravel(), Y.ravel()))) - 0.5) xmin = (((pixcrd_min[(:, 1)] - center[1]) / np.sqrt(2.0)) / q_width) ymin = (((pixcrd_min[(:, 0)] - center[0]) / np.sqrt(2.0)) / p_width) pixcrd_max = (np.array(list(zip(X.ravel(), Y.ravel()))) + 0.5) xmax = (((pixcrd_max[(:, 1)] - center[1]) / np.sqrt(2.0)) / q_width) ymax = (((pixcrd_max[(:, 0)] - center[0]) / np.sqrt(2.0)) / p_width) dx = (pixcrd_max[(:, 1)] - pixcrd_min[(:, 1)]) dy = (pixcrd_max[(:, 0)] - pixcrd_min[(:, 0)]) data = (((((norm * 0.25) / dx) / dy) * (special.erf(xmax) - special.erf(xmin))) * (special.erf(ymax) - special.erf(ymin))) data = np.reshape(data, (shape[1], shape[0])).T else: (yy, xx) = (np.mgrid[(:(shape[0] * factor), :(shape[1] * factor))] / factor) data = gauss(yy, xx) data = data.reshape(shape[0], 2, shape[1], 2).sum(axis=(1, 3)) data /= (factor ** 2) else: (yy, xx) = np.mgrid[(:shape[0], :shape[1])] data = gauss(yy, xx) return Image(data=(data + cont), wcs=wcs, unit=unit, copy=False, dtype=None)<|docstring|>Create a new image from a 2D gaussian. Parameters ---------- shape : int or (int,int) Lengths of the image in Y and X with python notation: (ny,nx). (101,101) by default. If wcs object contains dimensions, shape is ignored and wcs dimensions are used. wcs : `mpdaf.obj.WCS` World coordinates. factor : int If factor<=1, gaussian value is computed in the center of each pixel. If factor>1, for each pixel, gaussian value is the sum of the gaussian values on the factor*factor pixels divided by the pixel area. gauss : `mpdaf.obj.Gauss2D` Object that contains all Gaussian parameters. If it is present, the following parameters are not used. center : (float,float) Gaussian center (y_peak, x_peak). If None the center of the image is used. The unit is given by the unit_center parameter (degrees by default). flux : float Integrated gaussian flux or gaussian peak value if peak is True. fwhm : (float,float) Gaussian fwhm (fwhm_y,fwhm_x). The unit is given by the unit_fwhm parameter (arcseconds by default). peak : bool If true, flux contains a gaussian peak value. rot : float Angle position in degree. cont : float Continuum value. 0 by default. unit_center : `astropy.units.Unit` type of the center and position coordinates. Degrees by default (use None for coordinates in pixels). unit_fwhm : `astropy.units.Unit` FWHM unit. Arcseconds by default (use None for radius in pixels) Returns ------- out : `~mpdaf.obj.Image`<|endoftext|>
b5b3171dcf7ffebc8e9718a571758048f542faf56bd0d30d09aa15fff9c7a7ac
def moffat_image(shape=(101, 101), wcs=None, factor=1, moffat=None, center=None, flux=1.0, fwhm=(1.0, 1.0), peak=False, n=2, rot=0.0, cont=0, unit_center=u.deg, unit_fwhm=u.arcsec, unit=u.dimensionless_unscaled): 'Create a new image from a 2D Moffat function.\n\n Parameters\n ----------\n shape : int or (int,int)\n Lengths of the image in Y and X with python notation: (ny,nx).\n (101,101) by default. If wcs object contains dimensions, shape is\n ignored and wcs dimensions are used.\n wcs : `mpdaf.obj.WCS`\n World coordinates.\n factor : int\n If factor<=1, moffat value is computed in the center of each pixel.\n If factor>1, for each pixel, moffat value is the sum\n of the moffat values on the factor*factor pixels divided\n by the pixel area.\n moffat : `mpdaf.obj.Moffat2D`\n object that contains all moffat parameters.\n If it is present, following parameters are not used.\n center : (float,float)\n Peak center (x_peak, y_peak). The unit is genven byt the parameter\n unit_center (degrees by default). If None the center of the image is\n used.\n flux : float\n Integrated gaussian flux or gaussian peak value\n if peak is True.\n fwhm : (float,float)\n Gaussian fwhm (fwhm_y,fwhm_x).\n The unit is given by the parameter unit_fwhm (arcseconds by default)\n peak : bool\n If true, flux contains a gaussian peak value.\n n : int\n Atmospheric scattering coefficient. 2 by default.\n rot : float\n Angle position in degree.\n cont : float\n Continuum value. 0 by default.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_fwhm : `astropy.units.Unit`\n FWHM unit. Arcseconds by default (use None for radius in pixels)\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' n = float(n) if is_int(shape): shape = (shape, shape) shape = np.array(shape) wcs = (wcs or WCS()) if ((wcs.naxis1 == 1.0) and (wcs.naxis2 == 1.0)): wcs.naxis1 = shape[1] wcs.naxis2 = shape[0] elif ((wcs.naxis1 != 0.0) or (wcs.naxis2 != 0.0)): shape[1] = wcs.naxis1 shape[0] = wcs.naxis2 if (moffat is not None): center = moffat.center flux = moffat.flux fwhm = moffat.fwhm peak = False n = moffat.n rot = moffat.rot cont = moffat.cont fwhm = np.array(fwhm) a = (fwhm[0] / (2 * np.sqrt(((2 ** (1.0 / n)) - 1.0)))) e = (fwhm[1] / fwhm[0]) if (unit_fwhm is not None): a = (a / wcs.get_step(unit=unit_fwhm)[0]) if peak: norm = flux else: norm = ((flux * (n - 1)) / (((np.pi * a) * a) * e)) if (center is None): center = np.array([((shape[0] - 1) / 2.0), ((shape[1] - 1) / 2.0)]) elif (unit_center is not None): center = wcs.sky2pix(center, unit=unit_center)[0] theta = ((np.pi * rot) / 180.0) def moffat(p, q): cost = np.cos(theta) sint = np.sin(theta) xdiff = (p - center[0]) ydiff = (q - center[1]) return (norm * (((1 + ((((xdiff * cost) - (ydiff * sint)) / a) ** 2)) + (((((xdiff * sint) + (ydiff * cost)) / a) / e) ** 2)) ** (- n))) if (factor > 1): (X, Y) = np.meshgrid(range((shape[0] * factor)), range((shape[1] * factor))) factor = float(factor) pixcrd = np.array(list(zip((X.ravel() / factor), (Y.ravel() / factor)))) data = moffat(pixcrd[(:, 0)], pixcrd[(:, 1)]) data = ((data.reshape(shape[1], factor, shape[0], factor).sum(1).sum(2) / factor) / factor).T else: (yy, xx) = np.mgrid[(:shape[0], :shape[1])] data = moffat(yy, xx) return Image(data=(data + cont), wcs=wcs, unit=unit, copy=False, dtype=None)
Create a new image from a 2D Moffat function. Parameters ---------- shape : int or (int,int) Lengths of the image in Y and X with python notation: (ny,nx). (101,101) by default. If wcs object contains dimensions, shape is ignored and wcs dimensions are used. wcs : `mpdaf.obj.WCS` World coordinates. factor : int If factor<=1, moffat value is computed in the center of each pixel. If factor>1, for each pixel, moffat value is the sum of the moffat values on the factor*factor pixels divided by the pixel area. moffat : `mpdaf.obj.Moffat2D` object that contains all moffat parameters. If it is present, following parameters are not used. center : (float,float) Peak center (x_peak, y_peak). The unit is genven byt the parameter unit_center (degrees by default). If None the center of the image is used. flux : float Integrated gaussian flux or gaussian peak value if peak is True. fwhm : (float,float) Gaussian fwhm (fwhm_y,fwhm_x). The unit is given by the parameter unit_fwhm (arcseconds by default) peak : bool If true, flux contains a gaussian peak value. n : int Atmospheric scattering coefficient. 2 by default. rot : float Angle position in degree. cont : float Continuum value. 0 by default. unit_center : `astropy.units.Unit` type of the center and position coordinates. Degrees by default (use None for coordinates in pixels). unit_fwhm : `astropy.units.Unit` FWHM unit. Arcseconds by default (use None for radius in pixels) Returns ------- out : `~mpdaf.obj.Image`
lib/mpdaf/obj/image.py
moffat_image
musevlt/mpdaf
4
python
def moffat_image(shape=(101, 101), wcs=None, factor=1, moffat=None, center=None, flux=1.0, fwhm=(1.0, 1.0), peak=False, n=2, rot=0.0, cont=0, unit_center=u.deg, unit_fwhm=u.arcsec, unit=u.dimensionless_unscaled): 'Create a new image from a 2D Moffat function.\n\n Parameters\n ----------\n shape : int or (int,int)\n Lengths of the image in Y and X with python notation: (ny,nx).\n (101,101) by default. If wcs object contains dimensions, shape is\n ignored and wcs dimensions are used.\n wcs : `mpdaf.obj.WCS`\n World coordinates.\n factor : int\n If factor<=1, moffat value is computed in the center of each pixel.\n If factor>1, for each pixel, moffat value is the sum\n of the moffat values on the factor*factor pixels divided\n by the pixel area.\n moffat : `mpdaf.obj.Moffat2D`\n object that contains all moffat parameters.\n If it is present, following parameters are not used.\n center : (float,float)\n Peak center (x_peak, y_peak). The unit is genven byt the parameter\n unit_center (degrees by default). If None the center of the image is\n used.\n flux : float\n Integrated gaussian flux or gaussian peak value\n if peak is True.\n fwhm : (float,float)\n Gaussian fwhm (fwhm_y,fwhm_x).\n The unit is given by the parameter unit_fwhm (arcseconds by default)\n peak : bool\n If true, flux contains a gaussian peak value.\n n : int\n Atmospheric scattering coefficient. 2 by default.\n rot : float\n Angle position in degree.\n cont : float\n Continuum value. 0 by default.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_fwhm : `astropy.units.Unit`\n FWHM unit. Arcseconds by default (use None for radius in pixels)\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' n = float(n) if is_int(shape): shape = (shape, shape) shape = np.array(shape) wcs = (wcs or WCS()) if ((wcs.naxis1 == 1.0) and (wcs.naxis2 == 1.0)): wcs.naxis1 = shape[1] wcs.naxis2 = shape[0] elif ((wcs.naxis1 != 0.0) or (wcs.naxis2 != 0.0)): shape[1] = wcs.naxis1 shape[0] = wcs.naxis2 if (moffat is not None): center = moffat.center flux = moffat.flux fwhm = moffat.fwhm peak = False n = moffat.n rot = moffat.rot cont = moffat.cont fwhm = np.array(fwhm) a = (fwhm[0] / (2 * np.sqrt(((2 ** (1.0 / n)) - 1.0)))) e = (fwhm[1] / fwhm[0]) if (unit_fwhm is not None): a = (a / wcs.get_step(unit=unit_fwhm)[0]) if peak: norm = flux else: norm = ((flux * (n - 1)) / (((np.pi * a) * a) * e)) if (center is None): center = np.array([((shape[0] - 1) / 2.0), ((shape[1] - 1) / 2.0)]) elif (unit_center is not None): center = wcs.sky2pix(center, unit=unit_center)[0] theta = ((np.pi * rot) / 180.0) def moffat(p, q): cost = np.cos(theta) sint = np.sin(theta) xdiff = (p - center[0]) ydiff = (q - center[1]) return (norm * (((1 + ((((xdiff * cost) - (ydiff * sint)) / a) ** 2)) + (((((xdiff * sint) + (ydiff * cost)) / a) / e) ** 2)) ** (- n))) if (factor > 1): (X, Y) = np.meshgrid(range((shape[0] * factor)), range((shape[1] * factor))) factor = float(factor) pixcrd = np.array(list(zip((X.ravel() / factor), (Y.ravel() / factor)))) data = moffat(pixcrd[(:, 0)], pixcrd[(:, 1)]) data = ((data.reshape(shape[1], factor, shape[0], factor).sum(1).sum(2) / factor) / factor).T else: (yy, xx) = np.mgrid[(:shape[0], :shape[1])] data = moffat(yy, xx) return Image(data=(data + cont), wcs=wcs, unit=unit, copy=False, dtype=None)
def moffat_image(shape=(101, 101), wcs=None, factor=1, moffat=None, center=None, flux=1.0, fwhm=(1.0, 1.0), peak=False, n=2, rot=0.0, cont=0, unit_center=u.deg, unit_fwhm=u.arcsec, unit=u.dimensionless_unscaled): 'Create a new image from a 2D Moffat function.\n\n Parameters\n ----------\n shape : int or (int,int)\n Lengths of the image in Y and X with python notation: (ny,nx).\n (101,101) by default. If wcs object contains dimensions, shape is\n ignored and wcs dimensions are used.\n wcs : `mpdaf.obj.WCS`\n World coordinates.\n factor : int\n If factor<=1, moffat value is computed in the center of each pixel.\n If factor>1, for each pixel, moffat value is the sum\n of the moffat values on the factor*factor pixels divided\n by the pixel area.\n moffat : `mpdaf.obj.Moffat2D`\n object that contains all moffat parameters.\n If it is present, following parameters are not used.\n center : (float,float)\n Peak center (x_peak, y_peak). The unit is genven byt the parameter\n unit_center (degrees by default). If None the center of the image is\n used.\n flux : float\n Integrated gaussian flux or gaussian peak value\n if peak is True.\n fwhm : (float,float)\n Gaussian fwhm (fwhm_y,fwhm_x).\n The unit is given by the parameter unit_fwhm (arcseconds by default)\n peak : bool\n If true, flux contains a gaussian peak value.\n n : int\n Atmospheric scattering coefficient. 2 by default.\n rot : float\n Angle position in degree.\n cont : float\n Continuum value. 0 by default.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_fwhm : `astropy.units.Unit`\n FWHM unit. Arcseconds by default (use None for radius in pixels)\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' n = float(n) if is_int(shape): shape = (shape, shape) shape = np.array(shape) wcs = (wcs or WCS()) if ((wcs.naxis1 == 1.0) and (wcs.naxis2 == 1.0)): wcs.naxis1 = shape[1] wcs.naxis2 = shape[0] elif ((wcs.naxis1 != 0.0) or (wcs.naxis2 != 0.0)): shape[1] = wcs.naxis1 shape[0] = wcs.naxis2 if (moffat is not None): center = moffat.center flux = moffat.flux fwhm = moffat.fwhm peak = False n = moffat.n rot = moffat.rot cont = moffat.cont fwhm = np.array(fwhm) a = (fwhm[0] / (2 * np.sqrt(((2 ** (1.0 / n)) - 1.0)))) e = (fwhm[1] / fwhm[0]) if (unit_fwhm is not None): a = (a / wcs.get_step(unit=unit_fwhm)[0]) if peak: norm = flux else: norm = ((flux * (n - 1)) / (((np.pi * a) * a) * e)) if (center is None): center = np.array([((shape[0] - 1) / 2.0), ((shape[1] - 1) / 2.0)]) elif (unit_center is not None): center = wcs.sky2pix(center, unit=unit_center)[0] theta = ((np.pi * rot) / 180.0) def moffat(p, q): cost = np.cos(theta) sint = np.sin(theta) xdiff = (p - center[0]) ydiff = (q - center[1]) return (norm * (((1 + ((((xdiff * cost) - (ydiff * sint)) / a) ** 2)) + (((((xdiff * sint) + (ydiff * cost)) / a) / e) ** 2)) ** (- n))) if (factor > 1): (X, Y) = np.meshgrid(range((shape[0] * factor)), range((shape[1] * factor))) factor = float(factor) pixcrd = np.array(list(zip((X.ravel() / factor), (Y.ravel() / factor)))) data = moffat(pixcrd[(:, 0)], pixcrd[(:, 1)]) data = ((data.reshape(shape[1], factor, shape[0], factor).sum(1).sum(2) / factor) / factor).T else: (yy, xx) = np.mgrid[(:shape[0], :shape[1])] data = moffat(yy, xx) return Image(data=(data + cont), wcs=wcs, unit=unit, copy=False, dtype=None)<|docstring|>Create a new image from a 2D Moffat function. Parameters ---------- shape : int or (int,int) Lengths of the image in Y and X with python notation: (ny,nx). (101,101) by default. If wcs object contains dimensions, shape is ignored and wcs dimensions are used. wcs : `mpdaf.obj.WCS` World coordinates. factor : int If factor<=1, moffat value is computed in the center of each pixel. If factor>1, for each pixel, moffat value is the sum of the moffat values on the factor*factor pixels divided by the pixel area. moffat : `mpdaf.obj.Moffat2D` object that contains all moffat parameters. If it is present, following parameters are not used. center : (float,float) Peak center (x_peak, y_peak). The unit is genven byt the parameter unit_center (degrees by default). If None the center of the image is used. flux : float Integrated gaussian flux or gaussian peak value if peak is True. fwhm : (float,float) Gaussian fwhm (fwhm_y,fwhm_x). The unit is given by the parameter unit_fwhm (arcseconds by default) peak : bool If true, flux contains a gaussian peak value. n : int Atmospheric scattering coefficient. 2 by default. rot : float Angle position in degree. cont : float Continuum value. 0 by default. unit_center : `astropy.units.Unit` type of the center and position coordinates. Degrees by default (use None for coordinates in pixels). unit_fwhm : `astropy.units.Unit` FWHM unit. Arcseconds by default (use None for radius in pixels) Returns ------- out : `~mpdaf.obj.Image`<|endoftext|>
1313520c0591c3193254dbb398ca62ac5a02f9d5c84dd4d64add07d7b94bc2b6
def _antialias_filter_image(data, oldstep, newstep, oldfmax=None, window='blackman'): 'Apply an anti-aliasing prefilter to an image to prepare\n it for subsampling.\n\n Parameters\n ----------\n data : np.ndimage\n The 2D image to be filtered.\n oldstep: float or (float, float)\n The cell size of the input image. This can be a single\n number for both the X and Y axes, or it can be two\n numbers in an iterable, ordered like (ystep,xstep)\n newstep: float or (float, float)\n The cell size of the output image. This can be a single\n number for both the X and Y axes, or it can be two\n numbers in an iterable, ordered like (ystep,xstep)\n oldfmax : float,float or None\n When an image has previously been filtered, this\n argument can be used to indicate the frequency cutoffs\n that were applied at that time along the Y and X axes,\n respectively, in units of cycles per the unit of oldstep\n and newstep. Image axes that have already been sufficiently\n filtered will then not be refiltered redundantly. If no\n band-limits have previously been established, pass this\n argument as None.\n window : str\n The type of window function to use to filter the\n FFT, chosen from:\n\n blackman\n This window suppresses ringing better than any other\n window, at the expense of lowered image resolution. In\n the image plane, the PSF of this window is\n approximately gaussian, with a standard deviation of\n around 0.96*newstep, and a FWHM of about 2.3*newstep.\n\n gaussian\n A truncated gaussian window. This has a smaller PSF\n than the blackman window, however gaussians never fall\n to zero, so either significant ringing will be seen due\n to truncation of the gaussian, or low-level aliasing\n will occur, depending on the spatial frequency coverage\n of the image beyond the folding frequency. It can be a\n good choice for images that only contain smoothly\n varying features. It is equivalent to a convolution of\n the image with both an airy profile and a gaussian of\n standard deviation 0.724*newstep (FWHM 1.704*newstep).\n\n rectangle\n This window simply zeros all spatial frequencies above\n the highest that can be correctly sampled by the new\n pixel size. This gives the best resolution of any of\n the windows, but this is marred by the strong sidelobes\n of the resulting airy-profile, especially near bright\n point sources and CCD saturation lines.\n\n Returns\n -------\n out : numpy.ndarray, numpy.ndarray\n The filtered version of the 2D input image, followed by\n a 2-element array that contains the new band-limits\n along the Y and X axes, respectively.\n\n ' if is_number(oldstep): oldstep = (oldstep, oldstep) oldstep = abs(np.asarray(oldstep, dtype=float)) if is_number(newstep): newstep = (newstep, newstep) newstep = abs(np.asarray(newstep, dtype=float)) if (oldfmax is None): oldfmax = (0.5 / oldstep) else: oldfmax = np.minimum(oldfmax, (0.5 / oldstep)) newfmax = (0.5 / newstep) filter_axes = (newfmax < oldfmax) if np.all(np.logical_not(filter_axes)): return (data, oldfmax) image_slice = (slice(0, data.shape[0]), slice(0, data.shape[1])) shape = (2 ** np.ceil((np.log(np.asarray(data.shape)) / np.log(2.0))).astype(int)) if ((data.shape[0] != shape[0]) or (data.shape[1] != shape[1])): tmp = np.zeros(shape) tmp[image_slice] = data data = tmp (ny, nx) = shape fft = np.fft.rfft2(data) del data (fycut, fxcut) = newfmax wr = np.sqrt((((np.fft.rfftfreq(nx, oldstep[1]) / fxcut) ** 2) + ((np.fft.fftfreq(ny, oldstep[0]) / fycut)[(np.newaxis, :)].T ** 2))) if ((window is None) or (window == 'blackman')): winfn = (lambda r: np.where((r <= 1.0), ((0.42 + (0.5 * np.cos((np.pi * r)))) + (0.08 * np.cos(((2 * np.pi) * r)))), 0.0)) elif (window == 'gaussian'): sigma = 0.44 winfn = (lambda r: np.exp(((- 0.5) * ((r / sigma) ** 2)))) elif (window == 'rectangle'): winfn = (lambda r: np.where((r <= 1.0), 1.0, 0.0)) fft *= winfn(wr) del wr data = np.fft.irfft2(fft) del fft return (data[image_slice], np.where(filter_axes, newfmax, oldfmax))
Apply an anti-aliasing prefilter to an image to prepare it for subsampling. Parameters ---------- data : np.ndimage The 2D image to be filtered. oldstep: float or (float, float) The cell size of the input image. This can be a single number for both the X and Y axes, or it can be two numbers in an iterable, ordered like (ystep,xstep) newstep: float or (float, float) The cell size of the output image. This can be a single number for both the X and Y axes, or it can be two numbers in an iterable, ordered like (ystep,xstep) oldfmax : float,float or None When an image has previously been filtered, this argument can be used to indicate the frequency cutoffs that were applied at that time along the Y and X axes, respectively, in units of cycles per the unit of oldstep and newstep. Image axes that have already been sufficiently filtered will then not be refiltered redundantly. If no band-limits have previously been established, pass this argument as None. window : str The type of window function to use to filter the FFT, chosen from: blackman This window suppresses ringing better than any other window, at the expense of lowered image resolution. In the image plane, the PSF of this window is approximately gaussian, with a standard deviation of around 0.96*newstep, and a FWHM of about 2.3*newstep. gaussian A truncated gaussian window. This has a smaller PSF than the blackman window, however gaussians never fall to zero, so either significant ringing will be seen due to truncation of the gaussian, or low-level aliasing will occur, depending on the spatial frequency coverage of the image beyond the folding frequency. It can be a good choice for images that only contain smoothly varying features. It is equivalent to a convolution of the image with both an airy profile and a gaussian of standard deviation 0.724*newstep (FWHM 1.704*newstep). rectangle This window simply zeros all spatial frequencies above the highest that can be correctly sampled by the new pixel size. This gives the best resolution of any of the windows, but this is marred by the strong sidelobes of the resulting airy-profile, especially near bright point sources and CCD saturation lines. Returns ------- out : numpy.ndarray, numpy.ndarray The filtered version of the 2D input image, followed by a 2-element array that contains the new band-limits along the Y and X axes, respectively.
lib/mpdaf/obj/image.py
_antialias_filter_image
musevlt/mpdaf
4
python
def _antialias_filter_image(data, oldstep, newstep, oldfmax=None, window='blackman'): 'Apply an anti-aliasing prefilter to an image to prepare\n it for subsampling.\n\n Parameters\n ----------\n data : np.ndimage\n The 2D image to be filtered.\n oldstep: float or (float, float)\n The cell size of the input image. This can be a single\n number for both the X and Y axes, or it can be two\n numbers in an iterable, ordered like (ystep,xstep)\n newstep: float or (float, float)\n The cell size of the output image. This can be a single\n number for both the X and Y axes, or it can be two\n numbers in an iterable, ordered like (ystep,xstep)\n oldfmax : float,float or None\n When an image has previously been filtered, this\n argument can be used to indicate the frequency cutoffs\n that were applied at that time along the Y and X axes,\n respectively, in units of cycles per the unit of oldstep\n and newstep. Image axes that have already been sufficiently\n filtered will then not be refiltered redundantly. If no\n band-limits have previously been established, pass this\n argument as None.\n window : str\n The type of window function to use to filter the\n FFT, chosen from:\n\n blackman\n This window suppresses ringing better than any other\n window, at the expense of lowered image resolution. In\n the image plane, the PSF of this window is\n approximately gaussian, with a standard deviation of\n around 0.96*newstep, and a FWHM of about 2.3*newstep.\n\n gaussian\n A truncated gaussian window. This has a smaller PSF\n than the blackman window, however gaussians never fall\n to zero, so either significant ringing will be seen due\n to truncation of the gaussian, or low-level aliasing\n will occur, depending on the spatial frequency coverage\n of the image beyond the folding frequency. It can be a\n good choice for images that only contain smoothly\n varying features. It is equivalent to a convolution of\n the image with both an airy profile and a gaussian of\n standard deviation 0.724*newstep (FWHM 1.704*newstep).\n\n rectangle\n This window simply zeros all spatial frequencies above\n the highest that can be correctly sampled by the new\n pixel size. This gives the best resolution of any of\n the windows, but this is marred by the strong sidelobes\n of the resulting airy-profile, especially near bright\n point sources and CCD saturation lines.\n\n Returns\n -------\n out : numpy.ndarray, numpy.ndarray\n The filtered version of the 2D input image, followed by\n a 2-element array that contains the new band-limits\n along the Y and X axes, respectively.\n\n ' if is_number(oldstep): oldstep = (oldstep, oldstep) oldstep = abs(np.asarray(oldstep, dtype=float)) if is_number(newstep): newstep = (newstep, newstep) newstep = abs(np.asarray(newstep, dtype=float)) if (oldfmax is None): oldfmax = (0.5 / oldstep) else: oldfmax = np.minimum(oldfmax, (0.5 / oldstep)) newfmax = (0.5 / newstep) filter_axes = (newfmax < oldfmax) if np.all(np.logical_not(filter_axes)): return (data, oldfmax) image_slice = (slice(0, data.shape[0]), slice(0, data.shape[1])) shape = (2 ** np.ceil((np.log(np.asarray(data.shape)) / np.log(2.0))).astype(int)) if ((data.shape[0] != shape[0]) or (data.shape[1] != shape[1])): tmp = np.zeros(shape) tmp[image_slice] = data data = tmp (ny, nx) = shape fft = np.fft.rfft2(data) del data (fycut, fxcut) = newfmax wr = np.sqrt((((np.fft.rfftfreq(nx, oldstep[1]) / fxcut) ** 2) + ((np.fft.fftfreq(ny, oldstep[0]) / fycut)[(np.newaxis, :)].T ** 2))) if ((window is None) or (window == 'blackman')): winfn = (lambda r: np.where((r <= 1.0), ((0.42 + (0.5 * np.cos((np.pi * r)))) + (0.08 * np.cos(((2 * np.pi) * r)))), 0.0)) elif (window == 'gaussian'): sigma = 0.44 winfn = (lambda r: np.exp(((- 0.5) * ((r / sigma) ** 2)))) elif (window == 'rectangle'): winfn = (lambda r: np.where((r <= 1.0), 1.0, 0.0)) fft *= winfn(wr) del wr data = np.fft.irfft2(fft) del fft return (data[image_slice], np.where(filter_axes, newfmax, oldfmax))
def _antialias_filter_image(data, oldstep, newstep, oldfmax=None, window='blackman'): 'Apply an anti-aliasing prefilter to an image to prepare\n it for subsampling.\n\n Parameters\n ----------\n data : np.ndimage\n The 2D image to be filtered.\n oldstep: float or (float, float)\n The cell size of the input image. This can be a single\n number for both the X and Y axes, or it can be two\n numbers in an iterable, ordered like (ystep,xstep)\n newstep: float or (float, float)\n The cell size of the output image. This can be a single\n number for both the X and Y axes, or it can be two\n numbers in an iterable, ordered like (ystep,xstep)\n oldfmax : float,float or None\n When an image has previously been filtered, this\n argument can be used to indicate the frequency cutoffs\n that were applied at that time along the Y and X axes,\n respectively, in units of cycles per the unit of oldstep\n and newstep. Image axes that have already been sufficiently\n filtered will then not be refiltered redundantly. If no\n band-limits have previously been established, pass this\n argument as None.\n window : str\n The type of window function to use to filter the\n FFT, chosen from:\n\n blackman\n This window suppresses ringing better than any other\n window, at the expense of lowered image resolution. In\n the image plane, the PSF of this window is\n approximately gaussian, with a standard deviation of\n around 0.96*newstep, and a FWHM of about 2.3*newstep.\n\n gaussian\n A truncated gaussian window. This has a smaller PSF\n than the blackman window, however gaussians never fall\n to zero, so either significant ringing will be seen due\n to truncation of the gaussian, or low-level aliasing\n will occur, depending on the spatial frequency coverage\n of the image beyond the folding frequency. It can be a\n good choice for images that only contain smoothly\n varying features. It is equivalent to a convolution of\n the image with both an airy profile and a gaussian of\n standard deviation 0.724*newstep (FWHM 1.704*newstep).\n\n rectangle\n This window simply zeros all spatial frequencies above\n the highest that can be correctly sampled by the new\n pixel size. This gives the best resolution of any of\n the windows, but this is marred by the strong sidelobes\n of the resulting airy-profile, especially near bright\n point sources and CCD saturation lines.\n\n Returns\n -------\n out : numpy.ndarray, numpy.ndarray\n The filtered version of the 2D input image, followed by\n a 2-element array that contains the new band-limits\n along the Y and X axes, respectively.\n\n ' if is_number(oldstep): oldstep = (oldstep, oldstep) oldstep = abs(np.asarray(oldstep, dtype=float)) if is_number(newstep): newstep = (newstep, newstep) newstep = abs(np.asarray(newstep, dtype=float)) if (oldfmax is None): oldfmax = (0.5 / oldstep) else: oldfmax = np.minimum(oldfmax, (0.5 / oldstep)) newfmax = (0.5 / newstep) filter_axes = (newfmax < oldfmax) if np.all(np.logical_not(filter_axes)): return (data, oldfmax) image_slice = (slice(0, data.shape[0]), slice(0, data.shape[1])) shape = (2 ** np.ceil((np.log(np.asarray(data.shape)) / np.log(2.0))).astype(int)) if ((data.shape[0] != shape[0]) or (data.shape[1] != shape[1])): tmp = np.zeros(shape) tmp[image_slice] = data data = tmp (ny, nx) = shape fft = np.fft.rfft2(data) del data (fycut, fxcut) = newfmax wr = np.sqrt((((np.fft.rfftfreq(nx, oldstep[1]) / fxcut) ** 2) + ((np.fft.fftfreq(ny, oldstep[0]) / fycut)[(np.newaxis, :)].T ** 2))) if ((window is None) or (window == 'blackman')): winfn = (lambda r: np.where((r <= 1.0), ((0.42 + (0.5 * np.cos((np.pi * r)))) + (0.08 * np.cos(((2 * np.pi) * r)))), 0.0)) elif (window == 'gaussian'): sigma = 0.44 winfn = (lambda r: np.exp(((- 0.5) * ((r / sigma) ** 2)))) elif (window == 'rectangle'): winfn = (lambda r: np.where((r <= 1.0), 1.0, 0.0)) fft *= winfn(wr) del wr data = np.fft.irfft2(fft) del fft return (data[image_slice], np.where(filter_axes, newfmax, oldfmax))<|docstring|>Apply an anti-aliasing prefilter to an image to prepare it for subsampling. Parameters ---------- data : np.ndimage The 2D image to be filtered. oldstep: float or (float, float) The cell size of the input image. This can be a single number for both the X and Y axes, or it can be two numbers in an iterable, ordered like (ystep,xstep) newstep: float or (float, float) The cell size of the output image. This can be a single number for both the X and Y axes, or it can be two numbers in an iterable, ordered like (ystep,xstep) oldfmax : float,float or None When an image has previously been filtered, this argument can be used to indicate the frequency cutoffs that were applied at that time along the Y and X axes, respectively, in units of cycles per the unit of oldstep and newstep. Image axes that have already been sufficiently filtered will then not be refiltered redundantly. If no band-limits have previously been established, pass this argument as None. window : str The type of window function to use to filter the FFT, chosen from: blackman This window suppresses ringing better than any other window, at the expense of lowered image resolution. In the image plane, the PSF of this window is approximately gaussian, with a standard deviation of around 0.96*newstep, and a FWHM of about 2.3*newstep. gaussian A truncated gaussian window. This has a smaller PSF than the blackman window, however gaussians never fall to zero, so either significant ringing will be seen due to truncation of the gaussian, or low-level aliasing will occur, depending on the spatial frequency coverage of the image beyond the folding frequency. It can be a good choice for images that only contain smoothly varying features. It is equivalent to a convolution of the image with both an airy profile and a gaussian of standard deviation 0.724*newstep (FWHM 1.704*newstep). rectangle This window simply zeros all spatial frequencies above the highest that can be correctly sampled by the new pixel size. This gives the best resolution of any of the windows, but this is marred by the strong sidelobes of the resulting airy-profile, especially near bright point sources and CCD saturation lines. Returns ------- out : numpy.ndarray, numpy.ndarray The filtered version of the 2D input image, followed by a 2-element array that contains the new band-limits along the Y and X axes, respectively.<|endoftext|>
c1a791cef8948a940b891e6a6069c481066dbdf914d966a2568fdc4e8284d196
def _find_quadratic_peak(y): 'Given an array of 3 numbers in which the first and last numbers are\n less than the central number, determine the array index at which a\n quadratic curve through the 3 points reaches its peak value.\n\n Parameters\n ----------\n y : float,float,float\n The values of the curve at x=0,1,2 respectively. Note that y[1]\n must be greater than both y[0] and y[2]. Otherwise +/- infinity\n will be returned.\n\n Returns\n -------\n xpeak : float\n The floating point array index of the peak of the quadratic. This\n will always be in the range 0.0 to 2.0, provided that y[0]<y[1] and\n y[2]<y[1].\n\n ' a = (((0.5 * y[0]) - y[1]) + (0.5 * y[2])) b = ((((- 1.5) * y[0]) + (2.0 * y[1])) - (0.5 * y[2])) return ((- b) / (2 * a))
Given an array of 3 numbers in which the first and last numbers are less than the central number, determine the array index at which a quadratic curve through the 3 points reaches its peak value. Parameters ---------- y : float,float,float The values of the curve at x=0,1,2 respectively. Note that y[1] must be greater than both y[0] and y[2]. Otherwise +/- infinity will be returned. Returns ------- xpeak : float The floating point array index of the peak of the quadratic. This will always be in the range 0.0 to 2.0, provided that y[0]<y[1] and y[2]<y[1].
lib/mpdaf/obj/image.py
_find_quadratic_peak
musevlt/mpdaf
4
python
def _find_quadratic_peak(y): 'Given an array of 3 numbers in which the first and last numbers are\n less than the central number, determine the array index at which a\n quadratic curve through the 3 points reaches its peak value.\n\n Parameters\n ----------\n y : float,float,float\n The values of the curve at x=0,1,2 respectively. Note that y[1]\n must be greater than both y[0] and y[2]. Otherwise +/- infinity\n will be returned.\n\n Returns\n -------\n xpeak : float\n The floating point array index of the peak of the quadratic. This\n will always be in the range 0.0 to 2.0, provided that y[0]<y[1] and\n y[2]<y[1].\n\n ' a = (((0.5 * y[0]) - y[1]) + (0.5 * y[2])) b = ((((- 1.5) * y[0]) + (2.0 * y[1])) - (0.5 * y[2])) return ((- b) / (2 * a))
def _find_quadratic_peak(y): 'Given an array of 3 numbers in which the first and last numbers are\n less than the central number, determine the array index at which a\n quadratic curve through the 3 points reaches its peak value.\n\n Parameters\n ----------\n y : float,float,float\n The values of the curve at x=0,1,2 respectively. Note that y[1]\n must be greater than both y[0] and y[2]. Otherwise +/- infinity\n will be returned.\n\n Returns\n -------\n xpeak : float\n The floating point array index of the peak of the quadratic. This\n will always be in the range 0.0 to 2.0, provided that y[0]<y[1] and\n y[2]<y[1].\n\n ' a = (((0.5 * y[0]) - y[1]) + (0.5 * y[2])) b = ((((- 1.5) * y[0]) + (2.0 * y[1])) - (0.5 * y[2])) return ((- b) / (2 * a))<|docstring|>Given an array of 3 numbers in which the first and last numbers are less than the central number, determine the array index at which a quadratic curve through the 3 points reaches its peak value. Parameters ---------- y : float,float,float The values of the curve at x=0,1,2 respectively. Note that y[1] must be greater than both y[0] and y[2]. Otherwise +/- infinity will be returned. Returns ------- xpeak : float The floating point array index of the peak of the quadratic. This will always be in the range 0.0 to 2.0, provided that y[0]<y[1] and y[2]<y[1].<|endoftext|>
7199eaf312bdc4c3be02558bfd77f2bbca402f06de164fa755fb8f3012da852c
def copy(self): 'Return a new copy of an Image object.' obj = super(Image, self).copy() if (self._spflims is not None): obj._spflims = self._spflims.deepcopy() return obj
Return a new copy of an Image object.
lib/mpdaf/obj/image.py
copy
musevlt/mpdaf
4
python
def copy(self): obj = super(Image, self).copy() if (self._spflims is not None): obj._spflims = self._spflims.deepcopy() return obj
def copy(self): obj = super(Image, self).copy() if (self._spflims is not None): obj._spflims = self._spflims.deepcopy() return obj<|docstring|>Return a new copy of an Image object.<|endoftext|>
fff9857ada8dddfa7f79900053d75831166c80fd2f6e12568e973203d20ddd5e
def get_step(self, unit=None): "Return the angular height and width of a pixel along the\n Y and X axes of the image array.\n\n In MPDAF, images are sampled on a regular grid of square\n pixels that represent a flat projection of the celestial\n sphere. The get_step() method returns the angular width and\n height of these pixels on the sky.\n\n See also get_axis_increments().\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n The angular units of the returned values.\n\n Returns\n -------\n out : numpy.ndarray\n (dy,dx). These are the angular height and width of pixels\n along the Y and X axes of the image. The returned values are\n either in the unit specified by the 'unit' input parameter,\n or in the unit specified by the self.unit property.\n " if (self.wcs is not None): return self.wcs.get_step(unit)
Return the angular height and width of a pixel along the Y and X axes of the image array. In MPDAF, images are sampled on a regular grid of square pixels that represent a flat projection of the celestial sphere. The get_step() method returns the angular width and height of these pixels on the sky. See also get_axis_increments(). Parameters ---------- unit : `astropy.units.Unit` The angular units of the returned values. Returns ------- out : numpy.ndarray (dy,dx). These are the angular height and width of pixels along the Y and X axes of the image. The returned values are either in the unit specified by the 'unit' input parameter, or in the unit specified by the self.unit property.
lib/mpdaf/obj/image.py
get_step
musevlt/mpdaf
4
python
def get_step(self, unit=None): "Return the angular height and width of a pixel along the\n Y and X axes of the image array.\n\n In MPDAF, images are sampled on a regular grid of square\n pixels that represent a flat projection of the celestial\n sphere. The get_step() method returns the angular width and\n height of these pixels on the sky.\n\n See also get_axis_increments().\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n The angular units of the returned values.\n\n Returns\n -------\n out : numpy.ndarray\n (dy,dx). These are the angular height and width of pixels\n along the Y and X axes of the image. The returned values are\n either in the unit specified by the 'unit' input parameter,\n or in the unit specified by the self.unit property.\n " if (self.wcs is not None): return self.wcs.get_step(unit)
def get_step(self, unit=None): "Return the angular height and width of a pixel along the\n Y and X axes of the image array.\n\n In MPDAF, images are sampled on a regular grid of square\n pixels that represent a flat projection of the celestial\n sphere. The get_step() method returns the angular width and\n height of these pixels on the sky.\n\n See also get_axis_increments().\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n The angular units of the returned values.\n\n Returns\n -------\n out : numpy.ndarray\n (dy,dx). These are the angular height and width of pixels\n along the Y and X axes of the image. The returned values are\n either in the unit specified by the 'unit' input parameter,\n or in the unit specified by the self.unit property.\n " if (self.wcs is not None): return self.wcs.get_step(unit)<|docstring|>Return the angular height and width of a pixel along the Y and X axes of the image array. In MPDAF, images are sampled on a regular grid of square pixels that represent a flat projection of the celestial sphere. The get_step() method returns the angular width and height of these pixels on the sky. See also get_axis_increments(). Parameters ---------- unit : `astropy.units.Unit` The angular units of the returned values. Returns ------- out : numpy.ndarray (dy,dx). These are the angular height and width of pixels along the Y and X axes of the image. The returned values are either in the unit specified by the 'unit' input parameter, or in the unit specified by the self.unit property.<|endoftext|>
1e0469f187e1d230c5919ec16e2a2ac0605e1ecf7cd0562e70a85a707fadc3ee
def get_axis_increments(self, unit=None): "Return the displacements on the sky that result from\n incrementing the array indexes of the image by one along the Y\n and X axes, respectively.\n\n In MPDAF, images are sampled on a regular grid of square\n pixels that represent a flat projection of the celestial\n sphere. The get_axis_increments() method returns the angular\n width and height of these pixels on the sky, with signs that\n indicate whether the angle increases or decreases as one\n increments the array indexes. To keep plots consistent,\n regardless of the rotation angle of the image on the sky, the\n returned height is always positive, but the returned width is\n negative if a plot of the image with pixel 0,0 at the bottom\n left would place east anticlockwise of north, and positive\n otherwise.\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n The angular units of the returned values.\n\n Returns\n -------\n out : numpy.ndarray\n (dy,dx). These are the angular increments of pixels along\n the Y and X axes of the image. The returned values are\n either in the unit specified by the 'unit' input parameter,\n or in the unit specified by the self.unit property.\n\n " if (self.wcs is not None): return self.wcs.get_axis_increments(unit)
Return the displacements on the sky that result from incrementing the array indexes of the image by one along the Y and X axes, respectively. In MPDAF, images are sampled on a regular grid of square pixels that represent a flat projection of the celestial sphere. The get_axis_increments() method returns the angular width and height of these pixels on the sky, with signs that indicate whether the angle increases or decreases as one increments the array indexes. To keep plots consistent, regardless of the rotation angle of the image on the sky, the returned height is always positive, but the returned width is negative if a plot of the image with pixel 0,0 at the bottom left would place east anticlockwise of north, and positive otherwise. Parameters ---------- unit : `astropy.units.Unit` The angular units of the returned values. Returns ------- out : numpy.ndarray (dy,dx). These are the angular increments of pixels along the Y and X axes of the image. The returned values are either in the unit specified by the 'unit' input parameter, or in the unit specified by the self.unit property.
lib/mpdaf/obj/image.py
get_axis_increments
musevlt/mpdaf
4
python
def get_axis_increments(self, unit=None): "Return the displacements on the sky that result from\n incrementing the array indexes of the image by one along the Y\n and X axes, respectively.\n\n In MPDAF, images are sampled on a regular grid of square\n pixels that represent a flat projection of the celestial\n sphere. The get_axis_increments() method returns the angular\n width and height of these pixels on the sky, with signs that\n indicate whether the angle increases or decreases as one\n increments the array indexes. To keep plots consistent,\n regardless of the rotation angle of the image on the sky, the\n returned height is always positive, but the returned width is\n negative if a plot of the image with pixel 0,0 at the bottom\n left would place east anticlockwise of north, and positive\n otherwise.\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n The angular units of the returned values.\n\n Returns\n -------\n out : numpy.ndarray\n (dy,dx). These are the angular increments of pixels along\n the Y and X axes of the image. The returned values are\n either in the unit specified by the 'unit' input parameter,\n or in the unit specified by the self.unit property.\n\n " if (self.wcs is not None): return self.wcs.get_axis_increments(unit)
def get_axis_increments(self, unit=None): "Return the displacements on the sky that result from\n incrementing the array indexes of the image by one along the Y\n and X axes, respectively.\n\n In MPDAF, images are sampled on a regular grid of square\n pixels that represent a flat projection of the celestial\n sphere. The get_axis_increments() method returns the angular\n width and height of these pixels on the sky, with signs that\n indicate whether the angle increases or decreases as one\n increments the array indexes. To keep plots consistent,\n regardless of the rotation angle of the image on the sky, the\n returned height is always positive, but the returned width is\n negative if a plot of the image with pixel 0,0 at the bottom\n left would place east anticlockwise of north, and positive\n otherwise.\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n The angular units of the returned values.\n\n Returns\n -------\n out : numpy.ndarray\n (dy,dx). These are the angular increments of pixels along\n the Y and X axes of the image. The returned values are\n either in the unit specified by the 'unit' input parameter,\n or in the unit specified by the self.unit property.\n\n " if (self.wcs is not None): return self.wcs.get_axis_increments(unit)<|docstring|>Return the displacements on the sky that result from incrementing the array indexes of the image by one along the Y and X axes, respectively. In MPDAF, images are sampled on a regular grid of square pixels that represent a flat projection of the celestial sphere. The get_axis_increments() method returns the angular width and height of these pixels on the sky, with signs that indicate whether the angle increases or decreases as one increments the array indexes. To keep plots consistent, regardless of the rotation angle of the image on the sky, the returned height is always positive, but the returned width is negative if a plot of the image with pixel 0,0 at the bottom left would place east anticlockwise of north, and positive otherwise. Parameters ---------- unit : `astropy.units.Unit` The angular units of the returned values. Returns ------- out : numpy.ndarray (dy,dx). These are the angular increments of pixels along the Y and X axes of the image. The returned values are either in the unit specified by the 'unit' input parameter, or in the unit specified by the self.unit property.<|endoftext|>
c513ef4730fcaaf4f16d452ecbca080a75e9b5d5f762cfa7148719259001e27f
def get_range(self, unit=None): "Return the minimum and maximum right-ascensions and declinations\n in the image array.\n\n Specifically a list is returned with the following contents:\n\n [dec_min, ra_min, dec_max, ra_max]\n\n Note that if the Y axis of the image is not parallel to the\n declination axis, then the 4 returned values will all come\n from different corners of the image. In particular, note that\n this means that the coordinates [dec_min,ra_min] and\n [dec_max,ra_max] will only coincide with pixels in the image\n if the Y axis is aligned with the declination axis. Otherwise\n they will be outside the bounds of the image.\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n The units of the returned angles.\n\n Returns\n -------\n out : numpy.ndarray\n The range of right ascensions and declinations, arranged as\n [dec_min, ra_min, dec_max, ra_max]. The returned values are\n either in the units specified in the 'unit' input parameter,\n or in the units stored in the self.unit property.\n\n\n " if (self.wcs is not None): return self.wcs.get_range(unit)
Return the minimum and maximum right-ascensions and declinations in the image array. Specifically a list is returned with the following contents: [dec_min, ra_min, dec_max, ra_max] Note that if the Y axis of the image is not parallel to the declination axis, then the 4 returned values will all come from different corners of the image. In particular, note that this means that the coordinates [dec_min,ra_min] and [dec_max,ra_max] will only coincide with pixels in the image if the Y axis is aligned with the declination axis. Otherwise they will be outside the bounds of the image. Parameters ---------- unit : `astropy.units.Unit` The units of the returned angles. Returns ------- out : numpy.ndarray The range of right ascensions and declinations, arranged as [dec_min, ra_min, dec_max, ra_max]. The returned values are either in the units specified in the 'unit' input parameter, or in the units stored in the self.unit property.
lib/mpdaf/obj/image.py
get_range
musevlt/mpdaf
4
python
def get_range(self, unit=None): "Return the minimum and maximum right-ascensions and declinations\n in the image array.\n\n Specifically a list is returned with the following contents:\n\n [dec_min, ra_min, dec_max, ra_max]\n\n Note that if the Y axis of the image is not parallel to the\n declination axis, then the 4 returned values will all come\n from different corners of the image. In particular, note that\n this means that the coordinates [dec_min,ra_min] and\n [dec_max,ra_max] will only coincide with pixels in the image\n if the Y axis is aligned with the declination axis. Otherwise\n they will be outside the bounds of the image.\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n The units of the returned angles.\n\n Returns\n -------\n out : numpy.ndarray\n The range of right ascensions and declinations, arranged as\n [dec_min, ra_min, dec_max, ra_max]. The returned values are\n either in the units specified in the 'unit' input parameter,\n or in the units stored in the self.unit property.\n\n\n " if (self.wcs is not None): return self.wcs.get_range(unit)
def get_range(self, unit=None): "Return the minimum and maximum right-ascensions and declinations\n in the image array.\n\n Specifically a list is returned with the following contents:\n\n [dec_min, ra_min, dec_max, ra_max]\n\n Note that if the Y axis of the image is not parallel to the\n declination axis, then the 4 returned values will all come\n from different corners of the image. In particular, note that\n this means that the coordinates [dec_min,ra_min] and\n [dec_max,ra_max] will only coincide with pixels in the image\n if the Y axis is aligned with the declination axis. Otherwise\n they will be outside the bounds of the image.\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n The units of the returned angles.\n\n Returns\n -------\n out : numpy.ndarray\n The range of right ascensions and declinations, arranged as\n [dec_min, ra_min, dec_max, ra_max]. The returned values are\n either in the units specified in the 'unit' input parameter,\n or in the units stored in the self.unit property.\n\n\n " if (self.wcs is not None): return self.wcs.get_range(unit)<|docstring|>Return the minimum and maximum right-ascensions and declinations in the image array. Specifically a list is returned with the following contents: [dec_min, ra_min, dec_max, ra_max] Note that if the Y axis of the image is not parallel to the declination axis, then the 4 returned values will all come from different corners of the image. In particular, note that this means that the coordinates [dec_min,ra_min] and [dec_max,ra_max] will only coincide with pixels in the image if the Y axis is aligned with the declination axis. Otherwise they will be outside the bounds of the image. Parameters ---------- unit : `astropy.units.Unit` The units of the returned angles. Returns ------- out : numpy.ndarray The range of right ascensions and declinations, arranged as [dec_min, ra_min, dec_max, ra_max]. The returned values are either in the units specified in the 'unit' input parameter, or in the units stored in the self.unit property.<|endoftext|>
0de4e2b912a5579c27e301a234bc48b2a168d68e13e84678eba4633f1c403227
def get_start(self, unit=None): 'Return [y,x] corresponding to pixel (0,0).\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n type of the world coordinates\n\n Returns\n -------\n out : float array\n ' if (self.wcs is not None): return self.wcs.get_start(unit)
Return [y,x] corresponding to pixel (0,0). Parameters ---------- unit : `astropy.units.Unit` type of the world coordinates Returns ------- out : float array
lib/mpdaf/obj/image.py
get_start
musevlt/mpdaf
4
python
def get_start(self, unit=None): 'Return [y,x] corresponding to pixel (0,0).\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n type of the world coordinates\n\n Returns\n -------\n out : float array\n ' if (self.wcs is not None): return self.wcs.get_start(unit)
def get_start(self, unit=None): 'Return [y,x] corresponding to pixel (0,0).\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n type of the world coordinates\n\n Returns\n -------\n out : float array\n ' if (self.wcs is not None): return self.wcs.get_start(unit)<|docstring|>Return [y,x] corresponding to pixel (0,0). Parameters ---------- unit : `astropy.units.Unit` type of the world coordinates Returns ------- out : float array<|endoftext|>
71be15f4c8fbb29b845243c9d233d2a0ce1909987ef3441e7fe5b97db3fdc7f3
def get_end(self, unit=None): 'Return [y,x] corresponding to pixel (-1,-1).\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n type of the world coordinates\n\n Returns\n -------\n out : float array\n ' if (self.wcs is not None): return self.wcs.get_end(unit)
Return [y,x] corresponding to pixel (-1,-1). Parameters ---------- unit : `astropy.units.Unit` type of the world coordinates Returns ------- out : float array
lib/mpdaf/obj/image.py
get_end
musevlt/mpdaf
4
python
def get_end(self, unit=None): 'Return [y,x] corresponding to pixel (-1,-1).\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n type of the world coordinates\n\n Returns\n -------\n out : float array\n ' if (self.wcs is not None): return self.wcs.get_end(unit)
def get_end(self, unit=None): 'Return [y,x] corresponding to pixel (-1,-1).\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n type of the world coordinates\n\n Returns\n -------\n out : float array\n ' if (self.wcs is not None): return self.wcs.get_end(unit)<|docstring|>Return [y,x] corresponding to pixel (-1,-1). Parameters ---------- unit : `astropy.units.Unit` type of the world coordinates Returns ------- out : float array<|endoftext|>
88df5816365793a84653588b6537cc57f06ade138f6a4a72a40e0dca149c66d8
def get_rot(self, unit=u.deg): 'Return the rotation angle of the image, defined such that a\n rotation angle of zero aligns north along the positive Y axis,\n and a positive rotation angle rotates north away from the Y\n axis, in the sense of a rotation from north to east.\n\n Note that the rotation angle is defined in a flat\n map-projection of the sky. It is what would be seen if\n the pixels of the image were drawn with their pixel\n widths scaled by the angular pixel increments returned\n by the get_axis_increments() method.\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n The unit to give the returned angle (degrees by default).\n\n Returns\n -------\n out : float\n The angle between celestial north and the Y axis of\n the image, in the sense of an eastward rotation of\n celestial north from the Y-axis.\n\n ' if (self.wcs is not None): return self.wcs.get_rot(unit)
Return the rotation angle of the image, defined such that a rotation angle of zero aligns north along the positive Y axis, and a positive rotation angle rotates north away from the Y axis, in the sense of a rotation from north to east. Note that the rotation angle is defined in a flat map-projection of the sky. It is what would be seen if the pixels of the image were drawn with their pixel widths scaled by the angular pixel increments returned by the get_axis_increments() method. Parameters ---------- unit : `astropy.units.Unit` The unit to give the returned angle (degrees by default). Returns ------- out : float The angle between celestial north and the Y axis of the image, in the sense of an eastward rotation of celestial north from the Y-axis.
lib/mpdaf/obj/image.py
get_rot
musevlt/mpdaf
4
python
def get_rot(self, unit=u.deg): 'Return the rotation angle of the image, defined such that a\n rotation angle of zero aligns north along the positive Y axis,\n and a positive rotation angle rotates north away from the Y\n axis, in the sense of a rotation from north to east.\n\n Note that the rotation angle is defined in a flat\n map-projection of the sky. It is what would be seen if\n the pixels of the image were drawn with their pixel\n widths scaled by the angular pixel increments returned\n by the get_axis_increments() method.\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n The unit to give the returned angle (degrees by default).\n\n Returns\n -------\n out : float\n The angle between celestial north and the Y axis of\n the image, in the sense of an eastward rotation of\n celestial north from the Y-axis.\n\n ' if (self.wcs is not None): return self.wcs.get_rot(unit)
def get_rot(self, unit=u.deg): 'Return the rotation angle of the image, defined such that a\n rotation angle of zero aligns north along the positive Y axis,\n and a positive rotation angle rotates north away from the Y\n axis, in the sense of a rotation from north to east.\n\n Note that the rotation angle is defined in a flat\n map-projection of the sky. It is what would be seen if\n the pixels of the image were drawn with their pixel\n widths scaled by the angular pixel increments returned\n by the get_axis_increments() method.\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n The unit to give the returned angle (degrees by default).\n\n Returns\n -------\n out : float\n The angle between celestial north and the Y axis of\n the image, in the sense of an eastward rotation of\n celestial north from the Y-axis.\n\n ' if (self.wcs is not None): return self.wcs.get_rot(unit)<|docstring|>Return the rotation angle of the image, defined such that a rotation angle of zero aligns north along the positive Y axis, and a positive rotation angle rotates north away from the Y axis, in the sense of a rotation from north to east. Note that the rotation angle is defined in a flat map-projection of the sky. It is what would be seen if the pixels of the image were drawn with their pixel widths scaled by the angular pixel increments returned by the get_axis_increments() method. Parameters ---------- unit : `astropy.units.Unit` The unit to give the returned angle (degrees by default). Returns ------- out : float The angle between celestial north and the Y axis of the image, in the sense of an eastward rotation of celestial north from the Y-axis.<|endoftext|>
43249c194d221f552ed63c2231553f453dc7226c1357d8170381fec578d66a8f
def mask_region(self, center, radius, unit_center=u.deg, unit_radius=u.arcsec, inside=True, posangle=0.0): 'Mask values inside or outside a circular or rectangular region.\n\n Parameters\n ----------\n center : (float,float)\n Center (y,x) of the region, where y,x are usually celestial\n coordinates along the Y and X axes of the image, but are\n interpretted as Y,X array-indexes if unit_center is changed\n to None.\n radius : float or (float,float)\n The radius of a circular region, or the half-width and\n half-height of a rectangular region, respectively.\n unit_center : `astropy.units.Unit`\n The units of the coordinates of the center argument\n (degrees by default). If None, the units of the center\n argument are assumed to be pixels.\n unit_radius : `astropy.units.Unit`\n The units of the radius argument (arcseconds by default).\n If None, the units are assumed to be pixels.\n inside : bool\n If inside is True, pixels inside the region are masked.\n If inside is False, pixels outside the region are masked.\n posangle : float\n When the region is rectangular, this is the counter-clockwise\n rotation angle of the rectangle in degrees. When posangle is\n 0.0 (the default), the X and Y axes of the ellipse are along\n the X and Y axes of the image.\n\n ' center = np.array(center) if np.isscalar(radius): return self.mask_ellipse(center=center, radius=radius, posangle=0.0, unit_center=unit_center, unit_radius=unit_radius, inside=inside) if (unit_center is not None): center = self.wcs.sky2pix(center, unit=unit_center)[0] if (unit_radius is None): step = np.array([1.0, 1.0]) else: step = self.wcs.get_step(unit=unit_radius) if (not np.isclose(posangle, 0.0)): cos = np.cos(np.radians(posangle)) sin = np.sin(np.radians(posangle)) (hw, hh) = radius poly = np.array([[(((- hw) * sin) - (hh * cos)), (((- hw) * cos) + (hh * sin))], [(((- hw) * sin) + (hh * cos)), (((- hw) * cos) - (hh * sin))], [(((+ hw) * sin) + (hh * cos)), (((+ hw) * cos) - (hh * sin))], [(((+ hw) * sin) - (hh * cos)), (((+ hw) * cos) + (hh * sin))]]) return self.mask_polygon(((poly / step) + center), unit=None, inside=inside) (sy, sx) = bounding_box(form='rectangle', center=center, radii=radius, shape=self.shape, step=step)[0] if inside: self.data[(sy, sx)] = np.ma.masked else: self.data[(0:sy.start, :)] = np.ma.masked self.data[(sy.stop:, :)] = np.ma.masked self.data[(sy, 0:sx.start)] = np.ma.masked self.data[(sy, sx.stop:)] = np.ma.masked
Mask values inside or outside a circular or rectangular region. Parameters ---------- center : (float,float) Center (y,x) of the region, where y,x are usually celestial coordinates along the Y and X axes of the image, but are interpretted as Y,X array-indexes if unit_center is changed to None. radius : float or (float,float) The radius of a circular region, or the half-width and half-height of a rectangular region, respectively. unit_center : `astropy.units.Unit` The units of the coordinates of the center argument (degrees by default). If None, the units of the center argument are assumed to be pixels. unit_radius : `astropy.units.Unit` The units of the radius argument (arcseconds by default). If None, the units are assumed to be pixels. inside : bool If inside is True, pixels inside the region are masked. If inside is False, pixels outside the region are masked. posangle : float When the region is rectangular, this is the counter-clockwise rotation angle of the rectangle in degrees. When posangle is 0.0 (the default), the X and Y axes of the ellipse are along the X and Y axes of the image.
lib/mpdaf/obj/image.py
mask_region
musevlt/mpdaf
4
python
def mask_region(self, center, radius, unit_center=u.deg, unit_radius=u.arcsec, inside=True, posangle=0.0): 'Mask values inside or outside a circular or rectangular region.\n\n Parameters\n ----------\n center : (float,float)\n Center (y,x) of the region, where y,x are usually celestial\n coordinates along the Y and X axes of the image, but are\n interpretted as Y,X array-indexes if unit_center is changed\n to None.\n radius : float or (float,float)\n The radius of a circular region, or the half-width and\n half-height of a rectangular region, respectively.\n unit_center : `astropy.units.Unit`\n The units of the coordinates of the center argument\n (degrees by default). If None, the units of the center\n argument are assumed to be pixels.\n unit_radius : `astropy.units.Unit`\n The units of the radius argument (arcseconds by default).\n If None, the units are assumed to be pixels.\n inside : bool\n If inside is True, pixels inside the region are masked.\n If inside is False, pixels outside the region are masked.\n posangle : float\n When the region is rectangular, this is the counter-clockwise\n rotation angle of the rectangle in degrees. When posangle is\n 0.0 (the default), the X and Y axes of the ellipse are along\n the X and Y axes of the image.\n\n ' center = np.array(center) if np.isscalar(radius): return self.mask_ellipse(center=center, radius=radius, posangle=0.0, unit_center=unit_center, unit_radius=unit_radius, inside=inside) if (unit_center is not None): center = self.wcs.sky2pix(center, unit=unit_center)[0] if (unit_radius is None): step = np.array([1.0, 1.0]) else: step = self.wcs.get_step(unit=unit_radius) if (not np.isclose(posangle, 0.0)): cos = np.cos(np.radians(posangle)) sin = np.sin(np.radians(posangle)) (hw, hh) = radius poly = np.array([[(((- hw) * sin) - (hh * cos)), (((- hw) * cos) + (hh * sin))], [(((- hw) * sin) + (hh * cos)), (((- hw) * cos) - (hh * sin))], [(((+ hw) * sin) + (hh * cos)), (((+ hw) * cos) - (hh * sin))], [(((+ hw) * sin) - (hh * cos)), (((+ hw) * cos) + (hh * sin))]]) return self.mask_polygon(((poly / step) + center), unit=None, inside=inside) (sy, sx) = bounding_box(form='rectangle', center=center, radii=radius, shape=self.shape, step=step)[0] if inside: self.data[(sy, sx)] = np.ma.masked else: self.data[(0:sy.start, :)] = np.ma.masked self.data[(sy.stop:, :)] = np.ma.masked self.data[(sy, 0:sx.start)] = np.ma.masked self.data[(sy, sx.stop:)] = np.ma.masked
def mask_region(self, center, radius, unit_center=u.deg, unit_radius=u.arcsec, inside=True, posangle=0.0): 'Mask values inside or outside a circular or rectangular region.\n\n Parameters\n ----------\n center : (float,float)\n Center (y,x) of the region, where y,x are usually celestial\n coordinates along the Y and X axes of the image, but are\n interpretted as Y,X array-indexes if unit_center is changed\n to None.\n radius : float or (float,float)\n The radius of a circular region, or the half-width and\n half-height of a rectangular region, respectively.\n unit_center : `astropy.units.Unit`\n The units of the coordinates of the center argument\n (degrees by default). If None, the units of the center\n argument are assumed to be pixels.\n unit_radius : `astropy.units.Unit`\n The units of the radius argument (arcseconds by default).\n If None, the units are assumed to be pixels.\n inside : bool\n If inside is True, pixels inside the region are masked.\n If inside is False, pixels outside the region are masked.\n posangle : float\n When the region is rectangular, this is the counter-clockwise\n rotation angle of the rectangle in degrees. When posangle is\n 0.0 (the default), the X and Y axes of the ellipse are along\n the X and Y axes of the image.\n\n ' center = np.array(center) if np.isscalar(radius): return self.mask_ellipse(center=center, radius=radius, posangle=0.0, unit_center=unit_center, unit_radius=unit_radius, inside=inside) if (unit_center is not None): center = self.wcs.sky2pix(center, unit=unit_center)[0] if (unit_radius is None): step = np.array([1.0, 1.0]) else: step = self.wcs.get_step(unit=unit_radius) if (not np.isclose(posangle, 0.0)): cos = np.cos(np.radians(posangle)) sin = np.sin(np.radians(posangle)) (hw, hh) = radius poly = np.array([[(((- hw) * sin) - (hh * cos)), (((- hw) * cos) + (hh * sin))], [(((- hw) * sin) + (hh * cos)), (((- hw) * cos) - (hh * sin))], [(((+ hw) * sin) + (hh * cos)), (((+ hw) * cos) - (hh * sin))], [(((+ hw) * sin) - (hh * cos)), (((+ hw) * cos) + (hh * sin))]]) return self.mask_polygon(((poly / step) + center), unit=None, inside=inside) (sy, sx) = bounding_box(form='rectangle', center=center, radii=radius, shape=self.shape, step=step)[0] if inside: self.data[(sy, sx)] = np.ma.masked else: self.data[(0:sy.start, :)] = np.ma.masked self.data[(sy.stop:, :)] = np.ma.masked self.data[(sy, 0:sx.start)] = np.ma.masked self.data[(sy, sx.stop:)] = np.ma.masked<|docstring|>Mask values inside or outside a circular or rectangular region. Parameters ---------- center : (float,float) Center (y,x) of the region, where y,x are usually celestial coordinates along the Y and X axes of the image, but are interpretted as Y,X array-indexes if unit_center is changed to None. radius : float or (float,float) The radius of a circular region, or the half-width and half-height of a rectangular region, respectively. unit_center : `astropy.units.Unit` The units of the coordinates of the center argument (degrees by default). If None, the units of the center argument are assumed to be pixels. unit_radius : `astropy.units.Unit` The units of the radius argument (arcseconds by default). If None, the units are assumed to be pixels. inside : bool If inside is True, pixels inside the region are masked. If inside is False, pixels outside the region are masked. posangle : float When the region is rectangular, this is the counter-clockwise rotation angle of the rectangle in degrees. When posangle is 0.0 (the default), the X and Y axes of the ellipse are along the X and Y axes of the image.<|endoftext|>
8ba0e99d38f58fe33ff4d8b162041eb3a626526b266a18343c29f350d162beb9
def mask_ellipse(self, center, radius, posangle, unit_center=u.deg, unit_radius=u.arcsec, inside=True): 'Mask values inside or outside an elliptical region.\n\n Parameters\n ----------\n center : (float,float)\n Center (y,x) of the region, where y,x are usually celestial\n coordinates along the Y and X axes of the image, but are\n interpretted as Y,X array-indexes if unit_center is changed\n to None.\n radius : (float,float)\n The radii of the two orthogonal axes of the ellipse.\n When posangle is zero, radius[0] is the radius along\n the X axis of the image-array, and radius[1] is\n the radius along the Y axis of the image-array.\n posangle : float\n The counter-clockwise rotation angle of the ellipse in\n degrees. When posangle is zero, the X and Y axes of the\n ellipse are along the X and Y axes of the image.\n unit_center : `astropy.units.Unit`\n The units of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_radius : `astropy.units.Unit`\n The units of the radius argument. Arcseconds by default.\n (use None for radius in pixels)\n inside : bool\n If inside is True, pixels inside the described region are masked.\n If inside is False, pixels outside the described region are masked.\n\n ' center = np.array(center) if (unit_center is not None): center = self.wcs.sky2pix(center, unit=unit_center)[0] if (unit_radius is None): step = np.array([1.0, 1.0]) else: step = self.wcs.get_step(unit=unit_radius) if np.isscalar(radius): radii = np.array([radius, radius]) else: radii = np.asarray(radius) ([sy, sx], _, center) = bounding_box(form='ellipse', center=center, radii=radii, shape=self.shape, posangle=posangle, step=step) cospa = np.cos(np.radians(posangle)) sinpa = np.sin(np.radians(posangle)) (x, y) = np.meshgrid(((np.arange(sx.start, sx.stop) - center[1]) * step[1]), ((np.arange(sy.start, sy.stop) - center[0]) * step[0])) ksel = (((((x * cospa) + (y * sinpa)) / radii[0]) ** 2) + ((((y * cospa) - (x * sinpa)) / radii[1]) ** 2)) if inside: self.data[(sy, sx)][(ksel < 1)] = np.ma.masked else: self.data[(0:sy.start, :)] = np.ma.masked self.data[(sy.stop:, :)] = np.ma.masked self.data[(sy, 0:sx.start)] = np.ma.masked self.data[(sy, sx.stop:)] = np.ma.masked self.data[(sy, sx)][(ksel > 1)] = np.ma.masked
Mask values inside or outside an elliptical region. Parameters ---------- center : (float,float) Center (y,x) of the region, where y,x are usually celestial coordinates along the Y and X axes of the image, but are interpretted as Y,X array-indexes if unit_center is changed to None. radius : (float,float) The radii of the two orthogonal axes of the ellipse. When posangle is zero, radius[0] is the radius along the X axis of the image-array, and radius[1] is the radius along the Y axis of the image-array. posangle : float The counter-clockwise rotation angle of the ellipse in degrees. When posangle is zero, the X and Y axes of the ellipse are along the X and Y axes of the image. unit_center : `astropy.units.Unit` The units of the center coordinates. Degrees by default (use None for coordinates in pixels). unit_radius : `astropy.units.Unit` The units of the radius argument. Arcseconds by default. (use None for radius in pixels) inside : bool If inside is True, pixels inside the described region are masked. If inside is False, pixels outside the described region are masked.
lib/mpdaf/obj/image.py
mask_ellipse
musevlt/mpdaf
4
python
def mask_ellipse(self, center, radius, posangle, unit_center=u.deg, unit_radius=u.arcsec, inside=True): 'Mask values inside or outside an elliptical region.\n\n Parameters\n ----------\n center : (float,float)\n Center (y,x) of the region, where y,x are usually celestial\n coordinates along the Y and X axes of the image, but are\n interpretted as Y,X array-indexes if unit_center is changed\n to None.\n radius : (float,float)\n The radii of the two orthogonal axes of the ellipse.\n When posangle is zero, radius[0] is the radius along\n the X axis of the image-array, and radius[1] is\n the radius along the Y axis of the image-array.\n posangle : float\n The counter-clockwise rotation angle of the ellipse in\n degrees. When posangle is zero, the X and Y axes of the\n ellipse are along the X and Y axes of the image.\n unit_center : `astropy.units.Unit`\n The units of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_radius : `astropy.units.Unit`\n The units of the radius argument. Arcseconds by default.\n (use None for radius in pixels)\n inside : bool\n If inside is True, pixels inside the described region are masked.\n If inside is False, pixels outside the described region are masked.\n\n ' center = np.array(center) if (unit_center is not None): center = self.wcs.sky2pix(center, unit=unit_center)[0] if (unit_radius is None): step = np.array([1.0, 1.0]) else: step = self.wcs.get_step(unit=unit_radius) if np.isscalar(radius): radii = np.array([radius, radius]) else: radii = np.asarray(radius) ([sy, sx], _, center) = bounding_box(form='ellipse', center=center, radii=radii, shape=self.shape, posangle=posangle, step=step) cospa = np.cos(np.radians(posangle)) sinpa = np.sin(np.radians(posangle)) (x, y) = np.meshgrid(((np.arange(sx.start, sx.stop) - center[1]) * step[1]), ((np.arange(sy.start, sy.stop) - center[0]) * step[0])) ksel = (((((x * cospa) + (y * sinpa)) / radii[0]) ** 2) + ((((y * cospa) - (x * sinpa)) / radii[1]) ** 2)) if inside: self.data[(sy, sx)][(ksel < 1)] = np.ma.masked else: self.data[(0:sy.start, :)] = np.ma.masked self.data[(sy.stop:, :)] = np.ma.masked self.data[(sy, 0:sx.start)] = np.ma.masked self.data[(sy, sx.stop:)] = np.ma.masked self.data[(sy, sx)][(ksel > 1)] = np.ma.masked
def mask_ellipse(self, center, radius, posangle, unit_center=u.deg, unit_radius=u.arcsec, inside=True): 'Mask values inside or outside an elliptical region.\n\n Parameters\n ----------\n center : (float,float)\n Center (y,x) of the region, where y,x are usually celestial\n coordinates along the Y and X axes of the image, but are\n interpretted as Y,X array-indexes if unit_center is changed\n to None.\n radius : (float,float)\n The radii of the two orthogonal axes of the ellipse.\n When posangle is zero, radius[0] is the radius along\n the X axis of the image-array, and radius[1] is\n the radius along the Y axis of the image-array.\n posangle : float\n The counter-clockwise rotation angle of the ellipse in\n degrees. When posangle is zero, the X and Y axes of the\n ellipse are along the X and Y axes of the image.\n unit_center : `astropy.units.Unit`\n The units of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_radius : `astropy.units.Unit`\n The units of the radius argument. Arcseconds by default.\n (use None for radius in pixels)\n inside : bool\n If inside is True, pixels inside the described region are masked.\n If inside is False, pixels outside the described region are masked.\n\n ' center = np.array(center) if (unit_center is not None): center = self.wcs.sky2pix(center, unit=unit_center)[0] if (unit_radius is None): step = np.array([1.0, 1.0]) else: step = self.wcs.get_step(unit=unit_radius) if np.isscalar(radius): radii = np.array([radius, radius]) else: radii = np.asarray(radius) ([sy, sx], _, center) = bounding_box(form='ellipse', center=center, radii=radii, shape=self.shape, posangle=posangle, step=step) cospa = np.cos(np.radians(posangle)) sinpa = np.sin(np.radians(posangle)) (x, y) = np.meshgrid(((np.arange(sx.start, sx.stop) - center[1]) * step[1]), ((np.arange(sy.start, sy.stop) - center[0]) * step[0])) ksel = (((((x * cospa) + (y * sinpa)) / radii[0]) ** 2) + ((((y * cospa) - (x * sinpa)) / radii[1]) ** 2)) if inside: self.data[(sy, sx)][(ksel < 1)] = np.ma.masked else: self.data[(0:sy.start, :)] = np.ma.masked self.data[(sy.stop:, :)] = np.ma.masked self.data[(sy, 0:sx.start)] = np.ma.masked self.data[(sy, sx.stop:)] = np.ma.masked self.data[(sy, sx)][(ksel > 1)] = np.ma.masked<|docstring|>Mask values inside or outside an elliptical region. Parameters ---------- center : (float,float) Center (y,x) of the region, where y,x are usually celestial coordinates along the Y and X axes of the image, but are interpretted as Y,X array-indexes if unit_center is changed to None. radius : (float,float) The radii of the two orthogonal axes of the ellipse. When posangle is zero, radius[0] is the radius along the X axis of the image-array, and radius[1] is the radius along the Y axis of the image-array. posangle : float The counter-clockwise rotation angle of the ellipse in degrees. When posangle is zero, the X and Y axes of the ellipse are along the X and Y axes of the image. unit_center : `astropy.units.Unit` The units of the center coordinates. Degrees by default (use None for coordinates in pixels). unit_radius : `astropy.units.Unit` The units of the radius argument. Arcseconds by default. (use None for radius in pixels) inside : bool If inside is True, pixels inside the described region are masked. If inside is False, pixels outside the described region are masked.<|endoftext|>
42860fdb00e194dfefae82c118f1eb3821dd5cc78e949ec1bad97b72527418dd
def mask_polygon(self, poly, unit=u.deg, inside=True): 'Mask values inside or outside a polygonal region.\n\n Parameters\n ----------\n poly : (float, float)\n An array of (float,float) containing a set of (p,q) or (dec,ra)\n values for the polygon vertices.\n unit : `astropy.units.Unit`\n The units of the polygon coordinates (by default in degrees).\n Use unit=None to have polygon coordinates in pixels.\n inside : bool\n If inside is True, pixels inside the polygonal region are masked.\n If inside is False, pixels outside the polygonal region are masked.\n\n ' if (unit is not None): poly = np.array([[self.wcs.sky2pix((val[0], val[1]), unit=unit)[0][0], self.wcs.sky2pix((val[0], val[1]), unit=unit)[0][1]] for val in poly]) b = np.mgrid[(:self.shape[0], :self.shape[1])].reshape(2, (- 1)).T from matplotlib.path import Path polymask = Path(poly) c = polymask.contains_points(b) if (not inside): c = (~ c) self._mask |= c.reshape(self.shape) return poly
Mask values inside or outside a polygonal region. Parameters ---------- poly : (float, float) An array of (float,float) containing a set of (p,q) or (dec,ra) values for the polygon vertices. unit : `astropy.units.Unit` The units of the polygon coordinates (by default in degrees). Use unit=None to have polygon coordinates in pixels. inside : bool If inside is True, pixels inside the polygonal region are masked. If inside is False, pixels outside the polygonal region are masked.
lib/mpdaf/obj/image.py
mask_polygon
musevlt/mpdaf
4
python
def mask_polygon(self, poly, unit=u.deg, inside=True): 'Mask values inside or outside a polygonal region.\n\n Parameters\n ----------\n poly : (float, float)\n An array of (float,float) containing a set of (p,q) or (dec,ra)\n values for the polygon vertices.\n unit : `astropy.units.Unit`\n The units of the polygon coordinates (by default in degrees).\n Use unit=None to have polygon coordinates in pixels.\n inside : bool\n If inside is True, pixels inside the polygonal region are masked.\n If inside is False, pixels outside the polygonal region are masked.\n\n ' if (unit is not None): poly = np.array([[self.wcs.sky2pix((val[0], val[1]), unit=unit)[0][0], self.wcs.sky2pix((val[0], val[1]), unit=unit)[0][1]] for val in poly]) b = np.mgrid[(:self.shape[0], :self.shape[1])].reshape(2, (- 1)).T from matplotlib.path import Path polymask = Path(poly) c = polymask.contains_points(b) if (not inside): c = (~ c) self._mask |= c.reshape(self.shape) return poly
def mask_polygon(self, poly, unit=u.deg, inside=True): 'Mask values inside or outside a polygonal region.\n\n Parameters\n ----------\n poly : (float, float)\n An array of (float,float) containing a set of (p,q) or (dec,ra)\n values for the polygon vertices.\n unit : `astropy.units.Unit`\n The units of the polygon coordinates (by default in degrees).\n Use unit=None to have polygon coordinates in pixels.\n inside : bool\n If inside is True, pixels inside the polygonal region are masked.\n If inside is False, pixels outside the polygonal region are masked.\n\n ' if (unit is not None): poly = np.array([[self.wcs.sky2pix((val[0], val[1]), unit=unit)[0][0], self.wcs.sky2pix((val[0], val[1]), unit=unit)[0][1]] for val in poly]) b = np.mgrid[(:self.shape[0], :self.shape[1])].reshape(2, (- 1)).T from matplotlib.path import Path polymask = Path(poly) c = polymask.contains_points(b) if (not inside): c = (~ c) self._mask |= c.reshape(self.shape) return poly<|docstring|>Mask values inside or outside a polygonal region. Parameters ---------- poly : (float, float) An array of (float,float) containing a set of (p,q) or (dec,ra) values for the polygon vertices. unit : `astropy.units.Unit` The units of the polygon coordinates (by default in degrees). Use unit=None to have polygon coordinates in pixels. inside : bool If inside is True, pixels inside the polygonal region are masked. If inside is False, pixels outside the polygonal region are masked.<|endoftext|>
236808df98925d12d49e7d9f985803df2d1248a77c26e3b20b63c40b4a0c294e
def truncate(self, y_min, y_max, x_min, x_max, mask=True, unit=u.deg, inplace=False): 'Return a sub-image that contains a specified area of the sky.\n\n The ranges x_min to x_max and y_min to y_max, specify a rectangular\n region of the sky in world coordinates. The truncate function returns\n the sub-image that just encloses this region. Note that if the world\n coordinate axes are not parallel to the array axes, the region will\n appear to be a rotated rectangle within the sub-image. In such cases,\n the corners of the sub-image will contain pixels that are outside the\n region. By default these pixels are masked. However this can be\n disabled by changing the optional mask argument to False.\n\n Parameters\n ----------\n y_min : float\n The minimum Y-axis world-coordinate of the selected\n region. The Y-axis is usually Declination, which may not\n be parallel to the Y-axis of the image array.\n y_max : float\n The maximum Y-axis world coordinate of the selected region.\n x_min : float\n The minimum X-axis world-coordinate of the selected\n region. The X-axis is usually Right Ascension, which may\n not be parallel to the X-axis of the image array.\n x_max : float\n The maximum X-axis world coordinate of the selected region.\n mask : bool\n If True, any pixels in the sub-image that remain outside the\n range x_min to x_max and y_min to y_max, will be masked.\n unit : `astropy.units.Unit`\n The units of the X and Y world-coordinates (degrees by default).\n inplace : bool\n If False, return a truncated copy of the image (the default).\n If True, truncate the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' skycrd = np.array([[y_min, x_min], [y_min, x_max], [y_max, x_min], [y_max, x_max]]) if (unit is not None): pixcrd = self.wcs.sky2pix(skycrd, unit=unit) else: pixcrd = skycrd imin = max(0, int((np.min(pixcrd[(:, 0)]) + 0.5))) imax = min(self.shape[0], (int((np.max(pixcrd[(:, 0)]) + 0.5)) + 1)) jmin = max(0, int((np.min(pixcrd[(:, 1)]) + 0.5))) jmax = min(self.shape[1], (int((np.max(pixcrd[(:, 1)]) + 0.5)) + 1)) subima = self[(imin:imax, jmin:jmax)] if inplace: self._data = subima._data if (self._var is not None): self._var = subima._var self._mask = subima._mask self.wcs = subima.wcs out = self else: out = subima.copy() if mask: pixcrd = np.mgrid[(:out.shape[0], :out.shape[1])].reshape(2, (- 1)).T if (unit is None): skycrd = pixcrd else: skycrd = np.array(out.wcs.pix2sky(pixcrd, unit=unit)) x = skycrd[(:, 1)].reshape(out.shape) y = skycrd[(:, 0)].reshape(out.shape) test_x = np.logical_or((x < x_min), (x > x_max)) test_y = np.logical_or((y < y_min), (y > y_max)) test = np.logical_or(test_x, test_y) out._mask = np.logical_or(out._mask, test) out.crop() return out
Return a sub-image that contains a specified area of the sky. The ranges x_min to x_max and y_min to y_max, specify a rectangular region of the sky in world coordinates. The truncate function returns the sub-image that just encloses this region. Note that if the world coordinate axes are not parallel to the array axes, the region will appear to be a rotated rectangle within the sub-image. In such cases, the corners of the sub-image will contain pixels that are outside the region. By default these pixels are masked. However this can be disabled by changing the optional mask argument to False. Parameters ---------- y_min : float The minimum Y-axis world-coordinate of the selected region. The Y-axis is usually Declination, which may not be parallel to the Y-axis of the image array. y_max : float The maximum Y-axis world coordinate of the selected region. x_min : float The minimum X-axis world-coordinate of the selected region. The X-axis is usually Right Ascension, which may not be parallel to the X-axis of the image array. x_max : float The maximum X-axis world coordinate of the selected region. mask : bool If True, any pixels in the sub-image that remain outside the range x_min to x_max and y_min to y_max, will be masked. unit : `astropy.units.Unit` The units of the X and Y world-coordinates (degrees by default). inplace : bool If False, return a truncated copy of the image (the default). If True, truncate the original image in-place, and return that. Returns ------- out : `~mpdaf.obj.Image`
lib/mpdaf/obj/image.py
truncate
musevlt/mpdaf
4
python
def truncate(self, y_min, y_max, x_min, x_max, mask=True, unit=u.deg, inplace=False): 'Return a sub-image that contains a specified area of the sky.\n\n The ranges x_min to x_max and y_min to y_max, specify a rectangular\n region of the sky in world coordinates. The truncate function returns\n the sub-image that just encloses this region. Note that if the world\n coordinate axes are not parallel to the array axes, the region will\n appear to be a rotated rectangle within the sub-image. In such cases,\n the corners of the sub-image will contain pixels that are outside the\n region. By default these pixels are masked. However this can be\n disabled by changing the optional mask argument to False.\n\n Parameters\n ----------\n y_min : float\n The minimum Y-axis world-coordinate of the selected\n region. The Y-axis is usually Declination, which may not\n be parallel to the Y-axis of the image array.\n y_max : float\n The maximum Y-axis world coordinate of the selected region.\n x_min : float\n The minimum X-axis world-coordinate of the selected\n region. The X-axis is usually Right Ascension, which may\n not be parallel to the X-axis of the image array.\n x_max : float\n The maximum X-axis world coordinate of the selected region.\n mask : bool\n If True, any pixels in the sub-image that remain outside the\n range x_min to x_max and y_min to y_max, will be masked.\n unit : `astropy.units.Unit`\n The units of the X and Y world-coordinates (degrees by default).\n inplace : bool\n If False, return a truncated copy of the image (the default).\n If True, truncate the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' skycrd = np.array([[y_min, x_min], [y_min, x_max], [y_max, x_min], [y_max, x_max]]) if (unit is not None): pixcrd = self.wcs.sky2pix(skycrd, unit=unit) else: pixcrd = skycrd imin = max(0, int((np.min(pixcrd[(:, 0)]) + 0.5))) imax = min(self.shape[0], (int((np.max(pixcrd[(:, 0)]) + 0.5)) + 1)) jmin = max(0, int((np.min(pixcrd[(:, 1)]) + 0.5))) jmax = min(self.shape[1], (int((np.max(pixcrd[(:, 1)]) + 0.5)) + 1)) subima = self[(imin:imax, jmin:jmax)] if inplace: self._data = subima._data if (self._var is not None): self._var = subima._var self._mask = subima._mask self.wcs = subima.wcs out = self else: out = subima.copy() if mask: pixcrd = np.mgrid[(:out.shape[0], :out.shape[1])].reshape(2, (- 1)).T if (unit is None): skycrd = pixcrd else: skycrd = np.array(out.wcs.pix2sky(pixcrd, unit=unit)) x = skycrd[(:, 1)].reshape(out.shape) y = skycrd[(:, 0)].reshape(out.shape) test_x = np.logical_or((x < x_min), (x > x_max)) test_y = np.logical_or((y < y_min), (y > y_max)) test = np.logical_or(test_x, test_y) out._mask = np.logical_or(out._mask, test) out.crop() return out
def truncate(self, y_min, y_max, x_min, x_max, mask=True, unit=u.deg, inplace=False): 'Return a sub-image that contains a specified area of the sky.\n\n The ranges x_min to x_max and y_min to y_max, specify a rectangular\n region of the sky in world coordinates. The truncate function returns\n the sub-image that just encloses this region. Note that if the world\n coordinate axes are not parallel to the array axes, the region will\n appear to be a rotated rectangle within the sub-image. In such cases,\n the corners of the sub-image will contain pixels that are outside the\n region. By default these pixels are masked. However this can be\n disabled by changing the optional mask argument to False.\n\n Parameters\n ----------\n y_min : float\n The minimum Y-axis world-coordinate of the selected\n region. The Y-axis is usually Declination, which may not\n be parallel to the Y-axis of the image array.\n y_max : float\n The maximum Y-axis world coordinate of the selected region.\n x_min : float\n The minimum X-axis world-coordinate of the selected\n region. The X-axis is usually Right Ascension, which may\n not be parallel to the X-axis of the image array.\n x_max : float\n The maximum X-axis world coordinate of the selected region.\n mask : bool\n If True, any pixels in the sub-image that remain outside the\n range x_min to x_max and y_min to y_max, will be masked.\n unit : `astropy.units.Unit`\n The units of the X and Y world-coordinates (degrees by default).\n inplace : bool\n If False, return a truncated copy of the image (the default).\n If True, truncate the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' skycrd = np.array([[y_min, x_min], [y_min, x_max], [y_max, x_min], [y_max, x_max]]) if (unit is not None): pixcrd = self.wcs.sky2pix(skycrd, unit=unit) else: pixcrd = skycrd imin = max(0, int((np.min(pixcrd[(:, 0)]) + 0.5))) imax = min(self.shape[0], (int((np.max(pixcrd[(:, 0)]) + 0.5)) + 1)) jmin = max(0, int((np.min(pixcrd[(:, 1)]) + 0.5))) jmax = min(self.shape[1], (int((np.max(pixcrd[(:, 1)]) + 0.5)) + 1)) subima = self[(imin:imax, jmin:jmax)] if inplace: self._data = subima._data if (self._var is not None): self._var = subima._var self._mask = subima._mask self.wcs = subima.wcs out = self else: out = subima.copy() if mask: pixcrd = np.mgrid[(:out.shape[0], :out.shape[1])].reshape(2, (- 1)).T if (unit is None): skycrd = pixcrd else: skycrd = np.array(out.wcs.pix2sky(pixcrd, unit=unit)) x = skycrd[(:, 1)].reshape(out.shape) y = skycrd[(:, 0)].reshape(out.shape) test_x = np.logical_or((x < x_min), (x > x_max)) test_y = np.logical_or((y < y_min), (y > y_max)) test = np.logical_or(test_x, test_y) out._mask = np.logical_or(out._mask, test) out.crop() return out<|docstring|>Return a sub-image that contains a specified area of the sky. The ranges x_min to x_max and y_min to y_max, specify a rectangular region of the sky in world coordinates. The truncate function returns the sub-image that just encloses this region. Note that if the world coordinate axes are not parallel to the array axes, the region will appear to be a rotated rectangle within the sub-image. In such cases, the corners of the sub-image will contain pixels that are outside the region. By default these pixels are masked. However this can be disabled by changing the optional mask argument to False. Parameters ---------- y_min : float The minimum Y-axis world-coordinate of the selected region. The Y-axis is usually Declination, which may not be parallel to the Y-axis of the image array. y_max : float The maximum Y-axis world coordinate of the selected region. x_min : float The minimum X-axis world-coordinate of the selected region. The X-axis is usually Right Ascension, which may not be parallel to the X-axis of the image array. x_max : float The maximum X-axis world coordinate of the selected region. mask : bool If True, any pixels in the sub-image that remain outside the range x_min to x_max and y_min to y_max, will be masked. unit : `astropy.units.Unit` The units of the X and Y world-coordinates (degrees by default). inplace : bool If False, return a truncated copy of the image (the default). If True, truncate the original image in-place, and return that. Returns ------- out : `~mpdaf.obj.Image`<|endoftext|>
4b28541d41a1e94bb554d258d94a5c4f077fe34b7eb50854265986f59a778fd7
def subimage(self, center, size, unit_center=u.deg, unit_size=u.arcsec, minsize=2.0): 'Return a view on a square or rectangular part.\n\n This method returns a square or rectangular sub-image whose center and\n size are specified in world coordinates. Note that this is a view on\n the original map and that both will be modified at the same time. If\n you need to modify only the sub-image, copy() the result of the\n method.\n\n Parameters\n ----------\n center : (float,float)\n The center (dec, ra) of the square region. If this position\n is not within the parent image, None is returned.\n size : float or (float,float)\n The width of a square region, or the width and height of\n a rectangular region.\n unit_center : `astropy.units.Unit`\n The units of the center coordinates.\n Degrees are assumed by default. To specify the center\n in pixels, assign None to unit_center.\n unit_size : `astropy.units.Unit`\n The units of the size and minsize arguments.\n Arcseconds are assumed by default (use None to specify\n sizes in pixels).\n minsize : float\n The minimum width of the output image along both the Y and\n X axes. This function returns None if size is smaller than\n minsize, or if the part of the square that lies within the\n parent image is smaller than minsize along either axis.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' if np.isscalar(size): size = np.array([size, size]) else: size = np.asarray(size) if ((size[0] <= 0) or (size[1] <= 0)): raise ValueError('Size must be positive') center = np.asarray(center) if (unit_center is not None): center = self.wcs.sky2pix(center, unit=unit_center)[0] if (unit_size is None): step = np.array([1.0, 1.0]) else: step = self.wcs.get_step(unit=unit_size) minsize /= step radius = (size / 2.0) ([sy, sx], [uy, ux], center) = bounding_box(form='rectangle', center=center, radii=radius, shape=self.shape, step=step) if ((sx.start >= self.shape[1]) or (sx.stop < 0) or (sx.start == sx.stop) or (sy.start >= self.shape[0]) or (sy.stop < 0) or (sy.start == sy.stop)): raise ValueError('Sub-image boundaries are outside the cube: center: {}, shape: {}, size: {}'.format(center, self.shape, size)) if ((((sy.stop - sy.start) + 1) < minsize[0]) or (((sx.stop - sx.start) + 1) < minsize[1])): self.logger.warning('extracted image is too small') return res = self[(sy, sx)] if ((sy == uy) and (sx == ux)): return res shape = ((uy.stop - uy.start), (ux.stop - ux.start)) data = np.zeros(shape, dtype=self.data.dtype) if (self._var is None): var = None else: var = np.zeros(shape) if (self._mask is ma.nomask): mask = ma.nomask data[:] = (np.nan if (self.dtype.kind == 'f') else self.data.fill_value) if (var is not None): var[:] = np.nan else: mask = np.ones(shape, dtype=bool) slices = (slice((sy.start - uy.start), (sy.stop - uy.start)), slice((sx.start - ux.start), (sx.stop - ux.start))) data[slices] = res._data[:] if (var is not None): var[slices] = res._var[:] if ((mask is not None) and (mask is not ma.nomask)): mask[slices] = res._mask[:] wcs = res.wcs wcs.set_crpix1((wcs.wcs.wcs.crpix[0] + slices[1].start)) wcs.set_crpix2((wcs.wcs.wcs.crpix[1] + slices[0].start)) wcs.naxis1 = shape[1] wcs.naxis2 = shape[0] return Image(wcs=wcs, unit=self.unit, copy=False, data=data, var=var, mask=mask, data_header=fits.Header(self.data_header), primary_header=fits.Header(self.primary_header), filename=self.filename)
Return a view on a square or rectangular part. This method returns a square or rectangular sub-image whose center and size are specified in world coordinates. Note that this is a view on the original map and that both will be modified at the same time. If you need to modify only the sub-image, copy() the result of the method. Parameters ---------- center : (float,float) The center (dec, ra) of the square region. If this position is not within the parent image, None is returned. size : float or (float,float) The width of a square region, or the width and height of a rectangular region. unit_center : `astropy.units.Unit` The units of the center coordinates. Degrees are assumed by default. To specify the center in pixels, assign None to unit_center. unit_size : `astropy.units.Unit` The units of the size and minsize arguments. Arcseconds are assumed by default (use None to specify sizes in pixels). minsize : float The minimum width of the output image along both the Y and X axes. This function returns None if size is smaller than minsize, or if the part of the square that lies within the parent image is smaller than minsize along either axis. Returns ------- out : `~mpdaf.obj.Image`
lib/mpdaf/obj/image.py
subimage
musevlt/mpdaf
4
python
def subimage(self, center, size, unit_center=u.deg, unit_size=u.arcsec, minsize=2.0): 'Return a view on a square or rectangular part.\n\n This method returns a square or rectangular sub-image whose center and\n size are specified in world coordinates. Note that this is a view on\n the original map and that both will be modified at the same time. If\n you need to modify only the sub-image, copy() the result of the\n method.\n\n Parameters\n ----------\n center : (float,float)\n The center (dec, ra) of the square region. If this position\n is not within the parent image, None is returned.\n size : float or (float,float)\n The width of a square region, or the width and height of\n a rectangular region.\n unit_center : `astropy.units.Unit`\n The units of the center coordinates.\n Degrees are assumed by default. To specify the center\n in pixels, assign None to unit_center.\n unit_size : `astropy.units.Unit`\n The units of the size and minsize arguments.\n Arcseconds are assumed by default (use None to specify\n sizes in pixels).\n minsize : float\n The minimum width of the output image along both the Y and\n X axes. This function returns None if size is smaller than\n minsize, or if the part of the square that lies within the\n parent image is smaller than minsize along either axis.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' if np.isscalar(size): size = np.array([size, size]) else: size = np.asarray(size) if ((size[0] <= 0) or (size[1] <= 0)): raise ValueError('Size must be positive') center = np.asarray(center) if (unit_center is not None): center = self.wcs.sky2pix(center, unit=unit_center)[0] if (unit_size is None): step = np.array([1.0, 1.0]) else: step = self.wcs.get_step(unit=unit_size) minsize /= step radius = (size / 2.0) ([sy, sx], [uy, ux], center) = bounding_box(form='rectangle', center=center, radii=radius, shape=self.shape, step=step) if ((sx.start >= self.shape[1]) or (sx.stop < 0) or (sx.start == sx.stop) or (sy.start >= self.shape[0]) or (sy.stop < 0) or (sy.start == sy.stop)): raise ValueError('Sub-image boundaries are outside the cube: center: {}, shape: {}, size: {}'.format(center, self.shape, size)) if ((((sy.stop - sy.start) + 1) < minsize[0]) or (((sx.stop - sx.start) + 1) < minsize[1])): self.logger.warning('extracted image is too small') return res = self[(sy, sx)] if ((sy == uy) and (sx == ux)): return res shape = ((uy.stop - uy.start), (ux.stop - ux.start)) data = np.zeros(shape, dtype=self.data.dtype) if (self._var is None): var = None else: var = np.zeros(shape) if (self._mask is ma.nomask): mask = ma.nomask data[:] = (np.nan if (self.dtype.kind == 'f') else self.data.fill_value) if (var is not None): var[:] = np.nan else: mask = np.ones(shape, dtype=bool) slices = (slice((sy.start - uy.start), (sy.stop - uy.start)), slice((sx.start - ux.start), (sx.stop - ux.start))) data[slices] = res._data[:] if (var is not None): var[slices] = res._var[:] if ((mask is not None) and (mask is not ma.nomask)): mask[slices] = res._mask[:] wcs = res.wcs wcs.set_crpix1((wcs.wcs.wcs.crpix[0] + slices[1].start)) wcs.set_crpix2((wcs.wcs.wcs.crpix[1] + slices[0].start)) wcs.naxis1 = shape[1] wcs.naxis2 = shape[0] return Image(wcs=wcs, unit=self.unit, copy=False, data=data, var=var, mask=mask, data_header=fits.Header(self.data_header), primary_header=fits.Header(self.primary_header), filename=self.filename)
def subimage(self, center, size, unit_center=u.deg, unit_size=u.arcsec, minsize=2.0): 'Return a view on a square or rectangular part.\n\n This method returns a square or rectangular sub-image whose center and\n size are specified in world coordinates. Note that this is a view on\n the original map and that both will be modified at the same time. If\n you need to modify only the sub-image, copy() the result of the\n method.\n\n Parameters\n ----------\n center : (float,float)\n The center (dec, ra) of the square region. If this position\n is not within the parent image, None is returned.\n size : float or (float,float)\n The width of a square region, or the width and height of\n a rectangular region.\n unit_center : `astropy.units.Unit`\n The units of the center coordinates.\n Degrees are assumed by default. To specify the center\n in pixels, assign None to unit_center.\n unit_size : `astropy.units.Unit`\n The units of the size and minsize arguments.\n Arcseconds are assumed by default (use None to specify\n sizes in pixels).\n minsize : float\n The minimum width of the output image along both the Y and\n X axes. This function returns None if size is smaller than\n minsize, or if the part of the square that lies within the\n parent image is smaller than minsize along either axis.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' if np.isscalar(size): size = np.array([size, size]) else: size = np.asarray(size) if ((size[0] <= 0) or (size[1] <= 0)): raise ValueError('Size must be positive') center = np.asarray(center) if (unit_center is not None): center = self.wcs.sky2pix(center, unit=unit_center)[0] if (unit_size is None): step = np.array([1.0, 1.0]) else: step = self.wcs.get_step(unit=unit_size) minsize /= step radius = (size / 2.0) ([sy, sx], [uy, ux], center) = bounding_box(form='rectangle', center=center, radii=radius, shape=self.shape, step=step) if ((sx.start >= self.shape[1]) or (sx.stop < 0) or (sx.start == sx.stop) or (sy.start >= self.shape[0]) or (sy.stop < 0) or (sy.start == sy.stop)): raise ValueError('Sub-image boundaries are outside the cube: center: {}, shape: {}, size: {}'.format(center, self.shape, size)) if ((((sy.stop - sy.start) + 1) < minsize[0]) or (((sx.stop - sx.start) + 1) < minsize[1])): self.logger.warning('extracted image is too small') return res = self[(sy, sx)] if ((sy == uy) and (sx == ux)): return res shape = ((uy.stop - uy.start), (ux.stop - ux.start)) data = np.zeros(shape, dtype=self.data.dtype) if (self._var is None): var = None else: var = np.zeros(shape) if (self._mask is ma.nomask): mask = ma.nomask data[:] = (np.nan if (self.dtype.kind == 'f') else self.data.fill_value) if (var is not None): var[:] = np.nan else: mask = np.ones(shape, dtype=bool) slices = (slice((sy.start - uy.start), (sy.stop - uy.start)), slice((sx.start - ux.start), (sx.stop - ux.start))) data[slices] = res._data[:] if (var is not None): var[slices] = res._var[:] if ((mask is not None) and (mask is not ma.nomask)): mask[slices] = res._mask[:] wcs = res.wcs wcs.set_crpix1((wcs.wcs.wcs.crpix[0] + slices[1].start)) wcs.set_crpix2((wcs.wcs.wcs.crpix[1] + slices[0].start)) wcs.naxis1 = shape[1] wcs.naxis2 = shape[0] return Image(wcs=wcs, unit=self.unit, copy=False, data=data, var=var, mask=mask, data_header=fits.Header(self.data_header), primary_header=fits.Header(self.primary_header), filename=self.filename)<|docstring|>Return a view on a square or rectangular part. This method returns a square or rectangular sub-image whose center and size are specified in world coordinates. Note that this is a view on the original map and that both will be modified at the same time. If you need to modify only the sub-image, copy() the result of the method. Parameters ---------- center : (float,float) The center (dec, ra) of the square region. If this position is not within the parent image, None is returned. size : float or (float,float) The width of a square region, or the width and height of a rectangular region. unit_center : `astropy.units.Unit` The units of the center coordinates. Degrees are assumed by default. To specify the center in pixels, assign None to unit_center. unit_size : `astropy.units.Unit` The units of the size and minsize arguments. Arcseconds are assumed by default (use None to specify sizes in pixels). minsize : float The minimum width of the output image along both the Y and X axes. This function returns None if size is smaller than minsize, or if the part of the square that lies within the parent image is smaller than minsize along either axis. Returns ------- out : `~mpdaf.obj.Image`<|endoftext|>
2bedd89a648b2bd2f16f99f5c0a26d2b47b86a63d996f5e3523ec8d24983a490
def rotate(self, theta=0.0, interp='no', reshape=False, order=1, pivot=None, unit=u.deg, regrid=None, flux=False, cutoff=0.25, inplace=False): "Rotate the sky within an image in the sense of a rotation from\n north to east.\n\n For example if the image rotation angle that is currently\n returned by image.get_rot() is zero, image.rotate(10.0) will\n rotate the northward direction of the image 10 degrees\n eastward of where it was, and self.get_rot() will thereafter\n return 10.0.\n\n Uses `scipy.ndimage.affine_transform`.\n\n Parameters\n ----------\n theta : float\n The angle to rotate the image (degrees). Positive\n angles rotate features in the image in the sense of a\n rotation from north to east.\n interp : 'no' | 'linear' | 'spline'\n If 'no', replace masked data with the median value of the\n image. This is the default.\n If 'linear', replace masked values using a linear\n interpolation between neighboring values.\n if 'spline', replace masked values using a spline\n interpolation between neighboring values.\n reshape : bool\n If True, the size of the output image array is adjusted\n so that the input image is contained completely in the\n output. The default is False.\n order : int\n The order of the prefilter that is applied by the affine\n transform function. Prefiltering is not really needed for\n band-limited images, but this option is retained for\n backwards compatibility with an older version of the\n image.rotate method. In general orders > 1 tend to\n generate ringing at sharp edges, such as those of CCD\n saturation spikes, so this argument is best left with\n its default value of 1.\n pivot : float,float or None\n When the reshape option is True, or the pivot argument is\n None, the image is rotated around its center.\n Alternatively, when the reshape option is False, the pivot\n argument can be used to indicate which pixel index [y,x]\n the image will be rotated around. Integer pixel indexes\n specify the centers of pixels. Non-integer values can be\n used to indicate positions between pixel centers.\n\n On the sky, the rotation always occurs around the\n coordinate reference position of the observation. However\n the rotated sky is then mapped onto the pixel array of the\n image in such a way as to keep the sky position of the\n pivot pixel at the same place. This makes the image appear\n to rotate around that pixel.\n unit : `astropy.units.Unit`\n The angular units of the rotation angle, theta.\n regrid : bool\n When this option is True, the pixel sizes along each axis\n are adjusted to avoid undersampling or oversampling any\n direction in the original image that would otherwise be\n rotated onto a lower or higher resolution axis. This is\n particularly important for images whose pixels have\n different angular dimensions along the X and Y axes, but\n it can also be important for images with square pixels,\n because the diagonal of an image with square pixels has\n higher resolution than the axes of that image.\n\n If this option is left with its default value of None,\n then it is given the value of the reshape option.\n flux : bool\n This tells the function whether the pixel units of the\n image are flux densities (flux=True), such as\n erg/s/cm2/Hz, or whether they are per-steradian brightness\n units (flux=False), such as erg/s/cm2/Hz/steradian. It\n needs to know this when it changes the pixel size, because\n when pixel sizes change, resampled flux densities need to\n be corrected for the change in the area per pixel, where\n resampled brightnesses don't.\n cutoff : float\n Mask each output pixel where at least this fraction of the\n pixel was interpolated from dummy values given to masked\n input pixels.\n inplace : bool\n If False, return a rotated copy of the image (the default).\n If True, rotate the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n " res = (self if inplace else self.copy()) res._rotate(theta=theta, interp=interp, reshape=reshape, order=order, pivot=pivot, unit=unit, regrid=regrid, flux=flux, cutoff=cutoff) return res
Rotate the sky within an image in the sense of a rotation from north to east. For example if the image rotation angle that is currently returned by image.get_rot() is zero, image.rotate(10.0) will rotate the northward direction of the image 10 degrees eastward of where it was, and self.get_rot() will thereafter return 10.0. Uses `scipy.ndimage.affine_transform`. Parameters ---------- theta : float The angle to rotate the image (degrees). Positive angles rotate features in the image in the sense of a rotation from north to east. interp : 'no' | 'linear' | 'spline' If 'no', replace masked data with the median value of the image. This is the default. If 'linear', replace masked values using a linear interpolation between neighboring values. if 'spline', replace masked values using a spline interpolation between neighboring values. reshape : bool If True, the size of the output image array is adjusted so that the input image is contained completely in the output. The default is False. order : int The order of the prefilter that is applied by the affine transform function. Prefiltering is not really needed for band-limited images, but this option is retained for backwards compatibility with an older version of the image.rotate method. In general orders > 1 tend to generate ringing at sharp edges, such as those of CCD saturation spikes, so this argument is best left with its default value of 1. pivot : float,float or None When the reshape option is True, or the pivot argument is None, the image is rotated around its center. Alternatively, when the reshape option is False, the pivot argument can be used to indicate which pixel index [y,x] the image will be rotated around. Integer pixel indexes specify the centers of pixels. Non-integer values can be used to indicate positions between pixel centers. On the sky, the rotation always occurs around the coordinate reference position of the observation. However the rotated sky is then mapped onto the pixel array of the image in such a way as to keep the sky position of the pivot pixel at the same place. This makes the image appear to rotate around that pixel. unit : `astropy.units.Unit` The angular units of the rotation angle, theta. regrid : bool When this option is True, the pixel sizes along each axis are adjusted to avoid undersampling or oversampling any direction in the original image that would otherwise be rotated onto a lower or higher resolution axis. This is particularly important for images whose pixels have different angular dimensions along the X and Y axes, but it can also be important for images with square pixels, because the diagonal of an image with square pixels has higher resolution than the axes of that image. If this option is left with its default value of None, then it is given the value of the reshape option. flux : bool This tells the function whether the pixel units of the image are flux densities (flux=True), such as erg/s/cm2/Hz, or whether they are per-steradian brightness units (flux=False), such as erg/s/cm2/Hz/steradian. It needs to know this when it changes the pixel size, because when pixel sizes change, resampled flux densities need to be corrected for the change in the area per pixel, where resampled brightnesses don't. cutoff : float Mask each output pixel where at least this fraction of the pixel was interpolated from dummy values given to masked input pixels. inplace : bool If False, return a rotated copy of the image (the default). If True, rotate the original image in-place, and return that. Returns ------- out : `~mpdaf.obj.Image`
lib/mpdaf/obj/image.py
rotate
musevlt/mpdaf
4
python
def rotate(self, theta=0.0, interp='no', reshape=False, order=1, pivot=None, unit=u.deg, regrid=None, flux=False, cutoff=0.25, inplace=False): "Rotate the sky within an image in the sense of a rotation from\n north to east.\n\n For example if the image rotation angle that is currently\n returned by image.get_rot() is zero, image.rotate(10.0) will\n rotate the northward direction of the image 10 degrees\n eastward of where it was, and self.get_rot() will thereafter\n return 10.0.\n\n Uses `scipy.ndimage.affine_transform`.\n\n Parameters\n ----------\n theta : float\n The angle to rotate the image (degrees). Positive\n angles rotate features in the image in the sense of a\n rotation from north to east.\n interp : 'no' | 'linear' | 'spline'\n If 'no', replace masked data with the median value of the\n image. This is the default.\n If 'linear', replace masked values using a linear\n interpolation between neighboring values.\n if 'spline', replace masked values using a spline\n interpolation between neighboring values.\n reshape : bool\n If True, the size of the output image array is adjusted\n so that the input image is contained completely in the\n output. The default is False.\n order : int\n The order of the prefilter that is applied by the affine\n transform function. Prefiltering is not really needed for\n band-limited images, but this option is retained for\n backwards compatibility with an older version of the\n image.rotate method. In general orders > 1 tend to\n generate ringing at sharp edges, such as those of CCD\n saturation spikes, so this argument is best left with\n its default value of 1.\n pivot : float,float or None\n When the reshape option is True, or the pivot argument is\n None, the image is rotated around its center.\n Alternatively, when the reshape option is False, the pivot\n argument can be used to indicate which pixel index [y,x]\n the image will be rotated around. Integer pixel indexes\n specify the centers of pixels. Non-integer values can be\n used to indicate positions between pixel centers.\n\n On the sky, the rotation always occurs around the\n coordinate reference position of the observation. However\n the rotated sky is then mapped onto the pixel array of the\n image in such a way as to keep the sky position of the\n pivot pixel at the same place. This makes the image appear\n to rotate around that pixel.\n unit : `astropy.units.Unit`\n The angular units of the rotation angle, theta.\n regrid : bool\n When this option is True, the pixel sizes along each axis\n are adjusted to avoid undersampling or oversampling any\n direction in the original image that would otherwise be\n rotated onto a lower or higher resolution axis. This is\n particularly important for images whose pixels have\n different angular dimensions along the X and Y axes, but\n it can also be important for images with square pixels,\n because the diagonal of an image with square pixels has\n higher resolution than the axes of that image.\n\n If this option is left with its default value of None,\n then it is given the value of the reshape option.\n flux : bool\n This tells the function whether the pixel units of the\n image are flux densities (flux=True), such as\n erg/s/cm2/Hz, or whether they are per-steradian brightness\n units (flux=False), such as erg/s/cm2/Hz/steradian. It\n needs to know this when it changes the pixel size, because\n when pixel sizes change, resampled flux densities need to\n be corrected for the change in the area per pixel, where\n resampled brightnesses don't.\n cutoff : float\n Mask each output pixel where at least this fraction of the\n pixel was interpolated from dummy values given to masked\n input pixels.\n inplace : bool\n If False, return a rotated copy of the image (the default).\n If True, rotate the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n " res = (self if inplace else self.copy()) res._rotate(theta=theta, interp=interp, reshape=reshape, order=order, pivot=pivot, unit=unit, regrid=regrid, flux=flux, cutoff=cutoff) return res
def rotate(self, theta=0.0, interp='no', reshape=False, order=1, pivot=None, unit=u.deg, regrid=None, flux=False, cutoff=0.25, inplace=False): "Rotate the sky within an image in the sense of a rotation from\n north to east.\n\n For example if the image rotation angle that is currently\n returned by image.get_rot() is zero, image.rotate(10.0) will\n rotate the northward direction of the image 10 degrees\n eastward of where it was, and self.get_rot() will thereafter\n return 10.0.\n\n Uses `scipy.ndimage.affine_transform`.\n\n Parameters\n ----------\n theta : float\n The angle to rotate the image (degrees). Positive\n angles rotate features in the image in the sense of a\n rotation from north to east.\n interp : 'no' | 'linear' | 'spline'\n If 'no', replace masked data with the median value of the\n image. This is the default.\n If 'linear', replace masked values using a linear\n interpolation between neighboring values.\n if 'spline', replace masked values using a spline\n interpolation between neighboring values.\n reshape : bool\n If True, the size of the output image array is adjusted\n so that the input image is contained completely in the\n output. The default is False.\n order : int\n The order of the prefilter that is applied by the affine\n transform function. Prefiltering is not really needed for\n band-limited images, but this option is retained for\n backwards compatibility with an older version of the\n image.rotate method. In general orders > 1 tend to\n generate ringing at sharp edges, such as those of CCD\n saturation spikes, so this argument is best left with\n its default value of 1.\n pivot : float,float or None\n When the reshape option is True, or the pivot argument is\n None, the image is rotated around its center.\n Alternatively, when the reshape option is False, the pivot\n argument can be used to indicate which pixel index [y,x]\n the image will be rotated around. Integer pixel indexes\n specify the centers of pixels. Non-integer values can be\n used to indicate positions between pixel centers.\n\n On the sky, the rotation always occurs around the\n coordinate reference position of the observation. However\n the rotated sky is then mapped onto the pixel array of the\n image in such a way as to keep the sky position of the\n pivot pixel at the same place. This makes the image appear\n to rotate around that pixel.\n unit : `astropy.units.Unit`\n The angular units of the rotation angle, theta.\n regrid : bool\n When this option is True, the pixel sizes along each axis\n are adjusted to avoid undersampling or oversampling any\n direction in the original image that would otherwise be\n rotated onto a lower or higher resolution axis. This is\n particularly important for images whose pixels have\n different angular dimensions along the X and Y axes, but\n it can also be important for images with square pixels,\n because the diagonal of an image with square pixels has\n higher resolution than the axes of that image.\n\n If this option is left with its default value of None,\n then it is given the value of the reshape option.\n flux : bool\n This tells the function whether the pixel units of the\n image are flux densities (flux=True), such as\n erg/s/cm2/Hz, or whether they are per-steradian brightness\n units (flux=False), such as erg/s/cm2/Hz/steradian. It\n needs to know this when it changes the pixel size, because\n when pixel sizes change, resampled flux densities need to\n be corrected for the change in the area per pixel, where\n resampled brightnesses don't.\n cutoff : float\n Mask each output pixel where at least this fraction of the\n pixel was interpolated from dummy values given to masked\n input pixels.\n inplace : bool\n If False, return a rotated copy of the image (the default).\n If True, rotate the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n " res = (self if inplace else self.copy()) res._rotate(theta=theta, interp=interp, reshape=reshape, order=order, pivot=pivot, unit=unit, regrid=regrid, flux=flux, cutoff=cutoff) return res<|docstring|>Rotate the sky within an image in the sense of a rotation from north to east. For example if the image rotation angle that is currently returned by image.get_rot() is zero, image.rotate(10.0) will rotate the northward direction of the image 10 degrees eastward of where it was, and self.get_rot() will thereafter return 10.0. Uses `scipy.ndimage.affine_transform`. Parameters ---------- theta : float The angle to rotate the image (degrees). Positive angles rotate features in the image in the sense of a rotation from north to east. interp : 'no' | 'linear' | 'spline' If 'no', replace masked data with the median value of the image. This is the default. If 'linear', replace masked values using a linear interpolation between neighboring values. if 'spline', replace masked values using a spline interpolation between neighboring values. reshape : bool If True, the size of the output image array is adjusted so that the input image is contained completely in the output. The default is False. order : int The order of the prefilter that is applied by the affine transform function. Prefiltering is not really needed for band-limited images, but this option is retained for backwards compatibility with an older version of the image.rotate method. In general orders > 1 tend to generate ringing at sharp edges, such as those of CCD saturation spikes, so this argument is best left with its default value of 1. pivot : float,float or None When the reshape option is True, or the pivot argument is None, the image is rotated around its center. Alternatively, when the reshape option is False, the pivot argument can be used to indicate which pixel index [y,x] the image will be rotated around. Integer pixel indexes specify the centers of pixels. Non-integer values can be used to indicate positions between pixel centers. On the sky, the rotation always occurs around the coordinate reference position of the observation. However the rotated sky is then mapped onto the pixel array of the image in such a way as to keep the sky position of the pivot pixel at the same place. This makes the image appear to rotate around that pixel. unit : `astropy.units.Unit` The angular units of the rotation angle, theta. regrid : bool When this option is True, the pixel sizes along each axis are adjusted to avoid undersampling or oversampling any direction in the original image that would otherwise be rotated onto a lower or higher resolution axis. This is particularly important for images whose pixels have different angular dimensions along the X and Y axes, but it can also be important for images with square pixels, because the diagonal of an image with square pixels has higher resolution than the axes of that image. If this option is left with its default value of None, then it is given the value of the reshape option. flux : bool This tells the function whether the pixel units of the image are flux densities (flux=True), such as erg/s/cm2/Hz, or whether they are per-steradian brightness units (flux=False), such as erg/s/cm2/Hz/steradian. It needs to know this when it changes the pixel size, because when pixel sizes change, resampled flux densities need to be corrected for the change in the area per pixel, where resampled brightnesses don't. cutoff : float Mask each output pixel where at least this fraction of the pixel was interpolated from dummy values given to masked input pixels. inplace : bool If False, return a rotated copy of the image (the default). If True, rotate the original image in-place, and return that. Returns ------- out : `~mpdaf.obj.Image`<|endoftext|>
edd9237b9cf72d7c67df234aae223466c830f610e24770dd9e3f27a0cb60d0ec
def norm(self, typ='flux', value=1.0): "Normalize in place total flux to value (default 1).\n\n Parameters\n ----------\n type : 'flux' | 'sum' | 'max'\n If 'flux',the flux is normalized and\n the pixel area is taken into account.\n\n If 'sum', the flux is normalized to the sum\n of flux independently of pixel size.\n\n If 'max', the flux is normalized so that\n the maximum of intensity will be 'value'.\n value : float\n Normalized value (default 1).\n " if (typ == 'flux'): norm = (value / (self.get_step().prod() * self.data.sum())) elif (typ == 'sum'): norm = (value / self.data.sum()) elif (typ == 'max'): norm = (value / self.data.max()) else: raise ValueError('Error in type: only flux,sum,max permitted') self._data *= norm if (self._var is not None): self._var *= (norm * norm)
Normalize in place total flux to value (default 1). Parameters ---------- type : 'flux' | 'sum' | 'max' If 'flux',the flux is normalized and the pixel area is taken into account. If 'sum', the flux is normalized to the sum of flux independently of pixel size. If 'max', the flux is normalized so that the maximum of intensity will be 'value'. value : float Normalized value (default 1).
lib/mpdaf/obj/image.py
norm
musevlt/mpdaf
4
python
def norm(self, typ='flux', value=1.0): "Normalize in place total flux to value (default 1).\n\n Parameters\n ----------\n type : 'flux' | 'sum' | 'max'\n If 'flux',the flux is normalized and\n the pixel area is taken into account.\n\n If 'sum', the flux is normalized to the sum\n of flux independently of pixel size.\n\n If 'max', the flux is normalized so that\n the maximum of intensity will be 'value'.\n value : float\n Normalized value (default 1).\n " if (typ == 'flux'): norm = (value / (self.get_step().prod() * self.data.sum())) elif (typ == 'sum'): norm = (value / self.data.sum()) elif (typ == 'max'): norm = (value / self.data.max()) else: raise ValueError('Error in type: only flux,sum,max permitted') self._data *= norm if (self._var is not None): self._var *= (norm * norm)
def norm(self, typ='flux', value=1.0): "Normalize in place total flux to value (default 1).\n\n Parameters\n ----------\n type : 'flux' | 'sum' | 'max'\n If 'flux',the flux is normalized and\n the pixel area is taken into account.\n\n If 'sum', the flux is normalized to the sum\n of flux independently of pixel size.\n\n If 'max', the flux is normalized so that\n the maximum of intensity will be 'value'.\n value : float\n Normalized value (default 1).\n " if (typ == 'flux'): norm = (value / (self.get_step().prod() * self.data.sum())) elif (typ == 'sum'): norm = (value / self.data.sum()) elif (typ == 'max'): norm = (value / self.data.max()) else: raise ValueError('Error in type: only flux,sum,max permitted') self._data *= norm if (self._var is not None): self._var *= (norm * norm)<|docstring|>Normalize in place total flux to value (default 1). Parameters ---------- type : 'flux' | 'sum' | 'max' If 'flux',the flux is normalized and the pixel area is taken into account. If 'sum', the flux is normalized to the sum of flux independently of pixel size. If 'max', the flux is normalized so that the maximum of intensity will be 'value'. value : float Normalized value (default 1).<|endoftext|>
48d23a4abc0841f2aaeda8102d950c5307bdecff4cdcf25787c1d2e5044f4961
def background(self, niter=3, sigma=3.0): 'Compute the image background with sigma-clipping.\n\n Returns the background value and its standard deviation.\n\n Parameters\n ----------\n niter : int\n Number of iterations.\n sigma : float\n Number of sigma used for the clipping.\n\n Returns\n -------\n out : 2-dim float array\n ' tab = self.data.compressed() for n in range((niter + 1)): tab = tab[(tab <= (tab.mean() + (sigma * tab.std())))] return (tab.mean(), tab.std())
Compute the image background with sigma-clipping. Returns the background value and its standard deviation. Parameters ---------- niter : int Number of iterations. sigma : float Number of sigma used for the clipping. Returns ------- out : 2-dim float array
lib/mpdaf/obj/image.py
background
musevlt/mpdaf
4
python
def background(self, niter=3, sigma=3.0): 'Compute the image background with sigma-clipping.\n\n Returns the background value and its standard deviation.\n\n Parameters\n ----------\n niter : int\n Number of iterations.\n sigma : float\n Number of sigma used for the clipping.\n\n Returns\n -------\n out : 2-dim float array\n ' tab = self.data.compressed() for n in range((niter + 1)): tab = tab[(tab <= (tab.mean() + (sigma * tab.std())))] return (tab.mean(), tab.std())
def background(self, niter=3, sigma=3.0): 'Compute the image background with sigma-clipping.\n\n Returns the background value and its standard deviation.\n\n Parameters\n ----------\n niter : int\n Number of iterations.\n sigma : float\n Number of sigma used for the clipping.\n\n Returns\n -------\n out : 2-dim float array\n ' tab = self.data.compressed() for n in range((niter + 1)): tab = tab[(tab <= (tab.mean() + (sigma * tab.std())))] return (tab.mean(), tab.std())<|docstring|>Compute the image background with sigma-clipping. Returns the background value and its standard deviation. Parameters ---------- niter : int Number of iterations. sigma : float Number of sigma used for the clipping. Returns ------- out : 2-dim float array<|endoftext|>
5cee9db0255daec95f24edafe747917331cb509332e94b4b2b864efedc13e488
def peak_detection(self, nstruct, niter, threshold=None): 'Return a list of peak locations.\n\n Parameters\n ----------\n nstruct : int\n Size of the structuring element used for the erosion.\n niter : int\n Number of iterations used for the erosion and the dilatation.\n threshold : float\n Threshold value. If None, it is initialized with background value.\n\n Returns\n -------\n out : np.array\n\n ' if (threshold is None): (background, std) = self.background() threshold = (background + (10 * std)) def _struct(n): struct = np.zeros([n, n]) for i in range(0, n): dist = abs((i - (n // 2))) struct[i][dist:abs((n - dist))] = 1 return struct selec = (self.data > threshold) selec.fill_value = False struct = _struct(nstruct) selec = ndi.binary_erosion(selec, structure=struct, iterations=niter) selec = ndi.binary_dilation(selec, structure=struct, iterations=niter) selec = ndi.binary_fill_holes(selec) structure = ndi.generate_binary_structure(2, 2) label = ndi.measurements.label(selec, structure) pos = ndi.measurements.center_of_mass(self.data, label[0], (np.arange(label[1]) + 1)) return np.array(pos)
Return a list of peak locations. Parameters ---------- nstruct : int Size of the structuring element used for the erosion. niter : int Number of iterations used for the erosion and the dilatation. threshold : float Threshold value. If None, it is initialized with background value. Returns ------- out : np.array
lib/mpdaf/obj/image.py
peak_detection
musevlt/mpdaf
4
python
def peak_detection(self, nstruct, niter, threshold=None): 'Return a list of peak locations.\n\n Parameters\n ----------\n nstruct : int\n Size of the structuring element used for the erosion.\n niter : int\n Number of iterations used for the erosion and the dilatation.\n threshold : float\n Threshold value. If None, it is initialized with background value.\n\n Returns\n -------\n out : np.array\n\n ' if (threshold is None): (background, std) = self.background() threshold = (background + (10 * std)) def _struct(n): struct = np.zeros([n, n]) for i in range(0, n): dist = abs((i - (n // 2))) struct[i][dist:abs((n - dist))] = 1 return struct selec = (self.data > threshold) selec.fill_value = False struct = _struct(nstruct) selec = ndi.binary_erosion(selec, structure=struct, iterations=niter) selec = ndi.binary_dilation(selec, structure=struct, iterations=niter) selec = ndi.binary_fill_holes(selec) structure = ndi.generate_binary_structure(2, 2) label = ndi.measurements.label(selec, structure) pos = ndi.measurements.center_of_mass(self.data, label[0], (np.arange(label[1]) + 1)) return np.array(pos)
def peak_detection(self, nstruct, niter, threshold=None): 'Return a list of peak locations.\n\n Parameters\n ----------\n nstruct : int\n Size of the structuring element used for the erosion.\n niter : int\n Number of iterations used for the erosion and the dilatation.\n threshold : float\n Threshold value. If None, it is initialized with background value.\n\n Returns\n -------\n out : np.array\n\n ' if (threshold is None): (background, std) = self.background() threshold = (background + (10 * std)) def _struct(n): struct = np.zeros([n, n]) for i in range(0, n): dist = abs((i - (n // 2))) struct[i][dist:abs((n - dist))] = 1 return struct selec = (self.data > threshold) selec.fill_value = False struct = _struct(nstruct) selec = ndi.binary_erosion(selec, structure=struct, iterations=niter) selec = ndi.binary_dilation(selec, structure=struct, iterations=niter) selec = ndi.binary_fill_holes(selec) structure = ndi.generate_binary_structure(2, 2) label = ndi.measurements.label(selec, structure) pos = ndi.measurements.center_of_mass(self.data, label[0], (np.arange(label[1]) + 1)) return np.array(pos)<|docstring|>Return a list of peak locations. Parameters ---------- nstruct : int Size of the structuring element used for the erosion. niter : int Number of iterations used for the erosion and the dilatation. threshold : float Threshold value. If None, it is initialized with background value. Returns ------- out : np.array<|endoftext|>
ee2e49f99544b36818a312efc44ef3f63091d46fcf3e27520482663892b592ce
def peak(self, center=None, radius=0, unit_center=u.deg, unit_radius=u.arcsec, dpix=2, background=None, plot=False): "Find image peak location.\n\n Used `scipy.ndimage.measurements.maximum_position` and\n `scipy.ndimage.measurements.center_of_mass`.\n\n Parameters\n ----------\n center : (float,float)\n Center (y,x) of the explored region.\n If center is None, the full image is explored.\n radius : float or (float,float)\n Radius defined the explored region.\n unit_center : `astropy.units.Unit`\n Type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_radius : `astropy.units.Unit`\n Radius unit.\n Arcseconds by default (use None for radius in pixels)\n dpix : int\n Half size of the window (in pixels) to compute the center of\n gravity.\n background : float\n Background value. If None, it is computed.\n plot : bool\n If True, the peak center is overplotted on the image.\n\n Returns\n -------\n out : dict {'y', 'x', 'p', 'q', 'data'}\n Containing the peak position and the peak intensity.\n\n " if ((center is None) or (radius == 0)): d = self.data imin = 0 jmin = 0 else: if is_number(radius): radius = (radius, radius) if (unit_center is not None): center = self.wcs.sky2pix(center, unit=unit_center)[0] if (unit_radius is not None): radius = (radius / self.wcs.get_step(unit=unit_radius)) imin = max(0, int((center[0] - radius[0]))) imax = min(self.shape[0], int(((center[0] + radius[0]) + 1))) jmin = max(0, int((center[1] - radius[1]))) jmax = min(self.shape[1], int(((center[1] + radius[1]) + 1))) d = self.data[(imin:imax, jmin:jmax)] if ((np.shape(d)[0] == 0) or (np.shape(d)[1] == 0)): raise ValueError('Coord area outside image limits') (ic, jc) = ndi.measurements.maximum_position(d) if (dpix == 0): di = 0 dj = 0 else: if (background is None): background = self.background()[0] (di, dj) = ndi.measurements.center_of_mass((d[(max(0, (ic - dpix)):((ic + dpix) + 1), max(0, (jc - dpix)):((jc + dpix) + 1))] - background)) ic = ((imin + max(0, (ic - dpix))) + di) jc = ((jmin + max(0, (jc - dpix))) + dj) (iic, jjc) = (int(round(ic)), int(round(jc))) if ((iic < 0) or (jjc < 0) or (iic >= self.data.shape[0]) or (jjc >= self.data.shape[1])): return None [[dec, ra]] = self.wcs.pix2sky([[ic, jc]]) maxv = self.data[(int(round(ic)), int(round(jc)))] if plot: self._ax.plot(jc, ic, 'r+') try: _str = ('center (%g,%g) radius (%g,%g) dpix %i peak: %g %g' % (center[0], center[1], radius[0], radius[1], dpix, jc, ic)) except Exception: _str = ('dpix %i peak: %g %g' % (dpix, ic, jc)) self._ax.title(_str) return {'x': ra, 'y': dec, 'p': ic, 'q': jc, 'data': maxv}
Find image peak location. Used `scipy.ndimage.measurements.maximum_position` and `scipy.ndimage.measurements.center_of_mass`. Parameters ---------- center : (float,float) Center (y,x) of the explored region. If center is None, the full image is explored. radius : float or (float,float) Radius defined the explored region. unit_center : `astropy.units.Unit` Type of the center coordinates. Degrees by default (use None for coordinates in pixels). unit_radius : `astropy.units.Unit` Radius unit. Arcseconds by default (use None for radius in pixels) dpix : int Half size of the window (in pixels) to compute the center of gravity. background : float Background value. If None, it is computed. plot : bool If True, the peak center is overplotted on the image. Returns ------- out : dict {'y', 'x', 'p', 'q', 'data'} Containing the peak position and the peak intensity.
lib/mpdaf/obj/image.py
peak
musevlt/mpdaf
4
python
def peak(self, center=None, radius=0, unit_center=u.deg, unit_radius=u.arcsec, dpix=2, background=None, plot=False): "Find image peak location.\n\n Used `scipy.ndimage.measurements.maximum_position` and\n `scipy.ndimage.measurements.center_of_mass`.\n\n Parameters\n ----------\n center : (float,float)\n Center (y,x) of the explored region.\n If center is None, the full image is explored.\n radius : float or (float,float)\n Radius defined the explored region.\n unit_center : `astropy.units.Unit`\n Type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_radius : `astropy.units.Unit`\n Radius unit.\n Arcseconds by default (use None for radius in pixels)\n dpix : int\n Half size of the window (in pixels) to compute the center of\n gravity.\n background : float\n Background value. If None, it is computed.\n plot : bool\n If True, the peak center is overplotted on the image.\n\n Returns\n -------\n out : dict {'y', 'x', 'p', 'q', 'data'}\n Containing the peak position and the peak intensity.\n\n " if ((center is None) or (radius == 0)): d = self.data imin = 0 jmin = 0 else: if is_number(radius): radius = (radius, radius) if (unit_center is not None): center = self.wcs.sky2pix(center, unit=unit_center)[0] if (unit_radius is not None): radius = (radius / self.wcs.get_step(unit=unit_radius)) imin = max(0, int((center[0] - radius[0]))) imax = min(self.shape[0], int(((center[0] + radius[0]) + 1))) jmin = max(0, int((center[1] - radius[1]))) jmax = min(self.shape[1], int(((center[1] + radius[1]) + 1))) d = self.data[(imin:imax, jmin:jmax)] if ((np.shape(d)[0] == 0) or (np.shape(d)[1] == 0)): raise ValueError('Coord area outside image limits') (ic, jc) = ndi.measurements.maximum_position(d) if (dpix == 0): di = 0 dj = 0 else: if (background is None): background = self.background()[0] (di, dj) = ndi.measurements.center_of_mass((d[(max(0, (ic - dpix)):((ic + dpix) + 1), max(0, (jc - dpix)):((jc + dpix) + 1))] - background)) ic = ((imin + max(0, (ic - dpix))) + di) jc = ((jmin + max(0, (jc - dpix))) + dj) (iic, jjc) = (int(round(ic)), int(round(jc))) if ((iic < 0) or (jjc < 0) or (iic >= self.data.shape[0]) or (jjc >= self.data.shape[1])): return None [[dec, ra]] = self.wcs.pix2sky([[ic, jc]]) maxv = self.data[(int(round(ic)), int(round(jc)))] if plot: self._ax.plot(jc, ic, 'r+') try: _str = ('center (%g,%g) radius (%g,%g) dpix %i peak: %g %g' % (center[0], center[1], radius[0], radius[1], dpix, jc, ic)) except Exception: _str = ('dpix %i peak: %g %g' % (dpix, ic, jc)) self._ax.title(_str) return {'x': ra, 'y': dec, 'p': ic, 'q': jc, 'data': maxv}
def peak(self, center=None, radius=0, unit_center=u.deg, unit_radius=u.arcsec, dpix=2, background=None, plot=False): "Find image peak location.\n\n Used `scipy.ndimage.measurements.maximum_position` and\n `scipy.ndimage.measurements.center_of_mass`.\n\n Parameters\n ----------\n center : (float,float)\n Center (y,x) of the explored region.\n If center is None, the full image is explored.\n radius : float or (float,float)\n Radius defined the explored region.\n unit_center : `astropy.units.Unit`\n Type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_radius : `astropy.units.Unit`\n Radius unit.\n Arcseconds by default (use None for radius in pixels)\n dpix : int\n Half size of the window (in pixels) to compute the center of\n gravity.\n background : float\n Background value. If None, it is computed.\n plot : bool\n If True, the peak center is overplotted on the image.\n\n Returns\n -------\n out : dict {'y', 'x', 'p', 'q', 'data'}\n Containing the peak position and the peak intensity.\n\n " if ((center is None) or (radius == 0)): d = self.data imin = 0 jmin = 0 else: if is_number(radius): radius = (radius, radius) if (unit_center is not None): center = self.wcs.sky2pix(center, unit=unit_center)[0] if (unit_radius is not None): radius = (radius / self.wcs.get_step(unit=unit_radius)) imin = max(0, int((center[0] - radius[0]))) imax = min(self.shape[0], int(((center[0] + radius[0]) + 1))) jmin = max(0, int((center[1] - radius[1]))) jmax = min(self.shape[1], int(((center[1] + radius[1]) + 1))) d = self.data[(imin:imax, jmin:jmax)] if ((np.shape(d)[0] == 0) or (np.shape(d)[1] == 0)): raise ValueError('Coord area outside image limits') (ic, jc) = ndi.measurements.maximum_position(d) if (dpix == 0): di = 0 dj = 0 else: if (background is None): background = self.background()[0] (di, dj) = ndi.measurements.center_of_mass((d[(max(0, (ic - dpix)):((ic + dpix) + 1), max(0, (jc - dpix)):((jc + dpix) + 1))] - background)) ic = ((imin + max(0, (ic - dpix))) + di) jc = ((jmin + max(0, (jc - dpix))) + dj) (iic, jjc) = (int(round(ic)), int(round(jc))) if ((iic < 0) or (jjc < 0) or (iic >= self.data.shape[0]) or (jjc >= self.data.shape[1])): return None [[dec, ra]] = self.wcs.pix2sky([[ic, jc]]) maxv = self.data[(int(round(ic)), int(round(jc)))] if plot: self._ax.plot(jc, ic, 'r+') try: _str = ('center (%g,%g) radius (%g,%g) dpix %i peak: %g %g' % (center[0], center[1], radius[0], radius[1], dpix, jc, ic)) except Exception: _str = ('dpix %i peak: %g %g' % (dpix, ic, jc)) self._ax.title(_str) return {'x': ra, 'y': dec, 'p': ic, 'q': jc, 'data': maxv}<|docstring|>Find image peak location. Used `scipy.ndimage.measurements.maximum_position` and `scipy.ndimage.measurements.center_of_mass`. Parameters ---------- center : (float,float) Center (y,x) of the explored region. If center is None, the full image is explored. radius : float or (float,float) Radius defined the explored region. unit_center : `astropy.units.Unit` Type of the center coordinates. Degrees by default (use None for coordinates in pixels). unit_radius : `astropy.units.Unit` Radius unit. Arcseconds by default (use None for radius in pixels) dpix : int Half size of the window (in pixels) to compute the center of gravity. background : float Background value. If None, it is computed. plot : bool If True, the peak center is overplotted on the image. Returns ------- out : dict {'y', 'x', 'p', 'q', 'data'} Containing the peak position and the peak intensity.<|endoftext|>
25cb2e81adfb65854e6ad7a74b516434135b0dc9fd8f7ad1fbcc406a747a4149
def fwhm(self, center=None, radius=0, unit_center=u.deg, unit_radius=u.arcsec): 'Compute the fwhm.\n\n Parameters\n ----------\n center : (float,float)\n Center of the explored region.\n If center is None, the full image is explored.\n radius : float or (float,float)\n Radius defined the explored region.\n unit_center : `astropy.units.Unit`\n type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_radius : `astropy.units.Unit`\n Radius unit. Arcseconds by default (use None for radius in pixels)\n\n Returns\n -------\n out : array of float\n [fwhm_y,fwhm_x], returned in unit_radius (arcseconds by default).\n\n ' if ((center is None) or (radius == 0)): img = self else: size = (((radius * 2), (radius * 2)) if is_number(radius) else ((radius[0] * 2), (radius[1] * 2))) img = self.subimage(center, size, unit_center=unit_center, unit_size=unit_radius) width = img.moments(unit=unit_radius) return ((width / 2) * gaussian_sigma_to_fwhm)
Compute the fwhm. Parameters ---------- center : (float,float) Center of the explored region. If center is None, the full image is explored. radius : float or (float,float) Radius defined the explored region. unit_center : `astropy.units.Unit` type of the center coordinates. Degrees by default (use None for coordinates in pixels). unit_radius : `astropy.units.Unit` Radius unit. Arcseconds by default (use None for radius in pixels) Returns ------- out : array of float [fwhm_y,fwhm_x], returned in unit_radius (arcseconds by default).
lib/mpdaf/obj/image.py
fwhm
musevlt/mpdaf
4
python
def fwhm(self, center=None, radius=0, unit_center=u.deg, unit_radius=u.arcsec): 'Compute the fwhm.\n\n Parameters\n ----------\n center : (float,float)\n Center of the explored region.\n If center is None, the full image is explored.\n radius : float or (float,float)\n Radius defined the explored region.\n unit_center : `astropy.units.Unit`\n type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_radius : `astropy.units.Unit`\n Radius unit. Arcseconds by default (use None for radius in pixels)\n\n Returns\n -------\n out : array of float\n [fwhm_y,fwhm_x], returned in unit_radius (arcseconds by default).\n\n ' if ((center is None) or (radius == 0)): img = self else: size = (((radius * 2), (radius * 2)) if is_number(radius) else ((radius[0] * 2), (radius[1] * 2))) img = self.subimage(center, size, unit_center=unit_center, unit_size=unit_radius) width = img.moments(unit=unit_radius) return ((width / 2) * gaussian_sigma_to_fwhm)
def fwhm(self, center=None, radius=0, unit_center=u.deg, unit_radius=u.arcsec): 'Compute the fwhm.\n\n Parameters\n ----------\n center : (float,float)\n Center of the explored region.\n If center is None, the full image is explored.\n radius : float or (float,float)\n Radius defined the explored region.\n unit_center : `astropy.units.Unit`\n type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_radius : `astropy.units.Unit`\n Radius unit. Arcseconds by default (use None for radius in pixels)\n\n Returns\n -------\n out : array of float\n [fwhm_y,fwhm_x], returned in unit_radius (arcseconds by default).\n\n ' if ((center is None) or (radius == 0)): img = self else: size = (((radius * 2), (radius * 2)) if is_number(radius) else ((radius[0] * 2), (radius[1] * 2))) img = self.subimage(center, size, unit_center=unit_center, unit_size=unit_radius) width = img.moments(unit=unit_radius) return ((width / 2) * gaussian_sigma_to_fwhm)<|docstring|>Compute the fwhm. Parameters ---------- center : (float,float) Center of the explored region. If center is None, the full image is explored. radius : float or (float,float) Radius defined the explored region. unit_center : `astropy.units.Unit` type of the center coordinates. Degrees by default (use None for coordinates in pixels). unit_radius : `astropy.units.Unit` Radius unit. Arcseconds by default (use None for radius in pixels) Returns ------- out : array of float [fwhm_y,fwhm_x], returned in unit_radius (arcseconds by default).<|endoftext|>
0e0d8f0d58bb8efdb3826b11876e1e0908bda704832e7ee0fd2d638a58a37a8f
def ee(self, center=None, radius=0, unit_center=u.deg, unit_radius=u.arcsec, frac=False, cont=0): 'Compute ensquared/encircled energy.\n\n Parameters\n ----------\n center : (float,float)\n Center of the explored region.\n If center is None, the full image is explored.\n radius : float or (float,float)\n Radius defined the explored region.\n If float, it defined a circular region (encircled energy).\n If (float,float), it defined a rectangular region (ensquared\n energy).\n unit_center : `astropy.units.Unit`\n Type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_radius : `astropy.units.Unit`\n Radius unit. Arcseconds by default (use None for radius in pixels)\n frac : bool\n If frac is True, result is given relative to the total energy of\n the full image.\n cont : float\n Continuum value.\n\n Returns\n -------\n out : float\n Ensquared/encircled flux.\n\n ' if ((center is None) or (radius == 0)): if frac: return 1.0 else: return (self.data - cont).sum() else: if is_number(radius): circular = True radius2 = (radius * radius) radius = (radius, radius) else: circular = False if (unit_center is not None): center = self.wcs.sky2pix(center, unit=unit_center)[0] if (unit_radius is not None): radius = (radius / self.wcs.get_step(unit=unit_radius)) radius2 = (radius[0] * radius[1]) imin = max(0, (center[0] - radius[0])) imax = min(((center[0] + radius[0]) + 1), self.shape[0]) jmin = max(0, (center[1] - radius[1])) jmax = min(((center[1] + radius[1]) + 1), self.shape[1]) ima = self[(imin:imax, jmin:jmax)] if circular: xaxis = (np.arange(ima.shape[0], dtype=float) - (ima.shape[0] / 2.0)) yaxis = (np.arange(ima.shape[1], dtype=float) - (ima.shape[1] / 2.0)) gridx = np.empty(ima.shape, dtype=float) gridy = np.empty(ima.shape, dtype=float) for j in range(ima.shape[1]): gridx[(:, j)] = xaxis for i in range(ima.shape[0]): gridy[(i, :)] = yaxis r2 = ((gridx * gridx) + (gridy * gridy)) ksel = np.where((r2 < radius2)) if frac: return ((ima.data[ksel] - cont).sum() / (self.data - cont).sum()) else: return (ima.data[ksel] - cont).sum() elif frac: return ((ima.data - cont).sum() / (self.data - cont).sum()) else: return (ima.data - cont).sum()
Compute ensquared/encircled energy. Parameters ---------- center : (float,float) Center of the explored region. If center is None, the full image is explored. radius : float or (float,float) Radius defined the explored region. If float, it defined a circular region (encircled energy). If (float,float), it defined a rectangular region (ensquared energy). unit_center : `astropy.units.Unit` Type of the center coordinates. Degrees by default (use None for coordinates in pixels). unit_radius : `astropy.units.Unit` Radius unit. Arcseconds by default (use None for radius in pixels) frac : bool If frac is True, result is given relative to the total energy of the full image. cont : float Continuum value. Returns ------- out : float Ensquared/encircled flux.
lib/mpdaf/obj/image.py
ee
musevlt/mpdaf
4
python
def ee(self, center=None, radius=0, unit_center=u.deg, unit_radius=u.arcsec, frac=False, cont=0): 'Compute ensquared/encircled energy.\n\n Parameters\n ----------\n center : (float,float)\n Center of the explored region.\n If center is None, the full image is explored.\n radius : float or (float,float)\n Radius defined the explored region.\n If float, it defined a circular region (encircled energy).\n If (float,float), it defined a rectangular region (ensquared\n energy).\n unit_center : `astropy.units.Unit`\n Type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_radius : `astropy.units.Unit`\n Radius unit. Arcseconds by default (use None for radius in pixels)\n frac : bool\n If frac is True, result is given relative to the total energy of\n the full image.\n cont : float\n Continuum value.\n\n Returns\n -------\n out : float\n Ensquared/encircled flux.\n\n ' if ((center is None) or (radius == 0)): if frac: return 1.0 else: return (self.data - cont).sum() else: if is_number(radius): circular = True radius2 = (radius * radius) radius = (radius, radius) else: circular = False if (unit_center is not None): center = self.wcs.sky2pix(center, unit=unit_center)[0] if (unit_radius is not None): radius = (radius / self.wcs.get_step(unit=unit_radius)) radius2 = (radius[0] * radius[1]) imin = max(0, (center[0] - radius[0])) imax = min(((center[0] + radius[0]) + 1), self.shape[0]) jmin = max(0, (center[1] - radius[1])) jmax = min(((center[1] + radius[1]) + 1), self.shape[1]) ima = self[(imin:imax, jmin:jmax)] if circular: xaxis = (np.arange(ima.shape[0], dtype=float) - (ima.shape[0] / 2.0)) yaxis = (np.arange(ima.shape[1], dtype=float) - (ima.shape[1] / 2.0)) gridx = np.empty(ima.shape, dtype=float) gridy = np.empty(ima.shape, dtype=float) for j in range(ima.shape[1]): gridx[(:, j)] = xaxis for i in range(ima.shape[0]): gridy[(i, :)] = yaxis r2 = ((gridx * gridx) + (gridy * gridy)) ksel = np.where((r2 < radius2)) if frac: return ((ima.data[ksel] - cont).sum() / (self.data - cont).sum()) else: return (ima.data[ksel] - cont).sum() elif frac: return ((ima.data - cont).sum() / (self.data - cont).sum()) else: return (ima.data - cont).sum()
def ee(self, center=None, radius=0, unit_center=u.deg, unit_radius=u.arcsec, frac=False, cont=0): 'Compute ensquared/encircled energy.\n\n Parameters\n ----------\n center : (float,float)\n Center of the explored region.\n If center is None, the full image is explored.\n radius : float or (float,float)\n Radius defined the explored region.\n If float, it defined a circular region (encircled energy).\n If (float,float), it defined a rectangular region (ensquared\n energy).\n unit_center : `astropy.units.Unit`\n Type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_radius : `astropy.units.Unit`\n Radius unit. Arcseconds by default (use None for radius in pixels)\n frac : bool\n If frac is True, result is given relative to the total energy of\n the full image.\n cont : float\n Continuum value.\n\n Returns\n -------\n out : float\n Ensquared/encircled flux.\n\n ' if ((center is None) or (radius == 0)): if frac: return 1.0 else: return (self.data - cont).sum() else: if is_number(radius): circular = True radius2 = (radius * radius) radius = (radius, radius) else: circular = False if (unit_center is not None): center = self.wcs.sky2pix(center, unit=unit_center)[0] if (unit_radius is not None): radius = (radius / self.wcs.get_step(unit=unit_radius)) radius2 = (radius[0] * radius[1]) imin = max(0, (center[0] - radius[0])) imax = min(((center[0] + radius[0]) + 1), self.shape[0]) jmin = max(0, (center[1] - radius[1])) jmax = min(((center[1] + radius[1]) + 1), self.shape[1]) ima = self[(imin:imax, jmin:jmax)] if circular: xaxis = (np.arange(ima.shape[0], dtype=float) - (ima.shape[0] / 2.0)) yaxis = (np.arange(ima.shape[1], dtype=float) - (ima.shape[1] / 2.0)) gridx = np.empty(ima.shape, dtype=float) gridy = np.empty(ima.shape, dtype=float) for j in range(ima.shape[1]): gridx[(:, j)] = xaxis for i in range(ima.shape[0]): gridy[(i, :)] = yaxis r2 = ((gridx * gridx) + (gridy * gridy)) ksel = np.where((r2 < radius2)) if frac: return ((ima.data[ksel] - cont).sum() / (self.data - cont).sum()) else: return (ima.data[ksel] - cont).sum() elif frac: return ((ima.data - cont).sum() / (self.data - cont).sum()) else: return (ima.data - cont).sum()<|docstring|>Compute ensquared/encircled energy. Parameters ---------- center : (float,float) Center of the explored region. If center is None, the full image is explored. radius : float or (float,float) Radius defined the explored region. If float, it defined a circular region (encircled energy). If (float,float), it defined a rectangular region (ensquared energy). unit_center : `astropy.units.Unit` Type of the center coordinates. Degrees by default (use None for coordinates in pixels). unit_radius : `astropy.units.Unit` Radius unit. Arcseconds by default (use None for radius in pixels) frac : bool If frac is True, result is given relative to the total energy of the full image. cont : float Continuum value. Returns ------- out : float Ensquared/encircled flux.<|endoftext|>
f837873776f51f00ad91f8cd0172891c18b4295c2787cf3aca6d98d331426915
def eer_curve(self, center=None, unit_center=u.deg, unit_radius=u.arcsec, etot=None, cont=0): 'Return containing enclosed energy as function of radius.\n\n The enclosed energy ratio (EER) shows how much light is concentrated\n within a certain radius around the image-center.\n\n\n Parameters\n ----------\n center : (float,float)\n Center of the explored region.\n If center is None, center of the image is used.\n unit_center : `astropy.units.Unit`\n Type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_radius : `astropy.units.Unit`\n Radius units (arcseconds by default)/\n etot : float\n Total energy used to comute the ratio.\n If etot is not set, it is computed from the full image.\n cont : float\n Continuum value.\n\n Returns\n -------\n out : (float array, float array)\n Radius array, EER array\n ' if (center is None): i = (self.shape[0] // 2) j = (self.shape[1] // 2) elif (unit_center is None): i = center[0] j = center[1] else: pixcrd = self.wcs.sky2pix([center[0], center[1]], nearest=True, unit=unit_center) i = pixcrd[0][0] j = pixcrd[0][1] nmax = min((self.shape[0] - i), (self.shape[1] - j), i, j) if (etot is None): etot = (self.data - cont).sum() if (nmax <= 1): raise ValueError('Coord area outside image limits') ee = np.empty(nmax) for d in range(0, nmax): ee[d] = ((self.data[((i - d):((i + d) + 1), (j - d):((j + d) + 1))] - cont).sum() / etot) radius = np.arange(0, nmax) if (unit_radius is not None): step = np.mean(self.get_step(unit=unit_radius)) radius = (radius * step) return (radius, ee)
Return containing enclosed energy as function of radius. The enclosed energy ratio (EER) shows how much light is concentrated within a certain radius around the image-center. Parameters ---------- center : (float,float) Center of the explored region. If center is None, center of the image is used. unit_center : `astropy.units.Unit` Type of the center coordinates. Degrees by default (use None for coordinates in pixels). unit_radius : `astropy.units.Unit` Radius units (arcseconds by default)/ etot : float Total energy used to comute the ratio. If etot is not set, it is computed from the full image. cont : float Continuum value. Returns ------- out : (float array, float array) Radius array, EER array
lib/mpdaf/obj/image.py
eer_curve
musevlt/mpdaf
4
python
def eer_curve(self, center=None, unit_center=u.deg, unit_radius=u.arcsec, etot=None, cont=0): 'Return containing enclosed energy as function of radius.\n\n The enclosed energy ratio (EER) shows how much light is concentrated\n within a certain radius around the image-center.\n\n\n Parameters\n ----------\n center : (float,float)\n Center of the explored region.\n If center is None, center of the image is used.\n unit_center : `astropy.units.Unit`\n Type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_radius : `astropy.units.Unit`\n Radius units (arcseconds by default)/\n etot : float\n Total energy used to comute the ratio.\n If etot is not set, it is computed from the full image.\n cont : float\n Continuum value.\n\n Returns\n -------\n out : (float array, float array)\n Radius array, EER array\n ' if (center is None): i = (self.shape[0] // 2) j = (self.shape[1] // 2) elif (unit_center is None): i = center[0] j = center[1] else: pixcrd = self.wcs.sky2pix([center[0], center[1]], nearest=True, unit=unit_center) i = pixcrd[0][0] j = pixcrd[0][1] nmax = min((self.shape[0] - i), (self.shape[1] - j), i, j) if (etot is None): etot = (self.data - cont).sum() if (nmax <= 1): raise ValueError('Coord area outside image limits') ee = np.empty(nmax) for d in range(0, nmax): ee[d] = ((self.data[((i - d):((i + d) + 1), (j - d):((j + d) + 1))] - cont).sum() / etot) radius = np.arange(0, nmax) if (unit_radius is not None): step = np.mean(self.get_step(unit=unit_radius)) radius = (radius * step) return (radius, ee)
def eer_curve(self, center=None, unit_center=u.deg, unit_radius=u.arcsec, etot=None, cont=0): 'Return containing enclosed energy as function of radius.\n\n The enclosed energy ratio (EER) shows how much light is concentrated\n within a certain radius around the image-center.\n\n\n Parameters\n ----------\n center : (float,float)\n Center of the explored region.\n If center is None, center of the image is used.\n unit_center : `astropy.units.Unit`\n Type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_radius : `astropy.units.Unit`\n Radius units (arcseconds by default)/\n etot : float\n Total energy used to comute the ratio.\n If etot is not set, it is computed from the full image.\n cont : float\n Continuum value.\n\n Returns\n -------\n out : (float array, float array)\n Radius array, EER array\n ' if (center is None): i = (self.shape[0] // 2) j = (self.shape[1] // 2) elif (unit_center is None): i = center[0] j = center[1] else: pixcrd = self.wcs.sky2pix([center[0], center[1]], nearest=True, unit=unit_center) i = pixcrd[0][0] j = pixcrd[0][1] nmax = min((self.shape[0] - i), (self.shape[1] - j), i, j) if (etot is None): etot = (self.data - cont).sum() if (nmax <= 1): raise ValueError('Coord area outside image limits') ee = np.empty(nmax) for d in range(0, nmax): ee[d] = ((self.data[((i - d):((i + d) + 1), (j - d):((j + d) + 1))] - cont).sum() / etot) radius = np.arange(0, nmax) if (unit_radius is not None): step = np.mean(self.get_step(unit=unit_radius)) radius = (radius * step) return (radius, ee)<|docstring|>Return containing enclosed energy as function of radius. The enclosed energy ratio (EER) shows how much light is concentrated within a certain radius around the image-center. Parameters ---------- center : (float,float) Center of the explored region. If center is None, center of the image is used. unit_center : `astropy.units.Unit` Type of the center coordinates. Degrees by default (use None for coordinates in pixels). unit_radius : `astropy.units.Unit` Radius units (arcseconds by default)/ etot : float Total energy used to comute the ratio. If etot is not set, it is computed from the full image. cont : float Continuum value. Returns ------- out : (float array, float array) Radius array, EER array<|endoftext|>
4fc89064d43eb0c22d530d7df2d21e5bd5ade552486793d62275fed8646c8baa
def ee_size(self, center=None, unit_center=u.deg, etot=None, frac=0.9, cont=0, unit_size=u.arcsec): 'Compute the size of the square centered on (y,x) containing the\n fraction of the energy.\n\n Parameters\n ----------\n center : (float,float)\n Center (y,x) of the explored region.\n If center is None, center of the image is used.\n unit : `astropy.units.Unit`\n Type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n etot : float\n Total energy used to comute the ratio.\n If etot is not set, it is computed from the full image.\n frac : float in ]0,1]\n Fraction of energy.\n cont : float\n continuum value\n unit_center : `astropy.units.Unit`\n Type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_size : `astropy.units.Unit`\n Size unit. Arcseconds by default (use None for sier in pixels).\n\n Returns\n -------\n out : float array\n ' if (center is None): i = (self.shape[0] // 2) j = (self.shape[1] // 2) elif (unit_center is None): i = center[0] j = center[1] else: pixcrd = self.wcs.sky2pix([[center[0], center[1]]], unit=unit_center) i = int((pixcrd[0][0] + 0.5)) j = int((pixcrd[0][1] + 0.5)) nmax = min((self.shape[0] - i), (self.shape[1] - j), i, j) if (etot is None): etot = (self.data - cont).sum() if (nmax <= 1): if (unit_size is None): return np.array([1, 1]) else: return self.get_step(unit_size) for d in range(1, nmax): ee2 = ((self.data[((i - d):((i + d) + 1), (j - d):((j + d) + 1))] - cont).sum() / etot) if (ee2 > frac): break d -= 1 ee1 = ((self.data[((i - d):((i + d) + 1), (i - d):((i + d) + 1))] - cont).sum() / etot) d += ((frac - ee1) / (ee2 - ee1)) d *= 2 if (unit_size is None): return np.array([d, d]) else: step = self.get_step(unit_size) return np.array([(d * step[0]), (d * step[1])])
Compute the size of the square centered on (y,x) containing the fraction of the energy. Parameters ---------- center : (float,float) Center (y,x) of the explored region. If center is None, center of the image is used. unit : `astropy.units.Unit` Type of the center coordinates. Degrees by default (use None for coordinates in pixels). etot : float Total energy used to comute the ratio. If etot is not set, it is computed from the full image. frac : float in ]0,1] Fraction of energy. cont : float continuum value unit_center : `astropy.units.Unit` Type of the center coordinates. Degrees by default (use None for coordinates in pixels). unit_size : `astropy.units.Unit` Size unit. Arcseconds by default (use None for sier in pixels). Returns ------- out : float array
lib/mpdaf/obj/image.py
ee_size
musevlt/mpdaf
4
python
def ee_size(self, center=None, unit_center=u.deg, etot=None, frac=0.9, cont=0, unit_size=u.arcsec): 'Compute the size of the square centered on (y,x) containing the\n fraction of the energy.\n\n Parameters\n ----------\n center : (float,float)\n Center (y,x) of the explored region.\n If center is None, center of the image is used.\n unit : `astropy.units.Unit`\n Type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n etot : float\n Total energy used to comute the ratio.\n If etot is not set, it is computed from the full image.\n frac : float in ]0,1]\n Fraction of energy.\n cont : float\n continuum value\n unit_center : `astropy.units.Unit`\n Type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_size : `astropy.units.Unit`\n Size unit. Arcseconds by default (use None for sier in pixels).\n\n Returns\n -------\n out : float array\n ' if (center is None): i = (self.shape[0] // 2) j = (self.shape[1] // 2) elif (unit_center is None): i = center[0] j = center[1] else: pixcrd = self.wcs.sky2pix([[center[0], center[1]]], unit=unit_center) i = int((pixcrd[0][0] + 0.5)) j = int((pixcrd[0][1] + 0.5)) nmax = min((self.shape[0] - i), (self.shape[1] - j), i, j) if (etot is None): etot = (self.data - cont).sum() if (nmax <= 1): if (unit_size is None): return np.array([1, 1]) else: return self.get_step(unit_size) for d in range(1, nmax): ee2 = ((self.data[((i - d):((i + d) + 1), (j - d):((j + d) + 1))] - cont).sum() / etot) if (ee2 > frac): break d -= 1 ee1 = ((self.data[((i - d):((i + d) + 1), (i - d):((i + d) + 1))] - cont).sum() / etot) d += ((frac - ee1) / (ee2 - ee1)) d *= 2 if (unit_size is None): return np.array([d, d]) else: step = self.get_step(unit_size) return np.array([(d * step[0]), (d * step[1])])
def ee_size(self, center=None, unit_center=u.deg, etot=None, frac=0.9, cont=0, unit_size=u.arcsec): 'Compute the size of the square centered on (y,x) containing the\n fraction of the energy.\n\n Parameters\n ----------\n center : (float,float)\n Center (y,x) of the explored region.\n If center is None, center of the image is used.\n unit : `astropy.units.Unit`\n Type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n etot : float\n Total energy used to comute the ratio.\n If etot is not set, it is computed from the full image.\n frac : float in ]0,1]\n Fraction of energy.\n cont : float\n continuum value\n unit_center : `astropy.units.Unit`\n Type of the center coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_size : `astropy.units.Unit`\n Size unit. Arcseconds by default (use None for sier in pixels).\n\n Returns\n -------\n out : float array\n ' if (center is None): i = (self.shape[0] // 2) j = (self.shape[1] // 2) elif (unit_center is None): i = center[0] j = center[1] else: pixcrd = self.wcs.sky2pix([[center[0], center[1]]], unit=unit_center) i = int((pixcrd[0][0] + 0.5)) j = int((pixcrd[0][1] + 0.5)) nmax = min((self.shape[0] - i), (self.shape[1] - j), i, j) if (etot is None): etot = (self.data - cont).sum() if (nmax <= 1): if (unit_size is None): return np.array([1, 1]) else: return self.get_step(unit_size) for d in range(1, nmax): ee2 = ((self.data[((i - d):((i + d) + 1), (j - d):((j + d) + 1))] - cont).sum() / etot) if (ee2 > frac): break d -= 1 ee1 = ((self.data[((i - d):((i + d) + 1), (i - d):((i + d) + 1))] - cont).sum() / etot) d += ((frac - ee1) / (ee2 - ee1)) d *= 2 if (unit_size is None): return np.array([d, d]) else: step = self.get_step(unit_size) return np.array([(d * step[0]), (d * step[1])])<|docstring|>Compute the size of the square centered on (y,x) containing the fraction of the energy. Parameters ---------- center : (float,float) Center (y,x) of the explored region. If center is None, center of the image is used. unit : `astropy.units.Unit` Type of the center coordinates. Degrees by default (use None for coordinates in pixels). etot : float Total energy used to comute the ratio. If etot is not set, it is computed from the full image. frac : float in ]0,1] Fraction of energy. cont : float continuum value unit_center : `astropy.units.Unit` Type of the center coordinates. Degrees by default (use None for coordinates in pixels). unit_size : `astropy.units.Unit` Size unit. Arcseconds by default (use None for sier in pixels). Returns ------- out : float array<|endoftext|>
f847119ab6ae3f4f625f4d127abcceac344f8177de4d0be11bbf361a3613cce4
def _interp(self, grid, spline=False): 'Return the interpolated values corresponding to the grid points.\n\n Parameters\n ----------\n grid :\n pixel values\n spline : bool\n If False, linear interpolation (uses\n `scipy.interpolate.griddata`), or if True: spline\n interpolation (uses `scipy.interpolate.bisplrep` and\n `scipy.interpolate.bisplev`).\n\n ' if (self.mask is np.ma.nomask): (x, y) = np.mgrid[(:self.shape[0], :self.shape[1])].reshape(2, (- 1)) data = self._data else: (x, y) = np.where((~ self._mask)) data = self._data[(x, y)] grid = np.array(grid) if spline: if (self.var is not None): var = self.var.filled(np.inf) weight = (1 / np.sqrt(np.abs(var[(x, y)]))) else: weight = None tck = interpolate.bisplrep(x, y, data, w=weight) res = interpolate.bisplev(grid[0], grid[1], tck) return res else: res = interpolate.griddata((x, y), data, grid.T, method='linear') return res
Return the interpolated values corresponding to the grid points. Parameters ---------- grid : pixel values spline : bool If False, linear interpolation (uses `scipy.interpolate.griddata`), or if True: spline interpolation (uses `scipy.interpolate.bisplrep` and `scipy.interpolate.bisplev`).
lib/mpdaf/obj/image.py
_interp
musevlt/mpdaf
4
python
def _interp(self, grid, spline=False): 'Return the interpolated values corresponding to the grid points.\n\n Parameters\n ----------\n grid :\n pixel values\n spline : bool\n If False, linear interpolation (uses\n `scipy.interpolate.griddata`), or if True: spline\n interpolation (uses `scipy.interpolate.bisplrep` and\n `scipy.interpolate.bisplev`).\n\n ' if (self.mask is np.ma.nomask): (x, y) = np.mgrid[(:self.shape[0], :self.shape[1])].reshape(2, (- 1)) data = self._data else: (x, y) = np.where((~ self._mask)) data = self._data[(x, y)] grid = np.array(grid) if spline: if (self.var is not None): var = self.var.filled(np.inf) weight = (1 / np.sqrt(np.abs(var[(x, y)]))) else: weight = None tck = interpolate.bisplrep(x, y, data, w=weight) res = interpolate.bisplev(grid[0], grid[1], tck) return res else: res = interpolate.griddata((x, y), data, grid.T, method='linear') return res
def _interp(self, grid, spline=False): 'Return the interpolated values corresponding to the grid points.\n\n Parameters\n ----------\n grid :\n pixel values\n spline : bool\n If False, linear interpolation (uses\n `scipy.interpolate.griddata`), or if True: spline\n interpolation (uses `scipy.interpolate.bisplrep` and\n `scipy.interpolate.bisplev`).\n\n ' if (self.mask is np.ma.nomask): (x, y) = np.mgrid[(:self.shape[0], :self.shape[1])].reshape(2, (- 1)) data = self._data else: (x, y) = np.where((~ self._mask)) data = self._data[(x, y)] grid = np.array(grid) if spline: if (self.var is not None): var = self.var.filled(np.inf) weight = (1 / np.sqrt(np.abs(var[(x, y)]))) else: weight = None tck = interpolate.bisplrep(x, y, data, w=weight) res = interpolate.bisplev(grid[0], grid[1], tck) return res else: res = interpolate.griddata((x, y), data, grid.T, method='linear') return res<|docstring|>Return the interpolated values corresponding to the grid points. Parameters ---------- grid : pixel values spline : bool If False, linear interpolation (uses `scipy.interpolate.griddata`), or if True: spline interpolation (uses `scipy.interpolate.bisplrep` and `scipy.interpolate.bisplev`).<|endoftext|>
0b7d72056c1e5b8cb407b8bcf186e7ac7b21cb82daf8f11968dc6cb8a0c0fe40
def _interp_data(self, spline=False): 'Return data array with interpolated values for masked pixels.\n\n Parameters\n ----------\n spline : bool\n False: bilinear interpolation (it uses\n `scipy.interpolate.griddata`), True: spline interpolation (it\n uses `scipy.interpolate.bisplrep` and\n `scipy.interpolate.bisplev`).\n\n ' if (not self._mask.any()): return self._data else: ksel = np.where(self._mask) data = self._data.__copy__() data[ksel] = self._interp(ksel, spline) return data
Return data array with interpolated values for masked pixels. Parameters ---------- spline : bool False: bilinear interpolation (it uses `scipy.interpolate.griddata`), True: spline interpolation (it uses `scipy.interpolate.bisplrep` and `scipy.interpolate.bisplev`).
lib/mpdaf/obj/image.py
_interp_data
musevlt/mpdaf
4
python
def _interp_data(self, spline=False): 'Return data array with interpolated values for masked pixels.\n\n Parameters\n ----------\n spline : bool\n False: bilinear interpolation (it uses\n `scipy.interpolate.griddata`), True: spline interpolation (it\n uses `scipy.interpolate.bisplrep` and\n `scipy.interpolate.bisplev`).\n\n ' if (not self._mask.any()): return self._data else: ksel = np.where(self._mask) data = self._data.__copy__() data[ksel] = self._interp(ksel, spline) return data
def _interp_data(self, spline=False): 'Return data array with interpolated values for masked pixels.\n\n Parameters\n ----------\n spline : bool\n False: bilinear interpolation (it uses\n `scipy.interpolate.griddata`), True: spline interpolation (it\n uses `scipy.interpolate.bisplrep` and\n `scipy.interpolate.bisplev`).\n\n ' if (not self._mask.any()): return self._data else: ksel = np.where(self._mask) data = self._data.__copy__() data[ksel] = self._interp(ksel, spline) return data<|docstring|>Return data array with interpolated values for masked pixels. Parameters ---------- spline : bool False: bilinear interpolation (it uses `scipy.interpolate.griddata`), True: spline interpolation (it uses `scipy.interpolate.bisplrep` and `scipy.interpolate.bisplev`).<|endoftext|>
e0e940d6856df625cacda3cd7c246cf67def0f43d076ceed7b73d8f1c1378ecc
def _prepare_data(self, interp='no'): "Return a copy of the data array in which masked values\n have been filled, either with the median value of the image,\n or by interpolating neighboring pixels.\n\n Parameters\n ----------\n interp : 'no' | 'linear' | 'spline'\n If 'no', replace masked data with the median image value.\n If 'linear', replace masked values using a linear\n interpolation between neighboring values.\n if 'spline', replace masked values using a spline\n interpolation between neighboring values.\n\n Returns\n -------\n out : numpy.ndarray\n A patched copy of the data array.\n\n " if (interp == 'linear'): data = self._interp_data(spline=False) elif (interp == 'spline'): data = self._interp_data(spline=True) else: data = np.ma.filled(self.data, np.ma.median(self.data)) return data
Return a copy of the data array in which masked values have been filled, either with the median value of the image, or by interpolating neighboring pixels. Parameters ---------- interp : 'no' | 'linear' | 'spline' If 'no', replace masked data with the median image value. If 'linear', replace masked values using a linear interpolation between neighboring values. if 'spline', replace masked values using a spline interpolation between neighboring values. Returns ------- out : numpy.ndarray A patched copy of the data array.
lib/mpdaf/obj/image.py
_prepare_data
musevlt/mpdaf
4
python
def _prepare_data(self, interp='no'): "Return a copy of the data array in which masked values\n have been filled, either with the median value of the image,\n or by interpolating neighboring pixels.\n\n Parameters\n ----------\n interp : 'no' | 'linear' | 'spline'\n If 'no', replace masked data with the median image value.\n If 'linear', replace masked values using a linear\n interpolation between neighboring values.\n if 'spline', replace masked values using a spline\n interpolation between neighboring values.\n\n Returns\n -------\n out : numpy.ndarray\n A patched copy of the data array.\n\n " if (interp == 'linear'): data = self._interp_data(spline=False) elif (interp == 'spline'): data = self._interp_data(spline=True) else: data = np.ma.filled(self.data, np.ma.median(self.data)) return data
def _prepare_data(self, interp='no'): "Return a copy of the data array in which masked values\n have been filled, either with the median value of the image,\n or by interpolating neighboring pixels.\n\n Parameters\n ----------\n interp : 'no' | 'linear' | 'spline'\n If 'no', replace masked data with the median image value.\n If 'linear', replace masked values using a linear\n interpolation between neighboring values.\n if 'spline', replace masked values using a spline\n interpolation between neighboring values.\n\n Returns\n -------\n out : numpy.ndarray\n A patched copy of the data array.\n\n " if (interp == 'linear'): data = self._interp_data(spline=False) elif (interp == 'spline'): data = self._interp_data(spline=True) else: data = np.ma.filled(self.data, np.ma.median(self.data)) return data<|docstring|>Return a copy of the data array in which masked values have been filled, either with the median value of the image, or by interpolating neighboring pixels. Parameters ---------- interp : 'no' | 'linear' | 'spline' If 'no', replace masked data with the median image value. If 'linear', replace masked values using a linear interpolation between neighboring values. if 'spline', replace masked values using a spline interpolation between neighboring values. Returns ------- out : numpy.ndarray A patched copy of the data array.<|endoftext|>
35c224b3105a075a687d515327b88f466bdf7b326d4d259cfe11cfc187dfa916
def moments(self, unit=u.arcsec): 'Return [width_y, width_x] first moments of the 2D gaussian.\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n Unit of the returned moments (arcseconds by default).\n If None, moments will be in pixels.\n\n Returns\n -------\n out : float array\n\n ' total = np.abs(self.data).sum() (P, Q) = np.indices(self.data.shape) p = np.argmax(((Q * np.abs(self.data)).sum(axis=1) / total)) q = np.argmax(((P * np.abs(self.data)).sum(axis=0) / total)) col = self.data[(int(p), :)] width_q = np.sqrt((np.abs(((np.arange(col.size) - p) * col)).sum() / np.abs(col).sum())) row = self.data[(:, int(q))] width_p = np.sqrt((np.abs(((np.arange(row.size) - q) * row)).sum() / np.abs(row).sum())) mom = np.array([width_p, width_q]) if (unit is not None): mom *= self.wcs.get_step(unit=unit) return mom
Return [width_y, width_x] first moments of the 2D gaussian. Parameters ---------- unit : `astropy.units.Unit` Unit of the returned moments (arcseconds by default). If None, moments will be in pixels. Returns ------- out : float array
lib/mpdaf/obj/image.py
moments
musevlt/mpdaf
4
python
def moments(self, unit=u.arcsec): 'Return [width_y, width_x] first moments of the 2D gaussian.\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n Unit of the returned moments (arcseconds by default).\n If None, moments will be in pixels.\n\n Returns\n -------\n out : float array\n\n ' total = np.abs(self.data).sum() (P, Q) = np.indices(self.data.shape) p = np.argmax(((Q * np.abs(self.data)).sum(axis=1) / total)) q = np.argmax(((P * np.abs(self.data)).sum(axis=0) / total)) col = self.data[(int(p), :)] width_q = np.sqrt((np.abs(((np.arange(col.size) - p) * col)).sum() / np.abs(col).sum())) row = self.data[(:, int(q))] width_p = np.sqrt((np.abs(((np.arange(row.size) - q) * row)).sum() / np.abs(row).sum())) mom = np.array([width_p, width_q]) if (unit is not None): mom *= self.wcs.get_step(unit=unit) return mom
def moments(self, unit=u.arcsec): 'Return [width_y, width_x] first moments of the 2D gaussian.\n\n Parameters\n ----------\n unit : `astropy.units.Unit`\n Unit of the returned moments (arcseconds by default).\n If None, moments will be in pixels.\n\n Returns\n -------\n out : float array\n\n ' total = np.abs(self.data).sum() (P, Q) = np.indices(self.data.shape) p = np.argmax(((Q * np.abs(self.data)).sum(axis=1) / total)) q = np.argmax(((P * np.abs(self.data)).sum(axis=0) / total)) col = self.data[(int(p), :)] width_q = np.sqrt((np.abs(((np.arange(col.size) - p) * col)).sum() / np.abs(col).sum())) row = self.data[(:, int(q))] width_p = np.sqrt((np.abs(((np.arange(row.size) - q) * row)).sum() / np.abs(row).sum())) mom = np.array([width_p, width_q]) if (unit is not None): mom *= self.wcs.get_step(unit=unit) return mom<|docstring|>Return [width_y, width_x] first moments of the 2D gaussian. Parameters ---------- unit : `astropy.units.Unit` Unit of the returned moments (arcseconds by default). If None, moments will be in pixels. Returns ------- out : float array<|endoftext|>
ffeec4a997d9a57ffafa78163f1ee149a72e2885d272234490e2d0da45510a82
def gauss_fit(self, pos_min=None, pos_max=None, center=None, flux=None, fwhm=None, circular=False, cont=0, fit_back=True, rot=0, peak=False, factor=1, weight=True, plot=False, unit_center=u.deg, unit_fwhm=u.arcsec, maxiter=0, verbose=True, full_output=0): 'Perform Gaussian fit on image.\n\n Parameters\n ----------\n pos_min : (float,float)\n Minimum y and x values. Their unit is given by the unit_center\n parameter (degrees by default).\n pos_max : (float,float)\n Maximum y and x values. Their unit is given by the unit_center\n parameter (degrees by default).\n center : (float,float)\n Initial gaussian center (y_peak,x_peak) If None it is estimated.\n The unit is given by the unit_center parameter (degrees by\n default).\n flux : float\n Initial integrated gaussian flux or gaussian peak value if peak is\n True. If None, peak value is estimated.\n fwhm : (float,float)\n Initial gaussian fwhm (fwhm_y,fwhm_x). If None, they are estimated.\n The unit is given by ``unit_fwhm`` (arcseconds by default).\n circular : bool\n True: circular gaussian, False: elliptical gaussian\n cont : float\n continuum value, 0 by default.\n fit_back : bool\n False: continuum value is fixed,\n True: continuum value is a fit parameter.\n rot : float\n Initial rotation in degree.\n If None, rotation is fixed to 0.\n peak : bool\n If true, flux contains a gaussian peak value.\n factor : int\n If factor<=1, gaussian value is computed in the center of each\n pixel. If factor>1, for each pixel, gaussian value is the sum of\n the gaussian values on the factor*factor pixels divided by the\n pixel area.\n weight : bool\n If weight is True, the weight is computed as the inverse of\n variance.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_fwhm : `astropy.units.Unit`\n FWHM unit. Arcseconds by default (use None for radius in pixels)\n maxiter : int\n The maximum number of iterations during the sum of square\n minimization.\n plot : bool\n If True, the gaussian is plotted.\n verbose : bool\n If True, the Gaussian parameters are printed at the end of the\n method.\n full_output : bool\n True-zero to return a `mpdaf.obj.Gauss2D` object containing\n the gauss image.\n\n Returns\n -------\n out : `mpdaf.obj.Gauss2D`\n\n ' (ima, pmin, pmax, qmin, qmax, data, wght, p, q, center, fwhm) = self._prepare_fit_parameters(pos_min, pos_max, weight=weight, center=center, unit_center=unit_center, fwhm=fwhm, unit_fwhm=unit_fwhm) if (flux is None): peak = (ima._data[(int(center[0]), int(center[1]))] - cont) elif (peak is True): peak = (flux - cont) N = len(p) width = (fwhm * gaussian_fwhm_to_sigma) flux = ((peak * np.sqrt(((2 * np.pi) * (width[0] ** 2)))) * np.sqrt(((2 * np.pi) * (width[1] ** 2)))) if circular: rot = None if (not fit_back): gaussfit = (lambda v, p, q: (cont + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((p - v[1]) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((q - v[3]) ** 2)) / (2 * (v[2] ** 2))))))) v0 = [flux, center[0], width[0], center[1]] else: gaussfit = (lambda v, p, q: (v[4] + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((p - v[1]) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((q - v[3]) ** 2)) / (2 * (v[2] ** 2))))))) v0 = [flux, center[0], width[0], center[1], cont] elif (not fit_back): if (rot is None): gaussfit = (lambda v, p, q: (cont + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((p - v[1]) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[4] ** 2))))) * np.exp(((- ((q - v[3]) ** 2)) / (2 * (v[4] ** 2))))))) v0 = [flux, center[0], width[0], center[1], width[1]] else: rot = ((np.pi * rot) / 180.0) gaussfit = (lambda v, p, q: (cont + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((((p - v[1]) * np.cos(v[5])) - ((q - v[3]) * np.sin(v[5]))) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[4] ** 2))))) * np.exp(((- ((((p - v[1]) * np.sin(v[5])) + ((q - v[3]) * np.cos(v[5]))) ** 2)) / (2 * (v[4] ** 2))))))) v0 = [flux, center[0], width[0], center[1], width[1], rot] elif (rot is None): gaussfit = (lambda v, p, q: (v[5] + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((p - v[1]) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[4] ** 2))))) * np.exp(((- ((q - v[3]) ** 2)) / (2 * (v[4] ** 2))))))) v0 = [flux, center[0], width[0], center[1], width[1], cont] else: rot = ((np.pi * rot) / 180.0) gaussfit = (lambda v, p, q: (v[6] + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((((p - v[1]) * np.cos(v[5])) - ((q - v[3]) * np.sin(v[5]))) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[4] ** 2))))) * np.exp(((- ((((p - v[1]) * np.sin(v[5])) + ((q - v[3]) * np.cos(v[5]))) ** 2)) / (2 * (v[4] ** 2))))))) v0 = [flux, center[0], width[0], center[1], width[1], rot, cont] if (factor > 1): factor = int(factor) deci = ((((np.ones((factor, factor)) * np.arange(factor)[(:, np.newaxis)]) / float(factor)) + (1.0 / float((factor * 2)))) - 0.5) fp = (p[(:, np.newaxis)] + deci.ravel()[(np.newaxis, :)]).ravel() fq = (q[(:, np.newaxis)] + deci.T.ravel()[(np.newaxis, :)]).ravel() pixcrd = np.array(list(zip(fp, fq))) e_gauss_fit = (lambda v, p, q, data, w: (w * (((gaussfit(v, p, q).reshape(N, (factor * factor)).sum(1) / factor) / factor).T.ravel() - data))) (v, covar, info, mesg, success) = leastsq(e_gauss_fit, v0[:], args=(pixcrd[(:, 0)], pixcrd[(:, 1)], data, wght), maxfev=maxiter, full_output=1) else: e_gauss_fit = (lambda v, p, q, data, w: (w * (gaussfit(v, p, q) - data))) (v, covar, info, mesg, success) = leastsq(e_gauss_fit, v0[:], args=(p, q, data, wght), maxfev=maxiter, full_output=1) if (success not in [1, 2, 3, 4]): self._logger.info(mesg) chisq = sum((info['fvec'] * info['fvec'])) dof = (len(info['fvec']) - len(v)) if (covar is not None): err = np.array([(np.sqrt(np.abs(covar[(i, i)])) * np.sqrt(np.abs((chisq / dof)))) for i in range(len(v))]) else: err = None v[1] += int(pmin) v[3] += int(qmin) if plot: pp = np.arange(pmin, pmax, (float((pmax - pmin)) / 100)) qq = np.arange(qmin, qmax, (float((qmax - qmin)) / 100)) ff = np.empty((np.shape(pp)[0], np.shape(qq)[0])) for i in range(np.shape(pp)[0]): ff[(i, :)] = gaussfit(v, pp[i], qq[:]) self._ax.contour(qq, pp, ff, 5) flux = v[0] p_peak = v[1] q_peak = v[3] if circular: if fit_back: cont = v[4] p_width = np.abs(v[2]) q_width = p_width rot = 0 else: if fit_back: if (rot is None): cont = v[5] else: cont = v[6] if (rot is None): p_width = np.abs(v[2]) q_width = np.abs(v[4]) rot = 0 elif (np.abs(v[2]) > np.abs(v[4])): p_width = np.abs(v[2]) q_width = np.abs(v[4]) rot = (((v[5] * 180.0) / np.pi) % 180) else: p_width = np.abs(v[4]) q_width = np.abs(v[2]) rot = ((((v[5] * 180.0) / np.pi) + 90) % 180) p_fwhm = (p_width * gaussian_sigma_to_fwhm) q_fwhm = (q_width * gaussian_sigma_to_fwhm) peak = ((flux / np.sqrt(((2 * np.pi) * (p_width ** 2)))) / np.sqrt(((2 * np.pi) * (q_width ** 2)))) if (err is not None): err_flux = err[0] err_p_peak = err[1] err_q_peak = err[3] if circular: if fit_back: err_cont = err[4] else: err_cont = 0 err_p_width = np.abs(err[2]) err_q_width = err_p_width err_rot = 0 else: if fit_back: try: err_cont = err[6] except Exception: err_cont = err[5] else: err_cont = 0 if ((np.abs(v[2]) > np.abs(v[4])) or (rot == 0)): err_p_width = np.abs(err[2]) err_q_width = np.abs(err[4]) else: err_p_width = np.abs(err[4]) err_q_width = np.abs(err[2]) try: err_rot = ((err[4] * 180.0) / np.pi) except Exception: err_rot = 0 err_p_fwhm = (err_p_width * gaussian_sigma_to_fwhm) err_q_fwhm = (err_q_width * gaussian_sigma_to_fwhm) err_peak = ((((err_flux * p_width) * q_width) - (flux * ((err_p_width * q_width) + (err_q_width * p_width)))) / (((((2 * np.pi) * p_width) * p_width) * q_width) * q_width)) else: err_flux = np.NAN err_p_peak = np.NAN err_p_width = np.NAN err_p_fwhm = np.NAN err_q_peak = np.NAN err_q_width = np.NAN err_q_fwhm = np.NAN err_rot = np.NAN err_peak = np.NAN err_cont = np.NAN if (unit_center is not None): center = self.wcs.pix2sky([p_peak, q_peak], unit=unit_center)[0] err_center = (np.array([err_p_peak, err_q_peak]) * self.wcs.get_step(unit=unit_center)) else: center = (p_peak, q_peak) err_center = (err_p_peak, err_q_peak) step = self.wcs.get_step(unit=unit_fwhm) fwhm = (np.array([p_fwhm, q_fwhm]) * step) err_fwhm = (np.array([err_p_fwhm, err_q_fwhm]) * step) gauss = Gauss2D(center, flux, fwhm, cont, rot, peak, err_center, err_flux, err_fwhm, err_cont, err_rot, err_peak) if verbose: gauss.print_param() if full_output: ima = gauss_image(shape=self.shape, wcs=self.wcs, gauss=gauss, unit_center=unit_center, unit_fwhm=unit_fwhm) gauss.ima = ima return gauss
Perform Gaussian fit on image. Parameters ---------- pos_min : (float,float) Minimum y and x values. Their unit is given by the unit_center parameter (degrees by default). pos_max : (float,float) Maximum y and x values. Their unit is given by the unit_center parameter (degrees by default). center : (float,float) Initial gaussian center (y_peak,x_peak) If None it is estimated. The unit is given by the unit_center parameter (degrees by default). flux : float Initial integrated gaussian flux or gaussian peak value if peak is True. If None, peak value is estimated. fwhm : (float,float) Initial gaussian fwhm (fwhm_y,fwhm_x). If None, they are estimated. The unit is given by ``unit_fwhm`` (arcseconds by default). circular : bool True: circular gaussian, False: elliptical gaussian cont : float continuum value, 0 by default. fit_back : bool False: continuum value is fixed, True: continuum value is a fit parameter. rot : float Initial rotation in degree. If None, rotation is fixed to 0. peak : bool If true, flux contains a gaussian peak value. factor : int If factor<=1, gaussian value is computed in the center of each pixel. If factor>1, for each pixel, gaussian value is the sum of the gaussian values on the factor*factor pixels divided by the pixel area. weight : bool If weight is True, the weight is computed as the inverse of variance. unit_center : `astropy.units.Unit` type of the center and position coordinates. Degrees by default (use None for coordinates in pixels). unit_fwhm : `astropy.units.Unit` FWHM unit. Arcseconds by default (use None for radius in pixels) maxiter : int The maximum number of iterations during the sum of square minimization. plot : bool If True, the gaussian is plotted. verbose : bool If True, the Gaussian parameters are printed at the end of the method. full_output : bool True-zero to return a `mpdaf.obj.Gauss2D` object containing the gauss image. Returns ------- out : `mpdaf.obj.Gauss2D`
lib/mpdaf/obj/image.py
gauss_fit
musevlt/mpdaf
4
python
def gauss_fit(self, pos_min=None, pos_max=None, center=None, flux=None, fwhm=None, circular=False, cont=0, fit_back=True, rot=0, peak=False, factor=1, weight=True, plot=False, unit_center=u.deg, unit_fwhm=u.arcsec, maxiter=0, verbose=True, full_output=0): 'Perform Gaussian fit on image.\n\n Parameters\n ----------\n pos_min : (float,float)\n Minimum y and x values. Their unit is given by the unit_center\n parameter (degrees by default).\n pos_max : (float,float)\n Maximum y and x values. Their unit is given by the unit_center\n parameter (degrees by default).\n center : (float,float)\n Initial gaussian center (y_peak,x_peak) If None it is estimated.\n The unit is given by the unit_center parameter (degrees by\n default).\n flux : float\n Initial integrated gaussian flux or gaussian peak value if peak is\n True. If None, peak value is estimated.\n fwhm : (float,float)\n Initial gaussian fwhm (fwhm_y,fwhm_x). If None, they are estimated.\n The unit is given by ``unit_fwhm`` (arcseconds by default).\n circular : bool\n True: circular gaussian, False: elliptical gaussian\n cont : float\n continuum value, 0 by default.\n fit_back : bool\n False: continuum value is fixed,\n True: continuum value is a fit parameter.\n rot : float\n Initial rotation in degree.\n If None, rotation is fixed to 0.\n peak : bool\n If true, flux contains a gaussian peak value.\n factor : int\n If factor<=1, gaussian value is computed in the center of each\n pixel. If factor>1, for each pixel, gaussian value is the sum of\n the gaussian values on the factor*factor pixels divided by the\n pixel area.\n weight : bool\n If weight is True, the weight is computed as the inverse of\n variance.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_fwhm : `astropy.units.Unit`\n FWHM unit. Arcseconds by default (use None for radius in pixels)\n maxiter : int\n The maximum number of iterations during the sum of square\n minimization.\n plot : bool\n If True, the gaussian is plotted.\n verbose : bool\n If True, the Gaussian parameters are printed at the end of the\n method.\n full_output : bool\n True-zero to return a `mpdaf.obj.Gauss2D` object containing\n the gauss image.\n\n Returns\n -------\n out : `mpdaf.obj.Gauss2D`\n\n ' (ima, pmin, pmax, qmin, qmax, data, wght, p, q, center, fwhm) = self._prepare_fit_parameters(pos_min, pos_max, weight=weight, center=center, unit_center=unit_center, fwhm=fwhm, unit_fwhm=unit_fwhm) if (flux is None): peak = (ima._data[(int(center[0]), int(center[1]))] - cont) elif (peak is True): peak = (flux - cont) N = len(p) width = (fwhm * gaussian_fwhm_to_sigma) flux = ((peak * np.sqrt(((2 * np.pi) * (width[0] ** 2)))) * np.sqrt(((2 * np.pi) * (width[1] ** 2)))) if circular: rot = None if (not fit_back): gaussfit = (lambda v, p, q: (cont + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((p - v[1]) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((q - v[3]) ** 2)) / (2 * (v[2] ** 2))))))) v0 = [flux, center[0], width[0], center[1]] else: gaussfit = (lambda v, p, q: (v[4] + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((p - v[1]) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((q - v[3]) ** 2)) / (2 * (v[2] ** 2))))))) v0 = [flux, center[0], width[0], center[1], cont] elif (not fit_back): if (rot is None): gaussfit = (lambda v, p, q: (cont + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((p - v[1]) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[4] ** 2))))) * np.exp(((- ((q - v[3]) ** 2)) / (2 * (v[4] ** 2))))))) v0 = [flux, center[0], width[0], center[1], width[1]] else: rot = ((np.pi * rot) / 180.0) gaussfit = (lambda v, p, q: (cont + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((((p - v[1]) * np.cos(v[5])) - ((q - v[3]) * np.sin(v[5]))) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[4] ** 2))))) * np.exp(((- ((((p - v[1]) * np.sin(v[5])) + ((q - v[3]) * np.cos(v[5]))) ** 2)) / (2 * (v[4] ** 2))))))) v0 = [flux, center[0], width[0], center[1], width[1], rot] elif (rot is None): gaussfit = (lambda v, p, q: (v[5] + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((p - v[1]) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[4] ** 2))))) * np.exp(((- ((q - v[3]) ** 2)) / (2 * (v[4] ** 2))))))) v0 = [flux, center[0], width[0], center[1], width[1], cont] else: rot = ((np.pi * rot) / 180.0) gaussfit = (lambda v, p, q: (v[6] + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((((p - v[1]) * np.cos(v[5])) - ((q - v[3]) * np.sin(v[5]))) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[4] ** 2))))) * np.exp(((- ((((p - v[1]) * np.sin(v[5])) + ((q - v[3]) * np.cos(v[5]))) ** 2)) / (2 * (v[4] ** 2))))))) v0 = [flux, center[0], width[0], center[1], width[1], rot, cont] if (factor > 1): factor = int(factor) deci = ((((np.ones((factor, factor)) * np.arange(factor)[(:, np.newaxis)]) / float(factor)) + (1.0 / float((factor * 2)))) - 0.5) fp = (p[(:, np.newaxis)] + deci.ravel()[(np.newaxis, :)]).ravel() fq = (q[(:, np.newaxis)] + deci.T.ravel()[(np.newaxis, :)]).ravel() pixcrd = np.array(list(zip(fp, fq))) e_gauss_fit = (lambda v, p, q, data, w: (w * (((gaussfit(v, p, q).reshape(N, (factor * factor)).sum(1) / factor) / factor).T.ravel() - data))) (v, covar, info, mesg, success) = leastsq(e_gauss_fit, v0[:], args=(pixcrd[(:, 0)], pixcrd[(:, 1)], data, wght), maxfev=maxiter, full_output=1) else: e_gauss_fit = (lambda v, p, q, data, w: (w * (gaussfit(v, p, q) - data))) (v, covar, info, mesg, success) = leastsq(e_gauss_fit, v0[:], args=(p, q, data, wght), maxfev=maxiter, full_output=1) if (success not in [1, 2, 3, 4]): self._logger.info(mesg) chisq = sum((info['fvec'] * info['fvec'])) dof = (len(info['fvec']) - len(v)) if (covar is not None): err = np.array([(np.sqrt(np.abs(covar[(i, i)])) * np.sqrt(np.abs((chisq / dof)))) for i in range(len(v))]) else: err = None v[1] += int(pmin) v[3] += int(qmin) if plot: pp = np.arange(pmin, pmax, (float((pmax - pmin)) / 100)) qq = np.arange(qmin, qmax, (float((qmax - qmin)) / 100)) ff = np.empty((np.shape(pp)[0], np.shape(qq)[0])) for i in range(np.shape(pp)[0]): ff[(i, :)] = gaussfit(v, pp[i], qq[:]) self._ax.contour(qq, pp, ff, 5) flux = v[0] p_peak = v[1] q_peak = v[3] if circular: if fit_back: cont = v[4] p_width = np.abs(v[2]) q_width = p_width rot = 0 else: if fit_back: if (rot is None): cont = v[5] else: cont = v[6] if (rot is None): p_width = np.abs(v[2]) q_width = np.abs(v[4]) rot = 0 elif (np.abs(v[2]) > np.abs(v[4])): p_width = np.abs(v[2]) q_width = np.abs(v[4]) rot = (((v[5] * 180.0) / np.pi) % 180) else: p_width = np.abs(v[4]) q_width = np.abs(v[2]) rot = ((((v[5] * 180.0) / np.pi) + 90) % 180) p_fwhm = (p_width * gaussian_sigma_to_fwhm) q_fwhm = (q_width * gaussian_sigma_to_fwhm) peak = ((flux / np.sqrt(((2 * np.pi) * (p_width ** 2)))) / np.sqrt(((2 * np.pi) * (q_width ** 2)))) if (err is not None): err_flux = err[0] err_p_peak = err[1] err_q_peak = err[3] if circular: if fit_back: err_cont = err[4] else: err_cont = 0 err_p_width = np.abs(err[2]) err_q_width = err_p_width err_rot = 0 else: if fit_back: try: err_cont = err[6] except Exception: err_cont = err[5] else: err_cont = 0 if ((np.abs(v[2]) > np.abs(v[4])) or (rot == 0)): err_p_width = np.abs(err[2]) err_q_width = np.abs(err[4]) else: err_p_width = np.abs(err[4]) err_q_width = np.abs(err[2]) try: err_rot = ((err[4] * 180.0) / np.pi) except Exception: err_rot = 0 err_p_fwhm = (err_p_width * gaussian_sigma_to_fwhm) err_q_fwhm = (err_q_width * gaussian_sigma_to_fwhm) err_peak = ((((err_flux * p_width) * q_width) - (flux * ((err_p_width * q_width) + (err_q_width * p_width)))) / (((((2 * np.pi) * p_width) * p_width) * q_width) * q_width)) else: err_flux = np.NAN err_p_peak = np.NAN err_p_width = np.NAN err_p_fwhm = np.NAN err_q_peak = np.NAN err_q_width = np.NAN err_q_fwhm = np.NAN err_rot = np.NAN err_peak = np.NAN err_cont = np.NAN if (unit_center is not None): center = self.wcs.pix2sky([p_peak, q_peak], unit=unit_center)[0] err_center = (np.array([err_p_peak, err_q_peak]) * self.wcs.get_step(unit=unit_center)) else: center = (p_peak, q_peak) err_center = (err_p_peak, err_q_peak) step = self.wcs.get_step(unit=unit_fwhm) fwhm = (np.array([p_fwhm, q_fwhm]) * step) err_fwhm = (np.array([err_p_fwhm, err_q_fwhm]) * step) gauss = Gauss2D(center, flux, fwhm, cont, rot, peak, err_center, err_flux, err_fwhm, err_cont, err_rot, err_peak) if verbose: gauss.print_param() if full_output: ima = gauss_image(shape=self.shape, wcs=self.wcs, gauss=gauss, unit_center=unit_center, unit_fwhm=unit_fwhm) gauss.ima = ima return gauss
def gauss_fit(self, pos_min=None, pos_max=None, center=None, flux=None, fwhm=None, circular=False, cont=0, fit_back=True, rot=0, peak=False, factor=1, weight=True, plot=False, unit_center=u.deg, unit_fwhm=u.arcsec, maxiter=0, verbose=True, full_output=0): 'Perform Gaussian fit on image.\n\n Parameters\n ----------\n pos_min : (float,float)\n Minimum y and x values. Their unit is given by the unit_center\n parameter (degrees by default).\n pos_max : (float,float)\n Maximum y and x values. Their unit is given by the unit_center\n parameter (degrees by default).\n center : (float,float)\n Initial gaussian center (y_peak,x_peak) If None it is estimated.\n The unit is given by the unit_center parameter (degrees by\n default).\n flux : float\n Initial integrated gaussian flux or gaussian peak value if peak is\n True. If None, peak value is estimated.\n fwhm : (float,float)\n Initial gaussian fwhm (fwhm_y,fwhm_x). If None, they are estimated.\n The unit is given by ``unit_fwhm`` (arcseconds by default).\n circular : bool\n True: circular gaussian, False: elliptical gaussian\n cont : float\n continuum value, 0 by default.\n fit_back : bool\n False: continuum value is fixed,\n True: continuum value is a fit parameter.\n rot : float\n Initial rotation in degree.\n If None, rotation is fixed to 0.\n peak : bool\n If true, flux contains a gaussian peak value.\n factor : int\n If factor<=1, gaussian value is computed in the center of each\n pixel. If factor>1, for each pixel, gaussian value is the sum of\n the gaussian values on the factor*factor pixels divided by the\n pixel area.\n weight : bool\n If weight is True, the weight is computed as the inverse of\n variance.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_fwhm : `astropy.units.Unit`\n FWHM unit. Arcseconds by default (use None for radius in pixels)\n maxiter : int\n The maximum number of iterations during the sum of square\n minimization.\n plot : bool\n If True, the gaussian is plotted.\n verbose : bool\n If True, the Gaussian parameters are printed at the end of the\n method.\n full_output : bool\n True-zero to return a `mpdaf.obj.Gauss2D` object containing\n the gauss image.\n\n Returns\n -------\n out : `mpdaf.obj.Gauss2D`\n\n ' (ima, pmin, pmax, qmin, qmax, data, wght, p, q, center, fwhm) = self._prepare_fit_parameters(pos_min, pos_max, weight=weight, center=center, unit_center=unit_center, fwhm=fwhm, unit_fwhm=unit_fwhm) if (flux is None): peak = (ima._data[(int(center[0]), int(center[1]))] - cont) elif (peak is True): peak = (flux - cont) N = len(p) width = (fwhm * gaussian_fwhm_to_sigma) flux = ((peak * np.sqrt(((2 * np.pi) * (width[0] ** 2)))) * np.sqrt(((2 * np.pi) * (width[1] ** 2)))) if circular: rot = None if (not fit_back): gaussfit = (lambda v, p, q: (cont + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((p - v[1]) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((q - v[3]) ** 2)) / (2 * (v[2] ** 2))))))) v0 = [flux, center[0], width[0], center[1]] else: gaussfit = (lambda v, p, q: (v[4] + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((p - v[1]) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((q - v[3]) ** 2)) / (2 * (v[2] ** 2))))))) v0 = [flux, center[0], width[0], center[1], cont] elif (not fit_back): if (rot is None): gaussfit = (lambda v, p, q: (cont + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((p - v[1]) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[4] ** 2))))) * np.exp(((- ((q - v[3]) ** 2)) / (2 * (v[4] ** 2))))))) v0 = [flux, center[0], width[0], center[1], width[1]] else: rot = ((np.pi * rot) / 180.0) gaussfit = (lambda v, p, q: (cont + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((((p - v[1]) * np.cos(v[5])) - ((q - v[3]) * np.sin(v[5]))) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[4] ** 2))))) * np.exp(((- ((((p - v[1]) * np.sin(v[5])) + ((q - v[3]) * np.cos(v[5]))) ** 2)) / (2 * (v[4] ** 2))))))) v0 = [flux, center[0], width[0], center[1], width[1], rot] elif (rot is None): gaussfit = (lambda v, p, q: (v[5] + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((p - v[1]) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[4] ** 2))))) * np.exp(((- ((q - v[3]) ** 2)) / (2 * (v[4] ** 2))))))) v0 = [flux, center[0], width[0], center[1], width[1], cont] else: rot = ((np.pi * rot) / 180.0) gaussfit = (lambda v, p, q: (v[6] + ((((v[0] * (1 / np.sqrt(((2 * np.pi) * (v[2] ** 2))))) * np.exp(((- ((((p - v[1]) * np.cos(v[5])) - ((q - v[3]) * np.sin(v[5]))) ** 2)) / (2 * (v[2] ** 2))))) * (1 / np.sqrt(((2 * np.pi) * (v[4] ** 2))))) * np.exp(((- ((((p - v[1]) * np.sin(v[5])) + ((q - v[3]) * np.cos(v[5]))) ** 2)) / (2 * (v[4] ** 2))))))) v0 = [flux, center[0], width[0], center[1], width[1], rot, cont] if (factor > 1): factor = int(factor) deci = ((((np.ones((factor, factor)) * np.arange(factor)[(:, np.newaxis)]) / float(factor)) + (1.0 / float((factor * 2)))) - 0.5) fp = (p[(:, np.newaxis)] + deci.ravel()[(np.newaxis, :)]).ravel() fq = (q[(:, np.newaxis)] + deci.T.ravel()[(np.newaxis, :)]).ravel() pixcrd = np.array(list(zip(fp, fq))) e_gauss_fit = (lambda v, p, q, data, w: (w * (((gaussfit(v, p, q).reshape(N, (factor * factor)).sum(1) / factor) / factor).T.ravel() - data))) (v, covar, info, mesg, success) = leastsq(e_gauss_fit, v0[:], args=(pixcrd[(:, 0)], pixcrd[(:, 1)], data, wght), maxfev=maxiter, full_output=1) else: e_gauss_fit = (lambda v, p, q, data, w: (w * (gaussfit(v, p, q) - data))) (v, covar, info, mesg, success) = leastsq(e_gauss_fit, v0[:], args=(p, q, data, wght), maxfev=maxiter, full_output=1) if (success not in [1, 2, 3, 4]): self._logger.info(mesg) chisq = sum((info['fvec'] * info['fvec'])) dof = (len(info['fvec']) - len(v)) if (covar is not None): err = np.array([(np.sqrt(np.abs(covar[(i, i)])) * np.sqrt(np.abs((chisq / dof)))) for i in range(len(v))]) else: err = None v[1] += int(pmin) v[3] += int(qmin) if plot: pp = np.arange(pmin, pmax, (float((pmax - pmin)) / 100)) qq = np.arange(qmin, qmax, (float((qmax - qmin)) / 100)) ff = np.empty((np.shape(pp)[0], np.shape(qq)[0])) for i in range(np.shape(pp)[0]): ff[(i, :)] = gaussfit(v, pp[i], qq[:]) self._ax.contour(qq, pp, ff, 5) flux = v[0] p_peak = v[1] q_peak = v[3] if circular: if fit_back: cont = v[4] p_width = np.abs(v[2]) q_width = p_width rot = 0 else: if fit_back: if (rot is None): cont = v[5] else: cont = v[6] if (rot is None): p_width = np.abs(v[2]) q_width = np.abs(v[4]) rot = 0 elif (np.abs(v[2]) > np.abs(v[4])): p_width = np.abs(v[2]) q_width = np.abs(v[4]) rot = (((v[5] * 180.0) / np.pi) % 180) else: p_width = np.abs(v[4]) q_width = np.abs(v[2]) rot = ((((v[5] * 180.0) / np.pi) + 90) % 180) p_fwhm = (p_width * gaussian_sigma_to_fwhm) q_fwhm = (q_width * gaussian_sigma_to_fwhm) peak = ((flux / np.sqrt(((2 * np.pi) * (p_width ** 2)))) / np.sqrt(((2 * np.pi) * (q_width ** 2)))) if (err is not None): err_flux = err[0] err_p_peak = err[1] err_q_peak = err[3] if circular: if fit_back: err_cont = err[4] else: err_cont = 0 err_p_width = np.abs(err[2]) err_q_width = err_p_width err_rot = 0 else: if fit_back: try: err_cont = err[6] except Exception: err_cont = err[5] else: err_cont = 0 if ((np.abs(v[2]) > np.abs(v[4])) or (rot == 0)): err_p_width = np.abs(err[2]) err_q_width = np.abs(err[4]) else: err_p_width = np.abs(err[4]) err_q_width = np.abs(err[2]) try: err_rot = ((err[4] * 180.0) / np.pi) except Exception: err_rot = 0 err_p_fwhm = (err_p_width * gaussian_sigma_to_fwhm) err_q_fwhm = (err_q_width * gaussian_sigma_to_fwhm) err_peak = ((((err_flux * p_width) * q_width) - (flux * ((err_p_width * q_width) + (err_q_width * p_width)))) / (((((2 * np.pi) * p_width) * p_width) * q_width) * q_width)) else: err_flux = np.NAN err_p_peak = np.NAN err_p_width = np.NAN err_p_fwhm = np.NAN err_q_peak = np.NAN err_q_width = np.NAN err_q_fwhm = np.NAN err_rot = np.NAN err_peak = np.NAN err_cont = np.NAN if (unit_center is not None): center = self.wcs.pix2sky([p_peak, q_peak], unit=unit_center)[0] err_center = (np.array([err_p_peak, err_q_peak]) * self.wcs.get_step(unit=unit_center)) else: center = (p_peak, q_peak) err_center = (err_p_peak, err_q_peak) step = self.wcs.get_step(unit=unit_fwhm) fwhm = (np.array([p_fwhm, q_fwhm]) * step) err_fwhm = (np.array([err_p_fwhm, err_q_fwhm]) * step) gauss = Gauss2D(center, flux, fwhm, cont, rot, peak, err_center, err_flux, err_fwhm, err_cont, err_rot, err_peak) if verbose: gauss.print_param() if full_output: ima = gauss_image(shape=self.shape, wcs=self.wcs, gauss=gauss, unit_center=unit_center, unit_fwhm=unit_fwhm) gauss.ima = ima return gauss<|docstring|>Perform Gaussian fit on image. Parameters ---------- pos_min : (float,float) Minimum y and x values. Their unit is given by the unit_center parameter (degrees by default). pos_max : (float,float) Maximum y and x values. Their unit is given by the unit_center parameter (degrees by default). center : (float,float) Initial gaussian center (y_peak,x_peak) If None it is estimated. The unit is given by the unit_center parameter (degrees by default). flux : float Initial integrated gaussian flux or gaussian peak value if peak is True. If None, peak value is estimated. fwhm : (float,float) Initial gaussian fwhm (fwhm_y,fwhm_x). If None, they are estimated. The unit is given by ``unit_fwhm`` (arcseconds by default). circular : bool True: circular gaussian, False: elliptical gaussian cont : float continuum value, 0 by default. fit_back : bool False: continuum value is fixed, True: continuum value is a fit parameter. rot : float Initial rotation in degree. If None, rotation is fixed to 0. peak : bool If true, flux contains a gaussian peak value. factor : int If factor<=1, gaussian value is computed in the center of each pixel. If factor>1, for each pixel, gaussian value is the sum of the gaussian values on the factor*factor pixels divided by the pixel area. weight : bool If weight is True, the weight is computed as the inverse of variance. unit_center : `astropy.units.Unit` type of the center and position coordinates. Degrees by default (use None for coordinates in pixels). unit_fwhm : `astropy.units.Unit` FWHM unit. Arcseconds by default (use None for radius in pixels) maxiter : int The maximum number of iterations during the sum of square minimization. plot : bool If True, the gaussian is plotted. verbose : bool If True, the Gaussian parameters are printed at the end of the method. full_output : bool True-zero to return a `mpdaf.obj.Gauss2D` object containing the gauss image. Returns ------- out : `mpdaf.obj.Gauss2D`<|endoftext|>
43409319e973e56b775632bb6be1b3a5d64787d645a0ec4e36d2cf640cc030b3
def moffat_fit(self, pos_min=None, pos_max=None, center=None, fwhm=None, flux=None, n=2.0, circular=False, cont=0, fit_back=True, rot=0, peak=False, factor=1, weight=True, plot=False, unit_center=u.deg, unit_fwhm=u.arcsec, verbose=True, full_output=0, fit_n=True, maxiter=0): 'Perform moffat fit on image.\n\n Parameters\n ----------\n\n pos_min : (float,float)\n Minimum y and x values. Their unit is given by the unit_center\n parameter (degrees by default).\n pos_max : (float,float)\n Maximum y and x values. Their unit is given by the unit_center\n parameter (degrees by default).\n center : (float,float)\n Initial moffat center (y_peak,x_peak). If None it is estimated.\n The unit is given by the unit_center parameter (degrees by\n default).\n flux : float\n Initial integrated gaussian flux or gaussian peak value if peak is\n True. If None, peak value is estimated.\n fwhm : (float,float)\n Initial gaussian fwhm (fwhm_y,fwhm_x). If None, they are estimated.\n Their unit is given by the unit_fwhm parameter (arcseconds by\n default).\n n : int\n Initial atmospheric scattering coefficient.\n circular : bool\n True: circular moffat, False: elliptical moffat\n cont : float\n continuum value, 0 by default.\n fit_back : bool\n False: continuum value is fixed,\n True: continuum value is a fit parameter.\n rot : float\n Initial angle position in degree.\n peak : bool\n If true, flux contains a gaussian peak value.\n factor : int\n If factor<=1, gaussian is computed in the center of each pixel.\n If factor>1, for each pixel, gaussian value is the sum of the\n gaussian values on the factor*factor pixels divided by the pixel\n area.\n weight : bool\n If weight is True, the weight is computed as the inverse of\n variance.\n plot : bool\n If True, the gaussian is plotted.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_fwhm : `astropy.units.Unit`\n FWHM unit. Arcseconds by default (use None for radius in pixels)\n full_output : bool\n True to return a `mpdaf.obj.Moffat2D` object containing the\n moffat image.\n fit_n : bool\n False: n value is fixed,\n True: n value is a fit parameter.\n maxiter : int\n The maximum number of iterations during the sum of square\n minimization.\n\n Returns\n -------\n out : `mpdaf.obj.Moffat2D`\n\n ' (ima, pmin, pmax, qmin, qmax, data, wght, p, q, center, fwhm) = self._prepare_fit_parameters(pos_min, pos_max, weight=weight, center=center, unit_center=unit_center, fwhm=fwhm, unit_fwhm=unit_fwhm) N = len(p) a = (fwhm[0] / (2 * np.sqrt(((2 ** (1.0 / n)) - 1.0)))) e = (fwhm[0] / fwhm[1]) if (flux is None): I = (ima.data.data[(int(center[0]), int(center[1]))] - cont) elif (peak is True): I = (flux - cont) else: I = ((flux * (n - 1)) / (((np.pi * a) * a) * e)) def moffat(c, x, y, amplitude, x_0, y_0, alpha, beta, e): 'Two dimensional Moffat model function' rr_gg = ((((x - x_0) / alpha) ** 2) + ((((y - y_0) / alpha) / e) ** 2)) return (c + (amplitude * ((1 + rr_gg) ** (- beta)))) if circular: rot = None if (not fit_back): if fit_n: moffatfit = (lambda v, p, q: moffat(cont, p, q, v[0], v[1], v[2], v[3], v[4], 1)) v0 = [I, center[0], center[1], a, n] else: moffatfit = (lambda v, p, q: moffat(cont, p, q, v[0], v[1], v[2], v[3], n, 1)) v0 = [I, center[0], center[1], a] elif fit_n: moffatfit = (lambda v, p, q: moffat(v[5], p, q, v[0], v[1], v[2], v[3], v[4], 1)) v0 = [I, center[0], center[1], a, n, cont] else: moffatfit = (lambda v, p, q: moffat(v[4], p, q, v[0], v[1], v[2], v[3], n, 1)) v0 = [I, center[0], center[1], a, cont] elif (not fit_back): if (rot is None): if fit_n: moffatfit = (lambda v, p, q: moffat(cont, p, q, v[0], v[1], v[2], v[3], v[4], v[5])) v0 = [I, center[0], center[1], a, n, e] else: moffatfit = (lambda v, p, q: moffat(cont, p, q, v[0], v[1], v[2], v[3], n, v[5])) v0 = [I, center[0], center[1], a, e] else: rot = ((np.pi * rot) / 180.0) if fit_n: moffatfit = (lambda v, p, q: (cont + (v[0] * (((1 + (((((p - v[1]) * np.cos(v[6])) - ((q - v[2]) * np.sin(v[6]))) / v[3]) ** 2)) + ((((((p - v[1]) * np.sin(v[6])) + ((q - v[2]) * np.cos(v[6]))) / v[3]) / v[5]) ** 2)) ** (- v[4]))))) v0 = [I, center[0], center[1], a, n, e, rot] else: moffatfit = (lambda v, p, q: (cont + (v[0] * (((1 + (((((p - v[1]) * np.cos(v[5])) - ((q - v[2]) * np.sin(v[5]))) / v[3]) ** 2)) + ((((((p - v[1]) * np.sin(v[5])) + ((q - v[2]) * np.cos(v[5]))) / v[3]) / v[4]) ** 2)) ** (- n))))) v0 = [I, center[0], center[1], a, e, rot] elif (rot is None): if fit_n: moffatfit = (lambda v, p, q: moffat(v[6], p, q, v[0], v[1], v[2], v[3], v[4], v[5])) v0 = [I, center[0], center[1], a, n, e, cont] else: moffatfit = (lambda v, p, q: moffat(v[5], p, q, v[0], v[1], v[2], v[3], n, v[4])) v0 = [I, center[0], center[1], a, e, cont] else: rot = ((np.pi * rot) / 180.0) if fit_n: moffatfit = (lambda v, p, q: (v[7] + (v[0] * (((1 + (((((p - v[1]) * np.cos(v[6])) - ((q - v[2]) * np.sin(v[6]))) / v[3]) ** 2)) + ((((((p - v[1]) * np.sin(v[6])) + ((q - v[2]) * np.cos(v[6]))) / v[3]) / v[5]) ** 2)) ** (- v[4]))))) v0 = [I, center[0], center[1], a, n, e, rot, cont] else: moffatfit = (lambda v, p, q: (v[6] + (v[0] * (((1 + (((((p - v[1]) * np.cos(v[5])) - ((q - v[2]) * np.sin(v[5]))) / v[3]) ** 2)) + ((((((p - v[1]) * np.sin(v[5])) + ((q - v[2]) * np.cos(v[5]))) / v[3]) / v[4]) ** 2)) ** (- n))))) v0 = [I, center[0], center[1], a, e, rot, cont] if (factor > 1): factor = int(factor) deci = (((np.ones((factor, factor)) * np.arange(factor)[(:, np.newaxis)]) / float(factor)) + (1 / float((factor * 2)))) fp = (p[(:, np.newaxis)] + deci.ravel()[(np.newaxis, :)]).ravel() fq = (q[(:, np.newaxis)] + deci.T.ravel()[(np.newaxis, :)]).ravel() pixcrd = np.array(list(zip(fp, fq))) e_moffat_fit = (lambda v, p, q, data, w: (w * (((moffatfit(v, p, q).reshape(N, (factor * factor)).sum(1) / factor) / factor).T.ravel() - data))) (v, covar, info, mesg, success) = leastsq(e_moffat_fit, v0[:], args=(pixcrd[(:, 0)], pixcrd[(:, 1)], data, wght), maxfev=maxiter, full_output=1) else: e_moffat_fit = (lambda v, p, q, data, w: (w * (moffatfit(v, p, q) - data))) (v, covar, info, mesg, success) = leastsq(e_moffat_fit, v0[:], args=(p, q, data, wght), maxfev=maxiter, full_output=1) if (success not in [1, 2, 3, 4]): self._logger.warning(mesg) chisq = sum((info['fvec'] * info['fvec'])) dof = (len(info['fvec']) - len(v)) if (covar is not None): err = np.array([(np.sqrt(np.abs(covar[(i, i)])) * np.sqrt(np.abs((chisq / dof)))) for i in range(len(v))]) else: err = np.zeros_like(v) err[:] = np.abs((v[:] - v0[:])) v[1] += int(pmin) v[2] += int(qmin) if plot: pp = np.arange(pmin, pmax, (float((pmax - pmin)) / 100)) qq = np.arange(qmin, qmax, (float((qmax - qmin)) / 100)) ff = np.empty((np.shape(pp)[0], np.shape(qq)[0])) for i in range(np.shape(pp)[0]): ff[(i, :)] = moffatfit(v, pp[i], qq[:]) self._ax.contour(qq, pp, ff, 5) (I, p_peak, q_peak) = v[:3] a = np.abs(v[3]) v = list(v[4:]) if fit_back: cont = v.pop() if fit_n: n = v.pop(0) _fwhm = (a * (2 * np.sqrt(((2 ** (1.0 / n)) - 1.0)))) if circular: rot = 0 fwhm = (_fwhm, _fwhm) else: e = v.pop(0) if (e < 1): fwhm = (_fwhm, (_fwhm * e)) else: fwhm = ((_fwhm * e), _fwhm) if (rot is None): rot = 0 elif (e < 1): rot = (((v[0] * 180.0) / np.pi) % 180) else: rot = ((((v[0] * 180.0) / np.pi) + 90) % 180) flux = ((I / (n - 1)) * (((np.pi * a) * a) * e)) if (err is not None): (err_I, err_p_peak, err_q_peak) = err[:3] err_a = err[3] if fit_n: err_n = err[4] err_fwhm = (err_a * n) if circular: err_e = 0 err_rot = 0 err_fwhm = np.array([err_fwhm, err_fwhm]) if fit_back: err_cont = err[5] else: err_cont = 0 err_flux = (((err_I * err_n) * err_a) * err_a) else: err_e = err[5] if (err_e != 0): err_fwhm = np.array([err_fwhm, (err_fwhm / err_e)]) else: err_fwhm = np.array([err_fwhm, err_fwhm]) if (rot is None): err_rot = 0 if fit_back: err_cont = err[6] else: err_cont = 0 else: err_rot = ((err[6] * 180.0) / np.pi) if fit_back: err_cont = err[7] else: err_cont = 0 err_flux = ((((err_I * err_n) * err_a) * err_a) * err_e) else: err_n = 0 err_fwhm = (err_a * n) if circular: err_e = 0 err_rot = 0 err_fwhm = np.array([err_fwhm, err_fwhm]) if fit_back: err_cont = err[4] else: err_cont = 0 err_flux = (((err_I * err_n) * err_a) * err_a) else: err_e = err[4] if (err_e != 0): err_fwhm = np.array([err_fwhm, (err_fwhm / err_e)]) else: err_fwhm = np.array([err_fwhm, err_fwhm]) if (rot is None): err_rot = 0 if fit_back: err_cont = err[5] else: err_cont = 0 else: err_rot = ((err[5] * 180.0) / np.pi) if fit_back: err_cont = err[6] else: err_cont = 0 err_flux = ((((err_I * err_n) * err_a) * err_a) * err_e) else: err_I = np.NAN err_p_peak = np.NAN err_q_peak = np.NAN err_a = np.NAN err_n = np.NAN err_e = np.NAN err_rot = np.NAN err_cont = np.NAN err_fwhm = (np.NAN, np.NAN) err_flux = np.NAN if (unit_center is None): center = (p_peak, q_peak) err_center = (err_p_peak, err_q_peak) else: center = self.wcs.pix2sky([p_peak, q_peak], unit=unit_center)[0] err_center = (np.array([err_p_peak, err_q_peak]) * self.wcs.get_step(unit=unit_center)) fwhm = np.array(fwhm) if (unit_fwhm is not None): step0 = self.wcs.get_step(unit=unit_fwhm)[0] a = (a * step0) err_a = (err_a * step0) fwhm = (fwhm * step0) err_fwhm = (err_fwhm * step0) result = Moffat2D(center, flux, fwhm, cont, n, rot, I, err_center, err_flux, err_fwhm, err_cont, err_n, err_rot, err_I) if verbose: result.print_param() if full_output: ima = moffat_image(shape=self.shape, wcs=self.wcs, moffat=result, unit_center=unit_center, unit_fwhm=unit_fwhm) result.ima = ima return result
Perform moffat fit on image. Parameters ---------- pos_min : (float,float) Minimum y and x values. Their unit is given by the unit_center parameter (degrees by default). pos_max : (float,float) Maximum y and x values. Their unit is given by the unit_center parameter (degrees by default). center : (float,float) Initial moffat center (y_peak,x_peak). If None it is estimated. The unit is given by the unit_center parameter (degrees by default). flux : float Initial integrated gaussian flux or gaussian peak value if peak is True. If None, peak value is estimated. fwhm : (float,float) Initial gaussian fwhm (fwhm_y,fwhm_x). If None, they are estimated. Their unit is given by the unit_fwhm parameter (arcseconds by default). n : int Initial atmospheric scattering coefficient. circular : bool True: circular moffat, False: elliptical moffat cont : float continuum value, 0 by default. fit_back : bool False: continuum value is fixed, True: continuum value is a fit parameter. rot : float Initial angle position in degree. peak : bool If true, flux contains a gaussian peak value. factor : int If factor<=1, gaussian is computed in the center of each pixel. If factor>1, for each pixel, gaussian value is the sum of the gaussian values on the factor*factor pixels divided by the pixel area. weight : bool If weight is True, the weight is computed as the inverse of variance. plot : bool If True, the gaussian is plotted. unit_center : `astropy.units.Unit` type of the center and position coordinates. Degrees by default (use None for coordinates in pixels). unit_fwhm : `astropy.units.Unit` FWHM unit. Arcseconds by default (use None for radius in pixels) full_output : bool True to return a `mpdaf.obj.Moffat2D` object containing the moffat image. fit_n : bool False: n value is fixed, True: n value is a fit parameter. maxiter : int The maximum number of iterations during the sum of square minimization. Returns ------- out : `mpdaf.obj.Moffat2D`
lib/mpdaf/obj/image.py
moffat_fit
musevlt/mpdaf
4
python
def moffat_fit(self, pos_min=None, pos_max=None, center=None, fwhm=None, flux=None, n=2.0, circular=False, cont=0, fit_back=True, rot=0, peak=False, factor=1, weight=True, plot=False, unit_center=u.deg, unit_fwhm=u.arcsec, verbose=True, full_output=0, fit_n=True, maxiter=0): 'Perform moffat fit on image.\n\n Parameters\n ----------\n\n pos_min : (float,float)\n Minimum y and x values. Their unit is given by the unit_center\n parameter (degrees by default).\n pos_max : (float,float)\n Maximum y and x values. Their unit is given by the unit_center\n parameter (degrees by default).\n center : (float,float)\n Initial moffat center (y_peak,x_peak). If None it is estimated.\n The unit is given by the unit_center parameter (degrees by\n default).\n flux : float\n Initial integrated gaussian flux or gaussian peak value if peak is\n True. If None, peak value is estimated.\n fwhm : (float,float)\n Initial gaussian fwhm (fwhm_y,fwhm_x). If None, they are estimated.\n Their unit is given by the unit_fwhm parameter (arcseconds by\n default).\n n : int\n Initial atmospheric scattering coefficient.\n circular : bool\n True: circular moffat, False: elliptical moffat\n cont : float\n continuum value, 0 by default.\n fit_back : bool\n False: continuum value is fixed,\n True: continuum value is a fit parameter.\n rot : float\n Initial angle position in degree.\n peak : bool\n If true, flux contains a gaussian peak value.\n factor : int\n If factor<=1, gaussian is computed in the center of each pixel.\n If factor>1, for each pixel, gaussian value is the sum of the\n gaussian values on the factor*factor pixels divided by the pixel\n area.\n weight : bool\n If weight is True, the weight is computed as the inverse of\n variance.\n plot : bool\n If True, the gaussian is plotted.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_fwhm : `astropy.units.Unit`\n FWHM unit. Arcseconds by default (use None for radius in pixels)\n full_output : bool\n True to return a `mpdaf.obj.Moffat2D` object containing the\n moffat image.\n fit_n : bool\n False: n value is fixed,\n True: n value is a fit parameter.\n maxiter : int\n The maximum number of iterations during the sum of square\n minimization.\n\n Returns\n -------\n out : `mpdaf.obj.Moffat2D`\n\n ' (ima, pmin, pmax, qmin, qmax, data, wght, p, q, center, fwhm) = self._prepare_fit_parameters(pos_min, pos_max, weight=weight, center=center, unit_center=unit_center, fwhm=fwhm, unit_fwhm=unit_fwhm) N = len(p) a = (fwhm[0] / (2 * np.sqrt(((2 ** (1.0 / n)) - 1.0)))) e = (fwhm[0] / fwhm[1]) if (flux is None): I = (ima.data.data[(int(center[0]), int(center[1]))] - cont) elif (peak is True): I = (flux - cont) else: I = ((flux * (n - 1)) / (((np.pi * a) * a) * e)) def moffat(c, x, y, amplitude, x_0, y_0, alpha, beta, e): 'Two dimensional Moffat model function' rr_gg = ((((x - x_0) / alpha) ** 2) + ((((y - y_0) / alpha) / e) ** 2)) return (c + (amplitude * ((1 + rr_gg) ** (- beta)))) if circular: rot = None if (not fit_back): if fit_n: moffatfit = (lambda v, p, q: moffat(cont, p, q, v[0], v[1], v[2], v[3], v[4], 1)) v0 = [I, center[0], center[1], a, n] else: moffatfit = (lambda v, p, q: moffat(cont, p, q, v[0], v[1], v[2], v[3], n, 1)) v0 = [I, center[0], center[1], a] elif fit_n: moffatfit = (lambda v, p, q: moffat(v[5], p, q, v[0], v[1], v[2], v[3], v[4], 1)) v0 = [I, center[0], center[1], a, n, cont] else: moffatfit = (lambda v, p, q: moffat(v[4], p, q, v[0], v[1], v[2], v[3], n, 1)) v0 = [I, center[0], center[1], a, cont] elif (not fit_back): if (rot is None): if fit_n: moffatfit = (lambda v, p, q: moffat(cont, p, q, v[0], v[1], v[2], v[3], v[4], v[5])) v0 = [I, center[0], center[1], a, n, e] else: moffatfit = (lambda v, p, q: moffat(cont, p, q, v[0], v[1], v[2], v[3], n, v[5])) v0 = [I, center[0], center[1], a, e] else: rot = ((np.pi * rot) / 180.0) if fit_n: moffatfit = (lambda v, p, q: (cont + (v[0] * (((1 + (((((p - v[1]) * np.cos(v[6])) - ((q - v[2]) * np.sin(v[6]))) / v[3]) ** 2)) + ((((((p - v[1]) * np.sin(v[6])) + ((q - v[2]) * np.cos(v[6]))) / v[3]) / v[5]) ** 2)) ** (- v[4]))))) v0 = [I, center[0], center[1], a, n, e, rot] else: moffatfit = (lambda v, p, q: (cont + (v[0] * (((1 + (((((p - v[1]) * np.cos(v[5])) - ((q - v[2]) * np.sin(v[5]))) / v[3]) ** 2)) + ((((((p - v[1]) * np.sin(v[5])) + ((q - v[2]) * np.cos(v[5]))) / v[3]) / v[4]) ** 2)) ** (- n))))) v0 = [I, center[0], center[1], a, e, rot] elif (rot is None): if fit_n: moffatfit = (lambda v, p, q: moffat(v[6], p, q, v[0], v[1], v[2], v[3], v[4], v[5])) v0 = [I, center[0], center[1], a, n, e, cont] else: moffatfit = (lambda v, p, q: moffat(v[5], p, q, v[0], v[1], v[2], v[3], n, v[4])) v0 = [I, center[0], center[1], a, e, cont] else: rot = ((np.pi * rot) / 180.0) if fit_n: moffatfit = (lambda v, p, q: (v[7] + (v[0] * (((1 + (((((p - v[1]) * np.cos(v[6])) - ((q - v[2]) * np.sin(v[6]))) / v[3]) ** 2)) + ((((((p - v[1]) * np.sin(v[6])) + ((q - v[2]) * np.cos(v[6]))) / v[3]) / v[5]) ** 2)) ** (- v[4]))))) v0 = [I, center[0], center[1], a, n, e, rot, cont] else: moffatfit = (lambda v, p, q: (v[6] + (v[0] * (((1 + (((((p - v[1]) * np.cos(v[5])) - ((q - v[2]) * np.sin(v[5]))) / v[3]) ** 2)) + ((((((p - v[1]) * np.sin(v[5])) + ((q - v[2]) * np.cos(v[5]))) / v[3]) / v[4]) ** 2)) ** (- n))))) v0 = [I, center[0], center[1], a, e, rot, cont] if (factor > 1): factor = int(factor) deci = (((np.ones((factor, factor)) * np.arange(factor)[(:, np.newaxis)]) / float(factor)) + (1 / float((factor * 2)))) fp = (p[(:, np.newaxis)] + deci.ravel()[(np.newaxis, :)]).ravel() fq = (q[(:, np.newaxis)] + deci.T.ravel()[(np.newaxis, :)]).ravel() pixcrd = np.array(list(zip(fp, fq))) e_moffat_fit = (lambda v, p, q, data, w: (w * (((moffatfit(v, p, q).reshape(N, (factor * factor)).sum(1) / factor) / factor).T.ravel() - data))) (v, covar, info, mesg, success) = leastsq(e_moffat_fit, v0[:], args=(pixcrd[(:, 0)], pixcrd[(:, 1)], data, wght), maxfev=maxiter, full_output=1) else: e_moffat_fit = (lambda v, p, q, data, w: (w * (moffatfit(v, p, q) - data))) (v, covar, info, mesg, success) = leastsq(e_moffat_fit, v0[:], args=(p, q, data, wght), maxfev=maxiter, full_output=1) if (success not in [1, 2, 3, 4]): self._logger.warning(mesg) chisq = sum((info['fvec'] * info['fvec'])) dof = (len(info['fvec']) - len(v)) if (covar is not None): err = np.array([(np.sqrt(np.abs(covar[(i, i)])) * np.sqrt(np.abs((chisq / dof)))) for i in range(len(v))]) else: err = np.zeros_like(v) err[:] = np.abs((v[:] - v0[:])) v[1] += int(pmin) v[2] += int(qmin) if plot: pp = np.arange(pmin, pmax, (float((pmax - pmin)) / 100)) qq = np.arange(qmin, qmax, (float((qmax - qmin)) / 100)) ff = np.empty((np.shape(pp)[0], np.shape(qq)[0])) for i in range(np.shape(pp)[0]): ff[(i, :)] = moffatfit(v, pp[i], qq[:]) self._ax.contour(qq, pp, ff, 5) (I, p_peak, q_peak) = v[:3] a = np.abs(v[3]) v = list(v[4:]) if fit_back: cont = v.pop() if fit_n: n = v.pop(0) _fwhm = (a * (2 * np.sqrt(((2 ** (1.0 / n)) - 1.0)))) if circular: rot = 0 fwhm = (_fwhm, _fwhm) else: e = v.pop(0) if (e < 1): fwhm = (_fwhm, (_fwhm * e)) else: fwhm = ((_fwhm * e), _fwhm) if (rot is None): rot = 0 elif (e < 1): rot = (((v[0] * 180.0) / np.pi) % 180) else: rot = ((((v[0] * 180.0) / np.pi) + 90) % 180) flux = ((I / (n - 1)) * (((np.pi * a) * a) * e)) if (err is not None): (err_I, err_p_peak, err_q_peak) = err[:3] err_a = err[3] if fit_n: err_n = err[4] err_fwhm = (err_a * n) if circular: err_e = 0 err_rot = 0 err_fwhm = np.array([err_fwhm, err_fwhm]) if fit_back: err_cont = err[5] else: err_cont = 0 err_flux = (((err_I * err_n) * err_a) * err_a) else: err_e = err[5] if (err_e != 0): err_fwhm = np.array([err_fwhm, (err_fwhm / err_e)]) else: err_fwhm = np.array([err_fwhm, err_fwhm]) if (rot is None): err_rot = 0 if fit_back: err_cont = err[6] else: err_cont = 0 else: err_rot = ((err[6] * 180.0) / np.pi) if fit_back: err_cont = err[7] else: err_cont = 0 err_flux = ((((err_I * err_n) * err_a) * err_a) * err_e) else: err_n = 0 err_fwhm = (err_a * n) if circular: err_e = 0 err_rot = 0 err_fwhm = np.array([err_fwhm, err_fwhm]) if fit_back: err_cont = err[4] else: err_cont = 0 err_flux = (((err_I * err_n) * err_a) * err_a) else: err_e = err[4] if (err_e != 0): err_fwhm = np.array([err_fwhm, (err_fwhm / err_e)]) else: err_fwhm = np.array([err_fwhm, err_fwhm]) if (rot is None): err_rot = 0 if fit_back: err_cont = err[5] else: err_cont = 0 else: err_rot = ((err[5] * 180.0) / np.pi) if fit_back: err_cont = err[6] else: err_cont = 0 err_flux = ((((err_I * err_n) * err_a) * err_a) * err_e) else: err_I = np.NAN err_p_peak = np.NAN err_q_peak = np.NAN err_a = np.NAN err_n = np.NAN err_e = np.NAN err_rot = np.NAN err_cont = np.NAN err_fwhm = (np.NAN, np.NAN) err_flux = np.NAN if (unit_center is None): center = (p_peak, q_peak) err_center = (err_p_peak, err_q_peak) else: center = self.wcs.pix2sky([p_peak, q_peak], unit=unit_center)[0] err_center = (np.array([err_p_peak, err_q_peak]) * self.wcs.get_step(unit=unit_center)) fwhm = np.array(fwhm) if (unit_fwhm is not None): step0 = self.wcs.get_step(unit=unit_fwhm)[0] a = (a * step0) err_a = (err_a * step0) fwhm = (fwhm * step0) err_fwhm = (err_fwhm * step0) result = Moffat2D(center, flux, fwhm, cont, n, rot, I, err_center, err_flux, err_fwhm, err_cont, err_n, err_rot, err_I) if verbose: result.print_param() if full_output: ima = moffat_image(shape=self.shape, wcs=self.wcs, moffat=result, unit_center=unit_center, unit_fwhm=unit_fwhm) result.ima = ima return result
def moffat_fit(self, pos_min=None, pos_max=None, center=None, fwhm=None, flux=None, n=2.0, circular=False, cont=0, fit_back=True, rot=0, peak=False, factor=1, weight=True, plot=False, unit_center=u.deg, unit_fwhm=u.arcsec, verbose=True, full_output=0, fit_n=True, maxiter=0): 'Perform moffat fit on image.\n\n Parameters\n ----------\n\n pos_min : (float,float)\n Minimum y and x values. Their unit is given by the unit_center\n parameter (degrees by default).\n pos_max : (float,float)\n Maximum y and x values. Their unit is given by the unit_center\n parameter (degrees by default).\n center : (float,float)\n Initial moffat center (y_peak,x_peak). If None it is estimated.\n The unit is given by the unit_center parameter (degrees by\n default).\n flux : float\n Initial integrated gaussian flux or gaussian peak value if peak is\n True. If None, peak value is estimated.\n fwhm : (float,float)\n Initial gaussian fwhm (fwhm_y,fwhm_x). If None, they are estimated.\n Their unit is given by the unit_fwhm parameter (arcseconds by\n default).\n n : int\n Initial atmospheric scattering coefficient.\n circular : bool\n True: circular moffat, False: elliptical moffat\n cont : float\n continuum value, 0 by default.\n fit_back : bool\n False: continuum value is fixed,\n True: continuum value is a fit parameter.\n rot : float\n Initial angle position in degree.\n peak : bool\n If true, flux contains a gaussian peak value.\n factor : int\n If factor<=1, gaussian is computed in the center of each pixel.\n If factor>1, for each pixel, gaussian value is the sum of the\n gaussian values on the factor*factor pixels divided by the pixel\n area.\n weight : bool\n If weight is True, the weight is computed as the inverse of\n variance.\n plot : bool\n If True, the gaussian is plotted.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_fwhm : `astropy.units.Unit`\n FWHM unit. Arcseconds by default (use None for radius in pixels)\n full_output : bool\n True to return a `mpdaf.obj.Moffat2D` object containing the\n moffat image.\n fit_n : bool\n False: n value is fixed,\n True: n value is a fit parameter.\n maxiter : int\n The maximum number of iterations during the sum of square\n minimization.\n\n Returns\n -------\n out : `mpdaf.obj.Moffat2D`\n\n ' (ima, pmin, pmax, qmin, qmax, data, wght, p, q, center, fwhm) = self._prepare_fit_parameters(pos_min, pos_max, weight=weight, center=center, unit_center=unit_center, fwhm=fwhm, unit_fwhm=unit_fwhm) N = len(p) a = (fwhm[0] / (2 * np.sqrt(((2 ** (1.0 / n)) - 1.0)))) e = (fwhm[0] / fwhm[1]) if (flux is None): I = (ima.data.data[(int(center[0]), int(center[1]))] - cont) elif (peak is True): I = (flux - cont) else: I = ((flux * (n - 1)) / (((np.pi * a) * a) * e)) def moffat(c, x, y, amplitude, x_0, y_0, alpha, beta, e): 'Two dimensional Moffat model function' rr_gg = ((((x - x_0) / alpha) ** 2) + ((((y - y_0) / alpha) / e) ** 2)) return (c + (amplitude * ((1 + rr_gg) ** (- beta)))) if circular: rot = None if (not fit_back): if fit_n: moffatfit = (lambda v, p, q: moffat(cont, p, q, v[0], v[1], v[2], v[3], v[4], 1)) v0 = [I, center[0], center[1], a, n] else: moffatfit = (lambda v, p, q: moffat(cont, p, q, v[0], v[1], v[2], v[3], n, 1)) v0 = [I, center[0], center[1], a] elif fit_n: moffatfit = (lambda v, p, q: moffat(v[5], p, q, v[0], v[1], v[2], v[3], v[4], 1)) v0 = [I, center[0], center[1], a, n, cont] else: moffatfit = (lambda v, p, q: moffat(v[4], p, q, v[0], v[1], v[2], v[3], n, 1)) v0 = [I, center[0], center[1], a, cont] elif (not fit_back): if (rot is None): if fit_n: moffatfit = (lambda v, p, q: moffat(cont, p, q, v[0], v[1], v[2], v[3], v[4], v[5])) v0 = [I, center[0], center[1], a, n, e] else: moffatfit = (lambda v, p, q: moffat(cont, p, q, v[0], v[1], v[2], v[3], n, v[5])) v0 = [I, center[0], center[1], a, e] else: rot = ((np.pi * rot) / 180.0) if fit_n: moffatfit = (lambda v, p, q: (cont + (v[0] * (((1 + (((((p - v[1]) * np.cos(v[6])) - ((q - v[2]) * np.sin(v[6]))) / v[3]) ** 2)) + ((((((p - v[1]) * np.sin(v[6])) + ((q - v[2]) * np.cos(v[6]))) / v[3]) / v[5]) ** 2)) ** (- v[4]))))) v0 = [I, center[0], center[1], a, n, e, rot] else: moffatfit = (lambda v, p, q: (cont + (v[0] * (((1 + (((((p - v[1]) * np.cos(v[5])) - ((q - v[2]) * np.sin(v[5]))) / v[3]) ** 2)) + ((((((p - v[1]) * np.sin(v[5])) + ((q - v[2]) * np.cos(v[5]))) / v[3]) / v[4]) ** 2)) ** (- n))))) v0 = [I, center[0], center[1], a, e, rot] elif (rot is None): if fit_n: moffatfit = (lambda v, p, q: moffat(v[6], p, q, v[0], v[1], v[2], v[3], v[4], v[5])) v0 = [I, center[0], center[1], a, n, e, cont] else: moffatfit = (lambda v, p, q: moffat(v[5], p, q, v[0], v[1], v[2], v[3], n, v[4])) v0 = [I, center[0], center[1], a, e, cont] else: rot = ((np.pi * rot) / 180.0) if fit_n: moffatfit = (lambda v, p, q: (v[7] + (v[0] * (((1 + (((((p - v[1]) * np.cos(v[6])) - ((q - v[2]) * np.sin(v[6]))) / v[3]) ** 2)) + ((((((p - v[1]) * np.sin(v[6])) + ((q - v[2]) * np.cos(v[6]))) / v[3]) / v[5]) ** 2)) ** (- v[4]))))) v0 = [I, center[0], center[1], a, n, e, rot, cont] else: moffatfit = (lambda v, p, q: (v[6] + (v[0] * (((1 + (((((p - v[1]) * np.cos(v[5])) - ((q - v[2]) * np.sin(v[5]))) / v[3]) ** 2)) + ((((((p - v[1]) * np.sin(v[5])) + ((q - v[2]) * np.cos(v[5]))) / v[3]) / v[4]) ** 2)) ** (- n))))) v0 = [I, center[0], center[1], a, e, rot, cont] if (factor > 1): factor = int(factor) deci = (((np.ones((factor, factor)) * np.arange(factor)[(:, np.newaxis)]) / float(factor)) + (1 / float((factor * 2)))) fp = (p[(:, np.newaxis)] + deci.ravel()[(np.newaxis, :)]).ravel() fq = (q[(:, np.newaxis)] + deci.T.ravel()[(np.newaxis, :)]).ravel() pixcrd = np.array(list(zip(fp, fq))) e_moffat_fit = (lambda v, p, q, data, w: (w * (((moffatfit(v, p, q).reshape(N, (factor * factor)).sum(1) / factor) / factor).T.ravel() - data))) (v, covar, info, mesg, success) = leastsq(e_moffat_fit, v0[:], args=(pixcrd[(:, 0)], pixcrd[(:, 1)], data, wght), maxfev=maxiter, full_output=1) else: e_moffat_fit = (lambda v, p, q, data, w: (w * (moffatfit(v, p, q) - data))) (v, covar, info, mesg, success) = leastsq(e_moffat_fit, v0[:], args=(p, q, data, wght), maxfev=maxiter, full_output=1) if (success not in [1, 2, 3, 4]): self._logger.warning(mesg) chisq = sum((info['fvec'] * info['fvec'])) dof = (len(info['fvec']) - len(v)) if (covar is not None): err = np.array([(np.sqrt(np.abs(covar[(i, i)])) * np.sqrt(np.abs((chisq / dof)))) for i in range(len(v))]) else: err = np.zeros_like(v) err[:] = np.abs((v[:] - v0[:])) v[1] += int(pmin) v[2] += int(qmin) if plot: pp = np.arange(pmin, pmax, (float((pmax - pmin)) / 100)) qq = np.arange(qmin, qmax, (float((qmax - qmin)) / 100)) ff = np.empty((np.shape(pp)[0], np.shape(qq)[0])) for i in range(np.shape(pp)[0]): ff[(i, :)] = moffatfit(v, pp[i], qq[:]) self._ax.contour(qq, pp, ff, 5) (I, p_peak, q_peak) = v[:3] a = np.abs(v[3]) v = list(v[4:]) if fit_back: cont = v.pop() if fit_n: n = v.pop(0) _fwhm = (a * (2 * np.sqrt(((2 ** (1.0 / n)) - 1.0)))) if circular: rot = 0 fwhm = (_fwhm, _fwhm) else: e = v.pop(0) if (e < 1): fwhm = (_fwhm, (_fwhm * e)) else: fwhm = ((_fwhm * e), _fwhm) if (rot is None): rot = 0 elif (e < 1): rot = (((v[0] * 180.0) / np.pi) % 180) else: rot = ((((v[0] * 180.0) / np.pi) + 90) % 180) flux = ((I / (n - 1)) * (((np.pi * a) * a) * e)) if (err is not None): (err_I, err_p_peak, err_q_peak) = err[:3] err_a = err[3] if fit_n: err_n = err[4] err_fwhm = (err_a * n) if circular: err_e = 0 err_rot = 0 err_fwhm = np.array([err_fwhm, err_fwhm]) if fit_back: err_cont = err[5] else: err_cont = 0 err_flux = (((err_I * err_n) * err_a) * err_a) else: err_e = err[5] if (err_e != 0): err_fwhm = np.array([err_fwhm, (err_fwhm / err_e)]) else: err_fwhm = np.array([err_fwhm, err_fwhm]) if (rot is None): err_rot = 0 if fit_back: err_cont = err[6] else: err_cont = 0 else: err_rot = ((err[6] * 180.0) / np.pi) if fit_back: err_cont = err[7] else: err_cont = 0 err_flux = ((((err_I * err_n) * err_a) * err_a) * err_e) else: err_n = 0 err_fwhm = (err_a * n) if circular: err_e = 0 err_rot = 0 err_fwhm = np.array([err_fwhm, err_fwhm]) if fit_back: err_cont = err[4] else: err_cont = 0 err_flux = (((err_I * err_n) * err_a) * err_a) else: err_e = err[4] if (err_e != 0): err_fwhm = np.array([err_fwhm, (err_fwhm / err_e)]) else: err_fwhm = np.array([err_fwhm, err_fwhm]) if (rot is None): err_rot = 0 if fit_back: err_cont = err[5] else: err_cont = 0 else: err_rot = ((err[5] * 180.0) / np.pi) if fit_back: err_cont = err[6] else: err_cont = 0 err_flux = ((((err_I * err_n) * err_a) * err_a) * err_e) else: err_I = np.NAN err_p_peak = np.NAN err_q_peak = np.NAN err_a = np.NAN err_n = np.NAN err_e = np.NAN err_rot = np.NAN err_cont = np.NAN err_fwhm = (np.NAN, np.NAN) err_flux = np.NAN if (unit_center is None): center = (p_peak, q_peak) err_center = (err_p_peak, err_q_peak) else: center = self.wcs.pix2sky([p_peak, q_peak], unit=unit_center)[0] err_center = (np.array([err_p_peak, err_q_peak]) * self.wcs.get_step(unit=unit_center)) fwhm = np.array(fwhm) if (unit_fwhm is not None): step0 = self.wcs.get_step(unit=unit_fwhm)[0] a = (a * step0) err_a = (err_a * step0) fwhm = (fwhm * step0) err_fwhm = (err_fwhm * step0) result = Moffat2D(center, flux, fwhm, cont, n, rot, I, err_center, err_flux, err_fwhm, err_cont, err_n, err_rot, err_I) if verbose: result.print_param() if full_output: ima = moffat_image(shape=self.shape, wcs=self.wcs, moffat=result, unit_center=unit_center, unit_fwhm=unit_fwhm) result.ima = ima return result<|docstring|>Perform moffat fit on image. Parameters ---------- pos_min : (float,float) Minimum y and x values. Their unit is given by the unit_center parameter (degrees by default). pos_max : (float,float) Maximum y and x values. Their unit is given by the unit_center parameter (degrees by default). center : (float,float) Initial moffat center (y_peak,x_peak). If None it is estimated. The unit is given by the unit_center parameter (degrees by default). flux : float Initial integrated gaussian flux or gaussian peak value if peak is True. If None, peak value is estimated. fwhm : (float,float) Initial gaussian fwhm (fwhm_y,fwhm_x). If None, they are estimated. Their unit is given by the unit_fwhm parameter (arcseconds by default). n : int Initial atmospheric scattering coefficient. circular : bool True: circular moffat, False: elliptical moffat cont : float continuum value, 0 by default. fit_back : bool False: continuum value is fixed, True: continuum value is a fit parameter. rot : float Initial angle position in degree. peak : bool If true, flux contains a gaussian peak value. factor : int If factor<=1, gaussian is computed in the center of each pixel. If factor>1, for each pixel, gaussian value is the sum of the gaussian values on the factor*factor pixels divided by the pixel area. weight : bool If weight is True, the weight is computed as the inverse of variance. plot : bool If True, the gaussian is plotted. unit_center : `astropy.units.Unit` type of the center and position coordinates. Degrees by default (use None for coordinates in pixels). unit_fwhm : `astropy.units.Unit` FWHM unit. Arcseconds by default (use None for radius in pixels) full_output : bool True to return a `mpdaf.obj.Moffat2D` object containing the moffat image. fit_n : bool False: n value is fixed, True: n value is a fit parameter. maxiter : int The maximum number of iterations during the sum of square minimization. Returns ------- out : `mpdaf.obj.Moffat2D`<|endoftext|>
447bd5a70c29c637f07181566f4696e69a64fbe20a7cb73b1cac620c9e9577e8
def rebin(self, factor, margin='center', inplace=False): "Combine neighboring pixels to reduce the size of an image by\n integer factors along each axis.\n\n Each output pixel is the mean of n pixels, where n is the\n product of the reduction factors in the factor argument.\n\n Parameters\n ----------\n factor : int or (int,int)\n The integer reduction factor along the y and x array axes.\n Note the conventional python ordering of the axes.\n margin : 'center'|'right'|'left'|'origin'\n When the dimensions of the input image are not integer\n multiples of the reduction factor, the image is truncated\n to remove just enough pixels that its dimensions are\n multiples of the reduction factor. This subimage is then\n rebinned in place of the original image. The margin\n parameter determines which pixels of the input image are\n truncated, and which remain.\n\n The options are:\n 'origin' or 'center':\n The starts of the axes of the output image are\n coincident with the starts of the axes of the input\n image.\n 'center':\n The center of the output image is aligned with the\n center of the input image, within one pixel along\n each axis.\n 'right':\n The ends of the axes of the output image are\n coincident with the ends of the axes of the input\n image.\n inplace : bool\n If False, return a rebinned copy of the image (the default).\n If True, rebin the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n " res = self._rebin(factor, margin, inplace) res.update_spatial_fmax((0.5 / res.wcs.get_step())) return res
Combine neighboring pixels to reduce the size of an image by integer factors along each axis. Each output pixel is the mean of n pixels, where n is the product of the reduction factors in the factor argument. Parameters ---------- factor : int or (int,int) The integer reduction factor along the y and x array axes. Note the conventional python ordering of the axes. margin : 'center'|'right'|'left'|'origin' When the dimensions of the input image are not integer multiples of the reduction factor, the image is truncated to remove just enough pixels that its dimensions are multiples of the reduction factor. This subimage is then rebinned in place of the original image. The margin parameter determines which pixels of the input image are truncated, and which remain. The options are: 'origin' or 'center': The starts of the axes of the output image are coincident with the starts of the axes of the input image. 'center': The center of the output image is aligned with the center of the input image, within one pixel along each axis. 'right': The ends of the axes of the output image are coincident with the ends of the axes of the input image. inplace : bool If False, return a rebinned copy of the image (the default). If True, rebin the original image in-place, and return that. Returns ------- out : `~mpdaf.obj.Image`
lib/mpdaf/obj/image.py
rebin
musevlt/mpdaf
4
python
def rebin(self, factor, margin='center', inplace=False): "Combine neighboring pixels to reduce the size of an image by\n integer factors along each axis.\n\n Each output pixel is the mean of n pixels, where n is the\n product of the reduction factors in the factor argument.\n\n Parameters\n ----------\n factor : int or (int,int)\n The integer reduction factor along the y and x array axes.\n Note the conventional python ordering of the axes.\n margin : 'center'|'right'|'left'|'origin'\n When the dimensions of the input image are not integer\n multiples of the reduction factor, the image is truncated\n to remove just enough pixels that its dimensions are\n multiples of the reduction factor. This subimage is then\n rebinned in place of the original image. The margin\n parameter determines which pixels of the input image are\n truncated, and which remain.\n\n The options are:\n 'origin' or 'center':\n The starts of the axes of the output image are\n coincident with the starts of the axes of the input\n image.\n 'center':\n The center of the output image is aligned with the\n center of the input image, within one pixel along\n each axis.\n 'right':\n The ends of the axes of the output image are\n coincident with the ends of the axes of the input\n image.\n inplace : bool\n If False, return a rebinned copy of the image (the default).\n If True, rebin the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n " res = self._rebin(factor, margin, inplace) res.update_spatial_fmax((0.5 / res.wcs.get_step())) return res
def rebin(self, factor, margin='center', inplace=False): "Combine neighboring pixels to reduce the size of an image by\n integer factors along each axis.\n\n Each output pixel is the mean of n pixels, where n is the\n product of the reduction factors in the factor argument.\n\n Parameters\n ----------\n factor : int or (int,int)\n The integer reduction factor along the y and x array axes.\n Note the conventional python ordering of the axes.\n margin : 'center'|'right'|'left'|'origin'\n When the dimensions of the input image are not integer\n multiples of the reduction factor, the image is truncated\n to remove just enough pixels that its dimensions are\n multiples of the reduction factor. This subimage is then\n rebinned in place of the original image. The margin\n parameter determines which pixels of the input image are\n truncated, and which remain.\n\n The options are:\n 'origin' or 'center':\n The starts of the axes of the output image are\n coincident with the starts of the axes of the input\n image.\n 'center':\n The center of the output image is aligned with the\n center of the input image, within one pixel along\n each axis.\n 'right':\n The ends of the axes of the output image are\n coincident with the ends of the axes of the input\n image.\n inplace : bool\n If False, return a rebinned copy of the image (the default).\n If True, rebin the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n " res = self._rebin(factor, margin, inplace) res.update_spatial_fmax((0.5 / res.wcs.get_step())) return res<|docstring|>Combine neighboring pixels to reduce the size of an image by integer factors along each axis. Each output pixel is the mean of n pixels, where n is the product of the reduction factors in the factor argument. Parameters ---------- factor : int or (int,int) The integer reduction factor along the y and x array axes. Note the conventional python ordering of the axes. margin : 'center'|'right'|'left'|'origin' When the dimensions of the input image are not integer multiples of the reduction factor, the image is truncated to remove just enough pixels that its dimensions are multiples of the reduction factor. This subimage is then rebinned in place of the original image. The margin parameter determines which pixels of the input image are truncated, and which remain. The options are: 'origin' or 'center': The starts of the axes of the output image are coincident with the starts of the axes of the input image. 'center': The center of the output image is aligned with the center of the input image, within one pixel along each axis. 'right': The ends of the axes of the output image are coincident with the ends of the axes of the input image. inplace : bool If False, return a rebinned copy of the image (the default). If True, rebin the original image in-place, and return that. Returns ------- out : `~mpdaf.obj.Image`<|endoftext|>
26be9bb57e144d7412cf2a5e37fe3d40bc85dbf46a132b47cef02278c7f1b896
def resample(self, newdim, newstart, newstep, flux=False, order=1, interp='no', unit_start=u.deg, unit_step=u.arcsec, antialias=True, inplace=False, window='blackman'): "Resample an image of the sky to select its angular resolution and\n to specify which sky position appears at the center of pixel [0,0].\n\n This function is a simplified interface to the `mpdaf.obj.Image.regrid`\n function, which it calls with the following arguments::\n\n regrid(newdim, newstart, [0.0, 0.0],\n [abs(newstep[0]),-abs(newstep[1])]\n flux=flux, order=order, interp=interp, unit_pos=unit_start,\n unit_inc=unit_step, inplace=inplace)\n\n When this function is used to resample an image to a lower\n resolution, a low-pass anti-aliasing filter is applied to the\n image before it is resampled, to remove all spatial frequencies\n below half the new sampling rate. This is required to satisfy\n the Nyquist sampling constraint. It prevents high\n spatial-frequency noise and edges from being folded into lower\n frequency artefacts in the resampled image. The removal of\n this noise improves the signal to noise ratio of the resampled\n image.\n\n Parameters\n ----------\n newdim : int or (int,int)\n The desired new dimensions. Python notation: (ny,nx)\n newstart : float or (float, float)\n The sky position (dec,ra) that should appear at the center\n of pixel [0,0].\n\n If None, the value of self.get_start() is substituted,\n so that the sky position that appears at the center of pixel\n [0,0] is unchanged by the resampling operation.\n newstep : float or (float, float)\n The desired angular size of the image pixels on the sky.\n The size is expressed as either one number to request\n square pixels on the sky with that width and height, or\n two numbers that specify the height and width of\n rectangular pixels on the sky. In the latter case, the two\n numbers are the size along the Y axis of the image array\n followed by the size along the X axis.\n flux : bool\n This tells the function whether the pixel units of the\n image are flux densities (flux=True), such as\n erg/s/cm2/Hz, or whether they are per-steradian brightness\n units (flux=False), such as erg/s/cm2/Hz/steradian. It\n needs to know this when it changes the pixel size, because\n when pixel sizes change, resampled flux densities need to\n be corrected for the change in the area per pixel, where\n resampled brightnesses don't.\n order : int\n The order of the spline interpolation. This can take any\n value from 0-5. The default is 1 (linear interpolation).\n When this function is used to lower the resolution of\n an image, the low-pass anti-aliasing filter that is applied,\n makes linear interpolation sufficient.\n Conversely, when this function is used to increase the\n image resolution, order=3 might be useful. Higher\n orders than this will tend to introduce ringing artefacts.\n interp : 'no' | 'linear' | 'spline'\n If 'no', replace masked data with the median image value.\n If 'linear', replace masked values using a linear\n interpolation between neighboring values.\n if 'spline', replace masked values using a spline\n interpolation between neighboring values.\n unit_start : `astropy.units.Unit`\n The angular units of the newstart coordinates. Degrees by default.\n unit_step : `astropy.units.Unit`\n The angular units of the step argument. Arcseconds by default.\n antialias : bool\n By default, when the resolution of an image axis is about\n to be reduced, a low pass filter is first applied to suppress\n high spatial frequencies that can not be represented by the\n reduced sampling interval. If this is not done, high-frequency\n noise and sharp edges get folded back to lower frequencies,\n where they increase the noise level of the image and introduce\n ringing artefacts next to sharp edges, such as CCD saturation\n spikes. This filtering can be disabled by passing False to\n the antialias argument.\n inplace : bool\n If False, return a rotated copy of the image (the default).\n If True, rotate the original image in-place, and return that.\n window : str\n The type of window function to use for antialiasing\n in the Fourier plane. The following windows are supported:\n\n blackman\n This window suppresses ringing better than any other\n window, at the expense of lowered image resolution. In\n the image plane, the PSF of this window is\n approximately gaussian, with a standard deviation of\n around 0.96*newstep, and a FWHM of about 2.3*newstep.\n\n gaussian\n A truncated gaussian window. This has a smaller PSF\n than the blackman window, however gaussians never fall\n to zero, so either significant ringing will be seen due\n to truncation of the gaussian, or low-level aliasing\n will occur, depending on the spatial frequency coverage\n of the image beyond the folding frequency. It can be a\n good choice for images that only contain smoothly\n varying features. It is equivalent to a convolution of\n the image with both an airy profile and a gaussian of\n standard deviation 0.724*newstep (FWHM 1.704*newstep).\n\n rectangle\n This window simply zeros all spatial frequencies above\n the highest that can be correctly sampled by the new\n pixel size. This gives the best resolution of any of\n the windows, but this is marred by the strong sidelobes\n of the resulting airy-profile, especially near bright\n point sources and CCD saturation lines.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n The resampled image.\n\n " step_signs = np.sign(self.get_axis_increments()) if is_number(newstep): newinc = (step_signs * abs(newstep)) else: newinc = (step_signs * abs(np.asarray(newstep))) refpix = (None if (newstart is None) else [0.0, 0.0]) return self.regrid(newdim, newstart, refpix, newinc, flux=flux, order=order, interp=interp, unit_pos=unit_start, unit_inc=unit_step, antialias=antialias, inplace=inplace, window=window)
Resample an image of the sky to select its angular resolution and to specify which sky position appears at the center of pixel [0,0]. This function is a simplified interface to the `mpdaf.obj.Image.regrid` function, which it calls with the following arguments:: regrid(newdim, newstart, [0.0, 0.0], [abs(newstep[0]),-abs(newstep[1])] flux=flux, order=order, interp=interp, unit_pos=unit_start, unit_inc=unit_step, inplace=inplace) When this function is used to resample an image to a lower resolution, a low-pass anti-aliasing filter is applied to the image before it is resampled, to remove all spatial frequencies below half the new sampling rate. This is required to satisfy the Nyquist sampling constraint. It prevents high spatial-frequency noise and edges from being folded into lower frequency artefacts in the resampled image. The removal of this noise improves the signal to noise ratio of the resampled image. Parameters ---------- newdim : int or (int,int) The desired new dimensions. Python notation: (ny,nx) newstart : float or (float, float) The sky position (dec,ra) that should appear at the center of pixel [0,0]. If None, the value of self.get_start() is substituted, so that the sky position that appears at the center of pixel [0,0] is unchanged by the resampling operation. newstep : float or (float, float) The desired angular size of the image pixels on the sky. The size is expressed as either one number to request square pixels on the sky with that width and height, or two numbers that specify the height and width of rectangular pixels on the sky. In the latter case, the two numbers are the size along the Y axis of the image array followed by the size along the X axis. flux : bool This tells the function whether the pixel units of the image are flux densities (flux=True), such as erg/s/cm2/Hz, or whether they are per-steradian brightness units (flux=False), such as erg/s/cm2/Hz/steradian. It needs to know this when it changes the pixel size, because when pixel sizes change, resampled flux densities need to be corrected for the change in the area per pixel, where resampled brightnesses don't. order : int The order of the spline interpolation. This can take any value from 0-5. The default is 1 (linear interpolation). When this function is used to lower the resolution of an image, the low-pass anti-aliasing filter that is applied, makes linear interpolation sufficient. Conversely, when this function is used to increase the image resolution, order=3 might be useful. Higher orders than this will tend to introduce ringing artefacts. interp : 'no' | 'linear' | 'spline' If 'no', replace masked data with the median image value. If 'linear', replace masked values using a linear interpolation between neighboring values. if 'spline', replace masked values using a spline interpolation between neighboring values. unit_start : `astropy.units.Unit` The angular units of the newstart coordinates. Degrees by default. unit_step : `astropy.units.Unit` The angular units of the step argument. Arcseconds by default. antialias : bool By default, when the resolution of an image axis is about to be reduced, a low pass filter is first applied to suppress high spatial frequencies that can not be represented by the reduced sampling interval. If this is not done, high-frequency noise and sharp edges get folded back to lower frequencies, where they increase the noise level of the image and introduce ringing artefacts next to sharp edges, such as CCD saturation spikes. This filtering can be disabled by passing False to the antialias argument. inplace : bool If False, return a rotated copy of the image (the default). If True, rotate the original image in-place, and return that. window : str The type of window function to use for antialiasing in the Fourier plane. The following windows are supported: blackman This window suppresses ringing better than any other window, at the expense of lowered image resolution. In the image plane, the PSF of this window is approximately gaussian, with a standard deviation of around 0.96*newstep, and a FWHM of about 2.3*newstep. gaussian A truncated gaussian window. This has a smaller PSF than the blackman window, however gaussians never fall to zero, so either significant ringing will be seen due to truncation of the gaussian, or low-level aliasing will occur, depending on the spatial frequency coverage of the image beyond the folding frequency. It can be a good choice for images that only contain smoothly varying features. It is equivalent to a convolution of the image with both an airy profile and a gaussian of standard deviation 0.724*newstep (FWHM 1.704*newstep). rectangle This window simply zeros all spatial frequencies above the highest that can be correctly sampled by the new pixel size. This gives the best resolution of any of the windows, but this is marred by the strong sidelobes of the resulting airy-profile, especially near bright point sources and CCD saturation lines. Returns ------- out : `~mpdaf.obj.Image` The resampled image.
lib/mpdaf/obj/image.py
resample
musevlt/mpdaf
4
python
def resample(self, newdim, newstart, newstep, flux=False, order=1, interp='no', unit_start=u.deg, unit_step=u.arcsec, antialias=True, inplace=False, window='blackman'): "Resample an image of the sky to select its angular resolution and\n to specify which sky position appears at the center of pixel [0,0].\n\n This function is a simplified interface to the `mpdaf.obj.Image.regrid`\n function, which it calls with the following arguments::\n\n regrid(newdim, newstart, [0.0, 0.0],\n [abs(newstep[0]),-abs(newstep[1])]\n flux=flux, order=order, interp=interp, unit_pos=unit_start,\n unit_inc=unit_step, inplace=inplace)\n\n When this function is used to resample an image to a lower\n resolution, a low-pass anti-aliasing filter is applied to the\n image before it is resampled, to remove all spatial frequencies\n below half the new sampling rate. This is required to satisfy\n the Nyquist sampling constraint. It prevents high\n spatial-frequency noise and edges from being folded into lower\n frequency artefacts in the resampled image. The removal of\n this noise improves the signal to noise ratio of the resampled\n image.\n\n Parameters\n ----------\n newdim : int or (int,int)\n The desired new dimensions. Python notation: (ny,nx)\n newstart : float or (float, float)\n The sky position (dec,ra) that should appear at the center\n of pixel [0,0].\n\n If None, the value of self.get_start() is substituted,\n so that the sky position that appears at the center of pixel\n [0,0] is unchanged by the resampling operation.\n newstep : float or (float, float)\n The desired angular size of the image pixels on the sky.\n The size is expressed as either one number to request\n square pixels on the sky with that width and height, or\n two numbers that specify the height and width of\n rectangular pixels on the sky. In the latter case, the two\n numbers are the size along the Y axis of the image array\n followed by the size along the X axis.\n flux : bool\n This tells the function whether the pixel units of the\n image are flux densities (flux=True), such as\n erg/s/cm2/Hz, or whether they are per-steradian brightness\n units (flux=False), such as erg/s/cm2/Hz/steradian. It\n needs to know this when it changes the pixel size, because\n when pixel sizes change, resampled flux densities need to\n be corrected for the change in the area per pixel, where\n resampled brightnesses don't.\n order : int\n The order of the spline interpolation. This can take any\n value from 0-5. The default is 1 (linear interpolation).\n When this function is used to lower the resolution of\n an image, the low-pass anti-aliasing filter that is applied,\n makes linear interpolation sufficient.\n Conversely, when this function is used to increase the\n image resolution, order=3 might be useful. Higher\n orders than this will tend to introduce ringing artefacts.\n interp : 'no' | 'linear' | 'spline'\n If 'no', replace masked data with the median image value.\n If 'linear', replace masked values using a linear\n interpolation between neighboring values.\n if 'spline', replace masked values using a spline\n interpolation between neighboring values.\n unit_start : `astropy.units.Unit`\n The angular units of the newstart coordinates. Degrees by default.\n unit_step : `astropy.units.Unit`\n The angular units of the step argument. Arcseconds by default.\n antialias : bool\n By default, when the resolution of an image axis is about\n to be reduced, a low pass filter is first applied to suppress\n high spatial frequencies that can not be represented by the\n reduced sampling interval. If this is not done, high-frequency\n noise and sharp edges get folded back to lower frequencies,\n where they increase the noise level of the image and introduce\n ringing artefacts next to sharp edges, such as CCD saturation\n spikes. This filtering can be disabled by passing False to\n the antialias argument.\n inplace : bool\n If False, return a rotated copy of the image (the default).\n If True, rotate the original image in-place, and return that.\n window : str\n The type of window function to use for antialiasing\n in the Fourier plane. The following windows are supported:\n\n blackman\n This window suppresses ringing better than any other\n window, at the expense of lowered image resolution. In\n the image plane, the PSF of this window is\n approximately gaussian, with a standard deviation of\n around 0.96*newstep, and a FWHM of about 2.3*newstep.\n\n gaussian\n A truncated gaussian window. This has a smaller PSF\n than the blackman window, however gaussians never fall\n to zero, so either significant ringing will be seen due\n to truncation of the gaussian, or low-level aliasing\n will occur, depending on the spatial frequency coverage\n of the image beyond the folding frequency. It can be a\n good choice for images that only contain smoothly\n varying features. It is equivalent to a convolution of\n the image with both an airy profile and a gaussian of\n standard deviation 0.724*newstep (FWHM 1.704*newstep).\n\n rectangle\n This window simply zeros all spatial frequencies above\n the highest that can be correctly sampled by the new\n pixel size. This gives the best resolution of any of\n the windows, but this is marred by the strong sidelobes\n of the resulting airy-profile, especially near bright\n point sources and CCD saturation lines.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n The resampled image.\n\n " step_signs = np.sign(self.get_axis_increments()) if is_number(newstep): newinc = (step_signs * abs(newstep)) else: newinc = (step_signs * abs(np.asarray(newstep))) refpix = (None if (newstart is None) else [0.0, 0.0]) return self.regrid(newdim, newstart, refpix, newinc, flux=flux, order=order, interp=interp, unit_pos=unit_start, unit_inc=unit_step, antialias=antialias, inplace=inplace, window=window)
def resample(self, newdim, newstart, newstep, flux=False, order=1, interp='no', unit_start=u.deg, unit_step=u.arcsec, antialias=True, inplace=False, window='blackman'): "Resample an image of the sky to select its angular resolution and\n to specify which sky position appears at the center of pixel [0,0].\n\n This function is a simplified interface to the `mpdaf.obj.Image.regrid`\n function, which it calls with the following arguments::\n\n regrid(newdim, newstart, [0.0, 0.0],\n [abs(newstep[0]),-abs(newstep[1])]\n flux=flux, order=order, interp=interp, unit_pos=unit_start,\n unit_inc=unit_step, inplace=inplace)\n\n When this function is used to resample an image to a lower\n resolution, a low-pass anti-aliasing filter is applied to the\n image before it is resampled, to remove all spatial frequencies\n below half the new sampling rate. This is required to satisfy\n the Nyquist sampling constraint. It prevents high\n spatial-frequency noise and edges from being folded into lower\n frequency artefacts in the resampled image. The removal of\n this noise improves the signal to noise ratio of the resampled\n image.\n\n Parameters\n ----------\n newdim : int or (int,int)\n The desired new dimensions. Python notation: (ny,nx)\n newstart : float or (float, float)\n The sky position (dec,ra) that should appear at the center\n of pixel [0,0].\n\n If None, the value of self.get_start() is substituted,\n so that the sky position that appears at the center of pixel\n [0,0] is unchanged by the resampling operation.\n newstep : float or (float, float)\n The desired angular size of the image pixels on the sky.\n The size is expressed as either one number to request\n square pixels on the sky with that width and height, or\n two numbers that specify the height and width of\n rectangular pixels on the sky. In the latter case, the two\n numbers are the size along the Y axis of the image array\n followed by the size along the X axis.\n flux : bool\n This tells the function whether the pixel units of the\n image are flux densities (flux=True), such as\n erg/s/cm2/Hz, or whether they are per-steradian brightness\n units (flux=False), such as erg/s/cm2/Hz/steradian. It\n needs to know this when it changes the pixel size, because\n when pixel sizes change, resampled flux densities need to\n be corrected for the change in the area per pixel, where\n resampled brightnesses don't.\n order : int\n The order of the spline interpolation. This can take any\n value from 0-5. The default is 1 (linear interpolation).\n When this function is used to lower the resolution of\n an image, the low-pass anti-aliasing filter that is applied,\n makes linear interpolation sufficient.\n Conversely, when this function is used to increase the\n image resolution, order=3 might be useful. Higher\n orders than this will tend to introduce ringing artefacts.\n interp : 'no' | 'linear' | 'spline'\n If 'no', replace masked data with the median image value.\n If 'linear', replace masked values using a linear\n interpolation between neighboring values.\n if 'spline', replace masked values using a spline\n interpolation between neighboring values.\n unit_start : `astropy.units.Unit`\n The angular units of the newstart coordinates. Degrees by default.\n unit_step : `astropy.units.Unit`\n The angular units of the step argument. Arcseconds by default.\n antialias : bool\n By default, when the resolution of an image axis is about\n to be reduced, a low pass filter is first applied to suppress\n high spatial frequencies that can not be represented by the\n reduced sampling interval. If this is not done, high-frequency\n noise and sharp edges get folded back to lower frequencies,\n where they increase the noise level of the image and introduce\n ringing artefacts next to sharp edges, such as CCD saturation\n spikes. This filtering can be disabled by passing False to\n the antialias argument.\n inplace : bool\n If False, return a rotated copy of the image (the default).\n If True, rotate the original image in-place, and return that.\n window : str\n The type of window function to use for antialiasing\n in the Fourier plane. The following windows are supported:\n\n blackman\n This window suppresses ringing better than any other\n window, at the expense of lowered image resolution. In\n the image plane, the PSF of this window is\n approximately gaussian, with a standard deviation of\n around 0.96*newstep, and a FWHM of about 2.3*newstep.\n\n gaussian\n A truncated gaussian window. This has a smaller PSF\n than the blackman window, however gaussians never fall\n to zero, so either significant ringing will be seen due\n to truncation of the gaussian, or low-level aliasing\n will occur, depending on the spatial frequency coverage\n of the image beyond the folding frequency. It can be a\n good choice for images that only contain smoothly\n varying features. It is equivalent to a convolution of\n the image with both an airy profile and a gaussian of\n standard deviation 0.724*newstep (FWHM 1.704*newstep).\n\n rectangle\n This window simply zeros all spatial frequencies above\n the highest that can be correctly sampled by the new\n pixel size. This gives the best resolution of any of\n the windows, but this is marred by the strong sidelobes\n of the resulting airy-profile, especially near bright\n point sources and CCD saturation lines.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n The resampled image.\n\n " step_signs = np.sign(self.get_axis_increments()) if is_number(newstep): newinc = (step_signs * abs(newstep)) else: newinc = (step_signs * abs(np.asarray(newstep))) refpix = (None if (newstart is None) else [0.0, 0.0]) return self.regrid(newdim, newstart, refpix, newinc, flux=flux, order=order, interp=interp, unit_pos=unit_start, unit_inc=unit_step, antialias=antialias, inplace=inplace, window=window)<|docstring|>Resample an image of the sky to select its angular resolution and to specify which sky position appears at the center of pixel [0,0]. This function is a simplified interface to the `mpdaf.obj.Image.regrid` function, which it calls with the following arguments:: regrid(newdim, newstart, [0.0, 0.0], [abs(newstep[0]),-abs(newstep[1])] flux=flux, order=order, interp=interp, unit_pos=unit_start, unit_inc=unit_step, inplace=inplace) When this function is used to resample an image to a lower resolution, a low-pass anti-aliasing filter is applied to the image before it is resampled, to remove all spatial frequencies below half the new sampling rate. This is required to satisfy the Nyquist sampling constraint. It prevents high spatial-frequency noise and edges from being folded into lower frequency artefacts in the resampled image. The removal of this noise improves the signal to noise ratio of the resampled image. Parameters ---------- newdim : int or (int,int) The desired new dimensions. Python notation: (ny,nx) newstart : float or (float, float) The sky position (dec,ra) that should appear at the center of pixel [0,0]. If None, the value of self.get_start() is substituted, so that the sky position that appears at the center of pixel [0,0] is unchanged by the resampling operation. newstep : float or (float, float) The desired angular size of the image pixels on the sky. The size is expressed as either one number to request square pixels on the sky with that width and height, or two numbers that specify the height and width of rectangular pixels on the sky. In the latter case, the two numbers are the size along the Y axis of the image array followed by the size along the X axis. flux : bool This tells the function whether the pixel units of the image are flux densities (flux=True), such as erg/s/cm2/Hz, or whether they are per-steradian brightness units (flux=False), such as erg/s/cm2/Hz/steradian. It needs to know this when it changes the pixel size, because when pixel sizes change, resampled flux densities need to be corrected for the change in the area per pixel, where resampled brightnesses don't. order : int The order of the spline interpolation. This can take any value from 0-5. The default is 1 (linear interpolation). When this function is used to lower the resolution of an image, the low-pass anti-aliasing filter that is applied, makes linear interpolation sufficient. Conversely, when this function is used to increase the image resolution, order=3 might be useful. Higher orders than this will tend to introduce ringing artefacts. interp : 'no' | 'linear' | 'spline' If 'no', replace masked data with the median image value. If 'linear', replace masked values using a linear interpolation between neighboring values. if 'spline', replace masked values using a spline interpolation between neighboring values. unit_start : `astropy.units.Unit` The angular units of the newstart coordinates. Degrees by default. unit_step : `astropy.units.Unit` The angular units of the step argument. Arcseconds by default. antialias : bool By default, when the resolution of an image axis is about to be reduced, a low pass filter is first applied to suppress high spatial frequencies that can not be represented by the reduced sampling interval. If this is not done, high-frequency noise and sharp edges get folded back to lower frequencies, where they increase the noise level of the image and introduce ringing artefacts next to sharp edges, such as CCD saturation spikes. This filtering can be disabled by passing False to the antialias argument. inplace : bool If False, return a rotated copy of the image (the default). If True, rotate the original image in-place, and return that. window : str The type of window function to use for antialiasing in the Fourier plane. The following windows are supported: blackman This window suppresses ringing better than any other window, at the expense of lowered image resolution. In the image plane, the PSF of this window is approximately gaussian, with a standard deviation of around 0.96*newstep, and a FWHM of about 2.3*newstep. gaussian A truncated gaussian window. This has a smaller PSF than the blackman window, however gaussians never fall to zero, so either significant ringing will be seen due to truncation of the gaussian, or low-level aliasing will occur, depending on the spatial frequency coverage of the image beyond the folding frequency. It can be a good choice for images that only contain smoothly varying features. It is equivalent to a convolution of the image with both an airy profile and a gaussian of standard deviation 0.724*newstep (FWHM 1.704*newstep). rectangle This window simply zeros all spatial frequencies above the highest that can be correctly sampled by the new pixel size. This gives the best resolution of any of the windows, but this is marred by the strong sidelobes of the resulting airy-profile, especially near bright point sources and CCD saturation lines. Returns ------- out : `~mpdaf.obj.Image` The resampled image.<|endoftext|>
ce1904c92da3f1302d328cf75e8563098e9861c6c23f1d8992876e6fdce7077e
def regrid(self, newdim, refpos, refpix, newinc, flux=False, order=1, interp='no', unit_pos=u.deg, unit_inc=u.arcsec, antialias=True, inplace=False, cutoff=0.25, window='blackman'): "Resample an image of the sky to select its angular resolution,\n to specify the position of the sky in the image array, and\n optionally to reflect one or more of its axes.\n\n This function can be used to decrease or increase the\n resolution of an image. It can also shift the contents of an\n image to place a specific (dec,ra) position at a specific\n fractional pixel position. Finally, it can be used to invert\n the direction of one or both of the array axes on the sky.\n\n When this function is used to resample an image to a lower\n resolution, a low-pass anti-aliasing filter is applied to the\n image before it is resampled, to remove all spatial\n frequencies below half the new sampling rate. This is required\n to satisfy the Nyquist sampling constraint. It prevents high\n spatial-frequency noise and edges from being aliased to lower\n frequency artefacts in the resampled image. The removal of\n this noise improves the signal to noise ratio of the resampled\n image.\n\n Parameters\n ----------\n newdim : int or (int,int)\n The desired new dimensions. Python notation: (ny,nx)\n refpos : (float, float)\n The sky position (dec,ra) to place at the pixel specified\n by the refpix argument.\n\n If refpix and refpos are both None, the sky position at\n the bottom corner of the input image is placed at the\n bottom left corner of the output image. Note that refpix\n and refpos must either both be given values, or both\n be None.\n refpix : (float, float)\n The [Y, X] indexes of the output pixel where the sky\n position, refpos, should be placed. Y and X are\n interpreted as floating point indexes, where integer\n values indicate pixel centers and integer values +/- 0.5\n indicate the edges of pixels.\n\n If refpix and refpos are both None, the sky position at\n the bottom corner of the input image is placed at the\n bottom left corner of the output image. Note that refpix\n and refpos must either both be given values, or both\n be None.\n newinc : float or (float, float)\n The signed increments of the angle on the sky from one\n pixel to the next, given as either a single increment for\n both image axes, or two numbers (dy,dx) for the Y and X\n axes respectively.\n\n The signs of these increments are interpreted as described\n in the documentation of the Image.get_axis_increments()\n function. In particular, note that dy is typically\n positive and dx is usually negative, such that when the\n image is plotted, east appears anticlockwise of north, and\n east is towards the left of the plot when the image\n rotation angle is zero.\n\n If either of the signs of the two newinc numbers is\n different from the sign of the increments of the original\n image (queryable with image.get_axis_increments()), then\n the image will be reflected about that axis. In this case\n the value of the refpix argument should be chosen with\n care, because otherwise the sampled part of the image may\n end up being reflected outside the limits of the image\n array, and the result will be a blank image.\n\n If only one number is given for newinc then both axes\n are given the same resolution, but the signs of the\n increments are kept the same as the pixel increments\n of the original image.\n flux : bool\n This tells the function whether the pixel units of the\n image are flux densities (flux=True), such as\n erg/s/cm2/Hz, or whether they are per-steradian brightness\n units (flux=False), such as erg/s/cm2/Hz/steradian. It\n needs to know this when it changes the pixel size, because\n when pixel sizes change, resampled flux densities need to\n be corrected for the change in the area per pixel, where\n resampled brightnesses don't.\n order : int\n The order of the spline interpolation. This can take any\n value from 0-5. The default is 1 (linear interpolation).\n When this function is used to lower the resolution of\n an image, the low-pass anti-aliasing filter that is applied,\n makes linear interpolation sufficient.\n Conversely, when this function is used to increase the\n image resolution, order=3 might be useful. Higher\n orders than this will tend to introduce ringing artefacts.\n interp : 'no' | 'linear' | 'spline'\n If 'no', replace masked data with the median image value.\n If 'linear', replace masked values using a linear\n interpolation between neighboring values.\n if 'spline', replace masked values using a spline\n interpolation between neighboring values.\n unit_pos : `astropy.units.Unit`\n The units of the refpos coordinates. Degrees by default.\n unit_inc : `astropy.units.Unit`\n The units of newinc. Arcseconds by default.\n antialias : bool\n By default, when the resolution of an image axis is about\n to be reduced, a low pass filter is first applied to suppress\n high spatial frequencies that can not be represented by the\n reduced sampling interval. If this is not done, high-frequency\n noise and sharp edges get folded back to lower frequencies,\n where they increase the noise level of the image and introduce\n ringing artefacts next to sharp edges, such as CCD saturation\n spikes. This filtering can be disabled by passing False to\n the antialias argument.\n inplace : bool\n If False, return a resampled copy of the image (the default).\n If True, resample the original image in-place, and return that.\n cutoff : float\n Mask each output pixel where at least this fraction of the\n pixel was interpolated from dummy values given to masked\n input pixels.\n window : str\n The type of window function to use for antialiasing\n in the Fourier plane. The following windows are supported:\n\n blackman\n This window suppresses ringing better than any other\n window, at the expense of lowered image resolution. In\n the image plane, the PSF of this window is\n approximately gaussian, with a standard deviation of\n around 0.96*newstep, and a FWHM of about 2.3*newstep.\n\n gaussian\n A truncated gaussian window. This has a smaller PSF\n than the blackman window, however gaussians never fall\n to zero, so either significant ringing will be seen due\n to truncation of the gaussian, or low-level aliasing\n will occur, depending on the spatial frequency coverage\n of the image beyond the folding frequency. It can be a\n good choice for images that only contain smoothly\n varying features. It is equivalent to a convolution of\n the image with both an airy profile and a gaussian of\n standard deviation 0.724*newstep (FWHM 1.704*newstep).\n\n rectangle\n This window simply zeros all spatial frequencies above\n the highest that can be correctly sampled by the new\n pixel size. This gives the best resolution of any of\n the windows, but this is marred by the strong sidelobes\n of the resulting airy-profile, especially near bright\n point sources and CCD saturation lines.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n The resampled image is returned.\n\n " if is_int(newdim): newdim = (newdim, newdim) newdim = np.asarray(newdim, dtype=int) if ((refpos is None) and (refpix is None)): refpix = np.array([(- 0.5), (- 0.5)]) refpos = self.wcs.pix2sky(refpix) elif ((refpos is not None) and (refpix is not None)): refpos = np.asarray(refpos, dtype=float) if (unit_pos is not None): refpos = UnitArray(refpos, unit_pos, self.wcs.unit) refpix = np.asarray(refpix, dtype=float) else: raise ValueError('The refpos and refpix arguments should both be None or both have values.') oldinc = self.wcs.get_axis_increments() if is_number(newinc): size = abs(newinc) newinc = ((size * np.sign(oldinc[0])), (size * np.sign(oldinc[1]))) newinc = np.asarray(newinc, dtype=float) if (unit_inc is not None): newinc = UnitArray(newinc, unit_inc, self.wcs.unit) data = self._prepare_data(interp) if antialias: (data, newfmax) = _antialias_filter_image(data, abs(oldinc), abs(newinc), self.get_spatial_fmax(), window) else: newfmax = (0.5 / abs(newinc)) new2old = np.array([[(newinc[0] / oldinc[0]), 0], [0, (newinc[1] / oldinc[1])]]) old2new = np.linalg.inv(new2old) offset = (self.wcs.sky2pix(refpos).T[(:, :1)] - np.dot(new2old, refpix[(np.newaxis, :)].T)) data = affine_transform(data, new2old, offset.flatten(), output_shape=newdim, order=order, prefilter=(order >= 3)) mask = self._mask.astype(float) mask = affine_transform(mask, new2old, offset.flatten(), cval=1.0, output_shape=newdim, output=float) mask = np.greater(mask, max(cutoff, 1e-06)) if (self._var is not None): var = affine_transform(self._var, new2old, offset.flatten(), output_shape=newdim, order=order, prefilter=(order >= 3)) else: var = None xs = abs((newinc[1] / oldinc[1])) ys = abs((newinc[0] / oldinc[0])) n = (xs * ys) if flux: data *= n if (var is not None): var *= ((xs if ((xs > 1.0) and antialias) else (xs ** 2)) * (ys if ((ys > 1.0) and antialias) else (ys ** 2))) elif ((var is not None) and ((xs > 1.0) or (ys > 1.0))): var *= (((1 / xs) if ((xs > 1.0) and antialias) else 1.0) * ((1 / ys) if ((ys > 1.0) and antialias) else 1.0)) oldcrpix = np.array([[(self.wcs.get_crpix2() - 1)], [(self.wcs.get_crpix1() - 1)]]) newcrpix = np.dot(old2new, (oldcrpix - offset)) wcs = self.wcs.copy() wcs.set_axis_increments(newinc) wcs.naxis1 = newdim[1] wcs.naxis2 = newdim[0] wcs.set_crpix1((newcrpix[1] + 1)) wcs.set_crpix2((newcrpix[0] + 1)) out = (self if inplace else self.clone()) out._data = data out._mask = mask out._var = var out.wcs = wcs out.update_spatial_fmax(newfmax) return out
Resample an image of the sky to select its angular resolution, to specify the position of the sky in the image array, and optionally to reflect one or more of its axes. This function can be used to decrease or increase the resolution of an image. It can also shift the contents of an image to place a specific (dec,ra) position at a specific fractional pixel position. Finally, it can be used to invert the direction of one or both of the array axes on the sky. When this function is used to resample an image to a lower resolution, a low-pass anti-aliasing filter is applied to the image before it is resampled, to remove all spatial frequencies below half the new sampling rate. This is required to satisfy the Nyquist sampling constraint. It prevents high spatial-frequency noise and edges from being aliased to lower frequency artefacts in the resampled image. The removal of this noise improves the signal to noise ratio of the resampled image. Parameters ---------- newdim : int or (int,int) The desired new dimensions. Python notation: (ny,nx) refpos : (float, float) The sky position (dec,ra) to place at the pixel specified by the refpix argument. If refpix and refpos are both None, the sky position at the bottom corner of the input image is placed at the bottom left corner of the output image. Note that refpix and refpos must either both be given values, or both be None. refpix : (float, float) The [Y, X] indexes of the output pixel where the sky position, refpos, should be placed. Y and X are interpreted as floating point indexes, where integer values indicate pixel centers and integer values +/- 0.5 indicate the edges of pixels. If refpix and refpos are both None, the sky position at the bottom corner of the input image is placed at the bottom left corner of the output image. Note that refpix and refpos must either both be given values, or both be None. newinc : float or (float, float) The signed increments of the angle on the sky from one pixel to the next, given as either a single increment for both image axes, or two numbers (dy,dx) for the Y and X axes respectively. The signs of these increments are interpreted as described in the documentation of the Image.get_axis_increments() function. In particular, note that dy is typically positive and dx is usually negative, such that when the image is plotted, east appears anticlockwise of north, and east is towards the left of the plot when the image rotation angle is zero. If either of the signs of the two newinc numbers is different from the sign of the increments of the original image (queryable with image.get_axis_increments()), then the image will be reflected about that axis. In this case the value of the refpix argument should be chosen with care, because otherwise the sampled part of the image may end up being reflected outside the limits of the image array, and the result will be a blank image. If only one number is given for newinc then both axes are given the same resolution, but the signs of the increments are kept the same as the pixel increments of the original image. flux : bool This tells the function whether the pixel units of the image are flux densities (flux=True), such as erg/s/cm2/Hz, or whether they are per-steradian brightness units (flux=False), such as erg/s/cm2/Hz/steradian. It needs to know this when it changes the pixel size, because when pixel sizes change, resampled flux densities need to be corrected for the change in the area per pixel, where resampled brightnesses don't. order : int The order of the spline interpolation. This can take any value from 0-5. The default is 1 (linear interpolation). When this function is used to lower the resolution of an image, the low-pass anti-aliasing filter that is applied, makes linear interpolation sufficient. Conversely, when this function is used to increase the image resolution, order=3 might be useful. Higher orders than this will tend to introduce ringing artefacts. interp : 'no' | 'linear' | 'spline' If 'no', replace masked data with the median image value. If 'linear', replace masked values using a linear interpolation between neighboring values. if 'spline', replace masked values using a spline interpolation between neighboring values. unit_pos : `astropy.units.Unit` The units of the refpos coordinates. Degrees by default. unit_inc : `astropy.units.Unit` The units of newinc. Arcseconds by default. antialias : bool By default, when the resolution of an image axis is about to be reduced, a low pass filter is first applied to suppress high spatial frequencies that can not be represented by the reduced sampling interval. If this is not done, high-frequency noise and sharp edges get folded back to lower frequencies, where they increase the noise level of the image and introduce ringing artefacts next to sharp edges, such as CCD saturation spikes. This filtering can be disabled by passing False to the antialias argument. inplace : bool If False, return a resampled copy of the image (the default). If True, resample the original image in-place, and return that. cutoff : float Mask each output pixel where at least this fraction of the pixel was interpolated from dummy values given to masked input pixels. window : str The type of window function to use for antialiasing in the Fourier plane. The following windows are supported: blackman This window suppresses ringing better than any other window, at the expense of lowered image resolution. In the image plane, the PSF of this window is approximately gaussian, with a standard deviation of around 0.96*newstep, and a FWHM of about 2.3*newstep. gaussian A truncated gaussian window. This has a smaller PSF than the blackman window, however gaussians never fall to zero, so either significant ringing will be seen due to truncation of the gaussian, or low-level aliasing will occur, depending on the spatial frequency coverage of the image beyond the folding frequency. It can be a good choice for images that only contain smoothly varying features. It is equivalent to a convolution of the image with both an airy profile and a gaussian of standard deviation 0.724*newstep (FWHM 1.704*newstep). rectangle This window simply zeros all spatial frequencies above the highest that can be correctly sampled by the new pixel size. This gives the best resolution of any of the windows, but this is marred by the strong sidelobes of the resulting airy-profile, especially near bright point sources and CCD saturation lines. Returns ------- out : `~mpdaf.obj.Image` The resampled image is returned.
lib/mpdaf/obj/image.py
regrid
musevlt/mpdaf
4
python
def regrid(self, newdim, refpos, refpix, newinc, flux=False, order=1, interp='no', unit_pos=u.deg, unit_inc=u.arcsec, antialias=True, inplace=False, cutoff=0.25, window='blackman'): "Resample an image of the sky to select its angular resolution,\n to specify the position of the sky in the image array, and\n optionally to reflect one or more of its axes.\n\n This function can be used to decrease or increase the\n resolution of an image. It can also shift the contents of an\n image to place a specific (dec,ra) position at a specific\n fractional pixel position. Finally, it can be used to invert\n the direction of one or both of the array axes on the sky.\n\n When this function is used to resample an image to a lower\n resolution, a low-pass anti-aliasing filter is applied to the\n image before it is resampled, to remove all spatial\n frequencies below half the new sampling rate. This is required\n to satisfy the Nyquist sampling constraint. It prevents high\n spatial-frequency noise and edges from being aliased to lower\n frequency artefacts in the resampled image. The removal of\n this noise improves the signal to noise ratio of the resampled\n image.\n\n Parameters\n ----------\n newdim : int or (int,int)\n The desired new dimensions. Python notation: (ny,nx)\n refpos : (float, float)\n The sky position (dec,ra) to place at the pixel specified\n by the refpix argument.\n\n If refpix and refpos are both None, the sky position at\n the bottom corner of the input image is placed at the\n bottom left corner of the output image. Note that refpix\n and refpos must either both be given values, or both\n be None.\n refpix : (float, float)\n The [Y, X] indexes of the output pixel where the sky\n position, refpos, should be placed. Y and X are\n interpreted as floating point indexes, where integer\n values indicate pixel centers and integer values +/- 0.5\n indicate the edges of pixels.\n\n If refpix and refpos are both None, the sky position at\n the bottom corner of the input image is placed at the\n bottom left corner of the output image. Note that refpix\n and refpos must either both be given values, or both\n be None.\n newinc : float or (float, float)\n The signed increments of the angle on the sky from one\n pixel to the next, given as either a single increment for\n both image axes, or two numbers (dy,dx) for the Y and X\n axes respectively.\n\n The signs of these increments are interpreted as described\n in the documentation of the Image.get_axis_increments()\n function. In particular, note that dy is typically\n positive and dx is usually negative, such that when the\n image is plotted, east appears anticlockwise of north, and\n east is towards the left of the plot when the image\n rotation angle is zero.\n\n If either of the signs of the two newinc numbers is\n different from the sign of the increments of the original\n image (queryable with image.get_axis_increments()), then\n the image will be reflected about that axis. In this case\n the value of the refpix argument should be chosen with\n care, because otherwise the sampled part of the image may\n end up being reflected outside the limits of the image\n array, and the result will be a blank image.\n\n If only one number is given for newinc then both axes\n are given the same resolution, but the signs of the\n increments are kept the same as the pixel increments\n of the original image.\n flux : bool\n This tells the function whether the pixel units of the\n image are flux densities (flux=True), such as\n erg/s/cm2/Hz, or whether they are per-steradian brightness\n units (flux=False), such as erg/s/cm2/Hz/steradian. It\n needs to know this when it changes the pixel size, because\n when pixel sizes change, resampled flux densities need to\n be corrected for the change in the area per pixel, where\n resampled brightnesses don't.\n order : int\n The order of the spline interpolation. This can take any\n value from 0-5. The default is 1 (linear interpolation).\n When this function is used to lower the resolution of\n an image, the low-pass anti-aliasing filter that is applied,\n makes linear interpolation sufficient.\n Conversely, when this function is used to increase the\n image resolution, order=3 might be useful. Higher\n orders than this will tend to introduce ringing artefacts.\n interp : 'no' | 'linear' | 'spline'\n If 'no', replace masked data with the median image value.\n If 'linear', replace masked values using a linear\n interpolation between neighboring values.\n if 'spline', replace masked values using a spline\n interpolation between neighboring values.\n unit_pos : `astropy.units.Unit`\n The units of the refpos coordinates. Degrees by default.\n unit_inc : `astropy.units.Unit`\n The units of newinc. Arcseconds by default.\n antialias : bool\n By default, when the resolution of an image axis is about\n to be reduced, a low pass filter is first applied to suppress\n high spatial frequencies that can not be represented by the\n reduced sampling interval. If this is not done, high-frequency\n noise and sharp edges get folded back to lower frequencies,\n where they increase the noise level of the image and introduce\n ringing artefacts next to sharp edges, such as CCD saturation\n spikes. This filtering can be disabled by passing False to\n the antialias argument.\n inplace : bool\n If False, return a resampled copy of the image (the default).\n If True, resample the original image in-place, and return that.\n cutoff : float\n Mask each output pixel where at least this fraction of the\n pixel was interpolated from dummy values given to masked\n input pixels.\n window : str\n The type of window function to use for antialiasing\n in the Fourier plane. The following windows are supported:\n\n blackman\n This window suppresses ringing better than any other\n window, at the expense of lowered image resolution. In\n the image plane, the PSF of this window is\n approximately gaussian, with a standard deviation of\n around 0.96*newstep, and a FWHM of about 2.3*newstep.\n\n gaussian\n A truncated gaussian window. This has a smaller PSF\n than the blackman window, however gaussians never fall\n to zero, so either significant ringing will be seen due\n to truncation of the gaussian, or low-level aliasing\n will occur, depending on the spatial frequency coverage\n of the image beyond the folding frequency. It can be a\n good choice for images that only contain smoothly\n varying features. It is equivalent to a convolution of\n the image with both an airy profile and a gaussian of\n standard deviation 0.724*newstep (FWHM 1.704*newstep).\n\n rectangle\n This window simply zeros all spatial frequencies above\n the highest that can be correctly sampled by the new\n pixel size. This gives the best resolution of any of\n the windows, but this is marred by the strong sidelobes\n of the resulting airy-profile, especially near bright\n point sources and CCD saturation lines.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n The resampled image is returned.\n\n " if is_int(newdim): newdim = (newdim, newdim) newdim = np.asarray(newdim, dtype=int) if ((refpos is None) and (refpix is None)): refpix = np.array([(- 0.5), (- 0.5)]) refpos = self.wcs.pix2sky(refpix) elif ((refpos is not None) and (refpix is not None)): refpos = np.asarray(refpos, dtype=float) if (unit_pos is not None): refpos = UnitArray(refpos, unit_pos, self.wcs.unit) refpix = np.asarray(refpix, dtype=float) else: raise ValueError('The refpos and refpix arguments should both be None or both have values.') oldinc = self.wcs.get_axis_increments() if is_number(newinc): size = abs(newinc) newinc = ((size * np.sign(oldinc[0])), (size * np.sign(oldinc[1]))) newinc = np.asarray(newinc, dtype=float) if (unit_inc is not None): newinc = UnitArray(newinc, unit_inc, self.wcs.unit) data = self._prepare_data(interp) if antialias: (data, newfmax) = _antialias_filter_image(data, abs(oldinc), abs(newinc), self.get_spatial_fmax(), window) else: newfmax = (0.5 / abs(newinc)) new2old = np.array([[(newinc[0] / oldinc[0]), 0], [0, (newinc[1] / oldinc[1])]]) old2new = np.linalg.inv(new2old) offset = (self.wcs.sky2pix(refpos).T[(:, :1)] - np.dot(new2old, refpix[(np.newaxis, :)].T)) data = affine_transform(data, new2old, offset.flatten(), output_shape=newdim, order=order, prefilter=(order >= 3)) mask = self._mask.astype(float) mask = affine_transform(mask, new2old, offset.flatten(), cval=1.0, output_shape=newdim, output=float) mask = np.greater(mask, max(cutoff, 1e-06)) if (self._var is not None): var = affine_transform(self._var, new2old, offset.flatten(), output_shape=newdim, order=order, prefilter=(order >= 3)) else: var = None xs = abs((newinc[1] / oldinc[1])) ys = abs((newinc[0] / oldinc[0])) n = (xs * ys) if flux: data *= n if (var is not None): var *= ((xs if ((xs > 1.0) and antialias) else (xs ** 2)) * (ys if ((ys > 1.0) and antialias) else (ys ** 2))) elif ((var is not None) and ((xs > 1.0) or (ys > 1.0))): var *= (((1 / xs) if ((xs > 1.0) and antialias) else 1.0) * ((1 / ys) if ((ys > 1.0) and antialias) else 1.0)) oldcrpix = np.array([[(self.wcs.get_crpix2() - 1)], [(self.wcs.get_crpix1() - 1)]]) newcrpix = np.dot(old2new, (oldcrpix - offset)) wcs = self.wcs.copy() wcs.set_axis_increments(newinc) wcs.naxis1 = newdim[1] wcs.naxis2 = newdim[0] wcs.set_crpix1((newcrpix[1] + 1)) wcs.set_crpix2((newcrpix[0] + 1)) out = (self if inplace else self.clone()) out._data = data out._mask = mask out._var = var out.wcs = wcs out.update_spatial_fmax(newfmax) return out
def regrid(self, newdim, refpos, refpix, newinc, flux=False, order=1, interp='no', unit_pos=u.deg, unit_inc=u.arcsec, antialias=True, inplace=False, cutoff=0.25, window='blackman'): "Resample an image of the sky to select its angular resolution,\n to specify the position of the sky in the image array, and\n optionally to reflect one or more of its axes.\n\n This function can be used to decrease or increase the\n resolution of an image. It can also shift the contents of an\n image to place a specific (dec,ra) position at a specific\n fractional pixel position. Finally, it can be used to invert\n the direction of one or both of the array axes on the sky.\n\n When this function is used to resample an image to a lower\n resolution, a low-pass anti-aliasing filter is applied to the\n image before it is resampled, to remove all spatial\n frequencies below half the new sampling rate. This is required\n to satisfy the Nyquist sampling constraint. It prevents high\n spatial-frequency noise and edges from being aliased to lower\n frequency artefacts in the resampled image. The removal of\n this noise improves the signal to noise ratio of the resampled\n image.\n\n Parameters\n ----------\n newdim : int or (int,int)\n The desired new dimensions. Python notation: (ny,nx)\n refpos : (float, float)\n The sky position (dec,ra) to place at the pixel specified\n by the refpix argument.\n\n If refpix and refpos are both None, the sky position at\n the bottom corner of the input image is placed at the\n bottom left corner of the output image. Note that refpix\n and refpos must either both be given values, or both\n be None.\n refpix : (float, float)\n The [Y, X] indexes of the output pixel where the sky\n position, refpos, should be placed. Y and X are\n interpreted as floating point indexes, where integer\n values indicate pixel centers and integer values +/- 0.5\n indicate the edges of pixels.\n\n If refpix and refpos are both None, the sky position at\n the bottom corner of the input image is placed at the\n bottom left corner of the output image. Note that refpix\n and refpos must either both be given values, or both\n be None.\n newinc : float or (float, float)\n The signed increments of the angle on the sky from one\n pixel to the next, given as either a single increment for\n both image axes, or two numbers (dy,dx) for the Y and X\n axes respectively.\n\n The signs of these increments are interpreted as described\n in the documentation of the Image.get_axis_increments()\n function. In particular, note that dy is typically\n positive and dx is usually negative, such that when the\n image is plotted, east appears anticlockwise of north, and\n east is towards the left of the plot when the image\n rotation angle is zero.\n\n If either of the signs of the two newinc numbers is\n different from the sign of the increments of the original\n image (queryable with image.get_axis_increments()), then\n the image will be reflected about that axis. In this case\n the value of the refpix argument should be chosen with\n care, because otherwise the sampled part of the image may\n end up being reflected outside the limits of the image\n array, and the result will be a blank image.\n\n If only one number is given for newinc then both axes\n are given the same resolution, but the signs of the\n increments are kept the same as the pixel increments\n of the original image.\n flux : bool\n This tells the function whether the pixel units of the\n image are flux densities (flux=True), such as\n erg/s/cm2/Hz, or whether they are per-steradian brightness\n units (flux=False), such as erg/s/cm2/Hz/steradian. It\n needs to know this when it changes the pixel size, because\n when pixel sizes change, resampled flux densities need to\n be corrected for the change in the area per pixel, where\n resampled brightnesses don't.\n order : int\n The order of the spline interpolation. This can take any\n value from 0-5. The default is 1 (linear interpolation).\n When this function is used to lower the resolution of\n an image, the low-pass anti-aliasing filter that is applied,\n makes linear interpolation sufficient.\n Conversely, when this function is used to increase the\n image resolution, order=3 might be useful. Higher\n orders than this will tend to introduce ringing artefacts.\n interp : 'no' | 'linear' | 'spline'\n If 'no', replace masked data with the median image value.\n If 'linear', replace masked values using a linear\n interpolation between neighboring values.\n if 'spline', replace masked values using a spline\n interpolation between neighboring values.\n unit_pos : `astropy.units.Unit`\n The units of the refpos coordinates. Degrees by default.\n unit_inc : `astropy.units.Unit`\n The units of newinc. Arcseconds by default.\n antialias : bool\n By default, when the resolution of an image axis is about\n to be reduced, a low pass filter is first applied to suppress\n high spatial frequencies that can not be represented by the\n reduced sampling interval. If this is not done, high-frequency\n noise and sharp edges get folded back to lower frequencies,\n where they increase the noise level of the image and introduce\n ringing artefacts next to sharp edges, such as CCD saturation\n spikes. This filtering can be disabled by passing False to\n the antialias argument.\n inplace : bool\n If False, return a resampled copy of the image (the default).\n If True, resample the original image in-place, and return that.\n cutoff : float\n Mask each output pixel where at least this fraction of the\n pixel was interpolated from dummy values given to masked\n input pixels.\n window : str\n The type of window function to use for antialiasing\n in the Fourier plane. The following windows are supported:\n\n blackman\n This window suppresses ringing better than any other\n window, at the expense of lowered image resolution. In\n the image plane, the PSF of this window is\n approximately gaussian, with a standard deviation of\n around 0.96*newstep, and a FWHM of about 2.3*newstep.\n\n gaussian\n A truncated gaussian window. This has a smaller PSF\n than the blackman window, however gaussians never fall\n to zero, so either significant ringing will be seen due\n to truncation of the gaussian, or low-level aliasing\n will occur, depending on the spatial frequency coverage\n of the image beyond the folding frequency. It can be a\n good choice for images that only contain smoothly\n varying features. It is equivalent to a convolution of\n the image with both an airy profile and a gaussian of\n standard deviation 0.724*newstep (FWHM 1.704*newstep).\n\n rectangle\n This window simply zeros all spatial frequencies above\n the highest that can be correctly sampled by the new\n pixel size. This gives the best resolution of any of\n the windows, but this is marred by the strong sidelobes\n of the resulting airy-profile, especially near bright\n point sources and CCD saturation lines.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n The resampled image is returned.\n\n " if is_int(newdim): newdim = (newdim, newdim) newdim = np.asarray(newdim, dtype=int) if ((refpos is None) and (refpix is None)): refpix = np.array([(- 0.5), (- 0.5)]) refpos = self.wcs.pix2sky(refpix) elif ((refpos is not None) and (refpix is not None)): refpos = np.asarray(refpos, dtype=float) if (unit_pos is not None): refpos = UnitArray(refpos, unit_pos, self.wcs.unit) refpix = np.asarray(refpix, dtype=float) else: raise ValueError('The refpos and refpix arguments should both be None or both have values.') oldinc = self.wcs.get_axis_increments() if is_number(newinc): size = abs(newinc) newinc = ((size * np.sign(oldinc[0])), (size * np.sign(oldinc[1]))) newinc = np.asarray(newinc, dtype=float) if (unit_inc is not None): newinc = UnitArray(newinc, unit_inc, self.wcs.unit) data = self._prepare_data(interp) if antialias: (data, newfmax) = _antialias_filter_image(data, abs(oldinc), abs(newinc), self.get_spatial_fmax(), window) else: newfmax = (0.5 / abs(newinc)) new2old = np.array([[(newinc[0] / oldinc[0]), 0], [0, (newinc[1] / oldinc[1])]]) old2new = np.linalg.inv(new2old) offset = (self.wcs.sky2pix(refpos).T[(:, :1)] - np.dot(new2old, refpix[(np.newaxis, :)].T)) data = affine_transform(data, new2old, offset.flatten(), output_shape=newdim, order=order, prefilter=(order >= 3)) mask = self._mask.astype(float) mask = affine_transform(mask, new2old, offset.flatten(), cval=1.0, output_shape=newdim, output=float) mask = np.greater(mask, max(cutoff, 1e-06)) if (self._var is not None): var = affine_transform(self._var, new2old, offset.flatten(), output_shape=newdim, order=order, prefilter=(order >= 3)) else: var = None xs = abs((newinc[1] / oldinc[1])) ys = abs((newinc[0] / oldinc[0])) n = (xs * ys) if flux: data *= n if (var is not None): var *= ((xs if ((xs > 1.0) and antialias) else (xs ** 2)) * (ys if ((ys > 1.0) and antialias) else (ys ** 2))) elif ((var is not None) and ((xs > 1.0) or (ys > 1.0))): var *= (((1 / xs) if ((xs > 1.0) and antialias) else 1.0) * ((1 / ys) if ((ys > 1.0) and antialias) else 1.0)) oldcrpix = np.array([[(self.wcs.get_crpix2() - 1)], [(self.wcs.get_crpix1() - 1)]]) newcrpix = np.dot(old2new, (oldcrpix - offset)) wcs = self.wcs.copy() wcs.set_axis_increments(newinc) wcs.naxis1 = newdim[1] wcs.naxis2 = newdim[0] wcs.set_crpix1((newcrpix[1] + 1)) wcs.set_crpix2((newcrpix[0] + 1)) out = (self if inplace else self.clone()) out._data = data out._mask = mask out._var = var out.wcs = wcs out.update_spatial_fmax(newfmax) return out<|docstring|>Resample an image of the sky to select its angular resolution, to specify the position of the sky in the image array, and optionally to reflect one or more of its axes. This function can be used to decrease or increase the resolution of an image. It can also shift the contents of an image to place a specific (dec,ra) position at a specific fractional pixel position. Finally, it can be used to invert the direction of one or both of the array axes on the sky. When this function is used to resample an image to a lower resolution, a low-pass anti-aliasing filter is applied to the image before it is resampled, to remove all spatial frequencies below half the new sampling rate. This is required to satisfy the Nyquist sampling constraint. It prevents high spatial-frequency noise and edges from being aliased to lower frequency artefacts in the resampled image. The removal of this noise improves the signal to noise ratio of the resampled image. Parameters ---------- newdim : int or (int,int) The desired new dimensions. Python notation: (ny,nx) refpos : (float, float) The sky position (dec,ra) to place at the pixel specified by the refpix argument. If refpix and refpos are both None, the sky position at the bottom corner of the input image is placed at the bottom left corner of the output image. Note that refpix and refpos must either both be given values, or both be None. refpix : (float, float) The [Y, X] indexes of the output pixel where the sky position, refpos, should be placed. Y and X are interpreted as floating point indexes, where integer values indicate pixel centers and integer values +/- 0.5 indicate the edges of pixels. If refpix and refpos are both None, the sky position at the bottom corner of the input image is placed at the bottom left corner of the output image. Note that refpix and refpos must either both be given values, or both be None. newinc : float or (float, float) The signed increments of the angle on the sky from one pixel to the next, given as either a single increment for both image axes, or two numbers (dy,dx) for the Y and X axes respectively. The signs of these increments are interpreted as described in the documentation of the Image.get_axis_increments() function. In particular, note that dy is typically positive and dx is usually negative, such that when the image is plotted, east appears anticlockwise of north, and east is towards the left of the plot when the image rotation angle is zero. If either of the signs of the two newinc numbers is different from the sign of the increments of the original image (queryable with image.get_axis_increments()), then the image will be reflected about that axis. In this case the value of the refpix argument should be chosen with care, because otherwise the sampled part of the image may end up being reflected outside the limits of the image array, and the result will be a blank image. If only one number is given for newinc then both axes are given the same resolution, but the signs of the increments are kept the same as the pixel increments of the original image. flux : bool This tells the function whether the pixel units of the image are flux densities (flux=True), such as erg/s/cm2/Hz, or whether they are per-steradian brightness units (flux=False), such as erg/s/cm2/Hz/steradian. It needs to know this when it changes the pixel size, because when pixel sizes change, resampled flux densities need to be corrected for the change in the area per pixel, where resampled brightnesses don't. order : int The order of the spline interpolation. This can take any value from 0-5. The default is 1 (linear interpolation). When this function is used to lower the resolution of an image, the low-pass anti-aliasing filter that is applied, makes linear interpolation sufficient. Conversely, when this function is used to increase the image resolution, order=3 might be useful. Higher orders than this will tend to introduce ringing artefacts. interp : 'no' | 'linear' | 'spline' If 'no', replace masked data with the median image value. If 'linear', replace masked values using a linear interpolation between neighboring values. if 'spline', replace masked values using a spline interpolation between neighboring values. unit_pos : `astropy.units.Unit` The units of the refpos coordinates. Degrees by default. unit_inc : `astropy.units.Unit` The units of newinc. Arcseconds by default. antialias : bool By default, when the resolution of an image axis is about to be reduced, a low pass filter is first applied to suppress high spatial frequencies that can not be represented by the reduced sampling interval. If this is not done, high-frequency noise and sharp edges get folded back to lower frequencies, where they increase the noise level of the image and introduce ringing artefacts next to sharp edges, such as CCD saturation spikes. This filtering can be disabled by passing False to the antialias argument. inplace : bool If False, return a resampled copy of the image (the default). If True, resample the original image in-place, and return that. cutoff : float Mask each output pixel where at least this fraction of the pixel was interpolated from dummy values given to masked input pixels. window : str The type of window function to use for antialiasing in the Fourier plane. The following windows are supported: blackman This window suppresses ringing better than any other window, at the expense of lowered image resolution. In the image plane, the PSF of this window is approximately gaussian, with a standard deviation of around 0.96*newstep, and a FWHM of about 2.3*newstep. gaussian A truncated gaussian window. This has a smaller PSF than the blackman window, however gaussians never fall to zero, so either significant ringing will be seen due to truncation of the gaussian, or low-level aliasing will occur, depending on the spatial frequency coverage of the image beyond the folding frequency. It can be a good choice for images that only contain smoothly varying features. It is equivalent to a convolution of the image with both an airy profile and a gaussian of standard deviation 0.724*newstep (FWHM 1.704*newstep). rectangle This window simply zeros all spatial frequencies above the highest that can be correctly sampled by the new pixel size. This gives the best resolution of any of the windows, but this is marred by the strong sidelobes of the resulting airy-profile, especially near bright point sources and CCD saturation lines. Returns ------- out : `~mpdaf.obj.Image` The resampled image is returned.<|endoftext|>
0e104b35daab298637558af0caf68b266138d36c9a66a84523943405a8f7357c
def align_with_image(self, other, flux=False, inplace=False, cutoff=0.25, antialias=True, window='blackman'): "Resample the image to give it the same orientation, position,\n resolution and size as a given image.\n\n The image is first rotated to give it the same orientation on\n the sky as the other image. The resampling process also\n eliminates any shear terms from the original image, so that\n its pixels can be correctly drawn on a rectangular grid.\n\n Secondly the image is resampled. This changes its resolution,\n shifts the image such that the same points on the sky appear\n in the same pixels as in the other image, and changes the\n dimensions of the image array to match that of the other\n image.\n\n The rotation and resampling processes are performed as\n separate steps because the anti-aliasing filter that needs to\n be applied in the resampling step reduces the resolution, is\n difficult to implement before the axes have been rotated to\n the final orientation.\n\n Parameters\n ----------\n other : `~mpdaf.obj.Image`\n The image to be aligned with.\n flux : bool\n This tells the function whether the pixel units of the\n image are flux densities (flux=True), such as\n erg/s/cm2/Hz, or whether they are per-steradian brightness\n units (flux=False), such as erg/s/cm2/Hz/steradian. It\n needs to know this when it changes the pixel size, because\n when pixel sizes change, resampled flux densities need to\n be corrected for the change in the area per pixel, where\n resampled brightnesses don't.\n inplace : bool\n If False, return an aligned copy of the image (the default).\n If True, align the original image in-place, and return that.\n cutoff : float\n Mask each output pixel where at least this fraction of the\n pixel was interpolated from dummy values given to masked\n input pixels.\n antialias : bool\n By default, when the resolution of an image axis is about\n to be reduced, a low pass filter is first applied to suppress\n high spatial frequencies that can not be represented by the\n reduced sampling interval. If this is not done, high-frequency\n noise and sharp edges get folded back to lower frequencies,\n where they increase the noise level of the image and introduce\n ringing artefacts next to sharp edges, such as CCD saturation\n spikes and bright unresolved stars. This filtering can be\n disabled by passing False to the antialias argument.\n window : str\n The type of window function to use for antialiasing\n in the Fourier plane. The following windows are supported:\n\n blackman\n This window suppresses ringing better than any other\n window, at the expense of lowered image resolution. In\n the image plane, the PSF of this window is\n approximately gaussian, with a standard deviation of\n around 0.96*newstep, and a FWHM of about 2.3*newstep.\n\n gaussian\n A truncated gaussian window. This has a smaller PSF\n than the blackman window, however gaussians never fall\n to zero, so either significant ringing will be seen due\n to truncation of the gaussian, or low-level aliasing\n will occur, depending on the spatial frequency coverage\n of the image beyond the folding frequency. It can be a\n good choice for images that only contain smoothly\n varying features. It is equivalent to a convolution of\n the image with both an airy profile and a gaussian of\n standard deviation 0.724*newstep (FWHM 1.704*newstep).\n\n rectangle\n This window simply zeros all spatial frequencies above\n the highest that can be correctly sampled by the new\n pixel size. This gives the best resolution of any of\n the windows, but this is marred by the strong sidelobes\n of the resulting airy-profile, especially near bright\n point sources and CCD saturation lines.\n\n " if self.wcs.isEqual(other.wcs): return (self if inplace else self.copy()) pixsky = other.wcs.pix2sky([[(- 1), (- 1)], [other.shape[0], (- 1)], [(- 1), other.shape[1]], [other.shape[0], other.shape[1]]], unit=u.deg) (dec_min, ra_min) = pixsky.min(axis=0) (dec_max, ra_max) = pixsky.max(axis=0) out = self.truncate(dec_min, dec_max, ra_min, ra_max, mask=False, unit=u.deg, inplace=inplace) out._rotate((other.wcs.get_rot() - out.wcs.get_rot()), reshape=True, regrid=True, flux=flux, cutoff=cutoff) centerpix = (np.asarray(other.shape) / 2.0) centersky = other.wcs.pix2sky(centerpix)[0] out.regrid(other.shape, centersky, centerpix, other.wcs.get_axis_increments(unit=u.deg), flux, unit_inc=u.deg, inplace=True, cutoff=cutoff, antialias=antialias, window=window) return out
Resample the image to give it the same orientation, position, resolution and size as a given image. The image is first rotated to give it the same orientation on the sky as the other image. The resampling process also eliminates any shear terms from the original image, so that its pixels can be correctly drawn on a rectangular grid. Secondly the image is resampled. This changes its resolution, shifts the image such that the same points on the sky appear in the same pixels as in the other image, and changes the dimensions of the image array to match that of the other image. The rotation and resampling processes are performed as separate steps because the anti-aliasing filter that needs to be applied in the resampling step reduces the resolution, is difficult to implement before the axes have been rotated to the final orientation. Parameters ---------- other : `~mpdaf.obj.Image` The image to be aligned with. flux : bool This tells the function whether the pixel units of the image are flux densities (flux=True), such as erg/s/cm2/Hz, or whether they are per-steradian brightness units (flux=False), such as erg/s/cm2/Hz/steradian. It needs to know this when it changes the pixel size, because when pixel sizes change, resampled flux densities need to be corrected for the change in the area per pixel, where resampled brightnesses don't. inplace : bool If False, return an aligned copy of the image (the default). If True, align the original image in-place, and return that. cutoff : float Mask each output pixel where at least this fraction of the pixel was interpolated from dummy values given to masked input pixels. antialias : bool By default, when the resolution of an image axis is about to be reduced, a low pass filter is first applied to suppress high spatial frequencies that can not be represented by the reduced sampling interval. If this is not done, high-frequency noise and sharp edges get folded back to lower frequencies, where they increase the noise level of the image and introduce ringing artefacts next to sharp edges, such as CCD saturation spikes and bright unresolved stars. This filtering can be disabled by passing False to the antialias argument. window : str The type of window function to use for antialiasing in the Fourier plane. The following windows are supported: blackman This window suppresses ringing better than any other window, at the expense of lowered image resolution. In the image plane, the PSF of this window is approximately gaussian, with a standard deviation of around 0.96*newstep, and a FWHM of about 2.3*newstep. gaussian A truncated gaussian window. This has a smaller PSF than the blackman window, however gaussians never fall to zero, so either significant ringing will be seen due to truncation of the gaussian, or low-level aliasing will occur, depending on the spatial frequency coverage of the image beyond the folding frequency. It can be a good choice for images that only contain smoothly varying features. It is equivalent to a convolution of the image with both an airy profile and a gaussian of standard deviation 0.724*newstep (FWHM 1.704*newstep). rectangle This window simply zeros all spatial frequencies above the highest that can be correctly sampled by the new pixel size. This gives the best resolution of any of the windows, but this is marred by the strong sidelobes of the resulting airy-profile, especially near bright point sources and CCD saturation lines.
lib/mpdaf/obj/image.py
align_with_image
musevlt/mpdaf
4
python
def align_with_image(self, other, flux=False, inplace=False, cutoff=0.25, antialias=True, window='blackman'): "Resample the image to give it the same orientation, position,\n resolution and size as a given image.\n\n The image is first rotated to give it the same orientation on\n the sky as the other image. The resampling process also\n eliminates any shear terms from the original image, so that\n its pixels can be correctly drawn on a rectangular grid.\n\n Secondly the image is resampled. This changes its resolution,\n shifts the image such that the same points on the sky appear\n in the same pixels as in the other image, and changes the\n dimensions of the image array to match that of the other\n image.\n\n The rotation and resampling processes are performed as\n separate steps because the anti-aliasing filter that needs to\n be applied in the resampling step reduces the resolution, is\n difficult to implement before the axes have been rotated to\n the final orientation.\n\n Parameters\n ----------\n other : `~mpdaf.obj.Image`\n The image to be aligned with.\n flux : bool\n This tells the function whether the pixel units of the\n image are flux densities (flux=True), such as\n erg/s/cm2/Hz, or whether they are per-steradian brightness\n units (flux=False), such as erg/s/cm2/Hz/steradian. It\n needs to know this when it changes the pixel size, because\n when pixel sizes change, resampled flux densities need to\n be corrected for the change in the area per pixel, where\n resampled brightnesses don't.\n inplace : bool\n If False, return an aligned copy of the image (the default).\n If True, align the original image in-place, and return that.\n cutoff : float\n Mask each output pixel where at least this fraction of the\n pixel was interpolated from dummy values given to masked\n input pixels.\n antialias : bool\n By default, when the resolution of an image axis is about\n to be reduced, a low pass filter is first applied to suppress\n high spatial frequencies that can not be represented by the\n reduced sampling interval. If this is not done, high-frequency\n noise and sharp edges get folded back to lower frequencies,\n where they increase the noise level of the image and introduce\n ringing artefacts next to sharp edges, such as CCD saturation\n spikes and bright unresolved stars. This filtering can be\n disabled by passing False to the antialias argument.\n window : str\n The type of window function to use for antialiasing\n in the Fourier plane. The following windows are supported:\n\n blackman\n This window suppresses ringing better than any other\n window, at the expense of lowered image resolution. In\n the image plane, the PSF of this window is\n approximately gaussian, with a standard deviation of\n around 0.96*newstep, and a FWHM of about 2.3*newstep.\n\n gaussian\n A truncated gaussian window. This has a smaller PSF\n than the blackman window, however gaussians never fall\n to zero, so either significant ringing will be seen due\n to truncation of the gaussian, or low-level aliasing\n will occur, depending on the spatial frequency coverage\n of the image beyond the folding frequency. It can be a\n good choice for images that only contain smoothly\n varying features. It is equivalent to a convolution of\n the image with both an airy profile and a gaussian of\n standard deviation 0.724*newstep (FWHM 1.704*newstep).\n\n rectangle\n This window simply zeros all spatial frequencies above\n the highest that can be correctly sampled by the new\n pixel size. This gives the best resolution of any of\n the windows, but this is marred by the strong sidelobes\n of the resulting airy-profile, especially near bright\n point sources and CCD saturation lines.\n\n " if self.wcs.isEqual(other.wcs): return (self if inplace else self.copy()) pixsky = other.wcs.pix2sky([[(- 1), (- 1)], [other.shape[0], (- 1)], [(- 1), other.shape[1]], [other.shape[0], other.shape[1]]], unit=u.deg) (dec_min, ra_min) = pixsky.min(axis=0) (dec_max, ra_max) = pixsky.max(axis=0) out = self.truncate(dec_min, dec_max, ra_min, ra_max, mask=False, unit=u.deg, inplace=inplace) out._rotate((other.wcs.get_rot() - out.wcs.get_rot()), reshape=True, regrid=True, flux=flux, cutoff=cutoff) centerpix = (np.asarray(other.shape) / 2.0) centersky = other.wcs.pix2sky(centerpix)[0] out.regrid(other.shape, centersky, centerpix, other.wcs.get_axis_increments(unit=u.deg), flux, unit_inc=u.deg, inplace=True, cutoff=cutoff, antialias=antialias, window=window) return out
def align_with_image(self, other, flux=False, inplace=False, cutoff=0.25, antialias=True, window='blackman'): "Resample the image to give it the same orientation, position,\n resolution and size as a given image.\n\n The image is first rotated to give it the same orientation on\n the sky as the other image. The resampling process also\n eliminates any shear terms from the original image, so that\n its pixels can be correctly drawn on a rectangular grid.\n\n Secondly the image is resampled. This changes its resolution,\n shifts the image such that the same points on the sky appear\n in the same pixels as in the other image, and changes the\n dimensions of the image array to match that of the other\n image.\n\n The rotation and resampling processes are performed as\n separate steps because the anti-aliasing filter that needs to\n be applied in the resampling step reduces the resolution, is\n difficult to implement before the axes have been rotated to\n the final orientation.\n\n Parameters\n ----------\n other : `~mpdaf.obj.Image`\n The image to be aligned with.\n flux : bool\n This tells the function whether the pixel units of the\n image are flux densities (flux=True), such as\n erg/s/cm2/Hz, or whether they are per-steradian brightness\n units (flux=False), such as erg/s/cm2/Hz/steradian. It\n needs to know this when it changes the pixel size, because\n when pixel sizes change, resampled flux densities need to\n be corrected for the change in the area per pixel, where\n resampled brightnesses don't.\n inplace : bool\n If False, return an aligned copy of the image (the default).\n If True, align the original image in-place, and return that.\n cutoff : float\n Mask each output pixel where at least this fraction of the\n pixel was interpolated from dummy values given to masked\n input pixels.\n antialias : bool\n By default, when the resolution of an image axis is about\n to be reduced, a low pass filter is first applied to suppress\n high spatial frequencies that can not be represented by the\n reduced sampling interval. If this is not done, high-frequency\n noise and sharp edges get folded back to lower frequencies,\n where they increase the noise level of the image and introduce\n ringing artefacts next to sharp edges, such as CCD saturation\n spikes and bright unresolved stars. This filtering can be\n disabled by passing False to the antialias argument.\n window : str\n The type of window function to use for antialiasing\n in the Fourier plane. The following windows are supported:\n\n blackman\n This window suppresses ringing better than any other\n window, at the expense of lowered image resolution. In\n the image plane, the PSF of this window is\n approximately gaussian, with a standard deviation of\n around 0.96*newstep, and a FWHM of about 2.3*newstep.\n\n gaussian\n A truncated gaussian window. This has a smaller PSF\n than the blackman window, however gaussians never fall\n to zero, so either significant ringing will be seen due\n to truncation of the gaussian, or low-level aliasing\n will occur, depending on the spatial frequency coverage\n of the image beyond the folding frequency. It can be a\n good choice for images that only contain smoothly\n varying features. It is equivalent to a convolution of\n the image with both an airy profile and a gaussian of\n standard deviation 0.724*newstep (FWHM 1.704*newstep).\n\n rectangle\n This window simply zeros all spatial frequencies above\n the highest that can be correctly sampled by the new\n pixel size. This gives the best resolution of any of\n the windows, but this is marred by the strong sidelobes\n of the resulting airy-profile, especially near bright\n point sources and CCD saturation lines.\n\n " if self.wcs.isEqual(other.wcs): return (self if inplace else self.copy()) pixsky = other.wcs.pix2sky([[(- 1), (- 1)], [other.shape[0], (- 1)], [(- 1), other.shape[1]], [other.shape[0], other.shape[1]]], unit=u.deg) (dec_min, ra_min) = pixsky.min(axis=0) (dec_max, ra_max) = pixsky.max(axis=0) out = self.truncate(dec_min, dec_max, ra_min, ra_max, mask=False, unit=u.deg, inplace=inplace) out._rotate((other.wcs.get_rot() - out.wcs.get_rot()), reshape=True, regrid=True, flux=flux, cutoff=cutoff) centerpix = (np.asarray(other.shape) / 2.0) centersky = other.wcs.pix2sky(centerpix)[0] out.regrid(other.shape, centersky, centerpix, other.wcs.get_axis_increments(unit=u.deg), flux, unit_inc=u.deg, inplace=True, cutoff=cutoff, antialias=antialias, window=window) return out<|docstring|>Resample the image to give it the same orientation, position, resolution and size as a given image. The image is first rotated to give it the same orientation on the sky as the other image. The resampling process also eliminates any shear terms from the original image, so that its pixels can be correctly drawn on a rectangular grid. Secondly the image is resampled. This changes its resolution, shifts the image such that the same points on the sky appear in the same pixels as in the other image, and changes the dimensions of the image array to match that of the other image. The rotation and resampling processes are performed as separate steps because the anti-aliasing filter that needs to be applied in the resampling step reduces the resolution, is difficult to implement before the axes have been rotated to the final orientation. Parameters ---------- other : `~mpdaf.obj.Image` The image to be aligned with. flux : bool This tells the function whether the pixel units of the image are flux densities (flux=True), such as erg/s/cm2/Hz, or whether they are per-steradian brightness units (flux=False), such as erg/s/cm2/Hz/steradian. It needs to know this when it changes the pixel size, because when pixel sizes change, resampled flux densities need to be corrected for the change in the area per pixel, where resampled brightnesses don't. inplace : bool If False, return an aligned copy of the image (the default). If True, align the original image in-place, and return that. cutoff : float Mask each output pixel where at least this fraction of the pixel was interpolated from dummy values given to masked input pixels. antialias : bool By default, when the resolution of an image axis is about to be reduced, a low pass filter is first applied to suppress high spatial frequencies that can not be represented by the reduced sampling interval. If this is not done, high-frequency noise and sharp edges get folded back to lower frequencies, where they increase the noise level of the image and introduce ringing artefacts next to sharp edges, such as CCD saturation spikes and bright unresolved stars. This filtering can be disabled by passing False to the antialias argument. window : str The type of window function to use for antialiasing in the Fourier plane. The following windows are supported: blackman This window suppresses ringing better than any other window, at the expense of lowered image resolution. In the image plane, the PSF of this window is approximately gaussian, with a standard deviation of around 0.96*newstep, and a FWHM of about 2.3*newstep. gaussian A truncated gaussian window. This has a smaller PSF than the blackman window, however gaussians never fall to zero, so either significant ringing will be seen due to truncation of the gaussian, or low-level aliasing will occur, depending on the spatial frequency coverage of the image beyond the folding frequency. It can be a good choice for images that only contain smoothly varying features. It is equivalent to a convolution of the image with both an airy profile and a gaussian of standard deviation 0.724*newstep (FWHM 1.704*newstep). rectangle This window simply zeros all spatial frequencies above the highest that can be correctly sampled by the new pixel size. This gives the best resolution of any of the windows, but this is marred by the strong sidelobes of the resulting airy-profile, especially near bright point sources and CCD saturation lines.<|endoftext|>
575f30a67aa9881120c8d95036e6536deb747a9d2f00addc3d83b2cdf0498aa1
def estimate_coordinate_offset(self, ref, nsigma=1.0): 'Given a reference image of the sky that is expected to\n overlap with the current image, attempt to fit for any offset\n between the sky coordinate system of the current image and\n that of the reference image. The returned value is designed to\n be added to the coordinate reference pixel values of self.wcs.\n\n This function performs the following steps:\n\n 1. The align_with_image() method is called to resample the\n reference image onto the same coordinate grid as the\n current image.\n\n 2. The two images are then cross-correlated, after zeroing all\n background values in the images below nsigma standard\n deviations above the mean.\n\n 3. The peak in the auto-correlation image is found and its\n sub-pixel position is estimated by a simple quadratic\n interpolation. This position, relative to the center of the\n auto-correlation image, gives the average position offset\n between similar features in the two images.\n\n Parameters\n ----------\n ref : `~mpdaf.obj.Image`\n The image of the sky that is to be used as the coordinate\n reference. The sky coverage of this image should overlap\n with that of self. Ideally the resolution of this image\n should be at least as good as the resolution of self.\n nsigma : float\n Only values that exceed this many standard deviations\n above the mean of each image will be used.\n\n Returns\n -------\n out : float,float\n The pixel offsets that would need to be added to the\n coordinate reference pixel values, crpix2 and crpix1, of\n self.wcs to make the features in self line up with those\n in the reference image.\n\n ' ref = ref.align_with_image(self) mask = np.ma.mask_or(self._mask, ref._mask) sdata = np.ma.array(data=self._data, mask=mask) rdata = np.ma.array(data=ref._data, mask=mask) sdata = np.ma.filled(sdata, np.ma.median(sdata)) rdata = np.ma.filled(rdata, np.ma.median(rdata)) mask = (sdata < (sdata.mean() + (nsigma * sdata.std()))) sdata[mask] = 0 mask = (rdata < (rdata.mean() + (nsigma * rdata.std()))) rdata[mask] = 0 sdata = np.log((1.0 + sdata)) rdata = np.log((1.0 + rdata)) cc = signal.fftconvolve(sdata, rdata[(::(- 1), ::(- 1))], mode='same') (py, px) = np.unravel_index(np.argmax(cc), cc.shape) py2 = ((py - 1) + _find_quadratic_peak(cc[((py - 1):(py + 2), px)])) px2 = ((px - 1) + _find_quadratic_peak(cc[(py, (px - 1):(px + 2))])) dy = (py2 - float((cc.shape[0] // 2))) dx = (px2 - float((cc.shape[1] // 2))) return (dy, dx)
Given a reference image of the sky that is expected to overlap with the current image, attempt to fit for any offset between the sky coordinate system of the current image and that of the reference image. The returned value is designed to be added to the coordinate reference pixel values of self.wcs. This function performs the following steps: 1. The align_with_image() method is called to resample the reference image onto the same coordinate grid as the current image. 2. The two images are then cross-correlated, after zeroing all background values in the images below nsigma standard deviations above the mean. 3. The peak in the auto-correlation image is found and its sub-pixel position is estimated by a simple quadratic interpolation. This position, relative to the center of the auto-correlation image, gives the average position offset between similar features in the two images. Parameters ---------- ref : `~mpdaf.obj.Image` The image of the sky that is to be used as the coordinate reference. The sky coverage of this image should overlap with that of self. Ideally the resolution of this image should be at least as good as the resolution of self. nsigma : float Only values that exceed this many standard deviations above the mean of each image will be used. Returns ------- out : float,float The pixel offsets that would need to be added to the coordinate reference pixel values, crpix2 and crpix1, of self.wcs to make the features in self line up with those in the reference image.
lib/mpdaf/obj/image.py
estimate_coordinate_offset
musevlt/mpdaf
4
python
def estimate_coordinate_offset(self, ref, nsigma=1.0): 'Given a reference image of the sky that is expected to\n overlap with the current image, attempt to fit for any offset\n between the sky coordinate system of the current image and\n that of the reference image. The returned value is designed to\n be added to the coordinate reference pixel values of self.wcs.\n\n This function performs the following steps:\n\n 1. The align_with_image() method is called to resample the\n reference image onto the same coordinate grid as the\n current image.\n\n 2. The two images are then cross-correlated, after zeroing all\n background values in the images below nsigma standard\n deviations above the mean.\n\n 3. The peak in the auto-correlation image is found and its\n sub-pixel position is estimated by a simple quadratic\n interpolation. This position, relative to the center of the\n auto-correlation image, gives the average position offset\n between similar features in the two images.\n\n Parameters\n ----------\n ref : `~mpdaf.obj.Image`\n The image of the sky that is to be used as the coordinate\n reference. The sky coverage of this image should overlap\n with that of self. Ideally the resolution of this image\n should be at least as good as the resolution of self.\n nsigma : float\n Only values that exceed this many standard deviations\n above the mean of each image will be used.\n\n Returns\n -------\n out : float,float\n The pixel offsets that would need to be added to the\n coordinate reference pixel values, crpix2 and crpix1, of\n self.wcs to make the features in self line up with those\n in the reference image.\n\n ' ref = ref.align_with_image(self) mask = np.ma.mask_or(self._mask, ref._mask) sdata = np.ma.array(data=self._data, mask=mask) rdata = np.ma.array(data=ref._data, mask=mask) sdata = np.ma.filled(sdata, np.ma.median(sdata)) rdata = np.ma.filled(rdata, np.ma.median(rdata)) mask = (sdata < (sdata.mean() + (nsigma * sdata.std()))) sdata[mask] = 0 mask = (rdata < (rdata.mean() + (nsigma * rdata.std()))) rdata[mask] = 0 sdata = np.log((1.0 + sdata)) rdata = np.log((1.0 + rdata)) cc = signal.fftconvolve(sdata, rdata[(::(- 1), ::(- 1))], mode='same') (py, px) = np.unravel_index(np.argmax(cc), cc.shape) py2 = ((py - 1) + _find_quadratic_peak(cc[((py - 1):(py + 2), px)])) px2 = ((px - 1) + _find_quadratic_peak(cc[(py, (px - 1):(px + 2))])) dy = (py2 - float((cc.shape[0] // 2))) dx = (px2 - float((cc.shape[1] // 2))) return (dy, dx)
def estimate_coordinate_offset(self, ref, nsigma=1.0): 'Given a reference image of the sky that is expected to\n overlap with the current image, attempt to fit for any offset\n between the sky coordinate system of the current image and\n that of the reference image. The returned value is designed to\n be added to the coordinate reference pixel values of self.wcs.\n\n This function performs the following steps:\n\n 1. The align_with_image() method is called to resample the\n reference image onto the same coordinate grid as the\n current image.\n\n 2. The two images are then cross-correlated, after zeroing all\n background values in the images below nsigma standard\n deviations above the mean.\n\n 3. The peak in the auto-correlation image is found and its\n sub-pixel position is estimated by a simple quadratic\n interpolation. This position, relative to the center of the\n auto-correlation image, gives the average position offset\n between similar features in the two images.\n\n Parameters\n ----------\n ref : `~mpdaf.obj.Image`\n The image of the sky that is to be used as the coordinate\n reference. The sky coverage of this image should overlap\n with that of self. Ideally the resolution of this image\n should be at least as good as the resolution of self.\n nsigma : float\n Only values that exceed this many standard deviations\n above the mean of each image will be used.\n\n Returns\n -------\n out : float,float\n The pixel offsets that would need to be added to the\n coordinate reference pixel values, crpix2 and crpix1, of\n self.wcs to make the features in self line up with those\n in the reference image.\n\n ' ref = ref.align_with_image(self) mask = np.ma.mask_or(self._mask, ref._mask) sdata = np.ma.array(data=self._data, mask=mask) rdata = np.ma.array(data=ref._data, mask=mask) sdata = np.ma.filled(sdata, np.ma.median(sdata)) rdata = np.ma.filled(rdata, np.ma.median(rdata)) mask = (sdata < (sdata.mean() + (nsigma * sdata.std()))) sdata[mask] = 0 mask = (rdata < (rdata.mean() + (nsigma * rdata.std()))) rdata[mask] = 0 sdata = np.log((1.0 + sdata)) rdata = np.log((1.0 + rdata)) cc = signal.fftconvolve(sdata, rdata[(::(- 1), ::(- 1))], mode='same') (py, px) = np.unravel_index(np.argmax(cc), cc.shape) py2 = ((py - 1) + _find_quadratic_peak(cc[((py - 1):(py + 2), px)])) px2 = ((px - 1) + _find_quadratic_peak(cc[(py, (px - 1):(px + 2))])) dy = (py2 - float((cc.shape[0] // 2))) dx = (px2 - float((cc.shape[1] // 2))) return (dy, dx)<|docstring|>Given a reference image of the sky that is expected to overlap with the current image, attempt to fit for any offset between the sky coordinate system of the current image and that of the reference image. The returned value is designed to be added to the coordinate reference pixel values of self.wcs. This function performs the following steps: 1. The align_with_image() method is called to resample the reference image onto the same coordinate grid as the current image. 2. The two images are then cross-correlated, after zeroing all background values in the images below nsigma standard deviations above the mean. 3. The peak in the auto-correlation image is found and its sub-pixel position is estimated by a simple quadratic interpolation. This position, relative to the center of the auto-correlation image, gives the average position offset between similar features in the two images. Parameters ---------- ref : `~mpdaf.obj.Image` The image of the sky that is to be used as the coordinate reference. The sky coverage of this image should overlap with that of self. Ideally the resolution of this image should be at least as good as the resolution of self. nsigma : float Only values that exceed this many standard deviations above the mean of each image will be used. Returns ------- out : float,float The pixel offsets that would need to be added to the coordinate reference pixel values, crpix2 and crpix1, of self.wcs to make the features in self line up with those in the reference image.<|endoftext|>
20c84b5f48fa5948a045d492c1cffdaae48ed6aa47a30ae2ddf2df8d47bb07ad
def adjust_coordinates(self, ref, nsigma=1.0, inplace=False): 'Given a reference image of the sky that is expected to\n overlap with the current image, attempt to fit for any offset\n between the sky coordinate system of the current image and\n that of the reference image. Apply this offset to the\n coordinates of the current image, to bring it into line with\n the reference image.\n\n This function calls self.estimate_coordinate_offset() to\n fit for the offset between the coordinate systems of the\n two images, then adjusts the coordinate reference pixel of\n the current image to bring its coordinates into line with\n those of the reference image.\n\n Parameters\n ----------\n ref : `~mpdaf.obj.Image`\n The image of the sky that is to be used as the coordinate\n reference. The sky coverage of this image should overlap\n with that of self. Ideally the resolution of this image\n should be at least as good as the resolution of self.\n nsigma : float\n Only values that exceed this many standard deviations\n above the mean of each image will be used.\n inplace : bool\n If False, return a shifted copy of the image (the default).\n If True, shift the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n A version of self in which the sky coordinates have been\n shifted to match those of the reference image.\n\n ' out = (self if inplace else self.copy()) (dy, dx) = out.estimate_coordinate_offset(ref, nsigma) out.wcs.set_crpix1((out.wcs.get_crpix1() + dx)) out.wcs.set_crpix2((out.wcs.get_crpix2() + dy)) units = (u.arcsec if (self.wcs.unit is u.deg) else self.wcs.unit) offset = (np.array([(- dy), (- dx)]) * self.wcs.get_axis_increments(units)) self._logger.info(('Shifted the coordinates by dy=%.3g dx=%.3g %s' % (offset[0], offset[1], units))) return out
Given a reference image of the sky that is expected to overlap with the current image, attempt to fit for any offset between the sky coordinate system of the current image and that of the reference image. Apply this offset to the coordinates of the current image, to bring it into line with the reference image. This function calls self.estimate_coordinate_offset() to fit for the offset between the coordinate systems of the two images, then adjusts the coordinate reference pixel of the current image to bring its coordinates into line with those of the reference image. Parameters ---------- ref : `~mpdaf.obj.Image` The image of the sky that is to be used as the coordinate reference. The sky coverage of this image should overlap with that of self. Ideally the resolution of this image should be at least as good as the resolution of self. nsigma : float Only values that exceed this many standard deviations above the mean of each image will be used. inplace : bool If False, return a shifted copy of the image (the default). If True, shift the original image in-place, and return that. Returns ------- out : `~mpdaf.obj.Image` A version of self in which the sky coordinates have been shifted to match those of the reference image.
lib/mpdaf/obj/image.py
adjust_coordinates
musevlt/mpdaf
4
python
def adjust_coordinates(self, ref, nsigma=1.0, inplace=False): 'Given a reference image of the sky that is expected to\n overlap with the current image, attempt to fit for any offset\n between the sky coordinate system of the current image and\n that of the reference image. Apply this offset to the\n coordinates of the current image, to bring it into line with\n the reference image.\n\n This function calls self.estimate_coordinate_offset() to\n fit for the offset between the coordinate systems of the\n two images, then adjusts the coordinate reference pixel of\n the current image to bring its coordinates into line with\n those of the reference image.\n\n Parameters\n ----------\n ref : `~mpdaf.obj.Image`\n The image of the sky that is to be used as the coordinate\n reference. The sky coverage of this image should overlap\n with that of self. Ideally the resolution of this image\n should be at least as good as the resolution of self.\n nsigma : float\n Only values that exceed this many standard deviations\n above the mean of each image will be used.\n inplace : bool\n If False, return a shifted copy of the image (the default).\n If True, shift the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n A version of self in which the sky coordinates have been\n shifted to match those of the reference image.\n\n ' out = (self if inplace else self.copy()) (dy, dx) = out.estimate_coordinate_offset(ref, nsigma) out.wcs.set_crpix1((out.wcs.get_crpix1() + dx)) out.wcs.set_crpix2((out.wcs.get_crpix2() + dy)) units = (u.arcsec if (self.wcs.unit is u.deg) else self.wcs.unit) offset = (np.array([(- dy), (- dx)]) * self.wcs.get_axis_increments(units)) self._logger.info(('Shifted the coordinates by dy=%.3g dx=%.3g %s' % (offset[0], offset[1], units))) return out
def adjust_coordinates(self, ref, nsigma=1.0, inplace=False): 'Given a reference image of the sky that is expected to\n overlap with the current image, attempt to fit for any offset\n between the sky coordinate system of the current image and\n that of the reference image. Apply this offset to the\n coordinates of the current image, to bring it into line with\n the reference image.\n\n This function calls self.estimate_coordinate_offset() to\n fit for the offset between the coordinate systems of the\n two images, then adjusts the coordinate reference pixel of\n the current image to bring its coordinates into line with\n those of the reference image.\n\n Parameters\n ----------\n ref : `~mpdaf.obj.Image`\n The image of the sky that is to be used as the coordinate\n reference. The sky coverage of this image should overlap\n with that of self. Ideally the resolution of this image\n should be at least as good as the resolution of self.\n nsigma : float\n Only values that exceed this many standard deviations\n above the mean of each image will be used.\n inplace : bool\n If False, return a shifted copy of the image (the default).\n If True, shift the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n A version of self in which the sky coordinates have been\n shifted to match those of the reference image.\n\n ' out = (self if inplace else self.copy()) (dy, dx) = out.estimate_coordinate_offset(ref, nsigma) out.wcs.set_crpix1((out.wcs.get_crpix1() + dx)) out.wcs.set_crpix2((out.wcs.get_crpix2() + dy)) units = (u.arcsec if (self.wcs.unit is u.deg) else self.wcs.unit) offset = (np.array([(- dy), (- dx)]) * self.wcs.get_axis_increments(units)) self._logger.info(('Shifted the coordinates by dy=%.3g dx=%.3g %s' % (offset[0], offset[1], units))) return out<|docstring|>Given a reference image of the sky that is expected to overlap with the current image, attempt to fit for any offset between the sky coordinate system of the current image and that of the reference image. Apply this offset to the coordinates of the current image, to bring it into line with the reference image. This function calls self.estimate_coordinate_offset() to fit for the offset between the coordinate systems of the two images, then adjusts the coordinate reference pixel of the current image to bring its coordinates into line with those of the reference image. Parameters ---------- ref : `~mpdaf.obj.Image` The image of the sky that is to be used as the coordinate reference. The sky coverage of this image should overlap with that of self. Ideally the resolution of this image should be at least as good as the resolution of self. nsigma : float Only values that exceed this many standard deviations above the mean of each image will be used. inplace : bool If False, return a shifted copy of the image (the default). If True, shift the original image in-place, and return that. Returns ------- out : `~mpdaf.obj.Image` A version of self in which the sky coordinates have been shifted to match those of the reference image.<|endoftext|>
dff07a790efe5376d65a45a28195b7535ebcb14de866365f81957090f3565d12
def gaussian_filter(self, sigma=3, interp='no', inplace=False): "Return an image containing Gaussian filter applied to the current\n image.\n\n Uses `scipy.ndimage.gaussian_filter`.\n\n Parameters\n ----------\n sigma : float\n Standard deviation for Gaussian kernel\n interp : 'no' | 'linear' | 'spline'\n if 'no', data median value replaced masked values.\n if 'linear', linear interpolation of the masked values.\n if 'spline', spline interpolation of the masked values.\n inplace : bool\n If False, return a filtered copy of the image (the default).\n If True, filter the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n " out = (self if inplace else self.copy()) data = out._prepare_data(interp) out._data = ndi.gaussian_filter(data, sigma) if (out._var is not None): out._var = ndi.gaussian_filter(out._var, sigma) return out
Return an image containing Gaussian filter applied to the current image. Uses `scipy.ndimage.gaussian_filter`. Parameters ---------- sigma : float Standard deviation for Gaussian kernel interp : 'no' | 'linear' | 'spline' if 'no', data median value replaced masked values. if 'linear', linear interpolation of the masked values. if 'spline', spline interpolation of the masked values. inplace : bool If False, return a filtered copy of the image (the default). If True, filter the original image in-place, and return that. Returns ------- out : `~mpdaf.obj.Image`
lib/mpdaf/obj/image.py
gaussian_filter
musevlt/mpdaf
4
python
def gaussian_filter(self, sigma=3, interp='no', inplace=False): "Return an image containing Gaussian filter applied to the current\n image.\n\n Uses `scipy.ndimage.gaussian_filter`.\n\n Parameters\n ----------\n sigma : float\n Standard deviation for Gaussian kernel\n interp : 'no' | 'linear' | 'spline'\n if 'no', data median value replaced masked values.\n if 'linear', linear interpolation of the masked values.\n if 'spline', spline interpolation of the masked values.\n inplace : bool\n If False, return a filtered copy of the image (the default).\n If True, filter the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n " out = (self if inplace else self.copy()) data = out._prepare_data(interp) out._data = ndi.gaussian_filter(data, sigma) if (out._var is not None): out._var = ndi.gaussian_filter(out._var, sigma) return out
def gaussian_filter(self, sigma=3, interp='no', inplace=False): "Return an image containing Gaussian filter applied to the current\n image.\n\n Uses `scipy.ndimage.gaussian_filter`.\n\n Parameters\n ----------\n sigma : float\n Standard deviation for Gaussian kernel\n interp : 'no' | 'linear' | 'spline'\n if 'no', data median value replaced masked values.\n if 'linear', linear interpolation of the masked values.\n if 'spline', spline interpolation of the masked values.\n inplace : bool\n If False, return a filtered copy of the image (the default).\n If True, filter the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n " out = (self if inplace else self.copy()) data = out._prepare_data(interp) out._data = ndi.gaussian_filter(data, sigma) if (out._var is not None): out._var = ndi.gaussian_filter(out._var, sigma) return out<|docstring|>Return an image containing Gaussian filter applied to the current image. Uses `scipy.ndimage.gaussian_filter`. Parameters ---------- sigma : float Standard deviation for Gaussian kernel interp : 'no' | 'linear' | 'spline' if 'no', data median value replaced masked values. if 'linear', linear interpolation of the masked values. if 'spline', spline interpolation of the masked values. inplace : bool If False, return a filtered copy of the image (the default). If True, filter the original image in-place, and return that. Returns ------- out : `~mpdaf.obj.Image`<|endoftext|>
f6f39f01f026190207034053ab627db358ceffadd7a0c04a454d62e53939221f
def segment(self, shape=(2, 2), minsize=20, minpts=None, background=20, interp='no', median=None): "Segment the image in a number of smaller images.\n\n Returns a list of images. Uses\n `scipy.ndimage.generate_binary_structure`,\n `scipy.ndimage.grey_dilation`, `scipy.ndimage.measurements.label`, and\n `scipy.ndimage.measurements.find_objects`.\n\n Parameters\n ----------\n shape : (int,int)\n Shape used for connectivity.\n minsize : int\n Minimmum size of the images.\n minpts : int\n Minimmum number of points in the object.\n background : float\n Under this value, flux is considered as background.\n interp : 'no' | 'linear' | 'spline'\n if 'no', data median value replaced masked values.\n if 'linear', linear interpolation of the masked values.\n if 'spline', spline interpolation of the masked values.\n median : (int,int) or None\n If not None (default), size of the window to apply a median filter\n on the image.\n\n Returns\n -------\n out : list of `Image`\n\n " data = self._prepare_data(interp) if (median is not None): data = np.ma.array(ndi.median_filter(data, median), mask=self._mask) expanded = ndi.grey_dilation(data, (minsize, minsize)) expanded[(expanded < background)] = 0 structure = ndi.generate_binary_structure(shape[0], shape[1]) (labels, nlabels) = ndi.measurements.label(expanded, structure) slices = ndi.measurements.find_objects(labels) return [self[slices[i]] for i in range(nlabels) if ((minpts is None) or (len(data[(labels == (i + 1))]) >= minpts))]
Segment the image in a number of smaller images. Returns a list of images. Uses `scipy.ndimage.generate_binary_structure`, `scipy.ndimage.grey_dilation`, `scipy.ndimage.measurements.label`, and `scipy.ndimage.measurements.find_objects`. Parameters ---------- shape : (int,int) Shape used for connectivity. minsize : int Minimmum size of the images. minpts : int Minimmum number of points in the object. background : float Under this value, flux is considered as background. interp : 'no' | 'linear' | 'spline' if 'no', data median value replaced masked values. if 'linear', linear interpolation of the masked values. if 'spline', spline interpolation of the masked values. median : (int,int) or None If not None (default), size of the window to apply a median filter on the image. Returns ------- out : list of `Image`
lib/mpdaf/obj/image.py
segment
musevlt/mpdaf
4
python
def segment(self, shape=(2, 2), minsize=20, minpts=None, background=20, interp='no', median=None): "Segment the image in a number of smaller images.\n\n Returns a list of images. Uses\n `scipy.ndimage.generate_binary_structure`,\n `scipy.ndimage.grey_dilation`, `scipy.ndimage.measurements.label`, and\n `scipy.ndimage.measurements.find_objects`.\n\n Parameters\n ----------\n shape : (int,int)\n Shape used for connectivity.\n minsize : int\n Minimmum size of the images.\n minpts : int\n Minimmum number of points in the object.\n background : float\n Under this value, flux is considered as background.\n interp : 'no' | 'linear' | 'spline'\n if 'no', data median value replaced masked values.\n if 'linear', linear interpolation of the masked values.\n if 'spline', spline interpolation of the masked values.\n median : (int,int) or None\n If not None (default), size of the window to apply a median filter\n on the image.\n\n Returns\n -------\n out : list of `Image`\n\n " data = self._prepare_data(interp) if (median is not None): data = np.ma.array(ndi.median_filter(data, median), mask=self._mask) expanded = ndi.grey_dilation(data, (minsize, minsize)) expanded[(expanded < background)] = 0 structure = ndi.generate_binary_structure(shape[0], shape[1]) (labels, nlabels) = ndi.measurements.label(expanded, structure) slices = ndi.measurements.find_objects(labels) return [self[slices[i]] for i in range(nlabels) if ((minpts is None) or (len(data[(labels == (i + 1))]) >= minpts))]
def segment(self, shape=(2, 2), minsize=20, minpts=None, background=20, interp='no', median=None): "Segment the image in a number of smaller images.\n\n Returns a list of images. Uses\n `scipy.ndimage.generate_binary_structure`,\n `scipy.ndimage.grey_dilation`, `scipy.ndimage.measurements.label`, and\n `scipy.ndimage.measurements.find_objects`.\n\n Parameters\n ----------\n shape : (int,int)\n Shape used for connectivity.\n minsize : int\n Minimmum size of the images.\n minpts : int\n Minimmum number of points in the object.\n background : float\n Under this value, flux is considered as background.\n interp : 'no' | 'linear' | 'spline'\n if 'no', data median value replaced masked values.\n if 'linear', linear interpolation of the masked values.\n if 'spline', spline interpolation of the masked values.\n median : (int,int) or None\n If not None (default), size of the window to apply a median filter\n on the image.\n\n Returns\n -------\n out : list of `Image`\n\n " data = self._prepare_data(interp) if (median is not None): data = np.ma.array(ndi.median_filter(data, median), mask=self._mask) expanded = ndi.grey_dilation(data, (minsize, minsize)) expanded[(expanded < background)] = 0 structure = ndi.generate_binary_structure(shape[0], shape[1]) (labels, nlabels) = ndi.measurements.label(expanded, structure) slices = ndi.measurements.find_objects(labels) return [self[slices[i]] for i in range(nlabels) if ((minpts is None) or (len(data[(labels == (i + 1))]) >= minpts))]<|docstring|>Segment the image in a number of smaller images. Returns a list of images. Uses `scipy.ndimage.generate_binary_structure`, `scipy.ndimage.grey_dilation`, `scipy.ndimage.measurements.label`, and `scipy.ndimage.measurements.find_objects`. Parameters ---------- shape : (int,int) Shape used for connectivity. minsize : int Minimmum size of the images. minpts : int Minimmum number of points in the object. background : float Under this value, flux is considered as background. interp : 'no' | 'linear' | 'spline' if 'no', data median value replaced masked values. if 'linear', linear interpolation of the masked values. if 'spline', spline interpolation of the masked values. median : (int,int) or None If not None (default), size of the window to apply a median filter on the image. Returns ------- out : list of `Image`<|endoftext|>
2a1fd1062280f5f3e95e60be8547cd66bafdac2c11bed39d604ed177341ab53b
def add_gaussian_noise(self, sigma, interp='no'): "Add Gaussian noise to image in place.\n\n Parameters\n ----------\n sigma : float\n Standard deviation.\n interp : 'no' | 'linear' | 'spline'\n if 'no', data median value replaced masked values.\n if 'linear', linear interpolation of the masked values.\n if 'spline', spline interpolation of the masked values.\n " data = self._prepare_data(interp) self._data = np.random.normal(data, sigma) if (self._var is None): self._var = ((np.ones(self.shape) * sigma) * sigma) else: self._var *= (sigma * sigma)
Add Gaussian noise to image in place. Parameters ---------- sigma : float Standard deviation. interp : 'no' | 'linear' | 'spline' if 'no', data median value replaced masked values. if 'linear', linear interpolation of the masked values. if 'spline', spline interpolation of the masked values.
lib/mpdaf/obj/image.py
add_gaussian_noise
musevlt/mpdaf
4
python
def add_gaussian_noise(self, sigma, interp='no'): "Add Gaussian noise to image in place.\n\n Parameters\n ----------\n sigma : float\n Standard deviation.\n interp : 'no' | 'linear' | 'spline'\n if 'no', data median value replaced masked values.\n if 'linear', linear interpolation of the masked values.\n if 'spline', spline interpolation of the masked values.\n " data = self._prepare_data(interp) self._data = np.random.normal(data, sigma) if (self._var is None): self._var = ((np.ones(self.shape) * sigma) * sigma) else: self._var *= (sigma * sigma)
def add_gaussian_noise(self, sigma, interp='no'): "Add Gaussian noise to image in place.\n\n Parameters\n ----------\n sigma : float\n Standard deviation.\n interp : 'no' | 'linear' | 'spline'\n if 'no', data median value replaced masked values.\n if 'linear', linear interpolation of the masked values.\n if 'spline', spline interpolation of the masked values.\n " data = self._prepare_data(interp) self._data = np.random.normal(data, sigma) if (self._var is None): self._var = ((np.ones(self.shape) * sigma) * sigma) else: self._var *= (sigma * sigma)<|docstring|>Add Gaussian noise to image in place. Parameters ---------- sigma : float Standard deviation. interp : 'no' | 'linear' | 'spline' if 'no', data median value replaced masked values. if 'linear', linear interpolation of the masked values. if 'spline', spline interpolation of the masked values.<|endoftext|>
a0d6b11c1b527ff1f524dafd545bd27b00a30604fd2d6575934adba4c72a44bd
def inside(self, coord, unit=u.deg): 'Return True if coord is inside image.\n\n Parameters\n ----------\n coord : (float,float)\n coordinates (y,x).\n unit : `astropy.units.Unit`\n Type of the coordinates (degrees by default)\n\n Returns\n -------\n out : bool\n ' if (unit is not None): pixcrd = self.wcs.sky2pix([coord[0], coord[1]], unit=unit)[0] else: pixcrd = coord if ((pixcrd >= ((- self.wcs.get_step(unit=unit)) / 100)).all() and (pixcrd < (self.shape + (self.wcs.get_step(unit=unit) / 100))).all()): return True else: return False
Return True if coord is inside image. Parameters ---------- coord : (float,float) coordinates (y,x). unit : `astropy.units.Unit` Type of the coordinates (degrees by default) Returns ------- out : bool
lib/mpdaf/obj/image.py
inside
musevlt/mpdaf
4
python
def inside(self, coord, unit=u.deg): 'Return True if coord is inside image.\n\n Parameters\n ----------\n coord : (float,float)\n coordinates (y,x).\n unit : `astropy.units.Unit`\n Type of the coordinates (degrees by default)\n\n Returns\n -------\n out : bool\n ' if (unit is not None): pixcrd = self.wcs.sky2pix([coord[0], coord[1]], unit=unit)[0] else: pixcrd = coord if ((pixcrd >= ((- self.wcs.get_step(unit=unit)) / 100)).all() and (pixcrd < (self.shape + (self.wcs.get_step(unit=unit) / 100))).all()): return True else: return False
def inside(self, coord, unit=u.deg): 'Return True if coord is inside image.\n\n Parameters\n ----------\n coord : (float,float)\n coordinates (y,x).\n unit : `astropy.units.Unit`\n Type of the coordinates (degrees by default)\n\n Returns\n -------\n out : bool\n ' if (unit is not None): pixcrd = self.wcs.sky2pix([coord[0], coord[1]], unit=unit)[0] else: pixcrd = coord if ((pixcrd >= ((- self.wcs.get_step(unit=unit)) / 100)).all() and (pixcrd < (self.shape + (self.wcs.get_step(unit=unit) / 100))).all()): return True else: return False<|docstring|>Return True if coord is inside image. Parameters ---------- coord : (float,float) coordinates (y,x). unit : `astropy.units.Unit` Type of the coordinates (degrees by default) Returns ------- out : bool<|endoftext|>
ee8babfb87dd68c7802ff2c8ff25618aa08c87936258c574d795428e1ada46b1
def convolve(self, other, inplace=False): 'Convolve an Image with a 2D array or another Image, using the\n discrete convolution equation.\n\n This function, which uses the discrete convolution equation, is\n usually slower than Image.fftconvolve(). However it can be faster when\n other.data.size is small, and it always uses much less memory, so it\n is sometimes the only practical choice.\n\n Masked values in self.data and self.var are replaced with zeros before\n the convolution is performed, but they are masked again after the\n convolution.\n\n If self.var exists, the variances are propagated using the equation:\n\n result.var = self.var (*) other**2\n\n where (*) indicates convolution. This equation can be derived by\n applying the usual rules of error-propagation to the discrete\n convolution equation.\n\n The speed of this function scales as O(Nd x No) where\n Nd=self.data.size and No=other.data.size.\n\n Uses `scipy.signal.convolve`.\n\n Parameters\n ----------\n other : Image or numpy.ndarray\n The 2D array with which to convolve the image in self.data.\n This array can be an image of the same size as self, or it\n can be a smaller image, such as a small gaussian to use to\n smooth the larger image.\n\n When ``other`` contains a symmetric filtering function, such\n as a two-dimensional gaussian, the center of the function\n should be placed at the center of pixel:\n\n ``(other.shape - 1) // 2``\n\n If other is an MPDAF Image object, note that only its data\n array is used. Masked values in this array are treated\n as zero. Any variances found in other.var are ignored.\n inplace : bool\n If False (the default), return the results in a new Image.\n If True, record the result in self and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' return self._convolve(signal.convolve, other=other, inplace=inplace)
Convolve an Image with a 2D array or another Image, using the discrete convolution equation. This function, which uses the discrete convolution equation, is usually slower than Image.fftconvolve(). However it can be faster when other.data.size is small, and it always uses much less memory, so it is sometimes the only practical choice. Masked values in self.data and self.var are replaced with zeros before the convolution is performed, but they are masked again after the convolution. If self.var exists, the variances are propagated using the equation: result.var = self.var (*) other**2 where (*) indicates convolution. This equation can be derived by applying the usual rules of error-propagation to the discrete convolution equation. The speed of this function scales as O(Nd x No) where Nd=self.data.size and No=other.data.size. Uses `scipy.signal.convolve`. Parameters ---------- other : Image or numpy.ndarray The 2D array with which to convolve the image in self.data. This array can be an image of the same size as self, or it can be a smaller image, such as a small gaussian to use to smooth the larger image. When ``other`` contains a symmetric filtering function, such as a two-dimensional gaussian, the center of the function should be placed at the center of pixel: ``(other.shape - 1) // 2`` If other is an MPDAF Image object, note that only its data array is used. Masked values in this array are treated as zero. Any variances found in other.var are ignored. inplace : bool If False (the default), return the results in a new Image. If True, record the result in self and return that. Returns ------- out : `~mpdaf.obj.Image`
lib/mpdaf/obj/image.py
convolve
musevlt/mpdaf
4
python
def convolve(self, other, inplace=False): 'Convolve an Image with a 2D array or another Image, using the\n discrete convolution equation.\n\n This function, which uses the discrete convolution equation, is\n usually slower than Image.fftconvolve(). However it can be faster when\n other.data.size is small, and it always uses much less memory, so it\n is sometimes the only practical choice.\n\n Masked values in self.data and self.var are replaced with zeros before\n the convolution is performed, but they are masked again after the\n convolution.\n\n If self.var exists, the variances are propagated using the equation:\n\n result.var = self.var (*) other**2\n\n where (*) indicates convolution. This equation can be derived by\n applying the usual rules of error-propagation to the discrete\n convolution equation.\n\n The speed of this function scales as O(Nd x No) where\n Nd=self.data.size and No=other.data.size.\n\n Uses `scipy.signal.convolve`.\n\n Parameters\n ----------\n other : Image or numpy.ndarray\n The 2D array with which to convolve the image in self.data.\n This array can be an image of the same size as self, or it\n can be a smaller image, such as a small gaussian to use to\n smooth the larger image.\n\n When ``other`` contains a symmetric filtering function, such\n as a two-dimensional gaussian, the center of the function\n should be placed at the center of pixel:\n\n ``(other.shape - 1) // 2``\n\n If other is an MPDAF Image object, note that only its data\n array is used. Masked values in this array are treated\n as zero. Any variances found in other.var are ignored.\n inplace : bool\n If False (the default), return the results in a new Image.\n If True, record the result in self and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' return self._convolve(signal.convolve, other=other, inplace=inplace)
def convolve(self, other, inplace=False): 'Convolve an Image with a 2D array or another Image, using the\n discrete convolution equation.\n\n This function, which uses the discrete convolution equation, is\n usually slower than Image.fftconvolve(). However it can be faster when\n other.data.size is small, and it always uses much less memory, so it\n is sometimes the only practical choice.\n\n Masked values in self.data and self.var are replaced with zeros before\n the convolution is performed, but they are masked again after the\n convolution.\n\n If self.var exists, the variances are propagated using the equation:\n\n result.var = self.var (*) other**2\n\n where (*) indicates convolution. This equation can be derived by\n applying the usual rules of error-propagation to the discrete\n convolution equation.\n\n The speed of this function scales as O(Nd x No) where\n Nd=self.data.size and No=other.data.size.\n\n Uses `scipy.signal.convolve`.\n\n Parameters\n ----------\n other : Image or numpy.ndarray\n The 2D array with which to convolve the image in self.data.\n This array can be an image of the same size as self, or it\n can be a smaller image, such as a small gaussian to use to\n smooth the larger image.\n\n When ``other`` contains a symmetric filtering function, such\n as a two-dimensional gaussian, the center of the function\n should be placed at the center of pixel:\n\n ``(other.shape - 1) // 2``\n\n If other is an MPDAF Image object, note that only its data\n array is used. Masked values in this array are treated\n as zero. Any variances found in other.var are ignored.\n inplace : bool\n If False (the default), return the results in a new Image.\n If True, record the result in self and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' return self._convolve(signal.convolve, other=other, inplace=inplace)<|docstring|>Convolve an Image with a 2D array or another Image, using the discrete convolution equation. This function, which uses the discrete convolution equation, is usually slower than Image.fftconvolve(). However it can be faster when other.data.size is small, and it always uses much less memory, so it is sometimes the only practical choice. Masked values in self.data and self.var are replaced with zeros before the convolution is performed, but they are masked again after the convolution. If self.var exists, the variances are propagated using the equation: result.var = self.var (*) other**2 where (*) indicates convolution. This equation can be derived by applying the usual rules of error-propagation to the discrete convolution equation. The speed of this function scales as O(Nd x No) where Nd=self.data.size and No=other.data.size. Uses `scipy.signal.convolve`. Parameters ---------- other : Image or numpy.ndarray The 2D array with which to convolve the image in self.data. This array can be an image of the same size as self, or it can be a smaller image, such as a small gaussian to use to smooth the larger image. When ``other`` contains a symmetric filtering function, such as a two-dimensional gaussian, the center of the function should be placed at the center of pixel: ``(other.shape - 1) // 2`` If other is an MPDAF Image object, note that only its data array is used. Masked values in this array are treated as zero. Any variances found in other.var are ignored. inplace : bool If False (the default), return the results in a new Image. If True, record the result in self and return that. Returns ------- out : `~mpdaf.obj.Image`<|endoftext|>
17ae3c73165da0fa9d2e19e6661291785d21f4b7beeed874ea38af2a8f385436
def fftconvolve(self, other, inplace=False): 'Convolve an Image with a 2D array or another Image, using the\n Fourier convolution theorem.\n\n This function, which performs the convolution by multiplying the\n Fourier transforms of the two images, is usually much faster than\n Image.convolve(), except when other.data.size is small. However it\n uses much more memory, so Image.convolve() is sometimes a better\n choice.\n\n Masked values in self.data and self.var are replaced with zeros before\n the convolution is performed, but they are masked again after the\n convolution.\n\n If self.var exists, the variances are propagated using the equation:\n\n result.var = self.var (*) other**2\n\n where (*) indicates convolution. This equation can be derived by\n applying the usual rules of error-propagation to the discrete\n convolution equation.\n\n The speed of this function scales as O(Nd x log(Nd)) where\n Nd=self.data.size. It temporarily allocates a pair of arrays that\n have the sum of the shapes of self.shape and other.shape, rounded up\n to a power of two along each axis. This can involve a lot of memory\n being allocated. For this reason, when other.shape is small,\n Image.convolve() may be more efficient than Image.fftconvolve().\n\n Uses `scipy.signal.fftconvolve`.\n\n Parameters\n ----------\n other : Image or numpy.ndarray\n The 2D array with which to convolve the image in self.data. This\n array can be an image of the same size as self, or it can be a\n smaller image, such as a small 2D gaussian to use to smooth the\n larger image.\n\n When ``other`` contains a symmetric filtering function, such as a\n two-dimensional gaussian, the center of the function should be\n placed at the center of pixel:\n\n ``(other.shape - 1) // 2``\n\n If other is an MPDAF Image object, note that only its data array\n is used. Masked values in this array are treated as zero. Any\n variances found in other.var are ignored.\n inplace : bool\n If False (the default), return the results in a new Image.\n If True, record the result in self and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' return self._convolve(signal.fftconvolve, other=other, inplace=inplace)
Convolve an Image with a 2D array or another Image, using the Fourier convolution theorem. This function, which performs the convolution by multiplying the Fourier transforms of the two images, is usually much faster than Image.convolve(), except when other.data.size is small. However it uses much more memory, so Image.convolve() is sometimes a better choice. Masked values in self.data and self.var are replaced with zeros before the convolution is performed, but they are masked again after the convolution. If self.var exists, the variances are propagated using the equation: result.var = self.var (*) other**2 where (*) indicates convolution. This equation can be derived by applying the usual rules of error-propagation to the discrete convolution equation. The speed of this function scales as O(Nd x log(Nd)) where Nd=self.data.size. It temporarily allocates a pair of arrays that have the sum of the shapes of self.shape and other.shape, rounded up to a power of two along each axis. This can involve a lot of memory being allocated. For this reason, when other.shape is small, Image.convolve() may be more efficient than Image.fftconvolve(). Uses `scipy.signal.fftconvolve`. Parameters ---------- other : Image or numpy.ndarray The 2D array with which to convolve the image in self.data. This array can be an image of the same size as self, or it can be a smaller image, such as a small 2D gaussian to use to smooth the larger image. When ``other`` contains a symmetric filtering function, such as a two-dimensional gaussian, the center of the function should be placed at the center of pixel: ``(other.shape - 1) // 2`` If other is an MPDAF Image object, note that only its data array is used. Masked values in this array are treated as zero. Any variances found in other.var are ignored. inplace : bool If False (the default), return the results in a new Image. If True, record the result in self and return that. Returns ------- out : `~mpdaf.obj.Image`
lib/mpdaf/obj/image.py
fftconvolve
musevlt/mpdaf
4
python
def fftconvolve(self, other, inplace=False): 'Convolve an Image with a 2D array or another Image, using the\n Fourier convolution theorem.\n\n This function, which performs the convolution by multiplying the\n Fourier transforms of the two images, is usually much faster than\n Image.convolve(), except when other.data.size is small. However it\n uses much more memory, so Image.convolve() is sometimes a better\n choice.\n\n Masked values in self.data and self.var are replaced with zeros before\n the convolution is performed, but they are masked again after the\n convolution.\n\n If self.var exists, the variances are propagated using the equation:\n\n result.var = self.var (*) other**2\n\n where (*) indicates convolution. This equation can be derived by\n applying the usual rules of error-propagation to the discrete\n convolution equation.\n\n The speed of this function scales as O(Nd x log(Nd)) where\n Nd=self.data.size. It temporarily allocates a pair of arrays that\n have the sum of the shapes of self.shape and other.shape, rounded up\n to a power of two along each axis. This can involve a lot of memory\n being allocated. For this reason, when other.shape is small,\n Image.convolve() may be more efficient than Image.fftconvolve().\n\n Uses `scipy.signal.fftconvolve`.\n\n Parameters\n ----------\n other : Image or numpy.ndarray\n The 2D array with which to convolve the image in self.data. This\n array can be an image of the same size as self, or it can be a\n smaller image, such as a small 2D gaussian to use to smooth the\n larger image.\n\n When ``other`` contains a symmetric filtering function, such as a\n two-dimensional gaussian, the center of the function should be\n placed at the center of pixel:\n\n ``(other.shape - 1) // 2``\n\n If other is an MPDAF Image object, note that only its data array\n is used. Masked values in this array are treated as zero. Any\n variances found in other.var are ignored.\n inplace : bool\n If False (the default), return the results in a new Image.\n If True, record the result in self and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' return self._convolve(signal.fftconvolve, other=other, inplace=inplace)
def fftconvolve(self, other, inplace=False): 'Convolve an Image with a 2D array or another Image, using the\n Fourier convolution theorem.\n\n This function, which performs the convolution by multiplying the\n Fourier transforms of the two images, is usually much faster than\n Image.convolve(), except when other.data.size is small. However it\n uses much more memory, so Image.convolve() is sometimes a better\n choice.\n\n Masked values in self.data and self.var are replaced with zeros before\n the convolution is performed, but they are masked again after the\n convolution.\n\n If self.var exists, the variances are propagated using the equation:\n\n result.var = self.var (*) other**2\n\n where (*) indicates convolution. This equation can be derived by\n applying the usual rules of error-propagation to the discrete\n convolution equation.\n\n The speed of this function scales as O(Nd x log(Nd)) where\n Nd=self.data.size. It temporarily allocates a pair of arrays that\n have the sum of the shapes of self.shape and other.shape, rounded up\n to a power of two along each axis. This can involve a lot of memory\n being allocated. For this reason, when other.shape is small,\n Image.convolve() may be more efficient than Image.fftconvolve().\n\n Uses `scipy.signal.fftconvolve`.\n\n Parameters\n ----------\n other : Image or numpy.ndarray\n The 2D array with which to convolve the image in self.data. This\n array can be an image of the same size as self, or it can be a\n smaller image, such as a small 2D gaussian to use to smooth the\n larger image.\n\n When ``other`` contains a symmetric filtering function, such as a\n two-dimensional gaussian, the center of the function should be\n placed at the center of pixel:\n\n ``(other.shape - 1) // 2``\n\n If other is an MPDAF Image object, note that only its data array\n is used. Masked values in this array are treated as zero. Any\n variances found in other.var are ignored.\n inplace : bool\n If False (the default), return the results in a new Image.\n If True, record the result in self and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' return self._convolve(signal.fftconvolve, other=other, inplace=inplace)<|docstring|>Convolve an Image with a 2D array or another Image, using the Fourier convolution theorem. This function, which performs the convolution by multiplying the Fourier transforms of the two images, is usually much faster than Image.convolve(), except when other.data.size is small. However it uses much more memory, so Image.convolve() is sometimes a better choice. Masked values in self.data and self.var are replaced with zeros before the convolution is performed, but they are masked again after the convolution. If self.var exists, the variances are propagated using the equation: result.var = self.var (*) other**2 where (*) indicates convolution. This equation can be derived by applying the usual rules of error-propagation to the discrete convolution equation. The speed of this function scales as O(Nd x log(Nd)) where Nd=self.data.size. It temporarily allocates a pair of arrays that have the sum of the shapes of self.shape and other.shape, rounded up to a power of two along each axis. This can involve a lot of memory being allocated. For this reason, when other.shape is small, Image.convolve() may be more efficient than Image.fftconvolve(). Uses `scipy.signal.fftconvolve`. Parameters ---------- other : Image or numpy.ndarray The 2D array with which to convolve the image in self.data. This array can be an image of the same size as self, or it can be a smaller image, such as a small 2D gaussian to use to smooth the larger image. When ``other`` contains a symmetric filtering function, such as a two-dimensional gaussian, the center of the function should be placed at the center of pixel: ``(other.shape - 1) // 2`` If other is an MPDAF Image object, note that only its data array is used. Masked values in this array are treated as zero. Any variances found in other.var are ignored. inplace : bool If False (the default), return the results in a new Image. If True, record the result in self and return that. Returns ------- out : `~mpdaf.obj.Image`<|endoftext|>
944028d1c24fc555c4876cea54f910ca39b041ac09047b5da4893989122608c9
def fftconvolve_gauss(self, center=None, flux=1.0, fwhm=(1.0, 1.0), peak=False, rot=0.0, factor=1, unit_center=u.deg, unit_fwhm=u.arcsec, inplace=False): 'Return the convolution of the image with a 2D gaussian.\n\n Parameters\n ----------\n center : (float,float)\n Gaussian center (y_peak, x_peak). If None the center of the image\n is used. The unit is given by the unit_center parameter (degrees\n by default).\n flux : float\n Integrated gaussian flux or gaussian peak value if peak is True.\n fwhm : (float,float)\n Gaussian fwhm (fwhm_y,fwhm_x). The unit is given by the unit_fwhm\n parameter (arcseconds by default).\n peak : bool\n If true, flux contains a gaussian peak value.\n rot : float\n Angle position in degree.\n factor : int\n If factor<=1, gaussian value is computed in the center of each\n pixel. If factor>1, for each pixel, gaussian value is the sum of\n the gaussian values on the factor*factor pixels divided by the\n pixel area.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_fwhm : `astropy.units.Unit`\n FWHM unit. Arcseconds by default (use None for radius in pixels)\n inplace : bool\n If False, return a convolved copy of the image (default value).\n If True, convolve the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' ima = gauss_image(self.shape, wcs=self.wcs, center=center, flux=flux, fwhm=fwhm, peak=peak, rot=rot, factor=factor, gauss=None, unit_center=unit_center, unit_fwhm=unit_fwhm, cont=0, unit=self.unit) ima.norm(typ='sum') return self.fftconvolve(ima, inplace=inplace)
Return the convolution of the image with a 2D gaussian. Parameters ---------- center : (float,float) Gaussian center (y_peak, x_peak). If None the center of the image is used. The unit is given by the unit_center parameter (degrees by default). flux : float Integrated gaussian flux or gaussian peak value if peak is True. fwhm : (float,float) Gaussian fwhm (fwhm_y,fwhm_x). The unit is given by the unit_fwhm parameter (arcseconds by default). peak : bool If true, flux contains a gaussian peak value. rot : float Angle position in degree. factor : int If factor<=1, gaussian value is computed in the center of each pixel. If factor>1, for each pixel, gaussian value is the sum of the gaussian values on the factor*factor pixels divided by the pixel area. unit_center : `astropy.units.Unit` type of the center and position coordinates. Degrees by default (use None for coordinates in pixels). unit_fwhm : `astropy.units.Unit` FWHM unit. Arcseconds by default (use None for radius in pixels) inplace : bool If False, return a convolved copy of the image (default value). If True, convolve the original image in-place, and return that. Returns ------- out : `~mpdaf.obj.Image`
lib/mpdaf/obj/image.py
fftconvolve_gauss
musevlt/mpdaf
4
python
def fftconvolve_gauss(self, center=None, flux=1.0, fwhm=(1.0, 1.0), peak=False, rot=0.0, factor=1, unit_center=u.deg, unit_fwhm=u.arcsec, inplace=False): 'Return the convolution of the image with a 2D gaussian.\n\n Parameters\n ----------\n center : (float,float)\n Gaussian center (y_peak, x_peak). If None the center of the image\n is used. The unit is given by the unit_center parameter (degrees\n by default).\n flux : float\n Integrated gaussian flux or gaussian peak value if peak is True.\n fwhm : (float,float)\n Gaussian fwhm (fwhm_y,fwhm_x). The unit is given by the unit_fwhm\n parameter (arcseconds by default).\n peak : bool\n If true, flux contains a gaussian peak value.\n rot : float\n Angle position in degree.\n factor : int\n If factor<=1, gaussian value is computed in the center of each\n pixel. If factor>1, for each pixel, gaussian value is the sum of\n the gaussian values on the factor*factor pixels divided by the\n pixel area.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_fwhm : `astropy.units.Unit`\n FWHM unit. Arcseconds by default (use None for radius in pixels)\n inplace : bool\n If False, return a convolved copy of the image (default value).\n If True, convolve the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' ima = gauss_image(self.shape, wcs=self.wcs, center=center, flux=flux, fwhm=fwhm, peak=peak, rot=rot, factor=factor, gauss=None, unit_center=unit_center, unit_fwhm=unit_fwhm, cont=0, unit=self.unit) ima.norm(typ='sum') return self.fftconvolve(ima, inplace=inplace)
def fftconvolve_gauss(self, center=None, flux=1.0, fwhm=(1.0, 1.0), peak=False, rot=0.0, factor=1, unit_center=u.deg, unit_fwhm=u.arcsec, inplace=False): 'Return the convolution of the image with a 2D gaussian.\n\n Parameters\n ----------\n center : (float,float)\n Gaussian center (y_peak, x_peak). If None the center of the image\n is used. The unit is given by the unit_center parameter (degrees\n by default).\n flux : float\n Integrated gaussian flux or gaussian peak value if peak is True.\n fwhm : (float,float)\n Gaussian fwhm (fwhm_y,fwhm_x). The unit is given by the unit_fwhm\n parameter (arcseconds by default).\n peak : bool\n If true, flux contains a gaussian peak value.\n rot : float\n Angle position in degree.\n factor : int\n If factor<=1, gaussian value is computed in the center of each\n pixel. If factor>1, for each pixel, gaussian value is the sum of\n the gaussian values on the factor*factor pixels divided by the\n pixel area.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_fwhm : `astropy.units.Unit`\n FWHM unit. Arcseconds by default (use None for radius in pixels)\n inplace : bool\n If False, return a convolved copy of the image (default value).\n If True, convolve the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' ima = gauss_image(self.shape, wcs=self.wcs, center=center, flux=flux, fwhm=fwhm, peak=peak, rot=rot, factor=factor, gauss=None, unit_center=unit_center, unit_fwhm=unit_fwhm, cont=0, unit=self.unit) ima.norm(typ='sum') return self.fftconvolve(ima, inplace=inplace)<|docstring|>Return the convolution of the image with a 2D gaussian. Parameters ---------- center : (float,float) Gaussian center (y_peak, x_peak). If None the center of the image is used. The unit is given by the unit_center parameter (degrees by default). flux : float Integrated gaussian flux or gaussian peak value if peak is True. fwhm : (float,float) Gaussian fwhm (fwhm_y,fwhm_x). The unit is given by the unit_fwhm parameter (arcseconds by default). peak : bool If true, flux contains a gaussian peak value. rot : float Angle position in degree. factor : int If factor<=1, gaussian value is computed in the center of each pixel. If factor>1, for each pixel, gaussian value is the sum of the gaussian values on the factor*factor pixels divided by the pixel area. unit_center : `astropy.units.Unit` type of the center and position coordinates. Degrees by default (use None for coordinates in pixels). unit_fwhm : `astropy.units.Unit` FWHM unit. Arcseconds by default (use None for radius in pixels) inplace : bool If False, return a convolved copy of the image (default value). If True, convolve the original image in-place, and return that. Returns ------- out : `~mpdaf.obj.Image`<|endoftext|>
f415674fda1b94025de92bc7ff58be311d836fe031c990dc7bc891b56c358a24
def fftconvolve_moffat(self, center=None, flux=1.0, a=1.0, q=1.0, n=2, peak=False, rot=0.0, factor=1, unit_center=u.deg, unit_a=u.arcsec, inplace=False): 'Return the convolution of the image with a 2D moffat.\n\n Parameters\n ----------\n center : (float,float)\n Gaussian center (y_peak, x_peak). If None the center of the image\n is used. The unit is given by the unit_center parameter (degrees\n by default).\n flux : float\n Integrated gaussian flux or gaussian peak value if peak is True.\n a : float\n Half width at half maximum of the image in the absence of\n atmospheric scattering. 1 by default. The unit is given by the\n unit_a parameter (arcseconds by default).\n q : float\n Axis ratio, 1 by default.\n n : int\n Atmospheric scattering coefficient. 2 by default.\n rot : float\n Angle position in degree.\n factor : int\n If factor<=1, moffat value is computed in the center of each pixel.\n If factor>1, for each pixel, moffat value is the sum\n of the moffat values on the factor*factor pixels\n divided by the pixel area.\n peak : bool\n If true, flux contains a gaussian peak value.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_a : `astropy.units.Unit`\n a unit. Arcseconds by default (use None for radius in pixels)\n inplace : bool\n If False, return a convolved copy of the image (default value).\n If True, convolve the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' fwhmy = (a * (2 * np.sqrt(((2 ** (1.0 / n)) - 1.0)))) fwhmx = (fwhmy / q) ima = moffat_image(self.shape, wcs=self.wcs, factor=factor, center=center, flux=flux, fwhm=(fwhmy, fwhmx), n=n, rot=rot, peak=peak, unit_center=unit_center, unit_fwhm=unit_a, unit=self.unit) ima.norm(typ='sum') return self.fftconvolve(ima, inplace=inplace)
Return the convolution of the image with a 2D moffat. Parameters ---------- center : (float,float) Gaussian center (y_peak, x_peak). If None the center of the image is used. The unit is given by the unit_center parameter (degrees by default). flux : float Integrated gaussian flux or gaussian peak value if peak is True. a : float Half width at half maximum of the image in the absence of atmospheric scattering. 1 by default. The unit is given by the unit_a parameter (arcseconds by default). q : float Axis ratio, 1 by default. n : int Atmospheric scattering coefficient. 2 by default. rot : float Angle position in degree. factor : int If factor<=1, moffat value is computed in the center of each pixel. If factor>1, for each pixel, moffat value is the sum of the moffat values on the factor*factor pixels divided by the pixel area. peak : bool If true, flux contains a gaussian peak value. unit_center : `astropy.units.Unit` type of the center and position coordinates. Degrees by default (use None for coordinates in pixels). unit_a : `astropy.units.Unit` a unit. Arcseconds by default (use None for radius in pixels) inplace : bool If False, return a convolved copy of the image (default value). If True, convolve the original image in-place, and return that. Returns ------- out : `~mpdaf.obj.Image`
lib/mpdaf/obj/image.py
fftconvolve_moffat
musevlt/mpdaf
4
python
def fftconvolve_moffat(self, center=None, flux=1.0, a=1.0, q=1.0, n=2, peak=False, rot=0.0, factor=1, unit_center=u.deg, unit_a=u.arcsec, inplace=False): 'Return the convolution of the image with a 2D moffat.\n\n Parameters\n ----------\n center : (float,float)\n Gaussian center (y_peak, x_peak). If None the center of the image\n is used. The unit is given by the unit_center parameter (degrees\n by default).\n flux : float\n Integrated gaussian flux or gaussian peak value if peak is True.\n a : float\n Half width at half maximum of the image in the absence of\n atmospheric scattering. 1 by default. The unit is given by the\n unit_a parameter (arcseconds by default).\n q : float\n Axis ratio, 1 by default.\n n : int\n Atmospheric scattering coefficient. 2 by default.\n rot : float\n Angle position in degree.\n factor : int\n If factor<=1, moffat value is computed in the center of each pixel.\n If factor>1, for each pixel, moffat value is the sum\n of the moffat values on the factor*factor pixels\n divided by the pixel area.\n peak : bool\n If true, flux contains a gaussian peak value.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_a : `astropy.units.Unit`\n a unit. Arcseconds by default (use None for radius in pixels)\n inplace : bool\n If False, return a convolved copy of the image (default value).\n If True, convolve the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' fwhmy = (a * (2 * np.sqrt(((2 ** (1.0 / n)) - 1.0)))) fwhmx = (fwhmy / q) ima = moffat_image(self.shape, wcs=self.wcs, factor=factor, center=center, flux=flux, fwhm=(fwhmy, fwhmx), n=n, rot=rot, peak=peak, unit_center=unit_center, unit_fwhm=unit_a, unit=self.unit) ima.norm(typ='sum') return self.fftconvolve(ima, inplace=inplace)
def fftconvolve_moffat(self, center=None, flux=1.0, a=1.0, q=1.0, n=2, peak=False, rot=0.0, factor=1, unit_center=u.deg, unit_a=u.arcsec, inplace=False): 'Return the convolution of the image with a 2D moffat.\n\n Parameters\n ----------\n center : (float,float)\n Gaussian center (y_peak, x_peak). If None the center of the image\n is used. The unit is given by the unit_center parameter (degrees\n by default).\n flux : float\n Integrated gaussian flux or gaussian peak value if peak is True.\n a : float\n Half width at half maximum of the image in the absence of\n atmospheric scattering. 1 by default. The unit is given by the\n unit_a parameter (arcseconds by default).\n q : float\n Axis ratio, 1 by default.\n n : int\n Atmospheric scattering coefficient. 2 by default.\n rot : float\n Angle position in degree.\n factor : int\n If factor<=1, moffat value is computed in the center of each pixel.\n If factor>1, for each pixel, moffat value is the sum\n of the moffat values on the factor*factor pixels\n divided by the pixel area.\n peak : bool\n If true, flux contains a gaussian peak value.\n unit_center : `astropy.units.Unit`\n type of the center and position coordinates.\n Degrees by default (use None for coordinates in pixels).\n unit_a : `astropy.units.Unit`\n a unit. Arcseconds by default (use None for radius in pixels)\n inplace : bool\n If False, return a convolved copy of the image (default value).\n If True, convolve the original image in-place, and return that.\n\n Returns\n -------\n out : `~mpdaf.obj.Image`\n\n ' fwhmy = (a * (2 * np.sqrt(((2 ** (1.0 / n)) - 1.0)))) fwhmx = (fwhmy / q) ima = moffat_image(self.shape, wcs=self.wcs, factor=factor, center=center, flux=flux, fwhm=(fwhmy, fwhmx), n=n, rot=rot, peak=peak, unit_center=unit_center, unit_fwhm=unit_a, unit=self.unit) ima.norm(typ='sum') return self.fftconvolve(ima, inplace=inplace)<|docstring|>Return the convolution of the image with a 2D moffat. Parameters ---------- center : (float,float) Gaussian center (y_peak, x_peak). If None the center of the image is used. The unit is given by the unit_center parameter (degrees by default). flux : float Integrated gaussian flux or gaussian peak value if peak is True. a : float Half width at half maximum of the image in the absence of atmospheric scattering. 1 by default. The unit is given by the unit_a parameter (arcseconds by default). q : float Axis ratio, 1 by default. n : int Atmospheric scattering coefficient. 2 by default. rot : float Angle position in degree. factor : int If factor<=1, moffat value is computed in the center of each pixel. If factor>1, for each pixel, moffat value is the sum of the moffat values on the factor*factor pixels divided by the pixel area. peak : bool If true, flux contains a gaussian peak value. unit_center : `astropy.units.Unit` type of the center and position coordinates. Degrees by default (use None for coordinates in pixels). unit_a : `astropy.units.Unit` a unit. Arcseconds by default (use None for radius in pixels) inplace : bool If False, return a convolved copy of the image (default value). If True, convolve the original image in-place, and return that. Returns ------- out : `~mpdaf.obj.Image`<|endoftext|>
7f4ed1832529a4abb99151f1c15661a3e094fc18b70ad89c73aac97ef763d4a0
def correlate2d(self, other, interp='no'): "Return the cross-correlation of the image with an array/image\n\n Uses `scipy.signal.correlate2d`.\n\n Parameters\n ----------\n other : 2d-array or Image\n Second Image or 2d-array.\n interp : 'no' | 'linear' | 'spline'\n if 'no', data median value replaced masked values.\n if 'linear', linear interpolation of the masked values.\n if 'spline', spline interpolation of the masked values.\n\n " if (not isinstance(other, DataArray)): data = self._prepare_data(interp) res = self.copy() res._data = signal.correlate2d(data, other, mode='same', boundary='symm') if (res._var is not None): res._var = signal.correlate2d(res._var, other, mode='same', boundary='symm') return res elif (other.ndim == 2): data = self._prepare_data(interp) other_data = other._prepare_data(interp) other_data = UnitMaskedArray(other_data, other.unit, self.unit) res = self.copy() res._data = signal.correlate2d(data, other_data, mode='same') if (res._var is not None): res._var = signal.correlate2d(res._var, other_data, mode='same') return res else: raise IOError('Operation forbidden')
Return the cross-correlation of the image with an array/image Uses `scipy.signal.correlate2d`. Parameters ---------- other : 2d-array or Image Second Image or 2d-array. interp : 'no' | 'linear' | 'spline' if 'no', data median value replaced masked values. if 'linear', linear interpolation of the masked values. if 'spline', spline interpolation of the masked values.
lib/mpdaf/obj/image.py
correlate2d
musevlt/mpdaf
4
python
def correlate2d(self, other, interp='no'): "Return the cross-correlation of the image with an array/image\n\n Uses `scipy.signal.correlate2d`.\n\n Parameters\n ----------\n other : 2d-array or Image\n Second Image or 2d-array.\n interp : 'no' | 'linear' | 'spline'\n if 'no', data median value replaced masked values.\n if 'linear', linear interpolation of the masked values.\n if 'spline', spline interpolation of the masked values.\n\n " if (not isinstance(other, DataArray)): data = self._prepare_data(interp) res = self.copy() res._data = signal.correlate2d(data, other, mode='same', boundary='symm') if (res._var is not None): res._var = signal.correlate2d(res._var, other, mode='same', boundary='symm') return res elif (other.ndim == 2): data = self._prepare_data(interp) other_data = other._prepare_data(interp) other_data = UnitMaskedArray(other_data, other.unit, self.unit) res = self.copy() res._data = signal.correlate2d(data, other_data, mode='same') if (res._var is not None): res._var = signal.correlate2d(res._var, other_data, mode='same') return res else: raise IOError('Operation forbidden')
def correlate2d(self, other, interp='no'): "Return the cross-correlation of the image with an array/image\n\n Uses `scipy.signal.correlate2d`.\n\n Parameters\n ----------\n other : 2d-array or Image\n Second Image or 2d-array.\n interp : 'no' | 'linear' | 'spline'\n if 'no', data median value replaced masked values.\n if 'linear', linear interpolation of the masked values.\n if 'spline', spline interpolation of the masked values.\n\n " if (not isinstance(other, DataArray)): data = self._prepare_data(interp) res = self.copy() res._data = signal.correlate2d(data, other, mode='same', boundary='symm') if (res._var is not None): res._var = signal.correlate2d(res._var, other, mode='same', boundary='symm') return res elif (other.ndim == 2): data = self._prepare_data(interp) other_data = other._prepare_data(interp) other_data = UnitMaskedArray(other_data, other.unit, self.unit) res = self.copy() res._data = signal.correlate2d(data, other_data, mode='same') if (res._var is not None): res._var = signal.correlate2d(res._var, other_data, mode='same') return res else: raise IOError('Operation forbidden')<|docstring|>Return the cross-correlation of the image with an array/image Uses `scipy.signal.correlate2d`. Parameters ---------- other : 2d-array or Image Second Image or 2d-array. interp : 'no' | 'linear' | 'spline' if 'no', data median value replaced masked values. if 'linear', linear interpolation of the masked values. if 'spline', spline interpolation of the masked values.<|endoftext|>
dd54454368849795308652461fd2046296af316f45af2756af45a569ef02aeed
def plot(self, title=None, scale='linear', vmin=None, vmax=None, zscale=False, colorbar=None, var=False, show_xlabel=False, show_ylabel=False, ax=None, unit=u.deg, use_wcs=False, **kwargs): "Plot the image with axes labeled in pixels.\n\n If either axis has just one pixel, plot a line instead of an image.\n\n Colors are assigned to each pixel value as follows. First each\n pixel value, ``pv``, is normalized over the range ``vmin`` to ``vmax``,\n to have a value ``nv``, that goes from 0 to 1, as follows::\n\n nv = (pv - vmin) / (vmax - vmin)\n\n This value is then mapped to another number between 0 and 1 which\n determines a position along the colorbar, and thus the color to give\n the displayed pixel. The mapping from normalized values to colorbar\n position, color, can be chosen using the scale argument, from the\n following options:\n\n - 'linear': ``color = nv``\n - 'log': ``color = log(1000 * nv + 1) / log(1000 + 1)``\n - 'sqrt': ``color = sqrt(nv)``\n - 'arcsinh': ``color = arcsinh(10*nv) / arcsinh(10.0)``\n\n A colorbar can optionally be drawn. If the colorbar argument is given\n the value 'h', then a colorbar is drawn horizontally, above the plot.\n If it is 'v', the colorbar is drawn vertically, to the right of the\n plot.\n\n By default the image is displayed in its own plot. Alternatively\n to make it a subplot of a larger figure, a suitable\n ``matplotlib.axes.Axes`` object can be passed via the ``ax`` argument.\n Note that unless matplotlib interative mode has previously been enabled\n by calling ``matplotlib.pyplot.ion()``, the plot window will not appear\n until the next time that ``matplotlib.pyplot.show()`` is called. So to\n arrange that a new window appears as soon as ``Image.plot()`` is\n called, do the following before the first call to ``Image.plot()``::\n\n import matplotlib.pyplot as plt\n plt.ion()\n\n Parameters\n ----------\n title : str\n An optional title for the figure (None by default).\n scale : 'linear' | 'log' | 'sqrt' | 'arcsinh'\n The stretch function to use mapping pixel values to\n colors (The default is 'linear'). The pixel values are\n first normalized to range from 0 for values <= vmin,\n to 1 for values >= vmax, then the stretch algorithm maps\n these normalized values, nv, to a position p from 0 to 1\n along the colorbar, as follows:\n linear: p = nv\n log: p = log(1000 * nv + 1) / log(1000 + 1)\n sqrt: p = sqrt(nv)\n arcsinh: p = arcsinh(10*nv) / arcsinh(10.0)\n vmin : float\n Pixels that have values <= vmin are given the color\n at the dark end of the color bar. Pixel values between\n vmin and vmax are given colors along the colorbar according\n to the mapping algorithm specified by the scale argument.\n vmax : float\n Pixels that have values >= vmax are given the color\n at the bright end of the color bar. If None, vmax is\n set to the maximum pixel value in the image.\n zscale : bool\n If True, vmin and vmax are automatically computed\n using the IRAF zscale algorithm.\n colorbar : str\n If 'h', a horizontal colorbar is drawn above the image.\n If 'v', a vertical colorbar is drawn to the right of the image.\n If None (the default), no colorbar is drawn.\n var : bool\n If true variance array is shown in place of data array\n ax : matplotlib.axes.Axes\n An optional Axes instance in which to draw the image,\n or None to have one created using ``matplotlib.pyplot.gca()``.\n unit : `astropy.units.Unit`\n The units to use for displaying world coordinates\n (degrees by default). In the interactive plot, when\n the mouse pointer is over a pixel in the image the\n coordinates of the pixel are shown using these units,\n along with the pixel value.\n use_wcs : bool\n If True, use `astropy.visualization.wcsaxes` to get axes\n with world coordinates.\n kwargs : matplotlib.artist.Artist\n Optional extra keyword/value arguments to be passed to\n the ``ax.imshow()`` function.\n\n Returns\n -------\n out : matplotlib AxesImage\n\n " import matplotlib.pyplot as plt cax = None xlabel = 'q (pixel)' ylabel = 'p (pixel)' if (ax is None): if use_wcs: ax = plt.subplot(projection=self.wcs.wcs) xlabel = 'ra' ylabel = 'dec' else: ax = plt.gca() elif use_wcs: self._logger.warning('use_wcs does not work when giving also an axis (ax)') if var: data_plot = self.var else: data_plot = self.data if (self.shape[1] == 1): yaxis = np.arange(self.shape[0], dtype=float) ax.plot(yaxis, data_plot) xlabel = 'p (pixel)' ylabel = self.unit elif (self.shape[0] == 1): xaxis = np.arange(self.shape[1], dtype=float) ax.plot(xaxis, data_plot.T) xlabel = 'q (pixel)' ylabel = self.unit else: norm = get_plot_norm(data_plot, vmin=vmin, vmax=vmax, zscale=zscale, scale=scale) cax = ax.imshow(data_plot, interpolation='nearest', origin='lower', norm=norm, **kwargs) import matplotlib.axes as maxes from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(ax) if (colorbar == 'h'): cax2 = divider.append_axes('top', size='5%', pad=0.2, axes_class=maxes.Axes) cbar = plt.colorbar(cax, cax=cax2, orientation='horizontal') for t in cbar.ax.xaxis.get_major_ticks(): t.tick1On = True t.tick2On = True t.label1On = False t.label2On = True elif (colorbar == 'v'): cax2 = divider.append_axes('right', size='5%', pad=0.05, axes_class=maxes.Axes) plt.colorbar(cax, cax=cax2) self._ax = ax if show_xlabel: ax.set_xlabel(xlabel) if show_ylabel: ax.set_ylabel(ylabel) if (title is not None): ax.set_title(title) ax.format_coord = FormatCoord(self, data_plot) self._unit = unit return cax
Plot the image with axes labeled in pixels. If either axis has just one pixel, plot a line instead of an image. Colors are assigned to each pixel value as follows. First each pixel value, ``pv``, is normalized over the range ``vmin`` to ``vmax``, to have a value ``nv``, that goes from 0 to 1, as follows:: nv = (pv - vmin) / (vmax - vmin) This value is then mapped to another number between 0 and 1 which determines a position along the colorbar, and thus the color to give the displayed pixel. The mapping from normalized values to colorbar position, color, can be chosen using the scale argument, from the following options: - 'linear': ``color = nv`` - 'log': ``color = log(1000 * nv + 1) / log(1000 + 1)`` - 'sqrt': ``color = sqrt(nv)`` - 'arcsinh': ``color = arcsinh(10*nv) / arcsinh(10.0)`` A colorbar can optionally be drawn. If the colorbar argument is given the value 'h', then a colorbar is drawn horizontally, above the plot. If it is 'v', the colorbar is drawn vertically, to the right of the plot. By default the image is displayed in its own plot. Alternatively to make it a subplot of a larger figure, a suitable ``matplotlib.axes.Axes`` object can be passed via the ``ax`` argument. Note that unless matplotlib interative mode has previously been enabled by calling ``matplotlib.pyplot.ion()``, the plot window will not appear until the next time that ``matplotlib.pyplot.show()`` is called. So to arrange that a new window appears as soon as ``Image.plot()`` is called, do the following before the first call to ``Image.plot()``:: import matplotlib.pyplot as plt plt.ion() Parameters ---------- title : str An optional title for the figure (None by default). scale : 'linear' | 'log' | 'sqrt' | 'arcsinh' The stretch function to use mapping pixel values to colors (The default is 'linear'). The pixel values are first normalized to range from 0 for values <= vmin, to 1 for values >= vmax, then the stretch algorithm maps these normalized values, nv, to a position p from 0 to 1 along the colorbar, as follows: linear: p = nv log: p = log(1000 * nv + 1) / log(1000 + 1) sqrt: p = sqrt(nv) arcsinh: p = arcsinh(10*nv) / arcsinh(10.0) vmin : float Pixels that have values <= vmin are given the color at the dark end of the color bar. Pixel values between vmin and vmax are given colors along the colorbar according to the mapping algorithm specified by the scale argument. vmax : float Pixels that have values >= vmax are given the color at the bright end of the color bar. If None, vmax is set to the maximum pixel value in the image. zscale : bool If True, vmin and vmax are automatically computed using the IRAF zscale algorithm. colorbar : str If 'h', a horizontal colorbar is drawn above the image. If 'v', a vertical colorbar is drawn to the right of the image. If None (the default), no colorbar is drawn. var : bool If true variance array is shown in place of data array ax : matplotlib.axes.Axes An optional Axes instance in which to draw the image, or None to have one created using ``matplotlib.pyplot.gca()``. unit : `astropy.units.Unit` The units to use for displaying world coordinates (degrees by default). In the interactive plot, when the mouse pointer is over a pixel in the image the coordinates of the pixel are shown using these units, along with the pixel value. use_wcs : bool If True, use `astropy.visualization.wcsaxes` to get axes with world coordinates. kwargs : matplotlib.artist.Artist Optional extra keyword/value arguments to be passed to the ``ax.imshow()`` function. Returns ------- out : matplotlib AxesImage
lib/mpdaf/obj/image.py
plot
musevlt/mpdaf
4
python
def plot(self, title=None, scale='linear', vmin=None, vmax=None, zscale=False, colorbar=None, var=False, show_xlabel=False, show_ylabel=False, ax=None, unit=u.deg, use_wcs=False, **kwargs): "Plot the image with axes labeled in pixels.\n\n If either axis has just one pixel, plot a line instead of an image.\n\n Colors are assigned to each pixel value as follows. First each\n pixel value, ``pv``, is normalized over the range ``vmin`` to ``vmax``,\n to have a value ``nv``, that goes from 0 to 1, as follows::\n\n nv = (pv - vmin) / (vmax - vmin)\n\n This value is then mapped to another number between 0 and 1 which\n determines a position along the colorbar, and thus the color to give\n the displayed pixel. The mapping from normalized values to colorbar\n position, color, can be chosen using the scale argument, from the\n following options:\n\n - 'linear': ``color = nv``\n - 'log': ``color = log(1000 * nv + 1) / log(1000 + 1)``\n - 'sqrt': ``color = sqrt(nv)``\n - 'arcsinh': ``color = arcsinh(10*nv) / arcsinh(10.0)``\n\n A colorbar can optionally be drawn. If the colorbar argument is given\n the value 'h', then a colorbar is drawn horizontally, above the plot.\n If it is 'v', the colorbar is drawn vertically, to the right of the\n plot.\n\n By default the image is displayed in its own plot. Alternatively\n to make it a subplot of a larger figure, a suitable\n ``matplotlib.axes.Axes`` object can be passed via the ``ax`` argument.\n Note that unless matplotlib interative mode has previously been enabled\n by calling ``matplotlib.pyplot.ion()``, the plot window will not appear\n until the next time that ``matplotlib.pyplot.show()`` is called. So to\n arrange that a new window appears as soon as ``Image.plot()`` is\n called, do the following before the first call to ``Image.plot()``::\n\n import matplotlib.pyplot as plt\n plt.ion()\n\n Parameters\n ----------\n title : str\n An optional title for the figure (None by default).\n scale : 'linear' | 'log' | 'sqrt' | 'arcsinh'\n The stretch function to use mapping pixel values to\n colors (The default is 'linear'). The pixel values are\n first normalized to range from 0 for values <= vmin,\n to 1 for values >= vmax, then the stretch algorithm maps\n these normalized values, nv, to a position p from 0 to 1\n along the colorbar, as follows:\n linear: p = nv\n log: p = log(1000 * nv + 1) / log(1000 + 1)\n sqrt: p = sqrt(nv)\n arcsinh: p = arcsinh(10*nv) / arcsinh(10.0)\n vmin : float\n Pixels that have values <= vmin are given the color\n at the dark end of the color bar. Pixel values between\n vmin and vmax are given colors along the colorbar according\n to the mapping algorithm specified by the scale argument.\n vmax : float\n Pixels that have values >= vmax are given the color\n at the bright end of the color bar. If None, vmax is\n set to the maximum pixel value in the image.\n zscale : bool\n If True, vmin and vmax are automatically computed\n using the IRAF zscale algorithm.\n colorbar : str\n If 'h', a horizontal colorbar is drawn above the image.\n If 'v', a vertical colorbar is drawn to the right of the image.\n If None (the default), no colorbar is drawn.\n var : bool\n If true variance array is shown in place of data array\n ax : matplotlib.axes.Axes\n An optional Axes instance in which to draw the image,\n or None to have one created using ``matplotlib.pyplot.gca()``.\n unit : `astropy.units.Unit`\n The units to use for displaying world coordinates\n (degrees by default). In the interactive plot, when\n the mouse pointer is over a pixel in the image the\n coordinates of the pixel are shown using these units,\n along with the pixel value.\n use_wcs : bool\n If True, use `astropy.visualization.wcsaxes` to get axes\n with world coordinates.\n kwargs : matplotlib.artist.Artist\n Optional extra keyword/value arguments to be passed to\n the ``ax.imshow()`` function.\n\n Returns\n -------\n out : matplotlib AxesImage\n\n " import matplotlib.pyplot as plt cax = None xlabel = 'q (pixel)' ylabel = 'p (pixel)' if (ax is None): if use_wcs: ax = plt.subplot(projection=self.wcs.wcs) xlabel = 'ra' ylabel = 'dec' else: ax = plt.gca() elif use_wcs: self._logger.warning('use_wcs does not work when giving also an axis (ax)') if var: data_plot = self.var else: data_plot = self.data if (self.shape[1] == 1): yaxis = np.arange(self.shape[0], dtype=float) ax.plot(yaxis, data_plot) xlabel = 'p (pixel)' ylabel = self.unit elif (self.shape[0] == 1): xaxis = np.arange(self.shape[1], dtype=float) ax.plot(xaxis, data_plot.T) xlabel = 'q (pixel)' ylabel = self.unit else: norm = get_plot_norm(data_plot, vmin=vmin, vmax=vmax, zscale=zscale, scale=scale) cax = ax.imshow(data_plot, interpolation='nearest', origin='lower', norm=norm, **kwargs) import matplotlib.axes as maxes from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(ax) if (colorbar == 'h'): cax2 = divider.append_axes('top', size='5%', pad=0.2, axes_class=maxes.Axes) cbar = plt.colorbar(cax, cax=cax2, orientation='horizontal') for t in cbar.ax.xaxis.get_major_ticks(): t.tick1On = True t.tick2On = True t.label1On = False t.label2On = True elif (colorbar == 'v'): cax2 = divider.append_axes('right', size='5%', pad=0.05, axes_class=maxes.Axes) plt.colorbar(cax, cax=cax2) self._ax = ax if show_xlabel: ax.set_xlabel(xlabel) if show_ylabel: ax.set_ylabel(ylabel) if (title is not None): ax.set_title(title) ax.format_coord = FormatCoord(self, data_plot) self._unit = unit return cax
def plot(self, title=None, scale='linear', vmin=None, vmax=None, zscale=False, colorbar=None, var=False, show_xlabel=False, show_ylabel=False, ax=None, unit=u.deg, use_wcs=False, **kwargs): "Plot the image with axes labeled in pixels.\n\n If either axis has just one pixel, plot a line instead of an image.\n\n Colors are assigned to each pixel value as follows. First each\n pixel value, ``pv``, is normalized over the range ``vmin`` to ``vmax``,\n to have a value ``nv``, that goes from 0 to 1, as follows::\n\n nv = (pv - vmin) / (vmax - vmin)\n\n This value is then mapped to another number between 0 and 1 which\n determines a position along the colorbar, and thus the color to give\n the displayed pixel. The mapping from normalized values to colorbar\n position, color, can be chosen using the scale argument, from the\n following options:\n\n - 'linear': ``color = nv``\n - 'log': ``color = log(1000 * nv + 1) / log(1000 + 1)``\n - 'sqrt': ``color = sqrt(nv)``\n - 'arcsinh': ``color = arcsinh(10*nv) / arcsinh(10.0)``\n\n A colorbar can optionally be drawn. If the colorbar argument is given\n the value 'h', then a colorbar is drawn horizontally, above the plot.\n If it is 'v', the colorbar is drawn vertically, to the right of the\n plot.\n\n By default the image is displayed in its own plot. Alternatively\n to make it a subplot of a larger figure, a suitable\n ``matplotlib.axes.Axes`` object can be passed via the ``ax`` argument.\n Note that unless matplotlib interative mode has previously been enabled\n by calling ``matplotlib.pyplot.ion()``, the plot window will not appear\n until the next time that ``matplotlib.pyplot.show()`` is called. So to\n arrange that a new window appears as soon as ``Image.plot()`` is\n called, do the following before the first call to ``Image.plot()``::\n\n import matplotlib.pyplot as plt\n plt.ion()\n\n Parameters\n ----------\n title : str\n An optional title for the figure (None by default).\n scale : 'linear' | 'log' | 'sqrt' | 'arcsinh'\n The stretch function to use mapping pixel values to\n colors (The default is 'linear'). The pixel values are\n first normalized to range from 0 for values <= vmin,\n to 1 for values >= vmax, then the stretch algorithm maps\n these normalized values, nv, to a position p from 0 to 1\n along the colorbar, as follows:\n linear: p = nv\n log: p = log(1000 * nv + 1) / log(1000 + 1)\n sqrt: p = sqrt(nv)\n arcsinh: p = arcsinh(10*nv) / arcsinh(10.0)\n vmin : float\n Pixels that have values <= vmin are given the color\n at the dark end of the color bar. Pixel values between\n vmin and vmax are given colors along the colorbar according\n to the mapping algorithm specified by the scale argument.\n vmax : float\n Pixels that have values >= vmax are given the color\n at the bright end of the color bar. If None, vmax is\n set to the maximum pixel value in the image.\n zscale : bool\n If True, vmin and vmax are automatically computed\n using the IRAF zscale algorithm.\n colorbar : str\n If 'h', a horizontal colorbar is drawn above the image.\n If 'v', a vertical colorbar is drawn to the right of the image.\n If None (the default), no colorbar is drawn.\n var : bool\n If true variance array is shown in place of data array\n ax : matplotlib.axes.Axes\n An optional Axes instance in which to draw the image,\n or None to have one created using ``matplotlib.pyplot.gca()``.\n unit : `astropy.units.Unit`\n The units to use for displaying world coordinates\n (degrees by default). In the interactive plot, when\n the mouse pointer is over a pixel in the image the\n coordinates of the pixel are shown using these units,\n along with the pixel value.\n use_wcs : bool\n If True, use `astropy.visualization.wcsaxes` to get axes\n with world coordinates.\n kwargs : matplotlib.artist.Artist\n Optional extra keyword/value arguments to be passed to\n the ``ax.imshow()`` function.\n\n Returns\n -------\n out : matplotlib AxesImage\n\n " import matplotlib.pyplot as plt cax = None xlabel = 'q (pixel)' ylabel = 'p (pixel)' if (ax is None): if use_wcs: ax = plt.subplot(projection=self.wcs.wcs) xlabel = 'ra' ylabel = 'dec' else: ax = plt.gca() elif use_wcs: self._logger.warning('use_wcs does not work when giving also an axis (ax)') if var: data_plot = self.var else: data_plot = self.data if (self.shape[1] == 1): yaxis = np.arange(self.shape[0], dtype=float) ax.plot(yaxis, data_plot) xlabel = 'p (pixel)' ylabel = self.unit elif (self.shape[0] == 1): xaxis = np.arange(self.shape[1], dtype=float) ax.plot(xaxis, data_plot.T) xlabel = 'q (pixel)' ylabel = self.unit else: norm = get_plot_norm(data_plot, vmin=vmin, vmax=vmax, zscale=zscale, scale=scale) cax = ax.imshow(data_plot, interpolation='nearest', origin='lower', norm=norm, **kwargs) import matplotlib.axes as maxes from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(ax) if (colorbar == 'h'): cax2 = divider.append_axes('top', size='5%', pad=0.2, axes_class=maxes.Axes) cbar = plt.colorbar(cax, cax=cax2, orientation='horizontal') for t in cbar.ax.xaxis.get_major_ticks(): t.tick1On = True t.tick2On = True t.label1On = False t.label2On = True elif (colorbar == 'v'): cax2 = divider.append_axes('right', size='5%', pad=0.05, axes_class=maxes.Axes) plt.colorbar(cax, cax=cax2) self._ax = ax if show_xlabel: ax.set_xlabel(xlabel) if show_ylabel: ax.set_ylabel(ylabel) if (title is not None): ax.set_title(title) ax.format_coord = FormatCoord(self, data_plot) self._unit = unit return cax<|docstring|>Plot the image with axes labeled in pixels. If either axis has just one pixel, plot a line instead of an image. Colors are assigned to each pixel value as follows. First each pixel value, ``pv``, is normalized over the range ``vmin`` to ``vmax``, to have a value ``nv``, that goes from 0 to 1, as follows:: nv = (pv - vmin) / (vmax - vmin) This value is then mapped to another number between 0 and 1 which determines a position along the colorbar, and thus the color to give the displayed pixel. The mapping from normalized values to colorbar position, color, can be chosen using the scale argument, from the following options: - 'linear': ``color = nv`` - 'log': ``color = log(1000 * nv + 1) / log(1000 + 1)`` - 'sqrt': ``color = sqrt(nv)`` - 'arcsinh': ``color = arcsinh(10*nv) / arcsinh(10.0)`` A colorbar can optionally be drawn. If the colorbar argument is given the value 'h', then a colorbar is drawn horizontally, above the plot. If it is 'v', the colorbar is drawn vertically, to the right of the plot. By default the image is displayed in its own plot. Alternatively to make it a subplot of a larger figure, a suitable ``matplotlib.axes.Axes`` object can be passed via the ``ax`` argument. Note that unless matplotlib interative mode has previously been enabled by calling ``matplotlib.pyplot.ion()``, the plot window will not appear until the next time that ``matplotlib.pyplot.show()`` is called. So to arrange that a new window appears as soon as ``Image.plot()`` is called, do the following before the first call to ``Image.plot()``:: import matplotlib.pyplot as plt plt.ion() Parameters ---------- title : str An optional title for the figure (None by default). scale : 'linear' | 'log' | 'sqrt' | 'arcsinh' The stretch function to use mapping pixel values to colors (The default is 'linear'). The pixel values are first normalized to range from 0 for values <= vmin, to 1 for values >= vmax, then the stretch algorithm maps these normalized values, nv, to a position p from 0 to 1 along the colorbar, as follows: linear: p = nv log: p = log(1000 * nv + 1) / log(1000 + 1) sqrt: p = sqrt(nv) arcsinh: p = arcsinh(10*nv) / arcsinh(10.0) vmin : float Pixels that have values <= vmin are given the color at the dark end of the color bar. Pixel values between vmin and vmax are given colors along the colorbar according to the mapping algorithm specified by the scale argument. vmax : float Pixels that have values >= vmax are given the color at the bright end of the color bar. If None, vmax is set to the maximum pixel value in the image. zscale : bool If True, vmin and vmax are automatically computed using the IRAF zscale algorithm. colorbar : str If 'h', a horizontal colorbar is drawn above the image. If 'v', a vertical colorbar is drawn to the right of the image. If None (the default), no colorbar is drawn. var : bool If true variance array is shown in place of data array ax : matplotlib.axes.Axes An optional Axes instance in which to draw the image, or None to have one created using ``matplotlib.pyplot.gca()``. unit : `astropy.units.Unit` The units to use for displaying world coordinates (degrees by default). In the interactive plot, when the mouse pointer is over a pixel in the image the coordinates of the pixel are shown using these units, along with the pixel value. use_wcs : bool If True, use `astropy.visualization.wcsaxes` to get axes with world coordinates. kwargs : matplotlib.artist.Artist Optional extra keyword/value arguments to be passed to the ``ax.imshow()`` function. Returns ------- out : matplotlib AxesImage<|endoftext|>
e97dd6f4f6974782d63e2b27fa2bb01706d30966ba59330e1f9be533cf5ae501
def get_spatial_fmax(self, rot=None): 'Return the spatial-frequency band-limits of the image along\n the Y and X axes.\n\n See the documentation of set_spatial_fmax() for an explanation\n of what the band-limits are used for.\n\n If no band limits have been specified yet, this function has the\n side-effect of setting them to the band-limits dictated by the\n sampling interval of the image array. Specifically, an X axis\n with a sampling interval of dx can sample spatial frequencies of\n up to 0.5/dx cycles per unit of dx without aliasing.\n\n Parameters\n ----------\n rot : float or None\n Either None, to request band-limits that pertain to the\n Y and X axes of the current image without any rotation,\n or, if the band-limits pertain to a rotated version of\n the image, the rotation angle of its Y axis westward of north\n (degrees). This is defined such that if image.wcs.get_rot()\n is passed to this function, the band limits for the Y and\n X axes of the current image axes will be returned.\n\n Returns\n -------\n out : numpy.ndarray\n The spatial-frequency band-limits of the image along\n the Y and X axes of the image in cycles per self.wcs.unit.\n\n ' if (rot is None): rot = self.wcs.get_rot() if (self._spflims is None): self.set_spatial_fmax((0.5 / self.get_step()), self.wcs.get_rot()) return self._spflims.get_fmax(rot)
Return the spatial-frequency band-limits of the image along the Y and X axes. See the documentation of set_spatial_fmax() for an explanation of what the band-limits are used for. If no band limits have been specified yet, this function has the side-effect of setting them to the band-limits dictated by the sampling interval of the image array. Specifically, an X axis with a sampling interval of dx can sample spatial frequencies of up to 0.5/dx cycles per unit of dx without aliasing. Parameters ---------- rot : float or None Either None, to request band-limits that pertain to the Y and X axes of the current image without any rotation, or, if the band-limits pertain to a rotated version of the image, the rotation angle of its Y axis westward of north (degrees). This is defined such that if image.wcs.get_rot() is passed to this function, the band limits for the Y and X axes of the current image axes will be returned. Returns ------- out : numpy.ndarray The spatial-frequency band-limits of the image along the Y and X axes of the image in cycles per self.wcs.unit.
lib/mpdaf/obj/image.py
get_spatial_fmax
musevlt/mpdaf
4
python
def get_spatial_fmax(self, rot=None): 'Return the spatial-frequency band-limits of the image along\n the Y and X axes.\n\n See the documentation of set_spatial_fmax() for an explanation\n of what the band-limits are used for.\n\n If no band limits have been specified yet, this function has the\n side-effect of setting them to the band-limits dictated by the\n sampling interval of the image array. Specifically, an X axis\n with a sampling interval of dx can sample spatial frequencies of\n up to 0.5/dx cycles per unit of dx without aliasing.\n\n Parameters\n ----------\n rot : float or None\n Either None, to request band-limits that pertain to the\n Y and X axes of the current image without any rotation,\n or, if the band-limits pertain to a rotated version of\n the image, the rotation angle of its Y axis westward of north\n (degrees). This is defined such that if image.wcs.get_rot()\n is passed to this function, the band limits for the Y and\n X axes of the current image axes will be returned.\n\n Returns\n -------\n out : numpy.ndarray\n The spatial-frequency band-limits of the image along\n the Y and X axes of the image in cycles per self.wcs.unit.\n\n ' if (rot is None): rot = self.wcs.get_rot() if (self._spflims is None): self.set_spatial_fmax((0.5 / self.get_step()), self.wcs.get_rot()) return self._spflims.get_fmax(rot)
def get_spatial_fmax(self, rot=None): 'Return the spatial-frequency band-limits of the image along\n the Y and X axes.\n\n See the documentation of set_spatial_fmax() for an explanation\n of what the band-limits are used for.\n\n If no band limits have been specified yet, this function has the\n side-effect of setting them to the band-limits dictated by the\n sampling interval of the image array. Specifically, an X axis\n with a sampling interval of dx can sample spatial frequencies of\n up to 0.5/dx cycles per unit of dx without aliasing.\n\n Parameters\n ----------\n rot : float or None\n Either None, to request band-limits that pertain to the\n Y and X axes of the current image without any rotation,\n or, if the band-limits pertain to a rotated version of\n the image, the rotation angle of its Y axis westward of north\n (degrees). This is defined such that if image.wcs.get_rot()\n is passed to this function, the band limits for the Y and\n X axes of the current image axes will be returned.\n\n Returns\n -------\n out : numpy.ndarray\n The spatial-frequency band-limits of the image along\n the Y and X axes of the image in cycles per self.wcs.unit.\n\n ' if (rot is None): rot = self.wcs.get_rot() if (self._spflims is None): self.set_spatial_fmax((0.5 / self.get_step()), self.wcs.get_rot()) return self._spflims.get_fmax(rot)<|docstring|>Return the spatial-frequency band-limits of the image along the Y and X axes. See the documentation of set_spatial_fmax() for an explanation of what the band-limits are used for. If no band limits have been specified yet, this function has the side-effect of setting them to the band-limits dictated by the sampling interval of the image array. Specifically, an X axis with a sampling interval of dx can sample spatial frequencies of up to 0.5/dx cycles per unit of dx without aliasing. Parameters ---------- rot : float or None Either None, to request band-limits that pertain to the Y and X axes of the current image without any rotation, or, if the band-limits pertain to a rotated version of the image, the rotation angle of its Y axis westward of north (degrees). This is defined such that if image.wcs.get_rot() is passed to this function, the band limits for the Y and X axes of the current image axes will be returned. Returns ------- out : numpy.ndarray The spatial-frequency band-limits of the image along the Y and X axes of the image in cycles per self.wcs.unit.<|endoftext|>
41ffd62089ee12f572c6522b5f18d7b0c7ad5531a9f79294b35bfbea020f174e
def update_spatial_fmax(self, newfmax, rot=None): 'Update the spatial-frequency band-limits recorded for the\n current image.\n\n See the documentation of set_spatial_fmax() for an explanation\n of what the band-limits are used for.\n\n If either of the new limits is less than an existing\n band-limit, and the rotation angle of the new limits is\n the same as the angle of the recorded limits, then the smaller\n limits replace the originals.\n\n If either of the new limits is smaller than the existing\n limits, but the rotation angle for the new limits differs from\n the recorded limits, then both of the original limits are\n discarded and replaced by the new ones at the specified angle.\n\n Parameters\n ----------\n newfmax : numpy.ndarray\n The frequency limits along the Y and X axes, respectively,\n specified in cycles per the angular unit in self.wcs.unit.\n rot : float or None\n Either None, to specify band-limits that pertain to the Y\n and X axes of the current image without any rotation, or,\n if the band-limits pertain to a rotated version of the\n image, the rotation angle of its Y axis westward of north\n (degrees). This is defined such that if\n image.wcs.get_rot() is passed to this function, the\n band-limit newfmax[0] will be along the Y axis of the\n image and newfmax[1] will be along its X axis.\n\n ' if (rot is None): rot = self.wcs.get_rot() if (self._spflims is None): self.set_spatial_fmax(newfmax, rot) else: oldfmax = self._spflims.get_fmax(rot) if np.any((newfmax < oldfmax)): if np.isclose(rot, self._spflims.rot): newfmax = np.minimum(newfmax, oldfmax) self.set_spatial_fmax(newfmax, rot)
Update the spatial-frequency band-limits recorded for the current image. See the documentation of set_spatial_fmax() for an explanation of what the band-limits are used for. If either of the new limits is less than an existing band-limit, and the rotation angle of the new limits is the same as the angle of the recorded limits, then the smaller limits replace the originals. If either of the new limits is smaller than the existing limits, but the rotation angle for the new limits differs from the recorded limits, then both of the original limits are discarded and replaced by the new ones at the specified angle. Parameters ---------- newfmax : numpy.ndarray The frequency limits along the Y and X axes, respectively, specified in cycles per the angular unit in self.wcs.unit. rot : float or None Either None, to specify band-limits that pertain to the Y and X axes of the current image without any rotation, or, if the band-limits pertain to a rotated version of the image, the rotation angle of its Y axis westward of north (degrees). This is defined such that if image.wcs.get_rot() is passed to this function, the band-limit newfmax[0] will be along the Y axis of the image and newfmax[1] will be along its X axis.
lib/mpdaf/obj/image.py
update_spatial_fmax
musevlt/mpdaf
4
python
def update_spatial_fmax(self, newfmax, rot=None): 'Update the spatial-frequency band-limits recorded for the\n current image.\n\n See the documentation of set_spatial_fmax() for an explanation\n of what the band-limits are used for.\n\n If either of the new limits is less than an existing\n band-limit, and the rotation angle of the new limits is\n the same as the angle of the recorded limits, then the smaller\n limits replace the originals.\n\n If either of the new limits is smaller than the existing\n limits, but the rotation angle for the new limits differs from\n the recorded limits, then both of the original limits are\n discarded and replaced by the new ones at the specified angle.\n\n Parameters\n ----------\n newfmax : numpy.ndarray\n The frequency limits along the Y and X axes, respectively,\n specified in cycles per the angular unit in self.wcs.unit.\n rot : float or None\n Either None, to specify band-limits that pertain to the Y\n and X axes of the current image without any rotation, or,\n if the band-limits pertain to a rotated version of the\n image, the rotation angle of its Y axis westward of north\n (degrees). This is defined such that if\n image.wcs.get_rot() is passed to this function, the\n band-limit newfmax[0] will be along the Y axis of the\n image and newfmax[1] will be along its X axis.\n\n ' if (rot is None): rot = self.wcs.get_rot() if (self._spflims is None): self.set_spatial_fmax(newfmax, rot) else: oldfmax = self._spflims.get_fmax(rot) if np.any((newfmax < oldfmax)): if np.isclose(rot, self._spflims.rot): newfmax = np.minimum(newfmax, oldfmax) self.set_spatial_fmax(newfmax, rot)
def update_spatial_fmax(self, newfmax, rot=None): 'Update the spatial-frequency band-limits recorded for the\n current image.\n\n See the documentation of set_spatial_fmax() for an explanation\n of what the band-limits are used for.\n\n If either of the new limits is less than an existing\n band-limit, and the rotation angle of the new limits is\n the same as the angle of the recorded limits, then the smaller\n limits replace the originals.\n\n If either of the new limits is smaller than the existing\n limits, but the rotation angle for the new limits differs from\n the recorded limits, then both of the original limits are\n discarded and replaced by the new ones at the specified angle.\n\n Parameters\n ----------\n newfmax : numpy.ndarray\n The frequency limits along the Y and X axes, respectively,\n specified in cycles per the angular unit in self.wcs.unit.\n rot : float or None\n Either None, to specify band-limits that pertain to the Y\n and X axes of the current image without any rotation, or,\n if the band-limits pertain to a rotated version of the\n image, the rotation angle of its Y axis westward of north\n (degrees). This is defined such that if\n image.wcs.get_rot() is passed to this function, the\n band-limit newfmax[0] will be along the Y axis of the\n image and newfmax[1] will be along its X axis.\n\n ' if (rot is None): rot = self.wcs.get_rot() if (self._spflims is None): self.set_spatial_fmax(newfmax, rot) else: oldfmax = self._spflims.get_fmax(rot) if np.any((newfmax < oldfmax)): if np.isclose(rot, self._spflims.rot): newfmax = np.minimum(newfmax, oldfmax) self.set_spatial_fmax(newfmax, rot)<|docstring|>Update the spatial-frequency band-limits recorded for the current image. See the documentation of set_spatial_fmax() for an explanation of what the band-limits are used for. If either of the new limits is less than an existing band-limit, and the rotation angle of the new limits is the same as the angle of the recorded limits, then the smaller limits replace the originals. If either of the new limits is smaller than the existing limits, but the rotation angle for the new limits differs from the recorded limits, then both of the original limits are discarded and replaced by the new ones at the specified angle. Parameters ---------- newfmax : numpy.ndarray The frequency limits along the Y and X axes, respectively, specified in cycles per the angular unit in self.wcs.unit. rot : float or None Either None, to specify band-limits that pertain to the Y and X axes of the current image without any rotation, or, if the band-limits pertain to a rotated version of the image, the rotation angle of its Y axis westward of north (degrees). This is defined such that if image.wcs.get_rot() is passed to this function, the band-limit newfmax[0] will be along the Y axis of the image and newfmax[1] will be along its X axis.<|endoftext|>
dcc5d5e331de47d393b6c3d5178f6ce3c370a319b326ed8f5975d3a9ddb34d57
def set_spatial_fmax(self, newfmax=None, rot=None): 'Specify the spatial-frequency band-limits of the image along\n the Y and X axis. This function completely replaces any existing\n band-limits. See also update_spatial_fmax().\n\n The recorded limits are used to avoid redundantly performing\n anti-aliasing measures such as low-pass filtering an image\n before resampling to a lower resolution, or decreasing pixel\n sizes before rotating high resolution axes onto low resolution\n axes.\n\n Parameters\n ----------\n newfmax : numpy.ndarray\n The new frequency limits along the Y and X axes or a\n band-limiting ellipse, specified in cycles per the angular\n unit in self.wcs.unit.\n rot : float or None\n Either None, to specify band-limits that pertain to the Y\n and X axes of the current image without any rotation, or,\n if the band-limits pertain to a rotated version of the\n image, the rotation angle of its Y axis westward of north\n (degrees). This is defined such that if\n image.wcs.get_rot() is passed to this function, the\n band-limit newfmax[0] will be along the Y axis of the\n image and newfmax[1] will be along its X axis.\n\n ' if (rot is None): rot = self.wcs.get_rot() self._spflims = SpatialFrequencyLimits(newfmax, rot)
Specify the spatial-frequency band-limits of the image along the Y and X axis. This function completely replaces any existing band-limits. See also update_spatial_fmax(). The recorded limits are used to avoid redundantly performing anti-aliasing measures such as low-pass filtering an image before resampling to a lower resolution, or decreasing pixel sizes before rotating high resolution axes onto low resolution axes. Parameters ---------- newfmax : numpy.ndarray The new frequency limits along the Y and X axes or a band-limiting ellipse, specified in cycles per the angular unit in self.wcs.unit. rot : float or None Either None, to specify band-limits that pertain to the Y and X axes of the current image without any rotation, or, if the band-limits pertain to a rotated version of the image, the rotation angle of its Y axis westward of north (degrees). This is defined such that if image.wcs.get_rot() is passed to this function, the band-limit newfmax[0] will be along the Y axis of the image and newfmax[1] will be along its X axis.
lib/mpdaf/obj/image.py
set_spatial_fmax
musevlt/mpdaf
4
python
def set_spatial_fmax(self, newfmax=None, rot=None): 'Specify the spatial-frequency band-limits of the image along\n the Y and X axis. This function completely replaces any existing\n band-limits. See also update_spatial_fmax().\n\n The recorded limits are used to avoid redundantly performing\n anti-aliasing measures such as low-pass filtering an image\n before resampling to a lower resolution, or decreasing pixel\n sizes before rotating high resolution axes onto low resolution\n axes.\n\n Parameters\n ----------\n newfmax : numpy.ndarray\n The new frequency limits along the Y and X axes or a\n band-limiting ellipse, specified in cycles per the angular\n unit in self.wcs.unit.\n rot : float or None\n Either None, to specify band-limits that pertain to the Y\n and X axes of the current image without any rotation, or,\n if the band-limits pertain to a rotated version of the\n image, the rotation angle of its Y axis westward of north\n (degrees). This is defined such that if\n image.wcs.get_rot() is passed to this function, the\n band-limit newfmax[0] will be along the Y axis of the\n image and newfmax[1] will be along its X axis.\n\n ' if (rot is None): rot = self.wcs.get_rot() self._spflims = SpatialFrequencyLimits(newfmax, rot)
def set_spatial_fmax(self, newfmax=None, rot=None): 'Specify the spatial-frequency band-limits of the image along\n the Y and X axis. This function completely replaces any existing\n band-limits. See also update_spatial_fmax().\n\n The recorded limits are used to avoid redundantly performing\n anti-aliasing measures such as low-pass filtering an image\n before resampling to a lower resolution, or decreasing pixel\n sizes before rotating high resolution axes onto low resolution\n axes.\n\n Parameters\n ----------\n newfmax : numpy.ndarray\n The new frequency limits along the Y and X axes or a\n band-limiting ellipse, specified in cycles per the angular\n unit in self.wcs.unit.\n rot : float or None\n Either None, to specify band-limits that pertain to the Y\n and X axes of the current image without any rotation, or,\n if the band-limits pertain to a rotated version of the\n image, the rotation angle of its Y axis westward of north\n (degrees). This is defined such that if\n image.wcs.get_rot() is passed to this function, the\n band-limit newfmax[0] will be along the Y axis of the\n image and newfmax[1] will be along its X axis.\n\n ' if (rot is None): rot = self.wcs.get_rot() self._spflims = SpatialFrequencyLimits(newfmax, rot)<|docstring|>Specify the spatial-frequency band-limits of the image along the Y and X axis. This function completely replaces any existing band-limits. See also update_spatial_fmax(). The recorded limits are used to avoid redundantly performing anti-aliasing measures such as low-pass filtering an image before resampling to a lower resolution, or decreasing pixel sizes before rotating high resolution axes onto low resolution axes. Parameters ---------- newfmax : numpy.ndarray The new frequency limits along the Y and X axes or a band-limiting ellipse, specified in cycles per the angular unit in self.wcs.unit. rot : float or None Either None, to specify band-limits that pertain to the Y and X axes of the current image without any rotation, or, if the band-limits pertain to a rotated version of the image, the rotation angle of its Y axis westward of north (degrees). This is defined such that if image.wcs.get_rot() is passed to this function, the band-limit newfmax[0] will be along the Y axis of the image and newfmax[1] will be along its X axis.<|endoftext|>
162c5b36b4a67e59fb48ab24c461a127f9e047346e4eeeaa841519ddcd8d579d
def get_fmax(self, rot): "Return the spatial-frequency band-limits along a Y axis that is\n 'rot' degrees west of north, and an X axis that is 90 degrees\n away from this Y axis in the sense of a rotation from north to east.\n\n Parameters\n ----------\n rot : float\n The angle of the target Y axis west of north (degrees).\n\n Returns\n -------\n out : numpy.ndarray\n The maximum spatial frequencies along the Y and X axes at\n rotation angle rot, in the same units as were used to\n initialize the object.\n\n " (ys, xs) = self.fmax psi = np.deg2rad((rot - self.rot)) cos_psi = np.cos(psi) sin_psi = np.sin(psi) t_xmax = np.arctan2(((- ys) * sin_psi), (xs * cos_psi)) t_ymax = np.arctan2((ys * cos_psi), (xs * sin_psi)) xmax = (((xs * np.cos(t_xmax)) * cos_psi) - ((ys * np.sin(t_xmax)) * sin_psi)) ymax = (((xs * np.cos(t_ymax)) * sin_psi) + ((ys * np.sin(t_ymax)) * cos_psi)) return np.array([ymax, xmax], dtype=float)
Return the spatial-frequency band-limits along a Y axis that is 'rot' degrees west of north, and an X axis that is 90 degrees away from this Y axis in the sense of a rotation from north to east. Parameters ---------- rot : float The angle of the target Y axis west of north (degrees). Returns ------- out : numpy.ndarray The maximum spatial frequencies along the Y and X axes at rotation angle rot, in the same units as were used to initialize the object.
lib/mpdaf/obj/image.py
get_fmax
musevlt/mpdaf
4
python
def get_fmax(self, rot): "Return the spatial-frequency band-limits along a Y axis that is\n 'rot' degrees west of north, and an X axis that is 90 degrees\n away from this Y axis in the sense of a rotation from north to east.\n\n Parameters\n ----------\n rot : float\n The angle of the target Y axis west of north (degrees).\n\n Returns\n -------\n out : numpy.ndarray\n The maximum spatial frequencies along the Y and X axes at\n rotation angle rot, in the same units as were used to\n initialize the object.\n\n " (ys, xs) = self.fmax psi = np.deg2rad((rot - self.rot)) cos_psi = np.cos(psi) sin_psi = np.sin(psi) t_xmax = np.arctan2(((- ys) * sin_psi), (xs * cos_psi)) t_ymax = np.arctan2((ys * cos_psi), (xs * sin_psi)) xmax = (((xs * np.cos(t_xmax)) * cos_psi) - ((ys * np.sin(t_xmax)) * sin_psi)) ymax = (((xs * np.cos(t_ymax)) * sin_psi) + ((ys * np.sin(t_ymax)) * cos_psi)) return np.array([ymax, xmax], dtype=float)
def get_fmax(self, rot): "Return the spatial-frequency band-limits along a Y axis that is\n 'rot' degrees west of north, and an X axis that is 90 degrees\n away from this Y axis in the sense of a rotation from north to east.\n\n Parameters\n ----------\n rot : float\n The angle of the target Y axis west of north (degrees).\n\n Returns\n -------\n out : numpy.ndarray\n The maximum spatial frequencies along the Y and X axes at\n rotation angle rot, in the same units as were used to\n initialize the object.\n\n " (ys, xs) = self.fmax psi = np.deg2rad((rot - self.rot)) cos_psi = np.cos(psi) sin_psi = np.sin(psi) t_xmax = np.arctan2(((- ys) * sin_psi), (xs * cos_psi)) t_ymax = np.arctan2((ys * cos_psi), (xs * sin_psi)) xmax = (((xs * np.cos(t_xmax)) * cos_psi) - ((ys * np.sin(t_xmax)) * sin_psi)) ymax = (((xs * np.cos(t_ymax)) * sin_psi) + ((ys * np.sin(t_ymax)) * cos_psi)) return np.array([ymax, xmax], dtype=float)<|docstring|>Return the spatial-frequency band-limits along a Y axis that is 'rot' degrees west of north, and an X axis that is 90 degrees away from this Y axis in the sense of a rotation from north to east. Parameters ---------- rot : float The angle of the target Y axis west of north (degrees). Returns ------- out : numpy.ndarray The maximum spatial frequencies along the Y and X axes at rotation angle rot, in the same units as were used to initialize the object.<|endoftext|>
7a01d1f5253093f7505117276bbb3403fc41f1cb91eb603a575fdba3c6017a62
def ellipse_locus(self, t, rot): 'Return the Y,X coordinates of the band-limiting ellipse\n at ellipse phase t.\n\n Parameters\n ----------\n t : float\n The elliptical phase at which the calculate the\n coordinates (radians).\n rot : float\n The rotation angle of the Y axis of the ellipse west\n of north (degrees).\n\n Returns\n -------\n out : numpy.ndarray\n The Y and X coordinates of the band-limiting ellipse.\n ' (ys, xs) = self.fmax psi = np.deg2rad((rot - self.rot)) cos_psi = np.cos(psi) sin_psi = np.sin(psi) cos_t = np.cos(t) sin_t = np.sin(t) x = (((xs * cos_t) * cos_psi) - ((ys * sin_t) * sin_psi)) y = (((xs * cos_t) * sin_psi) + ((ys * sin_t) * cos_psi)) return np.array([y, x], dtype=float)
Return the Y,X coordinates of the band-limiting ellipse at ellipse phase t. Parameters ---------- t : float The elliptical phase at which the calculate the coordinates (radians). rot : float The rotation angle of the Y axis of the ellipse west of north (degrees). Returns ------- out : numpy.ndarray The Y and X coordinates of the band-limiting ellipse.
lib/mpdaf/obj/image.py
ellipse_locus
musevlt/mpdaf
4
python
def ellipse_locus(self, t, rot): 'Return the Y,X coordinates of the band-limiting ellipse\n at ellipse phase t.\n\n Parameters\n ----------\n t : float\n The elliptical phase at which the calculate the\n coordinates (radians).\n rot : float\n The rotation angle of the Y axis of the ellipse west\n of north (degrees).\n\n Returns\n -------\n out : numpy.ndarray\n The Y and X coordinates of the band-limiting ellipse.\n ' (ys, xs) = self.fmax psi = np.deg2rad((rot - self.rot)) cos_psi = np.cos(psi) sin_psi = np.sin(psi) cos_t = np.cos(t) sin_t = np.sin(t) x = (((xs * cos_t) * cos_psi) - ((ys * sin_t) * sin_psi)) y = (((xs * cos_t) * sin_psi) + ((ys * sin_t) * cos_psi)) return np.array([y, x], dtype=float)
def ellipse_locus(self, t, rot): 'Return the Y,X coordinates of the band-limiting ellipse\n at ellipse phase t.\n\n Parameters\n ----------\n t : float\n The elliptical phase at which the calculate the\n coordinates (radians).\n rot : float\n The rotation angle of the Y axis of the ellipse west\n of north (degrees).\n\n Returns\n -------\n out : numpy.ndarray\n The Y and X coordinates of the band-limiting ellipse.\n ' (ys, xs) = self.fmax psi = np.deg2rad((rot - self.rot)) cos_psi = np.cos(psi) sin_psi = np.sin(psi) cos_t = np.cos(t) sin_t = np.sin(t) x = (((xs * cos_t) * cos_psi) - ((ys * sin_t) * sin_psi)) y = (((xs * cos_t) * sin_psi) + ((ys * sin_t) * cos_psi)) return np.array([y, x], dtype=float)<|docstring|>Return the Y,X coordinates of the band-limiting ellipse at ellipse phase t. Parameters ---------- t : float The elliptical phase at which the calculate the coordinates (radians). rot : float The rotation angle of the Y axis of the ellipse west of north (degrees). Returns ------- out : numpy.ndarray The Y and X coordinates of the band-limiting ellipse.<|endoftext|>
685ae25b1b5d6778c33d14a35b75480553b7e418bf2521b4ce9be209394039da
def moffat(c, x, y, amplitude, x_0, y_0, alpha, beta, e): 'Two dimensional Moffat model function' rr_gg = ((((x - x_0) / alpha) ** 2) + ((((y - y_0) / alpha) / e) ** 2)) return (c + (amplitude * ((1 + rr_gg) ** (- beta))))
Two dimensional Moffat model function
lib/mpdaf/obj/image.py
moffat
musevlt/mpdaf
4
python
def moffat(c, x, y, amplitude, x_0, y_0, alpha, beta, e): rr_gg = ((((x - x_0) / alpha) ** 2) + ((((y - y_0) / alpha) / e) ** 2)) return (c + (amplitude * ((1 + rr_gg) ** (- beta))))
def moffat(c, x, y, amplitude, x_0, y_0, alpha, beta, e): rr_gg = ((((x - x_0) / alpha) ** 2) + ((((y - y_0) / alpha) / e) ** 2)) return (c + (amplitude * ((1 + rr_gg) ** (- beta))))<|docstring|>Two dimensional Moffat model function<|endoftext|>
90e14161f806edd2a544f57f87a9c2255051c09b16e529149d9bb7aaa00867f5
def _dict_repr(self) -> Any: '\n Returns the dict representation of your object.\n\n It is the only method that you would want to redefine in most cases to represent data.\n ' return vars(self).copy()
Returns the dict representation of your object. It is the only method that you would want to redefine in most cases to represent data.
flanautils/models/bases.py
_dict_repr
AlberLC/flanautils
0
python
def _dict_repr(self) -> Any: '\n Returns the dict representation of your object.\n\n It is the only method that you would want to redefine in most cases to represent data.\n ' return vars(self).copy()
def _dict_repr(self) -> Any: '\n Returns the dict representation of your object.\n\n It is the only method that you would want to redefine in most cases to represent data.\n ' return vars(self).copy()<|docstring|>Returns the dict representation of your object. It is the only method that you would want to redefine in most cases to represent data.<|endoftext|>
12f4df84341e8debf8c63ac6b7bffc4538dc6caecd7dac275cb8e6550bbf898c
def _json_repr(self) -> Any: '\n Returns the JSON representation of your object.\n\n It is the only method that you would want to redefine in most cases to represent data.\n ' return vars(self)
Returns the JSON representation of your object. It is the only method that you would want to redefine in most cases to represent data.
flanautils/models/bases.py
_json_repr
AlberLC/flanautils
0
python
def _json_repr(self) -> Any: '\n Returns the JSON representation of your object.\n\n It is the only method that you would want to redefine in most cases to represent data.\n ' return vars(self)
def _json_repr(self) -> Any: '\n Returns the JSON representation of your object.\n\n It is the only method that you would want to redefine in most cases to represent data.\n ' return vars(self)<|docstring|>Returns the JSON representation of your object. It is the only method that you would want to redefine in most cases to represent data.<|endoftext|>
9c98464d3cb3699a63b3cf8a977e0072bdec061505eadfff9a32f31826846eb7
@classmethod def from_json(cls, text: str) -> Any: 'Classmethod that constructs an object given a JSON string.' def decode_str(obj_: Any) -> Any: 'Inner function to decode JSON strings to anything.' if (not isinstance(obj_, str)): return obj_ try: bytes_ = base64.b64decode(obj_.encode(), validate=True) decoded_obj = pickle.loads(bytes_) except (binascii.Error, pickle.UnpicklingError, EOFError): return obj_ return decoded_obj def decode_list(obj_: Any) -> Any: 'Inner function to decode JSON lists to anything.' return [decode_str(e) for e in obj_] def decode_dict(cls_: Any, dict_: dict) -> Any: 'Inner function to decode JSON dictionaries to anything.' kwargs = {} for (k, v) in dict_.items(): k = decode_str(k) v = decode_str(v) if isinstance(v, dict): try: v = decode_dict(typing.get_type_hints(cls_)[k], v) except KeyError: pass kwargs[k] = v return cls_(**kwargs) if (not isinstance(text, str)): raise TypeError(f'must be str, not {type(text).__name__}') obj = json.loads(text) if isinstance(obj, str): return decode_str(obj) elif isinstance(obj, list): return decode_list(obj) elif isinstance(obj, dict): return decode_dict(cls, obj) else: return obj
Classmethod that constructs an object given a JSON string.
flanautils/models/bases.py
from_json
AlberLC/flanautils
0
python
@classmethod def from_json(cls, text: str) -> Any: def decode_str(obj_: Any) -> Any: 'Inner function to decode JSON strings to anything.' if (not isinstance(obj_, str)): return obj_ try: bytes_ = base64.b64decode(obj_.encode(), validate=True) decoded_obj = pickle.loads(bytes_) except (binascii.Error, pickle.UnpicklingError, EOFError): return obj_ return decoded_obj def decode_list(obj_: Any) -> Any: 'Inner function to decode JSON lists to anything.' return [decode_str(e) for e in obj_] def decode_dict(cls_: Any, dict_: dict) -> Any: 'Inner function to decode JSON dictionaries to anything.' kwargs = {} for (k, v) in dict_.items(): k = decode_str(k) v = decode_str(v) if isinstance(v, dict): try: v = decode_dict(typing.get_type_hints(cls_)[k], v) except KeyError: pass kwargs[k] = v return cls_(**kwargs) if (not isinstance(text, str)): raise TypeError(f'must be str, not {type(text).__name__}') obj = json.loads(text) if isinstance(obj, str): return decode_str(obj) elif isinstance(obj, list): return decode_list(obj) elif isinstance(obj, dict): return decode_dict(cls, obj) else: return obj
@classmethod def from_json(cls, text: str) -> Any: def decode_str(obj_: Any) -> Any: 'Inner function to decode JSON strings to anything.' if (not isinstance(obj_, str)): return obj_ try: bytes_ = base64.b64decode(obj_.encode(), validate=True) decoded_obj = pickle.loads(bytes_) except (binascii.Error, pickle.UnpicklingError, EOFError): return obj_ return decoded_obj def decode_list(obj_: Any) -> Any: 'Inner function to decode JSON lists to anything.' return [decode_str(e) for e in obj_] def decode_dict(cls_: Any, dict_: dict) -> Any: 'Inner function to decode JSON dictionaries to anything.' kwargs = {} for (k, v) in dict_.items(): k = decode_str(k) v = decode_str(v) if isinstance(v, dict): try: v = decode_dict(typing.get_type_hints(cls_)[k], v) except KeyError: pass kwargs[k] = v return cls_(**kwargs) if (not isinstance(text, str)): raise TypeError(f'must be str, not {type(text).__name__}') obj = json.loads(text) if isinstance(obj, str): return decode_str(obj) elif isinstance(obj, list): return decode_list(obj) elif isinstance(obj, dict): return decode_dict(cls, obj) else: return obj<|docstring|>Classmethod that constructs an object given a JSON string.<|endoftext|>
5be833807f0878afbc9772952ef6a9e2a9d79c6b29a4c2b54af81ce8bdb1f1d7
@classmethod def mean(cls, objects: Sequence, ratios: list[float]=None, attribute_names: Iterable[str]=()) -> MeanBase: '\n Classmethod that builds a new object calculating the mean of the objects in the iterable for the attributes\n specified in attribute_names with the provided ratios.\n\n When calculating the mean, if an attribute is None, the ratio given for that object is distributed among the\n rest whose attributes with that name contain some value other than None.\n\n By default, ratios is 1 / n_objects for every object in objects.\n ' if (not objects): return cls() n_objects = len(objects) if (not ratios): ratios = [(1 / n_objects) for _ in objects] elif (len(ratios) != len(objects)): raise ValueError('Wrong ratios length') attributes_ratios = {} attributes_ratios_length = {} for attribute_name in attribute_names: attributes_ratios[attribute_name] = ratios.copy() attributes_ratios_length[attribute_name] = len(attributes_ratios[attribute_name]) for (object_index, object_) in enumerate(objects): if ((not object_) or (getattr(object_, attribute_name, None) is None)): attributes_ratios_length[attribute_name] -= 1 try: ratio_part_to_add = (attributes_ratios[attribute_name][object_index] / attributes_ratios_length[attribute_name]) except ZeroDivisionError: ratio_part_to_add = 0 attributes_ratios[attribute_name][object_index] = 0 for (ratio_index, _) in enumerate(attributes_ratios[attribute_name]): if attributes_ratios[attribute_name][ratio_index]: attributes_ratios[attribute_name][ratio_index] += ratio_part_to_add attribute_values = {} timezone: (datetime.timezone | None) = None for (attribute_name, attribute_ratios) in attributes_ratios.items(): values = [] for (object_, ratio) in zip(objects, attribute_ratios): if ratio: attribute = getattr(object_, attribute_name) if (attribute_name in ('sunrise', 'sunset')): timezone = attribute.tzinfo attribute = attribute.timestamp() values.append((attribute * ratio)) if values: final_value = sum(values) if (attribute_name in ('sunrise', 'sunset')): final_value = datetime.datetime.fromtimestamp(final_value, timezone) attribute_values[attribute_name] = final_value return cls(**attribute_values)
Classmethod that builds a new object calculating the mean of the objects in the iterable for the attributes specified in attribute_names with the provided ratios. When calculating the mean, if an attribute is None, the ratio given for that object is distributed among the rest whose attributes with that name contain some value other than None. By default, ratios is 1 / n_objects for every object in objects.
flanautils/models/bases.py
mean
AlberLC/flanautils
0
python
@classmethod def mean(cls, objects: Sequence, ratios: list[float]=None, attribute_names: Iterable[str]=()) -> MeanBase: '\n Classmethod that builds a new object calculating the mean of the objects in the iterable for the attributes\n specified in attribute_names with the provided ratios.\n\n When calculating the mean, if an attribute is None, the ratio given for that object is distributed among the\n rest whose attributes with that name contain some value other than None.\n\n By default, ratios is 1 / n_objects for every object in objects.\n ' if (not objects): return cls() n_objects = len(objects) if (not ratios): ratios = [(1 / n_objects) for _ in objects] elif (len(ratios) != len(objects)): raise ValueError('Wrong ratios length') attributes_ratios = {} attributes_ratios_length = {} for attribute_name in attribute_names: attributes_ratios[attribute_name] = ratios.copy() attributes_ratios_length[attribute_name] = len(attributes_ratios[attribute_name]) for (object_index, object_) in enumerate(objects): if ((not object_) or (getattr(object_, attribute_name, None) is None)): attributes_ratios_length[attribute_name] -= 1 try: ratio_part_to_add = (attributes_ratios[attribute_name][object_index] / attributes_ratios_length[attribute_name]) except ZeroDivisionError: ratio_part_to_add = 0 attributes_ratios[attribute_name][object_index] = 0 for (ratio_index, _) in enumerate(attributes_ratios[attribute_name]): if attributes_ratios[attribute_name][ratio_index]: attributes_ratios[attribute_name][ratio_index] += ratio_part_to_add attribute_values = {} timezone: (datetime.timezone | None) = None for (attribute_name, attribute_ratios) in attributes_ratios.items(): values = [] for (object_, ratio) in zip(objects, attribute_ratios): if ratio: attribute = getattr(object_, attribute_name) if (attribute_name in ('sunrise', 'sunset')): timezone = attribute.tzinfo attribute = attribute.timestamp() values.append((attribute * ratio)) if values: final_value = sum(values) if (attribute_name in ('sunrise', 'sunset')): final_value = datetime.datetime.fromtimestamp(final_value, timezone) attribute_values[attribute_name] = final_value return cls(**attribute_values)
@classmethod def mean(cls, objects: Sequence, ratios: list[float]=None, attribute_names: Iterable[str]=()) -> MeanBase: '\n Classmethod that builds a new object calculating the mean of the objects in the iterable for the attributes\n specified in attribute_names with the provided ratios.\n\n When calculating the mean, if an attribute is None, the ratio given for that object is distributed among the\n rest whose attributes with that name contain some value other than None.\n\n By default, ratios is 1 / n_objects for every object in objects.\n ' if (not objects): return cls() n_objects = len(objects) if (not ratios): ratios = [(1 / n_objects) for _ in objects] elif (len(ratios) != len(objects)): raise ValueError('Wrong ratios length') attributes_ratios = {} attributes_ratios_length = {} for attribute_name in attribute_names: attributes_ratios[attribute_name] = ratios.copy() attributes_ratios_length[attribute_name] = len(attributes_ratios[attribute_name]) for (object_index, object_) in enumerate(objects): if ((not object_) or (getattr(object_, attribute_name, None) is None)): attributes_ratios_length[attribute_name] -= 1 try: ratio_part_to_add = (attributes_ratios[attribute_name][object_index] / attributes_ratios_length[attribute_name]) except ZeroDivisionError: ratio_part_to_add = 0 attributes_ratios[attribute_name][object_index] = 0 for (ratio_index, _) in enumerate(attributes_ratios[attribute_name]): if attributes_ratios[attribute_name][ratio_index]: attributes_ratios[attribute_name][ratio_index] += ratio_part_to_add attribute_values = {} timezone: (datetime.timezone | None) = None for (attribute_name, attribute_ratios) in attributes_ratios.items(): values = [] for (object_, ratio) in zip(objects, attribute_ratios): if ratio: attribute = getattr(object_, attribute_name) if (attribute_name in ('sunrise', 'sunset')): timezone = attribute.tzinfo attribute = attribute.timestamp() values.append((attribute * ratio)) if values: final_value = sum(values) if (attribute_name in ('sunrise', 'sunset')): final_value = datetime.datetime.fromtimestamp(final_value, timezone) attribute_values[attribute_name] = final_value return cls(**attribute_values)<|docstring|>Classmethod that builds a new object calculating the mean of the objects in the iterable for the attributes specified in attribute_names with the provided ratios. When calculating the mean, if an attribute is None, the ratio given for that object is distributed among the rest whose attributes with that name contain some value other than None. By default, ratios is 1 / n_objects for every object in objects.<|endoftext|>
53b2ec0e5a462a8b9a56c1e317ba2a94ee964404dc20a97f4beb5ee9788b9177
def _create_unique_indices(self): 'Create the unique indices in the database based on _unique_keys and _nullable_unique_keys attributes.' if (not self._unique_keys): return unique_keys = [(unique_key, pymongo.ASCENDING) for unique_key in self._unique_keys] type_filter = {'$type': ['number', 'string', 'object', 'array', 'binData', 'objectId', 'bool', 'date', 'regex', 'javascript', 'regex', 'timestamp', 'minKey', 'maxKey']} partial_unique_filter = {nullable_unique_key: type_filter for nullable_unique_key in self._nullable_unique_keys} self.collection.create_index(unique_keys, partialFilterExpression=partial_unique_filter, unique=True)
Create the unique indices in the database based on _unique_keys and _nullable_unique_keys attributes.
flanautils/models/bases.py
_create_unique_indices
AlberLC/flanautils
0
python
def _create_unique_indices(self): if (not self._unique_keys): return unique_keys = [(unique_key, pymongo.ASCENDING) for unique_key in self._unique_keys] type_filter = {'$type': ['number', 'string', 'object', 'array', 'binData', 'objectId', 'bool', 'date', 'regex', 'javascript', 'regex', 'timestamp', 'minKey', 'maxKey']} partial_unique_filter = {nullable_unique_key: type_filter for nullable_unique_key in self._nullable_unique_keys} self.collection.create_index(unique_keys, partialFilterExpression=partial_unique_filter, unique=True)
def _create_unique_indices(self): if (not self._unique_keys): return unique_keys = [(unique_key, pymongo.ASCENDING) for unique_key in self._unique_keys] type_filter = {'$type': ['number', 'string', 'object', 'array', 'binData', 'objectId', 'bool', 'date', 'regex', 'javascript', 'regex', 'timestamp', 'minKey', 'maxKey']} partial_unique_filter = {nullable_unique_key: type_filter for nullable_unique_key in self._nullable_unique_keys} self.collection.create_index(unique_keys, partialFilterExpression=partial_unique_filter, unique=True)<|docstring|>Create the unique indices in the database based on _unique_keys and _nullable_unique_keys attributes.<|endoftext|>
598bbab90dce5e515f3985e6509e89ba434c8e18dd4d9745a49ac7ed4157a7c0
def _mongo_repr(self) -> Any: 'Returns the object representation to save in mongo database.' return {k: (v.value if isinstance(v, Enum) else v) for (k, v) in self._dict_repr().items()}
Returns the object representation to save in mongo database.
flanautils/models/bases.py
_mongo_repr
AlberLC/flanautils
0
python
def _mongo_repr(self) -> Any: return {k: (v.value if isinstance(v, Enum) else v) for (k, v) in self._dict_repr().items()}
def _mongo_repr(self) -> Any: return {k: (v.value if isinstance(v, Enum) else v) for (k, v) in self._dict_repr().items()}<|docstring|>Returns the object representation to save in mongo database.<|endoftext|>
afc24950ba3b94507e45ee894b25b8bfb5b2ac701de9ea7da6ff664c1e6ce7c3
def delete(self, cascade=False): '\n Delete the object from the database.\n\n If cascade=True all objects whose classes inherit from MongoBase are also deleted.\n ' if cascade: for referenced_object in self.get_referenced_objects(): referenced_object.delete(cascade) self.collection.delete_one({'_id': self._id})
Delete the object from the database. If cascade=True all objects whose classes inherit from MongoBase are also deleted.
flanautils/models/bases.py
delete
AlberLC/flanautils
0
python
def delete(self, cascade=False): '\n Delete the object from the database.\n\n If cascade=True all objects whose classes inherit from MongoBase are also deleted.\n ' if cascade: for referenced_object in self.get_referenced_objects(): referenced_object.delete(cascade) self.collection.delete_one({'_id': self._id})
def delete(self, cascade=False): '\n Delete the object from the database.\n\n If cascade=True all objects whose classes inherit from MongoBase are also deleted.\n ' if cascade: for referenced_object in self.get_referenced_objects(): referenced_object.delete(cascade) self.collection.delete_one({'_id': self._id})<|docstring|>Delete the object from the database. If cascade=True all objects whose classes inherit from MongoBase are also deleted.<|endoftext|>
05fb812aa2c4bb78571e5431b4101ed8b10765d07848a6424fd2a3e59cc30870
@classmethod def find_one(cls, query: dict=None, sort_keys: (str | Iterable[(str | tuple[(str, int)])])=()) -> (MongoBase | None): 'Query the collection and return the first match.' return next(cls.find(query, sort_keys, lazy=True), None)
Query the collection and return the first match.
flanautils/models/bases.py
find_one
AlberLC/flanautils
0
python
@classmethod def find_one(cls, query: dict=None, sort_keys: (str | Iterable[(str | tuple[(str, int)])])=()) -> (MongoBase | None): return next(cls.find(query, sort_keys, lazy=True), None)
@classmethod def find_one(cls, query: dict=None, sort_keys: (str | Iterable[(str | tuple[(str, int)])])=()) -> (MongoBase | None): return next(cls.find(query, sort_keys, lazy=True), None)<|docstring|>Query the collection and return the first match.<|endoftext|>
0be46f89a912f20060f47fd047d163843ae3fad813a4b4f360b5fdb5ff463aef
def find_in_database_by_id(self, object_id: ObjectId) -> (dict | None): 'Find an object in all database collections by its ObjectId.' collections = (self._database[name] for name in self._database.list_collection_names()) return next((document for collection in collections if (document := collection.find_one({'_id': object_id}))), None)
Find an object in all database collections by its ObjectId.
flanautils/models/bases.py
find_in_database_by_id
AlberLC/flanautils
0
python
def find_in_database_by_id(self, object_id: ObjectId) -> (dict | None): collections = (self._database[name] for name in self._database.list_collection_names()) return next((document for collection in collections if (document := collection.find_one({'_id': object_id}))), None)
def find_in_database_by_id(self, object_id: ObjectId) -> (dict | None): collections = (self._database[name] for name in self._database.list_collection_names()) return next((document for collection in collections if (document := collection.find_one({'_id': object_id}))), None)<|docstring|>Find an object in all database collections by its ObjectId.<|endoftext|>
b6683193fa67185af8726f8620e66230b8688b239987da920cecf0d6f5c1238a
def pull_from_database(self, overwrite_fields: Iterable[str]=('_id',), exclude: Iterable[str]=()): '\n Updates the values of the current object with the values of the same object located in the database.\n\n By default, it updates the ObjectId and the attributes of the current object that contain None. You can force\n write from database with database_priority=True (by default database_priority=False).\n\n Ignore the attributes specified in exclude.\n ' unique_attributes = self.unique_attributes if any(((value is None) for value in unique_attributes.values())): query = {'_id': self._id} else: query = {} for (k, v) in unique_attributes.items(): if isinstance(v, MongoBase): v.pull_from_database(overwrite_fields, exclude) v = v._id query[k] = v if (document := self.collection.find_one(query)): for (database_key, database_value) in vars(self.from_dict(document)).items(): self_value = getattr(self, database_key) if ((database_key not in exclude) and (((database_key in overwrite_fields) and (database_value is not None)) or (self_value is None) or (isinstance(self_value, Iterable) and (not self_value)))): super().__setattr__(database_key, database_value)
Updates the values of the current object with the values of the same object located in the database. By default, it updates the ObjectId and the attributes of the current object that contain None. You can force write from database with database_priority=True (by default database_priority=False). Ignore the attributes specified in exclude.
flanautils/models/bases.py
pull_from_database
AlberLC/flanautils
0
python
def pull_from_database(self, overwrite_fields: Iterable[str]=('_id',), exclude: Iterable[str]=()): '\n Updates the values of the current object with the values of the same object located in the database.\n\n By default, it updates the ObjectId and the attributes of the current object that contain None. You can force\n write from database with database_priority=True (by default database_priority=False).\n\n Ignore the attributes specified in exclude.\n ' unique_attributes = self.unique_attributes if any(((value is None) for value in unique_attributes.values())): query = {'_id': self._id} else: query = {} for (k, v) in unique_attributes.items(): if isinstance(v, MongoBase): v.pull_from_database(overwrite_fields, exclude) v = v._id query[k] = v if (document := self.collection.find_one(query)): for (database_key, database_value) in vars(self.from_dict(document)).items(): self_value = getattr(self, database_key) if ((database_key not in exclude) and (((database_key in overwrite_fields) and (database_value is not None)) or (self_value is None) or (isinstance(self_value, Iterable) and (not self_value)))): super().__setattr__(database_key, database_value)
def pull_from_database(self, overwrite_fields: Iterable[str]=('_id',), exclude: Iterable[str]=()): '\n Updates the values of the current object with the values of the same object located in the database.\n\n By default, it updates the ObjectId and the attributes of the current object that contain None. You can force\n write from database with database_priority=True (by default database_priority=False).\n\n Ignore the attributes specified in exclude.\n ' unique_attributes = self.unique_attributes if any(((value is None) for value in unique_attributes.values())): query = {'_id': self._id} else: query = {} for (k, v) in unique_attributes.items(): if isinstance(v, MongoBase): v.pull_from_database(overwrite_fields, exclude) v = v._id query[k] = v if (document := self.collection.find_one(query)): for (database_key, database_value) in vars(self.from_dict(document)).items(): self_value = getattr(self, database_key) if ((database_key not in exclude) and (((database_key in overwrite_fields) and (database_value is not None)) or (self_value is None) or (isinstance(self_value, Iterable) and (not self_value)))): super().__setattr__(database_key, database_value)<|docstring|>Updates the values of the current object with the values of the same object located in the database. By default, it updates the ObjectId and the attributes of the current object that contain None. You can force write from database with database_priority=True (by default database_priority=False). Ignore the attributes specified in exclude.<|endoftext|>
76257ed2efa89e695a3ab77630f84fbd7e35391e6d198e42a18e973212e345f6
def resolve(self): 'Resolve all the ObjectId references (ObjectId -> MongoBase).' for k in vars(self): getattr(self, k)
Resolve all the ObjectId references (ObjectId -> MongoBase).
flanautils/models/bases.py
resolve
AlberLC/flanautils
0
python
def resolve(self): for k in vars(self): getattr(self, k)
def resolve(self): for k in vars(self): getattr(self, k)<|docstring|>Resolve all the ObjectId references (ObjectId -> MongoBase).<|endoftext|>
53c39b0c6ff257c0a841e0c3440b7e4fe8355396945a409d2823fc503b792bed
@property def unique_attributes(self): '\n Property that returns a dictionary with the name of the attributes that must be unique in the database and their\n values.\n ' unique_attributes = {} for unique_key in self._unique_keys: attribute_value = getattr(self, unique_key, None) unique_attributes[unique_key] = (attribute_value.value if isinstance(attribute_value, Enum) else attribute_value) return unique_attributes
Property that returns a dictionary with the name of the attributes that must be unique in the database and their values.
flanautils/models/bases.py
unique_attributes
AlberLC/flanautils
0
python
@property def unique_attributes(self): '\n Property that returns a dictionary with the name of the attributes that must be unique in the database and their\n values.\n ' unique_attributes = {} for unique_key in self._unique_keys: attribute_value = getattr(self, unique_key, None) unique_attributes[unique_key] = (attribute_value.value if isinstance(attribute_value, Enum) else attribute_value) return unique_attributes
@property def unique_attributes(self): '\n Property that returns a dictionary with the name of the attributes that must be unique in the database and their\n values.\n ' unique_attributes = {} for unique_key in self._unique_keys: attribute_value = getattr(self, unique_key, None) unique_attributes[unique_key] = (attribute_value.value if isinstance(attribute_value, Enum) else attribute_value) return unique_attributes<|docstring|>Property that returns a dictionary with the name of the attributes that must be unique in the database and their values.<|endoftext|>
aba467cd151537856c76861f5f0278bfa1247001459e9bd237401073335d3f3c
def decode_str(obj_: Any) -> Any: 'Inner function to decode JSON strings to anything.' if (not isinstance(obj_, str)): return obj_ try: bytes_ = base64.b64decode(obj_.encode(), validate=True) decoded_obj = pickle.loads(bytes_) except (binascii.Error, pickle.UnpicklingError, EOFError): return obj_ return decoded_obj
Inner function to decode JSON strings to anything.
flanautils/models/bases.py
decode_str
AlberLC/flanautils
0
python
def decode_str(obj_: Any) -> Any: if (not isinstance(obj_, str)): return obj_ try: bytes_ = base64.b64decode(obj_.encode(), validate=True) decoded_obj = pickle.loads(bytes_) except (binascii.Error, pickle.UnpicklingError, EOFError): return obj_ return decoded_obj
def decode_str(obj_: Any) -> Any: if (not isinstance(obj_, str)): return obj_ try: bytes_ = base64.b64decode(obj_.encode(), validate=True) decoded_obj = pickle.loads(bytes_) except (binascii.Error, pickle.UnpicklingError, EOFError): return obj_ return decoded_obj<|docstring|>Inner function to decode JSON strings to anything.<|endoftext|>
819380ca14724af62f4ef4bf7be1dd3e9d32206351716ddf08df46b7b66be162
def decode_list(obj_: Any) -> Any: 'Inner function to decode JSON lists to anything.' return [decode_str(e) for e in obj_]
Inner function to decode JSON lists to anything.
flanautils/models/bases.py
decode_list
AlberLC/flanautils
0
python
def decode_list(obj_: Any) -> Any: return [decode_str(e) for e in obj_]
def decode_list(obj_: Any) -> Any: return [decode_str(e) for e in obj_]<|docstring|>Inner function to decode JSON lists to anything.<|endoftext|>
9e59bcff3d15e2b1d9eea655a85d8efb80c3bba67c09ad4aef41e0221df77faf
def decode_dict(cls_: Any, dict_: dict) -> Any: 'Inner function to decode JSON dictionaries to anything.' kwargs = {} for (k, v) in dict_.items(): k = decode_str(k) v = decode_str(v) if isinstance(v, dict): try: v = decode_dict(typing.get_type_hints(cls_)[k], v) except KeyError: pass kwargs[k] = v return cls_(**kwargs)
Inner function to decode JSON dictionaries to anything.
flanautils/models/bases.py
decode_dict
AlberLC/flanautils
0
python
def decode_dict(cls_: Any, dict_: dict) -> Any: kwargs = {} for (k, v) in dict_.items(): k = decode_str(k) v = decode_str(v) if isinstance(v, dict): try: v = decode_dict(typing.get_type_hints(cls_)[k], v) except KeyError: pass kwargs[k] = v return cls_(**kwargs)
def decode_dict(cls_: Any, dict_: dict) -> Any: kwargs = {} for (k, v) in dict_.items(): k = decode_str(k) v = decode_str(v) if isinstance(v, dict): try: v = decode_dict(typing.get_type_hints(cls_)[k], v) except KeyError: pass kwargs[k] = v return cls_(**kwargs)<|docstring|>Inner function to decode JSON dictionaries to anything.<|endoftext|>
8de36190932efa4cd286b4a94028a78b18fe49369a19a3dd7d62bb3924836488
@scope.define def hyperopt_param(label, obj): 'A graph node primarily for annotating - VectorizeHelper looks out\n for these guys, and optimizes subgraphs of the form:\n\n hyperopt_param(<stochastic_expression>(...))\n\n ' return obj
A graph node primarily for annotating - VectorizeHelper looks out for these guys, and optimizes subgraphs of the form: hyperopt_param(<stochastic_expression>(...))
hyperopt/pyll_utils.py
hyperopt_param
hamidelmaazouz/hyperopt
6,071
python
@scope.define def hyperopt_param(label, obj): 'A graph node primarily for annotating - VectorizeHelper looks out\n for these guys, and optimizes subgraphs of the form:\n\n hyperopt_param(<stochastic_expression>(...))\n\n ' return obj
@scope.define def hyperopt_param(label, obj): 'A graph node primarily for annotating - VectorizeHelper looks out\n for these guys, and optimizes subgraphs of the form:\n\n hyperopt_param(<stochastic_expression>(...))\n\n ' return obj<|docstring|>A graph node primarily for annotating - VectorizeHelper looks out for these guys, and optimizes subgraphs of the form: hyperopt_param(<stochastic_expression>(...))<|endoftext|>
4c7952e6687f1cb8f3928ba6e3540ffe451bfd6b64ec5eceaa26563b4a2ad339
@validate_label def hp_pchoice(label, p_options): '\n label: string\n p_options: list of (probability, option) pairs\n ' (p, options) = list(zip(*p_options)) ch = scope.hyperopt_param(label, scope.categorical(p)) return scope.switch(ch, *options)
label: string p_options: list of (probability, option) pairs
hyperopt/pyll_utils.py
hp_pchoice
hamidelmaazouz/hyperopt
6,071
python
@validate_label def hp_pchoice(label, p_options): '\n label: string\n p_options: list of (probability, option) pairs\n ' (p, options) = list(zip(*p_options)) ch = scope.hyperopt_param(label, scope.categorical(p)) return scope.switch(ch, *options)
@validate_label def hp_pchoice(label, p_options): '\n label: string\n p_options: list of (probability, option) pairs\n ' (p, options) = list(zip(*p_options)) ch = scope.hyperopt_param(label, scope.categorical(p)) return scope.switch(ch, *options)<|docstring|>label: string p_options: list of (probability, option) pairs<|endoftext|>
f6b2d47e4fb8f190fbdc371afb2a3cc3762af7e7c018d89c33d2bd7c6ebd2aca
def expr_to_config(expr, conditions, hps): "\n Populate dictionary `hps` with the hyperparameters in pyll graph `expr`\n and conditions for participation in the evaluation of `expr`.\n\n Arguments:\n expr - a pyll expression root.\n conditions - a tuple of conditions (`Cond`) that must be True for\n `expr` to be evaluated.\n hps - dictionary to populate\n\n Creates `hps` dictionary:\n label -> { 'node': apply node of hyperparameter distribution,\n 'conditions': `conditions` + tuple,\n 'label': label\n }\n " expr = as_apply(expr) if (conditions is None): conditions = () assert isinstance(expr, Apply) _expr_to_config(expr, conditions, hps) _remove_allpaths(hps, conditions)
Populate dictionary `hps` with the hyperparameters in pyll graph `expr` and conditions for participation in the evaluation of `expr`. Arguments: expr - a pyll expression root. conditions - a tuple of conditions (`Cond`) that must be True for `expr` to be evaluated. hps - dictionary to populate Creates `hps` dictionary: label -> { 'node': apply node of hyperparameter distribution, 'conditions': `conditions` + tuple, 'label': label }
hyperopt/pyll_utils.py
expr_to_config
hamidelmaazouz/hyperopt
6,071
python
def expr_to_config(expr, conditions, hps): "\n Populate dictionary `hps` with the hyperparameters in pyll graph `expr`\n and conditions for participation in the evaluation of `expr`.\n\n Arguments:\n expr - a pyll expression root.\n conditions - a tuple of conditions (`Cond`) that must be True for\n `expr` to be evaluated.\n hps - dictionary to populate\n\n Creates `hps` dictionary:\n label -> { 'node': apply node of hyperparameter distribution,\n 'conditions': `conditions` + tuple,\n 'label': label\n }\n " expr = as_apply(expr) if (conditions is None): conditions = () assert isinstance(expr, Apply) _expr_to_config(expr, conditions, hps) _remove_allpaths(hps, conditions)
def expr_to_config(expr, conditions, hps): "\n Populate dictionary `hps` with the hyperparameters in pyll graph `expr`\n and conditions for participation in the evaluation of `expr`.\n\n Arguments:\n expr - a pyll expression root.\n conditions - a tuple of conditions (`Cond`) that must be True for\n `expr` to be evaluated.\n hps - dictionary to populate\n\n Creates `hps` dictionary:\n label -> { 'node': apply node of hyperparameter distribution,\n 'conditions': `conditions` + tuple,\n 'label': label\n }\n " expr = as_apply(expr) if (conditions is None): conditions = () assert isinstance(expr, Apply) _expr_to_config(expr, conditions, hps) _remove_allpaths(hps, conditions)<|docstring|>Populate dictionary `hps` with the hyperparameters in pyll graph `expr` and conditions for participation in the evaluation of `expr`. Arguments: expr - a pyll expression root. conditions - a tuple of conditions (`Cond`) that must be True for `expr` to be evaluated. hps - dictionary to populate Creates `hps` dictionary: label -> { 'node': apply node of hyperparameter distribution, 'conditions': `conditions` + tuple, 'label': label }<|endoftext|>
57ab7b6af9f73f7451a224825c1828693b2df11f800cbfe13a85fe79578975a4
def _remove_allpaths(hps, conditions): 'Hacky way to recognize some kinds of false dependencies\n Better would be logic programming.\n ' potential_conds = {} for (k, v) in list(hps.items()): if (v['node'].name == 'randint'): low = v['node'].arg['low'].obj domain_size = ((v['node'].arg['high'].obj - low) if (v['node'].arg['high'] != MissingArgument) else low) potential_conds[k] = frozenset([EQ(k, ii) for ii in range(domain_size)]) elif (v['node'].name == 'categorical'): p = v['node'].arg['p'].obj potential_conds[k] = frozenset([EQ(k, ii) for ii in range(p.size)]) for (k, v) in list(hps.items()): if (len(v['conditions']) > 1): all_conds = [[c for c in cond if (c is not True)] for cond in v['conditions']] all_conds = [cond for cond in all_conds if (len(cond) >= 1)] if (len(all_conds) == 0): v['conditions'] = {conditions} continue depvar = all_conds[0][0].name all_one_var = all((((len(cond) == 1) and (cond[0].name == depvar)) for cond in all_conds)) if all_one_var: conds = [cond[0] for cond in all_conds] if (frozenset(conds) == potential_conds[depvar]): v['conditions'] = {conditions} continue
Hacky way to recognize some kinds of false dependencies Better would be logic programming.
hyperopt/pyll_utils.py
_remove_allpaths
hamidelmaazouz/hyperopt
6,071
python
def _remove_allpaths(hps, conditions): 'Hacky way to recognize some kinds of false dependencies\n Better would be logic programming.\n ' potential_conds = {} for (k, v) in list(hps.items()): if (v['node'].name == 'randint'): low = v['node'].arg['low'].obj domain_size = ((v['node'].arg['high'].obj - low) if (v['node'].arg['high'] != MissingArgument) else low) potential_conds[k] = frozenset([EQ(k, ii) for ii in range(domain_size)]) elif (v['node'].name == 'categorical'): p = v['node'].arg['p'].obj potential_conds[k] = frozenset([EQ(k, ii) for ii in range(p.size)]) for (k, v) in list(hps.items()): if (len(v['conditions']) > 1): all_conds = [[c for c in cond if (c is not True)] for cond in v['conditions']] all_conds = [cond for cond in all_conds if (len(cond) >= 1)] if (len(all_conds) == 0): v['conditions'] = {conditions} continue depvar = all_conds[0][0].name all_one_var = all((((len(cond) == 1) and (cond[0].name == depvar)) for cond in all_conds)) if all_one_var: conds = [cond[0] for cond in all_conds] if (frozenset(conds) == potential_conds[depvar]): v['conditions'] = {conditions} continue
def _remove_allpaths(hps, conditions): 'Hacky way to recognize some kinds of false dependencies\n Better would be logic programming.\n ' potential_conds = {} for (k, v) in list(hps.items()): if (v['node'].name == 'randint'): low = v['node'].arg['low'].obj domain_size = ((v['node'].arg['high'].obj - low) if (v['node'].arg['high'] != MissingArgument) else low) potential_conds[k] = frozenset([EQ(k, ii) for ii in range(domain_size)]) elif (v['node'].name == 'categorical'): p = v['node'].arg['p'].obj potential_conds[k] = frozenset([EQ(k, ii) for ii in range(p.size)]) for (k, v) in list(hps.items()): if (len(v['conditions']) > 1): all_conds = [[c for c in cond if (c is not True)] for cond in v['conditions']] all_conds = [cond for cond in all_conds if (len(cond) >= 1)] if (len(all_conds) == 0): v['conditions'] = {conditions} continue depvar = all_conds[0][0].name all_one_var = all((((len(cond) == 1) and (cond[0].name == depvar)) for cond in all_conds)) if all_one_var: conds = [cond[0] for cond in all_conds] if (frozenset(conds) == potential_conds[depvar]): v['conditions'] = {conditions} continue<|docstring|>Hacky way to recognize some kinds of false dependencies Better would be logic programming.<|endoftext|>
0acc8293ae430d45b58e029fc06ef7fe51785b9ef6823b66cf74f680cbf0c8c5
@pytest.fixture def repository_under_test(): '\n Create database resource and mock table\n ' with moto.mock_dynamodb2(): job_repository_under_test = JobRepository() JobRepository().create_table_if_not_exists() (yield job_repository_under_test) JobRepository().delete_table()
Create database resource and mock table
pipeline_control/tests/offline/adapters/job_repository/job_repository_fixtures.py
repository_under_test
aws-samples/financial-crimes-discovery-using-graph-database
0
python
@pytest.fixture def repository_under_test(): '\n \n ' with moto.mock_dynamodb2(): job_repository_under_test = JobRepository() JobRepository().create_table_if_not_exists() (yield job_repository_under_test) JobRepository().delete_table()
@pytest.fixture def repository_under_test(): '\n \n ' with moto.mock_dynamodb2(): job_repository_under_test = JobRepository() JobRepository().create_table_if_not_exists() (yield job_repository_under_test) JobRepository().delete_table()<|docstring|>Create database resource and mock table<|endoftext|>
5607a2b1122691e441177424da9b73aaeec78b8eed18b1aa1ddf42ec9ec320f9
@moto.mock_dynamodb2 @pytest.fixture def small_test_job(repository_under_test, create_test_job): '\n Create database resource and mock table\n ' job_repository_under_test = repository_under_test job_id = create_test_job yield_val = job_id (yield yield_val) job_repository_under_test.delete_job_by_id(job_id)
Create database resource and mock table
pipeline_control/tests/offline/adapters/job_repository/job_repository_fixtures.py
small_test_job
aws-samples/financial-crimes-discovery-using-graph-database
0
python
@moto.mock_dynamodb2 @pytest.fixture def small_test_job(repository_under_test, create_test_job): '\n \n ' job_repository_under_test = repository_under_test job_id = create_test_job yield_val = job_id (yield yield_val) job_repository_under_test.delete_job_by_id(job_id)
@moto.mock_dynamodb2 @pytest.fixture def small_test_job(repository_under_test, create_test_job): '\n \n ' job_repository_under_test = repository_under_test job_id = create_test_job yield_val = job_id (yield yield_val) job_repository_under_test.delete_job_by_id(job_id)<|docstring|>Create database resource and mock table<|endoftext|>
789eb1214bbba9928724adff3fe55f4084521d1a1788c21690a3e537f4c98061
def work(self, Task, input_q, output_q, meta_q): '\n The main processing loop for `task`.\n ' task = Task(num_workers=self.num_workers, task_id=self.task_id) input_job = input_q._link_mem() output_job = output_q._link_mem() meta_buffer = meta_q._link_mem() id_buffer = meta_buffer['id'] data_buffer = meta_buffer['data'] id_buffer[:] = [task.id, self.id, 1][:] start_time = time_ns() data_buffer[:] = [start_time, start_time][:] assert (meta_q.put() is not BaseQueue.Full), 'meta q should always put (prejob)' id_buffer[(- 1)] = 0 job_map = task.create_map(self, input_job, output_job) input_status = BaseQueue.Empty while (not self.EXIT_FLAG): if ((input_status := input_q.get()) is BaseQueue.Empty): continue elif (input_status is BaseQueue.Closed): break data_buffer[0] = time_ns() job_map() data_buffer[1] = time_ns() assert (meta_q.put() is not BaseQueue.Full), 'meta q should always put' t = time_ns() while (output_q.put() is BaseQueue.Full): pass task.cleanup() finish_time = time_ns() id_buffer[(- 1)] = 1 data_buffer[:] = [start_time, finish_time][:] meta_q.put() print(f'Worker Done -- Task: {task.name} | ID: {self.id}')
The main processing loop for `task`.
src/ptlib/core/worker.py
work
jfw225/ptlib
1
python
def work(self, Task, input_q, output_q, meta_q): '\n \n ' task = Task(num_workers=self.num_workers, task_id=self.task_id) input_job = input_q._link_mem() output_job = output_q._link_mem() meta_buffer = meta_q._link_mem() id_buffer = meta_buffer['id'] data_buffer = meta_buffer['data'] id_buffer[:] = [task.id, self.id, 1][:] start_time = time_ns() data_buffer[:] = [start_time, start_time][:] assert (meta_q.put() is not BaseQueue.Full), 'meta q should always put (prejob)' id_buffer[(- 1)] = 0 job_map = task.create_map(self, input_job, output_job) input_status = BaseQueue.Empty while (not self.EXIT_FLAG): if ((input_status := input_q.get()) is BaseQueue.Empty): continue elif (input_status is BaseQueue.Closed): break data_buffer[0] = time_ns() job_map() data_buffer[1] = time_ns() assert (meta_q.put() is not BaseQueue.Full), 'meta q should always put' t = time_ns() while (output_q.put() is BaseQueue.Full): pass task.cleanup() finish_time = time_ns() id_buffer[(- 1)] = 1 data_buffer[:] = [start_time, finish_time][:] meta_q.put() print(f'Worker Done -- Task: {task.name} | ID: {self.id}')
def work(self, Task, input_q, output_q, meta_q): '\n \n ' task = Task(num_workers=self.num_workers, task_id=self.task_id) input_job = input_q._link_mem() output_job = output_q._link_mem() meta_buffer = meta_q._link_mem() id_buffer = meta_buffer['id'] data_buffer = meta_buffer['data'] id_buffer[:] = [task.id, self.id, 1][:] start_time = time_ns() data_buffer[:] = [start_time, start_time][:] assert (meta_q.put() is not BaseQueue.Full), 'meta q should always put (prejob)' id_buffer[(- 1)] = 0 job_map = task.create_map(self, input_job, output_job) input_status = BaseQueue.Empty while (not self.EXIT_FLAG): if ((input_status := input_q.get()) is BaseQueue.Empty): continue elif (input_status is BaseQueue.Closed): break data_buffer[0] = time_ns() job_map() data_buffer[1] = time_ns() assert (meta_q.put() is not BaseQueue.Full), 'meta q should always put' t = time_ns() while (output_q.put() is BaseQueue.Full): pass task.cleanup() finish_time = time_ns() id_buffer[(- 1)] = 1 data_buffer[:] = [start_time, finish_time][:] meta_q.put() print(f'Worker Done -- Task: {task.name} | ID: {self.id}')<|docstring|>The main processing loop for `task`.<|endoftext|>
bc753c7bfe8333095fe494857991e7269f4135687ebd8b6c0f9535f24ad6c34d
def _get_arc_wcs_center(arc: DXFGraphic) -> Vector: ' Returns the center of an ARC or CIRCLE as WCS coordinates. ' center = arc.dxf.center if arc.dxf.hasattr('extrusion'): ocs = arc.ocs() return ocs.to_wcs(center) else: return center
Returns the center of an ARC or CIRCLE as WCS coordinates.
src/ezdxf/addons/drawing/frontend.py
_get_arc_wcs_center
George-Jiang/ezdxf
0
python
def _get_arc_wcs_center(arc: DXFGraphic) -> Vector: ' ' center = arc.dxf.center if arc.dxf.hasattr('extrusion'): ocs = arc.ocs() return ocs.to_wcs(center) else: return center
def _get_arc_wcs_center(arc: DXFGraphic) -> Vector: ' ' center = arc.dxf.center if arc.dxf.hasattr('extrusion'): ocs = arc.ocs() return ocs.to_wcs(center) else: return center<|docstring|>Returns the center of an ARC or CIRCLE as WCS coordinates.<|endoftext|>
fd0c1ac69c36dca37d7f5daf22a3b1e18963bcbb463489803785e88a83427f6b
def decode_batch(self, window, location): "\n Resizing each output image window in the batch as an image volume\n location specifies the original input image (so that the\n interpolation order, original shape information retained in the\n\n generated outputs).For the fields that have the keyword 'window' in the\n dictionary key, it will be saved as image. The rest will be saved as\n csv. CSV files will contain at saving a first line of 0 (to be\n changed into the header by the user), the first column being the\n index of the window, followed by the list of output.\n\n " n_samples = location.shape[0] for batch_id in range(n_samples): if self._is_stopping_signal(location[batch_id]): return False self.image_id = location[(batch_id, 0)] (self.image_out, self.csv_out) = ({}, {}) for key in window: if ('window' in key): while (window[key].ndim < 5): window[key] = window[key][(..., np.newaxis, :)] self.image_out[key] = window[key][(batch_id, ...)] else: window[key] = np.asarray(window[key]).reshape([n_samples, (- 1)]) n_elements = window[key].shape[(- 1)] table_header = (['{}_{}'.format(key, idx) for idx in range(n_elements)] if (n_elements > 1) else ['{}'.format(key)]) self.csv_out[key] = self._initialise_empty_csv(key_names=table_header) csv_row = window[key][(batch_id:(batch_id + 1), :)].ravel() self.csv_out[key] = self.csv_out[key].append(OrderedDict(zip(table_header, csv_row)), ignore_index=True) self._save_current_image() self._save_current_csv() return True
Resizing each output image window in the batch as an image volume location specifies the original input image (so that the interpolation order, original shape information retained in the generated outputs).For the fields that have the keyword 'window' in the dictionary key, it will be saved as image. The rest will be saved as csv. CSV files will contain at saving a first line of 0 (to be changed into the header by the user), the first column being the index of the window, followed by the list of output.
niftynet/engine/windows_aggregator_resize.py
decode_batch
tdml13/NiftyNet
1,403
python
def decode_batch(self, window, location): "\n Resizing each output image window in the batch as an image volume\n location specifies the original input image (so that the\n interpolation order, original shape information retained in the\n\n generated outputs).For the fields that have the keyword 'window' in the\n dictionary key, it will be saved as image. The rest will be saved as\n csv. CSV files will contain at saving a first line of 0 (to be\n changed into the header by the user), the first column being the\n index of the window, followed by the list of output.\n\n " n_samples = location.shape[0] for batch_id in range(n_samples): if self._is_stopping_signal(location[batch_id]): return False self.image_id = location[(batch_id, 0)] (self.image_out, self.csv_out) = ({}, {}) for key in window: if ('window' in key): while (window[key].ndim < 5): window[key] = window[key][(..., np.newaxis, :)] self.image_out[key] = window[key][(batch_id, ...)] else: window[key] = np.asarray(window[key]).reshape([n_samples, (- 1)]) n_elements = window[key].shape[(- 1)] table_header = (['{}_{}'.format(key, idx) for idx in range(n_elements)] if (n_elements > 1) else ['{}'.format(key)]) self.csv_out[key] = self._initialise_empty_csv(key_names=table_header) csv_row = window[key][(batch_id:(batch_id + 1), :)].ravel() self.csv_out[key] = self.csv_out[key].append(OrderedDict(zip(table_header, csv_row)), ignore_index=True) self._save_current_image() self._save_current_csv() return True
def decode_batch(self, window, location): "\n Resizing each output image window in the batch as an image volume\n location specifies the original input image (so that the\n interpolation order, original shape information retained in the\n\n generated outputs).For the fields that have the keyword 'window' in the\n dictionary key, it will be saved as image. The rest will be saved as\n csv. CSV files will contain at saving a first line of 0 (to be\n changed into the header by the user), the first column being the\n index of the window, followed by the list of output.\n\n " n_samples = location.shape[0] for batch_id in range(n_samples): if self._is_stopping_signal(location[batch_id]): return False self.image_id = location[(batch_id, 0)] (self.image_out, self.csv_out) = ({}, {}) for key in window: if ('window' in key): while (window[key].ndim < 5): window[key] = window[key][(..., np.newaxis, :)] self.image_out[key] = window[key][(batch_id, ...)] else: window[key] = np.asarray(window[key]).reshape([n_samples, (- 1)]) n_elements = window[key].shape[(- 1)] table_header = (['{}_{}'.format(key, idx) for idx in range(n_elements)] if (n_elements > 1) else ['{}'.format(key)]) self.csv_out[key] = self._initialise_empty_csv(key_names=table_header) csv_row = window[key][(batch_id:(batch_id + 1), :)].ravel() self.csv_out[key] = self.csv_out[key].append(OrderedDict(zip(table_header, csv_row)), ignore_index=True) self._save_current_image() self._save_current_csv() return True<|docstring|>Resizing each output image window in the batch as an image volume location specifies the original input image (so that the interpolation order, original shape information retained in the generated outputs).For the fields that have the keyword 'window' in the dictionary key, it will be saved as image. The rest will be saved as csv. CSV files will contain at saving a first line of 0 (to be changed into the header by the user), the first column being the index of the window, followed by the list of output.<|endoftext|>
4d8de853c0bf1ce722b6845edca4930eae5edf655dfb504b396e081776c33522
def _initialise_image_shape(self, image_id, n_channels): '\n Return the shape of the empty image to be saved\n :param image_id: index to find the appropriate input image from the\n reader\n :param n_channels: number of channels of the image\n :return: shape of the empty image\n ' self.image_id = image_id spatial_shape = self.input_image[self.name].shape[:3] output_image_shape = (spatial_shape + (1, n_channels)) empty_image = np.zeros(output_image_shape, dtype=np.bool) for layer in self.reader.preprocessors: if isinstance(layer, PadLayer): (empty_image, _) = layer(empty_image) return empty_image.shape
Return the shape of the empty image to be saved :param image_id: index to find the appropriate input image from the reader :param n_channels: number of channels of the image :return: shape of the empty image
niftynet/engine/windows_aggregator_resize.py
_initialise_image_shape
tdml13/NiftyNet
1,403
python
def _initialise_image_shape(self, image_id, n_channels): '\n Return the shape of the empty image to be saved\n :param image_id: index to find the appropriate input image from the\n reader\n :param n_channels: number of channels of the image\n :return: shape of the empty image\n ' self.image_id = image_id spatial_shape = self.input_image[self.name].shape[:3] output_image_shape = (spatial_shape + (1, n_channels)) empty_image = np.zeros(output_image_shape, dtype=np.bool) for layer in self.reader.preprocessors: if isinstance(layer, PadLayer): (empty_image, _) = layer(empty_image) return empty_image.shape
def _initialise_image_shape(self, image_id, n_channels): '\n Return the shape of the empty image to be saved\n :param image_id: index to find the appropriate input image from the\n reader\n :param n_channels: number of channels of the image\n :return: shape of the empty image\n ' self.image_id = image_id spatial_shape = self.input_image[self.name].shape[:3] output_image_shape = (spatial_shape + (1, n_channels)) empty_image = np.zeros(output_image_shape, dtype=np.bool) for layer in self.reader.preprocessors: if isinstance(layer, PadLayer): (empty_image, _) = layer(empty_image) return empty_image.shape<|docstring|>Return the shape of the empty image to be saved :param image_id: index to find the appropriate input image from the reader :param n_channels: number of channels of the image :return: shape of the empty image<|endoftext|>
eaae58ae11d8b10d11537dedf5ebc481ba151a07bb0e91dba20dee545348852f
def _save_current_image(self): '\n Loop through the dictionary of images output and resize and reverse\n the preprocessing prior to saving\n :return:\n ' if (self.input_image is None): return self.current_out = {} for i in self.image_out: resize_to_shape = self._initialise_image_shape(image_id=self.image_id, n_channels=self.image_out[i].shape[(- 1)]) window_shape = resize_to_shape current_out = self.image_out[i] while (current_out.ndim < 5): current_out = current_out[(..., np.newaxis, :)] if (self.window_border and any([(b > 0) for b in self.window_border])): np_border = self.window_border while (len(np_border) < 5): np_border = (np_border + (0,)) np_border = [(b,) for b in np_border] current_out = np.pad(current_out, np_border, mode='edge') image_shape = current_out.shape zoom_ratio = [(float(p) / float(d)) for (p, d) in zip(window_shape, image_shape)] image_shape = (list(image_shape[:3]) + [1, image_shape[(- 1)]]) current_out = np.reshape(current_out, image_shape) current_out = zoom_3d(image=current_out, ratio=zoom_ratio, interp_order=self.output_interp_order) self.current_out[i] = current_out for layer in reversed(self.reader.preprocessors): if isinstance(layer, PadLayer): for i in self.image_out: (self.current_out[i], _) = layer.inverse_op(self.current_out[i]) if isinstance(layer, DiscreteLabelNormalisationLayer): for i in self.image_out: (self.image_out[i], _) = layer.inverse_op(self.image_out[i]) subject_name = self.reader.get_subject_id(self.image_id) for i in self.image_out: filename = '{}_{}_{}.nii.gz'.format(i, subject_name, self.postfix) source_image_obj = self.input_image[self.name] misc_io.save_data_array(self.output_path, filename, self.current_out[i], source_image_obj, self.output_interp_order) self.log_inferred(subject_name, filename) return
Loop through the dictionary of images output and resize and reverse the preprocessing prior to saving :return:
niftynet/engine/windows_aggregator_resize.py
_save_current_image
tdml13/NiftyNet
1,403
python
def _save_current_image(self): '\n Loop through the dictionary of images output and resize and reverse\n the preprocessing prior to saving\n :return:\n ' if (self.input_image is None): return self.current_out = {} for i in self.image_out: resize_to_shape = self._initialise_image_shape(image_id=self.image_id, n_channels=self.image_out[i].shape[(- 1)]) window_shape = resize_to_shape current_out = self.image_out[i] while (current_out.ndim < 5): current_out = current_out[(..., np.newaxis, :)] if (self.window_border and any([(b > 0) for b in self.window_border])): np_border = self.window_border while (len(np_border) < 5): np_border = (np_border + (0,)) np_border = [(b,) for b in np_border] current_out = np.pad(current_out, np_border, mode='edge') image_shape = current_out.shape zoom_ratio = [(float(p) / float(d)) for (p, d) in zip(window_shape, image_shape)] image_shape = (list(image_shape[:3]) + [1, image_shape[(- 1)]]) current_out = np.reshape(current_out, image_shape) current_out = zoom_3d(image=current_out, ratio=zoom_ratio, interp_order=self.output_interp_order) self.current_out[i] = current_out for layer in reversed(self.reader.preprocessors): if isinstance(layer, PadLayer): for i in self.image_out: (self.current_out[i], _) = layer.inverse_op(self.current_out[i]) if isinstance(layer, DiscreteLabelNormalisationLayer): for i in self.image_out: (self.image_out[i], _) = layer.inverse_op(self.image_out[i]) subject_name = self.reader.get_subject_id(self.image_id) for i in self.image_out: filename = '{}_{}_{}.nii.gz'.format(i, subject_name, self.postfix) source_image_obj = self.input_image[self.name] misc_io.save_data_array(self.output_path, filename, self.current_out[i], source_image_obj, self.output_interp_order) self.log_inferred(subject_name, filename) return
def _save_current_image(self): '\n Loop through the dictionary of images output and resize and reverse\n the preprocessing prior to saving\n :return:\n ' if (self.input_image is None): return self.current_out = {} for i in self.image_out: resize_to_shape = self._initialise_image_shape(image_id=self.image_id, n_channels=self.image_out[i].shape[(- 1)]) window_shape = resize_to_shape current_out = self.image_out[i] while (current_out.ndim < 5): current_out = current_out[(..., np.newaxis, :)] if (self.window_border and any([(b > 0) for b in self.window_border])): np_border = self.window_border while (len(np_border) < 5): np_border = (np_border + (0,)) np_border = [(b,) for b in np_border] current_out = np.pad(current_out, np_border, mode='edge') image_shape = current_out.shape zoom_ratio = [(float(p) / float(d)) for (p, d) in zip(window_shape, image_shape)] image_shape = (list(image_shape[:3]) + [1, image_shape[(- 1)]]) current_out = np.reshape(current_out, image_shape) current_out = zoom_3d(image=current_out, ratio=zoom_ratio, interp_order=self.output_interp_order) self.current_out[i] = current_out for layer in reversed(self.reader.preprocessors): if isinstance(layer, PadLayer): for i in self.image_out: (self.current_out[i], _) = layer.inverse_op(self.current_out[i]) if isinstance(layer, DiscreteLabelNormalisationLayer): for i in self.image_out: (self.image_out[i], _) = layer.inverse_op(self.image_out[i]) subject_name = self.reader.get_subject_id(self.image_id) for i in self.image_out: filename = '{}_{}_{}.nii.gz'.format(i, subject_name, self.postfix) source_image_obj = self.input_image[self.name] misc_io.save_data_array(self.output_path, filename, self.current_out[i], source_image_obj, self.output_interp_order) self.log_inferred(subject_name, filename) return<|docstring|>Loop through the dictionary of images output and resize and reverse the preprocessing prior to saving :return:<|endoftext|>
76b107f9ad040fe71d0db30d9d156df138ef48eff9de6ade5002043f2b1201b4
def _save_current_csv(self): '\n Save all csv output present in the dictionary of csv_output.\n :return:\n ' if (self.input_image is None): return subject_name = self.reader.get_subject_id(self.image_id) for i in self.csv_out: filename = '{}_{}_{}.csv'.format(i, subject_name, self.postfix) misc_io.save_csv_array(self.output_path, filename, self.csv_out[i]) self.log_inferred(subject_name, filename) return
Save all csv output present in the dictionary of csv_output. :return:
niftynet/engine/windows_aggregator_resize.py
_save_current_csv
tdml13/NiftyNet
1,403
python
def _save_current_csv(self): '\n Save all csv output present in the dictionary of csv_output.\n :return:\n ' if (self.input_image is None): return subject_name = self.reader.get_subject_id(self.image_id) for i in self.csv_out: filename = '{}_{}_{}.csv'.format(i, subject_name, self.postfix) misc_io.save_csv_array(self.output_path, filename, self.csv_out[i]) self.log_inferred(subject_name, filename) return
def _save_current_csv(self): '\n Save all csv output present in the dictionary of csv_output.\n :return:\n ' if (self.input_image is None): return subject_name = self.reader.get_subject_id(self.image_id) for i in self.csv_out: filename = '{}_{}_{}.csv'.format(i, subject_name, self.postfix) misc_io.save_csv_array(self.output_path, filename, self.csv_out[i]) self.log_inferred(subject_name, filename) return<|docstring|>Save all csv output present in the dictionary of csv_output. :return:<|endoftext|>
2040bd978444c28e290456023f799fe4636e2eff378b5934a972e537df5b2226
def _initialise_empty_csv(self, key_names): '\n Initialise the array to be saved as csv as a line of zeros according\n to the number of elements to be saved\n :param n_channel:\n :return:\n ' return pd.DataFrame(columns=key_names)
Initialise the array to be saved as csv as a line of zeros according to the number of elements to be saved :param n_channel: :return:
niftynet/engine/windows_aggregator_resize.py
_initialise_empty_csv
tdml13/NiftyNet
1,403
python
def _initialise_empty_csv(self, key_names): '\n Initialise the array to be saved as csv as a line of zeros according\n to the number of elements to be saved\n :param n_channel:\n :return:\n ' return pd.DataFrame(columns=key_names)
def _initialise_empty_csv(self, key_names): '\n Initialise the array to be saved as csv as a line of zeros according\n to the number of elements to be saved\n :param n_channel:\n :return:\n ' return pd.DataFrame(columns=key_names)<|docstring|>Initialise the array to be saved as csv as a line of zeros according to the number of elements to be saved :param n_channel: :return:<|endoftext|>
4d975713eab09dc6fc4ffe1f1d05b403d18576cadc8e03fb35650cbd2748d54e
def get_language_for_file(filename: str) -> str: '\n Get the language for a file based on its extension or suffix.\n :param filename: the filename of the file\n :return: the language of the file\n ' for (suffix, language) in SUFFIX_TO_LANGUAGE.items(): if filename.endswith(suffix): return language for (prefix, language) in PREFIX_TO_LANGUAGE.items(): if filename.startswith(prefix): return language return None
Get the language for a file based on its extension or suffix. :param filename: the filename of the file :return: the language of the file
codiga/utils/file_utils.py
get_language_for_file
codiga/clitool
2
python
def get_language_for_file(filename: str) -> str: '\n Get the language for a file based on its extension or suffix.\n :param filename: the filename of the file\n :return: the language of the file\n ' for (suffix, language) in SUFFIX_TO_LANGUAGE.items(): if filename.endswith(suffix): return language for (prefix, language) in PREFIX_TO_LANGUAGE.items(): if filename.startswith(prefix): return language return None
def get_language_for_file(filename: str) -> str: '\n Get the language for a file based on its extension or suffix.\n :param filename: the filename of the file\n :return: the language of the file\n ' for (suffix, language) in SUFFIX_TO_LANGUAGE.items(): if filename.endswith(suffix): return language for (prefix, language) in PREFIX_TO_LANGUAGE.items(): if filename.startswith(prefix): return language return None<|docstring|>Get the language for a file based on its extension or suffix. :param filename: the filename of the file :return: the language of the file<|endoftext|>
de4591ed62b4c365bb84e7451a79902eb604fa49a6620d5aaf696803e1d9f300
def associate_files_with_language(filenames: Set[str]) -> Dict[(str, str)]: '\n For a list of filenames, check the language associated with them and returns a dictionary that associate\n the filename and the language. If the filename does not have a matching language, just return.\n :param filenames: the list of filenames\n :return: a dictionary that associates the filenames with their languages.\n ' filenames_to_languages: Dict[(str, str)] = dict() for filename in filenames: language = get_language_for_file(filename) if language: filenames_to_languages[filename] = language return filenames_to_languages
For a list of filenames, check the language associated with them and returns a dictionary that associate the filename and the language. If the filename does not have a matching language, just return. :param filenames: the list of filenames :return: a dictionary that associates the filenames with their languages.
codiga/utils/file_utils.py
associate_files_with_language
codiga/clitool
2
python
def associate_files_with_language(filenames: Set[str]) -> Dict[(str, str)]: '\n For a list of filenames, check the language associated with them and returns a dictionary that associate\n the filename and the language. If the filename does not have a matching language, just return.\n :param filenames: the list of filenames\n :return: a dictionary that associates the filenames with their languages.\n ' filenames_to_languages: Dict[(str, str)] = dict() for filename in filenames: language = get_language_for_file(filename) if language: filenames_to_languages[filename] = language return filenames_to_languages
def associate_files_with_language(filenames: Set[str]) -> Dict[(str, str)]: '\n For a list of filenames, check the language associated with them and returns a dictionary that associate\n the filename and the language. If the filename does not have a matching language, just return.\n :param filenames: the list of filenames\n :return: a dictionary that associates the filenames with their languages.\n ' filenames_to_languages: Dict[(str, str)] = dict() for filename in filenames: language = get_language_for_file(filename) if language: filenames_to_languages[filename] = language return filenames_to_languages<|docstring|>For a list of filenames, check the language associated with them and returns a dictionary that associate the filename and the language. If the filename does not have a matching language, just return. :param filenames: the list of filenames :return: a dictionary that associates the filenames with their languages.<|endoftext|>
14bc4a65c3ed73cbee9eec67ebcb12afc394412879e2d634110b61d7b55acb66
def assertShapeCorrect(self, batcher, name): '\n interval should be 2D, with shape [batch_size, input_length]\n signal should be 3d, with shape [batch_size, input_length, input_channel]\n label should be 3d, wish shape [batch_size, output_length, out_channel]\n ' batch_size = (int((np.random.rand() * 100)) + 1) for method in [batcher.next_train, batcher.next_test]: (interval, signal, label) = method(batch_size) interval = np.array(interval) shape = (batch_size, batcher.input_length) self.assertTupleEqual(interval.shape, shape, ((((name + ' Interval Dimension Error: ') + str(interval.shape)) + ' vs. ') + str(shape))) signal = np.array(signal) shape = (batch_size, batcher.input_length, batcher.input_channel) self.assertTupleEqual(signal.shape, shape, ((((name + ' Signal Dimension Error: ') + str(signal.shape)) + ' vs. ') + str(shape))) label = np.array(label) shape = (batch_size, batcher.output_length, batcher.output_channel) self.assertTupleEqual(label.shape, shape, ((((name + ' Label Dimension Error: ') + str(label.shape)) + ' vs. ') + str(shape)))
interval should be 2D, with shape [batch_size, input_length] signal should be 3d, with shape [batch_size, input_length, input_channel] label should be 3d, wish shape [batch_size, output_length, out_channel]
Data/batcher_unittest.py
assertShapeCorrect
shihui2010/continuous_cnn
0
python
def assertShapeCorrect(self, batcher, name): '\n interval should be 2D, with shape [batch_size, input_length]\n signal should be 3d, with shape [batch_size, input_length, input_channel]\n label should be 3d, wish shape [batch_size, output_length, out_channel]\n ' batch_size = (int((np.random.rand() * 100)) + 1) for method in [batcher.next_train, batcher.next_test]: (interval, signal, label) = method(batch_size) interval = np.array(interval) shape = (batch_size, batcher.input_length) self.assertTupleEqual(interval.shape, shape, ((((name + ' Interval Dimension Error: ') + str(interval.shape)) + ' vs. ') + str(shape))) signal = np.array(signal) shape = (batch_size, batcher.input_length, batcher.input_channel) self.assertTupleEqual(signal.shape, shape, ((((name + ' Signal Dimension Error: ') + str(signal.shape)) + ' vs. ') + str(shape))) label = np.array(label) shape = (batch_size, batcher.output_length, batcher.output_channel) self.assertTupleEqual(label.shape, shape, ((((name + ' Label Dimension Error: ') + str(label.shape)) + ' vs. ') + str(shape)))
def assertShapeCorrect(self, batcher, name): '\n interval should be 2D, with shape [batch_size, input_length]\n signal should be 3d, with shape [batch_size, input_length, input_channel]\n label should be 3d, wish shape [batch_size, output_length, out_channel]\n ' batch_size = (int((np.random.rand() * 100)) + 1) for method in [batcher.next_train, batcher.next_test]: (interval, signal, label) = method(batch_size) interval = np.array(interval) shape = (batch_size, batcher.input_length) self.assertTupleEqual(interval.shape, shape, ((((name + ' Interval Dimension Error: ') + str(interval.shape)) + ' vs. ') + str(shape))) signal = np.array(signal) shape = (batch_size, batcher.input_length, batcher.input_channel) self.assertTupleEqual(signal.shape, shape, ((((name + ' Signal Dimension Error: ') + str(signal.shape)) + ' vs. ') + str(shape))) label = np.array(label) shape = (batch_size, batcher.output_length, batcher.output_channel) self.assertTupleEqual(label.shape, shape, ((((name + ' Label Dimension Error: ') + str(label.shape)) + ' vs. ') + str(shape)))<|docstring|>interval should be 2D, with shape [batch_size, input_length] signal should be 3d, with shape [batch_size, input_length, input_channel] label should be 3d, wish shape [batch_size, output_length, out_channel]<|endoftext|>
5576c16958e02a44f4d9a24e8aa2bc6b8f62dd52686a83adfec6681b505f2e57
def DoTasksForSimulation(snaps=[], tasks=[], task_params=[], interp_fac=1, nproc=1, nthreads=1): '\n Main CrunchSnaps routine, performs a list of tasks using (possibly interpolated) time series simulation data\n snaps - list of paths of simulation snapshots\n tasks - list of tasks to perform at each simulation time\n task_params - shape [N_tasks,N_params] list of dictionaries containing the parameters for each task - if only (N_tasks,) list is provided this will be broadcast\n ' if ((len(snaps) == 0) or (len(tasks) == 0)): return snaps = natsorted(snaps) N_tasks = len(tasks) if ((len(tasks) > 1) and task_params): for i in range(len(task_params)): if (type(tasks[i]) == dict): tasks[i] = [tasks[i], tasks[i]] elif (type(tasks[i]) == list): if (len(tasks[i]) < N_tasks): tasks[i] = [tasks[0], tasks[0]] (snaptimes, snapnums) = ([], []) print('getting snapshot timeline...') for s in snaps: with h5py.File(s, 'r') as F: snaptimes.append(F['Header'].attrs['Time']) snapnums.append(int(s.split('snapshot_')[1].split('.hdf5')[0])) print('done!') snaptimes = np.array(snaptimes) snapdict = dict(zip(snaptimes, snaps)) if ((not task_params) or (type(task_params) == dict)): N_params = (len(snaps) * interp_fac) if (interp_fac > 1): params_times = np.interp((np.arange(N_params) / interp_fac), np.arange((N_params // interp_fac)), snaptimes) else: params_times = snaptimes if (not task_params): task_params = [[{'Time': params_times[i], 'index': i, 'threads': nthreads} for i in range(N_params)] for t in tasks] else: task_params_orig = task_params.copy() task_params = [[task_params_orig.copy() for i in range(N_params)] for t in tasks] [[task_params[j][i].update({'Time': params_times[i], 'index': i, 'threads': nthreads}) for i in range(N_params)] for j in range(N_tasks)] else: N_params = len(task_params[0]) index_chunks = np.array_split(np.arange(N_params), nproc) chunks = [(index_chunks[i], tasks, snaps, task_params, snapdict, snaptimes, snapnums) for i in range(nproc)] if (nproc > 1): Pool(nproc).map(DoParamsPass, chunks, chunksize=1) else: [DoParamsPass(c) for c in chunks]
Main CrunchSnaps routine, performs a list of tasks using (possibly interpolated) time series simulation data snaps - list of paths of simulation snapshots tasks - list of tasks to perform at each simulation time task_params - shape [N_tasks,N_params] list of dictionaries containing the parameters for each task - if only (N_tasks,) list is provided this will be broadcast
src/CrunchSnaps/CrunchSnaps.py
DoTasksForSimulation
mikegrudic/CrunchSnaps
2
python
def DoTasksForSimulation(snaps=[], tasks=[], task_params=[], interp_fac=1, nproc=1, nthreads=1): '\n Main CrunchSnaps routine, performs a list of tasks using (possibly interpolated) time series simulation data\n snaps - list of paths of simulation snapshots\n tasks - list of tasks to perform at each simulation time\n task_params - shape [N_tasks,N_params] list of dictionaries containing the parameters for each task - if only (N_tasks,) list is provided this will be broadcast\n ' if ((len(snaps) == 0) or (len(tasks) == 0)): return snaps = natsorted(snaps) N_tasks = len(tasks) if ((len(tasks) > 1) and task_params): for i in range(len(task_params)): if (type(tasks[i]) == dict): tasks[i] = [tasks[i], tasks[i]] elif (type(tasks[i]) == list): if (len(tasks[i]) < N_tasks): tasks[i] = [tasks[0], tasks[0]] (snaptimes, snapnums) = ([], []) print('getting snapshot timeline...') for s in snaps: with h5py.File(s, 'r') as F: snaptimes.append(F['Header'].attrs['Time']) snapnums.append(int(s.split('snapshot_')[1].split('.hdf5')[0])) print('done!') snaptimes = np.array(snaptimes) snapdict = dict(zip(snaptimes, snaps)) if ((not task_params) or (type(task_params) == dict)): N_params = (len(snaps) * interp_fac) if (interp_fac > 1): params_times = np.interp((np.arange(N_params) / interp_fac), np.arange((N_params // interp_fac)), snaptimes) else: params_times = snaptimes if (not task_params): task_params = [[{'Time': params_times[i], 'index': i, 'threads': nthreads} for i in range(N_params)] for t in tasks] else: task_params_orig = task_params.copy() task_params = [[task_params_orig.copy() for i in range(N_params)] for t in tasks] [[task_params[j][i].update({'Time': params_times[i], 'index': i, 'threads': nthreads}) for i in range(N_params)] for j in range(N_tasks)] else: N_params = len(task_params[0]) index_chunks = np.array_split(np.arange(N_params), nproc) chunks = [(index_chunks[i], tasks, snaps, task_params, snapdict, snaptimes, snapnums) for i in range(nproc)] if (nproc > 1): Pool(nproc).map(DoParamsPass, chunks, chunksize=1) else: [DoParamsPass(c) for c in chunks]
def DoTasksForSimulation(snaps=[], tasks=[], task_params=[], interp_fac=1, nproc=1, nthreads=1): '\n Main CrunchSnaps routine, performs a list of tasks using (possibly interpolated) time series simulation data\n snaps - list of paths of simulation snapshots\n tasks - list of tasks to perform at each simulation time\n task_params - shape [N_tasks,N_params] list of dictionaries containing the parameters for each task - if only (N_tasks,) list is provided this will be broadcast\n ' if ((len(snaps) == 0) or (len(tasks) == 0)): return snaps = natsorted(snaps) N_tasks = len(tasks) if ((len(tasks) > 1) and task_params): for i in range(len(task_params)): if (type(tasks[i]) == dict): tasks[i] = [tasks[i], tasks[i]] elif (type(tasks[i]) == list): if (len(tasks[i]) < N_tasks): tasks[i] = [tasks[0], tasks[0]] (snaptimes, snapnums) = ([], []) print('getting snapshot timeline...') for s in snaps: with h5py.File(s, 'r') as F: snaptimes.append(F['Header'].attrs['Time']) snapnums.append(int(s.split('snapshot_')[1].split('.hdf5')[0])) print('done!') snaptimes = np.array(snaptimes) snapdict = dict(zip(snaptimes, snaps)) if ((not task_params) or (type(task_params) == dict)): N_params = (len(snaps) * interp_fac) if (interp_fac > 1): params_times = np.interp((np.arange(N_params) / interp_fac), np.arange((N_params // interp_fac)), snaptimes) else: params_times = snaptimes if (not task_params): task_params = [[{'Time': params_times[i], 'index': i, 'threads': nthreads} for i in range(N_params)] for t in tasks] else: task_params_orig = task_params.copy() task_params = [[task_params_orig.copy() for i in range(N_params)] for t in tasks] [[task_params[j][i].update({'Time': params_times[i], 'index': i, 'threads': nthreads}) for i in range(N_params)] for j in range(N_tasks)] else: N_params = len(task_params[0]) index_chunks = np.array_split(np.arange(N_params), nproc) chunks = [(index_chunks[i], tasks, snaps, task_params, snapdict, snaptimes, snapnums) for i in range(nproc)] if (nproc > 1): Pool(nproc).map(DoParamsPass, chunks, chunksize=1) else: [DoParamsPass(c) for c in chunks]<|docstring|>Main CrunchSnaps routine, performs a list of tasks using (possibly interpolated) time series simulation data snaps - list of paths of simulation snapshots tasks - list of tasks to perform at each simulation time task_params - shape [N_tasks,N_params] list of dictionaries containing the parameters for each task - if only (N_tasks,) list is provided this will be broadcast<|endoftext|>
44273c0844eeace9cbbe7d904e69d28744e7bb6ceed6dfdd3ab44c3a5400d22c
def hermitian(A): 'Returns the Hermitian transpose of an array\n\n Args:\n A (jax.numpy.ndarray): An array\n\n Returns:\n (jax.numpy.ndarray): An array: :math:`A^H`\n ' return jnp.conjugate(A.T)
Returns the Hermitian transpose of an array Args: A (jax.numpy.ndarray): An array Returns: (jax.numpy.ndarray): An array: :math:`A^H`
src/cr/nimble/_src/array.py
hermitian
carnotresearch/cr-nimble
2
python
def hermitian(A): 'Returns the Hermitian transpose of an array\n\n Args:\n A (jax.numpy.ndarray): An array\n\n Returns:\n (jax.numpy.ndarray): An array: :math:`A^H`\n ' return jnp.conjugate(A.T)
def hermitian(A): 'Returns the Hermitian transpose of an array\n\n Args:\n A (jax.numpy.ndarray): An array\n\n Returns:\n (jax.numpy.ndarray): An array: :math:`A^H`\n ' return jnp.conjugate(A.T)<|docstring|>Returns the Hermitian transpose of an array Args: A (jax.numpy.ndarray): An array Returns: (jax.numpy.ndarray): An array: :math:`A^H`<|endoftext|>
24870817433e03a8a75e31e4c993976fbb1fe92950e71e639e894e347004073c
def check_shapes_are_equal(array1, array2): 'Raise an error if the shapes of the two arrays do not match.\n \n Raises:\n ValueError: if the shape of two arrays is not same\n ' if (not (array1.shape == array2.shape)): raise ValueError('Input arrays must have the same shape.') return
Raise an error if the shapes of the two arrays do not match. Raises: ValueError: if the shape of two arrays is not same
src/cr/nimble/_src/array.py
check_shapes_are_equal
carnotresearch/cr-nimble
2
python
def check_shapes_are_equal(array1, array2): 'Raise an error if the shapes of the two arrays do not match.\n \n Raises:\n ValueError: if the shape of two arrays is not same\n ' if (not (array1.shape == array2.shape)): raise ValueError('Input arrays must have the same shape.') return
def check_shapes_are_equal(array1, array2): 'Raise an error if the shapes of the two arrays do not match.\n \n Raises:\n ValueError: if the shape of two arrays is not same\n ' if (not (array1.shape == array2.shape)): raise ValueError('Input arrays must have the same shape.') return<|docstring|>Raise an error if the shapes of the two arrays do not match. Raises: ValueError: if the shape of two arrays is not same<|endoftext|>
7b43ee2553a1e2ac63a4be9ccb1bd166efe4a18d4b8d2ee67faf9ebe0f284487
def destroy_database(pathname: str) -> None: 'if you can, delete the whole database file. If not, show an error message.' try: if (not os.path.exists(pathname)): messagebox.showerror('Error al eliminar', f'''Parece que no se puede eliminar '{pathname}' porque este archivo no existe. ¿No ha eliminado previamente esta base de datos? Verifique o intente de nuevo.''') return None os.remove(pathname) ensureDatabase(pathname) messagebox.showinfo('Proceso terminado', 'El proceso ha terminado exitosamente. La base de datos fue eliminada.') except Exception as e: messagebox.showerror('Error al eliminar', f'''Parece que no se puede eliminar el archivo '{pathname}'. Verifique que no haya otros programas abriendo este archivo o no se encuentre bajo otros procesos. (Error reportado '{str(e)}')''')
if you can, delete the whole database file. If not, show an error message.
delete-db.py
destroy_database
ControlDeAgua/ControlDeAgua
2
python
def destroy_database(pathname: str) -> None: try: if (not os.path.exists(pathname)): messagebox.showerror('Error al eliminar', f'Parece que no se puede eliminar '{pathname}' porque este archivo no existe. ¿No ha eliminado previamente esta base de datos? Verifique o intente de nuevo.') return None os.remove(pathname) ensureDatabase(pathname) messagebox.showinfo('Proceso terminado', 'El proceso ha terminado exitosamente. La base de datos fue eliminada.') except Exception as e: messagebox.showerror('Error al eliminar', f'Parece que no se puede eliminar el archivo '{pathname}'. Verifique que no haya otros programas abriendo este archivo o no se encuentre bajo otros procesos. (Error reportado '{str(e)}')')
def destroy_database(pathname: str) -> None: try: if (not os.path.exists(pathname)): messagebox.showerror('Error al eliminar', f'Parece que no se puede eliminar '{pathname}' porque este archivo no existe. ¿No ha eliminado previamente esta base de datos? Verifique o intente de nuevo.') return None os.remove(pathname) ensureDatabase(pathname) messagebox.showinfo('Proceso terminado', 'El proceso ha terminado exitosamente. La base de datos fue eliminada.') except Exception as e: messagebox.showerror('Error al eliminar', f'Parece que no se puede eliminar el archivo '{pathname}'. Verifique que no haya otros programas abriendo este archivo o no se encuentre bajo otros procesos. (Error reportado '{str(e)}')')<|docstring|>if you can, delete the whole database file. If not, show an error message.<|endoftext|>
5e3750ff157db40d3c949958d73c6cd40fab92ddeea78e1ad44283fdbb31b81a
def __init__(self, root: Optional[Tk]=None) -> None: 'generate the interface.' if (not isinstance(root, Tk)): self.root = Tk() else: self.root = root windowmanager.windowTitle(self.root, 'Opciones para Eliminar la base de datos') self.build()
generate the interface.
delete-db.py
__init__
ControlDeAgua/ControlDeAgua
2
python
def __init__(self, root: Optional[Tk]=None) -> None: if (not isinstance(root, Tk)): self.root = Tk() else: self.root = root windowmanager.windowTitle(self.root, 'Opciones para Eliminar la base de datos') self.build()
def __init__(self, root: Optional[Tk]=None) -> None: if (not isinstance(root, Tk)): self.root = Tk() else: self.root = root windowmanager.windowTitle(self.root, 'Opciones para Eliminar la base de datos') self.build()<|docstring|>generate the interface.<|endoftext|>
9081c856b12e6e4b8349447a2778796119414bc31fbaa52d8d1430d3ce48bec0
def loop(self) -> None: 'use this if the Tk root was generated inside.' self.root.mainloop()
use this if the Tk root was generated inside.
delete-db.py
loop
ControlDeAgua/ControlDeAgua
2
python
def loop(self) -> None: self.root.mainloop()
def loop(self) -> None: self.root.mainloop()<|docstring|>use this if the Tk root was generated inside.<|endoftext|>
94fab186424c2fbbbce674287ffb91a780b0a8b34012978b5692ba7616ddabb6
def build(self) -> None: 'create the GUI' self.frame = Frame(self.root) self.frame.grid() destroy_label = Label(self.frame, text=self.__doc__, bg='whitesmoke', fg='black', font=('Calibri', '15', 'bold')).grid(row=0, column=0, sticky='ew') destroy_b = Button(self.frame, text='Eliminar base de datos', bg='red', fg='white', font=('Calibri', '12', 'bold'), command=self.destroy).grid(row=1, column=0, sticky='ew') view_b = Button(self.frame, text='Abrir base de datos', bg='gray', fg='white', font=('Calibri', '12', 'bold'), command=self.gotoDB).grid(row=2, column=0, sticky='ew') safe_b = Button(self.frame, text='Salir', bg='gray', fg='white', font=('Calibri', '12', 'bold'), command=self.root.quit).grid(row=3, column=0, sticky='ew')
create the GUI
delete-db.py
build
ControlDeAgua/ControlDeAgua
2
python
def build(self) -> None: self.frame = Frame(self.root) self.frame.grid() destroy_label = Label(self.frame, text=self.__doc__, bg='whitesmoke', fg='black', font=('Calibri', '15', 'bold')).grid(row=0, column=0, sticky='ew') destroy_b = Button(self.frame, text='Eliminar base de datos', bg='red', fg='white', font=('Calibri', '12', 'bold'), command=self.destroy).grid(row=1, column=0, sticky='ew') view_b = Button(self.frame, text='Abrir base de datos', bg='gray', fg='white', font=('Calibri', '12', 'bold'), command=self.gotoDB).grid(row=2, column=0, sticky='ew') safe_b = Button(self.frame, text='Salir', bg='gray', fg='white', font=('Calibri', '12', 'bold'), command=self.root.quit).grid(row=3, column=0, sticky='ew')
def build(self) -> None: self.frame = Frame(self.root) self.frame.grid() destroy_label = Label(self.frame, text=self.__doc__, bg='whitesmoke', fg='black', font=('Calibri', '15', 'bold')).grid(row=0, column=0, sticky='ew') destroy_b = Button(self.frame, text='Eliminar base de datos', bg='red', fg='white', font=('Calibri', '12', 'bold'), command=self.destroy).grid(row=1, column=0, sticky='ew') view_b = Button(self.frame, text='Abrir base de datos', bg='gray', fg='white', font=('Calibri', '12', 'bold'), command=self.gotoDB).grid(row=2, column=0, sticky='ew') safe_b = Button(self.frame, text='Salir', bg='gray', fg='white', font=('Calibri', '12', 'bold'), command=self.root.quit).grid(row=3, column=0, sticky='ew')<|docstring|>create the GUI<|endoftext|>
de8c6b0e8e7101e165eb31f4dad28a8400186fc346427562aed94db6c48a1b57
def destroy(self) -> None: 'just... destroy the whole database! This is a danger zone, ok? be careful' if messagebox.askyesno('¿Proceder?', f'''¿Eliminar la base de datos? (Este proceso no se puede deshacer)'''): destroy_database(PathName) else: messagebox.showinfo('Proceso cancelado', 'No se ha eliminado el archivo.')
just... destroy the whole database! This is a danger zone, ok? be careful
delete-db.py
destroy
ControlDeAgua/ControlDeAgua
2
python
def destroy(self) -> None: if messagebox.askyesno('¿Proceder?', f'¿Eliminar la base de datos? (Este proceso no se puede deshacer)'): destroy_database(PathName) else: messagebox.showinfo('Proceso cancelado', 'No se ha eliminado el archivo.')
def destroy(self) -> None: if messagebox.askyesno('¿Proceder?', f'¿Eliminar la base de datos? (Este proceso no se puede deshacer)'): destroy_database(PathName) else: messagebox.showinfo('Proceso cancelado', 'No se ha eliminado el archivo.')<|docstring|>just... destroy the whole database! This is a danger zone, ok? be careful<|endoftext|>
da1e2d1b3b2b81d4b2a07e22d32b01bae39b0551c6f20d59f44d65b6dd983fff
def gotoDB(self) -> None: 'go to the database' try: os.startfile(PathName) except: messagebox.showerror('No se pudo abrir', 'Verifique e intente de nuevo')
go to the database
delete-db.py
gotoDB
ControlDeAgua/ControlDeAgua
2
python
def gotoDB(self) -> None: try: os.startfile(PathName) except: messagebox.showerror('No se pudo abrir', 'Verifique e intente de nuevo')
def gotoDB(self) -> None: try: os.startfile(PathName) except: messagebox.showerror('No se pudo abrir', 'Verifique e intente de nuevo')<|docstring|>go to the database<|endoftext|>
f1540e4ccf0b132e8a2177a45d1c7d88b8c1035c4bbb6118135e446d38d3d4af
def __init__(self, root=None): '\n Construct a BinaryTree, possibly with a single element in it.\n but for the BST (and other tree types) we can.\n ' if root: self.root = Node(root) else: self.root = None
Construct a BinaryTree, possibly with a single element in it. but for the BST (and other tree types) we can.
containers/BinaryTree.py
__init__
vbopardi/Week8Containers
0
python
def __init__(self, root=None): '\n Construct a BinaryTree, possibly with a single element in it.\n but for the BST (and other tree types) we can.\n ' if root: self.root = Node(root) else: self.root = None
def __init__(self, root=None): '\n Construct a BinaryTree, possibly with a single element in it.\n but for the BST (and other tree types) we can.\n ' if root: self.root = Node(root) else: self.root = None<|docstring|>Construct a BinaryTree, possibly with a single element in it. but for the BST (and other tree types) we can.<|endoftext|>
91cfae51df82eec03440e9d88048ad24de16e0694580f1b08b9f5575ee3bb9c5
def __str__(self): '\n We can visualize a tree by visualizing its root node.\n ' return str(self.root)
We can visualize a tree by visualizing its root node.
containers/BinaryTree.py
__str__
vbopardi/Week8Containers
0
python
def __str__(self): '\n \n ' return str(self.root)
def __str__(self): '\n \n ' return str(self.root)<|docstring|>We can visualize a tree by visualizing its root node.<|endoftext|>