Instruction:
Can you generate a brief explanation for the following Python 3 code
def specimens_results_magic(infile='pmag_specimens.txt', measfile='magic_measurements.txt', sampfile='er_samples.txt', sitefile='er_sites.txt', agefile='er_ages.txt', specout='er_specimens.txt', sampout='pmag_samples.txt', siteout='pmag_sites.txt', resout='pmag_results.txt', critout='pmag_criteria.txt', instout='magic_instruments.txt', plotsites=False, fmt='svg', dir_path='.', cors=[], priorities=['DA-AC-ARM', 'DA-AC-TRM'], coord='g', user='', vgps_level='site', do_site_intensity=True, DefaultAge=["none"], avg_directions_by_sample=False, avg_intensities_by_sample=False, avg_all_components=False, avg_by_polarity=False, skip_directions=False, skip_intensities=False, use_sample_latitude=False, use_paleolatitude=False, use_criteria='default'):
    # initialize some variables
    plotsites = False  # cannot use draw_figs from within ipmag
    Comps = []  # list of components
    version_num = pmag.get_version()
    args = sys.argv
    model_lat_file = ""
    Dcrit, Icrit, nocrit = 0, 0, 0
    corrections = []
    nocorrection = ['DA-NL', 'DA-AC', 'DA-CR']

    # do some data adjustments
    for cor in cors:
        nocorrection.remove('DA-' + cor)
        corrections.append('DA-' + cor)

    for p in priorities:
        if not p.startswith('DA-AC-'):
            p = 'DA-AC-' + p

    # translate coord into coords
    if coord == 's':
        coords = ['-1']
    if coord == 'g':
        coords = ['0']
    if coord == 't':
        coords = ['100']
    if coord == 'b':
        coords = ['0', '100']

    if vgps_level == 'sample':
        vgps = 1  # save sample level VGPS/VADMs
    else:
        vgps = 0  # site level

    if do_site_intensity:
        nositeints = 0
    else:
        nositeints = 1

    # chagne these all to True/False instead of 1/0

    if not skip_intensities:
        # set model lat and
        if use_sample_latitude and use_paleolatitude:
            print("you should set a paleolatitude file OR use present day lat - not both")
            return False
        elif use_sample_latitude:
            get_model_lat = 1
        elif use_paleolatitude:
            get_model_lat = 2
            try:
                model_lat_file = dir_path + '/' + args[ind + 1]
                get_model_lat = 2
                mlat = open(model_lat_file, 'r')
                ModelLats = []
                for line in mlat.readlines():
                    ModelLat = {}
                    tmp = line.split()
                    ModelLat["er_site_name"] = tmp[0]
                    ModelLat["site_model_lat"] = tmp[1]
                    ModelLat["er_sample_name"] = tmp[0]
                    ModelLat["sample_lat"] = tmp[1]
                    ModelLats.append(ModelLat)
                mlat.clos()
            except:
                print("use_paleolatitude option requires a valid paleolatitude file")
        else:
            get_model_lat = 0  # skips VADM calculation entirely

    if plotsites and not skip_directions:  # plot by site - set up plot window
        EQ = {}
        EQ['eqarea'] = 1
        # define figure 1 as equal area projection
        pmagplotlib.plot_init(EQ['eqarea'], 5, 5)
        # I don't know why this has to be here, but otherwise the first plot
        # never plots...
        pmagplotlib.plot_net(EQ['eqarea'])
        pmagplotlib.draw_figs(EQ)

    infile = os.path.join(dir_path, infile)
    measfile = os.path.join(dir_path, measfile)
    instout = os.path.join(dir_path, instout)
    sampfile = os.path.join(dir_path, sampfile)
    sitefile = os.path.join(dir_path, sitefile)
    agefile = os.path.join(dir_path, agefile)
    specout = os.path.join(dir_path, specout)
    sampout = os.path.join(dir_path, sampout)
    siteout = os.path.join(dir_path, siteout)
    resout = os.path.join(dir_path, resout)
    critout = os.path.join(dir_path, critout)

    if use_criteria == 'none':
        Dcrit, Icrit, nocrit = 1, 1, 1  # no selection criteria
        crit_data = pmag.default_criteria(nocrit)
    elif use_criteria == 'default':
        crit_data = pmag.default_criteria(nocrit)  # use default criteria
    elif use_criteria == 'existing':
        crit_data, file_type = pmag.magic_read(
            critout)  # use pmag_criteria file
        print("Acceptance criteria read in from ", critout)
    accept = {}
    for critrec in crit_data:
        for key in list(critrec.keys()):
            # need to migrate specimen_dang to specimen_int_dang for intensity
            # data using old format
            if 'IE-SPEC' in list(critrec.keys()) and 'specimen_dang' in list(critrec.keys()) and 'specimen_int_dang' not in list(critrec.keys()):
                critrec['specimen_int_dang'] = critrec['specimen_dang']
                del critrec['specimen_dang']
# need to get rid of ron shaars sample_int_sigma_uT
            if 'sample_int_sigma_uT' in list(critrec.keys()):
                critrec['sample_int_sigma'] = '%10.3e' % (
                    eval(critrec['sample_int_sigma_uT']) * 1e-6)
            if key not in list(accept.keys()) and critrec[key] != '':
                accept[key] = critrec[key]

    if use_criteria == 'default':
        pmag.magic_write(critout, [accept], 'pmag_criteria')
        print("\n Pmag Criteria stored in ", critout, '\n')

# now we're done slow dancing

    # read in site data - has the lats and lons
    SiteNFO, file_type = pmag.magic_read(sitefile)
    # read in site data - has the lats and lons
    SampNFO, file_type = pmag.magic_read(sampfile)
    # find all the sites with height info.
    height_nfo = pmag.get_dictitem(SiteNFO, 'site_height', '', 'F')
    if agefile:
        AgeNFO, file_type = pmag.magic_read(
            agefile)  # read in the age information
    # read in specimen interpretations
    Data, file_type = pmag.magic_read(infile)
    # retrieve specimens with intensity data
    IntData = pmag.get_dictitem(Data, 'specimen_int', '', 'F')
    comment, orient = "", []
    samples, sites = [], []
    for rec in Data:  # run through the data filling in missing keys and finding all components, coordinates available
        # fill in missing fields, collect unique sample and site names
        if 'er_sample_name' not in list(rec.keys()):
            rec['er_sample_name'] = ""
        elif rec['er_sample_name'] not in samples:
            samples.append(rec['er_sample_name'])
        if 'er_site_name' not in list(rec.keys()):
            rec['er_site_name'] = ""
        elif rec['er_site_name'] not in sites:
            sites.append(rec['er_site_name'])
        if 'specimen_int' not in list(rec.keys()):
            rec['specimen_int'] = ''
        if 'specimen_comp_name' not in list(rec.keys()) or rec['specimen_comp_name'] == "":
            rec['specimen_comp_name'] = 'A'
        if rec['specimen_comp_name'] not in Comps:
            Comps.append(rec['specimen_comp_name'])
        rec['specimen_tilt_correction'] = rec['specimen_tilt_correction'].strip(
            '\n')
        if "specimen_tilt_correction" not in list(rec.keys()):
            rec["specimen_tilt_correction"] = "-1"  # assume sample coordinates
        if rec["specimen_tilt_correction"] not in orient:
            # collect available coordinate systems
            orient.append(rec["specimen_tilt_correction"])
        if "specimen_direction_type" not in list(rec.keys()):
            # assume direction is line - not plane
            rec["specimen_direction_type"] = 'l'
        if "specimen_dec" not in list(rec.keys()):
            # if no declination, set direction type to blank
            rec["specimen_direction_type"] = ''
        if "specimen_n" not in list(rec.keys()):
            rec["specimen_n"] = ''  # put in n
        if "specimen_alpha95" not in list(rec.keys()):
            rec["specimen_alpha95"] = ''  # put in alpha95
        if "magic_method_codes" not in list(rec.keys()):
            rec["magic_method_codes"] = ''
     # start parsing data into SpecDirs, SpecPlanes, SpecInts
    SpecInts, SpecDirs, SpecPlanes = [], [], []
    samples.sort()  # get sorted list of samples and sites
    sites.sort()
    if not skip_intensities:  # don't skip intensities
        # retrieve specimens with intensity data
        IntData = pmag.get_dictitem(Data, 'specimen_int', '', 'F')
        if nocrit == 0:  # use selection criteria
            for rec in IntData:  # do selection criteria
                kill = pmag.grade(rec, accept, 'specimen_int')
                if len(kill) == 0:
                    # intensity record to be included in sample, site
                    # calculations
                    SpecInts.append(rec)
        else:
            SpecInts = IntData[:]  # take everything - no selection criteria
# check for required data adjustments
        if len(corrections) > 0 and len(SpecInts) > 0:
            for cor in corrections:
                # only take specimens with the required corrections
                SpecInts = pmag.get_dictitem(
                    SpecInts, 'magic_method_codes', cor, 'has')
        if len(nocorrection) > 0 and len(SpecInts) > 0:
            for cor in nocorrection:
                # exclude the corrections not specified for inclusion
                SpecInts = pmag.get_dictitem(
                    SpecInts, 'magic_method_codes', cor, 'not')
# take top priority specimen of its name in remaining specimens (only one
# per customer)
        PrioritySpecInts = []
        specimens = pmag.get_specs(SpecInts)  # get list of uniq specimen names
        for spec in specimens:
            # all the records for this specimen
            ThisSpecRecs = pmag.get_dictitem(
                SpecInts, 'er_specimen_name', spec, 'T')
            if len(ThisSpecRecs) == 1:
                PrioritySpecInts.append(ThisSpecRecs[0])
            elif len(ThisSpecRecs) > 1:  # more than one
                prec = []
                for p in priorities:
                    # all the records for this specimen
                    ThisSpecRecs = pmag.get_dictitem(
                        SpecInts, 'magic_method_codes', p, 'has')
                    if len(ThisSpecRecs) > 0:
                        prec.append(ThisSpecRecs[0])
                PrioritySpecInts.append(prec[0])  # take the best one
        SpecInts = PrioritySpecInts  # this has the first specimen record
    if not skip_directions:  # don't skip directions
        # retrieve specimens with directed lines and planes
        AllDirs = pmag.get_dictitem(Data, 'specimen_direction_type', '', 'F')
        # get all specimens with specimen_n information
        Ns = pmag.get_dictitem(AllDirs, 'specimen_n', '', 'F')
        if nocrit != 1:  # use selection criteria
            for rec in Ns:  # look through everything with specimen_n for "good" data
                kill = pmag.grade(rec, accept, 'specimen_dir')
                if len(kill) == 0:  # nothing killed it
                    SpecDirs.append(rec)
        else:  # no criteria
            SpecDirs = AllDirs[:]  # take them all
