Exemple #1
0
 def test_get_area_definition(self, file_handler, name, resolution,
                              area_exp):
     """Test getting area definitions."""
     dataset_id = make_dataid(name=name, resolution=resolution)
     area = file_handler.get_area_def(dataset_id)
     a, b = proj4_radius_parameters(area.proj_dict)
     a_exp, b_exp = proj4_radius_parameters(area_exp.proj_dict)
     assert a == a_exp
     assert b == b_exp
     assert area.width == area_exp.width
     assert area.height == area_exp.height
     for key in ['h', 'lon_0', 'proj', 'units']:
         assert area.proj_dict[key] == area_exp.proj_dict[key]
     np.testing.assert_allclose(area.area_extent, area_exp.area_extent)
Exemple #2
0
def get_geostationary_angle_extent(geos_area):
    """Get the max earth (vs space) viewing angles in x and y."""
    # TODO: take into account sweep_axis_angle parameter

    # get some projection parameters
    try:
        crs = geos_area.crs
        a = crs.ellipsoid.semi_major_metre
        b = crs.ellipsoid.semi_minor_metre
        if np.isnan(b):
            # see https://github.com/pyproj4/pyproj/issues/457
            raise AttributeError("'semi_minor_metre' attribute is not valid "
                                 "in older versions of pyproj.")
    except AttributeError:
        # older versions of pyproj don't have CRS objects
        from pyresample.utils import proj4_radius_parameters
        a, b = proj4_radius_parameters(geos_area.proj_dict)

    req = float(a) / 1000
    rp = float(b) / 1000
    h = float(geos_area.proj_dict['h']) / 1000 + req

    # compute some constants
    aeq = 1 - req**2 / (h**2)
    ap_ = 1 - rp**2 / (h**2)

    # generate points around the north hemisphere in satellite projection
    # make it a bit smaller so that we stay inside the valid area
    xmax = np.arccos(np.sqrt(aeq))
    ymax = np.arccos(np.sqrt(ap_))
    return xmax, ymax
Exemple #3
0
 def test_proj4_radius_parameters_provided(self):
     from pyresample import utils
     a, b = utils.proj4_radius_parameters(
         '+proj=stere +a=6378273 +b=6356889.44891',
     )
     np.testing.assert_almost_equal(a, 6378273)
     np.testing.assert_almost_equal(b, 6356889.44891)
Exemple #4
0
    def test_get_area_def(self):
        """Test getting the area definition."""
        self.reader.mda.update({
            'cfac': 10216334,
            'lfac': 10216334,
            'coff': 1408.0,
            'loff': 944.0,
            'number_of_lines': 464,
            'number_of_columns': 2816
        })
        dsid = make_dataid(name="CH1",
                           calibration='reflectance',
                           resolution=3000)
        area = self.reader.get_area_def(dsid)

        a, b = proj4_radius_parameters(area.proj_dict)
        assert a == EQUATOR_RADIUS
        assert b == POLE_RADIUS
        assert area.proj_dict['h'] == ALTITUDE
        assert area.proj_dict['lon_0'] == 100.1640625
        assert area.proj_dict['proj'] == 'geos'
        assert area.proj_dict['units'] == 'm'
        assert area.width == 2816
        assert area.height == 464
        assert area.area_id == 'goes-15_goes_imager_fd_3km'
        area_extent_exp = (-5639254.900260435, 1925159.4881528523,
                           5643261.475678028, 3784210.48191544)
        np.testing.assert_allclose(area.area_extent, area_extent_exp)
    def test_get_area_def(self):
        """Test getting the area def."""
        from pyresample.utils import proj4_radius_parameters
        area = self.reader.get_area_def(
            make_dataid(name='VIS006', resolution=3000))
        proj_dict = area.proj_dict
        a, b = proj4_radius_parameters(proj_dict)
        self.assertEqual(a, 6378169.0)
        self.assertAlmostEqual(b, 6356583.8)
        self.assertEqual(proj_dict['h'], 35785831.0)
        self.assertEqual(proj_dict['lon_0'], self.projection_longitude)
        self.assertEqual(proj_dict['proj'], 'geos')
        self.assertEqual(proj_dict['units'], 'm')
        self.assertEqual(area.area_extent,
                         (-77771774058.38356, -3720765401003.719,
                          30310525626438.438, 77771774058.38356))

        # Data shifted by 1.5km to N-W
        self.reader.mda['offset_corrected'] = False
        area = self.reader.get_area_def(
            make_dataid(name='VIS006', resolution=3000))
        self.assertEqual(area.area_extent,
                         (-77771772558.38356, -3720765402503.719,
                          30310525627938.438, 77771772558.38356))

        self.assertEqual(area.area_id, 'msg_seviri_rss_3km')
