Instruction:
Make a summary of the following Python 3 code
def iodp_srm(csv_file="", dir_path=".", input_dir_path="",
             meas_file="measurements.txt", spec_file="specimens.txt",
             samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt",
             lat="", lon="", noave=0):

    """
    Converts IODP LIMS and LORE SRM archive half sample format files
    to measurements format files.

    Parameters
    ----------
    csv_file : str
        input csv file, default ""
        if no file name is provided, find any .csv files in the provided dir_path
    dir_path : str
        working directory, default "."
    input_dir_path : str
        input file directory IF different from dir_path, default ""
    meas_file : str
        output measurement file name, default "measurements.txt"
    spec_file : str
        output specimen file name, default "specimens.txt"
    samp_file: str
        output sample file name, default "samples.txt"
    site_file : str
        output site file name, default "sites.txt"
    loc_file : str
        output location file name, default "locations.txt"
    lat : float
        latitude, default ""
    lon : float
        longitude, default ""
    noave : bool
       do not average duplicate measurements, default False (so by default, DO average)

    Returns
    --------
    type - Tuple : (True or False indicating if conversion was sucessful, meas_file name written)

    """

    # helper function

    def pad_year(date, ind, warn=False, fname=''):
        """
        Parameters
        ----------
        Date: str
            date as colon-delimited string, i.e. 04:10:2015:06:45:00
        ind: int
            index of year position
        warn : bool (default False)
            verbose or not
        fname: str (default '')
            filename for more informative warning

        Returns
        ---------
        new_date: str
           date as colon-delimited,
           with year padded if it wasn't before
        """
        date_list = date.split(':')
        year = date_list[ind]
        if len(year) == 2:
            padded_year = '20' + year
            date_list[ind] = padded_year
            if warn:
                print('-W- Ambiguous year "{}" in {}.'.format(year, fname))
                print('    Assuming {}.'.format(padded_year))
        new_date = ':'.join(date_list)
        if new_date != date and warn:
            print('    Date translated to {}'.format(new_date))
        return new_date

    # initialize defaults
    version_num = pmag.get_version()
    citations = "This study"
    demag = 'NRM'
    depth_method = 'a'
    # format variables
    input_dir_path, output_dir_path = pmag.fix_directories(input_dir_path, dir_path)
    if csv_file == "":
        # read in list of files to import
        filelist = os.listdir(input_dir_path)
    else:
        filelist = [csv_file]

    # parsing the data
    MeasRecs, SpecRecs, SampRecs, SiteRecs, LocRecs = [], [], [], [], []
    file_found = False
    for f in filelist:  # parse each file
        year_warning = True
        if f[-3:].lower() == 'csv':
            print('processing:', f)
            file_found = True
            # get correct full filename and read data
            fname = pmag.resolve_file_name(f, input_dir_path)
            full_file = open(fname)
            file_input = full_file.readlines()
            full_file.close()
            keys = file_input[0].replace('\n', '').split(
                ',')  # splits on underscores
            keys = [k.strip('"') for k in keys]
            if "Interval Top (cm) on SHLF" in keys:
                interval_key = "Interval Top (cm) on SHLF"
            elif " Interval Bot (cm) on SECT" in keys:
                interval_key = " Interval Bot (cm) on SECT"
            elif "Offset (cm)" in keys:
                interval_key = "Offset (cm)"
            else:
                print("couldn't find interval or offset amount")
            # get depth key
            if "Top Depth (m)" in keys:
                depth_key = "Top Depth (m)"
            elif "CSF-A Top (m)" in keys:
                depth_key = "CSF-A Top (m)"
            elif "Depth CSF-A (m)" in keys:
                depth_key = "Depth CSF-A (m)"
            else:
                print("couldn't find depth")
            # get comp depth key
            if "CSF-B Top (m)" in keys:
                comp_depth_key = "CSF-B Top (m)"  # use this model if available
            elif "Depth CSF-B (m)" in keys:
                comp_depth_key = "Depth CSF-B (m)"
            else:
                comp_depth_key = ""
                print("couldn't find composite depth")
            if "Demag level (mT)" in keys:
                demag_key = "Demag level (mT)"
            elif "Demag Level (mT)" in keys:
                demag_key = "Demag Level (mT)"
            elif "Treatment Value" in keys:
                demag_key = "Treatment Value"
            else:
                print("couldn't find demag type")
            # Get inclination key
            if "Inclination (Tray- and Bkgrd-Corrected) (deg)" in keys:
                inc_key = "Inclination (Tray- and Bkgrd-Corrected) (deg)"
            elif "Inclination background + tray corrected  (deg)" in keys:
                inc_key = "Inclination background + tray corrected  (deg)"
            elif "Inclination background + tray corrected  (\xc2\xb0)" in keys:
                inc_key = "Inclination background + tray corrected  (\xc2\xb0)"
            elif "Inclination background & tray corrected (deg)" in keys:
                inc_key = "Inclination background & tray corrected (deg)"
            elif "Inclination background & tray corrected (deg)" in keys:
                inc_key = "Inclination background & tray corrected (deg)"
            elif "Inclination background & drift corrected (deg)" in keys:
                inc_key = "Inclination background & drift corrected (deg)"
            elif "Inclination background + tray corrected  (\N{DEGREE SIGN})" in keys:
                inc_key = "Inclination background + tray corrected  (\N{DEGREE SIGN})"
            else:
                print("couldn't find inclination")
            # get declination key
            if "Declination (Tray- and Bkgrd-Corrected) (deg)" in keys:
                dec_key = "Declination (Tray- and Bkgrd-Corrected) (deg)"
            elif "Declination background + tray corrected (\N{DEGREE SIGN})" in keys:
                dec_key = "Declination background + tray corrected (\N{DEGREE SIGN})"
            elif "Declination background + tray corrected (deg)" in keys:
                dec_key = "Declination background + tray corrected (deg)"
            elif "Declination background + tray corrected (\xc2\xb0)" in keys:
                dec_key = "Declination background + tray corrected (\xc2\xb0)"
            elif "Declination background & tray corrected (deg)" in keys:
                dec_key = "Declination background & tray corrected (deg)"
            elif "Declination background & tray corrected (deg)" in keys:
                dec_key = "Declination background & tray corrected (deg)"
            elif "Declination background & drift corrected (deg)" in keys:
                dec_key = "Declination background & drift corrected (deg)"
            else:
                print("couldn't find declination")
            if "Intensity (Tray- and Bkgrd-Corrected) (A/m)" in keys:
                int_key = "Intensity (Tray- and Bkgrd-Corrected) (A/m)"
            elif "Intensity background + tray corrected  (A/m)" in keys:
                int_key = "Intensity background + tray corrected  (A/m)"
            elif "Intensity background & tray corrected (A/m)" in keys:
                int_key = "Intensity background & tray corrected (A/m)"
            elif "Intensity background & tray corrected (A/m)" in keys:
                int_key = "Intensity background & tray corrected (A/m)"
            elif "Intensity background & drift corrected (A/m)" in keys:
                int_key = "Intensity background & drift corrected (A/m)"
            else:
                print("couldn't find magnetic moment")
            if "Core Type" in keys:
                core_type = "Core Type"
            elif "Type" in keys:
                core_type = "Type"
            else:
                print("couldn't find core type")
            if 'Run Number' in keys:
                run_number_key = 'Run Number'
            elif 'Test No.' in keys:
                run_number_key = 'Test No.'
            else:
                print("couldn't find run number")
            if 'Test Changed On' in keys:
                date_key = 'Test Changed On'
            elif "Timestamp (UTC)" in keys:
                date_key = "Timestamp (UTC)"
            else:
                print("couldn't find timestamp")
            if "Section" in keys:
                sect_key = "Section"
            elif "Sect" in keys:
                sect_key = "Sect"
            else:
                print("couldn't find section number")
            if 'Section Half' in keys:
                half_key = 'Section Half'
            elif "A/W" in keys:
                half_key = "A/W"
            else:
                print("couldn't find half number")
            if "Text ID" in keys:
                text_id = "Text ID"
            elif "Text Id" in keys:
                text_id = "Text Id"
            else:
                print("couldn't find ID number")
            for line in file_input[1:]:
                InRec = {}
                test = 0
                recs = line.split(',')
                for k in range(len(keys)):
                    if len(recs) == len(keys):
                        InRec[keys[k]] = line.split(',')[k].strip(""" " ' """)
                if 'Exp' in list(InRec.keys()) and InRec['Exp'] != "":
                    # get rid of pesky blank lines (why is this a thing?)
                    test = 1
                if not test:
                    continue
                run_number = ""
                inst = "IODP-SRM"
                volume = '15.59'  # set default volume to this
                if 'Sample Area (cm?)' in list(InRec.keys()) and InRec['Sample Area (cm?)'] != "":
                    volume = InRec['Sample Area (cm?)']
                MeasRec, SpecRec, SampRec, SiteRec, LocRec = {}, {}, {}, {}, {}
                expedition = InRec['Exp']
                location = InRec['Site']+InRec['Hole']
