Instruction:
Can you tell what is the following Python 3 function doing
def curie(path_to_file='.', file_name='', magic=False,
          window_length=3, save=False, save_folder='.', fmt='svg', t_begin="", t_end=""):
    """
    Plots and interprets curie temperature data.
    ***
    The 1st derivative is calculated from smoothed M-T curve (convolution
    with trianfular window with width= <-w> degrees)
    ***
    The 2nd derivative is calculated from smoothed 1st derivative curve
    (using the same sliding window width)
    ***
    The estimated curie temp. is the maximum of the 2nd derivative.
    Temperature steps should be in multiples of 1.0 degrees.

    Parameters
    __________
    file_name : name of file to be opened

    Optional Parameters (defaults are used if not specified)
    ----------
    path_to_file : path to directory that contains file (default is current directory, '.')
    window_length : dimension of smoothing window (input to smooth() function)
    save : boolean argument to save plots (default is False)
    save_folder : relative directory where plots will be saved (default is current directory, '.')
    fmt : format of saved figures
    t_begin: start of truncated window for search
    t_end: end of truncated window for search
    magic : True if MagIC formated measurements.txt file
    """
    plot = 0
    window_len = window_length

    # read data from file
    complete_path = os.path.join(path_to_file, file_name)
    if magic:
        data_df = pd.read_csv(complete_path, sep='\t', header=1)
        T = data_df['meas_temp'].values-273
        magn_key = cb.get_intensity_col(data_df)
        M = data_df[magn_key].values
    else:
        Data = np.loadtxt(complete_path, dtype=np.float)
        T = Data.transpose()[0]
        M = Data.transpose()[1]
    T = list(T)
    M = list(M)
    # cut the data if -t is one of the flags
    if t_begin != "":
        while T[0] < t_begin:
            M.pop(0)
            T.pop(0)
        while T[-1] > t_end:
            M.pop(-1)
            T.pop(-1)

    # prepare the signal:
    # from M(T) array with unequal deltaT
    # to M(T) array with deltaT=(1 degree).
    # if delataT is larger, then points are added using linear fit between
    # consecutive data points.
    # exit if deltaT is not integer
    i = 0
    while i < (len(T) - 1):
        if (T[i + 1] - T[i]) % 1 > 0.001:
            print("delta T should be integer, this program will not work!")
            print("temperature range:", T[i], T[i + 1])
            sys.exit()
        if (T[i + 1] - T[i]) == 0.:
            M[i] = np.average([M[i], M[i + 1]])
            M.pop(i + 1)
            T.pop(i + 1)
        elif (T[i + 1] - T[i]) < 0.:
            M.pop(i + 1)
            T.pop(i + 1)
            print("check data in T=%.0f ,M[T] is ignored" % (T[i]))
        elif (T[i + 1] - T[i]) > 1.:
            slope, b = np.polyfit([T[i], T[i + 1]], [M[i], M[i + 1]], 1)
            for j in range(int(T[i + 1]) - int(T[i]) - 1):
                M.insert(i + 1, slope * (T[i] + 1.) + b)
                T.insert(i + 1, (T[i] + 1.))
                i = i + 1
        i = i + 1

    # calculate the smoothed signal
    M = np.array(M, 'f')
    T = np.array(T, 'f')
    M_smooth = []
    M_smooth = smooth(M, window_len)

    # plot the original data and the smooth data
    PLT = {'M_T': 1, 'der1': 2, 'der2': 3, 'Curie': 4}
    plt.figure(num=PLT['M_T'], figsize=(5, 5))
    string = 'M-T (sliding window=%i)' % int(window_len)
    pmagplotlib.plot_xy(PLT['M_T'], T, M_smooth, sym='-')
    pmagplotlib.plot_xy(PLT['M_T'], T, M, sym='--',
                        xlab='Temperature C', ylab='Magnetization', title=string)

    # calculate first derivative
    d1, T_d1 = [], []
    for i in range(len(M_smooth) - 1):
        Dy = M_smooth[i - 1] - M_smooth[i + 1]
        Dx = T[i - 1] - T[i + 1]
        d1.append(old_div(Dy, Dx))
    T_d1 = T[1:len(T - 1)]
    d1 = np.array(d1, 'f')
    d1_smooth = smooth(d1, window_len)

    # plot the first derivative
    plt.figure(num=PLT['der1'], figsize=(5, 5))
    string = '1st derivative (sliding window=%i)' % int(window_len)
    pmagplotlib.plot_xy(PLT['der1'], T_d1, d1_smooth,
                        sym='-', xlab='Temperature C', title=string)
    pmagplotlib.plot_xy(PLT['der1'], T_d1, d1, sym='b--')

    # calculate second derivative
    d2, T_d2 = [], []
    for i in range(len(d1_smooth) - 1):
        Dy = d1_smooth[i - 1] - d1_smooth[i + 1]
        Dx = T[i - 1] - T[i + 1]
        # print Dy/Dx
        d2.append(old_div(Dy, Dx))
    T_d2 = T[2:len(T - 2)]
    d2 = np.array(d2, 'f')
    d2_smooth = smooth(d2, window_len)

    # plot the second derivative
    plt.figure(num=PLT['der2'], figsize=(5, 5))
    string = '2nd derivative (sliding window=%i)' % int(window_len)
    pmagplotlib.plot_xy(PLT['der2'], T_d2, d2, sym='-',
                        xlab='Temperature C', title=string)
    d2 = list(d2)
    print('second derivative maximum is at T=%i' %
          int(T_d2[d2.index(max(d2))]))

    # calculate Curie temperature for different width of sliding windows
    curie, curie_1 = [], []
    wn = list(range(5, 50, 1))
    for win in wn:
        # calculate the smoothed signal
        M_smooth = []
        M_smooth = smooth(M, win)
        # calculate first derivative
        d1, T_d1 = [], []
        for i in range(len(M_smooth) - 1):
            Dy = M_smooth[i - 1] - M_smooth[i + 1]
            Dx = T[i - 1] - T[i + 1]
            d1.append(old_div(Dy, Dx))
        T_d1 = T[1:len(T - 1)]
        d1 = np.array(d1, 'f')
        d1_smooth = smooth(d1, win)
        # calculate second derivative
        d2, T_d2 = [], []
        for i in range(len(d1_smooth) - 1):
            Dy = d1_smooth[i - 1] - d1_smooth[i + 1]
            Dx = T[i - 1] - T[i + 1]
            d2.append(old_div(Dy, Dx))
        T_d2 = T[2:len(T - 2)]
        d2 = np.array(d2, 'f')
        d2_smooth = smooth(d2, win)
        d2 = list(d2)
        d2_smooth = list(d2_smooth)
        curie.append(T_d2[d2.index(max(d2))])
        curie_1.append(T_d2[d2_smooth.index(max(d2_smooth))])

    # plot Curie temp for different sliding window length
    plt.figure(num=PLT['Curie'], figsize=(5, 5))
    pmagplotlib.plot_xy(PLT['Curie'], wn, curie, sym='.',
                        xlab='Sliding Window Width (degrees)', ylab='Curie Temp', title='Curie Statistics')
    files = {}
    for key in list(PLT.keys()):
        files[key] = str(key) + '.' + fmt
    if save == True:
        for key in list(PLT.keys()):
            try:
                plt.figure(num=PLT[key])
                plt.savefig(save_folder + '/' + files[key].replace('/', '-'))
            except:
                print('could not save: ', PLT[key], files[key])
                print("output file format not supported ")
    plt.show()

Response: Function that creates a curie from a file.


Instruction:
How would you explain what the following Python 3 function does
def chi_magic2(path_to_file='.', file_name='magic_measurements.txt',
              save=False, save_folder='.', fmt='svg'):
    """
    Generates plots that compare susceptibility to temperature at different
    frequencies.

    Optional Parameters (defaults are used if not specified)
    ----------
    path_to_file : path to directory that contains file (default is current directory, '.')
    file_name : name of file to be opened (default is 'magic_measurements.txt')
    save : boolean argument to save plots (default is False)
    save_folder : relative directory where plots will be saved (default is current directory, '.')
    """
    cont, FTinit, BTinit, k = "", 0, 0, 0
    complete_path = os.path.join(path_to_file, file_name)
    Tind, cont = 0, ""
    EXP = ""
    #
    meas_data, file_type = pmag.magic_read(complete_path)
    #
    # get list of unique experiment names
    #
    # initialize some variables (a continuation flag, plot initialization
    # flags and the experiment counter
    experiment_names = []
    for rec in meas_data:
        if rec['magic_experiment_name'] not in experiment_names:
            experiment_names.append(rec['magic_experiment_name'])
    #
    # hunt through by experiment name
    if EXP != "":
        try:
            k = experiment_names.index(EXP)
        except:
            print("Bad experiment name")
            sys.exit()
    while k < len(experiment_names):
        e = experiment_names[k]
        if EXP == "":
            print(e, k + 1, 'out of ', len(experiment_names))
    #
    # initialize lists of data, susceptibility, temperature, frequency and
    # field
        X, T, F, B = [], [], [], []
        for rec in meas_data:
            methcodes = rec['magic_method_codes']
            meths = methcodes.strip().split(':')
            if rec['magic_experiment_name'] == e and "LP-X" in meths:  # looking for chi measurement
                if 'measurement_temp' not in list(rec.keys()):
                    rec['measurement_temp'] = '300'  # set defaults
                if 'measurement_freq' not in list(rec.keys()):
                    rec['measurement_freq'] = '0'  # set defaults
                if 'measurement_lab_field_ac' not in list(rec.keys()):
                    rec['measurement_lab_field_ac'] = '0'  # set default
                X.append(float(rec['measurement_x']))
                T.append(float(rec['measurement_temp']))
                F.append(float(rec['measurement_freq']))
                B.append(float(rec['measurement_lab_field_ac']))
    #
    # get unique list of Ts,Fs, and Bs
    #
        Ts, Fs, Bs = [], [], []
        for k in range(len(X)):   # hunt through all the measurements
            if T[k] not in Ts:
                Ts.append(T[k])  # append if not in list
            if F[k] not in Fs:
                Fs.append(F[k])
            if B[k] not in Bs:
                Bs.append(B[k])
        Ts.sort()  # sort list of temperatures, frequencies and fields
        Fs.sort()
        Bs.sort()
        if '-x' in sys.argv:
            k = len(experiment_names) + 1  # just plot the one
        else:
            k += 1  # increment experiment number
    #
    # plot chi versus T and F holding B constant
    #
        plotnum = 1  # initialize plot number to 1
        if len(X) > 2:  # if there are any data to plot, continue
            b = Bs[-1]  # keeping field constant and at maximum
            XTF = []  # initialize list of chi versus Temp and freq
            for f in Fs:   # step through frequencies sequentially
                XT = []  # initialize list of chi versus temp
                for kk in range(len(X)):  # hunt through all the data
                    if F[kk] == f and B[kk] == b:  # select data with given freq and field
                        XT.append([X[kk], T[kk]])  # append to list
                XTF.append(XT)  # append list to list of frequencies
            if len(XT) > 1:  # if there are any temperature dependent data
                plt.figure(num=plotnum, figsize=(5, 5))  # initialize plot
                # call the plotting function
                pmagplotlib.plot_xtf(plotnum, XTF, Fs, e, b)
                pmagplotlib.show_fig(plotnum)
                plotnum += 1  # increment plot number
            f = Fs[0]  # set frequency to minimum
            XTB = []  # initialize list if chi versus Temp and field
            for b in Bs:  # step through field values
                XT = []  # initial chi versus temp list for this field
                for kk in range(len(X)):  # hunt through all the data
                    if F[kk] == f and B[kk] == b:  # select data with given freq and field
                        XT.append([X[kk], T[kk]])  # append to list
                XTB.append(XT)
            if len(XT) > 1:  # if there are any temperature dependent data
                plt.figure(num=plotnum, figsize=(5, 5))  # set up plot
                # call the plotting function
                pmagplotlib.plot_xtb(plotnum, XTB, Bs, e, f)
                pmagplotlib.show_fig(plotnum)
                plotnum += 1  # increment plot number
            if save == True:
                files = {}
                PLTS = {}
                for p in range(1, plotnum):
                    key = str(p)
                    files[key] = e + '_' + key + '.' + fmt
                    PLTS[key] = p
                for key in list(PLTS.keys()):
                    try:
                        plt.figure(num=PLTS[key])
                        plt.savefig(save_folder + '/' +
                                    files[key].replace('/', '-'))
                    except:
                        print('could not save: ', PLTS[key], files[key])
                        print("output file format not supported ")

