Beispiel #1
0
    def read(self, filename, **kwargs):
        """
        :param filename: ROI_PAC binary file
        :type filename: str
        :param par_file: Corresponding parameter (:file:`*rsc`) file.
                         (optional)
        :type par_file: str
        :returns: Import dictionary
        :rtype: dict
        :raises: ImportError
        """
        par_file = kwargs.pop('par_file', self._getParameterFile(filename))

        par = self._parseParameterFile(par_file)
        nlines = int(par['FILE_LENGTH'])
        nrows = int(par['WIDTH'])
        wavelength = par['WAVELENGTH']
        heading = par['HEADING_DEG']
        lat_ref = par['LAT_REF1']
        lon_ref = par['LON_REF1']
        look_ref1 = par['LOOK_REF1']
        look_ref2 = par['LOOK_REF2']
        look_ref3 = par['LOOK_REF3']
        look_ref4 = par['LOOK_REF4']

        utm_zone_letter = utm.latitude_to_zone_letter(
                    par['LAT_REF1'])
        utm_zone = utm.latlon_to_zone_number(par['LAT_REF1'], par['LON_REF1'])

        look = num.mean(
            num.array([look_ref1, look_ref2, look_ref3, look_ref4]))

        data = num.memmap(filename, dtype='<f4')
        data = data.reshape(nlines, nrows*2)

        displ = data[:, nrows:]
        displ[displ == -0.] = num.nan
        displ = displ / (4.*num.pi) * wavelength

        z_scale = par.get('Z_SCALE', 1.)
        z_offset = par.get('Z_OFFSET', 0.)
        displ += z_offset
        displ *= z_scale

        c = self.container

        c.displacement = displ
        c.theta = 90. - look
        c.phi = -heading - 180

        c.meta.title = par.get('TITLE', 'None')
        c.meta.wavelength = par['WAVELENGTH']
        c.bin_file = filename
        c.par_file = par_file

        c.frame.llLat = par['Y_FIRST'] + par['Y_STEP'] * nrows
        c.frame.llLon = par['X_FIRST']
        c.frame.dLon = par['X_STEP']
        c.frame.dLat = par['Y_STEP']
        return self.container
Beispiel #2
0
def utm_from_latlon(lats, lons):
    import utm
    import pyproj
    n = utm.latlon_to_zone_number(lats[0], lons[0])
    l = utm.latitude_to_zone_letter(lats[0])
    proj_src = pyproj.Proj('+proj=latlong')
    proj_dst = pyproj.Proj('+proj=utm +zone={}{}'.format(n, l))
    return pyproj.transform(proj_src, proj_dst, lons, lats)
Beispiel #3
0
def utm_from_latlon(lats, lons):
    """
    Fast function to convert latitudes, longitudes to UTM coordinates.
    """
    import utm
    import pyproj
    n = utm.latlon_to_zone_number(lats[0], lons[0])
    l = utm.latitude_to_zone_letter(lats[0])
    proj_src = pyproj.Proj('+proj=latlong')

    srs = '+proj=utm +zone={}{}'.format(n, l)
    if l < 'N':  # latitude bands in the southern hemisphere range from 'C' to 'M'
        srs += ' +south'
    proj_dst = pyproj.Proj(srs)

    return pyproj.transform(proj_src, proj_dst, lons, lats)
Beispiel #4
0
def get_utm_zone(x, y, epsg_in=4326):
    # type: (float, float, int) -> (int, str)
    """
    Get UTM zone from a given coordinate.

    :param x: x-coordinate
    :param y: y-coordinate
    :param epsg_in: EPSG code of input coordinates
    :return: Tuple of UTM zone number as integer and Hemisphere as string
    """
    if epsg_in != 4326:
        x, y = project_coords_epsg(x, y, epsg_in, 4326)
    zone_num = utm.latlon_to_zone_number(y, x)
    zone_letter = utm.latitude_to_zone_letter(y)
    zone_letter = 'N' if zone_letter > 'M' else 'S'
    return zone_num, zone_letter