# SpecDirs is now the list of all specimen directions (lines and planes)
# that pass muster
    # list of all sample data and list of those that pass the DE-SAMP criteria
    PmagSamps, SampDirs = [], []
    PmagSites, PmagResults = [], []  # list of all site data and selected results
    SampInts = []
    for samp in samples:  # run through the sample names
        if avg_directions_by_sample:  # average by sample if desired
            # get all the directional data for this sample
            SampDir = pmag.get_dictitem(SpecDirs, 'er_sample_name', samp, 'T')
            if len(SampDir) > 0:  # there are some directions
                for coord in coords:  # step through desired coordinate systems
                    # get all the directions for this sample
                    CoordDir = pmag.get_dictitem(
                        SampDir, 'specimen_tilt_correction', coord, 'T')
                    if len(CoordDir) > 0:  # there are some with this coordinate system
                        if not avg_all_components:  # look component by component
                            for comp in Comps:
                                # get all directions from this component
                                CompDir = pmag.get_dictitem(
                                    CoordDir, 'specimen_comp_name', comp, 'T')
                                if len(CompDir) > 0:  # there are some
                                    # get a sample average from all specimens
                                    PmagSampRec = pmag.lnpbykey(
                                        CompDir, 'sample', 'specimen')
                                    # decorate the sample record
                                    PmagSampRec["er_location_name"] = CompDir[0]['er_location_name']
                                    PmagSampRec["er_site_name"] = CompDir[0]['er_site_name']
                                    PmagSampRec["er_sample_name"] = samp
                                    PmagSampRec["er_citation_names"] = "This study"
                                    PmagSampRec["er_analyst_mail_names"] = user
                                    PmagSampRec['magic_software_packages'] = version_num
                                    if CompDir[0]['specimen_flag'] == 'g':
                                        PmagSampRec['sample_flag'] = 'g'
                                    else:
                                        PmagSampRec['sample_flag'] = 'b'
                                    if nocrit != 1:
                                        PmagSampRec['pmag_criteria_codes'] = "ACCEPT"
                                    if agefile != "":
                                        PmagSampRec = pmag.get_age(
                                            PmagSampRec, "er_site_name", "sample_inferred_", AgeNFO, DefaultAge)
                                    site_height = pmag.get_dictitem(
                                        height_nfo, 'er_site_name', PmagSampRec['er_site_name'], 'T')
                                    if len(site_height) > 0:
                                        # add in height if available
                                        PmagSampRec["sample_height"] = site_height[0]['site_height']
                                    PmagSampRec['sample_comp_name'] = comp
                                    PmagSampRec['sample_tilt_correction'] = coord
                                    PmagSampRec['er_specimen_names'] = pmag.get_list(
                                        CompDir, 'er_specimen_name')  # get a list of the specimen names used
                                    PmagSampRec['magic_method_codes'] = pmag.get_list(
                                        CompDir, 'magic_method_codes')  # get a list of the methods used
                                    if nocrit != 1:  # apply selection criteria
                                        kill = pmag.grade(
                                            PmagSampRec, accept, 'sample_dir')
                                    else:
                                        kill = []
                                    if len(kill) == 0:
                                        SampDirs.append(PmagSampRec)
                                        if vgps == 1:  # if sample level VGP info desired, do that now
                                            PmagResRec = pmag.getsampVGP(
                                                PmagSampRec, SiteNFO)
                                            if PmagResRec != "":
                                                PmagResults.append(PmagResRec)
#                                   print(PmagSampRec)
                                    PmagSamps.append(PmagSampRec)
                        if avg_all_components:  # average all components together  basically same as above
                            PmagSampRec = pmag.lnpbykey(
                                CoordDir, 'sample', 'specimen')
                            PmagSampRec["er_location_name"] = CoordDir[0]['er_location_name']
                            PmagSampRec["er_site_name"] = CoordDir[0]['er_site_name']
                            PmagSampRec["er_sample_name"] = samp
                            PmagSampRec["er_citation_names"] = "This study"
                            PmagSampRec["er_analyst_mail_names"] = user
                            PmagSampRec['magic_software_packages'] = version_num
                            if all(i['specimen_flag'] == 'g' for i in CoordDir):
                                PmagSampRec['sample_flag'] = 'g'
                            else:
                                PmagSampRec['sample_flag'] = 'b'
                            if nocrit != 1:
                                PmagSampRec['pmag_criteria_codes'] = ""
                            if agefile != "":
                                PmagSampRec = pmag.get_age(
                                    PmagSampRec, "er_site_name", "sample_inferred_", AgeNFO, DefaultAge)
                            site_height = pmag.get_dictitem(
                                height_nfo, 'er_site_name', site, 'T')
                            if len(site_height) > 0:
                                # add in height if available
                                PmagSampRec["sample_height"] = site_height[0]['site_height']
                            PmagSampRec['sample_tilt_correction'] = coord
                            PmagSampRec['sample_comp_name'] = pmag.get_list(
                                CoordDir, 'specimen_comp_name')  # get components used
                            PmagSampRec['er_specimen_names'] = pmag.get_list(
                                CoordDir, 'er_specimen_name')  # get specimne names averaged
                            PmagSampRec['magic_method_codes'] = pmag.get_list(
                                CoordDir, 'magic_method_codes')  # assemble method codes
                            if nocrit != 1:  # apply selection criteria
                                kill = pmag.grade(
                                    PmagSampRec, accept, 'sample_dir')
                                if len(kill) == 0:  # passes the mustard
                                    SampDirs.append(PmagSampRec)
                                    if vgps == 1:
                                        PmagResRec = pmag.getsampVGP(
                                            PmagSampRec, SiteNFO)
                                        if PmagResRec != "":
                                            PmagResults.append(PmagResRec)
                            else:  # take everything
                                SampDirs.append(PmagSampRec)
                                if vgps == 1:
                                    PmagResRec = pmag.getsampVGP(
                                        PmagSampRec, SiteNFO)
                                    if PmagResRec != "":
                                        PmagResults.append(PmagResRec)
                            PmagSamps.append(PmagSampRec)
        if avg_intensities_by_sample:  # average by sample if desired
            # get all the intensity data for this sample
            SampI = pmag.get_dictitem(SpecInts, 'er_sample_name', samp, 'T')
            if len(SampI) > 0:  # there are some
                # get average intensity stuff
                PmagSampRec = pmag.average_int(SampI, 'specimen', 'sample')
                # decorate sample record
                PmagSampRec["sample_description"] = "sample intensity"
                PmagSampRec["sample_direction_type"] = ""
                PmagSampRec['er_site_name'] = SampI[0]["er_site_name"]
                PmagSampRec['er_sample_name'] = samp
                PmagSampRec['er_location_name'] = SampI[0]["er_location_name"]
                PmagSampRec["er_citation_names"] = "This study"
                PmagSampRec["er_analyst_mail_names"] = user
                if agefile != "":
                    PmagSampRec = pmag.get_age(
                        PmagSampRec, "er_site_name", "sample_inferred_", AgeNFO, DefaultAge)
                site_height = pmag.get_dictitem(
                    height_nfo, 'er_site_name', PmagSampRec['er_site_name'], 'T')
                if len(site_height) > 0:
                    # add in height if available
                    PmagSampRec["sample_height"] = site_height[0]['site_height']
                PmagSampRec['er_specimen_names'] = pmag.get_list(
                    SampI, 'er_specimen_name')
                PmagSampRec['magic_method_codes'] = pmag.get_list(
                    SampI, 'magic_method_codes')
                if nocrit != 1:  # apply criteria!
                    kill = pmag.grade(PmagSampRec, accept, 'sample_int')
                    if len(kill) == 0:
                        PmagSampRec['pmag_criteria_codes'] = "ACCEPT"
                        SampInts.append(PmagSampRec)
                        PmagSamps.append(PmagSampRec)
                    else:
                        PmagSampRec = {}  # sample rejected
                else:  # no criteria
                    SampInts.append(PmagSampRec)
                    PmagSamps.append(PmagSampRec)
                    PmagSampRec['pmag_criteria_codes'] = ""
                if vgps == 1 and get_model_lat != 0 and PmagSampRec != {}:
                    if get_model_lat == 1:  # use sample latitude
                        PmagResRec = pmag.getsampVDM(PmagSampRec, SampNFO)
                        # get rid of the model lat key
                        del(PmagResRec['model_lat'])
                    elif get_model_lat == 2:  # use model latitude
                        PmagResRec = pmag.getsampVDM(PmagSampRec, ModelLats)
                        if PmagResRec != {}:
                            PmagResRec['magic_method_codes'] = PmagResRec['magic_method_codes'] + ":IE-MLAT"
                    if PmagResRec != {}:
                        PmagResRec['er_specimen_names'] = PmagSampRec['er_specimen_names']
                        PmagResRec['er_sample_names'] = PmagSampRec['er_sample_name']
                        PmagResRec['pmag_criteria_codes'] = 'ACCEPT'
                        PmagResRec['average_int_sigma_perc'] = PmagSampRec['sample_int_sigma_perc']
                        PmagResRec['average_int_sigma'] = PmagSampRec['sample_int_sigma']
                        PmagResRec['average_int_n'] = PmagSampRec['sample_int_n']
                        PmagResRec['vadm_n'] = PmagSampRec['sample_int_n']
                        PmagResRec['data_type'] = 'i'
                        PmagResults.append(PmagResRec)
    if len(PmagSamps) > 0:
        # fill in missing keys from different types of records
        TmpSamps, keylist = pmag.fillkeys(PmagSamps)
        # save in sample output file
        pmag.magic_write(sampout, TmpSamps, 'pmag_samples')
        print(' sample averages written to ', sampout)