Exemple #6
0
def _get_pixel_size(projection_name, area_def):
    if projection_name in [
            'PLAT',
            'MERC',
    ]:
        proj = Proj(area_def.proj_dict)
        upper_left = proj(area_def.area_extent[0],
                          area_def.area_extent[3],
                          inverse=True)
        lower_right = proj(area_def.area_extent[2],
                           area_def.area_extent[1],
                           inverse=True)
        pixel_size = abs(lower_right[0] - upper_left[0]) / area_def.shape[1],\
            abs(upper_left[1] - lower_right[1]) / area_def.shape[0]

    elif projection_name in (
            'NPOL',
            'SPOL',
    ):
        a, b = proj4_radius_parameters(area_def.proj_dict)
        pixel_size = (np.rad2deg(area_def.pixel_size_x / a),
                      np.rad2deg(area_def.pixel_size_y / b))
    else:
        raise ValueError(
            "Could not determine pixel size from projection name '%s'" %
            projection_name + " (Unknown)")
    return pixel_size
Exemple #7
0
 def test_proj4_radius_parameters_ellps(self):
     from pyresample import utils
     a, b = utils.proj4_radius_parameters(
         '+proj=stere +ellps=WGS84',
     )
     np.testing.assert_almost_equal(a, 6378137.)
     np.testing.assert_almost_equal(b, 6356752.314245, decimal=6)
    def test_get_area_def(self):
        """Test getting the area def."""
        from pyresample.utils import proj4_radius_parameters
        area = self.reader.get_area_def(
            make_dataid(name='HRV', resolution=1000))
        self.assertEqual(area.area_extent,
                         (-45561979844414.07, -3720765401003.719,
                          45602912357076.38, 77771774058.38356))
        proj_dict = area.proj_dict
        a, b = proj4_radius_parameters(proj_dict)
        self.assertEqual(a, 6378169.0)
        self.assertAlmostEqual(b, 6356583.8)
        self.assertEqual(proj_dict['h'], 35785831.0)
        self.assertEqual(proj_dict['lon_0'], 0.0)
        self.assertEqual(proj_dict['proj'], 'geos')
        self.assertEqual(proj_dict['units'], 'm')
        self.reader.fill_hrv = False
        area = self.reader.get_area_def(
            make_dataid(name='HRV', resolution=1000))
        npt.assert_allclose(area.defs[0].area_extent,
                            (-22017598561055.01, -2926674655354.9604,
                             23564847539690.22, 77771774058.38356))
        npt.assert_allclose(area.defs[1].area_extent,
                            (-30793529275853.656, -3720765401003.719,
                             14788916824891.568, -2926674655354.9604))

        self.assertEqual(area.defs[0].area_id, 'msg_seviri_fes_1km')
        self.assertEqual(area.defs[1].area_id, 'msg_seviri_fes_1km')
Exemple #9
0
 def test_proj4_radius_parameters_default(self):
     from pyresample import utils
     a, b = utils.proj4_radius_parameters(
         '+proj=lcc',
     )
     # WGS84
     np.testing.assert_almost_equal(a, 6378137.)
     np.testing.assert_almost_equal(b, 6356752.314245, decimal=6)
