Ejemplo n.º 1
0
def load_paramfile(paramfile):
    """initiate one of the parameterizer and prior pdf according to the param file"""
    A = AsciiFile(paramfile)

    # ------------------------
    if A.metadata['TYPE'] == "mZVSVPRH":
        p = Parameterizer_mZVSVPRH(A)
    elif A.metadata['TYPE'] == "mZVSPRRH":
        p = Parameterizer_mZVSPRRH(A)
    elif A.metadata['TYPE'] == "mZVSPRzRHvp":
        p = Parameterizer_mZVSPRzRHvp(A)
    elif A.metadata['TYPE'] == "mZVSPRzRHz":
        p = Parameterizer_mZVSPRzRHz(A)
    elif A.metadata['TYPE'] == "mZVSVPvsRHvp":
        p = Parameterizer_mZVSVPvsRHvp(A)
    else:
        raise Exception('could not load %s (TYPE not recognized)' % paramfile)

    # ------------------------
    if not "PRIORTYPE" in A.metadata.keys():
        logRHOM = DefaultLogRhoM(p)

    elif A.metadata['PRIORTYPE'] == "DVS":
        logRHOM = LogRhoM_DVS(p,
                              dvsmin=A.metadata['DVSMIN'],
                              dvsmax=A.metadata['DVSMAX'])

    elif A.metadata['PRIORTYPE'] == "DVPDVSDRH":
        logRHOM = LogRhoM_DVPDVSDRH(p,
                                    dvpmin=A.metadata['DVPMIN'],
                                    dvpmax=A.metadata['DVPMAX'],
                                    dvsmin=A.metadata['DVSMIN'],
                                    dvsmax=A.metadata['DVSMAX'],
                                    drhmin=A.metadata['DRHMIN'],
                                    drhmax=A.metadata['DRHMAX'])

    elif A.metadata['PRIORTYPE'] == "DVPDVSDRHDPR":
        logRHOM = LogRhoM_DVPDVSDRHDPR(p,
                                       dvpmin=A.metadata['DVPMIN'],
                                       dvpmax=A.metadata['DVPMAX'],
                                       dvsmin=A.metadata['DVSMIN'],
                                       dvsmax=A.metadata['DVSMAX'],
                                       drhmin=A.metadata['DRHMIN'],
                                       drhmax=A.metadata['DRHMAX'],
                                       dprmin=A.metadata['DPRMIN'],
                                       dprmax=A.metadata['DPRMAX'])
    else:
        raise Exception('could not load %s (PRIORTYPE not recognized)' %
                        paramfile)

    # ------------------------
    print "parameter type : ", p.__class__.__name__
    print "prior type     : ", logRHOM.__class__.__name__
    return p, logRHOM