#
# create site averages from specimens or samples as specified
#
    for site in sites:
        for coord in coords:
            if not avg_directions_by_sample:
                key, dirlist = 'specimen', SpecDirs  # if specimen averages at site level desired
            if avg_directions_by_sample:
                key, dirlist = 'sample', SampDirs  # if sample averages at site level desired
            # get all the sites with  directions
            tmp = pmag.get_dictitem(dirlist, 'er_site_name', site, 'T')
            # use only the last coordinate if avg_all_components==False
            tmp1 = pmag.get_dictitem(tmp, key + '_tilt_correction', coord, 'T')
            # fish out site information (lat/lon, etc.)
            sd = pmag.get_dictitem(SiteNFO, 'er_site_name', site, 'T')
            if len(sd) > 0:
                sitedat = sd[0]
                if not avg_all_components:  # do component wise averaging
                    for comp in Comps:
                        # get all components comp
                        siteD = pmag.get_dictitem(
                            tmp1, key + '_comp_name', comp, 'T')
                        # remove bad data from means
                        quality_siteD = []
                        # remove any records for which specimen_flag or sample_flag are 'b'
                        # assume 'g' if flag is not provided
                        for rec in siteD:
                            spec_quality = rec.get('specimen_flag', 'g')
                            samp_quality = rec.get('sample_flag', 'g')
                            if (spec_quality == 'g') and (samp_quality == 'g'):
                                quality_siteD.append(rec)
                        siteD = quality_siteD
                        if len(siteD) > 0:  # there are some for this site and component name
                            # get an average for this site
                            PmagSiteRec = pmag.lnpbykey(siteD, 'site', key)
                            # decorate the site record
                            PmagSiteRec['site_comp_name'] = comp
                            PmagSiteRec["er_location_name"] = siteD[0]['er_location_name']
                            PmagSiteRec["er_site_name"] = siteD[0]['er_site_name']
                            PmagSiteRec['site_tilt_correction'] = coord
                            PmagSiteRec['site_comp_name'] = pmag.get_list(
                                siteD, key + '_comp_name')
                            if avg_directions_by_sample:
                                PmagSiteRec['er_sample_names'] = pmag.get_list(
                                    siteD, 'er_sample_name')
                            else:
                                PmagSiteRec['er_specimen_names'] = pmag.get_list(
                                    siteD, 'er_specimen_name')
    # determine the demagnetization code (DC3,4 or 5) for this site
                            AFnum = len(pmag.get_dictitem(
                                siteD, 'magic_method_codes', 'LP-DIR-AF', 'has'))
                            Tnum = len(pmag.get_dictitem(
                                siteD, 'magic_method_codes', 'LP-DIR-T', 'has'))
                            DC = 3
                            if AFnum > 0:
                                DC += 1
                            if Tnum > 0:
                                DC += 1
                            PmagSiteRec['magic_method_codes'] = pmag.get_list(
                                siteD, 'magic_method_codes') + ':' + 'LP-DC' + str(DC)
                            PmagSiteRec['magic_method_codes'].strip(":")
                            if plotsites:
                                print(PmagSiteRec['er_site_name'])
                                # plot and list the data
                                pmagplotlib.plot_site(
                                    EQ['eqarea'], PmagSiteRec, siteD, key)
                                pmagplotlib.draw_figs(EQ)
                            PmagSites.append(PmagSiteRec)
                else:  # last component only
                    # get the last orientation system specified
                    siteD = tmp1[:]
                    if len(siteD) > 0:  # there are some
                        # get the average for this site
                        PmagSiteRec = pmag.lnpbykey(siteD, 'site', key)
                        # decorate the record
                        PmagSiteRec["er_location_name"] = siteD[0]['er_location_name']
                        PmagSiteRec["er_site_name"] = siteD[0]['er_site_name']
                        PmagSiteRec['site_comp_name'] = comp
                        PmagSiteRec['site_tilt_correction'] = coord
                        PmagSiteRec['site_comp_name'] = pmag.get_list(
                            siteD, key + '_comp_name')
                        PmagSiteRec['er_specimen_names'] = pmag.get_list(
                            siteD, 'er_specimen_name')
                        PmagSiteRec['er_sample_names'] = pmag.get_list(
                            siteD, 'er_sample_name')
                        AFnum = len(pmag.get_dictitem(
                            siteD, 'magic_method_codes', 'LP-DIR-AF', 'has'))
                        Tnum = len(pmag.get_dictitem(
                            siteD, 'magic_method_codes', 'LP-DIR-T', 'has'))
                        DC = 3
                        if AFnum > 0:
                            DC += 1
                        if Tnum > 0:
                            DC += 1
                        PmagSiteRec['magic_method_codes'] = pmag.get_list(
                            siteD, 'magic_method_codes') + ':' + 'LP-DC' + str(DC)
                        PmagSiteRec['magic_method_codes'].strip(":")
                        if not avg_directions_by_sample:
                            PmagSiteRec['site_comp_name'] = pmag.get_list(
                                siteD, key + '_comp_name')
                        if plotsites:
                            pmagplotlib.plot_site(
                                EQ['eqarea'], PmagSiteRec, siteD, key)
                            pmagplotlib.draw_figs(EQ)
                        PmagSites.append(PmagSiteRec)
            else:
                print('site information not found in er_sites for site, ',
                      site, ' site will be skipped')
    for PmagSiteRec in PmagSites:  # now decorate each dictionary some more, and calculate VGPs etc. for results table
        PmagSiteRec["er_citation_names"] = "This study"
        PmagSiteRec["er_analyst_mail_names"] = user
        PmagSiteRec['magic_software_packages'] = version_num
        if agefile != "":
            PmagSiteRec = pmag.get_age(
                PmagSiteRec, "er_site_name", "site_inferred_", AgeNFO, DefaultAge)
        PmagSiteRec['pmag_criteria_codes'] = 'ACCEPT'
        if 'site_n_lines' in list(PmagSiteRec.keys()) and 'site_n_planes' in list(PmagSiteRec.keys()) and PmagSiteRec['site_n_lines'] != "" and PmagSiteRec['site_n_planes'] != "":
            if int(PmagSiteRec["site_n_planes"]) > 0:
                PmagSiteRec["magic_method_codes"] = PmagSiteRec['magic_method_codes'] + ":DE-FM-LP"
            elif int(PmagSiteRec["site_n_lines"]) > 2:
                PmagSiteRec["magic_method_codes"] = PmagSiteRec['magic_method_codes'] + ":DE-FM"
            kill = pmag.grade(PmagSiteRec, accept, 'site_dir')
            if len(kill) == 0:
                PmagResRec = {}  # set up dictionary for the pmag_results table entry
                PmagResRec['data_type'] = 'i'  # decorate it a bit
                PmagResRec['magic_software_packages'] = version_num
                PmagSiteRec['site_description'] = 'Site direction included in results table'
                PmagResRec['pmag_criteria_codes'] = 'ACCEPT'
                dec = float(PmagSiteRec["site_dec"])
                inc = float(PmagSiteRec["site_inc"])
                if 'site_alpha95' in list(PmagSiteRec.keys()) and PmagSiteRec['site_alpha95'] != "":
                    a95 = float(PmagSiteRec["site_alpha95"])
                else:
                    a95 = 180.
                sitedat = pmag.get_dictitem(SiteNFO, 'er_site_name', PmagSiteRec['er_site_name'], 'T')[
                    0]  # fish out site information (lat/lon, etc.)
                lat = float(sitedat['site_lat'])
                lon = float(sitedat['site_lon'])
                plon, plat, dp, dm = pmag.dia_vgp(
                    dec, inc, a95, lat, lon)  # get the VGP for this site
                if PmagSiteRec['site_tilt_correction'] == '-1':
                    C = ' (spec coord) '
                if PmagSiteRec['site_tilt_correction'] == '0':
                    C = ' (geog. coord) '
                if PmagSiteRec['site_tilt_correction'] == '100':
                    C = ' (strat. coord) '
                PmagResRec["pmag_result_name"] = "VGP Site: " + \
                    PmagSiteRec["er_site_name"]  # decorate some more
                PmagResRec["result_description"] = "Site VGP, coord system = " + \
                    str(coord) + ' component: ' + comp
                PmagResRec['er_site_names'] = PmagSiteRec['er_site_name']
                PmagResRec['pmag_criteria_codes'] = 'ACCEPT'
                PmagResRec['er_citation_names'] = 'This study'
                PmagResRec['er_analyst_mail_names'] = user
                PmagResRec["er_location_names"] = PmagSiteRec["er_location_name"]
                if avg_directions_by_sample:
                    PmagResRec["er_sample_names"] = PmagSiteRec["er_sample_names"]
                else:
                    PmagResRec["er_specimen_names"] = PmagSiteRec["er_specimen_names"]
                PmagResRec["tilt_correction"] = PmagSiteRec['site_tilt_correction']
                PmagResRec["pole_comp_name"] = PmagSiteRec['site_comp_name']
                PmagResRec["average_dec"] = PmagSiteRec["site_dec"]
                PmagResRec["average_inc"] = PmagSiteRec["site_inc"]
                PmagResRec["average_alpha95"] = PmagSiteRec["site_alpha95"]
                PmagResRec["average_n"] = PmagSiteRec["site_n"]
                PmagResRec["average_n_lines"] = PmagSiteRec["site_n_lines"]
                PmagResRec["average_n_planes"] = PmagSiteRec["site_n_planes"]
                PmagResRec["vgp_n"] = PmagSiteRec["site_n"]
                PmagResRec["average_k"] = PmagSiteRec["site_k"]
                PmagResRec["average_r"] = PmagSiteRec["site_r"]
                PmagResRec["average_lat"] = '%10.4f ' % (lat)
                PmagResRec["average_lon"] = '%10.4f ' % (lon)
                if agefile != "":
                    PmagResRec = pmag.get_age(
                        PmagResRec, "er_site_names", "average_", AgeNFO, DefaultAge)
                site_height = pmag.get_dictitem(
                    height_nfo, 'er_site_name', site, 'T')
                if len(site_height) > 0:
                    PmagResRec["average_height"] = site_height[0]['site_height']
                PmagResRec["vgp_lat"] = '%7.1f ' % (plat)
                PmagResRec["vgp_lon"] = '%7.1f ' % (plon)
                PmagResRec["vgp_dp"] = '%7.1f ' % (dp)
                PmagResRec["vgp_dm"] = '%7.1f ' % (dm)
                PmagResRec["magic_method_codes"] = PmagSiteRec["magic_method_codes"]
                if '0' in PmagSiteRec['site_tilt_correction'] and "DA-DIR-GEO" not in PmagSiteRec['magic_method_codes']:
                    PmagSiteRec['magic_method_codes'] = PmagSiteRec['magic_method_codes'] + ":DA-DIR-GEO"
                if '100' in PmagSiteRec['site_tilt_correction'] and "DA-DIR-TILT" not in PmagSiteRec['magic_method_codes']:
                    PmagSiteRec['magic_method_codes'] = PmagSiteRec['magic_method_codes'] + ":DA-DIR-TILT"
                PmagSiteRec['site_polarity'] = ""
                if avg_by_polarity:  # assign polarity based on angle of pole lat to spin axis - may want to re-think this sometime
                    angle = pmag.angle([0, 0], [0, (90 - plat)])
                    if angle <= 55.:
                        PmagSiteRec["site_polarity"] = 'n'
                    if angle > 55. and angle < 125.:
                        PmagSiteRec["site_polarity"] = 't'
                    if angle >= 125.:
                        PmagSiteRec["site_polarity"] = 'r'
                PmagResults.append(PmagResRec)
    if avg_by_polarity:
        # find the tilt corrected data
        crecs = pmag.get_dictitem(
            PmagSites, 'site_tilt_correction', '100', 'T')
        if len(crecs) < 2:
            # if there aren't any, find the geographic corrected data
            crecs = pmag.get_dictitem(
                PmagSites, 'site_tilt_correction', '0', 'T')
        if len(crecs) > 2:  # if there are some,
            comp = pmag.get_list(crecs, 'site_comp_name').split(':')[
                0]  # find the first component
            # fish out all of the first component
            crecs = pmag.get_dictitem(crecs, 'site_comp_name', comp, 'T')
            precs = []
            for rec in crecs:
                precs.append({'dec': rec['site_dec'], 'inc': rec['site_inc'],
                              'name': rec['er_site_name'], 'loc': rec['er_location_name']})
            # calculate average by polarity
            polpars = pmag.fisher_by_pol(precs)
            # hunt through all the modes (normal=A, reverse=B, all=ALL)
            for mode in list(polpars.keys()):
                PolRes = {}
                PolRes['er_citation_names'] = 'This study'
                PolRes["pmag_result_name"] = "Polarity Average: Polarity " + mode
                PolRes["data_type"] = "a"
                PolRes["average_dec"] = '%7.1f' % (polpars[mode]['dec'])
                PolRes["average_inc"] = '%7.1f' % (polpars[mode]['inc'])
                PolRes["average_n"] = '%i' % (polpars[mode]['n'])
                PolRes["average_r"] = '%5.4f' % (polpars[mode]['r'])
                PolRes["average_k"] = '%6.0f' % (polpars[mode]['k'])
                PolRes["average_alpha95"] = '%7.1f' % (
                    polpars[mode]['alpha95'])
                PolRes['er_site_names'] = polpars[mode]['sites']
                PolRes['er_location_names'] = polpars[mode]['locs']
                PolRes['magic_software_packages'] = version_num
                PmagResults.append(PolRes)

    if not skip_intensities and nositeints != 1:
        for site in sites:  # now do intensities for each site
            if plotsites:
                print(site)
            if not avg_intensities_by_sample:
                key, intlist = 'specimen', SpecInts  # if using specimen level data
            if avg_intensities_by_sample:
                key, intlist = 'sample', PmagSamps  # if using sample level data
            # get all the intensities  for this site
            Ints = pmag.get_dictitem(intlist, 'er_site_name', site, 'T')
            if len(Ints) > 0:  # there are some
                # get average intensity stuff for site table
                PmagSiteRec = pmag.average_int(Ints, key, 'site')
                # get average intensity stuff for results table
                PmagResRec = pmag.average_int(Ints, key, 'average')
                if plotsites:  # if site by site examination requested - print this site out to the screen
                    for rec in Ints:
                        print(rec['er_' + key + '_name'], ' %7.1f' %
                              (1e6 * float(rec[key + '_int'])))
                    if len(Ints) > 1:
                        print('Average: ', '%7.1f' % (
                            1e6 * float(PmagResRec['average_int'])), 'N: ', len(Ints))
                        print('Sigma: ', '%7.1f' % (
                            1e6 * float(PmagResRec['average_int_sigma'])), 'Sigma %: ', PmagResRec['average_int_sigma_perc'])
                    input('Press any key to continue\n')
                er_location_name = Ints[0]["er_location_name"]
                # decorate the records
                PmagSiteRec["er_location_name"] = er_location_name
                PmagSiteRec["er_citation_names"] = "This study"
                PmagResRec["er_location_names"] = er_location_name
                PmagResRec["er_citation_names"] = "This study"
                PmagSiteRec["er_analyst_mail_names"] = user
                PmagResRec["er_analyst_mail_names"] = user
                PmagResRec["data_type"] = 'i'
                if not avg_intensities_by_sample:
                    PmagSiteRec['er_specimen_names'] = pmag.get_list(
                        Ints, 'er_specimen_name')  # list of all specimens used
                    PmagResRec['er_specimen_names'] = pmag.get_list(
                        Ints, 'er_specimen_name')
                PmagSiteRec['er_sample_names'] = pmag.get_list(
                    Ints, 'er_sample_name')  # list of all samples used
                PmagResRec['er_sample_names'] = pmag.get_list(
                    Ints, 'er_sample_name')
                PmagSiteRec['er_site_name'] = site
                PmagResRec['er_site_names'] = site
                PmagSiteRec['magic_method_codes'] = pmag.get_list(
                    Ints, 'magic_method_codes')
                PmagResRec['magic_method_codes'] = pmag.get_list(
                    Ints, 'magic_method_codes')
                kill = pmag.grade(PmagSiteRec, accept, 'site_int')
                if nocrit == 1 or len(kill) == 0:
                    b, sig = float(PmagResRec['average_int']), ""
                    if(PmagResRec['average_int_sigma']) != "":
                        sig = float(PmagResRec['average_int_sigma'])
                    # fish out site direction
                    sdir = pmag.get_dictitem(
                        PmagResults, 'er_site_names', site, 'T')
                    # get the VDM for this record using last average
                    # inclination (hope it is the right one!)
                    if len(sdir) > 0 and sdir[-1]['average_inc'] != "":
                        inc = float(sdir[0]['average_inc'])
                        # get magnetic latitude using dipole formula
                        mlat = pmag.magnetic_lat(inc)
                        # get VDM with magnetic latitude
                        PmagResRec["vdm"] = '%8.3e ' % (pmag.b_vdm(b, mlat))
                        PmagResRec["vdm_n"] = PmagResRec['average_int_n']
                        if 'average_int_sigma' in list(PmagResRec.keys()) and PmagResRec['average_int_sigma'] != "":
                            vdm_sig = pmag.b_vdm(
                                float(PmagResRec['average_int_sigma']), mlat)
                            PmagResRec["vdm_sigma"] = '%8.3e ' % (vdm_sig)
                        else:
                            PmagResRec["vdm_sigma"] = ""
                    mlat = ""  # define a model latitude
                    if get_model_lat == 1:  # use present site latitude
                        mlats = pmag.get_dictitem(
                            SiteNFO, 'er_site_name', site, 'T')
                        if len(mlats) > 0:
                            mlat = mlats[0]['site_lat']
                    # use a model latitude from some plate reconstruction model
                    # (or something)
                    elif get_model_lat == 2:
                        mlats = pmag.get_dictitem(
                            ModelLats, 'er_site_name', site, 'T')
                        if len(mlats) > 0:
                            PmagResRec['model_lat'] = mlats[0]['site_model_lat']
                        mlat = PmagResRec['model_lat']
                    if mlat != "":
                        # get the VADM using the desired latitude
                        PmagResRec["vadm"] = '%8.3e ' % (
                            pmag.b_vdm(b, float(mlat)))
                        if sig != "":
                            vdm_sig = pmag.b_vdm(
                                float(PmagResRec['average_int_sigma']), float(mlat))
                            PmagResRec["vadm_sigma"] = '%8.3e ' % (vdm_sig)
                            PmagResRec["vadm_n"] = PmagResRec['average_int_n']
                        else:
                            PmagResRec["vadm_sigma"] = ""
                    # fish out site information (lat/lon, etc.)
                    sitedat = pmag.get_dictitem(
                        SiteNFO, 'er_site_name', PmagSiteRec['er_site_name'], 'T')
                    if len(sitedat) > 0:
                        sitedat = sitedat[0]
                        PmagResRec['average_lat'] = sitedat['site_lat']
                        PmagResRec['average_lon'] = sitedat['site_lon']
                    else:
                        PmagResRec['average_lon'] = 'UNKNOWN'
                        PmagResRec['average_lon'] = 'UNKNOWN'
                    PmagResRec['magic_software_packages'] = version_num
                    PmagResRec["pmag_result_name"] = "V[A]DM: Site " + site
                    PmagResRec["result_description"] = "V[A]DM of site"
                    PmagResRec["pmag_criteria_codes"] = "ACCEPT"
                    if agefile != "":
                        PmagResRec = pmag.get_age(
                            PmagResRec, "er_site_names", "average_", AgeNFO, DefaultAge)
                    site_height = pmag.get_dictitem(
                        height_nfo, 'er_site_name', site, 'T')
                    if len(site_height) > 0:
                        PmagResRec["average_height"] = site_height[0]['site_height']
                    PmagSites.append(PmagSiteRec)
                    PmagResults.append(PmagResRec)
    if len(PmagSites) > 0:
        Tmp, keylist = pmag.fillkeys(PmagSites)
        pmag.magic_write(siteout, Tmp, 'pmag_sites')
        print(' sites written to ', siteout)
    else:
        print("No Site level table")
    if len(PmagResults) > 0:
        TmpRes, keylist = pmag.fillkeys(PmagResults)
        pmag.magic_write(resout, TmpRes, 'pmag_results')
        print(' results written to ', resout)
    else:
        print("No Results level table")

