Beispiel #1
0
    def from_crs(crs_from, crs_to, skip_equivalent=False):
        """Make a Transformer from a :obj:`~pyproj.crs.CRS` or input used to create one.

        Parameters
        ----------
        crs_from: ~pyproj.crs.CRS or input used to create one
            Projection of input data.
        crs_to: ~pyproj.crs.CRS or input used to create one
            Projection of output data.
        skip_equivalent: bool, optional
            If true, will skip the transformation operation if input and output
            projections are equivalent. Default is false.

        Returns
        -------
        :obj:`~Transformer`

        """
        transformer = Transformer()
        transformer._transformer = _Transformer.from_crs(
            CRS.from_user_input(crs_from),
            CRS.from_user_input(crs_to),
            skip_equivalent=skip_equivalent,
        )
        return transformer
Beispiel #2
0
def test_epsg():
    with pytest.warns(FutureWarning):
        assert CRS({"init": "EPSG:4326"}).to_epsg(20) == 4326
        assert CRS({"init": "EPSG:4326"}).to_epsg() is None
    assert CRS.from_user_input(4326).to_epsg() == 4326
    assert CRS.from_epsg(4326).to_epsg() == 4326
    assert CRS.from_user_input("epsg:4326").to_epsg() == 4326
Beispiel #3
0
def transform_polygon(polygon, src_crs, dst_crs):
    src_crs = CRS.from_user_input(src_crs)
    dst_crs = CRS.from_user_input(dst_crs)
    if not dst_crs.equals(src_crs):
        transformer = Transformer.from_crs(src_crs, dst_crs, always_xy=True)
        polygon = transform(transformer.transform, polygon)
    return polygon
Beispiel #4
0
    def from_crs(crs_from, crs_to, skip_equivalent=False, always_xy=False):
        """Make a Transformer from a :obj:`~pyproj.crs.CRS` or input used to create one.

        Parameters
        ----------
        crs_from: ~pyproj.crs.CRS or input used to create one
            Projection of input data.
        crs_to: ~pyproj.crs.CRS or input used to create one
            Projection of output data.
        skip_equivalent: bool, optional
            If true, will skip the transformation operation if input and output
            projections are equivalent. Default is false.
        always_xy: bool, optional
            If true, the transform method will accept as input and return as output
            coordinates using the traditional GIS order, that is longitude, latitude
            for geographic CRS and easting, northing for most projected CRS.
            Default is false.

        Returns
        -------
        :obj:`~Transformer`

        """
        transformer = Transformer(
            _Transformer.from_crs(
                CRS.from_user_input(crs_from),
                CRS.from_user_input(crs_to),
                skip_equivalent=skip_equivalent,
                always_xy=always_xy,
            ))
        return transformer
Beispiel #5
0
    def crs(self):
        if self._crs is False:
            return None
        elif self._crs is not None:
            return self._crs

        grid_mapping = self._obj.attrs.get("grid_mapping")
        if grid_mapping:
            warnings.warn(
                "'grid_mapping' attribute found, but no grid_mapping variable"
                " was provided. Use 'data_arr.geo.set_cf_grid_mapping' to "
                "provide one. Will search other metadata for CRS information.")

        # TODO: Check for lon/lat 2D coordinate arrays
        coords_crs = self._obj.coords.get("crs")
        attrs_crs = self._obj.attrs.get("crs")
        area = self._obj.attrs.get("area")
        if coords_crs is not None:
            crs = CRS.from_user_input(coords_crs)
        elif attrs_crs is not None:
            crs = CRS.from_user_input(attrs_crs)
        elif has_pyresample and isinstance(area, AreaDefinition):
            crs = area.crs
        elif has_pyresample and isinstance(area, SwathDefinition):
            # TODO: Convert and gather information from definitions
            self._is_gridded = False
            crs = False
        else:
            crs = False

        self._crs = crs
        return self._crs if self._crs is not False else None