Ejemplo n.º 2
0
def _display_function(rootname, argv, verbose, mapkwargs):
    """private"""
    targetfile = "%s/_HerrMet.target" % rootname
    paramfile = "%s/_HerrMet.param" % rootname
    runfile = '%s/_HerrMet.run' % rootname
    pngfile = '%s/_HerrMet.png' % rootname
    #HerrLininitfile = '%s/_HerrLin.init' % rootname

    # ------ Initiate the displayer using the target data if exists
    if "-compact" in argv.keys():  # compact mode
        which_displayer = DepthDispDisplayCompact
    else:
        which_displayer = DepthDispDisplay

    if os.path.exists(targetfile):
        rd = which_displayer(targetfile=targetfile)
        d = makedatacoder(
            targetfile, which=Datacoder_log)  # datacoder based on observations
        dobs, _ = d.target()
    else:
        print "no target file found in %s" % rootname
        rd = which_displayer()

    # ------ Display run results if exist
    if os.path.exists(runfile) and ("-plot" in argv.keys()
                                    or "-pdf" in argv.keys()):

        with RunFile(runfile, verbose=verbose) as rundb:
            s = rundb.select('select MODELID from MODELS limit 1')
            if s is not None:
                # --- display best models
                if "-plot" in argv.keys():

                    assert argv["-plot"] == [] or len(
                        argv["-plot"]) == 4  # unexpected argument number
                    if argv["-plot"] == []:
                        plot_mode, plot_limit, plot_llkmin, plot_step = \
                            default_plot_mode, default_plot_limit, \
                            default_plot_llkmin, default_plot_step
                    elif len(argv['-plot']) == 4:
                        plot_mode, plot_limit, plot_llkmin, plot_step = argv[
                            '-plot']
                    else:
                        raise Exception()

                    print "plot : %s, limit %d, llkmin %f, step %d" % (
                        plot_mode, plot_limit, plot_llkmin, plot_step),
                    if plot_mode == "best":
                        chainids, weights, llks, ms, ds = \
                            rundb.getzip(limit=plot_limit,
                                         llkmin=plot_llkmin,
                                         step=plot_step,
                                         algo="METROPOLIS")
                    elif plot_mode == "last":
                        chainids, weights, llks, ms, ds = \
                            rundb.getlastszip(limit=plot_limit,
                                              llkmin=plot_llkmin,
                                              step=plot_step,
                                              algo="METROPOLIS")
                    else:
                        raise Exception('unexpected plot mode %s' % plot_mode)

                    vmin, vmax = llks.min(), llks.max()
                    # colors = values2colors(llks, vmin=vmin, vmax=vmax, cmap=argv['-cmap'])

                    if "-overdisp" in argv.keys():
                        """note : recomputing dispersion with another frequency array might
                                  result in a completely different dispersion curve in case
                                  of root search failure """
                        waves, types, modes, freqs, _ = ds[0]
                        overwaves, overtypes, overmodes, _, _ = zip(*list(
                            groupbywtm(waves, types, modes, freqs,
                                       np.arange(len(freqs)), None, True)))
                        overfreqs = [
                            freqspace(0.6 * min(freqs), 1.4 * max(freqs), 100,
                                      "plog") for _ in xrange(len(overwaves))
                        ]
                        overwaves, overtypes, overmodes, overfreqs = \
                            igroupbywtm(overwaves, overtypes, overmodes, overfreqs)
                        for llk, (mms, dds) in zip(
                                llks[::-1],
                                overdisp(ms[::-1],
                                         overwaves,
                                         overtypes,
                                         overmodes,
                                         overfreqs,
                                         verbose=verbose,
                                         **mapkwargs)):
                            # rd.plotmodel(color=clr, alpha=1.0, linewidth=3, *mms)
                            rd.addmodel(colorvalue=llk, *mms)
                            try:
                                # rd.plotdisp(color=clr, alpha=1.0, linewidth=3, *dds)
                                rd.adddisp(colorvalue=llk, *dds)
                            except KeyboardInterrupt:
                                raise
                            except Exception as e:
                                print "Error : could not plot dispersion curve (%s)" % str(
                                    e)

                        # cb = makecolorbar(vmin=vmin, vmax=vmax, cmap=argv['-cmap'])
                        # pos = rd.axdisp[-1].get_position()
                        # cax = rd.fig.add_axes((pos.x0, 0.12, pos.width, 0.01))
                        # rd.fig.colorbar(cb, cax=cax, label="log likelyhood", orientation="horizontal")

                    else:
                        "display the dispersion curves as stored in the database"
                        for i in range(len(llks))[::-1]:
                            # rd.plotmodel(color=colors[i], alpha=1.0, linewidth=3, *ms[i])
                            # rd.plotdisp(color=colors[i], alpha=1.0, linewidth=3, *ds[i])
                            rd.addmodel(colorvalue=llks[i], *ms[i])
                            rd.adddisp(colorvalue=llks[i], *ds[i])
                        # cb = makecolorbar(vmin=vmin, vmax=vmax, cmap=argv['-cmap'])
                        # pos = rd.axdisp[-1].get_position()
                        # cax = rd.fig.add_axes((pos.x0, 0.12, pos.width, 0.01))
                        # rd.fig.colorbar(cb, cax=cax, label="log likelyhood", orientation="horizontal")
                        # cax.set_xticklabels(cax.get_xticklabels(), rotation=90., horizontalalignment="center")

                    rd.showdispcoll(vmin=vmin,
                                    vmax=vmax,
                                    cmap=argv['-cmap'],
                                    alpha=1.0,
                                    linewidth=3)
                    rd.showdepthcoll(vmin=vmin,
                                     vmax=vmax,
                                     cmap=argv['-cmap'],
                                     alpha=1.0,
                                     linewidth=3)
                    rd.colorbar(vmin=vmin,
                                vmax=vmax,
                                cmap=argv['-cmap'],
                                label="log likelyhood",
                                orientation="horizontal")
                    print rd.cax.get_position()
                    rd.cax.set_xticklabels(rd.cax.get_xticklabels(),
                                           rotation=90.,
                                           horizontalalignment="center")

                # ---- display posterior pdf
                if "-pdf" in argv.keys():

                    assert argv["-pdf"] == [] or len(
                        argv["-pdf"]) == 4  # unexpected argument number
                    if argv["-pdf"] == []:
                        pdf_mode, pdf_limit, pdf_llkmin, pdf_step = \
                            default_pdf_mode, default_pdf_limit, default_pdf_llkmin, default_pdf_step
                    elif len(argv['-pdf']) == 4:
                        pdf_mode, pdf_limit, pdf_llkmin, pdf_step = argv[
                            '-pdf']
                    else:
                        raise Exception()

                    print "pdf : %s, limit %d, llkmin %f, step %d" % (
                        pdf_mode, pdf_limit, pdf_llkmin, pdf_step),
                    if pdf_mode == "best":
                        chainids, weights, llks, ms, ds = \
                            rundb.getzip(limit=pdf_limit,
                                         llkmin=pdf_llkmin,
                                         step=pdf_step,
                                         algo="METROPOLIS")
                    elif pdf_mode == "last":
                        chainids, weights, llks, ms, ds = \
                            rundb.getlastszip(limit=pdf_limit,
                                              llkmin=pdf_llkmin,
                                              step=pdf_step,
                                              algo="METROPOLIS")
                    else:
                        raise Exception('unexpected pdf mode %s' % pdf_mode)

                    dms = [
                        depthmodel_from_arrays(ztop, vp, vs, rh)
                        for ztop, vp, vs, rh in ms
                    ]

                    # display percentiles of model and data pdfs
                    clr = "b" if "-plot" not in argv.keys() else "k"
                    alp = 1.0 if "-plot" not in argv.keys() else 0.5

                    for p, (vppc, vspc, rhpc, prpc) in \
                            dmstats1(dms,
                                     percentiles=[0.01, 0.16, 0.5, 0.84, 0.99],
                                     Ndepth=100,
                                     Nvalue=100,
                                     weights=weights,
                                     **mapkwargs):
                        try:
                            l = 3 if p == 0.5 else 1
                            for what, where in zip([vppc, vspc, rhpc, prpc], [
                                    rd.axdepth['VP'], rd.axdepth['VS'],
                                    rd.axdepth['RH'], rd.axdepth['PR']
                            ]):
                                if where is not None:
                                    what.show(where,
                                              color=clr,
                                              linewidth=l,
                                              alpha=alp)

                        except KeyboardInterrupt:
                            raise
                        except Exception as e:
                            print "Error", str(e)

                    # display the disp pdf
                    for p, (wpc, tpc, mpc, fpc, vpc) in \
                            dispstats(ds,
                                      percentiles=[0.01, 0.16, 0.5, 0.84, 0.99],
                                      Ndisp=100,
                                      weights=weights,
                                      **mapkwargs):
                        try:
                            l = 3 if p == 0.5 else 1
                            rd.plotdisp(wpc,
                                        tpc,
                                        mpc,
                                        fpc,
                                        vpc,
                                        dvalues=None,
                                        color=clr,
                                        alpha=alp,
                                        linewidth=l)

                        except KeyboardInterrupt:
                            raise
                        except Exception as e:
                            print "Error", str(e)

    # ------
    if os.path.exists(paramfile):
        p, _ = load_paramfile(paramfile)
        showvp, showvs, showrh, showpr = True, True, True, True
        if isinstance(p, Parameterizer_mZVSVPRH):
            showpr = False
        elif isinstance(p, Parameterizer_mZVSPRRH):
            showvp = False
        elif isinstance(p, Parameterizer_mZVSPRzRHvp):
            showvp = showpr = showrh = False
        elif isinstance(p, Parameterizer_mZVSPRzRHz):
            showvp = showpr = showrh = False
        else:
            raise Exception('')

        #
        vplow, vphgh, vslow, vshgh, rhlow, rhhgh, prlow, prhgh = p.boundaries()

        for what, where in zip(\
                [vplow, vphgh, vslow, vshgh, rhlow, rhhgh, prlow, prhgh],
                [rd.axdepth['VP'], rd.axdepth['VP'], rd.axdepth['VS'], rd.axdepth['VS'], rd.axdepth['RH'], rd.axdepth['RH'], rd.axdepth['PR'], rd.axdepth['PR']]):
            if where is not None:
                what.show(where,
                          alpha=1.0,
                          color="k",
                          marker="o--",
                          linewidth=1,
                          markersize=3)
        zmax = 1.1 * p.inv(p.MINF)[0][-1]

        if isinstance(p, Parameterizer_mZVSPRzRHvp):
            rd.axdepth['PR'].plot(p.PRz(np.linspace(0., zmax, 100)),
                                  np.linspace(0., zmax, 100),
                                  "r--",
                                  linewidth=3)
            legendtext(rd.axdepth['PR'], p.PRzName, loc=4)
            legendtext(rd.axdepth['RH'], p.RHvpName, loc=4)
        elif isinstance(p, Parameterizer_mZVSPRzRHz):
            rd.axdepth['PR'].plot(p.PRz(np.linspace(0., zmax, 100)),
                                  np.linspace(0., zmax, 100),
                                  "r--",
                                  linewidth=3)
            rd.axdepth['RH'].plot(p.RHz(np.linspace(0., zmax, 100)),
                                  np.linspace(0., zmax, 100),
                                  "r--",
                                  linewidth=3)
            legendtext(rd.axdepth['PR'], p.PRzName, loc=4)
            legendtext(rd.axdepth['RH'], p.RHzName, loc=4)

        rd.set_zlim(np.array([0, zmax]))
    else:
        print "call option --param to see prior depth boundaries"

    # --------------------
    if "-m96" in argv.keys():  # plot user data on top
        for m96 in argv['-m96']:
            try:
                dm = depthmodel_from_mod96(m96)
                dm.vp.show(rd.axdepth['VP'], "m", linewidth=3, label=m96)
                dm.vs.show(rd.axdepth['VS'], "m", linewidth=3)
                dm.rh.show(rd.axdepth['RH'], "m", linewidth=3)
                dm.pr().show(rd.axdepth['PR'], "m", linewidth=3)
            except KeyboardInterrupt:
                raise
            except:  #Exception as e:
                print 'could not read or display %s (reason : %s)' % (m96,
                                                                      str(e))
            rd.axdepth['VP'].legend(loc=3)
    if "-ritt" in argv.keys():
        a = AsciiFile('/mnt/labex2/home/max/data/boreholes/GRT1/GRT1.logsonic')

        for what, where in zip(
            [a.data['VS'], a.data['VP'], a.data['VP'] / a.data['VS']],
            [rd.axdepth['VS'], rd.axdepth['VP'], rd.axdepth['PR']]):
            if where is not None:
                where.plot(what, a.data['TVD'] / 1000., "m", alpha=0.5)

    # --------------------
    if os.path.exists(targetfile):
        # plot data on top
        rd.plotdisp(d.waves,
                    d.types,
                    d.modes,
                    d.freqs,
                    d.inv(dobs),
                    dvalues=d.dvalues,
                    alpha=.5,
                    color="r",
                    linewidth=2)

        if "-overdisp" in argv.keys():
            rd.set_vlim((0.5 * d.values.min(), 1.5 * d.values.max()))
            rd.set_plim((0.8 / overfreqs.max(), 1.2 / overfreqs.min()))
        else:
            rd.set_vlim((0.8 * d.values.min(), 1.2 * d.values.max()))
            rd.set_plim((0.8 / d.freqs.max(), 1.2 / d.freqs.min()))
    rd.tick()
    rd.grid()
    rd.fig.suptitle(rootname.split('_HerrMet_')[-1])
    if "-ftsz" in argv.keys():
        chftsz(rd.fig, argv["-ftsz"][0])
    else:
        chftsz(rd.fig, default_fontsize)
    if "-png" in argv.keys():
        dpi = argv['-png'][0] if len(argv['-png']) else default_dpi
        if verbose:
            print "writing %s" % pngfile
        rd.fig.savefig(pngfile, dpi=dpi)
    elif "-inline" in argv.keys():
        plt.show()
    else:
        showme()
    plt.close(rd.fig)
