Instruction:
Write a Python 3 function that can
adjust a value to be within a range 0 - 360.

Response:
def adjust_to_360(val, key):
    """
    Take in a value and a key.  If the key is of the type:
    declination/longitude/azimuth/direction, adjust it to be within
    the range 0-360 as required by the MagIC data model
    """
    CheckDec = ['_dec', '_lon', '_azimuth', 'dip_direction']
    adjust = False
    for dec_key in CheckDec:
        if dec_key in key:
            if key.endswith(dec_key) or key.endswith('_'):
                adjust = True
    if not val:
        return ''
    elif not adjust:
        return val
    elif adjust:
        new_val = float(val) % 360
        if new_val != float(val):
            print('-I- adjusted {} {} to 0=>360.: {}'.format(key, val, new_val))
        return new_val


Instruction:
Here you have a function in Python 3, explain what it does
def adjust_all_to_360(dictionary):
    for key in dictionary:
        dictionary[key] = adjust_to_360(dictionary[key], key)
    return dictionary

Response: Adjusts all declination longitude and azimuth direction of all items in a dictionary to be within 0 - 360


Instruction:
Create a Python 3 function for
returning lists of declination, inclination and intensities for lat/lon grid for desired model and date. Parameters: _________________ date = Required date in decimal years (Common Era, negative for Before Common Era) Optional Parameters: ______________ mod = model to use ('arch3k','cals3k','pfm9k','hfm10k','cals10k.2','shadif14k','cals10k.1b','custom') file = l m g h formatted filefor custom model lon_0 : central longitude for Hammer projection alt = altitude resolution = ['low','high'] default is low Returns: ______________ Bdec=list of declinations Binc=list of inclinations B = list of total field intensities in nT Br = list of radial field intensities lons = list of longitudes evaluated lats = list of latitudes evaluated

Response:
def do_mag_map(date, lon_0=0, alt=0, file="", mod="cals10k",resolution='low'):
    """
    returns lists of declination, inclination and intensities for lat/lon grid for
    desired model and date.

    Parameters:
    _________________
    date = Required date in decimal years (Common Era, negative for Before Common Era)

    Optional Parameters:
    ______________
    mod  = model to use ('arch3k','cals3k','pfm9k','hfm10k','cals10k.2','shadif14k','cals10k.1b','custom')
    file = l m g h formatted filefor custom model
    lon_0 : central longitude for Hammer projection
    alt  = altitude
    resolution = ['low','high'] default is low

    Returns:
    ______________
    Bdec=list of declinations
    Binc=list of inclinations
    B = list of total field intensities in nT
    Br = list of radial field intensities
    lons = list of longitudes evaluated
    lats = list of latitudes evaluated

    """
    if resolution=='low':
        incr = 10  # we can vary to the resolution of the model
    elif resolution=='high':
        incr = 2  # we can vary to the resolution of the model
    if lon_0 == 180:
        lon_0 = 179.99
    if lon_0 > 180:
        lon_0 = lon_0-360.
    # get some parameters for our arrays of lat/lon
    lonmax = (lon_0 + 180.) % 360 + incr
    lonmin = (lon_0 - 180.)
    latmax = 90 + incr
    # make a 1D array of longitudes (like elons)
    lons = np.arange(lonmin, lonmax, incr)
    # make a 1D array of longitudes (like elats)
    lats = np.arange(-90, latmax, incr)
    # set up some containers for the field elements
    B = np.zeros((len(lats), len(lons)))
    Binc = np.zeros((len(lats), len(lons)))
    Bdec = np.zeros((len(lats), len(lons)))
    Brad = np.zeros((len(lats), len(lons)))
    if mod == 'custom' and file != '':
        gh = []
        lmgh = np.loadtxt(file).transpose()
        gh.append(lmgh[2][0])
        for i in range(1, lmgh.shape[1]):
            gh.append(lmgh[2][i])
            if lmgh[1][i] != 0:
                gh.append(lmgh[3][i])
    for j in range(len(lats)):  # step through the latitudes
        for i in range(len(lons)):  # and the longitudes
            # get the field elements
            if mod == 'custom':
                x, y, z, f = docustom(lons[i], lats[j], alt, gh)
            else:
                x, y, z, f = doigrf(
                    lons[i], lats[j], alt, date, mod=mod, file=file)
            # turn them into polar coordinates
            Dec, Inc, Int = cart2dir([x, y, z])
            if mod != 'custom':
                # convert the string to microtesla (from nT)
                B[j][i] = Int * 1e-3
            else:
                B[j][i] = Int  # convert the string to microtesla (from nT)
            Binc[j][i] = Inc  # store the inclination value
            if Dec > 180:
                Dec = Dec-360.
            Bdec[j][i] = Dec  # store the declination value
            if mod != 'custom':
                Brad[j][i] = z*1e-3
            else:
                Brad[j][i] = z
    return Bdec, Binc, B, Brad, lons, lats


Instruction:
Can you generate the documentation for the following Python 3 function
def doeqdi(x, y, UP=False):
    xp, yp = y, x  # need to switch into geographic convention
    r = np.sqrt(xp**2+yp**2)
    z = 1.-r**2
    t = np.arcsin(z)
    if UP == 1:
        t = -t
    p = np.arctan2(yp, xp)
    dec, inc = np.degrees(p) % 360, np.degrees(t)
    return dec, inc

Response: Takes digitized x y data and returns the dec inc assuming an upper hemisphere projection


Instruction:
Implement a function in Python 3 to
separate set of directions into two lists of nested dec inc pairs.

Response:
def separate_directions(di_block):
    """
    Separates set of directions into two modes based on principal direction

    Parameters
    _______________
    di_block : block of nested dec,inc pairs

    Return
    mode_1_block,mode_2_block :  two lists of nested dec,inc pairs
    """
    ppars = doprinc(di_block)
    di_df = pd.DataFrame(di_block)  # turn into a data frame for easy filtering
    di_df.columns = ['dec', 'inc']
    di_df['pdec'] = ppars['dec']
    di_df['pinc'] = ppars['inc']
    di_df['angle'] = angle(di_df[['dec', 'inc']].values,
                           di_df[['pdec', 'pinc']].values)
    mode1_df = di_df[di_df['angle'] <= 90]
    mode2_df = di_df[di_df['angle'] > 90]
    mode1 = mode1_df[['dec', 'inc']].values.tolist()
    mode2 = mode2_df[['dec', 'inc']].values.tolist()
    return mode1, mode2


Instruction:
Here you have a function in Python 3, explain what it does
def dovandamme(vgp_df):
    vgp_df['delta'] = 90.-vgp_df['vgp_lat'].values
    ASD = np.sqrt(np.sum(vgp_df.delta**2)/(vgp_df.shape[0]-1))
    A = 1.8 * ASD + 5.
    delta_max = vgp_df.delta.max()
    while delta_max > A:
        delta_max = vgp_df.delta.max()
        if delta_max < A:
            return vgp_df, A, ASD
        vgp_df = vgp_df[vgp_df.delta < delta_max]
        ASD = np.sqrt(np.sum(vgp_df.delta**2)/(vgp_df.shape[0]-1))
        A = 1.8 * ASD + 5.

Response: This function is used to determine the S_b value for VGPs using the Vandamme method.


Instruction:
Here you have a function in Python 3, explain what it does
def scalc_vgp_df(vgp_df, anti=0, rev=0, cutoff=180., kappa=0, n=0, spin=0, v=0, boot=0, mm97=0, nb=1000):
    vgp_df['delta'] = 90.-vgp_df.vgp_lat.values
    # filter by cutoff, kappa, and n
    vgp_df = vgp_df[vgp_df.delta <= cutoff]
    vgp_df = vgp_df[vgp_df.dir_k >= kappa]
    vgp_df = vgp_df[vgp_df.dir_n_samples >= n]
    if spin:  # do transformation to pole
        Pvgps = vgp_df[['vgp_lon', 'vgp_lat']].values
        ppars = doprinc(Pvgps)
        Bdirs = np.full((Pvgps.shape[0]), ppars['dec']-180.)
        Bdips = np.full((Pvgps.shape[0]), 90.-ppars['inc'])
        Pvgps = np.column_stack((Pvgps, Bdirs, Bdips))
        lons, lats = dotilt_V(Pvgps)
        vgp_df['vgp_lon'] = lons
        vgp_df['vgp_lat'] = lats
        vgp_df['delta'] = 90.-vgp_df.vgp_lat
    if anti:
        print('flipping reverse')
        vgp_rev = vgp_df[vgp_df.vgp_lat < 0]
        vgp_norm = vgp_df[vgp_df.vgp_lat >= 0]
        vgp_anti = vgp_rev
        vgp_anti['vgp_lat'] = -vgp_anti['vgp_lat']
        vgp_anti['vgp_lon'] = (vgp_anti['vgp_lon']-180) % 360
        vgp_df = pd.concat([vgp_norm, vgp_anti], sort=True)
    if rev:
        vgp_df = vgp_df[vgp_df.vgp_lat < 0]  # use only reverse data
    if v:
        vgp_df, cutoff, S_v = dovandamme(vgp_df)  # do vandamme cutoff
    S_B = get_sb_df(vgp_df, mm97=mm97)  # get
    N = vgp_df.shape[0]
    SBs, low, high = [], 0, 0
    if boot:
        for i in range(nb):  # now do bootstrap
            bs_df = vgp_df.sample(n=N, replace=True)
            Sb_bs = get_sb_df(bs_df)
            SBs.append(Sb_bs)
        SBs.sort()
        low = SBs[int(.025 * nb)]
        high = SBs[int(.975 * nb)]
    return N, S_B, low, high, cutoff

