示例#1
0
    def __init__(self, vmodel_name):

        vmodel_obj = velocity_models.get_velocity_model_by_name(vmodel_name)
        if vmodel_obj is None:
            raise IndexError("Cannot find velocity model: %s" % (vmodel_name))

        vmodel_params = vmodel_obj.get_codebase_params('gp')
        # Configure needed parameters from velocity model
        if 'GF_DIR' in vmodel_params:
            self.A_GP_GF_DIR = os.path.join(vmodel_obj.base_dir,
                                            vmodel_params['GF_DIR'])
        else:
            raise KeyError("GF_DIR parameter missing in velocity model %s" %
                           (vmodel_name))
        if 'GF_NAME' in vmodel_params:
            self.GF_NAME = vmodel_params['GF_NAME']
        else:
            raise KeyError("GF_NAME parameter missing in velocity model %s" %
                           (vmodel_name))
        if 'GF_LOCS' in vmodel_params:
            self.GF_LOCS = os.path.join(vmodel_obj.base_dir,
                                        vmodel_params['GF_LOCS'])
        else:
            raise KeyError("GF_LOCS parameter missing in velocity model %s" %
                           (vmodel_name))
        if 'GF_TIMES' in vmodel_params:
            self.GF_TIMES = os.path.join(vmodel_obj.base_dir,
                                         vmodel_params['GF_TIMES'])
        else:
            raise KeyError("GF_TIMES parameter missing in velocity model %s" %
                           (vmodel_name))
        if 'GF_DT' in vmodel_params:
            self.MIN_GFDT = float(vmodel_params['GF_DT'])
        else:
            raise KeyError("GF_DT parameter missing in velocity model %s" %
                           (vmodel_name))
        # Now, look for optional parameters in the velocity model
        if 'MAX_GFNT' in vmodel_params:
            self.MAX_GFNT = int(vmodel_params['MAX_GFNT'])
        else:
            self.MAX_GFNT = 4096
        if 'NTOUT' in vmodel_params:
            self.NTOUT = int(vmodel_params['NTOUT'])
        else:
            self.NTOUT = 4096

        # Now, configure other paramteres
        self.GF_SWAP_BYTES = 0
        self.DTOUT = self.MIN_GFDT
        self.COMPS = ["000", "090", "ver"]
        self.VREF = 865
示例#2
0
    def __init__(self, vmodel_name, a_srcname=None):
        install = InstallCfg.getInstance()
        #
        # Name and Path to executable
        #
        self.R_UC_FFSP_EXE = "ffsp_v2"
        self.A_UC_FFSP_EXE = os.path.join(install.A_UCSB_BIN_DIR,
                                          self.R_UC_FFSP_EXE)
        self.FFSP_OUTPUT_PREFIX = "FFSP_OUTPUT"

        self.FMAX = 50.0 # Nyquist -- use 50 for 100Hz

        vmodel_obj = velocity_models.get_velocity_model_by_name(vmodel_name)
        if vmodel_obj is None:
            raise IndexError("Cannot find velocity model: %s" %
                             (vmodel_name))

        vmodel_params = vmodel_obj.get_codebase_params('ucsb')
        # Configure DT based on information from velocity model
        if 'GF_DT' in vmodel_params:
            self.DT = float(vmodel_params['GF_DT'])
        else:
            raise KeyError("%s parameter missing in velocity model %s" %
                           ("GF_DT", vmodel_name))

        # Other region-specific parameters
        if 'RV_AVG' in vmodel_params:
            self.RV_AVG = float(vmodel_params['RV_AVG'])
        else:
            self.RV_AVG = 2.5

        if 'TP_TR' in vmodel_params:
            self.TP_TR = float(vmodel_params['TP_TR'])
        else:
            self.TP_TR = 0.1

        if 'LF_VELMODEL' in vmodel_params:
            self.A_UC_LF_VELMODEL = os.path.join(vmodel_obj.base_dir,
                                                 vmodel_params['LF_VELMODEL'])
        else:
            raise KeyError("%s parameter missing in velocity model %s" %
                           ("LF_VELMODEL", vmodel_name))

        if a_srcname:
            self.CFGDICT = bband_utils.parse_src_file(a_srcname)

            # RV_AVG is optional!
            # If SRC file has it, it overrides the region and the default values
            if "rv_avg" in self.CFGDICT:
                self.RV_AVG = self.CFGDICT["rv_avg"]
示例#3
0
    def setUp(self):
        """
        Cope needed files to run the test
        """
        self.vmodel_name = "LABasin"
        self.sim_id = int(seqnum.get_seq_num())
        self.install = InstallCfg()
        self.vmodel_obj = vmodels.get_velocity_model_by_name(self.vmodel_name)

        indir = os.path.join(self.install.A_IN_DATA_DIR, str(self.sim_id))
        tmpdir = os.path.join(self.install.A_TMP_DATA_DIR, str(self.sim_id))
        outdir = os.path.join(self.install.A_OUT_DATA_DIR, str(self.sim_id))
        logdir = os.path.join(self.install.A_OUT_LOG_DIR, str(self.sim_id))
        # Create all directories
        bband_utils.mkdirs([indir, tmpdir, outdir, logdir], print_cmd=False)

        # Copy needed files

        # src file
        r_src_file = "nr_v12_11_0_fs.src"
        src_file = os.path.join(self.install.A_TEST_REF_DIR, "uwo", r_src_file)
        self.src_file = os.path.join(indir, r_src_file)
        cmd = "cp %s %s" % (src_file, self.src_file)
        bband_utils.runprog(cmd)

        # exsim param template file
        vmodel_params = self.vmodel_obj.get_codebase_params('exsim')
        self.failIf('GENERIC_PARAM' not in vmodel_params)
        r_param_template = vmodel_params['GENERIC_PARAM']

        self.failIf(r_param_template == "" or r_param_template is None)
        param_template = os.path.join(self.vmodel_obj.base_dir,
                                      r_param_template)
        # r_param_template is relative to the velocity model basedir,
        # get only basename
        r_param_template = os.path.basename(r_param_template)
        self.param_template = os.path.join(indir, r_param_template)
        cmd = "cp %s %s" % (param_template, self.param_template)
        bband_utils.runprog(cmd)

        # station file
        r_stations = "nr_v12_11_2.stl"
        stations = os.path.join(self.install.A_TEST_REF_DIR, "uwo", r_stations)
        self.stations = os.path.join(indir, r_stations)
        cmd = "cp %s %s" % (stations, self.stations)
        bband_utils.runprog(cmd)
示例#4
0
    def __init__(self, vmodel_name, method):
        # self.SITEAMP_MODEL3D = "cb2014"
        self.SITEAMP_MODEL = "bssa2014"
        self.FILTLIST = "filtmatchlist1"
        self.GEN_ROCK_VS = 865
        self.VREF_MAX = 1100
        self.FMIN = 0.05
        self.FMIDBOT = 0.1
        self.FLOWCAP = 0.0
        self.FMAX = 50.0
        self.FHIGHTOP = 20.0
        self.COMPS = ["000", "090", "ver"]

        vmodel_obj = velocity_models.get_velocity_model_by_name(vmodel_name)
        if vmodel_obj is None:
            raise IndexError("Cannot find velocity model: %s" % (vmodel_name))

        if method.lower() == "ucsb":
            vmodel_params = vmodel_obj.get_codebase_params('ucsb')
        elif method.lower() == "exsim":
            vmodel_params = vmodel_obj.get_codebase_params('exsim')
        elif method.lower() == "sdsu":
            vmodel_params = vmodel_obj.get_codebase_params('sdsu')
        else:
            # For now...
            vmodel_params = vmodel_obj.get_codebase_params('gp')

        # Read reference velocities for LF and HF components, use defaults
        # values if not found so that the code will still work without GP GFs
        if 'LF_VREF' in vmodel_params:
            self.LF_VREF = int(vmodel_params['LF_VREF'])
        else:
            self.LF_VREF = self.GEN_ROCK_VS
        if 'HF_VREF' in vmodel_params:
            self.HF_VREF = int(vmodel_params['HF_VREF'])
        else:
            self.HF_VREF = self.GEN_ROCK_VS
示例#5
0
    def create_bbtoolbox_files(self, stat_file):
        """
        This function creates the files needed by bbtoolbox, including
        the scattering file (if not provided), the station file, and
        the parameter file
        """
        sta_base = os.path.basename(os.path.splitext(self.r_stations)[0])
        a_indir = os.path.join(self.install.A_IN_DATA_DIR, str(self.sim_id))
        a_tmpdir = os.path.join(self.install.A_TMP_DATA_DIR, str(self.sim_id))
        a_tmpdir_mod = os.path.join(self.install.A_TMP_DATA_DIR,
                                    str(self.sim_id),
                                    "bbtoolbox_%s" % (sta_base))
        a_outdir = os.path.join(self.install.A_OUT_DATA_DIR, str(self.sim_id))
        a_param_outdir = os.path.join(a_outdir, "param_files")

        stat_list = StationList(stat_file)

        # 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))
        vmodel_params = vel_obj.get_codebase_params('sdsu')

        # Look for the source function parameter
        if 'SOURCE_FUNC' in vmodel_params:
            self.source_func = vmodel_params['SOURCE_FUNC']

        # Look for correlation file parameter
        if "CORRELATION_FILE" in vmodel_params:
            # Set flag
            self.infcorr_flag = 1
            # Find correlation file
            self.correlation_file = os.path.join(
                vel_obj.base_dir, vmodel_params['CORRELATION_FILE'])
            # Also copy file to bbtoolbox directory
            shutil.copy2(
                self.correlation_file,
                os.path.join(a_tmpdir_mod,
                             os.path.basename(self.correlation_file)))
        else:
            # Disable flag
            self.infcorr_flag = 0
            self.correlation_file = "correlation_file_not_used.txt"

        # Take care of scattering file
        if not self.r_scattering:
            # Need to create our file
            scattering_template = os.path.join(self.install.A_SDSU_DATA_DIR,
                                               "scattering_generic.dat")
            self.r_scattering = "scattering.dat"
            a_scattering = os.path.join(a_indir, self.r_scattering)

            # Look for KAPPA
            if 'KAPPA' in vmodel_params:
                self.kappa = float(vmodel_params['KAPPA'])
            # Look for FMAX
            if 'FMAX' in vmodel_params:
                self.fmax = float(vmodel_params['FMAX'])
            if 'Q' in vmodel_params:
                self.q_coda = float(vmodel_params['Q'])
            if 'FDEC' in vmodel_params:
                self.fdec = float(vmodel_params['FDEC'])
            if 'GS_FLAG' in vmodel_params:
                self.gs_flag = float(vmodel_params['GS_FLAG'])
            if 'NGAW_FLAG' in vmodel_params:
                self.ngaw_flag = float(vmodel_params['NGAW_FLAG'])
            if 'TR_SCA' in vmodel_params:
                self.tr_sca = float(vmodel_params['TR_SCA'])
            if 'AFAC' in vmodel_params:
                self.afac = float(vmodel_params['AFAC'])
            if 'BFAC' in vmodel_params:
                self.bfac = float(vmodel_params['BFAC'])
            if 'STR_FAC' in vmodel_params:
                self.str_fac = float(vmodel_params['STR_FAC'])

            # Check if we need to calculate stress
            if 'CALCULATE_STRESS' in vmodel_params:
                if float(vmodel_params['CALCULATE_STRESS']) == True:
                    # Calculate stress based on depth of hypocenter
                    self.str_fac = self.config.calculate_stress()

            # Open template and output files
            scat_in = open(scattering_template, 'r')
            scat_out = open(a_scattering, 'w')

            for line in scat_in:
                if line.find(r"\* iseed - seed number for scattering") >= 0:
                    # This is the iseed line, insert the random iseed here
                    pos = line.find(r"\* iseed - seed number for scattering")
                    scat_out.write("%d   %s" % (self.iseed, line[pos:]))
                elif line.find(r"\* kappa - kappa at the site") >= 0:
                    # This is the kappa line, insert self.kappa here
                    pos = line.find(r"\* kappa - kappa at the site")
                    scat_out.write("%.3f   %s" % (self.kappa, line[pos:]))
                elif line.find(r"\* fmax - ") >= 0:
                    # This is the fmax line, insert self.fmax here
                    pos = line.find(r"\* fmax - ")
                    scat_out.write("%.2f   %s" % (self.fmax, line[pos:]))
                elif line.find(r"\* Q - Q for the coda") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* Q - Q for the coda")
                    scat_out.write("%.1f   %s" % (self.q_coda, line[pos:]))
                elif line.find(r"\* fdec - see equation") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* fdec - see equation")
                    scat_out.write("%.2f    %s" % (self.fdec, line[pos:]))
                elif line.find(r"\* gs_flag - determine type") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* gs_flag - determine type")
                    scat_out.write("%d    %s" %
                                   (int(self.gs_flag), line[pos:]))
                elif line.find(r"\* ngaw_flag - GMPEs") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* ngaw_flag - GMPEs")
                    scat_out.write("%d    %s" %
                                   (int(self.ngaw_flag), line[pos:]))
                elif line.find(r"\* Tr_sca - scaling factor") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* Tr_sca - scaling factor")
                    scat_out.write("%.4f  %s" % (self.tr_sca, line[pos:]))
                elif line.find(r"\* afac - qk factor") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* afac - qk factor")
                    scat_out.write("%.1f    %s" % (self.afac, line[pos:]))
                elif line.find(r"\* bfac - qk factor") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* bfac - qk factor")
                    scat_out.write("%.1f    %s" % (self.bfac, line[pos:]))
                elif line.find(r"\* str_fac - Brune stress") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* str_fac - Brune stress")
                    scat_out.write("%.2e %s" % (self.str_fac, line[pos:]))
                elif line.find(r"\* cseed - seed number") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* cseed - seed number")
                    scat_out.write("%d   %s" % (self.config.SEED, line[pos:]))
                elif line.find(r"\* infcorr_flag") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* infcorr_flag")
                    scat_out.write("%d    %s" %
                                   (int(self.infcorr_flag), line[pos:]))
                else:
                    scat_out.write(line)

            # Done
            scat_in.close()
            scat_out.flush()
            scat_out.close()

        # Keep copy of scattering file in outdata
        shutil.copy2(a_scattering,
                     os.path.join(a_param_outdir, self.r_scattering))

        # Convert station file
        a_tmpfile = "station_%s.coords" % (sta_base)
        a_sdsu_stat_list = os.path.join(a_tmpdir_mod,
                                        "bbtstations_%s.tmp" % (sta_base))
        a_sdsu_extended_fault = os.path.join(a_indir, "extended_fault")
        param_filename = stas2files.bbp2sdsu_statlist(
            a_indir, stat_list, a_sdsu_stat_list, self.r_srffile,
            self.r_xyz_srffile, a_sdsu_extended_fault, a_tmpfile)
        r_faultfile = os.path.basename(a_sdsu_extended_fault)
        # param_filename = stas2files.bbp2sdsu_statlist(a_indir, stat_list,
        #                                               a_sdsu_stat_list, hypo)
        # now a_sdsu_stat_list has X Y name vs rho kappa
        # a_sdsu_stat_list.par has bbextension, bbstat, bbhypo

        # Build real station list
        self.r_stations = "bbtstations_%s.dat" % (sta_base)
        stalist_fp = open(os.path.join(a_indir, self.r_stations), 'w')
        # write headers
        stalist_fp.write("/* STATIONS FILE FOR BROAD-BAND COMPUTATION CODE " +
                         "(P.M. MAI & K.B.OLSEN) */\n")
        stalist_fp.write("/* STATIONS COORDINATES ARE IN THE X-Y SYSTEM " +
                         "REPORTED IN FIG.1 OF APPENDIX A */\n\n")
        stalist_fp.write("/* INPUT DIRECTORY */\n")
        # Create input directory and file prefix for the stations files
        file_prefix = os.path.join(a_tmpdir_mod, "%d." % (self.sim_id))
        stalist_fp.write("%s\n\n" % (file_prefix))
        stalist_fp.write("/* FILES FORMAT [RGF BIN CMP 3SF] */\n")
        stalist_fp.write("\t3SF\n\n")
        stalist_fp.write("/* FILES EXTENSION OR BINARY FILE NAME */\n")
        glob_stat = "%s/*-lf.bbp" % (a_tmpdir)
        bbp_list = glob.glob(glob_stat)
        # Now, figure out the file suffix
        if len(bbp_list) > 0:
            file_suffix = "-lf.bbp"
        else:
            file_suffix = ".bbp"

        # Write suffix
        stalist_fp.write("%s\n\n" % (file_suffix))

        # Write header for station list
        stalist_fp.write("/*\tX\tY\tNAME\tVs\tRho\tKappa */\n")

        # Now, append the station list we have in a_sdsu_stat_list
        conv_list_fp = open(a_sdsu_stat_list, 'r')
        for line in conv_list_fp:
            stalist_fp.write(line)
            # Figure out if station file path is too long
            pieces = line.split()
            st_name = pieces[2]
            total_length = len(file_prefix) + len(st_name) + len(file_suffix)
            if total_length >= bband_utils.SDSU_MAX_FILENAME:
                # Close files
                stalist_fp.close()
                conv_list_fp.close()
                raise ValueError("station path for %s " % (st_name) +
                                 " is %d characters long, maximum is %d" %
                                 (total_length, bband_utils.SDSU_MAX_FILENAME))
        # Flush all data, and close this file
        stalist_fp.flush()
        stalist_fp.close()
        # Close station file
        conv_list_fp.close()

        # Keep copy of station file in outdata
        shutil.copy2(os.path.join(a_indir, self.r_stations),
                     os.path.join(a_param_outdir, self.r_stations))

        # Read param file
        conv_par_fp = open(param_filename, 'r')
        conv_par_data = conv_par_fp.readlines()
        conv_par_fp.close()

        # 2nd line is hypo coordinates
        hypo_line = conv_par_data[1].split(':')[1]
        hypo_coords = []
        for i in range(0, 3):
            hypo_coords.append(hypo_line.split()[i])
        min_box_dims = []
        min_box_line = conv_par_data[0].split(':')[1]
        for i in range(0, 2):
            min_box_dims.append(float(min_box_line.split()[i]))

        # FS: Feb-2013: Get magnitude directly from SRC file
        # FS: Mar-2013: We use this magnitude only when we don't have
        # a SRC file
        # get magnitude from 3rd line
        magnitude = float(conv_par_data[2].split(':')[1])

        self.r_bbparfile = "%d_%s.bbpar" % (self.sim_id, sta_base)
        parfile_name = os.path.join(a_indir, self.r_bbparfile)
        parfile_fp = open(parfile_name, 'w')
        parfile_fp.write("/* MODALITY FLAG: [0] LF-HF MERGING, " +
                         "[1] LF-SCATTERING, [2] LF-ISOCHRONE */\n")
        parfile_fp.write(" %d\n" % (self.config.MODALITY))
        parfile_fp.write("/* OUTPUT DIRECTORY */\n")
        parfile_fp.write('"%s"\n' % a_tmpdir_mod)
        parfile_fp.write('/* VELOCITY MODEL FILE (3D MODEL OR 1D MODEL) */\n')
        parfile_fp.write('"%s"\n' % (os.path.join(a_indir, self.r_velmodel)))
        parfile_fp.write("/* STATIONS FILE REPORTING [X-Y] COORDINATES, " +
                         "FILENAMES AND PARAMETERS */\n")
        parfile_fp.write('"%s"\n' % (os.path.join(a_indir, self.r_stations)))
        parfile_fp.write("/* OPTIONAL 2ND STATIONS FILE REPORTING ONLY " +
                         "FILENAMES - ONLY FOR MODALITY = 0  */\n")
        parfile_fp.write("2ndstations.dat\n")
        parfile_fp.write("/* FAULT MODEL TYPE: [POINT], " +
                         "[EXTENDED FAULT-MODEL FILE] */\n")
        parfile_fp.write(' extended "%s"\n' %
                         (os.path.join(a_indir, r_faultfile)))
        # parfile_fp.write(' point\n')
        parfile_fp.write("/* HYPOCENTER COORDINATES [X-Y-Z] IN KM */\n")
        parfile_fp.write("%.2f %.2f %.2f\n" % (float(
            hypo_coords[0]), float(hypo_coords[1]), float(hypo_coords[2])))
        parfile_fp.write('/* GRID DEFINITION [X-Y-Z] FOR RAYTRACING: ' +
                         '"NEAR-SIDE", GRID-SPACING (IN KM) */\n')
        parfile_fp.write("0.0 0.0 0.0 1.0\n")
        parfile_fp.write('/* GRID DEFINITION [X-Y-Z] FOR RAYTRACING: ' +
                         '"FAR-SIDE" (IN KM) */\n')
        if self.config.grid_x is not None and self.config.grid_y is not None:
            parfile_fp.write(
                "%.1f %.1f %.1f\n" %
                (self.config.grid_x, self.config.grid_y, self.config.grid_z))
        else:
            parfile_fp.write(
                "%.1f %.1f %.1f\n" %
                (round(min_box_dims[0] + 20.0, 0),
                 round(min_box_dims[1] + 20.0, 0), self.config.grid_z))
        parfile_fp.write("/* SCATTERING PARAMETERS FILE */\n")
        parfile_fp.write('"%s"\n' % (os.path.join(a_indir, self.r_scattering)))
        parfile_fp.write("/* EVENT MAGNITUDE */\n")
        if self.config.MAG is None:
            parfile_fp.write("%.2f\n" % (magnitude))
        else:
            parfile_fp.write("%.2f\n" % (self.config.MAG))
        parfile_fp.write("/* DOMINANT SOURCE MECHANISM [SS RS NS AL] */\n")
        parfile_fp.write("%s\n" % conv_par_data[3].split(":")[1].strip())
        parfile_fp.write("/* SOURCE TIME FUNCTION "
                         "[TRI BOX YOF DREG LIU USER-DEF] */\n")
        parfile_fp.write("%s\n" % (self.source_func))
        parfile_fp.write("/* VERBOSE MODE [ON OFF] */\n")
        parfile_fp.write("off\n")
        parfile_fp.write("/* SRF FILE */\n")
        parfile_fp.write('"%s"\n' %
                         (os.path.join(a_indir, self.r_xyz_srffile)))
        parfile_fp.write("/* CORRELATION FILE */\n")
        parfile_fp.write("%s\n" % (os.path.basename(self.correlation_file)))
        parfile_fp.write("/* RAKE */\n")
        parfile_fp.write("%.2f\n" % (self.config.RAKE))
        parfile_fp.flush()
        parfile_fp.close()

        # Keep a copy in the outdata directory
        shutil.copy2(parfile_name,
                     os.path.join(a_param_outdir, self.r_bbparfile))