Beispiel #5
0
    def read(self, filename, **kwargs):
        """
        :param filename: ROI_PAC binary file
        :type filename: str
        :param par_file: Corresponding parameter (:file:`*rsc`) file.
                         (optional)
        :type par_file: str
        :returns: Import dictionary
        :rtype: dict
        :raises: ImportError
        """
        par_file = kwargs.pop('par_file', self._getParameterFile(filename))

        par, geo_ref = self._parseParameterFile(par_file)
        nlines = int(par['FILE_LENGTH'])
        nrows = int(par['WIDTH'])
        wavelength = par['WAVELENGTH']
        heading = par['HEADING_DEG']
        if geo_ref == 'latlon':
            lat_ref = par['Y_FIRST']
            lon_ref = par['X_FIRST']
        elif geo_ref == 'all':
            lat_ref = par['LAT_REF3']
            lon_ref = par['LON_REF3']

        look_ref1 = par['LOOK_REF1']
        look_ref2 = par['LOOK_REF2']
        look_ref3 = par['LOOK_REF3']
        look_ref4 = par['LOOK_REF4']

        utm_zone_letter = utm.latitude_to_zone_letter(lat_ref)
        utm_zone = utm.latlon_to_zone_number(lat_ref, lon_ref)

        look = num.mean(
            num.array([look_ref1, look_ref2, look_ref3, look_ref4]))

        data = num.memmap(filename, dtype='<f4')
        data = data.reshape(nlines, nrows*2)

        displ = data[:, nrows:]
        displ = num.flipud(displ)
        displ[displ == -0.] = num.nan
        displ = displ / (4.*num.pi) * wavelength

        z_scale = par.get('Z_SCALE', 1.)
        z_offset = par.get('Z_OFFSET', 0.)
        displ += z_offset
        displ *= z_scale

        c = self.container

        c.displacement = displ
        c.theta = num.deg2rad(90. - look)
        c.phi = num.deg2rad(-heading + 180.)

        c.meta.title = par.get('TITLE', 'None')
        c.meta.wavelength = par['WAVELENGTH']
        c.bin_file = filename
        c.par_file = par_file

        if geo_ref == 'all':
            if par['X_UNIT'] == 'meters':
                c.frame.spacing = 'meter'
                c.frame.dE = par['X_STEP']
                c.frame.dN = -par['Y_STEP']
                geo_ref = 'utm'

            elif par['X_UNIT'] == 'degree':
                c.frame.spacing = 'degree'
                geo_ref = 'latlon'

        elif geo_ref == 'latlon':
            self._log.info('Georeferencing is in Lat-Lon [degrees].')
            c.frame.spacing = 'degree'
            c.frame.llLat = par['Y_FIRST'] + par['Y_STEP'] * nrows
            c.frame.llLon = par['X_FIRST']

            # c_utm_0 = utm.from_latlon(lat_ref, lon_ref)
            # c_utm_1 = utm.from_latlon(lat_ref + par['Y_STEP'],
            #                           lon_ref + par['X_STEP'])

            # c.frame.dE = c_utm_1[0] - c_utm_0[0]
            # c.frame.dN = abs(c_utm_1[1] - c_utm_0[1])
            c.frame.dE = par['X_STEP']
            c.frame.dN = -par['Y_STEP']

        elif geo_ref == 'utm':
            self._log.info('Georeferencing is in UTM (zone %d%s)',
                           utm_zone, utm_zone_letter)
            y_ll = par['Y_FIRST'] + par['Y_STEP'] * nrows
            c.frame.llLat, c.frame.llLon = utm.to_latlon(
                par['X_FIRST'], y_ll, utm_zone,
                zone_letter=utm_zone_letter)

        return self.container
