Esempio n. 1
0
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)
Esempio n. 2
0
def test_find_pixel_radii(smap):
    # The known maximum radius
    known_maximum_pixel_radius = 1.84183121

    # Calculate the pixel radii
    pixel_radii = find_pixel_radii(smap)

    # The shape of the pixel radii is the same as the input map
    assert pixel_radii.shape[0] == int(smap.dimensions[0].value)
    assert pixel_radii.shape[1] == int(smap.dimensions[1].value)

    # Make sure the unit is solar radii
    assert pixel_radii.unit == u.R_sun

    # Make sure the maximum
    assert_quantity_allclose((np.max(pixel_radii)).value, known_maximum_pixel_radius)

    # Test that the new scale is used
    pixel_radii = find_pixel_radii(smap, scale=2 * smap.rsun_obs)
    assert_quantity_allclose(np.max(pixel_radii).value, known_maximum_pixel_radius / 2)
Esempio n. 3
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,
    )
Esempio n. 4
0
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)
Esempio n. 5
0
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)
Esempio n. 6
0
def intensity_enhance(
    smap,
    radial_bin_edges,
    scale=None,
    summarize_bin_edges="center",
    summary=np.mean,
    degree=1,
    normalization_radius=1 * u.R_sun,
    fit_range=[1, 1.5] * u.R_sun,
    **summary_kwargs
):
    """
    Returns a SunPy Map with the intensity enhanced above a given radius.

    The enhancement is calculated as follows:

    A summary statistic of the radial dependence of the offlimb emission is calculated.
    Since the UV and EUV emission intensity drops of quickly off the solar limb, it makes sense
    to fit the log of the intensity statistic using some appropriate function.
    The function we use here is a polynomial.
    To calculate the enhancement, the fitted function is normalized to its value at the
    normalization radius from the center of the Sun (a sensible choice is the solar radius).
    The offlimb emission is then divided by this normalized function.

    .. 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 : `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.
    summarize_bin_edges : `str`, optional
        How to summarize the bin edges.
        Defaults to "center".
    summary : `function`, optional
        A function that returns a summary statistic of the radial intensity.
        Defaults to `numpy.mean`.
    degree : `int`, optional
        Degree of the polynomial fit to the log of the intensity as a function of radius.
        Defaults to 1.
    normalization_radius : `astropy.units.Quantity`, optional
        The radius at which the enhancement has value 1.
        For most cases the value of the enhancement will increase as a function of radius.
        Defaults to 1 solar radii.
    fit_range : `astropy.units.Quantity`, optional
        Array-like with 2 elements defining the range of radii over which the
        polynomial function is fit.
        The preferred units are solar radii.
        Defaults to ``[1, 1.5]`` solar radii.
    summary_kwargs : `dict`, optional
        Keywords applicable to the summary function.

    Returns
    -------
    `sunpy.map.Map`
        A SunPy map that has the emission above the normalization radius enhanced.
    """
    # Get the radii for every pixel
    map_r = find_pixel_radii(smap).to(u.R_sun)

    # Get the radial intensity distribution
    radial_intensity = get_radial_intensity_summary(
        smap, radial_bin_edges, scale=scale, summary=summary, **summary_kwargs
    )

    # Summarize the radial bins
    radial_bin_summary = bin_edge_summary(radial_bin_edges, summarize_bin_edges).to(u.R_sun)

    # Fit range
    if fit_range[0] >= fit_range[1]:
        raise ValueError("The fit range must be strictly increasing.")

    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,
    )

    # Fits a polynomial function to the natural logarithm of an estimate of
    # the intensity as a function of radius.
    polynomial = fit_polynomial_to_log_radial_intensity(
        radial_bin_summary[fit_here], radial_intensity[fit_here], degree
    )

    # Calculate the enhancement
    enhancement = 1 / normalize_fit_radial_intensity(map_r, polynomial, normalization_radius)
    enhancement[map_r < normalization_radius] = 1

    # Return a map with the intensity enhanced above the normalization radius
    # and the same meta data as the input map.
    return sunpy.map.Map(smap.data * enhancement, smap.meta)