Ejemplo n.º 1
0
 def get_radiometric():
     # type: () -> RadiometricType
     return RadiometricType(BetaZeroSFPoly=[
         [
             float(hf['calibration_factor'][()]),
         ],
     ])
Ejemplo n.º 2
0
Archivo: csk.py Proyecto: LordHui/sarpy
 def update_radiometric(sicd, band_name):
     # type: (SICDType, str) -> None
     if h5_dict['Range Spreading Loss Compensation Geometry'] != 'NONE':
         slant_range = h5_dict['Reference Slant Range']
         exp = h5_dict['Reference Slant Range Exponent']
         sf = slant_range**(2*exp)
         if h5_dict['Calibration Constant Compensation Flag'] == 0:
             rsf = h5_dict['Rescaling Factor']
             cal = band_dict[band_name]['Calibration Constant']
             sf /= cal*(rsf**2)
         sicd.Radiometric = RadiometricType(BetaZeroSFPoly=Poly2DType(Coefs=[[sf, ], ]))
Ejemplo n.º 3
0
        def get_radiometric() -> Union[None, RadiometricType]:
            if img['radiometry'].lower() != 'beta_nought':
                logger.warning('Got unrecognized Capella radiometry {},\n\t'
                               'skipping the radiometric metadata'.format(
                                   img['radiometry']))
                return None

            return RadiometricType(BetaZeroSFPoly=[
                [
                    img['scale_factor']**2,
                ],
            ])
Ejemplo n.º 4
0
        def define_radiometric():
            def get_poly(ds, name):
                array = ds[:]
                fill = ds.attrs['_FillValue']
                boolc = (array != fill)

                if numpy.any(boolc):
                    array = array[boolc]
                    if numpy.any(array != array[0]):
                        coefs, residuals, rank, sing_values = two_dim_poly_fit(
                            coords_rg_2d[boolc], coords_az_2d[boolc], array,
                            x_order=3, y_order=3, x_scale=1e-3, y_scale=1e-3, rcond=1e-40)
                        logger.info(
                            'The {} fit details:\n\t'
                            'root mean square residuals = {}\n\t'
                            'rank = {}\n\t'
                            'singular values = {}'.format(name, residuals, rank, sing_values))
                    else:
                        # it's constant, so just use a constant polynomial
                        coefs = [[array[0], ], ]
                        logger.info('The {} values are constant'.format(name))
                    return Poly2DType(Coefs=coefs)
                else:
                    logger.warning('No non-trivial values for {} provided.'.format(name))
                    return None

            beta0_poly = get_poly(beta0, 'beta0')
            gamma0_poly = get_poly(gamma0, 'gamma0')
            sigma0_poly = get_poly(sigma0, 'sigma0')

            nesz = hf['/science/LSAR/SLC/metadata/calibrationInformation/frequency{}/{}/nes0'.format(freq_name,
                                                                                                     pol_name)][:]
            noise_samples = nesz - (10 * numpy.log10(sigma0_poly.Coefs[0, 0]))

            coefs, residuals, rank, sing_values = two_dim_poly_fit(
                coords_rg_2d, coords_az_2d, noise_samples,
                x_order=3, y_order=3, x_scale=1e-3, y_scale=1e-3, rcond=1e-40)
            logger.info(
                'The noise_poly fit details:\n\t'
                'root mean square residuals = {}\n\t'
                'rank = {}\n\t'
                'singular values = {}'.format(
                    residuals, rank, sing_values))
            t_sicd.Radiometric = RadiometricType(
                BetaZeroSFPoly=beta0_poly,
                GammaZeroSFPoly=gamma0_poly,
                SigmaZeroSFPoly=sigma0_poly,
                NoiseLevel=NoiseLevelType_(
                    NoiseLevelType='ABSOLUTE', NoisePoly=Poly2DType(Coefs=coefs)))
Ejemplo n.º 5
0
Archivo: csk.py Proyecto: Ryanzgy/sarpy
 def update_radiometric(sicd, band_name):
     # type: (SICDType, str) -> None
     if 'KMP' in self._satellite:
         # TODO: skipping for now - strange results for kompsat
         return
     if h5_dict['Range Spreading Loss Compensation Geometry'] != 'NONE':
         slant_range = h5_dict['Reference Slant Range']
         exp = h5_dict['Reference Slant Range Exponent']
         sf = slant_range**(2*exp)
         rsf = h5_dict['Rescaling Factor']
         sf /= rsf * rsf
         if h5_dict.get('Calibration Constant Compensation Flag', None) == 0:
             cal = band_dict[band_name]['Calibration Constant']
             sf /= cal
         sicd.Radiometric = RadiometricType(BetaZeroSFPoly=Poly2DType(Coefs=[[sf, ], ]))
Ejemplo n.º 6
0
 def update_radiometric(sicd: SICDType, band_name: str) -> None:
     if self.mission_id in ['KMPS', 'CSG']:
         # TODO: skipping for now - strange results for flag == 77. Awaiting gidance - see Wade.
         return
     if h5_dict['Range Spreading Loss Compensation Geometry'] != 'NONE':
         slant_range = h5_dict['Reference Slant Range']
         exp = h5_dict['Reference Slant Range Exponent']
         sf = slant_range**(2 * exp)
         rsf = h5_dict['Rescaling Factor']
         sf /= rsf * rsf
         if h5_dict.get('Calibration Constant Compensation Flag',
                        None) == 0:
             cal = band_dict[band_name]['Calibration Constant']
             sf /= cal
         sicd.Radiometric = RadiometricType(BetaZeroSFPoly=Poly2DType(
             Coefs=[
                 [
                     sf,
                 ],
             ]))
