def calculate_hypo_depth(srcfile): """ Calculates the hypocenter depth using the SRC file parameters """ cfgdict = bband_utils.parse_properties(srcfile) # Look for the needed keys in the SRC file try: depth_to_top = cfgdict["depth_to_top"] except KeyError: bband_utils.ParameterError("SRC file missing DEPTH_TO_TOP parameter!") depth_to_top = float(depth_to_top) try: dip = cfgdict["dip"] except KeyError: bband_utils.ParameterError("SRC file missing DIP parameter!") dip = float(dip) try: hypo_down_dip = cfgdict["hypo_down_dip"] except KeyError: bband_utils.ParameterError("SRC file missing HYPO_DOWN_DIP parameter!") hypo_down_dip = float(hypo_down_dip) # Now, calculate the hypocenter depth hypo_depth = depth_to_top + hypo_down_dip * math.sin(math.radians(dip)) # Done return hypo_depth
def calculate_fault_edges(a_src_file): """ Calculates the edges of the fault plane """ # Read data from SRC file cfg_dict = bband_utils.parse_properties(a_src_file) if not "fault_length" in cfg_dict: raise bband_utils.ParameterError("SRC file missing fault_length!") if not "strike" in cfg_dict: raise bband_utils.ParameterError("SRC file missing strike!") if not "lat_top_center" in cfg_dict: raise bband_utils.ParameterError("SRC file missing lat_top_center!") if not "lon_top_center" in cfg_dict: raise bband_utils.ParameterError("SRC file missing lon_top_center!") fault_length = float(cfg_dict["fault_length"]) strike = float(cfg_dict["strike"]) lat_top_center = float(cfg_dict["lat_top_center"]) lon_top_center = float(cfg_dict["lon_top_center"]) dist = fault_length / 2 # Calculate 1st edge lat1, lon1 = calculate_fault_edge(lat_top_center, lon_top_center, dist, strike) # Reverse direction if strike >= 180: strike = strike - 180 else: strike = strike + 180 # Calculate 2nd edge lat2, lon2 = calculate_fault_edge(lat_top_center, lon_top_center, dist, strike) return lat1, lon1, lat_top_center, lon_top_center, lat2, lon2
def calculate_hypo_depth(srcfile): """ Calculates the hypocenter depth using the SRC file parameters """ cfgdict = bband_utils.parse_properties(srcfile) # Look for the needed keys in the SRC file try: depth_to_top = cfgdict["depth_to_top"] except KeyError: bband_utils.ParameterError("SRC file missing DEPTH_TO_TOP parameter!") depth_to_top = float(depth_to_top) try: dip = cfgdict["dip"] except KeyError: bband_utils.ParameterError("SRC file missing DIP parameter!") dip = float(dip) try: hypo_down_dip = cfgdict["hypo_down_dip"] except KeyError: bband_utils.ParameterError("SRC file missing HYPO_DOWN_DIP parameter!") hypo_down_dip = float(hypo_down_dip) # Now, calculate the hypocenter depth hypo_depth = depth_to_top + hypo_down_dip * math.sin(math.radians(dip)) # Done return hypo_depth
def generate_src_files(numsim, source_file, srcdir, prefix, new_seed=None): """ Generates num_sim source files in the srcdir using different random seeds """ src_props = bband_utils.parse_properties(source_file) # Delete "seed" from the property set if "seed" in src_props: # Keep track of SRC file seed value seed = int(src_props["seed"]) src_props.pop("seed") # But use new_seed if provided by the user if new_seed is not None: seed = new_seed else: if new_seed is None: raise bband_utils.ParameterError("Please specify a seed for" " this simulation!") seed = new_seed # Create common list of keys for all files output = "" for key in src_props: output = output + "%s = %s\n" % (key.upper(), src_props[key]) for sim in range(0, numsim): srcfile = os.path.join(srcdir, "%s-%04d.src" % (prefix, sim)) outfile = open(srcfile, 'w') outfile.write(output) outfile.write("SEED = %d\n" % (seed)) outfile.close()
def generate_src_files(numsim, source_file, srcdir, prefix, new_seed=None): """ Generates num_sim source files in the srcdir using different random seeds """ src_props = bband_utils.parse_properties(source_file) # Delete "seed" from the property set if "seed" in src_props: # Keep track of SRC file seed value seed = int(src_props["seed"]) src_props.pop("seed") # But use new_seed if provided by the user if new_seed is not None: seed = new_seed else: if new_seed is None: raise bband_utils.ParameterError("Please specify a seed for" " this simulation!") seed = new_seed # Create common list of keys for all files output = "" for key in src_props: output = output + "%s = %s\n" % (key.upper(), src_props[key]) for sim in range(0, numsim): srcfile = os.path.join(srcdir, "%s-%04d.src" % (prefix, sim)) outfile = open(srcfile, 'w') outfile.write(output) outfile.write("SEED = %d\n" % (seed)) outfile.close()
def generate_multi_segment_src_files(numsim, source_files, srcdir, prefix): """ Generates num_sim source files in the srcdir using different random seeds, make sure we keep the common_seed constant for all indivual segments in the multi-segment run """ src_props = [] all_seeds = [] output = [] for source_file in source_files: src_props.append(bband_utils.parse_properties(source_file)) # Delete "seed" and "common_seed" from the property set for props in src_props: if "seed" in props: props.pop("seed") if "common_seed" in props: props.pop("common_seed") # Start preparing output for idx, props in enumerate(src_props): # Create common list of keys for all realizations output.append("") for key in props: output[idx] = output[idx] + "%s = %s\n" % (key.upper(), props[key]) # Generate seeds for all source files and realizations for variation in range(1, (len(source_files) + 1)): seeds = [] for sim in range(0, numsim): random.seed((sim + 1) + (variation - 1) * 500) seeds.append(int(math.exp(7 * math.log(10.0)) * random.random())) all_seeds.append(seeds) # Write seeds file seed_file = open(os.path.join(srcdir, "seeds.txt"), 'w') seed_file.write("%d\n" % (numsim)) for seed in all_seeds[0]: seed_file.write("%d\n" % (seed)) seed_file.close() # Generate the numsim SRC files for sim in range(0, numsim): for segment in range(0, len(source_files)): srcfile = os.path.join( srcdir, "%s-%04d_seg%02d.src" % (prefix, sim, (segment + 1))) outfile = open(srcfile, 'w') # Write common part to all realizations outfile.write(output[segment]) # Write seed outfile.write("SEED = %d\n" % (all_seeds[segment][sim])) # Write common seed except for segment 1 if segment > 0: outfile.write("COMMON_SEED = %d\n" % (all_seeds[0][sim])) outfile.close()
def parse_src(self, a_srcfile): """ This function calls bband_utils's parse property file function to get a dictionary of key, value pairs and then looks for a the parameters needed by bbtoolbox """ self.cfgdict = bband_utils.parse_properties(a_srcfile) val = self.getval("depth_to_top") self.DEPTH_TO_TOP = float(val) val = self.getval("fault_length") self.LENGTH = float(val) val = self.getval("dip") self.DIP = float(val) val = self.getval("rake") self.RAKE = float(val) val = self.getval("hypo_along_stk") self.HYPO_ALONG_STK = float(val) val = self.getval("hypo_down_dip") self.HYPO_DOWN_DIP = float(val) val = self.getval("magnitude") self.MAG = float(val) val = self.getval("seed") self.SEED = int(float(val)) # Now look for the optional grid parameters if 'grid_x' in self.cfgdict: self.grid_x = float(self.getval("grid_x")) if 'grid_y' in self.cfgdict: self.grid_y = float(self.getval("grid_y")) if 'grid_z' in self.cfgdict: self.grid_z = float(self.getval("grid_z")) # # Read parameters out of the source file to obtain parameters # needed by the BBcoda codes # fcodes = cc.find_fx_fy_fz(self.HYPO_ALONG_STK, self.LENGTH, self.DIP, self.HYPO_DOWN_DIP, self.DEPTH_TO_TOP) self.fsx = fcodes[0] self.fsy = fcodes[1] self.fsz = fcodes[2]
def parse_src(self, a_srcfile): """ This function calls bband_utils's parse property file function to get a dictionary of key, value pairs and then looks for a the parameters needed by bbtoolbox """ self.cfgdict = bband_utils.parse_properties(a_srcfile) val = self.getval("depth_to_top") self.DEPTH_TO_TOP = float(val) val = self.getval("fault_length") self.LENGTH = float(val) val = self.getval("dip") self.DIP = float(val) val = self.getval("hypo_along_stk") self.HYPO_ALONG_STK = float(val) val = self.getval("hypo_down_dip") self.HYPO_DOWN_DIP = float(val) val = self.getval("magnitude") self.MAG = float(val) val = self.getval("seed") self.SEED = int(float(val)) # Now look for the optional grid parameters if 'grid_x' in self.cfgdict: self.grid_x = float(self.getval("grid_x")) if 'grid_y' in self.cfgdict: self.grid_y = float(self.getval("grid_y")) if 'grid_z' in self.cfgdict: self.grid_z = float(self.getval("grid_z")) # # Read parameters out of the source file to obtain parameters # needed by the BBcoda codes # fcodes = cc.find_fx_fy_fz(self.HYPO_ALONG_STK, self.LENGTH, self.DIP, self.HYPO_DOWN_DIP, self.DEPTH_TO_TOP) self.fsx = fcodes[0] self.fsy = fcodes[1] self.fsz = fcodes[2]
def parse_src_file(a_srcfile): """ Function parses the SRC file and checks for needed keys. It returns a dictionary containing the keys found in the src file. """ src_keys = bband_utils.parse_properties(a_srcfile) required_keys = ["magnitude", "fault_length", "fault_width", "dlen", "dwid", "depth_to_top", "strike", "rake", "dip", "lat_top_center", "lon_top_center"] for key in required_keys: if key not in src_keys: raise bband_utils.ParameterError("key %s missing in src file" % (key)) # Convert keys to floats for key in src_keys: src_keys[key] = float(src_keys[key]) return src_keys
def write_simple_trace(a_src_file, out_file): """ This function reads the SRC file and calculates the fault trace """ points = [] # Read data from SRC file cfg_dict = bband_utils.parse_properties(a_src_file) if not "fault_length" in cfg_dict: raise bband_utils.ParameterError("SRC file missing fault_length!") if not "strike" in cfg_dict: raise bband_utils.ParameterError("SRC file missing strike!") if not "lat_top_center" in cfg_dict: raise bband_utils.ParameterError("SRC file missing lat_top_center!") if not "lon_top_center" in cfg_dict: raise bband_utils.ParameterError("SRC file missing lon_top_center!") fault_length = float(cfg_dict["fault_length"]) strike = float(cfg_dict["strike"]) lat_top_center = float(cfg_dict["lat_top_center"]) lon_top_center = float(cfg_dict["lon_top_center"]) dist = fault_length / 2 # Calculate 1st edge lat1, lon1 = calculate_fault_edge(lat_top_center, lon_top_center, dist, strike) # Reverse direction if strike >= 180: strike = strike - 180 else: strike = strike + 180 # Calculate 2nd edge lat2, lon2 = calculate_fault_edge(lat_top_center, lon_top_center, dist, strike) points.append([lon1, lat1]) points.append([lon_top_center, lat_top_center]) points.append([lon2, lat2]) # Now, open output file, and write the data trace_file = open(out_file, 'w') for point in points: trace_file.write("%f %f\n" % (point[0], point[1])) trace_file.flush() trace_file.close() # Save trace return points
def write_simple_trace(a_src_file, out_file): """ This function reads the SRC file and calculates the fault trace """ points = [] # Read data from SRC file cfg_dict = bband_utils.parse_properties(a_src_file) if not "fault_length" in cfg_dict: raise bband_utils.ParameterError("SRC file missing fault_length!") if not "strike" in cfg_dict: raise bband_utils.ParameterError("SRC file missing strike!") if not "lat_top_center" in cfg_dict: raise bband_utils.ParameterError("SRC file missing lat_top_center!") if not "lon_top_center" in cfg_dict: raise bband_utils.ParameterError("SRC file missing lon_top_center!") fault_length = float(cfg_dict["fault_length"]) strike = float(cfg_dict["strike"]) lat_top_center = float(cfg_dict["lat_top_center"]) lon_top_center = float(cfg_dict["lon_top_center"]) dist = fault_length / 2 # Calculate 1st edge lat1, lon1 = calculate_fault_edge(lat_top_center, lon_top_center, dist, strike) # Reverse direction if strike >= 180: strike = strike - 180 else: strike = strike + 180 # Calculate 2nd edge lat2, lon2 = calculate_fault_edge(lat_top_center, lon_top_center, dist, strike) points.append([lon1, lat1]) points.append([lon_top_center, lat_top_center]) points.append([lon2, lat2]) # Now, open output file, and write the data trace_file = open(out_file, 'w') for point in points: trace_file.write("%f %f\n" % (point[0], point[1])) trace_file.flush() trace_file.close() # Save trace return points
def parse_src(self, a_srcfile): """ This function calls bband_utils' parse property file function to get a dictionary of key, value pairs and then looks for the parameters needed by CSM """ self.cfgdict = bband_utils.parse_properties(a_srcfile) val = self.getval("magnitude") self.MAGNITUDE = float(val) val = self.getval("fault_length") self.LENGTH = float(val) val = self.getval("fault_width") self.WIDTH = float(val) val = self.getval("depth_to_top") self.DEPTH_TO_TOP = float(val) val = self.getval("strike") self.STRIKE = float(val) val = self.getval("rake") self.RAKE = float(val) val = self.getval("dip") self.DIP = float(val) val = self.getval("lat_top_center") self.LAT_TOP_CENTER = float(val) val = self.getval("lon_top_center") self.LON_TOP_CENTER = float(val) val = self.getval("hypo_along_stk") self.HYPO_ALONG_STK = float(val) val = self.getval("hypo_down_dip") self.HYPO_DOWN_DIP = float(val) val = self.getval("seed") self.SEED = int(val)
def parse_src(self, a_srcfile): """ This function calls bband_utils' parse property file function to get a dictionary of key, value pairs and then looks for the parameters needed by CSM """ self.cfgdict = bband_utils.parse_properties(a_srcfile) val = self.getval("magnitude") self.MAGNITUDE = float(val) val = self.getval("fault_length") self.LENGTH = float(val) val = self.getval("fault_width") self.WIDTH = float(val) val = self.getval("depth_to_top") self.DEPTH_TO_TOP = float(val) val = self.getval("strike") self.STRIKE = float(val) val = self.getval("rake") self.RAKE = float(val) val = self.getval("dip") self.DIP = float(val) val = self.getval("lat_top_center") self.LAT_TOP_CENTER = float(val) val = self.getval("lon_top_center") self.LON_TOP_CENTER = float(val) val = self.getval("hypo_along_stk") self.HYPO_ALONG_STK = float(val) val = self.getval("hypo_down_dip") self.HYPO_DOWN_DIP = float(val) val = self.getval("seed") self.SEED = int(val)
def generate_src_files(numsim, source_file, srcdir, prefix, hypo_rand): """ Generates num_sim source files in the srcdir using different random seeds """ src_props = bband_utils.parse_properties(source_file) # Delete "seed" from the property set if "seed" in src_props: src_props.pop("seed") # Get FAULT_LENGTH and FAULT_WIDTH from the SRC file try: flen = float(src_props["fault_length"]) fwid = float(src_props["fault_width"]) except KeyError: raise bband_utils.ParameterError("Cannot read fault_length/fault_width" " parameters from SRC file!") if hypo_rand: # Delete HYPO_ALONG_STK and HYPO_DOWN_DIP if "hypo_along_stk" in src_props: src_props.pop("hypo_along_stk") if "hypo_down_dip" in src_props: src_props.pop("hypo_down_dip") # Create common list of keys for all files output = "" for key in src_props: output = output + "%s = %s\n" % (key.upper(), src_props[key]) for sim in range(0, numsim): random.seed(sim + 1) seed = int(math.exp(7 * math.log(10.0)) * random.random()) hypo_along_stk = flen * (0.2 + 0.6 * random.random() - 0.5) hypo_down_dip = fwid * (0.2 + 0.6 * random.random()) srcfile = os.path.join(srcdir, "%s-%04d.src" % (prefix, sim)) outfile = open(srcfile, 'w') outfile.write(output) if hypo_rand: outfile.write("HYPO_ALONG_STK = %.2f\n" % (hypo_along_stk)) outfile.write("HYPO_DOWN_DIP = %.2f\n" % (hypo_down_dip)) outfile.write("SEED = %d\n" % (seed)) outfile.close()
def generate_src_files(numsim, source_file, srcdir, prefix, hypo_rand): """ Generates num_sim source files in the srcdir using different random seeds """ src_props = bband_utils.parse_properties(source_file) # Delete "seed" from the property set if "seed" in src_props: src_props.pop("seed") # Get FAULT_LENGTH and FAULT_WIDTH from the SRC file try: flen = float(src_props["fault_length"]) fwid = float(src_props["fault_width"]) except KeyError: raise bband_utils.ParameterError("Cannot read fault_length/fault_width" " parameters from SRC file!") if hypo_rand: # Delete HYPO_ALONG_STK and HYPO_DOWN_DIP if "hypo_along_stk" in src_props: src_props.pop("hypo_along_stk") if "hypo_down_dip" in src_props: src_props.pop("hypo_down_dip") # Create common list of keys for all files output = "" for key in src_props: output = output + "%s = %s\n" % (key.upper(), src_props[key]) for sim in range(0, numsim): random.seed(sim + 1) seed = int(math.exp(7 * math.log(10.0)) * random.random()) hypo_along_stk = flen * (0.2 + 0.6 * random.random() - 0.5) hypo_down_dip = fwid * (0.2 + 0.6 * random.random()) srcfile = os.path.join(srcdir, "%s-%04d.src" % (prefix, sim)) outfile = open(srcfile, 'w') outfile.write(output) if hypo_rand: outfile.write("HYPO_ALONG_STK = %.2f\n" % (hypo_along_stk)) outfile.write("HYPO_DOWN_DIP = %.2f\n" % (hypo_down_dip)) outfile.write("SEED = %d\n" % (seed)) outfile.close()
def calculate_epicenter(input_file): """ This function returns the epicenter of an event using either a SRC file or a SRF file to look for the hypocenter location. It uses Rob Graves' xy2ll utility to convert the coordinates to lat/lon. """ # If we have a SRF file, we already have a function that does this if input_file.endswith(".srf"): # Get information from srf file hypo_lon, hypo_lat, _ = get_hypocenter(input_file) return hypo_lon, hypo_lat # If we don't have a SRC file, we should print an error here if not input_file.endswith(".src"): bband_utils.ParameterError("input file should be a SRC or SRF file!") # Ok, we have a SRC file # Get information from SRC file cfgdict = bband_utils.parse_properties(input_file) try: strike = cfgdict["strike"] except KeyError: bband_utils.ParameterError("SRC file missing STRIKE parameter!") strike = float(strike) try: dip = cfgdict["dip"] except KeyError: bband_utils.ParameterError("SRC file missing DIP parameter!") dip = float(dip) try: hypo_down_dip = cfgdict["hypo_down_dip"] except KeyError: bband_utils.ParameterError("SRC file missing " "HYPO_DOWN_DIP parameter!") hypo_down_dip = float(hypo_down_dip) try: hypo_along_strike = cfgdict["hypo_along_stk"] except KeyError: bband_utils.ParameterError("SRC file missing " "HYPO_ALONG_STK parameter!") hypo_along_strike = float(hypo_along_strike) try: lat_top_center = cfgdict["lat_top_center"] except KeyError: bband_utils.ParameterError("SRC file missing " "LAT_TOP_CENTER parameter!") lat_top_center = float(lat_top_center) try: lon_top_center = cfgdict["lon_top_center"] except KeyError: bband_utils.ParameterError("SRC file missing " "LON_TOP_CENTER parameter!") lon_top_center = float(lon_top_center) # Ok, we have all the parameters that we need! hypo_perpendicular_strike = hypo_down_dip * math.cos(math.radians(dip)) # Now call xy2ll program to convert it to lat/long # Create temp directory to avoid any race conditions tmpdir = tempfile.mkdtemp(prefix="bbp-") hypfile = os.path.join(tmpdir, "src_hypo.tmp") install = InstallCfg.getInstance() cmd = ('echo "%f %f" | %s mlat=%f mlon=%f xazim=%f > %s' % (hypo_along_strike, hypo_perpendicular_strike, os.path.join(install.A_GP_BIN_DIR, "xy2ll"), lat_top_center, lon_top_center, strike, hypfile)) bband_utils.runprog(cmd, print_cmd=False) src_hypo_fp = open(hypfile, 'r') src_hypo_data = src_hypo_fp.readline() src_hypo_fp.close() src_hypo = [float(val) for val in src_hypo_data.split()] # Delete temp directory shutil.rmtree(tmpdir) # Return calculated lon/lat return src_hypo[0], src_hypo[1]
def calculate_epicenter(input_file): """ This function returns the epicenter of an event using either a SRC file or a SRF file to look for the hypocenter location. It uses Rob Graves' xy2ll utility to convert the coordinates to lat/lon. """ # If we have a SRF file, we already have a function that does this if input_file.endswith(".srf"): # Get information from srf file hypo_lon, hypo_lat, _ = get_hypocenter(input_file) return hypo_lon, hypo_lat # If we don't have a SRC file, we should print an error here if not input_file.endswith(".src"): bband_utils.ParameterError("input file should be a SRC or SRF file!") # Ok, we have a SRC file # Get information from SRC file cfgdict = bband_utils.parse_properties(input_file) try: strike = cfgdict["strike"] except KeyError: bband_utils.ParameterError("SRC file missing STRIKE parameter!") strike = float(strike) try: dip = cfgdict["dip"] except KeyError: bband_utils.ParameterError("SRC file missing DIP parameter!") dip = float(dip) try: hypo_down_dip = cfgdict["hypo_down_dip"] except KeyError: bband_utils.ParameterError("SRC file missing " "HYPO_DOWN_DIP parameter!") hypo_down_dip = float(hypo_down_dip) try: hypo_along_strike = cfgdict["hypo_along_stk"] except KeyError: bband_utils.ParameterError("SRC file missing " "HYPO_ALONG_STK parameter!") hypo_along_strike = float(hypo_along_strike) try: lat_top_center = cfgdict["lat_top_center"] except KeyError: bband_utils.ParameterError("SRC file missing " "LAT_TOP_CENTER parameter!") lat_top_center = float(lat_top_center) try: lon_top_center = cfgdict["lon_top_center"] except KeyError: bband_utils.ParameterError("SRC file missing " "LON_TOP_CENTER parameter!") lon_top_center = float(lon_top_center) # Ok, we have all the parameters that we need! hypo_perpendicular_strike = hypo_down_dip * math.cos(math.radians(dip)) # Now call xy2ll program to convert it to lat/long # Create temp directory to avoid any race conditions tmpdir = tempfile.mkdtemp(prefix="bbp-") hypfile = os.path.join(tmpdir, "src_hypo.tmp") install = InstallCfg.getInstance() cmd = ('echo "%f %f" | %s mlat=%f mlon=%f xazim=%f > %s' % (hypo_along_strike, hypo_perpendicular_strike, os.path.join(install.A_GP_BIN_DIR, "xy2ll"), lat_top_center, lon_top_center, strike, hypfile)) bband_utils.runprog(cmd, print_cmd=False) src_hypo_fp = open(hypfile, 'r') src_hypo_data = src_hypo_fp.readline() src_hypo_fp.close() src_hypo = [float(val) for val in src_hypo_data.split()] # Delete temp directory shutil.rmtree(tmpdir) # Return calculated lon/lat return src_hypo[0], src_hypo[1]
def init_velocity_models(install_obj): """ This function compiles a list of available velocity models to be used within the Bradband platform by scanning the directories insite the Greens Functions directory """ # First we get all subdirectories in the GF_DIR top directory sub_dirs = bband_utils.list_subdirs(install_obj.A_GF_DIR) # Now we add ones that have a proper configuration file for directory in sub_dirs: base_dir = os.path.join(install_obj.A_GF_DIR, directory) # Look for velocity model configuration file file_list = glob.glob(os.path.join(base_dir, "*%s" % (VELMODEL_METAFILE_SUFFIX))) if len(file_list) == 0: # No configuration file found, skip this directory continue if len(file_list) > 1: # Multiple configuration files found, warn user, and skip print("Multiple velocity model configuration files found!") print("Skipping: %s" % (base_dir)) continue # Got it! metafile = file_list[0] # Parse file file_props = bband_utils.parse_properties(metafile) if VELMODEL_NAME_PROP not in file_props: # Doesn't have name key continue if VELMODEL_VERSION_PROP not in file_props: # Doesn't have version key continue ve_model = VelocityModel(file_props[VELMODEL_NAME_PROP], file_props[VELMODEL_VERSION_PROP], base_dir) # Dictionaries are not ordered, so we have to go over them # twice to first collect the available codebases and their # velocity model files, and later collect their # codebase-specific parameters for key in file_props: if key.startswith(VELMODEL_CODE_PROP): # This key has a velocity model file mapping codebase = key.split('_')[2].upper() ve_model.add_velocity_model(codebase, file_props[key]) ve_model.add_code(codebase) for key in file_props: if key.startswith(CODE_PROP): # This key has a codebase-specific parameter codebase = key.split('_')[1].upper() # For parameter, only split the first two '_' param = key.split('_', 2)[2].upper() if codebase not in ve_model.get_codebases(): print("Codebase %s not defined, ignoring parameter %s" % (codebase, param)) continue # Add parameter to codebase ve_model.add_codebase_param(codebase, param, file_props[key]) VE_MODELS.append(ve_model)
def run(self): """ Generate an index file in the outdata directory """ print("GenHTML".center(80, '-')) install = InstallCfg.getInstance() sim_id = self.sim_id a_indir = os.path.join(install.A_IN_DATA_DIR, str(sim_id)) a_tmpdir = os.path.join(install.A_TMP_DATA_DIR, str(sim_id)) a_outdir = os.path.join(install.A_OUT_DATA_DIR, str(sim_id)) self.log = os.path.join(install.A_OUT_LOG_DIR, str(sim_id), "%d.genhtml.log" % (sim_id)) a_statfile = os.path.join(a_indir, self.r_stations) a_param_outdir = os.path.join(a_outdir, "param_files") a_param_statfile = os.path.join(a_param_outdir, self.r_stations) if self.r_src_file is not None and self.r_src_file != "": a_src_file = os.path.join(a_indir, self.r_src_file) a_param_srcfile = os.path.join(a_param_outdir, self.r_src_file) src_props = bband_utils.parse_properties(a_src_file) if "seed" in src_props: seed = src_props["seed"] else: seed = "not available" else: a_src_file = None a_param_srcfile = None # Make sure tmpdir, outdir exist dirs = [a_tmpdir, a_outdir, a_param_outdir] bband_utils.mkdirs(dirs, print_cmd=False) # Copy station list, srf_file to outdir's param_files directory shutil.copy2(a_statfile, a_param_statfile) if a_param_srcfile is not None: shutil.copy2(a_src_file, a_param_srcfile) # Get pointer to the velocity model object vel_obj = velocity_models.get_velocity_model_by_name(self.vmodel_name) if vel_obj is None: raise bband_utils.ParameterError("Cannot find velocity model: %s" % (self.vmodel_name)) vel_version = ("%s - %s" % (vel_obj.get_name(), vel_obj.get_version())) # Get pointer to validation object, if any val_version = None if self.val_name: val_obj = validation_cfg.VE_EVENTS.get_event_by_name(self.val_name) if val_obj is not None: val_version = ("%s - %s" % (val_obj.get_print_name(), val_obj.get_version())) # # Read and parse the station list with this call # slo = StationList(a_statfile) site_list = slo.getStationList() index_file = os.path.join(a_outdir, "index-%d.html" % (sim_id)) idxout = open(index_file, 'w') idxout.write("<html>\n") idxout.write("<title>Results for simulation %d</title>\n" % (sim_id)) idxout.write("<body>\n") idxout.write("<h2>Simulation Results</h2>\n") idxout.write("<table>\n") idxout.write("<tr>\n") idxout.write("<td>Broadband Version</td>\n") idxout.write("<td>%s</td>\n" % (install.VERSION)) idxout.write("</tr>\n") idxout.write("<tr>\n") idxout.write("<td>Velocity model version</td>\n") idxout.write("<td>%s</td>\n" % (vel_version)) idxout.write("</tr>\n") if val_version: idxout.write("<tr>\n") idxout.write("<td>Validation package version</td>\n") idxout.write("<td>%s</td>\n" % (val_version)) idxout.write("</tr>\n") if install.start_time is not None: idxout.write("<tr>\n") idxout.write("<td>Simulation Start Time</td>\n") idxout.write("<td>%s</td>\n" % (time.strftime("%a %d %b %Y %X %Z", install.start_time))) idxout.write("</tr>\n") idxout.write("<tr>\n") idxout.write("<td>Simulation End Time</td>\n") idxout.write("<td>%s</td>\n" % (time.strftime("%a %d %b %Y %X %Z", time.localtime()))) idxout.write("</tr>\n") idxout.write("<tr>\n") idxout.write("<td>Simulation ID</td>\n") idxout.write("<td>%d</td>\n" % (sim_id)) idxout.write("</tr>\n") idxout.write("<tr>\n") idxout.write("<td>Simulation Method</td>\n") idxout.write("<td>%s</td>\n" % (self.method)) idxout.write("</tr>\n") # Add xml file if os.path.exists(os.path.join(a_outdir, "%d.xml" % (sim_id))): idxout.write("<tr>\n") idxout.write("<td>Sim Spec</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", "%d.xml" % (sim_id)), "%d.xml" % (sim_id))) idxout.write("</tr>\n") # Add station list and src_file if os.path.exists(os.path.join(a_param_outdir, self.r_stations)): idxout.write("<tr>\n") idxout.write("<td>Station List</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", "param_files", self.r_stations), self.r_stations)) idxout.write("</tr>\n") if a_param_srcfile is not None: if os.path.exists(os.path.join(a_param_outdir, self.r_src_file)): idxout.write("<tr>\n") idxout.write("<td>Source Description</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", "param_files", self.r_src_file), self.r_src_file)) idxout.write("</tr>\n") idxout.write("<tr>\n") idxout.write("<td>Random Seed</td>\n") idxout.write('<td>%s</td>\n' % (seed)) idxout.write("</tr>\n") # Get bias plots dist_lin_plot = glob.glob(os.path.join(a_outdir, "gof-dist-lin*.png")) dist_log_plot = glob.glob(os.path.join(a_outdir, "gof-dist-log*.png")) plots = glob.glob(os.path.join(a_outdir, "gof*.png")) rd50plot = glob.glob(os.path.join(a_outdir, "gof*-rd50.png")) gmpegofplot = glob.glob(os.path.join(a_outdir, "gof*-GMPE-*.png")) mapgofplot = glob.glob(os.path.join(a_outdir, "gof-map-*.png")) if len(gmpegofplot) == 1: gmpegofplot = gmpegofplot[0] else: gmpegofplot = "" if len(mapgofplot) == 1: mapgofplot = mapgofplot[0] else: mapgofplot = "" if len(dist_lin_plot) == 1: dist_lin_plot = dist_lin_plot[0] else: dist_lin_plot = "" if len(dist_log_plot) == 1: dist_log_plot = dist_log_plot[0] else: dist_log_plot = "" if len(rd50plot) == 1: rd50plot = rd50plot[0] else: if gmpegofplot: rd50plot = [plot for plot in rd50plot if plot != gmpegofplot] if mapgofplot: rd50plot = [plot for plot in rd50plot if plot != mapgofplot] if dist_lin_plot: rd50plot = [plot for plot in rd50plot if plot != dist_lin_plot] if dist_log_plot: rd50plot = [plot for plot in rd50plot if plot != dist_log_plot] if len(rd50plot) == 1: rd50plot = rd50plot[0] else: rd50plot = "" if len(plots) > 1: rspplot = [plot for plot in plots if (plot != rd50plot and plot != gmpegofplot and plot != mapgofplot and plot != dist_lin_plot and plot != dist_log_plot)] if len(rspplot) == 1: rspplot = rspplot[0] else: rspplot = "" else: rspplot = "" gmpegofplot = os.path.basename(gmpegofplot) mapgofplot = os.path.basename(mapgofplot) rd50plot = os.path.basename(rd50plot) rspplot = os.path.basename(rspplot) dist_lin_plot = os.path.basename(dist_lin_plot) dist_log_plot = os.path.basename(dist_log_plot) # Add RotD50 bias plot if rd50plot: idxout.write("<tr>\n") idxout.write("<td>RotD50 Bias Plot</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", "%s" % (rd50plot)), "PNG")) idxout.write("</tr>\n") if mapgofplot: idxout.write("<tr>\n") idxout.write("<td>RotD50 Map GOF Plot</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", "%s" % (mapgofplot)), "PNG")) idxout.write("</tr>\n") # Add RSP bias plot if rspplot: idxout.write("<tr>\n") idxout.write("<td>Respect Bias Plot</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", "%s" % (rspplot)), "PNG")) idxout.write("</tr>\n") # Add the GMPE bias plot if gmpegofplot: idxout.write("<tr>\n") idxout.write("<td>GMPE Comparison Bias Plot</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", "%s" % (gmpegofplot)), "PNG")) idxout.write("</tr>\n") # Add distance plots if dist_lin_plot: idxout.write("<tr>\n") idxout.write("<td>RotD50 Dist Bias Linear</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", "%s" % (dist_lin_plot)), "PNG")) idxout.write("</tr>\n") if dist_log_plot: idxout.write("<tr>\n") idxout.write("<td>RotD50 Dist Bias Log</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", "%s" % (dist_log_plot)), "PNG")) idxout.write("</tr>\n") # Add station map and kml file if os.path.exists(os.path.join(a_outdir, "station_map.png")): idxout.write("<tr>\n") idxout.write("<td>Station Map</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", "station_map.png"), "PNG")) if os.path.exists(os.path.join(a_outdir, "station_map.kml")): idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", "station_map.kml"), "KML")) idxout.write("</tr>\n") # Now get SRF file and plot srfs = glob.glob(os.path.join(a_outdir, "*.srf")) if len(srfs) == 1: srffile = os.path.basename(srfs[0]) srfplot = ("%s.png" % (os.path.basename(os.path.splitext(srffile)[0]))) if not os.path.exists(os.path.join(a_outdir, srfplot)): srfplot = "" else: srffile = "" srfplot = "" if srffile: idxout.write("<tr>\n") idxout.write("<td>Rupture file</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", srffile), "data")) if srfplot: idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", srfplot), "PNG")) idxout.write("</tr>\n") idxout.write("</table>\n") idxout.write("<p><p>\n") for sits in site_list: site = sits.scode idxout.write("<p>\n") idxout.write("<h2>%s</h2>\n" % (site)) idxout.write("<table>\n") # Find all files velfile = "%d.%s.vel.bbp" % (sim_id, site) velplot = "%d.%s_velocity_seis.png" % (sim_id, site) accfile = "%d.%s.acc.bbp" % (sim_id, site) accplot = "%d.%s_acceleration_seis.png" % (sim_id, site) rd50file = "%d.%s.rd50" % (sim_id, site) rspfile = "%d.%s.rsp" % (sim_id, site) rd50plot = glob.glob(os.path.join(a_outdir, "*_%d_%s_rotd50.png" % (sim_id, site))) if len(rd50plot) == 1: rd50plot = os.path.basename(rd50plot[0]) else: rd50plot = "" rspplot = glob.glob(os.path.join(a_outdir, "*_%d_%s_rsp.png" % (sim_id, site))) if len(rspplot) == 1: rspplot = os.path.basename(rspplot[0]) else: rspplot = "" overlayfile = glob.glob(os.path.join(a_outdir, "*_%d_%s_overlay.png" % (sim_id, site))) if len(overlayfile) == 1: overlayfile = os.path.basename(overlayfile[0]) else: overlayfile = "" gmpeplot = glob.glob(os.path.join(a_outdir, "*_%d_%s_gmpe.png" % (sim_id, site))) if len(gmpeplot) == 1: gmpeplot = os.path.basename(gmpeplot[0]) else: gmpeplot = "" if os.path.exists(os.path.join(a_outdir, velfile)): idxout.write("<tr>\n") idxout.write("<td>Velocity</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", velfile), "BBP")) if os.path.exists(os.path.join(a_outdir, velplot)): idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", velplot), "PNG")) idxout.write("</tr>\n") if os.path.exists(os.path.join(a_outdir, accfile)): idxout.write("<tr>\n") idxout.write("<td>Acceleration</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", accfile), "BBP")) if os.path.exists(os.path.join(a_outdir, accplot)): idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", accplot), "PNG")) idxout.write("</tr>\n") if os.path.exists(os.path.join(a_outdir, rd50file)): idxout.write("<tr>\n") idxout.write("<td>RotD50</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", rd50file), "data")) if rd50plot: idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", rd50plot), "PNG")) idxout.write("</tr>\n") if os.path.exists(os.path.join(a_outdir, rspfile)): idxout.write("<tr>\n") idxout.write("<td>Respect</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", rspfile), "data")) if rspplot: idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", rspplot), "PNG")) idxout.write("</tr>\n") if overlayfile: idxout.write("<tr>\n") idxout.write("<td>Overlay</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", overlayfile), "PNG")) idxout.write("</tr>\n") if gmpeplot: idxout.write("<tr>\n") idxout.write("<td>GMPE Plot</td>\n") idxout.write('<td><a href="%s">%s</a></td>\n' % (os.path.join(".", gmpeplot), "PNG")) idxout.write("</tr>\n") idxout.write("</table>\n") idxout.write("</body>\n") idxout.write("</html>\n") idxout.close() print("==> Wrote file: %s" % (index_file)) print("GenHTML Completed".center(80, '-'))
def init_velocity_models(install_obj): """ This function compiles a list of available velocity models to be used within the Bradband platform by scanning the directories insite the Greens Functions directory """ # First we get all subdirectories in the GF_DIR top directory sub_dirs = bband_utils.list_subdirs(install_obj.A_GF_DIR) # Now we add ones that have a proper configuration file for directory in sub_dirs: base_dir = os.path.join(install_obj.A_GF_DIR, directory) # Look for velocity model configuration file file_list = glob.glob( os.path.join(base_dir, "*%s" % (VELMODEL_METAFILE_SUFFIX))) if len(file_list) == 0: # No configuration file found, skip this directory continue if len(file_list) > 1: # Multiple configuration files found, warn user, and skip print("Multiple velocity model configuration files found!") print("Skipping: %s" % (base_dir)) continue # Got it! metafile = file_list[0] # Parse file file_props = bband_utils.parse_properties(metafile) if VELMODEL_NAME_PROP not in file_props: # Doesn't have name key print("Cannot find velocity model name attribute!") print("Skipping: %s" % (base_dir)) continue if VELMODEL_FORMAT_PROP not in file_props: # Doesn't have a format key print("Cannot find velocity model format attribute!") print("Skipping: %s" % (base_dir)) continue if VELMODEL_VERSION_PROP not in file_props: # Doesn't have version key print("Cannot find velocity model version attribute!") print("Skipping: %s" % (base_dir)) continue if VELMODEL_ACTIVE_REGION_PROP not in file_props: # Missing active region flag print("Cannot find active region attribute!") print("Skipping: %s" % (base_dir)) continue # Check if velocity model format matching this version of the BBP velmodel_format = file_props[VELMODEL_FORMAT_PROP] if velmodel_format.split(".")[0] != VELMODEL_FORMAT: # Major velocity model format version has to match print("Cannot use velocity model format %s!" % (velmodel_format)) print("Skipping: %s" % (base_dir)) continue if file_props[VELMODEL_ACTIVE_REGION_PROP].lower() in ["1", "true"]: active_region = True elif file_props[VELMODEL_ACTIVE_REGION_PROP].lower() in ["0", "false"]: active_region = False else: # Cannot parse active region flag print("Cannot parse velocity model active region flag!") print("Skipping: %s" % (base_dir)) continue ve_model = VelocityModel(file_props[VELMODEL_NAME_PROP], file_props[VELMODEL_VERSION_PROP], active_region, base_dir) # Dictionaries are not ordered, so we have to go over them # twice to first collect the available codebases and their # velocity model files, and later collect their # codebase-specific parameters for key in file_props: if key.startswith(VELMODEL_CODE_PROP): # This key has a velocity model file mapping codebase = key.split('_')[2].upper() ve_model.add_velocity_model(codebase, file_props[key]) ve_model.add_code(codebase) for key in file_props: if key.startswith(CODE_PROP): # This key has a codebase-specific parameter codebase = key.split('_')[1].upper() # For parameter, only split the first two '_' param = key.split('_', 2)[2].upper() if codebase not in ve_model.get_codebases(): print("Codebase %s not defined, ignoring parameter %s" % (codebase, param)) continue # Add parameter to codebase ve_model.add_codebase_param(codebase, param, file_props[key]) VE_MODELS.append(ve_model)
def init_validation_events(install_obj): """ This function creates the Validation Events class and adds a validation event for each event supported in the Broadband platform """ global VE_EVENTS VE_EVENTS = ValidationEvents() # First we get all subdirectories in the VAL_DIR top directory sub_dirs = bband_utils.list_subdirs(install_obj.A_VAL_DIR) # Now we add ones that have a proper configuration file for directory in sub_dirs: base_dir = os.path.join(install_obj.A_VAL_DIR, directory) # Look for the validation configuration file file_list = glob.glob( os.path.join(base_dir, "*%s" % (VALIDATION_METAFILE_SUFFIX))) if len(file_list) == 0: # No configuration file found, skip this directory continue if len(file_list) > 1: # Multiple configuration files found, warn user, and skip print("Multiple validation configuration files found!") print("Skipping: %s" % (base_dir)) continue # Got it! metafile = file_list[0] # Parse file file_props = bband_utils.parse_properties(metafile) # Check for the required event properties req_props = [ EVENT_NAME_PROP, EVENT_PRINTNAME_PROP, EVENT_CUTOFF_PROP, EVENT_OBS_PATH_PROP, EVENT_OBS_FORMAT_PROP, EVENT_OBS_CORR_PROP, EVENT_VELOCITY_MODEL_PROP, PACKAGE_VERSION_PROP, EVENT_GMPE_SET_PROP ] all_properties = True for prop in req_props: if prop not in file_props: # Validation event doesn't have a required property all_properties = False break # Missing required properties, skip this event if not all_properties: continue # Read the event_type property, if specified event_type = DEFAULT_EVENT_TYPE if EVENT_TYPE_PROP in file_props: event_type = file_props[EVENT_TYPE_PROP] # All properties are there, create event val_event = ValidationEvent(file_props[EVENT_NAME_PROP], file_props[EVENT_PRINTNAME_PROP], base_dir, event_type, file_props[PACKAGE_VERSION_PROP]) # Set basic event parameters val_event.set_cutoff(int(file_props[EVENT_CUTOFF_PROP])) val_event.set_obs_path(file_props[EVENT_OBS_PATH_PROP]) val_event.set_obs_format(file_props[EVENT_OBS_FORMAT_PROP]) val_event.set_obs_corrections(file_props[EVENT_OBS_CORR_PROP]) val_event.set_velocity_model(file_props[EVENT_VELOCITY_MODEL_PROP]) val_event.set_gmpe_set(file_props[EVENT_GMPE_SET_PROP]) # Go through the list of parsed properties and populate for key in file_props: if key.startswith(PATH_CODE_PROP): # This key has a codebase parameters that is a path to a file codebase = key.split('_')[2].upper() param = key.split('_', 3)[3].upper() value = file_props[key] val_event.set_input_path(codebase, param, value) if key.startswith(CODE_PROP): # This key has a regular codebase parameter codebase = key.split('_')[1].upper() param = key.split('_', 2)[2].upper() value = file_props[key] val_event.set_input(codebase, param, value) VE_EVENTS.add_event(val_event)
def generate_src_files(numsim, source_file, srcdir, prefix, hypo_rand, variation, multiseg, segment, first_seg_dir): """ Generates num_sim source files in the srcdir using different random seeds """ src_props = bband_utils.parse_properties(source_file) # Delete "seed" and "common_seed" from the property set if "seed" in src_props: src_props.pop("seed") if "common_seed" in src_props: src_props.pop("common_seed") # Get FAULT_LENGTH and FAULT_WIDTH from the SRC file try: flen = float(src_props["fault_length"]) fwid = float(src_props["fault_width"]) except KeyError: raise bband_utils.ParameterError("Cannot read fault_length/fault_width" " parameters from SRC file!") if hypo_rand: # Delete HYPO_ALONG_STK and HYPO_DOWN_DIP if "hypo_along_stk" in src_props: src_props.pop("hypo_along_stk") if "hypo_down_dip" in src_props: src_props.pop("hypo_down_dip") # Create common list of keys for all files output = "" for key in src_props: output = output + "%s = %s\n" % (key.upper(), src_props[key]) common_seeds = [] # Check if we are doing a multi-segment run if multiseg and first_seg_dir is not None: # Read common seeds from seed file seed_file = open(os.path.join(first_seg_dir, "Src", "seeds.txt"), 'r') first_seg_sims = int(seed_file.readline().strip()) if first_seg_sims != numsim: print("ERROR: Number of simulations must match across segments!") sys.exit(1) for line in seed_file: common_seeds.append(int(line.strip())) seed_file.close() # Generate the numsim SRC files all_seeds = [] for sim in range(0, numsim): random.seed((sim + 1) + (variation - 1) * 500) seed = int(math.exp(7 * math.log(10.0)) * random.random()) all_seeds.append(seed) hypo_along_stk = flen * (0.2 + 0.6 * random.random() - 0.5) hypo_down_dip = fwid * (0.2 + 0.6 * random.random()) if multiseg: srcfile = os.path.join( srcdir, "%s-%04d_seg%02d.src" % (prefix, sim, segment)) else: srcfile = os.path.join(srcdir, "%s-%04d.src" % (prefix, sim)) outfile = open(srcfile, 'w') outfile.write(output) if hypo_rand: outfile.write("HYPO_ALONG_STK = %.2f\n" % (hypo_along_stk)) outfile.write("HYPO_DOWN_DIP = %.2f\n" % (hypo_down_dip)) outfile.write("SEED = %d\n" % (seed)) if multiseg and first_seg_dir is not None: outfile.write("COMMON_SEED = %d\n" % (common_seeds[sim])) outfile.close() # Check if we need to write file with all seeds if multiseg and first_seg_dir is None: # This is the first segment, write seeds file seed_file = open(os.path.join(srcdir, "seeds.txt"), 'w') seed_file.write("%d\n" % (numsim)) for seed in all_seeds: seed_file.write("%d\n" % (seed)) seed_file.close()
def init_validation_events(install_obj): """ This function creates the Validation Events class and adds a validation event for each event supported in the Broadband platform """ global VE_EVENTS VE_EVENTS = ValidationEvents() # First we get all subdirectories in the VAL_DIR top directory sub_dirs = bband_utils.list_subdirs(install_obj.A_VAL_DIR) # Now we add ones that have a proper configuration file for directory in sub_dirs: base_dir = os.path.join(install_obj.A_VAL_DIR, directory) # Look for the validation configuration file file_list = glob.glob(os.path.join(base_dir, "*%s" % (VALIDATION_METAFILE_SUFFIX))) if len(file_list) == 0: # No configuration file found, skip this directory continue if len(file_list) > 1: # Multiple configuration files found, warn user, and skip print("Multiple validation configuration files found!") print("Skipping: %s" % (base_dir)) continue # Got it! metafile = file_list[0] # Parse file file_props = bband_utils.parse_properties(metafile) # Check for the required event properties req_props = [EVENT_NAME_PROP, EVENT_PRINTNAME_PROP, EVENT_MAGNITUDE_PROP, EVENT_CUTOFF_PROP, EVENT_OBS_PATH_PROP, EVENT_OBS_FORMAT_PROP, EVENT_OBS_CORR_PROP, EVENT_VELOCITY_MODEL_PROP, PACKAGE_VERSION_PROP, EVENT_GMPE_SET_PROP] all_properties = True for prop in req_props: if prop not in file_props: # Validation event doesn't have a required property all_properties = False break # Missing required properties, skip this event if not all_properties: continue # Read the event_type property, if specified event_type = DEFAULT_EVENT_TYPE if EVENT_TYPE_PROP in file_props: event_type = file_props[EVENT_TYPE_PROP] # All properties are there, create event val_event = ValidationEvent(file_props[EVENT_NAME_PROP], file_props[EVENT_PRINTNAME_PROP], base_dir, event_type, file_props[PACKAGE_VERSION_PROP]) # Set basic event parameters val_event.set_cutoff(int(file_props[EVENT_CUTOFF_PROP])) val_event.set_magnitude(float(file_props[EVENT_MAGNITUDE_PROP])) val_event.set_obs_path(file_props[EVENT_OBS_PATH_PROP]) val_event.set_obs_format(file_props[EVENT_OBS_FORMAT_PROP]) val_event.set_obs_corrections(file_props[EVENT_OBS_CORR_PROP]) val_event.set_velocity_model(file_props[EVENT_VELOCITY_MODEL_PROP]) val_event.set_gmpe_set(file_props[EVENT_GMPE_SET_PROP]) # Go through the list of parsed properties and populate for key in file_props: if key.startswith(PATH_CODE_PROP): # This key has a codebase parameters that is a path to a file codebase = key.split('_')[2].upper() param = key.split('_', 3)[3].upper() value = file_props[key] val_event.set_input_path(codebase, param, value) if key.startswith(CODE_PROP): # This key has a regular codebase parameter codebase = key.split('_')[1].upper() param = key.split('_', 2)[2].upper() value = file_props[key] val_event.set_input(codebase, param, value) VE_EVENTS.add_event(val_event)
def generate_src_files(numsim, source_file, srcdir, prefix, hypo_rand, hypo_area, variation, multiseg, first_seg_dir): """ Generates num_sim source files in the srcdir using different random seeds """ src_props = bband_utils.parse_properties(source_file) # Delete "seed" from the property set if "seed" in src_props: src_props.pop("seed") # Get FAULT_LENGTH and FAULT_WIDTH from the SRC file try: flen = float(src_props["fault_length"]) fwid = float(src_props["fault_width"]) except KeyError: raise bband_utils.ParameterError("Cannot read fault_length/fault_width" " parameters from SRC file!") # Figure out are where hypocenter should go, by default we want to # cut 20% in each side and place the hypocenter in the center area if hypo_area["hdd_min"] is None: hypo_area["hdd_min"] = 0.2 * fwid if hypo_area["hdd_max"] is None: hypo_area["hdd_max"] = 0.8 * fwid if hypo_area["has_min"] is None: hypo_area["has_min"] = -(0.5 - 0.2) * flen if hypo_area["has_max"] is None: hypo_area["has_max"] = (0.5 - 0.2) * flen if hypo_rand: # Delete HYPO_ALONG_STK and HYPO_DOWN_DIP if "hypo_along_stk" in src_props: src_props.pop("hypo_along_stk") if "hypo_down_dip" in src_props: src_props.pop("hypo_down_dip") # Create common list of keys for all files output = "" for key in src_props: output = output + "%s = %s\n" % (key.upper(), src_props[key]) common_seeds = [] # Check if we are doing a multi-segment run if multiseg and first_seg_dir is not None: # Read common seeds from seed file seed_file = open(os.path.join(first_seg_dir, "Src", "seeds.txt"), 'r') first_seg_sims = int(seed_file.readline().strip()) if first_seg_sims != numsim: print("ERROR: Number of simulations must match across segments!") sys.exit(1) for line in seed_file: common_seeds.append(int(line.strip())) seed_file.close() # Generate the numsim SRC files all_seeds = [] for sim in range(0, numsim): random.seed((sim + 1) + (variation - 1) * 500) seed = int(math.exp(7 * math.log(10.0)) * random.random()) all_seeds.append(seed) hypo_along_stk = ((hypo_area["has_max"] - hypo_area["has_min"]) * random.random()) + hypo_area["has_min"] hypo_down_dip = ((hypo_area["hdd_max"] - hypo_area["hdd_min"]) * random.random()) + hypo_area["hdd_min"] srcfile = os.path.join(srcdir, "%s-%04d.src" % (prefix, sim)) outfile = open(srcfile, 'w') outfile.write(output) if hypo_rand: outfile.write("HYPO_ALONG_STK = %.2f\n" % (hypo_along_stk)) outfile.write("HYPO_DOWN_DIP = %.2f\n" % (hypo_down_dip)) outfile.write("SEED = %d\n" % (seed)) if multiseg and first_seg_dir is not None: outfile.write("COMMON_SEED = %d\n" % (common_seeds[sim])) outfile.close() # Check if we need to write file with all seeds if multiseg and first_seg_dir is None: # This is the first segment, write seeds file seed_file = open(os.path.join(srcdir, "seeds.txt"), 'w') seed_file.write("%d\n" % (numsim)) for seed in all_seeds: seed_file.write("%d\n" % (seed)) seed_file.close()
def init_velocity_models(install_obj): """ This function compiles a list of available velocity models to be used within the Bradband platform by scanning the directories insite the Greens Functions directory """ # First we get all subdirectories in the GF_DIR top directory sub_dirs = bband_utils.list_subdirs(install_obj.A_GF_DIR) # Now we add ones that have a proper configuration file for directory in sub_dirs: base_dir = os.path.join(install_obj.A_GF_DIR, directory) # Look for velocity model configuration file file_list = glob.glob( os.path.join(base_dir, "*%s" % (VELMODEL_METAFILE_SUFFIX))) if len(file_list) == 0: # No configuration file found, skip this directory continue if len(file_list) > 1: # Multiple configuration files found, warn user, and skip print("Multiple velocity model configuration files found!") print("Skipping: %s" % (base_dir)) continue # Got it! metafile = file_list[0] # Parse file file_props = bband_utils.parse_properties(metafile) if VELMODEL_NAME_PROP not in file_props: # Doesn't have name key continue if VELMODEL_VERSION_PROP not in file_props: # Doesn't have version key continue ve_model = VelocityModel(file_props[VELMODEL_NAME_PROP], file_props[VELMODEL_VERSION_PROP], base_dir) # Dictionaries are not ordered, so we have to go over them # twice to first collect the available codebases and their # velocity model files, and later collect their # codebase-specific parameters for key in file_props: if key.startswith(VELMODEL_CODE_PROP): # This key has a velocity model file mapping codebase = key.split('_')[2].upper() ve_model.add_velocity_model(codebase, file_props[key]) ve_model.add_code(codebase) for key in file_props: if key.startswith(CODE_PROP): # This key has a codebase-specific parameter codebase = key.split('_')[1].upper() # For parameter, only split the first two '_' param = key.split('_', 2)[2].upper() if codebase not in ve_model.get_codebases(): print("Codebase %s not defined, ignoring parameter %s" % (codebase, param)) continue # Add parameter to codebase ve_model.add_codebase_param(codebase, param, file_props[key]) VE_MODELS.append(ve_model)