def run_modification(self, feat):
        showinfo(
            "INFORMATION",
            " Analysis takes a while.\nPython windows seem unresponsive in the meanwhile.\nCheck console messages.\n\nPRESS OK TO START"
        )
        if not self.verified:
            self.verify()
        if self.verified:
            modification = cMT.ModifyTerrain(condition=self.condition,
                                             unit_system=self.unit,
                                             feature_ids=self.feature_id_list,
                                             topo_in_dir=self.th_mod.in_topo,
                                             feat_in_dir=feat,
                                             reach_ids=self.reach_ids_applied)
            modification()
            self.prevent_popup = True
            try:
                fGl.rm_dir(modification.cache)
            except:
                showinfo(
                    "WARNING", "DELETE .CACHE FOLDER MANUALLY (%s)." %
                    str(modification.cache))
            self.master.bell()

            tk.Button(self,
                      width=25,
                      bg="forest green",
                      text="Terrain modification finished. Click to quit.",
                      command=lambda: self.quit_tab()).grid(sticky=tk.EW,
                                                            row=8,
                                                            column=0,
                                                            columnspan=2,
                                                            padx=self.xd,
                                                            pady=self.yd)
Exemple #2
0
    def clear_cache(self, *args):
        # if args[0]==False: the cache folder itself is not deleted
        arcpy.env.overwriteOutput = True
        arcpy.env.workspace = self.cache
        ras_list = arcpy.ListRasters()
        shp_list = arcpy.ListFeatureClasses()
        try:
            for ras in ras_list:
                try:
                    arcpy.Delete_management(str(ras))
                except:
                    pass
            for shp in shp_list:
                try:
                    arcpy.Delete_management(str(shp))
                except:
                    pass
            try:
                arcpy.env.workspace = os.path.dirname(os.path.abspath(__file__))  # temporary workspace
                fGl.rm_dir(self.cache)
                if not args[0]:
                    self.logger.info("        * restoring cache ...")
                    fGl.chk_dir(self.cache)
                    arcpy.env.workspace = self.cache
            except:
                self.logger.info(" >> Cleared .cache folder (arcpy.Delete_management) ...")

        except:
            self.logger.info("WARNING: .cache folder will be removed by package controls.")
    def run_raster_calc(self):
        msg0 = "Analysis takes a while. \nPython windows seem unresponsive in the meanwhile. \nCheck console messages."
        msg1 = "\n\nClick OK to start DHSI and VHSI calculation."
        showinfo("INFORMATION ", msg0 + msg1)
        hhsi = chsi.HHSI(self.dir_input_ras, self.condition, self.unit)

        hhsi.make_hhsi(self.fish_applied, self.boundary_shp)
        self.top.bell()

        try:
            if not hhsi.error:
                fGl.open_folder(hhsi.path_hsi)
                self.l_run_info.config(fg="forest green", text="RUN SUCCESSFULLY COMPLETED (close window)")
                self.b_run.config(width=30, fg="dark green", bg="PaleGreen1", text="Re-run (generate habitat condition)")
            else:
                self.l_run_info.config(fg="red", text="RUN COMPLETED WITH ERRORS")
                self.b_run.config(bg="salmon", text="Re-run (generate habitat condition)")
        except:
            pass
        msg = "COMPUTATION FINISHED - Check logfile (logfile.log)."
        try:
            hhsi.clear_cache()
            try:
                fGl.rm_dir(hhsi.cache)
            except:
                pass
            msg = str("WARNING: Remove .cache (%s) folder manually \n\n" % str(hhsi.cache)) + msg
        except:
            pass
        showinfo("INFO", msg)
Exemple #4
0
    def clean_up(self):
        arcpy.env.overwriteOutput = True
        arcpy.env.workspace = self.cache
        ras_list = arcpy.ListRasters()
        shp_list = arcpy.ListFeatureClasses()
        try:

            self.logger.info(
                "   * clearing .cache (arcpy.Delete_management) ...")
            for ras in ras_list:
                try:
                    arcpy.Delete_management(str(ras))
                except:
                    pass
            for shp in shp_list:
                try:
                    arcpy.Delete_management(str(shp))
                except:
                    pass
            fGl.rm_dir(self.cache)
            if self.reset_cache:
                fGl.chk_dir(self.cache)
            self.logger.info("   * ok")
        except:
            self.logger.info(
                "WARNING: .cache folder will be removed by package controls.")