Response: Calculates the Sf for a dataframe with VGP Lat. and optional Fisher s k site latitude and optional N information can be used to correct for within site scatter.


Instruction:
Can you write a function in Python 3 where it
calculates Watson s F statistic for two data sets.

Response:
def watsons_f(DI1, DI2):
    """
    calculates Watson's F statistic (equation 11.16 in Essentials text book).

    Parameters
    _________
    DI1 : nested array of [Dec,Inc] pairs
    DI2 : nested array of [Dec,Inc] pairs

    Returns
    _______
    F : Watson's F
    Fcrit : critical value from F table
    """
    # first calculate R for the combined data set, then R1 and R2 for each individually.
    # create a new array from two smaller ones
    DI = np.concatenate((DI1, DI2), axis=0)
    fpars = fisher_mean(DI)  # re-use our functionfrom problem 1b
    fpars1 = fisher_mean(DI1)
    fpars2 = fisher_mean(DI2)
    N = fpars['n']
    R = fpars['r']
    R1 = fpars1['r']
    R2 = fpars2['r']
    F = (N-2.)*((R1+R2-R)/(N-R1-R2))
    Fcrit = fcalc(2, 2*(N-2))
    return F, Fcrit


Instruction:
Implement a Python 3 function for
calculating expected pole positions and directions for given plate, location and age Parameters _________ data : [plate,lat,lon,age] plate : [NA, SA, AF, IN, EU, AU, ANT, GL] NA : North America SA : South America AF : Africa IN : India EU : Eurasia AU : Australia ANT: Antarctica GL : Greenland lat/lon : latitude/longitude in degrees N/E age : age in millions of years print_results : if True will print out nicely formatted results Returns _________ if print_results is False, [Age,Paleolat, Dec, Inc, Pole_lat, Pole_lon]

Response:
def apwp(data, print_results=False):
    """
    calculates expected pole positions and directions for given plate, location and age
    Parameters
    _________
        data : [plate,lat,lon,age]
            plate : [NA, SA, AF, IN, EU, AU, ANT, GL]
                NA : North America
                SA : South America
                AF : Africa
                IN : India
                EU : Eurasia
                AU : Australia
                ANT: Antarctica
                GL : Greenland
             lat/lon : latitude/longitude in degrees N/E
             age : age in millions of years
        print_results : if True will print out nicely formatted results
    Returns
    _________
        if print_results is False, [Age,Paleolat, Dec, Inc, Pole_lat, Pole_lon]
    """
    pole_lat, pole_lon = bc02(data)  # get the pole for these parameters
    # get the declination and inclination for that pole
    ExpDec, ExpInc = vgp_di(pole_lat, pole_lon, data[1], data[2])
    # convert the inclination to paleo latitude
    paleo_lat = magnetic_lat(ExpInc)
    if print_results:
        # print everything out
        print(' Age   Paleolat.   Dec.   Inc.   Pole_lat.  Pole_Long.')
        print('%7.1f %7.1f %7.1f %7.1f %7.1f  %7.1f\n'
              % (data[3], paleo_lat, ExpDec, ExpInc, pole_lat, pole_lon))

    else:
        return [data[3], paleo_lat, ExpDec, ExpInc, pole_lat, pole_lon]


Instruction:
How would you explain what the following Python 3 function does
def chart_maker(Int, Top, start=100, outfile='chart.txt'):
    low, k, iz = start, 0, 0
    Tzero = []
    f = open('chart.txt', 'w')
    vline = '\t%s\n' % (
        '   |      |        |         |          |       |    |      |')
    hline = '______________________________________________________________________________\n'
    f.write('file:_________________    field:___________uT\n\n\n')
    f.write('%s\n' % (
        '               date | run# | zone I | zone II | zone III | start | sp | cool|'))
    f.write(hline)
    f.write('\t%s' % ('   0.0'))
    f.write(vline)
    f.write(hline)
    for k in range(len(Top)):
        for t in range(low, Top[k]+Int[k], Int[k]):
            if iz == 0:
                Tzero.append(t)  # zero field first step
                f.write('%s \t %s' % ('Z', str(t)+'.'+str(iz)))
                f.write(vline)
                f.write(hline)
                if len(Tzero) > 1:
                    f.write('%s \t %s' % ('P', str(Tzero[-2])+'.'+str(2)))
                    f.write(vline)
                    f.write(hline)
                iz = 1
                # infield after zero field first
                f.write('%s \t %s' % ('I', str(t)+'.'+str(iz)))
                f.write(vline)
                f.write(hline)

#                f.write('%s \t %s'%('T',str(t)+'.'+str(3))) # print second zero field (tail check)
#                f.write(vline)
#                f.write(hline)

            elif iz == 1:
                # infield first step
                f.write('%s \t %s' % ('I', str(t)+'.'+str(iz)))
                f.write(vline)
                f.write(hline)
                iz = 0
                # zero field step (after infield)
                f.write('%s \t %s' % ('Z', str(t)+'.'+str(iz)))
                f.write(vline)
                f.write(hline)
        try:
            low = Top[k]+Int[k+1]  # increment to next temp step
        except:
            f.close()
    print("output stored in: chart.txt")

Response: This function creates a chart for performing IZZI experiments.


Instruction:
Can you create a Python 3 function that
tries to import Basemap and print out a useful help message if it can t be imported.

Response:
def import_basemap():
    """
    Try to import Basemap and print out a useful help message
    if Basemap is either not installed or is missing required
    environment variables.

    Returns
    ---------
    has_basemap : bool
    Basemap : Basemap package if possible else None
    """

    Basemap = None
    has_basemap = True
    has_cartopy = import_cartopy()[0]
    try:
        from mpl_toolkits.basemap import Basemap
        WARNINGS['has_basemap'] = True
    except ImportError:
        has_basemap = False
        # if they have installed cartopy, no warning is needed
        if has_cartopy:
            return has_basemap, False
        # if they haven't installed Basemap or cartopy, they need to be warned
        if not WARNINGS['basemap']:
            print(
                "-W- You haven't installed a module for plotting maps (cartopy or Basemap)")
            print("    Recommended: install cartopy.  With conda:")
            print("    conda install cartopy")
            print(
                "    For more information, see http://earthref.org/PmagPy/Cookbook#getting_python")
    except (KeyError, FileNotFoundError):
        has_basemap = False
        # if cartopy is installed, no warning is needed
        if has_cartopy:
            return has_basemap, False
        if not WARNINGS['basemap']:
            print('-W- Basemap is installed but could not be imported.')
            print('    You are probably missing a required environment variable')
            print(
                '    If you need to use Basemap, you will need to run this program or notebook in a conda env.')
            print('    For more on how to create a conda env, see: https://conda.io/docs/user-guide/tasks/manage-environments.html')
            print(
                '    Recommended alternative: install cartopy for plotting maps.  With conda:')
            print('    conda install cartopy')
    if has_basemap and not has_cartopy:
        print("-W- You have installed Basemap but not cartopy.")
        print("    In the future, Basemap will no longer be supported.")
        print("    To continue to make maps, install using conda:")
        print('    conda install cartopy')

    WARNINGS['basemap'] = True
    return has_basemap, Basemap


Instruction:
Write a Python 3 function for
trying to import cartopy and print out a help message if it is not installed

Response:
def import_cartopy():
    """
    Try to import cartopy and print out a help message
    if it is not installed

    Returns
    ---------
    has_cartopy : bool
    cartopy : cartopy package if available else None
    """
    cartopy = None
    has_cartopy = True
    try:
        import cartopy
        WARNINGS['has_cartopy'] = True
    except ImportError:
        has_cartopy = False
        if not WARNINGS['cartopy']:
            print('-W- cartopy is not installed')
            print('    If you want to make maps, install using conda:')
            print('    conda install cartopy')
    WARNINGS['cartopy'] = True
    return has_cartopy, cartopy


Instruction:
How would you explain what the following Python 3 function does
def age_to_BP(age, age_unit):
    ageBP = -1e9
    if age_unit == "Years AD (+/-)" or age_unit == "Years Cal AD (+/-)":
        if age < 0:
            age = age+1  # to correct for there being no 0 AD
        ageBP = 1950-age
    elif age_unit == "Years BP" or age_unit == "Years Cal BP":
        ageBP = age
    elif age_unit == "ka":
        ageBP = age*1000
    elif age_unit == "Ma":
        ageBP = age*1e6
    elif age_unit == "Ga":
        ageBP = age*1e9
    else:
        print("Age unit invalid. Age set to -1.0e9")

    return ageBP

