Exemplo n.º 1
0
def test_compare_crs_non_crs():
    assert CRS.from_epsg(4326) != 4.2
    assert CRS.from_epsg(4326) == 4326
    with pytest.warns(FutureWarning):
        assert CRS.from_dict({"init": "epsg:4326"}) == {"init": "epsg:4326"}
        assert CRS.from_dict({"init": "epsg:4326"}) != "epsg:4326"
    assert CRS("epsg:4326") == CustomCRS()
Exemplo n.º 2
0
    def __init__(self, crs_spec: Any):
        """
        :param crs_str: string representation of a CRS, often an EPSG code like 'EPSG:4326'
        :raises: `pyproj.exceptions.CRSError`
        """
        if isinstance(crs_spec, str):
            self._crs, self._str, self._epsg = _make_crs(crs_spec)
        elif isinstance(crs_spec, CRS):
            self._crs = crs_spec._crs
            self._epsg = crs_spec._epsg
            self._str = crs_spec._str
        elif isinstance(crs_spec, _CRS):
            self._crs, self._str, self._epsg = _make_crs(crs_spec)
        elif isinstance(crs_spec, dict):
            self._crs, self._str, self._epsg = _make_crs(_CRS.from_dict(crs_spec))
        else:
            _to_epsg = getattr(crs_spec, "to_epsg", None)
            if _to_epsg is not None:
                self._crs, self._str, self._epsg = _make_crs(f"EPSG:{_to_epsg()}")
                return
            _to_wkt = getattr(crs_spec, "to_wkt", None)
            if _to_wkt is not None:
                self._crs, self._str, self._epsg = _make_crs(_to_wkt())
                return

            raise CRSError(
                "Expect string or any object with `.to_epsg()` or `.to_wkt()` methods"
            )
Exemplo n.º 3
0
def open_file(path, corners, engine='h5netcdf'):
    ds = xr.open_dataset(path, engine=engine)
    proj_info = ds.goes_imager_projection
    proj4_params = {
        "ellps": "WGS84",
        "a": proj_info.semi_major_axis.item(),
        "b": proj_info.semi_minor_axis.item(),
        "rf": proj_info.inverse_flattening.item(),
        "proj": "geos",
        "lon_0": proj_info.longitude_of_projection_origin.item(),
        "lat_0": 0.0,
        "h": proj_info.perspective_point_height.item(),
        "x_0": 0,
        "y_0": 0,
        "units": "m",
        "sweep": proj_info.sweep_angle_axis,
    }
    crs = CRS.from_dict(proj4_params)
    bnds = transform(crs.geodetic_crs, crs, corners[:, 0], corners[:, 1])
    ds = ds.update({
        "x": ds.x * proj_info.perspective_point_height,
        "y": ds.y * proj_info.perspective_point_height,
    }).assign_attrs(crs=crs, proj4_params=proj4_params)

    xarg = np.nonzero(
        ((ds.x >= bnds[0].min()) & (ds.x <= bnds[0].max())).values)[0]
    yarg = np.nonzero(
        ((ds.y >= bnds[1].min()) & (ds.y <= bnds[1].max())).values)[0]
    return ds.isel(x=xarg, y=yarg)
Exemplo n.º 4
0
def get_proj4(grid_mapping):
    cf_parameters = dict(grid_mapping.attrs)
    decode_bytes(cf_parameters)

    crs_dict = CRS.from_cf(cf_parameters).to_dict()
    if 'standard_parallel' in cf_parameters:
        crs_dict['lat_ts'] = cf_parameters['standard_parallel']
    return CRS.from_dict(crs_dict).to_proj4()
Exemplo n.º 5
0
 def test_explicit_crs_from_epsg(self):
     with pytest.warns(FutureWarning):
         assert explicit_crs_from_epsg(epsg=4326) == CRS.from_epsg(4326)
         assert explicit_crs_from_epsg(epsg="4326") == CRS.from_epsg(4326)
         assert explicit_crs_from_epsg(
             crs={"init": "epsg:4326"}) == CRS.from_dict(
                 {"init": "epsg:4326"})
         assert explicit_crs_from_epsg(
             crs="+init=epsg:4326") == CRS.from_proj4("+init=epsg:4326")