Exemple #5
0
 def clear_cache(self, *args):
     try:
         # check for optional BOOL argument to restore cache
         recreate_cache = args[0]
     except:
         recreate_cache = False
     arcpy.env.overwriteOutput = True
     arcpy.env.workspace = self.cache
     ras_list = arcpy.ListRasters()
     shp_list = arcpy.ListFeatureClasses()
     try:
         if not recreate_cache:
             self.logger.info(
                 "   * clearing .cache (arcpy.Delete_management) ...")
         else:
             self.logger.info(
                 "   * resetting .cache (arcpy.Delete_management) ...")
         for ras in ras_list:
             try:
                 arcpy.Delete_management(str(ras))
             except:
                 pass
         for shp in shp_list:
             try:
                 arcpy.Delete_management(str(shp))
             except:
                 pass
         fGl.rm_dir(self.cache)
         self.cache_count = 0
         if recreate_cache:
             fGl.chk_dir(self.cache)
         self.logger.info("   * ok")
     except:
         self.logger.info(
             "       .cache folder will be removed by package controls.")
 def clean_up(self):
     try:
         self.logger.info("Cleaning up ...")
         fGl.clean_dir(self.cache)
         fGl.rm_dir(self.cache)
         self.logger.info("OK")
     except:
         self.logger.info("Failed to clean up .cache folder.")
Exemple #7
0
 def clean_up(self):
     try:
         print(" * cleaning up ...")
         fGl.clean_dir(self.cache)
         fGl.rm_dir(self.cache)
         print("   - OK")
     except:
         print("WARNING: Failed to clean up .cache folder.")
 def clean_up(self):
     try:
         self.logger.info(" * Cleaning up ...")
         del self.ras_mu, self.raster_dict
         fGl.clean_dir(self.cache)
         fGl.rm_dir(self.cache)
         self.logger.info(" * OK")
     except:
         self.logger.info(" * Failed to clean up .cache folder.")
Exemple #9
0
    def run_raster_calc(self):
        relevant_types = []
        for rt in self.hsi_types.keys():
            if self.hsi_types[rt].get():
                relevant_types.append(rt)

        msg0 = "Analysis takes a while. \nPython windows seem unresponsive in the meanwhile. \nCheck console messages."
        msg1 = "\n\nThe following HSI types will be created:\n - "
        showinfo("INFORMATION ", msg0 + msg1 + "\n - ".join(relevant_types))
        error_occurred = False
        dir_out = ""
        for cov in relevant_types:
            cov_hsi = chsi.CovHSI(self.dir_input_ras, self.condition, cov,
                                  self.unit)
            cov_hsi.make_covhsi(self.fish_applied, self.h_ras_path)
            if cov_hsi.error:
                error_occurred = True
            else:
                dir_out = cov_hsi.path_hsi
            del cov_hsi
            try:
                fGl.clean_dir(
                    os.path.dirname(os.path.realpath(__file__)) + "\\.cache\\")
                try:
                    fGl.rm_dir(cov_hsi.cache)
                except:
                    pass
            except:
                print("WARNING: Could not clean up cache.")
        self.top.bell()
        try:
            if not error_occurred:
                fGl.open_folder(dir_out)
                self.l_run_info.config(fg="forest green",
                                       text="HSI RASTERS SUCCESSFULLY CREATED")
                self.b_run.config(width=30,
                                  bg="pale green",
                                  text="RE-run (generate habitat condition)",
                                  command=lambda: self.run_raster_calc())
            else:
                self.l_run_info.config(fg="red",
                                       text="HSI RASTERS COMPILED WITH ERRORS")
                self.b_run.config(bg="salmon",
                                  text="RE-run (generate habitat condition)",
                                  command=lambda: self.run_raster_calc())
        except:
            pass

        showinfo("COMPUTATION FINISHED", "Check logfile (logfile.log).")
    def run_volume_calculator(self):
        showinfo(
            "INFORMATION",
            " Analysis may take a while.\nPython windows seem unresponsive in the meanwhile.\nCheck console messages.\n \n PRESS OK TO START"
        )
        vola = cMT.VolumeAssessment(unit_system=self.unit,
                                    org_ras_dir=self.org_dem_dir,
                                    mod_ras_dir=self.mod_dem_dir,
                                    reach_ids=self.reach_ids_applied)
        self.vol_name, self.dir_ras_vol = vola.get_volumes()
        self.raster4mapping = vola.rasters
        try:
            fGl.rm_dir(vola.cache)
        except:
            showinfo("WARNING",
                     "Could not remove %s.\nManual deletion required")

        self.runmenu.entryconfig(1, command=lambda: self.run_map_maker())
        if self.mapping.get():
            self.run_map_maker()
        self.master.bell()