Exemple #10
0
    def test_region(self, fromfile, np2str):
        """Test region navigation."""
        from pyresample.utils import proj4_radius_parameters
        np2str.side_effect = lambda x: x
        m = mock.mock_open()
        with mock.patch('satpy.readers.ahi_hsd.open', m, create=True):
            fh = AHIHSDFileHandler('somefile', {
                'segment': 1,
                'total_segments': 1
            },
                                   filetype_info={'file_type': 'hsd_b01'},
                                   user_calibration=None)
            fh.proj_info = {
                'CFAC': 40932549,
                'COFF': -591.5,
                'LFAC': 40932549,
                'LOFF': 5132.5,
                'blocklength': 127,
                'coeff_for_sd': 1737122264.0,
                'distance_from_earth_center': 42164.0,
                'earth_equatorial_radius': 6378.137,
                'earth_polar_radius': 6356.7523,
                'hblock_number': 3,
                'req2_rpol2': 1.006739501,
                'req2_rpol2_req2': 0.0066943844,
                'resampling_size': 4,
                'resampling_types': 0,
                'rpol2_req2': 0.993305616,
                'spare': '',
                'sub_lon': 140.7
            }

            fh.data_info = {
                'blocklength': 50,
                'compression_flag_for_data': 0,
                'hblock_number': 2,
                'number_of_bits_per_pixel': 16,
                'number_of_columns': 1000,
                'number_of_lines': 1000,
                'spare': ''
            }

            area_def = fh.get_area_def(None)
            proj_dict = area_def.proj_dict
            a, b = proj4_radius_parameters(proj_dict)
            self.assertEqual(a, 6378137.0)
            self.assertEqual(b, 6356752.3)
            self.assertEqual(proj_dict['h'], 35785863.0)
            self.assertEqual(proj_dict['lon_0'], 140.7)
            self.assertEqual(proj_dict['proj'], 'geos')
            self.assertEqual(proj_dict['units'], 'm')
            np.testing.assert_allclose(area_def.area_extent,
                                       (592000.0038256242, 4132000.0267018233,
                                        1592000.0102878273, 5132000.033164027))
Exemple #11
0
    def test_get_area_definition(self):
        """Test the retrieval of the area definition."""
        from pyresample.utils import proj4_radius_parameters
        pdict, extent = self.make_pdict_ext(1, 'N2S')
        good_res = (-3000.4032785810186, -3000.4032785810186)

        a_def = get_area_definition(pdict, extent)
        self.assertEqual(a_def.area_id, pdict['a_name'])
        self.assertEqual(a_def.resolution, good_res)
        self.assertEqual(a_def.proj_dict['proj'], 'geos')
        self.assertEqual(a_def.proj_dict['units'], 'm')
        a, b = proj4_radius_parameters(a_def.proj_dict)
        self.assertEqual(a, 6378169)
        self.assertEqual(b, 6356583.8)
        self.assertEqual(a_def.proj_dict['h'], 35785831)
Exemple #12
0
 def test_get_area_def(self):
     """Test getting an area definition."""
     from pyresample.utils import proj4_radius_parameters
     area = self.reader.get_area_def('VIS06')
     proj_dict = area.proj_dict
     a, b = proj4_radius_parameters(proj_dict)
     self.assertEqual(a, 6378169.0)
     self.assertEqual(b, 6356583.8)
     self.assertEqual(proj_dict['h'], 35785831.0)
     self.assertEqual(proj_dict['lon_0'], 44.0)
     self.assertEqual(proj_dict['proj'], 'geos')
     self.assertEqual(proj_dict['units'], 'm')
     self.assertEqual(area.area_extent,
                      (-77771774058.38356, -77771774058.38356,
                       30310525626438.438, 3720765401003.719))
Exemple #13
0
def geos2cf(area):
    """Return the cf grid mapping for the geos projection."""
    from pyresample.utils import proj4_radius_parameters
    proj_dict = area.proj_dict
    a, b = proj4_radius_parameters(proj_dict)
    args = dict(
        perspective_point_height=proj_dict.get('h'),
        latitude_of_projection_origin=proj_dict.get('lat_0', 0),
        longitude_of_projection_origin=proj_dict.get('lon_0', 0),
        grid_mapping_name='geostationary',
        semi_major_axis=a,
        semi_minor_axis=b,
        # semi_major_axis=proj_dict.get('a'),
        # semi_minor_axis=proj_dict.get('b'),
        sweep_axis=proj_dict.get('sweep'),
    )
    return args