Response: Writes the data from the pmag_specimens. txt file to the pmag_samples. txt and pmag_sites. txt file to the pmag_results. txt file.


Instruction:
Can you tell what is the following Python 3 function doing
def orientation_magic(or_con=1, dec_correction_con=1, dec_correction=0, bed_correction=True,
                      samp_con='1', hours_from_gmt=0, method_codes='', average_bedding=False,
                      orient_file='orient.txt', samp_file='samples.txt', site_file='sites.txt',
                      output_dir_path='.', input_dir_path='', append=False, data_model=3):
    """
    use this function to convert tab delimited field notebook information to MagIC formatted tables (er_samples and er_sites)

    INPUT FORMAT
        Input files must be tab delimited and have in the first line:
tab  location_name
        Note: The "location_name" will facilitate searching in the MagIC database. Data from different
            "locations" should be put in separate files.  The definition of a "location" is rather loose.
             Also this is the word 'tab' not a tab, which will be indicated by '\t'.
        The second line has the names of the columns (tab delimited), e.g.:
site_name sample_name mag_azimuth field_dip date lat long sample_lithology sample_type sample_class shadow_angle hhmm stratigraphic_height bedding_dip_direction bedding_dip GPS_baseline image_name image_look image_photographer participants method_codes site_description sample_description GPS_Az, sample_igsn, sample_texture, sample_cooling_rate, cooling_rate_corr, cooling_rate_mcd

      Notes:
        1) column order doesn't matter but the NAMES do.
        2) sample_name, sample_lithology, sample_type, sample_class, lat and long are required.  all others are optional.
        3) If subsequent data are the same (e.g., date, bedding orientation, participants, stratigraphic_height),
            you can leave the field blank and the program will fill in the last recorded information. BUT if you really want a blank stratigraphic_height, enter a '-1'.    These will not be inherited and must be specified for each entry: image_name, look, photographer or method_codes
        4) hhmm must be in the format:  hh:mm and the hh must be in 24 hour time.
    date must be mm/dd/yy (years < 50 will be converted to  20yy and >50 will be assumed 19yy).  hours_from_gmt is the number of hours to SUBTRACT from hh to get to  GMT.
        5) image_name, image_look and image_photographer are colon delimited lists of file name (e.g., IMG_001.jpg) image look direction and the name of the photographer respectively.  If all images had same look and photographer, just enter info once.  The images will be assigned to the site for which they were taken - not at the sample level.
        6) participants:  Names of who helped take the samples.  These must be a colon delimited list.
        7) method_codes:  Special method codes on a sample level, e.g., SO-GT5 which means the orientation is has an uncertainty of >5 degrees
             for example if it broke off before orienting....
        8) GPS_Az is the place to put directly determined GPS Azimuths, using, e.g., points along the drill direction.
        9) sample_cooling_rate is the cooling rate in K per Ma
        10) int_corr_cooling_rate
        11) cooling_rate_mcd:  data adjustment method code for cooling rate correction;  DA-CR-EG is educated guess; DA-CR-PS is percent estimated from pilot samples; DA-CR-TRM is comparison between 2 TRMs acquired with slow and rapid cooling rates.
is the percent cooling rate factor to apply to specimens from this sample, DA-CR-XX is the method code

    defaults:
    orientation_magic(or_con=1, dec_correction_con=1, dec_correction=0, bed_correction=True, samp_con='1', hours_from_gmt=0, method_codes='', average_bedding=False, orient_file='orient.txt', samp_file='er_samples.txt', site_file='er_sites.txt', output_dir_path='.', input_dir_path='', append=False):
    orientation conventions:
        [1] Standard Pomeroy convention of azimuth and hade (degrees from vertical down)
             of the drill direction (field arrow).  lab arrow azimuth= sample_azimuth = mag_azimuth;
             lab arrow dip = sample_dip =-field_dip. i.e. the lab arrow dip is minus the hade.
        [2] Field arrow is the strike  of the plane orthogonal to the drill direction,
             Field dip is the hade of the drill direction.  Lab arrow azimuth = mag_azimuth-90
             Lab arrow dip = -field_dip
        [3] Lab arrow is the same as the drill direction;
             hade was measured in the field.
             Lab arrow azimuth = mag_azimuth; Lab arrow dip = 90-field_dip
        [4] lab azimuth and dip are same as mag_azimuth, field_dip : use this for unoriented samples too
        [5] Same as AZDIP convention explained below -
            azimuth and inclination of the drill direction are mag_azimuth and field_dip;
            lab arrow is as in [1] above.
            lab azimuth is same as mag_azimuth,lab arrow dip=field_dip-90
        [6] Lab arrow azimuth = mag_azimuth-90; Lab arrow dip = 90-field_dip
        [7] see http://earthref.org/PmagPy/cookbook/#field_info for more information.  You can customize other format yourself, or email ltauxe@ucsd.edu for help.

    Magnetic declination convention:
        [1] Use the IGRF value at the lat/long and date supplied [default]
        [2] Will supply declination correction
        [3] mag_az is already corrected in file
        [4] Correct mag_az but not bedding_dip_dir

    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 = sample name
        [6] site name entered in site_name column in the orient.txt format input file  -- NOT CURRENTLY SUPPORTED
        [7-Z] [XXX]YYY:  XXX is site designation with Z characters from samples  XXXYYY
        NB: all others you will have to either customize your
            self or e-mail ltauxe@ucsd.edu for help.

    """
    # initialize some variables
    # bed_correction used to be BedCorr
    # dec_correction_con used to be corr
    # dec_correction used to be DecCorr
    # meths is now method_codes
    # delta_u is now hours_from_gmt

    input_dir_path, output_dir_path = pmag.fix_directories(input_dir_path, output_dir_path)
    or_con, dec_correction_con, dec_correction = int(
        or_con), int(dec_correction_con), float(dec_correction)
    hours_from_gmt = float(hours_from_gmt)
    stratpos = ""
    # date of sampling, latitude (pos North), longitude (pos East)
    date, lat, lon = "", "", ""
    bed_dip, bed_dip_dir = "", ""
    Lats, Lons = [], []  # list of latitudes and longitudes
    # lists of Sample records and Site records
    SampOuts, SiteOuts, ImageOuts = [], [], []
    samplelist, sitelist, imagelist = [], [], []
    Z = 1
    newbaseline, newbeddir, newbeddip = "", "", ""
    fpars = []
    sclass, lithology, sample_type = "", "", ""
    newclass, newlith, newtype = '', '', ''
    BPs = []  # bedding pole declinations, bedding pole inclinations
    image_file = "er_images.txt"
    #
    # use 3.0. default filenames when in 3.0.
    # but, still allow for custom names
    data_model = int(data_model)
    if data_model == 3:
        if samp_file == "er_samples.txt":
            samp_file = "samples.txt"
        if site_file == "er_sites.txt":
            site_file = "sites.txt"
        image_file = "images.txt"
    orient_file = pmag.resolve_file_name(orient_file, input_dir_path)
    if not os.path.exists(orient_file):
        return False, "No such file: {}.  If the orientation file is not in your current working directory, make sure you have specified the correct input directory.".format(orient_file)
    samp_file = os.path.join(output_dir_path, samp_file)
    site_file = os.path.join(output_dir_path, site_file)
    image_file = os.path.join(output_dir_path, image_file)

    # validate input
    if '4' in samp_con[0]:
        pattern = re.compile('[4][-]\d')
        result = pattern.match(samp_con)
        if not result:
            raise Exception(
                "If using sample naming convention 4, you must provide the number of characters with which to distinguish sample from site. [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX)")

    if '7' in samp_con[0]:
        pattern = re.compile('[7][-]\d')
        result = pattern.match(samp_con)
        if not result:
            raise Exception(
                "If using sample naming convention 7, you must provide the number of characters with which to distinguish sample from site.  [7-Z] [XXX]YYY:  XXX is site designation with Z characters from samples  XXXYYY")

    if dec_correction_con == 2 and not dec_correction:
        raise Exception(
            "If using magnetic declination convention 2, you must also provide a declincation correction in degrees")

    SampRecs, SiteRecs, ImageRecs = [], [], []
    SampRecs_sorted, SiteRecs_sorted = {}, {}

    if append:
        try:
            SampRecs, file_type = pmag.magic_read(samp_file)
            # convert 3.0. sample file to 2.5 format
            if data_model == 3:
                SampRecs3 = SampRecs
                SampRecs = []
                for samp_rec in SampRecs3:
                    rec = map_magic.mapping(
                        samp_rec, map_magic.samp_magic3_2_magic2_map)
                    SampRecs.append(rec)
            # magic_data dictionary sorted by sample_name
            SampRecs_sorted = pmag.sort_magic_data(SampRecs, 'er_sample_name')
            print('sample data to be appended to: ', samp_file)
        except Exception as ex:
            print(ex)
            print('problem with existing file: ',
                  samp_file, ' will create new.')
        try:
            SiteRecs, file_type = pmag.magic_read(site_file)
            # convert 3.0. site file to 2.5 format
            if data_model == 3:
                SiteRecs3 = SiteRecs
                SiteRecs = []
                for site_rec in SiteRecs3:
                    SiteRecs.append(map_magic.mapping(
                        site_rec, map_magic.site_magic3_2_magic2_map))
            # magic_data dictionary sorted by site_name
            SiteRecs_sorted = pmag.sort_magic_data(SiteRecs, 'er_site_name')
            print('site data to be appended to: ', site_file)
        except Exception as ex:
            print(ex)
            print('problem with existing file: ',
                  site_file, ' will create new.')
        try:
            ImageRecs, file_type = pmag.magic_read(image_file)
            # convert from 3.0. --> 2.5
            if data_model == 3:
                ImageRecs3 = ImageRecs
                ImageRecs = []
                for image_rec in ImageRecs3:
                    ImageRecs.append(map_magic.mapping(
                        image_rec, map_magic.image_magic3_2_magic2_map))
            print('image data to be appended to: ', image_file)
        except:
            print('problem with existing file: ',
                  image_file, ' will create new.')
    #
    # read in file to convert
    #
    OrData, location_name = pmag.magic_read(orient_file)
    if location_name == "demag_orient":
        location_name = ""
    #
    # step through the data sample by sample
    #
    # use map_magic in here...

    for OrRec in OrData:
        if 'mag_azimuth' not in list(OrRec.keys()):
            OrRec['mag_azimuth'] = ""
        if 'field_dip' not in list(OrRec.keys()):
            OrRec['field_dip'] = ""
        if OrRec['mag_azimuth'] == " ":
            OrRec["mag_azimuth"] = ""
        if OrRec['field_dip'] == " ":
            OrRec["field_dip"] = ""
        if 'sample_description' in list(OrRec.keys()):
            sample_description = OrRec['sample_description']
        else:
            sample_description = ""
        if 'cooling_rate_corr' in list(OrRec.keys()):
            if 'cooling_rate_mcd' not in list(OrRec.keys()):
                OrRec['cooling_rate_mcd'] = 'DA-CR'
        sample_orientation_flag = 'g'
        if 'sample_orientation_flag' in list(OrRec.keys()):
            if OrRec['sample_orientation_flag'] == 'b' or OrRec["mag_azimuth"] == "":
                sample_orientation_flag = 'b'
        methcodes = method_codes  # initialize method codes
        if methcodes:
            if 'method_codes' in list(OrRec.keys()) and OrRec['method_codes'].strip() != "":
                methcodes = methcodes + ":" + \
                    OrRec['method_codes']  # add notes
        else:
            if 'method_codes' in list(OrRec.keys()) and OrRec['method_codes'].strip() != "":
                methcodes = OrRec['method_codes']  # add notes

        codes = methcodes.replace(" ", "").split(":")
        sample_name = OrRec["sample_name"]
        # patch added by rshaar 7/2016
        # if sample_name already exists in er_samples.txt:
        # merge the new data colmuns calculated by orientation_magic with the existing data colmuns
        # this is done to make sure no previous data in er_samples.txt and
        # er_sites.txt is lost.

        if sample_name in list(SampRecs_sorted.keys()):
            Prev_MagRec = SampRecs_sorted[sample_name][-1]
            MagRec = Prev_MagRec
        else:
            Prev_MagRec = {}
            MagRec = {}
        MagRec["er_citation_names"] = "This study"

        # the following keys were calculated or defined in the code above:
        for key in ['sample_igsn', 'sample_texture', 'sample_cooling_rate',
                    'cooling_rate_corr', 'cooling_rate_mcd']:
            val = OrRec.get(key, '')
            if val:
                MagRec[key] = val
            elif key in list(Prev_MagRec.keys()):
                MagRec[key] = Prev_MagRec[key]
            else:
                MagRec[key] = ""

            if location_name != "":
                MagRec["er_location_name"] = location_name
            elif "er_location_name" in list(Prev_MagRec.keys()):
                MagRec["er_location_name"] = Prev_MagRec["er_location_name"]
            else:
                MagRec["er_location_name"] = ""

        # the following keys are taken directly from OrRec dictionary:
        for key in ["sample_height", "er_sample_alternatives", "sample_orientation_flag"]:
            if key in list(OrRec.keys()) and OrRec[key] != "":
                MagRec[key] = OrRec[key]
            elif key in list(Prev_MagRec.keys()):
                MagRec[key] = Prev_MagRec[key]
            else:
                MagRec[key] = ""

        # the following keys, if blank, used to be defined here as "Not Specified" :

        for key in ["sample_class", "sample_lithology", "sample_type"]:
            if key in list(OrRec.keys()) and OrRec[key] != "" and OrRec[key] != "Not Specified":
                MagRec[key] = OrRec[key]
            elif key in list(Prev_MagRec.keys()) and Prev_MagRec[key] != "" and Prev_MagRec[key] != "Not Specified":
                MagRec[key] = Prev_MagRec[key]
            else:
                MagRec[key] = ""  # "Not Specified"

        # (rshaar) From here parse new information and replace previous, if exists:
    #
    # parse information common to all orientation methods
    #
        MagRec["er_sample_name"] = OrRec["sample_name"]
        if "IGSN" in list(OrRec.keys()):
            MagRec["sample_igsn"] = OrRec["IGSN"]
        else:
            MagRec["sample_igsn"] = ""
        # MagRec["sample_height"],MagRec["sample_bed_dip_direction"],MagRec["sample_bed_dip"]="","",""
        MagRec["sample_bed_dip_direction"], MagRec["sample_bed_dip"] = "", ""
        # if "er_sample_alternatives" in OrRec.keys():
        #    MagRec["er_sample_alternatives"]=OrRec["sample_alternatives"]
        sample = OrRec["sample_name"]
        if OrRec['mag_azimuth'] == "" and OrRec['field_dip'] != "":
            OrRec['mag_azimuth'] = '999'
        if OrRec["mag_azimuth"] != "":
            labaz, labdip = pmag.orient(
                float(OrRec["mag_azimuth"]), float(OrRec["field_dip"]), or_con)
            if labaz < 0:
                labaz += 360.
        else:
            labaz, labdip = "", ""
        if OrRec['mag_azimuth'] == '999':
            labaz = ""
        if "GPS_baseline" in list(OrRec.keys()) and OrRec['GPS_baseline'] != "":
            newbaseline = OrRec["GPS_baseline"]
        if newbaseline != "":
            baseline = float(newbaseline)
        MagRec['er_scientist_mail_names'] = OrRec.get('participants', '')
        newlat = OrRec["lat"]
        if newlat != "":
            lat = float(newlat)
        if lat == "":
            print("No latitude specified for ! ", sample,
                  ". Latitude is required for all samples.")
            return False, "No latitude specified for ! " + sample + ". Latitude is required for all samples."
        MagRec["sample_lat"] = '%11.5f' % (lat)
        newlon = OrRec["long"]
        if newlon != "":
            lon = float(newlon)
        if lon == "":
            print("No longitude specified for ! ", sample,
                  ". Longitude is required for all samples.")
            return False, str("No longitude specified for ! " + sample + ". Longitude is required for all samples.")
        MagRec["sample_lon"] = '%11.5f' % (lon)
        if 'bedding_dip_direction' in list(OrRec.keys()):
            newbeddir = OrRec["bedding_dip_direction"]
        if newbeddir != "":
            bed_dip_dir = OrRec['bedding_dip_direction']
        if 'bedding_dip' in list(OrRec.keys()):
            newbeddip = OrRec["bedding_dip"]
        if newbeddip != "":
            bed_dip = OrRec['bedding_dip']
        MagRec["sample_bed_dip"] = bed_dip
        MagRec["sample_bed_dip_direction"] = bed_dip_dir
        # MagRec["sample_type"]=sample_type
        if labdip != "":
            MagRec["sample_dip"] = '%7.1f' % labdip
        else:
            MagRec["sample_dip"] = ""
        if "date" in list(OrRec.keys()) and OrRec["date"] != "":
            newdate = OrRec["date"]
            if newdate != "":
                date = newdate
            mmddyy = date.split('/')
            yy = int(mmddyy[2])
            if yy > 50:
                yy = 1900 + yy
            else:
                yy = 2000 + yy
            decimal_year = yy + old_div(float(mmddyy[0]), 12)
            sample_date = '%i:%s:%s' % (yy, mmddyy[0], mmddyy[1])
            time = OrRec['hhmm']
            if time:
                sample_date += (':' + time)
            MagRec["sample_date"] = sample_date.strip(':')
        if labaz != "":
            MagRec["sample_azimuth"] = '%7.1f' % (labaz)
        else:
            MagRec["sample_azimuth"] = ""
        if "stratigraphic_height" in list(OrRec.keys()):
            if OrRec["stratigraphic_height"] != "":
                MagRec["sample_height"] = OrRec["stratigraphic_height"]
                stratpos = OrRec["stratigraphic_height"]
            elif OrRec["stratigraphic_height"] == '-1':
                MagRec["sample_height"] = ""   # make empty
            elif stratpos != "":
                # keep last record if blank
                MagRec["sample_height"] = stratpos