Response: Generates a chi - plot of the magic_measurements. txt file.


Instruction:
Can you generate the documentation for the following Python 3 function
def pmag_results_extract(res_file="pmag_results.txt", crit_file="", spec_file="",
                         age_file="", latex=False, grade=False, WD="."):
    """
    Generate tab delimited output file(s) with result data.
    Save output files and return True if successful.
    Possible output files: Directions, Intensities, SiteNfo, Criteria,
                           Specimens

    Optional Parameters (defaults are used if not specified)
    ----------
    res_file : name of pmag_results file (default is "pmag_results.txt")
    crit_file : name of criteria file (default is "pmag_criteria.txt")
    spec_file : name of specimen file (default is "pmag_specimens.txt")
    age_file : name of age file (default is "er_ages.txt")
    latex : boolean argument to output in LaTeX (default is False)
    WD : path to directory that contains input files and takes output (default is current directory, '.')
    """
    # format outfiles
    if latex:
        latex = 1
        file_type = '.tex'
    else:
        latex = 0
        file_type = '.txt'
    dir_path = os.path.realpath(WD)
    outfile = os.path.join(dir_path, 'Directions' + file_type)
    Ioutfile = os.path.join(dir_path, 'Intensities' + file_type)
    Soutfile = os.path.join(dir_path, 'SiteNfo' + file_type)
    Specout = os.path.join(dir_path, 'Specimens' + file_type)
    Critout = os.path.join(dir_path, 'Criteria' + file_type)
    # format infiles
    res_file = os.path.join(dir_path, res_file)
    if crit_file:
        crit_file = os.path.join(dir_path, crit_file)
    if spec_file:
        spec_file = os.path.join(dir_path, spec_file)
    else:
        grade = False
    # open output files
    f = open(outfile, 'w')
    sf = open(Soutfile, 'w')
    fI = open(Ioutfile, 'w')
    if crit_file:
        cr = open(Critout, 'w')
    # set up column headers
    Sites, file_type = pmag.magic_read(res_file)
    if crit_file:
        Crits, file_type = pmag.magic_read(crit_file)
    else:
        Crits = []
    SiteCols = ["Site", "Location",
                "Lat. (N)", "Long. (E)", "Age ", "Age sigma", "Units"]
    SiteKeys = ["er_site_names", "average_lat", "average_lon", "average_age",
                "average_age_sigma", "average_age_unit"]
    DirCols = ["Site", 'Comp.', "perc TC", "Dec.", "Inc.", "Nl", "Np", "k    ", "R", "a95",
               "PLat", "PLong"]
    DirKeys = ["er_site_names", "pole_comp_name", "tilt_correction", "average_dec", "average_inc",
               "average_n_lines", "average_n_planes", "average_k", "average_r", "average_alpha95",
               "vgp_lat", "vgp_lon"]
    IntCols = ["Site", "N", "B (uT)", "sigma",
               "sigma perc", "VADM", "VADM sigma"]
    IntKeys = ["er_site_names", "average_int_n", "average_int", "average_int_sigma",
               'average_int_sigma_perc', "vadm", "vadm_sigma"]
    AllowedKeys = ['specimen_frac', 'specimen_scat', 'specimen_gap_max', 'measurement_step_min',
                   'measurement_step_max', 'measurement_step_unit', 'specimen_polarity',
                   'specimen_nrm', 'specimen_direction_type', 'specimen_comp_nmb', 'specimen_mad',
                   'specimen_alpha95', 'specimen_n', 'specimen_int_sigma',
                   'specimen_int_sigma_perc', 'specimen_int_rel_sigma',
                   'specimen_int_rel_sigma_perc', 'specimen_int_mad', 'specimen_int_n',
                   'specimen_w', 'specimen_q', 'specimen_f', 'specimen_fvds', 'specimen_b_sigma',
                   'specimen_b_beta', 'specimen_g', 'specimen_dang', 'specimen_md',
                   'specimen_ptrm', 'specimen_drat', 'specimen_drats', 'specimen_rsc',
                   'specimen_viscosity_index', 'specimen_magn_moment', 'specimen_magn_volume',
                   'specimen_magn_mass', 'specimen_int_ptrm_n', 'specimen_delta', 'specimen_theta',
                   'specimen_gamma', 'sample_polarity', 'sample_nrm', 'sample_direction_type',
                   'sample_comp_nmb', 'sample_sigma', 'sample_alpha95', 'sample_n',
                   'sample_n_lines', 'sample_n_planes', 'sample_k', 'sample_r',
                   'sample_tilt_correction', 'sample_int_sigma', 'sample_int_sigma_perc',
                   'sample_int_rel_sigma', 'sample_int_rel_sigma_perc', 'sample_int_n',
                   'sample_magn_moment', 'sample_magn_volume', 'sample_magn_mass', 'site_polarity',
                   'site_nrm', 'site_direction_type', 'site_comp_nmb', 'site_sigma',
                   'site_alpha95', 'site_n', 'site_n_lines', 'site_n_planes', 'site_k', 'site_r',
                   'site_tilt_correction', 'site_int_sigma', 'site_int_sigma_perc',
                   'site_int_rel_sigma', 'site_int_rel_sigma_perc', 'site_int_n',
                   'site_magn_moment', 'site_magn_volume', 'site_magn_mass', 'average_age_min',
                   'average_age_max', 'average_age_sigma', 'average_age_unit', 'average_sigma',
                   'average_alpha95', 'average_n', 'average_nn', 'average_k', 'average_r',
                   'average_int_sigma', 'average_int_rel_sigma', 'average_int_rel_sigma_perc',
                   'average_int_n', 'average_int_nn', 'vgp_dp', 'vgp_dm', 'vgp_sigma',
                   'vgp_alpha95', 'vgp_n', 'vdm_sigma', 'vdm_n', 'vadm_sigma', 'vadm_n']
    if crit_file:
        crit = Crits[0]  # get a list of useful keys
        for key in list(crit.keys()):
            if key not in AllowedKeys:
                del(crit[key])
        for key in list(crit.keys()):
            if (not crit[key]) or (eval(crit[key]) > 1000) or (eval(crit[key]) == 0):
                # get rid of all blank or too big ones or too little ones
                del(crit[key])
        CritKeys = list(crit.keys())
    if spec_file:
        Specs, file_type = pmag.magic_read(spec_file)
        fsp = open(Specout, 'w')  # including specimen intensities if desired
        SpecCols = ["Site", "Specimen", "B (uT)", "MAD", "Beta", "N", "Q", "DANG", "f-vds",
                    "DRATS", "T (C)"]
        SpecKeys = ['er_site_name', 'er_specimen_name', 'specimen_int', 'specimen_int_mad',
                    'specimen_b_beta', 'specimen_int_n', 'specimen_q', 'specimen_dang',
                    'specimen_fvds', 'specimen_drats', 'trange']
        Xtra = ['specimen_frac', 'specimen_scat', 'specimen_gmax']
        if grade:
            SpecCols.append('Grade')
            SpecKeys.append('specimen_grade')
        for x in Xtra:  # put in the new intensity keys if present
            if x in list(Specs[0].keys()):
                SpecKeys.append(x)
                newkey = ""
                for k in x.split('_')[1:]:
                    newkey = newkey + k + '_'
                SpecCols.append(newkey.strip('_'))
        SpecCols.append('Corrections')
        SpecKeys.append('corrections')
    # these should be multiplied by 1e6
    Micro = ['specimen_int', 'average_int', 'average_int_sigma']
    Zeta = ['vadm', 'vadm_sigma']  # these should be multiplied by 1e21
    # write out the header information for each output file
    if latex:  # write out the latex header stuff
        sep = ' & '
        end = '\\\\'
        f.write('\\documentclass{article}\n')
        f.write('\\usepackage[margin=1in]{geometry}\n')
        f.write('\\usepackage{longtable}\n')
        f.write('\\begin{document}\n')
        sf.write('\\documentclass{article}\n')
        sf.write('\\usepackage[margin=1in]{geometry}\n')
        sf.write('\\usepackage{longtable}\n')
        sf.write('\\begin{document}\n')
        fI.write('\\documentclass{article}\n')
        fI.write('\\usepackage[margin=1in]{geometry}\n')
        fI.write('\\usepackage{longtable}\n')
        fI.write('\\begin{document}\n')
        if crit_file:
            cr.write('\\documentclass{article}\n')
            cr.write('\\usepackage[margin=1in]{geometry}\n')
            cr.write('\\usepackage{longtable}\n')
            cr.write('\\begin{document}\n')
        if spec_file:
            fsp.write('\\documentclass{article}\n')
            fsp.write('\\usepackage[margin=1in]{geometry}\n')
            fsp.write('\\usepackage{longtable}\n')
            fsp.write('\\begin{document}\n')
        tabstring = '\\begin{longtable}{'
        fstring = tabstring
        for k in range(len(SiteCols)):
            fstring = fstring + 'r'
        sf.write(fstring + '}\n')
        sf.write('\hline\n')
        fstring = tabstring
        for k in range(len(DirCols)):
            fstring = fstring + 'r'
        f.write(fstring + '}\n')
        f.write('\hline\n')
        fstring = tabstring
        for k in range(len(IntCols)):
            fstring = fstring + 'r'
        fI.write(fstring + '}\n')
        fI.write('\hline\n')
        fstring = tabstring
        if crit_file:
            for k in range(len(CritKeys)):
                fstring = fstring + 'r'
            cr.write(fstring + '}\n')
            cr.write('\hline\n')
        if spec_file:
            fstring = tabstring
            for k in range(len(SpecCols)):
                fstring = fstring + 'r'
            fsp.write(fstring + '}\n')
            fsp.write('\hline\n')
    else:   # just set the tab and line endings for tab delimited
        sep = ' \t '
        end = ''