Response: Converts an age value into the equivalent in time Before Present ( BP


Instruction:
Implement a Python 3 function for
converting a MagIC database vocabulary to other standards.

Response:
def vocab_convert(vocab, standard, key=''):
    """
    Converts MagIC database terms (method codes, geologic_types, etc) to other standards.
    May not be comprehensive for each standard. Terms added to standards as people need them
    and may not be up-to-date.

    'key' can be used to distinguish vocab terms that exist in two different lists.

    Returns:
    value of the MagIC vocab in the standard requested

    Example:
    vocab_convert('Egypt','GEOMAGIA') will return '1'
    """

    places_to_geomagia = {
        'Egypt':                 "1",
        'Japan':                 "2",
        'France':                "3",
        'Ukraine':               "5",
        'India':                 "6",
        'China':                 "7",
        'Finland':               "8",
        'Greece':                "9",
        'Italy':                 "11",
        'Switzerland':           "12",
        'Bulgaria':              "13",
        'Syria':                 "14",
        'Hungary':               "15",
        'East Pacific Ridge':    "17",
        'Hawaii':                "18",
        'Morocco':               "19",
        'Australia':             "20",
        'Georgia':               "21",
        'Azerbaijan':            "22",
        'Spain':                 "24",
        'England':               "25",
        'Czech Republic':        "26",
        'Mexico':                "27",
        'Iraq':                  "28",
        'Israel':                "29",
        'Iran':                  "30",
        'Uzbekistan':            "31",
        'Turkmenistan':          "32",
        'Mongolia':              "33",
        'Iceland':               "34",
        'New Zealand':           "35",
        'Amsterdam Island':      "36",
        'Guadeloupe':            "37",
        'Mid Atlantic Ridge':    "38",
        'Austria':               "39",
        'Belgium':               "40",
        'Romania':               "41",
        'Guatemala':             "42",
        'El Salvador':           "43",
        'Canary Islands':        "45",
        'Moldova':               "46",
        'Latvia':                "47",
        'Lithuania':             "48",
        'Russia':                "49",
        'Germany':               "51",
        'Martinique':            "52",
        'Netherlands':           "53",
        'Turkey':                "54",
        'Denmark':               "55",
        'Cameroon':              "56",
        'Honduras':              "57",
        'Jordan':                "58",
        'Brazil':                "59",
        'Estonia':               "61",
        'Sweden':                "62",
        'Peru':                  "63",
        'Bolivia':               "64",
        'Ecuador':               "65",
        'Ontario':               "66",
        'New Mexico':            "67",
        'Arizona':               "68",
        'California':            "69",
        'Colorado':              "70",
        'Utah':                  "71",
        'Washington':            "72",
        'Oregon':                "73",
        'British Columbia':      "74",
        'Idaho':                 "75",
        'Arkansas':              "76",
        'Tennessee':             "78",
        'Serbia':                "79",
        'Kosovo':                "80",
        'Portugal':              "81",
        'Thailand':              "82",
        'South Korea':           "83",
        'Kazakhstan':            "84",
        'Nebraska':              "85",
        'La Reunion':            "86",
        'Cyprus':                "87",
        'Papua New Guinea':      "88",
        'Vanuatu':               "89",
        'Fiji':                  "90",
        'Argentina':             "91",
        'Tunisia':               "92",
        'Mali':                  "93",
        'Senegal':               "95",
        'Alaska':                "96",
        'North Atlantic':        "97",
        'South Atlantic':        "98",
        'Beaufort Sea':          "99",
        'Chukchi Sea':           "100",
        'Kyrgyzstan':            "101",
        'Indonesia':             "102",
        'Azores':                "103",
        'Quebec':                "104",
        'Norway':                "105",
        'Northern Ireland':      "106",
        'Wales':                 "107",
        'Scotland':              "108",
        'Virginia':              "109",
        'North West Pacific':    "110",
        'Mediterranean':         "111",
        'Slovakia':              "121",
        'Poland':                "124"
    }

    geologic_types_to_geomagia = {
        "Baked Clay":                                  "2",
        "Tile":                                        "3",
        "Lava":                                        "4",
        "Pottery":                                     "5",
        "Sun Dried Object":                            "6",
        "Porcelain":                                   "7",
        "Ceramic":                                     "8",
        "Kiln":                                        "9",
        "Oven or Hearth (GEOMAGIA Only)":              "10",
        "Mixed Archeological Objects":                 "11",
        "Slag":                                        "12",
        "Baked Rock":                                  "13",
        "Fresco":                                      "14",
        "Mosaic":                                      "15",
        "Wall":                                        "16",
        "Bath":                                        "17",
        "Burnt Floor":                                 "18",
        "Funeral Pyre":                                "19",
        "Hypocaust":                                   "20",
        "Burnt Pit":                                   "21",
        "Bell Mould":                                  "22",
        "Smoking Chamber":                             "23",
        "Baked Mud":                                   "24",
        "Volcanic Ash":                                "25",
        "Burnt Structure":                             "26",
        "Burnt Castle Wall":                           "27",
        "Charcoal Pile":                               "28",
        "Burnt Earth":                                 "29",
        "Vitrified Object":                            "30",
        "Unbaked Sediment":                            "31",
        "Tuyere":                                      "32",
        "Sauna":                                       "33",
        "Pit Structure":                               "35",
        "Room":                                        "36",
        "Pit House":                                   "37",
        "Salt Kiln":                                   "38",
        "Burnt Sediment":                              "39",
        "Archeological Ashes":                         "40",
        "Volcanic Other or Undefined (GEOMAGIA Only)": "41",
        "Mural":                                       "42",
        "Vitrified Stone":                             "43",
        "Soil":                                        "44",
        "Kamadogu":                                    "45",
        "Foundry":                                     "46",
        "Obsidian":                                    "47",
        "Chert":                                       "48",
        "Burnt daub":                                  "49",
        "Amphora":                                     "50",
        "Granite":                                     "51",
        "Volcanic Glass":                              "52",
        "Furnace":                                     "53",
        "Roasting Pit":                                "54"

    }

#   Some of the simple method code mappings are done here

    method_codes_to_geomagia = {
        "GM-NO":        "0",
        "GM-CC-ARCH":   "101",
        "GM-C14-CAL":   "102",
        "GM-C14-UNCAL": "103",
        "GM-LUM-TH":    "104",
        "GM-HIST":      "105",
        "GM-PMAG-ARCH": "106",
        "GM-ARAR":      "107",
        "GM-CC-TEPH":   "108",
        "GM-CC-STRAT":  "109",
        "GM-CC-REL":    "110",
        "GM-DENDRO":    "111",
        "GM-RATH":      "112",
        "GM-KAR":       "113",
        "GM-UTH":       "114",
        "GM-FT":        "115",
        "GM-C14-AMS":   "116",
        "GM-LUM-OS":    "117",
        "GM-HE3":       "118",
        "GM-VARVE":     "119",
        "GM-CS137":     "120",
        "GM-USD-PB210": "121",
        "GM-C14-BETA":  "122",
        "GM-O18":       "123",
        "GM-PA":        "124"
    }

    standard = standard.lower()
    standard_value = ""
    if standard == "geomagia":
        if vocab in places_to_geomagia.keys():
            standard_value = places_to_geomagia[vocab]
        if vocab in geologic_types_to_geomagia.keys():
            standard_value = geologic_types_to_geomagia[vocab]
        if vocab in method_codes_to_geomagia.keys():
            standard_value = method_codes_to_geomagia[vocab]
    if standard_value == "":
        if vocab=='':
            standard_value="Fail:vocab_to_convert_is_null"
        elif vocab.isspace() or vocab!='':
            standard_value="Fail:vocab_to_convert_is_all_whitespace"
        else:
            print("pmag.vocab_convert:Magic vocab '", vocab, "' not found for standard ", standard, sep='')
            return(vocab)
    return standard_value


Instruction:
Can you implement a function in Python 3 that
takes arguments input_directory output_directory and returns realpath for both values.

Response:
def fix_directories(input_dir_path, output_dir_path):
    """
    Take arguments input/output directories and fixes them.
    If no input_directory, default to output_dir_path for both.
    Then return realpath for both values.

    Parameters
    ----------
    input_dir_path : str
    output_dir_path : str

    Returns
    ---------
    input_dir_path, output_dir_path
    """
    if not input_dir_path:
        input_dir_path = output_dir_path
    input_dir_path = os.path.realpath(input_dir_path)
    output_dir_path = os.path.realpath(output_dir_path)
    return input_dir_path, output_dir_path


Instruction:
Here you have a function in Python 3, explain what it does
def main():
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file_name=sys.argv[ind+1]
    else:
        print("MagIC file name needed. Please add the file name after the -f option.")

#   Create all the table files from the magic.txt file so they can be imported by the cb
    command = "download_magic.py -f " + file_name
    os.system(command)

    md = cb.Contribution()  #md stands for magic file data
    md.propagate_location_to_measurements()
    md.propagate_location_to_specimens()
    md.propagate_location_to_samples()
    if not md.tables:
        print('-E- No MagIC tables could be found in this directory')
        error_log("No MagIC tables found")
        return

    doi=md.tables['contribution'].df.iloc[0]['reference']
    id=md.tables['contribution'].df.iloc[0]['id']
    timestamp=md.tables['contribution'].df.iloc[0]['timestamp']
    contributor=md.tables['contribution'].df.iloc[0]['contributor']
    print("c=",contributor)
    contributor=contributor.replace('@','')
    print("c=",contributor)

    cr = Crossref()
    ref=cr.works(doi)

#    authors = "Doe J.X., Alexander,T.G."
    status= ref["status"]
    message= ref["message"]
#    print("message=",message)
    authors= message["author"]
#    print("authors=",authors)
    authorList=""
    for author in authors:
#        print ("Name:",author['given'], author['family'])
        author_given=""
        names=author['given'].split(' ')
        for name in names:
            author_given +=name[0]+"."
        authorList += author['family'] + " " + author_given + ", "
#    print(authorList)
    authorList=authorList[:-2]
#    print(authorList)

    title = message['title'][0]
    year = message['created']['date-parts'][0][0]
#    print(year)
    journal = message['short-container-title'][0]
    volume = message['volume']
#    print(volume)
    pages='0'
    if "page" in message.keys():
        pages = message['page']
#    print(pages)
    url = "https://earthref.org/MagIC/doi/" + doi

    print("REFS")
    print("Insert into REFS values(NULL,'", authorList, "','", title, "', ", year, ", '", journal, "', ", volume, ", '", pages, "', '", doi, "', '", url, "');", sep='')

    print()
    print("ARCHEODIJ")

    sites=md.tables['sites'].df
    locations=md.tables['locations'].df

    print("UID,NUM_SAMPLES,NUM_ACC_SPEC,NUM_MEAS_SPEC,BA,SIGMA_BA,AGE, AGE_MIN,AGE_MAX,NUM_SIGMAS,AGE_ERROR_TYPE_ID,SITE_LAT, SITE_LON,VADM,SIGMA_VADM,SITE_ID,PI_METHODS_ID,AC_ID,MD_CK_ ID,AN_CORR_ID,CR_CORR_ID,DM_METHOD_ID,AF_STEP,T_STEP,DM_ ANALYSIS_ID,SPECIMEN_TYPE_ID,MATERIAL_ID,REFERENCE_ID,NUM_ C14_SAMPLES,C14_ID,CALIB_C14_AGE,CALIB_C14_AGE_SIGMA_MIN, CALIB_C14_AGE_SIGMA_MAX,NUM_C14_SIGMAS,CALC_CALIB_C14_AGE, CALC_CALIB_C14_AGE_SIGMA_MIN,CALC_CALIB_C14_AGE_SIGMA_MAX, C14_CALIB_SOFTWARE_ID,CALC_C14_CALIB_SOFTWARE_ID,C14_CALIB_DATASET_ID,CALC_C14_ CALIB_DATASET_ID,DENDRO_ID,TOT_NUM_DENDRO,NUM_DENDRO_ USED,DATING_METHOD_ID,NUM_DIR_SAMPLES,NUM_DIR_SPECIMENS,NUM_ DIR_SPEC_COLLECTED,DECL,INCL,ALPHA_95,K,VDM,SIGMA_VDM,SAMPLE_ID,c_csv,SITE_NAME, SITE_HORIZON,1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014, SUPERSEEDED,UPLOAD_YEAR,UPLOAD_MONTH,UPLOADER,EDITOR,EDIT_DATE,NOTES")

    for index, row in sites.iterrows():
        int_n_samples,int_n_specimens,int_n_total_specimens,int_abs,int_abs_sigma=-1,-1,-1,-1,-1
        if 'int_n_samples' in sites.columns.values:
            int_n_samples=row['int_n_samples']
        if 'int_n_specimens' in sites.columns.values:
            int_n_specimens=row['int_n_specimens']
        if 'int_n_total_specimens' in sites.columns.values:
            int_n_total_specimens=row['int_n_total_specimens']

        if int_n_specimens == -1 and int_n_samples >0:
            int_n_spcimens = int_n_samples

        if 'int_abs' in sites.columns.values:
            int_abs=row['int_abs']
            if int_abs is not None:
                int_abs=round(int_abs*1e6,1)
        if 'int_abs_sigma' in sites.columns.values:
            int_abs_sigma=row['int_abs_sigma']
            if int_abs_sigma is not None:
                int_abs_sigma=round(row['int_abs_sigma']*1e6,1)

        age,age_high,age_low=-1e9,-1e9,-1e9
        age_error_type='0'  #

        if 'age_unit' not in sites.columns.values:
            print("Malformed Magic sites data table. Required column row 'age_unit' is missing")
            sys.exit()
        age_unit=row['age_unit']
        if 'age' in sites.columns.values:
            age=row['age']
            age=pmag.age_to_BP(age,age_unit)
        if 'age_high' in sites.columns.values:
            age_high=row['age_high']
            age_high=pmag.age_to_BP(age_high,age_unit)
        if 'age_low' in sites.columns.values:
            age_low=row['age_low']
            age_low=pmag.age_to_BP(age_low,age_unit)
        if 'age_sigma' in sites.columns.values:
            age_sigma=row['age_sigma']
            age_sigma=pmag.age_to_BP(age_sigma,age_unit)
            age_high=age+age_sigma
            age_low=age-age_sigma
            age_error_type='5'  #Magic is one sigma for all sigma state/province column to data modelages

        if age_low > age_high: # MagIC lets age_high and age_low be in any order. Fix that for GEOMAGIA
            temp=age_high
            age_high=age_low
            age_low=temp
        if age == -1e9:               # If only age_low and age_high are in the MagIC file then calculate the age.
            age=(age_high+age_low)/2
            age_error_type='8'  #If MagIC age only high and low then error type is "range"

        age_min=age-age_low  # GEOMAGIA has the max and min as differences from the age, not absolute.
        age_max=age_high-age
        age_BP=age
        age=1950-age  #GEOMAGIA want +-AD/BC so convert BP to AD/-BC

        lat=row['lat']
        lon=row['lon']

        vadm,vadm_sigma=-1,-1

        if 'vadm' in sites.columns.values:
            vadm=row['vadm']
            vadm=vadm/1e22
        if 'vadm_sigma' in sites.columns.values:
            vadm=row['vadm']
            vadm=vadm/1e22

        site_name=row['site']

#       For paleointensity codes just give the method code list and Max will decide on the right
#       GEOMAGIA code.
        method_codes="No MagIC method codes available"
        if 'method_codes' in sites.columns.values:
            method_codes=row['method_codes']

#       Just give Max all the method codes for him to decide for now
        paleointensity_procedure=method_codes

        alteration_monitor="0"
        alteration_monitor=method_codes_to_geomagia(method_codes,'ALTERATION_MONIT_CORR')
        multidomain_check="0"
        multidomain_check=method_codes_to_geomagia(method_codes,'MD_CHECKS')
        anisotropy_correction="0"
        anisotropy_correction=method_codes_to_geomagia(method_codes,'ANISOTROPY_CORRECTION')
        cooling_rate="0"
        cooling_rate=method_codes_to_geomagia(method_codes,'COOLING_RATE')
        demag_method="0"
        demag_method=method_codes_to_geomagia(method_codes,'DM_METHODS')
        demag_analysis="0"
        demag_analysis=method_codes_to_geomagia(method_codes,'DM_ANALYSIS')
        specimen_shape="0"
        specimen_shape=method_codes_to_geomagia(method_codes,'SPECIMEN_TYPE_ID')

        materials=""
        geologic_types=""
        if 'geologic_types' in sites.columns.values:
            geologic_types=row['geologic_types']
        if ":" in geologic_types:
            gtypes=geologic_types.split(":")
            for gtype in gtypes:
                materials=materials+pmag.vocab_convert(gtype,"geomagia")+":"
            materials=materials[:-1]
        else:
            materials=pmag.vocab_convert(geologic_types,"geomagia")

        geochron_codes=""
        if ":" in method_codes:
            gcodes=method_codes.split(":")
            for gcode in gcodes:
                if "GM-" == gcode[:3]:
                    geochron_codes=geochron_codes+pmag.vocab_convert(gcode,"geomagia")+":"
            geochron_codes=geochron_codes[:-1]
        else:
            geochron_codes=pmag.vocab_convert(geochron_codes,"geomagia")
        if geochron_codes == "":
            geochron_codes="0"

        dir_n_samples="-1"
        if 'dir_n_samples' in sites.columns.values:
            dir_n_samples=row['dir_n_samples']

        dir_n_samples="-1"
        if 'dir_n_samples' in sites.columns.values:
            dir_n_samples=row['dir_n_samples']

#       Not in MagIC
        dir_n_specimens="-1"

#       using total number of samples for total specimen number
        dir_n_total_samples="-1"
        if 'dir_n_total_samples' in sites.columns.values:
            dir_n_total_samples=row['dir_n_total_samples']

        dir_dec="999"
        if 'dir_dec' in sites.columns.values:
            dir_dec=row['dir_dec']

        dir_inc="999"
        if 'dir_inc' in sites.columns.values:
            dir_inc=row['dir_inc']

        dir_alpha95="-1"
        if 'dir_alpha95' in sites.columns.values:
            dir_alpha95=row['dir_alpha95']

        dir_k="-1"
        if 'dir_k' in sites.columns.values:
            dir_k=row['dir_k']

        vdm=-1
        if 'vdm' in sites.columns.values:
            vdm=float(row['vdm'])
            vdm=vdm/1e22

        vdm_sigma=-1
        if 'vdm_sigma' in sites.columns.values:
            vdm_sigma=float(row['vdm_sigma'])
            vdm_sigma=vdm_sigma/1e22

# Could try and get sample names from samples table (using Contribution object) but just taking the list
# if it exists for now.
        sample_list="-1"
        if 'samples' in sites.columns.values:
            sample_list=row['samples']

# c_csv is in GEOMAGIA insert. What it is I don't know. Max said set to 0
        c_csv='0'

# This place_id is SITE_ID in GEOMAGIA

        place_id="0"
        location=row['location']
        if 'state_province' in locations.columns.values:
            place=locations.loc[location,'state_province']
            if place != "":
                place_id=pmag.vocab_convert(place,'GEOMAGIA')
        if place_id == "0":
            if 'country' in locations.columns.values:
                place=locations.loc[location,'country']
                if place != "":
                    place_id=pmag.vocab_convert(place,'GEOMAGIA')
        if place_id == "0":
            if 'continent_ocean' in locations.columns.values:
                place_id=locations.loc[location,'continent_ocean']
                if place != "":
                    place_id=pmag.vocab_convert(place,'GEOMAGIA')

        site=row['site']
        dt=dateutil.parser.parse(timestamp)

        description="-1"
        if 'description' in sites.columns.values:
            description=row['description']

        if age_BP <= 50000:
            print("0",int_n_samples,int_n_specimens,int_n_total_specimens,int_abs,int_abs_sigma,age,age_min,age_max,"1",age_error_type,lat,lon,vadm,vadm_sigma,place_id,paleointensity_procedure,alteration_monitor,multidomain_check,anisotropy_correction,cooling_rate,demag_method,"0","0",demag_analysis,specimen_shape,materials,doi,"-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1",geochron_codes,dir_n_samples,dir_n_samples,dir_n_total_samples,dir_dec,dir_inc,dir_alpha95,dir_k,vdm,vdm_sigma,sample_list,c_csv,location,site,"-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1","-1",dt.year,dt.month,contributor,"-1,-1",description,sep=',')

Response: This function is the main function that is used to download and insert a MagIC file into the Max Brown s GEOMAGIA database and return the data for easier input into Max Brown s GEOMAGIA database.


Instruction:
Explain what the following Python 3 code does
def method_codes_to_geomagia(magic_method_codes,geomagia_table):
    codes=magic_method_codes
    geomagia=geomagia_table.lower()
    geomagia_code='0'

    if geomagia=='alteration_monit_corr':
        if  "DA-ALT-V" or "LP-PI-ALT-PTRM" or "LP-PI-ALT-PMRM" in codes:
            geomagia_code='1'
        elif "LP-PI-ALT-SUSC" in codes:
            geomagia_code='2'
        elif "DA-ALT-RS" or "LP-PI-ALT-AFARM" in codes:
            geomagia_code='3'
        elif "LP-PI-ALT-WALTON" in codes:
            geomagia_code='4'
        elif "LP-PI-ALT-TANGUY" in codes:
            geomagia_code='5'
        elif "DA-ALT" in codes:
            geomagia_code='6'   #at end to fill generic if others don't exist
        elif "LP-PI-ALT-FABIAN" in codes:
            geomagia_code='7'

    if geomagia=='md_checks':
        if ("LT-PTRM-MD" in codes) or ("LT-PMRM-MD" in codes):
            geomagia_code='1:'
        if ("LP-PI-BT-LT" in codes) or ("LT-LT-Z" in codes):
            if "0" in geomagia_code:
                geomagia_code="23:"
            else:
                geomagia_code+='2:'
        geomagia_code=geomagia_code[:-1]

    if geomagia=='anisotropy_correction':
        if  "DA-AC-AMS" in codes:
            geomagia_code='1'
        elif "DA-AC-AARM" in codes:
            geomagia_code='2'
        elif "DA-AC-ATRM" in codes:
            geomagia_code='3'
        elif "LT-NRM-PAR" in codes:
            geomagia_code='4'
        elif "DA-AC-AIRM" in codes:
            geomagia_code='6'
        elif "DA-AC" in codes:  #at end to fill generic if others don't exist
            geomagia_code='5'

    if geomagia=='cooling_rate':
        if  "DA-CR" in codes:  #all current CR codes but CR-EG are a 1 but may change in the future
            geomagia_code='1'
        if "DA-CR-EG" in codes:
            geomagia_code='2'

    if geomagia=='dm_methods':
        if  "LP-DIR-AF" in codes:
            geomagia_code='1'
        elif "LT-AF-D" in codes:
            geomagia_code='1'
        elif "LT-AF-G" in codes:
            geomagia_code='1'
        elif "LT-AF-Z" in codes:
            geomagia_code='1'
        elif "LP-DIR-T" in codes:
            geomagia_code='2'
        elif "LT-AF-Z" in codes:
            geomagia_code='2'
        elif "LP-DIR-M" in codes:
            geomagia_code='5'
        elif "LT-M-Z" in codes:
            geomagia_code='5'

    if geomagia=='dm_analysis':
        if  "DE-BFL" in codes:
            geomagia_code='1'
        elif "DE-BLANKET" in codes:
            geomagia_code='2'
        elif "DE-FM" in codes:
            geomagia_code='3'
        elif "DE-NRM" in codes:
            geomagia_code='6'

    if geomagia=='specimen_type_id':
        if  "SC-TYPE-CYC" in codes:
            geomagia_code='1'
        elif  "SC-TYPE-CUBE" in codes:
            geomagia_code='2'
        elif  "SC-TYPE-MINI" in codes:
            geomagia_code='3'
        elif  "SC-TYPE-SC" in codes:
            geomagia_code='4'
        elif  "SC-TYPE-UC" in codes:
            geomagia_code='5'
        elif  "SC-TYPE-LARGE" in codes:
            geomagia_code='6'

    return geomagia_code

Response: Converts a list of MagIC method codes to a list of GEOMAGIA codes.


Instruction:
Write a Python 3 script for
naming microwave_magic.py DESCRIPTION plots microwave paleointensity data, allowing interactive setting of bounds. Saves and reads interpretations from a pmag_specimen formatted table, default: microwave_specimens.txt SYNTAX microwave_magic.py [command line options] OPTIONS -h prints help message and quits -f MEAS, set magic_measurements input file -fsp PRIOR, set pmag_specimen prior interpretations file -fcr CRIT, set criteria file for grading. -fmt [svg,png,jpg], format for images - default is svg -sav, saves plots with out review (default format) -spc SPEC, plots single specimen SPEC, saves plot with specified format with optional -b bounds adn quits -b BEG END: sets bounds for calculation BEG: starting step for slope calculation END: ending step for slope calculation DEFAULTS MEAS: magic_measurements.txt CRIT: NONE PRIOR: microwave_specimens.txt OUTPUT figures: ALL: numbers refer to temperature steps in command line window 1) Arai plot: closed circles are zero-field first/infield open circles are infield first/zero-field triangles are pTRM checks squares are pTRM tail checks VDS is vector difference sum diamonds are bounds for interpretation 2) Zijderveld plot: closed (open) symbols are X-Y (X-Z) planes X rotated to NRM direction 3) (De/Re)Magnetization diagram: circles are NRM remaining squares are pTRM gained command line window: list is: temperature step numbers, power (J), Dec, Inc, Int (units of magic_measuements) list of possible commands: type letter followed by return to select option saving of plots creates .svg format files with specimen_name, plot type as name