Exemple #14
0
    def set_projection_attrs(self, area_id, proj4_info):
        """
        assign projection attributes per GRB standard
        """
        proj4_info['a'], proj4_info['b'] = proj4_radius_parameters(proj4_info)
        if proj4_info["proj"] == "geos":
            p = self.projection = self._nc.createVariable("fixedgrid_projection", 'i4')
            self.image_data.grid_mapping = "fixedgrid_projection"
            p.short_name = area_id
            p.grid_mapping_name = "geostationary"
            p.sweep_angle_axis = proj4_info.get("sweep", "y")
            p.perspective_point_height = proj4_info['h']
            p.latitude_of_projection_origin = np.float32(0.0)
            p.longitude_of_projection_origin = np.float32(proj4_info.get('lon_0', 0.0))  # is the float32 needed?
        elif proj4_info["proj"] == "lcc":
            p = self.projection = self._nc.createVariable("lambert_projection", 'i4')
            self.image_data.grid_mapping = "lambert_projection"
            p.short_name = area_id
            p.grid_mapping_name = "lambert_conformal_conic"
            p.standard_parallel = proj4_info["lat_0"]  # How do we specify two standard parallels?
            p.longitude_of_central_meridian = proj4_info["lon_0"]
            p.latitude_of_projection_origion = proj4_info.get('lat_1', proj4_info['lat_0'])  # Correct?
        elif proj4_info['proj'] == 'stere':
            p = self.projection = self._nc.createVariable("polar_projection", 'i4')
            self.image_data.grid_mapping = "polar_projection"
            p.short_name = area_id
            p.grid_mapping_name = "polar_stereographic"
            p.standard_parallel = proj4_info["lat_ts"]
            p.straight_vertical_longitude_from_pole = proj4_info.get("lon_0", 0.0)
            p.latitude_of_projection_origion = proj4_info["lat_0"]  # ?
        elif proj4_info['proj'] == 'merc':
            p = self.projection = self._nc.createVariable("mercator_projection", 'i4')
            self.image_data.grid_mapping = "mercator_projection"
            p.short_name = area_id
            p.grid_mapping_name = "mercator"
            p.standard_parallel = proj4_info.get('lat_ts', proj4_info.get('lat_0', 0.0))
            p.longitude_of_projection_origin = proj4_info.get("lon_0", 0.0)
        else:
            raise ValueError("SCMI can not handle projection '{}'".format(proj4_info['proj']))

        p.semi_major_axis = np.float64(proj4_info["a"])
        p.semi_minor_axis = np.float64(proj4_info["b"])
        p.false_easting = np.float32(proj4_info.get("x", 0.0))
        p.false_northing = np.float32(proj4_info.get("y", 0.0))
Exemple #15
0
    def test_get_area_def(self):
        """Test getting the area def."""
        from pyresample.utils import proj4_radius_parameters
        area = self.reader.get_area_def(DatasetID('VIS006'))
        proj_dict = area.proj_dict
        a, b = proj4_radius_parameters(proj_dict)
        self.assertEqual(a, 6378169.0)
        self.assertEqual(b, 6356583.8)
        self.assertEqual(proj_dict['h'], 35785831.0)
        self.assertEqual(proj_dict['lon_0'], 44.0)
        self.assertEqual(proj_dict['proj'], 'geos')
        self.assertEqual(proj_dict['units'], 'm')
        self.assertEqual(area.area_extent,
                         (-77771774058.38356, -3720765401003.719,
                          30310525626438.438, 77771774058.38356))

        # Data shifted by 1.5km to N-W
        self.reader.mda['offset_corrected'] = False
        area = self.reader.get_area_def(DatasetID('VIS006'))
        self.assertEqual(area.area_extent,
                         (-77771772558.38356, -3720765402503.719,
                          30310525627938.438, 77771772558.38356))
def ninjo_nav_parameters(options, area_def):
    """Fill options with the navigation parameter in Ninjo format."""
    # TODO: add altitude if available
    proj = Proj(area_def.proj_dict)
    upper_left = proj(
        area_def.area_extent[0],
        area_def.area_extent[3],
        inverse=True)
    lower_right = proj(
        area_def.area_extent[2],
        area_def.area_extent[1],
        inverse=True)

    # Ninjo's projection name.
    options.setdefault('projection', _get_projection_name(area_def))

    # Get pixel size
    if 'pixel_xres' not in options or 'pixel_yres' not in options:
        options['pixel_xres'], options['pixel_yres'] = \
            _get_pixel_size(options['projection'], area_def)

    options['meridian_west'] = upper_left[0]
    options['meridian_east'] = lower_right[0]
    if options['projection'].endswith("POL"):
        if 'lat_ts' in area_def.proj_dict:
            options['ref_lat1'] = area_def.proj_dict['lat_ts']
            options['ref_lat2'] = 0
    else:
        if 'lat_0' in area_def.proj_dict:
            options['ref_lat1'] = area_def.proj_dict['lat_0']
            options['ref_lat2'] = 0
    if 'lon_0' in area_def.proj_dict:
        options['central_meridian'] = area_def.proj_dict['lon_0']

    a, b = proj4_radius_parameters(area_def.proj_dict)
    options['radius_a'] = a
    options['radius_b'] = b
    options['origin_lon'] = upper_left[0]
    options['origin_lat'] = upper_left[1]
