Instruction:
Implement a Python 3 function for
plotting the b - element of the araiblock.

Response:
def plot_b(Figs, araiblock, zijdblock, pars):
    """
    deprecated (used in thellier_magic/microwave_magic)
    """
    angle = zijdblock[0][1]
    plotblock = []
    Dir, zx, zy, zz, ax, ay = [], [], [], [], [], []
    zstart, zend = 0, len(zijdblock)
    first_Z, first_I = araiblock[0], araiblock[1]
    for rec in zijdblock:
        if rec[0] == pars["measurement_step_min"]:
            Dir.append((rec[1] - angle, rec[2],
                        old_div(rec[3], zijdblock[0][3])))
        if rec[0] == pars["measurement_step_max"]:
            Dir.append((rec[1] - angle, rec[2],
                        old_div(rec[3], zijdblock[0][3])))
    for drec in Dir:
        cart = pmag.dir2cart(drec)
        zx.append(cart[0])
      #   zy.append(-cart[1])
      #   zz.append(-cart[2])
        zy.append(cart[1])
        zz.append(cart[2])
    if len(zx) > 0:
        plt.figure(num=Figs['zijd'])
        plt.scatter(zx, zy, marker='d', s=100, c='y')
        plt.scatter(zx, zz, marker='d', s=100, c='y')
        plt.axis("equal")
    ax.append(old_div(first_I[0][3], first_Z[0][3]))
    ax.append(old_div(first_I[-1][3], first_Z[0][3]))
    ay.append(old_div(first_Z[0][3], first_Z[0][3]))
    ay.append(old_div(first_Z[-1][3], first_Z[0][3]))
    for k in range(len(first_Z)):
        if first_Z[k][0] == pars["measurement_step_min"]:
            ay[0] = (old_div(first_Z[k][3], first_Z[0][3]))
        if first_Z[k][0] == pars["measurement_step_max"]:
            ay[1] = (old_div(first_Z[k][3], first_Z[0][3]))
        if first_I[k][0] == pars["measurement_step_min"]:
            ax[0] = (old_div(first_I[k][3], first_Z[0][3]))
        if first_I[k][0] == pars["measurement_step_max"]:
            ax[1] = (old_div(first_I[k][3], first_Z[0][3]))
    new_Z, new_I = [], []
    for zrec in first_Z:
        if zrec[0] >= pars['measurement_step_min'] and zrec[0] <= pars['measurement_step_max']:
            new_Z.append(zrec)
    for irec in first_I:
        if irec[0] >= pars['measurement_step_min'] and irec[0] <= pars['measurement_step_max']:
            new_I.append(irec)
    newblock = [new_Z, new_I]
    plot_teq(Figs['eqarea'], newblock, "", pars)
    plt.figure(num=Figs['arai'])
    plt.scatter(ax, ay, marker='d', s=100, c='y')
#
#  find midpoint between two endpoints
#
    sy = []
    sy.append((pars["specimen_b"] * ax[0] +
               old_div(pars["specimen_ytot"], first_Z[0][3])))
    sy.append((pars["specimen_b"] * ax[1] +
               old_div(pars["specimen_ytot"], first_Z[0][3])))
    plt.plot(ax, sy, 'g', linewidth=2)
    bounds = plt.axis()
    if pars['specimen_grade'] != '':
        notestr = 'Grade: ' + pars["specimen_grade"]
        plt.text(.7 * bounds[1], .9 * bounds[3], notestr)
    notestr = 'B: ' + '%6.2f' % (pars["specimen_int"] * 1e6) + ' uT'
    plt.text(.7 * bounds[1], .8 * bounds[3], notestr)