# now write out the actual column headers
    Soutstring, Doutstring, Ioutstring, Spoutstring, Croutstring = "", "", "", "", ""
    for k in range(len(SiteCols)):
        Soutstring = Soutstring + SiteCols[k] + sep
    Soutstring = Soutstring.strip(sep)
    Soutstring = Soutstring + end + '\n'
    sf.write(Soutstring)
    for k in range(len(DirCols)):
        Doutstring = Doutstring + DirCols[k] + sep
    Doutstring = Doutstring.strip(sep)
    Doutstring = Doutstring + end + '\n'
    f.write(Doutstring)
    for k in range(len(IntCols)):
        Ioutstring = Ioutstring + IntCols[k] + sep
    Ioutstring = Ioutstring.strip(sep)
    Ioutstring = Ioutstring + end + '\n'
    fI.write(Ioutstring)
    if crit_file:
        for k in range(len(CritKeys)):
            Croutstring = Croutstring + CritKeys[k] + sep
        Croutstring = Croutstring.strip(sep)
        Croutstring = Croutstring + end + '\n'
        cr.write(Croutstring)
    if spec_file:
        for k in range(len(SpecCols)):
            Spoutstring = Spoutstring + SpecCols[k] + sep
        Spoutstring = Spoutstring.strip(sep)
        Spoutstring = Spoutstring + end + "\n"
        fsp.write(Spoutstring)
    if latex:  # put in a horizontal line in latex file
        f.write('\hline\n')
        sf.write('\hline\n')
        fI.write('\hline\n')
        if crit_file:
            cr.write('\hline\n')
        if spec_file:
            fsp.write('\hline\n')
 # do criteria
    if crit_file:
        for crit in Crits:
            Croutstring = ""
            for key in CritKeys:
                Croutstring = Croutstring + crit[key] + sep
            Croutstring = Croutstring.strip(sep) + end
            cr.write(Croutstring + '\n')
 # do directions
    # get all results with VGPs
    VGPs = pmag.get_dictitem(Sites, 'vgp_lat', '', 'F')
    VGPs = pmag.get_dictitem(VGPs, 'data_type', 'i',
                             'T')  # get site level stuff
    for site in VGPs:
        if len(site['er_site_names'].split(":")) == 1:
            if 'er_sample_names' not in list(site.keys()):
                site['er_sample_names'] = ''
            if 'pole_comp_name' not in list(site.keys()):
                site['pole_comp_name'] = "A"
            if 'average_nn' not in list(site.keys()) and 'average_n' in list(site.keys()):
                site['average_nn'] = site['average_n']
            if 'average_n_lines' not in list(site.keys()):
                site['average_n_lines'] = site['average_nn']
            if 'average_n_planes' not in list(site.keys()):
                site['average_n_planes'] = ""
            Soutstring, Doutstring = "", ""
            for key in SiteKeys:
                if key in list(site.keys()):
                    Soutstring = Soutstring + site[key] + sep
            Soutstring = Soutstring.strip(sep) + end
            sf.write(Soutstring + '\n')
            for key in DirKeys:
                if key in list(site.keys()):
                    Doutstring = Doutstring + site[key] + sep
            Doutstring = Doutstring.strip(sep) + end
            f.write(Doutstring + '\n')
# now do intensities
    VADMs = pmag.get_dictitem(Sites, 'vadm', '', 'F')
    VADMs = pmag.get_dictitem(VADMs, 'data_type', 'i', 'T')
    for site in VADMs:  # do results level stuff
        if site not in VGPs:
            Soutstring = ""
            for key in SiteKeys:
                if key in list(site.keys()):
                    Soutstring = Soutstring + site[key] + sep
                else:
                    Soutstring = Soutstring + " " + sep
            Soutstring = Soutstring.strip(sep) + end
            sf.write(Soutstring + '\n')
        if len(site['er_site_names'].split(":")) == 1 and site['data_type'] == 'i':
            if 'average_int_sigma_perc' not in list(site.keys()):
                site['average_int_sigma_perc'] = "0"
            if site["average_int_sigma"] == "":
                site["average_int_sigma"] = "0"
            if site["average_int_sigma_perc"] == "":
                site["average_int_sigma_perc"] = "0"
            if site["vadm"] == "":
                site["vadm"] = "0"
            if site["vadm_sigma"] == "":
                site["vadm_sigma"] = "0"
        for key in list(site.keys()):  # reformat vadms, intensities
            if key in Micro:
                site[key] = '%7.1f' % (float(site[key]) * 1e6)
            if key in Zeta:
                site[key] = '%7.1f' % (float(site[key]) * 1e-21)
        outstring = ""
        for key in IntKeys:
            if key not in list(site.keys()):
                site[key] = ""
            outstring = outstring + site[key] + sep
        outstring = outstring.strip(sep) + end + '\n'
        fI.write(outstring)
#    VDMs=pmag.get_dictitem(Sites,'vdm','','F') # get non-blank VDMs
#    for site in VDMs: # do results level stuff
#      if len(site['er_site_names'].split(":"))==1:
#            if 'average_int_sigma_perc' not in site.keys():site['average_int_sigma_perc']="0"
#            if site["average_int_sigma"]=="":site["average_int_sigma"]="0"
#            if site["average_int_sigma_perc"]=="":site["average_int_sigma_perc"]="0"
#            if site["vadm"]=="":site["vadm"]="0"
#            if site["vadm_sigma"]=="":site["vadm_sigma"]="0"
#      for key in site.keys(): # reformat vadms, intensities
#            if key in Micro: site[key]='%7.1f'%(float(site[key])*1e6)
#            if key in Zeta: site[key]='%7.1f'%(float(site[key])*1e-21)
#      outstring=""
#      for key in IntKeys:
#          outstring=outstring+site[key]+sep
#      fI.write(outstring.strip(sep)+'\n')
    if spec_file:
        SpecsInts = pmag.get_dictitem(Specs, 'specimen_int', '', 'F')
        for spec in SpecsInts:
            spec['trange'] = '%i' % (int(float(spec['measurement_step_min']) - 273)) + \
                '-' + '%i' % (int(float(spec['measurement_step_max']) - 273))
            meths = spec['magic_method_codes'].split(':')
            corrections = ''
            for meth in meths:
                if 'DA' in meth:
                    corrections = corrections + meth[3:] + ':'
            corrections = corrections.strip(':')
            if corrections.strip() == "":
                corrections = "None"
            spec['corrections'] = corrections
            outstring = ""
            for key in SpecKeys:
                if key in Micro:
                    spec[key] = '%7.1f' % (float(spec[key]) * 1e6)
                if key in Zeta:
                    spec[key] = '%7.1f' % (float(spec[key]) * 1e-21)
                outstring = outstring + spec[key] + sep
            fsp.write(outstring.strip(sep) + end + '\n')
    #
    if latex:  # write out the tail stuff
        f.write('\hline\n')
        sf.write('\hline\n')
        fI.write('\hline\n')
        f.write('\end{longtable}\n')
        sf.write('\end{longtable}\n')
        fI.write('\end{longtable}\n')
        f.write('\end{document}\n')
        sf.write('\end{document}\n')
        fI.write('\end{document}\n')
        if spec_file:
            fsp.write('\hline\n')
            fsp.write('\end{longtable}\n')
            fsp.write('\end{document}\n')
        if crit_file:
            cr.write('\hline\n')
            cr.write('\end{longtable}\n')
            cr.write('\end{document}\n')
    f.close()
    sf.close()
    fI.close()
    print('data saved in: ', outfile, Ioutfile, Soutfile)
    outfiles = [outfile, Ioutfile, Soutfile]
    if spec_file:
        fsp.close()
        print('specimen data saved in: ', Specout)
        outfiles.append(Specout)
    if crit_file:
        cr.close()
        print('Selection criteria saved in: ', Critout)
        outfiles.append(Critout)
    return True, outfiles

Response: Extract data from pmag_results. txt and return a list of files.