Ejemplo n.º 3
0
        keys = ["-Z%d" % i for i in xrange(1, nlayer)] + \
               ["VS%d" % i for i in xrange(nlayer)] + \
               ["PR%d" % i for i in xrange(nlayer)] + \
               ["RH%d" % i for i in xrange(nlayer)]
        vinfs = np.concatenate((ztopinf, vsinf, prinf, rhinf))
        vsups = np.concatenate((ztopsup, vssup, prsup, rhsup))
        with open('_HerrMet.param', 'w') as fid:
            fid.write('#met TYPE = "mZVSPRRH"\n')
            fid.write('#met NLAYER = %d\n' % nlayer)
            write_priortype_header(fid, dvp, dvs, drh)
            fid.write('#fld KEY VINF VSUP\n')
            fid.write('#unt - - -\n')
            fid.write('#fmt %5s %16f %16f\n')
            for k, vinf, vsup in zip(keys, vinfs, vsups):
                fid.write('%s %s %s\n' % (k, vinf, vsup))
        A = AsciiFile('_HerrMet.param')

        A.write()  #to screen
        A.write('_HerrMet.param')  #to file
    # ----------------------------
    elif type == "mZVSVPRH":
        if basedon is None:
            ztop = np.linspace(0, zbot, nlayer)
            ztopinf = -ztop[1:]  # deepest side
            ztopsup = -ztop[:-1]  # shallow side
            ztopsup[0] -= 0.001
            vsinf = 0.1 * np.ones(nlayer)
            vssup = 3.5 * np.ones(nlayer)
            vpinf = 0.5 * np.ones(nlayer)
            vpsup = 6.5 * np.ones(nlayer)
            rhinf = 1.8 * np.ones(nlayer)