Instruction:
Create a Python 3 function for
making a single line plot on a great circle with alpha 95 and mean deprecated ( used in pmagplotlib

Response:
def plot_slnp(fignum, SiteRec, datablock, key):
    """
    plots lines and planes on a great  circle with alpha 95 and mean
    deprecated (used in pmagplotlib)
    """
# make the stereonet
    plt.figure(num=fignum)
    plot_net(fignum)
    s = SiteRec['er_site_name']
#
#   plot on the data
#
    coord = SiteRec['site_tilt_correction']
    title = ''
    if coord == '-1':
        title = s + ": specimen coordinates"
    if coord == '0':
        title = s + ": geographic coordinates"
    if coord == '100':
        title = s + ": tilt corrected coordinates"
    DIblock, GCblock = [], []
    for plotrec in datablock:
        if plotrec[key + '_direction_type'] == 'p':  # direction is pole to plane
            GCblock.append(
                (float(plotrec[key + "_dec"]), float(plotrec[key + "_inc"])))
        else:  # assume direction is a directed line
            DIblock.append(
                (float(plotrec[key + "_dec"]), float(plotrec[key + "_inc"])))
    if len(DIblock) > 0:
        plot_di(fignum, DIblock)  # plot directed lines
    if len(GCblock) > 0:
        for pole in GCblock:
            plot_circ(fignum, pole, 90., 'g')  # plot directed lines
#
# put on the mean direction
#
    x, y = [], []
    XY = pmag.dimap(float(SiteRec["site_dec"]), float(SiteRec["site_inc"]))
    x.append(XY[0])
    y.append(XY[1])
    plt.scatter(x, y, marker='d', s=80, c='g')
    plt.title(title)
#
# get the alpha95
#
    Xcirc, Ycirc = [], []
    Da95, Ia95 = pmag.circ(float(SiteRec["site_dec"]), float(
        SiteRec["site_inc"]), float(SiteRec["site_alpha95"]))
    for k in range(len(Da95)):
        XY = pmag.dimap(Da95[k], Ia95[k])
        Xcirc.append(XY[0])
        Ycirc.append(XY[1])
    plt.plot(Xcirc, Ycirc, 'g')


Instruction:
Given the following Python 3 function, write the documentation
def plot_lnp(fignum, s, datablock, fpars, direction_type_key):
# make the stereonet
    plot_net(fignum)
#
#   plot on the data
#
    dec_key, inc_key, tilt_key = 'dec', 'inc', 'tilt_correction'
    if 'dir_dec' in datablock[0].keys():  # this is data model 3.0
        dec_key, inc_key, tilt_key = 'dir_dec', 'dir_inc', 'dir_tilt_correction'
    coord = datablock[0][tilt_key]
    title = s
    if coord == '-1':
        title = title + ": specimen coordinates"
    if coord == '0':
        title = title + ": geographic coordinates"
    if coord == '100':
        title = title + ": tilt corrected coordinates"
    DIblock, GCblock = [], []
    for plotrec in datablock:
        if plotrec[direction_type_key] == 'p':  # direction is pole to plane
            GCblock.append((float(plotrec[dec_key]), float(plotrec[inc_key])))
        else:  # assume direction is a directed line
            DIblock.append((float(plotrec[dec_key]), float(plotrec[inc_key])))
    if len(DIblock) > 0:
        plot_di(fignum, DIblock)  # plot directed lines
    if len(GCblock) > 0:
        for pole in GCblock:
            plot_circ(fignum, pole, 90., 'g')  # plot directed lines
#
# put on the mean direction
#
    x, y = [], []
    XY = pmag.dimap(float(fpars["dec"]), float(fpars["inc"]))
    x.append(XY[0])
    y.append(XY[1])
    plt.figure(num=fignum)
    plt.scatter(x, y, marker='d', s=80, c='g')
    plt.title(title)
#
# get the alpha95
#
    Xcirc, Ycirc = [], []
    Da95, Ia95 = pmag.circ(float(fpars["dec"]), float(
        fpars["inc"]), float(fpars["alpha95"]))
    for k in range(len(Da95)):
        XY = pmag.dimap(Da95[k], Ia95[k])
        Xcirc.append(XY[0])
        Ycirc.append(XY[1])
    plt.plot(Xcirc, Ycirc, 'g')

Response: make the lnp plot on the stereonet object s


Instruction:
Can you implement a function in Python 3 that
plots the eqarea projection

Response:
def plot_eq(fignum, DIblock, s):
    """
    plots directions on eqarea projection
    Parameters
    __________
    fignum : matplotlib figure number
    DIblock : nested list of dec/inc pairs
    s : specimen name
    """
# make the stereonet
    plt.figure(num=fignum)
    if len(DIblock) < 1:
        return
    # plt.clf()
    if not isServer:
        plt.figtext(.02, .01, version_num)
    plot_net(fignum)
#
#   put on the directions
#
    plot_di(fignum, DIblock)  # plot directions
    plt.axis("equal")
    plt.text(-1.1, 1.15, s)
    plt.draw()


Instruction:
Write a Python 3 script for
plotting directions with specified symbol in the same site as DIblock.

Response:
def plot_eq_sym(fignum, DIblock, s, sym):
    """
    plots directions with specified symbol
    Parameters
    __________
    fignum : matplotlib figure number
    DIblock : nested list of dec/inc pairs
    s : specimen name
    sym : matplotlib symbol (e.g., 'bo' for blue circle)
    """
# make the stereonet
    plt.figure(num=fignum)
    if len(DIblock) < 1:
        return
    # plt.clf()
    if not isServer:
        plt.figtext(.02, .01, version_num)
    plot_net(fignum)
#
#   put on the directions
#
    plot_di_sym(fignum, DIblock, sym)  # plot directions with symbols in sym
    plt.axis("equal")
    plt.text(-1.1, 1.15, s)


Instruction:
Write a Python 3 function that can
plot the television of the object.

Response:
def plot_teq(fignum, araiblock, s, pars):
    """
    plots directions  of pTRM steps and zero field steps

    Parameters
    __________
    fignum : figure number for matplotlib object
    araiblock : nested list of data from pmag.sortarai()
    s : specimen name
    pars : default is "",
        otherwise is dictionary with keys:
        'measurement_step_min' and 'measurement_step_max'

    Effects
    _______
    makes the equal area projection with color coded symbols
        red circles: ZI steps
        blue squares: IZ steps
        yellow : pTRM steps

    """
    first_Z, first_I = araiblock[0], araiblock[1]
# make the stereonet
    plt.figure(num=fignum)
    plt.clf()
    ZIblock, IZblock, pTblock = [], [], []
    for zrec in first_Z:  # sort out the zerofield steps
        if zrec[4] == 1:  # this is a ZI step
            ZIblock.append([zrec[1], zrec[2]])
        else:
            IZblock.append([zrec[1], zrec[2]])
    plot_net(fignum)
    if pars != "":
        min, max = float(pars["measurement_step_min"]), float(
            pars["measurement_step_max"])
    else:
        min, max = first_I[0][0], first_I[-1][0]
    for irec in first_I:
        if irec[1] != 0 and irec[1] != 0 and irec[0] >= min and irec[0] <= max:
            pTblock.append([irec[1], irec[2]])
    if len(ZIblock) < 1 and len(IZblock) < 1 and len(pTblock) < 1:
        return
    if not isServer:
        plt.figtext(.02, .01, version_num)
#
#   put on the directions
#
    sym = {'lower': ['o', 'r'], 'upper': ['o', 'm']}
    if len(ZIblock) > 0:
        plot_di_sym(fignum, ZIblock, sym)  # plot ZI directions
    sym = {'lower': ['s', 'b'], 'upper': ['s', 'c']}
    if len(IZblock) > 0:
        plot_di_sym(fignum, IZblock, sym)  # plot IZ directions
    sym = {'lower': ['^', 'g'], 'upper': ['^', 'y']}
    if len(pTblock) > 0:
        plot_di_sym(fignum, pTblock, sym)  # plot pTRM directions
    plt.axis("equal")
    plt.text(-1.1, 1.15, s)


Instruction:
Can you tell what is the following Python 3 function doing
def save_plots(Figs, filenames, **kwargs):
    saved = []
    for key in list(Figs.keys()):
        try:
            plt.figure(num=Figs[key])
            fname = filenames[key]
            if set_env.IS_WIN:  # always truncate filenames if on Windows
                fname = os.path.split(fname)[1]
            if not isServer:  # remove illegal ':' character for windows
                fname = fname.replace(':', '_')
            if 'incl_directory' in kwargs.keys() and not set_env.IS_WIN:
                if kwargs['incl_directory']:
                    pass # do not flatten file name
                else:
                    fname = fname.replace('/', '-') # flatten file name
            else:
                fname = fname.replace('/', '-') # flatten file name
            if 'dpi' in list(kwargs.keys()):
                plt.savefig(fname, dpi=kwargs['dpi'])
            elif isServer:
                plt.savefig(fname, dpi=240)
            else:
                plt.savefig(fname)
            if verbose:
                print(Figs[key], " saved in ", fname)
            saved.append(fname)
            plt.close(Figs[key])
        except Exception as ex:
            print(type(ex), ex)
            print('could not save: ', Figs[key], filenames[key])
            print("output file format not supported ")
    return saved

Response: Save the plots of the current language and associated resources.


Instruction:
Create a Python 3 function for
plotting eigenvector directions of S vectors

Response:
def plot_evec(fignum, Vs, symsize, title):
    """
    plots eigenvector directions of S vectors

    Paramters
    ________
    fignum : matplotlib figure number
    Vs : nested list of eigenvectors
    symsize : size in pts for symbol
    title : title for plot
    """
#
    plt.figure(num=fignum)
    plt.text(-1.1, 1.15, title)
    # plot V1s as squares, V2s as triangles and V3s as circles
    symb, symkey = ['s', 'v', 'o'], 0
    col = ['r', 'b', 'k']  # plot V1s rec, V2s blue, V3s black
    for VEC in range(3):
        X, Y = [], []
        for Vdirs in Vs:
            #
            #
            #   plot the V1 data  first
            #
            XY = pmag.dimap(Vdirs[VEC][0], Vdirs[VEC][1])
            X.append(XY[0])
            Y.append(XY[1])
        plt.scatter(X, Y, s=symsize,
                    marker=symb[VEC], c=col[VEC], edgecolors='none')
    plt.axis("equal")


Instruction:
Write a Python 3 function for
functioning to plot the points on an ellipse about Pdec Pdip with angle beta gamma Gdec Ginc and Ginc.

Response:
def plot_ell(fignum, pars, col, lower, plot):
    """
    function to calcualte/plot points on an ellipse about Pdec,Pdip with angle beta,gamma
    Parameters
    _________
    fignum : matplotlib figure number
    pars : list of [Pdec, Pinc, beta, Bdec, Binc, gamma, Gdec, Ginc ]
         where P is direction, Bdec,Binc are beta direction, and Gdec,Ginc are gamma direction
    col : color for ellipse
    lower : boolean, if True, lower hemisphere projection
    plot : boolean, if False, return the points, if False, make the plot
    """
    plt.figure(num=fignum)
    rad = old_div(np.pi, 180.)
    Pdec, Pinc, beta, Bdec, Binc, gamma, Gdec, Ginc = pars[0], pars[
        1], pars[2], pars[3], pars[4], pars[5], pars[6], pars[7]
    if beta > 90. or gamma > 90:
        beta = 180. - beta
        gamma = 180. - gamma
        Pdec = Pdec - 180.
        Pinc = -Pinc
    beta, gamma = beta * rad, gamma * rad  # convert to radians
    X_ell, Y_ell, X_up, Y_up, PTS = [], [], [], [], []
    nums = 201
    xnum = old_div(float(nums - 1.), 2.)
# set up t matrix
    t = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    X = pmag.dir2cart((Pdec, Pinc, 1.0))  # convert to cartesian coordintes
    if lower == 1 and X[2] < 0:
        for i in range(3):
            X[i] = -X[i]
# set up rotation matrix t
    t[0][2] = X[0]
    t[1][2] = X[1]
    t[2][2] = X[2]
    X = pmag.dir2cart((Bdec, Binc, 1.0))
    if lower == 1 and X[2] < 0:
        for i in range(3):
            X[i] = -X[i]
    t[0][0] = X[0]
    t[1][0] = X[1]
    t[2][0] = X[2]
    X = pmag.dir2cart((Gdec, Ginc, 1.0))
    if lower == 1 and X[2] < 0:
        for i in range(3):
            X[i] = -X[i]
    t[0][1] = X[0]
    t[1][1] = X[1]
    t[2][1] = X[2]
# set up v matrix
    v = [0, 0, 0]
    for i in range(nums):  # incremental point along ellipse
        psi = float(i) * np.pi / xnum
        v[0] = np.sin(beta) * np.cos(psi)
        v[1] = np.sin(gamma) * np.sin(psi)
        v[2] = np.sqrt(1. - v[0]**2 - v[1]**2)
        elli = [0, 0, 0]
# calculate points on the ellipse
        for j in range(3):
            for k in range(3):
                # cartesian coordinate j of ellipse
                elli[j] = elli[j] + t[j][k] * v[k]
        pts = pmag.cart2dir(elli)
        PTS.append([pts[0], pts[1]])
        # put on an equal area projection
        R = old_div(np.sqrt(
            1. - abs(elli[2])), (np.sqrt(elli[0]**2 + elli[1]**2)))
        if elli[2] <= 0:
            #            for i in range(3): elli[i]=-elli[i]
            X_up.append(elli[1] * R)
            Y_up.append(elli[0] * R)
        else:
            X_ell.append(elli[1] * R)
            Y_ell.append(elli[0] * R)
    if plot == 1:
        col = col[0]+'.'
        if X_ell != []:
            plt.plot(X_ell, Y_ell, col, markersize=3)
        if X_up != []:
            plt.plot(X_up, Y_up, col, markersize=3)
    else:
        return PTS


Instruction:
How would you explain what the following Python 3 function does
def plot_strat(fignum, data, labels):
    vertical_plot_init(fignum, 10, 3)
    xlab, ylab, title = labels[0], labels[1], labels[2]
    X, Y = [], []
    for rec in data:
        X.append(rec[0])
        Y.append(rec[1])
    plt.plot(X, Y)
    plt.plot(X, Y, 'ro')
    plt.xlabel(xlab)
    plt.ylabel(ylab)
    plt.title(title)

Response: Plots a time series with the given data.


Instruction:
How would you explain what the following Python 3 function does
def plot_cdf(fignum, data, xlab, sym, title, **kwargs):
#
    #if len(sym)==1:sym=sym+'-'
    fig = plt.figure(num=fignum)
    # sdata=np.array(data).sort()
    sdata = []
    for d in data:
        sdata.append(d)  # have to copy the data to avoid overwriting it!
    sdata.sort()
    X, Y = [], []
    color = ""
    for j in range(len(sdata)):
        Y.append(old_div(float(j), float(len(sdata))))
        X.append(sdata[j])
    if 'color' in list(kwargs.keys()):
        color = kwargs['color']
    if 'linewidth' in list(kwargs.keys()):
        lw = kwargs['linewidth']
    else:
        lw = 1
    if color != "":
        plt.plot(X, Y, color=sym, linewidth=lw)
    else:
        plt.plot(X, Y, sym, linewidth=lw)

    plt.xlabel(xlab)
    plt.ylabel('Cumulative Distribution')
    plt.title(title)
    return X, Y

Response: Plots the cumulative distribution function.


Instruction:
Write a Python 3 script to
plot horizontal lines at Ys values at Ys values

Response:
def plot_hs(fignum, Ys, c, ls):
    """
    plots  horizontal lines at Ys values

    Parameters
    _________
    fignum : matplotlib figure number
    Ys : list of Y values for lines
    c : color for lines
    ls : linestyle for lines
    """
    fig = plt.figure(num=fignum)
    for yv in Ys:
        bounds = plt.axis()
        plt.axhline(y=yv, xmin=0, xmax=1, linewidth=1, color=c, linestyle=ls)


Instruction:
Write a Python 3 script to
plot the vertical lines at Xs values at Xs

Response:
def plot_vs(fignum, Xs, c, ls):
    """
    plots  vertical lines at Xs values

    Parameters
    _________
    fignum : matplotlib figure number
    Xs : list of X values for lines
    c : color for lines
    ls : linestyle for lines
    """
    fig = plt.figure(num=fignum)
    for xv in Xs:
        bounds = plt.axis()
        plt.axvline(
            x=xv, ymin=bounds[2], ymax=bounds[3], linewidth=1, color=c, linestyle=ls)


Instruction:
Write a Python 3 script to
plot the geomagnetic polarity time scale for a set of dates.

Response:
def plot_ts(fignum, dates, ts):
    """
    plot the geomagnetic polarity time scale

    Parameters
    __________
    fignum : matplotlib figure number
    dates : bounding dates for plot
    ts : time scale ck95, gts04, or gts12
    """
    vertical_plot_init(fignum, 10, 3)
    TS, Chrons = pmag.get_ts(ts)
    p = 1
    X, Y = [], []
    for d in TS:
        if d <= dates[1]:
            if d >= dates[0]:
                if len(X) == 0:
                    ind = TS.index(d)
                    X.append(TS[ind - 1])
                    Y.append(p % 2)
                X.append(d)
                Y.append(p % 2)
                p += 1
                X.append(d)
                Y.append(p % 2)
        else:
            X.append(dates[1])
            Y.append(p % 2)
            plt.plot(X, Y, 'k')
            plot_vs(fignum, dates, 'w', '-')
            plot_hs(fignum, [1.1, -.1], 'w', '-')
            plt.xlabel("Age (Ma): " + ts)
            isign = -1
            for c in Chrons:
                off = -.1
                isign = -1 * isign
                if isign > 0:
                    off = 1.05
                if c[1] >= X[0] and c[1] < X[-1]:
                    plt.text(c[1] - .2, off, c[0])
            return


Instruction:
Implement a function in Python 3 to
function to plot Delta M curves

Response:
def plot_delta_m(fignum, B, DM, Bcr, s):
    """
    function to plot Delta M curves

    Parameters
    __________
    fignum : matplotlib figure number
    B : array of field values
    DM : array of difference between top and bottom curves in hysteresis loop
    Bcr : coercivity of remanence
    s : specimen name
    """
    plt.figure(num=fignum)
    plt.clf()
    if not isServer:
        plt.figtext(.02, .01, version_num)
    plt.plot(B, DM, 'b')
    plt.xlabel('B (T)')
    plt.ylabel('Delta M')
    linex = [0, Bcr, Bcr]
    liney = [old_div(DM[0], 2.), old_div(DM[0], 2.), 0]
    plt.plot(linex, liney, 'r')
    plt.title(s)


Instruction:
Can you generate the documentation for the following Python 3 function
def plot_d_delta_m(fignum, Bdm, DdeltaM, s):
    plt.figure(num=fignum)
    plt.clf()
    if not isServer:
        plt.figtext(.02, .01, version_num)
    start = len(Bdm) - len(DdeltaM)
    plt.plot(Bdm[start:], DdeltaM, 'b')
    plt.xlabel('B (T)')
    plt.ylabel('d (Delta M)/dB')
    plt.title(s)

Response: Function to plot d delta M


Instruction:
Given the following Python 3 function, write the documentation
def plot_imag(fignum, Bimag, Mimag, s):
    plt.figure(num=fignum)
    plt.clf()
    if not isServer:
        plt.figtext(.02, .01, version_num)
    plt.plot(Bimag, Mimag, 'r')
    plt.xlabel('B (T)')
    plt.ylabel('M/Ms')
    plt.axvline(0, color='k')
    plt.title(s)

Response: function to plot the imaginary Bimag and Mimag


Instruction:
Here you have a function in Python 3, explain what it does
def plot_hdd(HDD, B, M, s):
    hpars, deltaM, Bdm = plot_hys(
        HDD['hyst'], B, M, s)  # Moff is the "fixed" loop data
    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 = np.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:
            plot_delta_m(HDD['deltaM'], Bdm, deltaM, Bcr, s)
            plt.axhline(0, color='k')
            plt.axvline(0, color='k')
            plot_d_delta_m(HDD['DdeltaM'], Bdm, DdeltaM, s)
    except:
        hpars['hysteresis_bcr'] = '0'
        hpars['magic_method_codes'] = ""
    return hpars

Response: Function to make hysteresis plot for a given set of fields in the tesla t t


Instruction:
Given the following Python 3 function, write the documentation
def plot_day(fignum, BcrBc, S, sym, **kwargs):
    plt.figure(num=fignum)
    plt.plot(BcrBc, S, sym)
    plt.axhline(0, color='k')
    plt.axhline(.05, color='k')
    plt.axhline(.5, color='k')
    plt.axvline(1, color='k')
    plt.axvline(4, color='k')
    plt.xlabel('Bcr/Bc')
    plt.ylabel('Mr/Ms')
    plt.title('Day Plot')
    plt.xlim(0, 6)
    #bounds= plt.axis()
    #plt.axis([0, bounds[1],0, 1])
    mu_o = 4. * np.pi * 1e-7
    Bc_sd = 46e-3  # (MV1H) dunlop and carter-stiglitz 2006 (in T)
    Bc_md = 5.56e-3  # (041183) dunlop and carter-stiglitz 2006 (in T)
    chi_sd = 5.20e6 * mu_o  # now in T
    chi_md = 4.14e6 * mu_o  # now in T
    chi_r_sd = 4.55e6 * mu_o  # now in T
    chi_r_md = 0.88e6 * mu_o  # now in T
    Bcr_sd, Bcr_md = 52.5e-3, 26.1e-3  # (MV1H and 041183 in DC06 in tesla)
    Ms = 480e3  # A/m
    p = .1  # from Dunlop 2002
    N = old_div(1., 3.)  # demagnetizing factor
    f_sd = np.arange(1., 0., -.01)  # fraction of sd
    f_md = 1. - f_sd  # fraction of md
    f_sp = 1. - f_sd  # fraction of sp
    # Mr/Ms ratios for USD,MD and Jax shaped
    sdrat, mdrat, cbrat = 0.498, 0.048, 0.6
    Mrat = f_sd * sdrat + f_md * mdrat  # linear mixing - eq. 9 in Dunlop 2002
    Bc = old_div((f_sd * chi_sd * Bc_sd + f_md * chi_md * Bc_md),
                 (f_sd * chi_sd + f_md * chi_md))  # eq. 10 in Dunlop 2002
    Bcr = old_div((f_sd * chi_r_sd * Bcr_sd + f_md * chi_r_md * Bcr_md),
                  (f_sd * chi_r_sd + f_md * chi_r_md))  # eq. 11 in Dunlop 2002
    chi_sps = np.arange(1, 5) * chi_sd
    plt.plot(old_div(Bcr, Bc), Mrat, 'r-')
    if 'names' in list(kwargs.keys()):
        names = kwargs['names']
        for k in range(len(names)):
            plt.text(BcrBc[k], S[k], names[k])

Response: Function to plot the day of the chemical structure of the current state of the atom.


Instruction:
Given the following Python 3 function, write the documentation
def plot_s_bc(fignum, Bc, S, sym):
    plt.figure(num=fignum)
    plt.plot(Bc, S, sym)
    plt.xlabel('Bc')
    plt.ylabel('Mr/Ms')
    plt.title('Squareness-Coercivity Plot')
    bounds = plt.axis()
    plt.axis([0, bounds[1], 0, 1])

Response: Function to plot Squareness - Coercivity


Instruction:
Here you have a function in Python 3, explain what it does
def plot_s_bcr(fignum, Bcr, S, sym):
    plt.figure(num=fignum)
    plt.plot(Bcr, S, sym)
    plt.xlabel('Bcr')
    plt.ylabel('Mr/Ms')
    plt.title('Squareness-Bcr Plot')
    bounds = plt.axis()
    plt.axis([0, bounds[1], 0, 1])

Response: Function to plot Squareness Coercivity of remanence


Instruction:
Can you generate a brief explanation for the following Python 3 code
def plot_bcr(fignum, Bcr1, Bcr2):
    plt.figure(num=fignum)
    plt.plot(Bcr1, Bcr2, 'ro')
    plt.xlabel('Bcr1')
    plt.ylabel('Bcr2')
    plt.title('Compare coercivity of remanence')

Response: function to plot two estimates of Bcr against each other


Instruction:
Explain what the following Python 3 code does
def plot_hpars(HDD, hpars, sym):
    plt.figure(num=HDD['hyst'])
    X, Y = [], []
    X.append(0)
    Y.append(old_div(float(hpars['hysteresis_mr_moment']), float(
        hpars['hysteresis_ms_moment'])))
    X.append(float(hpars['hysteresis_bc']))
    Y.append(0)
    plt.plot(X, Y, sym)
    bounds = plt.axis()
    n4 = 'Ms: ' + '%8.2e' % (float(hpars['hysteresis_ms_moment'])) + ' Am^2'
    plt.text(bounds[1] - .9 * bounds[1], -.9, n4)
    n1 = 'Mr: ' + '%8.2e' % (float(hpars['hysteresis_mr_moment'])) + ' Am^2'
    plt.text(bounds[1] - .9 * bounds[1], -.7, n1)
    n2 = 'Bc: ' + '%8.2e' % (float(hpars['hysteresis_bc'])) + ' T'
    plt.text(bounds[1] - .9 * bounds[1], -.5, n2)
    if 'hysteresis_xhf' in list(hpars.keys()):
        n3 = r'Xhf: ' + '%8.2e' % (float(hpars['hysteresis_xhf'])) + ' m^3'
        plt.text(bounds[1] - .9 * bounds[1], -.3, n3)
    plt.figure(num=HDD['deltaM'])
    X, Y, Bcr = [], [], ""
    if 'hysteresis_bcr' in list(hpars.keys()):
        X.append(float(hpars['hysteresis_bcr']))
        Y.append(0)
        Bcr = float(hpars['hysteresis_bcr'])
    plt.plot(X, Y, sym)
    bounds = plt.axis()
    if Bcr != "":
        n1 = 'Bcr: ' + '%8.2e' % (Bcr) + ' T'
        plt.text(bounds[1] - .5 * bounds[1], .9 * bounds[3], n1)

Response: function to plot hysteresis parameters


Instruction:
How would you explain what the following Python 3 function does
def plot_irm(fignum, B, M, title):
    rpars = {}
    Mnorm = []
    backfield = 0
    X, Y = [], []
    for k in range(len(B)):
        if M[k] < 0:
            break
    if k <= 5:
        kmin = 0
    else:
        kmin = k - 5
    for k in range(kmin, k + 1):
        X.append(B[k])
        if B[k] < 0:
            backfield = 1
        Y.append(M[k])
    if backfield == 1:
        poly = np.polyfit(X, Y, 1)
        if poly[0] != 0:
            bcr = (old_div(-poly[1], poly[0]))
        else:
            bcr = 0
        rpars['remanence_mr_moment'] = '%8.3e' % (M[0])
        rpars['remanence_bcr'] = '%8.3e' % (-bcr)
        rpars['magic_method_codes'] = 'LP-BCR-BF'
        if M[0] != 0:
            for m in M:
                Mnorm.append(old_div(m, M[0]))  # normalize to unity Msat
            title = title + ':' + '%8.3e' % (M[0])
    else:
        if M[-1] != 0:
            for m in M:
                Mnorm.append(old_div(m, M[-1]))  # normalize to unity Msat
            title = title + ':' + '%8.3e' % (M[-1])
# do plots if desired
    if fignum != 0 and M[0] != 0:  # skip plot for fignum = 0
        plt.figure(num=fignum)
        plt.clf()
        if not isServer:
            plt.figtext(.02, .01, version_num)
        plt.plot(B, Mnorm)
        plt.axhline(0, color='k')
        plt.axvline(0, color='k')
        plt.xlabel('B (T)')
        plt.ylabel('M/Mr')
        plt.title(title)
        if backfield == 1:
            plt.scatter([bcr], [0], marker='s', c='b')
            bounds = plt.axis()
            n1 = 'Bcr: ' + '%8.2e' % (-bcr) + ' T'
            plt.figtext(.2, .5, n1)
            n2 = 'Mr: ' + '%8.2e' % (M[0]) + ' Am^2'
            plt.figtext(.2, .45, n2)
    elif fignum != 0:
        plt.figure(num=fignum)
        # plt.clf()
        if not isServer:
            plt.figtext(.02, .01, version_num)
        print('M[0]=0,  skipping specimen')
    return rpars

Response: function to plot IRM backfield curves


Instruction:
Write a Python 3 function for
functioning to plot series of chi measurements as a function of temperature holding field constant and varying frequency

Response:
def plot_xtf(fignum, XTF, Fs, e, b):
    """
    function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency
    """
    plt.figure(num=fignum)
    plt.xlabel('Temperature (K)')
    plt.ylabel('Susceptibility (m^3/kg)')
    k = 0
    Flab = []
    for freq in XTF:
        T, X = [], []
        for xt in freq:
            X.append(xt[0])
            T.append(xt[1])
        plt.plot(T, X)
        plt.text(T[-1], X[-1], str(int(Fs[k])) + ' Hz')
#        Flab.append(str(int(Fs[k]))+' Hz')
        k += 1
    plt.title(e + ': B = ' + '%8.1e' % (b) + ' T')


Instruction:
Implement a Python 3 function for
functioning to plot series of chi measurements as a function of temperature holding frequency constant and varying B

Response:
def plot_xtb(fignum, XTB, Bs, e, f):
    """ function to plot series of chi measurements as a function of temperature, holding frequency constant and varying B
    """
    plt.figure(num=fignum)
    plt.xlabel('Temperature (K)')
    plt.ylabel('Susceptibility (m^3/kg)')
    k = 0
    Blab = []
    for field in XTB:
        T, X = [], []
        for xt in field:
            X.append(xt[0])
            T.append(xt[1])
        plt.plot(T, X)
        plt.text(T[-1], X[-1], '%8.2e' % (Bs[k]) + ' T')
#        Blab.append('%8.1e'%(Bs[k])+' T')
        k += 1
    plt.title(e + ': f = ' + '%i' % (int(f)) + ' Hz')


Instruction:
Here you have a function in Python 3, explain what it does
def plot_xft(fignum, XF, T, e, b):
    plt.figure(num=fignum)
    plt.clf()
    if not isServer:
        plt.figtext(.02, .01, version_num)
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Susceptibility (m^3/kg)')
    k = 0
    F, X = [], []
    for xf in XF:
        X.append(xf[0])
        F.append(xf[1])
    plt.plot(F, X)
    plt.semilogx()
    plt.title(e + ': B = ' + '%8.1e' % (b) + ' T')

    plt.legend(['%i' % (int(T)) + ' K'])

Response: function to plot series of chi measurements as a function of temperature holding field constant and varying frequency


Instruction:
How would you explain what the following Python 3 function does
def plot_xbt(fignum, XB, T, e, b):
    plt.figure(num=fignum)
    plt.clf()
    if not isServer:
        plt.figtext(.02, .01, version_num)
    plt.xlabel('Field (T)')
    plt.ylabel('Susceptibility (m^3/kg)')
    k = 0
    B, X = [], []
    for xb in XB:
        X.append(xb[0])
        B.append(xb[1])
    plt.plot(B, X)
    plt.legend(['%i' % (int(T)) + ' K'])
    plt.title(e + ': f = ' + '%i' % (int(f)) + ' Hz')

Response: function to plot series of chi measurements as a function of temperature holding field constant and varying frequency


Instruction:
How would you explain what the following Python 3 function does
def plot_ltc(LTC_CM, LTC_CT, LTC_WM, LTC_WT, e):
    leglist, init = [], 0
    if len(LTC_CM) > 2:
        if init == 0:
            plot_init(1, 5, 5)
        plt.plot(LTC_CT, LTC_CM, 'b')
        leglist.append('RT SIRM, measured while cooling')
        init = 1
    if len(LTC_WM) > 2:
        if init == 0:
            plot_init(1, 5, 5)
        plt.plot(LTC_WT, LTC_WM, 'r')
        leglist.append('RT SIRM, measured while warming')
    if init != 0:
        plt.legend(leglist, 'lower left')
        plt.xlabel('Temperature (K)')
        plt.ylabel('Magnetization (Am^2/kg)')
        if len(LTC_CM) > 2:
            plt.plot(LTC_CT, LTC_CM, 'bo')
        if len(LTC_WM) > 2:
            plt.plot(LTC_WT, LTC_WM, 'ro')
        plt.title(e)

Response: function to plot low temperature cycling experiments


Instruction:
How would you explain what the following Python 3 function does
def plot_conf(fignum, s, datablock, pars, new):
# make the stereonet
    if new == 1:
        plot_net(fignum)
#
#   plot the data
#
    DIblock = []
    for plotrec in datablock:
        DIblock.append((float(plotrec["dec"]), float(plotrec["inc"])))
    if len(DIblock) > 0:
        plot_di(fignum, DIblock)  # plot directed lines
#
# put on the mean direction
#
    x, y = [], []
    XY = pmag.dimap(float(pars[0]), float(pars[1]))
    x.append(XY[0])
    y.append(XY[1])
    plt.figure(num=fignum)
    if new == 1:
        plt.scatter(x, y, marker='d', s=80, c='r')
    else:
        if float(pars[1] > 0):
            plt.scatter(x, y, marker='^', s=100, c='r')
        else:
            plt.scatter(x, y, marker='^', s=100, c='y')
    plt.title(s)
#
# plot the ellipse
#
    plot_ell(fignum, pars, 'r-,', 0, 1)

Response: make the main plot of the main figure


Instruction:
Make a summary of the following Python 3 code
def add_borders(Figs, titles, border_color='#000000', text_color='#800080', con_id=""):

    """
    Formatting for generating plots on the server
    Default border color: black
    Default text color: purple
    """
    def split_title(s):
        """
        Add '\n's to split of overly long titles
        """
        s_list = s.split(",")
        lines = []
        tot = 0
        line = []
        for i in s_list:
            tot += len(i)
            if tot < 30:
                line.append(i + ",")
            else:
                lines.append(" ".join(line))
                line = [i]
                tot = 0
        lines.append(" ".join(line))
        return "\n".join(lines).strip(',')

    # format contribution id if available
    if con_id:
        if not str(con_id).startswith("/"):
            con_id = "/" + str(con_id)

    import datetime
    now = datetime.datetime.utcnow()

    for key in list(Figs.keys()):

        fig = plt.figure(Figs[key])
        plot_title = split_title(titles[key]).strip().strip('\n')
        fig.set_figheight(5.5)
        #get returns Bbox with x0, y0, x1, y1
        pos = fig.gca().get_position()
        # tweak some of the default values
        w = pos.x1 - pos.x0
        h = (pos.y1 - pos.y0) / 1.1
        x = pos.x0
        y = pos.y0 * 1.3
        # set takes: left, bottom, width, height
        fig.gca().set_position([x, y, w, h])

        # add an axis covering the entire figure
        border_ax = fig.add_axes([0, 0, 1, 1])
        border_ax.set_frame_on(False)
        border_ax.set_xticks([])
        border_ax.set_yticks([])
        # add a border
        if "\n" in plot_title:
            y_val = 1.0  # lower border
            #fig.set_figheight(6.25)
        else:
            y_val = 1.04  # higher border
        #border_ax.text(-0.02, y_val, "                                                                                #                                                                                |",
        #               horizontalalignment='left',
        #               verticalalignment='top',
        #               color=text_color,
        #               bbox=dict(edgecolor=border_color,
        #                         facecolor='#FFFFFF', linewidth=0.25),
        #               size=50)
        #border_ax.text(-0.02, 0, "|                                                                                #                                                                                |",
        #               horizontalalignment='left',
        #               verticalalignment='bottom',
        #               color=text_color,
        #               bbox=dict(edgecolor=border_color,
        #                         facecolor='#FFFFFF', linewidth=0.25),
        #               size=20)#18)

        # add text

        border_ax.text((4. / fig.get_figwidth()) * 0.015, 0.03, now.strftime("%Y-%m-%d, %I:%M:%S {}".format('UT')),
                       horizontalalignment='left',
                       verticalalignment='top',
                       color=text_color,
                       size=10)
        border_ax.text(0.5, 0.98, plot_title,
                       horizontalalignment='center',
                       verticalalignment='top',
                       color=text_color,
                       size=20)
        border_ax.text(1 - (4. / fig.get_figwidth()) * 0.015, 0.03, 'earthref.org/MagIC{}'.format(con_id),
                       horizontalalignment='right',
                       verticalalignment='top',
                       color=text_color,
                       size=10)
    return Figs

Response: Add borders to the server figure.


Instruction:
Explain what the following Python 3 code does
def plot_map(fignum, lats, lons, Opts):
    if not has_cartopy:
        print('This function requires installation of cartopy')
        return
    from matplotlib import cm
    # draw meridian labels on the bottom [left,right,top,bottom]
    mlabels = [0, 0, 0, 1]
    plabels = [1, 0, 0, 0]  # draw parallel labels on the left
    Opts_defaults = {'latmin': -90, 'latmax': 90, 'lonmin': 0, 'lonmax': 360,
                     'lat_0': 0, 'lon_0': 0, 'proj': 'moll', 'sym': 'ro', 'symsize': 5,
                     'edge': None, 'pltgrid': 1, 'res': 'c', 'boundinglat': 0.,
                     'padlon': 0, 'padlat': 0, 'gridspace': 30, 'global': 1, 'cmap': 'jet','oceancolor':'azure','landcolor':'bisque',
                     'details': {'fancy': 0, 'coasts': 0, 'rivers': 0, 'states': 0, 'countries': 0, 'ocean': 0},
                     'edgecolor': 'face'}
    for key in Opts_defaults.keys():
        if key not in Opts.keys() and key != 'details':
            Opts[key] = Opts_defaults[key]
        if key == 'details':
            if key not in Opts.keys():
                Opts[key] = Opts_defaults[key]
            for detail_key in Opts_defaults[key].keys():
                if detail_key not in Opts[key].keys():
                    Opts[key][detail_key] = Opts_defaults[key][detail_key]
    if Opts['proj'] == 'pc':
        ax = plt.axes(projection=ccrs.PlateCarree())
        ax.set_extent([Opts['lonmin'], Opts['lonmax'], Opts['latmin'], Opts['latmax']],
                      crs=ccrs.PlateCarree())
    if Opts['proj'] == 'aea':
        ax = plt.axes(projection=ccrs.AlbersEqualArea(
            central_longitude=Opts['lon_0'],
            central_latitude=Opts['lat_0'],
            false_easting=0.0, false_northing=0.0, standard_parallels=(20.0, 50.0),
            globe=None))
    if Opts['proj'] == 'lcc':
        proj = ccrs.LambertConformal(central_longitude=Opts['lon_0'],  central_latitude=Opts['lat_0'],\
               false_easting=0.0, false_northing=0.0, standard_parallels=(20.0, 50.0),
               globe=None)
        fig=plt.figure(fignum,figsize=(6,6),frameon=True)
        ax = plt.axes(projection=proj)
        ax.set_extent([Opts['lonmin'], Opts['lonmax'], Opts['latmin'], Opts['latmax']],
                      crs=ccrs.PlateCarree())
    if Opts['proj'] == 'lcyl':
        ax = plt.axes(projection=ccrs.LambertCylindrical(
            central_longitude=Opts['lon_0']))

    if Opts['proj'] == 'merc':
        ax = plt.axes(projection=ccrs.Mercator(
            central_longitude=Opts['lon_0'], min_latitude=Opts['latmin'],
            max_latitude=Opts['latmax'], latitude_true_scale=0.0, globe=None))
        ax.set_extent([Opts['lonmin'],Opts['lonmax'],\
                     Opts['latmin'],Opts['latmax']])
    if Opts['proj'] == 'mill':
        ax = plt.axes(projection=ccrs.Miller(
            central_longitude=Opts['lon_0']))
    if Opts['proj'] == 'moll':
        ax = plt.axes(projection=ccrs.Mollweide(
            central_longitude=Opts['lat_0'], globe=None))
    if Opts['proj'] == 'ortho':
        ax = plt.axes(projection=ccrs.Orthographic(
            central_longitude=Opts['lon_0'],
            central_latitude=Opts['lat_0']))
    if Opts['proj'] == 'robin':
        ax = plt.axes(projection=ccrs.Robinson(
            central_longitude=Opts['lon_0'],
            globe=None))

    if Opts['proj'] == 'sinu':
        ax = plt.axes(projection=ccrs.Sinusoidal(
            central_longitude=Opts['lon_0'],
            false_easting=0.0, false_northing=0.0,
            globe=None))

    if Opts['proj'] == 'stere':
        ax = plt.axes(projection=ccrs.Stereographic(
            central_longitude=Opts['lon_0'],
            false_easting=0.0, false_northing=0.0,
            true_scale_latitude=None,
            scale_factor=None,
            globe=None))
    if Opts['proj'] == 'tmerc':
        ax = plt.axes(projection=ccrs.TransverseMercator(
            central_longitude=Opts['lon_0'], central_latitude=Opts['lat_0'],
            false_easting=0.0, false_northing=0.0,
            scale_factor=None,
            globe=None))
    if Opts['proj'] == 'utm':
        ax = plt.axes(projection=ccrs.UTM(
            zone=Opts['zone'],
            southern_hemisphere=Opts['south'],
            globe=None))
    if Opts['proj'] == 'geos':
        ax = plt.axes(projection=ccrs.Geostationary(
            central_longitude=Opts['lon_0'],
            false_easting=0.0, false_northing=0.0,
            satellite_height=35785831,
            sweep_axis='y',
            globe=None))
    if Opts['proj'] == 'laea':
        ax = plt.axes(projection=ccrs.LambertAzimuthalEqualArea(
            central_longitude=Opts['lon_0'], central_latitude=Opts['lat_0'],
            false_easting=0.0, false_northing=0.0,
            globe=None))
    if Opts['proj'] == 'npstere':
        ax = plt.axes(projection=ccrs.NorthPolarStereo(
            central_longitude=Opts['lon_0'],
            true_scale_latitude=None,
            globe=None))
    if Opts['proj'] == 'spstere':
        ax = plt.axes(projection=ccrs.SouthPolarStereo(
            central_longitude=Opts['lon_0'],
            true_scale_latitude=None,
            globe=None))

    if 'details' in list(Opts.keys()):
        if Opts['details']['fancy'] == 1:
            pmag_data_dir = find_pmag_dir.get_data_files_dir()
            EDIR = os.path.join(pmag_data_dir, "etopo20")
            etopo_path = os.path.join(EDIR, 'etopo20data.gz')
            etopo = np.loadtxt(os.path.join(EDIR, 'etopo20data.gz'))
            elons = np.loadtxt(os.path.join(EDIR, 'etopo20lons.gz'))
            elats = np.loadtxt(os.path.join(EDIR, 'etopo20lats.gz'))
            xx, yy = np.meshgrid(elons, elats)
            levels = np.arange(-10000, 8000, 500)  # define contour intervals
            m = ax.contourf(xx, yy, etopo, levels,
                            transform=ccrs.PlateCarree(),
                            cmap=Opts['cmap'])
            cbar=plt.colorbar(m)
        if Opts['details']['coasts'] == 1:
            if Opts['res']=='c' or Opts['res']=='l':
                ax.coastlines(resolution='110m')
            elif Opts['res']=='i':
                ax.coastlines(resolution='50m')
            elif Opts['res']=='h':
                ax.coastlines(resolution='10m')
        if Opts['details']['rivers'] == 1:
            ax.add_feature(cfeature.RIVERS)
        if Opts['details']['states'] == 1:
            states_provinces = cfeature.NaturalEarthFeature(
                category='cultural',
                name='admin_1_states_provinces_lines',
                scale='50m',
                edgecolor='black',
                facecolor='none',
                linestyle='dotted')
            ax.add_feature(states_provinces)
        if Opts['details']['countries'] == 1:
            ax.add_feature(BORDERS, linestyle='-', linewidth=2)
        if Opts['details']['ocean'] == 1:
            ax.add_feature(OCEAN, color=Opts['oceancolor'])
            ax.add_feature(LAND, color=Opts['landcolor'])
            ax.add_feature(LAKES, color=Opts['oceancolor'])
    if Opts['proj'] in ['merc', 'pc','lcc']:
        if Opts['pltgrid']:
            if Opts['proj']=='lcc':
                fig.canvas.draw()
                #xticks=list(np.arange(Opts['lonmin'],Opts['lonmax']+Opts['gridspace'],Opts['gridspace']))
                #yticks=list(np.arange(Opts['latmin'],Opts['latmax']+Opts['gridspace'],Opts['gridspace']))
                xticks=list(np.arange(-180,180,Opts['gridspace']))
                yticks=list(np.arange(-90,90,Opts['gridspace']))
                ax.gridlines(ylocs=yticks,xlocs=xticks,linewidth=2,
                              linestyle='dotted')
                ax.xaxis.set_major_formatter(LONGITUDE_FORMATTER) # you need this here
                ax.yaxis.set_major_formatter(LATITUDE_FORMATTER)# you need this here, too

                try:
                    import pmagpy.lcc_ticks as lcc_ticks
                    lcc_ticks.lambert_xticks(ax, xticks)
                    lcc_ticks.lambert_yticks(ax, yticks)

                except:
                    print ('plotting of tick marks on Lambert Conformal requires the package "shapely".\n Try importing with "conda install -c conda-forge shapely"')
            else:
                gl = ax.gridlines(crs=ccrs.PlateCarree(), linewidth=2,
                              linestyle='dotted', draw_labels=True)
                gl.ylocator = mticker.FixedLocator(np.arange(-80, 81, Opts['gridspace']))
                gl.xlocator = mticker.FixedLocator(np.arange(-180, 181, Opts['gridspace']))
                gl.xformatter = LONGITUDE_FORMATTER
                gl.yformatter = LATITUDE_FORMATTER
                gl.xlabels_top = False
        else:
            gl = ax.gridlines(crs=ccrs.PlateCarree(),
                              linewidth=2, linestyle='dotted')
    elif Opts['pltgrid']:
        print('gridlines only supported for PlateCarree, Lambert Conformal, and Mercator plots currently')
    prn_name, symsize = 0, 5
    # if 'names' in list(Opts.keys()) > 0:
    #    names = Opts['names']
    #    if len(names) > 0:
    #        prn_name = 1
##
    X, Y, T, k = [], [], [], 0
    if 'symsize' in list(Opts.keys()):
        symsize = Opts['symsize']
    if Opts['sym'][-1] != '-':  # just plot points
        color, symbol = Opts['sym'][0], Opts['sym'][1]
        ax.scatter(lons, lats, s=Opts['symsize'], c=color, marker=symbol,
                   transform=ccrs.Geodetic(), edgecolors=Opts['edgecolor'])
        if prn_name == 1:
            print('labels not yet implemented in plot_map')
            # for pt in range(len(lats)):
            #    T.append(plt.text(X[pt] + 5000, Y[pt] - 5000, names[pt]))
    else:  # for lines,  need to separate chunks using lat==100.
        ax.plot(lons, lats, Opts['sym'], transform=ccrs.Geodetic())
    if Opts['global']:
        ax.set_global()

Response: Plots a cartopy map with the specified lats and lons.


Instruction:
Can you write a function in Python 3 where it
plots a basemap of the desired field element

Response:
def plot_mag_map_basemap(fignum, element, lons, lats, element_type, cmap='RdYlBu', lon_0=0, date=""):
    """
    makes a color contour map of geomagnetic field element

    Parameters
    ____________
    fignum : matplotlib figure number
    element : field element array from pmag.do_mag_map for plotting
    lons : longitude array from pmag.do_mag_map for plotting
    lats : latitude array from pmag.do_mag_map for plotting
    element_type : [B,Br,I,D] geomagnetic element type
        B : field intensity
        Br : radial field intensity
        I : inclinations
        D : declinations
    Optional
    _________
        cmap : matplotlib color map
        lon_0 : central longitude of the Hammer projection
        date : date used for field evaluation,
               if custom ghfile was used, supply filename

    Effects
    ______________
    plots a Hammer projection color contour with  the desired field element
    """
    if not has_basemap:
        print('-W- Basemap must be installed to run plot_mag_map_basemap')
        return
    from matplotlib import cm  # matplotlib's color map module
    lincr = 1
    if type(date) != str:
        date = str(date)
    fig = plt.figure(fignum)
    m = Basemap(projection='hammer', lon_0=lon_0)
    x, y = m(*meshgrid(lons, lats))
    m.drawcoastlines()
    if element_type == 'B':
        levmax = element.max()+lincr
        levmin = round(element.min()-lincr)
        levels = np.arange(levmin, levmax, lincr)
        cs = m.contourf(x, y, element, levels=levels, cmap=cmap)
        plt.title('Field strength ($\mu$T): '+date)
    if element_type == 'Br':
        levmax = element.max()+lincr
        levmin = round(element.min()-lincr)
        cs = m.contourf(x, y, element, levels=np.arange(
            levmin, levmax, lincr), cmap=cmap)
        plt.title('Radial field strength ($\mu$T): '+date)
    if element_type == 'I':
        levmax = element.max()+lincr
        levmin = round(element.min()-lincr)
        cs = m.contourf(
            x, y, element, levels=np.arange(-90, 100, 20), cmap=cmap)
        m.contour(x, y, element, levels=np.arange(-80, 90, 10), colors='black')
        plt.title('Field inclination: '+date)
    if element_type == 'D':
        # cs=m.contourf(x,y,element,levels=np.arange(-180,180,10),cmap=cmap)
        cs = m.contourf(
            x, y, element, levels=np.arange(-180, 180, 10), cmap=cmap)
        m.contour(x, y, element, levels=np.arange(-180, 180, 10), colors='black')
        plt.title('Field declination: '+date)
    cbar = m.colorbar(cs, location='bottom')


Instruction:
Can you tell what is the following Python 3 function doing
def plot_mag_map(fignum, element, lons, lats, element_type, cmap='coolwarm', lon_0=0, date="", contours=False, proj='PlateCarree'):

    if not has_cartopy:
        print('This function requires installation of cartopy')
        return
    from matplotlib import cm
    if lon_0 == 180:
        lon_0 = 179.99
    if lon_0 > 180:
        lon_0 = lon_0-360.
    lincr = 1
    if type(date) != str:
        date = str(date)
    if proj == 'PlateCarree':
        fig = plt.figure(fignum)
        ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=lon_0))
    if proj == 'Mollweide':
        fig = plt.figure(fignum)
        # this issue is fixed in >=0.17
        if not LooseVersion(Cartopy.__version__) > LooseVersion('0.16.0'):
            if lon_0 != 0:
                print('This projection requires lon_0=0')
                return

        ax = plt.axes(projection=ccrs.Mollweide(central_longitude=lon_0))
    xx, yy = np.meshgrid(lons, lats)
    levmax = 5*round(element.max()/5)+5
    levmin = 5*round(element.min()/5)-5
    if element_type == 'Br' or element_type == 'B':
        plt.contourf(xx, yy, element,
                     levels=np.arange(levmin, levmax, 1),
                     cmap=cmap, transform=ccrs.PlateCarree())
        cbar = plt.colorbar(orientation='horizontal')
        if contours:
            plt.contour(xx, yy, element, levels=np.arange(levmin, levmax, 10),
                        colors='black', transform=ccrs.PlateCarree())

        if element_type == 'Br':
            plt.title('Radial field strength ($\mu$T): '+date)
        else:
            plt.title('Total field strength ($\mu$T): '+date)
    if element_type == 'I':
        plt.contourf(xx, yy, element,
                     levels=np.arange(-90, 90, lincr),
                     cmap=cmap, transform=ccrs.PlateCarree())
        cbar = plt.colorbar(orientation='horizontal')
        if contours:
            plt.contour(xx, yy, element, levels=np.arange(-80, 90, 10),
                        colors='black', transform=ccrs.PlateCarree())
        plt.title('Field inclination: '+date)
    if element_type == 'D':
        plt.contourf(xx, yy, element,
                     levels=np.arange(-180, 180, 10),
                     cmap=cmap, transform=ccrs.PlateCarree())
        cbar = plt.colorbar(orientation='horizontal')
        if contours:
            plt.contour(xx, yy, element, levels=np.arange(-180, 180, 10),
                        colors='black', transform=ccrs.PlateCarree())
        plt.title('Field declination: '+date)
    ax.coastlines()
    ax.set_global()
    return ax