# Maintain backward compatibility for the ever-changing LIMS format (Argh!)
                while len(InRec['Core']) < 3:
                    InRec['Core'] = '0'+InRec['Core']
                # assume discrete sample
                if "Last Tray Measurment" in list(InRec.keys()) and "SHLF" not in InRec[text_id] or 'dscr' in csv_file:
                    specimen = expedition+'-'+location+'-' + \
                        InRec['Core']+InRec[core_type]+"-"+InRec[sect_key] + \
                        '-'+InRec[half_key]+'-'+str(InRec[interval_key])
                else:  # mark as continuous measurements
                    specimen = expedition+'-'+location+'-' + \
                        InRec['Core']+InRec[core_type]+"_"+InRec[sect_key] + \
                        InRec[half_key]+'-'+str(InRec[interval_key])
                sample = expedition+'-'+location + \
                    '-'+InRec['Core']+InRec[core_type]
                site = expedition+'-'+location

                if not InRec[dec_key] or not InRec[inc_key]:
                    print("No dec or inc found for specimen %s, skipping" % specimen)
                    continue

                if specimen != "" and specimen not in [x['specimen'] if 'specimen' in list(x.keys()) else "" for x in SpecRecs]:
                    SpecRec['specimen'] = specimen
                    SpecRec['sample'] = sample
                    SpecRec['citations'] = citations
                    SpecRec['volume'] = volume
                    SpecRec['specimen_alternatives'] = InRec[text_id]
                    SpecRecs.append(SpecRec)
                if sample != "" and sample not in [x['sample'] if 'sample' in list(x.keys()) else "" for x in SampRecs]:
                    SampRec['sample'] = sample
                    SampRec['site'] = site
                    SampRec['citations'] = citations
                    SampRec['azimuth'] = '0'
                    SampRec['dip'] = '0'
                    SampRec['core_depth'] = InRec[depth_key]
                    if comp_depth_key != '':
                        SampRec['composite_depth'] = InRec[comp_depth_key]
                        SiteRec['composite_depth'] = InRec[comp_depth_key]
                    if "SHLF" not in InRec[text_id]:
                        SampRec['method_codes'] = 'FS-C-DRILL-IODP:SP-SS-C:SO-V'
                    else:
                        SampRec['method_codes'] = 'FS-C-DRILL-IODP:SO-V'
                    SampRecs.append(SampRec)
                if site != "" and site not in [x['site'] if 'site' in list(x.keys()) else "" for x in SiteRecs]:
                    SiteRec['site'] = site
                    SiteRec['location'] = location
                    SiteRec['citations'] = citations
                    SiteRec['lat'] = lat
                    SiteRec['lon'] = lon
                    SiteRecs.append(SiteRec)
                    SiteRec['core_depth'] = InRec[depth_key]
                if location != "" and location not in [x['location'] if 'location' in list(x.keys()) else "" for x in LocRecs]:
                    LocRec['location'] = location
                    LocRec['citations'] = citations
                    LocRec['expedition_name'] = expedition
                    LocRec['lat_n'] = lat
                    LocRec['lon_e'] = lon
                    LocRec['lat_s'] = lat
                    LocRec['lon_w'] = lon
                    LocRecs.append(LocRec)

                MeasRec['specimen'] = specimen
                MeasRec['software_packages'] = version_num
                MeasRec["treat_temp"] = '%8.3e' % (273)  # room temp in kelvin
                MeasRec["meas_temp"] = '%8.3e' % (273)  # room temp in kelvin
                MeasRec["treat_ac_field"] = 0
                MeasRec["treat_dc_field"] = '0'
                MeasRec["treat_dc_field_phi"] = '0'
                MeasRec["treat_dc_field_theta"] = '0'
                MeasRec["quality"] = 'g'  # assume all data are "good"
                MeasRec["standard"] = 'u'  # assume all data are "good"
                if run_number_key in list(InRec.keys()) and InRec[run_number_key] != "":
                    run_number = InRec[run_number_key]
                # date time is second line of file
                datestamp = InRec[date_key].split()
                if '/' in datestamp[0]:
                    # break into month day year
                    mmddyy = datestamp[0].split('/')
                    if len(mmddyy[0]) == 1:
                        mmddyy[0] = '0'+mmddyy[0]  # make 2 characters
                    if len(mmddyy[1]) == 1:
                        mmddyy[1] = '0'+mmddyy[1]  # make 2 characters
                    if len(mmddyy[2]) == 1:
                        mmddyy[2] = '0'+mmddyy[2]  # make 2 characters
                    if len(datestamp[1]) == 1:
                        datestamp[1] = '0'+datestamp[1]  # make 2 characters
                    hour, minute = datestamp[1].split(':')
                    if len(hour) == 1:
                        hour = '0' + hour
                    date = mmddyy[0]+':'+mmddyy[1]+":" + \
                        mmddyy[2] + ':' + hour + ":" + minute + ":00"
                    #date=mmddyy[2] + ':'+mmddyy[0]+":"+mmddyy[1] +':' + hour + ":" + minute + ":00"
                if '-' in datestamp[0]:
                    # break into month day year
                    mmddyy = datestamp[0].split('-')
                    date = mmddyy[0]+':'+mmddyy[1]+":" + \
                        mmddyy[2] + ':' + datestamp[1]+":0"
                if len(date.split(":")) > 6:
                    date = date[:-2]
                # try with month:day:year
                try:
                    utc_dt = datetime.datetime.strptime(
                        date, "%m:%d:%Y:%H:%M:%S")
                except ValueError:
                    # try with year:month:day
                    try:
                        utc_dt = datetime.datetime.strptime(
                            date, "%Y:%m:%d:%H:%M:%S")
                    except ValueError:
                        # if all else fails, assume the year is in the third position
                        # and try padding with '20'
                        new_date = pad_year(
                            date, ind=2, warn=year_warning, fname=os.path.split(f)[1])
                        utc_dt = datetime.datetime.strptime(
                            new_date, "%m:%d:%Y:%H:%M:%S")
                        # only give warning once per csv file
                        year_warning = False
                MeasRec['timestamp'] = utc_dt.strftime("%Y-%m-%dT%H:%M:%S")+"Z"
                MeasRec["method_codes"] = 'LT-NO'
                if 'Treatment Type' in list(InRec.keys()) and InRec['Treatment Type'] != "":
                    if "AF" in InRec['Treatment Type'].upper():
                        MeasRec['method_codes'] = 'LT-AF-Z'
                        inst = inst+':IODP-SRM-AF'  # measured on shipboard in-line 2G AF
                        treatment_value = float(
                            InRec[demag_key].strip('"'))*1e-3  # convert mT => T
                        # AF demag in treat mT => T
                        MeasRec["treat_ac_field"] = treatment_value
                    elif "T" in InRec['Treatment Type'].upper():
                        MeasRec['method_codes'] = 'LT-T-Z'
                        inst = inst+':IODP-TDS'  # measured on shipboard Schonstedt thermal demagnetizer
                        try:
                            treatment_value = float(
                                InRec['Treatment Value'])+273  # convert C => K
                        except KeyError:
                            try:
                                treatment_value = float(
                                    InRec["Treatment value<br> (mT or \N{DEGREE SIGN}C)"]) + 273
                            except KeyError:
                                print([k for k in InRec.keys() if 'treat' in k.lower()])
                                print("-W- Couldn't find column for Treatment Value")
                                treatment_value = ""
                        MeasRec["treat_temp"] = str(treatment_value)
                    elif 'Alternating Frequency' in InRec['Treatment Type']:
                        MeasRec['method_codes'] = 'LT-AF-Z'
                        inst = inst+':IODP-DTECH'  # measured on shipboard Dtech D2000
                        treatment_value = float(
                            InRec[demag_key])*1e-3  # convert mT => T
                        # AF demag in treat mT => T
                        MeasRec["treat_ac_field"] = treatment_value
                    elif 'Thermal' in InRec['Treatment Type']:
                        MeasRec['method_codes'] = 'LT-T-Z'
                        inst = inst+':IODP-TDS'  # measured on shipboard Schonstedt thermal demagnetizer
                        treatment_value = float(
                            InRec[demag_key])+273  # convert C => K
                        MeasRec["treat_temp"] = '%8.3e' % (treatment_value)
                elif InRec[demag_key] != "0":
                    MeasRec['method_codes'] = 'LT-AF-Z'
                    inst = inst+':IODP-SRM-AF'  # measured on shipboard in-line 2G AF
                    try:
                        treatment_value = float(
                            InRec[demag_key])*1e-3  # convert mT => T
                    except ValueError:
                        print("Couldn't determine treatment value was given treatment value of %s and demag key %s; setting to blank you will have to manually correct this (or fix it)" % (
                            InRec[demag_key], demag_key))
                        treatment_value = ''
                    # AF demag in treat mT => T
                    MeasRec["treat_ac_field"] = treatment_value
                MeasRec["standard"] = 'u'  # assume all data are "good"
                vol = float(volume)*1e-6  # convert from cc to m^3
                if run_number != "":
                    MeasRec['external_database_ids'] = {'LIMS': run_number}
                else:
                    MeasRec['external_database_ids'] = ""
                MeasRec['dir_inc'] = InRec[inc_key]
                MeasRec['dir_dec'] = InRec[dec_key]
                intens = InRec[int_key]
                try:
                    # convert intensity from A/m to Am^2 using vol
                    MeasRec['magn_moment'] = '%8.3e' % (float(intens)*vol)
                except ValueError:
                    print("couldn't find magnetic moment for specimen %s and int_key %s; leaving this field blank you'll have to fix this manually" % (
                        specimen, int_key))
                    MeasRec['magn_moment'] = ''
                MeasRec['instrument_codes'] = inst
                MeasRec['treat_step_num'] = 0
                MeasRec['dir_csd'] = '0'
                MeasRec['meas_n_orient'] = ''
                MeasRecs.append(MeasRec)
    if not file_found:
        print("No .csv files were found")
        return (False, "No .csv files were found")

    con = cb.Contribution(output_dir_path, read_tables=[])

    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)
    #MeasSort=sorted(MeasRecs,key=lambda x: (x['specimen'], float(x['treat_ac_field'])))
    #MeasSort=sorted(MeasRecs,key=lambda x: float(x['treat_ac_field']))
    # MeasOuts=pmag.measurements_methods3(MeasSort,noave)
    MeasOuts = pmag.measurements_methods3(MeasRecs, noave)
    con.add_magic_table_from_data(dtype='measurements', data=MeasOuts)

    con.write_table_to_file('specimens', custom_name=spec_file,dir_path=dir_path)
    con.write_table_to_file('samples', custom_name=samp_file,dir_path=dir_path)
    con.write_table_to_file('sites', custom_name=site_file,dir_path=dir_path)
    con.write_table_to_file('locations', custom_name=loc_file,dir_path=dir_path)
    con.write_table_to_file('measurements', custom_name=meas_file,dir_path=dir_path)

    return (True, meas_file)

Response: This function converts IODP LIMS and LORE SRM archive half sample format files to measurements format files.


Instruction:
How would you implement a function in Python 3 that
converts JR6. jr6 files to MagIC files.