Response:
def main():
    """
    NAME
        microwave_magic.py

    DESCRIPTION
        plots microwave paleointensity data, allowing interactive setting of bounds.
        Saves and reads interpretations
        from a pmag_specimen formatted table, default: microwave_specimens.txt

    SYNTAX
        microwave_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f MEAS, set magic_measurements input file
        -fsp PRIOR, set pmag_specimen prior interpretations file
        -fcr CRIT, set criteria file for grading.
        -fmt [svg,png,jpg], format for images - default is svg
        -sav,  saves plots with out review (default format)
        -spc SPEC, plots single specimen SPEC, saves plot with specified format
            with optional -b bounds adn quits
        -b BEG END: sets  bounds for calculation
           BEG: starting step for slope calculation
           END: ending step for slope calculation

    DEFAULTS
        MEAS: magic_measurements.txt
        CRIT: NONE
        PRIOR: microwave_specimens.txt

    OUTPUT
        figures:
            ALL:  numbers refer to temperature steps in command line window
            1) Arai plot:  closed circles are zero-field first/infield
                           open circles are infield first/zero-field
                           triangles are pTRM checks
                           squares are pTRM tail checks
                           VDS is vector difference sum
                           diamonds are bounds for interpretation
            2) Zijderveld plot:  closed (open) symbols are X-Y (X-Z) planes
                                 X rotated to NRM direction
            3) (De/Re)Magnetization diagram:
                           circles are NRM remaining
                           squares are pTRM gained
        command line window:
            list is: temperature step numbers, power (J), Dec, Inc, Int (units of magic_measuements)
                     list of possible commands: type letter followed by return to select option
                     saving of plots creates .svg format files with specimen_name, plot type as name
    """