Response: Plots a color contour map of the desired field element.


Instruction:
How would you implement a function in Python 3 that
plots the dec inc block as a color contour

Response:
def plot_eq_cont(fignum, DIblock, color_map='coolwarm'):
    """
    plots dec inc block as a color contour
    Parameters
    __________________
    Input:
        fignum :  figure number
        DIblock : nested pairs of [Declination, Inclination]
        color_map : matplotlib color map [default is coolwarm]
    Output:
        figure
    """
    import random
    plt.figure(num=fignum)
    plt.axis("off")
    XY = []
    centres = []
    counter = 0
    for rec in DIblock:
        counter = counter + 1
        X = pmag.dir2cart([rec[0], rec[1], 1.])
        # from Collinson 1983
        R = old_div(np.sqrt(1. - X[2]), (np.sqrt(X[0]**2 + X[1]**2)))
        XY.append([X[0] * R, X[1] * R])
    # radius of the circle
    radius = (old_div(3., (np.sqrt(np.pi * (9. + float(counter)))))) + 0.01
    num = 2. * (old_div(1., radius))  # number of circles
    # a,b are the extent of the grids over which the circles are equispaced
    a1, a2 = (0. - (radius * num / 2.)), (0. + (radius * num / 2.))
    b1, b2 = (0. - (radius * num / 2.)), (0. + (radius * num / 2.))
    # this is to get an array (a list of list wont do) of x,y values
    xlist = np.linspace(a1, a2, int(np.ceil(num)))
    ylist = np.linspace(b1, b2, int(np.ceil(num)))
    X, Y = np.meshgrid(xlist, ylist)
    # to put z in the array I just multiply both x,y with zero.  I will add to
    # the zero values later
    Z = X * Y * 0.
    # keeping the centres of the circles as a separate list instead of in
    # array helps later
    for j in range(len(ylist)):
        for i in range(len(xlist)):
            centres.append([xlist[i], ylist[j]])
    # the following lines are to figure out what happens at the edges where part of a circle might lie outside
    # a thousand random numbers are generated within the x,y limit of the circles and tested whether it is contained in
    # the eq area net space....their ratio gives the fraction of circle
    # contained in the net
    fraction = []
    beta, alpha = 0.001, 0.001  # to avoid those 'division by float' thingy
    for i in range(0, int(np.ceil(num))**2):
        if np.sqrt(((centres[i][0])**2) + ((centres[i][1])**2)) - 1. < radius:
            for j in range(1, 1000):
                rnd1 = random.uniform(
                    centres[i][0] - radius, centres[i][0] + radius)
                rnd2 = random.uniform(
                    centres[i][1] - radius, centres[i][1] + radius)
                if ((centres[i][0] - rnd1)**2 + (centres[i][1] - rnd2)**2) <= radius**2:
                    if (rnd1**2) + (rnd2**2) < 1.:
                        alpha = alpha + 1.
                        beta = beta + 1.
                    else:
                        alpha = alpha + 1.
            fraction.append(old_div(alpha, beta))
            alpha, beta = 0.001, 0.001
        else:
            fraction.append(1.)  # if the whole circle lies in the net

    # for every circle count the number of points lying in it
    count = 0
    dotspercircle = 0.
    for j in range(0, int(np.ceil(num))):
        for i in range(0, int(np.ceil(num))):
            for k in range(0, counter):
                if (XY[k][0] - centres[count][0])**2 + (XY[k][1] - centres[count][1])**2 <= radius**2:
                    dotspercircle += 1.
            Z[i][j] = Z[i][j] + (dotspercircle * fraction[count])
            count += 1
            dotspercircle = 0.
    im = plt.imshow(Z, interpolation='bilinear', origin='lower',
                    # cmap=plt.color_map.hot, extent=(-1., 1., -1., 1.))
                    cmap=color_map, extent=(-1., 1., -1., 1.))
    plt.colorbar(shrink=0.5)
    x, y = [], []
    # Draws the border
    for i in range(0, 360):
        x.append(np.sin((old_div(np.pi, 180.)) * float(i)))
        y.append(np.cos((old_div(np.pi, 180.)) * float(i)))
    plt.plot(x, y, 'w-')
    x, y = [], []
    # the map will be a square of 1X1..this is how I erase the redundant area
    for j in range(1, 4):
        for i in range(0, 360):
            x.append(np.sin((old_div(np.pi, 180.)) * float(i))
                     * (1. + (old_div(float(j), 10.))))
            y.append(np.cos((old_div(np.pi, 180.)) * float(i))
                     * (1. + (old_div(float(j), 10.))))
        plt.plot(x, y, 'w-', linewidth=26)
        x, y = [], []
    # the axes
    plt.axis("equal")