def geo_file_maker(condition, feature_type, dir_base_ras, *args, **kwargs):
    # feature_type = STR - either "terraforming", "plantings", "bioengineering" or "connectivity"
    # kwargs: unit_system ("us" or "si"), alternate_inpath (STR)

    allowed_feature_types = [
        "terraforming", "plantings", "bioengineering", "connectivity"
    ]
    unit_system = "us"
    alternate_inpath = None
    try:
        for k in kwargs.items():
            if "unit_system" in k[0].lower():
                unit_system = str(k[1]).lower()
            if "alternate_inpath" in k[0].lower():
                alternate_inpath = k[1]
    except:
        pass

    logger = logging.getLogger("logfile")
    logger.info("*** unit system: " + str(unit_system))
    logger.info("*** condition: " + str(condition))
    if not (feature_type in allowed_feature_types):
        feature_type = "terraforming"
        logger.info("Bad argument type. Applying: " + str(feature_type))

    feature_assessment = cAA.ArcPyContainer(condition, feature_type,
                                            dir_base_ras, unit_system,
                                            alternate_inpath)
    feature_assessment()  # call data processing

    try:
        cache_dir = str(feature_assessment.cache)
        del feature_assessment
        fGl.cool_down(5)
        fGl.rm_dir(cache_dir)  # dump cache after feature analysis
    except:
        logger.info("WARNING: Could not remove .cache.")