Instruction:
Make a summary of the following Python 3 code
def demag_magic(path_to_file='.', file_name='magic_measurements.txt',
                save=False, save_folder='.', fmt='svg', plot_by='loc',
                treat=None, XLP="", individual=None, average_measurements=False,
                single_plot=False):
    '''
    Takes demagnetization data (from magic_measurements file) and outputs
    intensity plots (with optional save).

    Parameters
    -----------
    path_to_file : path to directory that contains files (default is current directory, '.')
    file_name : name of measurements file (default is 'magic_measurements.txt')
    save : boolean argument to save plots (default is False)
    save_folder : relative directory where plots will be saved (default is current directory, '.')
    fmt : format of saved figures (default is 'svg')
    plot_by : specifies what sampling level you wish to plot the data at
        ('loc' -- plots all samples of the same location on the same plot
        'exp' -- plots all samples of the same expedition on the same plot
        'site' -- plots all samples of the same site on the same plot
        'sample' -- plots all measurements of the same sample on the same plot
        'spc' -- plots each specimen individually)
    treat : treatment step
        'T' = thermal demagnetization
        'AF' = alternating field demagnetization
        'M' = microwave radiation demagnetization
        (default is 'AF')
    XLP : filter data by a particular method
    individual : This function outputs all plots by default. If plotting by sample
        or specimen, you may not wish to see (or wait for) every single plot. You can
        therefore specify a particular plot by setting this keyword argument to
        a string of the site/sample/specimen name.
    average_measurements : Option to average demagnetization measurements by
        the grouping specified with the 'plot_by' keyword argument (default is False)
    single_plot : Option to output a single plot with all measurements (default is False)
    '''

    FIG = {}  # plot dictionary
    FIG['demag'] = 1  # demag is figure 1
    in_file, plot_key, LT = os.path.join(
        path_to_file, file_name), 'er_location_name', "LT-AF-Z"
    XLP = ""
    norm = 1
    units, dmag_key = 'T', 'treatment_ac_field'
    plot_num = 0

    if plot_by == 'loc':
        plot_key = 'er_location_name'
    elif plot_by == 'exp':
        plot_key = 'er_expedition_name'
    elif plot_by == 'site':
        plot_key = 'er_site_name'
    elif plot_by == 'sam':
        plot_key = 'er_sample_name'
    elif plot_by == 'spc':
        plot_key = 'er_specimen_name'

    if treat != None:
        LT = 'LT-' + treat + '-Z'  # get lab treatment for plotting
        if LT == 'LT-T-Z':
            units, dmag_key = 'K', 'treatment_temp'
        elif LT == 'LT-AF-Z':
            units, dmag_key = 'T', 'treatment_ac_field'
        elif LT == 'LT-M-Z':
            units, dmag_key = 'J', 'treatment_mw_energy'
        else:
            units = 'U'
    else:
        LT = 'LT-AF-Z'

    plot_dict = {}
    data, file_type = pmag.magic_read(in_file)
    sids = pmag.get_specs(data)
    plt.figure(num=FIG['demag'], figsize=(5, 5))
    print(len(data), ' records read from ', in_file)
    #
    #
    # find desired intensity data
    #
    # get plotlist
    #
    plotlist, intlist = [], ['measurement_magnitude', 'measurement_magn_moment',
                             'measurement_magn_volume', 'measurement_magn_mass']
    IntMeths = []
    FixData = []
    for rec in data:
        meths = []
        methcodes = rec['magic_method_codes'].split(':')
        for meth in methcodes:
            meths.append(meth.strip())
        for key in list(rec.keys()):
            if key in intlist and rec[key] != "":
                if key not in IntMeths:
                    IntMeths.append(key)
                if rec[plot_key] not in plotlist and LT in meths:
                    plotlist.append(rec[plot_key])
                if 'measurement_flag' not in list(rec.keys()):
                    rec['measurement_flag'] = 'g'
                FixData.append(rec)
        plotlist.sort()
    if len(IntMeths) == 0:
        print('No intensity information found')
    data = FixData
    # plot first intensity method found - normalized to initial value anyway -
    # doesn't matter which used
    int_key = IntMeths[0]
    # print plotlist
    if individual is not None:
        if type(individual) == list or type(individual) == tuple:
            plotlist = list(individual)
        else:
            plotlist = []
            plotlist.append(individual)
    for plot in plotlist:
        print(plot, 'plotting by: ', plot_key)
        # fish out all the data for this type of plot
        PLTblock = pmag.get_dictitem(data, plot_key, plot, 'T')
        # fish out all the dmag for this experiment type
        PLTblock = pmag.get_dictitem(PLTblock, 'magic_method_codes', LT, 'has')
        # get all with this intensity key non-blank
        PLTblock = pmag.get_dictitem(PLTblock, int_key, '', 'F')
        if XLP != "":
            # reject data with XLP in method_code
            PLTblock = pmag.get_dictitem(
                PLTblock, 'magic_method_codes', XLP, 'not')
    # for plot in plotlist:
        if len(PLTblock) > 2:
            title = PLTblock[0][plot_key]
            spcs = []
            for rec in PLTblock:
                if rec['er_specimen_name'] not in spcs:
                    spcs.append(rec['er_specimen_name'])
            if average_measurements is False:
                for spc in spcs:
                    # plot specimen by specimen
                    SPCblock = pmag.get_dictitem(
                        PLTblock, 'er_specimen_name', spc, 'T')
                    INTblock = []
                    for rec in SPCblock:
                        INTblock.append([float(rec[dmag_key]), 0, 0, float(
                            rec[int_key]), 1, rec['measurement_flag']])
                    if len(INTblock) > 2:
                        pmagplotlib.plot_mag(
                            FIG['demag'], INTblock, title, 0, units, norm)
            else:
                AVGblock = {}
                for spc in spcs:
                    # plot specimen by specimen
                    SPCblock = pmag.get_dictitem(
                        PLTblock, 'er_specimen_name', spc, 'T')
                    for rec in SPCblock:
                        if rec['measurement_flag'] == 'g':
                            if float(rec[dmag_key]) not in list(AVGblock.keys()):
                                AVGblock[float(rec[dmag_key])] = [
                                    float(rec[int_key])]
                            else:
                                AVGblock[float(rec[dmag_key])].append(
                                    float(rec[int_key]))
                INTblock = []
                for step in sorted(AVGblock.keys()):
                    INTblock.append([float(step), 0, 0, old_div(
                        float(sum(AVGblock[step])), float(len(AVGblock[step]))), 1, 'g'])
                pmagplotlib.plot_mag(FIG['demag'], INTblock,
                                     title, 0, units, norm)
        if save == True:
            plt.savefig(os.path.join(save_folder, title) + '.' + fmt)
        if single_plot is False:
            plt.show()
    if single_plot is True:
        plt.show()

Response: This function creates a demagnetization of the specified magic_measurements file and outputs the intensity plots of the specified individual.


Instruction:
Write a Python 3 script for
functioning to plot hysteresis data for specific use in matplotlib notebook

Response:
def iplot_hys(fignum, B, M, s):
    """
    function to plot hysteresis data

    This function has been adapted from pmagplotlib.iplot_hys for specific use
    within a Jupyter notebook.

    Parameters
    -----------
    fignum : reference number for matplotlib figure being created
    B : list of B (flux density) values of hysteresis experiment
    M : list of M (magnetization) values of hysteresis experiment
    s : specimen name
    """
    if fignum != 0:
        plt.figure(num=fignum)
        plt.clf()
    hpars = {}
# close up loop
    Npts = len(M)
    B70 = 0.7 * B[0]  # 70 percent of maximum field
    for b in B:
        if b < B70:
            break
    Nint = B.index(b) - 1
    if Nint > 30:
        Nint = 30
    if Nint < 10:
        Nint = 10
    Bzero, Mzero, Mfix, Mnorm, Madj, MadjN = "", "", [], [], [], []
    Mazero = ""
    m_init = 0.5 * (M[0] + M[1])
    m_fin = 0.5 * (M[-1] + M[-2])
    diff = m_fin - m_init
    Bmin = 0.
    for k in range(Npts):
        frac = old_div(float(k), float(Npts - 1))
        Mfix.append((M[k] - diff * frac))
        if Bzero == "" and B[k] < 0:
            Bzero = k
        if B[k] < Bmin:
            Bmin = B[k]
            kmin = k
    # adjust slope with first 30 data points (throwing out first 3)
    Bslop = B[2:Nint + 2]
    Mslop = Mfix[2:Nint + 2]
    polyU = polyfit(Bslop, Mslop, 1)  # best fit line to high field points
    # adjust slope with first 30 points of ascending branch
    Bslop = B[kmin:kmin + (Nint + 1)]
    Mslop = Mfix[kmin:kmin + (Nint + 1)]
    polyL = polyfit(Bslop, Mslop, 1)  # best fit line to high field points
    xhf = 0.5 * (polyU[0] + polyL[0])  # mean of two slopes
    # convert B to A/m, high field slope in m^3
    hpars['hysteresis_xhf'] = '%8.2e' % (xhf * 4 * np.pi * 1e-7)
    meanint = 0.5 * (polyU[1] + polyL[1])  # mean of two intercepts
    Msat = 0.5 * (polyU[1] - polyL[1])  # mean of saturation remanence
    Moff = []
    for k in range(Npts):
        # take out linear slope and offset (makes symmetric about origin)
        Moff.append((Mfix[k] - xhf * B[k] - meanint))
        if Mzero == "" and Moff[k] < 0:
            Mzero = k
        if Mzero != "" and Mazero == "" and Moff[k] > 0:
            Mazero = k
    hpars['hysteresis_ms_moment'] = '%8.3e' % (Msat)  # Ms in Am^2
#
# split into upper and lower loops for splining
    Mupper, Bupper, Mlower, Blower = [], [], [], []
    deltaM, Bdm = [], []  # diff between upper and lower curves at Bdm
    for k in range(kmin - 2, 0, -2):
        Mupper.append(old_div(Moff[k], Msat))
        Bupper.append(B[k])
    for k in range(kmin + 2, len(B)-1):
        Mlower.append(Moff[k] / Msat)
        Blower.append(B[k])
    Iupper = spline.Spline(Bupper, Mupper)  # get splines for upper up and down
    Ilower = spline.Spline(Blower, Mlower)  # get splines for lower
    for b in np.arange(B[0]):  # get range of field values
        Mpos = ((Iupper(b) - Ilower(b)))  # evaluate on both sides of B
        Mneg = ((Iupper(-b) - Ilower(-b)))
        Bdm.append(b)
        deltaM.append(0.5 * (Mpos + Mneg))  # take average delta M
    print('whew')
    for k in range(Npts):
        MadjN.append(old_div(Moff[k], Msat))
        Mnorm.append(old_div(M[k], Msat))
# find Mr : average of two spline fits evaluted at B=0 (times Msat)
    Mr = Msat * 0.5 * (Iupper(0.) - Ilower(0.))
    hpars['hysteresis_mr_moment'] = '%8.3e' % (Mr)
# find Bc (x intercept), interpolate between two bounding points
    Bz = B[Mzero - 1:Mzero + 1]
    Mz = Moff[Mzero - 1:Mzero + 1]
    Baz = B[Mazero - 1:Mazero + 1]
    Maz = Moff[Mazero - 1:Mazero + 1]
    try:
        poly = polyfit(Bz, Mz, 1)  # best fit line through two bounding points
        Bc = old_div(-poly[1], poly[0])  # x intercept
        # best fit line through two bounding points
        poly = polyfit(Baz, Maz, 1)
        Bac = old_div(-poly[1], poly[0])  # x intercept
        hpars['hysteresis_bc'] = '%8.3e' % (0.5 * (abs(Bc) + abs(Bac)))
    except:
        hpars['hysteresis_bc'] = '0'
    return hpars, deltaM, Bdm, B, Mnorm, MadjN


