Instruction:
Write a Python 3 function that can
get bootstrap parameters for s data

Response:
def sbootpars(Taus, Vs):
    """
     get bootstrap parameters for s data
    """
#
    Tau1s, Tau2s, Tau3s = [], [], []
    V1s, V2s, V3s = [], [], []
    nb = len(Taus)
    bpars = {}
    for k in range(nb):
        Tau1s.append(Taus[k][0])
        Tau2s.append(Taus[k][1])
        Tau3s.append(Taus[k][2])
        V1s.append(Vs[k][0])
        V2s.append(Vs[k][1])
        V3s.append(Vs[k][2])
    x, sig = gausspars(Tau1s)
    bpars["t1_sigma"] = sig
    x, sig = gausspars(Tau2s)
    bpars["t2_sigma"] = sig
    x, sig = gausspars(Tau3s)
    bpars["t3_sigma"] = sig
    V1s=flip(V1s,combine=True)
    kpars = dokent(V1s, len(V1s))
    bpars["v1_dec"] = kpars["dec"]
    bpars["v1_inc"] = kpars["inc"]
    bpars["v1_zeta"] = (kpars["Zeta"] * np.sqrt(nb)) % 360.
    bpars["v1_eta"] = (kpars["Eta"] * np.sqrt(nb)) % 360.
    bpars["v1_zeta_dec"] = kpars["Zdec"]
    bpars["v1_zeta_inc"] = kpars["Zinc"]
    bpars["v1_eta_dec"] = kpars["Edec"]
    bpars["v1_eta_inc"] = kpars["Einc"]
    V2s=flip(V2s,combine=True)
    kpars = dokent(V2s, len(V2s))
    bpars["v2_dec"] = kpars["dec"]
    bpars["v2_inc"] = kpars["inc"]
    bpars["v2_zeta"] = (kpars["Zeta"] * np.sqrt(nb)) % 360.
    bpars["v2_eta"] = (kpars["Eta"] * np.sqrt(nb)) % 360.
    bpars["v2_zeta_dec"] = kpars["Zdec"]
    bpars["v2_zeta_inc"] = kpars["Zinc"]
    bpars["v2_eta_dec"] = kpars["Edec"]
    bpars["v2_eta_inc"] = kpars["Einc"]
    V3s=flip(V3s,combine=True)
    kpars = dokent(V3s, len(V3s))
    bpars["v3_dec"] = kpars["dec"]
    bpars["v3_inc"] = kpars["inc"]
    bpars["v3_zeta"] = (kpars["Zeta"] * np.sqrt(nb)) % 360.
    bpars["v3_eta"] = (kpars["Eta"] * np.sqrt(nb)) % 360.
    bpars["v3_zeta_dec"] = kpars["Zdec"]
    bpars["v3_zeta_inc"] = kpars["Zinc"]
    bpars["v3_eta_dec"] = kpars["Edec"]
    bpars["v3_eta_inc"] = kpars["Einc"]
    return bpars


Instruction:
Write a Python 3 script for
returning bootstrap parameters for S data Parameters __________ Ss : nested array of [[x11 x22 x33 x12 x23 x13],....] data ipar : if True, do a parametric bootstrap nb : number of bootstraps Returns ________ Tmean : average eigenvalues Vmean : average eigvectors Taus : bootstrapped eigenvalues Vs : bootstrapped eigenvectors

Response:
def s_boot(Ss, ipar=0, nb=1000):
    """
    Returns bootstrap parameters for S data

    Parameters
    __________
    Ss : nested array of [[x11 x22 x33 x12 x23 x13],....] data
    ipar : if True, do a parametric bootstrap
    nb : number of bootstraps

    Returns
    ________
    Tmean : average eigenvalues
    Vmean : average eigvectors
    Taus : bootstrapped eigenvalues
    Vs :  bootstrapped eigenvectors

    """
    #npts = len(Ss)
    Ss = np.array(Ss)
    npts = Ss.shape[0]
# get average s for whole dataset
    nf, Sigma, avs = sbar(Ss)
    Tmean, Vmean = doseigs(avs)  # get eigenvectors of mean tensor
#
# now do bootstrap to collect Vs and taus of bootstrap means
#
    Taus, Vs = [], []  # number of bootstraps, list of bootstrap taus and eigenvectors
#
    for k in range(int(float(nb))):  # repeat nb times
        #        if k%50==0:print k,' out of ',nb
        # get a pseudosample - if ipar=1, do a parametric bootstrap
        BSs = apseudo(Ss, ipar, Sigma)
        nf, sigma, avbs = sbar(BSs)  # get bootstrap mean s
        tau, Vdirs = doseigs(avbs)  # get bootstrap eigenparameters
        Taus.append(tau)
        Vs.append(Vdirs)
    return Tmean, Vmean, Taus, Vs


Instruction:
Make a summary of the following Python 3 code
def designAARM(npos):
    #
    """
    calculates B matrix for AARM calculations.
    """
    if npos != 9:
        print('Sorry - only 9 positions available')
        return
    Dec = [315., 225., 180., 135., 45., 90., 270.,
           270., 270., 90., 0., 0., 0., 180., 180.]
    Dip = [0., 0., 0., 0., 0., -45., -45., 0.,
           45., 45., 45., -45., -90., -45., 45.]
    index9 = [0, 1, 2, 5, 6, 7, 10, 11, 12]
    H = []
    for ind in range(15):
        Dir = [Dec[ind], Dip[ind], 1.]
        H.append(dir2cart(Dir))  # 15 field directionss
#
# make design matrix A
#
    A = np.zeros((npos * 3, 6), 'f')
    tmpH = np.zeros((npos, 3), 'f')  # define tmpH
    if npos == 9:
        for i in range(9):
            k = index9[i]
            ind = i * 3
            A[ind][0] = H[k][0]
            A[ind][3] = H[k][1]
            A[ind][5] = H[k][2]
            ind = i * 3 + 1
            A[ind][3] = H[k][0]
            A[ind][1] = H[k][1]
            A[ind][4] = H[k][2]
            ind = i * 3 + 2
            A[ind][5] = H[k][0]
            A[ind][4] = H[k][1]
            A[ind][2] = H[k][2]
            for j in range(3):
                tmpH[i][j] = H[k][j]
        At = np.transpose(A)
        ATA = np.dot(At, A)
        ATAI = linalg.inv(ATA)
        B = np.dot(ATAI, At)
    else:
        print("B matrix not yet supported")
        return
    return B, H, tmpH

Response: Calculates AARM matrix for AARM.


Instruction:
Implement a Python 3 function for
converting a magic record into the domagic mag format

Response:
def domagicmag(file, Recs):
    """
    converts a magic record back into the SIO mag format
    """
    for rec in Recs:
        type = ".0"
        meths = []
        tmp = rec["magic_method_codes"].split(':')
        for meth in tmp:
            meths.append(meth.strip())
        if 'LT-T-I' in meths:
            type = ".1"
        if 'LT-PTRM-I' in meths:
            type = ".2"
        if 'LT-PTRM-MD' in meths:
            type = ".3"
        treatment = float(rec["treatment_temp"]) - 273
        tr = '%i' % (treatment) + type
        inten = '%8.7e ' % (float(rec["measurement_magn_moment"]) * 1e3)
        outstring = rec["er_specimen_name"] + " " + tr + " " + rec["measurement_csd"] + \
            " " + inten + " " + rec["measurement_dec"] + \
            " " + rec["measurement_inc"] + "\n"
        file.write(outstring)


Instruction:
Can you write a function in Python 3 where it
cleans up unbalanced steps failure can be from missing steps

Response:
def cleanup(first_I, first_Z):
    """
     cleans up unbalanced steps
     failure can be from unbalanced final step, or from missing steps,
     this takes care of  missing steps
    """
    cont = 0
    Nmin = len(first_I)
    if len(first_Z) < Nmin:
        Nmin = len(first_Z)
    for kk in range(Nmin):
        if first_I[kk][0] != first_Z[kk][0]:
            print("\n WARNING: ")
            if first_I[kk] < first_Z[kk]:
                del first_I[kk]
            else:
                del first_Z[kk]
            print("Unmatched step number: ", kk + 1, '  ignored')
            cont = 1
        if cont == 1:
            return first_I, first_Z, cont
    return first_I, first_Z, cont


Instruction:
Given the following Python 3 function, write the documentation
def sortarai(datablock, s, Zdiff, **kwargs):
    if 'version' in list(kwargs.keys()) and kwargs['version'] == 3:
        dec_key, inc_key = 'dir_dec', 'dir_inc'
        Mkeys = ['magn_moment', 'magn_volume', 'magn_mass', 'magnitude']
        meth_key = 'method_codes'
        temp_key, dc_key = 'treat_temp', 'treat_dc_field'
        dc_theta_key, dc_phi_key = 'treat_dc_field_theta', 'treat_dc_field_phi'
        # convert dataframe to list of dictionaries
        datablock = datablock.to_dict('records')
    else:
        dec_key, inc_key = 'measurement_dec', 'measurement_inc'
        Mkeys = ['measurement_magn_moment', 'measurement_magn_volume',
                 'measurement_magn_mass', 'measurement_magnitude']
        meth_key = 'magic_method_codes'
        temp_key, dc_key = 'treatment_temp', 'treatment_dc_field'
        dc_theta_key, dc_phi_key = 'treatment_dc_field_theta', 'treatment_dc_field_phi'
    first_Z, first_I, zptrm_check, ptrm_check, ptrm_tail = [], [], [], [], []
    field, phi, theta = "", "", ""
    starthere = 0
    Treat_I, Treat_Z, Treat_PZ, Treat_PI, Treat_M = [], [], [], [], []
    ISteps, ZSteps, PISteps, PZSteps, MSteps = [], [], [], [], []
    GammaChecks = []  # comparison of pTRM direction acquired and lab field
    rec = datablock[0]
    for key in Mkeys:
        if key in list(rec.keys()) and rec[key] != "":
            momkey = key
            break
# first find all the steps
    for k in range(len(datablock)):
        rec = datablock[k]
        temp = float(rec[temp_key])
        methcodes = []
        tmp = rec[meth_key].split(":")
        for meth in tmp:
            methcodes.append(meth.strip())
        if 'LT-T-I' in methcodes and 'LP-TRM' not in methcodes and 'LP-PI-TRM' in methcodes:
            Treat_I.append(temp)
            ISteps.append(k)
            if field == "":
                field = float(rec[dc_key])
            if phi == "":
                phi = float(rec[dc_phi_key])
                theta = float(rec[dc_theta_key])