Beispiel #6
0
    def read(self, filename, **kwargs):
        """
        :param filename: Gamma software parameter file
        :type filename: str
        :param par_file: Corresponding parameter (:file:`*par`) file.
                         (optional)
        :type par_file: str
        :returns: Import dictionary
        :rtype: dict
        :raises: ImportError
        """
        par_file = kwargs.pop('par_file', filename)

        params = self._getParameters(par_file, log=True)

        try:
            params_slc = self._getSLCParameters(par_file)
        except ImportError as e:
            raise e

        fill = None

        nrows = int(params['width'])
        nlines = int(params['nlines'])
        radar_frequency = params_slc.get('radar_frequency', None)

        displ = num.fromfile(filename, dtype='>f4')
        # Resize array if last line is not scanned completely
        if (displ.size % nrows) != 0:
            fill = num.empty(nrows - displ.size % nrows)
            fill.fill(num.nan)
            displ = num.append(displ, fill)

        displ = displ.reshape(nlines, nrows)
        displ[displ == -0.] = num.nan
        displ = num.flipud(displ)

        if radar_frequency is not None:
            radar_frequency = float(radar_frequency)
            self._log.info('Scaling displacement by radar_frequency %f GHz'
                           % (radar_frequency/1e9))
            wavelength = util.C / radar_frequency
            displ /= -4*num.pi
            displ *= wavelength

        else:
            wavelength = 'None'
            self._log.warning(
                'Could not determine radar_frequency from *.slc.par file!'
                ' Leaving displacement to radians.')

        phi = self._getLOSAngles(filename, '*phi*')
        theta = self._getLOSAngles(filename, '*theta*')
        theta = theta

        if isinstance(phi, num.ndarray):
            phi = phi.reshape(nlines, nrows)
            phi = num.flipud(phi)
        if isinstance(theta, num.ndarray):
            theta = theta.reshape(nlines, nrows)
            theta = num.flipud(theta)

        if fill is not None:
            theta = num.append(theta, fill)
            phi = num.append(phi, fill)

        c = self.container

        c.displacement = displ
        c.theta = theta
        c.phi = phi

        c.meta.wavelength = wavelength
        c.meta.title = params.get('title', 'None')

        c.bin_file = filename
        c.par_file = par_file

        if params['DEM_projection'] == 'UTM':
            utm_zone = params['projection_zone']
            try:
                utm_zone_letter = utm.latitude_to_zone_letter(
                    params['center_latitude'])
            except ValueError:
                self._log.warning('Could not parse UTM Zone letter,'
                                  ' defaulting to N!')
                utm_zone_letter = 'N'

            self._log.info('Using UTM reference: Zone %d%s'
                           % (utm_zone, utm_zone_letter))

            dN = params['post_north']
            dE = params['post_east']

            utm_corn_e = params['corner_east']
            utm_corn_n = params['corner_north']

            utm_corn_eo = utm_corn_e + dE * displ.shape[1]
            utm_corn_no = utm_corn_n + dN * displ.shape[0]

            utm_e = num.linspace(utm_corn_e, utm_corn_eo, displ.shape[1])
            utm_n = num.linspace(utm_corn_n, utm_corn_no, displ.shape[0])

            llLat, llLon = utm.to_latlon(utm_e.min(), utm_n.min(),
                                         utm_zone, utm_zone_letter)

            c.frame.llLat = llLat
            c.frame.llLon = llLon

            c.frame.dE = abs(dE)
            c.frame.dN = abs(dN)

        else:
            self._log.info('Using Lat/Lon reference')
            c.frame.spacing = 'degree'
            c.frame.llLat = params['corner_lat'] \
                + params['post_lat'] * nrows
            c.frame.llLon = params['corner_lon']
            c.frame.dE = abs(params['post_lon'])
            c.frame.dN = abs(params['post_lat'])

        return c
Beispiel #7
0
    def read(self, filename, **kwargs):
        """
        :param filename: ROI_PAC binary file
        :type filename: str
        :param par_file: Corresponding parameter (:file:`*rsc`) file.
                         (optional)
        :type par_file: str
        :returns: Import dictionary
        :rtype: dict
        :raises: ImportError
        """
        par_file = kwargs.pop("par_file", self._getParameterFile(filename))

        par, geo_ref = self._parseParameterFile(par_file)
        nlines = int(par["FILE_LENGTH"])
        ncols = int(par["WIDTH"])
        wavelength = par["WAVELENGTH"]
        heading = par["HEADING_DEG"]
        if geo_ref == "latlon":
            lat_ref = par["Y_FIRST"]
            lon_ref = par["X_FIRST"]
        elif geo_ref == "all":
            lat_ref = par["LAT_REF3"]
            lon_ref = par["LON_REF3"]

        look_ref1 = par["LOOK_REF1"]
        look_ref2 = par["LOOK_REF2"]
        look_ref3 = par["LOOK_REF3"]
        look_ref4 = par["LOOK_REF4"]

        utm_zone_letter = utm.latitude_to_zone_letter(lat_ref)
        utm_zone = utm.latlon_to_zone_number(lat_ref, lon_ref)

        look = num.mean(num.array([look_ref1, look_ref2, look_ref3,
                                   look_ref4]))

        data = num.memmap(filename, dtype="<f4")
        data = data.reshape(nlines, ncols * 2)

        displ = data[:, ncols:]
        displ = num.flipud(displ)
        displ[displ == -0.0] = num.nan
        displ = displ / (4.0 * num.pi) * wavelength

        z_scale = par.get("Z_SCALE", 1.0)
        z_offset = par.get("Z_OFFSET", 0.0)
        displ += z_offset
        displ *= z_scale

        container = self.container

        container.displacement = displ
        container.theta = num.deg2rad(90.0 - look)
        container.phi = num.deg2rad(-heading + 180.0)

        container.meta.title = par.get("TITLE", "None")
        container.meta.wavelength = par["WAVELENGTH"]
        container.bin_file = filename
        container.par_file = par_file

        if geo_ref == "all":
            if par["X_UNIT"] == "meters":
                container.frame.spacing = "meter"
                container.frame.dE = par["X_STEP"]
                container.frame.dN = -par["Y_STEP"]
                geo_ref = "utm"

            elif par["X_UNIT"] == "degree":
                container.frame.spacing = "degree"
                geo_ref = "latlon"

        elif geo_ref == "latlon":
            self._log.info("Georeferencing is in Lat-Lon [degrees].")
            container.frame.spacing = "degree"
            container.frame.llLat = par["Y_FIRST"] + par["Y_STEP"] * nlines
            container.frame.llLon = par["X_FIRST"]

            # c_utm_0 = utm.from_latlon(lat_ref, lon_ref)
            # c_utm_1 = utm.from_latlon(lat_ref + par['Y_STEP'],
            #                           lon_ref + par['X_STEP'])

            # c.frame.dE = c_utm_1[0] - c_utm_0[0]
            # c.frame.dN = abs(c_utm_1[1] - c_utm_0[1])
            container.frame.dE = par["X_STEP"]
            container.frame.dN = -par["Y_STEP"]

        elif geo_ref == "utm":
            self._log.info("Georeferencing is in UTM (zone %d%s)", utm_zone,
                           utm_zone_letter)
            y_ll = par["Y_FIRST"] + par["Y_STEP"] * nlines
            container.frame.llLat, container.frame.llLon = utm.to_latlon(
                par["X_FIRST"], y_ll, utm_zone, zone_letter=utm_zone_letter)

        return self.container