Instruction:
Write a Python 3 script to
calculate hysteresis parameters, saves them in rmag_hysteresis format file. If selected, this function also plots hysteresis loops, delta M curves, d (Delta M)/dB curves, and IRM backfield curves. Parameters (defaults are used if not specified) ---------- path_to_file : path to directory that contains files (default is current directory, '.') hyst_file : hysteresis file (default is 'rmag_hysteresis.txt') save : boolean argument to save plots (default is False) save_folder : relative directory where plots will be saved (default is current directory, '.') fmt : format of saved figures (default is 'pdf') plots: whether or not to display the plots (default is true)

Response:
def hysteresis_magic2(path_to_file='.', hyst_file="rmag_hysteresis.txt",
                      save=False, save_folder='.',
                      fmt="svg", plots=True):
    """
    Calculates hysteresis parameters, saves them in rmag_hysteresis format file.
    If selected, this function also plots hysteresis loops, delta M curves,
    d (Delta M)/dB curves, and IRM backfield curves.

    Parameters (defaults are used if not specified)
    ----------
    path_to_file : path to directory that contains files (default is current directory, '.')
    hyst_file : hysteresis file (default is 'rmag_hysteresis.txt')
    save : boolean argument to save plots (default is False)
    save_folder : relative directory where plots will be saved (default is current directory, '.')
    fmt : format of saved figures (default is 'pdf')
    plots: whether or not to display the plots (default is true)
    """
    user, meas_file, rmag_out, rmag_file = "", "agm_measurements.txt", "rmag_hysteresis.txt", ""
    pltspec = ""
    dir_path = save_folder
    verbose = pmagplotlib.verbose
    version_num = pmag.get_version()
    rmag_out = save_folder + '/' + rmag_out
    meas_file = path_to_file + '/' + hyst_file
    rmag_rem = save_folder + "/rmag_remanence.txt"
    #
    #
    meas_data, file_type = pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print(hysteresis_magic.__doc__)
        print('bad file')
        return

    # initialize some variables
    # define figure numbers for hyst,deltaM,DdeltaM curves
    HystRecs, RemRecs = [], []
    HDD = {}
    HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'] = 1, 2, 3
    experiment_names, sids = [], []
    for rec in meas_data:
        meths = rec['magic_method_codes'].split(':')
        methods = []
        for meth in meths:
            methods.append(meth.strip())
        if 'LP-HYS' in methods:
            if 'er_synthetic_name' in list(rec.keys()) and rec['er_synthetic_name'] != "":
                rec['er_specimen_name'] = rec['er_synthetic_name']
            if rec['magic_experiment_name'] not in experiment_names:
                experiment_names.append(rec['magic_experiment_name'])
            if rec['er_specimen_name'] not in sids:
                sids.append(rec['er_specimen_name'])
    #
    fignum = 1
    sample_num = 0
    # initialize variables to record some bulk info in first loop
    first_dcd_rec, first_rec, first_imag_rec = 1, 1, 1
    while sample_num < len(sids):
        sample = sids[sample_num]
        print(sample, sample_num + 1, 'out of ', len(sids))
        # B,M for hysteresis, Bdcd,Mdcd for irm-dcd data
        B, M, Bdcd, Mdcd = [], [], [], []
        Bimag, Mimag = [], []  # Bimag,Mimag for initial magnetization curves
        for rec in meas_data:
            methcodes = rec['magic_method_codes'].split(':')
            meths = []
            for meth in methcodes:
                meths.append(meth.strip())
            if rec['er_specimen_name'] == sample and "LP-HYS" in meths:
                B.append(float(rec['measurement_lab_field_dc']))
                M.append(float(rec['measurement_magn_moment']))
                if first_rec == 1:
                    e = rec['magic_experiment_name']
                    HystRec = {}
                    first_rec = 0
                    if "er_location_name" in list(rec.keys()):
                        HystRec["er_location_name"] = rec["er_location_name"]
                        locname = rec['er_location_name'].replace('/', '-')
                    if "er_sample_name" in list(rec.keys()):
                        HystRec["er_sample_name"] = rec["er_sample_name"]
                    if "er_site_name" in list(rec.keys()):
                        HystRec["er_site_name"] = rec["er_site_name"]
                    if "er_synthetic_name" in list(rec.keys()) and rec['er_synthetic_name'] != "":
                        HystRec["er_synthetic_name"] = rec["er_synthetic_name"]
                    else:
                        HystRec["er_specimen_name"] = rec["er_specimen_name"]
            if rec['er_specimen_name'] == sample and "LP-IRM-DCD" in meths:
                Bdcd.append(float(rec['treatment_dc_field']))
                Mdcd.append(float(rec['measurement_magn_moment']))
                if first_dcd_rec == 1:
                    RemRec = {}
                    irm_exp = rec['magic_experiment_name']
                    first_dcd_rec = 0
                    if "er_location_name" in list(rec.keys()):
                        RemRec["er_location_name"] = rec["er_location_name"]
                    if "er_sample_name" in list(rec.keys()):
                        RemRec["er_sample_name"] = rec["er_sample_name"]
                    if "er_site_name" in list(rec.keys()):
                        RemRec["er_site_name"] = rec["er_site_name"]
                    if "er_synthetic_name" in list(rec.keys()) and rec['er_synthetic_name'] != "":
                        RemRec["er_synthetic_name"] = rec["er_synthetic_name"]
                    else:
                        RemRec["er_specimen_name"] = rec["er_specimen_name"]
            if rec['er_specimen_name'] == sample and "LP-IMAG" in meths:
                if first_imag_rec == 1:
                    imag_exp = rec['magic_experiment_name']
                    first_imag_rec = 0
                Bimag.append(float(rec['measurement_lab_field_dc']))
                Mimag.append(float(rec['measurement_magn_moment']))
        if len(B) > 0:
            hmeths = []
            for meth in meths:
                hmeths.append(meth)
    #         fignum = 1
            fig = plt.figure(figsize=(8, 8))
            hpars, deltaM, Bdm, B, Mnorm, MadjN = iplot_hys(1, B, M, sample)
            ax1 = fig.add_subplot(2, 2, 1)
            ax1.axhline(0, color='k')
            ax1.axvline(0, color='k')
            ax1.plot(B, Mnorm, 'r')
            ax1.plot(B, MadjN, 'b')
            ax1.set_xlabel('B (T)')
            ax1.set_ylabel("M/Msat")
    #         ax1.set_title(sample)
            ax1.set_xlim(-1, 1)
            ax1.set_ylim(-1, 1)
            bounds = ax1.axis()
            n4 = 'Ms: ' + \
                '%8.2e' % (float(hpars['hysteresis_ms_moment'])) + ' Am^2'
            ax1.text(bounds[1] - .9 * bounds[1], -.9, n4, fontsize=9)
            n1 = 'Mr: ' + \
                '%8.2e' % (float(hpars['hysteresis_mr_moment'])) + ' Am^2'
            ax1.text(bounds[1] - .9 * bounds[1], -.7, n1, fontsize=9)
            n2 = 'Bc: ' + '%8.2e' % (float(hpars['hysteresis_bc'])) + ' T'
            ax1.text(bounds[1] - .9 * bounds[1], -.5, n2, fontsize=9)
            if 'hysteresis_xhf' in list(hpars.keys()):
                n3 = r'Xhf: ' + \
                    '%8.2e' % (float(hpars['hysteresis_xhf'])) + ' m^3'
                ax1.text(bounds[1] - .9 * bounds[1], -.3, n3, fontsize=9)
    #         plt.subplot(1,2,2)
    #         plt.subplot(1,3,3)
        DdeltaM = []
        Mhalf = ""
        for k in range(2, len(Bdm)):
            # differnential
            DdeltaM.append(
                old_div(abs(deltaM[k] - deltaM[k - 2]), (Bdm[k] - Bdm[k - 2])))
        for k in range(len(deltaM)):
            if old_div(deltaM[k], deltaM[0]) < 0.5:
                Mhalf = k
                break
        try:
            Bhf = Bdm[Mhalf - 1:Mhalf + 1]
            Mhf = deltaM[Mhalf - 1:Mhalf + 1]
            # best fit line through two bounding points
            poly = polyfit(Bhf, Mhf, 1)
            Bcr = old_div((.5 * deltaM[0] - poly[1]), poly[0])
            hpars['hysteresis_bcr'] = '%8.3e' % (Bcr)
            hpars['magic_method_codes'] = "LP-BCR-HDM"
            if HDD['deltaM'] != 0:
                ax2 = fig.add_subplot(2, 2, 2)
                ax2.plot(Bdm, deltaM, 'b')
                ax2.set_xlabel('B (T)')
                ax2.set_ylabel('Delta M')
                linex = [0, Bcr, Bcr]
                liney = [old_div(deltaM[0], 2.), old_div(deltaM[0], 2.), 0]
                ax2.plot(linex, liney, 'r')
    #             ax2.set_title(sample)
                ax3 = fig.add_subplot(2, 2, 3)
                ax3.plot(Bdm[(len(Bdm) - len(DdeltaM)):], DdeltaM, 'b')
                ax3.set_xlabel('B (T)')
                ax3.set_ylabel('d (Delta M)/dB')
    #             ax3.set_title(sample)

                ax4 = fig.add_subplot(2, 2, 4)
                ax4.plot(Bdcd, Mdcd)
                ax4.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'))
                ax4.axhline(0, color='k')
                ax4.axvline(0, color='k')
                ax4.set_xlabel('B (T)')
                ax4.set_ylabel('M/Mr')
        except:
            print("not doing it")
            hpars['hysteresis_bcr'] = '0'
            hpars['magic_method_codes'] = ""
        plt.gcf()
        plt.gca()
        plt.tight_layout()
        if save:
            plt.savefig(save_folder + '/' + sample + '_hysteresis.' + fmt)
        plt.show()
        sample_num += 1


