Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[map branch] Reproject consistency #7603

Open
wants to merge 3 commits into
base: map_ndcube_migration
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/7586.removal.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Remove `sunpy.map.GenericMap.reproject_to` in favor of `ndcube.NDCube.reproject_to`.
180 changes: 151 additions & 29 deletions sunpy/map/mapbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,17 @@
from sunpy.image.resample import resample as sunpy_image_resample
from sunpy.image.resample import reshape_image_to_4d_superpixel
from sunpy.image.transform import _get_transform_method, _rotation_function_names, affine_transform
from sunpy.map.mixins.mapdeprecate import MapDeprecateMixin
from sunpy.map.mixins.mapmeta import MapMetaMixin
from sunpy.util import MetaDict
from sunpy.util.decorators import add_common_docstring, cached_property_based_on
from sunpy.util.decorators import (
add_common_docstring,
cached_property_based_on,
check_arithmetic_compatibility,
)
from sunpy.util.exceptions import warn_user
from sunpy.util.functools import seconddispatch
from sunpy.util.util import _figure_to_base64, fix_duplicate_notes
from sunpy.visualization.plotter.mpl_plotter import MapPlotter
from sunpy.visualization.colormaps import cm as sunpy_cm
from .mixins.mapmeta import MapMetaMixin, PixelPair

TIME_FORMAT = config.get("general", "time_format")
_NUMPY_COPY_IF_NEEDED = False if np.__version__.startswith("1.") else None
Expand Down Expand Up @@ -97,7 +100,7 @@
__all__ = ['GenericMap']


class GenericMap(MapDeprecateMixin, MapMetaMixin, NDCube):
class GenericMap(MapMetaMixin, NDCube):
"""
A Generic spatially-aware 2D data array

Expand Down Expand Up @@ -231,19 +234,26 @@ def __init__(self, data, *, wcs=None, uncertainty=None, mask=None, meta,
# TODO: This should be a function of the header, not of the map
self._validate_meta()

self.plotter = MapPlotter
self.plot_settings = {'cmap': 'gray',
'interpolation': 'nearest',
'origin': 'lower'
}
if self.dtype != np.uint8:
# Put import here to reduce sunpy.map import time
from matplotlib import colors
self.plot_settings['norm'] = colors.Normalize()
if plot_settings:
self.plotter.plot_settings.update(plot_settings)
self.plot_settings.update(plot_settings)

@property
# @deprecated('6.0', alternative='plotter.plot_settings')
def plot_settings(self):
return self.plotter.plot_settings

@plot_settings.setter
# @deprecated('6.0', alternative='plotter.plot_settings')
def plot_settings(self, value):
self.plotter.plot_settings = value
# Try and set the colormap. This is not always possible if this method
# is run before map sources fix some of their metadata, so
# just ignore any exceptions raised.
try:
cmap = self._get_cmap_name()
if cmap in sunpy_cm.cmlist:
self.plot_settings['cmap'] = cmap
except Exception:
pass

def __getitem__(self, key):
def format_slice(key):
Expand Down Expand Up @@ -285,7 +295,7 @@ def _text_summary(self):
Wavelength:\t\t {wave}
Observation Date:\t {date}
Exposure Time:\t\t {dt}
Pixel Dimensions:\t\t {dim}
Dimension:\t\t {dim}
Coordinate System:\t {coord}
Scale:\t\t\t {scale}
Reference Pixel:\t {refpix}
Expand All @@ -294,7 +304,7 @@ def _text_summary(self):
meas=measurement, wave=wave,
date=self.date.strftime(TIME_FORMAT),
dt=dt,
dim=u.Quantity(self.shape[::-1]),
dim=u.Quantity(self.dimensions),
scale=u.Quantity(self.scale),
coord=self._coordinate_frame_name,
refpix=u.Quantity(self.reference_pixel),
Expand Down Expand Up @@ -502,18 +512,13 @@ def quicklook(self):
</html>"""))
webbrowser.open_new_tab(url)

def _new_instance(self, data=None, meta=None, plot_settings=None, **kwargs):
@classmethod
def _new_instance(cls, data, meta, plot_settings=None, **kwargs):
"""
Instantiate a new instance of this class using given data.
This is a shortcut for ``type(self)(data, meta, plot_settings)``.
"""
if meta is None:
meta = copy.deepcopy(getattr(self, 'meta'))
if new_unit := kwargs.get('unit', None):
meta['bunit'] = new_unit.to_string('fits')
# NOTE: wcs=None is explicitly passed here because the wcs of a map is
# derived from the information in the metadata.
new_map = super()._new_instance(data=data, meta=meta, wcs=None, **kwargs)
new_map = cls(data, meta=meta, **kwargs)
# plot_settings are set explicitly here as some map sources
# explicitly set some of the plot_settings in the constructor
# and we want to preserve the plot_settings of the previous
Expand All @@ -535,6 +540,62 @@ def quantity(self):
"""Unitful representation of the map data."""
return u.Quantity(self.data, self.unit, copy=_NUMPY_COPY_IF_NEEDED)

def _new_instance_from_op(self, new_data):
"""
Helper function for creating new map instances after arithmetic
operations.
"""
new_meta = copy.deepcopy(self.meta)
new_meta['bunit'] = new_data.unit.to_string('fits')
return self._new_instance(new_data.value, new_meta, plot_settings=self.plot_settings)