def collect_realization_params(args, realization):
    """
    Collects parameters for one realization
    """
    indir = os.path.join(args.top_level_indir, realization)
    outdir = os.path.join(args.top_level_outdir, realization)
    src_files = glob.glob("%s/*.src" % (indir))
    stl_file = glob.glob("%s/*.stl" % (indir))[0]
    data = {}

    # Compile data from SRC file(s)
    data["num_src"] = len(src_files)
    # Save info in args too for first realization
    if "num_src" not in args:
        args.num_src = len(src_files)
    for i, src_file in zip(range(1, len(src_files) + 1), src_files):
        src_index = "bbp_src_%d" % (i)
        src_keys = bband_utils.parse_src_file(src_file)
        src_keys["mechanism"] = calculate_mechanism(src_keys["rake"])
        data[src_index] = src_keys

    # Combine SRC information
    data["segments_length"] = data["bbp_src_1"]["fault_length"]
    data["segments_width"] = data["bbp_src_1"]["fault_width"]
    data["segments_ztor"] = data["bbp_src_1"]["depth_to_top"]
    data["segments_strike"] = data["bbp_src_1"]["strike"]
    data["segments_rake"] = data["bbp_src_1"]["rake"]
    data["segments_dip"] = data["bbp_src_1"]["dip"]
    data["total_length"] = float(data["bbp_src_1"]["fault_length"])
    data["average_strike"] = [float(data["bbp_src_1"]["strike"])]
    data["average_rake"] = [float(data["bbp_src_1"]["rake"])]
    data["average_dip"] = [float(data["bbp_src_1"]["dip"])]
    data["average_width"] = [float(data["bbp_src_1"]["fault_width"])]
    data["average_ztor"] = [float(data["bbp_src_1"]["depth_to_top"])]
    for i in range(2, len(src_files) + 1):
        src_index = "bbp_src_%d" % (i)
        data["segments_length"] = "%s,%s" % (data["segments_length"],
                                             data[src_index]["fault_length"])
        data["segments_width"] = "%s,%s" % (data["segments_width"],
                                            data[src_index]["fault_width"])
        data["segments_ztor"] = "%s,%s" % (data["segments_ztor"],
                                           data[src_index]["depth_to_top"])
        data["segments_strike"] = "%s,%s" % (data["segments_strike"],
                                             data[src_index]["strike"])
        data["segments_rake"] = "%s,%s" % (data["segments_rake"],
                                           data[src_index]["rake"])
        data["segments_dip"] = "%s,%s" % (data["segments_dip"],
                                          data[src_index]["dip"])
        data["total_length"] = (data["total_length"] +
                                float(data[src_index]["fault_length"]))
        data["average_strike"].append(data[src_index]["strike"])
        data["average_rake"].append(data[src_index]["rake"])
        data["average_dip"].append(data[src_index]["dip"])
        data["average_width"].append(data[src_index]["fault_width"])
        data["average_ztor"].append(data[src_index]["depth_to_top"])
    data["average_strike"] = np.average(data["average_strike"])
    data["average_rake"] = np.average(data["average_rake"])
    data["average_dip"] = np.average(data["average_dip"])
    data["average_width"] = np.average(data["average_width"])
    data["average_ztor"] = np.average(data["average_ztor"])
    data["average_mechanism"] = calculate_mechanism(data["average_rake"])

    # Get velocity model data
    html_file = glob.glob("%s/*.html" % (outdir))[0]
    data["vmodel_name"] = get_vmodel_from_html(html_file)
    vel_obj = velocity_models.get_velocity_model_by_name(data["vmodel_name"])
    if vel_obj is None:
        print("ERROR: Cannot find velocity model %s!" % (data["vmodel_name"]))
        sys.exit(-1)
    if args.general_method in ["gp", "sdsu", "song"]:
        vmodel_params = vel_obj.get_codebase_params('gp')
        vmodel_file = vel_obj.get_velocity_model('gp')
        data["gf_name"] = vmodel_params['GF_NAME']
        data["vs_30"] = calculate_vs30(vmodel_file)
        data["gf_dt"] = float(vmodel_params['GF_DT'])
    elif args.general_method in ["ucsb"]:
        vmodel_params = vel_obj.get_codebase_params('ucsb')
        vmodel_file = vel_obj.get_velocity_model('ucsb')
        data["gf_name"] = vmodel_params['GREEN_SOIL']
        data["vs_30"] = "-999"
        data["gf_dt"] = float(vmodel_params['GF_DT'])
    else:
        data["gf_name"] = "-888"
        data["vs_30"] = "-888"
        data["gf_dt"] = "-888"

    # Parse STL file
    slo = StationList(stl_file)
    site_list = slo.getStationList()
    station_names = []
    for site in site_list:
        station_names.append(site.scode)
    data["station_names"] = station_names

    stations = {}
    for site in site_list:
        stations[site.scode] = {}
        if args.bbp_software_info_site == "None":
            vs_30 = data["vs_30"]
        elif site.vs30 is None:
            vs_30 = data["vs_30"]
        else:
            vs_30 = site.vs30
        collect_station_params(site, stations[site.scode], src_files, args,
                               realization, vs_30)
        collect_rd50_values(stations[site.scode], args)
        collect_rd100_values(stations[site.scode], args)

    # Save data
    data["stations"] = stations

    # Save realization data
    args.data[realization] = data
示例#7
0
文件: genslip.py 项目: xiaolongma/bbp
    def run(self):
        """
        Runs Genslip
        """
        print("GP Rupture Generator GenSlip".center(80, '-'))

        # Load configuration, set sim_id
        install = InstallCfg.getInstance()
        sim_id = self.sim_id

        # Build directory paths
        a_tmpdir = os.path.join(install.A_TMP_DATA_DIR, str(sim_id))
        a_indir = os.path.join(install.A_IN_DATA_DIR, str(sim_id))
        a_outdir = os.path.join(install.A_OUT_DATA_DIR, str(sim_id))
        a_logdir = os.path.join(install.A_OUT_LOG_DIR, str(sim_id))

        # Make sure the output and tmp directories exist
        bband_utils.mkdirs([a_tmpdir, a_indir, a_outdir], print_cmd=False)

        # Now, file paths
        self.log = os.path.join(a_logdir, "%d.genslip.log" % (sim_id))
        a_srcfile = os.path.join(a_indir, self.r_srcfile)
        a_velfile = os.path.join(a_indir, self.r_velmodel)

        # Read src file
        cfg = GenslipCfg(a_srcfile)

        # Define location of input velocity model file
        a_velmodel = os.path.join(a_tmpdir, self.r_velmodel)

        # 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))
        # Check for velocity model-specific parameters
        vmodel_params = vel_obj.get_codebase_params('gp')
        # Look for RISETIME_COEF
        if 'RISETIME_COEF' in vmodel_params:
            self.risetime_coef = float(vmodel_params['RISETIME_COEF'])
        else:
            self.risetime_coef = cfg.RISETIME_COEF
        # Look for SHAL_VRUP
        if 'SHAL_VRUP' in vmodel_params:
            self.shal_vrup = float(vmodel_params['SHAL_VRUP'])
        else:
            self.shal_vrup = cfg.SHAL_VRUP
        # Look for MEAN_RVFAC
        if 'MEAN_RVFAC' in vmodel_params:
            self.mean_rvfac = float(vmodel_params['MEAN_RVFAC'])
        else:
            self.mean_rvfac = cfg.MEAN_RVFAC
        # Look for RANGE_RVFAC
        if 'RANGE_RVFAC' in vmodel_params:
            self.range_rvfac = float(vmodel_params['RANGE_RVFAC'])
        else:
            self.range_rvfac = cfg.RANGE_RVFAC
        # Look for RISETIME_FAC
        if 'RISETIME_FAC' in vmodel_params:
            self.risetime_fac = float(vmodel_params['RISETIME_FAC'])
        else:
            self.risetime_fac = cfg.RISETIME_FAC
        # Look for DEEP_RISETIME_FAC
        if 'DEEP_RISETIME_FAC' in vmodel_params:
            self.deep_risetime_fac = float(vmodel_params['DEEP_RISETIME_FAC'])
        else:
            self.deep_risetime_fac = cfg.DEEP_RISETIME_FAC
        # Look for SLIP SIGMA
        if 'SLIP_SIGMA' in vmodel_params:
            self.slip_sigma = float(vmodel_params['SLIP_SIGMA'])
        else:
            self.slip_sigma = cfg.SLIP_SIGMA

        # Look for DT
        if 'GF_DT' in vmodel_params:
            gf_dt = float(vmodel_params['GF_DT'])
        else:
            raise bband_utils.ParameterError("Cannot find GF_DT parameter in"
                                             "velocity model %s!" %
                                             (self.vmodel_name))

        # Calculate nstk,ndip
        nstk = round(cfg.CFGDICT["fault_length"] / cfg.CFGDICT["dlen"])
        ndip = round(cfg.CFGDICT["fault_width"] / cfg.CFGDICT["dwid"])

        # Calculate rvfac
        if "common_seed" in cfg.CFGDICT:
            rvfac = calculate_rvfac(self.mean_rvfac, self.range_rvfac,
                                    cfg.CFGDICT["common_seed"])
        else:
            rvfac = calculate_rvfac(self.mean_rvfac, self.range_rvfac,
                                    cfg.CFGDICT["seed"])

        # moment = math.pow(10, 1.5 * (cfg.MAG + 10.7))

        # For multi-segment SRC files
        if "rupture_delay" in cfg.CFGDICT:
            rupture_delay = cfg.CFGDICT["rupture_delay"]
        else:
            rupture_delay = 0.0

        if "moment_fraction" in cfg.CFGDICT:
            moment_fraction = cfg.CFGDICT["moment_fraction"]
        else:
            moment_fraction = -1.0

        if "max_fault_length" in cfg.CFGDICT:
            flen_max = cfg.CFGDICT["max_fault_length"]
        else:
            flen_max = -1.0

        r_gsftmp = "m%.2f-%.2fx%.2f.gsf" % (
            cfg.CFGDICT["magnitude"], cfg.CFGDICT["dlen"], cfg.CFGDICT["dwid"])
        a_gsftmp = os.path.join(a_tmpdir, r_gsftmp)

        r_outroot = "m%.2f-%.2fx%.2f_s%d-v5.2.2" % (
            cfg.CFGDICT["magnitude"], cfg.CFGDICT["dlen"], cfg.CFGDICT["dwid"],
            cfg.CFGDICT["seed"])
        a_srffile = os.path.join(a_indir, "%s.srf" % (r_outroot))

        progstring = (
            "%s/fault_seg2gsf read_slip_vals=0 << EOF > %s 2>> %s\n" %
            (install.A_GP_BIN_DIR, a_gsftmp, self.log) + "1\n" +
            "%f %f %f %f %f %f %f %f %d %d\n" %
            (cfg.CFGDICT["lon_top_center"], cfg.CFGDICT["lat_top_center"],
             cfg.CFGDICT["depth_to_top"], cfg.CFGDICT["strike"], cfg.
             CFGDICT["dip"], cfg.CFGDICT["rake"], cfg.CFGDICT["fault_length"],
             cfg.CFGDICT["fault_width"], nstk, ndip) + "EOF")
        bband_utils.runprog(progstring)

        progstring = ("%s/genslip-v5.2.2 read_erf=0 write_srf=1 " %
                      (install.A_GP_BIN_DIR) +
                      "read_gsf=1 write_gsf=0 infile=%s " % (a_gsftmp) +
                      "mag=%.2f nstk=%d ndip=%d " %
                      (cfg.CFGDICT["magnitude"], nstk, ndip) + "ns=1 nh=1 " +
                      "kmodel=2 seed=%d slip_sigma=%f " %
                      (cfg.CFGDICT["seed"], self.slip_sigma) +
                      "circular_average=0 modified_corners=0 " +
                      "velfile=%s shypo=%f dhypo=%f rvfrac=%f " %
                      (a_velfile, cfg.CFGDICT["hypo_along_stk"],
                       cfg.CFGDICT["hypo_down_dip"], rvfac) +
                      "shal_vrup_dep=%f shal_vrup_deprange=%f shal_vrup=%f " %
                      (cfg.RTDEP, cfg.RTDEP_RANGE, self.shal_vrup) +
                      "side_taper=0.02 bot_taper=0.0 top_taper=0.0 " +
                      "dt=%f risetime_coef=%f plane_header=1 " %
                      (gf_dt, self.risetime_coef) +
                      "risetimefac=%f risetimedep=%f risetimedep_range=%f " %
                      (self.risetime_fac, cfg.RTDEP, cfg.RTDEP_RANGE) +
                      "rt_scalefac=%f slip_water_level=%f " %
                      (cfg.RT_SCALEFAC, cfg.SLIP_WATER_LEVEL) +
                      "deep_risetimedep=%f deep_risetimedep_range=%f " %
                      (cfg.DEEP_RISETIMEDEP, cfg.DEEP_RISETIMEDEP_RANGE) +
                      "deep_risetimefac=%f " % (self.deep_risetime_fac) +
                      "flen_max=%f rupture_delay=%f moment_fraction=%f " %
                      (flen_max, rupture_delay, moment_fraction) +
                      "srf_version=2.0 rake_sigma=15.0 fdrup_time=1 " +
                      "deep_vrup=0.6 use_gaus=1 alpha_rough=0.01 " +
                      "lambda_min=0.08 tsfac_coef=1.1 tsfac1_sigma=1.0 " +
                      "tsfac1_scor=0.8 rtime1_sigma=0.85 rtime1_scor=0.8 " +
                      "> %s 2>> %s" % (a_srffile, self.log))
        bband_utils.runprog(progstring)

        #
        # mv result to outputfile
        #
        progstring = "cp %s %s" % (a_srffile,
                                   os.path.join(a_tmpdir, self.r_srffile))
        bband_utils.runprog(progstring)
        progstring = "cp %s %s" % (a_srffile,
                                   os.path.join(a_indir, self.r_srffile))
        bband_utils.runprog(progstring)
        progstring = "cp %s %s" % (a_srffile,
                                   os.path.join(a_outdir, self.r_srffile))
        bband_utils.runprog(progstring)

        # Plot SRF
        plot_srf.run(self.r_srffile, sim_id=self.sim_id)

        print("GP GenSlip Completed".center(80, '-'))