#
        # get magnetic declination (corrected with igrf value)
        if dec_correction_con == 1 and MagRec['sample_azimuth'] != "":
            x, y, z, f = pmag.doigrf(lon, lat, 0, decimal_year)
            Dir = pmag.cart2dir((x, y, z))
            dec_correction = Dir[0]
        if "bedding_dip" in list(OrRec.keys()):
            if OrRec["bedding_dip"] != "":
                MagRec["sample_bed_dip"] = OrRec["bedding_dip"]
                bed_dip = OrRec["bedding_dip"]
            else:
                MagRec["sample_bed_dip"] = bed_dip
        else:
            MagRec["sample_bed_dip"] = '0'
        if "bedding_dip_direction" in list(OrRec.keys()):
            if OrRec["bedding_dip_direction"] != "" and bed_correction == 1:
                dd = float(OrRec["bedding_dip_direction"]) + dec_correction
                if dd > 360.:
                    dd = dd - 360.
                MagRec["sample_bed_dip_direction"] = '%7.1f' % (dd)
                dip_dir = MagRec["sample_bed_dip_direction"]
            else:
                MagRec["sample_bed_dip_direction"] = OrRec['bedding_dip_direction']
        else:
            MagRec["sample_bed_dip_direction"] = '0'
        if average_bedding:
            if str(MagRec["sample_bed_dip_direction"]) and str(MagRec["sample_bed_dip"]):
                BPs.append([float(MagRec["sample_bed_dip_direction"]),
                            float(MagRec["sample_bed_dip"]) - 90., 1.])
        if MagRec['sample_azimuth'] == "" and MagRec['sample_dip'] == "":
            MagRec["sample_declination_correction"] = ''
            methcodes = methcodes + ':SO-NO'
        MagRec["magic_method_codes"] = methcodes
        MagRec['sample_description'] = sample_description
    #
    # work on the site stuff too
        if 'site_name' in list(OrRec.keys()) and OrRec['site_name'] != "":
            site = OrRec['site_name']
        elif 'site_name' in list(Prev_MagRec.keys()) and Prev_MagRec['site_name'] != "":
            site = Prev_MagRec['site_name']
        else:
            # parse out the site name
            site = pmag.parse_site(OrRec["sample_name"], samp_con, Z)
        MagRec["er_site_name"] = site
        site_description = ""  # overwrite any prior description
        if 'site_description' in list(OrRec.keys()) and OrRec['site_description'] != "":
            site_description = OrRec['site_description'].replace(",", ";")
        if "image_name" in list(OrRec.keys()):
            images = OrRec["image_name"].split(":")
            if "image_look" in list(OrRec.keys()):
                looks = OrRec['image_look'].split(":")
            else:
                looks = []
            if "image_photographer" in list(OrRec.keys()):
                photographers = OrRec['image_photographer'].split(":")
            else:
                photographers = []
            for image in images:
                if image != "" and image not in imagelist:
                    imagelist.append(image)
                    ImageRec = {}
                    ImageRec['er_image_name'] = image
                    ImageRec['image_type'] = "outcrop"
                    ImageRec['image_date'] = sample_date
                    ImageRec['er_citation_names'] = "This study"
                    ImageRec['er_location_name'] = location_name
                    ImageRec['er_site_name'] = MagRec['er_site_name']
                    k = images.index(image)
                    if len(looks) > k:
                        ImageRec['er_image_description'] = "Look direction: " + looks[k]
                    elif len(looks) >= 1:
                        ImageRec['er_image_description'] = "Look direction: " + looks[-1]
                    else:
                        ImageRec['er_image_description'] = "Look direction: unknown"
                    if len(photographers) > k:
                        ImageRec['er_photographer_mail_names'] = photographers[k]
                    elif len(photographers) >= 1:
                        ImageRec['er_photographer_mail_names'] = photographers[-1]
                    else:
                        ImageRec['er_photographer_mail_names'] = "unknown"
                    ImageOuts.append(ImageRec)
        if site not in sitelist:
            sitelist.append(site)  # collect unique site names
            # patch added by rshaar 7/2016
            # if sample_name already exists in er_samples.txt:
            # merge the new data colmuns calculated by orientation_magic with the existing data colmuns
            # this is done to make sure no previous data in er_samples.txt and
            # er_sites.txt is lost.

            if site in list(SiteRecs_sorted.keys()):
                Prev_MagRec = SiteRecs_sorted[site][-1]
                SiteRec = Prev_MagRec
            else:
                Prev_MagRec = {}
                SiteRec = {}
            SiteRec["er_citation_names"] = "This study"
            SiteRec["er_site_name"] = site
            SiteRec["site_definition"] = "s"

            if "er_location_name" in SiteRec and SiteRec.get("er_location_name"):
                pass
            elif key in list(Prev_MagRec.keys()) and Prev_MagRec[key] != "":
                SiteRec[key] = Prev_MagRec[key]
            else:
                print('setting location name to ""')
                SiteRec[key] = ""

            for key in ["lat", "lon", "height"]:
                if "site_" + key in list(Prev_MagRec.keys()) and Prev_MagRec["site_" + key] != "":
                    SiteRec["site_" + key] = Prev_MagRec["site_" + key]
                else:
                    SiteRec["site_" + key] = MagRec["sample_" + key]

            # SiteRec["site_lat"]=MagRec["sample_lat"]
            # SiteRec["site_lon"]=MagRec["sample_lon"]
            # SiteRec["site_height"]=MagRec["sample_height"]

            for key in ["class", "lithology", "type"]:
                if "site_" + key in list(Prev_MagRec.keys()) and Prev_MagRec["site_" + key] != "Not Specified":
                    SiteRec["site_" + key] = Prev_MagRec["site_" + key]
                else:
                    SiteRec["site_" + key] = MagRec["sample_" + key]

            # SiteRec["site_class"]=MagRec["sample_class"]
            # SiteRec["site_lithology"]=MagRec["sample_lithology"]
            # SiteRec["site_type"]=MagRec["sample_type"]

            if site_description != "":  # overwrite only if site_description has something
                SiteRec["site_description"] = site_description
            SiteOuts.append(SiteRec)
        if sample not in samplelist:
            samplelist.append(sample)
            if MagRec['sample_azimuth'] != "":  # assume magnetic compass only
                MagRec['magic_method_codes'] = MagRec['magic_method_codes'] + ':SO-MAG'
                MagRec['magic_method_codes'] = MagRec['magic_method_codes'].strip(
                    ":")
            SampOuts.append(MagRec)
            if MagRec['sample_azimuth'] != "" and dec_correction_con != 3:
                az = labaz + dec_correction
                if az > 360.:
                    az = az - 360.
                CMDRec = {}
                for key in list(MagRec.keys()):
                    CMDRec[key] = MagRec[key]  # make a copy of MagRec
                CMDRec["sample_azimuth"] = '%7.1f' % (az)
                CMDRec["magic_method_codes"] = methcodes + ':SO-CMD-NORTH'
                CMDRec["magic_method_codes"] = CMDRec['magic_method_codes'].strip(
                    ':')
                CMDRec["sample_declination_correction"] = '%7.1f' % (
                    dec_correction)
                if dec_correction_con == 1:
                    CMDRec['sample_description'] = sample_description + \
                        ':Declination correction calculated from IGRF'
                else:
                    CMDRec['sample_description'] = sample_description + \
                        ':Declination correction supplied by user'
                CMDRec["sample_description"] = CMDRec['sample_description'].strip(
                    ':')
                SampOuts.append(CMDRec)
            if "mag_az_bs" in list(OrRec.keys()) and OrRec["mag_az_bs"] != "" and OrRec["mag_az_bs"] != " ":
                SRec = {}
                for key in list(MagRec.keys()):
                    SRec[key] = MagRec[key]  # make a copy of MagRec
                labaz = float(OrRec["mag_az_bs"])
                az = labaz + dec_correction
                if az > 360.:
                    az = az - 360.
                SRec["sample_azimuth"] = '%7.1f' % (az)
                SRec["sample_declination_correction"] = '%7.1f' % (
                    dec_correction)
                SRec["magic_method_codes"] = methcodes + \
                    ':SO-SIGHT-BACK:SO-CMD-NORTH'
                SampOuts.append(SRec)
    #
    # check for suncompass data
    #
            # there are sun compass data
            if "shadow_angle" in list(OrRec.keys()) and OrRec["shadow_angle"] != "":
                if hours_from_gmt == "":
                    #hours_from_gmt=raw_input("Enter hours to subtract from time for  GMT: [0] ")
                    hours_from_gmt = 0
                SunRec, sundata = {}, {}
                shad_az = float(OrRec["shadow_angle"])
                if not OrRec["hhmm"]:
                    print('If using the column shadow_angle for sun compass data, you must also provide the time for each sample.  Sample ',
                          sample, ' has shadow_angle but is missing the "hh:mm" column.')
                else:  # calculate sun declination
                    sundata["date"] = '%i:%s:%s:%s' % (
                        yy, mmddyy[0], mmddyy[1], OrRec["hhmm"])
                    sundata["delta_u"] = hours_from_gmt
                    sundata["lon"] = lon  # do not truncate!
                    sundata["lat"] = lat  # do not truncate!
                    sundata["shadow_angle"] = OrRec["shadow_angle"]
                    # now you can truncate
                    sundec = '%7.1f' % (pmag.dosundec(sundata))
                    for key in list(MagRec.keys()):
                        SunRec[key] = MagRec[key]  # make a copy of MagRec
                    SunRec["sample_azimuth"] = sundec  # do not truncate!
                    SunRec["sample_declination_correction"] = ''
                    SunRec["magic_method_codes"] = methcodes + ':SO-SUN'
                    SunRec["magic_method_codes"] = SunRec['magic_method_codes'].strip(
                        ':')
                    SampOuts.append(SunRec)
    #
    # check for differential GPS data
    #
            # there are diff GPS data
            if "prism_angle" in list(OrRec.keys()) and OrRec["prism_angle"] != "":
                GPSRec = {}
                for key in list(MagRec.keys()):
                    GPSRec[key] = MagRec[key]  # make a copy of MagRec
                    prism_angle = float(OrRec["prism_angle"])
                    sundata["shadow_angle"] = OrRec["shadow_angle"]
                    sundec = pmag.dosundec(sundata)
                    for key in list(MagRec.keys()):
                        SunRec[key] = MagRec[key]  # make a copy of MagRec
                    SunRec["sample_azimuth"] = '%7.1f' % (sundec)
                    SunRec["sample_declination_correction"] = ''
                    SunRec["magic_method_codes"] = methcodes + ':SO-SUN'
                    SunRec["magic_method_codes"] = SunRec['magic_method_codes'].strip(
                        ':')
                    SampOuts.append(SunRec)
    #
    # check for differential GPS data
    #
            # there are diff GPS data
            if "prism_angle" in list(OrRec.keys()) and OrRec["prism_angle"] != "":
                GPSRec = {}
                for key in list(MagRec.keys()):
                    GPSRec[key] = MagRec[key]  # make a copy of MagRec
                prism_angle = float(OrRec["prism_angle"])
                laser_angle = float(OrRec["laser_angle"])
                if OrRec["GPS_baseline"] != "":
                    baseline = float(OrRec["GPS_baseline"])  # new baseline
                gps_dec = baseline + laser_angle + prism_angle - 90.
                while gps_dec > 360.:
                    gps_dec = gps_dec - 360.
                while gps_dec < 0:
                    gps_dec = gps_dec + 360.
                for key in list(MagRec.keys()):
                    GPSRec[key] = MagRec[key]  # make a copy of MagRec
                GPSRec["sample_azimuth"] = '%7.1f' % (gps_dec)
                GPSRec["sample_declination_correction"] = ''
                GPSRec["magic_method_codes"] = methcodes + ':SO-GPS-DIFF'
                SampOuts.append(GPSRec)
            # there are differential GPS Azimuth data
            if "GPS_Az" in list(OrRec.keys()) and OrRec["GPS_Az"] != "":
                GPSRec = {}
                for key in list(MagRec.keys()):
                    GPSRec[key] = MagRec[key]  # make a copy of MagRec
                GPSRec["sample_azimuth"] = '%7.1f' % (float(OrRec["GPS_Az"]))
                GPSRec["sample_declination_correction"] = ''
                GPSRec["magic_method_codes"] = methcodes + ':SO-GPS-DIFF'
                SampOuts.append(GPSRec)
        if average_bedding != "0" and fpars:
            fpars = pmag.fisher_mean(BPs)
            print('over-writing all bedding with average ')
    Samps = []
    for rec in SampOuts:
        if average_bedding != "0" and fpars:
            rec['sample_bed_dip_direction'] = '%7.1f' % (fpars['dec'])
            rec['sample_bed_dip'] = '%7.1f' % (fpars['inc'] + 90.)
            Samps.append(rec)
        else:
            Samps.append(rec)
    for rec in SampRecs:
        if rec['er_sample_name'] not in samplelist:  # overwrite prior for this sample
            Samps.append(rec)
    for rec in SiteRecs:
        if rec['er_site_name'] not in sitelist:  # overwrite prior for this sample
            SiteOuts.append(rec)
    for rec in ImageRecs:
        if rec['er_image_name'] not in imagelist:  # overwrite prior for this sample
            ImageOuts.append(rec)
    print('saving data...')
    SampsOut, keys = pmag.fillkeys(Samps)
    Sites, keys = pmag.fillkeys(SiteOuts)
    if data_model == 3:
        SampsOut3 = []
        Sites3 = []
        for samp_rec in SampsOut:
            new_rec = map_magic.mapping(
                samp_rec, map_magic.samp_magic2_2_magic3_map)
            SampsOut3.append(new_rec)
        for site_rec in Sites:
            new_rec = map_magic.mapping(
                site_rec, map_magic.site_magic2_2_magic3_map)
            Sites3.append(new_rec)
        wrote_samps = pmag.magic_write(samp_file, SampsOut3, "samples")
        wrote_sites = pmag.magic_write(site_file, Sites3, "sites")
    else:
        wrote_samps = pmag.magic_write(samp_file, SampsOut, "er_samples")
        wrote_sites = pmag.magic_write(site_file, Sites, "er_sites")
    if wrote_samps:
        print("Data saved in ", samp_file, ' and ', site_file)
    else:
        print("No data found")
    if len(ImageOuts) > 0:
        # need to do conversion here 3.0. --> 2.5
        Images, keys = pmag.fillkeys(ImageOuts)
        image_type = "er_images"
        if data_model == 3:
            # convert 2.5 --> 3.0.
            image_type = "images"
            Images2 = Images
            Images = []
            for image_rec in Images2:
                Images.append(map_magic.mapping(
                    image_rec, map_magic.image_magic2_2_magic3_map))
        pmag.magic_write(image_file, Images, image_type)
        print("Image info saved in ", image_file)
    return True, None