Response:
def jr6_jr6(mag_file, dir_path=".", input_dir_path="",
            meas_file="measurements.txt", spec_file="specimens.txt",
            samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt",
            specnum=1, samp_con='1', location='unknown', lat='', lon='',
            noave=False, meth_code="LP-NO", volume=12, JR=False, user=""):

    """
    Convert JR6 .jr6 files to MagIC file(s)

    Parameters
    ----------
    mag_file : str
        input file name
    dir_path : str
        working directory, default "."
    input_dir_path : str
        input file directory IF different from dir_path, default ""
    meas_file : str
        output measurement file name, default "measurements.txt"
    spec_file : str
        output specimen file name, default "specimens.txt"
    samp_file: str
        output sample file name, default "samples.txt"
    site_file : str
        output site file name, default "sites.txt"
    loc_file : str
        output location file name, default "locations.txt"
    specnum : int
        number of characters to designate a specimen, default 0
    samp_con : str
        sample/site naming convention, default '1', see info below
    location : str
        location name, default "unknown"
    lat : float
        latitude, default ""
    lon : float
        longitude, default ""
    noave : bool
       do not average duplicate measurements, default False (so by default, DO average)
    meth_code : str
        colon-delimited method codes, default "LP-NO"
    volume : float
        volume in ccs, default 12
    JR : bool
        IODP samples were measured on the JOIDES RESOLUTION, default False
    user : str
        user name, default ""

    Returns
    ---------
    Tuple : (True or False indicating if conversion was sucessful, meas_file name written)

    Info
    --------
    Sample naming convention:
        [1] XXXXY: where XXXX is an arbitrary length site designation and Y
            is the single character sample designation.  e.g., TG001a is the
            first sample from site TG001.    [default]
        [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
        [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
        [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
        [5] site name same as sample
        [6] site is entered under a separate column -- NOT CURRENTLY SUPPORTED
        [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY

    """

    version_num = pmag.get_version()
    input_dir_path, output_dir_path = pmag.fix_directories(input_dir_path, dir_path)
    specnum = - int(specnum)
    samp_con = str(samp_con)
    volume = float(volume) * 1e-6
    # need to add these
    meas_file = pmag.resolve_file_name(meas_file, output_dir_path)
    spec_file = pmag.resolve_file_name(spec_file, output_dir_path)
    samp_file = pmag.resolve_file_name(samp_file, output_dir_path)
    site_file = pmag.resolve_file_name(site_file, output_dir_path)
    loc_file = pmag.resolve_file_name(loc_file, output_dir_path)
    mag_file = pmag.resolve_file_name(mag_file, input_dir_path)

    if JR:
        if meth_code == "LP-NO":
            meth_code = ""
        meth_code = meth_code+":FS-C-DRILL-IODP:SP-SS-C:SO-V"
        meth_code = meth_code.strip(":")
        samp_con = '5'

    # format variables
    tmp_file = mag_file.split(os.extsep)[0]+os.extsep+'tmp'
    mag_file = pmag.resolve_file_name(mag_file, input_dir_path)
    if samp_con.startswith("4"):
        if "-" not in samp_con:
            print("option [4] must be in form 4-Z where Z is an integer")
            return False, "naming convention option [4] must be in form 4-Z where Z is an integer"
        else:
            Z = samp_con.split("-")[1]
            samp_con = "4"
    elif samp_con.startswith("7"):
        if "-" not in samp_con:
            print("option [7] must be in form 7-Z where Z is an integer")
            return False, "naming convention option [7] must be in form 7-Z where Z is an integer"
        else:
            Z = samp_con.split("-")[1]
            samp_con = "7"
    else:
        Z = 1

    # parse data
    # fix .jr6 file so that there are spaces between all the columns.
    pre_data = open(mag_file, 'r')
    tmp_data = open(tmp_file, 'w')
    if samp_con != '2':
        fixed_data = pre_data.read().replace('-', ' -')
    else:
        fixed_data = ""
        for line in pre_data.readlines():
            entries = line.split()
            if len(entries) < 2:
                continue
            fixed_line = entries[0] + ' ' + reduce(
                lambda x, y: x+' '+y, [x.replace('-', ' -') for x in entries[1:]])
            fixed_data += fixed_line+os.linesep
    tmp_data.write(fixed_data)
    tmp_data.close()
    pre_data.close()

    if not JR:
        column_names = ['specimen', 'step', 'x', 'y', 'z', 'expon', 'azimuth', 'dip', 'bed_dip_direction',
                        'bed_dip', 'bed_dip_dir2', 'bed_dip2', 'param1', 'param2', 'param3', 'param4', 'dir_csd']
    else:  # measured on the Joides Resolution JR6
        column_names = ['specimen', 'step', 'negz', 'y', 'x', 'expon', 'azimuth', 'dip', 'bed_dip_direction',
                        'bed_dip', 'bed_dip_dir2', 'bed_dip2', 'param1', 'param2', 'param3', 'param4', 'dir_csd']
    data = pd.read_csv(tmp_file, delim_whitespace=True,
                       names=column_names, index_col=False)
    if isinstance(data['x'][0], str):
        column_names = ['specimen', 'step', 'step_unit', 'x', 'y', 'z', 'expon', 'azimuth', 'dip', 'bed_dip_direction',
                        'bed_dip', 'bed_dip_dir2', 'bed_dip2', 'param1', 'param2', 'param3', 'param4', 'dir_csd']
        data = pd.read_csv(tmp_file, delim_whitespace=True,
                           names=column_names, index_col=False)
    if JR:
        data['z'] = -data['negz']
    cart = np.array([data['x'], data['y'], data['z']]).transpose()
    dir_dat = pmag.cart2dir(cart).transpose()
    data['dir_dec'] = dir_dat[0]
    data['dir_inc'] = dir_dat[1]
    # the data are in A/m - this converts to Am^2
    data['magn_moment'] = dir_dat[2]*(10.0**data['expon'])*volume
    data['magn_volume'] = dir_dat[2] * \
        (10.0**data['expon'])  # A/m  - data in A/m
    data['dip'] = -data['dip']

    data['specimen']
    # put data into magic tables
    MagRecs, SpecRecs, SampRecs, SiteRecs, LocRecs = [], [], [], [], []
    for rowNum, row in data.iterrows():
        MeasRec, SpecRec, SampRec, SiteRec, LocRec = {}, {}, {}, {}, {}
        specimen = row['specimen']
        if specnum != 0:
            sample = specimen[:specnum]
        else:
            sample = specimen
        site = pmag.parse_site(sample, samp_con, Z)
        if specimen != "" and specimen not in [x['specimen'] if 'specimen' in list(x.keys()) else "" for x in SpecRecs]:
            SpecRec['specimen'] = specimen
            SpecRec['sample'] = sample
            SpecRec["citations"] = "This study"
            SpecRec["analysts"] = user
            SpecRec['volume'] = volume
            SpecRecs.append(SpecRec)
        if sample != "" and sample not in [x['sample'] if 'sample' in list(x.keys()) else "" for x in SampRecs]:
            SampRec['sample'] = sample
            SampRec['site'] = site
            SampRec["citations"] = "This study"
            SampRec["analysts"] = user
            SampRec['azimuth'] = row['azimuth']
            SampRec['dip'] = row['dip']
            SampRec['bed_dip_direction'] = row['bed_dip_direction']
            SampRec['bed_dip'] = row['bed_dip']
            SampRec['method_codes'] = meth_code
            SampRecs.append(SampRec)
        if site != "" and site not in [x['site'] if 'site' in list(x.keys()) else "" for x in SiteRecs]:
            SiteRec['site'] = site
            SiteRec['location'] = location
            SiteRec["citations"] = "This study"
            SiteRec["analysts"] = user
            SiteRec['lat'] = lat
            SiteRec['lon'] = lon
            SiteRecs.append(SiteRec)
        if location != "" and location not in [x['location'] if 'location' in list(x.keys()) else "" for x in LocRecs]:
            LocRec['location'] = location
            LocRec["citations"] = "This study"
            LocRec["analysts"] = user
            LocRec['lat_n'] = lat
            LocRec['lon_e'] = lon
            LocRec['lat_s'] = lat
            LocRec['lon_w'] = lon
            LocRecs.append(LocRec)
        MeasRec["citations"] = "This study"
        MeasRec["analysts"] = user
        MeasRec["specimen"] = specimen
        MeasRec['software_packages'] = version_num
        MeasRec["treat_temp"] = '%8.3e' % (273)  # room temp in kelvin
        MeasRec["meas_temp"] = '%8.3e' % (273)  # room temp in kelvin
        MeasRec["quality"] = 'g'
        MeasRec["standard"] = 'u'
        MeasRec["treat_step_num"] = 0
        MeasRec["treat_ac_field"] = '0'
        if row['step'] == 'NRM':
            meas_type = "LT-NO"
        elif 'step_unit' in row and row['step_unit'] == 'C':
            meas_type = "LT-T-Z"
            treat = float(row['step'])
            MeasRec["treat_temp"] = '%8.3e' % (treat+273.)  # temp in kelvin
        elif row['step'][0:2] == 'AD':
            meas_type = "LT-AF-Z"
            treat = float(row['step'][2:])
            MeasRec["treat_ac_field"] = '%8.3e' % (
                treat*1e-3)  # convert from mT to tesla
        elif row['step'][0] == 'A':
            meas_type = "LT-AF-Z"
            treat = float(row['step'][1:])
            MeasRec["treat_ac_field"] = '%8.3e' % (
                treat*1e-3)  # convert from mT to tesla
        elif row['step'][0] == 'TD':
            meas_type = "LT-T-Z"
            treat = float(row['step'][2:])
            MeasRec["treat_temp"] = '%8.3e' % (treat+273.)  # temp in kelvin
        elif row['step'][0] == 'T':
            meas_type = "LT-T-Z"
            treat = float(row['step'][1:])
            MeasRec["treat_temp"] = '%8.3e' % (treat+273.)  # temp in kelvin
        else:  # need to add IRM, and ARM options
            print("measurement type unknown", row['step'])
            return False, "measurement type unknown"
        MeasRec["magn_moment"] = str(row['magn_moment'])
        MeasRec["magn_volume"] = str(row['magn_volume'])
        MeasRec["dir_dec"] = str(row['dir_dec'])
        MeasRec["dir_inc"] = str(row['dir_inc'])
        MeasRec['method_codes'] = meas_type
        MagRecs.append(MeasRec)

    con = cb.Contribution(output_dir_path, read_tables=[])

    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(MagRecs, noave)
    con.add_magic_table_from_data(dtype='measurements', data=MeasOuts)

    con.tables['specimens'].write_magic_file(custom_name=spec_file)
    con.tables['samples'].write_magic_file(custom_name=samp_file)
    con.tables['sites'].write_magic_file(custom_name=site_file)
    con.tables['locations'].write_magic_file(custom_name=loc_file)
    con.tables['measurements'].write_magic_file(custom_name=meas_file)

    try:
        os.remove(tmp_file)
    except (OSError, IOError) as e:
        print("couldn't remove temperary fixed JR6 file %s" % tmp_file)

    return True, meas_file