Beispiel #6
0
    def __init__(
        self,
        crs_from: Any,
        crs_to: Any,
        always_xy: bool = False,
        area_of_interest: Optional[AreaOfInterest] = None,
        authority: Optional[str] = None,
        accuracy: Optional[float] = None,
        allow_ballpark: bool = True,
    ) -> None:
        """Get all possible transformations from a :obj:`pyproj.crs.CRS`
        or input used to create one.

        .. versionadded:: 3.4.0 authority, accuracy, allow_ballpark

        Parameters
        ----------
        crs_from: pyproj.crs.CRS or input used to create one
            Projection of input data.
        crs_to: pyproj.crs.CRS or input used to create one
            Projection of output data.
        always_xy: bool, default=False
            If true, the transform method will accept as input and return as output
            coordinates using the traditional GIS order, that is longitude, latitude
            for geographic CRS and easting, northing for most projected CRS.
        area_of_interest: :class:`pyproj.transformer.AreaOfInterest`, optional
            The area of interest to help order the transformations based on the
            best operation for the area.
        authority: str, optional
            When not specified, coordinate operations from any authority will be
            searched, with the restrictions set in the
            authority_to_authority_preference database table related to the
            authority of the source/target CRS themselves. If authority is set
            to “any”, then coordinate operations from any authority will be
            searched. If authority is a non-empty string different from "any",
            then coordinate operations will be searched only in that authority
            namespace (e.g. EPSG).
        accuracy: float, optional
            The minimum desired accuracy (in metres) of the candidate
            coordinate operations.
        allow_ballpark: bool, default=True
            Set to False to disallow the use of Ballpark transformation
            in the candidate coordinate operations. Default is to allow.

        """
        super().__init__(
            CRS.from_user_input(crs_from)._crs,
            CRS.from_user_input(crs_to)._crs,
            always_xy=always_xy,
            area_of_interest=area_of_interest,
            authority=authority,
            accuracy=-1 if accuracy is None else accuracy,
            allow_ballpark=allow_ballpark,
        )
        for iii, transformer in enumerate(self._transformers):
            # pylint: disable=unsupported-assignment-operation
            self._transformers[iii] = Transformer(
                TransformerUnsafe(transformer))
Beispiel #7
0
    def from_crs(
        crs_from: Any,
        crs_to: Any,
        always_xy: bool = False,
        area_of_interest: Optional[AreaOfInterest] = None,
        authority: Optional[str] = None,
        accuracy: Optional[float] = None,
        allow_ballpark: Optional[bool] = None,
    ) -> "Transformer":
        """Make a Transformer from a :obj:`pyproj.crs.CRS` or input used to create one.

        .. versionadded:: 2.2.0 always_xy
        .. versionadded:: 2.3.0 area_of_interest
        .. versionadded:: 3.1.0 authority, accuracy, allow_ballpark

        Parameters
        ----------
        crs_from: pyproj.crs.CRS or input used to create one
            Projection of input data.
        crs_to: pyproj.crs.CRS or input used to create one
            Projection of output data.
        always_xy: bool, default=False
            If true, the transform method will accept as input and return as output
            coordinates using the traditional GIS order, that is longitude, latitude
            for geographic CRS and easting, northing for most projected CRS.
        area_of_interest: :class:`pyproj.transformer.AreaOfInterest`, optional
            The area of interest to help select the transformation.
        authority: str, optional
            When not specified, coordinate operations from any authority will be
            searched, with the restrictions set in the
            authority_to_authority_preference database table related to the
            authority of the source/target CRS themselves. If authority is set
            to “any”, then coordinate operations from any authority will be
            searched. If authority is a non-empty string different from "any",
            then coordinate operations will be searched only in that authority
            namespace (e.g. EPSG).
        accuracy: float, optional
            The minimum desired accuracy (in metres) of the candidate
            coordinate operations.
        allow_ballpark: bool, optional
            Set to False to disallow the use of Ballpark transformation
            in the candidate coordinate operations. Default is to allow.

        Returns
        -------
        Transformer

        """
        return Transformer(
            TransformerFromCRS(
                cstrencode(CRS.from_user_input(crs_from).srs),
                cstrencode(CRS.from_user_input(crs_to).srs),
                always_xy=always_xy,
                area_of_interest=area_of_interest,
                authority=authority,
                accuracy=accuracy if accuracy is None else str(accuracy),
                allow_ballpark=allow_ballpark,
            ))
