Example #1
0
def JI_contains_full_disk(smap):
    """
    Copied from Jack Ireland's local implementation:
    https://github.com/wafels/sunpy/blob/faster_full_disk/sunpy/map/maputils.py#L127
    """
    # Calculate all the edge pixels
    top_, bottom, left_hand_side, right_hand_side = map_edges(smap)

    def _xy(ep):
        x = [p[0] for p in ep] * u.pix
        y = [p[1] for p in ep] * u.pix
        return x, y
    x, y = _xy(top_)
    horizontal1 = smap.pixel_to_world(x, y)

    x, y = _xy(bottom)
    horizontal2 = smap.pixel_to_world(x, y)

    x, y = _xy(left_hand_side)
    vertical1 = smap.pixel_to_world(x, y)

    x, y = _xy(right_hand_side)
    vertical2 = smap.pixel_to_world(x, y)

    radius = smap.rsun_obs

    # Determine the top and bottom edges of the map
    top = None
    bot = None
    if np.all(horizontal1.Ty > radius):
        top = horizontal1
    elif np.all(horizontal1.Ty < -radius):
        bot = horizontal1

    if np.all(horizontal2.Ty > radius):
        top = horizontal2
    elif np.all(horizontal2.Ty < -radius):
        bot = horizontal2

    # If either the top edge
    if top is None or bot is None:
        return False

    lhs = None
    rhs = None
    if np.all(vertical1.Tx > radius):
        rhs = vertical1
    elif np.all(vertical1.Tx < -radius):
        lhs = vertical1

    if np.all(vertical2.Tx > radius):
        rhs = vertical2
    elif np.all(vertical2.Tx < -radius):
        lhs = vertical2

    if lhs is None or rhs is None:
        return False

    return np.all(top.Ty > radius) and np.all(bot.Ty < -radius) and np.all(lhs.Tx < -radius) and np.all(rhs.Tx > radius)