Instruction:
Make a summary of the following Python 3 code
def jr6_txt(mag_file, dir_path=".", input_dir_path="",
            meas_file="measurements.txt", spec_file="specimens.txt",
            samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt",
            user="", specnum=1, samp_con='1', location='unknown', lat='', lon='',
            noave=False, volume=12, timezone="UTC", meth_code="LP-NO"):

    """
    Converts JR6 .txt format files to MagIC measurements format files.

    Parameters
    ----------
    mag_file : str
        input file name
    dir_path : str
        working directory, default "."
    input_dir_path : str
        input file directory IF different from dir_path, default ""
    meas_file : str
        output measurement file name, default "measurements.txt"
    spec_file : str
        output specimen file name, default "specimens.txt"
    samp_file: str
        output sample file name, default "samples.txt"
    site_file : str
        output site file name, default "sites.txt"
    loc_file : str
        output location file name, default "locations.txt"
    user : str
        user name, default ""
    specnum : int
        number of characters to designate a specimen, default 0
    samp_con : str
        sample/site naming convention, default '1', see info below
    location : str
        location name, default "unknown"
    lat : float
        latitude, default ""
    lon : float
        longitude, default ""
    noave : bool
       do not average duplicate measurements, default False (so by default, DO average)
    volume : float
        volume in ccs, default 12
    timezone : timezone of date/time string in comment string, default UTC
    meth_code : str
        default "LP-NO"

    Returns
    ---------
    Tuple : (True or False indicating if conversion was sucessful, meas_file name written)

    """

    version_num = pmag.get_version()
    input_dir_path, output_dir_path = pmag.fix_directories(input_dir_path, dir_path)
    mag_file = pmag.resolve_file_name(mag_file, input_dir_path)
    input_dir_path = os.path.split(mag_file)[0]
    specnum = - int(specnum)
    samp_con = str(samp_con)
    volume = float(volume) * 1e-6

    # format variables
    mag_file = pmag.resolve_file_name(mag_file, input_dir_path)
    if samp_con.startswith("4"):
        if "-" not in samp_con:
            print("option [4] must be in form 4-Z where Z is an integer")
            return False, "naming convention option [4] must be in form 4-Z where Z is an integer"
        else:
            Z = samp_con.split("-")[1]
            samp_con = "4"
    elif samp_con.startswith("7"):
        if "-" not in samp_con:
            print("option [7] must be in form 7-Z where Z is an integer")
            return False, "naming convention option [7] must be in form 7-Z where Z is an integer"
        else:
            Z = samp_con.split("-")[1]
            samp_con = "7"
    else:
        Z = 1

    # create data holders
    MeasRecs, SpecRecs, SampRecs, SiteRecs, LocRecs = [], [], [], [], []

    data = pmag.open_file(mag_file)
    # remove garbage/blank lines
    data = [i for i in data if len(i) >= 5]
    if not len(data):
        print('No data')
        return

    n = 0
    end = False
    # loop through records
    while not end:
        first_line = data[n].split()
        sampleName = first_line[0]
        demagLevel = first_line[2]
        date = first_line[3] + ":0:0:0"
        n += 2
        third_line = data[n].split()
        if not third_line[0].startswith('SPEC.ANGLES'):
            print('third line of a block should start with SPEC.ANGLES')
            print(third_line)
            return
        specimenAngleDec = third_line[1]
        specimenAngleInc = third_line[2]
        n += 4
        while not data[n].startswith('MEAN'):
            n += 1
        mean_line = data[n]
        Mx = mean_line[1]
        My = mean_line[2]
        Mz = mean_line[3]
        n += 1
        precision_line = data[n].split()
        if not precision_line[0].startswith('Modulus'):
            print('precision line should start with "Modulus"')
            return
        splitExp = precision_line[2].split('A')
        intensityVolStr = precision_line[1] + splitExp[0]
        intensityVol = float(intensityVolStr)
        # check and see if Prec is too big and messes with the parcing.
        precisionStr = ''
        if len(precision_line) == 6:  # normal line
            precisionStr = precision_line[5][0:-1]
        else:
            precisionStr = precision_line[4][0:-1]

        precisionPer = float(precisionStr)
        precision = intensityVol * precisionPer/100

        while not data[n].startswith('SPEC.'):
            n += 1
        specimen_line = data[n].split()
        specimenDec = specimen_line[2]
        specimenInc = specimen_line[3]
        n += 1
        geographic_line = data[n]
        if not geographic_line.startswith('GEOGR'):
            geographic_dec = ''
            geographic_inc = ''
        else:
            geographic_line = geographic_line.split()
            geographicDec = geographic_line[1]
            geographicInc = geographic_line[2]
        # Add data to various MagIC data tables.
        specimen = sampleName
        if specnum != 0:
            sample = specimen[:specnum]
        else:
            sample = specimen
        site = pmag.parse_site(sample, samp_con, Z)

        MeasRec, SpecRec, SampRec, SiteRec, LocRec = {}, {}, {}, {}, {}

        if specimen != "" and specimen not in [x['specimen'] if 'specimen' in list(x.keys()) else "" for x in SpecRecs]:
            SpecRec['specimen'] = specimen
            SpecRec['sample'] = sample
            SpecRec["citations"] = "This study"
            SpecRec["analysts"] = user
            SpecRec['volume'] = volume
            SpecRecs.append(SpecRec)
        if sample != "" and sample not in [x['sample'] if 'sample' in list(x.keys()) else "" for x in SampRecs]:
            SampRec['sample'] = sample
            SampRec['site'] = site
            SampRec["citations"] = "This study"
            SampRec["analysts"] = user
            SampRec['azimuth'] = specimenAngleDec
            # convert to magic orientation
            sample_dip = str(float(specimenAngleInc)-90.0)
            SampRec['dip'] = sample_dip
            SampRec['method_codes'] = meth_code
            SampRecs.append(SampRec)
        if site != "" and site not in [x['site'] if 'site' in list(x.keys()) else "" for x in SiteRecs]:
            SiteRec['site'] = site
            SiteRec['location'] = location
            SiteRec["citations"] = "This study"
            SiteRec["analysts"] = user
            SiteRec['lat'] = lat
            SiteRec['lon'] = lon
            SiteRecs.append(SiteRec)
        if location != "" and location not in [x['location'] if 'location' in list(x.keys()) else "" for x in LocRecs]:
            LocRec['location'] = location
            LocRec["citations"] = "This study"
            LocRec["analysts"] = user
            LocRec['lat_n'] = lat
            LocRec['lon_e'] = lon
            LocRec['lat_s'] = lat
            LocRec['lon_w'] = lon
            LocRecs.append(LocRec)

        local = pytz.timezone(timezone)
        naive = datetime.datetime.strptime(date, "%m-%d-%Y:%H:%M:%S")
        local_dt = local.localize(naive, is_dst=None)
        utc_dt = local_dt.astimezone(pytz.utc)
        timestamp = utc_dt.strftime("%Y-%m-%dT%H:%M:%S")+"Z"
        MeasRec["specimen"] = specimen
        MeasRec["timestamp"] = timestamp
        MeasRec['description'] = ''
        MeasRec["citations"] = "This study"
        MeasRec['software_packages'] = version_num
        MeasRec["treat_temp"] = '%8.3e' % (273)  # room temp in kelvin
        MeasRec["meas_temp"] = '%8.3e' % (273)  # room temp in kelvin
        MeasRec["quality"] = 'g'
        MeasRec["standard"] = 'u'
        MeasRec["treat_step_num"] = 0
        MeasRec["treat_ac_field"] = '0'
        if demagLevel == 'NRM':
            meas_type = "LT-NO"
        elif demagLevel[0] == 'A':
            if demagLevel[:2] == 'AD':
                treat = float(demagLevel[2:])
            else:
                treat = float(demagLevel[1:])
            meas_type = "LT-AF-Z"
            MeasRec["treat_ac_field"] = '%8.3e' % (
                treat*1e-3)  # convert from mT to tesla
        elif demagLevel[0] == 'T':
            meas_type = "LT-T-Z"
            treat = float(demagLevel[1:])
            MeasRec["treat_temp"] = '%8.3e' % (treat+273.)  # temp in kelvin
        else:
            print("measurement type unknown", demagLevel)
            return False, "measurement type unknown"

        MeasRec["magn_moment"] = str(intensityVol*volume)  # Am^2
        MeasRec["magn_volume"] = intensityVolStr  # A/m
        MeasRec["dir_dec"] = specimenDec
        MeasRec["dir_inc"] = specimenInc
        MeasRec['method_codes'] = meas_type
        MeasRecs.append(MeasRec)

        # ignore all the rest of the special characters. Some data files not consistantly formatted.
        n += 1
        while ((len(data[n]) <= 5 and data[n] != '') or data[n].startswith('----')):
            n += 1
            if n >= len(data):
                break
        if n >= len(data):
            # we're done!
            end = True

        # end of data while loop

    con = cb.Contribution(output_dir_path, read_tables=[])

    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)
    con.add_magic_table_from_data(dtype='measurements', data=MeasOuts)

    con.tables['specimens'].write_magic_file(custom_name=spec_file,dir_path=dir_path)
    con.tables['samples'].write_magic_file(custom_name=samp_file,dir_path=dir_path)
    con.tables['sites'].write_magic_file(custom_name=site_file,dir_path=dir_path)
    con.tables['locations'].write_magic_file(custom_name=loc_file,dir_path=dir_path)
    con.tables['measurements'].write_magic_file(custom_name=meas_file,dir_path=dir_path)

    return True, meas_file

Response: This function converts JR6. txt format files to MagIC measurements format files.


Instruction:
Can you generate the documentation for the following Python 3 function
def k15(k15file, dir_path='.', input_dir_path='',
        meas_file='measurements.txt', aniso_outfile='specimens.txt',
        samp_file="samples.txt", result_file ="rmag_anisotropy.txt",
        specnum=0, sample_naming_con='1', location="unknown",
        data_model_num=3):
    """
    converts .k15 format data to MagIC  format.
    assumes Jelinek Kappabridge measurement scheme.

    Parameters
    ----------
    k15file : str
        input file name
    dir_path : str
        output file directory, default "."
    input_dir_path : str
        input file directory IF different from dir_path, default ""
    meas_file : str
        output measurement file name, default "measurements.txt"
    aniso_outfile : str
        output specimen file name, default "specimens.txt"
    samp_file: str
        output sample file name, default "samples.txt"
    aniso_results_file : str
        output result file name, default "rmag_results.txt", data model 2 only
    specnum : int
        number of characters to designate a specimen, default 0
    samp_con : str
        sample/site naming convention, default '1', see info below
    location : str
        location name, default "unknown"
    data_model_num : int
        MagIC data model [2, 3], default 3

    Returns
    --------
    type - Tuple : (True or False indicating if conversion was sucessful, samp_file name written)

    Info
    --------
      Infile format:
          name [az,pl,strike,dip], followed by
          3 rows of 5 measurements for each specimen

       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXXYYY:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site name entered in site_name column in the orient.txt format input file  -- NOT CURRENTLY SUPPORTED
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail ltauxe@ucsd.edu for help.

    """
    #
    # initialize some variables
    #
    input_dir_path, output_dir_path = pmag.fix_directories(input_dir_path, dir_path)
    version_num = pmag.get_version()
    syn = 0
    itilt, igeo, linecnt, key = 0, 0, 0, ""
    first_save = 1
    k15 = []
    citation = 'This study'

    data_model_num = int(float(data_model_num))

    # set column names for MagIC 3
    spec_name_col = 'specimen'  #
    samp_name_col = 'sample'   #
    site_name_col = 'site'   #
    loc_name_col = 'location' #
    citation_col = 'citations'
    method_col = 'method_codes'
    site_description_col = 'description'
    expedition_col = 'expedition_name'
    instrument_col = 'instrument_codes'
    experiment_col = 'experiments'
    analyst_col = 'analysts'
    quality_col = 'quality'
    aniso_quality_col = 'result_quality'
    meas_standard_col = 'standard'
    meas_description_col = 'description'
    aniso_type_col = 'aniso_type'
    aniso_unit_col = 'aniso_s_unit'
    aniso_n_col = 'aniso_s_n_measurements'
    azimuth_col = 'azimuth'
    spec_volume_col = 'volume'
    samp_dip_col = 'dip'
    bed_dip_col = 'bed_dip'
    bed_dip_direction_col = 'bed_dip_direction'
    chi_vol_col = 'susc_chi_volume'
    aniso_sigma_col = 'aniso_s_sigma'
    aniso_unit_col = 'aniso_s_unit'
    aniso_tilt_corr_col = 'aniso_tilt_correction'
    meas_table_name = 'measurements'
    spec_table_name = 'specimens'
    samp_table_name = 'samples'
    site_table_name = 'sites'
    meas_name_col = 'measurement'
    meas_time_col = 'timestamp'
    meas_ac_col = 'meas_field_ac'
    meas_temp_col = "meas_temp"
    #
    software_col = 'software_packages'
    description_col = 'description' # sites.description
    treat_temp_col = 'treat_temp'
    meas_orient_phi_col = "meas_orient_phi"
    meas_orient_theta_col = "meas_orient_theta"
    aniso_mean_col = 'aniso_s_mean'
    result_description_col = "description"

    # set defaults correctly for MagIC 2
    if data_model_num == 2:
        if meas_file == 'measurements.txt':
            meas_file = 'magic_measurements.txt'
        if samp_file == 'samples.txt':
            samp_file = 'er_samples.txt'
        if aniso_outfile == 'specimens.txt':
            aniso_outfile = 'rmag_anisotropy.txt'

    # set column names for MagIC 2
    if data_model_num == 2:
        spec_name_col = 'er_specimen_name'
        samp_name_col = 'er_sample_name'
        site_name_col = 'er_site_name'
        loc_name_col = 'er_location_name'
        citation_col = 'er_citation_names'
        method_col = 'magic_method_codes'
        site_description_col = 'site_description'
        expedition_col = 'er_expedition_name'
        instrument_col = 'magic_instrument_codes'
        experiment_col = 'magic_experiment_names'
        analyst_col = 'er_analyst_mail_names'
        quality_col = 'measurement_flag'
        aniso_quality_col = 'anisotropy_flag'
        meas_standard_col = 'measurement_standard'
        meas_description_col = 'measurement_description'
        aniso_type_col = 'anisotropy_type'
        aniso_unit_col = 'anisotropy_unit'
        aniso_n_col = 'anisotropy_n'
        azimuth_col = 'sample_azimuth'
        spec_volume_col = 'specimen_volume'
        samp_dip_col = 'sample_dip'
        bed_dip_col = 'sample_bed_dip'
        bed_dip_direction_col = 'sample_bed_dip_direction'
        chi_vol_col = 'measurement_chi_volume'
        aniso_sigma_col = 'anisotropy_sigma'
        aniso_unit_col = 'anisotropy_unit'
        aniso_tilt_corr_col = 'anisotropy_tilt_correction'
        meas_table_name = 'magic_measurements'
        spec_table_name = 'er_specimens'
        samp_table_name = 'er_samples'
        site_table_name = 'er_sites'
        meas_name_col = 'measurement_number'
        meas_time_col = 'measurement_date'
        meas_ac_col = 'measurement_lab_field_ac'
        meas_temp_col = "measurement_temp"
        #
        software_col = 'magic_software_packages'
        description_col = 'rmag_result_name'
        treat_temp_col = 'treatment_temp'
        meas_temp_col = "measurement_temp"
        meas_orient_phi_col = "measurement_orient_phi"
        meas_orient_theta_col = "measurement_orient_theta"
        aniso_mean_col = 'anisotropy_mean'
        result_description_col = "result_description"