Ejemplo n.º 4
0
def load_paramfile(paramfile, verbose=True):
    """initiate one of the parameterizer and prior pdf according to the param file"""
    if os.path.isfile(paramfile):
        A = AsciiFile(paramfile)
    elif "#fld" in paramfile:
        A = AsciiFile_fromstring(paramfile)
    else:
        raise ValueError('paramfile must be either a file name or a string with the file content')

    # ==========================
    if A.metadata['TYPE'] == "mZVSVPRH":
        parameterizer = Parameterizer_mZVSVPRH(A)

    elif A.metadata['TYPE'] == "mZVSPRRH":
        parameterizer = Parameterizer_mZVSPRRH(A)

    elif A.metadata['TYPE'] == "mZVSPRzRHvp":
        parameterizer = Parameterizer_mZVSPRzRHvp(A)

    elif A.metadata['TYPE'] == "mZVSPRzRHz":
        parameterizer = Parameterizer_mZVSPRzRHz(A)

    elif A.metadata['TYPE'] == "mZVSVPvsRHvp":
        parameterizer = Parameterizer_mZVSVPvsRHvp(A)

    else:
        raise Exception('could not load %s (TYPE not recognized)' % paramfile)

    # ==========================
    if not "PRIORTYPE" in A.metadata.keys():
        logRHOM = DefaultLogRhoM(parameterizer)

    elif A.metadata['PRIORTYPE'] == "DVS":
        logRHOM = LogRhoM_DVS(parameterizer,
                    dvsmin=A.metadata['DVSMIN'],
                    dvsmax=A.metadata['DVSMAX'])

    elif A.metadata['PRIORTYPE'] == "DVPDVSDRH":
        logRHOM = LogRhoM_DVPDVSDRH(parameterizer,
                    dvpmin=A.metadata['DVPMIN'],
                    dvpmax=A.metadata['DVPMAX'],
                    dvsmin=A.metadata['DVSMIN'],
                    dvsmax=A.metadata['DVSMAX'],
                    drhmin=A.metadata['DRHMIN'],
                    drhmax=A.metadata['DRHMAX'])

    elif A.metadata['PRIORTYPE'] == "DVPDVSDRHDPR":
        logRHOM = LogRhoM_DVPDVSDRHDPR(parameterizer,
                    dvpmin=A.metadata['DVPMIN'],
                    dvpmax=A.metadata['DVPMAX'],
                    dvsmin=A.metadata['DVSMIN'],
                    dvsmax=A.metadata['DVSMAX'],
                    drhmin=A.metadata['DRHMIN'],
                    drhmax=A.metadata['DRHMAX'],
                    dprmin=A.metadata['DPRMIN'],
                    dprmax=A.metadata['DPRMAX'])
    else:
        raise Exception('could not load %s (PRIORTYPE not recognized)' % paramfile)

    if verbose:
        print("parameter type : ", parameterizer.__class__.__name__)
        print("prior type     : ", logRHOM.__class__.__name__)
    return parameterizer, logRHOM