# stick  first zero field stuff into first_Z
        if 'LT-NO' in methcodes:
            Treat_Z.append(temp)
            ZSteps.append(k)
        if 'LT-T-Z' in methcodes:
            Treat_Z.append(temp)
            ZSteps.append(k)
        if 'LT-PTRM-Z' in methcodes:
            Treat_PZ.append(temp)
            PZSteps.append(k)
        if 'LT-PTRM-I' in methcodes:
            Treat_PI.append(temp)
            PISteps.append(k)
        if 'LT-PTRM-MD' in methcodes:
            Treat_M.append(temp)
            MSteps.append(k)
        if 'LT-NO' in methcodes:
            dec = float(rec[dec_key])
            inc = float(rec[inc_key])
            st = float(rec[momkey])
            first_I.append([273, 0., 0., 0., 1])
            first_Z.append([273, dec, inc, st, 1])  # NRM step
    for temp in Treat_I:  # look through infield steps and find matching Z step
        if temp in Treat_Z:  # found a match
            istep = ISteps[Treat_I.index(temp)]
            irec = datablock[istep]
            methcodes = []
            tmp = irec[meth_key].split(":")
            for meth in tmp:
                methcodes.append(meth.strip())
            # take last record as baseline to subtract
            brec = datablock[istep - 1]
            zstep = ZSteps[Treat_Z.index(temp)]
            zrec = datablock[zstep]
    # sort out first_Z records
            if "LP-PI-TRM-IZ" in methcodes:
                ZI = 0
            else:
                ZI = 1
            dec = float(zrec[dec_key])
            inc = float(zrec[inc_key])
            st = float(zrec[momkey])
            first_Z.append([temp, dec, inc, st, ZI])
    # sort out first_I records
            try:
                idec = float(irec[dec_key])
                iinc = float(irec[inc_key])
                istr = float(irec[momkey])
            except TypeError as ex:
                raise Exception('Malformed data of some sort for dec/inc/moment in measurement: {}.  You must fix this before proceeding.\n           Bad record: {}'.format(irec.get('measurement', ''), irec))
            X = dir2cart([idec, iinc, istr])
            BL = dir2cart([dec, inc, st])
            I = []
            for c in range(3):
                I.append((X[c] - BL[c]))
            if I[2] != 0:
                iDir = cart2dir(I)
                if Zdiff == 0:
                    first_I.append([temp, iDir[0], iDir[1], iDir[2], ZI])
                else:
                    first_I.append([temp, 0., 0., I[2], ZI])
                gamma = angle([iDir[0], iDir[1]], [phi, theta])
            else:
                first_I.append([temp, 0., 0., 0., ZI])
                gamma = 0.0
# put in Gamma check (infield trm versus lab field)
            if 180. - gamma < gamma:
                gamma = 180. - gamma
            GammaChecks.append([temp - 273., gamma])
    for temp in Treat_PI:  # look through infield steps and find matching Z step
        step = PISteps[Treat_PI.index(temp)]
        rec = datablock[step]
        dec = float(rec[dec_key])
        inc = float(rec[inc_key])
        st = float(rec[momkey])
        brec = datablock[step - 1]  # take last record as baseline to subtract
        pdec = float(brec[dec_key])
        pinc = float(brec[inc_key])
        pint = float(brec[momkey])
        X = dir2cart([dec, inc, st])
        prevX = dir2cart([pdec, pinc, pint])
        I = []
        for c in range(3):
            I.append(X[c] - prevX[c])
        dir1 = cart2dir(I)
        if Zdiff == 0:
            ptrm_check.append([temp, dir1[0], dir1[1], dir1[2]])
        else:
            ptrm_check.append([temp, 0., 0., I[2]])
# in case there are zero-field pTRM checks (not the SIO way)
    for temp in Treat_PZ:
        step = PZSteps[Treat_PZ.index(temp)]
        rec = datablock[step]
        dec = float(rec[dec_key])
        inc = float(rec[inc_key])
        st = float(rec[momkey])
        brec = datablock[step - 1]
        pdec = float(brec[dec_key])
        pinc = float(brec[inc_key])
        pint = float(brec[momkey])
        X = dir2cart([dec, inc, st])
        prevX = dir2cart([pdec, pinc, pint])
        I = []
        for c in range(3):
            I.append(X[c] - prevX[c])
        dir2 = cart2dir(I)
        zptrm_check.append([temp, dir2[0], dir2[1], dir2[2]])
    # get pTRM tail checks together -
    for temp in Treat_M:
        # tail check step - just do a difference in magnitude!
        step = MSteps[Treat_M.index(temp)]
        rec = datablock[step]
        st = float(rec[momkey])
        if temp in Treat_Z:
            step = ZSteps[Treat_Z.index(temp)]
            brec = datablock[step]
            pint = float(brec[momkey])
#        X=dir2cart([dec,inc,st])
#        prevX=dir2cart([pdec,pinc,pint])
#        I=[]
#        for c in range(3):I.append(X[c]-prevX[c])
#        d=cart2dir(I)
#        ptrm_tail.append([temp,d[0],d[1],d[2]])
            # difference - if negative, negative tail!
            ptrm_tail.append([temp, 0, 0, st - pint])
        else:
            print(
                s, '  has a tail check with no first zero field step - check input file! for step', temp - 273.)
#
# final check
#
    if len(first_Z) != len(first_I):
        print(len(first_Z), len(first_I))
        print(" Something wrong with this specimen! Better fix it or delete it ")
        input(" press return to acknowledge message")
    araiblock = (first_Z, first_I, ptrm_check,
                 ptrm_tail, zptrm_check, GammaChecks)
    return araiblock, field

Response: This function sorts data block in to first_Z first_I etc.


Instruction:
Here you have a function in Python 3, explain what it does
def sortmwarai(datablock, exp_type):
    first_Z, first_I, ptrm_check, ptrm_tail, zptrm_check = [], [], [], [], []
    field, phi, theta = "", "", ""
    POWT_I, POWT_Z, POWT_PZ, POWT_PI, POWT_M = [], [], [], [], []
    ISteps, ZSteps, PZSteps, PISteps, MSteps = [], [], [], [], []
    rad = old_div(np.pi, 180.)
    ThetaChecks = []
    DeltaChecks = []
    GammaChecks = []
# first find all the steps
    for k in range(len(datablock)):
        rec = datablock[k]
        powt = int(float(rec["treatment_mw_energy"]))
        methcodes = []
        tmp = rec["magic_method_codes"].split(":")
        for meth in tmp:
            methcodes.append(meth.strip())
        if 'LT-M-I' in methcodes and 'LP-MRM' not in methcodes:
            POWT_I.append(powt)
            ISteps.append(k)
            if field == "":
                field = float(rec['treatment_dc_field'])
            if phi == "":
                phi = float(rec['treatment_dc_field_phi'])
                theta = float(rec['treatment_dc_field_theta'])
        if 'LT-M-Z' in methcodes:
            POWT_Z.append(powt)
            ZSteps.append(k)
        if 'LT-PMRM-Z' in methcodes:
            POWT_PZ.append(powt)
            PZSteps.append(k)
        if 'LT-PMRM-I' in methcodes:
            POWT_PI.append(powt)
            PISteps.append(k)
        if 'LT-PMRM-MD' in methcodes:
            POWT_M.append(powt)
            MSteps.append(k)
        if 'LT-NO' in methcodes:
            dec = float(rec["measurement_dec"])
            inc = float(rec["measurement_inc"])
            st = float(rec["measurement_magn_moment"])
            first_I.append([0, 0., 0., 0., 1])
            first_Z.append([0, dec, inc, st, 1])  # NRM step
    if exp_type == "LP-PI-M-D":
        # now look trough infield steps and  find matching Z step
        for powt in POWT_I:
            if powt in POWT_Z:
                istep = ISteps[POWT_I.index(powt)]
                irec = datablock[istep]
                methcodes = []
                tmp = irec["magic_method_codes"].split(":")
                for meth in tmp:
                    methcodes.append(meth.strip())
                # take last record as baseline to subtract
                brec = datablock[istep - 1]
                zstep = ZSteps[POWT_Z.index(powt)]
                zrec = datablock[zstep]
    # sort out first_Z records
                if "LP-PI-M-IZ" in methcodes:
                    ZI = 0
                else:
                    ZI = 1
                dec = float(zrec["measurement_dec"])
                inc = float(zrec["measurement_inc"])
                st = float(zrec["measurement_magn_moment"])
                first_Z.append([powt, dec, inc, st, ZI])
    # sort out first_I records
                idec = float(irec["measurement_dec"])
                iinc = float(irec["measurement_inc"])
                istr = float(irec["measurement_magn_moment"])
                X = dir2cart([idec, iinc, istr])
                BL = dir2cart([dec, inc, st])
                I = []
                for c in range(3):
                    I.append((X[c] - BL[c]))
                iDir = cart2dir(I)
                first_I.append([powt, iDir[0], iDir[1], iDir[2], ZI])
# put in Gamma check (infield trm versus lab field)
                gamma = angle([iDir[0], iDir[1]], [phi, theta])
                GammaChecks.append([powt, gamma])
    elif exp_type == "LP-PI-M-S":
        # find last zero field step before first infield step
        lzrec = datablock[ISteps[0] - 1]
        irec = datablock[ISteps[0]]
        ndec = float(lzrec["measurement_dec"])
        ninc = float(lzrec["measurement_inc"])
        nstr = float(lzrec["measurement_magn_moment"])
        NRM = dir2cart([ndec, ninc, nstr])
        fdec = float(irec["treatment_dc_field_phi"])
        finc = float(irec["treatment_dc_field_theta"])
        Flab = dir2cart([fdec, finc, 1.])
        for step in ISteps:
            irec = datablock[step]
            rdec = float(irec["measurement_dec"])
            rinc = float(irec["measurement_inc"])
            rstr = float(irec["measurement_magn_moment"])
            theta1 = angle([ndec, ninc], [rdec, rinc])
            theta2 = angle([rdec, rinc], [fdec, finc])
            powt = int(float(irec["treatment_mw_energy"]))
            ThetaChecks.append([powt, theta1 + theta2])
            p = (180. - (theta1 + theta2))
            nstr = rstr * (old_div(np.sin(theta2 * rad), np.sin(p * rad)))
            tmstr = rstr * (old_div(np.sin(theta1 * rad), np.sin(p * rad)))
            first_Z.append([powt, ndec, ninc, nstr, 1])
            first_I.append([powt, dec, inc, tmstr, 1])
# check if zero field steps are parallel to assumed NRM
        for step in ZSteps:
            zrec = datablock[step]
            powt = int(float(zrec["treatment_mw_energy"]))
            zdec = float(zrec["measurement_dec"])
            zinc = float(zrec["measurement_inc"])
            delta = angle([ndec, ninc], [zdec, zinc])
            DeltaChecks.append([powt, delta])
    # get pTRMs together - take previous record and subtract
    for powt in POWT_PI:
        step = PISteps[POWT_PI.index(powt)]
        rec = datablock[step]
        dec = float(rec["measurement_dec"])
        inc = float(rec["measurement_inc"])
        st = float(rec["measurement_magn_moment"])
        brec = datablock[step - 1]  # take last record as baseline to subtract
        pdec = float(brec["measurement_dec"])
        pinc = float(brec["measurement_inc"])
        pint = float(brec["measurement_magn_moment"])
        X = dir2cart([dec, inc, st])
        prevX = dir2cart([pdec, pinc, pint])
        I = []
        for c in range(3):
            I.append(X[c] - prevX[c])
        dir1 = cart2dir(I)
        ptrm_check.append([powt, dir1[0], dir1[1], dir1[2]])
    # get zero field pTRM  checks together
    for powt in POWT_PZ:
        step = PZSteps[POWT_PZ.index(powt)]
        rec = datablock[step]
        dec = float(rec["measurement_dec"])
        inc = float(rec["measurement_inc"])
        st = float(rec["measurement_magn_moment"])
        brec = datablock[step - 1]
        pdec = float(brec["measurement_dec"])
        pinc = float(brec["measurement_inc"])
        pint = float(brec["measurement_magn_moment"])
        X = dir2cart([dec, inc, st])
        prevX = dir2cart([pdec, pinc, pint])
        I = []
        for c in range(3):
            I.append(X[c] - prevX[c])
        dir2 = cart2dir(I)
        zptrm_check.append([powt, dir2[0], dir2[1], dir2[2]])
    # get pTRM tail checks together -
    for powt in POWT_M:
        step = MSteps[POWT_M.index(powt)]  # tail check step
        rec = datablock[step]
