def test_write_and_get_xpath(self):
     from xml.etree import ElementTree
     from Common import FileSystem
     file_path = os.path.join(self.root, "dummy_xml.xml")
     mission_expected = "DummyMission"
     xpath = "./Fixed_Header/Mission"
     root = ElementTree.Element("Earth_Explorer_Header")
     sub = ElementTree.SubElement(root, "Fixed_Header")
     ElementTree.SubElement(sub, "Mission").text = mission_expected
     ElementTree.SubElement(root, "Variable_Header")
     XMLTools.write_xml(root, file_path)
     self.assertTrue(os.path.exists(file_path))
     mission_calculated = XMLTools.get_xpath(file_path, xpath)[0].text
     mission_calculated_2 = XMLTools.get_single_xpath(file_path, xpath)
     self.assertEqual(mission_calculated, mission_expected)
     self.assertEqual(mission_expected, mission_calculated_2)
     FileSystem.remove_file(file_path)
Beispiel #2
0
 def get_mission(hdr):
     """
     Return the "Mission" field for a single GIPP file.
     :param hdr: The full path to the HDR file
     :return:
     """
     from Common import XMLTools
     return XMLTools.get_single_xpath(hdr, "./Fixed_Header/Mission")
    def process_one_file(output_dir, aot_file, rh_file, mr_file, mission="s2"):
        """
        Process a single netcdf triplet
        :param output_dir: The existing output directory
        :param aot_file: The AOT .netcdf file
        :param rh_file: The RH .netcdf file
        :param mr_file: The MR .netcdf file
        :param mission: The desired mission.
        :return: Writes the DBL.DIR and HDR to the given output directory
        """
        from Common import XMLTools
        from collections import namedtuple
        satellite = namedtuple('satellite', ('full_name', 'short_name'))
        mission_choices = {
            "s2": satellite("SENTINEL-2_", "S2_"),
            "l8": satellite("LANDSAT_8", "L8"),
            "ve": satellite("VENuS", "VE"),
            "gen": satellite("GENERIC", "GEN")
        }
        current_satellite = mission_choices[mission]
        date_end = datetime(year=2100, month=1, day=1)
        acq_date = RawCAMSArchive.get_raw_cams_date(aot_file)[0]

        if not acq_date:
            raise ValueError("Cannot get Acquisition date for CAMS file %s " %
                             aot_file)

        output_file_basename = "{}_OPER_EXO_CAMS_{}_{}".format(
            current_satellite.short_name, acq_date.strftime("%Y%m%dT%H%M%S"),
            date_end.strftime("%Y%m%dT%H%M%S"))

        # Create archive
        netcdf = [aot_file, rh_file, mr_file]
        dbl_filename, cams = RawCAMSArchive.create_archive(
            output_dir, netcdf, output_file_basename)

        # Create hdr
        output_filename = os.path.join(output_dir,
                                       output_file_basename + ".HDR")
        basename_out = os.path.basename(os.path.splitext(output_filename)[0])
        root = RawCAMSArchive.get_cams_root(mission)
        RawCAMSArchive._update_nodes(root, current_satellite.full_name,
                                     basename_out, date_end, acq_date, cams)
        XMLTools.write_xml(root, output_filename)
Beispiel #4
0
 def validity(self):
     if self.level == "l1c" and os.path.exists(self.metadata_file):
         return True
     if self.level == "l2a":
         try:
             jpi = FileSystem.find_single("*JPI_ALL.xml", self.fpath)
         except ValueError:
             return False
         validity_xpath = "./Processing_Flags_And_Modes_List/Processing_Flags_And_Modes/Value"
         processing_flags = XMLTools.get_xpath(jpi, validity_xpath)
         validity_flags = [flg.text for flg in processing_flags]
         if "L2VALD" in validity_flags:
             return True
     return False