Ejemplo n.º 5
0
def write_default_paramfile(nlayer, zbot,
                            which_parameterizer="mZVSPRRH", basedon=None,
                            dvp=None, dvs=None, drh=None, dpr=None):
    """create a default parameter file to be customized by user"""
    # ------

    if np.all([_ is None for _ in (dvs, dvp, drh, dpr)]):
        which_prior = DefaultLogRhoM
    elif dvs is not None and dvp is None and drh is None and dpr is None:
        which_prior = LogRhoM_DVS
    elif dvs is not None and dvp is not None and drh is not None and dpr is None:
        which_prior = LogRhoM_DVPDVSDRH
    elif dvs is not None and dvp is not None and drh is not None and dpr is not None:
        which_prior = LogRhoM_DVPDVSDRHDPR
    else:
        raise NotImplementedError('please specify either dvs alone, or dvp, dvs and drh, or dvp, dvs, drh and dpr')

    if which_parameterizer == "mZVSPRRH":
        if basedon is None:
            ztop = np.linspace(0, zbot, nlayer)
            ztopinf = -ztop[1:]  # deepest side
            ztopsup = -ztop[:-1] # shallow side
            ztopsup[0] -= 0.001
            vsinf = 0.1 * np.ones(nlayer)
            vssup = 3.5 * np.ones(nlayer)
            prinf = 1.70 * np.ones(nlayer) #r43 * np.ones(nlayer)
            prsup = 2.15 * np.ones(nlayer) #3.5 * np.ones(nlayer)
            rhinf = 1.8 * np.ones(nlayer)
            rhsup = 3.0 * np.ones(nlayer)
        else:
            b = depthmodel_from_mod96(basedon)
            #ztop = np.linspace(0., b.vp.z.max(), nlayer)
            ztop = depthspace(zbot, nlayer)
            b = b.interp(ztop, interpmethod="weightedstairs")
            ztopinf = -b.vp.z[1:]
            ztopsup = -b.vp.z[1:]
            vsinf = b.vs.values.copy()
            vssup = b.vs.values.copy()
            prinf = b.pr().values.copy()
            prsup = b.pr().values.copy()
            rhinf = b.rh.values.copy()
            rhsup = b.rh.values.copy()

        keys = ["-Z%d" % i for i in range(1, nlayer)] + \
               ["VS%d" % i for i in range(nlayer)] + \
               ["PR%d" % i for i in range(nlayer)] + \
               ["RH%d" % i for i in range(nlayer)]
        vinfs = np.concatenate((ztopinf, vsinf, prinf, rhinf))
        vsups = np.concatenate((ztopsup, vssup, prsup, rhsup))
        with open(HERRMETPARAMFILELOCAL, 'w') as fid:
            fid.write('#met TYPE = "mZVSPRRH"\n')
            fid.write('#met NLAYER = %d\n' % nlayer)

            fid.write(which_prior.header(dvp=dvp, dvs=dvs, drh=drh, dpr=dpr))

            fid.write('#fld KEY VINF VSUP\n')
            fid.write('#unt - - -\n')
            fid.write('#fmt %5s %16f %16f\n')
            for k, vinf, vsup in zip(keys, vinfs, vsups):
                fid.write('%s %s %s\n' % (k, vinf, vsup))
        A = AsciiFile(HERRMETPARAMFILELOCAL)

        A.write() #to screen
        A.write(HERRMETPARAMFILELOCAL) #to file

    elif which_parameterizer == "mZVSVPRH":
        if basedon is None:
            ztop = np.linspace(0, zbot, nlayer)
            ztopinf = -ztop[1:]  # deepest side
            ztopsup = -ztop[:-1] # shallow side
            ztopsup[0] -= 0.001
            vsinf = 0.1 * np.ones(nlayer)
            vssup = 3.5 * np.ones(nlayer)
            vpinf = 0.5 * np.ones(nlayer)
            vpsup = 6.5 * np.ones(nlayer)
            rhinf = 1.8 * np.ones(nlayer)
            rhsup = 3.0 * np.ones(nlayer)

        else:
            b = depthmodel_from_mod96(basedon)
            # ztop = np.linspace(0., b.vp.z.max(), nlayer)
            ztop = depthspace(zbot, nlayer)
            b = b.interp(ztop, interpmethod="weightedstairs")
            ztopinf = -b.vp.z[1:]
            ztopsup = -b.vp.z[1:]
            vsinf = b.vs.values.copy()
            vssup = b.vs.values.copy()
            vpinf = b.vp.values.copy()
            vpsup = b.vp.values.copy()
            rhinf = b.rh.values.copy()
            rhsup = b.rh.values.copy()

        keys = ["-Z%d" % i for i in range(1, nlayer)] + \
               ["VS%d" % i for i in range(nlayer)] + \
               ["VP%d" % i for i in range(nlayer)] + \
               ["RH%d" % i for i in range(nlayer)]

        vinfs = np.concatenate((ztopinf, vsinf, vpinf, rhinf))
        vsups = np.concatenate((ztopsup, vssup, vpsup, rhsup))

        with open(HERRMETPARAMFILELOCAL, 'w') as fid:
            fid.write('#met TYPE = "mZVSVPRH"\n')
            fid.write('#met NLAYER = %d\n' % nlayer)

            fid.write(which_prior.header(dvp=dvp, dvs=dvs, drh=drh, dpr=dpr))

            fid.write('#fld KEY VINF VSUP\n')
            fid.write('#unt - - -\n')
            fid.write('#fmt %5s %16f %16f\n')
            for k, vinf, vsup in zip(keys, vinfs, vsups):
                fid.write('%s %s %s\n' % (k, vinf, vsup))
        A = AsciiFile(HERRMETPARAMFILELOCAL)

        A.write()  # to screen
        A.write(HERRMETPARAMFILELOCAL)  # to file

    elif which_parameterizer == "mZVSPRzRHvp":
        if basedon is None:
            ztop = np.linspace(0, zbot, nlayer)
            ztopinf = -ztop[1:]  # deepest side
            ztopsup = -ztop[:-1] # shallow side
            ztopsup[0] -= 0.001
            vsinf = 0.1 * np.ones(nlayer)
            vssup = 3.5 * np.ones(nlayer)
        else:
            b = depthmodel_from_mod96(basedon)
            # ztop = np.linspace(0., b.vp.z.max(), nlayer)
            ztop = depthspace(zbot, nlayer)
            b = b.interp(ztop, interpmethod="weightedstairs")
            ztopinf = -b.vp.z[1:]
            ztopsup = -b.vp.z[1:]
            vsinf = b.vs.values.copy()
            vssup = b.vs.values.copy()

        keys = ["-Z%d" % i for i in range(1, nlayer)] + \
               ["VS%d" % i for i in range(nlayer)]

        vinfs = np.concatenate((ztopinf, vsinf))
        vsups = np.concatenate((ztopsup, vssup))

        with open(HERRMETPARAMFILELOCAL, 'w') as fid:
            fid.write('#met TYPE = "mZVSPRzRHvp"\n')
            fid.write('#met NLAYER = %d\n' % nlayer)
            # fid.write('#met PRz  = "def PRz(Z): return 1.0335 * np.exp(-Z / 0.5408) + 1.7310"\n')
            # fid.write('#met RHvp = "def RHvp(VP): return 1.74 * VP ** 0.25"\n')
            fid.write('#met PRz  = "lambda Z: 1.0335 * np.exp(-Z / 0.5408) + 1.7310"\n')
            fid.write('#met RHvp = "lambda VP: 1.74 * VP ** 0.25"\n')

            fid.write(which_prior.header(dvp=dvp, dvs=dvs, drh=drh, dpr=dpr))

            fid.write('#fld KEY VINF VSUP\n')
            fid.write('#unt - - -\n')
            fid.write('#fmt %5s %16f %16f\n')
            for k, vinf, vsup in zip(keys, vinfs, vsups):
                fid.write('%s %s %s\n' % (k, vinf, vsup))
        A = AsciiFile(HERRMETPARAMFILELOCAL)

        A.write() #to screen
        A.write(HERRMETPARAMFILELOCAL) #to file

    elif which_parameterizer == "mZVSPRzRHz":
        if basedon is None:
            ztop = np.linspace(0, zbot, nlayer)
            ztopinf = -ztop[1:]  # deepest side
            ztopsup = -ztop[:-1] # shallow side
            ztopsup[0] -= 0.001
            vsinf = 0.1 * np.ones(nlayer)
            vssup = 3.5 * np.ones(nlayer)
        else:
            b = depthmodel_from_mod96(basedon)
            #ztop = np.linspace(0., b.vp.z.max(), nlayer)
            ztop = depthspace(zbot, nlayer)
            b = b.interp(ztop, interpmethod="weightedstairs")
            ztopinf = -b.vp.z[1:]
            ztopsup = -b.vp.z[1:]
            vsinf = b.vs.values.copy()
            vssup = b.vs.values.copy()

        keys = ["-Z%d" % i for i in range(1, nlayer)] + \
               ["VS%d" % i for i in range(nlayer)]

        vinfs = np.concatenate((ztopinf, vsinf))
        vsups = np.concatenate((ztopsup, vssup))

        with open(HERRMETPARAMFILELOCAL, 'w') as fid:
            fid.write('#met TYPE = "mZVSPRzRHvp"\n')
            fid.write('#met NLAYER = %d\n' % nlayer)
            # fid.write('#met PRz  = "def PRz(Z): return 1.0335 * np.exp(-Z / 0.5408) + 1.7310"\n')
            # fid.write('#met RHz  = "def RHz(Z): return Z * 0. + 2.67"\n')
            fid.write('#met PRz  = "lambda Z: 1.0335 * np.exp(-Z / 0.5408) + 1.7310"\n')
            fid.write('#met RHz  = "lambda Z: Z * 0. + 2.67"\n')

            fid.write(which_prior.header(dvp=dvp, dvs=dvs, drh=drh, dpr=dpr))

            fid.write('#fld KEY VINF VSUP\n')
            fid.write('#unt - - -\n')
            fid.write('#fmt %5s %16f %16f\n')
            for k, vinf, vsup in zip(keys, vinfs, vsups):
                fid.write('%s %s %s\n' % (k, vinf, vsup))
        A = AsciiFile(HERRMETPARAMFILELOCAL)

        A.write() #to screen
        A.write(HERRMETPARAMFILELOCAL) #to file

    elif which_parameterizer == "mZVSVPvsRHvp":
        if basedon is None:
            ztop = np.linspace(0, zbot, nlayer)
            ztopinf = -ztop[1:]  # deepest side
            ztopsup = -ztop[:-1]  # shallow side
            ztopsup[0] -= 0.001
            vsinf = 0.1 * np.ones(nlayer)
            vssup = 3.5 * np.ones(nlayer)
        else:
            raise NotImplementedError('option -basedon not implemented for mZVSVPvsRHvp')

        keys = ["-Z%d" % i for i in range(1, nlayer)] + \
               ["VS%d" % i for i in range(nlayer)]

        vinfs = np.concatenate((ztopinf, vsinf))
        vsups = np.concatenate((ztopsup, vssup))

        with open(HERRMETPARAMFILELOCAL, 'w') as fid:
            fid.write('#met TYPE = "mZVSVPvsRHvp"\n')
            fid.write('#met NLAYER = %d\n' % nlayer)
            fid.write('# BROCHER2005\n')
            fid.write(
               '#met VPvs = "lambda VS: '
               '0.9409 + 2.0947 * VS - 0.8206 * VS ** 2.0 + 0.2683 * VS ** 3.0 '
               '- 0.0251 * VS ** 4.0"\n')
            fid.write(
                '#met RHvp = "lambda VP: '
                '1.6612 * VP - 0.4721 * VP ** 2.0 + 0.0671 * VP ** 3.0 '
                '- 0.0043 * VP ** 4.0 + 0.000106 * VP ** 5.0"\n')

            fid.write(which_prior.header(dvp=dvp, dvs=dvs, drh=drh, dpr=dpr))

            fid.write('#fld KEY VINF VSUP\n')
            fid.write('#unt - - -\n')
            fid.write('#fmt %5s %16f %16f\n')
            for k, vinf, vsup in zip(keys, vinfs, vsups):
                fid.write('%s %s %s\n' % (k, vinf, vsup))
        A = AsciiFile(HERRMETPARAMFILELOCAL)

        A.write()  # to screen
        A.write(HERRMETPARAMFILELOCAL)  # to file
    else:
        raise NotImplementedError('no such parameter file type implemented %s' % which_parameterizer)