#        dec=float(rec["measurement_dec"])
#        inc=float(rec["measurement_inc"])
        st = float(rec["measurement_magn_moment"])
        step = ZSteps[POWT_Z.index(powt)]
        brec = datablock[step]
#        pdec=float(brec["measurement_dec"])
#        pinc=float(brec["measurement_inc"])
        pint = float(brec["measurement_magn_moment"])
#        X=dir2cart([dec,inc,st])
#        prevX=dir2cart([pdec,pinc,pint])
#        I=[]
#        for c in range(3):I.append(X[c]-prevX[c])
#        d=cart2dir(I)
 #       ptrm_tail.append([powt,d[0],d[1],d[2]])
        # just do absolute magnitude difference # not vector diff
        ptrm_tail.append([powt, 0, 0, st - pint])
    #  check
    #
        if len(first_Z) != len(first_I):
            print(len(first_Z), len(first_I))
            print(" Something wrong with this specimen! Better fix it or delete it ")
            input(" press return to acknowledge message")
            print(MaxRec)
    araiblock = (first_Z, first_I, ptrm_check, ptrm_tail,
                 zptrm_check, GammaChecks, ThetaChecks, DeltaChecks)
    return araiblock, field

Response: sorts microwave double heating data block in to first_Z first_I etc.


Instruction:
Here you have a function in Python 3, explain what it does
def docustom(lon, lat, alt, gh):
    model, date, itype = 0, 0, 1
    sv = np.zeros(len(gh))
    colat = 90. - lat
    x, y, z, f = magsyn(gh, sv, model, date, itype, alt, colat, lon)
    return x, y, z, f

Response: Calculates the field from the coefficients in the specified location.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def doigrf(lon, lat, alt, date, **kwargs):
    from . import coefficients as cf
    gh, sv = [], []
    colat = 90. - lat
#! convert to colatitude for MB routine
    if lon < 0:
        lon = lon + 360.
# ensure all positive east longitudes
    itype = 1
    models, igrf12coeffs = cf.get_igrf12()
    if 'mod' in list(kwargs.keys()):
        if kwargs['mod'] == 'arch3k':
            psvmodels, psvcoeffs = cf.get_arch3k()  # use ARCH3k coefficients
        elif kwargs['mod'] == 'cals3k':
            # use CALS3K_4b coefficients between -1000,1940
            psvmodels, psvcoeffs = cf.get_cals3k()
        elif kwargs['mod'] == 'pfm9k':
            # use PFM9k (Nilsson et al., 2014), coefficients from -7000 to 1900
            psvmodels, psvcoeffs = cf.get_pfm9k()
        elif kwargs['mod'] == 'hfm10k':
            # use HFM.OL1.A1 (Constable et al., 2016), coefficients from -8000
            # to 1900
            psvmodels, psvcoeffs = cf.get_hfm10k()
        elif kwargs['mod'] == 'cals10k.2':
            # use CALS10k.2 (Constable et al., 2016), coefficients from -8000
            # to 1900
            psvmodels, psvcoeffs = cf.get_cals10k_2()
        elif kwargs['mod'] == 'shadif14k':
            # use CALS10k.2 (Constable et al., 2016), coefficients from -8000
            # to 1900
            psvmodels, psvcoeffs = cf.get_shadif14k()
        else:
            # Korte and Constable, 2011;  use prior to -1000, back to -8000
            psvmodels, psvcoeffs = cf.get_cals10k()
# use geodetic coordinates
    if 'models' in kwargs:
        if 'mod' in list(kwargs.keys()):
            return psvmodels, psvcoeffs
        else:
            return models, igrf12coeffs
    if date < -12000:
        print('too old')
        return
    if 'mod' in list(kwargs.keys()) and kwargs['mod'] == 'shadif14k':
        if date < -10000:
            incr = 100
        else:
            incr = 50
        model = date - date % incr
        gh = psvcoeffs[psvmodels.index(int(model))]
        sv = old_div(
            (psvcoeffs[psvmodels.index(int(model + incr))] - gh), float(incr))
        x, y, z, f = magsyn(gh, sv, model, date, itype, alt, colat, lon)
    elif date < -1000:
        incr = 10
        model = date - date % incr
        gh = psvcoeffs[psvmodels.index(int(model))]
        sv = old_div(
            (psvcoeffs[psvmodels.index(int(model + incr))] - gh), float(incr))
        x, y, z, f = magsyn(gh, sv, model, date, itype, alt, colat, lon)
    elif date < 1900:
        if kwargs['mod'] == 'cals10k':
            incr = 50
        else:
            incr = 10
        model = date - date % incr
        gh = psvcoeffs[psvmodels.index(model)]
        if model + incr < 1900:
            sv = old_div(
                (psvcoeffs[psvmodels.index(model + incr)] - gh), float(incr))
        else:
            field2 = igrf12coeffs[models.index(1940)][0:120]
            sv = old_div((field2 - gh), float(1940 - model))
        x, y, z, f = magsyn(gh, sv, model, date, itype, alt, colat, lon)
    else:
        model = date - date % 5
        if date < 2015:
            gh = igrf12coeffs[models.index(model)]
            sv = old_div((igrf12coeffs[models.index(model + 5)] - gh), 5.)
            x, y, z, f = magsyn(gh, sv, model, date, itype, alt, colat, lon)
        else:
            gh = igrf12coeffs[models.index(2015)]
            sv = igrf12coeffs[models.index(2015.20)]
            x, y, z, f = magsyn(gh, sv, model, date, itype, alt, colat, lon)
    if 'coeffs' in list(kwargs.keys()):
        return gh
    else:
        return x, y, z, f

Response: This function calculates the interpolated or extrapolated main field and returns the interpolated main field and the interpolated secular variation coefficients.


Instruction:
Can you generate the documentation for the following Python 3 function
def unpack(gh):
    data = []
    k, l = 0, 1
    while k + 1 < len(gh):
        for m in range(l + 1):
            if m == 0:
                data.append([l, m, gh[k], 0])
                k += 1
            else:
                data.append([l, m, gh[k], gh[k + 1]])
                k += 2
        l += 1
    return data

Response: Unpacks a list of gauss coefficients into l m g h type list


Instruction:
Explain what the following Python 3 code does
def measurements_methods(meas_data, noave):
#
    version_num = get_version()
    sids = get_specs(meas_data)
# list  of measurement records for this specimen
#
# step through spec by spec
#
    SpecTmps, SpecOuts = [], []
    for spec in sids:
        TRM, IRM3D, ATRM, CR = 0, 0, 0, 0
        expcodes = ""
# first collect all data for this specimen and do lab treatments
        # list  of measurement records for this specimen
        SpecRecs = get_dictitem(meas_data, 'er_specimen_name', spec, 'T')
        for rec in SpecRecs:
            if 'measurement_flag' not in list(rec.keys()):
                rec['measurement_flag'] = 'g'
            tmpmeths = rec['magic_method_codes'].split(":")
            meths = []
            if "LP-TRM" in tmpmeths:
                TRM = 1  # catch these suckers here!
            if "LP-IRM-3D" in tmpmeths:
                IRM3D = 1  # catch these suckers here!
            elif "LP-AN-TRM" in tmpmeths:
                ATRM = 1  # catch these suckers here!
            elif "LP-CR-TRM" in tmpmeths:
                CR = 1  # catch these suckers here!
#
# otherwise write over existing method codes
#
# find NRM data (LT-NO)
#
            elif float(rec["measurement_temp"]) >= 273. and float(rec["measurement_temp"]) < 323.:
                # between 0 and 50C is room T measurement
                if ("measurement_dc_field" not in list(rec.keys()) or float(rec["measurement_dc_field"]) == 0 or rec["measurement_dc_field"] == "") and ("measurement_ac_field" not in list(rec.keys()) or float(rec["measurement_ac_field"]) == 0 or rec["measurement_ac_field"] == ""):
                    # measurement done in zero field!
                    if "treatment_temp" not in list(rec.keys()) or rec["treatment_temp"].strip() == "" or (float(rec["treatment_temp"]) >= 273. and float(rec["treatment_temp"]) < 298.):
                        # between 0 and 50C is room T treatment
                        if "treatment_ac_field" not in list(rec.keys()) or rec["treatment_ac_field"] == "" or float(rec["treatment_ac_field"]) == 0:
                            # no AF
                            # no IRM!
                            if "treatment_dc_field" not in list(rec.keys()) or rec["treatment_dc_field"] == "" or float(rec["treatment_dc_field"]) == 0:
                                if "LT-NO" not in meths:
                                    meths.append("LT-NO")
                            elif "LT-IRM" not in meths:
                                meths.append("LT-IRM")  # it's an IRM
#
# find AF/infield/zerofield
#
                        # no ARM
                        elif "treatment_dc_field" not in list(rec.keys()) or rec["treatment_dc_field"] == "" or float(rec["treatment_dc_field"]) == 0:
                            if "LT-AF-Z" not in meths:
                                meths.append("LT-AF-Z")
                        else:  # yes ARM
                            if "LT-AF-I" not in meths:
                                meths.append("LT-AF-I")
#
# find Thermal/infield/zerofield
#
                    elif float(rec["treatment_temp"]) >= 323:  # treatment done at  high T
                        if TRM == 1:
                            if "LT-T-I" not in meths:
                                # TRM - even if zero applied field!
                                meths.append("LT-T-I")
                        # no TRM
                        elif "treatment_dc_field" not in list(rec.keys()) or rec["treatment_dc_field"] == "" or float(rec["treatment_dc_field"]) == 0.:
                            if "LT-T-Z" not in meths:
                                # don't overwrite if part of a TRM experiment!
                                meths.append("LT-T-Z")
                        else:  # yes TRM
                            if "LT-T-I" not in meths:
                                meths.append("LT-T-I")
#
# find low-T infield,zero field
#
                    else:  # treatment done at low T
                        # no field
                        if "treatment_dc_field" not in list(rec.keys()) or rec["treatment_dc_field"] == "" or float(rec["treatment_dc_field"]) == 0:
                            if "LT-LT-Z" not in meths:
                                meths.append("LT-LT-Z")
                        else:  # yes field
                            if "LT-LT-I" not in meths:
                                meths.append("LT-LT-I")
                if "measurement_chi_volume" in list(rec.keys()) or "measurement_chi_mass" in list(rec.keys()):
                    if "LP-X" not in meths:
                        meths.append("LP-X")
                # measurement in presence of dc field and not susceptibility;
                # hysteresis!
                elif "measurement_lab_dc_field" in list(rec.keys()) and rec["measurement_lab_dc_field"] != 0:
                    if "LP-HYS" not in meths:
                        hysq = input("Is this a hysteresis experiment? [1]/0")
                        if hysq == "" or hysq == "1":
                            meths.append("LP-HYS")
                        else:
                            metha = input(
                                "Enter the lab protocol code that best describes this experiment ")
                            meths.append(metha)
                methcode = ""
                for meth in meths:
                    methcode = methcode + meth.strip() + ":"
                rec["magic_method_codes"] = methcode[:-1]  # assign them back