#
#   initializations
#
    meas_file,critout,inspec="magic_measurements.txt","","microwave_specimens.txt"
    inlt=0
    version_num=pmag.get_version()
    Tinit,DCZ,field,first_save=0,0,-1,1
    user,comment="",''
    ans,specimen,recnum,start,end=0,0,0,0,0
    plots,pmag_out,samp_file,style=0,"","","svg"
    fmt='.'+style
#
# default acceptance criteria
#
    accept_keys=['specimen_int_ptrm_n','specimen_md','specimen_fvds','specimen_b_beta','specimen_dang','specimen_drats','specimen_Z']
    accept={}
    accept['specimen_int_ptrm_n']=2
    accept['specimen_md']=10
    accept['specimen_fvds']=0.35
    accept['specimen_b_beta']=.1
    accept['specimen_int_mad']=7
    accept['specimen_dang']=10
    accept['specimen_drats']=10
    accept['specimen_Z']=10
#
# parse command line options
#
    spc,BEG,END="","",""
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        meas_file=sys.argv[ind+1]
    if '-fsp' in sys.argv:
        ind=sys.argv.index('-fsp')
        inspec=sys.argv[ind+1]
    if '-fcr' in sys.argv:
        ind=sys.argv.index('-fcr')
        critout=sys.argv[ind+1]
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt='.'+sys.argv[ind+1]
    if '-spc' in sys.argv:
        ind=sys.argv.index('-spc')
        spc=sys.argv[ind+1]
        if '-b' in sys.argv:
            ind=sys.argv.index('-b')
            BEG=int(sys.argv[ind+1])
            END=int(sys.argv[ind+2])
    if critout!="":
        crit_data,file_type=pmag.magic_read(critout)
        if pmagplotlib.verbose:
            print("Acceptance criteria read in from ", critout)
        accept={}
        accept['specimen_int_ptrm_n']=2.0
        for critrec in crit_data:
            if critrec["pmag_criteria_code"]=="IE-SPEC":
                for key in accept_keys:
                    if key not in list(critrec.keys()):
                        accept[key]=-1
                    else:
                        accept[key]=float(critrec[key])
    try:
        open(inspec,'r')
        PriorRecs,file_type=pmag.magic_read(inspec)
        if file_type != 'pmag_specimens':
            print(file_type)
            print(file_type,inspec," is not a valid pmag_specimens file ")
            sys.exit()
        for rec in PriorRecs:
            if 'magic_software_packages' not in list(rec.keys()):rec['magic_software_packages']=""
    except IOError:
        PriorRecs=[]
        if pmagplotlib.verbose:print("starting new specimen interpretation file: ",inspec)
    meas_data,file_type=pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print(file_type)
        print(file_type,"This is not a valid magic_measurements file ")
        sys.exit()
    backup=0
    # define figure numbers for arai, zijderveld and
    #   de-,re-magization diagrams
    AZD={}
    AZD['deremag'], AZD['zijd'],AZD['arai'],AZD['eqarea']=1,2,3,4
    pmagplotlib.plot_init(AZD['arai'],4,4)
    pmagplotlib.plot_init(AZD['zijd'],4,4)
    pmagplotlib.plot_init(AZD['deremag'],4,4)
    pmagplotlib.plot_init(AZD['eqarea'],4,4)
    #
    #
    #
    # get list of unique specimen names
    #
    CurrRec=[]
    sids=pmag.get_specs(meas_data)
    # get plots for specimen s - default is just to step through arai diagrams
    #
    if spc!="": specimen =sids.index(spc)
    while specimen < len(sids):
        methcodes=[]
        if pmagplotlib.verbose and spc!="":
            print(sids[specimen],specimen+1, 'of ', len(sids))
        MeasRecs=[]
        s=sids[specimen]
        datablock,trmblock=[],[]
        PmagSpecRec={}
        PmagSpecRec["er_analyst_mail_names"]=user
        PmagSpecRec["specimen_correction"]='u'
    #
    # find the data from the meas_data file for this specimen
    #
        for rec in meas_data:
            if rec["er_specimen_name"]==s:
                MeasRecs.append(rec)
                methods=rec["magic_method_codes"].split(":")
                meths=[]
                for meth in methods:
                    meths.append(meth.strip()) # take off annoying spaces
                methods=""
                for meth in meths:
                    if meth.strip() not in methcodes and "LP-" in meth:methcodes.append(meth.strip())
                    methods=methods+meth+":"
                methods=methods[:-1]
                rec["magic_method_codes"]=methods
                if "LP-PI-M" in meths: datablock.append(rec)
                if "LP-MRM" in meths: trmblock.append(rec)
        if len(trmblock)>2 and inspec!="":
            if Tinit==0:
                Tinit=1
                AZD['MRM']=4
                pmagplotlib.plot_init(AZD['MRM'],4,4)
            elif Tinit==1:
                pmagplotlib.clearFIG(AZD['MRM'])
        if len(datablock) <4:
           if backup==0:
               specimen+=1
               if pmagplotlib.verbose:
                   print('skipping specimen - moving forward ', s)
           else:
               specimen-=1
               if pmagplotlib.verbose:
                   print('skipping specimen - moving backward ', s)
    #
    #  collect info for the PmagSpecRec dictionary
    #
        else:
           rec=datablock[0]
           PmagSpecRec["er_citation_names"]="This study"
           PmagSpecRec["er_specimen_name"]=s
           PmagSpecRec["er_sample_name"]=rec["er_sample_name"]
           PmagSpecRec["er_site_name"]=rec["er_site_name"]
           PmagSpecRec["er_location_name"]=rec["er_location_name"]
           if "magic_instrument_codes" not in list(rec.keys()):rec["magic_instrument_codes"]=""
           PmagSpecRec["magic_instrument_codes"]=rec["magic_instrument_codes"]
           PmagSpecRec["measurement_step_unit"]="J"
           if "magic_experiment_name" not in list(rec.keys()):
               rec["magic_experiment_name"]=""
           else:
               PmagSpecRec["magic_experiment_names"]=rec["magic_experiment_name"]

           meths=rec["magic_method_codes"].split(':')
       # sort data into types
           if "LP-PI-M-D" in meths: # this is a double heating experiment
               exp_type="LP-PI-M-D"
           elif "LP-PI-M-S" in meths:
               exp_type="LP-PI-M-S"
           else:
               print("experiment type not supported yet ")
               break
           araiblock,field=pmag.sortmwarai(datablock,exp_type)
           first_Z=araiblock[0]
           first_I=araiblock[1]
           GammaChecks=araiblock[-3]
           ThetaChecks=araiblock[-2]
           DeltaChecks=araiblock[-1]
           if len(first_Z)<3:
               if backup==0:
                   specimen+=1
                   if pmagplotlib.verbose:
                       print('skipping specimen - moving forward ', s)
               else:
                   specimen-=1
                   if pmagplotlib.verbose:
                       print('skipping specimen - moving backward ', s)
           else:
               backup=0
               zijdblock,units=pmag.find_dmag_rec(s,meas_data)
               if exp_type=="LP-PI-M-D":
                   recnum=0
                   print("ZStep Watts  Dec Inc  Int")
                   for plotrec in zijdblock:
                       if pmagplotlib.verbose:
                           print('%i  %i %7.1f %7.1f %8.3e ' % (recnum,plotrec[0],plotrec[1],plotrec[2],plotrec[3]))
                           recnum += 1
                   recnum = 1
                   if GammaChecks!="":
                       print("IStep Watts  Gamma")
                       for gamma in GammaChecks:
                           if pmagplotlib.verbose: print('%i %i %7.1f ' % (recnum, gamma[0],gamma[1]))
                           recnum += 1
               if exp_type=="LP-PI-M-S":
                   if pmagplotlib.verbose:
                       print("IStep Watts  Theta")
                       kk=0
                       for theta in ThetaChecks:
                           kk+=1
                           print('%i  %i %7.1f ' % (kk,theta[0],theta[1]))
                   if pmagplotlib.verbose:
                       print("Watts  Delta")
                       for delta in DeltaChecks:
                           print('%i %7.1f ' % (delta[0],delta[1]))
               pmagplotlib.plot_arai_zij(AZD,araiblock,zijdblock,s,units[0])
               if inspec !="":
                   if pmagplotlib.verbose: print('Looking up saved interpretation....')
                   found = 0
                   for k in range(len(PriorRecs)):
                       try:
                         if PriorRecs[k]["er_specimen_name"]==s:
                           found =1
                           CurrRec.append(PriorRecs[k])
                           for j in range(len(araiblock[0])):
                               if float(araiblock[0][j][0])==float(PriorRecs[k]["measurement_step_min"]):start=j
                               if float(araiblock[0][j][0])==float(PriorRecs[k]["measurement_step_max"]):end=j
                           pars,errcode=pmag.PintPars(araiblock,zijdblock,start,end)
                           pars['measurement_step_unit']="J"
                           del PriorRecs[k]  # put in CurrRec, take out of PriorRecs
                           if errcode!=1:
                               pars["specimen_lab_field_dc"]=field
                               pars["specimen_int"]=-1*field*pars["specimen_b"]
                               pars["er_specimen_name"]=s
                               if pmagplotlib.verbose:
                                   print('Saved interpretation: ')
                               pars=pmag.scoreit(pars,PmagSpecRec,accept,'',0)
                               pmagplotlib.plot_b(AZD,araiblock,zijdblock,pars)
                               if len(trmblock)>2:
                                   blab=field
                                   best=pars["specimen_int"]
                                   Bs,TRMs=[],[]
                                   for trec in trmblock:
                                       Bs.append(float(trec['treatment_dc_field']))
                                       TRMs.append(float(trec['measurement_magn_moment']))
                                   NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc
                                   Mp,Bp=[],[]
                                   for k in  range(int(max(Bs)*1e6)):
                                       Bp.append(float(k)*1e-6)
                                       npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field
                                       Mp.append(npred)
                                   pmagplotlib.plot_trm(AZD['MRM'],Bs,TRMs,Bp,Mp,NLpars,trec['magic_experiment_name'])
                                   print(npred)
                                   print('Banc= ',float(NLpars['banc'])*1e6)
                                   if pmagplotlib.verbose:
                                       print('Banc= ',float(NLpars['banc'])*1e6)
                                   pmagplotlib.draw_figs(AZD)
                           else:
                               print('error on specimen ',s)
                       except:
                         pass
                   if pmagplotlib.verbose and found==0: print('    None found :(  ')
               if spc!="":
                   if BEG!="":
                       pars,errcode=pmag.PintPars(araiblock,zijdblock,BEG,END)
                       pars['measurement_step_unit']="J"
                       pars["specimen_lab_field_dc"]=field
                       pars["specimen_int"]=-1*field*pars["specimen_b"]
                       pars["er_specimen_name"]=s
                       pars['specimen_grade']='' # ungraded
                       pmagplotlib.plot_b(AZD,araiblock,zijdblock,pars)
                       if len(trmblock)>2:
                           if inlt==0:
                               donlt()
                               inlt=1
                           blab=field
                           best=pars["specimen_int"]
                           Bs,TRMs=[],[]
                           for trec in trmblock:
                               Bs.append(float(trec['treatment_dc_field']))
                               TRMs.append(float(trec['measurement_magn_moment']))
                           NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc
    #
                           Mp,Bp=[],[]
                           for k in  range(int(max(Bs)*1e6)):
                               Bp.append(float(k)*1e-6)
                               npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field
                   files={}
                   for key in list(AZD.keys()):
                       files[key]=s+'_'+key+fmt
                   pmagplotlib.save_plots(AZD,files)
                   sys.exit()
               if plots==0:
                   ans='b'
                   while ans != "":
                       print("""
               s[a]ve plot, set [b]ounds for calculation, [d]elete current interpretation, [p]revious, [s]ample, [q]uit:
               """)
                       ans=input('Return for next specimen \n')
                       if ans=="":
                           specimen +=1
                       if ans=="d":
                           save_redo(PriorRecs,inspec)
                           CurrRec=[]
                           pmagplotlib.plot_arai_zij(AZD,araiblock,zijdblock,s,units[0])
                           pmagplotlib.draw_figs(AZD)
                       if ans=='a':
                           files={}
                           for key in list(AZD.keys()):
                               files[key]=s+'_'+key+fmt
                           pmagplotlib.save_plots(AZD,files)
                           ans=""
                       if ans=='q':
                           print("Good bye")
                           sys.exit()
                       if ans=='p':
                           specimen =specimen -1
                           backup = 1
                           ans=""
                       if ans=='s':
                           keepon=1
                           spec=input('Enter desired specimen name (or first part there of): ')
                           while keepon==1:
                               try:
                                   specimen =sids.index(spec)
                                   keepon=0
                               except:
                                   tmplist=[]
                                   for qq in range(len(sids)):
                                       if spec in sids[qq]:tmplist.append(sids[qq])
                                   print(specimen," not found, but this was: ")
                                   print(tmplist)
                                   spec=input('Select one or try again\n ')
                           ans=""
                       if  ans=='b':
                           if end==0 or end >=len(araiblock[0]):end=len(araiblock[0])-1
                           GoOn=0
                           while GoOn==0:
                               print('Enter index of first point for calculation: ','[',start,']')
                               answer=input('return to keep default  ')
                               if answer != "":start=int(answer)
                               print('Enter index  of last point for calculation: ','[',end,']')
                               answer=input('return to keep default  ')
                               if answer != "":
                                   end=int(answer)
                               if start >=0 and start <len(araiblock[0])-2 and end >0 and end <len(araiblock[0]) and start<end:
                                   GoOn=1
                               else:
                                   print("Bad endpoints - try again! ")
                                   start,end=0,len(araiblock)
                           s=sids[specimen]
                           pars,errcode=pmag.PintPars(araiblock,zijdblock,start,end)
                           pars['measurement_step_unit']="J"
                           pars["specimen_lab_field_dc"]=field
                           pars["specimen_int"]=-1*field*pars["specimen_b"]
                           pars["er_specimen_name"]=s
                           pars=pmag.scoreit(pars,PmagSpecRec,accept,'',0)
                           PmagSpecRec["measurement_step_min"]='%8.3e' % (pars["measurement_step_min"])
                           PmagSpecRec["measurement_step_max"]='%8.3e' % (pars["measurement_step_max"])
                           PmagSpecRec["measurement_step_unit"]="J"
                           PmagSpecRec["specimen_int_n"]='%i'%(pars["specimen_int_n"])
                           PmagSpecRec["specimen_lab_field_dc"]='%8.3e'%(pars["specimen_lab_field_dc"])
                           PmagSpecRec["specimen_int"]='%8.3e '%(pars["specimen_int"])
                           PmagSpecRec["specimen_b"]='%5.3f '%(pars["specimen_b"])
                           PmagSpecRec["specimen_q"]='%5.1f '%(pars["specimen_q"])
                           PmagSpecRec["specimen_f"]='%5.3f '%(pars["specimen_f"])
                           PmagSpecRec["specimen_fvds"]='%5.3f'%(pars["specimen_fvds"])
                           PmagSpecRec["specimen_b_beta"]='%5.3f'%(pars["specimen_b_beta"])
                           PmagSpecRec["specimen_int_mad"]='%7.1f'%(pars["specimen_int_mad"])
                           PmagSpecRec["specimen_Z"]='%7.1f'%(pars["specimen_Z"])
                           if pars["method_codes"]!="":
                               tmpcodes=pars["method_codes"].split(":")
                               for t in tmpcodes:
                                   if t.strip() not in methcodes:methcodes.append(t.strip())
                           PmagSpecRec["specimen_dec"]='%7.1f'%(pars["specimen_dec"])
                           PmagSpecRec["specimen_inc"]='%7.1f'%(pars["specimen_inc"])
                           PmagSpecRec["specimen_tilt_correction"]='-1'
                           PmagSpecRec["specimen_direction_type"]='l'
                           PmagSpecRec["direction_type"]='l' # this is redudant, but helpful - won't be imported
                           PmagSpecRec["specimen_dang"]='%7.1f '%(pars["specimen_dang"])
                           PmagSpecRec["specimen_drats"]='%7.1f '%(pars["specimen_drats"])
                           PmagSpecRec["specimen_int_ptrm_n"]='%i '%(pars["specimen_int_ptrm_n"])
                           PmagSpecRec["specimen_rsc"]='%6.4f '%(pars["specimen_rsc"])
                           PmagSpecRec["specimen_md"]='%i '%(int(pars["specimen_md"]))
                           if PmagSpecRec["specimen_md"]=='-1':PmagSpecRec["specimen_md"]=""
                           PmagSpecRec["specimen_b_sigma"]='%5.3f '%(pars["specimen_b_sigma"])
                           if "IE-TT" not in  methcodes:methcodes.append("IE-TT")
                           methods=""
                           for meth in methcodes:
                               methods=methods+meth+":"
                           PmagSpecRec["magic_method_codes"]=methods[:-1]
                           PmagSpecRec["specimen_description"]=comment
                           PmagSpecRec["magic_software_packages"]=version_num
                           pmagplotlib.plot_arai_zij(AZD,araiblock,zijdblock,s,units[0])
                           pmagplotlib.plot_b(AZD,araiblock,zijdblock,pars)
                           if len(trmblock)>2:
                               blab=field
                               best=pars["specimen_int"]
                               Bs,TRMs=[],[]
                               for trec in trmblock:
                                   Bs.append(float(trec['treatment_dc_field']))
                                   TRMs.append(float(trec['measurement_magn_moment']))
                               NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc
                               Mp,Bp=[],[]
                               for k in  range(int(max(Bs)*1e6)):
                                   Bp.append(float(k)*1e-6)
                                   npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field
                                   Mp.append(npred)
                               pmagplotlib.plot_trm(AZD['MRM'],Bs,TRMs,Bp,Mp,NLpars,trec['magic_experiment_name'])
                               print('Banc= ',float(NLpars['banc'])*1e6)
                           pmagplotlib.draw_figs(AZD)
                           pars["specimen_lab_field_dc"]=field
                           pars["specimen_int"]=-1*field*pars["specimen_b"]
                           saveit=input("Save this interpretation? [y]/n \n")
                           if saveit!='n':
                               specimen+=1
                               PriorRecs.append(PmagSpecRec) # put back an interpretation
                               save_redo(PriorRecs,inspec)
                           ans=""
               else:
                   specimen+=1
                   if fmt != ".pmag":
                       basename=s+'_microwave'+fmt
                       files={}
                       for key in list(AZD.keys()):
                           files[key]=s+'_'+key+fmt
                       if pmagplotlib.isServer:
                           black     = '#000000'
                           purple    = '#800080'
                           titles={}
                           titles['deremag']='DeReMag Plot'
                           titles['zijd']='Zijderveld Plot'
                           titles['arai']='Arai Plot'
                           AZD = pmagplotlib.add_borders(AZD,titles,black,purple)
                       pmagplotlib.save_plots(AZD,files)
    #                   pmagplotlib.combineFigs(s,files,3)
        if len(CurrRec)>0:
            for rec in CurrRec:
                PriorRecs.append(rec)
        CurrRec=[]
    if plots!=1:
        ans=input(" Save last plot? 1/[0] ")
        if ans=="1":
            if fmt != ".pmag":
                files={}
                for key in list(AZD.keys()):
                    files[key]=s+'_'+key+fmt
                pmagplotlib.save_plots(AZD,files)
        if len(CurrRec)>0:PriorRecs.append(CurrRec) # put back an interpretation
        if len(PriorRecs)>0:
            save_redo(PriorRecs,inspec)
            print('Updated interpretations saved in ',inspec)
    if pmagplotlib.verbose:
        print("Good bye")