Beispiel #8
0
 def _transform_polygon(polygon, src_crs, dst_crs):
     if isinstance(src_crs, str):
         src_crs = CRS.from_user_input(src_crs)
     if isinstance(dst_crs, str):
         dst_crs = CRS.from_user_input(dst_crs)
     if dst_crs.srs != src_crs.srs:
         transformer = Transformer.from_crs(
             src_crs, dst_crs, always_xy=True)
         polygon = transform(transformer.transform, polygon)
     return polygon
Beispiel #9
0
def test_is_projected():
    assert CRS({"init": "EPSG:3857"}).is_projected is True

    lcc_crs = CRS.from_string(
        "+lon_0=-95 +ellps=GRS80 +y_0=0 +no_defs=True +proj=lcc +x_0=0 +units=m +lat_2=77 +lat_1=49 +lat_0=0"
    )
    assert CRS.from_user_input(lcc_crs).is_projected is True

    wgs84_crs = CRS.from_string("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
    assert CRS.from_user_input(wgs84_crs).is_projected is False
Beispiel #10
0
def test_is_projected():
    assert CRS({"init": "EPSG:3857"}).is_projected is True

    lcc_crs = CRS.from_string(
        "+lon_0=-95 +ellps=GRS80 +y_0=0 +no_defs=True +proj=lcc +x_0=0 +units=m +lat_2=77 +lat_1=49 +lat_0=0"
    )
    assert CRS.from_user_input(lcc_crs).is_projected is True

    wgs84_crs = CRS.from_string("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
    assert CRS.from_user_input(wgs84_crs).is_projected is False
Beispiel #11
0
    def __init__(
        self,
        crs_from,
        crs_to,
        skip_equivalent=False,
        always_xy=False,
        area_of_interest=None,
    ):
        """Get all possible transformations from a :obj:`~pyproj.crs.CRS`
        or input used to create one.


        Parameters
        ----------
        crs_from: ~pyproj.crs.CRS or input used to create one
            Projection of input data.
        crs_to: ~pyproj.crs.CRS or input used to create one
            Projection of output data.
        skip_equivalent: bool, optional
            If true, will skip the transformation operation if input and output
            projections are equivalent. Default is false.
        always_xy: bool, optional
            If true, the transform method will accept as input and return as output
            coordinates using the traditional GIS order, that is longitude, latitude
            for geographic CRS and easting, northing for most projected CRS.
            Default is false.
        area_of_interest: :class:`~pyproj.transformer.AreaOfInterest`, optional
            The area of interest to help order the transformations based on the
            best operation for the area.

        """
        self._transformers = []
        self._unavailable_operations = []
        self._best_available = True
        for iii, operation in enumerate(
            transformer_list_from_crs(
                CRS.from_user_input(crs_from),
                CRS.from_user_input(crs_to),
                skip_equivalent=skip_equivalent,
                always_xy=always_xy,
                area_of_interest=area_of_interest,
            )
        ):
            if isinstance(operation, _Transformer):
                self._transformers.append(Transformer(operation))
            else:
                self._unavailable_operations.append(operation)
                if iii == 0:
                    self._best_available = False
                    warnings.warn(
                        "Best transformation is not available due to missing "
                        "{!r}".format(operation.grids[0])
                    )
Beispiel #12
0
    def from_crs(
        crs_from: Any,
        crs_to: Any,
        skip_equivalent: bool = False,
        always_xy: bool = False,
        area_of_interest: Optional[AreaOfInterest] = None,
        network: Optional[bool] = None,
    ) -> "Transformer":
        """Make a Transformer from a :obj:`pyproj.crs.CRS` or input used to create one.

        .. versionadded:: 2.1.2 skip_equivalent
        .. versionadded:: 2.2.0 always_xy
        .. versionadded:: 2.3.0 area_of_interest
        .. versionadded:: 3.0.0 network

        Parameters
        ----------
        crs_from: pyproj.crs.CRS or input used to create one
            Projection of input data.
        crs_to: pyproj.crs.CRS or input used to create one
            Projection of output data.
        skip_equivalent: bool, optional
            If true, will skip the transformation operation if input and output
            projections are equivalent. Default is false.
        always_xy: bool, optional
            If true, the transform method will accept as input and return as output
            coordinates using the traditional GIS order, that is longitude, latitude
            for geographic CRS and easting, northing for most projected CRS.
            Default is false.
        area_of_interest: :class:`pyproj.transformer.AreaOfInterest`, optional
            The area of interest to help select the transformation.
        network: bool, optional
            Default is None, which uses the system defaults for networking.
            If True, it will force the use of network for grids regardless of
            any other network setting. If False, it will force disable use of
            network for grids regardless of any other network setting.

        Returns
        -------
        Transformer

        """
        return Transformer(
            _Transformer.from_crs(
                CRS.from_user_input(crs_from),
                CRS.from_user_input(crs_to),
                skip_equivalent=skip_equivalent,
                always_xy=always_xy,
                area_of_interest=area_of_interest,
                network=network,
            ))
Beispiel #13
0
    def __init__(
        self,
        crs_from: Any,
        crs_to: Any,
        skip_equivalent: bool = False,
        always_xy: bool = False,
        area_of_interest: Optional[AreaOfInterest] = None,
    ) -> None:
        """Get all possible transformations from a :obj:`pyproj.crs.CRS`
        or input used to create one.


        Parameters
        ----------
        crs_from: pyproj.crs.CRS or input used to create one
            Projection of input data.
        crs_to: pyproj.crs.CRS or input used to create one
            Projection of output data.
        skip_equivalent: bool, optional
            If true, will skip the transformation operation if input and output
            projections are equivalent. Default is false.
        always_xy: bool, optional
            If true, the transform method will accept as input and return as output
            coordinates using the traditional GIS order, that is longitude, latitude
            for geographic CRS and easting, northing for most projected CRS.
            Default is false.
        area_of_interest: :class:`pyproj.transformer.AreaOfInterest`, optional
            The area of interest to help order the transformations based on the
            best operation for the area.


        Example:

        >>> from pyproj.transformer import TransformerGroup
        >>> trans_group = TransformerGroup(4326, 2964)
        >>> trans_group
        <TransformerGroup: best_available=True>
        - transformers: 8
        - unavailable_operations: 1

        """
        super().__init__(
            CRS.from_user_input(crs_from),
            CRS.from_user_input(crs_to),
            skip_equivalent=skip_equivalent,
            always_xy=always_xy,
            area_of_interest=area_of_interest,
        )
        for iii, transformer in enumerate(self._transformers):
            self._transformers[iii] = Transformer(transformer)
Beispiel #14
0
 def _transform_multipolygon(multipolygon, src_crs, dst_crs):
     if isinstance(src_crs, str):
         src_crs = CRS.from_user_input(src_crs)
     if isinstance(dst_crs, str):
         dst_crs = CRS.from_user_input(dst_crs)
     if dst_crs.srs != src_crs.srs:
         transformer = Transformer.from_crs(
             src_crs, dst_crs, always_xy=True)
         polygon_collection = list()
         for polygon in multipolygon:
             polygon_collection.append(
                 transform(transformer.transform, polygon))
         outer = polygon_collection.pop(0)
         multipolygon = MultiPolygon([outer, *polygon_collection])
     return multipolygon
Beispiel #15
0
    def __init__(
        self,
        crs_from: Any,
        crs_to: Any,
        skip_equivalent: bool = False,
        always_xy: bool = False,
        area_of_interest: Optional[AreaOfInterest] = None,
    ) -> None:
        """Get all possible transformations from a :obj:`pyproj.crs.CRS`
        or input used to create one.

        .. deprecated:: 3.1 skip_equivalent

        Parameters
        ----------
        crs_from: pyproj.crs.CRS or input used to create one
            Projection of input data.
        crs_to: pyproj.crs.CRS or input used to create one
            Projection of output data.
        skip_equivalent: bool, default=False
            DEPRECATED: If true, will skip the transformation operation
            if input and output projections are equivalent.
        always_xy: bool, default=False
            If true, the transform method will accept as input and return as output
            coordinates using the traditional GIS order, that is longitude, latitude
            for geographic CRS and easting, northing for most projected CRS.
        area_of_interest: :class:`pyproj.transformer.AreaOfInterest`, optional
            The area of interest to help order the transformations based on the
            best operation for the area.

        """
        if skip_equivalent:
            warnings.warn(
                "skip_equivalent is deprecated.",
                DeprecationWarning,
                stacklevel=2,
            )

        super().__init__(
            CRS.from_user_input(crs_from)._crs,
            CRS.from_user_input(crs_to)._crs,
            always_xy=always_xy,
            area_of_interest=area_of_interest,
        )
        for iii, transformer in enumerate(self._transformers):
            # pylint: disable=unsupported-assignment-operation
            self._transformers[iii] = Transformer(
                TransformerUnsafe(transformer))
Beispiel #16
0
    def __init__(self, nodes: Dict[Hashable, List[List]], crs=None):
        """Setter for the nodes attribute.

        Argument nodes must be of the form:
            {id: [(x0, y0), z0]}
            or
            {id: [(x0, y0), [z0, ..., zn]}

        Grd format is assumed to be exclusively a 2D format that can hold
        triangles or quads.

        """

        for coords, _ in nodes.values():
            if len(coords) != 2:
                raise ValueError(
                    'Coordinate vertices for a gr3 type must be 2D, but got '
                    f'coordinates {coords}.')

        self._id = list(nodes.keys())
        self._coords = np.array(
            [coords for coords, _ in nodes.values()])
        self._crs = CRS.from_user_input(crs) if crs is not None else crs
        self._values = np.array(
            [value for _, value in nodes.values()])
Beispiel #17
0
    def __init__(
        self,
        nodes: DataFrame,
        elements: DataFrame = None,
        description: str = None,
        crs: CRS = None,
    ):
        if isinstance(nodes, Mapping):
            nodes = DataFrame.from_dict(nodes, orient='index')
        if isinstance(elements, Mapping):
            elements = DataFrame.from_dict(elements, orient='index')

        if crs is not None and not isinstance(crs, CRS):
            crs = CRS.from_user_input(crs)

        records_with_extra_values = np.any(~pandas.isna(nodes.iloc[:, 3:]),
                                           axis=1)
        if np.any(records_with_extra_values):
            raise ValueError(
                f'Coordinate vertices for a gr3 type must be 2D, but got coordinates {nodes[records_with_extra_values]}.'
            )

        nodes = nodes.loc[:, nodes.columns[:2].to_list() + nodes.columns[2:][
            np.any(~pandas.isna(nodes.iloc[:, 2:]), axis=0)].to_list(), ]

        self._coords = nodes.iloc[:, :2]
        self._crs = crs
        self._values = nodes.iloc[:, 2:]

        self.nodes = nodes
        self.elements = Elements(self.nodes, elements, crs)
        self.description = "" if description is None else str(description)
        self.hull = Hull(self)
Beispiel #18
0
def read(resource: Union[str, os.PathLike], boundaries: bool = True, crs=True):
    """Converts a file-like object representing a grd-formatted unstructured
    mesh into a python dictionary:

    Args:
        resource: Path to file on disk or file-like object such as
            :class:`io.StringIO`
    """
    resource = pathlib.Path(resource)
    with open(resource, 'r') as stream:
        grd = buffer_to_dict(stream)
    if boundaries is False:
        grd.pop('boundaries', None)
    if crs is True:
        crs = None
    if crs is None:
        for try_crs in grd['description'].split():
            try:
                crs = CRS.from_user_input(try_crs)
                break
            except CRSError:
                pass
    if crs is None:
        warnings.warn(f'File {str(resource)} does not contain CRS '
                      'information and no CRS was given.')
    if crs is not False:
        grd.update({'crs': crs})
    return grd
Beispiel #19
0
def crs_to_wkt(crs_input):
    """
    This is to deal with change in rasterio.crs.CRS
    as well as to assist in the transition between GDAL 2/3.

    Parameters
    ----------
    crs_input: Any
        Input to create a CRS.

    Returns
    -------
    str: WKT string.

    """
    try:
        # rasterio.crs.CRS <1.0.14 and
        # old versions of opendatacube CRS
        crs_input = crs_input.wkt
    except AttributeError:
        pass
    crs = CRS.from_user_input(crs_input)
    if LooseVersion(rasterio.__gdal_version__) > LooseVersion("3.0.0"):
        return crs.to_wkt()
    return crs.to_wkt("WKT1_GDAL")
Beispiel #20
0
def to_geotiff(fn, z, transform, crs=None, compress=None):
    """
    Writes geotiff from an array (assumed 3d)
    :param fn: filename
    :param z: array (3-D)
    :param transform: Affine transform
    :param crs=None: coordinate ref system
    :param compress: compression if needed
    :return:
    """
    if crs is not None:
        try:
            crs = CRS.from_user_input(crs)
        except:
            raise ValueError(f'CRS "{crs}" is not valid')
        if crs.is_geographic:
            raise TypeError(
                "CRS is of geographic type, a projected type (unit: meters) is required"
            )
    with rasterio.open(
            fn,
            "w",
            driver="GTiff",
            height=z.shape[1],
            width=z.shape[2],
            count=z.shape[0],
            dtype=z.dtype,
            crs=crs.to_proj4() if crs is not None else None,
            transform=transform,
            compress=compress,
    ) as ds:
        for n, _z in enumerate(z):
            ds.write(_z, n + 1)
Beispiel #21
0
def to_geojson(geom, crs=None):
    """
    Converts a single geometry in a geographically aware geojson
    :param geom: shapely feature (single!!)
    :param crs=None: pyproj readible crs
    :return: str, geojson format
    """
    # prepare a crs
    if crs is not None:
        try:
            crs = CRS.from_user_input(crs)
        except:
            raise ValueError(f'CRS "{crs}" is not valid')
        if crs.is_geographic:
            raise TypeError(
                "CRS is of geographic type, a projected type (unit: meters) is required"
            )
        try:
            epsg = crs.to_epsg()
        except:
            raise ValueError(f"CRS cannot be converted to EPSG code")
    # prepare json compatible crs dict
    crs_json = ({
        "type": "EPSG",
        "properties": {
            "code": epsg
        }
    } if crs is not None else None)
    # prepare geojson feature
    f = geojson.Feature(geometry=geom, properties={"ID": 0})
    # collate all into a geojson feature collection
    return geojson.FeatureCollection([f], crs=crs_json)
Beispiel #22
0
    def warp(self, dst_crs):
        dst_crs = CRS.from_user_input(dst_crs)
        transform, width, height = warp.calculate_default_transform(
            self._src.crs,
            dst_crs.srs,
            self._src.width,
            self._src.height,
            *self._src.bounds,
            dst_width=self._src.width,
            dst_height=self._src.height)
        kwargs = self._src.meta.copy()
        kwargs.update({
            'crs': dst_crs.srs,
            'transform': transform,
            'width': width,
            'height': height
        })
        tmpfile = tempfile.NamedTemporaryFile(prefix=tmpdir)

        with rasterio.open(tmpfile.name, 'w', **kwargs) as dst:
            for i in range(1, self._src.count + 1):
                rasterio.warp.reproject(
                    source=rasterio.band(self._src, i),
                    destination=rasterio.band(dst, i),
                    src_transform=self._src.transform,
                    crs=self._src.crs,
                    dst_transform=transform,
                    dst_crs=dst_crs.srs,
                    resampling=self.resampling_method,
                    num_threads=multiprocessing.cpu_count(),
                )

        self._tmpfile = tmpfile
Beispiel #23
0
    def project_to_camera(self, lon, lat, elevation):
        """ Project a lat/lon/elevation point into the image
        
        :param lat: The latitiude
        :type lat: float
        :param lon: The longitiude
        :type lon: float
        :param elevation: The elevation
        :type elevation: float
        :return: The row, col value of the pixel
        :rtype: class: `np.Array`
        """

        # Convert lat/lon/elev to camera CRS
        transformer = Transformer.from_crs(CRS.from_user_input(4326),
                                           self.crs,
                                           always_xy=True)
        x, y, z = transformer.transform(lon, lat, elevation)
        pt = np.transpose(np.array([[x, y, z, 1.0]]))

        # Do projection
        img_pt_h = self.projection_matrix @ pt
        img_pt = img_pt_h / img_pt_h[2]

        # Offset pixel by bounds
        img_pt[0] -= self.image_bounds[0]
        img_pt[1] -= self.image_bounds[1]
        img_pt = np.transpose(img_pt)
        return img_pt[0][0:2]
Beispiel #24
0
    def __init__(self, df, traj_id, obj_id=None, parent=None):
        """
        Create Trajectory from GeoDataFrame

        Parameters
        ----------
        df : GeoDataFrame
            GeoDataFrame with point geometry column and timestamp index
        traj_id : any
            Trajectory ID
        obj_id : any
            Moving object ID
        parent : Trajectory
            Parent trajectory
        """
        if len(df) < 2:
            raise ValueError(
                "Trajectory dataframe must have at least two rows!")

        self.id = traj_id
        self.obj_id = obj_id
        df.sort_index(inplace=True)
        self.df = df[~df.index.duplicated(keep='first')]
        self.crs = df.crs
        self.parent = parent
        try:
            crs = CRS.from_user_input(self.crs)
            self.is_latlon = crs.is_geographic
        except NameError:
            self.is_latlon = self.crs['init'] == from_epsg(4326)['init']
Beispiel #25
0
    def validate(cls, value: Union[CRS, str]) -> CRS:
        """Validate CRS."""
        # If input is a string we tranlate it to CRS
        if not isinstance(value, CRS):
            return CRS.from_user_input(value)

        return value
Beispiel #26
0
def reproject_bounds(bounds: Bounds, src_crs: CRS, crs: CRS) -> Bounds:
    """Reproject source bounds from source CRS to destination CRS.

    Make sure that coordinates fall within real world coordinates system
    Taken from pixetl
    """

    left, bottom, right, top = bounds

    min_lng, min_lat, max_lng, max_lat = world_bounds(crs)

    proj = Transformer.from_crs(CRS.from_user_input(src_crs),
                                crs,
                                always_xy=True)

    reproject_top = replace_inf_nan(round(proj.transform(0, top)[1], 8),
                                    max_lat)
    reproject_left = replace_inf_nan(round(proj.transform(left, 0)[0], 8),
                                     min_lng)
    reproject_bottom = replace_inf_nan(round(proj.transform(0, bottom)[1], 8),
                                       min_lat)
    reproject_right = replace_inf_nan(round(proj.transform(right, 0)[0], 8),
                                      max_lng)

    return reproject_left, reproject_bottom, reproject_right, reproject_top
Beispiel #27
0
 def setUp(self):
     self.proj = np.array([[
         -234.48497951320869, -11689.146112537686, -3420.9549093694854,
         54967162069.77626
     ],
                           [
                               -11527.74509904331, 527.9966478964207,
                               -3108.9307732776556, 2267432568.205459
                           ],
                           [
                               0.07731721986909759, 0.01342309733163904,
                               -0.996916676327768, -93150.24955090503
                           ]])
     self.bounds = [4405, 655, 5587, 1420]
     self.cen = [411228.51669897616, 4693677.177776167, 1653.5802147550032]
     self.geo_bounds = [
         -88.07607063663191, 42.387928513288855, -88.07499236028416,
         42.38917669615173
     ]
     self.elev = 250.522
     self.crs = CRS.from_user_input(32616)
     self.path = "foo.jpg"
     self.cam = Camera(self.proj, self.bounds, self.cen, self.geo_bounds,
                       self.elev, self.crs, self.path)
     pass
Beispiel #28
0
def crs_from_user_input(crs_input):
    """
    Return a rasterio.crs.CRS from user input.

    This is to deal with change in rasterio.crs.CRS
    as well as to assist in the transition between GDAL 2/3.

    Parameters
    ----------
    crs_input: Any
        Input to create a CRS.

    Returns
    -------
    rasterio.crs.CRS

    """
    if isinstance(crs_input, rasterio.crs.CRS):
        return crs_input
    try:
        # old versions of opendatacube CRS
        crs_input = crs_input.wkt
    except AttributeError:
        pass
    try:
        return rasterio.crs.CRS.from_user_input(crs_input)
    except CRSError:
        pass
    # use pyproj for edge cases
    crs = CRS.from_user_input(crs_input)
    if version.parse(rasterio.__gdal_version__) > version.parse("3.0.0"):
        return rasterio.crs.CRS.from_wkt(crs.to_wkt())
    return rasterio.crs.CRS.from_wkt(crs.to_wkt("WKT1_GDAL"))
Beispiel #29
0
    def reproject_bounds(self, crs: CRS) -> Bounds:
        """Reproject src bounds to dst CRT.

        Make sure that coordinates fall within real world coordinates
        system
        """

        left, bottom, right, top = self.bounds

        LOGGER.debug("SRC Extent: {}, {}, {}, {}".format(
            left,
            bottom,
            right,
            top,
        ))

        min_lng, min_lat, max_lng, max_lat = utils.world_bounds(crs)

        proj = Transformer.from_crs(CRS.from_user_input(self.crs),
                                    crs,
                                    always_xy=True)

        reproject_top = replace_inf_nan(round(proj.transform(0, top)[1], 8),
                                        max_lat)
        reproject_left = replace_inf_nan(round(proj.transform(left, 0)[0], 8),
                                         min_lng)
        reproject_bottom = replace_inf_nan(
            round(proj.transform(0, bottom)[1], 8), min_lat)
        reproject_right = replace_inf_nan(
            round(proj.transform(right, 0)[0], 8), max_lng)

        LOGGER.debug("Reprojected, cropped Extent: {}, {}, {}, {}".format(
            reproject_left, reproject_bottom, reproject_right, reproject_top))

        return reproject_left, reproject_bottom, reproject_right, reproject_top
Beispiel #30
0
    def __init__(self, *args: Optional[Any], **kwargs: Optional[Any]):
        if args:
            klass = f"'{self.__class__.__name__}'"
            if len(args) == 1 and ("crs" not in kwargs
                                   or kwargs["crs"] is None):
                wmsg = (f"{klass} received an unexpected argument. "
                        "Assuming 'crs' keyword argument instead...")
                warn(wmsg)
                kwargs["crs"] = args[0]
                args = ()
            else:
                plural = "s" if len(args) > 1 else ""
                pre = ",".join([f"'{arg}'" for arg in args[:-1]])
                bad = f"{pre} and '{args[-1]}'" if pre else f"'{args[0]}'"
                emsg = (
                    f"{klass} received {len(args)} unexpected argument{plural}, {bad}."
                )
                raise ValueError(emsg)

        if "crs" in kwargs:
            crs = kwargs.pop("crs")
            crs = CRS.from_user_input(crs)
        else:
            crs = WGS84
        self.crs = crs
        super().__init__(*args, **kwargs)
Beispiel #31
0
    def __init__(self,
                 shape: Union[None, MultiPolygon, Polygon] = None,
                 shape_crs: CRS = CRS.from_user_input("EPSG:4326"),
                 shapefile: Union[None, str, Path] = None):

        if not (shape or shapefile):
            raise ValueError("No patch input provided")

        # crs input is only for shape, shapefile needs to provide
        # its own crs
        self._shape_crs = shape_crs
        self._shape = None
        self._shapefile = Path(shapefile if shapefile else "")
        if isinstance(shape, Polygon):
            self._shape = MultiPolygon([shape])

        elif isinstance(shape, MultiPolygon):
            self._shape = shape

        elif shape is not None:
            raise TypeError(
                f"Type of shape input must be either {MultiPolygon}"
                f" or {Polygon}")

        elif not self._shapefile.is_file():
            raise ValueError("Not shape input for patch definition")
Beispiel #32
0
def test_epsg():
    assert CRS({"init": "EPSG:4326"}).to_epsg(20) == 4326
    assert CRS({"init": "EPSG:4326"}).to_epsg() is None
    assert CRS.from_user_input(4326).to_epsg() == 4326
    assert CRS.from_epsg(4326).to_epsg() == 4326
    assert CRS.from_user_input("epsg:4326").to_epsg() == 4326
Beispiel #33
0
def test_from_user_input_epsg():
    assert "+proj=longlat" in CRS.from_user_input("EPSG:4326").to_proj4(4)
Beispiel #34
0
def test_from_user_input_custom_crs_class():
    class CustomCRS(object):
        def to_wkt(self):
            return CRS.from_epsg(4326).to_wkt()

    assert CRS.from_user_input(CustomCRS()) == CRS.from_epsg(4326)