# pick off stuff from command line
    Z = ""
    if "4" in sample_naming_con:
        if "-" not in sample_naming_con:
            print("option [4] must be in form 4-Z where Z is an integer")
            return False, "option [4] must be in form 4-Z where Z is an integer"
        else:
            Z = sample_naming_con.split("-")[1]
            sample_naming_con = "4"
    if sample_naming_con == '6':
        Samps, filetype = pmag.magic_read(
            os.path.join(input_dir_path, samp_table_name + ".txt"))
    samp_file = pmag.resolve_file_name(samp_file, output_dir_path)
    meas_file = pmag.resolve_file_name(meas_file, output_dir_path)
    aniso_outfile = pmag.resolve_file_name(aniso_outfile, output_dir_path)
    result_file = pmag.resolve_file_name(result_file, output_dir_path)
    k15file = pmag.resolve_file_name(k15file, input_dir_path)
    if not os.path.exists(k15file):
        print(k15file)
        return False, "You must provide a valid k15 format file"
    try:
        SampRecs, filetype = pmag.magic_read(
            samp_file)  # append new records to existing
        samplist = []
        for samp in SampRecs:
            if samp[samp_name_col] not in samplist:
                samplist.append(samp[samp_name_col])
    except IOError:
        SampRecs = []
    # measurement directions for Jelinek 1977 protocol:
    Decs = [315, 225, 180, 135, 45, 90, 270, 270, 270, 90, 180, 180, 0, 0, 0]
    Incs = [0, 0, 0, 0, 0, -45, -45, 0, 45, 45, 45, -45, -90, -45, 45]
    # some defaults to read in  .k15 file format
    # list of measurements and default number of characters for specimen ID