#
# done with first pass, collect and assign provisional method codes
            if "measurement_description" not in list(rec.keys()):
                rec["measurement_description"] = ""
            rec["er_citation_names"] = "This study"
            SpecTmps.append(rec)
# ready for second pass through, step through specimens, check whether ptrm, ptrm tail checks, or AARM, etc.
#
    for spec in sids:
        MD, pTRM, IZ, ZI = 0, 0, 0, 0  # these are flags for the lab protocol codes
        expcodes = ""
        NewSpecs, SpecMeths = [], []
        experiment_name, measnum = "", 1
        if IRM3D == 1:
            experiment_name = "LP-IRM-3D"
        if ATRM == 1:
            experiment_name = "LP-AN-TRM"
        if CR == 1:
            experiment_name = "LP-CR"
        NewSpecs = get_dictitem(SpecTmps, 'er_specimen_name', spec, 'T')
#
# first look for replicate measurements
#
        Ninit = len(NewSpecs)
        if noave != 1:
            # averages replicate measurements, returns treatment keys that are
            # being used
            vdata, treatkeys = vspec_magic(NewSpecs)
            if len(vdata) != len(NewSpecs):
                # print spec,'started with ',Ninit,' ending with ',len(vdata)
                NewSpecs = vdata
                # print "Averaged replicate measurements"
#
# now look through this specimen's records - try to figure out what experiment it is
#
        if len(NewSpecs) > 1:  # more than one meas for this spec - part of an unknown experiment
            SpecMeths = get_list(NewSpecs, 'magic_method_codes').split(":")
            # TRM steps, could be TRM acquisition, Shaw or a Thellier
            # experiment or TDS experiment
            if "LT-T-I" in SpecMeths and experiment_name == "":
                #
                # collect all the infield steps and look for changes in dc field vector
                #
                Steps, TI = [], 1
                for rec in NewSpecs:
                    methods = get_list(
                        NewSpecs, 'magic_method_codes').split(":")
                    if "LT-T-I" in methods:
                        Steps.append(rec)  # get all infield steps together
                rec_bak = Steps[0]
                if "treatment_dc_field_phi" in list(rec_bak.keys()) and "treatment_dc_field_theta" in list(rec_bak.keys()):
                    # at least there is field orientation info
                    if rec_bak["treatment_dc_field_phi"] != "" and rec_bak["treatment_dc_field_theta"] != "":
                        phi0, theta0 = rec_bak["treatment_dc_field_phi"], rec_bak["treatment_dc_field_theta"]
                        for k in range(1, len(Steps)):
                            rec = Steps[k]
                            phi, theta = rec["treatment_dc_field_phi"], rec["treatment_dc_field_theta"]
                            if phi != phi0 or theta != theta0:
                                ANIS = 1   # if direction changes, is some sort of anisotropy experiment
                if "LT-AF-I" in SpecMeths and "LT-AF-Z" in SpecMeths:  # must be Shaw :(
                    experiment_name = "LP-PI-TRM:LP-PI-ALT-AFARM"
                elif TRM == 1:
                    experiment_name = "LP-TRM"
            else:
                TI = 0  # no infield steps at all
            if "LT-T-Z" in SpecMeths and experiment_name == "":  # thermal demag steps
                if TI == 0:
                    experiment_name = "LP-DIR-T"  # just ordinary thermal demag
                elif TRM != 1:  # heart pounding - could be some  kind of TRM normalized paleointensity or LP-TRM-TD experiment
                    Temps = []
                    for step in Steps:  # check through the infield steps - if all at same temperature, then must be a demag of a total TRM with checks
                        if step['treatment_temp'] not in Temps:
                            Temps.append(step['treatment_temp'])
                    if len(Temps) > 1:
                        experiment_name = "LP-PI-TRM"  # paleointensity normalized by TRM
                    else:
                        # thermal demag of a lab TRM (could be part of a
                        # LP-PI-TDS experiment)
                        experiment_name = "LP-TRM-TD"
                TZ = 1
            else:
                TZ = 0  # no zero field steps at all
            if "LT-AF-I" in SpecMeths:  # ARM steps
                Steps = []
                for rec in NewSpecs:
                    tmp = rec["magic_method_codes"].split(":")
                    methods = []
                    for meth in tmp:
                        methods.append(meth.strip())
                    if "LT-AF-I" in methods:
                        Steps.append(rec)  # get all infield steps together
                rec_bak = Steps[0]
                if "treatment_dc_field_phi" in list(rec_bak.keys()) and "treatment_dc_field_theta" in list(rec_bak.keys()):
                    # at least there is field orientation info
                    if rec_bak["treatment_dc_field_phi"] != "" and rec_bak["treatment_dc_field_theta"] != "":
                        phi0, theta0 = rec_bak["treatment_dc_field_phi"], rec_bak["treatment_dc_field_theta"]
                        ANIS = 0
                        for k in range(1, len(Steps)):
                            rec = Steps[k]
                            phi, theta = rec["treatment_dc_field_phi"], rec["treatment_dc_field_theta"]
                            if phi != phi0 or theta != theta0:
                                ANIS = 1   # if direction changes, is some sort of anisotropy experiment
                        if ANIS == 1:
                            experiment_name = "LP-AN-ARM"
                if experiment_name == "":  # not anisotropy of ARM - acquisition?
                    field0 = rec_bak["treatment_dc_field"]
                    ARM = 0
                    for k in range(1, len(Steps)):
                        rec = Steps[k]
                        field = rec["treatment_dc_field"]
                        if field != field0:
                            ARM = 1
                    if ARM == 1:
                        experiment_name = "LP-ARM"
                AFI = 1
            else:
                AFI = 0  # no ARM steps at all
            if "LT-AF-Z" in SpecMeths and experiment_name == "":  # AF demag steps
                if AFI == 0:
                    experiment_name = "LP-DIR-AF"  # just ordinary AF demag
                else:  # heart pounding - a pseudothellier?
                    experiment_name = "LP-PI-ARM"
                AFZ = 1
            else:
                AFZ = 0  # no AF demag at all
            if "LT-IRM" in SpecMeths:  # IRM
                Steps = []
                for rec in NewSpecs:
                    tmp = rec["magic_method_codes"].split(":")
                    methods = []
                    for meth in tmp:
                        methods.append(meth.strip())
                    if "LT-IRM" in methods:
                        Steps.append(rec)  # get all infield steps together
                rec_bak = Steps[0]
                if "treatment_dc_field_phi" in list(rec_bak.keys()) and "treatment_dc_field_theta" in list(rec_bak.keys()):
                    # at least there is field orientation info
                    if rec_bak["treatment_dc_field_phi"] != "" and rec_bak["treatment_dc_field_theta"] != "":
                        phi0, theta0 = rec_bak["treatment_dc_field_phi"], rec_bak["treatment_dc_field_theta"]
                        ANIS = 0
                        for k in range(1, len(Steps)):
                            rec = Steps[k]
                            phi, theta = rec["treatment_dc_field_phi"], rec["treatment_dc_field_theta"]
                            if phi != phi0 or theta != theta0:
                                ANIS = 1   # if direction changes, is some sort of anisotropy experiment
                        if ANIS == 1:
                            experiment_name = "LP-AN-IRM"
                if experiment_name == "":  # not anisotropy of IRM - acquisition?
                    field0 = rec_bak["treatment_dc_field"]
                    IRM = 0
                    for k in range(1, len(Steps)):
                        rec = Steps[k]
                        field = rec["treatment_dc_field"]
                        if field != field0:
                            IRM = 1
                    if IRM == 1:
                        experiment_name = "LP-IRM"
                IRM = 1
            else:
                IRM = 0  # no IRM at all
            if "LP-X" in SpecMeths:  # susceptibility run
                Steps = get_dictitem(
                    NewSpecs, 'magic_method_codes', 'LT-X', 'has')
                if len(Steps) > 0:
                    rec_bak = Steps[0]
                    if "treatment_dc_field_phi" in list(rec_bak.keys()) and "treatment_dc_field_theta" in list(rec_bak.keys()):
                        # at least there is field orientation info
                        if rec_bak["treatment_dc_field_phi"] != "" and rec_bak["treatment_dc_field_theta"] != "":
                            phi0, theta0 = rec_bak["treatment_dc_field_phi"], rec_bak["treatment_dc_field_theta"]
                            ANIS = 0
                            for k in range(1, len(Steps)):
                                rec = Steps[k]
                                phi, theta = rec["treatment_dc_field_phi"], rec["treatment_dc_field_theta"]
                                if phi != phi0 or theta != theta0:
                                    ANIS = 1   # if direction changes, is some sort of anisotropy experiment
                            if ANIS == 1:
                                experiment_name = "LP-AN-MS"
            else:
                CHI = 0  # no susceptibility at all
    #
    # now need to deal with special thellier experiment problems - first clear up pTRM checks and  tail checks
    #
            if experiment_name == "LP-PI-TRM":  # is some sort of thellier experiment
                rec_bak = NewSpecs[0]
                tmp = rec_bak["magic_method_codes"].split(":")
                methbak = []
                for meth in tmp:
                    methbak.append(meth.strip())  # previous steps method codes
                for k in range(1, len(NewSpecs)):
                    rec = NewSpecs[k]
                    tmp = rec["magic_method_codes"].split(":")
                    meths = []
                    for meth in tmp:
                        # get this guys method codes
                        meths.append(meth.strip())
    #
    # check if this is a pTRM check
    #
                    if float(rec["treatment_temp"]) < float(rec_bak["treatment_temp"]):  # went backward
                        if "LT-T-I" in meths and "LT-T-Z" in methbak:  # must be a pTRM check after first z
                            #
                            # replace LT-T-I method code with LT-PTRM-I
                            #
                            methcodes = ""
                            for meth in meths:
                                if meth != "LT-T-I":
                                    methcode = methcode + meth.strip() + ":"
                            methcodes = methcodes + "LT-PTRM-I"
                            meths = methcodes.split(":")
                            pTRM = 1
                        elif "LT-T-Z" in meths and "LT-T-I" in methbak:  # must be pTRM check after first I
                            #
                            # replace LT-T-Z method code with LT-PTRM-Z
                            #
                            methcodes = ""
                            for meth in meths:
                                if meth != "LT-T-Z":
                                    methcode = methcode + meth + ":"
                            methcodes = methcodes + "LT-PTRM-Z"
                            meths = methcodes.split(":")
                            pTRM = 1
                    methcodes = ""
                    for meth in meths:
                        methcodes = methcodes + meth.strip() + ":"
                    # attach new method code
                    rec["magic_method_codes"] = methcodes[:-1]
                    rec_bak = rec  # next previous record
                    tmp = rec_bak["magic_method_codes"].split(":")
                    methbak = []
                    for meth in tmp:
                        # previous steps method codes
                        methbak.append(meth.strip())
    #
    # done with assigning pTRM checks.  data should be "fixed" in NewSpecs
    #
    # now let's find out which steps are infield zerofield (IZ) and which are zerofield infield (ZI)
    #
                rec_bak = NewSpecs[0]
                tmp = rec_bak["magic_method_codes"].split(":")
                methbak = []
                for meth in tmp:
                    methbak.append(meth.strip())  # previous steps method codes
                if "LT-NO" not in methbak:  # first measurement is not NRM
                    if "LT-T-I" in methbak:
                        IZorZI = "LP-PI-TRM-IZ"  # first pair is IZ
                    if "LT-T-Z" in methbak:
                        IZorZI = "LP-PI-TRM-ZI"  # first pair is ZI
                    if IZorZI not in methbak:
                        methbak.append(IZorZI)
                    methcode = ""
                    for meth in methbak:
                        methcode = methcode + meth + ":"
                    # fix first heating step when no NRM
                    NewSpecs[0]["magic_method_codes"] = methcode[:-1]
                else:
                    IZorZI = ""  # first measurement is NRM and not one of a pair
                for k in range(1, len(NewSpecs)):  # hunt through measurements again
                    rec = NewSpecs[k]
                    tmp = rec["magic_method_codes"].split(":")
                    meths = []
                    for meth in tmp:
                        # get this guys method codes
                        meths.append(meth.strip())
    #
    # check if this start a new temperature step of a infield/zerofield pair
    #
                    if float(rec["treatment_temp"]) > float(rec_bak["treatment_temp"]) and "LT-PTRM-I" not in methbak:  # new pair?
                        if "LT-T-I" in meths:  # infield of this pair
                            IZorZI = "LP-PI-TRM-IZ"
                            IZ = 1  # at least one IZ pair
                        elif "LT-T-Z" in meths:  # zerofield
                            IZorZI = "LP-PI-TRM-ZI"
                            ZI = 1  # at least one ZI pair
                    # new pair after out of sequence PTRM check?
                    elif float(rec["treatment_temp"]) > float(rec_bak["treatment_temp"]) and "LT-PTRM-I" in methbak and IZorZI != "LP-PI-TRM-ZI":
                        if "LT-T-I" in meths:  # infield of this pair
                            IZorZI = "LP-PI-TRM-IZ"
                            IZ = 1  # at least one IZ pair
                        elif "LT-T-Z" in meths:  # zerofield
                            IZorZI = "LP-PI-TRM-ZI"
                            ZI = 1  # at least one ZI pair
                    # stayed same temp
                    if float(rec["treatment_temp"]) == float(rec_bak["treatment_temp"]):
                        if "LT-T-Z" in meths and "LT-T-I" in methbak and IZorZI == "LP-PI-TRM-ZI":  # must be a tail check
                            #
                            # replace LT-T-Z method code with LT-PTRM-MD
                            #
                            methcodes = ""
                            for meth in meths:
                                if meth != "LT-T-Z":
                                    methcode = methcode + meth + ":"
                            methcodes = methcodes + "LT-PTRM-MD"
                            meths = methcodes.split(":")
                            MD = 1
    # fix method codes
                    if "LT-PTRM-I" not in meths and "LT-PTRM-MD" not in meths and IZorZI not in meths:
                        meths.append(IZorZI)
                    newmeths = []
                    for meth in meths:
                        if meth not in newmeths:
                            newmeths.append(meth)  # try to get uniq set
                    methcode = ""
                    for meth in newmeths:
                        methcode = methcode + meth + ":"
                    rec["magic_method_codes"] = methcode[:-1]
                    rec_bak = rec  # moving on to next record, making current one the backup
                    # get last specimen's method codes in a list
                    methbak = rec_bak["magic_method_codes"].split(":")

    #
    # done with this specimen's records, now  check if any pTRM checks or MD checks
    #
                if pTRM == 1:
                    experiment_name = experiment_name + ":LP-PI-ALT-PTRM"
                if MD == 1:
                    experiment_name = experiment_name + ":LP-PI-BT-MD"
                if IZ == 1 and ZI == 1:
                    experiment_name = experiment_name + ":LP-PI-BT-IZZI"
                if IZ == 1 and ZI == 0:
                    experiment_name = experiment_name + ":LP-PI-IZ"  # Aitken method
                if IZ == 0 and ZI == 1:
                    experiment_name = experiment_name + ":LP-PI-ZI"  # Coe method
                IZ, ZI, pTRM, MD = 0, 0, 0, 0  # reset these for next specimen
                for rec in NewSpecs:  # fix the experiment name for all recs for this specimen and save in SpecOuts
                    # assign an experiment name to all specimen measurements
                    # from this specimen
                    if experiment_name != "":
                        rec["magic_method_codes"] = rec["magic_method_codes"] + \
                            ":" + experiment_name
                    rec["magic_experiment_name"] = spec + ":" + experiment_name
                    rec['measurement_number'] = '%i' % (
                        measnum)  # assign measurement numbers
                    measnum += 1
                    #rec['sequence'] = '%i'%(seqnum)
                    #seqnum += 1
                    SpecOuts.append(rec)
            elif experiment_name == "LP-PI-TRM:LP-PI-ALT-AFARM":  # is a Shaw experiment!
                ARM, TRM = 0, 0
                for rec in NewSpecs:  # fix the experiment name for all recs for this specimen and save in SpecOuts
                    # assign an experiment name to all specimen measurements from this specimen
                    # make the second ARM in Shaw experiments LT-AF-I-2, stick
                    # in the AF of ARM and TRM codes
                    meths = rec["magic_method_codes"].split(":")
                    if ARM == 1:
                        if "LT-AF-I" in meths:
                            del meths[meths.index("LT-AF-I")]
                            meths.append("LT-AF-I-2")
                            ARM = 2
                        if "LT-AF-Z" in meths and TRM == 0:
                            meths.append("LP-ARM-AFD")
                    if TRM == 1 and ARM == 1:
                        if "LT-AF-Z" in meths:
                            meths.append("LP-TRM-AFD")
                    if ARM == 2:
                        if "LT-AF-Z" in meths:
                            meths.append("LP-ARM2-AFD")
                    newcode = ""
                    for meth in meths:
                        newcode = newcode + meth + ":"
                    rec["magic_method_codes"] = newcode[:-1]
                    if "LT-AF-I" in meths:
                        ARM = 1
                    if "LT-T-I" in meths:
                        TRM = 1
                    rec["magic_method_codes"] = rec["magic_method_codes"] + \
                        ":" + experiment_name
                    rec["magic_experiment_name"] = spec + ":" + experiment_name
                    rec['measurement_number'] = '%i' % (
                        measnum)  # assign measurement numbers
                    #rec['sequence'] = '%i'%(seqnum)
                    #seqnum += 1
                    measnum += 1
                    SpecOuts.append(rec)
            else:  # not a Thellier-Thellier  or a Shaw experiemnt
                for rec in NewSpecs:
                    if experiment_name == "":
                        rec["magic_method_codes"] = "LT-NO"
                        rec["magic_experiment_name"] = spec + ":LT-NO"
                        rec['measurement_number'] = '%i' % (
                            measnum)  # assign measurement numbers
                        #rec['sequence'] = '%i'%(seqnum)
                        #seqnum += 1
                        measnum += 1
                    else:
                        if experiment_name not in rec['magic_method_codes']:
                            rec["magic_method_codes"] = rec["magic_method_codes"] + \
                                ":" + experiment_name
                            rec["magic_method_codes"] = rec["magic_method_codes"].strip(
                                ':')
                        rec['measurement_number'] = '%i' % (
                            measnum)  # assign measurement numbers
                        #rec['sequence'] = '%i'%(seqnum)
                        #seqnum += 1
                        measnum += 1
                        rec["magic_experiment_name"] = spec + \
                            ":" + experiment_name
                    rec["magic_software_packages"] = version_num
                    SpecOuts.append(rec)
        else:
            NewSpecs[0]["magic_experiment_name"] = spec + ":" + \
                NewSpecs[0]['magic_method_codes'].split(':')[0]
            NewSpecs[0]["magic_software_packages"] = version_num
            # just copy over the single record as is
            SpecOuts.append(NewSpecs[0])
    return SpecOuts