Instruction:
Write a Python 3 function for
making a time scale plot between the specified ages.

Response:
def plot_ts(ax, agemin, agemax, timescale='gts12', ylabel="Age (Ma)"):
    """
    Make a time scale plot between specified ages.

    Parameters:
    ------------
    ax : figure object
    agemin : Minimum age for timescale
    agemax : Maximum age for timescale
    timescale : Time Scale [ default is Gradstein et al., (2012)]
       for other options see pmag.get_ts()
    ylabel : if set, plot as ylabel
    """
    ax.set_title(timescale.upper())
    ax.axis([-.25, 1.5, agemax, agemin])
    ax.axes.get_xaxis().set_visible(False)
    # get dates and chron names for timescale
    TS, Chrons = pmag.get_ts(timescale)
    X, Y, Y2 = [0, 1], [], []
    cnt = 0
    if agemin < TS[1]:  # in the Brunhes
        Y = [agemin, agemin]  # minimum age
        Y1 = [TS[1], TS[1]]  # age of the B/M boundary
        ax.fill_between(X, Y, Y1, facecolor='black')  # color in Brunhes, black
    for d in TS[1:]:
        pol = cnt % 2
        cnt += 1
        if d <= agemax and d >= agemin:
            ind = TS.index(d)
            Y = [TS[ind], TS[ind]]
            Y1 = [TS[ind+1], TS[ind+1]]
            if pol:
                # fill in every other time
                ax.fill_between(X, Y, Y1, facecolor='black')
    ax.plot([0, 1, 1, 0, 0], [agemin, agemin, agemax, agemax, agemin], 'k-')
    plt.yticks(np.arange(agemin, agemax+1, 1))
    if ylabel != "":
        ax.set_ylabel(ylabel)
    ax2 = ax.twinx()
    ax2.axis('off')
    for k in range(len(Chrons)-1):
        c = Chrons[k]
        cnext = Chrons[k+1]
        d = cnext[1]-(cnext[1]-c[1])/3.
        if d >= agemin and d < agemax:
            # make the Chron boundary tick
            ax2.plot([1, 1.5], [c[1], c[1]], 'k-')
            ax2.text(1.05, d, c[0])
    ax2.axis([-.25, 1.5, agemax, agemin])