Beispiel #8
0
    def read(self, filename, **kwargs):
        """
        :param filename: Gamma software parameter file
        :type filename: str
        :param par_file: Corresponding parameter (:file:`*par`) file.
                         (optional)
        :type par_file: str
        :returns: Import dictionary
        :rtype: dict
        :raises: ImportError
        """
        par_file = kwargs.pop("par_file", filename)

        params = self._getParameters(par_file, log=True)

        try:
            params_slc = self._getSLCParameters(par_file)
        except ImportError as e:
            raise e

        fill = None

        ncols = int(params["width"])
        nlines = int(params["nlines"])
        radar_frequency = float(params_slc.get("radar_frequency", None))

        displ = num.fromfile(filename, dtype=">f4")
        # Resize array if last line is not scanned completely
        if (displ.size % ncols) != 0:
            fill = num.empty(ncols - displ.size % ncols)
            fill.fill(num.nan)
            displ = num.append(displ, fill)

        displ = displ.reshape(nlines, ncols)
        displ[displ == -0.0] = num.nan
        displ = num.flipud(displ)

        if radar_frequency is not None:
            radar_frequency = float(radar_frequency)
            self._log.info("Scaling displacement by radar_frequency %f GHz" %
                           (radar_frequency / 1e9))
            wavelength = util.C / radar_frequency
            displ /= -4 * num.pi
            displ *= wavelength

        else:
            wavelength = "None"
            self._log.warning(
                "Could not determine radar_frequency from *.slc.par file!"
                " Leaving displacement to radians.")

        phi = self._getLOSAngles(filename, "*phi*")
        theta = self._getLOSAngles(filename, "*theta*")
        theta = theta

        if isinstance(phi, num.ndarray):
            phi = phi.reshape(nlines, ncols)
            phi = num.flipud(phi)
        if isinstance(theta, num.ndarray):
            theta = theta.reshape(nlines, ncols)
            theta = num.flipud(theta)

        if fill is not None:
            theta = num.append(theta, fill)
            phi = num.append(phi, fill)

        container = self.container

        container.displacement = displ
        container.theta = theta
        container.phi = phi

        container.meta.wavelength = wavelength
        container.meta.title = params.get("title", "None")

        container.bin_file = filename
        container.par_file = par_file

        if params["DEM_projection"] == "UTM":
            utm_zone = params["projection_zone"]
            try:
                utm_zone_letter = utm.latitude_to_zone_letter(
                    params["center_latitude"])
            except ValueError:
                self._log.warning("Could not parse UTM Zone letter,"
                                  " defaulting to N!")
                utm_zone_letter = "N"

            self._log.info("Using UTM reference: Zone %d%s" %
                           (utm_zone, utm_zone_letter))

            dN = params["post_north"]
            dE = params["post_east"]

            utm_corn_e = params["corner_east"]
            utm_corn_n = params["corner_north"]

            utm_corn_eo = utm_corn_e + dE * displ.shape[1]
            utm_corn_no = utm_corn_n + dN * displ.shape[0]

            utm_e = num.linspace(utm_corn_e, utm_corn_eo, displ.shape[1])
            utm_n = num.linspace(utm_corn_n, utm_corn_no, displ.shape[0])

            llLat, llLon = utm.to_latlon(utm_e.min(), utm_n.min(), utm_zone,
                                         utm_zone_letter)

            container.frame.llLat = llLat
            container.frame.llLon = llLon

            container.frame.dE = abs(dE)
            container.frame.dN = abs(dN)

        else:
            self._log.info("Using Lat/Lon reference")
            container.frame.spacing = "degree"
            container.frame.llLat = params[
                "corner_lat"] + params["post_lat"] * nlines
            container.frame.llLon = params["corner_lon"]
            container.frame.dE = abs(params["post_lon"])
            container.frame.dN = abs(params["post_lat"])

        return container