Instruction:
Given the following Python 3 function, write the documentation
def find_ei(data, nb=1000, save=False, save_folder='.', fmt='svg',
            site_correction=False, return_new_dirs=False):
    """
    Applies series of assumed flattening factor and "unsquishes" inclinations assuming tangent function.
    Finds flattening factor that gives elongation/inclination pair consistent with TK03;
    or, if correcting by site instead of for study-level secular variation,
    finds flattening factor that minimizes elongation and most resembles a
    Fisherian distribution.
    Finds bootstrap confidence bounds

    Required Parameter
    -----------
    data: a nested list of dec/inc pairs

    Optional Parameters (defaults are used unless specified)
    -----------
    nb: number of bootstrapped pseudo-samples (default is 1000)
    save: Boolean argument to save plots (default is False)
    save_folder: path to folder in which plots should be saved (default is current directory)
    fmt: specify format of saved plots (default is 'svg')
    site_correction: Boolean argument to specify whether to "unsquish" data to
        1) the elongation/inclination pair consistent with TK03 secular variation model
        (site_correction = False)
        or
        2) a Fisherian distribution (site_correction = True). Default is FALSE.
        Note that many directions (~ 100) are needed for this correction to be reliable.
    return_new_dirs: optional return of newly "unflattened" directions (default is False)

    Returns
    -----------
    four plots:   1) equal area plot of original directions
                  2) Elongation/inclination pairs as a function of f,  data plus 25 bootstrap samples
                  3) Cumulative distribution of bootstrapped optimal inclinations plus uncertainties.
                     Estimate from original data set plotted as solid line
                  4) Orientation of principle direction through unflattening

    NOTE: If distribution does not have a solution, plot labeled: Pathological.  Some bootstrap samples may have
       valid solutions and those are plotted in the CDFs and E/I plot.
    """
    print("Bootstrapping.... be patient")
    print("")
    sys.stdout.flush()

    upper, lower = int(round(.975 * nb)), int(round(.025 * nb))
    E, I = [], []

    plt.figure(num=1, figsize=(4, 4))
    plot_net(1)
    plot_di(di_block=data)
    plt.title('Original')
    ppars = pmag.doprinc(data)
    Io = ppars['inc']
    n = ppars["N"]
    Es, Is, Fs, V2s = pmag.find_f(data)
    if site_correction == True:
        Inc, Elong = Is[Es.index(min(Es))], Es[Es.index(min(Es))]
        flat_f = Fs[Es.index(min(Es))]
    else:
        Inc, Elong = Is[-1], Es[-1]
        flat_f = Fs[-1]

    plt.figure(num=2, figsize=(4, 4))
    plt.plot(Is, Es, 'r')
    plt.xlabel("Inclination")
    plt.ylabel("Elongation")
    plt.text(Inc, Elong, ' %3.1f' % (flat_f))
    plt.text(Is[0] - 2, Es[0], ' %s' % ('f=1'))

    b = 0

    while b < nb:
        bdata = pmag.pseudo(data)
        Esb, Isb, Fsb, V2sb = pmag.find_f(bdata)
        if b < 25:
            plt.plot(Isb, Esb, 'y')
        if Esb[-1] != 0:
            ppars = pmag.doprinc(bdata)
            if site_correction == True:
                I.append(abs(Isb[Esb.index(min(Esb))]))
                E.append(Esb[Esb.index(min(Esb))])
            else:
                I.append(abs(Isb[-1]))
                E.append(Esb[-1])
            b += 1

    I.sort()
    E.sort()
    Eexp = []
    for i in I:
        Eexp.append(pmag.EI(i))
    plt.plot(I, Eexp, 'g-')
    if Inc == 0:
        title = 'Pathological Distribution: ' + \
            '[%7.1f, %7.1f]' % (I[lower], I[upper])
    else:
        title = '%7.1f [%7.1f, %7.1f]' % (Inc, I[lower], I[upper])

    cdf_fig_num = 3
    plt.figure(num=cdf_fig_num, figsize=(4, 4))
    pmagplotlib.plot_cdf(cdf_fig_num, I, 'Inclinations', 'r', title)
    pmagplotlib.plot_vs(cdf_fig_num, [I[lower], I[upper]], 'b', '--')
    pmagplotlib.plot_vs(cdf_fig_num, [Inc], 'g', '-')
    pmagplotlib.plot_vs(cdf_fig_num, [Io], 'k', '-')

    # plot corrected directional data

    di_lists = unpack_di_block(data)
    if len(di_lists) == 3:
        decs, incs, intensity = di_lists
    if len(di_lists) == 2:
        decs, incs = di_lists
    if flat_f:
        unsquished_incs = unsquish(incs, flat_f)
        plt.figure(num=4, figsize=(4, 4))
        plot_net(4)
        plot_di(decs, unsquished_incs)
        plt.title('Corrected for flattening')
    else:
        plt.figure(num=4, figsize=(4, 4))
        plot_net(4)
        plot_di(decs, incs)
        plt.title('Corrected for flattening')

    if (Inc, Elong, flat_f) == (0, 0, 0):
        print("PATHOLOGICAL DISTRIBUTION")
    print("The original inclination was: " + str(Io))
    print("")
    print("The corrected inclination is: " + str(Inc))
    print("with bootstrapped confidence bounds of: " +
          str(I[lower]) + ' to ' + str(I[upper]))
    print("and elongation parameter of: " + str(Elong))
    print("The flattening factor is: " + str(flat_f))
    if return_new_dirs is True:
        return make_di_block(decs, unsquished_incs)

Response: Find the Elongation and Inclination Pairs for a given set of data.


Instruction:
Implement a function in Python 3 to
calculate the rate of a single plate in the Ma .

Response:
def plate_rate_mc(pole1_plon, pole1_plat, pole1_kappa, pole1_N, pole1_age, pole1_age_error,
                  pole2_plon, pole2_plat, pole2_kappa, pole2_N, pole2_age, pole2_age_error,
                  ref_loc_lon, ref_loc_lat, samplesize=10000, random_seed=None, plot=True,
                  savefig=True, save_directory='./', figure_name=''):
    """
    Determine the latitudinal motion implied by a pair of poles and utilize
    the Monte Carlo sampling method of Swanson-Hysell (2014) to determine the
    associated uncertainty.

    Parameters:
    ------------
    plon : longitude of pole
    plat : latitude of pole
    kappa : Fisher precision parameter for VPGs in pole
    N : number of VGPs in pole
    age : age assigned to pole in Ma
    age_error : 1 sigma age uncertainty in million years
    ref_loc_lon : longitude of reference location
    ref_loc_lat : latitude of reference location
    samplesize : number of draws from pole and age distributions (default set to 10000)
    random_seed : set random seed for reproducible number generation (default is None)
    plot : whether to make figures (default is True, optional)
    savefig : whether to save figures (default is True, optional)
    save_directory = default is local directory (optional)
    figure_name = prefix for file names (optional)

    Returns
    --------
    rate : rate of latitudinal motion in cm/yr along with estimated 2.5 and 97.5
    percentile rate estimates
    """
    ref_loc = [ref_loc_lon, ref_loc_lat]
    pole1 = (pole1_plon, pole1_plat)
    pole1_paleolat = 90 - pmag.angle(pole1, ref_loc)
    pole2 = (pole2_plon, pole2_plat)
    pole2_paleolat = 90 - pmag.angle(pole2, ref_loc)
    print("The paleolatitude for ref_loc resulting from pole 1 is:" +
          str(pole1_paleolat))
    print("The paleolatitude for ref_loc resulting from pole 2 is:" +
          str(pole2_paleolat))
    rate = old_div(((pole1_paleolat - pole2_paleolat) * 111 *
                    100000), ((pole1_age - pole2_age) * 1000000))
    print("The rate of paleolatitudinal change implied by the poles pairs in cm/yr is:" + str(rate))

    if random_seed != None:
        np.random.seed(random_seed)
    pole1_MCages = np.random.normal(pole1_age, pole1_age_error, samplesize)
    pole2_MCages = np.random.normal(pole2_age, pole2_age_error, samplesize)

    plt.hist(pole1_MCages, 100, histtype='stepfilled',
             color='darkred', label='Pole 1 ages')
    plt.hist(pole2_MCages, 100, histtype='stepfilled',
             color='darkblue', label='Pole 2 ages')
    plt.xlabel('Age (Ma)')
    plt.ylabel('n')
    plt.legend(loc=3)
    if savefig == True:
        plot_extension = '_1.svg'
        plt.savefig(save_directory + figure_name + plot_extension)
    plt.show()

    pole1_MCpoles = []
    pole1_MCpole_lat = []
    pole1_MCpole_long = []
    pole1_MCpaleolat = []
    for n in range(samplesize):
        vgp_samples = []
        for vgp in range(pole1_N):
            # pmag.dev returns a direction from a fisher distribution with
            # specified kappa
            direction_atN = pmag.fshdev(pole1_kappa)
            # this direction is centered at latitude of 90 degrees and needs to be rotated
            # to be centered on the mean pole position
            tilt_direction = pole1_plon
            tilt_amount = 90 - pole1_plat
            direction = pmag.dotilt(
                direction_atN[0], direction_atN[1], tilt_direction, tilt_amount)
            vgp_samples.append([direction[0], direction[1], 1.])
        mean = pmag.fisher_mean(vgp_samples)
        mean_pole_position = (mean['dec'], mean['inc'])
        pole1_MCpoles.append([mean['dec'], mean['inc'], 1.])
        pole1_MCpole_lat.append(mean['inc'])
        pole1_MCpole_long.append(mean['dec'])
        paleolat = 90 - pmag.angle(mean_pole_position, ref_loc)
        pole1_MCpaleolat.append(paleolat[0])

    pole2_MCpoles = []
    pole2_MCpole_lat = []
    pole2_MCpole_long = []
    pole2_MCpaleolat = []
    for n in range(samplesize):
        vgp_samples = []
        for vgp in range(pole2_N):
            # pmag.dev returns a direction from a fisher distribution with
            # specified kappa
            direction_atN = pmag.fshdev(pole2_kappa)
            # this direction is centered at latitude of 90 degrees and needs to be rotated
            # to be centered on the mean pole position
            tilt_direction = pole2_plon
            tilt_amount = 90 - pole2_plat
            direction = pmag.dotilt(
                direction_atN[0], direction_atN[1], tilt_direction, tilt_amount)
            vgp_samples.append([direction[0], direction[1], 1.])
        mean = pmag.fisher_mean(vgp_samples)
        mean_pole_position = (mean['dec'], mean['inc'])
        pole2_MCpoles.append([mean['dec'], mean['inc'], 1.])
        pole2_MCpole_lat.append(mean['inc'])
        pole2_MCpole_long.append(mean['dec'])
        paleolat = 90 - pmag.angle(mean_pole_position, ref_loc)
        pole2_MCpaleolat.append(paleolat[0])

    if plot is True:
        plt.figure(figsize=(5, 5))
        map_axis = make_mollweide_map()

        plot_vgp(map_axis, pole1_MCpole_long, pole1_MCpole_lat, color='b')
        plot_vgp(map_axis, pole2_MCpole_long, pole2_MCpole_lat, color='g')
        if savefig == True:
            plot_extension = '_2.svg'
            plt.savefig(save_directory + figure_name + plot_extension)
        plt.show()

    # calculating the change in paleolatitude between the Monte Carlo pairs
    pole1_pole2_Delta_degrees = []
    pole1_pole2_Delta_kilometers = []
    pole1_pole2_Delta_myr = []
    pole1_pole2_degrees_per_myr = []
    pole1_pole2_cm_per_yr = []

    for n in range(samplesize):
        Delta_degrees = pole1_MCpaleolat[n] - pole2_MCpaleolat[n]
        Delta_Myr = pole1_MCages[n] - pole2_MCages[n]
        pole1_pole2_Delta_degrees.append(Delta_degrees)
        degrees_per_myr = old_div(Delta_degrees, Delta_Myr)
        cm_per_yr = old_div(((Delta_degrees * 111) * 100000),
                            (Delta_Myr * 1000000))
        pole1_pole2_degrees_per_myr.append(degrees_per_myr)
        pole1_pole2_cm_per_yr.append(cm_per_yr)

    if plot is True:
        plotnumber = 100
        plt.figure(num=None, figsize=(10, 4))
        plt.subplot(1, 2, 1)
        for n in range(plotnumber):
            plt.plot([pole1_MCpaleolat[n], pole2_MCpaleolat[n]],
                     [pole1_MCages[n], pole2_MCages[n]], 'k-', linewidth=0.1, alpha=0.3)
        plt.scatter(pole1_MCpaleolat[:plotnumber],
                    pole1_MCages[:plotnumber], color='b', s=3)
        plt.scatter(pole1_paleolat, pole1_age, color='lightblue',
                    s=100, edgecolor='w', zorder=10000)
        plt.scatter(pole2_MCpaleolat[:plotnumber],
                    pole2_MCages[:plotnumber], color='g', s=3)
        plt.scatter(pole2_paleolat, pole2_age, color='lightgreen',
                    s=100, edgecolor='w', zorder=10000)
        plt.plot([pole1_paleolat, pole2_paleolat], [
                 pole1_age, pole2_age], 'w-', linewidth=2)
        plt.gca().invert_yaxis()
        plt.xlabel('paleolatitude (degrees)', size=14)
        plt.ylabel('time (Ma)', size=14)

        plt.subplot(1, 2, 2)
        plt.hist(pole1_pole2_cm_per_yr, bins=600)
        plt.ylabel('n', size=14)
        plt.xlabel('latitudinal drift rate (cm/yr)', size=14)
        # plt.xlim([0,90])
        if savefig == True:
            plot_extension = '_3.svg'
            plt.savefig(save_directory + figure_name + plot_extension)
        plt.show()

    twopointfive_percentile = stats.scoreatpercentile(
        pole1_pole2_cm_per_yr, 2.5)
    fifty_percentile = stats.scoreatpercentile(pole1_pole2_cm_per_yr, 50)
    ninetysevenpointfive_percentile = stats.scoreatpercentile(
        pole1_pole2_cm_per_yr, 97.5)
    print("2.5th percentile is: " +
          str(round(twopointfive_percentile, 2)) + " cm/yr")
    print("50th percentile is: " + str(round(fifty_percentile, 2)) + " cm/yr")
    print("97.5th percentile is: " +
          str(round(ninetysevenpointfive_percentile, 2)) + " cm/yr")
    return rate[0], twopointfive_percentile, ninetysevenpointfive_percentile