Instruction:
Given the following Python 3 function, write the documentation
def main():
    args = sys.argv
    PLT = 1
    plots = 0
    user, meas_file = "", "magic_measurements.txt"
    pltspec = ""
    dir_path = '.'
    fmt = 'png'
    verbose = pmagplotlib.verbose
    version_num = pmag.get_version()
    if '-WD' in args:
        ind = args.index('-WD')
        dir_path = args[ind+1]
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    if "-usr" in args:
        ind = args.index("-usr")
        user = args[ind+1]
    if '-f' in args:
        ind = args.index("-f")
        meas_file = args[ind+1]
    if '-sav' in args:
        verbose = 0
        plots = 1
    if '-spc' in args:
        ind = args.index("-spc")
        pltspec = args[ind+1]
        verbose = 0
        plots = 1
    if '-fmt' in args:
        ind = args.index("-fmt")
        fmt = args[ind+1]
    meas_file = dir_path+'/'+meas_file
    #
    #
    meas_data, file_type = pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print(main.__doc__)
        print('bad file')
        sys.exit()
    #
    # initialize some variables
    # define figure numbers for hyst,deltaM,DdeltaM curves
    HystRecs, RemRecs = [], []
    HDD = {}
    HDD['hyst'] = 1
    pmagplotlib.plot_init(HDD['hyst'], 5, 5)
    #
    # get list of unique experiment names and specimen names
    #
    experiment_names, sids = [], []
    hyst_data = pmag.get_dictitem(
        meas_data, 'magic_method_codes', 'LP-HYS', 'has')  # get all hysteresis data
    for rec in hyst_data:
        if 'er_synthetic_name' in 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'])
        if 'measurement_temp' not in rec.keys():
            # assume room T measurement unless otherwise specified
            rec['measurement_temp'] = '300'
    #
    k = 0
    if pltspec != "":
        k = sids.index(pltspec)
    intlist = ['measurement_magnitude', 'measurement_magn_moment',
               'measurement_magn_volume', 'measurement_magn_mass']
    while k < len(sids):
        locname, site, sample, synth = '', '', '', ''
        s = sids[k]
        hmeths = []
        if verbose:
            print(s, k+1, 'out of ', len(sids))
    #
    #
        B, M = [], []  # B,M for hysteresis, Bdcd,Mdcd for irm-dcd data
        # get all measurements for this specimen
        spec = pmag.get_dictitem(hyst_data, 'er_specimen_name', s, 'T')
        if 'er_location_name' in spec[0].keys():
            locname = spec[0]['er_location_name']
        if 'er_site_name' in spec[0].keys():
            site = spec[0]['er_site_name']
        if 'er_sample_name' in spec[0].keys():
            sample = spec[0]['er_sample_name']
        if 'er_synthetic_name' in spec[0].keys():
            synth = spec[0]['er_synthetic_name']
        for m in intlist:
            # get all non-blank data for this specimen
            meas_data = pmag.get_dictitem(spec, m, '', 'F')
            if len(meas_data) > 0:
                break
        c = ['k-', 'b-', 'c-', 'g-', 'm-', 'r-', 'y-']
        cnum = 0
        if len(meas_data) > 0:
            Temps = []
            xlab, ylab, title = '', '', ''
            for rec in meas_data:
                if rec['measurement_temp'] not in Temps:
                    Temps.append(rec['measurement_temp'])
            for t in Temps:
                print('working on t: ', t)
                t_data = pmag.get_dictitem(
                    meas_data, 'measurement_temp', t, 'T')
                B, M = [], []
                for rec in t_data:
                    B.append(float(rec['measurement_lab_field_dc']))
                    M.append(float(rec[m]))
    # now plot the hysteresis curve(s)
    #
                if len(B) > 0:
                    B = numpy.array(B)
                    M = numpy.array(M)
                    if t == Temps[-1]:
                        xlab = 'Field (T)'
                        ylab = m
                        title = 'Hysteresis: '+s
                    if t == Temps[0]:
                        pmagplotlib.clearFIG(HDD['hyst'])
                    pmagplotlib.plot_xy(
                        HDD['hyst'], B, M, sym=c[cnum], xlab=xlab, ylab=ylab, title=title)
                    pmagplotlib.plot_xy(HDD['hyst'], [
                                        1.1*B.min(), 1.1*B.max()], [0, 0], sym='k-', xlab=xlab, ylab=ylab, title=title)
                    pmagplotlib.plot_xy(HDD['hyst'], [0, 0], [
                                        1.1*M.min(), 1.1*M.max()], sym='k-', xlab=xlab, ylab=ylab, title=title)
                    if verbose:
                        pmagplotlib.draw_figs(HDD)
                    cnum += 1
                    if cnum == len(c):
                        cnum = 0
    #
        files = {}
        if plots:
            if pltspec != "":
                s = pltspec
            files = {}
            for key in HDD.keys():
                if pmagplotlib.isServer:  # use server plot naming convention
                    if synth == '':
                        filename = "LO:_"+locname+'_SI:_'+site + \
                            '_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt
                    else:
                        filename = 'SY:_'+synth+'_TY:_'+key+'_.'+fmt
                    files[key] = filename
                else:  # use more readable plot naming convention
                    if synth == '':
                        filename = ''
                        for item in [locname, site, sample, s, key]:
                            if item:
                                item = item.replace(' ', '_')
                                filename += item + '_'
                        if filename.endswith('_'):
                            filename = filename[:-1]
                        filename += ".{}".format(fmt)
                    else:
                        filename = synth+'_'+key+'.fmt'
                    files[key] = filename

            pmagplotlib.save_plots(HDD, files)
            if pltspec != "":
                sys.exit()
        if verbose:
            pmagplotlib.draw_figs(HDD)
            ans = raw_input(
                "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ")
            if ans == "a":
                files = {}
                for key in HDD.keys():
                    if pmagplotlib.isServer:
                        print('server')
                        files[key] = "LO:_"+locname+'_SI:_'+site + \
                            '_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt
                    else:
                        print('not server')
                        filename = ''
                        for item in [locname, site, sample, s, key]:
                            if item:
                                item = item.replace(' ', '_')
                                filename += item + '_'
                        if filename.endswith('_'):
                            filename = filename[:-1]
                        filename += ".{}".format(fmt)
                        files[key] = filename
                print('files', files)
                pmagplotlib.save_plots(HDD, files)
            if ans == '':
                k += 1
            if ans == "p":
                del HystRecs[-1]
                k -= 1
            if ans == 'q':
                print("Good bye")
                sys.exit()
            if ans == 's':
                keepon = 1
                specimen = raw_input(
                    'Enter desired specimen name (or first part there of): ')
                while keepon == 1:
                    try:
                        k = sids.index(specimen)
                        keepon = 0
                    except:
                        tmplist = []
                        for qq in range(len(sids)):
                            if specimen in sids[qq]:
                                tmplist.append(sids[qq])
                        print(specimen, " not found, but this was: ")
                        print(tmplist)
                        specimen = raw_input('Select one or try again\n ')
                        k = sids.index(specimen)
        else:
            k += 1
        if len(B) == 0:
            if verbose:
                print('skipping this one - no hysteresis data')
            k += 1