Exemplo n.º 6
0
def utm_zone2epsg_code(utm_zone):
    """Convert UTM Zone string to EPSG code.
    Parameters: utm_zone - str, atr['UTM_ZONE']
    Returns:    epsg     - str, EPSG code
    Examples:   epsg = utm_zone2epsg_code('11N')
    """
    crs = CRS.from_dict({'proj': 'utm',
                         'zone': int(utm_zone[:-1]),
                         'south': utm_zone[-1] == 'S',
                        })
    epsg = crs.to_authority()[1]
    return epsg
Exemplo n.º 7
0
 def _ensure_crs_extents_in_meters(crs, area_extent):
     """Fix units in Earth shape, satellite altitude and 'units' attribute."""
     if 'kilo' in crs.axis_info[0].unit_name:
         proj_dict = crs.to_dict()
         proj_dict["units"] = "m"
         if "a" in proj_dict:
             proj_dict["a"] *= 1000.
         if "b" in proj_dict:
             proj_dict["b"] *= 1000.
         if "R" in proj_dict:
             proj_dict["R"] *= 1000.
         proj_dict["h"] *= 1000.
         area_extent = tuple([val * 1000. for val in area_extent])
         crs = CRS.from_dict(proj_dict)
     return crs, area_extent
Exemplo n.º 8
0
def _guess_crs_str(crs_spec: Any) -> Optional[str]:
    """
    Returns a string representation of the crs spec.
    Returns `None` if it does not understand the spec.
    """
    if isinstance(crs_spec, str):
        return crs_spec
    if isinstance(crs_spec, dict):
        crs_spec = _CRS.from_dict(crs_spec)

    if hasattr(crs_spec, 'to_epsg'):
        epsg = crs_spec.to_epsg()
        if epsg is not None:
            return 'EPSG:{}'.format(crs_spec.to_epsg())
    if hasattr(crs_spec, 'to_wkt'):
        return crs_spec.to_wkt()
    return None
Exemplo n.º 9
0
def calculate_area(gdf: gpd.GeoDataFrame):
    areas = []
    for row in gdf.itertuples():
        centroid = row.geometry.centroid
        utm_tuple = utm.from_latlon(centroid.y, centroid.x)
        if centroid.y > 0:
            south = False
        else:
            south = True
        crs = CRS.from_dict({
            "proj": "utm",
            "zone": utm_tuple[2],
            south: south
        })
        crs_code = f"EPSG:{crs.to_authority()[1]}"
        row_as_df = pd.DataFrame.from_records([row], columns=row._fields)
        row_as_gdf = gpd.GeoDataFrame(row_as_df,
                                      geometry=row_as_df.geometry,
                                      crs="EPSG:4326")
        row_as_utm = row_as_gdf.to_crs(crs_code)
        areas.append(row_as_utm.area.sum())
    area = sum(areas)
    return area
Exemplo n.º 10
0
def test_to_dict_from_dict():
    cc = CRS.from_epsg(4326)
    with pytest.warns(UserWarning):
        assert CRS.from_dict(cc.to_dict()).name == "unknown"
Exemplo n.º 11
0
def test_from_dict__invalid():
    with pytest.raises(CRSError, match="CRS input is not a dict"):
        CRS.from_dict(4326)
Exemplo n.º 12
0
def test_to_dict_from_dict():
    cc = CRS.from_epsg(4326)
    assert CRS.from_dict(cc.to_dict()).name == "unknown"
Exemplo n.º 13
0
def test_compare_crs_non_crs():
    assert CRS.from_epsg(4326) != 4.2
    assert CRS.from_epsg(4326) == 4326
    assert CRS.from_dict({"init": "epsg:4326"}) == {"init": "epsg:4326"}
    assert CRS.from_dict({"init": "epsg:4326"}) != "epsg:4326"
    assert CRS("epsg:4326") == CustomCRS()