示例#8
0
文件: hfsims.py 项目: somu15/bbp
    def run(self):
        """
        This function prepares the parameters for HFSim and then calls it
        """
        print("GP HfSims".center(80, '-'))

        install = InstallCfg.getInstance()
        sim_id = self.sim_id

        # Find validation object if this is a validation run
        if self.val_name is not None:
            self.val_obj = validation_cfg.VE_EVENTS.get_event_by_name(
                self.val_name)

        sta_base = os.path.basename(os.path.splitext(self.r_stations)[0])
        self.log = os.path.join(install.A_OUT_LOG_DIR, str(sim_id),
                                "%d.hfsims_%s.log" % (sim_id, sta_base))

        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_srffile = os.path.join(a_indir, self.r_srffile)
        # Make sure we work when starting from an SRF file
        if self.r_srcfile:
            a_srcfile = os.path.join(a_indir, self.r_srcfile)
        else:
            a_srcfile = ""
        # Set up basic parameters, read SRC file if provided
        config = HfsimsCfg(a_srcfile=a_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))

        # Check for velocity model-specific parameters
        vmodel_params = vel_obj.get_codebase_params('gp')
        # Look for KAPPA
        if 'KAPPA' in vmodel_params:
            self.kappa = float(vmodel_params['KAPPA'])
        else:
            self.kappa = config.KAPPA
        # Look for QFEXP
        if 'QFEXP' in vmodel_params:
            self.qfexp = float(vmodel_params['QFEXP'])
        else:
            self.qfexp = config.DEFAULT_QFEXP
        # Look for SDROP
        if 'SDROP' in vmodel_params:
            self.sdrop = int(vmodel_params['SDROP'])
        else:
            self.sdrop = config.DEFAULT_SDROP
        # Look for C0 and C1
        if 'C0' in vmodel_params:
            self.c0 = int(vmodel_params['C0'])
        else:
            self.c0 = config.DEFAULT_C0
        if 'C1' in vmodel_params:
            self.c1 = int(vmodel_params['C1'])
        else:
            self.c1 = config.DEFAULT_C1
        # Look for DEFAULT_FCFAC
        if 'DEFAULT_FCFAC' in vmodel_params:
            self.default_fcfac = float(vmodel_params['DEFAULT_FCFAC'])
        else:
            self.default_fcfac = config.DEFAULT_FCFAC
        # Look for rayset
        if 'RAYSET' in vmodel_params:
            self.rayset = ast.literal_eval(vmodel_params['RAYSET'])
        else:
            self.rayset = config.RAYSET
        # Look for a high frequency DT
        if 'HF_DT' in vmodel_params:
            self.dt = float(vmodel_params['HF_DT'])
        else:
            self.dt = config.DT
        # Look for MEAN_RVFAC
        if 'MEAN_RVFAC' in vmodel_params:
            self.mean_rvfac = float(vmodel_params['MEAN_RVFAC'])
        else:
            self.mean_rvfac = config.MEAN_RVFAC
        # Look for RANGE_RVFAC
        if 'RANGE_RVFAC' in vmodel_params:
            self.range_rvfac = float(vmodel_params['RANGE_RVFAC'])
        else:
            self.range_rvfac = config.RANGE_RVFAC
        # Look for SHAL_RVFAC
        if 'SHAL_RVFAC' in vmodel_params:
            self.shal_rvfac = float(vmodel_params['SHAL_RVFAC'])
        else:
            self.shal_rvfac = config.SHAL_RVFAC
        # Look for VSMOHO
        if 'VSMOHO' in vmodel_params:
            self.vsmoho = float(vmodel_params['VSMOHO'])
        else:
            self.vsmoho = config.DEFAULT_VSMOHO
        # Look for DEEP_RVFAC
        if 'DEEP_RVFAC' in vmodel_params:
            self.deep_rvfac = float(vmodel_params['DEEP_RVFAC'])
        else:
            self.deep_rvfac = config.DEEP_RVFAC
        # Look for PATH_DUR_MODEL
        if 'PATH_DUR_MODEL' in vmodel_params:
            self.path_dur_model = int(vmodel_params['PATH_DUR_MODEL'])
        else:
            self.path_dur_model = config.PATH_DUR_MODEL
        # Look for RVSIG
        if 'RVSIG' in vmodel_params:
            self.rvsig = float(vmodel_params['RVSIG'])
        else:
            self.rvsig = config.RVSIG
        # Look for DX
        if 'DEFAULT_DX' in vmodel_params:
            self.default_dx = float(vmodel_params['DEFAULT_DX'])
        else:
            self.default_dx = config.DEFAULT_DX
        # Look for DY
        if 'DEFAULT_DY' in vmodel_params:
            self.default_dy = float(vmodel_params['DEFAULT_DY'])
        else:
            self.default_dy = config.DEFAULT_DY
        # Look for ISPAR_ADJUST
        if 'ISPAR_ADJUST' in vmodel_params:
            ispar_adjust = int(vmodel_params['ISPAR_ADJUST'])
        else:
            ispar_adjust = config.ISPAR_ADJUST

        # Calculate rvfac
        if "common_seed" in config.CFGDICT:
            rvfac = calculate_rvfac(self.mean_rvfac, self.range_rvfac,
                                    config.CFGDICT["common_seed"])
        else:
            rvfac = calculate_rvfac(self.mean_rvfac, self.range_rvfac,
                                    config.CFGDICT["seed"])

        # Look for tlen
        if "TLEN" in vmodel_params:
            self.tlen = float(vmodel_params['TLEN'])
        else:
            self.tlen = config.TLEN

        # Start with some default values
        moment = -1
        extra_fcfac = config.DEFAULT_EXTRA_FCFAC

        if self.val_obj is not None:
            extra_fcfac = float(self.val_obj.get_input("GP", "EXTRA_FCFAC"))
            try:
                tlen = float(self.val_obj.get_input("GP", "TLEN"))
                self.tlen = tlen
            except (ValueError, KeyError, TypeError):
                # No problem, just use the default TLEN for this simulation
                pass

        fcfac = round((1 + self.default_fcfac) * (1 + extra_fcfac) - 1, 4)

        a_slipfile = os.path.join(
            a_tmpdir, "%s.%s.%fx%f" %
            (self.r_srffile, sta_base, self.default_dx, self.default_dy))

        progstring = ("%s " %
                      (os.path.join(install.A_GP_BIN_DIR, "srf2stoch")) +
                      "infile=%s outfile=%s " % (a_srffile, a_slipfile) +
                      "target_dx=%f target_dy=%f " %
                      (self.default_dx, self.default_dy) + ">> %s 2>&1" %
                      (self.log))
        bband_utils.runprog(progstring)

        a_outp = os.path.join(a_tmpdir, "tmp_hfsim_out")
        a_velmod = os.path.join(install.A_IN_DATA_DIR, str(sim_id),
                                self.r_velmodel)
        a_statfile = os.path.join(install.A_IN_DATA_DIR, str(sim_id),
                                  self.r_stations)

        # Create local velocity model
        vel_in_fp = open(a_velmod, 'r')
        a_velmod = "%s_%s.local" % (a_velmod, sta_base)
        vel_out_fp = open(a_velmod, 'w')
        vel_in_data = vel_in_fp.readlines()
        vel_in_fp.close()
        i = 0
        for line in vel_in_data:
            i += 1
            if line.startswith('#') or line.startswith('%'):
                continue
            pieces = line.split()
            if len(pieces) >= 4:
                th = float(pieces[0])
                vp = float(pieces[1])
                vs = float(pieces[2])
                dn = float(pieces[3])
                qs = self.c0 + self.c1 * vs
                if i == len(vel_in_data):
                    th = 0.0
                vel_out_fp.write("%8.4f %8.4f %8.4f %8.4f %8.2f %8.2f\n" %
                                 (th, vp, vs, dn, qs, qs))
            else:
                vel_out_fp.write(line)
        vel_out_fp.flush()
        vel_out_fp.close()
        #
        # Scan the station list with this object construction
        # This scanner removes all the comment lines and the
        # list that is returned has one station per line in it.
        #
        slo = StationList(a_statfile)
        site_list = slo.getStationList()
        nstat = len(site_list)

        # Create rayset param list
        rayset_param = ""
        for item in self.rayset:
            rayset_param = rayset_param + "%d " % (item)
        rayset_param = rayset_param.strip()
        #
        # Run initial hfsim conf
        #
        progstring = (
            "%s >> %s 2>&1 << END\n" %
            (os.path.join(install.A_GP_BIN_DIR, config.HFSIM), self.log) +
            "%d\n" % self.sdrop + "%s\n" % a_statfile + "%s\n" % a_outp +
            "%s\n" % rayset_param + "%d\n" % config.SITEAMP +
            "4 0 0.02 19.9\n" + "%d\n" % config.CFGDICT["seed"] +
            "%d\n" % nstat + "%f %f %f %f %f\n" %
            (self.tlen, self.dt, config.FMAX, self.kappa, self.qfexp) +
            "%f %f %f %f %f\n" % (rvfac, self.shal_rvfac, self.deep_rvfac,
                                  config.C_ZERO, config.C_ALPHA) + "%s %f\n" %
            (moment, config.RUPV) + "%s\n" % a_slipfile + "%s\n" % a_velmod +
            "%f\n" % self.vsmoho + "-99 0.0 0.0 0.0 0.0 1\n" + "-1\n" +
            "%f 0.0 %f\n" % (config.FA_SIG1, self.rvsig) + "%d\n" %
            (self.path_dur_model) + "%d -1 -1\n" % (ispar_adjust) + "END")
        bband_utils.runprog(progstring)

        #
        # Start the per station processing
        #
        for site in site_list:
            # Need to integrate each component, since hfsims outputs cm/s/s
            for comp in ['000', '090', 'ver']:
                cmd = ("%s integ=1 " %
                       (os.path.join(install.A_GP_BIN_DIR, "integ_diff")) +
                       "filein=%s_%s.%s fileout=%s/%d.%s-hf.%s >> %s 2>&1" %
                       (a_outp, site.scode, comp, a_tmpdir, sim_id, site.scode,
                        comp, self.log))
                bband_utils.runprog(cmd, print_cmd=False)

            progstring1 = (
                "%s wcc2bbp=1 " %
                (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                'title="HF Sim NGAH, stat=%s" ' % (site.scode) +
                "nsfile=%s/%d.%s-hf.000 " % (a_tmpdir, sim_id, site.scode) +
                "ewfile=%s/%d.%s-hf.090 " % (a_tmpdir, sim_id, site.scode) +
                "udfile=%s/%d.%s-hf.ver " % (a_tmpdir, sim_id, site.scode) +
                'units="%s" > %s/%d.%s-hf.bbp 2>> %s\n' %
                (str(config.UNITS), a_tmpdir, sim_id, site.scode, self.log))
            bband_utils.runprog(progstring1, print_cmd=False)

            progstring1 = ("%s wcc2bbp=1 " %
                           (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                           'title="HF Sim NGAH, stat=%s" ' % site.scode +
                           "nsfile=%s_%s.000 " % (a_outp, site.scode) +
                           "ewfile=%s_%s.090 " % (a_outp, site.scode) +
                           "udfile=%s_%s.ver " % (a_outp, site.scode) +
                           '> %s_%s.bbp 2>> %s\n' %
                           (a_outp, site.scode, self.log))
            bband_utils.runprog(progstring1, print_cmd=False)

        print("GP HfSims Completed".center(80, '-'))
示例#9
0
文件: csm.py 项目: somu15/bbp
    def run(self):
        """
        This function prepares the parameter file for CSM, invokes
        it, and formats its output to be compatible with the Broadband
        Platform
        """
        print("UNR CSM".center(80, '-'))

        self.install = InstallCfg.getInstance()
        install = self.install
        sim_id = self.sim_id

        # 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))
        vmodel_params = vel_obj.get_codebase_params('csm')

        if 'SDROP' in vmodel_params:
            sdrp = float(vmodel_params['SDROP'])
        else:
            sdrp = None

        # Find validation object if this is a validation run
        if self.val_name is not None:
            self.val_obj = validation_cfg.VE_EVENTS.get_event_by_name(self.val_name)

        sta_base = os.path.basename(os.path.splitext(self.r_stations)[0])
        self.log = os.path.join(install.A_OUT_LOG_DIR,
                                str(sim_id),
                                "%d.csm_%s.log" % (sim_id, sta_base))
        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_tmpdir_mod = os.path.join(install.A_TMP_DATA_DIR,
                                    str(sim_id),
                                    "csm_%s" % (sta_base))
        a_outdir = os.path.join(install.A_OUT_DATA_DIR, str(sim_id))
        #
        # Make sure the output and two tmp directories exist
        #
        bband_utils.mkdirs([a_tmpdir, a_tmpdir_mod, a_outdir],
                           print_cmd=False)

        a_velmodel = os.path.join(a_indir, self.r_velmodel)
        a_stations = os.path.join(a_indir, self.r_stations)
        self.stat_list = StationList(a_stations)
        self.num_stations = len(self.stat_list.site_list)
        self.csm_dir = a_tmpdir_mod

        # Read input files, calculate CSM parameters
        self.config = CSMCfg(os.path.join(install.A_IN_DATA_DIR,
                                          str(sim_id),
                                          self.r_srcfile))
        self.config.calculate_params(a_velmodel, sdrp)

        # Create CSM station list
        self.create_station_list()

        # Create mod files
        self.create_mod_files()

        # Create Simula's station list
        self.create_simula_stations()

        # Create nuclear.in file
        self.create_nuclear_in()

        # Create simula.in file
        self.create_simula_in()

        # Create the random number file needed by Simula
        self.create_simula_random()

        # Create scat1d.in file
        self.create_scat1d_in()

        # Create compom.in file
        self.create_compom_in()

        # Create csevents01.dat file
        self.create_csevents()

        # Run in tmpdir subdir to isolate temp fortran files
        # Save cwd, change back to it at the end
        old_cwd = os.getcwd()
        os.chdir(a_tmpdir_mod)

        # Calculate the Greens Functions
        csm_gf_bin = os.path.join(install.A_UNR_BIN_DIR,
                                  "green_99v8")
        cmd = ("%s >> %s 2>&1" % (csm_gf_bin, self.log))
        bband_utils.runprog(cmd, abort_on_error=True)

        # Now, generate the simulations
        csm_sim_bin = os.path.join(install.A_UNR_BIN_DIR,
                                   "simula")
        cmd = ("%s >> %s 2>&1" % (csm_sim_bin, self.log))
        bband_utils.runprog(cmd, abort_on_error=True)

        # Restore working directory
        os.chdir(old_cwd)

        # Need to copy and re-format output seismograms
        self.process_seismograms()

        print("UNR CSM Completed".center(80, '-'))
示例#10
0
文件: csm.py 项目: SCECcode/BBP
    def run(self):
        """
        This function prepares the parameter file for CSM, invokes
        it, and formats its output to be compatible with the Broadband
        Platform
        """
        print("UNR CSM".center(80, '-'))

        self.install = InstallCfg.getInstance()
        install = self.install
        sim_id = self.sim_id

        # 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))
        vmodel_params = vel_obj.get_codebase_params('csm')

        if 'SDROP' in vmodel_params:
            sdrp = float(vmodel_params['SDROP'])
        else:
            sdrp = None

        # Find validation object if this is a validation run
        if self.val_name is not None:
            self.val_obj = validation_cfg.VE_EVENTS.get_event_by_name(self.val_name)

        sta_base = os.path.basename(os.path.splitext(self.r_stations)[0])
        self.log = os.path.join(install.A_OUT_LOG_DIR,
                                str(sim_id),
                                "%d.csm_%s.log" % (sim_id, sta_base))
        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_tmpdir_mod = os.path.join(install.A_TMP_DATA_DIR,
                                    str(sim_id),
                                    "csm_%s" % (sta_base))
        a_outdir = os.path.join(install.A_OUT_DATA_DIR, str(sim_id))
        #
        # Make sure the output and two tmp directories exist
        #
        bband_utils.mkdirs([a_tmpdir, a_tmpdir_mod, a_outdir],
                           print_cmd=False)

        a_velmodel = os.path.join(a_indir, self.r_velmodel)
        a_stations = os.path.join(a_indir, self.r_stations)
        self.stat_list = StationList(a_stations)
        self.num_stations = len(self.stat_list.site_list)
        self.csm_dir = a_tmpdir_mod

        # Read input files, calculate CSM parameters
        self.config = CSMCfg(os.path.join(install.A_IN_DATA_DIR,
                                          str(sim_id),
                                          self.r_srcfile))
        self.config.calculate_params(a_velmodel, sdrp)

        # Create CSM station list
        self.create_station_list()

        # Create mod files
        self.create_mod_files()

        # Create Simula's station list
        self.create_simula_stations()

        # Create nuclear.in file
        self.create_nuclear_in()

        # Create simula.in file
        self.create_simula_in()

        # Create the random number file needed by Simula
        self.create_simula_random()

        # Create scat1d.in file
        self.create_scat1d_in()

        # Create compom.in file
        self.create_compom_in()

        # Create csevents01.dat file
        self.create_csevents()

        # Run in tmpdir subdir to isolate temp fortran files
        # Save cwd, change back to it at the end
        old_cwd = os.getcwd()
        os.chdir(a_tmpdir_mod)

        # Calculate the Greens Functions
        csm_gf_bin = os.path.join(install.A_UNR_BIN_DIR,
                                  "green_99v8")
        cmd = ("%s >> %s 2>&1" % (csm_gf_bin, self.log))
        bband_utils.runprog(cmd, abort_on_error=True)

        # Now, generate the simulations
        csm_sim_bin = os.path.join(install.A_UNR_BIN_DIR,
                                   "simula")
        cmd = ("%s >> %s 2>&1" % (csm_sim_bin, self.log))
        bband_utils.runprog(cmd, abort_on_error=True)

        # Restore working directory
        os.chdir(old_cwd)

        # Need to copy and re-format output seismograms
        self.process_seismograms()

        print("UNR CSM Completed".center(80, '-'))
示例#11
0
文件: exsim.py 项目: somu15/bbp
    def create_exsim_param_file(self):
        """
        This function creates the parameter file needed by ExSim
        """
        sta_base = os.path.basename(os.path.splitext(self.r_stations)[0])
        a_indir = os.path.join(self.install.A_IN_DATA_DIR, str(self.sim_id))
        a_tmpdir_mod = os.path.join(self.install.A_TMP_DATA_DIR,
                                    str(self.sim_id), "exsim_%s" % (sta_base))
        a_param_template = os.path.join(a_indir, self.r_param_template)
        a_param_out = os.path.join(a_tmpdir_mod, self.config.PARAM_FILE)
        output_stem = "exsim-output-%s" % (sta_base)

        # 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))
        vmodel_params = vel_obj.get_codebase_params('exsim')

        # Look for additional files needed by ExSim
        if 'CRUSTAL_AMP' in vmodel_params:
            self.crustal_amp = os.path.join(vel_obj.base_dir,
                                            vmodel_params['CRUSTAL_AMP'])
        else:
            raise bband_utils.ParameterError("Cannot find crustal_amp "
                                             "parameter in velocity "
                                             "model %s" % (self.vmodel_name))
        if 'SITE_AMP' in vmodel_params:
            self.site_amp = os.path.join(vel_obj.base_dir,
                                         vmodel_params['SITE_AMP'])
        else:
            raise bband_utils.ParameterError("Cannot find site_amp "
                                             "parameter in velocity "
                                             "model %s" % (self.vmodel_name))
        if 'EMPIRICAL_DIR' in vmodel_params:
            self.empirical_dir = os.path.join(vel_obj.base_dir,
                                              vmodel_params['EMPIRICAL_DIR'])
        else:
            raise bband_utils.ParameterError("Cannot find empirical_dir "
                                             "parameter in velocity "
                                             "model %s" % (self.vmodel_name))
        if 'EMPIRICAL_RANGES' in vmodel_params:
            self.empirical_ranges = os.path.join(
                vel_obj.base_dir, vmodel_params['EMPIRICAL_RANGES'])
        else:
            raise bband_utils.ParameterError("Cannot find empirical_ranges "
                                             "parameter in velocity "
                                             "model %s" % (self.vmodel_name))
        if 'SLIP_WEIGHTS' in vmodel_params:
            self.slip_weights = os.path.join(vel_obj.base_dir,
                                             vmodel_params['SLIP_WEIGHTS'])
        else:
            raise bband_utils.ParameterError("Cannot find slip_weights "
                                             "parameter in velocity "
                                             "model %s" % (self.vmodel_name))
        # Look for KAPPA and STRESS
        if 'KAPPA' in vmodel_params:
            self.kappa = float(vmodel_params['KAPPA'])
        if 'STRESS' in vmodel_params:
            self.stress = float(vmodel_params['STRESS'])

        # Check if we need to calculate stress
        if 'CALCULATE_STRESS' in vmodel_params:
            if float(vmodel_params['CALCULATE_STRESS']) == True:
                # Calculate stress based on depth of hypocenter
                self.stress = self.config.calculate_stress()

        # Stage these files into tmpdir_mod directory
        shutil.copy2(self.crustal_amp, a_tmpdir_mod)
        shutil.copy2(self.site_amp, a_tmpdir_mod)
        shutil.copy2(self.slip_weights, a_tmpdir_mod)

        # Now we need to figure out which empirical_amps file to use
        empirical_file = self.find_empirical_file()
        empirical_in = os.path.join(self.empirical_dir, empirical_file)
        empirical_out = os.path.join(a_tmpdir_mod, self.config.EMPIRICAL_AMPS)
        shutil.copy2(empirical_in, empirical_out)

        # Ok, need to write ExSim's param file now!
        self.template_in = open(a_param_template, 'r')
        self.param_out = open(a_param_out, 'w')

        # Replace parameters in the order they appear in ExSim's template
        self.template_replace(["<MAG>", "<STRESS>"],
                              [self.config.CFGDICT['magnitude'], self.stress])
        self.template_replace(
            ["<MAG>", "<STRESS>", "<KAPPA>"],
            [self.config.CFGDICT['magnitude'], self.stress, self.kappa])
        self.template_replace(["<LAT>", "<LON>"], [
            self.config.CFGDICT['lat_top_edge'],
            self.config.CFGDICT['lon_top_edge']
        ])
        self.template_replace(["<STRIKE>", "<DIP>", "<DEPTH>"], [
            self.config.CFGDICT['strike'], self.config.CFGDICT['dip'],
            self.config.CFGDICT['depth_to_top']
        ])
        self.template_replace(["<F_LEN>", "<F_WID>"], [
            self.config.CFGDICT["fault_length"],
            self.config.CFGDICT["fault_width"]
        ])
        self.template_replace(["<HYPO_ALONG_STK>", "<HYPO_DOWN_DIP>"], [
            self.config.CFGDICT["hypo_along_stk"],
            self.config.CFGDICT["hypo_down_dip"]
        ])
        self.template_replace(["<OUTPUT_STEM>"], [output_stem])
        self.template_replace(["<CRUSTAL_AMP_FILE>"],
                              [os.path.basename(self.crustal_amp)])
        self.template_replace(["<SITE_AMP_FILE>"],
                              [os.path.basename(self.site_amp)])
        self.template_replace(["<EMPIRICAL_AMP_FILE>"],
                              [os.path.basename(self.config.EMPIRICAL_AMPS)])
        self.template_replace(["<SEED>"], [int(self.config.CFGDICT['seed'])])
        self.template_replace(["<SLIP_WEIGHTS_FILE>"],
                              [os.path.basename(self.slip_weights)])
        self.template_replace(["<NUM_STATIONS>"], [self.num_stations])
        # Now, copy everything else!
        self.template_replace(["<END_OF_TEMPLATE_FILE>"], [""])

        # Almost done, now we need to add stations
        site_list = self.stat_list.getStationList()

        # Check for maximum number of stations
        if len(site_list) > self.config.MAX_STATIONS:
            raise bband_utils.ParameterError("Too many stations in "
                                             "the station list: %d. " %
                                             (len(site_list)) +
                                             "Maximum limit is %d." %
                                             (self.config.MAX_STATIONS))

        for site in site_list:
            self.param_out.write("%f  %f\n" % (site.lat, site.lon))

        # Done! Close files.
        self.template_in.close()
        self.param_out.close()

        # Make copy of ExSIM param file in input directory
        shutil.copy2(a_param_out, a_indir)
示例#12
0
文件: match.py 项目: somu15/bbp
    def run(self):
        """
        Runs the match module to merge low and high frequency seismograms
        """
        print("Match".center(80, '-'))

        install = InstallCfg.getInstance()
        config = MatchCfg()

        sim_id = self.sim_id
        sta_base = os.path.basename(os.path.splitext(self.r_stations)[0])
        self.log = os.path.join(install.A_OUT_LOG_DIR, str(sim_id),
                                "%d.match_%s.log" % (sim_id, sta_base))

        a_statfile = os.path.join(install.A_IN_DATA_DIR, str(sim_id),
                                  self.r_stations)

        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))

        # Make sure tmpdir exists
        dirs = [a_tmpdir]
        bband_utils.mkdirs(dirs, print_cmd=False)

        pow2_param = 0
        if self.pow2:
            pow2_param = 1

        # Start with defaults
        self.phase = config.PHASE
        self.hf_fhi = config.HF_FHI
        self.lf_flo = config.LF_FLO

        # Set match method
        if config.MATCH_METHOD == 1:
            self.phase = 1
        elif config.MATCH_METHOD == 2:
            val = 1.0 / (2.0 * config.HF_ORD)
            self.hf_fhi = (self.hf_fhi *
                           math.exp(val * math.log(math.sqrt(2.0) - 1.0)))
            val = -1.0 / (2.0 * config.LF_ORD)
            self.lf_flo = (self.lf_flo *
                           math.exp(val * math.log(math.sqrt(2.0) - 1.0)))

        #
        # Read and parse the station list with this call
        #
        slo = StationList(a_statfile)
        site_list = slo.getStationList()

        # 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))

        # Check for velocity model-specific parameters
        vmodel_params = vel_obj.get_codebase_params('gp')

        # Figure out what DT we should use when resampling

        # Figure out the LF DT value
        if self.acc:
            seis_ext = '.acc.bbp'
        else:
            seis_ext = '.bbp'

        lf_seis = None
        hf_seis = None

        # Find one LF seismogram and one HF seismogram
        for sites in site_list:
            site = sites.scode
            if os.path.exists(
                    os.path.join(a_tmpdir,
                                 "%d.%s-lf%s" % (sim_id, site, seis_ext))):
                lf_seis = os.path.join(a_tmpdir,
                                       "%d.%s-lf%s" % (sim_id, site, seis_ext))
                if os.path.exists(
                        os.path.join(a_tmpdir,
                                     "%d.%s-hf%s" % (sim_id, site, seis_ext))):
                    hf_seis = os.path.join(
                        a_tmpdir, "%d.%s-hf%s" % (sim_id, site, seis_ext))
                    break

        # Need one of each
        if lf_seis is None:
            raise bband_utils.ParameterError("Cannot find a LF seismogram")
        if hf_seis is None:
            raise bband_utils.ParameterError("Cannot find a HF seismogram")

        # Pick DT from these files
        lf_dt = None
        lf_file = open(lf_seis)
        for line in lf_file:
            line = line.strip()
            if line.startswith("#") or line.startswith("%"):
                continue
            # Got to first timestamp. Now, pick two consecutive
            # timestamps values
            lf_t1 = float(line.strip().split()[0])
            lf_t2 = float(lf_file.next().strip().split()[0])
            # Subtract the two times
            lf_dt = lf_t2 - lf_t1
            # All done!
            break
        lf_file.close()

        if lf_dt is None:
            raise bband_utils.ParameterError("Cannot find LF_DT!")

        hf_dt = None
        hf_file = open(hf_seis)
        for line in hf_file:
            line = line.strip()
            if line.startswith("#") or line.startswith("%"):
                continue
            # Got to first timestamp. Now, pick two consecutive
            # timestamps values
            hf_t1 = float(line.strip().split()[0])
            hf_t2 = float(hf_file.next().strip().split()[0])
            # Subtract the two times
            hf_dt = hf_t2 - hf_t1
            # All done!
            break
        hf_file.close()

        if hf_dt is None:
            raise bband_utils.ParameterError("Cannot find HF_DT!")

        # In the GP method, we can potentially have two independent DT
        # values, one used by the rupture generator and the
        # low-frequency jbsim seismogram simulator, and another value
        # used by the high-frequency hfsims program. We have to use
        # the smaller of these two values in order to properly combine
        # the low-, and high-frequency seismograms.

        new_dt = min(lf_dt, hf_dt)

        # Go through the stations
        for sites in site_list:
            # Pick station name
            site = sites.scode
            #
            # We have a verbose of silent invocation. This is a very
            # verbose program so our default writes to dev/null
            #

            #
            # There are multiple possibilities; either we have
            # separate HF and LF files, we have HF and .bbp, LF and
            # .bbp, or just .bbp.  In all cases, we need to separate
            # them to get components.
            #
            hf_exists = False
            lf_exists = False

            if not self.acc:
                print("==> Processing velocity seismograms for station: %s" %
                      (site))
                # Need to convert to acc first
                if os.path.exists(
                        os.path.join(a_tmpdir,
                                     "%d.%s-hf.bbp" % (sim_id, site))):
                    hf_exists = True
                if os.path.exists(
                        os.path.join(a_tmpdir,
                                     "%d.%s-lf.bbp" % (sim_id, site))):
                    lf_exists = True

                # If no files exist for this station, make a note and continue
                if not hf_exists and not lf_exists:
                    print("===> No velocity seismograms found!")
                    print("===> Skipping station...")
                    continue

                # First process HF files to convert velocity to acceleration

                # Create path names and check if their sizes are
                # within bounds
                nsfile = os.path.join(a_tmpdir,
                                      "%d.%s-hf.000" % (sim_id, site))
                ewfile = os.path.join(a_tmpdir,
                                      "%d.%s-hf.090" % (sim_id, site))
                udfile = os.path.join(a_tmpdir,
                                      "%d.%s-hf.ver" % (sim_id, site))
                bbpfile = os.path.join(a_tmpdir,
                                       "%d.%s-hf.bbp" % (sim_id, site))

                bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                               bband_utils.GP_MAX_FILENAME)

                # Run wcc2bbp
                cmd = ("%s " %
                       (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                       "nsfile=%s ewfile=%s udfile=%s " %
                       (nsfile, ewfile, udfile) + "wcc2bbp=0 < %s >> %s 2>&1" %
                       (bbpfile, self.log))
                bband_utils.runprog(cmd, abort_on_error=True, print_cmd=False)

                for comp in config.COMPS:
                    # Create path names and check if their sizes
                    # are within bounds
                    filein = os.path.join(a_tmpdir,
                                          "%d.%s-hf.%s" % (sim_id, site, comp))
                    fileout = os.path.join(
                        a_tmpdir, "%d.%s-hf.acc.%s" % (sim_id, site, comp))

                    bband_utils.check_path_lengths([filein, fileout],
                                                   bband_utils.GP_MAX_FILENAME)

                    cmd = ("%s diff=1 " %
                           (os.path.join(install.A_GP_BIN_DIR, "integ_diff")) +
                           "filein=%s fileout=%s" % (filein, fileout))
                    bband_utils.runprog(cmd,
                                        abort_on_error=True,
                                        print_cmd=False)

                # Create path names and check if their sizes are within bounds
                nsfile = os.path.join(a_tmpdir,
                                      "%d.%s-hf.acc.000" % (sim_id, site))
                ewfile = os.path.join(a_tmpdir,
                                      "%d.%s-hf.acc.090" % (sim_id, site))
                udfile = os.path.join(a_tmpdir,
                                      "%d.%s-hf.acc.ver" % (sim_id, site))
                bbpfile = os.path.join(a_tmpdir,
                                       "%d.%s-hf.acc.bbp" % (sim_id, site))

                bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                               bband_utils.GP_MAX_FILENAME)

                cmd = ("%s " %
                       (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                       "nsfile=%s ewfile=%s udfile=%s " %
                       (nsfile, ewfile, udfile) +
                       "units=cm/s/s wcc2bbp=1 > %s 2>> %s" %
                       (bbpfile, self.log))
                bband_utils.runprog(cmd, abort_on_error=True, print_cmd=False)

                # Then process LF files to convert velocity to acceleration

                # Create path names and check if their sizes are within bounds
                nsfile = os.path.join(a_tmpdir,
                                      "%d.%s-lf.000" % (sim_id, site))
                ewfile = os.path.join(a_tmpdir,
                                      "%d.%s-lf.090" % (sim_id, site))
                udfile = os.path.join(a_tmpdir,
                                      "%d.%s-lf.ver" % (sim_id, site))
                bbpfile = os.path.join(a_tmpdir,
                                       "%d.%s-lf.bbp" % (sim_id, site))

                bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                               bband_utils.GP_MAX_FILENAME)

                cmd = ("%s " %
                       (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                       "nsfile=%s ewfile=%s udfile=%s " %
                       (nsfile, ewfile, udfile) + "wcc2bbp=0 < %s >> %s 2>&1" %
                       (bbpfile, self.log))
                bband_utils.runprog(cmd, abort_on_error=True, print_cmd=False)

                for comp in config.COMPS:
                    # Create path names and check if their sizes
                    # are within bounds
                    filein = os.path.join(a_tmpdir,
                                          "%d.%s-lf.%s" % (sim_id, site, comp))
                    fileout = os.path.join(
                        a_tmpdir, "%d.%s-lf.acc.%s" % (sim_id, site, comp))

                    bband_utils.check_path_lengths([filein, fileout],
                                                   bband_utils.GP_MAX_FILENAME)

                    cmd = ("%s " %
                           (os.path.join(install.A_GP_BIN_DIR, "integ_diff")) +
                           "diff=1 filein=%s fileout=%s" % (filein, fileout))
                    bband_utils.runprog(cmd,
                                        abort_on_error=True,
                                        print_cmd=False)

                # Create path names and check if their sizes are within bounds
                nsfile = os.path.join(a_tmpdir,
                                      "%d.%s-lf.acc.000" % (sim_id, site))
                ewfile = os.path.join(a_tmpdir,
                                      "%d.%s-lf.acc.090" % (sim_id, site))
                udfile = os.path.join(a_tmpdir,
                                      "%d.%s-lf.acc.ver" % (sim_id, site))
                bbpfile = os.path.join(a_tmpdir,
                                       "%d.%s-lf.acc.bbp" % (sim_id, site))

                bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                               bband_utils.GP_MAX_FILENAME)

                cmd = ("%s " %
                       (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                       "nsfile=%s ewfile=%s udfile=%s " %
                       (nsfile, ewfile, udfile) +
                       "units=cm/s/s wcc2bbp=1 > %s 2>> %s" %
                       (bbpfile, self.log))
                bband_utils.runprog(cmd, abort_on_error=True, print_cmd=False)

            # We should have acceleration files at this point
            hf_exists = False
            lf_exists = False

            if os.path.exists(
                    os.path.join(a_tmpdir,
                                 "%d.%s-hf.acc.bbp" % (sim_id, site))):
                hf_exists = True
            if os.path.exists(
                    os.path.join(a_tmpdir,
                                 "%d.%s-lf.acc.bbp" % (sim_id, site))):
                lf_exists = True

            print("==> Processing acceleration seismograms for station: %s" %
                  (site))

            # If no files exist for this station, make a note and continue
            if not hf_exists and not lf_exists:
                print("===> No acceleration seismograms found!")
                print("===> Skipping station...")
                continue

            #
            # Convert HF file to wcc components
            #

            # Create path names and check if their sizes are within bounds
            nsfile = os.path.join(a_tmpdir,
                                  "%d.%s-hf.acc.000" % (sim_id, site))
            ewfile = os.path.join(a_tmpdir,
                                  "%d.%s-hf.acc.090" % (sim_id, site))
            udfile = os.path.join(a_tmpdir,
                                  "%d.%s-hf.acc.ver" % (sim_id, site))
            bbpfile = os.path.join(a_tmpdir,
                                   "%d.%s-hf.acc.bbp" % (sim_id, site))

            bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                           bband_utils.GP_MAX_FILENAME)

            progstring = ("%s " %
                          (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                          "nsfile=%s ewfile=%s udfile=%s " %
                          (nsfile, ewfile, udfile) +
                          "wcc2bbp=0 < %s >> %s 2>&1" % (bbpfile, self.log))
            bband_utils.runprog(progstring,
                                abort_on_error=True,
                                print_cmd=False)

            #
            # Convert LF file to wcc components
            #

            # Create path names and check if their sizes are within bounds
            nsfile = os.path.join(a_tmpdir,
                                  "%d.%s-lf.acc.000" % (sim_id, site))
            ewfile = os.path.join(a_tmpdir,
                                  "%d.%s-lf.acc.090" % (sim_id, site))
            udfile = os.path.join(a_tmpdir,
                                  "%d.%s-lf.acc.ver" % (sim_id, site))
            bbpfile = os.path.join(a_tmpdir,
                                   "%d.%s-lf.acc.bbp" % (sim_id, site))

            bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                           bband_utils.GP_MAX_FILENAME)

            progstring = ("%s " %
                          (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                          "nsfile=%s ewfile=%s udfile=%s " %
                          (nsfile, ewfile, udfile) +
                          "wcc2bbp=0 < %s >> %s 2>&1" % (bbpfile, self.log))
            bband_utils.runprog(progstring,
                                abort_on_error=True,
                                print_cmd=False)

            #
            # Process each component
            #
            for entries in config.COMPS:
                compo = entries

                #
                # HF First
                #
                listfile = os.path.join(
                    a_tmpdir,
                    "%s.%s.hf.%s" % (config.FILTLIST, sta_base, compo))
                bband_utils.check_path_lengths([listfile],
                                               bband_utils.GP_MAX_FILENAME)

                # Create wcc_tfilter input file
                out = open(listfile, 'w')
                # Contains HF input file
                infile = os.path.join(
                    a_tmpdir, "%d.%s-hf.acc.%s" % (sim_id, site, compo))
                out.write("%s\n" % infile)
                out.flush()
                out.close()

                # Also check infile
                bband_utils.check_path_lengths([infile],
                                               bband_utils.GP_MAX_FILENAME)

                #
                # Pre-filter and resample HF file
                #
                shutil.copy2(infile, "%s.prefilter" % infile)
                progstring = (
                    "%s " %
                    (os.path.join(install.A_GP_BIN_DIR, "wcc_tfilter")) +
                    "filelist=%s order=%d fhi=%f flo=%s " %
                    (listfile, config.HF_ORD, self.hf_fhi, config.HF_FLO) +
                    "inbin=0 outbin=0 phase=%d " % (self.phase) +
                    "outpath=%s >> %s 2>&1" % (a_tmpdir, self.log))
                bband_utils.runprog(progstring,
                                    abort_on_error=True,
                                    print_cmd=False)

                outfile = os.path.join(
                    a_tmpdir, "%d.%s-hf-resamp.%s" % (sim_id, site, compo))
                bband_utils.check_path_lengths([outfile],
                                               bband_utils.GP_MAX_FILENAME)

                progstring = ("%s newdt=%f " % (os.path.join(
                    install.A_GP_BIN_DIR, "wcc_resamp_arbdt"), new_dt) +
                              "pow2=%d infile=%s outfile=%s >> %s 2>&1" %
                              (pow2_param, infile, outfile, self.log))
                bband_utils.runprog(progstring,
                                    abort_on_error=True,
                                    print_cmd=False)

                #
                # LF Next
                #
                listfile = os.path.join(
                    a_tmpdir,
                    "%s.%s.lf.%s" % (config.FILTLIST, sta_base, compo))
                bband_utils.check_path_lengths([listfile],
                                               bband_utils.GP_MAX_FILENAME)

                # Create wcc_tfilter input file
                out = open(listfile, 'w')
                # Contains LF input file
                infile = os.path.join(
                    a_tmpdir, "%d.%s-lf.acc.%s" % (sim_id, site, compo))
                out.write("%s\n" % infile)
                out.flush()
                out.close()

                # Also check infile
                bband_utils.check_path_lengths([infile],
                                               bband_utils.GP_MAX_FILENAME)

                #
                # Pre-filter and resample LF file
                #
                shutil.copy2(infile, "%s.prefilter" % infile)
                progstring = (
                    "%s " %
                    (os.path.join(install.A_GP_BIN_DIR, "wcc_tfilter")) +
                    "filelist=%s order=%d fhi=%f flo=%s " %
                    (listfile, config.LF_ORD, config.LF_FHI, self.lf_flo) +
                    "inbin=0 outbin=0 phase=%d " % (self.phase) +
                    "outpath=%s >> %s 2>&1 " % (a_tmpdir, self.log))
                bband_utils.runprog(progstring, print_cmd=False)

                outfile = os.path.join(
                    a_tmpdir, "%d.%s-lf-resamp.%s" % (sim_id, site, compo))
                bband_utils.check_path_lengths([outfile],
                                               bband_utils.GP_MAX_FILENAME)

                progstring = (
                    "%s " %
                    (os.path.join(install.A_GP_BIN_DIR, "wcc_resamp_arbdt")) +
                    "newdt=%f pow2=%d " % (new_dt, pow2_param) +
                    "infile=%s outfile=%s >> %s 2>&1" %
                    (infile, outfile, self.log))
                bband_utils.runprog(progstring,
                                    abort_on_error=True,
                                    print_cmd=False)

                #
                # Add LF and HF resampled acc seismograms
                #

                # Check all path lengths
                infile1 = os.path.join(
                    a_tmpdir, "%d.%s-lf-resamp.%s" % (sim_id, site, compo))
                infile2 = os.path.join(
                    a_tmpdir, "%d.%s-hf-resamp.%s" % (sim_id, site, compo))
                outfile = os.path.join(
                    a_tmpdir, "%d.%s.acc.add.%s" % (sim_id, site, compo))
                bband_utils.check_path_lengths([infile1, infile2, outfile],
                                               bband_utils.GP_MAX_FILENAME)

                progstring = ("%s " %
                              (os.path.join(install.A_GP_BIN_DIR, "wcc_add")) +
                              "f1=1.00 t1=%f inbin1=0 infile1=%s " %
                              (config.LF_TSTART, infile1) +
                              "f2=1.00 t2=%f inbin2=0 infile2=%s " %
                              (config.HF_TSTART, infile2) +
                              "outbin=0 outfile=%s >> %s 2>&1" %
                              (outfile, self.log))
                bband_utils.runprog(progstring,
                                    abort_on_error=True,
                                    print_cmd=False)

                #
                # Create combined velocity files
                #

                # Check path lengths
                filein = os.path.join(
                    a_tmpdir, "%d.%s.acc.add.%s" % (sim_id, site, compo))
                fileout = os.path.join(a_tmpdir,
                                       "%d.%s.%s" % (sim_id, site, compo))
                bband_utils.check_path_lengths([filein, fileout],
                                               bband_utils.GP_MAX_FILENAME)

                cmd = ("%s integ=1 filein=%s fileout=%s" % (os.path.join(
                    install.A_GP_BIN_DIR, "integ_diff"), filein, fileout))
                bband_utils.runprog(cmd, abort_on_error=True, print_cmd=False)

            # We have all the component files, create velocity seismogram

            # Create path names and check if their sizes are within bounds
            nsfile = os.path.join(a_tmpdir, "%d.%s.000" % (sim_id, site))
            ewfile = os.path.join(a_tmpdir, "%d.%s.090" % (sim_id, site))
            udfile = os.path.join(a_tmpdir, "%d.%s.ver" % (sim_id, site))
            bbpfile = os.path.join(a_tmpdir, "%d.%s.bbp" % (sim_id, site))

            bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                           bband_utils.GP_MAX_FILENAME)

            progstring = ("%s wcc2bbp=1 " %
                          (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                          'title="Sim NGAH, stat=%s" ' % site +
                          'nsfile=%s ewfile=%s udfile=%s > %s 2>> %s' %
                          (nsfile, ewfile, udfile, bbpfile, self.log))
            bband_utils.runprog(progstring,
                                abort_on_error=True,
                                print_cmd=False)

            # Copy velocity bbp file to outdir
            shutil.copy2(
                os.path.join(a_tmpdir, "%d.%s.bbp" % (sim_id, site)),
                os.path.join(a_outdir, "%d.%s.vel.bbp" % (sim_id, site)))

            # Also create acceleration bbp file in outdir

            # Create path names and check if their sizes are within bounds
            nsfile = os.path.join(a_tmpdir, "%d.%s.000" % (sim_id, site))
            ewfile = os.path.join(a_tmpdir, "%d.%s.090" % (sim_id, site))
            udfile = os.path.join(a_tmpdir, "%d.%s.ver" % (sim_id, site))
            bbpfile = os.path.join(a_tmpdir, "%d.%s.bbp" % (sim_id, site))

            bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                           bband_utils.GP_MAX_FILENAME)

            cmd = ("%s " % (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                   "nsfile=%s ewfile=%s udfile=%s " %
                   (nsfile, ewfile, udfile) + "wcc2bbp=0 < %s >> %s 2>&1" %
                   (bbpfile, self.log))
            bband_utils.runprog(cmd, abort_on_error=True, print_cmd=False)

            for comp in config.COMPS:
                # Create path names and check if their sizes are within bounds
                filein = os.path.join(a_tmpdir,
                                      "%d.%s.%s" % (sim_id, site, comp))
                fileout = os.path.join(a_tmpdir,
                                       "%d.%s.acc.%s" % (sim_id, site, comp))

                bband_utils.check_path_lengths([filein, fileout],
                                               bband_utils.GP_MAX_FILENAME)

                cmd = ("%s diff=1 filein=%s fileout=%s" % (os.path.join(
                    install.A_GP_BIN_DIR, "integ_diff"), filein, fileout))
                bband_utils.runprog(cmd, abort_on_error=True, print_cmd=False)

            # Create path names and check if their sizes are within bounds
            nsfile = os.path.join(a_tmpdir, "%d.%s.acc.000" % (sim_id, site))
            ewfile = os.path.join(a_tmpdir, "%d.%s.acc.090" % (sim_id, site))
            udfile = os.path.join(a_tmpdir, "%d.%s.acc.ver" % (sim_id, site))
            bbpfile = os.path.join(a_tmpdir, "%d.%s.acc.bbp" % (sim_id, site))

            bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                           bband_utils.GP_MAX_FILENAME)

            cmd = ("%s " % (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                   "nsfile=%s ewfile=%s udfile=%s " %
                   (nsfile, ewfile, udfile) +
                   "units=cm/s/s wcc2bbp=1 > %s 2>> %s" % (bbpfile, self.log))
            bband_utils.runprog(cmd, abort_on_error=True, print_cmd=False)

            # Copy acceleration bbp file to outdir
            shutil.copy2(
                os.path.join(a_tmpdir, "%d.%s.acc.bbp" % (sim_id, site)),
                os.path.join(a_outdir, "%d.%s.acc.bbp" % (sim_id, site)))

        print("Match Completed".center(80, '-'))
示例#13
0
文件: genslip.py 项目: SCECcode/BBP
    def run(self):
        """
        Runs Genslip
        """
        print("GP Rupture Generator GenSlip".center(80, '-'))

        # Load configuration, set sim_id
        install = InstallCfg.getInstance()
        sim_id = self.sim_id

        # Build directory paths
        a_tmpdir = os.path.join(install.A_TMP_DATA_DIR, str(sim_id))
        a_indir = os.path.join(install.A_IN_DATA_DIR, str(sim_id))
        a_outdir = os.path.join(install.A_OUT_DATA_DIR, str(sim_id))
        a_logdir = os.path.join(install.A_OUT_LOG_DIR, str(sim_id))

        # Make sure the output and tmp directories exist
        bband_utils.mkdirs([a_tmpdir, a_indir, a_outdir], print_cmd=False)

        # Now, file paths
        self.log = os.path.join(a_logdir, "%d.genslip.log" % (sim_id))
        a_srcfile = os.path.join(a_indir, self.r_srcfile)
        a_velfile = os.path.join(a_indir, self.r_velmodel)

        # Read src file
        cfg = GenslipCfg(a_srcfile)

        # Define location of input velocity model file
        a_velmodel = os.path.join(a_tmpdir, self.r_velmodel)

        # 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))
        # Check for velocity model-specific parameters
        vmodel_params = vel_obj.get_codebase_params('gp')
        # Look for RISETIME_COEF
        if 'RISETIME_COEF' in vmodel_params:
            self.risetime_coef = float(vmodel_params['RISETIME_COEF'])
        else:
            self.risetime_coef = cfg.RISETIME_COEF
        # Look for SHAL_VRUP
        if 'SHAL_VRUP' in vmodel_params:
            self.shal_vrup = float(vmodel_params['SHAL_VRUP'])
        else:
            self.shal_vrup = cfg.SHAL_VRUP
        # Look for MEAN_RVFAC
        if 'MEAN_RVFAC' in vmodel_params:
            self.mean_rvfac = float(vmodel_params['MEAN_RVFAC'])
        else:
            self.mean_rvfac = cfg.MEAN_RVFAC
        # Look for RANGE_RVFAC
        if 'RANGE_RVFAC' in vmodel_params:
            self.range_rvfac = float(vmodel_params['RANGE_RVFAC'])
        else:
            self.range_rvfac = cfg.RANGE_RVFAC
        # Look for RISETIME_FAC
        if 'RISETIME_FAC' in vmodel_params:
            self.risetime_fac = float(vmodel_params['RISETIME_FAC'])
        else:
            self.risetime_fac = cfg.RISETIME_FAC
        # Look for DEEP_RISETIME_FAC
        if 'DEEP_RISETIME_FAC' in vmodel_params:
            self.deep_risetime_fac = float(vmodel_params['DEEP_RISETIME_FAC'])
        else:
            self.deep_risetime_fac = cfg.DEEP_RISETIME_FAC
        # Look for SLIP SIGMA
        if 'SLIP_SIGMA' in vmodel_params:
            self.slip_sigma = float(vmodel_params['SLIP_SIGMA'])
        else:
            self.slip_sigma = cfg.SLIP_SIGMA

        # Look for DT
        if 'GF_DT' in vmodel_params:
            gf_dt = float(vmodel_params['GF_DT'])
        else:
            raise bband_utils.ParameterError("Cannot find GF_DT parameter in"
                                             "velocity model %s!" %
                                             (self.vmodel_name))

        # Calculate nstk,ndip
        nstk = round(cfg.CFGDICT["fault_length"] / cfg.CFGDICT["dlen"])
        ndip = round(cfg.CFGDICT["fault_width"] / cfg.CFGDICT["dwid"])

        # Calculate rvfac
        if "common_seed" in cfg.CFGDICT:
            rvfac = calculate_rvfac(self.mean_rvfac, self.range_rvfac,
                                    cfg.CFGDICT["common_seed"])
        else:
            rvfac = calculate_rvfac(self.mean_rvfac, self.range_rvfac,
                                    cfg.CFGDICT["seed"])

        # moment = math.pow(10, 1.5 * (cfg.MAG + 10.7))

        # For multi-segment SRC files
        if "rupture_delay" in cfg.CFGDICT:
            rupture_delay = cfg.CFGDICT["rupture_delay"]
        else:
            rupture_delay = 0.0

        if "moment_fraction" in cfg.CFGDICT:
            moment_fraction = cfg.CFGDICT["moment_fraction"]
        else:
            moment_fraction = -1.0

        if "max_fault_length" in cfg.CFGDICT:
            flen_max = cfg.CFGDICT["max_fault_length"]
        else:
            flen_max = -1.0

        r_gsftmp = "m%.2f-%.2fx%.2f.gsf" % (cfg.CFGDICT["magnitude"],
                                            cfg.CFGDICT["dlen"],
                                            cfg.CFGDICT["dwid"])
        a_gsftmp = os.path.join(a_tmpdir, r_gsftmp)

        r_outroot = "m%.2f-%.2fx%.2f_s%d-v5.2.2" % (cfg.CFGDICT["magnitude"],
                                                    cfg.CFGDICT["dlen"],
                                                    cfg.CFGDICT["dwid"],
                                                    cfg.CFGDICT["seed"])
        a_srffile = os.path.join(a_indir, "%s.srf" % (r_outroot))

        progstring = ("%s/fault_seg2gsf read_slip_vals=0 << EOF > %s 2>> %s\n" %
                      (install.A_GP_BIN_DIR, a_gsftmp, self.log) +
                      "1\n" +
                      "%f %f %f %f %f %f %f %f %d %d\n" %
                      (cfg.CFGDICT["lon_top_center"],
                       cfg.CFGDICT["lat_top_center"],
                       cfg.CFGDICT["depth_to_top"],
                       cfg.CFGDICT["strike"], cfg.CFGDICT["dip"],
                       cfg.CFGDICT["rake"], cfg.CFGDICT["fault_length"],
                       cfg.CFGDICT["fault_width"], nstk, ndip) + "EOF")
        bband_utils.runprog(progstring)

        progstring = ("%s/genslip-v5.2.2 read_erf=0 write_srf=1 " %
                      (install.A_GP_BIN_DIR) +
                      "read_gsf=1 write_gsf=0 infile=%s " % (a_gsftmp) +
                      "mag=%.2f nstk=%d ndip=%d " %
                      (cfg.CFGDICT["magnitude"], nstk, ndip) +
                      "ns=1 nh=1 " +
                      "kmodel=2 seed=%d slip_sigma=%f " %
                      (cfg.CFGDICT["seed"], self.slip_sigma) +
                      "circular_average=0 modified_corners=0 " +
                      "velfile=%s shypo=%f dhypo=%f rvfrac=%f " %
                      (a_velfile, cfg.CFGDICT["hypo_along_stk"],
                       cfg.CFGDICT["hypo_down_dip"], rvfac) +
                      "shal_vrup_dep=%f shal_vrup_deprange=%f shal_vrup=%f " %
                      (cfg.RTDEP, cfg.RTDEP_RANGE, self.shal_vrup) +
                      "side_taper=0.02 bot_taper=0.0 top_taper=0.0 " +
                      "dt=%f risetime_coef=%f plane_header=1 " %
                      (gf_dt, self.risetime_coef) +
                      "risetimefac=%f risetimedep=%f risetimedep_range=%f " %
                      (self.risetime_fac, cfg.RTDEP, cfg.RTDEP_RANGE) +
                      "rt_scalefac=%f slip_water_level=%f " %
                      (cfg.RT_SCALEFAC, cfg.SLIP_WATER_LEVEL) +
                      "deep_risetimedep=%f deep_risetimedep_range=%f " %
                      (cfg.DEEP_RISETIMEDEP, cfg.DEEP_RISETIMEDEP_RANGE) +
                      "deep_risetimefac=%f " %
                      (self.deep_risetime_fac) +
                      "flen_max=%f rupture_delay=%f moment_fraction=%f " %
                      (flen_max, rupture_delay, moment_fraction) +
                      "srf_version=2.0 rake_sigma=15.0 fdrup_time=1 " +
                      "deep_vrup=0.6 use_gaus=1 alpha_rough=0.01 " +
                      "lambda_min=0.08 tsfac_coef=1.1 tsfac1_sigma=1.0 " +
                      "tsfac1_scor=0.8 rtime1_sigma=0.85 rtime1_scor=0.8 " +
                      "> %s 2>> %s" % (a_srffile, self.log))
        bband_utils.runprog(progstring)

        #
        # mv result to outputfile
        #
        progstring = "cp %s %s" % (a_srffile, os.path.join(a_tmpdir, self.r_srffile))
        bband_utils.runprog(progstring)
        progstring = "cp %s %s" % (a_srffile, os.path.join(a_indir, self.r_srffile))
        bband_utils.runprog(progstring)
        progstring = "cp %s %s" % (a_srffile, os.path.join(a_outdir, self.r_srffile))
        bband_utils.runprog(progstring)

        # Plot SRF
        plot_srf.run(self.r_srffile, sim_id=self.sim_id)

        print("GP GenSlip Completed".center(80, '-'))
示例#14
0
文件: genhtml.py 项目: xiaolongma/bbp
    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, '-'))