Response:
NAME
        quick_hyst.py

    DESCRIPTION
        makes plots of hysteresis data

    SYNTAX
        quick_hyst.py [command line options]

    OPTIONS
        -h prints help message and quits
        -usr USER:   identify user, default is ""
        -f: specify input file, default is magic_measurements.txt
        -spc SPEC: specify specimen name to plot and quit
        -sav save all plots and quit
        -fmt [png,svg,eps,jpg]


Instruction:
Can you implement a function in Python 3 that
functions misfit evaluation for best - fit tanh curve

Response:
def funk(p, x, y):
    """
    Function misfit evaluation for best-fit tanh curve
    f(x[:]) = alpha*tanh(beta*x[:])
        alpha = params[0]
        beta = params[1]
    funk(params) = sqrt(sum((y[:] - f(x[:]))**2)/len(y[:]))
    Output is RMS misfit
      x=xx[0][:]
      y=xx[1][:]q
    """
    alpha=p[0]
    beta=p[1]
    dev=0
    for i in range(len(x)):
      dev=dev+((y[i]-(alpha*math.tanh(beta*x[i])))**2)
    rms=math.sqrt(old_div(dev,float(len(y))))
    return rms


Instruction:
Can you generate a brief explanation for the following Python 3 code
def compare(a, b):
    s=0
    for i in range(len(a)):
        s=s+abs(a[i]-b[i])
    return s

Response: Compare items in 2 arrays. Returns sum of absolute values.


Instruction:
How would you code a function in Python 3 to
calculate the TRM using tanh relationship

Response:
def TRM(f,a,b):
    """
     Calculate TRM using tanh relationship
      TRM(f)=a*math.tanh(b*f)
    """
    m = float(a) * math.tanh(float(b) * float(f))
    return float(m)


Instruction:
Make a summary of the following Python 3 code
def TRMinv(m,a,b):
    WARN = True    # Warn, rather than stop if I encounter a NaN...
    """
     Calculate applied field from TRM using tanh relationship
     TRMinv(m)=(1/b)*atanh(m/a)
    """
    if float(a)==0:
        print('ERROR: TRMinv: a==0.')
        if not WARN : sys.exit()
    if float(b)==0:
        print('ERROR: TRMinv: b==0.')
        if not WARN : sys.exit()
    x = (old_div(float(m), float(a)))
    if (1-x)<=0:
         print('ERROR:  TRMinv: (1-x)==0.')
         return -1
    if not WARN : sys.exit()
    f = (old_div(1.,float(b))) * 0.5 * math.log (old_div((1+x), (1-x)))
    return float(f)

Response: Calculate applied field from TRM using tanh relationship.


Instruction:
Can you tell what is the following Python 3 function doing
def NRM(f,a,b,best):
    WARN = True    # Warn, rather than stop if I encounter a NaN...
    """
    Calculate NRM expected lab field and estimated ancient field
    NRM(blab,best)= (best/blab)*TRM(blab)
    """
    if float(f)==0:
        print('ERROR: NRM: f==0.')
    if not WARN : sys.exit()
    m = (old_div(float(best),float(f))) * TRM(f,a,b)
    return float(m)

Response: Calculate NRM expected lab field and estimated ancient field


Instruction:
Here you have a function in Python 3, explain what it does
def main():
    dist='F' # default distribution is Fisherian
    mode=1
    title=""
    EQ={'eq':1}
    if len(sys.argv) > 0:
        if '-h' in sys.argv: # check if help is needed
            print(main.__doc__)
            sys.exit() # graceful quit
        if '-i' in sys.argv: # ask for filename
            file=input("Enter file name with dec, inc data: ")
            dist=input("Enter desired distrubution: [Fish]er, [Bing]ham, [Kent] [Boot] [default is Fisher]: ")
            if dist=="":dist="F"
            if dist=="Bing":dist="B"
            if dist=="Kent":dist="K"
            if dist=="Boot":
                 type=input(" Ellipses or distribution of vectors? [E]/V ")
                 if type=="" or type=="E":
                     dist="BE"
                 else:
                     dist="BE"
        else:
#
            if '-f' in sys.argv:
                ind=sys.argv.index('-f')
                file=sys.argv[ind+1]
            else:
                print('you must specify a file name')
                print(main.__doc__)
                sys.exit()
            if '-Bing' in sys.argv:dist='B'
            if '-Kent' in sys.argv:dist='K'
            if '-Boot' in sys.argv:
                ind=sys.argv.index('-Boot')
                type=sys.argv[ind+1]
                if type=='E':
                    dist='BE'
                elif type=='V':
                    dist='BV'
                    EQ['bdirs']=2
                    pmagplotlib.plot_init(EQ['bdirs'],5,5)
                else:
                    print(main.__doc__)
                    sys.exit()
    pmagplotlib.plot_init(EQ['eq'],5,5)
#
# get to work
    f=open(file,'r')
    data=f.readlines()