def __neg__(self):
return self._new_instance(-self.data, self.meta, plot_settings=self.plot_settings)

@check_arithmetic_compatibility
def __pow__(self, value):
new_data = self.quantity ** value
return self._new_instance_from_op(new_data)

@check_arithmetic_compatibility
def __add__(self, value):
new_data = self.quantity + value
return self._new_instance_from_op(new_data)

def __radd__(self, value):
return self.__add__(value)

def __sub__(self, value):
return self.__add__(-value)

def __rsub__(self, value):
return self.__neg__().__add__(value)

@check_arithmetic_compatibility
def __mul__(self, value):
new_data = self.quantity * value
return self._new_instance_from_op(new_data)

def __rmul__(self, value):
return self.__mul__(value)

@check_arithmetic_compatibility
def __truediv__(self, value):
return self.__mul__(1/value)

@check_arithmetic_compatibility
def __rtruediv__(self, value):
new_data = value / self.quantity
return self._new_instance_from_op(new_data)

def _set_symmetric_vmin_vmax(self):
"""
Set symmetric vmin and vmax about zero
"""
threshold = np.nanmax(abs(self.data))
self.plot_settings['norm'].vmin = -threshold
self.plot_settings['norm'].vmax = threshold

def _as_mpl_axes(self):
"""
Compatibility hook for Matplotlib and WCSAxes.
Expand All @@ -556,6 +617,51 @@ def _as_mpl_axes(self):
# This code is reused from Astropy
return WCSAxes, {'wcs': self.wcs}

# Some numpy extraction
@property
def dimensions(self):
"""
The dimensions of the array (x axis first, y axis second).
"""
return PixelPair(*u.Quantity(np.flipud(self.data.shape), 'pixel'))

@property
def dtype(self):
"""
The `numpy.dtype` of the array of the map.
"""
return self.data.dtype

@property
def ndim(self):
"""
The value of `numpy.ndarray.ndim` of the data array of the map.
"""
return self.data.ndim

def std(self, *args, **kwargs):
"""
Calculate the standard deviation of the data array, ignoring NaNs.
"""
return np.nanstd(self.data, *args, **kwargs)

def mean(self, *args, **kwargs):
"""
Calculate the mean of the data array, ignoring NaNs.
"""
return np.nanmean(self.data, *args, **kwargs)

def min(self, *args, **kwargs):
"""
Calculate the minimum value of the data array, ignoring NaNs.
"""
return np.nanmin(self.data, *args, **kwargs)

def max(self, *args, **kwargs):
"""
Calculate the maximum value of the data array, ignoring NaNs.
"""
return np.nanmax(self.data, *args, **kwargs)

@u.quantity_input
def shift_reference_coord(self, axis1: u.deg, axis2: u.deg):
Expand Down Expand Up @@ -750,8 +856,8 @@ def resample(self, dimensions: u.pixel, method='linear'):
method, center=True)
new_data = new_data.T

scale_factor_x = float(self.shape[1] / dimensions[0].value)
scale_factor_y = float(self.shape[0] / dimensions[1].value)
scale_factor_x = float(self.dimensions[0] / dimensions[0])
scale_factor_y = float(self.dimensions[1] / dimensions[1])

# Update image scale and number of pixels
new_meta = self.meta.copy()
Expand All @@ -771,7 +877,7 @@ def resample(self, dimensions: u.pixel, method='linear'):
new_meta['naxis2'] = new_data.shape[0]

# Create new map instance
new_map = self._new_instance(data=new_data, meta=new_meta, plot_settings=self.plotter.plot_settings)
new_map = self._new_instance(new_data, new_meta, self.plot_settings)
return new_map

@add_common_docstring(rotation_function_names=_rotation_function_names)
Expand Down Expand Up @@ -1345,6 +1451,8 @@ def _process_levels_arg(self, levels):
raise u.UnitsError("This map has no unit, so levels can only be specified in percent "
"or in u.dimensionless_unscaled units.")



def contour(self, level, **kwargs):
"""
Returns coordinates of the contours for a given level value.
Expand Down Expand Up @@ -1452,6 +1560,7 @@ def reproject_to(self, target_wcs, *, algorithm='interpolation', return_footprin
raise ImportError("This method requires the optional package `reproject`.") from exc

if not isinstance(target_wcs, astropy.wcs.WCS):
<<<<<<< HEAD
target_wcs = astropy.wcs.WCS(target_wcs)

# Select the desired reprojection algorithm
Expand All @@ -1468,6 +1577,19 @@ def reproject_to(self, target_wcs, *, algorithm='interpolation', return_footprin

# Reproject the array
output_array = func(self, target_wcs, return_footprint=return_footprint, **reproject_args)
=======
target_wcs = astropy.wcs.WCS(header=target_wcs)
# Check rsun mismatch
rsun_target = target_wcs.wcs.aux.rsun_ref * u.m
if self.rsun_meters != rsun_target:
warn_user("rsun mismatch detected: "
f"{self.name}.rsun_meters={self.rsun_meters} != {rsun_target} rsun_meters of target WCS."
"This might cause unexpected results during reprojection.")
reproject_outputs = super().reproject_to(target_wcs,
algorithm=algorithm,
return_footprint=return_footprint,
**reproject_args)
>>>>>>> a555e3c3b (Adds unit to Rsun check)
if return_footprint:
output_array, footprint = output_array

Expand Down