Response: get list of unique methods for this specimen


Instruction:
Can you tell what is the following Python 3 function doing
def parse_site(sample, convention, Z):
    convention = str(convention)
    site = sample  # default is that site = sample
#
#
# Sample is final letter on site designation eg:  TG001a (used by SIO lab
# in San Diego)
    if convention == "1":
        return sample[:-1]  # peel off terminal character
#
# Site-Sample format eg:  BG94-1  (used by PGL lab in Beijing)
#
    if convention == "2":
        parts = sample.strip('-').split('-')
        return parts[0]
#
# Sample is XXXX.YY where XXX is site and YY is sample
#
    if convention == "3":
        parts = sample.split('.')
        return parts[0]
#
# Sample is XXXXYYY where XXX is site desgnation and YYY is Z long integer
#
    if convention == "4":
        k = int(Z) - 1
        return sample[0:-k]  # peel off Z characters from site

    if convention == "5":  # sample == site
        return sample

    if convention == "6":  # should be names in orient.txt
        print("-W- Finding names in orient.txt is not currently supported")

    if convention == "7":  # peel off Z characters for site
        k = int(Z)
        return sample[0:k]

    if convention == "8":  # peel off Z characters for site
        return ""

    if convention == "9":  # peel off Z characters for site
        return sample

    print("Error in site parsing routine")
    return

Response: parse the site name from the sample name using the specified convention


Instruction:
How would you explain what the following Python 3 function does
def get_samp_con():
#
    samp_con, Z = "", ""
    while samp_con == "":
        samp_con = input("""
        Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail ltauxe@ucsd.edu for help.
            select one:
""")
    #
        if samp_con == "" or samp_con == "1":
            samp_con, Z = "1", 1
        if "4" in samp_con:
            if "-" not in samp_con:
                print("option [4] must be in form 4-Z where Z is an integer")
                samp_con = ""
            else:
                Z = samp_con.split("-")[1]
                samp_con = "4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print("option [7] must be in form 7-Z where Z is an integer")
                samp_con = ""
            else:
                Z = samp_con.split("-")[1]
                samp_con = "7"
        if samp_con.isdigit() == False or int(samp_con) > 7:
            print("Try again\n ")
            samp_con = ""
    return samp_con, Z

Response: get sample naming convention


Instruction:
Write a Python 3 script to
function to return the dip direction and dip that would yield the tilt corrected direction if applied to the uncorrected direction

Response:
def get_tilt(dec_geo, inc_geo, dec_tilt, inc_tilt):
    """
    Function to return the dip direction and dip that would yield the tilt
    corrected direction if applied to the uncorrected direction (geographic
    coordinates)

    Parameters
    ----------
    dec_geo : declination in geographic coordinates
    inc_geo : inclination in geographic coordinates
    dec_tilt : declination in tilt-corrected coordinates
    inc_tilt : inclination in tilt-corrected coordinates

    Returns
    -------
    DipDir, Dip : tuple of dip direction and dip
    """
# strike is horizontal line equidistant from two input directions
    SCart = [0, 0, 0]  # cartesian coordites of Strike
    SCart[2] = 0.  # by definition
    # cartesian coordites of Geographic D
    GCart = dir2cart([dec_geo, inc_geo, 1.])
    TCart = dir2cart([dec_tilt, inc_tilt, 1.])  # cartesian coordites of Tilt D
    X = old_div((TCart[1] - GCart[1]), (GCart[0] - TCart[0]))
    SCart[1] = np.sqrt(old_div(1, (X**2 + 1.)))
    SCart[0] = SCart[1] * X
    SDir = cart2dir(SCart)
    DipDir = (SDir[0] - 90.) % 360.
    DipDir = (SDir[0] + 90.) % 360.