Exemple #12
0
    def start_app(self, app_name, *args, **kwargs):
        # parse optional arguments
        try:
            for k in kwargs.items():
                if "cover" in k[0]:
                    self.cover_applies = k[1]
        except:
            pass

        # shout if no fish was selected
        if self.fish_applied.__len__() == 0:
            showinfo("ATTENTION", "Select Physical Habitat for fish!")
            return -1

        # instantiate app
        if app_name == "hhsi_gui":
            try:
                import sub_gui_hhsi as sgh
                if not self.apply_boundary.get():
                    sub_gui = sgh.HHSIgui(self.master, self.unit,
                                          self.fish_applied)
                else:
                    sub_gui = sgh.HHSIgui(self.master, self.unit,
                                          self.fish_applied, self.bound_shp)
                self.b_c_select_hy["state"] = "disabled"
                self.master.wait_window(sub_gui.top)
                self.b_c_select_hy["state"] = "normal"
                self.list_habitat_conditions()
            except:
                msg = "ERROR: Failed importing HHSI GUI."

        if app_name == "mhsi_gui":
            try:
                import sub_gui_covhsi as cgh
                sub_gui = cgh.CovHSIgui(self.master, self.unit,
                                        self.fish_applied)
                self.b_c_select_cov["state"] = "disabled"
                self.master.wait_window(sub_gui.top)
                self.b_c_select_cov["state"] = "normal"
                self.list_habitat_conditions()
                self.cover_applies = True
            except:
                msg = "Failed importing (cover) HSI GUI."

        if app_name == "cHSI":
            try:
                if self.cover_applies:
                    combine_hsi = cHSI.CHSI(self.chsi_condition_cov,
                                            self.cover_applies, self.unit)
                    self.cb_use_cov["state"] = "normal"
                    self.cb_use_cov.select()
                else:
                    combine_hsi = cHSI.CHSI(self.chsi_condition_hy,
                                            self.cover_applies, self.unit)
                if not self.apply_boundary.get():
                    ans = combine_hsi.launch_chsi_maker(
                        self.fish_applied, self.combine_method, "")
                else:
                    ans = combine_hsi.launch_chsi_maker(
                        self.fish_applied, self.combine_method, self.bound_shp)

                self.master.bell()
                try:
                    combine_hsi.clear_cache()
                    try:
                        fGl.rm_dir(combine_hsi.cache)
                    except:
                        pass
                except:
                    showinfo(
                        "WARNING", "Remove .cache (%s) folder manually." %
                        str(combine_hsi.cache))

                if not (ans == "OK"):
                    showinfo(
                        "WARNING",
                        "No HSI rasters were available for the selected fish species - lifestage."
                    )
                else:
                    # update SHArea buttons
                    self.b_sharc["state"] = "normal"
                    self.b_sha_th["state"] = "normal"
                    webbrowser.open(combine_hsi.path_csi)
            except:
                showinfo("ERROR", "Problem in CHSI object.")

        if app_name == "sharea":
            try:
                if self.cover_applies_sharea.get():
                    sharea = cHSI.CHSI(self.chsi_condition_cov, True,
                                       self.unit)
                else:
                    try:
                        if not self.cover_applies:
                            sharea = cHSI.CHSI(self.chsi_condition_hy, False,
                                               self.unit)
                        else:
                            sharea = cHSI.CHSI(self.chsi_condition_cov, True,
                                               self.unit)
                    except:
                        showinfo(
                            "INFO",
                            "Using \'WITH COVER\' option (hydraulic only condition is empty)."
                        )
                        sharea = cHSI.CHSI(self.chsi_condition_cov,
                                           self.cover_applies, self.unit)

                self.xlsx_condition = sharea.calculate_sha(
                    self.sharea_threshold, self.fish_applied,
                    self.apply_wua.get())

                try:
                    sharea.clear_cache()
                    try:
                        fGl.rm_dir(sharea.cache)
                    except:
                        pass
                except:
                    showinfo(
                        "WARNING", "Remove .cache (%s) folder manually." %
                        str(sharea.cache))

                if self.xlsx_condition.__len__() > 0:
                    webbrowser.open(config.dir2sh + "SHArea\\")
                    self.b_qua["state"] = "normal"
                    self.b_quat["state"] = "normal"
                else:
                    showinfo(
                        "WARNING",
                        "No CHSI rasters were available for the selected fish species - lifestage."
                    )
            except:
                showinfo(
                    "ERROR",
                    "Could not instantiate CHSI object for SHArea calculation."
                )

        if app_name == "no_condition":
            msg = "CONFIRM HABITAT CONDITION !"
            showinfo("ERROR", msg)
    def __init__(self, master):
        top = self.top = tk.Toplevel(master)
        self.condition_list = fGl.get_subdir_names(config.dir2conditions)
        self.dir2condition_act = '.'
        self.dir2dem = ''
        self.dir2h = ''
        self.dir2u = ''
        self.unit = "us"
        self.unit_dict = {"us": "U.S. customary", "si": "SI (metric)"}

        # define analysis type identifiers (default = False)
        self.bool_var = tk.BooleanVar()
        self.top.iconbitmap(config.code_icon)

        # ARRANGE GEOMETRY
        # width and height of the window.
        ww = 650
        wh = 570
        self.xd = 5  # distance holder in x-direction (pixel)
        self.yd = 5  # distance holder in y-direction (pixel)
        # height and location
        wx = (self.top.winfo_screenwidth() - ww) / 2
        wy = (self.top.winfo_screenheight() - wh) / 2
        self.top.geometry("%dx%d+%d+%d" % (ww, wh, wx, wy))
        self.top.title("Populate Condition")  # window title

        self.col_0_width = 25

        # Set Condition
        self.l_name = tk.Label(top, text="Select condition: ")
        self.l_name.grid(sticky=tk.W,
                         row=0,
                         rowspan=3,
                         column=0,
                         padx=self.xd,
                         pady=self.yd)
        self.sb_condition = tk.Scrollbar(top, orient=tk.VERTICAL)
        self.sb_condition.grid(sticky=tk.W,
                               row=0,
                               column=2,
                               padx=0,
                               pady=self.yd)
        self.lb_condition = tk.Listbox(top,
                                       height=3,
                                       width=15,
                                       yscrollcommand=self.sb_condition.set)
        for ce in self.condition_list:
            self.lb_condition.insert(tk.END, ce)
        self.lb_condition.grid(sticky=tk.EW,
                               row=0,
                               column=1,
                               padx=0,
                               pady=self.yd)
        self.sb_condition.config(command=self.lb_condition.yview)
        self.b_sc = tk.Button(top,
                              width=self.col_0_width - 5,
                              fg="firebrick3",
                              bg="white",
                              text="Validate",
                              command=lambda: self.set_condition())
        self.b_sc.grid(sticky=tk.E,
                       row=0,
                       rowspan=3,
                       column=2,
                       padx=self.xd,
                       pady=self.yd)
        self.l_c_dir = tk.Label(top,
                                fg="firebrick3",
                                text="Select a condition.")
        self.l_c_dir.grid(sticky=tk.W,
                          row=3,
                          column=0,
                          columnspan=4,
                          padx=self.xd,
                          pady=self.yd)
        tk.Label(top, text="").grid(sticky=tk.W, row=4, column=0)  # dummy

        # 02 Make d2w
        self.l_d2w = tk.Label(
            top, text="Create Depth to Groundwater Raster (d2w.tif)")
        self.l_d2w.grid(sticky=tk.W,
                        row=5,
                        column=0,
                        columnspan=4,
                        padx=self.xd,
                        pady=self.yd)
        self.b_sd2w = tk.Button(top,
                                width=self.col_0_width * 2,
                                bg="white",
                                text="Select minimum flow depth raster",
                                command=lambda: self.select_h())
        self.b_sd2w.grid(sticky=tk.EW,
                         row=6,
                         column=0,
                         columnspan=2,
                         padx=self.xd,
                         pady=self.yd)
        self.b_d2w = tk.Button(top,
                               width=self.col_0_width,
                               bg="white",
                               text="Run d2w creation",
                               command=lambda: self.run_d2w())
        self.b_d2w.grid(sticky=tk.EW,
                        row=6,
                        column=2,
                        padx=self.xd,
                        pady=self.yd)
        self.l_interp = tk.Label(top, text="Interpolation method:")
        self.l_interp.grid(sticky=tk.W,
                           row=7,
                           column=0,
                           columnspan=2,
                           padx=self.xd,
                           pady=self.yd)
        self.c_interp = ttk.Combobox(top, state='readonly')
        self.c_interp.grid(sticky=tk.W,
                           row=7,
                           column=1,
                           padx=self.xd,
                           pady=self.yd)
        self.c_interp["values"] = ("IDW", "EBK", "Kriging", "Nearest Neighbor")
        self.c_interp.current(0)
        self.l_d2w_dem = tk.Label(top, text="")
        self.l_d2w_dem.grid(sticky=tk.W,
                            row=8,
                            column=0,
                            columnspan=4,
                            padx=self.xd,
                            pady=self.yd)
        tk.Label(top, text="").grid(sticky=tk.W, row=9, column=0)  # dummy

        # 03 Make detDEM
        self.l_det = tk.Label(
            top, text="Create detrended DEM Raster (dem_detrend.tif)")
        self.l_det.grid(sticky=tk.W,
                        row=9,
                        column=0,
                        columnspan=4,
                        padx=self.xd,
                        pady=self.yd)
        self.b_sdet = tk.Button(top,
                                width=self.col_0_width * 2,
                                bg="white",
                                text="Select minimum flow depth raster",
                                command=lambda: self.select_h())
        self.b_sdet.grid(sticky=tk.EW,
                         row=10,
                         column=0,
                         columnspan=2,
                         padx=self.xd,
                         pady=self.yd)
        self.b_det = tk.Button(top,
                               width=self.col_0_width,
                               bg="white",
                               text="Run detrended DEM creation",
                               command=lambda: self.run_det())
        self.b_det.grid(sticky=tk.EW,
                        row=10,
                        column=2,
                        padx=self.xd,
                        pady=self.yd)
        self.l_det_dem = tk.Label(top, text="")
        self.l_det_dem.grid(sticky=tk.W,
                            row=11,
                            column=0,
                            columnspan=4,
                            padx=self.xd,
                            pady=self.yd)
        tk.Label(top, text="").grid(sticky=tk.W, row=12, column=0)  # dummy

        # 04 Make MU
        self.l_mu = tk.Label(top,
                             text="Create Morphological Unit Raster (mu.tif)")
        self.l_mu.grid(sticky=tk.W,
                       row=13,
                       column=0,
                       columnspan=4,
                       padx=self.xd,
                       pady=self.yd)
        self.b_smuh = tk.Button(top,
                                width=self.col_0_width,
                                bg="white",
                                text="Select depth raster",
                                command=lambda: self.select_h())
        self.b_smuh.grid(sticky=tk.EW,
                         row=14,
                         column=0,
                         padx=self.xd,
                         pady=self.yd)
        self.b_smuu = tk.Button(top,
                                width=self.col_0_width,
                                bg="white",
                                text="Select velocity raster",
                                command=lambda: self.select_u())
        self.b_smuu.grid(sticky=tk.EW,
                         row=14,
                         column=1,
                         padx=self.xd,
                         pady=self.yd)
        self.b_chg_mu = tk.Button(top,
                                  width=self.col_0_width * 2 + self.xd * 2,
                                  bg="white",
                                  text="View / change MU definitions",
                                  command=lambda: self.open_mu_xlsx())
        self.b_chg_mu.grid(sticky=tk.EW,
                           row=15,
                           column=0,
                           columnspan=2,
                           padx=self.xd,
                           pady=self.yd)
        self.b_mu = tk.Button(top,
                              width=self.col_0_width,
                              bg="white",
                              text="Run MU\ncreation",
                              command=lambda: self.run_mu())
        self.b_mu.grid(sticky=tk.EW,
                       row=14,
                       rowspan=2,
                       column=2,
                       padx=self.xd,
                       pady=self.yd)
        self.l_mu_unit = tk.Label(
            top,
            fg="dodger blue",
            text="Currently selected Raster unit system: % s" %
            self.unit_dict[self.unit])
        self.l_mu_unit.grid(sticky=tk.W,
                            row=16,
                            column=0,
                            columnspan=4,
                            padx=self.xd,
                            pady=self.yd)
        # tk.Label(top, text="").grid(sticky=tk.W, row=15, column=0)  # dummy

        self.b_return = tk.Button(top,
                                  width=self.col_0_width,
                                  fg="RoyalBlue3",
                                  bg="white",
                                  text="RETURN to MAIN WINDOW",
                                  command=lambda: self.gui_quit())
        self.b_return.grid(sticky=tk.E,
                           row=17,
                           column=2,
                           padx=self.xd,
                           pady=self.yd)

        # add units-menu
        self.mbar = tk.Menu(self.top,
                            foreground="dodger blue")  # create new menubar
        self.top.config(menu=self.mbar)  # attach it to the root window
        self.unitmenu = tk.Menu(self.mbar, tearoff=0,
                                foreground="dodger blue")  # create new menu
        self.mbar.add_cascade(
            label="Units", menu=self.unitmenu,
            foreground="dodger blue")  # attach it to the menubar
        self.unitmenu.add_command(label="[current]  U.S. customary",
                                  background="pale green")
        self.unitmenu.add_command(label="[             ]  SI (metric)",
                                  command=lambda: self.unit_change())

        self.b_d2w["state"] = "disabled"
        self.b_det["state"] = "disabled"
        self.b_mu["state"] = "disabled"
        self.b_sd2w["state"] = "disabled"
        self.c_interp["state"] = "disabled"
        self.b_sdet["state"] = "disabled"
        self.b_smuh["state"] = "disabled"
        self.b_smuu["state"] = "disabled"
        try:
            fGl.clean_dir(config.dir2gs + ".cache\\")
            fGl.rm_dir(config.dir2gs + ".cache\\")
        except:
            pass
    def start_app(self, app_name):
        # app_name = STR
        c_msg1 = "Background calcluation (check console window).\n\n"
        c_msg2 = "Python windows seem unresponsive in the meanwhile.\n\n"
        c_msg3 = "Logfile and cost master file automatically open once the process successfully terminated.\n\n"
        c_msg4 = "\n    >> PRESS OK TO START << "
        if app_name == "s2X":
            try:
                items = self.lb_condition_pl.curselection()
                condition_pl = [
                    self.condition_pl_list[int(item)] for item in items
                ][0]
                if (condition_pl.__len__() < 1) or (str(condition_pl)
                                                    == "Validate Variables"):
                    showinfo("ERROR", "Select condition.")
                    return -1
                dir2ml_pl = config.dir2ml + "Output\\Rasters\\" + condition_pl + "\\"
                showinfo("INFO", c_msg1 + c_msg2 + c_msg3 + c_msg4)
                if float(self.vege_cr.get()) > float(self.vege_stab_cr.get()):
                    showinfo(
                        "CORRECTION REQUIRED",
                        "The stabilization lifespan must be larger or equal to the minimum lifespans of plants."
                    )
                    return -1
                best_plant_dir = s20.main(dir2ml_pl, self.vege_cr.get(),
                                          self.prj_name.get(), self.unit,
                                          self.version)
            except:
                showinfo(
                    "ERROR",
                    "Select (highlight) at least one Max Lifespan condition.\n\nClose all relevant geofiles and the cost master workbook (xlsx)."
                )
                return -1

            try:
                lf_req = float(self.vege_stab_cr.get())
            except:
                showinfo(
                    "ERROR",
                    "Wrong format of critical lifespan (must be numeric).")
                return -1
            try:
                s21.main(
                    best_plant_dir,
                    config.dir2lf + "Output\\Rasters\\" + condition_pl + "\\",
                    lf_req, self.prj_name.get(), self.unit, self.version)
                self.b_s20.config(text="Plantings OK", fg="forest green")
                showinfo(
                    "INFO",
                    "Calulation finished. VERIFY CELL LINKS IN WORKBOOK! Make sure that cell links in column F of the COSTS tab link to the correct cells in the FROM_GEODATA tab."
                )
            except:
                showinfo(
                    "WARNING",
                    "Could not load Max Lifespan maps for nature-based engineering.\n\nRun Lifespan module for nature-based engineering for the selected condition first."
                )

            try:
                fGl.open_file("{0}{1}_{2}\\{1}_assessment_{2}.xlsx".format(
                    config.dir2pm, self.prj_name.get(), self.version))
            except:
                pass

        if app_name == "s30":
            try:
                items = self.lb_condition_ter.curselection()
                condition_ter = [
                    self.condition_ter_list[int(item)] for item in items
                ][0]
                if (condition_ter.__len__() < 1) or (str(condition_ter)
                                                     == "Validate Variables"):
                    showinfo("ERROR", "Validate Variables first.")
                    return -1
            except:
                showinfo("ERROR", "Select condition.")
                return -1
            try:
                dir2lf_ter = config.dir2lf + "Output\\Rasters\\" + condition_ter + "\\"
                showinfo("INFO", c_msg1 + c_msg2 + c_msg3 + c_msg4)
                try:
                    lf_req = float(self.ter_cr.get())
                except:
                    showinfo(
                        "ERROR",
                        "Wrong format of critical lifespan (must be numeric).")
                    return -1
                s30.main(dir2lf_ter, lf_req, self.prj_name.get(), self.unit,
                         self.version, self.n, self.txcr)
                self.b_s30.config(text="Stabilize terrain OK",
                                  fg="forest green")
                showinfo(
                    "INFO",
                    "Calulation finished. VERIFY CELL LINKS IN WORKBOOK! Make sure that cell links in column F of the COSTS tab link to the correct cells in the FROM_GEODATA tab."
                )
            except:
                showinfo(
                    "ERROR",
                    "Close all relevant geofiles and the cost master workbook (xlsx)."
                )

        if app_name == "s40":
            try:
                if self.fish_applied.__len__() == 0:
                    showinfo(
                        "ATTENTION",
                        "Select at least one Physical Habitat of a fish species - lifestage!"
                    )
                    return -1
                if self.cover_app_pre.get() or self.cover_app_post.get():
                    msg1 = "Make sure that cover cHSI rasters are available in SHArC/CHSI/"
                    msg2 = str(self.condition_init) + " AND / OR " + str(
                        self.condition_proj) + "/cover/.\n\n"
                    msg3 = "Press OK to launch SHArea calculation with cover."
                    showinfo("Info", msg1 + msg2 + msg3)
                if (self.condition_init.__len__() < 1) or (str(
                        self.condition_init) == "Validate Variables"):
                    showinfo("ERROR", "Select initial condition.")
                    return -1
                if (self.condition_proj.__len__() < 1) or (str(
                        self.condition_proj) == "Validate Variables"):
                    showinfo("ERROR", "Select condition after terraforming.")
                    return -1
                showinfo("INFO", c_msg1 + c_msg2 + c_msg3 + c_msg4)
                cache2del = s40.main(self.condition_init, self.condition_proj,
                                     self.cover_app_pre.get(),
                                     self.cover_app_post.get(),
                                     self.fish_applied, self.prj_name.get(),
                                     self.unit, self.version,
                                     self.apply_wua.get())
                self.b_s40.config(text="Net gain in SHArea calculation OK",
                                  fg="forest green")
                try:
                    fGl.rm_dir(cache2del)
                except:
                    showinfo(
                        "CHECK",
                        "Cache folder (%s) needs to be deleted manually." %
                        str(cache2del))
            except:
                showinfo(
                    "ERROR",
                    "Close all relevant geofiles and the cost master workbook (xlsx)."
                )