def differential_rotate(smap, observer=None, time=None, **diff_rot_kwargs):
    """
    Warp a `~sunpy.map.GenericMap` to take into account both solar differential
    rotation and the changing location of the observer.

    .. warning::
        This function, while greatly improved in 1.0, is still experimental.
        Please validate that it gives you results you expect and report any
        discrepancies on the SunPy issue tracker.


    The function transforms the input map data pixels by first rotating each
    pixel according to solar differential rotation.  The amount of solar
    differential applied is calculated by the time difference between the
    observation time of map and the new observation time, as specified by either the
    "time" keyword or the "obstime" property of the "observer" keyword.
    The location of the rotated pixels are then transformed to locations on the Sun
    as seen from the new observer position.  This is desirable since in most cases
    the observer does not remain at a fixed position in space. If
    the "time" keyword is used then the new observer position is assumed to
    be based on the location of the Earth.  If the "observer" keyword is used then
    this defines the new observer position.

    The function works with full disk maps and maps that contain portions of the
    solar disk (maps that are entirely off-disk will raise an error).  When the
    input map contains the full disk, the output map has the same dimensions as
    the input map.  When the input map images only part of the solar disk, only
    the on-disk pixels are differentially rotated and the output map can have
    a different dimensions compared to the input map.  In this case any off-disk
    emission shown in the input map is not included in the output map.

    Parameters
    ----------
    smap : `~sunpy.map.GenericMap`
        Original map that we want to transform.
    observer : `~astropy.coordinates.BaseCoordinateFrame`, `~astropy.coordinates.SkyCoord`, `None`, optional
        The location of the new observer.
        Instruments in Earth orbit can be approximated by using the position
        of the Earth at the observation time of the new observer.
    time : sunpy-compatible time, `~astropy.time.TimeDelta`, `~astropy.units.Quantity`, `None`, optional
        Used to define the duration over which the amount of solar rotation is
        calculated.  If 'time' is an `~astropy.time.Time` then the time interval
        is difference between 'time' and the map observation time. If 'time' is
        `~astropy.time.TimeDelta` or `~astropy.units.Quantity` then the calculation
        is "initial_obstime + time".

    Returns
    -------
    `~sunpy.map.GenericMap`
        A map with the result of applying solar differential rotation to the
        input map.
    """
    # If the entire map is off-disk, return an error so the user is aware.
    if is_all_off_disk(smap):
        raise ValueError(
            "The entire map is off disk. No data to differentially rotate.")

    # Get the new observer
    new_observer = _get_new_observer(smap.date, observer, time)

    # Only this function needs scikit image
    from skimage import transform

    # Check whether the input contains the full disk of the Sun
    is_sub_full_disk = not contains_full_disk(smap)
    if is_sub_full_disk:
        # Find the minimal submap of the input map that includes all the
        # on disk pixels. This is required in order to calculate how
        # much to pad the output (solar-differentially rotated) data array by
        # compared to the input map.
        # The amount of padding is dependent on the amount of solar differential
        # rotation and where the on-disk pixels are (since these pixels are the only ones
        # subject to solar differential rotation).
        if not is_all_on_disk(smap):
            # Get the bottom left and top right coordinates that are the
            # vertices that define a box that encloses the on disk pixels
            bottom_left, top_right = on_disk_bounding_coordinates(smap)

            # Create a submap that excludes the off disk emission that does
            # not need to be rotated.
            smap = smap.submap(bottom_left, top_right=top_right)
        bottom_left = smap.bottom_left_coord
        top_right = smap.top_right_coord

        # Get the edges of the minimal submap that contains all the on-disk pixels.
        edges = map_edges(smap)

        # Calculate where the output array moves to.
        # Rotate the top and bottom edges
        rotated_top = _rotate_submap_edge(smap,
                                          edges[0],
                                          observer=new_observer,
                                          **diff_rot_kwargs)
        rotated_bottom = _rotate_submap_edge(smap,
                                             edges[1],
                                             observer=new_observer,
                                             **diff_rot_kwargs)

        # Rotate the left and right hand edges
        rotated_lhs = _rotate_submap_edge(smap,
                                          edges[2],
                                          observer=new_observer,
                                          **diff_rot_kwargs)
        rotated_rhs = _rotate_submap_edge(smap,
                                          edges[3],
                                          observer=new_observer,
                                          **diff_rot_kwargs)

        # Calculate the bounding box of the rotated map
        rotated_bl, rotated_tr = _get_bounding_coordinates(
            [rotated_top, rotated_bottom, rotated_lhs, rotated_rhs])

        # Calculate the maximum distance in pixels the map has moved by comparing
        # how far the original and rotated bounding boxes have moved.
        diff_x = [(np.abs(rotated_bl.Tx - bottom_left.Tx)).value,
                  (np.abs(rotated_tr.Tx - top_right.Tx)).value]
        deltax = int(np.ceil(np.max(diff_x) / smap.scale.axis1).value)

        diff_y = [(np.abs(rotated_bl.Ty - bottom_left.Ty)).value,
                  (np.abs(rotated_tr.Ty - top_right.Ty)).value]
        deltay = int(np.ceil(np.max(diff_y) / smap.scale.axis2).value)

        # Create a new `smap` with the padding around it
        padded_data = np.pad(smap.data, ((deltay, deltay), (deltax, deltax)),
                             'constant',
                             constant_values=0)
        padded_meta = deepcopy(smap.meta)
        padded_meta['naxis2'], padded_meta['naxis1'] = smap.data.shape

        padded_meta['crpix1'] += deltax
        padded_meta['crpix2'] += deltay

        # Create the padded map that will be used to create the rotated map.
        smap = smap._new_instance(padded_data, padded_meta)

    # Check for masked maps
    if smap.mask is not None:
        smap_data = np.ma.array(smap.data, mask=smap.mask)
    else:
        smap_data = smap.data

    # Create the arguments for the warp function.
    warp_args = {'smap': smap, 'new_observer': new_observer}
    warp_args.update(diff_rot_kwargs)

    # Apply solar differential rotation as a scikit-image warp
    out_data = transform.warp(smap_data,
                              inverse_map=_warp_sun_coordinates,
                              map_args=warp_args,
                              preserve_range=True,
                              cval=np.nan)

    # Update the meta information with the new date and time.
    out_meta = deepcopy(smap.meta)
    if out_meta.get('date_obs', False):
        del out_meta['date_obs']
    out_meta['date-obs'] = new_observer.obstime.strftime(
        "%Y-%m-%dT%H:%M:%S.%f")

    # Need to update the observer location for the output map.
    # Remove all the possible observer keys
    all_keys = expand_list(
        [e[0] for e in smap._supported_observer_coordinates])
    for key in all_keys:
        out_meta.pop(key)

    # Add a new HGS observer
    out_meta.update(get_observer_meta(new_observer,
                                      out_meta['rsun_ref'] * u.m))

    if is_sub_full_disk:
        # Define a new reference pixel and the value at the reference pixel.
        # Note that according to the FITS convention the first pixel in the
        # image is at (1.0, 1.0).
        center_rotated = solar_rotate_coordinate(smap.center,
                                                 observer=new_observer,
                                                 **diff_rot_kwargs)
        out_meta['crval1'] = center_rotated.Tx.value
        out_meta['crval2'] = center_rotated.Ty.value
        out_meta['crpix1'] = 1 + smap.data.shape[1]/2.0 + \
            ((center_rotated.Tx - smap.center.Tx)/smap.scale.axis1).value
        out_meta['crpix2'] = 1 + smap.data.shape[0]/2.0 + \
            ((center_rotated.Ty - smap.center.Ty)/smap.scale.axis2).value
        return smap._new_instance(out_data,
                                  out_meta).submap(rotated_bl,
                                                   top_right=rotated_tr)
    else:
        return smap._new_instance(out_data, out_meta)