# D is creat circle distance between geo direction and strike
# theta is GCD between geo and tilt (on unit sphere).  use law of cosines
# to get small cirlce between geo and tilt (dip)
    cosd = GCart[0] * SCart[0] + GCart[1] * \
        SCart[1]  # cosine of angle between two
    d = np.arccos(cosd)
    cosTheta = GCart[0] * TCart[0] + GCart[1] * TCart[1] + GCart[2] * TCart[2]
    Dip = (old_div(180., np.pi)) * \
        np.arccos(-(old_div((cosd**2 - cosTheta), np.sin(d)**2)))
    if Dip > 90:
        Dip = -Dip
    return DipDir, Dip


Instruction:
Write a Python 3 function for
getting azimuth and pl from specimen dec inc gdec ginc

Response:
def get_azpl(cdec, cinc, gdec, ginc):
    """
     gets azimuth and pl from specimen dec inc (cdec,cinc) and gdec,ginc (geographic)  coordinates
    """
    TOL = 1e-4
    rad = old_div(np.pi, 180.)
    Xp = dir2cart([gdec, ginc, 1.])
    X = dir2cart([cdec, cinc, 1.])
    # find plunge first
    az, pl, zdif, ang = 0., -90., 1., 360.
    while zdif > TOL and pl < 180.:
        znew = X[0] * np.sin(pl * rad) + X[2] * np.cos(pl * rad)
        zdif = abs(Xp[2] - znew)
        pl += .01

    while ang > 0.1 and az < 360.:
        d, i = dogeo(cdec, cinc, az, pl)
        ang = angle([gdec, ginc], [d, i])
        az += .01
    return az - .01, pl - .01


Instruction:
Can you write a function in Python 3 where it
sets the priorities of the given methods

Response:
def set_priorities(SO_methods, ask):
    """
     figure out which sample_azimuth to use, if multiple orientation methods
    """
    # if ask set to 1, then can change priorities
    SO_methods = [meth.strip() for meth in SO_methods]
    SO_defaults = ['SO-SUN', 'SO-GPS-DIFF', 'SO-SUN-SIGHT', 'SO-SIGHT', 'SO-SIGHT-BS',
                   'SO-CMD-NORTH', 'SO-MAG', 'SO-SM', 'SO-REC', 'SO-V', 'SO-CORE', 'SO-NO']
    SO_priorities, prior_list = [], []
    if len(SO_methods) >= 1:
        for l in range(len(SO_defaults)):
            if SO_defaults[l] in SO_methods:
                SO_priorities.append(SO_defaults[l])
    pri, change = 0, "1"
    if ask == 1:
        print("""These methods of sample orientation were found:
      They have been assigned a provisional priority (top = zero, last = highest number) """)
        for m in range(len(SO_defaults)):
            if SO_defaults[m] in SO_methods:
                SO_priorities[SO_methods.index(SO_defaults[m])] = pri
                pri += 1
        while change == "1":
            prior_list = SO_priorities
            for m in range(len(SO_methods)):
                print(SO_methods[m], SO_priorities[m])
            change = input("Change these?  1/[0] ")
            if change != "1":
                break
        SO_priorities = []
        for l in range(len(SO_methods)):
            print(SO_methods[l])
            print(" Priority?   ", prior_list)
            pri = int(input())
            SO_priorities.append(pri)
            del prior_list[prior_list.index(pri)]
    return SO_priorities


Instruction:
Implement a function in Python 3 to
find EOL of input file

Response:
def get_EOL(file):
    """
     find EOL of input file (whether mac,PC or unix format)
    """
    f = open(file, 'r')
    firstline = f.read(350)
    EOL = ""
    for k in range(350):
        if firstline[k:k + 2] == "\r\n":
            print(file, ' appears to be a dos file')
            EOL = '\r\n'
            break
    if EOL == "":
        for k in range(350):
            if firstline[k] == "\r":
                print(file, ' appears to be a mac file')
                EOL = '\r'
    if EOL == "":
        print(file, " appears to be a  unix file")
        EOL = '\n'
    f.close()
    return EOL


Instruction:
Explain what the following Python 3 code does
def sortshaw(s, datablock):
    for rec in datablock:
        methcodes = rec["magic_method_codes"].split(":")
        step = float(rec["treatment_ac_field"])
        str = float(rec["measurement_magn_moment"])
        if "LT-NO" in methcodes:
            NRM.append([0, str])
        if "LT-T-I" in methcodes:
            TRM.append([0, str])
            field = float(rec["treatment_dc_field"])
        if "LT-AF-I" in methcodes:
            ARM1.append([0, str])
        if "LT-AF-I-2" in methcodes:
            ARM2.append([0, str])
        if "LT-AF-Z" in methcodes:
            if "LP-ARM-AFD" in methcodes:
                ARM1.append([step, str])
            elif "LP-TRM-AFD" in methcodes:
                TRM.append([step, str])
            elif "LP-ARM2-AFD" in methcodes:
                ARM2.append([step, str])
            else:
                NRM.append([step, str])
    cont = 1
    while cont == 1:
        if len(NRM) != len(TRM):
            print("Uneven NRM/TRM steps: ")
            NRM, TRM, cont = cleanup(TRM, NRM)
        else:
            cont = 0
    cont = 1
    while cont == 1:
        if len(ARM1) != len(ARM2):
            print("Uneven ARM1/ARM2 steps: ")
            ARM1, ARM2, cont = cleanup(ARM2, ARM1)
        else:
            cont = 0
#
# final check
#
    if len(NRM) != len(TRM) or len(ARM1) != len(ARM2):
        print(len(NRM), len(TRM), len(ARM1), len(ARM2))
        print(" Something wrong with this specimen! Better fix it or delete it ")
        input(" press return to acknowledge message")
# now do the ratio to "fix" NRM/TRM data
# a
    TRM_ADJ = []
    for kk in range(len(TRM)):
        step = TRM[kk][0]
        for k in range(len(ARM1)):
            if ARM1[k][0] == step:
                TRM_ADJ.append([step, TRM[kk][1] * ARM1[k][1] / ARM2[k][1]])
                break
    shawblock = (NRM, TRM, ARM1, ARM2, TRM_ADJ)
    return shawblock, field

Response: Sort data block in to ARM1 ARM2 NRM TRM and ARM1 and ARM2.


Instruction:
How would you code a function in Python 3 to
evaluate the vector at a given latitude and longitude for a specified .

Response:
def getvec(gh, lat, lon):
    """
    Evaluates the vector at a given latitude and longitude for a specified
    set of coefficients

    Parameters
    ----------
    gh : a list of gauss coefficients
    lat : latitude of location
    long : longitude of location

    Returns
    -------
    vec : direction in [dec, inc, intensity]
    """
    sv = []
    pad = 120 - len(gh)
    for x in range(pad):
        gh.append(0.)
    for x in range(len(gh)):
        sv.append(0.)
#! convert to colatitude for MB routine
    itype = 1
    colat = 90. - lat
    date, alt = 2000., 0.  # use a dummy date and altitude
    x, y, z, f = magsyn(gh, sv, date, date, itype, alt, colat, lon)
    vec = cart2dir([x, y, z])
    vec[2] = f
    return vec


Instruction:
Can you implement a function in Python 3 that
gets sigma as a function of degree l from Constable and Parker 1988

Response:
def s_l(l, alpha):
    """
    get sigma as a function of degree l from Constable and Parker (1988)
    """
    a2 = alpha**2
    c_a = 0.547
    s_l = np.sqrt(old_div(((c_a**(2. * l)) * a2), ((l + 1.) * (2. * l + 1.))))
    return s_l


Instruction:
Given the following Python 3 function, write the documentation
def mktk03(terms, seed, G2, G3):
# random.seed(n)
    p = 0
    n = seed
    gh = []
    g10, sfact, afact = -18e3, 3.8, 2.4
    g20 = G2 * g10
    g30 = G3 * g10
    alpha = g10/afact
    s1 = s_l(1, alpha)
    s10 = sfact * s1
    gnew = random.normal(g10, s10)
    if p == 1:
        print(1, 0, gnew, 0)
    gh.append(gnew)
    gh.append(random.normal(0, s1))
    gnew = gh[-1]
    gh.append(random.normal(0, s1))
    hnew = gh[-1]
    if p == 1:
        print(1, 1, gnew, hnew)
    for l in range(2, terms + 1):
        for m in range(l + 1):
            OFF = 0.0
            if l == 2 and m == 0:
                OFF = g20
            if l == 3 and m == 0:
                OFF = g30
            s = s_l(l, alpha)
            j = (l - m) % 2
            if j == 1:
                s = s * sfact
            gh.append(random.normal(OFF, s))
            gnew = gh[-1]
            if m == 0:
                hnew = 0
            else:
                gh.append(random.normal(0, s))
                hnew = gh[-1]
            if p == 1:
                print(l, m, gnew, hnew)
    return gh

Response: Generates a list of gauss coefficients drawn from the TK03 distribution.


Instruction:
Write a Python 3 function for
calculating paleoinclination from latitude using dipole formula

Response:
def pinc(lat):
    """
    calculate paleoinclination from latitude using dipole formula: tan(I) = 2tan(lat)
    Parameters
    ________________

    lat : either a single value or an array of latitudes

    Returns
    -------

    array of inclinations
    """
    tanl = np.tan(np.radians(lat))
    inc = np.arctan(2. * tanl)
    return np.degrees(inc)


Instruction:
Implement a function in Python 3 to
calculate paleolatitude from inclination using dipole formula

Response:
def plat(inc):
    """
    calculate paleolatitude from inclination using dipole formula: tan(I) = 2tan(lat)
    Parameters
    ________________

    inc : either a single value or an array of inclinations

    Returns
    -------

    array of latitudes
    """
    tani = np.tan(np.radians(inc))
    lat = np.arctan(tani/2.)
    return np.degrees(lat)


Instruction:
Make a summary of the following Python 3 code
def pseudo(DIs, random_seed=None):
    if random_seed != None:
        np.random.seed(random_seed)
    Inds = np.random.randint(len(DIs), size=len(DIs))
    D = np.array(DIs)
    return D[Inds]

Response: Draw a bootstrap sample of directions returning as many bootstrapped samples as in the input directions


Instruction:
Implement a function in Python 3 to
return bootstrap means for Directional data Parameters _________________ DIs : nested list of Dec,Inc pairs nb : number of bootstrap pseudosamples Returns ------- BDIs: nested list of bootstrapped mean Dec,Inc pairs

Response:
def di_boot(DIs, nb=5000):
    """
     returns bootstrap means  for Directional data
     Parameters
     _________________
     DIs : nested list of Dec,Inc pairs
     nb : number of bootstrap pseudosamples

     Returns
    -------
     BDIs:   nested list of bootstrapped mean Dec,Inc pairs
    """
#
# now do bootstrap to collect BDIs  bootstrap means
#
    BDIs = []  # number of bootstraps, list of bootstrap directions
#

    for k in range(nb):  # repeat nb times
        #        if k%50==0:print k,' out of ',nb
        pDIs = pseudo(DIs)  # get a pseudosample
        bfpars = fisher_mean(pDIs)  # get bootstrap mean bootstrap sample
        BDIs.append([bfpars['dec'], bfpars['inc']])
    return BDIs