Beispiel #9
0
    def read(self, filename, **kwargs):
        """
        :param filename: Gamma software parameter file
        :type filename: str
        :param par_file: Corresponding parameter (:file:`*par`) file.
                         (optional)
        :type par_file: str
        :returns: Import dictionary
        :rtype: dict
        :raises: ImportError
        """
        par_file, params = self._getParameters(op.dirname(
            op.abspath(filename)),
                                               log=True)

        ncols = int(params["num_samples_per_line"])
        nlines = int(params["num_output_lines"])
        radar_frequency = params.get("radar_frequency", None)
        heading_par = float(params.get("centre_heading", None))
        displ = num.fromfile(filename, dtype=">f4")

        # Resize array if last line is not scanned completely
        fill = 0
        if (displ.size % ncols) != 0:
            fill = num.empty(ncols - displ.size % ncols)
            fill.fill(num.nan)
            displ = num.append(displ, fill)

        displ = displ.reshape(nlines, ncols)
        displ[displ == -0.0] = num.nan
        displ = num.flipud(displ)

        if radar_frequency and "_dsp_" not in par_file:
            radar_frequency = float(radar_frequency)
            radar_frequency *= 1e6  # SNAP gives MHz
            self._log.info("Scaling displacement by radar_frequency %f GHz",
                           radar_frequency / 1e9)
            wavelength = util.C / radar_frequency
            displ /= -4 * num.pi
            displ *= wavelength

        elif not radar_frequency and "_dsp_" not in par_file:
            self._log.warning("Could not determine radar_frequency!")
            wavelength = None

        else:
            wavelength = None

        inc_angle = self._getLOSAngles(
            filename, "incidenceAngleFromEllipsoid.rslc").copy()
        if fill:
            inc_angle = num.append(inc_angle, fill)
        inc_angle[inc_angle == 0.0] = num.nan

        phi = num.full_like(displ, (180.0 - heading_par))
        theta = 90.0 - inc_angle.reshape(displ.shape)
        theta = num.flipud(theta)

        c = self.container

        c.displacement = displ
        c.theta = theta * d2r
        c.phi = phi * d2r

        c.meta.wavelength = wavelength
        c.meta.title = params.get("PRODUCT", "SNAP Import")
        c.meta.satellite_name = params.get("SPH_DESCRIPTOR", "None")

        orb = params.get("PASS", None)
        c.meta.orbital_node = orb.title() if orb else None

        c.bin_file = filename
        c.par_file = par_file

        if params["map_projection"] == "UTM":
            utm_zone = params["projection_zone"]
            try:
                utm_zone_letter = utm.latitude_to_zone_letter(
                    params["center_latitude"])
            except ValueError:
                self._log.warning("Could not parse UTM Zone letter,"
                                  " defaulting to N!")
                utm_zone_letter = "N"

            self._log.info("Using UTM reference: Zone %d%s", utm_zone,
                           utm_zone_letter)
            c.frame.spacing = "meter"

            dN = abs(params["post_north"])
            dE = abs(params["post_east"])

            utm_corn_e = params["corner_east"]
            utm_corn_n = params["corner_north"]

            utm_corn_eo = utm_corn_e + dE * displ.shape[1]
            utm_corn_no = utm_corn_n + dN * displ.shape[0]

            utm_e = num.linspace(utm_corn_e, utm_corn_eo, displ.shape[1])
            utm_n = num.linspace(utm_corn_n, utm_corn_no, displ.shape[0])

            llLat, llLon = utm.to_latlon(utm_e.min(), utm_n.min(), utm_zone,
                                         utm_zone_letter)

        else:
            self._log.info("Using Lat/Lon reference")
            c.frame.spacing = "degree"

            if orb.lower() == "ascending":
                llLat = params["last_near_lat"]
                llLon = params["last_near_long"]

            elif orb.lower() == "descending":
                llLat = params["last_far_lat"]
                llLon = params["first_near_long"]

            else:
                raise AttributeError("cannot determine orbit")

            dE = abs(params["lon_pixel_res"])
            dN = abs(params["lat_pixel_res"])

        c.frame.llLat = llLat
        c.frame.llLon = llLon

        c.frame.dE = dE
        c.frame.dN = dN

        return c