# some magic default definitions
    #
    # read in data
    with open(k15file, 'r') as finput:
        lines = finput.readlines()
    MeasRecs, SpecRecs, AnisRecs, ResRecs = [], [], [], []
    # read in data
    MeasRec, SpecRec, SampRec, SiteRec, AnisRec, ResRec = {}, {}, {}, {}, {}, {}
    for line in lines:
        linecnt += 1
        rec = line.split()
        if linecnt == 1:
            MeasRec[method_col] = ""
            SpecRec[method_col] = ""
            SampRec[method_col] = ""
            AnisRec[method_col] = ""
            SiteRec[method_col] = ""
            ResRec[method_col] = ""
            MeasRec[software_col] = version_num
            SpecRec[software_col] = version_num
            SampRec[software_col] = version_num
            AnisRec[software_col] = version_num
            SiteRec[software_col] = version_num
            ResRec[software_col] = version_num
            MeasRec[method_col] = "LP-X"
            MeasRec[quality_col] = "g"
            MeasRec[meas_standard_col] = "u"
            MeasRec[citation_col] = "This study"
            SpecRec[citation_col] = "This study"
            SampRec[citation_col] = "This study"
            AnisRec[citation_col] = "This study"
            ResRec[citation_col] = "This study"
            MeasRec[spec_name_col] = rec[0]
            MeasRec[experiment_col] = rec[0] + ":LP-AN-MS"
            AnisRec[experiment_col] = rec[0] + ":AMS"
            ResRec[experiment_col] = rec[0] + ":AMS"
            SpecRec[spec_name_col] = rec[0]
            AnisRec[spec_name_col] = rec[0]
            SampRec[spec_name_col] = rec[0]
            if data_model_num == 2:
                ResRec[description_col] = rec[0]
            if data_model_num == 3:
                ResRec[spec_name_col] = rec[0]
            specnum = int(specnum)
            if specnum != 0:
                MeasRec[samp_name_col] = rec[0][:-specnum]
            if specnum == 0:
                MeasRec[samp_name_col] = rec[0]
            SampRec[samp_name_col] = MeasRec[samp_name_col]
            SpecRec[samp_name_col] = MeasRec[samp_name_col]
            AnisRec[samp_name_col] = MeasRec[samp_name_col]
            if data_model_num == 3:
                ResRec[samp_name_col] = MeasRec[samp_name_col]
            else:
                ResRec[samp_name_col + "s"] = MeasRec[samp_name_col]
            if sample_naming_con == "6":
                for samp in Samps:
                    if samp[samp_name_col] == AnisRec[samp_name_col]:
                        sitename = samp[site_name_col]
                        location = samp[loc_name_col]
            elif sample_naming_con != "":
                sitename = pmag.parse_site(
                    AnisRec[samp_name_col], sample_naming_con, Z)
            MeasRec[site_name_col] = sitename
            MeasRec[loc_name_col] = location
            SampRec[site_name_col] = MeasRec[site_name_col]
            SpecRec[site_name_col] = MeasRec[site_name_col]
            AnisRec[site_name_col] = MeasRec[site_name_col]
            ResRec[loc_name_col] = location
            ResRec[site_name_col] = MeasRec[site_name_col]
            if data_model_num == 2:
                ResRec[site_name_col + "s"] = MeasRec[site_name_col]
            SampRec[loc_name_col] = MeasRec[loc_name_col]
            SpecRec[loc_name_col] = MeasRec[loc_name_col]
            AnisRec[loc_name_col] = MeasRec[loc_name_col]
            if data_model_num == 2 :
                ResRec[loc_name_col + "s"] = MeasRec[loc_name_col]
            if len(rec) >= 3:
                SampRec[azimuth_col], SampRec[samp_dip_col] = rec[1], rec[2]
                az, pl, igeo = float(rec[1]), float(rec[2]), 1
            if len(rec) == 5:
                SampRec[bed_dip_direction_col], SampRec[bed_dip_col] = '%7.1f' % (
                    90. + float(rec[3])), (rec[4])
                bed_az, bed_dip, itilt, igeo = 90. + \
                    float(rec[3]), float(rec[4]), 1, 1
        else:
            for i in range(5):
                # assume measurements in micro SI
                k15.append(1e-6 * float(rec[i]))
            if linecnt == 4:
                sbar, sigma, bulk = pmag.dok15_s(k15)
                hpars = pmag.dohext(9, sigma, sbar)
                MeasRec[treat_temp_col] = '%8.3e' % (
                    273)  # room temp in kelvin
                MeasRec[meas_temp_col] = '%8.3e' % (
                    273)  # room temp in kelvin
                for i in range(15):
                    NewMeas = copy.deepcopy(MeasRec)
                    NewMeas[meas_orient_phi_col] = '%7.1f' % (Decs[i])
                    NewMeas[meas_orient_theta_col] = '%7.1f' % (Incs[i])
                    NewMeas[chi_vol_col] = '%12.10f' % (k15[i])
                    NewMeas[meas_name_col] = '%i' % (i + 1)
                    if data_model_num == 2:
                        NewMeas["magic_experiment_name"] = rec[0] + ":LP-AN-MS"
                    else:
                        NewMeas["experiment"] = rec[0] + ":LP-AN-MS"
                    MeasRecs.append(NewMeas)
                if SampRec[samp_name_col] not in samplist:
                    SampRecs.append(SampRec)
                    samplist.append(SampRec[samp_name_col])
                SpecRecs.append(SpecRec)
                AnisRec[aniso_type_col] = "AMS"
                ResRec[aniso_type_col] = "AMS"
                s1_val = '{:12.10f}'.format(sbar[0])
                s2_val = '{:12.10f}'.format(sbar[1])
                s3_val = '{:12.10f}'.format(sbar[2])
                s4_val = '{:12.10f}'.format(sbar[3])
                s5_val = '{:12.10f}'.format(sbar[4])
                s6_val = '{:12.10f}'.format(sbar[5])
                # MAgIC 2
                if data_model_num == 2:
                    AnisRec["anisotropy_s1"] = s1_val
                    AnisRec["anisotropy_s2"] = s2_val
                    AnisRec["anisotropy_s3"] = s3_val
                    AnisRec["anisotropy_s4"] = s4_val
                    AnisRec["anisotropy_s5"] = s5_val
                    AnisRec["anisotropy_s6"] = s6_val
                # MagIC 3
                else:
                    vals = [s1_val, s2_val, s3_val, s4_val, s5_val, s6_val]
                    AnisRec['aniso_s'] = ":".join([str(v).strip() for v in vals])
                AnisRec[aniso_mean_col] = '%12.10f' % (bulk)
                AnisRec[aniso_sigma_col] = '%12.10f' % (sigma)
                AnisRec[aniso_mean_col] = '{:12.10f}'.format(bulk)
                AnisRec[aniso_sigma_col] = '{:12.10f}'.format(sigma)
                AnisRec[aniso_unit_col] = 'SI'
                AnisRec[aniso_n_col] = '15'
                AnisRec[aniso_tilt_corr_col] = '-1'
                AnisRec[method_col] = 'LP-X:AE-H:LP-AN-MS'
                AnisRecs.append(AnisRec)
                ResRec[method_col] = 'LP-X:AE-H:LP-AN-MS'
                ResRec[aniso_tilt_corr_col] = '-1'

                if data_model_num == 3:
                    aniso_v1 = ':'.join([str(i) for i in (hpars['t1'], hpars['v1_dec'], hpars['v1_inc'],  hpars['v2_dec'], hpars['v2_inc'], hpars['e12'], hpars['v3_dec'], hpars['v3_inc'], hpars['e13'])])
                    aniso_v2 = ':'.join([str(i) for i in (hpars['t2'], hpars['v2_dec'], hpars['v2_inc'], hpars['v1_dec'], hpars['v1_inc'], hpars['e12'], hpars['v3_dec'], hpars['v3_inc'], hpars['e23'])])
                    aniso_v3 = ':'.join([str(i) for i in (hpars['t3'], hpars['v3_dec'], hpars['v3_inc'], hpars['v1_dec'], hpars['v1_inc'], hpars['e13'], hpars['v2_dec'], hpars['v2_inc'], hpars['e23'])])
                    ResRec['aniso_v1'] = aniso_v1
                    ResRec['aniso_v2'] = aniso_v2
                    ResRec['aniso_v3'] = aniso_v3
                else: # data model 2
                    ResRec["anisotropy_t1"] = '%12.10f' % (hpars['t1'])
                    ResRec["anisotropy_t2"] = '%12.10f' % (hpars['t2'])
                    ResRec["anisotropy_t3"] = '%12.10f' % (hpars['t3'])
                    ResRec["anisotropy_fest"] = '%12.10f' % (hpars['F'])
                    ResRec["anisotropy_ftest12"] = '%12.10f' % (hpars['F12'])
                    ResRec["anisotropy_ftest23"] = '%12.10f' % (hpars['F23'])
                    ResRec["anisotropy_v1_dec"] = '%7.1f' % (hpars['v1_dec'])
                    ResRec["anisotropy_v2_dec"] = '%7.1f' % (hpars['v2_dec'])
                    ResRec["anisotropy_v3_dec"] = '%7.1f' % (hpars['v3_dec'])
                    ResRec["anisotropy_v1_inc"] = '%7.1f' % (hpars['v1_inc'])
                    ResRec["anisotropy_v2_inc"] = '%7.1f' % (hpars['v2_inc'])
                    ResRec["anisotropy_v3_inc"] = '%7.1f' % (hpars['v3_inc'])
                    ResRec['anisotropy_v1_eta_dec'] = ResRec['anisotropy_v2_dec']
                    ResRec['anisotropy_v1_eta_inc'] = ResRec['anisotropy_v2_inc']
                    ResRec['anisotropy_v1_zeta_dec'] = ResRec['anisotropy_v3_dec']
                    ResRec['anisotropy_v1_zeta_inc'] = ResRec['anisotropy_v3_inc']
                    ResRec['anisotropy_v2_eta_dec'] = ResRec['anisotropy_v1_dec']
                    ResRec['anisotropy_v2_eta_inc'] = ResRec['anisotropy_v1_inc']
                    ResRec['anisotropy_v2_zeta_dec'] = ResRec['anisotropy_v3_dec']
                    ResRec['anisotropy_v2_zeta_inc'] = ResRec['anisotropy_v3_inc']
                    ResRec['anisotropy_v3_eta_dec'] = ResRec['anisotropy_v1_dec']
                    ResRec['anisotropy_v3_eta_inc'] = ResRec['anisotropy_v1_inc']
                    ResRec['anisotropy_v3_zeta_dec'] = ResRec['anisotropy_v2_dec']
                    ResRec['anisotropy_v3_zeta_inc'] = ResRec['anisotropy_v2_inc']
                    ResRec["anisotropy_v1_eta_semi_angle"] = '%7.1f' % (
                        hpars['e12'])
                    ResRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f' % (
                        hpars['e13'])
                    ResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f' % (
                        hpars['e12'])
                    ResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f' % (
                        hpars['e23'])
                    ResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f' % (
                        hpars['e13'])
                    ResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f' % (
                        hpars['e23'])
                ResRec[result_description_col] = 'Critical F: ' + hpars["F_crit"] + ';Critical F12/F13: ' + hpars["F12_crit"]
                #
                ResRecs.append(ResRec)
                if igeo == 1:
                    sbarg = pmag.dosgeo(sbar, az, pl)
                    hparsg = pmag.dohext(9, sigma, sbarg)
                    AnisRecG = copy.copy(AnisRec)
                    ResRecG = copy.copy(ResRec)
                    if data_model_num == 3:
                        AnisRecG["aniso_s"] = ":".join('{:12.10f}'.format(i) for i in sbarg)
                    if data_model_num == 2:
                        AnisRecG["anisotropy_s1"] = '%12.10f' % (sbarg[0])
                        AnisRecG["anisotropy_s2"] = '%12.10f' % (sbarg[1])
                        AnisRecG["anisotropy_s3"] = '%12.10f' % (sbarg[2])
                        AnisRecG["anisotropy_s4"] = '%12.10f' % (sbarg[3])
                        AnisRecG["anisotropy_s5"] = '%12.10f' % (sbarg[4])
                        AnisRecG["anisotropy_s6"] = '%12.10f' % (sbarg[5])

                    AnisRecG[aniso_tilt_corr_col] = '0'
                    ResRecG[aniso_tilt_corr_col] = '0'

                    if data_model_num == 3:
                        aniso_v1 = ':'.join([str(i) for i in (hparsg['t1'], hparsg['v1_dec'], hparsg['v1_inc'],  hparsg['v2_dec'], hparsg['v2_inc'], hparsg['e12'], hparsg['v3_dec'], hparsg['v3_inc'], hparsg['e13'])])
                        aniso_v2 = ':'.join([str(i) for i in (hparsg['t2'], hparsg['v2_dec'], hparsg['v2_inc'], hparsg['v1_dec'], hparsg['v1_inc'], hparsg['e12'], hparsg['v3_dec'], hparsg['v3_inc'], hparsg['e23'])])
                        aniso_v3 = ':'.join([str(i) for i in (hparsg['t3'], hparsg['v3_dec'], hparsg['v3_inc'], hparsg['v1_dec'], hparsg['v1_inc'], hparsg['e13'], hparsg['v2_dec'], hparsg['v2_inc'], hparsg['e23'])])
                        ResRecG['aniso_v1'] = aniso_v1
                        ResRecG['aniso_v2'] = aniso_v2
                        ResRecG['aniso_v3'] = aniso_v3
                    #
                    if data_model_num == 2:
                        ResRecG["anisotropy_v1_dec"] = '%7.1f' % (hparsg['v1_dec'])
                        ResRecG["anisotropy_v2_dec"] = '%7.1f' % (hparsg['v2_dec'])
                        ResRecG["anisotropy_v3_dec"] = '%7.1f' % (hparsg['v3_dec'])
                        ResRecG["anisotropy_v1_inc"] = '%7.1f' % (hparsg['v1_inc'])
                        ResRecG["anisotropy_v2_inc"] = '%7.1f' % (hparsg['v2_inc'])
                        ResRecG["anisotropy_v3_inc"] = '%7.1f' % (hparsg['v3_inc'])
                        ResRecG['anisotropy_v1_eta_dec'] = ResRecG['anisotropy_v2_dec']
                        ResRecG['anisotropy_v1_eta_inc'] = ResRecG['anisotropy_v2_inc']
                        ResRecG['anisotropy_v1_zeta_dec'] = ResRecG['anisotropy_v3_dec']
                        ResRecG['anisotropy_v1_zeta_inc'] = ResRecG['anisotropy_v3_inc']
                        ResRecG['anisotropy_v2_eta_dec'] = ResRecG['anisotropy_v1_dec']
                        ResRecG['anisotropy_v2_eta_inc'] = ResRecG['anisotropy_v1_inc']
                        ResRecG['anisotropy_v2_zeta_dec'] = ResRecG['anisotropy_v3_dec']
                        ResRecG['anisotropy_v2_zeta_inc'] = ResRecG['anisotropy_v3_inc']
                        ResRecG['anisotropy_v3_eta_dec'] = ResRecG['anisotropy_v1_dec']
                        ResRecG['anisotropy_v3_eta_inc'] = ResRecG['anisotropy_v1_inc']
                        ResRecG['anisotropy_v3_zeta_dec'] = ResRecG['anisotropy_v2_dec']
                        ResRecG['anisotropy_v3_zeta_inc'] = ResRecG['anisotropy_v2_inc']
                    #
                    ResRecG[result_description_col] = 'Critical F: ' + \
                        hpars["F_crit"] + ';Critical F12/F13: ' + \
                        hpars["F12_crit"]
                    ResRecs.append(ResRecG)
                    AnisRecs.append(AnisRecG)
                if itilt == 1:
                    sbart = pmag.dostilt(sbarg, bed_az, bed_dip)
                    hparst = pmag.dohext(9, sigma, sbart)
                    AnisRecT = copy.copy(AnisRec)
                    ResRecT = copy.copy(ResRec)
                    if data_model_num == 3:
                        aniso_v1 = ':'.join([str(i) for i in (hparst['t1'], hparst['v1_dec'], hparst['v1_inc'],  hparst['v2_dec'], hparst['v2_inc'], hparst['e12'], hparst['v3_dec'], hparst['v3_inc'], hparst['e13'])])
                        aniso_v2 = ':'.join([str(i) for i in (hparst['t2'], hparst['v2_dec'], hparst['v2_inc'], hparst['v1_dec'], hparst['v1_inc'], hparst['e12'], hparst['v3_dec'], hparst['v3_inc'], hparst['e23'])])
                        aniso_v3 = ':'.join([str(i) for i in (hparst['t3'], hparst['v3_dec'], hparst['v3_inc'], hparst['v1_dec'], hparst['v1_inc'], hparst['e13'], hparst['v2_dec'], hparst['v2_inc'], hparst['e23'])])
                        ResRecT['aniso_v1'] = aniso_v1
                        ResRecT['aniso_v2'] = aniso_v2
                        ResRecT['aniso_v3'] = aniso_v3
                    #
                    if data_model_num == 2:
                        AnisRecT["anisotropy_s1"] = '%12.10f' % (sbart[0])
                        AnisRecT["anisotropy_s2"] = '%12.10f' % (sbart[1])
                        AnisRecT["anisotropy_s3"] = '%12.10f' % (sbart[2])
                        AnisRecT["anisotropy_s4"] = '%12.10f' % (sbart[3])
                        AnisRecT["anisotropy_s5"] = '%12.10f' % (sbart[4])
                        AnisRecT["anisotropy_s6"] = '%12.10f' % (sbart[5])
                        AnisRecT["anisotropy_tilt_correction"] = '100'
                        ResRecT["anisotropy_v1_dec"] = '%7.1f' % (hparst['v1_dec'])
                        ResRecT["anisotropy_v2_dec"] = '%7.1f' % (hparst['v2_dec'])
                        ResRecT["anisotropy_v3_dec"] = '%7.1f' % (hparst['v3_dec'])
                        ResRecT["anisotropy_v1_inc"] = '%7.1f' % (hparst['v1_inc'])
                        ResRecT["anisotropy_v2_inc"] = '%7.1f' % (hparst['v2_inc'])
                        ResRecT["anisotropy_v3_inc"] = '%7.1f' % (hparst['v3_inc'])
                        ResRecT['anisotropy_v1_eta_dec'] = ResRecT['anisotropy_v2_dec']
                        ResRecT['anisotropy_v1_eta_inc'] = ResRecT['anisotropy_v2_inc']
                        ResRecT['anisotropy_v1_zeta_dec'] = ResRecT['anisotropy_v3_dec']
                        ResRecT['anisotropy_v1_zeta_inc'] = ResRecT['anisotropy_v3_inc']
                        ResRecT['anisotropy_v2_eta_dec'] = ResRecT['anisotropy_v1_dec']
                        ResRecT['anisotropy_v2_eta_inc'] = ResRecT['anisotropy_v1_inc']
                        ResRecT['anisotropy_v2_zeta_dec'] = ResRecT['anisotropy_v3_dec']
                        ResRecT['anisotropy_v2_zeta_inc'] = ResRecT['anisotropy_v3_inc']
                        ResRecT['anisotropy_v3_eta_dec'] = ResRecT['anisotropy_v1_dec']
                        ResRecT['anisotropy_v3_eta_inc'] = ResRecT['anisotropy_v1_inc']
                        ResRecT['anisotropy_v3_zeta_dec'] = ResRecT['anisotropy_v2_dec']
                        ResRecT['anisotropy_v3_zeta_inc'] = ResRecT['anisotropy_v2_inc']
                    #
                    ResRecT[aniso_tilt_corr_col] = '100'
                    ResRecT[result_description_col] = 'Critical F: ' + \
                        hparst["F_crit"] + ';Critical F12/F13: ' + \
                        hparst["F12_crit"]
                    ResRecs.append(ResRecT)
                    AnisRecs.append(AnisRecT)
                k15, linecnt = [], 0
                MeasRec, SpecRec, SampRec, SiteRec, AnisRec = {}, {}, {}, {}, {}

    # samples
    pmag.magic_write(samp_file, SampRecs, samp_table_name)
    # specimens / rmag_anisotropy / rmag_results
    if data_model_num == 3:
        AnisRecs.extend(ResRecs)
        SpecRecs = AnisRecs.copy()
        SpecRecs, keys = pmag.fillkeys(SpecRecs)
        pmag.magic_write(aniso_outfile, SpecRecs, 'specimens')
        flist = [meas_file, aniso_outfile, samp_file]
    else:
        pmag.magic_write(aniso_outfile, AnisRecs, 'rmag_anisotropy')  # add to specimens?
        pmag.magic_write(result_file, ResRecs, 'rmag_results') # added to specimens (NOT sites)
        flist = [meas_file, samp_file, aniso_outfile, result_file]
    # measurements
    pmag.magic_write(meas_file, MeasRecs, meas_table_name)

    print("Data saved to: " + ", ".join(flist))
    return True, meas_file