#
    DIs= [] # set up list for dec inc data
    DiRecs=[]
    pars=[]
    nDIs,rDIs,npars,rpars=[],[],[],[]
    mode =1
    for line in data:   # read in the data from standard input
        DiRec={}
        rec=line.split() # split each line on space to get records
        DIs.append((float(rec[0]),float(rec[1]),1.))
        DiRec['dec']=rec[0]
        DiRec['inc']=rec[1]
        DiRec['direction_type']='l'
        DiRecs.append(DiRec)
    # split into two modes
    ppars=pmag.doprinc(DIs) # get principal directions
    for rec in DIs:
        angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']])
        if angle>90.:
            rDIs.append(rec)
        else:
            nDIs.append(rec)
    if dist=='B': # do on whole dataset
        title="Bingham confidence ellipse"
        bpars=pmag.dobingham(DIs)
        for key in list(bpars.keys()):
            if key!='n':print("    ",key, '%7.1f'%(bpars[key]))
            if key=='n':print("    ",key, '       %i'%(bpars[key]))
        npars.append(bpars['dec'])
        npars.append(bpars['inc'])
        npars.append(bpars['Zeta'])
        npars.append(bpars['Zdec'])
        npars.append(bpars['Zinc'])
        npars.append(bpars['Eta'])
        npars.append(bpars['Edec'])
        npars.append(bpars['Einc'])
    if dist=='F':
        title="Fisher confidence cone"
        if len(nDIs)>3:
            fpars=pmag.fisher_mean(nDIs)
            print("mode ",mode)
            for key in list(fpars.keys()):
                if key!='n':print("    ",key, '%7.1f'%(fpars[key]))
                if key=='n':print("    ",key, '       %i'%(fpars[key]))
            mode+=1
            npars.append(fpars['dec'])
            npars.append(fpars['inc'])
            npars.append(fpars['alpha95']) # Beta
            npars.append(fpars['dec'])
            isign=abs(fpars['inc']) / fpars['inc']
            npars.append(fpars['inc']-isign*90.) #Beta inc
            npars.append(fpars['alpha95']) # gamma
            npars.append(fpars['dec']+90.) # Beta dec
            npars.append(0.) #Beta inc
        if len(rDIs)>3:
            fpars=pmag.fisher_mean(rDIs)
            print("mode ",mode)
            for key in list(fpars.keys()):
                if key!='n':print("    ",key, '%7.1f'%(fpars[key]))
                if key=='n':print("    ",key, '       %i'%(fpars[key]))
            mode+=1
            rpars.append(fpars['dec'])
            rpars.append(fpars['inc'])
            rpars.append(fpars['alpha95']) # Beta
            rpars.append(fpars['dec'])
            isign=abs(fpars['inc']) / fpars['inc']
            rpars.append(fpars['inc']-isign*90.) #Beta inc
            rpars.append(fpars['alpha95']) # gamma
            rpars.append(fpars['dec']+90.) # Beta dec
            rpars.append(0.) #Beta inc
    if dist=='K':
        title="Kent confidence ellipse"
        if len(nDIs)>3:
            kpars=pmag.dokent(nDIs,len(nDIs))
            print("mode ",mode)
            for key in list(kpars.keys()):
                if key!='n':print("    ",key, '%7.1f'%(kpars[key]))
                if key=='n':print("    ",key, '       %i'%(kpars[key]))
            mode+=1
            npars.append(kpars['dec'])
            npars.append(kpars['inc'])
            npars.append(kpars['Zeta'])
            npars.append(kpars['Zdec'])
            npars.append(kpars['Zinc'])
            npars.append(kpars['Eta'])
            npars.append(kpars['Edec'])
            npars.append(kpars['Einc'])
        if len(rDIs)>3:
            kpars=pmag.dokent(rDIs,len(rDIs))
            print("mode ",mode)
            for key in list(kpars.keys()):
                if key!='n':print("    ",key, '%7.1f'%(kpars[key]))
                if key=='n':print("    ",key, '       %i'%(kpars[key]))
            mode+=1
            rpars.append(kpars['dec'])
            rpars.append(kpars['inc'])
            rpars.append(kpars['Zeta'])
            rpars.append(kpars['Zdec'])
            rpars.append(kpars['Zinc'])
            rpars.append(kpars['Eta'])
            rpars.append(kpars['Edec'])
            rpars.append(kpars['Einc'])
    else: # assume bootstrap
        if dist=='BE':
            if len(nDIs)>5:
                BnDIs=pmag.di_boot(nDIs)
                Bkpars=pmag.dokent(BnDIs,1.)
                print("mode ",mode)
                for key in list(Bkpars.keys()):
                    if key!='n':print("    ",key, '%7.1f'%(Bkpars[key]))
                    if key=='n':print("    ",key, '       %i'%(Bkpars[key]))
                mode+=1
                npars.append(Bkpars['dec'])
                npars.append(Bkpars['inc'])
                npars.append(Bkpars['Zeta'])
                npars.append(Bkpars['Zdec'])
                npars.append(Bkpars['Zinc'])
                npars.append(Bkpars['Eta'])
                npars.append(Bkpars['Edec'])
                npars.append(Bkpars['Einc'])
            if len(rDIs)>5:
                BrDIs=pmag.di_boot(rDIs)
                Bkpars=pmag.dokent(BrDIs,1.)
                print("mode ",mode)
                for key in list(Bkpars.keys()):
                    if key!='n':print("    ",key, '%7.1f'%(Bkpars[key]))
                    if key=='n':print("    ",key, '       %i'%(Bkpars[key]))
                mode+=1
                rpars.append(Bkpars['dec'])
                rpars.append(Bkpars['inc'])
                rpars.append(Bkpars['Zeta'])
                rpars.append(Bkpars['Zdec'])
                rpars.append(Bkpars['Zinc'])
                rpars.append(Bkpars['Eta'])
                rpars.append(Bkpars['Edec'])
                rpars.append(Bkpars['Einc'])
            title="Bootstrapped confidence ellipse"
        elif dist=='BV':
            if len(nDIs)>5:
                pmagplotlib.plot_eq(EQ['eq'],nDIs,'Data')
                BnDIs=pmag.di_boot(nDIs)
                pmagplotlib.plot_eq(EQ['bdirs'],BnDIs,'Bootstrapped Eigenvectors')
            if len(rDIs)>5:
                BrDIs=pmag.di_boot(rDIs)
                if len(nDIs)>5:  # plot on existing plots
                    pmagplotlib.plot_di(EQ['eq'],rDIs)
                    pmagplotlib.plot_di(EQ['bdirs'],BrDIs)
                else:
                    pmagplotlib.plot_eq(EQ['eq'],rDIs,'Data')
                    pmagplotlib.plot_eq(EQ['bdirs'],BrDIs,'Bootstrapped Eigenvectors')
            pmagplotlib.draw_figs(EQ)
            ans=input('s[a]ve, [q]uit ')
            if ans=='q':sys.exit()
            if ans=='a':
                files={}
                for key in list(EQ.keys()):
                    files[key]='BE_'+key+'.svg'
                pmagplotlib.save_plots(EQ,files)
            sys.exit()
    if len(nDIs)>5:
        pmagplotlib.plot_conf(EQ['eq'],title,DiRecs,npars,1)
        if len(rDIs)>5 and dist!='B':
            pmagplotlib.plot_conf(EQ['eq'],title,[],rpars,0)
    elif len(rDIs)>5 and dist!='B':
        pmagplotlib.plot_conf(EQ['eq'],title,DiRecs,rpars,1)
    pmagplotlib.draw_figs(EQ)
    ans=input('s[a]ve, [q]uit ')
    if ans=='q':sys.exit()
    if ans=='a':
        files={}
        for key in list(EQ.keys()):
            files[key]=key+'.svg'
        pmagplotlib.save_plots(EQ,files)

Response: NAME is the main function for the get_n_tweets function.


Instruction:
Write a Python 3 script to
initialize the GUI for the interpretation editor

Response:
def init_UI(self):
        """
        Builds User Interface for the interpretation Editor
        """

        #set fonts
        FONT_WEIGHT=1
        if sys.platform.startswith('win'): FONT_WEIGHT=-1
        font1 = wx.Font(9+FONT_WEIGHT, wx.SWISS, wx.NORMAL, wx.NORMAL, False, self.font_type)
        font2 = wx.Font(12+FONT_WEIGHT, wx.SWISS, wx.NORMAL, wx.NORMAL, False, self.font_type)

        #if you're on mac do some funny stuff to make it look okay
        is_mac = False
        if sys.platform.startswith("darwin"):
            is_mac = True

        self.search_bar = wx.SearchCtrl(self.panel, size=(350*self.GUI_RESOLUTION,25) ,style=wx.TE_PROCESS_ENTER | wx.TE_PROCESS_TAB | wx.TE_NOHIDESEL)
        self.Bind(wx.EVT_TEXT_ENTER, self.on_enter_search_bar,self.search_bar)
        self.Bind(wx.EVT_SEARCHCTRL_SEARCH_BTN, self.on_enter_search_bar,self.search_bar)
        self.search_bar.SetHelpText(dieh.search_help)