Ejemplo n.º 7
0
    def _get_radiometric(self, image_data, grid):
        """
        Gets the Radiometric metadata.

        Parameters
        ----------
        image_data : ImageDataType
        grid : GridType

        Returns
        -------
        RadiometricType
        """
        def perform_radiometric_fit(component_file):
            comp_struct = _parse_xml(component_file,
                                     without_ns=(self.generation != 'RS2'))
            comp_values = numpy.array([
                float(entry)
                for entry in comp_struct.find('./gains').text.split()
            ],
                                      dtype=numpy.float64)
            comp_values = 1. / (comp_values * comp_values
                                )  # adjust for sicd convention
            if numpy.all(comp_values == comp_values[0]):
                return numpy.array([
                    [
                        comp_values[0],
                    ],
                ], dtype=numpy.float64)
            else:
                # fit a 1-d polynomial in range
                coords_rg = (numpy.arange(image_data.NumRows) -
                             image_data.SCPPixel.Row) * grid.Row.SS
                if self.generation == 'RCM':  # the rows are sub-sampled
                    start = int(comp_struct.find('./pixelFirstLutValue').text)
                    num_vs = int(comp_struct.find('./numberOfValues').text)
                    t_step = int(comp_struct.find('./stepSize').text)
                    if t_step > 0:
                        rng_indices = numpy.arange(start, num_vs, t_step)
                    else:
                        rng_indices = numpy.arange(start, -1, t_step)
                    coords_rg = coords_rg[rng_indices]
                return numpy.atleast_2d(
                    polynomial.polyfit(coords_rg, comp_values, 3))

        base_path = os.path.dirname(self.file_name)
        if self.generation == 'RS2':
            beta_file = os.path.join(
                base_path,
                self._find('./imageAttributes'
                           '/lookupTable'
                           '[@incidenceAngleCorrection="Beta Nought"]').text)
            sigma_file = os.path.join(
                base_path,
                self._find('./imageAttributes'
                           '/lookupTable'
                           '[@incidenceAngleCorrection="Sigma Nought"]').text)
            gamma_file = os.path.join(
                base_path,
                self._find('./imageAttributes'
                           '/lookupTable'
                           '[@incidenceAngleCorrection="Gamma"]').text)
        elif self.generation == 'RCM':
            beta_file = os.path.join(
                base_path, 'calibration',
                self._find('./imageReferenceAttributes'
                           '/lookupTableFileName'
                           '[@sarCalibrationType="Beta Nought"]').text)
            sigma_file = os.path.join(
                base_path, 'calibration',
                self._find('./imageReferenceAttributes'
                           '/lookupTableFileName'
                           '[@sarCalibrationType="Sigma Nought"]').text)
            gamma_file = os.path.join(
                base_path, 'calibration',
                self._find('./imageReferenceAttributes'
                           '/lookupTableFileName'
                           '[@sarCalibrationType="Gamma"]').text)
        else:
            raise ValueError('unhandled generation {}'.format(self.generation))

        if not os.path.isfile(beta_file):
            logging.error(
                msg="Beta calibration information should be located in file {}, "
                "which doesn't exist.".format(beta_file))
            return None

        # perform beta, sigma, gamma fit
        beta_zero_sf_poly = perform_radiometric_fit(beta_file)
        sigma_zero_sf_poly = perform_radiometric_fit(sigma_file)
        gamma_zero_sf_poly = perform_radiometric_fit(gamma_file)

        # construct noise poly
        noise_level = None
        if self.generation == 'RS2':
            # noise is in the main product.xml
            beta0_element = self._find(
                './sourceAttributes/radarParameters'
                '/referenceNoiseLevel[@incidenceAngleCorrection="Beta Nought"]'
            )
        elif self.generation == 'RCM':
            noise_file = os.path.join(
                base_path, 'calibration',
                self._find(
                    './imageReferenceAttributes/noiseLevelFileName').text)
            noise_root = _parse_xml(noise_file, without_ns=True)
            noise_levels = noise_root.findall('./referenceNoiseLevel')
            beta0s = [
                entry for entry in noise_levels
                if entry.find('sarCalibrationType').text.startswith('Beta')
            ]
            beta0_element = beta0s[0] if len(beta0s) > 0 else None
        else:
            raise ValueError('unhandled generation {}'.format(self.generation))

        if beta0_element is not None:
            noise_level = NoiseLevelType_(NoiseLevelType='ABSOLUTE')
            pfv = float(beta0_element.find('pixelFirstNoiseValue').text)
            step = float(beta0_element.find('stepSize').text)
            beta0s = numpy.array([
                float(x)
                for x in beta0_element.find('noiseLevelValues').text.split()
            ])
            range_coords = grid.Row.SS * (numpy.arange(len(beta0s)) * step +
                                          pfv - image_data.SCPPixel.Row)
            noise_poly = polynomial.polyfit(
                range_coords, beta0s - 10 * numpy.log10(
                    polynomial.polyval(range_coords, beta_zero_sf_poly[:, 0])),
                2)
            noise_level.NoisePoly = Poly2DType(
                Coefs=numpy.atleast_2d(noise_poly))

        return RadiometricType(BetaZeroSFPoly=beta_zero_sf_poly,
                               SigmaZeroSFPoly=sigma_zero_sf_poly,
                               GammaZeroSFPoly=gamma_zero_sf_poly,
                               NoiseLevel=noise_level)