def analysis(feature, condition, reach_extents, habitat, output_dir,
             unit_system, wildcard, manning_n, extent_type):
    logger = logging.getLogger("logfile")
    pot_err_msg = "FUNDAMENTAL APPLICATION ERROR - Revise River Architect usage instructions"
    try:

        # instantiate GIS Analysis Object
        pot_err_msg = "ArcPyAnalysis"
        feature_analysis = cLDA.ArcPyAnalysis(condition, reach_extents,
                                              habitat, output_dir, unit_system,
                                              manning_n)  # arcpy class
        feature_analysis.extent_type = extent_type

        # assign analysis specific parameters if applies
        try:
            inverse_tcd = feature.inverse_tcd
            logger.info("   >> Inverse tcd analysis")
        except:
            inverse_tcd = False
        pot_err_msg = "inverse threshold verification"
        feature_analysis.verify_inverse_tcd(inverse_tcd)
        try:
            freq = feature.threshold_freq
            logger.info("   >> Customary frequency threshold = " + str(freq))
        except:
            freq = 0.0
        pot_err_msg = "frequency threshold verification"
        feature_analysis.verify_threshold_freq(freq)
        try:
            sf = feature.sf
            logger.info("   >> Customary safety factor (SF) = " + str(sf))
        except:
            sf = 1.0
        pot_err_msg = "safety factor verification"
        feature_analysis.verify_sf(sf)

        # call parameter analysis
        pot_err_msg = "parameter analysis"
        for par in feature.parameter_list:
            try:
                logger.info("   >> Checking if %s applies ... " % par)
                feature_analysis = analysis_call(par, feature,
                                                 feature_analysis)
            except:
                logger.info("ERROR: Failed checking " + par + " of " +
                            feature.name + ".")

        pot_err_msg = "habitat join"
        if habitat:
            feature_analysis.join_with_habitat()
        pot_err_msg = "wildcard join"
        if wildcard:
            feature_analysis.join_with_wildcard()
        pot_err_msg = "non applicable feature: saving an empty results-Raster"
        feature_analysis.save_manager(feature.ds, feature.lf, feature.id)
    except:
        logger.info("ERROR: Analysis stopped (" + pot_err_msg + " failed).")
    try:
        fGl.rm_dir(feature_analysis.cache)  # dump cache after feature analysis
    except:
        try:
            logger.info("WARNING: Could not remove .cache (%s) folder." %
                        str(feature_analysis.cache))
        except:
            logger.info("WARNING: Could not remove .cache folder.")