Response: This function converts. k15 format data to MagIC format.


Instruction:
Make a summary of the following Python 3 code
def ldeo(magfile, dir_path=".", input_dir_path="",
         meas_file="measurements.txt", spec_file="specimens.txt",
         samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt",
         specnum=0, samp_con="1", location="unknown", codelist="",
         coil="", arm_labfield=50e-6, trm_peakT=873., peakfield=0,
         labfield=0, phi=0, theta=0, mass_or_vol="v", noave=0):
    """
    converts Lamont Doherty Earth Observatory measurement files to MagIC data base model 3.0

    Parameters
    _________
    magfile : input measurement file
    dir_path : output directory path, default "."
    input_dir_path : input file directory IF different from dir_path, default ""
    meas_file : output file measurement file name, default "measurements.txt"
    spec_file : output file specimen file name, default "specimens.txt"
    samp_file : output file sample file name, default "samples.txt"
    site_file : output file site file name, default "sites.txt"
    loc_file : output file location file name, default "locations.txt"
    specnum : number of terminal characters distinguishing specimen from sample, default 0
    samp_con :  sample/site naming convention, default "1"
            "1" XXXXY: where XXXX is an arbitr[ary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            "2" XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            "3" XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            "4-Z" XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            "5" site name same as sample
            "6" site is entered under a separate column NOT CURRENTLY SUPPORTED
            "7-Z" [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail ltauxe@ucsd.edu for help.

            "8" synthetic - has no site name
            "9" ODP naming convention

    codelist : colon delimited string of lab protocols (e.g., codelist="AF"), default ""
        AF:  af demag
        T: thermal including thellier but not trm acquisition
        S: Shaw method
        I: IRM (acquisition)
        N: NRM only
        TRM: trm acquisition
        ANI: anisotropy experiment
        D: double AF demag
        G: triple AF demag (GRM protocol)
    coil : 1,2, or 3 unist of IRM field in volts using ASC coil #1,2 or 3, default ""
    arm_labfield : dc field for ARM in tesla, default 50e-6
    peakfield : peak af field for ARM, default 873.
    trm_peakT : peak temperature for TRM, default 0
    labfield : lab field in tesla for TRM, default 0
    phi, theta : direction of lab field, default 0, 0
    mass_or_vol : is the parameter in the file mass 'm' or volume 'v', default "v"
    noave : boolean, if False, average replicates, default False

    Returns
    --------
    type - Tuple : (True or False indicating if conversion was sucessful, meas_file name written)

    Effects
    _______
    creates MagIC formatted tables
    """
    # initialize some stuff
    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]
    tdec = [0, 90, 0, 180, 270, 0, 0, 90, 0]
    tinc = [0, 0, 90, 0, 0, -90, 0, 0, 90]
    demag = "N"
    trm = 0
    irm = 0

    # format/organize variables
    input_dir_path, output_dir_path = pmag.fix_directories(input_dir_path, dir_path)
    labfield = int(labfield) * 1e-6
    phi = int(phi)
    theta = int(theta)
    specnum = - int(specnum)

    if magfile:
        try:
            fname = pmag.resolve_file_name(magfile, input_dir_path)
            infile = open(fname, 'r')
        except IOError:
            print("bad mag file name")
            return False, "bad mag file name"
    else:
        print("mag_file field is required option")
        return False, "mag_file field is required option"

    samp_con = str(samp_con)
    if "4" in samp_con:
        if "-" not in samp_con:
            print(
                "naming convention option [4] must be in form 4-Z where Z is an integer")
            return False, "naming convention option [4] must be in form 4-Z where Z is an integer"
        else:
            Z = samp_con.split("-")[1]
            samp_con = "4"
    elif "7" in samp_con:
        if "-" not in samp_con:
            print(
                "naming convention option [7] must be in form 7-Z where Z is an integer")
            return False, "naming convention option [7] must be in form 7-Z where Z is an integer"
        else:
            Z = samp_con.split("-")[1]
            samp_con = "4"
    else:
        Z = 1

    codes = codelist.split(':')
    if "AF" in codes:
        demag = 'AF'
        if not labfield:
            methcode = "LT-AF-Z"
        if labfield:
            methcode = "LT-AF-I"
    if "T" in codes:
        demag = "T"
        if not labfield:
            methcode = "LT-T-Z"
        if labfield:
            methcode = "LT-T-I"
    if "I" in codes:
        methcode = "LP-IRM"
        irmunits = "mT"
    if "S" in codes:
        demag = "S"
        methcode = "LP-PI-TRM:LP-PI-ALT-AFARM"
        trm_labfield = labfield
        # should use arm_labfield and trm_peakT as well, but these values are currently never asked for
    if "G" in codes:
        methcode = "LT-AF-G"
    if "D" in codes:
        methcode = "LT-AF-D"
    if "TRM" in codes:
        demag = "T"
        trm = 1

    if coil:
        methcode = "LP-IRM"
        irmunits = "V"
        if coil not in ["1", "2", "3"]:
            print('not a valid coil specification')
            return False, 'not a valid coil specification'

    if demag == "T" and "ANI" in codes:
        methcode = "LP-AN-TRM"
    if demag == "AF" and "ANI" in codes:
        methcode = "LP-AN-ARM"
        if labfield == 0:
            labfield = 50e-6
        if peakfield == 0:
            peakfield = .180
    MeasRecs, SpecRecs, SampRecs, SiteRecs, LocRecs = [], [], [], [], []
    version_num = pmag.get_version()
    # find start of data:
    DIspec = []
    Data = infile.readlines()
    infile.close()
    for k in range(len(Data)):
        rec = Data[k].split()
        if len(rec) <= 2:
            continue
        if rec[0].upper() == "LAT:" and len(rec) > 3:
            lat, lon = rec[1], rec[3]
            continue
        elif rec[0].upper() == "ID":
            continue
        MeasRec, SpecRec, SampRec, SiteRec, LocRec = {}, {}, {}, {}, {}
        specimen = rec[0]
        if specnum != 0:
            sample = specimen[:specnum]
        else:
            sample = specimen
        site = pmag.parse_site(sample, samp_con, Z)
        if mass_or_vol == 'v':
            volume = float(rec[12])
            if volume > 0:
                # convert to SI (assume Bartington, 10-5 SI)
                susc_chi_volume = '%10.3e' % (
                    float(rec[11])*1e-5) / volume
            else:
                # convert to SI (assume Bartington, 10-5 SI)
                susc_chi_volume = '%10.3e' % (float(rec[11])*1e-5)
        else:
            mass = float(rec[12])
            if mass > 0:
                # convert to SI (assume Bartington, 10-5 SI)
                susc_chi_mass = '%10.3e' % (
                    float(rec[11])*1e-5) / mass
            else:
                # convert to SI (assume Bartington, 10-5 SI)
                susc_chi_mass = '%10.3e' % (float(rec[11])*1e-5)
        # print((specimen,sample,site,samp_con,Z))

        # fill tables besides measurements
        if specimen != "" and specimen not in [x['specimen'] if 'specimen' in list(x.keys()) else "" for x in SpecRecs]:
            SpecRec['specimen'] = specimen
            SpecRec['sample'] = sample
            if mass_or_vol == 'v':
                SpecRec["susc_chi_volume"] = susc_chi_volume
                SpecRec["volume"] = volume
            else:
                SpecRec["susc_chi_mass"] = susc_chi_mass
                SpecRec["magn_mass"] = mass
            SpecRecs.append(SpecRec)
        if sample != "" and sample not in [x['sample'] if 'sample' in list(x.keys()) else "" for x in SampRecs]:
            SampRec['sample'] = sample
            SampRec['site'] = site
            SampRecs.append(SampRec)
        if site != "" and site not in [x['site'] if 'site' in list(x.keys()) else "" for x in SiteRecs]:
            SiteRec['site'] = site
            SiteRec['location'] = location
            SiteRec['lat'] = lat
            SiteRec['lon'] = lon
            SiteRecs.append(SiteRec)
        if location != "" and location not in [x['location'] if 'location' in list(x.keys()) else "" for x in LocRecs]:
            LocRec['location'] = location
            LocRec['lat_n'] = lat
            LocRec['lon_e'] = lon
            LocRec['lat_s'] = lat
            LocRec['lon_w'] = lon
            LocRecs.append(LocRec)

        # fill measurements
        MeasRec["treat_temp"] = '%8.3e' % (273)  # room temp in kelvin
        MeasRec["meas_temp"] = '%8.3e' % (273)  # room temp in kelvin
        MeasRec["treat_ac_field"] = '0'
        MeasRec["treat_dc_field"] = '0'
        MeasRec["treat_dc_field_phi"] = '0'
        MeasRec["treat_dc_field_theta"] = '0'
        meas_type = "LT-NO"
        MeasRec["quality"] = 'g'
        MeasRec["standard"] = 'u'
        MeasRec["treat_step_num"] = 0
        MeasRec["specimen"] = specimen