Response: This function converts the orientation of a notebook to MagIC formatted tables.


Instruction:
Create a Python 3 function to
take space delimited AzDip file and converts to MagIC formatted tables Parameters __________ orient_file : name of azdip formatted input file samp_file : name of samples.txt formatted output file samp_con : integer of sample orientation 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 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 method_codes : colon delimited string with the following as desired FS-FD field sampling done with a drill FS-H field sampling done with hand samples FS-LOC-GPS field location done with GPS FS-LOC-MAP field location done with map SO-POM a Pomeroy orientation device was used SO-ASC an ASC orientation device was used SO-MAG orientation with magnetic compass location_name : location of samples append : boolean. if True, append to the output file output_dir : path to output file directory input_dir : path to input file directory data_model : MagIC data model. INPUT FORMAT Input files must be space delimited: Samp Az Dip Strike Dip Orientation convention: Lab arrow azimuth = mag_azimuth; Lab arrow dip = 90-field_dip e.g. field_dip is degrees from horizontal of drill direction Magnetic declination convention: Az is already corrected in file

Response:
def azdip_magic(orient_file='orient.txt', samp_file="samples.txt", samp_con="1", Z=1, method_codes='FS-FD', location_name='unknown', append=False, output_dir='.', input_dir='.', data_model=3):
    """
    takes space delimited AzDip file and converts to MagIC formatted tables

    Parameters
    __________
        orient_file : name of azdip formatted input file
        samp_file : name of samples.txt formatted output file
        samp_con :  integer of sample orientation 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 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

        method_codes :  colon delimited string with the following as desired
             FS-FD field sampling done with a drill
             FS-H field sampling done with hand samples
             FS-LOC-GPS  field location done with GPS
             FS-LOC-MAP  field location done with map
             SO-POM   a Pomeroy orientation device was used
             SO-ASC   an ASC orientation device was used
             SO-MAG   orientation with magnetic compass
        location_name : location of samples
        append : boolean.  if True, append to the output file
        output_dir : path to output file directory
        input_dir : path to input file directory
        data_model : MagIC data model.

    INPUT FORMAT
        Input files must be space delimited:
            Samp  Az Dip Strike Dip
        Orientation convention:
             Lab arrow azimuth = mag_azimuth; Lab arrow dip = 90-field_dip
                e.g. field_dip is degrees from horizontal of drill direction
         Magnetic declination convention:
             Az is already corrected in file

    """
    #
    # initialize variables
    #
    data_model = int(data_model)
    if (data_model != 3) and (samp_file == "samples.txt"):
        samp_file = "er_samples.txt"
    if (data_model == 2) and (samp_file == "er_samples.txt"):
        samp_file = "samples.txt"
    DEBUG = 0
    version_num = pmag.get_version()
    or_con, corr = "3", "1"
    # date of sampling, latitude (pos North), longitude (pos East)
    date, lat, lon = "", "", ""
    bed_dip, bed_dip_dir = "", ""
    participantlist = ""
    sites = []   # list of site names
    Lats, Lons = [], []  # list of latitudes and longitudes
    # lists of Sample records and Site records
    SampRecs, SiteRecs, ImageRecs, imagelist = [], [], [], []
    average_bedding = "1", 1, "0"
    newbaseline, newbeddir, newbeddip = "", "", ""
    delta_u = "0"
    sclass, lithology, type = "", "", ""
    newclass, newlith, newtype = '', '', ''
    user = ""
    corr == "3"
    DecCorr = 0.
    samp_file = pmag.resolve_file_name(samp_file, output_dir)
    orient_file = pmag.resolve_file_name(orient_file, input_dir)
    input_dir = os.path.split(orient_file)[0]
    output_dir = os.path.split(samp_file)[0]
    #
    #
    if append:
        try:
            SampRecs, file_type = pmag.magic_read(samp_file)
            print("sample data to be appended to: ", samp_file)
        except:
            print('problem with existing samp file: ',
                  samp_file, ' will create new')
    #
    # read in file to convert
    #
    azfile = open(orient_file, 'r')
    AzDipDat = azfile.readlines()
    azfile.close()
    if not AzDipDat:
        return False, 'No data in orientation file, please try again'
    azfile.close()
    SampOut, samplist = [], []
    for line in AzDipDat:
        orec = line.split()
        if len(orec) > 2:
            labaz, labdip = pmag.orient(float(orec[1]), float(orec[2]), or_con)
            bed_dip = float(orec[4])
            if bed_dip != 0:
                bed_dip_dir = float(orec[3]) - \
                    90.  # assume dip to right of strike
            else:
                bed_dip_dir = float(orec[3])  # assume dip to right of strike
            MagRec = {}
            MagRec["er_location_name"] = location_name
            MagRec["er_citation_names"] = "This study"
    #
    # parse information common to all orientation methods
    #
            MagRec["er_sample_name"] = orec[0]
            MagRec["sample_bed_dip"] = '%7.1f' % (bed_dip)
            MagRec["sample_bed_dip_direction"] = '%7.1f' % (bed_dip_dir)
            MagRec["sample_dip"] = '%7.1f' % (labdip)
            MagRec["sample_azimuth"] = '%7.1f' % (labaz)
            methods = method_codes.replace(" ", "").split(":")
            OR = 0
            for method in methods:
                method_type = method.split("-")
                if "SO" in method_type:
                    OR = 1
            if OR == 0:
                method_codes = method_codes + ":SO-NO"
            MagRec["magic_method_codes"] = method_codes
            # parse out the site name
            site = pmag.parse_site(orec[0], samp_con, Z)
            MagRec["er_site_name"] = site
            MagRec['magic_software_packages'] = version_num
            SampOut.append(MagRec)
            if MagRec['er_sample_name'] not in samplist:
                samplist.append(MagRec['er_sample_name'])
    for samp in SampRecs:
        if samp not in samplist:
            SampOut.append(samp)
    Samps, keys = pmag.fillkeys(SampOut)
    if data_model == 2:
        # write to file
        pmag.magic_write(samp_file, Samps, "er_samples")
    else:
        # translate sample records to MagIC 3
        Samps3 = []
        for samp in Samps:
            Samps3.append(map_magic.mapping(
                samp, map_magic.samp_magic2_2_magic3_map))
        # write to file
        pmag.magic_write(samp_file, Samps3, "samples")
    print("Data saved in ", samp_file)
    return True, None