Instruction:
Given the following Python 3 function, write the documentation
def main():
# initialize some stuff
    noave=0
    methcode,inst="",""
    phi,theta,peakfield,labfield=0,0,0,0
    dec=[315,225,180,135,45,90,270,270,270,90,180,180,0,0,0]
    inc=[0,0,0,0,0,-45,-45,0,45,45,45,-45,-90,-45,45]
    missing=1
    demag="N"
    er_location_name=""
    citation='This study'
    args=sys.argv
    methcode="LP-NO"
    trm=0
    irm=0
    dc="0"
    dir_path='.'
#
# get command line arguments
#
    meas_file="magic_measurements.txt"
    user=""
    if "-WD" in args:
        ind=args.index("-WD")
        dir_path=args[ind+1]
    samp_file=dir_path+'/'+'er_samples.txt'
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    if '-F' in args:
        ind=args.index("-F")
        meas_file=args[ind+1]
    if '-f' in args:
        ind=args.index("-f")
        mag_file=dir_path+'/'+args[ind+1]
        try:
            input=open(mag_file,'r')
        except:
            print("bad mag file name")
            sys.exit()
    else:
        print("spn_file field is required option")
        print(main.__doc__)
        sys.exit()
    vol=10.5e-6 # default for spinner program
    if "-V" in args:
        ind=args.index("-V")
        vol=float(args[ind+1])*1e-6 # convert volume to m^3
    if "-A" in args: noave=1
    if '-LP' in args:
        ind=args.index("-LP")
        codelist=args[ind+1]
        codes=codelist.split(':')
        if "AF" in codes:
            demag='AF'
            methcode="LT-AF-Z"
        if "T" in codes:
            demag="T"
            methcode="LT-T-Z"
        if "I" in codes:
            methcode="LP-IRM"
        if "A" in codes:
            methcode="LT-AF-I"
            dc='%10.3e'%(1e-3*float(args[ind+1]))
    MagRecs=[]
    version_num=pmag.get_version()
    meas_file=dir_path+'/'+meas_file
    for line in input.readlines():
        instcode="ODP-MSPN"
        rec=line.split()
        if len(rec)>2 and "Leg" not in line:
            MagRec={}
            MagRec['er_expedition_name']=rec[0]
            MagRec['er_location_name']=rec[1]+rec[2]
            MagRec["er_specimen_name"]=rec[0]+'-'+'U'+rec[1]+rec[2].upper()+"-"+rec[3]+rec[4].upper()+'-'+rec[5]+'-'+'W'+'-'+rec[6]
            MagRec["er_site_name"]=MagRec['er_specimen_name']
            MagRec["er_sample_name"]=MagRec['er_specimen_name']
            MagRec['magic_software_packages']=version_num
            MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
            MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
            MagRec["treatment_ac_field"]='0'
            MagRec["treatment_dc_field"]=dc
            MagRec["treatment_dc_field_phi"]='0'
            MagRec["treatment_dc_field_theta"]='0'
            meas_type="LT-NO"
            if float(rec[11])==0:
                pass
            elif demag=="AF":
                MagRec["treatment_ac_field"]='%8.3e' %(float(rec[11])*1e-3) # peak field in tesla
                meas_type="LT-AF-Z"
                MagRec["treatment_dc_field"]='0'
            else:
              MagRec["treatment_temp"]='%8.3e' % (float(rec[11])+273.) # temp in kelvin
              meas_type="LT-T-Z"
            intens=1e-3*float(rec[10])*vol # convert mA/m to Am^2
            MagRec["measurement_magn_moment"]='%10.3e'% (intens)
            MagRec["measurement_dec"]=rec[8]
            MagRec["measurement_inc"]=rec[9]
            MagRec["magic_instrument_codes"]="ODP-MSPN"
            MagRec["er_analyst_mail_names"]=user
            MagRec["er_citation_names"]=citation
            MagRec["magic_method_codes"]=meas_type
            MagRec["measurement_flag"]='g'
            MagRec["measurement_csd"]=''
            MagRec["measurement_number"]='1'
            MagRecs.append(MagRec)
    MagOuts=pmag.measurements_methods(MagRecs,noave)
    pmag.magic_write(meas_file,MagOuts,'magic_measurements')
    print("results put in ",meas_file)