#        if mass_or_vol=='v': MeasRec["susc_chi_volume"]=susc_chi_volume
#        else: MeasRec["susc_chi_mass"]=susc_chi_mass
        try:
            float(rec[3])
            MeasRec["dir_csd"] = rec[3]
        except ValueError:
            MeasRec["dir_csd"] = ''
        MeasRec["magn_moment"] = '%10.3e' % (float(rec[4])*1e-7)
        MeasRec["dir_dec"] = rec[5]
        MeasRec["dir_inc"] = rec[6]
        MeasRec["citations"] = "This study"
        if demag == "AF":
            if methcode != "LP-AN-ARM":
                MeasRec["treat_ac_field"] = '%8.3e' % (
                    float(rec[1])*1e-3)  # peak field in tesla
                meas_type = "LT-AF-Z"
                MeasRec["treat_dc_field"] = '0'
            else:  # AARM experiment
                if treat[1][0] == '0':
                    meas_type = "LT-AF-Z"
                    MeasRec["treat_ac_field"] = '%8.3e' % (
                        peakfield)  # peak field in tesla
                else:
                    meas_type = "LT-AF-I"
                    ipos = int(treat[0])-1
                    MeasRec["treat_dc_field_phi"] = '%7.1f' % (dec[ipos])
                    MeasRec["treat_dc_field_theta"] = '%7.1f' % (inc[ipos])
                    MeasRec["treat_dc_field"] = '%8.3e' % (labfield)
                    MeasRec["treat_ac_field"] = '%8.3e' % (
                        peakfield)  # peak field in tesla
        elif demag == "T":
            if rec[1][0] == ".":
                rec[1] = "0"+rec[1]
            treat = rec[1].split('.')
            if len(treat) == 1:
                treat.append('0')
            MeasRec["treat_temp"] = '%8.3e' % (
                float(rec[1])+273.)  # temp in kelvin
            meas_type = "LT-T-Z"
            MeasRec["treat_temp"] = '%8.3e' % (
                float(treat[0])+273.)  # temp in kelvin
            if trm == 0:  # demag=T and not trmaq
                if treat[1][0] == '0':
                    meas_type = "LT-T-Z"
                else:
                    # labfield in tesla (convert from microT)
                    MeasRec["treat_dc_field"] = '%8.3e' % (labfield)
                    MeasRec["treat_dc_field_phi"] = '%7.1f' % (
                        phi)  # labfield phi
                    MeasRec["treat_dc_field_theta"] = '%7.1f' % (
                        theta)  # labfield theta
                    if treat[1][0] == '1':
                        meas_type = "LT-T-I"  # in-field thermal step
                    if treat[1][0] == '2':
                        meas_type = "LT-PTRM-I"  # pTRM check
                        pTRM = 1
                    if treat[1][0] == '3':
                        # this is a zero field step
                        MeasRec["treat_dc_field"] = '0'
                        meas_type = "LT-PTRM-MD"  # pTRM tail check
            else:
                meas_type = "LT-T-I"  # trm acquisition experiment
        MeasRec['method_codes'] = meas_type
        MeasRecs.append(MeasRec)
    # need to add these
    meas_file = pmag.resolve_file_name(meas_file, output_dir_path)
    spec_file = pmag.resolve_file_name(spec_file, output_dir_path)
    samp_file = pmag.resolve_file_name(samp_file, output_dir_path)
    site_file = pmag.resolve_file_name(site_file, output_dir_path)
    loc_file = pmag.resolve_file_name(loc_file, output_dir_path)

    con = cb.Contribution(output_dir_path, read_tables=[])

    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)
    con.add_magic_table_from_data(dtype='measurements', data=MeasOuts)

    con.tables['specimens'].write_magic_file(custom_name=spec_file)
    con.tables['samples'].write_magic_file(custom_name=samp_file)
    con.tables['sites'].write_magic_file(custom_name=site_file)
    con.tables['locations'].write_magic_file(custom_name=loc_file)
    con.tables['measurements'].write_magic_file(custom_name=meas_file)

    return True, meas_file

Response: This function converts a Lamont Doherty Earth Observatory measurement file to MagIC data base model 3. 0.


Instruction:
Can you tell what is the following Python 3 function doing
def mini(magfile, dir_path='.', meas_file='measurements.txt',
         data_model_num=3, volume=12, noave=0,
         inst="", user="", methcode="LP-NO", input_dir_path=""):
    """
    Convert the Yale minispin format to MagIC format files

    Parameters
    ----------
    magfile : str
        input file name, required
    dir_path : str
        working directory, default "."
    meas_file : str
        output measurement file name, default "measurements.txt"
    data_model_num : int
        MagIC data model 2 or 3, default 3
    volume : float
        volume in ccs, default 12.
    noave : bool
       do not average duplicate measurements, default False (so by default, DO average)
    inst : str
        instrument, default ""
    user : str
        user name, default ""
    methcode : str
        colon-delimited protocols, include all that apply
        default "LP-NO"
        options include "AF" for demag and "T" for thermal
    input_dir_path : str,
        input file directory IF different from dir_path, default ""

    Returns
    ---------
    Tuple : (True or False indicating if conversion was sucessful, meas_file name written)

    """

    codes = methcode.split(':')
    demag = "N"
    if "AF" in codes:
        demag = 'AF'
        methcode = "LT-AF-Z"
    if "T" in codes:
        demag = "T"
        methcode = "LP-TRM-TD"

    # initialize
    citation = 'This study'
    MagRecs = []
    version_num = pmag.get_version()
    input_dir_path, dir_path = pmag.fix_directories(input_dir_path, dir_path)
    magfile = pmag.resolve_file_name(magfile, input_dir_path)
    input_dir_path = os.path.split(magfile)[0]
    try:
        with open(magfile, 'r') as finput:
            lines = finput.readlines()
    except OSError:
        print("bad mag file name")
        return False, "bad mag file name"
    # convert volume
    volume = 1e-6 * float(volume)
    # set col names based on MagIC 2 or 3
    if data_model_num == 2:
        spec_col = "er_specimen_name"
        loc_col = "er_location_name"
        site_col = "er_site_col"
        samp_col = "er_sample_name"
        software_col = "magic_software_packages"
        treat_temp_col = "treatment_temp"
        meas_temp_col = "measurement_temp"
        treat_ac_col = "treatment_ac_field"
        treat_dc_col = "treatment_dc_field"
        treat_dc_phi_col = "treatment_dc_field_phi"
        treat_dc_theta_col = "treatment_dc_field_theta"
        moment_col = "measurement_magn_moment"
        dec_col = "measurement_dec"
        inc_col = "measurement_inc"
        instrument_col = "magic_instrument_codes"
        analyst_col = "er_analyst_mail_names"
        citations_col = "er_citation_names"
        methods_col = "magic_method_codes"
        quality_col = "measurement_flag"
        meas_standard_col = "measurement_standard"
        meas_name_col = "measurement_number"
    else:
        spec_col = "specimen"
        loc_col = "location"
        site_col = "site"
        samp_col = "sample"
        software_col = "software_packages"
        treat_temp_col = "treat_temp"
        meas_temp_col = "meas_temp"
        treat_ac_col = "treat_ac_field"
        treat_dc_col = "treat_dc_field"
        treat_dc_phi_col = "treat_dc_field_phi"
        treat_dc_theta_col = "treat_dc_field_theta"
        moment_col = "magn_moment"
        dec_col = "dir_dec"
        inc_col = "dir_inc"
        instrument_col = "instrument_codes"
        analyst_col = "analysts"
        citations_col = "citations"
        methods_col = "method_codes"
        quality_col = "quality"
        meas_standard_col = "standard"
        meas_name_col = "experiment"
        meas_seq_col = "sequence"

    # go through the measurements
    seq=1
    for line in lines:
        rec = line.split(',')
        if len(rec) > 1:
            MagRec = {}
            IDs = rec[0].split('_')
            treat = IDs[1]
            MagRec[spec_col] = IDs[0]
            # print(MagRec[spec_col])
            sids = IDs[0].split('-')
            MagRec[loc_col] = sids[0]
            MagRec[site_col] = sids[0]+'-'+sids[1]
            if len(sids) == 2:
                MagRec[samp_col] = IDs[0]
            else:
                MagRec[samp_col] = sids[0]+'-'+sids[1]+'-'+sids[2]
            # print(MagRec)
            MagRec[software_col] = version_num
            MagRec[treat_temp_col] = '%8.3e' % (273)  # room temp in kelvin
            MagRec[meas_temp_col] = '%8.3e' % (273)  # room temp in kelvin
            MagRec[treat_ac_col] = '0'
            MagRec[treat_dc_col] = '0'
            MagRec[treat_dc_phi_col] = '0'
            MagRec[treat_dc_theta_col] = '0'
            meas_type = "LT-NO"
            if demag == "AF":
                MagRec[treat_ac_col] = '%8.3e' % (
                    float(treat)*1e-3)  # peak field in tesla
            if demag == "T":
                meas_type = "LT-T-Z"
                MagRec[treat_dc_col] = '%8.3e' % (0)
                MagRec[treat_ac_col] = '0'
                MagRec[treat_temp_col] = '%8.3e' % (
                    float(treat)+273.)  # temp in kelvin
            if demag == "N":
                meas_type = "LT-NO"
                MagRec[treat_ac_col] = '0'
                MagRec[treat_dc_col] = '0'
            MagRec[moment_col] = '%10.3e' % (
                volume*float(rec[3])*1e-3)  # moment in Am2 (from mA/m)
            MagRec[dec_col] = rec[1]
            MagRec[inc_col] = rec[2]
            MagRec[instrument_col] = inst
            MagRec[analyst_col] = user
            MagRec[citations_col] = citation
            MagRec[methods_col] = methcode.strip(':')
            MagRec[quality_col] = 'g'
            MagRec[meas_standard_col] = 'u'
            MagRec[meas_name_col] = '1'
            MagRecs.append(MagRec)

    if data_model_num == 2:
        MagOuts = pmag.measurements_methods(MagRecs, noave)
        pmag.magic_write(meas_file, MagOuts, 'magic_measurements')
    else:
        MagOuts = pmag.measurements_methods3(MagRecs, noave)
        pmag.magic_write(meas_file, MagOuts, 'measurements')
        # nicely parse all the specimen/sample/site/location data
        # and write it to file as well
        dir_path = os.path.split(meas_file)[0]
        con = cb.Contribution(dir_path, read_tables=['measurements'],
                              custom_filenames={'measurements': meas_file})
        con.propagate_measurement_info()
        for table in con.tables:
            con.write_table_to_file(table)
    print("results put in ", meas_file)
    return True, meas_file

Response: Convert the Yale minispin format to MagIC format files.