#        self.Bind(wx.EVT_TEXT, self.on_complete_search_bar,self.search_bar)

        #build logger
        self.logger = wx.ListCtrl(self.panel, -1, size=(100*self.GUI_RESOLUTION,475*self.GUI_RESOLUTION),style=wx.LC_REPORT)
        self.logger.SetFont(font1)
        self.logger.InsertColumn(0, 'specimen',width=75*self.GUI_RESOLUTION)
        self.logger.InsertColumn(1, 'fit name',width=65*self.GUI_RESOLUTION)
        self.logger.InsertColumn(2, 'max',width=55*self.GUI_RESOLUTION)
        self.logger.InsertColumn(3, 'min',width=55*self.GUI_RESOLUTION)
        self.logger.InsertColumn(4, 'n',width=25*self.GUI_RESOLUTION)
        self.logger.InsertColumn(5, 'fit type',width=60*self.GUI_RESOLUTION)
        self.logger.InsertColumn(6, 'dec',width=45*self.GUI_RESOLUTION)
        self.logger.InsertColumn(7, 'inc',width=45*self.GUI_RESOLUTION)
        self.logger.InsertColumn(8, 'mad',width=45*self.GUI_RESOLUTION)
        self.logger.InsertColumn(9, 'dang',width=45*self.GUI_RESOLUTION)
        self.logger.InsertColumn(10, 'a95',width=45*self.GUI_RESOLUTION)
        self.logger.InsertColumn(11, 'K',width=45*self.GUI_RESOLUTION)
        self.logger.InsertColumn(12, 'R',width=45*self.GUI_RESOLUTION)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnClick_listctrl, self.logger)
        self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK,self.OnRightClickListctrl,self.logger)
        self.logger.SetHelpText(dieh.logger_help)

        #set fit attributes boxsizers
        self.display_sizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, wx.ID_ANY, "display options"), wx.HORIZONTAL)
        self.name_sizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, wx.ID_ANY, "fit name/color"), wx.VERTICAL)
        self.bounds_sizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, wx.ID_ANY, "fit bounds"), wx.VERTICAL)
        self.buttons_sizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, wx.ID_ANY), wx.VERTICAL)

        #logger display selection box
        UPPER_LEVEL = self.parent.level_box.GetValue()
        if UPPER_LEVEL=='sample':
            name_choices = self.parent.samples
        if UPPER_LEVEL=='site':
            name_choices = self.parent.sites
        if UPPER_LEVEL=='location':
            name_choices = self.parent.locations
        if UPPER_LEVEL=='study':
            name_choices = ['this study']

        self.level_box = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), value=UPPER_LEVEL, choices=['sample','site','location','study'], style=wx.CB_DROPDOWN|wx.TE_READONLY)
        self.Bind(wx.EVT_COMBOBOX, self.on_select_high_level,self.level_box)
        self.level_box.SetHelpText(dieh.level_box_help)

        self.level_names = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), value=self.parent.level_names.GetValue(), choices=name_choices, style=wx.CB_DROPDOWN|wx.TE_READONLY)
        self.Bind(wx.EVT_COMBOBOX, self.on_select_level_name,self.level_names)
        self.level_names.SetHelpText(dieh.level_names_help)

        #mean type and plot display boxes
        self.mean_type_box = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), value=self.parent.mean_type_box.GetValue(), choices=['Fisher','Fisher by polarity','None'], style=wx.CB_DROPDOWN|wx.TE_READONLY, name="high_type")
        self.Bind(wx.EVT_COMBOBOX, self.on_select_mean_type_box,self.mean_type_box)
        self.mean_type_box.SetHelpText(dieh.mean_type_help)

        self.mean_fit_box = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), value=self.parent.mean_fit, choices=(['None','All'] + self.parent.fit_list), style=wx.CB_DROPDOWN|wx.TE_READONLY, name="high_type")
        self.Bind(wx.EVT_COMBOBOX, self.on_select_mean_fit_box,self.mean_fit_box)
        self.mean_fit_box.SetHelpText(dieh.mean_fit_help)

        #show box
        if UPPER_LEVEL == "study" or UPPER_LEVEL == "location":
            show_box_choices = ['specimens','samples','sites']
        if UPPER_LEVEL == "site":
            show_box_choices = ['specimens','samples']
        if UPPER_LEVEL == "sample":
            show_box_choices = ['specimens']

        self.show_box = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), value='specimens', choices=show_box_choices, style=wx.CB_DROPDOWN|wx.TE_READONLY,name="high_elements")
        self.Bind(wx.EVT_COMBOBOX, self.on_select_show_box,self.show_box)
        self.show_box.SetHelpText(dieh.show_help)

        #coordinates box
        self.coordinates_box = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), choices=self.parent.coordinate_list, value=self.parent.coordinates_box.GetValue(), style=wx.CB_DROPDOWN|wx.TE_READONLY, name="coordinates")
        self.Bind(wx.EVT_COMBOBOX, self.on_select_coordinates,self.coordinates_box)
        self.coordinates_box.SetHelpText(dieh.coordinates_box_help)

        #bounds select boxes
        self.tmin_box = wx.ComboBox(self.panel, -1, size=(80*self.GUI_RESOLUTION, 25), choices=[''] + self.parent.T_list, style=wx.CB_DROPDOWN|wx.TE_READONLY, name="lower bound")
        self.tmin_box.SetHelpText(dieh.tmin_box_help)

        self.tmax_box = wx.ComboBox(self.panel, -1, size=(80*self.GUI_RESOLUTION, 25), choices=[''] + self.parent.T_list, style=wx.CB_DROPDOWN|wx.TE_READONLY, name="upper bound")
        self.tmax_box.SetHelpText(dieh.tmax_box_help)

        #color box
        self.color_dict = self.parent.color_dict
        self.color_box = wx.ComboBox(self.panel, -1, size=(80*self.GUI_RESOLUTION, 25), choices=[''] + sorted(self.color_dict.keys()), style=wx.CB_DROPDOWN|wx.TE_PROCESS_ENTER, name="color")
        self.Bind(wx.EVT_TEXT_ENTER, self.add_new_color, self.color_box)
        self.color_box.SetHelpText(dieh.color_box_help)

        #name box
        self.name_box = wx.TextCtrl(self.panel, -1, size=(80*self.GUI_RESOLUTION, 25), name="name")
        self.name_box.SetHelpText(dieh.name_box_help)

        #more mac stuff
        h_size_buttons,button_spacing = 25,5.5
        if is_mac: h_size_buttons,button_spacing = 18,0.

        #buttons
        self.add_all_button = wx.Button(self.panel, id=-1, label='add new fit to all specimens',size=(160*self.GUI_RESOLUTION,h_size_buttons))
        self.add_all_button.SetFont(font1)
        self.Bind(wx.EVT_BUTTON, self.add_fit_to_all, self.add_all_button)
        self.add_all_button.SetHelpText(dieh.add_all_help)

        self.add_fit_button = wx.Button(self.panel, id=-1, label='add fit to highlighted specimens',size=(160*self.GUI_RESOLUTION,h_size_buttons))
        self.add_fit_button.SetFont(font1)
        self.Bind(wx.EVT_BUTTON, self.add_highlighted_fits, self.add_fit_button)
        self.add_fit_button.SetHelpText(dieh.add_fit_btn_help)

        self.delete_fit_button = wx.Button(self.panel, id=-1, label='delete highlighted fits',size=(160*self.GUI_RESOLUTION,h_size_buttons))
        self.delete_fit_button.SetFont(font1)
        self.Bind(wx.EVT_BUTTON, self.delete_highlighted_fits, self.delete_fit_button)
        self.delete_fit_button.SetHelpText(dieh.delete_fit_btn_help)

        self.apply_changes_button = wx.Button(self.panel, id=-1, label='apply changes to highlighted fits',size=(160*self.GUI_RESOLUTION,h_size_buttons))
        self.apply_changes_button.SetFont(font1)
        self.Bind(wx.EVT_BUTTON, self.apply_changes, self.apply_changes_button)
        self.apply_changes_button.SetHelpText(dieh.apply_changes_help)

        #windows
        display_window_0 = wx.GridSizer(2, 1, 10*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION)
        display_window_1 = wx.GridSizer(2, 1, 10*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION)
        display_window_2 = wx.GridSizer(2, 1, 10*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION)
        name_window = wx.GridSizer(2, 1, 10*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION)
        bounds_window = wx.GridSizer(2, 1, 10*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION)
        buttons1_window = wx.GridSizer(4, 1, 5*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION)
        display_window_0.AddMany( [(self.coordinates_box, wx.ALIGN_LEFT),
                                   (self.show_box, wx.ALIGN_LEFT)] )
        display_window_1.AddMany( [(self.level_box, wx.ALIGN_LEFT),
                                   (self.level_names, wx.ALIGN_LEFT)] )
        display_window_2.AddMany( [(self.mean_type_box, wx.ALIGN_LEFT),
                                   (self.mean_fit_box, wx.ALIGN_LEFT)] )
        name_window.AddMany( [(self.name_box, wx.ALIGN_LEFT),
                                (self.color_box, wx.ALIGN_LEFT)] )
        bounds_window.AddMany( [(self.tmin_box, wx.ALIGN_LEFT),
                                (self.tmax_box, wx.ALIGN_LEFT)] )
        buttons1_window.AddMany( [(self.add_fit_button, wx.ALL|wx.ALIGN_CENTER|wx.SHAPED, 0),
                                  (self.add_all_button, wx.ALL|wx.ALIGN_CENTER|wx.SHAPED, 0),
                                  (self.delete_fit_button, wx.ALL|wx.ALIGN_CENTER|wx.SHAPED, 0),
                                  (self.apply_changes_button, wx.ALL|wx.ALIGN_CENTER|wx.SHAPED, 0)])
        self.display_sizer.Add(display_window_0, 1, wx.TOP|wx.EXPAND, 8)
        self.display_sizer.Add(display_window_1, 1, wx.TOP | wx.LEFT|wx.EXPAND, 8)
        self.display_sizer.Add(display_window_2, 1, wx.TOP | wx.LEFT|wx.EXPAND, 8)
        self.name_sizer.Add(name_window, 1, wx.TOP, 5.5)
        self.bounds_sizer.Add(bounds_window, 1, wx.TOP, 5.5)
        self.buttons_sizer.Add(buttons1_window, 1, wx.TOP, 0)

        #duplicate high levels plot
        self.fig = Figure((2.5*self.GUI_RESOLUTION, 2.5*self.GUI_RESOLUTION), dpi=100)
        self.canvas = FigCanvas(self.panel, -1, self.fig, )
        self.toolbar = NavigationToolbar(self.canvas)
        self.toolbar.Hide()
        self.toolbar.zoom()
        self.high_EA_setting = "Zoom"
        self.canvas.Bind(wx.EVT_LEFT_DCLICK,self.on_equalarea_high_select)
        self.canvas.Bind(wx.EVT_MOTION,self.on_change_high_mouse_cursor)
        self.canvas.Bind(wx.EVT_MIDDLE_DOWN,self.home_high_equalarea)
        self.canvas.Bind(wx.EVT_RIGHT_DOWN,self.pan_zoom_high_equalarea)
        self.canvas.SetHelpText(dieh.eqarea_help)

        self.eqarea = self.fig.add_subplot(111)
        draw_net(self.eqarea)

        #Higher Level Statistics Box
        self.stats_sizer = wx.StaticBoxSizer( wx.StaticBox( self.panel, wx.ID_ANY,"mean statistics"  ), wx.VERTICAL)

        for parameter in ['mean_type','dec','inc','alpha95','K','R','n_lines','n_planes']:
            COMMAND="self.%s_window=wx.TextCtrl(self.panel,style=wx.TE_CENTER|wx.TE_READONLY,size=(100*self.GUI_RESOLUTION,25))"%parameter
            exec(COMMAND)
            COMMAND="self.%s_window.SetBackgroundColour(wx.WHITE)"%parameter
            exec(COMMAND)
            COMMAND="self.%s_window.SetFont(font2)"%parameter
            exec(COMMAND)
            COMMAND="self.%s_outer_window = wx.GridSizer(1,2,5*self.GUI_RESOLUTION,15*self.GUI_RESOLUTION)"%parameter
            exec(COMMAND)
            COMMAND="""self.%s_outer_window.AddMany([
                    (wx.StaticText(self.panel,label='%s',style=wx.TE_CENTER),wx.EXPAND),
                    (self.%s_window, wx.EXPAND)])"""%(parameter,parameter,parameter)
            exec(COMMAND)
            COMMAND="self.stats_sizer.Add(self.%s_outer_window, 1, wx.ALIGN_LEFT|wx.EXPAND, 0)"%parameter
            exec(COMMAND)

        self.switch_stats_button = wx.SpinButton(self.panel, id=wx.ID_ANY, style=wx.SP_HORIZONTAL|wx.SP_ARROW_KEYS|wx.SP_WRAP, name="change stats")
        self.Bind(wx.EVT_SPIN, self.on_select_stats_button,self.switch_stats_button)
        self.switch_stats_button.SetHelpText(dieh.switch_stats_btn_help)

        #construct panel
        hbox0 = wx.BoxSizer(wx.HORIZONTAL)
        hbox0.Add(self.name_sizer,flag=wx.ALIGN_TOP|wx.EXPAND,border=8)
        hbox0.Add(self.bounds_sizer,flag=wx.ALIGN_TOP|wx.EXPAND,border=8)

        vbox0 = wx.BoxSizer(wx.VERTICAL)
        vbox0.Add(hbox0,flag=wx.ALIGN_TOP,border=8)
        vbox0.Add(self.buttons_sizer,flag=wx.ALIGN_TOP,border=8)

        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        hbox1.Add(vbox0,flag=wx.ALIGN_TOP,border=8)
        hbox1.Add(self.stats_sizer,flag=wx.ALIGN_TOP,border=8)
        hbox1.Add(self.switch_stats_button,flag=wx.ALIGN_TOP|wx.EXPAND,border=8)

        vbox1 = wx.BoxSizer(wx.VERTICAL)
        vbox1.Add(self.display_sizer,flag=wx.ALIGN_TOP,border=8)
        vbox1.Add(hbox1,flag=wx.ALIGN_TOP,border=8)
        vbox1.Add(self.canvas,proportion=1,flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,border=8)

        vbox2 = wx.BoxSizer(wx.VERTICAL)
        vbox2.Add(self.search_bar,proportion=.5,flag=wx.ALIGN_LEFT | wx.ALIGN_BOTTOM | wx.EXPAND, border=8)
        vbox2.Add(self.logger,proportion=1,flag=wx.ALIGN_LEFT|wx.EXPAND,border=8)

        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        hbox2.Add(vbox2,proportion=1,flag=wx.ALIGN_LEFT|wx.EXPAND)
        hbox2.Add(vbox1,flag=wx.ALIGN_TOP|wx.EXPAND)

        self.panel.SetSizerAndFit(hbox2)
        hbox2.Fit(self)


Instruction:
Create a Python 3 function to
update the interpretation editor window to reflect the changes made to the interpretation data.

Response:
def update_editor(self):
        """
        updates the logger and plot on the interpretation editor window
        """

        self.fit_list = []
        self.search_choices = []
        for specimen in self.specimens_list:
            if specimen not in self.parent.pmag_results_data['specimens']: continue
            self.fit_list += [(fit,specimen) for fit in self.parent.pmag_results_data['specimens'][specimen]]

        self.logger.DeleteAllItems()
        offset = 0
        for i in range(len(self.fit_list)):
            i -= offset
            v = self.update_logger_entry(i)
            if v == "s": offset += 1


Instruction:
Can you tell what is the following Python 3 function doing
def update_logger_entry(self,i):
        if i < len(self.fit_list):
            tup = self.fit_list[i]
        elif i < self.logger.GetItemCount():
            self.logger.DeleteItem(i)
            return
        else: return

        coordinate_system = self.parent.COORDINATE_SYSTEM
        fit = tup[0]
        pars = fit.get(coordinate_system)
        fmin,fmax,n,ftype,dec,inc,mad,dang,a95,sk,sr2 = "","","","","","","","","","",""

        specimen = tup[1]
        if coordinate_system=='geographic':
            block_key = 'zijdblock_geo'
        elif coordinate_system=='tilt-corrected':
            block_key = 'zijdblock_tilt'
        else:
            block_key = 'zijdblock'

        name = fit.name
        if pars == {} and self.parent.Data[specimen][block_key] != []:
            fit.put(specimen, coordinate_system, self.parent.get_PCA_parameters(specimen,fit,fit.tmin,fit.tmax,coordinate_system,fit.PCA_type))
            pars = fit.get(coordinate_system)
        if self.parent.Data[specimen][block_key]==[]:
            spars = fit.get('specimen')
            fmin = fit.tmin
            fmax = fit.tmax
            if 'specimen_n' in list(spars.keys()): n = str(spars['specimen_n'])
            else: n = 'No Data'
            if 'calculation_type' in list(spars.keys()): ftype = spars['calculation_type']
            else: ftype = 'No Data'
            dec = 'No Data'
            inc = 'No Data'
            mad = 'No Data'
            dang = 'No Data'
            a95 = 'No Data'
            sk = 'No Data'
            sr2 = 'No Data'
        else:
            if 'measurement_step_min' in list(pars.keys()): fmin = str(fit.tmin)
            else: fmin = "N/A"
            if 'measurement_step_max' in list(pars.keys()): fmax = str(fit.tmax)
            else: fmax = "N/A"
            if 'specimen_n' in list(pars.keys()): n = str(pars['specimen_n'])
            else: n = "N/A"
            if 'calculation_type' in list(pars.keys()): ftype = pars['calculation_type']
            else: ftype = "N/A"
            if 'specimen_dec' in list(pars.keys()): dec = "%.1f"%pars['specimen_dec']
            else: dec = "N/A"
            if 'specimen_inc' in list(pars.keys()): inc = "%.1f"%pars['specimen_inc']
            else: inc = "N/A"
            if 'specimen_mad' in list(pars.keys()): mad = "%.1f"%pars['specimen_mad']
            else: mad = "N/A"
            if 'specimen_dang' in list(pars.keys()): dang = "%.1f"%pars['specimen_dang']
            else: dang = "N/A"
            if 'specimen_alpha95' in list(pars.keys()): a95 = "%.1f"%pars['specimen_alpha95']
            else: a95 = "N/A"
            if 'specimen_k' in list(pars.keys()): sk = "%.1f"%pars['specimen_k']
            else: sk = "N/A"
            if 'specimen_r' in list(pars.keys()): sr2 = "%.1f"%pars['specimen_r']
            else: sr2 = "N/A"

        if self.search_query != "":
            entry = (specimen+name+fmin+fmax+n+ftype+dec+inc+mad+dang+a95+sk+sr2).replace(" ","").lower()
            if self.search_query not in entry:
                self.fit_list.pop(i)
                if i < self.logger.GetItemCount():
                    self.logger.DeleteItem(i)
                return "s"
        for e in (specimen,name,fmin,fmax,n,ftype,dec,inc,mad,dang,a95,sk,sr2):
            if e not in self.search_choices:
                self.search_choices.append(e)

        if i < self.logger.GetItemCount():
            self.logger.DeleteItem(i)
        self.logger.InsertItem(i, str(specimen))
        self.logger.SetItem(i, 1, name)
        self.logger.SetItem(i, 2, fmin)
        self.logger.SetItem(i, 3, fmax)
        self.logger.SetItem(i, 4, n)
        self.logger.SetItem(i, 5, ftype)
        self.logger.SetItem(i, 6, dec)
        self.logger.SetItem(i, 7, inc)
        self.logger.SetItem(i, 8, mad)
        self.logger.SetItem(i, 9, dang)
        self.logger.SetItem(i, 10, a95)
        self.logger.SetItem(i, 11, sk)
        self.logger.SetItem(i, 12, sr2)
        self.logger.SetItemBackgroundColour(i,"WHITE")
        a,b = False,False
        if fit in self.parent.bad_fits:
            self.logger.SetItemBackgroundColour(i,"red")
            b = True
        if self.parent.current_fit == fit:
            self.logger.SetItemBackgroundColour(i,"LIGHT BLUE")
            self.logger_focus(i)
            self.current_fit_index = i
            a = True
        if a and b:
            self.logger.SetItemBackgroundColour(i,"red")

Response: helper function that updates the logger entry with the information from the fit_list parameter