Response: This function is the main entry point for the ODP s Molspin s. spn format files.


Instruction:
How would you explain what the following Python 3 function does
def convert(**kwargs):

    #get parameters from kwargs.get(parameter_name, default_value)
    user = kwargs.get('user', '')
    magfile = kwargs.get('magfile')

    #do any extra formating you need to variables here

    #open magfile to start reading data
    try:
        infile=open(magfile,'r')
    except Exception as ex:
        print(("bad file path: ", magfile))
        return False, "bad file path"

    #Depending on the dataset you may need to read in all data here put it in a list of dictionaries or something here. If you do just replace the "for line in infile.readlines():" bellow with "for d in data:" where data is the structure you put your data into

    #define the lists that hold each line of data for their respective tables
    SpecRecs,SampRecs,SiteRecs,LocRecs,MeasRecs=[],[],[],[],[]

    #itterate over the contence of the file
    for line in infile.readlines():
        MeasRec,SpecRec,SampRec,SiteRec,LocRec={},{},{},{},{}

        #extract data from line and put it in variables

        #fill this line of the Specimen table using above variables
        if specimen!="" and specimen not in [x['specimen'] if 'specimen' in list(x.keys()) else "" for x in SpecRecs]:
            SpecRec['analysts']=user
            SpecRecs.append(SpecRec)
        #fill this line of the Sample table using above variables
        if sample!="" and sample not in [x['sample'] if 'sample' in list(x.keys()) else "" for x in SampRecs]:
            SampRec['analysts']=user
            SampRecs.append(SampRec)
        #fill this line of the Site table using above variables
        if site!="" and site not in [x['site'] if 'site' in list(x.keys()) else "" for x in SiteRecs]:
            SiteRec['analysts']=user
            SiteRecs.append(SiteRec)
        #fill this line of the Location table using above variables
        if location!="" and location not in [x['location'] if 'location' in list(x.keys()) else "" for x in LocRecs]:
            LocRec['analysts']=user
            LocRecs.append(LocRec)

        #Fill this line of Meas Table using data in line
        MeasRec['analysts']=user
        MeasRecs.append(MeasRec)

    #close your file object so Python3 doesn't throw an annoying warning
    infile.close()

    #open a Contribution object
    con = cb.Contribution(output_dir_path,read_tables=[])

    #Create Magic Tables and add to a contribution
    con.add_magic_table_from_data(dtype='specimens', data=SpecRecs)
    con.add_magic_table_from_data(dtype='samples', data=SampRecs)
    con.add_magic_table_from_data(dtype='sites', data=SiteRecs)
    con.add_magic_table_from_data(dtype='locations', data=LocRecs)
    MeasOuts=pmag.measurements_methods3(MeasRecs,noave) #figures out method codes for measuremet data
    con.add_magic_table_from_data(dtype='measurements', data=MeasOuts)

    #write to file
    con.write_table_to_file('specimens', custom_name=spec_file)
    con.write_table_to_file('samples', custom_name=samp_file)
    con.write_table_to_file('sites', custom_name=site_file)
    con.write_table_to_file('locations', custom_name=loc_file)
    meas_file = con.write_table_to_file('measurements', custom_name=meas_file)

    return True, meas_file