Beispiel #10
0
    def read(self, filename, **kwargs):
        """
        :param filename: Gamma software parameter file
        :type filename: str
        :param par_file: Corresponding parameter (:file:`*par`) file.
                         (optional)
        :type par_file: str
        :returns: Import dictionary
        :rtype: dict
        :raises: ImportError
        """
        par_file, params = self._getParameters(
            op.dirname(op.abspath(filename)), log=True)

        ncols = int(params['num_samples_per_line'])
        nlines = int(params['num_output_lines'])
        radar_frequency = params.get('radar_frequency', None)
        heading_par = float(params.get('centre_heading', None))
        displ = num.fromfile(filename, dtype='>f4')

        # Resize array if last line is not scanned completely
        fill = 0
        if (displ.size % ncols) != 0:
            fill = num.empty(ncols - displ.size % ncols)
            fill.fill(num.nan)
            displ = num.append(displ, fill)

        displ = displ.reshape(nlines, ncols)
        displ[displ == -0.] = num.nan
        displ = num.flipud(displ)

        if radar_frequency and '_dsp_' not in par_file:
            radar_frequency = float(radar_frequency)
            radar_frequency *= 1e6  # SNAP gives MHz
            self._log.info('Scaling displacement by radar_frequency %f GHz',
                           radar_frequency/1e9)
            wavelength = util.C / radar_frequency
            displ /= -4*num.pi
            displ *= wavelength

        elif not radar_frequency and '_dsp_' not in par_file:
            self._log.warning('Could not determine radar_frequency!')
            wavelength = None

        else:
            wavelength = None

        inc_angle = self._getLOSAngles(
            filename, 'incidenceAngleFromEllipsoid.rslc').copy()
        if fill:
            inc_angle = num.append(inc_angle, fill)
        inc_angle[inc_angle == 0.] = num.nan

        phi = num.full_like(displ, (180. - heading_par))
        theta = 90. - inc_angle.reshape(displ.shape)
        theta = num.flipud(theta)

        c = self.container

        c.displacement = displ
        c.theta = theta * d2r
        c.phi = phi * d2r

        c.meta.wavelength = wavelength
        c.meta.title = params.get('PRODUCT', 'SNAP Import')
        c.meta.satellite_name = params.get('SPH_DESCRIPTOR', 'None')

        orb = params.get('PASS', None)
        c.meta.orbital_node = orb.title() if orb else None

        c.bin_file = filename
        c.par_file = par_file

        if params['map_projection'] == 'UTM':
            utm_zone = params['projection_zone']
            try:
                utm_zone_letter = utm.latitude_to_zone_letter(
                    params['center_latitude'])
            except ValueError:
                self._log.warning('Could not parse UTM Zone letter,'
                                  ' defaulting to N!')
                utm_zone_letter = 'N'

            self._log.info('Using UTM reference: Zone %d%s',
                           utm_zone, utm_zone_letter)
            c.frame.spacing = 'meter'

            dN = abs(params['post_north'])
            dE = abs(params['post_east'])

            utm_corn_e = params['corner_east']
            utm_corn_n = params['corner_north']

            utm_corn_eo = utm_corn_e + dE * displ.shape[1]
            utm_corn_no = utm_corn_n + dN * displ.shape[0]

            utm_e = num.linspace(utm_corn_e, utm_corn_eo, displ.shape[1])
            utm_n = num.linspace(utm_corn_n, utm_corn_no, displ.shape[0])

            llLat, llLon = utm.to_latlon(utm_e.min(), utm_n.min(),
                                         utm_zone, utm_zone_letter)

        else:
            self._log.info('Using Lat/Lon reference')
            c.frame.spacing = 'degree'

            if orb.lower() == 'ascending':
                llLat = params['last_near_lat']
                llLon = params['last_near_long']

            elif orb.lower() == 'descending':
                llLat = params['last_far_lat']
                llLon = params['first_near_long']

            else:
                raise AttributeError('cannot determine orbit')

            dE = abs(params['lon_pixel_res'])
            dN = abs(params['lat_pixel_res'])

        c.frame.llLat = llLat
        c.frame.llLon = llLon

        c.frame.dE = dE
        c.frame.dN = dN

        return c
