Exemplo n.º 1
0
    def __init__(self, geo_input_path, condition, *unit_system):

        # general directories and parameters
        self.cache = config.dir2sh + ".cache\\"
        self.condition = condition
        self.dir_in_geo = geo_input_path
        self.path_hsi = config.dir2sh + "HSI\\" + str(condition) + "\\"
        self.error = False
        self.flow_dict_h = {}
        self.flow_dict_u = {}
        self.fish = cFi.Fish()
        self.logger = logging.getLogger("logfile")
        self.raster_dict = {}
        self.ras_h = []
        self.ras_u = []

        fGl.chk_dir(self.cache)
        fGl.clean_dir(self.cache)
        fGl.chk_dir(self.path_hsi)
        fGl.chk_dir(self.dir_in_geo)

        # set unit system variables
        try:
            self.units = unit_system[0]
        except:
            self.units = "us"
            print("WARNING: Invalid unit_system identifier. unit_system must be either \'us\' or \'si\'.")
            print("         Setting unit_system default to \'us\'.")
 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.")
Exemplo n.º 3
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.")
Exemplo n.º 4
0
 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.")
Exemplo n.º 5
0
def calculate_phi(sediment_container, taux_raster_list):
    qgs = launch_qgis()
    for tx in taux_raster_list:
        sediment_container.make_phi2dz_mpm_ras(tx)
        sediment_container.make_phi2dz_rel_ras(tx)
    qgs.exitQgis()
    logging.info(
        ' -- Clearing taux Rasters (required for disk space preservation) ...')
    fun.clean_dir(sediment_container.dir_out + 'taux/')
Exemplo n.º 6
0
def calculate_hydraulics(roughness_laws, roughness, sediment_container):
    # roughness_laws = LIST of applicable roughness types included in roughness_dict
    # roughness = cRoughness.RoughnessLaw() object
    # sediment_container = cMorphoDynamic.SedimentDynamics() object
    qgs = launch_qgis()
    h_file = open("input/txt/flow_depth_list.txt", "r")
    u_file = open("input/txt/flow_velocity_list.txt", "r")

    h_list = h_file.read().splitlines()
    u_list = u_file.read().splitlines()
    hy_dict = dict(zip(h_list, u_list))

    roughness_dict = {
        "Bathurst": lambda go: roughness.Bathurst(),
        "Drag1": lambda go: roughness.Drag1(),
        "Drag2": lambda go: roughness.Drag2(),
        "Ferguson": lambda go: roughness.Ferguson(),
        "Hey": lambda go: roughness.Hey(),
        "Keulegan": lambda go: roughness.Keulegan(),
        "MPM": lambda go: roughness.MPM(),
        "ParkerA": lambda go: roughness.ParkerA(),
        "ParkerB": lambda go: roughness.ParkerB(),
        "Smart": lambda go: roughness.Smart(),
        "Strickler": lambda go: roughness.Strickler()
    }

    for rl in roughness_laws:
        logging.info(' APPLYING ROUGHNESS LAW: ' + str(rl).upper())
        logging.info(' -- Creating U-Ux Rasters ...')
        for flow_h in h_list:
            roughness.set_hy_rasters(flow_h, hy_dict[flow_h])
            try:
                logging.info(' --- Discharge: ' +
                             str(int(roughness.label_q) * 100) + ' cfs')
            except:
                logging.warning('INVALID discharge code:  ' +
                                str(roughness.label_q))
            try:
                roughness_dict[rl](1)
            except:
                logging.warning('ERROR: Could not calculate ' +
                                str(roughness.label_q) + '(' + str(rl) + ')')

        logging.info(' -- Creating TAUx Rasters ...')

        # calculate dimensionless bed shear stress taux
        for i, j in zip(u_list, roughness.out_txts):
            sediment_container.make_taux_ras(i, j)
        roughness.reset_out_txt()

        logging.info(
            ' -- Clearing uux (roughness) Rasters (required for disk space preservation) ...'
        )
        fun.clean_dir(roughness.dir_out)
        fun.chk_dir(
            os.path.abspath(os.path.dirname(__file__)) + "/output/roughness/")
    qgs.exitQgis()