Response: This function converts a single file into a single structure.


Instruction:
Can you tell what is the following Python 3 function doing
def main():
    inp,out="",""
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'r')
        inp=f.readlines()
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        o=sys.argv[ind+1]
        out=open(o,'w')
    if '-i' in sys.argv:
        cont=1
        while cont==1:
            try:
                b=1e-6*float(input('B (in microtesla): <cntl-D to quit '))
                lat=float(input('Latitude: '))
            except:
                print("\nGood bye\n")
                sys.exit()

            vdm= pmag.b_vdm(b,lat)
            print('%10.3e '%(vdm))
    if inp=="":
        inp = sys.stdin.readlines()  # read from standard input
    for line in inp:
        vdm=spitout(line)
        if out=="":
            print('%10.3e'%(vdm))
        else:
            out.write('%10.3e \n'%(vdm))

Response:
NAME b_vdm. py

 getTerminalEntry. py


Instruction:
Write a Python 3 script for
walking through data_files and list all in dict format

Response:
def do_walk(data_path):
    """
    Walk through data_files and list all in dict format
    """
    data_files = {}
    def cond(File, prefix):
        """
        Return True for useful files
        Return False for non-useful files
        """
        file_path = path.join(prefix, 'data_files', File)
        return (not File.startswith('!') and
                not File.endswith('~') and
                not File.endswith('#') and
                not File.endswith('.pyc') and
                not File.startswith('.') and
                path.exists(path.join(prefix, File)))

    for (dir_path, dirs, files) in os.walk(data_path):
        data_files[dir_path] = [f for f in files if cond(f, dir_path)]
        if not dirs:
            continue
        else:
            for Dir in dirs:
                do_walk(os.path.join(dir_path, Dir))
    return data_files


Instruction:
Can you tell what is the following Python 3 function doing
def main():
    dir_path="./"
    change='l'
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        magic_file=dir_path+'/'+sys.argv[ind+1]
    else:
        print(main.__doc__)
        sys.exit()
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        out_file=dir_path+'/'+sys.argv[ind+1]
    else: out_file=magic_file
    if '-keys' in sys.argv:
        ind=sys.argv.index('-keys')
        grab_keys=sys.argv[ind+1].split(":")
    else:
        print(main.__doc__)
        sys.exit()
    if '-U' in sys.argv: change='U'
    #
    #
    # get data read in
    Data,file_type=pmag.magic_read(magic_file)
    if len(Data)>0:
      for grab_key in grab_keys:
        for rec in Data:
            if change=='l':
                rec[grab_key]=rec[grab_key].lower()
            else:
                rec[grab_key]=rec[grab_key].upper()
    else:
        print('bad file name')
    pmag.magic_write(out_file,Data,file_type)

Response:
NAME
        change_case_magic.py

    DESCRIPTION
        picks out key and converts to upper or lower case

    SYNTAX
        change_case_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file
        -F FILE: specify output magic format file , default is to overwrite input file
        -keys KEY1:KEY2 specify colon delimited list of keys to convert
        -[U,l] : specify [U]PPER or [l]ower case, default is lower