def test_fig_nrgf(smap): radial_bin_edges = utils.equally_spaced_bins() radial_bin_edges *= u.R_sun out = rad.nrgf(smap, radial_bin_edges) out.plot()
def test_bin_edge_summary(): esb = equally_spaced_bins() center = bin_edge_summary(esb, "center") assert center.shape == (100,) assert center[0] == 1.005 assert center[99] == 1.995 left = bin_edge_summary(esb, "left") assert left.shape == (100,) assert left[0] == 1.0 assert left[99] == 1.99 right = bin_edge_summary(esb, "right") assert right.shape == (100,) assert right[0] == 1.01 assert right[99] == 2.0 # Correct selection of summary type with pytest.raises(ValueError): bin_edge_summary(esb, "should raise the error") # The correct shape of bin edges are passed in with pytest.raises(ValueError): bin_edge_summary(np.arange(0, 10), "center") with pytest.raises(ValueError): bin_edge_summary(np.zeros((3, 4)), "center")
def test_get_radial_intensity_summary(smap): radial_bin_edges = u.Quantity( utils.equally_spaced_bins(inner_value=1, outer_value=1.5)) * u.R_sun summary = np.mean map_r = utils.find_pixel_radii(smap, scale=smap.rsun_obs).to(u.R_sun) nbins = radial_bin_edges.shape[1] lower_edge = [ map_r > radial_bin_edges[0, i].to(u.R_sun) for i in range(0, nbins) ] upper_edge = [ map_r < radial_bin_edges[1, i].to(u.R_sun) for i in range(0, nbins) ] with warnings.catch_warnings(): # We want to ignore RuntimeWarning: Mean of empty slice warnings.simplefilter("ignore", category=RuntimeWarning) expected = np.asarray([ summary(smap.data[lower_edge[i] * upper_edge[i]]) for i in range(0, nbins) ]) assert np.allclose( utils.get_radial_intensity_summary(smap=smap, radial_bin_edges=radial_bin_edges), expected)
def test_fig_fnrgf(smap): radial_bin_edges = utils.equally_spaced_bins() radial_bin_edges *= u.R_sun order = 20 attenuation_coefficients = rad.set_attenuation_coefficients(order) out = rad.fnrgf(smap, radial_bin_edges, order, attenuation_coefficients) out.plot()
def test_equally_spaced_bins(): # test the default esb = equally_spaced_bins() assert esb.shape == (2, 100) assert esb[0, 0] == 1.0 assert esb[1, 0] == 1.01 assert esb[0, 99] == 1.99 assert esb[1, 99] == 2.00 # Bins are 0.015 wide esb2 = equally_spaced_bins(inner_value=0.5) assert esb2.shape == (2, 100) assert esb2[0, 0] == 0.5 assert esb2[1, 0] == 0.515 assert esb2[0, 99] == 1.985 assert esb2[1, 99] == 2.00 # Bins are 0.2 wide esb2 = equally_spaced_bins(outer_value=3.0) assert esb2.shape == (2, 100) assert esb2[0, 0] == 1.0 assert esb2[1, 0] == 1.02 assert esb2[0, 99] == 2.98 assert esb2[1, 99] == 3.00 # Bins are 0.01 wide esb2 = equally_spaced_bins(nbins=1000) assert esb2.shape == (2, 1000) assert esb2[0, 0] == 1.0 assert esb2[1, 0] == 1.001 assert esb2[0, 999] == 1.999 assert esb2[1, 999] == 2.000 # The radii have the correct relative sizes with pytest.raises(ValueError): equally_spaced_bins(inner_value=1.0, outer_value=1.0) with pytest.raises(ValueError): equally_spaced_bins(inner_value=1.5, outer_value=1.0) # The number of bins is strictly greater than 0 with pytest.raises(ValueError): equally_spaced_bins(nbins=0)
def test_intensity_enhance(map_test1): degree = 1 fit_range = [1, 1.5] * u.R_sun normalization_radius = 1 * u.R_sun summarize_bin_edges = "center" scale = 1 * map_test1.rsun_obs radial_bin_edges = u.Quantity(utils.equally_spaced_bins()) * u.R_sun radial_intensity = utils.get_radial_intensity_summary(map_test1, radial_bin_edges, scale=scale) map_r = utils.find_pixel_radii(map_test1).to(u.R_sun) radial_bin_summary = utils.bin_edge_summary( radial_bin_edges, summarize_bin_edges).to(u.R_sun) fit_here = np.logical_and( fit_range[0].to(u.R_sun).value <= radial_bin_summary.to(u.R_sun).value, radial_bin_summary.to(u.R_sun).value <= fit_range[1].to(u.R_sun).value, ) polynomial = rad.fit_polynomial_to_log_radial_intensity( radial_bin_summary[fit_here], radial_intensity[fit_here], degree) enhancement = 1 / rad.normalize_fit_radial_intensity( map_r, polynomial, normalization_radius) enhancement[map_r < normalization_radius] = 1 with pytest.raises(ValueError, match="The fit range must be strictly increasing."): rad.intensity_enhance(smap=map_test1, radial_bin_edges=radial_bin_edges, scale=scale, fit_range=fit_range[::-1]) assert np.allclose( enhancement * map_test1.data, rad.intensity_enhance(smap=map_test1, radial_bin_edges=radial_bin_edges, scale=scale).data, )
def fnrgf( smap, radial_bin_edges, order, attenuation_coefficients, ratio_mix=[15, 1], scale=None, intensity_summary=np.nanmean, intensity_summary_kwargs={}, width_function=np.std, width_function_kwargs={}, application_radius=1 * u.R_sun, number_angular_segments=130, ): """ Implementation of the fourier normalizing radial gradient filter (FNRGF). The filter works as follows: Fourier Normalizing Radial Gradient Filter approximates the local average and the local standard deviation by a finite Fourier series. This method enables the enhancement of finer details, especially in regions of lower contrast. It takes the input map and divides the region above the application radius and in the radial bins into various small angular segments. Then for each of these angular segments, the intensity summary and width is calculated. The intensity summary and the width of each angular segments are then used to find a Fourier approximation of the intensity summary and width for the entire radial bin, this Fourier approximated value is then used to noramlize the intensity in the radial bin. .. note:: After applying the filter, current plot settings such as the image normalization may have to be changed in order to obtain a good-looking plot. Parameters ---------- smap : `sunpy.map.Map` A SunPy map. radial_bin_edges : `astropy.units.Quantity` A two-dimensional array of bin edges of size ``[2, nbins]`` where ``nbins`` is the number of bins. order : `int` Order (number) of fourier coefficients and it can not be lower than 1. attenuation_coefficients : `float` A two dimensional array of shape ``[2, order + 1]``. The first row contain attenuation coefficients for mean calculations. The second row contains attenuation coefficients for standard deviation calculation. ratio_mix : `float`, optional A one dimensional array of shape ``[2, 1]`` with values equal to ``[K1, K2]``. The ratio in which the original image and filtered image are mixed. Defaults to ``[15, 1]``. scale : `None` or `astropy.units.Quantity`, optional The radius of the Sun expressed in map units. For example, in typical helioprojective Cartesian maps the solar radius is expressed in units of arcseconds. If `None` (the default), then the map scale is used. intensity_summary :`function`, optional A function that returns a summary statistic of the radial intensity. Default is `numpy.nanmean`. intensity_summary_kwargs : `None`, `~dict` Keywords applicable to the summary function. width_function : `function` A function that returns a summary statistic of the distribution of intensity, at a given radius. Defaults to `numpy.std`. width_function_kwargs : `function` Keywords applicable to the width function. application_radius : `astropy.units.Quantity` The FNRGF is applied to emission at radii above the application_radius. Defaults to 1 solar radii. number_angular_segments : `int` Number of angular segments in a circular annulus. Defaults to 130. Returns ------- `sunpy.map.Map` A SunPy map that has had the FNRGF applied to it. References ---------- * Morgan, Habbal & Druckmüllerová, 2011, Astrophysical Journal 737, 88. https://iopscience.iop.org/article/10.1088/0004-637X/737/2/88/pdf. * The implementation is highly inspired by this doctoral thesis. DRUCKMÜLLEROVÁ, H. Application of adaptive filters in processing of solar corona images. https://dspace.vutbr.cz/bitstream/handle/11012/34520/DoctoralThesis.pdf. """ if order < 1: raise ValueError("Minimum value of order is 1") # Get the radii for every pixel map_r = find_pixel_radii(smap).to(u.R_sun) # To make sure bins are in the map. if radial_bin_edges[1, -1] > np.max(map_r): radial_bin_edges = equally_spaced_bins( inner_value=radial_bin_edges[0, 0], outer_value=np.max(map_r), nbins=radial_bin_edges.shape[1] ) # Get the Helioprojective coordinates of each pixel x, y = np.meshgrid(*[np.arange(v.value) for v in smap.dimensions]) * u.pix coords = smap.pixel_to_world(x, y).transform_to(frames.Helioprojective) # Get angles associated with every pixel angles = np.arctan2(coords.Ty.value, coords.Tx.value) # Making sure all angles are between (0, 2 * pi) angles = np.where(angles < 0, angles + (2 * np.pi), angles) # Number of radial bins nbins = radial_bin_edges.shape[1] # Storage for the filtered data data = np.zeros_like(smap.data) # Iterate over each circular ring for i in range(0, nbins): # Finding the pixels which belong to a certain circular ring annulus = np.logical_and(map_r >= radial_bin_edges[0, i], map_r < radial_bin_edges[1, i]) annulus = np.logical_and(annulus, map_r > application_radius) # The angle subtended by each segment segment_angle = 2 * np.pi / number_angular_segments # Storage of mean and standard deviation of each segment in a circular ring average_segments = np.zeros((1, number_angular_segments)) std_dev = np.zeros((1, number_angular_segments)) # Calculating sin and cos of the angles to be multiplied with the means and standard # deviations to give the fourier approximation cos_matrix = np.cos( np.array( [ [(2 * np.pi * (j + 1) * (i + 0.5)) / number_angular_segments for j in range(order)] for i in range(number_angular_segments) ] ) ) sin_matrix = np.sin( np.array( [ [(2 * np.pi * (j + 1) * (i + 0.5)) / number_angular_segments for j in range(order)] for i in range(number_angular_segments) ] ) ) # Iterate over each segment in a circular ring for j in range(0, number_angular_segments, 1): # Finding all the pixels whose angle values lie in the segment angular_segment = np.logical_and(angles >= segment_angle * j, angles < segment_angle * (j + 1)) # Finding the particular segment in the circular ring annulus_segment = np.logical_and(annulus, angular_segment) # Finding mean and standard deviation in each segnment. If takes care of the empty # slices. if np.sum([annulus_segment > 0]) == 0: average_segments[0, j] = 0 std_dev[0, j] = 0 else: average_segments[0, j] = intensity_summary(smap.data[annulus_segment]) std_dev[0, j] = width_function(smap.data[annulus_segment]) # Calculating the fourier coefficients multiplied with the attenuation coefficients # Refer to equation (2), (3), (4), (5) in the paper fourier_coefficient_a_0 = np.sum(average_segments) * (2 / number_angular_segments) fourier_coefficient_a_0 *= attenuation_coefficients[0, 1] fourier_coefficients_a_k = np.matmul(average_segments, cos_matrix) * (2 / number_angular_segments) fourier_coefficients_a_k *= attenuation_coefficients[0][1:] fourier_coefficients_b_k = np.matmul(average_segments, sin_matrix) * (2 / number_angular_segments) fourier_coefficients_b_k *= attenuation_coefficients[0][1:] # Refer to equation (6) in the paper fourier_coefficient_c_0 = np.sum(std_dev) * (2 / number_angular_segments) fourier_coefficient_c_0 *= attenuation_coefficients[1, 1] fourier_coefficients_c_k = np.matmul(std_dev, cos_matrix) * (2 / number_angular_segments) fourier_coefficients_c_k *= attenuation_coefficients[1][1:] fourier_coefficients_d_k = np.matmul(std_dev, sin_matrix) * (2 / number_angular_segments) fourier_coefficients_d_k *= attenuation_coefficients[1][1:] # To calculate the multiples of angles of each pixel for finding the fourier approximation # at that point. See equations 6.8 and 6.9 of the doctoral thesis. K_matrix = np.ones((order, np.sum(annulus > 0))) * np.array(range(1, order + 1)).T.reshape(order, 1) phi_matrix = angles[annulus].reshape((1, angles[annulus].shape[0])) angles_of_pixel = K_matrix * phi_matrix # Get the approxiamted value of mean mean_approximated = np.matmul(fourier_coefficients_a_k, np.cos(angles_of_pixel)) mean_approximated += np.matmul(fourier_coefficients_b_k, np.sin(angles_of_pixel)) mean_approximated += fourier_coefficient_a_0 / 2 # Get the approxiamted value of standard deviation std_approximated = np.matmul(fourier_coefficients_c_k, np.cos(angles_of_pixel)) std_approximated += np.matmul(fourier_coefficients_d_k, np.sin(angles_of_pixel)) std_approximated += fourier_coefficient_c_0 / 2 # Normailize the data # Refer equation (7) in the paper std_approximated = np.where(std_approximated == 0.00, 1, std_approximated) data[annulus] = np.ravel((smap.data[annulus] - mean_approximated) / std_approximated) # Linear combination of original image and the filtered data. data[annulus] = ratio_mix[0] * smap.data[annulus] + ratio_mix[1] * data[annulus] return sunpy.map.Map(data, smap.meta)
def nrgf( smap, radial_bin_edges, scale=None, intensity_summary=np.nanmean, intensity_summary_kwargs={}, width_function=np.std, width_function_kwargs={}, application_radius=1 * u.R_sun, ): """ Implementation of the normalizing radial gradient filter (NRGF). The filter works as follows: Normalizing Radial Gradient Filter a simple filter for removing the radial gradient to reveal coronal structure. Applied to polarized brightness observations of the corona, the NRGF produces images which are striking in their detail. It takes the input map and find the intensity summary and width of intenstiy values in radial bins above the application radius. The intensity summary and the width is then used to normalize the intensity values in a particular radial bin. .. note:: After applying the filter, current plot settings such as the image normalization may have to be changed in order to obtain a good-looking plot. Parameters ---------- smap : `sunpy.map.Map` The SunPy map to enchance. radial_bin_edges : `astropy.units.Quantity` A two-dimensional array of bin edges of size ``[2, nbins]`` where ``nbins`` is the number of bins. scale : None or `astropy.units.Quantity`, optional The radius of the Sun expressed in map units. For example, in typical Helioprojective Cartesian maps the solar radius is expressed in units of arcseconds. Defaults to None, which means that the map scale is used. intensity_summary : `function`, optional A function that returns a summary statistic of the radial intensity. Defaults to `numpy.nanmean`. intensity_summary_kwargs : `dict`, optional Keywords applicable to the summary function. width_function : `function`, optional A function that returns a summary statistic of the distribution of intensity, at a given radius. Defaults to `numpy.std`. width_function_kwargs : `function`, optional Keywords applicable to the width function. application_radius : `astropy.units.Quantity`, optional The NRGF is applied to emission at radii above the application_radius. Defaults to 1 solar radii. Returns ------- `sunpy.map.Map` A SunPy map that has had the NRGF applied to it. References ---------- * Morgan, Habbal & Woo, 2006, Sol. Phys., 236, 263. https://link.springer.com/article/10.1007%2Fs11207-006-0113-6 """ # Get the radii for every pixel map_r = find_pixel_radii(smap).to(u.R_sun) # To make sure bins are in the map. if radial_bin_edges[1, -1] > np.max(map_r): radial_bin_edges = equally_spaced_bins( inner_value=radial_bin_edges[0, 0], outer_value=np.max(map_r), nbins=radial_bin_edges.shape[1] ) # Radial intensity radial_intensity = get_radial_intensity_summary( smap, radial_bin_edges, scale=scale, summary=intensity_summary, **intensity_summary_kwargs ) # An estimate of the width of the intensity distribution in each radial bin. radial_intensity_distribution_summary = get_radial_intensity_summary( smap, radial_bin_edges, scale=scale, summary=width_function, **width_function_kwargs ) # Storage for the filtered data data = np.zeros_like(smap.data) # Calculate the filter value for each radial bin. for i in range(0, radial_bin_edges.shape[1]): here = np.logical_and(map_r >= radial_bin_edges[0, i], map_r < radial_bin_edges[1, i]) here = np.logical_and(here, map_r > application_radius) data[here] = smap.data[here] - radial_intensity[i] if radial_intensity_distribution_summary[i] != 0.0: data[here] = data[here] / radial_intensity_distribution_summary[i] return sunpy.map.Map(data, smap.meta)
def radial_bin_edges(): radial_bins = utils.equally_spaced_bins(inner_value=0.001, outer_value=0.003, nbins=5) radial_bins = radial_bins * u.R_sun return radial_bins
########################################################################### # Sunpy's sample data contain a number of suitable FITS files for this purpose. aia_map = sunpy.map.Map(sunpy.data.sample.AIA_171_IMAGE) # The original image is plotted to showcase the difference. fig = plt.figure() ax = plt.subplot(projection=aia_map) aia_map.plot() ########################################################################### # Both the NRGF and FNRGF work on radial segments above their application radius. # Here we create those segments radial segments. Each segment created will be of # equal dimensions radially. The distance between 1 solar radii and 2 solar radii # is divided into 100 equal parts by the following two lines. radial_bin_edges = equally_spaced_bins() radial_bin_edges *= u.R_sun # The NRGF filter is applied after it. out1 = radial.nrgf(aia_map, radial_bin_edges) # The NRGF filtered map is plotted. # The image seems a little washed out so you may need to change some plotting settings # for a clearer output. fig = plt.figure() ax = plt.subplot(projection=out1) out1.plot() ########################################################################### # We will need to work out a few parameters for the FNRGF. # Order is the number of Fourier coefficients to be used in the approximation.