Beispiel #11
0
    def read(self, filename, **kwargs):
        """
        :param filename: Gamma software parameter file
        :type filename: str
        :param par_file: Corresponding parameter (:file:`*par`) file.
                         (optional)
        :type par_file: str
        :returns: Import dictionary
        :rtype: dict
        :raises: ImportError
        """
        par_file = kwargs.pop('par_file',
                              self._getParameterFile(filename))
        par = self._parseParameterFile(par_file)
        fill = None

        nrows = int(par['width'])
        nlines = int(par['nlines'])
        radar_frequency = par.get('radar_frequency', None)

        displ = num.fromfile(filename, dtype='>f4')
        # Resize array if last line is not scanned completely
        if (displ.size % nrows) != 0:
            fill = num.empty(nrows - displ.size % nrows)
            fill.fill(num.nan)
            displ = num.append(displ, fill)

        displ = displ.reshape(nlines, nrows)
        displ[displ == -0.] = num.nan
        displ = num.fliplr(displ)

        phi = self._getAngle(filename, '*phi*')
        theta = self._getAngle(filename, '*theta*')
        theta = num.cos(theta)

        if isinstance(phi, num.ndarray):
            phi = phi.reshape(nlines, nrows)
        if isinstance(theta, num.ndarray):
            theta = theta.reshape(nlines, nrows)

        if fill is not None:
            theta = num.append(theta, fill)
            phi = num.append(phi, fill)

        c = self.container

        if radar_frequency is not None:
            self._log.info('Scaling radian displacement by radar_frequency')
            wavelength = 299792458. / radar_frequency
            displ = (displ / (4.*num.pi)) * wavelength
            c['meta']['wavelength'] = wavelength

        c['displacement'] = displ
        c['theta'] = theta
        c['phi'] = phi

        c['meta']['title'] = par.get('title', 'None')
        c['bin_file'] = filename
        c['par_file'] = par_file

        if par['DEM_projection'] == 'UTM':
            self._log.info('Parameter file provides UTM reference')
            import utm
            c['displacement'] = num.transpose(displ/100)
            c['theta'] = num.transpose(theta)
            c['phi'] = num.transpose(phi)
            utm_zone = par['projection_zone']
            try:
                utm_zone_letter = utm.latitude_to_zone_letter(
                    par['center_latitude'])
            except ValueError:
                self._log.warning('Could not parse UTM Zone letter,'
                                  ' defaulting to N!')
                utm_zone_letter = 'N'

            utm_e = utm_n = None
            dN = par['post_north']
            dE = par['post_east']
            utm_corn_e = par['corner_east']
            utm_corn_n = par['corner_north']

            utm_corn_eo = utm_corn_e + dE * displ.shape[1]
            utm_corn_no = utm_corn_n + dN * displ.shape[0]

            utm_e = num.linspace(utm_corn_e, utm_corn_eo, displ.shape[1])
            utm_n = num.linspace(utm_corn_n, utm_corn_no, displ.shape[0])

            c['frame']['llLat'], c['frame']['llLon'] =\
                utm.to_latlon(utm_e.min(), utm_n.min(),
                              utm_zone, utm_zone_letter)
            urlat, urlon = utm.to_latlon(utm_e.max(), utm_n.max(),
                                         utm_zone, utm_zone_letter)
            c['frame']['dLat'] =\
                (urlat - c['frame']['llLat']) / displ.shape[0]

            c['frame']['dLon'] =\
                (urlon - c['frame']['llLon']) / displ.shape[1]
        else:
            self._log.info('Parameter file provides Lat/Lon reference')
            c['frame']['llLat'] = par['corner_lat'] + par['post_lat'] * nrows
            c['frame']['llLon'] = par['corner_lon']
            c['frame']['dLon'] = par['post_lon']
            c['frame']['dLat'] = par['post_lat']
        return self.container
Beispiel #12
0
def zonestring_from_lonlat(lon, lat):
    import utm
    n = utm.latlon_to_zone_number(lat, lon)
    l = utm.latitude_to_zone_letter(lat)
    s = "%d%s" % (n, l)
    return s