Instruction:
Can you generate the documentation for the following Python 3 function
def zeq(path_to_file='.', file='', data="", units='U', calculation_type="DE-BFL",
        save=False, save_folder='.', fmt='svg', begin_pca="", end_pca="", angle=0):
    """
    NAME
       zeq.py

    DESCRIPTION
       plots demagnetization data for a single specimen:
          - The solid (open) symbols in the Zijderveld diagram are X,Y (X,Z) pairs.  The demagnetization diagram plots the
          fractional remanence remaining after each step. The green line is the fraction of the total remaence removed
          between each step.  If the principle direction is desired, specify begin_pca and end_pca steps as bounds for calculation.

          -The equal area projection has the X direction (usually North in geographic coordinates)
          to the top.  The red line is the X axis of the Zijderveld diagram.  Solid symbols are lower hemisphere.

          - red dots and blue line is the remanence remaining after each step.  The green line is the partial TRM removed in each interval

    INPUT FORMAT
       reads from  file_name or takes a  Pandas DataFrame data with specimen treatment intensity declination inclination   as columns

    Keywords:
        file= FILE   a space or tab delimited file with
            specimen  treatment  declination inclination intensity
        units= [mT,C] specify units of mT OR C, default is unscaled
        save=[True,False]  save figure and quit, default is False
        fmt [svg,jpg,png,pdf] set figure format [default is svg]
        begin_pca [step number] treatment step for beginning of PCA calculation, default
        end_pca [step number] treatment step for end of PCA calculation, last step is default
        calculation_type [DE-BFL,DE-BFP,DE-FM] Calculation Type: best-fit line,  plane or fisher mean; line is default
        angle=[0-360]: angle to subtract from declination to rotate in horizontal plane, default is 0

    """
    if units == "C":
        SIunits = "K"
    if units == "mT":
        SIunits = "T"
    if units == "U":
        SIunits = "U"
    if file != "":
        f = pd.read_csv(os.path.join(path_to_file, file),
                        delim_whitespace=True, header=None)
        f.columns = ['specimen', 'treatment',
                     'intensity', 'declination', 'inclination']
        # adjust for angle rotation
        f['declination'] = (f['declination']-angle) % 360
        f['quality'] = 'g'
        f['type'] = ''
#
        s = f['specimen'].tolist()[0]
        if units == 'mT':
            f['treatment'] = f['treatment']*1e-3
        if units == 'C':
            f['treatment'] = f['treatment']+273
        data = f[['treatment', 'declination',
                  'inclination', 'intensity', 'type', 'quality']]
    print(s)
    datablock = data.values.tolist()
# define figure numbers in a dictionary for equal area, zijderveld,
#  and intensity vs. demagnetiztion step respectively
    ZED = {}
    ZED['eqarea'], ZED['zijd'],  ZED['demag'] = 2, 1, 3
    plt.figure(num=ZED['zijd'], figsize=(5, 5))
    plt.figure(num=ZED['eqarea'], figsize=(5, 5))
    plt.figure(num=ZED['demag'], figsize=(5, 5))
#
#
    pmagplotlib.plot_zed(ZED, datablock, angle, s, SIunits)  # plot the data
#
# print out data for this sample to screen
#
    recnum = 0
    print('step treat  intensity  dec    inc')
    for plotrec in datablock:
        if units == 'mT':
            print('%i  %7.1f %8.3e %7.1f %7.1f ' %
                  (recnum, plotrec[0]*1e3, plotrec[3], plotrec[1], plotrec[2]))
        if units == 'C':
            print('%i  %7.1f %8.3e %7.1f %7.1f ' %
                  (recnum, plotrec[0]-273., plotrec[3], plotrec[1], plotrec[2]))
        if units == 'U':
            print('%i  %7.1f %8.3e %7.1f %7.1f ' %
                  (recnum, plotrec[0], plotrec[3], plotrec[1], plotrec[2]))
        recnum += 1
        pmagplotlib.draw_figs(ZED)
    if begin_pca != "" and end_pca != "" and calculation_type != "":
        pmagplotlib.plot_zed(ZED, datablock, angle, s,
                             SIunits)  # plot the data
        # get best-fit direction/great circle
        mpars = pmag.domean(datablock, begin_pca, end_pca, calculation_type)
        # plot the best-fit direction/great circle
        pmagplotlib.plot_dir(ZED, mpars, datablock, angle)
        print('Specimen, calc_type, N, min, max, MAD, dec, inc')
        if units == 'mT':
            print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' % (s, calculation_type,
                                                               mpars["specimen_n"], mpars["measurement_step_min"]*1e3, mpars["measurement_step_max"]*1e3, mpars["specimen_mad"], mpars["specimen_dec"], mpars["specimen_inc"]))
        if units == 'C':
            print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' % (s, calculation_type,
                                                               mpars["specimen_n"], mpars["measurement_step_min"]-273, mpars["measurement_step_max"]-273, mpars["specimen_mad"], mpars["specimen_dec"], mpars["specimen_inc"]))
        if units == 'U':
            print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' % (s, calculation_type,
                                                               mpars["specimen_n"], mpars["measurement_step_min"], mpars["measurement_step_max"], mpars["specimen_mad"], mpars["specimen_dec"], mpars["specimen_inc"]))
        if save:
            files = {}
            for key in list(ZED.keys()):
                files[key] = s+'_'+key+'.'+fmt
            pmagplotlib.save_plots(ZED, files)

Response: A function that creates a Zijderveld diagram showing the demagnetization data for a single specimen.


Instruction:
Implement a function in Python 3 to
make plots of anisotropy eigenvectors, eigenvalues and confidence bounds All directions are on the lower hemisphere. Parameters __________ infile : specimens formatted file with aniso_s data samp_file : samples formatted file with sample => site relationship site_file : sites formatted file with site => location relationship verbose : if True, print messages to output confidence bounds options: ipar : if True - perform parametric bootstrap - requires non-blank aniso_s_sigma ihext : if True - Hext ellipses ivec : if True - plot bootstrapped eigenvectors instead of ellipses isite : if True plot by site, requires non-blank samp_file #iloc : if True plot by location, requires non-blank samp_file, and site_file NOT IMPLEMENTED iboot : if True - bootstrap ellipses vec : eigenvector for comparison with Dir Dir : [Dec,Inc] list for comparison direction PDir : [Pole_dec, Pole_Inc] for pole to plane for comparison green dots are on the lower hemisphere, cyan are on the upper hemisphere crd : ['s','g','t'], coordinate system for plotting whereby: s : specimen coordinates, aniso_tile_correction = -1, or unspecified g : geographic coordinates, aniso_tile_correction = 0 t : tilt corrected coordinates, aniso_tile_correction = 100 num_bootstraps : how many bootstraps to do, default 1000 dir_path : directory path fignum : matplotlib figure number, default 1 save_plots : bool, default True if True, create and save all requested plots interactive : bool, default False interactively plot and display for each specimen (this is best used on the command line only) fmt : str, default "svg" format for figures, [svg, jpg, pdf, png]