Instruction:
Can you generate the documentation for the following Python 3 function
def dayplot_magic(path_to_file='.', hyst_file="specimens.txt", rem_file='',
                  save=True, save_folder='.', fmt='svg', data_model=3,
                  interactive=False, contribution=None):
    """
    Makes 'day plots' (Day et al. 1977) and squareness/coercivity plots
    (Neel, 1955; plots after Tauxe et al., 2002); plots 'linear mixing'
    curve from Dunlop and Carter-Stiglitz (2006).

    Optional Parameters (defaults are used if not specified)
    ----------
    path_to_file : path to directory that contains files (default is current directory, '.')
    the default input file is 'specimens.txt' (data_model=3
    if data_model = 2, then must these are the defaults:
        hyst_file : hysteresis file (default is 'rmag_hysteresis.txt')
        rem_file : remanence file (default is 'rmag_remanence.txt')
    save : boolean argument to save plots (default is True)
    save_folder : relative directory where plots will be saved (default is current directory, '.')
    fmt : format of saved figures (default is 'pdf')
    """
    args = sys.argv
    hyst_path = os.path.join(path_to_file, hyst_file)
    if data_model == 2 and rem_file != '':
        rem_path = os.path.join(path_to_file, rem_file)
    # hyst_file,rem_file="rmag_hysteresis.txt","rmag_remanence.txt"
    dir_path = path_to_file
    verbose = pmagplotlib.verbose
    # initialize some variables
    # define figure numbers for Day,S-Bc,S-Bcr
    DSC = {}
    DSC['day'], DSC['S-Bc'], DSC['S-Bcr'], DSC['bcr1-bcr2'] = 1, 2, 3, 4
    hyst_data, file_type = pmag.magic_read(hyst_path)
    rem_data = []
    if data_model == 2 and rem_file != "":
        rem_data, file_type = pmag.magic_read(rem_path)
    S, BcrBc, Bcr2, Bc, hsids, Bcr = [], [], [], [], [], []
    Ms, Bcr1, Bcr1Bc, S1 = [], [], [], []
    locations = ''
    if data_model == 2:
        for rec in hyst_data:
            if 'er_location_name' in list(rec.keys()) and rec['er_location_name'] not in locations:
                locations = locations + rec['er_location_name'] + '_'
            if rec['hysteresis_bcr'] != "" and rec['hysteresis_mr_moment'] != "":
                S.append(old_div(float(rec['hysteresis_mr_moment']), float(
                    rec['hysteresis_ms_moment'])))
                Bcr.append(float(rec['hysteresis_bcr']))
                Bc.append(float(rec['hysteresis_bc']))
                BcrBc.append(old_div(Bcr[-1], Bc[-1]))
                if 'er_synthetic_name' in list(rec.keys()) and rec['er_synthetic_name'] != "":
                    rec['er_specimen_name'] = rec['er_synthetic_name']
                hsids.append(rec['er_specimen_name'])
        if len(rem_data) > 0:
            for rec in rem_data:
                if rec['remanence_bcr'] != "" and float(rec['remanence_bcr']) > 0:
                    try:
                        ind = hsids.index(rec['er_specimen_name'])
                        Bcr1.append(float(rec['remanence_bcr']))
                        Bcr1Bc.append(old_div(Bcr1[-1], Bc[ind]))
                        S1.append(S[ind])
                        Bcr2.append(Bcr[ind])
                    except ValueError:
                        if verbose:
                            print('hysteresis data for ',
                                  rec['er_specimen_name'], ' not found')
    else:
        fnames = {'specimens': hyst_file}
        if contribution:
            con = contribution
        else:
            con = cb.Contribution(dir_path, read_tables=['specimens'],
                                  custom_filenames=fnames)
        if 'specimens' not in con.tables:
            print('-E- No specimen file found in {}'.format(os.path.realpath(dir_path)))
            return False, []
        spec_container = con.tables['specimens']
        spec_df = spec_container.df

        # get as much data as possible for naming plots
        #if pmagplotlib.isServer:
        con.propagate_location_to_specimens()

        loc_list = []

        if 'location' in spec_df.columns:
            loc_list = spec_df['location'].unique()
        do_rem = bool('rem_bcr' in spec_df.columns)

        for ind, row in spec_df.iterrows():
            if row['hyst_bcr'] and row['hyst_mr_moment']:
                S.append(
                    old_div(float(row['hyst_mr_moment']), float(row['hyst_ms_moment'])))
                Bcr.append(float(row['hyst_bcr']))
                Bc.append(float(row['hyst_bc']))
                BcrBc.append(old_div(Bcr[-1], Bc[-1]))
                hsids.append(row['specimen'])
            if do_rem:
                if row['rem_bcr'] and float(row['rem_bcr']) > 0:
                    try:
                        Bcr1.append(float(row['rem_bcr']))
                        Bcr1Bc.append(old_div(Bcr1[-1], Bc[-1]))
                        S1.append(S[-1])
                        Bcr2.append(Bcr[-1])
                    except ValueError:
                        if verbose:
                            print('hysteresis data for ',
                                  row['specimen'], end=' ')
                            print(' not found')

    #
    # now plot the day and S-Bc, S-Bcr plots
    #
    fnames = {'day': os.path.join(save_folder, "_".join(loc_list) + '_Day.' + fmt),
          'S-Bcr': os.path.join(save_folder, "_".join(loc_list) + '_S-Bcr.' + fmt),
          'S-Bc': os.path.join(save_folder, "_".join(loc_list) + '_S-Bc.' + fmt)}
    if len(Bcr1) > 0:

        plt.figure(num=DSC['day'], figsize=(5, 5))
        #plt.figure(num=DSC['S-Bc'], figsize=(5, 5))
        plt.figure(num=DSC['S-Bcr'], figsize=(5, 5))
        plt.figure(num=DSC['bcr1-bcr2'], figsize=(5, 5))

        pmagplotlib.plot_day(DSC['day'], Bcr1Bc, S1, 'ro')
        pmagplotlib.plot_s_bcr(DSC['S-Bcr'], Bcr1, S1, 'ro')
        #pmagplotlib.plot_init(DSC['bcr1-bcr2'], 5, 5)
        pmagplotlib.plot_bcr(DSC['bcr1-bcr2'], Bcr1, Bcr2)
        fnames.pop('S-Bc')
        fnames['bcr1-bcr2'] = os.path.join(save_folder, 'bcr1-bcr2.png')
        DSC.pop('S-Bc')
        if pmagplotlib.isServer:
            for key in list(DSC.keys()):
                fnames[key] = 'LO:_' + ":".join(set(loc_list)) + '_' + 'SI:__SA:__SP:__TY:_' + key + '_.' + fmt
        if save:
            pmagplotlib.save_plots(DSC, fnames, incl_directory=True)
            return True, fnames.values()
        if interactive:
            pmagplotlib.draw_figs(DSC)
            ans = pmagplotlib.save_or_quit()
            if ans == 'a':
                pmagplotlib.save_plots(DSC, fnames, incl_directory=True)
                return True, fnames.values()

    else:
        plt.figure(num=DSC['day'], figsize=(5, 5))
        plt.figure(num=DSC['S-Bc'], figsize=(5, 5))
        plt.figure(num=DSC['S-Bcr'], figsize=(5, 5))
        #plt.figure(num=DSC['bcr1-bcr2'], figsize=(5, 5))
        del DSC['bcr1-bcr2']
        # do other plots instead
        pmagplotlib.plot_day(DSC['day'], BcrBc, S, 'bs')
        pmagplotlib.plot_s_bcr(DSC['S-Bcr'], Bcr, S, 'bs')
        pmagplotlib.plot_s_bc(DSC['S-Bc'], Bc, S, 'bs')
    if pmagplotlib.isServer:
        for key in list(DSC.keys()):
            fnames[key] = 'LO:_' + ":".join(set(loc_list)) + '_' + 'SI:__SA:__SP:__TY:_' + key + '_.' + fmt
    if save:
        pmagplotlib.save_plots(DSC, fnames, incl_directory=True)
        return True, fnames.values()
    elif interactive:
        pmagplotlib.draw_figs(DSC)
        ans = pmagplotlib.save_or_quit()
        if ans == 'a':
            pmagplotlib.save_plots(DSC, fnames, incl_directory=True)
            return True, fnames.values()
    return True, []

Response: Function that creates a dayplot of the magic files.