Instruction:
Can you generate a brief explanation for the following Python 3 code
def dir_df_boot(dir_df, nb=5000, par=False):
    N = dir_df.dir_dec.values.shape[0]  # number of data points
    BDIs = []
    for k in range(nb):
        pdir_df = dir_df.sample(n=N, replace=True)  # bootstrap pseudosample
        pdir_df.reset_index(inplace=True)  # reset the index
        if par:  # do a parametric bootstrap
            for i in pdir_df.index:  # set through the pseudosample
                n = pdir_df.loc[i, 'dir_n']  # get number of samples/site
                # get ks for each sample
                ks = np.ones(shape=n)*pdir_df.loc[i, 'dir_k']
                # draw a fisher distributed set of directions
                decs, incs = fshdev(ks)
                di_block = np.column_stack((decs, incs))
                #  rotate them to the mean
                di_block = dodirot_V(
                    di_block, pdir_df.loc[i, 'dir_dec'], pdir_df.loc[i, 'dir_inc'])
                # get the new mean direction for the pseudosample
                fpars = fisher_mean(di_block)
                # replace the pseudo sample mean direction
                pdir_df.loc[i, 'dir_dec'] = fpars['dec']
                pdir_df.loc[i, 'dir_inc'] = fpars['inc']
        # get bootstrap mean bootstrap sample
        bfpars = dir_df_fisher_mean(pdir_df)
        BDIs.append([bfpars['dec'], bfpars['inc']])
    return BDIs

Response: This function is used to bootstrap the direction DataFrame with optional parametric bootstraps.


Instruction:
Explain what the following Python 3 code does
def dir_df_fisher_mean(dir_df):
    N = dir_df.dir_dec.values.shape[0]  # number of data points
    fpars = {}
    if N < 2:
        return fpars
    dirs = dir_df[['dir_dec', 'dir_inc']].values
    X = dir2cart(dirs).transpose()
    Xbar = np.array([X[0].sum(), X[1].sum(), X[2].sum()])
    R = np.sqrt(Xbar[0]**2+Xbar[1]**2+Xbar[2]**2)
    Xbar = Xbar/R
    dir = cart2dir(Xbar)
    fpars["dec"] = dir[0]
    fpars["inc"] = dir[1]
    fpars["n"] = N
    fpars["r"] = R
    if N != R:
        k = (N - 1.) / (N - R)
        fpars["k"] = k
        csd = 81./np.sqrt(k)
    else:
        fpars['k'] = 'inf'
        csd = 0.
    b = 20.**(1./(N - 1.)) - 1
    a = 1 - b * (N - R) / R
    if a < -1:
        a = -1
    a95 = np.degrees(np.arccos(a))
    fpars["alpha95"] = a95
    fpars["csd"] = csd
    if a < 0:
        fpars["alpha95"] = 180.0
    return fpars

Response: Calculates the fisher mean for Pandas data frame dir_df


Instruction:
Make a summary of the following Python 3 code
def pseudosample(x):
#
    BXs = []
    for k in range(len(x)):
        ind = random.randint(0, len(x) - 1)
        BXs.append(x[ind])
    return BXs

Response: draw a bootstrap sample of x


Instruction:
Here you have a function in Python 3, explain what it does
def bc02(data):

    plate, site_lat, site_lon, age = data[0], data[1], data[2], data[3]
    apwp = get_plate_data(plate)
    recs = apwp.split()
    #
    # put it into  usable form in plate_data
    #
    k, plate_data = 0, []
    while k < len(recs) - 3:
        rec = [float(recs[k]), float(recs[k + 1]), float(recs[k + 2])]
        plate_data.append(rec)
        k = k + 3

    #
    # find the right pole for the age
    #
    for i in range(len(plate_data)):
        if age >= plate_data[i][0] and age <= plate_data[i + 1][0]:
            if (age - plate_data[i][0]) < (plate_data[i][0] - age):
                rec = i
            else:
                rec = i + 1
            break
    pole_lat = plate_data[rec][1]
    pole_lon = plate_data[rec][2]
    return pole_lat, pole_lon

Response: This function is used to get the APWP from Besse and Courtillot 2002 paper from Besse and Courtillot 2002 paper from 2002.


Instruction:
Write a Python 3 function that can
do a linear regression

Response:
def linreg(x, y):
    """
    does a linear regression
    """
    if len(x) != len(y):
        print('x and y must be same length')
        return
    xx, yy, xsum, ysum, xy, n, sum = 0, 0, 0, 0, 0, len(x), 0
    linpars = {}
    for i in range(n):
        xx += x[i] * x[i]
        yy += y[i] * y[i]
        xy += x[i] * y[i]
        xsum += x[i]
        ysum += y[i]
        xsig = np.sqrt(old_div((xx - old_div(xsum**2, n)), (n - 1.)))
        ysig = np.sqrt(old_div((yy - old_div(ysum**2, n)), (n - 1.)))
    linpars['slope'] = old_div(
        (xy - (xsum * ysum / n)), (xx - old_div((xsum**2), n)))
    linpars['b'] = old_div((ysum - linpars['slope'] * xsum), n)
    linpars['r'] = old_div((linpars['slope'] * xsig), ysig)
    for i in range(n):
        a = y[i] - linpars['b'] - linpars['slope'] * x[i]
        sum += a
    linpars['sigma'] = old_div(sum, (n - 2.))
    linpars['n'] = n
    return linpars


Instruction:
Can you write a function in Python 3 where it
returns 'flattened' inclination, assuming factor, f and King (1955) formula: tan (I_o) = f tan (I_f) Parameters __________ incs : array of inclination (I_f) data to flatten f : flattening factor Returns _______ I_o : inclinations after flattening

Response:
def squish(incs, f):
    """
    returns 'flattened' inclination, assuming factor, f and King (1955) formula:
    tan (I_o) = f tan (I_f)

    Parameters
    __________
    incs : array of inclination (I_f)  data to flatten
    f : flattening factor

    Returns
    _______
    I_o :  inclinations after flattening
    """
    incs = np.radians(incs)
    I_o = f * np.tan(incs)  # multiply tangent by flattening factor
    return np.degrees(np.arctan(I_o))


Instruction:
Write a Python 3 function for
returning a list of GPTS timescales and Chron labels for the given time period.