Exemple #17
0
def _get_geostationary_semi_axes(geos_area):
    from pyresample.utils import proj4_radius_parameters
    return proj4_radius_parameters(geos_area.crs)
Exemple #18
0
def write(image_data, output_fn, area_def, product_name=None, **kwargs):
    """Generic Ninjo TIFF writer.

    If 'prodcut_name' is given, it will load corresponding Ninjo tiff metadata
    from '${PPP_CONFIG_DIR}/ninjotiff.cfg'. Else, all Ninjo tiff metadata should
    be passed by '**kwargs'. A mixture is allowed, where passed arguments
    overwrite config file.

    :Parameters:
        image_data : 2D numpy array
            Satellite image data to be put into the NinJo compatible tiff
        output_fn : str
            The name of the TIFF file to be created
        area_def: pyresample.geometry.AreaDefinition
            Defintion of area
        product_name : str
            Optional index to Ninjo configuration file.

    :Keywords:
        kwargs : dict
            See _write
    """

    proj = Proj(area_def.proj_dict)
    upper_left = proj(area_def.area_extent[0],
                      area_def.area_extent[3],
                      inverse=True)
    lower_right = proj(area_def.area_extent[2],
                       area_def.area_extent[1],
                       inverse=True)

    if len(image_data.shape) == 3:
        if image_data.shape[2] == 4:
            shape = (area_def.y_size, area_def.x_size, 4)
            log.info("Will generate RGBA product")
        else:
            shape = (area_def.y_size, area_def.x_size, 3)
            log.info("Will generate RGB product")
        write_rgb = True
    else:
        shape = (area_def.y_size, area_def.x_size)
        write_rgb = False
        log.info("Will generate single band product")

    if image_data.shape != shape:
        raise ValueError(
            "Raster shape %s does not correspond to expected shape %s" %
            (str(image_data.shape), str(shape)))

    # Ninjo's physical units and value.
    # If just a physical unit (e.g. 'C') is passed, it will then be
    # translated into Ninjo's unit and value (e.q 'CELCIUS' and 'T').
    physic_unit = kwargs.get('physic_unit', None)
    if physic_unit and not kwargs.get('physic_value', None):
        kwargs['physic_unit'], kwargs['physic_value'] = \
            _get_physic_value(physic_unit)

    # Ninjo's projection name.
    kwargs['projection'] = kwargs.pop('projection', None) or \
        _get_projection_name(area_def) or \
        area_def.proj_id.split('_')[-1]

    # Get pixel size
    if 'pixel_xres' not in kwargs or 'pixel_yres' not in kwargs:
        kwargs['pixel_xres'], kwargs['pixel_yres'] = \
            _get_pixel_size(kwargs['projection'], area_def)

    # Get altitude.
    altitude = kwargs.pop('altitude', None) or \
        _get_satellite_altitude(output_fn)
    if altitude is not None:
        kwargs['altitude'] = altitude

    if product_name:
        # If ninjo_product_file in kwargs, load ninjo_product_file as config file
        if 'ninjo_product_file' in kwargs:
            options = deepcopy(
                get_product_config(product_name, True,
                                   kwargs['ninjo_product_file']))
        else:
            options = deepcopy(get_product_config(product_name))
    else:
        options = {}

    options['meridian_west'] = upper_left[0]
    options['meridian_east'] = lower_right[0]
    if kwargs['projection'].endswith("POL"):
        if 'lat_ts' in area_def.proj_dict:
            options['ref_lat1'] = area_def.proj_dict['lat_ts']
            options['ref_lat2'] = 0
    else:
        if 'lat_0' in area_def.proj_dict:
            options['ref_lat1'] = area_def.proj_dict['lat_0']
            options['ref_lat2'] = 0
    if 'lon_0' in area_def.proj_dict:
        options['central_meridian'] = area_def.proj_dict['lon_0']

    a, b = proj4_radius_parameters(area_def.proj_dict)
    options['radius_a'] = a
    options['radius_b'] = b
    options['origin_lon'] = upper_left[0]
    options['origin_lat'] = upper_left[1]
    options['min_gray_val'] = image_data.min()
    options['max_gray_val'] = image_data.max()
    options.update(kwargs)  # Update/overwrite with passed arguments

    _write(image_data, output_fn, write_rgb=write_rgb, **options)