示例#15
0
    def __init__(self, vmodel_name, a_srcname=None):

        # Get pointers to all directories
        install = InstallCfg.getInstance()

        # Parse SRC File
        if a_srcname:
            self.CFGDICT = bband_utils.parse_src_file(a_srcname)

        #
        # Name and Path to executables
        self.R_SLL2XY = "statLL2XY"
        self.A_SLL2XY = os.path.join(install.A_UCSB_BIN_DIR,
                                     self.R_SLL2XY)

        self.R_SRF2XY = "srfLL2XYKM"
        self.A_SRF2XY = os.path.join(install.A_UCSB_BIN_DIR,
                                     self.R_SRF2XY)

        self.R_SYN1D = "syn_1d"
        self.A_SYN1D = os.path.join(install.A_UCSB_BIN_DIR,
                                    self.R_SYN1D)

        self.R_CONV = "conv3CompBB"
        self.A_CONV = os.path.join(install.A_UCSB_BIN_DIR,
                                   self.R_CONV)

        self.R_STITCH = "stitch"
        self.A_STITCH = os.path.join(install.A_UCSB_BIN_DIR,
                                     self.R_STITCH)

        #
        # Define name used when input station file is converted into a
        # UC lat/lon version of the station file
        #
        self.R_UC_STATION_FILE = "uc_stations.ll"
        self.R_UC_VS30_FILE = "stations.vs30"
        self.R_UC_SOURCE_MODEL = "source_model.list"
        self.R_FFSP_FILE = "FFSP_OUTPUT.001"
        self.MAX_STATIONS = 300

        vmodel_obj = velocity_models.get_velocity_model_by_name(vmodel_name)
        if vmodel_obj is None:
            raise IndexError("Cannot find velocity model: %s" %
                             (vmodel_name))

        vmodel_params = vmodel_obj.get_codebase_params('ucsb')
        # Configure needed parameters from velocity model
        if 'LF_VELMODEL' in vmodel_params:
            self.A_UC_LF_VELMODEL = os.path.join(vmodel_obj.base_dir,
                                                 vmodel_params['LF_VELMODEL'])
        else:
            raise KeyError("%s parameter missing in velocity model %s" %
                           ("LF_VELMODEL", vmodel_name))
        if 'HF_VELMODEL' in vmodel_params:
            self.A_UC_HF_VELMODEL = os.path.join(vmodel_obj.base_dir,
                                                 vmodel_params['HF_VELMODEL'])
        else:
            raise KeyError("%s parameter missing in velocity model %s" %
                           ("HF_VELMODEL", vmodel_name))
        if 'GREENBANK' in vmodel_params:
            self.A_UC_GREENBANK = os.path.join(vmodel_obj.base_dir,
                                               vmodel_params['GREENBANK'])
        else:
            raise KeyError("%s parameter missing in velocity model %s" %
                           ("GREENBANK", vmodel_name))
        if 'GREEN_SOIL' in vmodel_params:
            self.A_UC_GREEN_SOIL = os.path.join(vmodel_obj.base_dir,
                                                vmodel_params['GREEN_SOIL'])
        else:
            raise KeyError("%s parameter missing in velocity model %s" %
                           ("GREEN_SOIL", vmodel_name))
        if 'HF_GREENBANK' in vmodel_params:
            self.A_UC_HF_GREENBANK = os.path.join(vmodel_obj.base_dir,
                                                  vmodel_params['HF_GREENBANK'])
        else:
            raise KeyError("%s parameter missing in velocity model %s" %
                           ("HF_GREENBANK", vmodel_name))
        if 'HF_GREEN_SOIL' in vmodel_params:
            self.A_UC_HF_GREEN_SOIL = os.path.join(vmodel_obj.base_dir,
                                                   vmodel_params['HF_GREEN_SOIL'])
        else:
            raise KeyError("%s parameter missing in velocity model %s" %
                           ("HF_GREEN_SOIL", vmodel_name))
        if 'SYN1D_INP_FILE' in vmodel_params:
            self.A_UC_SYN1D_INP_FILE = os.path.join(vmodel_obj.base_dir,
                                                    vmodel_params['SYN1D_INP_FILE'])
        else:
            raise KeyError("%s parameter missing in velocity model %s" %
                           ("SYN1D_INP_FILE", vmodel_name))