Response:
def aniso_magic_nb(infile='specimens.txt', samp_file='samples.txt', site_file='sites.txt', verbose=True,
                   ipar=False, ihext=True, ivec=False, isite=False, iloc=False, iboot=False, vec=0,
                   Dir=[], PDir=[], crd="s", num_bootstraps=1000, dir_path=".", fignum=1,
                   save_plots=True, interactive=False, fmt="png"):
    """
    Makes plots of anisotropy eigenvectors, eigenvalues and confidence bounds
    All directions are on the lower hemisphere.

    Parameters
    __________
        infile : specimens formatted file with aniso_s data
        samp_file : samples formatted file with sample => site relationship
        site_file : sites formatted file with site => location relationship
        verbose : if True, print messages to output
        confidence bounds options:
            ipar : if True - perform parametric bootstrap - requires non-blank aniso_s_sigma
            ihext : if True - Hext ellipses
            ivec : if True - plot bootstrapped eigenvectors instead of ellipses
            isite : if True plot by site, requires non-blank samp_file
            #iloc : if True plot by location, requires non-blank samp_file, and site_file  NOT IMPLEMENTED
            iboot : if True - bootstrap ellipses
        vec : eigenvector for comparison with Dir
        Dir : [Dec,Inc] list for comparison direction
        PDir : [Pole_dec, Pole_Inc] for pole to plane for comparison
              green dots are on the lower hemisphere, cyan are on the upper hemisphere
        crd : ['s','g','t'], coordinate system for plotting whereby:
            s : specimen coordinates, aniso_tile_correction = -1, or unspecified
            g : geographic coordinates, aniso_tile_correction = 0
            t : tilt corrected coordinates, aniso_tile_correction = 100
        num_bootstraps : how many bootstraps to do, default 1000
        dir_path : directory path
        fignum : matplotlib figure number, default 1
        save_plots : bool, default True
            if True, create and save all requested plots
        interactive : bool, default False
            interactively plot and display for each specimen
            (this is best used on the command line only)
        fmt : str, default "svg"
            format for figures, [svg, jpg, pdf, png]

    """
    figs = {}
    saved = []
    # make sure boolean values are in integer form
    # for backwards compatibility
    ipar = int(ipar)
    ihext = int(ihext)
    ivec = int(ivec)
    isite = int(isite)
    #iloc = int(iloc) # NOT USED
    iboot = int(iboot)
    # fix directory
    input_dir_path = os.path.realpath(dir_path)
    # initialize some variables
    version_num = pmag.get_version()
    hpars, bpars = [], []
    # set aniso_tilt_correction value
    CS = -1  # specimen
    if crd == 'g':
        CS = 0
    if crd == 't':
        CS = 100

    #
    #
    # read in the data

    fnames = {'specimens': infile, 'samples': samp_file, 'sites': site_file}
    con = cb.Contribution(input_dir_path, read_tables=['specimens', 'samples', 'sites', 'contribution'],
                          custom_filenames=fnames)
    # get contribution id if available
    con_id = ""
    if 'contribution' in con.tables:
        if 'id' in con.tables['contribution'].df.columns:
            con_id = str(con.tables['contribution'].df['id'].values[0])
    # get other data
    con.propagate_location_to_specimens()
    spec_container = con.tables['specimens']
    spec_df = spec_container.df
    # use only anisotropy records
    spec_df = spec_df.dropna(subset=['aniso_s']).copy()
    if 'aniso_tilt_correction' not in spec_df.columns:
        spec_df['aniso_tilt_correction'] = -1  # assume specimen coordinates
    if "aniso_s_n_measurements" not in spec_df.columns:
        spec_df["aniso_s_n_measurements"] = "6"
    if "aniso_s_sigma" not in spec_df.columns:
        spec_df["aniso_sigma"] = "0"
    orlist = spec_df['aniso_tilt_correction'].dropna().unique()
    if CS not in orlist:
        if len(orlist) > 0:
            CS = orlist[0]
        else:
            CS = -1
        if CS == -1:
            crd = 's'
        if CS == 0:
            crd = 'g'
        if CS == 100:
            crd = 't'
        if verbose:
            print("desired coordinate system not available, using available: ", crd)
    cs_df = spec_df[spec_df['aniso_tilt_correction'] == CS]
    if isite:
        sites = cs_df['site'].unique()
        for site in list(sites):
            site_df = cs_df[cs_df.site == site]
            loc = ""
            if 'sites' in con.tables:
                if 'location' in con.tables['sites'].df.columns:
                    locs = con.tables['sites'].df.loc[site, 'location'].dropna()
                    if any(locs):
                        loc = locs.iloc[0]
            figs = plot_aniso(fignum, site_df, Dir=Dir, PDir=PDir, ipar=ipar,
                              ihext=ihext, ivec=ivec, iboot=iboot,
                              vec=vec, num_bootstraps=num_bootstraps, title=site)
            files = {key: loc + "_" + site +"_" + crd + "_aniso-" + key + ".png" for (key, value) in figs.items()}
            if pmagplotlib.isServer:
                for key in figs.keys():
                    files[key] = "LO:_" + loc + "_SI:_" + site +  '_TY:_aniso_' + key + '_.' + fmt
                    titles = {}
                    titles['data'] = "Eigenvectors"
                    titles['tcdf'] = "Eigenvalue Confidence"
                    titles['conf'] = "Confidence Ellipses"
                    for key in figs:
                        if key not in titles:
                            titles[key] = key
                pmagplotlib.add_borders(figs, titles, con_id=con_id)
            if save_plots:
                saved.extend(pmagplotlib.save_plots(figs, files))
            elif interactive:
                pmagplotlib.draw_figs(figs)
                ans = pmagplotlib.save_or_quit()
                if ans == 'a':
                    saved.extend(pmagplotlib.save_plots(figs, files))
                else:
                    continue
            else:
                fignum += 2
                if iboot:
                    fignum += 1
                if len(Dir) > 0:
                    fignum += 1
    else:
        figs = plot_aniso(fignum, cs_df, Dir=Dir, PDir=PDir, ipar=ipar, ihext=ihext,
                          ivec=ivec, iboot=iboot, vec=vec, num_bootstraps=num_bootstraps)
        try:
            locs = cs_df['location'].unique()
        except:
            locs = [""]
        locs = "-".join(locs)
        files = {key:  locs + "_" + crd + "_aniso-" + key + ".png" for (key, value) in figs.items()}
        if pmagplotlib.isServer:
            for key in figs.keys():
                files[key] = 'MC:_' + con_id + '_TY:_aniso_' + key + '_.' + fmt
                titles = {}
                titles['data'] = "Eigenvectors"
                titles['tcdf'] = "Eigenvalue Confidence"
                titles['conf'] = "Confidence Ellipses"
                for key in figs:
                    if key not in titles:
                        titles[key] = key
            pmagplotlib.add_borders(figs, titles, con_id=con_id)
        if save_plots:
            saved.extend(pmagplotlib.save_plots(figs, files))
        elif interactive:
            pmagplotlib.draw_figs(figs)
            ans = pmagplotlib.save_or_quit()
            if ans == 'a':
                saved.extend(pmagplotlib.save_plots(figs, files))
    return True, saved


Instruction:
How would you code a function in Python 3 to
plot demagenetization data versus step for all specimens in pandas dataframe datablock Parameters ______________ data : Pandas dataframe with MagIC data model 3 columns: fignum : figure number specimen : specimen name dmag_key : one of these: ['treat_temp','treat_ac_field','treat_mw_energy'] selected using method_codes : ['LT_T-Z','LT-AF-Z','LT-M-Z'] respectively intensity : if blank will choose one of these: ['magn_moment', 'magn_volume', 'magn_mass'] quality : if True use the quality column of the DataFrame title : title for plot norm : if True, normalize data to first step Output : matptlotlib plot

Response:
def plot_dmag(data="", title="", fignum=1, norm=1,dmag_key='treat_ac_field',intensity='',
             quality=False):
    """
    plots demagenetization data versus step for all specimens in pandas dataframe datablock

    Parameters
    ______________
    data : Pandas dataframe with MagIC data model 3 columns:
        fignum : figure number
        specimen : specimen name
        dmag_key : one of these: ['treat_temp','treat_ac_field','treat_mw_energy']
            selected using method_codes : ['LT_T-Z','LT-AF-Z','LT-M-Z'] respectively
        intensity  : if blank will choose one of these: ['magn_moment', 'magn_volume', 'magn_mass']
        quality : if True use the quality column of the DataFrame
     title : title for plot
     norm : if True, normalize data to first step
    Output :
      matptlotlib plot
   """
    plt.figure(num=fignum, figsize=(5, 5))
    if intensity:
        int_key=intensity
    else:
        intlist = ['magn_moment', 'magn_volume', 'magn_mass']
    # get which key we have
        IntMeths = [col_name for col_name in data.columns if col_name in intlist]
        int_key = IntMeths[0]
    data = data[data[int_key].notnull()]  # fish out all data with this key
    units = "U"  # this  sets the units for plotting to undefined
    if not dmag_key:
        if 'treat_temp' in data.columns: units = "K"  # kelvin
        elif 'treat_ac_field' in data.columns: units = "T"  # tesla
        elif 'treat_mw_energy' in data.columns: units = "J"  # joules
    if dmag_key=='treat_temp': units='K'
    if dmag_key=='treat_ac_field': units='T'
    if dmag_key=='treat_mw_energy': units='J'
    spcs = data.specimen.unique()  # get a list of all specimens in DataFrame data
    if len(spcs)==0:
        print('no data for plotting')
        return
    # step through specimens to put on plot
    for spc in spcs:
        spec_data = data[data.specimen.str.contains(spc)]
        INTblock = []
        for ind, rec in spec_data.iterrows():
            INTblock.append([float(rec[dmag_key]), 0, 0,
                             float(rec[int_key]), 1, rec['quality']])
        if len(INTblock) > 2:
            pmagplotlib.plot_mag(fignum, INTblock, title, 0, units, norm)


Instruction:
Implement a function in Python 3 to
convert eigenparamters format data to s format

Response:
def eigs_s(infile="", dir_path='.'):
    """
    Converts eigenparamters format data to s format

    Parameters
    ___________________
    Input:
        file : input file name with eigenvalues (tau) and eigenvectors (V) with  format:
            tau_1 V1_dec V1_inc tau_2 V2_dec V2_inc tau_3 V3_dec V3_inc
    Output
         the six tensor elements as a nested array
          [[x11,x22,x33,x12,x23,x13],....]

    """
    file = os.path.join(dir_path, infile)
    eigs_data = np.loadtxt(file)
    Ss = []
    for ind in range(eigs_data.shape[0]):
        tau, Vdirs = [], []
        for k in range(0, 9, 3):
            tau.append(eigs_data[ind][k])
            Vdirs.append([eigs_data[ind][k+1], eigs_data[ind][k+2]])
        s = list(pmag.doeigs_s(tau, Vdirs))
        Ss.append(s)
    return Ss


Instruction:
Can you tell what is the following Python 3 function doing
def plot_gc(poles, color='g', fignum=1):
    for pole in poles:
        pmagplotlib.plot_circ(fignum, pole, 90., color)

Response: Plots a great circle on an equal area projection