Response:
def get_ts(ts):
    """
    returns GPTS timescales.
    options are:  ck95, gts04, and gts12
    returns timescales and Chron labels
    """
    if ts == 'ck95':
        TS = [0, 0.780, 0.990, 1.070, 1.770, 1.950, 2.140, 2.150, 2.581, 3.040, 3.110, 3.220, 3.330, 3.580, 4.180, 4.290, 4.480, 4.620, 4.800, 4.890, 4.980, 5.230, 5.894, 6.137, 6.269, 6.567, 6.935, 7.091, 7.135, 7.170, 7.341, 7.375, 7.432, 7.562, 7.650, 8.072, 8.225, 8.257, 8.699, 9.025, 9.230, 9.308, 9.580, 9.642, 9.740, 9.880, 9.920, 10.949, 11.052, 11.099, 11.476, 11.531, 11.935, 12.078, 12.184, 12.401, 12.678, 12.708, 12.775, 12.819, 12.991, 13.139, 13.302, 13.510, 13.703, 14.076, 14.178, 14.612, 14.800, 14.888, 15.034, 15.155, 16.014, 16.293, 16.327, 16.488, 16.556, 16.726, 17.277, 17.615, 18.281, 18.781, 19.048, 20.131, 20.518, 20.725, 20.996, 21.320, 21.768, 21.859, 22.151, 22.248, 22.459, 22.493, 22.588,
              22.750, 22.804, 23.069, 23.353, 23.535, 23.677, 23.800, 23.999, 24.118, 24.730, 24.781, 24.835, 25.183, 25.496, 25.648, 25.823, 25.951, 25.992, 26.554, 27.027, 27.972, 28.283, 28.512, 28.578, 28.745, 29.401, 29.662, 29.765, 30.098, 30.479, 30.939, 33.058, 33.545, 34.655, 34.940, 35.343, 35.526, 35.685, 36.341, 36.618, 37.473, 37.604, 37.848, 37.920, 38.113, 38.426, 39.552, 39.631, 40.130, 41.257, 41.521, 42.536, 43.789, 46.264, 47.906, 49.037, 49.714, 50.778, 50.946, 51.047, 51.743, 52.364, 52.663, 52.757, 52.801, 52.903, 53.347, 55.904, 56.391, 57.554, 57.911, 60.920, 61.276, 62.499, 63.634, 63.976, 64.745, 65.578, 67.610, 67.735, 68.737, 71.071, 71.338, 71.587, 73.004, 73.291, 73.374, 73.619, 79.075, 83.000]
        Labels = [['C1n', 0], ['C1r', 0.78], ['C2', 1.77], ['C2An', 2.581], ['C2Ar', 3.58], ['C3n', 4.18], ['C3r', 5.23], ['C3An', 5.894], ['C3Ar', 6.567], ['C3Bn', 6.935], ['C3Br', 7.091], ['C4n', 7.432], ['C4r', 8.072], ['C4An', 8.699], ['C4Ar', 9.025], ['C5n', 9.74], ['C5r', 10.949], ['C5An', 11.935], ['C5Ar', 12.401], ['C5AAn', 12.991], ['C5AAr', 13.139], ['C5ABn', 13.302], ['C5ABr', 13.51], ['C5ACn', 13.703], ['C5ACr', 14.076], ['C5ADn', 14.178], ['C5ADr', 14.612], ['C5Bn', 14.8], ['C5Br', 15.155], ['C5Cn', 16.014], ['C5Cr', 16.726], ['C5Dn', 17.277], ['C5Dr', 17.615], ['C5En', 18.281], ['C5Er', 18.781], ['C6n', 19.048], ['C6r', 20.131], ['C6An', 20.518], ['C6Ar', 21.32], ['C6AAn', 21.768], ['C6AAr', 21.859], ['C6Bn', 22.588], ['C6Br', 23.069], ['C6Cn', 23.353], ['C6Cr', 24.118], ['C7n', 24.73], ['C7r', 25.183], ['C7A', 25.496], ['C8n', 25.823], ['C8r', 26.554], [
            'C9n', 27.027], ['C9r', 27.972], ['C10n', 28.283], ['C10r', 28.745], ['C11n', 29.401], ['C11r', 30.098], ['C12n', 30.479], ['C12r', 30.939], ['C13n', 33.058], ['C13r', 33.545], ['C15n', 34.655], ['C15r', 34.94], ['C16n', 35.343], ['C16r', 36.341], ['C17n', 36.618], ['C17r', 38.113], ['C18n', 38.426], ['C18r', 40.13], ['C19n', 41.257], ['C19r', 41.521], ['C20n', 42.536], ['C20r', 43.789], ['C21n', 46.264], ['C21r', 47.906], ['C22n', 49.037], ['C22r', 49.714], ['C23n', 50.778], ['C23r', 51.743], ['C24n', 52.364], ['C24r', 53.347], ['C25n', 55.904], ['C25r', 56.391], ['C26n', 57.554], ['C26r', 57.911], ['C27n', 60.92], ['C27r', 61.276], ['C28n', 62.499], ['C28r', 63.634], ['C29n', 63.976], ['C29r', 64.745], ['C30n', 65.578], ['C30r', 67.61], ['C31n', 67.735], ['C31r', 68.737], ['C32n', 71.071], ['C32r', 73.004], ['C33n', 73.619], ['C33r', 79.075], ['C34n', 83]]
        return TS, Labels
    if ts == 'gts04':
        TS = [0, 0.781, 0.988, 1.072, 1.778, 1.945, 2.128, 2.148, 2.581, 3.032, 3.116, 3.207, 3.33, 3.596, 4.187, 4.3, 4.493, 4.631, 4.799, 4.896, 4.997, 5.235, 6.033, 6.252, 6.436, 6.733, 7.14, 7.212, 7.251, 7.285, 7.454, 7.489, 7.528, 7.642, 7.695, 8.108, 8.254, 8.3, 8.769, 9.098, 9.312, 9.409, 9.656, 9.717, 9.779, 9.934, 9.987, 11.04, 11.118, 11.154, 11.554, 11.614, 12.014, 12.116, 12.207, 12.415, 12.73, 12.765, 12.82, 12.878, 13.015, 13.183, 13.369, 13.605, 13.734, 14.095, 14.194, 14.581, 14.784, 14.877, 15.032, 15.16, 15.974, 16.268, 16.303, 16.472, 16.543, 16.721, 17.235, 17.533, 17.717, 17.74, 18.056, 18.524, 18.748, 20, 20.04, 20.213, 20.439, 20.709, 21.083, 21.159, 21.403, 21.483, 21.659, 21.688, 21.767,
              21.936, 21.992, 22.268, 22.564, 22.754, 22.902, 23.03, 23.249, 23.375, 24.044, 24.102, 24.163, 24.556, 24.915, 25.091, 25.295, 25.444, 25.492, 26.154, 26.714, 27.826, 28.186, 28.45, 28.525, 28.715, 29.451, 29.74, 29.853, 30.217, 30.627, 31.116, 33.266, 33.738, 34.782, 35.043, 35.404, 35.567, 35.707, 36.276, 36.512, 37.235, 37.345, 37.549, 37.61, 37.771, 38.032, 38.975, 39.041, 39.464, 40.439, 40.671, 41.59, 42.774, 45.346, 47.235, 48.599, 49.427, 50.73, 50.932, 51.057, 51.901, 52.648, 53.004, 53.116, 53.167, 53.286, 53.808, 56.665, 57.18, 58.379, 58.737, 61.65, 61.983, 63.104, 64.128, 64.432, 65.118, 65.861, 67.696, 67.809, 68.732, 70.961, 71.225, 71.474, 72.929, 73.231, 73.318, 73.577, 79.543, 84]
        Labels = [['C1n', 0.000], ['C1r', 0.781], ['C2', 1.778], ['C2An', 2.581], ['C2Ar', 3.596], ['C3n', 4.187], ['C3r', 5.235], ['C3An', 6.033], ['C3Ar', 6.733], ['C3Bn', 7.140], ['C3Br', 7.212], ['C4n', 7.528], ['C4r', 8.108], ['C4An', 8.769], ['C4Ar', 9.098], ['C5n', 9.779], ['C5r', 11.040], ['C5An', 12.014], ['C5Ar', 12.415], ['C5AAn', 13.015], ['C5AAr', 13.183], ['C5ABn', 13.369], ['C5ABr', 13.605], ['C5ACn', 13.734], ['C5ACr', 14.095], ['C5ADn', 14.194], ['C5ADr', 14.581], ['C5Bn', 14.784], ['C5Br', 15.160], ['C5Cn', 15.974], ['C5Cr', 16.721], ['C5Dn', 17.235], ['C5Dr', 17.533], ['C5En', 18.056], ['C5Er', 18.524], ['C6n', 18.748], ['C6r', 19.772], ['C6An', 20.040], ['C6Ar', 20.709], ['C6AAn', 21.083], ['C6AAr', 21.159], ['C6Bn', 21.767], ['C6Br', 22.268], ['C6Cn', 22.564], ['C6Cr', 23.375], ['C7n', 24.044], ['C7r', 24.556], ['C7A', 24.919], ['C8n', 25.295], [
            'C8r', 26.154], ['C9n', 26.714], ['C9r', 27.826], ['C10n', 28.186], ['C11n', 29.451], ['C11r', 30.217], ['C12n', 30.627], ['C12r', 31.116], ['C13n', 33.266], ['C13r', 33.738], ['C15n', 34.782], ['C15r', 35.043], ['C16n', 35.404], ['C16r', 36.276], ['C17n', 36.512], ['C17r', 37.771], ['C18n', 38.032], ['C18r', 39.464], ['C19n', 40.439], ['C19r', 40.671], ['C20n', 41.590], ['C20r', 42.774], ['C21n', 45.346], ['C21r', 47.235], ['C22n', 48.599], ['C22r', 49.427], ['C23n', 50.730], ['C23r', 51.901], ['C24n', 52.648], ['C24r', 53.808], ['C25n', 56.665], ['C25r', 57.180], ['C26n', 58.379], ['C26r', 58.737], ['C27n', 61.650], ['C27r', 61.938], ['C28n', 63.104], ['C28r', 64.128], ['C29n', 64.432], ['C29r', 65.118], ['C30n', 65.861], ['C30r', 67.696], ['C31n', 67.809], ['C31r', 68.732], ['C32n', 70.961], ['C32r', 72.929], ['C33n', 73.577], ['C33r', 79.543], ['C34n', 84.000]]
        return TS, Labels
    if ts == 'gts12':
        TS = [0, 0.781, 0.988, 1.072, 1.173, 1.185, 1.778, 1.945, 2.128, 2.148, 2.581, 3.032, 3.116, 3.207, 3.330, 3.596, 4.187, 4.300, 4.493, 4.631, 4.799, 4.896, 4.997, 5.235, 6.033, 6.252, 6.436, 6.733, 7.140, 7.212, 7.251, 7.285, 7.454, 7.489, 7.528, 7.642, 7.695, 8.108, 8.254, 8.300, 8.771, 9.105, 9.311, 9.426, 9.647, 9.721, 9.786, 9.937, 9.984, 11.056, 11.146, 11.188, 11.592, 11.657, 12.049, 12.174, 12.272, 12.474, 12.735, 12.770, 12.829, 12.887, 13.032, 13.183, 13.363, 13.608, 13.739, 14.070, 14.163, 14.609, 14.775, 14.870, 15.032, 15.160, 15.974, 16.268, 16.303, 16.472, 16.543, 16.721, 17.235, 17.533, 17.717, 17.740, 18.056, 18.524, 18.748, 19.722, 20.040, 20.213, 20.439, 20.709, 21.083, 21.159, 21.403, 21.483, 21.659,
              21.688, 21.767, 21.936, 21.992, 22.268, 22.564, 22.754, 22.902, 23.030, 23.233, 23.295, 23.962, 24.000, 24.109, 24.474, 24.761, 24.984, 25.099, 25.264, 25.304, 25.987, 26.420, 27.439, 27.859, 28.087, 28.141, 28.278, 29.183, 29.477, 29.527, 29.970, 30.591, 31.034, 33.157, 33.705, 34.999, 35.294, 35.706, 35.892, 36.051, 36.700, 36.969, 37.753, 37.872, 38.093, 38.159, 38.333, 38.615, 39.627, 39.698, 40.145, 41.154, 41.390, 42.301, 43.432, 45.724, 47.349, 48.566, 49.344, 50.628, 50.835, 50.961, 51.833, 52.620, 53.074, 53.199, 53.274, 53.416, 53.983, 57.101, 57.656, 58.959, 59.237, 62.221, 62.517, 63.494, 64.667, 64.958, 65.688, 66.398, 68.196, 68.369, 69.269, 71.449, 71.689, 71.939, 73.649, 73.949, 74.049, 74.309, 79.900, 83.64]
        Labels = [['C1n', 0.000], ['C1r', 0.781], ['C2n', 1.778], ['C2r', 1.945], ['C2An', 2.581], ['C2Ar', 3.596], ['C3n', 4.187], ['C3r', 5.235], ['C3An', 6.033], ['C3Ar', 6.733], ['C3Bn', 7.140], ['C3Br', 7.212], ['C4n', 7.528], ['C4r', 8.108], ['C4An', 8.771], ['C4Ar', 9.105], ['C5n', 9.786], ['C5r', 11.056], ['C5An', 12.049], ['C5Ar', 12.474], ['C5AAn', 13.032], ['C5AAr', 13.183], ['C5ABn', 13.363], ['C5ABr', 13.608], ['C5ACn', 13.739], ['C5ACr', 14.070], ['C5ADn', 14.163], ['C5ADr', 14.609], ['C5Bn', 14.775], ['C5Br', 15.160], ['C5Cn', 15.974], ['C5Cr', 16.721], ['C5Dn', 17.235], ['C5Dr', 17.533], ['C5En', 18.056], ['C5Er', 18.524], ['C6n', 18.748], ['C6r', 19.722], ['C6An', 20.040], ['C6Ar', 20.709], ['C6AAn', 21.083], ['C6AAr', 21.159], ['C6Bn', 21.767], ['C6Br', 22.268], ['C6Cn', 22.564], ['C6Cr', 23.295], ['C7n', 23.962], ['C7r', 24.474], ['C7An', 24.761], ['C7Ar', 24.984], ['C8n', 25.099], [
            'C8r', 25.987], ['C9n', 26.420], ['C9r', 27.439], ['C10n', 27.859], ['C10r', 28.278], ['C11n', 29.183], ['C11r', 29.970], ['C12n', 30.591], ['C12r', 31.034], ['C13n', 33.157], ['C13r', 33.705], ['C15n', 34.999], ['C15r', 35.294], ['C16n', 35.706], ['C16r', 36.700], ['C17n', 36.969], ['C17r', 38.333], ['C18n', 38.615], ['C18r', 40.145], ['C19n', 41.154], ['C19r', 41.390], ['C20n', 42.301], ['C20r', 43.432], ['C21n', 45.724], ['C21r', 47.349], ['C22n', 48.566], ['C22r', 49.344], ['C23n', 50.628], ['C23r', 51.833], ['C24n', 52.620], ['C24r', 53.983], ['C25n', 57.101], ['C25r', 57.656], ['C26n', 58.959], ['C26r', 59.237], ['C27n', 62.221], ['C27r', 62.517], ['C28n', 63.494], ['C28r', 64.667], ['C29n', 64.958], ['C29r', 65.688], ['C30n', 66.398], ['C30r', 68.196], ['C31n', 68.369], ['C31r', 69.269], ['C32n', 71.449], ['C32r', 73.649], ['C33n', 74.309], ['C33r', 79.900], ['C34n', 83.64]]
        return TS, Labels
    print("Time Scale Option Not Available")
    return


Instruction:
Write a Python 3 function for
executing a statement in a new namespace and return the output of the statement.

Response:
def execute(st, **kwargs):
    """
    Work around for Python3 exec function which doesn't allow changes to the local namespace because of scope.
    This breaks a lot of the old functionality in the code which was origionally in Python2. So this function
    runs just like exec except that it returns the output of the input statement to the local namespace. It may
    break if you start feeding it multiline monoliths of statements (haven't tested) but you shouldn't do that
    anyway (bad programming).

    Parameters
    -----------
    st : the statement you want executed and for which you want the return
    kwargs : anything that may need to be in this namespace to execute st

    Returns
    -------
    The return value of executing the input statement
    """
    namespace = kwargs
    exec("b = {}".format(st), namespace)
    return namespace['b']