示例#16
0
文件: match.py 项目: SCECcode/BBP
    def run(self):
        """
        Runs the match module to merge low and high frequency seismograms
        """
        print("Match".center(80, '-'))

        install = InstallCfg.getInstance()
        config = MatchCfg()

        sim_id = self.sim_id
        sta_base = os.path.basename(os.path.splitext(self.r_stations)[0])
        self.log = os.path.join(install.A_OUT_LOG_DIR,
                                str(sim_id),
                                "%d.match_%s.log" % (sim_id, sta_base))

        a_statfile = os.path.join(install.A_IN_DATA_DIR,
                                  str(sim_id),
                                  self.r_stations)

        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))

        # Make sure tmpdir exists
        dirs = [a_tmpdir]
        bband_utils.mkdirs(dirs, print_cmd=False)

        pow2_param = 0
        if self.pow2:
            pow2_param = 1

        # Start with defaults
        self.phase = config.PHASE
        self.hf_fhi = config.HF_FHI
        self.lf_flo = config.LF_FLO

        # Set match method
        if config.MATCH_METHOD == 1:
            self.phase = 1
        elif config.MATCH_METHOD == 2:
            val = 1.0 / (2.0 * config.HF_ORD)
            self.hf_fhi = (self.hf_fhi *
                           math.exp(val * math.log(math.sqrt(2.0) - 1.0)))
            val = -1.0 / (2.0 * config.LF_ORD)
            self.lf_flo = (self.lf_flo *
                           math.exp(val * math.log(math.sqrt(2.0) - 1.0)))

        #
        # Read and parse the station list with this call
        #
        slo = StationList(a_statfile)
        site_list = slo.getStationList()

        # 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))

        # Check for velocity model-specific parameters
        vmodel_params = vel_obj.get_codebase_params('gp')

        # Figure out what DT we should use when resampling

        # Figure out the LF DT value
        if self.acc:
            seis_ext = '.acc.bbp'
        else:
            seis_ext = '.bbp'
        lf_seis = None

        # Find one LF seismogram
        for sites in site_list:
            site = sites.scode
            if os.path.exists(os.path.join(a_tmpdir,
                                           "%d.%s-lf%s" %
                                           (sim_id, site,
                                            seis_ext))):
                lf_seis = os.path.join(a_tmpdir,
                                       "%d.%s-lf%s" %
                                       (sim_id, site,
                                        seis_ext))
                break

        # Need one file
        if lf_seis is None:
            raise bband_utils.ParameterError("Cannot find a LF seismogram")

        # Pick DT from this file
        lf_dt = None
        lf_file = open(lf_seis)
        for line in lf_file:
            line = line.strip()
            if line.startswith("#") or line.startswith("%"):
                continue
            # Got to first timestamp. Now, pick two consecutive
            # timestamps values
            lf_t1 = float(line.strip().split()[0])
            lf_t2 = float(lf_file.next().strip().split()[0])
            # Subtract the two times
            lf_dt = lf_t2 - lf_t1
            # All done!
            break
        lf_file.close()

        if lf_dt is None:
            raise bband_utils.ParameterError("Cannot find LF_DT!")

        # lf_dt *should* match the gf_dt used by jbsim
        #if not 'GF_DT' in vmodel_params:
        #    raise bband_utils.ParameterError("Cannot find GF_DT parameter in "
        #                                     "velocity model: %s" %
        #                                     (self.vmodel_name))
        # In the GP method, we can potentially have two independent DT
        # values, one used by the rupture generator and the
        # low-frequency jbsim seismogram simulator, and another value
        # used by the high-frequency hfsims program. We have to use
        # the smaller of these two values in order to properly combine
        # the low-, and high-frequency seismograms.
        #gf_dt = float(vmodel_params['GF_DT'])
        if 'HF_DT' in vmodel_params:
            hf_dt = float(vmodel_params['HF_DT'])
        else:
            hf_dt = config.NEW_HFDT

        new_dt = min(lf_dt, hf_dt)

        # Go through the stations
        for sites in site_list:
            # Pick station name
            site = sites.scode
            #
            # We have a verbose of silent invocation. This is a very
            # verbose program so our default writes to dev/null
            #

            #
            # There are multiple possibilities; either we have
            # separate HF and LF files, we have HF and .bbp, LF and
            # .bbp, or just .bbp.  In all cases, we need to separate
            # them to get components.
            #
            hf_exists = False
            lf_exists = False

            if not self.acc:
                print("==> Processing velocity seismograms for station: %s" %
                      (site))
                # Need to convert to acc first
                if os.path.exists(os.path.join(a_tmpdir,
                                               "%d.%s-hf.bbp" %
                                               (sim_id, site))):
                    hf_exists = True
                if os.path.exists(os.path.join(a_tmpdir,
                                               "%d.%s-lf.bbp" %
                                               (sim_id, site))):
                    lf_exists = True

                # If no files exist for this station, make a note and continue
                if not hf_exists and not lf_exists:
                    print("===> No velocity seismograms found!")
                    print("===> Skipping station...")
                    continue

                # First process HF files to convert velocity to acceleration

                # Create path names and check if their sizes are
                # within bounds
                nsfile = os.path.join(a_tmpdir,
                                      "%d.%s-hf.000" % (sim_id, site))
                ewfile = os.path.join(a_tmpdir,
                                      "%d.%s-hf.090" % (sim_id, site))
                udfile = os.path.join(a_tmpdir,
                                      "%d.%s-hf.ver" % (sim_id, site))
                bbpfile = os.path.join(a_tmpdir,
                                       "%d.%s-hf.bbp" % (sim_id, site))

                bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                               bband_utils.GP_MAX_FILENAME)

                # Run wcc2bbp
                cmd = ("%s " %
                       (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                       "nsfile=%s ewfile=%s udfile=%s " %
                       (nsfile, ewfile, udfile) +
                       "wcc2bbp=0 < %s >> %s 2>&1" %
                       (bbpfile, self.log))
                bband_utils.runprog(cmd, abort_on_error=True, print_cmd=False)

                for comp in config.COMPS:
                    # Create path names and check if their sizes
                    # are within bounds
                    filein = os.path.join(a_tmpdir,
                                          "%d.%s-hf.%s" %
                                          (sim_id, site, comp))
                    fileout = os.path.join(a_tmpdir,
                                           "%d.%s-hf.acc.%s" %
                                           (sim_id, site, comp))

                    bband_utils.check_path_lengths([filein, fileout],
                                                   bband_utils.GP_MAX_FILENAME)

                    cmd = ("%s diff=1 " %
                           (os.path.join(install.A_GP_BIN_DIR,
                                         "integ_diff")) +
                           "filein=%s fileout=%s" % (filein, fileout))
                    bband_utils.runprog(cmd, abort_on_error=True,
                                        print_cmd=False)

                # Create path names and check if their sizes are within bounds
                nsfile = os.path.join(a_tmpdir,
                                      "%d.%s-hf.acc.000" % (sim_id, site))
                ewfile = os.path.join(a_tmpdir,
                                      "%d.%s-hf.acc.090" % (sim_id, site))
                udfile = os.path.join(a_tmpdir,
                                      "%d.%s-hf.acc.ver" % (sim_id, site))
                bbpfile = os.path.join(a_tmpdir,
                                       "%d.%s-hf.acc.bbp" % (sim_id, site))

                bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                               bband_utils.GP_MAX_FILENAME)

                cmd = ("%s " %
                       (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                       "nsfile=%s ewfile=%s udfile=%s " %
                       (nsfile, ewfile, udfile) +
                       "units=cm/s/s wcc2bbp=1 > %s 2>> %s" %
                       (bbpfile, self.log))
                bband_utils.runprog(cmd, abort_on_error=True, print_cmd=False)

                # Then process LF files to convert velocity to acceleration

                # Create path names and check if their sizes are within bounds
                nsfile = os.path.join(a_tmpdir,
                                      "%d.%s-lf.000" % (sim_id, site))
                ewfile = os.path.join(a_tmpdir,
                                      "%d.%s-lf.090" % (sim_id, site))
                udfile = os.path.join(a_tmpdir,
                                      "%d.%s-lf.ver" % (sim_id, site))
                bbpfile = os.path.join(a_tmpdir,
                                       "%d.%s-lf.bbp" % (sim_id, site))

                bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                               bband_utils.GP_MAX_FILENAME)

                cmd = ("%s " %
                       (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                       "nsfile=%s ewfile=%s udfile=%s " %
                       (nsfile, ewfile, udfile) +
                       "wcc2bbp=0 < %s >> %s 2>&1" %
                       (bbpfile, self.log))
                bband_utils.runprog(cmd, abort_on_error=True, print_cmd=False)

                for comp in config.COMPS:
                    # Create path names and check if their sizes
                    # are within bounds
                    filein = os.path.join(a_tmpdir,
                                          "%d.%s-lf.%s" %
                                          (sim_id, site, comp))
                    fileout = os.path.join(a_tmpdir,
                                           "%d.%s-lf.acc.%s" %
                                           (sim_id, site, comp))

                    bband_utils.check_path_lengths([filein, fileout],
                                                   bband_utils.GP_MAX_FILENAME)

                    cmd = ("%s " %
                           (os.path.join(install.A_GP_BIN_DIR,
                                         "integ_diff")) +
                           "diff=1 filein=%s fileout=%s" %
                           (filein, fileout))
                    bband_utils.runprog(cmd, abort_on_error=True,
                                        print_cmd=False)

                # Create path names and check if their sizes are within bounds
                nsfile = os.path.join(a_tmpdir,
                                      "%d.%s-lf.acc.000" % (sim_id, site))
                ewfile = os.path.join(a_tmpdir,
                                      "%d.%s-lf.acc.090" % (sim_id, site))
                udfile = os.path.join(a_tmpdir,
                                      "%d.%s-lf.acc.ver" % (sim_id, site))
                bbpfile = os.path.join(a_tmpdir,
                                       "%d.%s-lf.acc.bbp" % (sim_id, site))

                bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                               bband_utils.GP_MAX_FILENAME)

                cmd = ("%s " %
                       (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                       "nsfile=%s ewfile=%s udfile=%s " %
                       (nsfile, ewfile, udfile) +
                       "units=cm/s/s wcc2bbp=1 > %s 2>> %s" %
                       (bbpfile, self.log))
                bband_utils.runprog(cmd, abort_on_error=True, print_cmd=False)

            # We should have acceleration files at this point
            hf_exists = False
            lf_exists = False

            if os.path.exists(os.path.join(a_tmpdir,
                                           "%d.%s-hf.acc.bbp" %
                                           (sim_id, site))):
                hf_exists = True
            if os.path.exists(os.path.join(a_tmpdir,
                                           "%d.%s-lf.acc.bbp" %
                                           (sim_id, site))):
                lf_exists = True

            print("==> Processing acceleration seismograms for station: %s" %
                  (site))

            # If no files exist for this station, make a note and continue
            if not hf_exists and not lf_exists:
                print("===> No acceleration seismograms found!")
                print("===> Skipping station...")
                continue

            #
            # Convert HF file to wcc components
            #

            # Create path names and check if their sizes are within bounds
            nsfile = os.path.join(a_tmpdir,
                                  "%d.%s-hf.acc.000" % (sim_id, site))
            ewfile = os.path.join(a_tmpdir,
                                  "%d.%s-hf.acc.090" % (sim_id, site))
            udfile = os.path.join(a_tmpdir,
                                  "%d.%s-hf.acc.ver" % (sim_id, site))
            bbpfile = os.path.join(a_tmpdir,
                                   "%d.%s-hf.acc.bbp" % (sim_id, site))

            bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                           bband_utils.GP_MAX_FILENAME)

            progstring = ("%s " %
                          (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                          "nsfile=%s ewfile=%s udfile=%s " %
                          (nsfile, ewfile, udfile) +
                          "wcc2bbp=0 < %s >> %s 2>&1" %
                          (bbpfile, self.log))
            bband_utils.runprog(progstring, abort_on_error=True,
                                print_cmd=False)

            #
            # Convert LF file to wcc components
            #

            # Create path names and check if their sizes are within bounds
            nsfile = os.path.join(a_tmpdir,
                                  "%d.%s-lf.acc.000" % (sim_id, site))
            ewfile = os.path.join(a_tmpdir,
                                  "%d.%s-lf.acc.090" % (sim_id, site))
            udfile = os.path.join(a_tmpdir,
                                  "%d.%s-lf.acc.ver" % (sim_id, site))
            bbpfile = os.path.join(a_tmpdir,
                                   "%d.%s-lf.acc.bbp" % (sim_id, site))

            bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                           bband_utils.GP_MAX_FILENAME)

            progstring = ("%s " %
                          (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                          "nsfile=%s ewfile=%s udfile=%s " %
                          (nsfile, ewfile, udfile) +
                          "wcc2bbp=0 < %s >> %s 2>&1" %
                          (bbpfile, self.log))
            bband_utils.runprog(progstring, abort_on_error=True,
                                print_cmd=False)

            #
            # Process each component
            #
            for entries in config.COMPS:
                compo = entries

                #
                # HF First
                #
                listfile = os.path.join(a_tmpdir, "%s.%s.hf.%s" %
                                        (config.FILTLIST, sta_base, compo))
                bband_utils.check_path_lengths([listfile],
                                               bband_utils.GP_MAX_FILENAME)

                # Create wcc_tfilter input file
                out = open(listfile, 'w')
                # Contains HF input file
                infile = os.path.join(a_tmpdir,
                                      "%d.%s-hf.acc.%s" %
                                      (sim_id, site, compo))
                out.write("%s\n" % infile)
                out.flush()
                out.close()

                # Also check infile
                bband_utils.check_path_lengths([infile],
                                               bband_utils.GP_MAX_FILENAME)

                #
                # Pre-filter and resample HF file
                #
                shutil.copy2(infile, "%s.prefilter" % infile)
                progstring = ("%s " %
                              (os.path.join(install.A_GP_BIN_DIR,
                                            "wcc_tfilter")) +
                              "filelist=%s order=%d fhi=%f flo=%s " %
                              (listfile, config.HF_ORD, self.hf_fhi,
                               config.HF_FLO) +
                              "inbin=0 outbin=0 phase=%d " %
                              (self.phase) +
                              "outpath=%s >> %s 2>&1" %
                              (a_tmpdir, self.log))
                bband_utils.runprog(progstring, abort_on_error=True,
                                    print_cmd=False)

                outfile = os.path.join(a_tmpdir, "%d.%s-hf-resamp.%s" %
                                       (sim_id, site, compo))
                bband_utils.check_path_lengths([outfile],
                                               bband_utils.GP_MAX_FILENAME)

                progstring = ("%s newdt=%f " %
                              (os.path.join(install.A_GP_BIN_DIR,
                                            "wcc_resamp_arbdt"), new_dt) +
                              "pow2=%d infile=%s outfile=%s >> %s 2>&1" %
                              (pow2_param, infile, outfile, self.log))
                bband_utils.runprog(progstring, abort_on_error=True,
                                    print_cmd=False)

                #
                # LF Next
                #
                listfile = os.path.join(a_tmpdir, "%s.%s.lf.%s" %
                                        (config.FILTLIST, sta_base, compo))
                bband_utils.check_path_lengths([listfile],
                                               bband_utils.GP_MAX_FILENAME)

                # Create wcc_tfilter input file
                out = open(listfile, 'w')
                # Contains LF input file
                infile = os.path.join(a_tmpdir,
                                      "%d.%s-lf.acc.%s" %
                                      (sim_id, site, compo))
                out.write("%s\n" % infile)
                out.flush()
                out.close()

                # Also check infile
                bband_utils.check_path_lengths([infile],
                                               bband_utils.GP_MAX_FILENAME)

                #
                # Pre-filter and resample LF file
                #
                shutil.copy2(infile, "%s.prefilter" % infile)
                if not self.using_3d:
                    progstring = ("%s " %
                                  (os.path.join(install.A_GP_BIN_DIR,
                                                "wcc_tfilter")) +
                                  "filelist=%s order=%d fhi=%f flo=%s " %
                                  (listfile, config.LF_ORD, config.LF_FHI,
                                   self.lf_flo) +
                                  "inbin=0 outbin=0 phase=%d " %
                                  (self.phase) +
                                  "outpath=%s >> %s 2>&1 " %
                                  (a_tmpdir, self.log))
                    bband_utils.runprog(progstring, print_cmd=False)

                outfile = os.path.join(a_tmpdir, "%d.%s-lf-resamp.%s" %
                                       (sim_id, site, compo))
                bband_utils.check_path_lengths([outfile],
                                               bband_utils.GP_MAX_FILENAME)

                progstring = ("%s " %
                              (os.path.join(install.A_GP_BIN_DIR,
                                            "wcc_resamp_arbdt")) +
                              "newdt=%f pow2=%d " %
                              (new_dt, pow2_param) +
                              "infile=%s outfile=%s >> %s 2>&1" %
                              (infile, outfile, self.log))
                bband_utils.runprog(progstring, abort_on_error=True,
                                    print_cmd=False)

                #
                # Add LF and HF resampled acc seismograms
                #

                # Check all path lengths
                infile1 = os.path.join(a_tmpdir, "%d.%s-lf-resamp.%s" %
                                       (sim_id, site, compo))
                infile2 = os.path.join(a_tmpdir, "%d.%s-hf-resamp.%s" %
                                       (sim_id, site, compo))
                outfile = os.path.join(a_tmpdir, "%d.%s.acc.add.%s" %
                                       (sim_id, site, compo))
                bband_utils.check_path_lengths([infile1, infile2, outfile],
                                               bband_utils.GP_MAX_FILENAME)

                progstring = ("%s " %
                              (os.path.join(install.A_GP_BIN_DIR, "wcc_add")) +
                              "f1=1.00 t1=%f inbin1=0 infile1=%s " %
                              (config.LF_TSTART, infile1) +
                              "f2=1.00 t2=%f inbin2=0 infile2=%s " %
                              (config.HF_TSTART, infile2) +
                              "outbin=0 outfile=%s >> %s 2>&1" %
                              (outfile, self.log))
                bband_utils.runprog(progstring, abort_on_error=True,
                                    print_cmd=False)

                #
                # Create combined velocity files
                #

                # Check path lengths
                filein = os.path.join(a_tmpdir,
                                      "%d.%s.acc.add.%s" %
                                      (sim_id, site, compo))
                fileout = os.path.join(a_tmpdir,
                                       "%d.%s.%s" %
                                       (sim_id, site, compo))
                bband_utils.check_path_lengths([filein, fileout],
                                               bband_utils.GP_MAX_FILENAME)

                cmd = ("%s integ=1 filein=%s fileout=%s" %
                       (os.path.join(install.A_GP_BIN_DIR,
                                     "integ_diff"), filein, fileout))
                bband_utils.runprog(cmd, abort_on_error=True, print_cmd=False)

            # We have all the component files, create velocity seismogram

            # Create path names and check if their sizes are within bounds
            nsfile = os.path.join(a_tmpdir,
                                  "%d.%s.000" % (sim_id, site))
            ewfile = os.path.join(a_tmpdir,
                                  "%d.%s.090" % (sim_id, site))
            udfile = os.path.join(a_tmpdir,
                                  "%d.%s.ver" % (sim_id, site))
            bbpfile = os.path.join(a_tmpdir,
                                   "%d.%s.bbp" % (sim_id, site))

            bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                           bband_utils.GP_MAX_FILENAME)

            progstring = ("%s wcc2bbp=1 " %
                          (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                          'title="Sim NGAH, stat=%s" ' % site +
                          'nsfile=%s ewfile=%s udfile=%s > %s 2>> %s' %
                          (nsfile, ewfile, udfile, bbpfile, self.log))
            bband_utils.runprog(progstring, abort_on_error=True,
                                print_cmd=False)

            # Copy velocity bbp file to outdir
            shutil.copy2(os.path.join(a_tmpdir, "%d.%s.bbp" %
                                      (sim_id, site)),
                         os.path.join(a_outdir, "%d.%s.vel.bbp" %
                                      (sim_id, site)))

            # Also create acceleration bbp file in outdir

            # Create path names and check if their sizes are within bounds
            nsfile = os.path.join(a_tmpdir,
                                  "%d.%s.000" % (sim_id, site))
            ewfile = os.path.join(a_tmpdir,
                                  "%d.%s.090" % (sim_id, site))
            udfile = os.path.join(a_tmpdir,
                                  "%d.%s.ver" % (sim_id, site))
            bbpfile = os.path.join(a_tmpdir,
                                   "%d.%s.bbp" % (sim_id, site))

            bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                           bband_utils.GP_MAX_FILENAME)

            cmd = ("%s " % (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                   "nsfile=%s ewfile=%s udfile=%s " %
                   (nsfile, ewfile, udfile) +
                   "wcc2bbp=0 < %s >> %s 2>&1" %
                   (bbpfile, self.log))
            bband_utils.runprog(cmd, abort_on_error=True, print_cmd=False)

            for comp in config.COMPS:
                # Create path names and check if their sizes are within bounds
                filein = os.path.join(a_tmpdir,
                                      "%d.%s.%s" %
                                      (sim_id, site, comp))
                fileout = os.path.join(a_tmpdir,
                                       "%d.%s.acc.%s" %
                                       (sim_id, site, comp))

                bband_utils.check_path_lengths([filein, fileout],
                                               bband_utils.GP_MAX_FILENAME)

                cmd = ("%s diff=1 filein=%s fileout=%s" %
                       (os.path.join(install.A_GP_BIN_DIR,
                                     "integ_diff"), filein, fileout))
                bband_utils.runprog(cmd, abort_on_error=True, print_cmd=False)

            # Create path names and check if their sizes are within bounds
            nsfile = os.path.join(a_tmpdir,
                                  "%d.%s.acc.000" % (sim_id, site))
            ewfile = os.path.join(a_tmpdir,
                                  "%d.%s.acc.090" % (sim_id, site))
            udfile = os.path.join(a_tmpdir,
                                  "%d.%s.acc.ver" % (sim_id, site))
            bbpfile = os.path.join(a_tmpdir,
                                   "%d.%s.acc.bbp" % (sim_id, site))

            bband_utils.check_path_lengths([nsfile, ewfile, udfile],
                                           bband_utils.GP_MAX_FILENAME)

            cmd = ("%s " % (os.path.join(install.A_GP_BIN_DIR, "wcc2bbp")) +
                   "nsfile=%s ewfile=%s udfile=%s " %
                   (nsfile, ewfile, udfile) +
                   "units=cm/s/s wcc2bbp=1 > %s 2>> %s" %
                   (bbpfile, self.log))
            bband_utils.runprog(cmd, abort_on_error=True, print_cmd=False)

            # Copy acceleration bbp file to outdir
            shutil.copy2(os.path.join(a_tmpdir, "%d.%s.acc.bbp" %
                                      (sim_id, site)),
                         os.path.join(a_outdir, "%d.%s.acc.bbp" %
                                      (sim_id, site)))

        print("Match Completed".center(80, '-'))
示例#17
0
文件: bbtoolbox.py 项目: SCECcode/BBP
    def create_bbtoolbox_files(self, stat_file):
        """
        This function creates the files needed by bbtoolbox, including
        the scattering file (if not provided), the station file, and
        the parameter file
        """
        sta_base = os.path.basename(os.path.splitext(self.r_stations)[0])
        a_indir = os.path.join(self.install.A_IN_DATA_DIR, str(self.sim_id))
        a_tmpdir = os.path.join(self.install.A_TMP_DATA_DIR, str(self.sim_id))
        a_tmpdir_mod = os.path.join(self.install.A_TMP_DATA_DIR,
                                    str(self.sim_id),
                                    "bbtoolbox_%s" % (sta_base))
        a_outdir = os.path.join(self.install.A_OUT_DATA_DIR, str(self.sim_id))
        a_param_outdir = os.path.join(a_outdir, "param_files")

        stat_list = StationList(stat_file)

        # 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))
        vmodel_params = vel_obj.get_codebase_params('sdsu')

        # Look for the source function parameter
        if 'SOURCE_FUNC' in vmodel_params:
            self.source_func = vmodel_params['SOURCE_FUNC']

        # Take care of scattering file
        if not self.r_scattering:
            # Need to create our file
            scattering_template = os.path.join(self.install.A_SDSU_DATA_DIR,
                                               "scattering_generic.dat")
            self.r_scattering = "scattering.dat"
            a_scattering = os.path.join(a_indir, self.r_scattering)

            # Look for KAPPA
            if 'KAPPA' in vmodel_params:
                self.kappa = float(vmodel_params['KAPPA'])
            # Look for FMAX
            if 'FMAX' in vmodel_params:
                self.fmax = float(vmodel_params['FMAX'])
            if 'Q' in vmodel_params:
                self.q_coda = float(vmodel_params['Q'])
            if 'FDEC' in vmodel_params:
                self.fdec = float(vmodel_params['FDEC'])
            if 'GS_FLAG' in vmodel_params:
                self.gs_flag = float(vmodel_params['GS_FLAG'])
            if 'NGAW_FLAG' in vmodel_params:
                self.ngaw_flag = float(vmodel_params['NGAW_FLAG'])
            if 'TR_SCA' in vmodel_params:
                self.tr_sca = float(vmodel_params['TR_SCA'])
            if 'AFAC' in vmodel_params:
                self.afac = float(vmodel_params['AFAC'])
            if 'BFAC' in vmodel_params:
                self.bfac = float(vmodel_params['BFAC'])
            if 'STR_FAC' in vmodel_params:
                self.str_fac = float(vmodel_params['STR_FAC'])

            # Check if we need to calculate stress
            if 'CALCULATE_STRESS' in vmodel_params:
                if float(vmodel_params['CALCULATE_STRESS']) == True:
                    # Calculate stress based on depth of hypocenter
                    self.str_fac = self.config.calculate_stress()

            # Open template and output files
            scat_in = open(scattering_template, 'r')
            scat_out = open(a_scattering, 'w')

            for line in scat_in:
                if line.find(r"\* iseed - seed number for scattering") >= 0:
                    # This is the iseed line, insert the random iseed here
                    pos = line.find(r"\* iseed - seed number for scattering")
                    scat_out.write("%d   %s" %
                                   (self.iseed,
                                    line[pos:]))
                elif line.find(r"\* kappa - kappa at the site") >= 0:
                    # This is the kappa line, insert self.kappa here
                    pos = line.find(r"\* kappa - kappa at the site")
                    scat_out.write("%.3f   %s" %
                                   (self.kappa,
                                    line[pos:]))
                elif line.find(r"\* fmax - ") >= 0:
                    # This is the fmax line, insert self.fmax here
                    pos = line.find(r"\* fmax - ")
                    scat_out.write("%.2f   %s" %
                                   (self.fmax,
                                    line[pos:]))
                elif line.find(r"\* Q - Q for the coda") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* Q - Q for the coda")
                    scat_out.write("%.1f   %s" %
                                   (self.q_coda,
                                    line[pos:]))
                elif line.find(r"\* fdec - see equation") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* fdec - see equation")
                    scat_out.write("%.2f    %s" %
                                   (self.fdec,
                                    line[pos:]))
                elif line.find(r"\* gs_flag - determine type") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* gs_flag - determine type")
                    scat_out.write("%d    %s" %
                                   (int(self.gs_flag),
                                    line[pos:]))
                elif line.find(r"\* ngaw_flag - GMPEs") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* ngaw_flag - GMPEs")
                    scat_out.write("%d    %s" %
                                   (int(self.ngaw_flag),
                                    line[pos:]))
                elif line.find(r"\* Tr_sca - scaling factor") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* Tr_sca - scaling factor")
                    scat_out.write("%.4f  %s" %
                                   (self.tr_sca,
                                    line[pos:]))
                elif line.find(r"\* afac - qk factor") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* afac - qk factor")
                    scat_out.write("%.1f    %s" %
                                   (self.afac,
                                    line[pos:]))
                elif line.find(r"\* bfac - qk factor") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* bfac - qk factor")
                    scat_out.write("%.1f    %s" %
                                   (self.bfac,
                                    line[pos:]))
                elif line.find(r"\* str_fac - Brune stress") >= 0:
                    # This is the line, insert here
                    pos = line.find(r"\* str_fac - Brune stress")
                    scat_out.write("%.2e %s" %
                                   (self.str_fac,
                                    line[pos:]))
                else:
                    scat_out.write(line)

            # Done
            scat_in.close()
            scat_out.flush()
            scat_out.close()

        # Keep copy of scattering file in outdata
        shutil.copy2(a_scattering, os.path.join(a_param_outdir,
                                                self.r_scattering))

        # Convert station file
        a_tmpfile = "station_%s.coords" % (sta_base)
        a_sdsu_stat_list = os.path.join(a_tmpdir_mod,
                                        "bbtstations_%s.tmp" % (sta_base))
        a_sdsu_extended_fault = os.path.join(a_indir, "extended_fault")
        param_filename = stas2files.bbp2sdsu_statlist(a_indir, stat_list,
                                                      a_sdsu_stat_list,
                                                      self.r_srffile,
                                                      self.r_xyz_srffile,
                                                      a_sdsu_extended_fault,
                                                      a_tmpfile)
        r_faultfile = os.path.basename(a_sdsu_extended_fault)
        # param_filename = stas2files.bbp2sdsu_statlist(a_indir, stat_list,
        #                                               a_sdsu_stat_list, hypo)
        # now a_sdsu_stat_list has X Y name vs rho kappa
        # a_sdsu_stat_list.par has bbextension, bbstat, bbhypo

        # Build real station list
        self.r_stations = "bbtstations_%s.dat" % (sta_base)
        stalist_fp = open(os.path.join(a_indir, self.r_stations), 'w')
        # write headers
        stalist_fp.write("/* STATIONS FILE FOR BROAD-BAND COMPUTATION CODE " +
                         "(P.M. MAI & K.B.OLSEN) */\n")
        stalist_fp.write("/* STATIONS COORDINATES ARE IN THE X-Y SYSTEM " +
                         "REPORTED IN FIG.1 OF APPENDIX A */\n\n")
        stalist_fp.write("/* INPUT DIRECTORY */\n")
        # Create input directory and file prefix for the stations files
        file_prefix = os.path.join(a_tmpdir_mod, "%d." % (self.sim_id))
        stalist_fp.write("%s\n\n" % (file_prefix))
        stalist_fp.write("/* FILES FORMAT [RGF BIN CMP 3SF] */\n")
        stalist_fp.write("\t3SF\n\n")
        stalist_fp.write("/* FILES EXTENSION OR BINARY FILE NAME */\n")
        glob_stat = "%s/*-lf.bbp" % (a_tmpdir)
        bbp_list = glob.glob(glob_stat)
        # Now, figure out the file suffix
        if len(bbp_list) > 0:
            file_suffix = "-lf.bbp"
        else:
            file_suffix = ".bbp"

        # Write suffix
        stalist_fp.write("%s\n\n" % (file_suffix))

        # Write header for station list
        stalist_fp.write("/*\tX\tY\tNAME\tVs\tRho\tKappa */\n")

        # Now, append the station list we have in a_sdsu_stat_list
        conv_list_fp = open(a_sdsu_stat_list, 'r')
        for line in conv_list_fp:
            stalist_fp.write(line)
            # Figure out if station file path is too long
            pieces = line.split()
            st_name = pieces[2]
            total_length = len(file_prefix) + len(st_name) + len(file_suffix)
            if total_length >= bband_utils.SDSU_MAX_FILENAME:
                # Close files
                stalist_fp.close()
                conv_list_fp.close()
                raise ValueError("station path for %s " % (st_name) +
                                 " is %d characters long, maximum is %d" %
                                 (total_length, bband_utils.SDSU_MAX_FILENAME))
        # Flush all data, and close this file
        stalist_fp.flush()
        stalist_fp.close()
        # Close station file
        conv_list_fp.close()

        # Keep copy of station file in outdata
        shutil.copy2(os.path.join(a_indir, self.r_stations),
                     os.path.join(a_param_outdir, self.r_stations))

        # Read param file
        conv_par_fp = open(param_filename, 'r')
        conv_par_data = conv_par_fp.readlines()
        conv_par_fp.close()

        # 2nd line is hypo coordinates
        hypo_line = conv_par_data[1].split(':')[1]
        hypo_coords = []
        for i in range(0, 3):
            hypo_coords.append(hypo_line.split()[i])
        min_box_dims = []
        min_box_line = conv_par_data[0].split(':')[1]
        for i in range(0, 2):
            min_box_dims.append(float(min_box_line.split()[i]))

        # FS: Feb-2013: Get magnitude directly from SRC file
        # FS: Mar-2013: We use this magnitude only when we don't have
        # a SRC file
        # get magnitude from 3rd line
        magnitude = float(conv_par_data[2].split(':')[1])

        self.r_bbparfile = "%d_%s.bbpar" % (self.sim_id, sta_base)
        parfile_name = os.path.join(a_indir, self.r_bbparfile)
        parfile_fp = open(parfile_name, 'w')
        parfile_fp.write("/* MODALITY FLAG: [0] LF-HF MERGING, " +
                         "[1] LF-SCATTERING, [2] LF-ISOCHRONE */\n")
        parfile_fp.write(" %d\n" % (self.config.MODALITY))
        parfile_fp.write("/* OUTPUT DIRECTORY */\n")
        parfile_fp.write('"%s"\n' % a_tmpdir_mod)
        parfile_fp.write('/* VELOCITY MODEL FILE (3D MODEL OR 1D MODEL) */\n')
        parfile_fp.write('"%s"\n' %
                         (os.path.join(a_indir, self.r_velmodel)))
        parfile_fp.write("/* STATIONS FILE REPORTING [X-Y] COORDINATES, " +
                         "FILENAMES AND PARAMETERS */\n")
        parfile_fp.write('"%s"\n' %
                         (os.path.join(a_indir, self.r_stations)))
        parfile_fp.write("/* OPTIONAL 2ND STATIONS FILE REPORTING ONLY " +
                         "FILENAMES - ONLY FOR MODALITY = 0  */\n")
        parfile_fp.write("2ndstations.dat\n")
        parfile_fp.write("/* FAULT MODEL TYPE: [POINT], " +
                         "[EXTENDED FAULT-MODEL FILE] */\n")
        parfile_fp.write(' extended "%s"\n' %
                         (os.path.join(a_indir, r_faultfile)))
        # parfile_fp.write(' point\n')
        parfile_fp.write("/* HYPOCENTER COORDINATES [X-Y-Z] IN KM */\n")
        parfile_fp.write("%.2f %.2f %.2f\n" % (float(hypo_coords[0]),
                                               float(hypo_coords[1]),
                                               float(hypo_coords[2])))
        parfile_fp.write('/* GRID DEFINITION [X-Y-Z] FOR RAYTRACING: ' +
                         '"NEAR-SIDE", GRID-SPACING (IN KM) */\n')
        parfile_fp.write("0.0 0.0 0.0 1.0\n")
        parfile_fp.write('/* GRID DEFINITION [X-Y-Z] FOR RAYTRACING: ' +
                         '"FAR-SIDE" (IN KM) */\n')
        if self.config.grid_x is not None and self.config.grid_y is not None:
            parfile_fp.write("%.1f %.1f %.1f\n" %
                             (self.config.grid_x,
                              self.config.grid_y,
                              self.config.grid_z))
        else:
            parfile_fp.write("%.1f %.1f %.1f\n" %
                             (round(min_box_dims[0] + 20.0, 0),
                              round(min_box_dims[1] + 20.0, 0),
                              self.config.grid_z))
        parfile_fp.write("/* SCATTERING PARAMETERS FILE */\n")
        parfile_fp.write('"%s"\n' %
                         (os.path.join(a_indir, self.r_scattering)))
        parfile_fp.write("/* EVENT MAGNITUDE */\n")
        if self.config.MAG is None:
            parfile_fp.write("%.2f\n" % (magnitude))
        else:
            parfile_fp.write("%.2f\n" % (self.config.MAG))
        parfile_fp.write("/* DOMINANT SOURCE MECHANISM [SS RS NS AL] */\n")
        parfile_fp.write("%s\n" % conv_par_data[3].split(":")[1].strip())
        parfile_fp.write("/* SOURCE TIME FUNCTION "
                         "[TRI BOX YOF DREG LIU USER-DEF] */\n")
        parfile_fp.write("%s\n" % (self.source_func))
        parfile_fp.write("/* VERBOSE MODE [ON OFF] */\n")
        parfile_fp.write("off\n")
        parfile_fp.write("/* SRF FILE */\n")
        parfile_fp.write('"%s"\n' %
                         (os.path.join(a_indir, self.r_xyz_srffile)))
        parfile_fp.flush()
        parfile_fp.close()

        # Keep a copy in the outdata directory
        shutil.copy2(parfile_name, os.path.join(a_param_outdir,
                                                self.r_bbparfile))