Beispiel #13
0
def aoi_info_from_geotiff_gt(ref_filename,
                             gt_filename,
                             padding=0.0,
                             height_guard=[-5, +5]):
    ''' aoi_from_gt
    Returns an aoi from an image and a gt

    padding: relative to the size the gt region (e.g. 0.1 adds a 10% of the extension of
    the region on the four boundaries)
    '''

    # get the dimensions of the first image
    width, height, pixel_dim = s2p.common.image_size_gdal(ref_filename)

    # get the rpc of the first image
    ref_image_rpc = rpcm.rpc_from_geotiff(ref_filename)
    # get the localization of the center of the image
    lon_center, lat_center = ref_image_rpc.localization(
        width // 2, height // 2, 0)

    zone_number = utm.latlon_to_zone_number(lat_center, lon_center)
    zone_letter = utm.latitude_to_zone_letter(lat_center)

    # Build the AOI of the GT ------------------------------

    gt_metadata = readGTIFFmeta(gt_filename)
    bounding_box = gt_metadata[1]
    gt_min_easting = bounding_box.left
    gt_max_easting = bounding_box.right
    gt_min_northing = bounding_box.bottom
    gt_max_northing = bounding_box.top

    # padding
    gt_easting_extension = gt_max_easting - gt_min_easting
    gt_northing_extension = gt_max_northing - gt_min_northing
    gt_min_easting -= padding * gt_easting_extension
    gt_max_easting += padding * gt_easting_extension
    gt_min_northing -= padding * gt_northing_extension
    gt_max_northing += padding * gt_northing_extension
    # update the extension
    gt_easting_extension = gt_max_easting - gt_min_easting
    gt_northing_extension = gt_max_northing - gt_min_northing

    # convert easting, northing to lon,lat
    gt_min_lat, gt_min_lon = utm.to_latlon(gt_min_easting, gt_min_northing,
                                           zone_number, zone_letter)
    gt_max_lat, gt_max_lon = utm.to_latlon(gt_max_easting, gt_max_northing,
                                           zone_number, zone_letter)

    zone_hemisphere = 'N' if gt_min_lat > 0 else 'S'

    aoi = {
        'coordinates': [[[gt_min_lon, gt_min_lat], [gt_min_lon, gt_max_lat],
                         [gt_max_lon, gt_max_lat], [gt_max_lon, gt_min_lat],
                         [gt_min_lon, gt_min_lat]]],
        'type':
        'Polygon'
    }

    utm_bbx = [
        gt_min_easting, gt_max_easting, gt_min_northing, gt_max_northing
    ]
    lonlat_bbx = [gt_min_lon, gt_max_lon, gt_min_lat, gt_max_lat]

    # get min and max height from the gt image
    gt = s2p.common.gdal_read_as_array_with_nans(gt_filename)
    min_height, max_height = robust_image_min_max(gt)
    # add height guard
    min_height += height_guard[0]
    max_height += height_guard[1]

    return aoi, min_height, max_height, zone_hemisphere, zone_letter, zone_number, utm_bbx, lonlat_bbx
Beispiel #14
0
 def convert_to_latlon(self, zone: LatLon):
     zone_number = latlon_to_zone_number(zone.lat, zone.lon)
     zone_letter = latitude_to_zone_letter(zone.lat)
     lat, lon = to_latlon(self.east, self.north, zone_number, zone_letter)
     return LatLon(lat, lon)
def get_grid_latitudes_longitudes_from_aoi(aoi, resolution=1, **kwargs):
    r""" get_grid_latitudes_longitudes_from_aoi
    
    Returns the arrays of latitudes and longitudes for a certain grid resolution on the aoi .
    
    Parameters
    ----------
    aoi :   dict with 'coordinates' key
            Area of interest (a rectangle is expected)
    resolution : double
            Resolution of the grid. Defaults to 1 (meter)
    **kwargs
        Arbitrary optional keyword argument.
        grid_shape : tuple or list or array of two integers defining the grid shape (rows (latitudes), cols (longitudes))
                     This parameter overrides resolution
    
    Returns
    -------
    latitudes:  1D numpy array
            Array of latitudes of the grid
    longitudes: 1D numpy array
            Array of longitudes of the grid
    """

    min_easting, max_easting, min_northing, max_northing = utils.utm_bounding_box_from_lonlat_aoi(
        aoi)

    if 'grid_shape' in kwargs.keys():
        m, n = kwargs.get('grid_shape')

        latitudes = np.arange(
            start=np.min(np.array(aoi['coordinates'])[0, :, 1]),
            stop=np.max(np.array(aoi['coordinates'])[0, :, 1]),
            step=(np.max(np.array(aoi['coordinates'])[0, :, 1]) -
                  np.min(np.array(aoi['coordinates'])[0, :, 1])) / m)

        longitudes = np.arange(
            start=np.min(np.array(aoi['coordinates'])[0, :, 0]),
            stop=np.max(np.array(aoi['coordinates'])[0, :, 0]),
            step=(np.max(np.array(aoi['coordinates'])[0, :, 0]) -
                  np.min(np.array(aoi['coordinates'])[0, :, 0])) / n)

    else:

        Northings = np.arange(min_northing, max_northing, resolution)
        Eastings = np.arange(min_easting, max_easting, resolution)

        zone_number = utm.latlon_to_zone_number(aoi['coordinates'][0][0][1],
                                                aoi['coordinates'][0][0][0])
        zone_letter = utm.latitude_to_zone_letter(aoi['coordinates'][0][0][1])
        latitudes = [
            utm.to_latlon(Eastings[0], Northings[i], zone_number,
                          zone_letter)[0] for i in range(len(Northings))
        ]
        longitudes = [
            utm.to_latlon(Eastings[i], Northings[0], zone_number,
                          zone_letter)[1] for i in range(len(Eastings))
        ]

        latitudes = np.array(latitudes)
        longitudes = np.array(longitudes)

    return latitudes, longitudes