Exemplo n.º 7
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).")
Exemplo n.º 8
0
 def __init__(self, input_csv=str()):
     """
     :param input_csv: STR of full dir to input csv
     """
     self.csv_file = input_csv
     self.cache = os.path.dirname(os.path.abspath(__file__)) + "/.cache/"
     fGl.chk_dir(self.cache)
     self.csv_name = input_csv.split("\\")[-1].split("/")[-1].split(
         ".csv")[0]
     self.out_dir = os.path.dirname(
         os.path.abspath(__file__)) + "/output/" + self.csv_name + "/"
     print(" * creating output dir (%s) ..." % self.out_dir)
     fGl.chk_dir(self.out_dir)
     print(" * cleaning output dir ...")
     fGl.clean_dir(self.out_dir)
     self.boundary_shp = self.out_dir + "boundary.shp"
     self.point_shp = self.out_dir + self.csv_name + "_pts.shp"
     self.raster_tif = self.out_dir + self.csv_name + ".tif"
     self.tin = self.out_dir + self.csv_name + "_tin"
     self.sr = arcpy.SpatialReference(26942)
    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 __init__(self, unit_system, org_ras_dir, mod_ras_dir, reach_ids):
        # unit_system must be either "us" or "si"
        # feature_ids = list of feature shortnames
        # reach_ids = list of reach names to limit the analysis

        # general directories and parameters
        self.cache = config.dir2va + ".cache%s\\" % str(random.randint(1000000, 9999999))
        self.vol_name = mod_ras_dir.split(":\\")[-1].split(":/")[-1].split("01_Conditions\\")[-1].split("01_Conditions/")[-1].split(".tif")[0].replace("\\", "_").replace("/", "_").replace("_dem", "")
        fGl.chk_dir(self.cache)
        fGl.clean_dir(self.cache)
        self.logger = logging.getLogger("logfile")
        self.output_ras_dir = config.dir2va + "Output\\%s\\" % self.vol_name
        fGl.chk_dir(self.output_ras_dir)
        fGl.clean_dir(self.output_ras_dir)
        self.rasters = []
        self.raster_info = ""
        self.rasters_for_pos_vol = {}
        self.rasters_for_neg_vol = {}
        self.reader = cRM.Read()
        self.reaches = cDef.ReachDefinitions()
        self.volume_neg_dict = {}
        self.volume_pos_dict = {}

        try:
            self.orig_raster = arcpy.Raster(org_ras_dir)
        except:
            self.orig_raster = Float(-1)
            self.logger.info("ERROR: Cannot load original DEM")
        try:
            self.modified_raster = arcpy.Raster(mod_ras_dir)
        except:
            self.modified_raster = Float(-1)
            self.logger.info("ERROR: Cannot load modified DEM.")

        # set relevant reaches
        try:
            self.reach_ids_applied = reach_ids
            self.reach_names_applied = []
            for rn in self.reach_ids_applied:
                self.reach_names_applied.append(self.reaches.dict_id_names[rn])
        except:
            self.reach_ids_applied = self.reaches.id_xlsx
            self.reach_names_applied = self.reaches.name_dict
            self.logger.info("WARNING: Cannot identify reaches.")

        # set unit system variables
        if ("us" in str(unit_system)) or ("si" in str(unit_system)):
            self.units = unit_system
        else:
            self.units = "us"
            self.logger.info("WARNING: Invalid unit_system identifier. unit_system must be either \'us\' or \'si\'.")
            self.logger.info("         Setting unit_system default to \'us\'.")

        if self.units == "us":
            self.convert_volume_to_cy = 0.037037037037037037037037037037037  #ft3 -> cy: float((1/3)**3)
            self.unit_info = " cubic yard"
            self.volume_threshold = 0.99  # ft -- CHANGE lod US customary HERE --
        else:
            self.convert_volume_to_cy = 1.0  # m3
            self.unit_info = " cubic meter"
            self.volume_threshold = 0.30  # m -- CHANGE lod SI metric HERE --