Beispiel #5
0
    def to_maja_format(self,
                       platform_id,
                       mission_field,
                       mnt_resolutions,
                       coarse_res,
                       full_res_only=False):
        """
        Writes an MNT in Maja (=EarthExplorer) format: A folder .DBL.DIR containing the rasters and an
        accompanying .HDR xml-file.
        The two files follow the maja syntax::
            *AUX_REFDE2*.(HDR|DBL.DIR)
        :param platform_id: The platform ID of two digits (e.g. S2_ for Sentinel2A/B; VS for Venus)
        :param mission_field: Similar to the platform ID, this is used in the <Mission>-field for the HDR file.
                              e.g. SENTINEL-2 for S2
        :param mnt_resolutions: A dict containing the resolutions for the given sensor. E.g.::
            {"XS": (10, -10)}
        :param coarse_res: A tuple of int describing the coarse resolution. E.g.::
            (240, -240).
        :param full_res_only:  If True, no coarse_res rasters will be created.
        :return: Writes the .DBL.DIR and .HDR into the specified self.dem_dir
        """
        assert len(mnt_resolutions) >= 1
        basename = str(
            "%s_TEST_AUX_REFDE2_%s_%s" %
            (platform_id, self.site.nom, str(self.dem_version).zfill(4)))

        # Get mnt data
        mnt_max_res = self.prepare_mnt()

        # Water mask not needed with optional coarse_res writing:
        if coarse_res and not full_res_only:
            # Get water data
            self.prepare_water_data()
        mnt_res = (self.site.res_x, self.site.res_y)
        dbl_base = basename + ".DBL.DIR"
        dbl_dir = os.path.join(self.dem_dir, dbl_base)
        FileSystem.create_directory(dbl_dir)
        hdr = os.path.join(self.dem_dir, basename + ".HDR")

        # Calulate gradient mask at MNT resolution:
        mnt_in, drv = ImageIO.tiff_to_array(mnt_max_res, array_only=False)
        grad_y_mnt, grad_x_mnt = self.calc_gradient(mnt_in, self.site.res_x,
                                                    self.site.res_y)

        full_res = (int(mnt_resolutions[0]["val"].split(" ")[0]),
                    int(mnt_resolutions[0]["val"].split(" ")[1]))

        grad_x = self.resample_to_full_resolution(grad_x_mnt,
                                                  mnt_resolution=mnt_res,
                                                  full_resolution=full_res,
                                                  order=3)
        grad_y = self.resample_to_full_resolution(grad_y_mnt,
                                                  mnt_resolution=mnt_res,
                                                  full_resolution=full_res,
                                                  order=3)

        slope, aspect = self.calc_slope_aspect(grad_y, grad_x)

        # Write full res slope and aspect
        geotransform = list(drv.GetGeoTransform())
        geotransform[1] = float(full_res[0])
        geotransform[-1] = float(full_res[1])
        projection = drv.GetProjection()
        tmp_asp = tempfile.mktemp(dir=self.wdir, suffix="_asp.tif")
        ImageIO.write_geotiff(aspect, tmp_asp, projection, tuple(geotransform))
        tmp_slp = tempfile.mktemp(dir=self.wdir, suffix="_slp.tif")
        ImageIO.write_geotiff(slope, tmp_slp, projection, tuple(geotransform))

        # Full resolution:
        write_resolution_name = True if len(mnt_resolutions) > 1 else False
        # Names for R1, R2 etc.
        rasters_written = []
        path_alt, path_asp, path_slp = "", "", ""
        all_paths_alt = []
        for res in mnt_resolutions:
            # ALT:
            bname_alt = basename + "_ALT"
            bname_alt += "_" + str(
                res["name"]) if write_resolution_name else ""
            bname_alt += ".TIF"
            rel_alt = os.path.join(dbl_base, bname_alt)
            path_alt = os.path.join(self.dem_dir, rel_alt)
            all_paths_alt.append(path_alt)
            ImageTools.gdal_warp(mnt_max_res,
                                 dst=path_alt,
                                 tr=res["val"],
                                 r="cubic",
                                 multi=True)
            rasters_written.append(rel_alt)
            # ASP:
            bname_asp = basename + "_ASP"
            bname_asp += "_" + res["name"] if write_resolution_name else ""
            bname_asp += ".TIF"
            rel_asp = os.path.join(dbl_base, bname_asp)
            path_asp = os.path.join(self.dem_dir, rel_asp)
            ImageTools.gdal_warp(tmp_asp,
                                 dst=path_asp,
                                 tr=res["val"],
                                 r="cubic",
                                 multi=True)
            rasters_written.append(rel_asp)
            # SLP:
            bname_slp = basename + "_SLP"
            bname_slp += "_" + res["name"] if write_resolution_name else ""
            bname_slp += ".TIF"
            rel_slp = os.path.join(dbl_base, bname_slp)
            path_slp = os.path.join(self.dem_dir, rel_slp)
            ImageTools.gdal_warp(tmp_slp,
                                 dst=path_slp,
                                 tr=res["val"],
                                 r="cubic",
                                 multi=True)
            rasters_written.append(rel_slp)

        # Optional coarse_res writing:
        if coarse_res and not full_res_only:
            # Resize all rasters for coarse res.
            coarse_res_str = str(coarse_res[0]) + " " + str(coarse_res[1])
            # ALC:
            bname_alc = basename + "_ALC.TIF"
            rel_alc = os.path.join(dbl_base, bname_alc)
            path_alc = os.path.join(self.dem_dir, rel_alc)
            ImageTools.gdal_warp(path_alt,
                                 dst=path_alc,
                                 tr=coarse_res_str,
                                 multi=True)
            rasters_written.append(rel_alc)
            # ALC:
            bname_asc = basename + "_ASC.TIF"
            rel_asc = os.path.join(dbl_base, bname_asc)
            path_asc = os.path.join(self.dem_dir, rel_asc)
            ImageTools.gdal_warp(path_asp,
                                 dst=path_asc,
                                 tr=coarse_res_str,
                                 multi=True)
            rasters_written.append(rel_asc)
            # ALC:
            bname_slc = basename + "_SLC.TIF"
            rel_slc = os.path.join(dbl_base, bname_slc)
            path_slc = os.path.join(self.dem_dir, rel_slc)
            ImageTools.gdal_warp(path_slp,
                                 dst=path_slc,
                                 tr=coarse_res_str,
                                 multi=True)
            rasters_written.append(rel_slc)
            # Water mask:
            bname_msk = basename + "_MSK.TIF"
            rel_msk = os.path.join(dbl_base, bname_msk)
            path_msk = os.path.join(self.dem_dir, rel_msk)
            ImageTools.gdal_warp(self.gsw_dst,
                                 dst=path_msk,
                                 tr=coarse_res_str,
                                 multi=True)
            rasters_written.append(rel_msk)

        # Write HDR Metadata:

        date_start = datetime(1970, 1, 1)
        date_end = datetime(2100, 1, 1)
        dem_info = DEMInfo(self.site, all_paths_alt[0])
        root = self._get_root()
        self._create_hdr(root, mission_field, basename, rasters_written,
                         dem_info, date_start, date_end, self.dem_version)
        XMLTools.write_xml(root, hdr)

        # Remove temp files:
        FileSystem.remove_file(tmp_asp)
        FileSystem.remove_file(tmp_slp)
        FileSystem.remove_file(mnt_max_res)
        return hdr, dbl_dir