Exemplo n.º 1
0
def main():
    """
    NAME
        HUJI_magic.py
 
    DESCRIPTION
        converts Hebrew University, Jerusalem format files to magic_measurements format files

    SYNTAX
        HUJI_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -usr USER:   identify user, default is ""
        -f FILE: specify HUJI format input file, required
        -F FILE: specify output file, default is magic_measurements.txt
        -LP [colon delimited list of protocols, include all that apply]
            AF:  af demag
            T: thermal including thellier but not trm acquisition
            N: NRM only
            TRM: trm acquisition
            ANI: anisotropy experiment
            G: triple AF demag (GRM protocol)
        -spc NUM : specify number of characters to designate a  specimen, default = 0
        -loc LOCNAME : specify location/study name, must have either LOCNAME 
        -dc B PHI THETA: dc lab field (in micro tesla) and phi,theta, default is none
              NB: use PHI, THETA = -1 -1 to signal that it changes, i.e. in anisotropy experiment
        -ac B : peak AF field (in mT) for ARM acquisition, default is none
        -ncn NCON:  specify naming convention: default is #1 below
        -A: don't average replicate measurements
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            [8] this is a synthetic sample with no site name
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 
    INPUT
        Best to put separate experiments (all AF, thermal, thellier, trm aquisition, Shaw, etc.) in 
           seperate files (eg. af.txt, thermal.txt, etc.)
        
        Spec: specimen name
        Treat:  treatment step
            XXX T in Centigrade
            XXX AF in mT
            for special experiments:
              Thellier:
                XXX.0  first zero field step
                XXX.1  first in field step [XXX.0 and XXX.1 can be done in any order]
                XXX.2  second in-field step at lower temperature (pTRM check)
                XXX.3  second zero-field step after infield (pTRM check step)
                       XXX.3 MUST be done in this order [XXX.0, XXX.1 [optional XXX.2] XXX.3]
              AARM:
                X.00  baseline step (AF in zero bias field - high peak field)
                X.1   ARM step (in field step)  where
                   X is the step number in the 15 position scheme 
                      (see Appendix to Lecture 13 - Lectures in Paleomagnetism, 2007)
              TRM:
                XXX.YYY  XXX is temperature step of total TRM
                         YYY is dc field in microtesla
         
         Intensity assumed to be total moment in 10^3 Am^2 (emu)
         Declination:  Declination in geographic coordinate system
         Inclination:  Declination in geographic coordinate system

    """
# initialize some stuff
    WD="."
    version_num=pmag.get_version()
    noave=0
    methcode,inst="",""
    phi,theta,peakfield,labfield=0,0,0,0
    pTRM,MD,samp_con,Z=0,0,'1',1
    dec=[315,225,180,135,45,90,270,270,270,90,180,180,0,0,0] # applied field for remanence anisotropy directions
    inc=[0,0,0,0,0,-45,-45,0,45,45,45,-45,-90,-45,45]
    demag="N"
    er_location_name=""
    citation='This study'
    args=sys.argv
    methcode="LP-NO" # NRM
    syn=0
    synfile='er_synthetics.txt'
    samp_file,site_file,ErSamps='er_samples.txt','er_sites.txt',[]
    samp_file_in=""
    meas_file="magic_measurements.txt"
    trm=0
    irm=0
    specnum=-1
#
# get command line arguments
#
    user=""
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind=args.index("-usr")
        user=args[ind+1]
    if '-F' in args:
        ind=args.index("-F")
        meas_file=args[ind+1]
    if '-Fsa' in args:
        ind=args.index("-Fsa")
        samp_file=args[ind+1]
        try:
            open(samp_file,'rU')
            ErSamps,file_type=pmag.magic_read(samp_file)
            print 'sample information will be appended to new er_samples.txt file'
        except:
            print 'sample information will be stored in new er_samples.txt file'
    if '-f' in args:
        ind=args.index("-f")
        magfile=args[ind+1]
        try:
            input=open(magfile,'rU')
        except:
            print "bad input file name"
            sys.exit()
    else: 
        print "mag_file field is required option"
        print main.__doc__
        sys.exit()
    if "-dc" in args:
        ind=args.index("-dc")
        labfield=float(args[ind+1])*1e-6
        phi=float(args[ind+2])
        theta=float(args[ind+3])
    if "-ac" in args:
        ind=args.index("-ac")
        peakfield=float(args[ind+1])*1e-3
    if "-spc" in args:
        ind=args.index("-spc")
        specnum=int(args[ind+1])
        if specnum!=0:specnum=-specnum
    if "-loc" in args:
        ind=args.index("-loc")
        er_location_name=args[ind+1]
    if '-syn' in args:
        syn=1
        ind=args.index("-syn")
        institution=args[ind+1]
        syntype=args[ind+2]
        if '-fsy' in args:
            ind=args.index("-fsy")
            synfile=args[ind+1]
    if "-A" in args: noave=1
    if "-ncn" in args:
        ind=args.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="7"
    if '-LP' in args:
        ind=args.index("-LP")
        codelist=args[ind+1]
        codes=codelist.split(':')
        if "AF" in codes:
            demag='AF' 
            if'-dc' not in args: methcode="LT-AF-Z"
            if'-dc' in args: methcode="LT-AF-I"
        if "T" in codes:
            demag="T"
            if '-dc' not in args: methcode="LT-T-Z"
            if '-dc' in args: methcode="LT-T-I"
        if "I" in codes:
            methcode="LP-IRM"
        if "G" in codes: methcode="LT-AF-G"
        if "TRM" in codes: 
            trm=1
            noave=1
    if demag=="T" and "ANI" in codes:
        methcode="LP-AN-TRM"
    if demag=="AF" and "ANI" in codes:
        methcode="LP-AN-ARM"
        if labfield==0: labfield=50e-6
        if peakfield==0: peakfield=180
    SynRecs,MagRecs=[],[]
    Data=input.readlines()
    for line in Data:
        instcode="HUJI-2G"
        if len(line)>1:
            rec=line.split()
            if rec[0][0]!='#': # HUJI way of marking bad data points
                SynRec={}
                MagRec={}
                MagRec['er_location_name']=er_location_name
                MagRec['magic_software_packages']=version_num
                MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
                MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
                MagRec["treatment_ac_field"]='0'
                MagRec["treatment_dc_field"]='0'
                MagRec["treatment_dc_field_phi"]='0'
                MagRec["treatment_dc_field_theta"]='0'
                meas_type="LT-NO"
                mmddyy=rec[2].split('/') # break date into mon/day/year
                hhmm=rec[3]
                yyyy=mmddyy[2]
                mm=int(mmddyy[0])
                if mm<10:
                    mm="0"+str(mm)
                else: 
                    mm=str(mm)
                dd=int(mmddyy[1])
                if dd<10:
                    dd="0"+str(dd)
                else: 
                    dd=str(dd)
                    time=mmddyy[1].split(':')
                MagRec["measurement_date"]=yyyy+":"+mm+":"+dd+":"+hhmm+":00.00"
                MagRec["measurement_time_zone"]='30'
                MagRec["measurement_positions"]='1'
                if rec[4]=='T': demag="T"
                if rec[4]=='A': demag="AF"
                MagRec["er_specimen_name"]=rec[0]
                if specnum!=0:
                    MagRec["er_sample_name"]=rec[0][:specnum]
                else:
                    MagRec["er_sample_name"]=rec[0]
                if samp_con!='8':
                    site=pmag.parse_site(MagRec['er_sample_name'],samp_con,Z)
                    MagRec["er_site_name"]=site
                    MagRec["er_location_name"]=er_location_name
                else: 
                    MagRec["er_site_name"]=""
                    MagRec["er_location_name"]=""
                    MagRec["er_synthetic_name"]=rec[0]
                treat=rec[5].split('.')
                if len(treat)==1:treat.append('.0')
                if demag=="AF":
                    if methcode != "LP-AN-ARM":
                        MagRec["treatment_ac_field"]='%8.3e' %(float(treat[0])*1e-3) # peak field in tesla
                        meas_type="LT-AF-Z"
                        MagRec["treatment_dc_field"]='0'
                    else: # AARM experiment
                        if treat[1][0]=='0':
                            meas_type="LT-AF-Z"
                            MagRec["treatment_ac_field"]='%8.3e' %(peakfield) # peak field in tesla
                            MagRec["treatment_dc_field"]='%8.3e'%(0)
                            if labfield!=0: print "inconsistency in mag file with lab field"
                        else:
                            meas_type="LT-AF-I"
                            ipos=int(treat[0])-1
                            MagRec["treatment_dc_field_phi"]='%7.1f' %(dec[ipos])
                            MagRec["treatment_dc_field_theta"]='%7.1f'% (inc[ipos])
                            MagRec["treatment_dc_field"]='%8.3e'%(labfield)
                            MagRec["treatment_ac_field"]='%8.3e' %(peakfield) # peak field in tesla
                else:  # thermal treatment
                  MagRec["treatment_temp"]='%8.3e' % (float(treat[0])+273.) # temp in kelvin
                  if trm==0:  # demag=T and not trmaq
                    if treat[1][0]=='0':
                        meas_type="LT-T-Z"
                    else: 
                        MagRec["treatment_dc_field"]='%8.3e' % (labfield) # labfield in tesla (convert from microT)
                        MagRec["treatment_dc_field_phi"]='%7.1f' % (phi) # labfield phi
                        MagRec["treatment_dc_field_theta"]='%7.1f' % (theta) # labfield theta
                        if treat[1][0]=='1':meas_type="LT-T-I" # in-field thermal step
                        if treat[1][0]=='2':
                            meas_type="LT-PTRM-I" # pTRM check
                            pTRM=1
                        if treat[1][0]=='3':
                            MagRec["treatment_dc_field"]='0'  # this is a zero field step
                            meas_type="LT-PTRM-MD" # pTRM tail check
                  else: 
                    meas_type="LT-T-I" # trm acquisition experiment
                    MagRec["treatment_dc_field"]='%8.3e' % (float(treat[1])*1e-6) # labfield in tesla (convert from microT)
                MagRec["measurement_magn_moment"]='%10.3e'% (float(rec[10])*1e-3) # moment in Am^2 (from emu)
                MagRec["measurement_dec"]=rec[6]
                MagRec["measurement_inc"]=rec[7]
                MagRec["magic_instrument_codes"]=instcode
                MagRec["er_citation_names"]=citation
                MagRec["magic_method_codes"]=meas_type
                MagRec["measurement_flag"]='g'
                MagRec["measurement_standard"]='u'
                MagRec["measurement_number"]='1'
                MagRecs.append(MagRec) 
            else:
                print 'skipping: ',rec[0]
    MagOuts=pmag.measurements_methods(MagRecs,noave)
    pmag.magic_write(meas_file,MagOuts,'magic_measurements')
    print "results put in ",meas_file
Exemplo n.º 2
0
def main():
    """
    NAME
        LIVMW_magic.py
 
    DESCRIPTION
        converts Liverpool microwave format files to magic_measurements format files

    SYNTAX
        LIVMW_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -f FILE: specify liverpool format input file, required
        -usr USER:   identify user, default is ""
        -ins INST:   identify instrument, e.g., LIV-TRISTAN, LIV-OLD14GHZ, default is ""
        -loc LOCNAME : specify location/study name, required
        -F FILE: specify output file, default is magic_measurements.txt
        -Fsa FILE: specify er_samples formatted  file for appending, default is new er_samples.txt
        -spc NUM : specify number of characters to designate a  specimen, default = 1
        -sit Site_name : specify site name for this specimen
        -unc measurement units are uncalibrated (default is uAm^2)
        -B PHI THETA: dc lab field phi, theta, default is 0, 90
        -ncn NCON:  specify naming convention  - required if -sit not specified
       Sample naming convention:
            do not use if -sit option used!
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 

    """
    # initialize some stuff
    version_num = pmag.get_version()
    noave = 0
    methcode, instcode = "", ""
    phi, theta, peakfield, labfield = 0, 0, 0, 0
    pMRM, MD, samp_con, Z, site = 0, 0, "6", "", ""
    er_location_name = ""
    citation = "This study"
    args = sys.argv
    methcode = "LP-NO"  # NRM
    specnum, measnum = 1, 1
    powt_max = 0
    ErSamps, Samps = [], []
    #
    # get command line arguments
    #
    dirpath = "."
    meas_file, samp_file = dirpath + "/magic_measurements.txt", dirpath + "/er_samples.txt"
    user = ""
    unc = 0
    if "-WD" in args:
        ind = args.index("-WD")
        dirpath = args[ind + 1]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind = args.index("-usr")
        user = args[ind + 1]
    if "-ins" in args:
        ind = args.index("-ins")
        instcode = args[ind + 1]
    if "-F" in args:
        ind = args.index("-F")
        meas_file = dirpath + "/" + args[ind + 1]
    if "-Fsa" in args:
        ind = args.index("-Fsa")
        samp_file = args[ind + 1]
        samp_file = dirpath + "/" + samp_file
        try:
            open(samp_file, "rU")
            ErSamps, file_type = pmag.magic_read(samp_file)
            print "sample information will be appended to new er_samples.txt file"
        except:
            print "er_samples.txt file does not exist"
            print "sample information will be stored in new er_samples.txt file"
    if "-f" in args:
        ind = args.index("-f")
        magfile = args[ind + 1]
        magfile = dirpath + "/" + magfile
        try:
            input = open(magfile, "rU")
        except:
            print "bad mag file name"
            sys.exit()
    else:
        print "mag_file field is required option"
        print main.__doc__
        sys.exit()
    if "-B" in args:
        ind = args.index("-B")
        phi = args[ind + 1]
        theta = args[ind + 2]
    else:
        phi, theta = "0.", "90."
    if "-spc" in args:
        ind = args.index("-spc")
        specnum = int(args[ind + 1])
        if specnum != 0:
            specnum = -specnum
    if "-loc" in args:
        ind = args.index("-loc")
        er_location_name = args[ind + 1]
    if "-unc" in args:
        unc = 1
    if "-sit" in args:
        ind = args.index("-sit")
        site = args[ind + 1]
    if "-ncn" in args:
        ind = args.index("-ncn")
        samp_con = sys.argv[ind + 1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z = samp_con.split("-")[1]
                samp_con = "4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z = samp_con.split("-")[1]
                samp_con = "7"
    if samp_con == "6" and site == "":
        print "you must either specify a naming convention, or a site name"
        print main.__doc__
        sys.exit()
    MagRecs = []
    if len(ErSamps) > 1:
        for samp in ErSamps:
            if samp["er_sample_name"] not in Samps:
                Samps.append(samp["er_sample_name"])
    Data = input.readlines()
    if 1:  # never mind
        for line in Data:
            if len(line) > 1:
                rec = line.split(",")
                MagRec = {}
                MagRec["er_citation_names"] = "This study"
                MagRec["er_location_name"] = er_location_name
                MagRec["magic_software_packages"] = version_num
                MagRec["treatment_temp"] = "%8.3e" % (273)  # room temp in kelvin
                MagRec["measurement_temp"] = "%8.3e" % (273)  # room temp in kelvin
                MagRec["treatment_ac_field"] = "0"
                MagRec["treatment_dc_field"] = "0"
                MagRec["treatment_dc_field_phi"] = ""
                MagRec["treatment_dc_field_theta"] = ""
                MagRec["treatment_mw_integral"] = ""
                meas_type = "LT-NO"
                MagRec["er_specimen_name"] = rec[0][1:-1]
                MagRec["er_location_name"] = er_location_name
                if specnum != 0:
                    MagRec["er_sample_name"] = rec[0][1:-1][:specnum]
                else:
                    MagRec["er_sample_name"] = rec[0][1:-1]
                if site == "":
                    site = pmag.parse_site(MagRec["er_sample_name"], samp_con, Z)
                MagRec["er_site_name"] = site
                MagRec["treatment_mw_power"] = rec[2]
                MagRec["treatment_mw_time"] = rec[3]
                powt = int(float(MagRec["treatment_mw_power"]) * (float(MagRec["treatment_mw_time"])))
                MagRec["treatment_mw_energy"] = "%7.1f" % (powt)
                if powt > powt_max:
                    powt_max = powt
                treat = rec[1].strip('"').upper()
                if treat == "Z":  #  in zero field
                    meas_type = "LT-M-Z"  #  as opposed to LT-MV-Z
                    if powt < powt_max:
                        meas_type = "LT-PMRM-Z"
                elif treat == "A":  #  in zero field
                    meas_type = "LT-M-I"  #  as opposed to LT-MV-I
                    labfield = float(rec[10]) * 1e-6  # assuming uT, convert to T
                    MagRec["treatment_dc_field"] = "%8.3e" % (labfield)  # labfield in tesla (convert from microT)
                    MagRec["treatment_dc_field_phi"] = phi  # labfield phi
                    MagRec["treatment_dc_field_theta"] = theta  # labfield theta
                    if powt < powt_max:
                        meas_type = "LT-PMRM-I"
                if len(rec) > 10:
                    MagRec["treatment_mw_integral"] = rec[10]
                if unc == 0:
                    MagRec["measurement_magn_moment"] = "%10.3e" % (float(rec[4]) * 1e-6)  # moment in Am^2 (from uAm^2)
                if unc == 1:
                    MagRec["measurement_magnitude"] = rec[4]  # uncalibrated moment
                cart = []
                cart.append(float(rec[7]))
                cart.append(float(rec[8]))
                cart.append(float(rec[9]))
                dir = pmag.cart2dir(cart)
                MagRec["measurement_dec"] = "%9.3f" % (dir[0])
                MagRec["measurement_inc"] = "%9.3f" % (dir[1])
                MagRec["magic_instrument_codes"] = instcode
                MagRec["magic_method_codes"] = meas_type
                MagRec["measurement_flag"] = "g"
                MagRec["measurement_standard"] = "u"
                MagRec["measurement_number"] = "%i" % (measnum)
                MagRec["magic_experiment_name"] = MagRec["er_specimen_name"] + ":" + methcode
                measnum += 1
                MagRecs.append(MagRec)
                if MagRec["er_sample_name"] not in Samps:  # add this puppy to the list in er_samples.txt
                    Samps.append(MagRec["er_sample_name"])
                    ErSamp = {}
                    ErSamp["er_sample_name"] = Samps[-1]
                    ErSamp["er_location_name"] = MagRec["er_location_name"]
                    ErSamp["er_site_name"] = site
                    ErSamp["er_citation_names"] = "This study"
                    gdec = float(rec[5])
                    ginc = float(rec[6])
                    az, pl = pmag.get_azpl(dir[0], dir[1], gdec, ginc)
                    ErSamp["sample_azimuth"] = "%7.1f" % az
                    ErSamp["sample_dip"] = "%7.1f" % pl
                    ErSamps.append(ErSamp)
    MagOuts = pmag.mw_measurements_methods(MagRecs)
    pmag.magic_write(meas_file, MagOuts, "magic_measurements")
    print "measurements put in ", meas_file
    pmag.magic_write(samp_file, ErSamps, "er_samples")
    print "sample names put in ", samp_file
Exemplo n.º 3
0
def main():
    """
    NAME
        MsT_magic.py
 
    DESCRIPTION
        converts MsT data (T,M) to magic_measurements format files

    SYNTAX
        MsT_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -usr USER:   identify user, default is ""
        -f FILE: specify T,M  format input file, required
        -fsa SFILE: name with sample, site, location information
        -F FILE: specify output file, default is MsT_measurements.txt
        -dc H: specify applied field during measurement, default is 0.5 T
        -syn  : This is a synthetic specimen and has no sample/site/location information
        -spn SPEC: specimen name 
        -spc NUM : specify number of characters to designate a  specimen, default = 0
        -loc LOCNAME : specify location/study name, must have either LOCNAME or SAMPFILE or be a synthetic
        -ncn NCON:  specify naming convention: default is #1 below
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
        INPUT files: 
            T M:  T is in Centigrade and M is uncalibrated magnitude

    """
# initialize some stuff
    samp_con,Z="1","0"
    dir_path='.'
    citation='This study'
    args=sys.argv
    specnum,measnum=0,1
#
# get command line arguments
#
    user=""
    if '-WD' in args:
        ind=args.index("-WD")
        dir_path=args[ind+1]
    meas_file=dir_path+"/MsT_measurements.txt"
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind=args.index("-usr")
        user=args[ind+1]
    labfield='0.5'
    if "-dc" in args:
        ind=args.index("-dc")
        labfield=args[ind+1]
    if '-F' in args:
        ind=args.index("-F")
        meas_file=dir_path+'/'+args[ind+1]
    if "-fsa" in args:
        ind=args.index("-fsa")
        samp_file=dir_path+'/'+args[ind+1]
        Samps,file_type=pmag.magic_read(samp_file)
    if '-f' in args:
        ind=args.index("-f")
        infile=dir_path+'/'+args[ind+1]
        try:
            input=open(infile,'rU')
        except:
            print "bad mag file name"
            sys.exit()
    else: 
        print main.__doc__
        print "-f  is required option"
        sys.exit()
    if "-spc" in args:
        ind=args.index("-spc")
        specnum=int(args[ind+1])
        if specnum!=0:specnum=-specnum
    er_location_name,syn,specimen_name='unknown',0,'unknown'
    if "-loc" in args:
        ind=args.index("-loc")
        er_location_name=args[ind+1]
    if "-spn" in args:
        ind=args.index("-spn")
        specimen_name=args[ind+1]
    else: 
        print main.__doc__
        print "-spn  is required option"
        sys.exit()
    if "-syn" in args: syn=1
    if "-ncn" in args:
        ind=args.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
            samp_con=sys.argv[ind+1]
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="7"
    MagRecs,specs=[],[]
    version_num=pmag.get_version()
    data=input.readlines()
    T0=float(data[0].split()[0])
    for line in data:
        instcode=""
        if len(line)>1:
            MagRec={}
            if syn==0: MagRec['er_location_name']=er_location_name
            MagRec['magic_software_packages']=version_num
            MagRec["treatment_dc_field"]=labfield
            rec=line.split()
            T=float(rec[0])
            MagRec["measurment_temp"]='%8.3e' % (float(rec[0])+273.) # temp in kelvin
            if T>T0:
                MagRec["magic_method_codes"]='LP-MW-I'
            elif T<T0:
                MagRec["magic_method_codes"]='LP-MC-I'
                T0=T 
            else:
                print 'skipping repeated temperature step'
                MagRec["magic_method_codes"]=''
            T0=T 
            MagRec["measurement_magnitude"]='%10.3e'% (float(rec[1])) # uncalibrated magnitude
            if syn==0:
                MagRec["er_specimen_name"]=specimen_name
                MagRec["er_site_name"]=""
                if specnum!=0:
                    MagRec["er_sample_name"]=specimen_name[:specnum]
                else:
                    MagRec["er_sample_name"]=specimen_name
                if "-fsa" in args:
                    for samp in Samps:
                        if samp["er_sample_name"] == MagRec["er_sample_name"]:
                            MagRec["er_location_name"]=samp["er_location_name"]
                            MagRec["er_site_name"]=samp["er_site_name"]
                            break
                elif int(samp_con)!=6:
                    site=pmag.parse_site(MagRec['er_sample_name'],samp_con,Z)
                    MagRec["er_site_name"]=site
                if MagRec['er_site_name']=="":
                    print 'No site name found for: ',MagRec['er_specimen_name'],MagRec['er_sample_name']
                if MagRec["er_location_name"]=="":
                    print 'no location name for: ',MagRec["er_specimen_name"] 
            else:
                MagRec["er_synthetic_name"]=specimen_name
                MagRec["er_location_name"]=""
                MagRec["er_sample_name"]=""
                MagRec["er_site_name"]=""
                MagRec["er_specimen_name"]=""
            MagRec["magic_instrument_codes"]=instcode
            MagRec["er_analyst_mail_names"]=user
            MagRec["er_citation_names"]=citation
            MagRec["measurement_flag"]='g'
            MagRec["measurement_number"]=str(measnum)
            measnum+=1
            MagRecs.append(MagRec) 
    for rec in MagRecs: # sort out the measurements by experiment type
        rec['magic_experiment_name']=specimen_name
        if rec['magic_method_codes']=='LP-MW-I':
            rec["magic_experiment_name"]=specimen_name+':LP-MW-I:Curie'
        elif rec['magic_method_codes']=='LP-MC-I':
            rec["magic_experiment_name"]=specimen_name+':LP-MC-I'
    pmag.magic_write(meas_file,MagRecs,'magic_measurements')
    print "results put in ",meas_file
Exemplo n.º 4
0
def main():
    """
    NAME
        k15_magic.py

    DESCRIPTION
        converts .k15 format data to magic_measurements  format.
        assums Jelinek Kappabridge measurement scheme
   
    SYNTAX 
        k15_magic.py [-h] [command line options]
    
    OPTIONS
        -h prints help message and quits
        -f KFILE: specify .k15 format input file
        -F MFILE: specify magic_measurements format output file
        -Fsa SFILE, specify er_samples format file for output 
        -Fa AFILE, specify rmag_anisotropy format file for output
        -loc LOC: specify location name for study
        -ins INST: specify instrument that measurements were made on
        -spc NUM: specify number of digets for specimen ID, default is 0
        -ncn NCOM: specify naming convention (default is #1)
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXXYYY:  YYY is sample designation with Z characters from site XXX
            [5] sample = site
            [6] sample, site, location info in er_samples.txt
            [7] all others you will have to either customize your

    DEFAULTS
        MFILE: k15_measurements.txt
        SFILE: er_samples.txt
        AFILE: rmag_anisotropy.txt
        LOC: unknown
        INST: unknown
        
    INPUT
      name [az,pl,strike,dip], followed by
      3 rows of 5 measurements for each specimen

    """
#
# initialize some variables
#
    version_num=pmag.get_version()
    specnum=0
    sampfile, measfile="er_samples.txt","k15_measurements.txt"
    anisfile='rmag_anisotropy.txt'
    resfile='rmag_results.txt'
    syn=0
    er_location_name="unknown"
    inst="unknown"
    itilt,igeo,linecnt,key=0,0,0,"" 
    first_save=1
    k15,specnum=[],0 
    citation='This study'
    dir_path='.'
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
# pick off stuff from command line
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        k15file=sys.argv[ind+1] 
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        measfile=sys.argv[ind+1] 
    if '-Fsa' in sys.argv:
        ind=sys.argv.index('-Fsa')
        sampfile=sys.argv[ind+1] 
    if '-Fa' in sys.argv:
        ind=sys.argv.index('-Fa')
        anisfile=sys.argv[ind+1] 
    if '-loc' in sys.argv:
        ind=sys.argv.index('-loc')
        er_location_name=sys.argv[ind+1] 
    if '-spc' in sys.argv:
        ind=sys.argv.index('-spc')
        specnum=-int(sys.argv[ind+1])
    samp_con,Z="1",""
    if "-ncn" in sys.argv:
        ind=sys.argv.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
        if samp_con=='6':
            Samps,filetype=pmag.magic_read(dirpath+'/er_samples.txt')
    sampfile, measfile=dir_path+'/'+sampfile,dir_path+'/'+measfile
    anisfile=dir_path+'/'+anisfile
    resfile=dir_path+'/'+resfile
    k15file=dir_path+'/'+k15file
    try:
        SampRecs,filetype=pmag.magic_read(sampfile) # append new records to existing
        samplist=[]
        for samp in SampRecs:
            if samp['er_sample_name'] not in samplist:samplist.append(samp['er_sample_name'])
    except IOError:
        SampRecs=[]
    # measurement directions for Jelinek 1977 protocol:
    Decs=[315,225,180,135,45,90,270,270,270,90,180,180,0,0,0]
    Incs=[0,0,0,0,0,-45,-45,0,45,45,45,-45,-90,-45,45]
    # some defaults to read in  .k15 file format
    # list of measurements and default number of characters for specimen ID
# some magic default definitions
    #
    # read in data
    input=open(k15file,'rU')
    MeasRecs,SpecRecs,AnisRecs,ResRecs=[],[],[],[]
    # read in data
    MeasRec,SpecRec,SampRec,SiteRec,AnisRec,ResRec={},{},{},{},{},{}
    for line in input.readlines():
            linecnt+=1
            rec=line.split()
            if linecnt==1:
                MeasRec["magic_method_codes"]=""
                SpecRec["magic_method_codes"]=""
                SampRec["magic_method_codes"]=""
                AnisRec["magic_method_codes"]=""
                SiteRec["magic_method_codes"]=""
                ResRec["magic_smethod_codes"]=""
                MeasRec["magic_software_packages"]=version_num
                SpecRec["magic_software_packages"]=version_num
                SampRec["magic_software_packages"]=version_num
                AnisRec["magic_software_packages"]=version_num
                SiteRec["magic_software_packages"]=version_num
                ResRec["magic_software_packages"]=version_num
                MeasRec["magic_method_codes"]="LP-X"
                MeasRec["measurement_flag"]="g"
                MeasRec["measurement_standard"]="u"
                MeasRec["er_citation_names"]="This study"
                SpecRec["er_citation_names"]="This study"
                SampRec["er_citation_names"]="This study"
                AnisRec["er_citation_names"]="This study"
                ResRec["er_citation_names"]="This study"
                MeasRec["er_specimen_name"]=rec[0]
                MeasRec["magic_experiment_name"]=rec[0]+":LP-AN-MS"
                AnisRec["magic_experiment_names"]=rec[0]+":AMS"
                ResRec["magic_experiment_names"]=rec[0]+":AMS"
                SpecRec["er_specimen_name"]=rec[0]
                AnisRec["er_specimen_name"]=rec[0]
                SampRec["er_specimen_name"]=rec[0]
                ResRec["rmag_result_name"]=rec[0]
                if specnum!=0: MeasRec["er_sample_name"]=rec[0][:specnum]
                if specnum==0: MeasRec["er_sample_name"]=rec[0]
                SampRec["er_sample_name"]=MeasRec["er_sample_name"]
                SpecRec["er_sample_name"]=MeasRec["er_sample_name"]
                AnisRec["er_sample_name"]=MeasRec["er_sample_name"]
                ResRec["er_sample_names"]=MeasRec["er_sample_name"]
                if samp_con=="6":
                    for samp in Samps:
                        if samp['er_sample_name']==AnisRec["er_sample_name"]:
                            sitename=samp['er_site_name']
                            er_location_name=samp['er_location_name']
                elif samp_con!="":
                    sitename=pmag.parse_site(AnisRec['er_sample_name'],samp_con,Z)
                MeasRec["er_site_name"]=sitename
                MeasRec["er_location_name"]=er_location_name
                SampRec["er_site_name"]=MeasRec["er_site_name"]
                SpecRec["er_site_name"]=MeasRec["er_site_name"]
                AnisRec["er_site_name"]=MeasRec["er_site_name"]
                ResRec["er_site_names"]=MeasRec["er_site_name"]
                SampRec["er_location_name"]=MeasRec["er_location_name"]
                SpecRec["er_location_name"]=MeasRec["er_location_name"]
                AnisRec["er_location_name"]=MeasRec["er_location_name"]
                ResRec["er_location_names"]=MeasRec["er_location_name"]
                if len(rec)>=3: 
                    SampRec["sample_azimuth"],SampRec["sample_dip"]=rec[1],rec[2]
                    az,pl,igeo=float(rec[1]),float(rec[2]),1
                if len(rec)==5: 
                    SampRec["sample_bed_dip_direction"],SampRec["sample_bed_dip"]= '(%7.1f)'%(90.+float(rec[3])),(rec[4])
                    bed_az,bed_dip,itilt,igeo=90.+float(rec[3]),float(rec[4]),1,1
            else: 
                for i in range(5):
                    k15.append(1e-6*float(rec[i])) # assume measurements in micro SI
                if linecnt==4:
                    sbar,sigma,bulk=pmag.dok15_s(k15) 
                    hpars=pmag.dohext(9,sigma,sbar) 
                    MeasRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
                    MeasRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
                    for i in range(15):
                        NewMeas=copy.deepcopy(MeasRec)
                        NewMeas["measurement_orient_phi"]='%7.1f' %(Decs[i])
                        NewMeas["measurement_orient_theta"]='%7.1f'% (Incs[i])
                        NewMeas["measurement_chi_volume"]='%12.10f'% (k15[i])
                        NewMeas["measurement_number"]='%i'% (i+1)
                        NewMeas["magic_experiment_name"]=rec[0]+":LP-AN-MS"
                        MeasRecs.append(NewMeas)
                    if SampRec['er_sample_name'] not in samplist:
                        SampRecs.append(SampRec)
                        samplist.append(SampRec['er_sample_name'])
                    SpecRecs.append(SpecRec)
                    AnisRec["anisotropy_type"]="AMS"
                    ResRec["anisotropy_type"]="AMS"
                    AnisRec["anisotropy_s1"]='%12.10f'%(sbar[0])
                    AnisRec["anisotropy_s2"]='%12.10f'%(sbar[1])
                    AnisRec["anisotropy_s3"]='%12.10f'%(sbar[2])
                    AnisRec["anisotropy_s4"]='%12.10f'%(sbar[3])
                    AnisRec["anisotropy_s5"]='%12.10f'%(sbar[4])
                    AnisRec["anisotropy_s6"]='%12.10f'%(sbar[5])
                    AnisRec["anisotropy_mean"]='%12.10f'%(bulk)
                    AnisRec["anisotropy_sigma"]='%12.10f'%(sigma)
                    AnisRec["anisotropy_unit"]='SI'
                    AnisRec["anisotropy_n"]='15'
                    AnisRec["anisotropy_tilt_correction"]='-1'
                    AnisRec["magic_method_codes"]='LP-X:AE-H:LP-AN-MS'
                    AnisRecs.append(AnisRec)
                    ResRec["magic_method_codes"]='LP-X:AE-H:LP-AN-MS'
                    ResRec["anisotropy_tilt_correction"]='-1'
                    ResRec["anisotropy_t1"]='%12.10f'%(hpars['t1'])
                    ResRec["anisotropy_t2"]='%12.10f'%(hpars['t2'])
                    ResRec["anisotropy_t3"]='%12.10f'%(hpars['t3'])
                    ResRec["anisotropy_fest"]='%12.10f'%(hpars['F'])
                    ResRec["anisotropy_ftest12"]='%12.10f'%(hpars['F12'])
                    ResRec["anisotropy_ftest23"]='%12.10f'%(hpars['F23'])
                    ResRec["anisotropy_v1_dec"]='%7.1f'%(hpars['v1_dec'])
                    ResRec["anisotropy_v2_dec"]='%7.1f'%(hpars['v2_dec'])
                    ResRec["anisotropy_v3_dec"]='%7.1f'%(hpars['v3_dec'])
                    ResRec["anisotropy_v1_inc"]='%7.1f'%(hpars['v1_inc'])
                    ResRec["anisotropy_v2_inc"]='%7.1f'%(hpars['v2_inc'])
                    ResRec["anisotropy_v3_inc"]='%7.1f'%(hpars['v3_inc'])
                    ResRec['anisotropy_v1_eta_dec']=ResRec['anisotropy_v2_dec']
                    ResRec['anisotropy_v1_eta_inc']=ResRec['anisotropy_v2_inc']
                    ResRec['anisotropy_v1_zeta_dec']=ResRec['anisotropy_v3_dec']
                    ResRec['anisotropy_v1_zeta_inc']=ResRec['anisotropy_v3_inc']
                    ResRec['anisotropy_v2_eta_dec']=ResRec['anisotropy_v1_dec']
                    ResRec['anisotropy_v2_eta_inc']=ResRec['anisotropy_v1_inc']
                    ResRec['anisotropy_v2_zeta_dec']=ResRec['anisotropy_v3_dec']
                    ResRec['anisotropy_v2_zeta_inc']=ResRec['anisotropy_v3_inc']
                    ResRec['anisotropy_v3_eta_dec']=ResRec['anisotropy_v1_dec']
                    ResRec['anisotropy_v3_eta_inc']=ResRec['anisotropy_v1_inc']
                    ResRec['anisotropy_v3_zeta_dec']=ResRec['anisotropy_v2_dec']
                    ResRec['anisotropy_v3_zeta_inc']=ResRec['anisotropy_v2_inc']
                    ResRec["anisotropy_v1_eta_semi_angle"]='%7.1f'%(hpars['e12'])
                    ResRec["anisotropy_v1_zeta_semi_angle"]='%7.1f'%(hpars['e13'])
                    ResRec["anisotropy_v2_eta_semi_angle"]='%7.1f'%(hpars['e12'])
                    ResRec["anisotropy_v2_zeta_semi_angle"]='%7.1f'%(hpars['e23'])
                    ResRec["anisotropy_v3_eta_semi_angle"]='%7.1f'%(hpars['e13'])
                    ResRec["anisotropy_v3_zeta_semi_angle"]='%7.1f'%(hpars['e23'])
                    ResRec["result_description"]='Critical F: '+hpars["F_crit"]+';Critical F12/F13: '+hpars["F12_crit"]
                    ResRecs.append(ResRec)
                    if igeo==1: 
                        sbarg=pmag.dosgeo(sbar,az,pl) 
                        hparsg=pmag.dohext(9,sigma,sbarg) 
                        AnisRecG=copy.copy(AnisRec)
                        ResRecG=copy.copy(ResRec)
                        AnisRecG["anisotropy_s1"]='%12.10f'%(sbarg[0])
                        AnisRecG["anisotropy_s2"]='%12.10f'%(sbarg[1])
                        AnisRecG["anisotropy_s3"]='%12.10f'%(sbarg[2])
                        AnisRecG["anisotropy_s4"]='%12.10f'%(sbarg[3])
                        AnisRecG["anisotropy_s5"]='%12.10f'%(sbarg[4])
                        AnisRecG["anisotropy_s6"]='%12.10f'%(sbarg[5])
                        AnisRecG["anisotropy_tilt_correction"]='0'
                        ResRecG["anisotropy_tilt_correction"]='0'
                        ResRecG["anisotropy_v1_dec"]='%7.1f'%(hparsg['v1_dec'])
                        ResRecG["anisotropy_v2_dec"]='%7.1f'%(hparsg['v2_dec'])
                        ResRecG["anisotropy_v3_dec"]='%7.1f'%(hparsg['v3_dec'])
                        ResRecG["anisotropy_v1_inc"]='%7.1f'%(hparsg['v1_inc'])
                        ResRecG["anisotropy_v2_inc"]='%7.1f'%(hparsg['v2_inc'])
                        ResRecG["anisotropy_v3_inc"]='%7.1f'%(hparsg['v3_inc'])
                        ResRecG['anisotropy_v1_eta_dec']=ResRecG['anisotropy_v2_dec']
                        ResRecG['anisotropy_v1_eta_inc']=ResRecG['anisotropy_v2_inc']
                        ResRecG['anisotropy_v1_zeta_dec']=ResRecG['anisotropy_v3_dec']
                        ResRecG['anisotropy_v1_zeta_inc']=ResRecG['anisotropy_v3_inc']
                        ResRecG['anisotropy_v2_eta_dec']=ResRecG['anisotropy_v1_dec']
                        ResRecG['anisotropy_v2_eta_inc']=ResRecG['anisotropy_v1_inc']
                        ResRecG['anisotropy_v2_zeta_dec']=ResRecG['anisotropy_v3_dec']
                        ResRecG['anisotropy_v2_zeta_inc']=ResRecG['anisotropy_v3_inc']
                        ResRecG['anisotropy_v3_eta_dec']=ResRecG['anisotropy_v1_dec']
                        ResRecG['anisotropy_v3_eta_inc']=ResRecG['anisotropy_v1_inc']
                        ResRecG['anisotropy_v3_zeta_dec']=ResRecG['anisotropy_v2_dec']
                        ResRecG['anisotropy_v3_zeta_inc']=ResRecG['anisotropy_v2_inc']
                        ResRecG["result_description"]='Critical F: '+hpars["F_crit"]+';Critical F12/F13: '+hpars["F12_crit"]
                        ResRecs.append(ResRecG)
                        AnisRecs.append(AnisRecG)
                    if itilt==1: 
                        sbart=pmag.dostilt(sbarg,bed_az,bed_dip) 
                        hparst=pmag.dohext(9,sigma,sbart)
                        AnisRecT=copy.copy(AnisRec)
                        ResRecT=copy.copy(ResRec)
                        AnisRecT["anisotropy_s1"]='%12.10f'%(sbart[0])
                        AnisRecT["anisotropy_s2"]='%12.10f'%(sbart[1])
                        AnisRecT["anisotropy_s3"]='%12.10f'%(sbart[2])
                        AnisRecT["anisotropy_s4"]='%12.10f'%(sbart[3])
                        AnisRecT["anisotropy_s5"]='%12.10f'%(sbart[4])
                        AnisRecT["anisotropy_s6"]='%12.10f'%(sbart[5])
                        AnisRecT["anisotropy_tilt_correction"]='100'
                        ResRecT["anisotropy_v1_dec"]='%7.1f'%(hparst['v1_dec'])
                        ResRecT["anisotropy_v2_dec"]='%7.1f'%(hparst['v2_dec'])
                        ResRecT["anisotropy_v3_dec"]='%7.1f'%(hparst['v3_dec'])
                        ResRecT["anisotropy_v1_inc"]='%7.1f'%(hparst['v1_inc'])
                        ResRecT["anisotropy_v2_inc"]='%7.1f'%(hparst['v2_inc'])
                        ResRecT["anisotropy_v3_inc"]='%7.1f'%(hparst['v3_inc'])
                        ResRecT['anisotropy_v1_eta_dec']=ResRecT['anisotropy_v2_dec']
                        ResRecT['anisotropy_v1_eta_inc']=ResRecT['anisotropy_v2_inc']
                        ResRecT['anisotropy_v1_zeta_dec']=ResRecT['anisotropy_v3_dec']
                        ResRecT['anisotropy_v1_zeta_inc']=ResRecT['anisotropy_v3_inc']
                        ResRecT['anisotropy_v2_eta_dec']=ResRecT['anisotropy_v1_dec']
                        ResRecT['anisotropy_v2_eta_inc']=ResRecT['anisotropy_v1_inc']
                        ResRecT['anisotropy_v2_zeta_dec']=ResRecT['anisotropy_v3_dec']
                        ResRecT['anisotropy_v2_zeta_inc']=ResRecT['anisotropy_v3_inc']
                        ResRecT['anisotropy_v3_eta_dec']=ResRecT['anisotropy_v1_dec']
                        ResRecT['anisotropy_v3_eta_inc']=ResRecT['anisotropy_v1_inc']
                        ResRecT['anisotropy_v3_zeta_dec']=ResRecT['anisotropy_v2_dec']
                        ResRecT['anisotropy_v3_zeta_inc']=ResRecT['anisotropy_v2_inc']
                        ResRecT["anisotropy_tilt_correction"]='100'
                        ResRecT["result_description"]='Critical F: '+hpars["F_crit"]+';Critical F12/F13: '+hpars["F12_crit"]
                        ResRecs.append(ResRecT)
                        AnisRecs.append(AnisRecT)
                    k15,linecnt=[],0
                    MeasRec,SpecRec,SampRec,SiteRec,AnisRec={},{},{},{},{}
    pmag.magic_write(sampfile,SampRecs,'er_samples')
    pmag.magic_write(anisfile,AnisRecs,'rmag_anisotropy')
    pmag.magic_write(resfile,ResRecs,'rmag_results')
    pmag.magic_write(measfile,MeasRecs,'magic_measurements')
    print "Data saved to: ",sampfile,anisfile,resfile,measfile
Exemplo n.º 5
0
def main():
    """
    NAME
        TDT_magic.py
 
    DESCRIPTION
        converts ThellierTool format files to magic_measurements format files

    SYNTAX
        TDT_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -usr USER:   identify user, default is ""
        -f FILE: specify .tdt format input file, required
        -F FILE: specify output file, default is magic_measurements.txt
        -spc NUM : specify number of characters to designate a  specimen, default = 0
        -loc LOCNAME : specify location/study name, must have either LOCNAME or SAMPFILE or be a synthetic
        -ncn NCON:  specify naming convention: default is #1 below
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 
 
    INPUT
        Format of ThellierTool  files:   
   2 line header:
   Thellier-tdt
   XX.0  (field in microtesla)
   Data:
   Spec Treat Intensity Declination Inclination
        
        Spec: specimen name
        Treat:  treatment step
                XXX.00  first zero field step
                XXX.11 (or .1)  first in field step [XXX.0 and XXX.1 can be done in any order]
                XXX.12 (or .2)second in-field step at lower temperature (pTRM check)
                XXX.13 (or .3) second zero-field step after infield (pTRM check step)
                       XXX.13 MUST be done in this order [XXX.00, XXX.11 [optional XXX.12] XXX.13]
         
         Intensity assumed to be total moment in 10^3 Am^2 (emu)
         Declination:  Declination in specimen coordinate system
         Inclination:  Declination in specimen coordinate system

    """
# initialize some stuff
    noave=0
    methcode,inst="",""
    phi,theta,labfield=0,90,0
    pTRM,MD,samp_con,Z=0,0,'1',1
    demag="N"
    er_location_name=""
    citation='This study'
    args=sys.argv
    methcode="LP-NO"
    specnum=0
#
# get command line arguments
#
    dir_path='.'
    meas_file,samp_file="magic_measurements.txt","er_samples.txt"
    user=""
    if "-WD" in args:
        ind=args.index("-WD")
        dir_path=args[ind+1]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind=args.index("-usr")
        user=args[ind+1]
    if '-F' in args:
        ind=args.index("-F")
        meas_file=dir_path+'/'+args[ind+1]
    if '-f' in args:
        ind=args.index("-f")
        magfile=dir_path+'/'+args[ind+1]
        try:
            input=open(magfile,'rU')
        except:
            print "bad mag file name"
            sys.exit()
    else: 
        print "mag_file field is required option"
        print main.__doc__
        sys.exit()
    if "-spc" in args:
        ind=args.index("-spc")
        specnum=int(args[ind+1])
        if specnum!=0:specnum=-specnum
    if "-loc" in args:
        ind=args.index("-loc")
        er_location_name=args[ind+1]
    if "-ncn" in args:
        ind=args.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
    MagRecs=[]
    demag="T"
    version_num=pmag.get_version()
    data=input.readlines()
    rec=data[1].split()
    labfield=float(rec[0])*1e-6
    for line in data[2:]:
        rec=line.split()
        if len(rec)>2:
            MagRec={}
            MagRec['er_location_name']=er_location_name
            MagRec['magic_software_packages']=version_num
            MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
            MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
            MagRec["treatment_ac_field"]='0'
            MagRec["treatment_dc_field"]='0'
            MagRec["treatment_dc_field_phi"]='0'
            MagRec["treatment_dc_field_theta"]='0'
            meas_type="LT-NO"
            MagRec["er_specimen_name"]=rec[0]
            MagRec["er_synthetic_name"]=""
            MagRec["er_site_name"]=""
            if specnum!=0:
                MagRec["er_sample_name"]=rec[0][:specnum]
            else:
                MagRec["er_sample_name"]=rec[0]
            if "-fsa" in args:
                for samp in Samps:
                    if samp["er_sample_name"] == MagRec["er_sample_name"]: 
                        MagRec["er_location_name"]=samp["er_location_name"]
                        MagRec["er_site_name"]=samp["er_site_name"]
                        break
            elif int(samp_con)!=6:
                site=pmag.parse_site(MagRec['er_sample_name'],samp_con,Z)
                MagRec["er_site_name"]=site
            if MagRec['er_site_name']=="":
                print 'No site name found for: ',MagRec['er_specimen_name'],MagRec['er_sample_name']
            if MagRec["er_location_name"]=="":
                print 'no location name for: ',MagRec["er_specimen_name"] 
            if rec[1]==".00":rec[1]="0.00"
            treat=rec[1].split('.')
            if float(rec[1])==0:
                pass 
            if len(treat)==1:treat.append('0')
            MagRec["treatment_temp"]='%8.3e' % (float(treat[0])+273.) # temp in kelvin
            if treat[1][0]=='0':
                meas_type="LT-T-Z"
            else: 
                MagRec["treatment_dc_field"]='%8.3e' % (labfield) # labfield in tesla (convert from microT)
                MagRec["treatment_dc_field_phi"]='%7.1f' % (phi) # labfield phi
                MagRec["treatment_dc_field_theta"]='%7.1f' % (theta) # labfield theta
                if treat[1][-1]=='1':meas_type="LT-T-I" # in-field thermal step
                if treat[1][-1]=='2':
                    meas_type="LT-PTRM-I" # pTRM check
                    pTRM=1
                if treat[1][-1]=='3':
                    MagRec["treatment_dc_field"]='0'  # this is a zero field step
                    meas_type="LT-PTRM-MD" # pTRM tail check
            MagRec["measurement_magn_moment"]='%10.3e'% (float(rec[2])*1e-3) # moment in Am^2 (from emu)
            MagRec["measurement_dec"]=rec[3]
            MagRec["measurement_inc"]=rec[4]
            MagRec["er_analyst_mail_names"]=user
            MagRec["er_citation_names"]=citation
            MagRec["magic_method_codes"]=meas_type
            MagRec["measurement_flag"]='g'
            MagRec["er_specimen_name"]=rec[0]
            MagRec["measurement_standard"]='u'
            MagRec["measurement_number"]='1'
            MagRecs.append(MagRec) 
    MagOuts=pmag.measurements_methods(MagRecs,noave)
    pmag.magic_write(meas_file,MagOuts,'magic_measurements')
    print "results put in ",meas_file
Exemplo n.º 6
0
def main():
    """
    NAME
        s_magic.py
  
    DESCRIPTION
        converts .s format data to magic_measurements  format.

    SYNTAX
        s_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f SFILE specifies the .s file name
        -sig last column has sigma
        -typ Anisotropy type:  AMS,AARM,ATRM (default is AMS)
        -F RFILE specifies the rmag_anisotropy file name
        -usr USER specify username
        -loc location specify location/study name
        -spc NUM : specify number of characters to 
              designate a  specimen, default = 0
        -spn SPECNAME, this specimen has the name SPECNAME
        -n first column has specimen name 
        -crd [s,g,t], specify coordinate system of data
           s=specimen,g=geographic,t=tilt adjusted, default is 's'
        -ncn NCON: naming conventionconvention NCON
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXXYYY:  YYY is sample designation with Z characters from site XXX
            [5] sample = site
            [6] sample, site, location info in er_samples.txt
            [7] all others you will have to either customize your

    
    DEFAULT
        RFILE:  rmag_anisotropy.txt

    INPUT
        X11,X22,X33,X12,X23,X13  (.s format file)
        X11,X22,X33,X12,X23,X13,sigma (.s format file with -sig option)
        SID, X11,X22,X33,X12,X23,X13  (.s format file with -n option)

    OUTPUT 
        rmag_anisotropy.txt format file

    NOTE
        because .s files do not have specimen names or location information, the output MagIC files
        will have to be changed prior to importing to data base.   
    """
    sfile,anisfile="","rmag_anisotropy.txt"
    location='unknown'
    user=""
    sitename,specnum='unknown',0
    samp_con,Z="",1
    user=""
    dir_path='.'
    name,sigma,spec=0,0,'unknown'
    type='AMS'
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if "-spc" in sys.argv:
        ind=sys.argv.index("-spc")
        specnum=int(sys.argv[ind+1])
        if specnum!=0:specnum=-specnum
    if "-spn" in sys.argv:
        ind=sys.argv.index("-spn")
        spec=sys.argv[ind+1]
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        sfile = sys.argv[ind+1]
    if '-sig' in sys.argv: sigma=1
    if '-typ' in sys.argv: 
        ind=sys.argv.index('-typ')
        type = sys.argv[ind+1]
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        anisfile = sys.argv[ind+1]
    if '-usr' in sys.argv:
        ind=sys.argv.index('-usr')
        user = sys.argv[ind+1]
    if '-loc' in sys.argv:
        ind=sys.argv.index('-loc')
        location = sys.argv[ind+1]
    if "-n" in sys.argv:
        name=1
    coord='-1'
    if "-crd" in sys.argv:
        ind=sys.argv.index("-crd")
        coord=sys.argv[ind+1]
        if coord=='s':coord='-1'
        if coord=='g':coord='0'
        if coord=='t':coord='100'
    if "-ncn" in sys.argv:
        ind=sys.argv.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
        if samp_con=='6':
            Samps,filetype=pmag.magic_read(dirpath+'/er_samples.txt')
    #
    # get down to bidness
    sfile=dir_path+'/'+sfile
    anisfile=dir_path+'/'+anisfile
    input=open(sfile,'rU')
    AnisRecs=[]
    linecnt=0
    citation="This study"
    # read in data
    for line in input.readlines():
        AnisRec={}
        rec=line.split()
        if name==1:
            k=1
            spec=rec[0]
        else:
            k=0
        trace=float(rec[k])+float(rec[k+1])+float(rec[k+2])
        s1='%10.9e'%(float(rec[k])/trace)
        s2='%10.9e'%(float(rec[k+1])/trace)
        s3='%10.9e'%(float(rec[k+2])/trace)
        s4='%10.9e'%(float(rec[k+3])/trace)
        s5='%10.9e'%(float(rec[k+4])/trace)
        s6='%10.9e'%(float(rec[k+5])/trace)
        AnisRec["er_citation_names"]=citation
        AnisRec["er_specimen_name"]=spec
        if specnum!=0:
            AnisRec["er_sample_name"]=spec[:specnum]
        else:
            AnisRec["er_sample_name"]=spec
        if samp_con=="6":
            for samp in Samps:
                if samp['er_sample_name']==AnisRec["er_sample_name"]:
                    sitename=samp['er_site_name']
                    location=samp['er_location_name']
        elif samp_con!="":
            sitename=pmag.parse_site(AnisRec['er_sample_name'],samp_con,Z)
        AnisRec["er_location_name"]=location
        AnisRec["er_site_name"]=sitename
        AnisRec["er_anylist_mail_names"]=user
        if type=='AMS':
            AnisRec["anisotropy_type"]="AMS"
            AnisRec["magic_experiment_names"]=spec+":LP-X"
        else:
            AnisRec["anisotropy_type"]=type
            AnisRec["magic_experiment_names"]=spec+":LP-"+type
        AnisRec["anisotropy_s1"]=s1
        AnisRec["anisotropy_s2"]=s2
        AnisRec["anisotropy_s3"]=s3
        AnisRec["anisotropy_s4"]=s4
        AnisRec["anisotropy_s5"]=s5
        AnisRec["anisotropy_s6"]=s6
        if sigma==1:AnisRec["anisotropy_sigma"]='%10.8e'%(float(rec[k+6])/trace)
        AnisRec["anisotropy_unit"]='SI'
        AnisRec["anisotropy_tilt_correction"]=coord
        AnisRec["magic_method_codes"]='LP-'+type
        AnisRecs.append(AnisRec)
    pmag.magic_write(anisfile,AnisRecs,'rmag_anisotropy')
    print 'data saved in ',anisfile 
Exemplo n.º 7
0
def main():
    """
    NAME
        sio_magic.py
 
    DESCRIPTION
        converts SIO .mag format files to magic_measurements format files

    SYNTAX
        sio_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -usr USER:   identify user, default is ""
        -f FILE: specify .mag format input file, required
        -fsa SAMPFILE : specify er_samples.txt file relating samples, site and locations names,default is none
        -F FILE: specify output file, default is magic_measurements.txt
        -Fsy: specify er_synthetics file, default is er_sythetics.txt
        -Fsa: specify output er_samples file, default is NONE (only for LDGO formatted files)
        -LP [colon delimited list of protocols, include all that apply]
            AF:  af demag
            T: thermal including thellier but not trm acquisition
            S: Shaw method
            I: IRM (acquisition)
            I3d: 3D IRM experiment
            N: NRM only
            TRM: trm acquisition
            ANI: anisotropy experiment
            D: double AF demag
            G: triple AF demag (GRM protocol)
            CR: cooling rate experiment.
                The treatment coding of the measurement file should be: XXX.00,XXX.10, XXX.20 ...XX.70 etc. (XXX.00 is optional)
                where XXX in the temperature and .10,.20... are running numbers of the cooling rates steps.
                XXX.00 is optional zerofield baseline. XXX.70 is alteration check.
                syntax in sio_magic is: -LP CR xxx,yyy,zzz,.....xx -A
                where xx, yyy,zzz...xxx  are cooling time in [K/minutes], seperated by comma, ordered at the same order as XXX.10,XXX.20 ...XX.70
                if you use a zerofield step then no need to specify the cooling rate for the zerofield
                It is important to add to the command line the -A option so the measurements will not be evraged.
                But users need to make sure that there are no duplicate meaurements in the file
        -V [1,2,3] units of IRM field in volts using ASC coil #1,2 or 3
        -spc NUM : specify number of characters to designate a  specimen, default = 0
        -loc LOCNAME : specify location/study name, must have either LOCNAME or SAMPFILE or be a synthetic
        -syn INST TYPE:  sets these specimens as synthetics created at institution INST and of type TYPE
        -ins INST : specify which demag instrument was used (e.g, SIO-Suzy or SIO-Odette),default is ""
        -dc B PHI THETA: dc lab field (in micro tesla) and phi,theta, default is none
              NB: use PHI, THETA = -1 -1 to signal that it changes, i.e. in anisotropy experiment
        -ac B : peak AF field (in mT) for ARM acquisition, default is none
        -ncn NCON:  specify naming convention: default is #1 below
        -A: don't average replicate measurements
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 
            [8] synthetic - has no site name
            [9] ODP naming convention 
    INPUT
        Best to put separate experiments (all AF, thermal, thellier, trm aquisition, Shaw, etc.) in 
           seperate .mag files (eg. af.mag, thermal.mag, etc.)

        Format of SIO .mag files:   
        Spec Treat CSD Intensity Declination Inclination [optional metadata string]
        
        
        Spec: specimen name
        Treat:  treatment step
            XXX T in Centigrade
            XXX AF in mT
            for special experiments:
              Thellier:
                XXX.0  first zero field step
                XXX.1  first in field step [XXX.0 and XXX.1 can be done in any order]
                XXX.2  second in-field step at lower temperature (pTRM check)
                XXX.3  second zero-field step after infield (pTRM check step)
                       XXX.3 MUST be done in this order [XXX.0, XXX.1 [optional XXX.2] XXX.3]
              AARM:
                X.00  baseline step (AF in zero bias field - high peak field)
                X.1   ARM step (in field step)  where
                   X is the step number in the 15 position scheme 
                      (see Appendix to Lecture 13 - http://magician.ucsd.edu/Essentials_2)
              ATRM:
                X.00 optional baseline
                X.1 ATRM step (+X)
                X.2 ATRM step (+Y)
                X.3 ATRM step (+Z)
                X.4 ATRM step (-X)
                X.5 ATRM step (-Y)
                X.6 ATRM step (-Z)
                X.7 optional alteration check (+X)

              TRM:
                XXX.YYY  XXX is temperature step of total TRM
                         YYY is dc field in microtesla

         
         Intensity assumed to be total moment in 10^3 Am^2 (emu)
         Declination:  Declination in specimen coordinate system
         Inclination:  Declination in specimen coordinate system

         Optional metatdata string:  mm/dd/yy;hh:mm;[dC,mT];xx.xx;UNITS;USER;INST;NMEAS
             hh in 24 hours.  
             dC or mT units of treatment XXX (see Treat above) for thermal or AF respectively
             xx.xxx   DC field
             UNITS of DC field (microT, mT)
             INST:  instrument code, number of axes, number of positions (e.g., G34 is 2G, three axes, 
                    measured in four positions)
             NMEAS: number of measurements in a single position (1,3,200...)
       
     
    """
# initialize some stuff
    infile_type="mag"
    noave=0
    methcode,inst="LP-NO",""
    phi,theta,peakfield,labfield=0,0,0,0
    pTRM,MD,samp_con,Z=0,0,'1',1
    dec=[315,225,180,135,45,90,270,270,270,90,180,180,0,0,0]
    inc=[0,0,0,0,0,-45,-45,0,45,45,45,-45,-90,-45,45]
    tdec=[0,90,0,180,270,0,0,90,0]
    tinc=[0,0,90,0,0,-90,0,0,90]
    missing=1
    demag="N"
    er_location_name=""
    citation='This study'
    args=sys.argv
    fmt='old'
    syn=0
    synfile='er_synthetics.txt'
    samp_file,ErSamps='',[]
    trm=0
    irm=0
    specnum=0
    coil=""
#
# get command line arguments
#
    meas_file="magic_measurements.txt"
    user=""
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind=args.index("-usr")
        user=args[ind+1]
    if '-F' in args:
        ind=args.index("-F")
        meas_file=args[ind+1]
    if '-Fsy' in args:
        ind=args.index("-Fsy")
        synfile=args[ind+1]
    if '-Fsa' in args:
        ind=args.index("-Fsa")
        samp_file=args[ind+1]
        try:
            open(samp_file,'rU')
            ErSamps,file_type=pmag.magic_read(samp_file)
            print 'sample information will be appended to new er_samples.txt file'
        except:
            print 'sample information will be stored in new er_samples.txt file'
    if '-f' in args:
        ind=args.index("-f")
        magfile=args[ind+1]
        try:
            input=open(magfile,'rU')
        except:
            print "bad mag file name"
            sys.exit()
    else: 
        print "mag_file field is required option"
        print main.__doc__
        sys.exit()
    if "-dc" in args:
        ind=args.index("-dc")
        labfield=float(args[ind+1])*1e-6
        phi=float(args[ind+2])
        theta=float(args[ind+3])
    if "-ac" in args:
        ind=args.index("-ac")
        peakfield=float(args[ind+1])*1e-3
    if "-spc" in args:
        ind=args.index("-spc")
        specnum=int(args[ind+1])
        if specnum!=0:specnum=-specnum
    if "-loc" in args:
        ind=args.index("-loc")
        er_location_name=args[ind+1]
    if "-fsa" in args:
        ind=args.index("-fsa")
        Samps,file_type=pmag.magic_read(args[ind+1])
    if '-syn' in args:
        syn=1
        ind=args.index("-syn")
        institution=args[ind+1]
        syntype=args[ind+2]
        if '-fsy' in args:
            ind=args.index("-fsy")
            synfile=args[ind+1]
    if "-ins" in args:
        ind=args.index("-ins")
        inst=args[ind+1]
    if "-A" in args: noave=1
    if "-ncn" in args:
        ind=args.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4-" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
        if "7-" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="7"
    if '-LP' in args:
        ind=args.index("-LP")
        codelist=args[ind+1]
        codes=codelist.split(':')
        if "AF" in codes:
            demag='AF' 
            if'-dc' not in args: methcode="LT-AF-Z"
            if'-dc' in args: methcode="LT-AF-I"
        if "T" in codes:
            demag="T"
            if '-dc' not in args: methcode="LT-T-Z"
            if '-dc' in args: methcode="LT-T-I"
        if "I" in codes:
            methcode="LP-IRM"
            irmunits="mT"
        if "I3d" in codes:
            methcode="LT-T-Z:LP-IRM-3D"
        if "S" in codes: 
            demag="S"
            methcode="LP-PI-TRM:LP-PI-ALT-AFARM"
            trm_labfield=labfield
            ans=raw_input("DC lab field for ARM step: [50uT] ")
            if ans=="":
                arm_labfield=50e-6
            else: 
                arm_labfield=float(ans)*1e-6
            ans=raw_input("temperature for total trm step: [600 C] ")
            if ans=="":
                trm_peakT=600+273 # convert to kelvin
            else: 
                trm_peakT=float(ans)+273 # convert to kelvin
        if "G" in codes: methcode="LT-AF-G"
	if "D" in codes: methcode="LT-AF-D"
        if "TRM" in codes: 
            demag="T"
            trm=1
        if "CR" in codes: 
            demag="T"
            cooling_rate_experiment=1
            ind=args.index("CR")
            coolling_times=args[ind+1]
            coolling_times_list=coolling_times.split(',')
            
    if "-V" in args:
        methcode="LP-IRM"
        ind=args.index("-V")
        irmunits="V"
        coil=args[ind+1]
        if coil not in ["1","2","3"]:
            print main.__doc__
            print 'not a valid coil specification'
            sys.exit()
    if demag=="T" and "ANI" in codes:
        methcode="LP-AN-TRM"
    if demag=="T" and "CR" in codes:
        methcode="LP-CR-TRM"
    if demag=="AF" and "ANI" in codes:
        methcode="LP-AN-ARM"
        if labfield==0: labfield=50e-6
        if peakfield==0: peakfield=.180
    SynRecs,MagRecs=[],[]
    version_num=pmag.get_version()
    if 1:
    #if infile_type=="SIO format":
        for line in input.readlines():
            instcode=""
            if len(line)>2:
                SynRec={}
                MagRec={}
                MagRec['er_location_name']=er_location_name
                MagRec['magic_software_packages']=version_num
                MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
                MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
                MagRec["treatment_ac_field"]='0'
                MagRec["treatment_dc_field"]='0'
                MagRec["treatment_dc_field_phi"]='0'
                MagRec["treatment_dc_field_theta"]='0'
                meas_type="LT-NO"
                rec=line.split()
                if rec[1]==".00":rec[1]="0.00"
                treat=rec[1].split('.')
                if methcode=="LP-IRM":
                    if irmunits=='mT':
                        labfield=float(treat[0])*1e-3
                    else:
                        labfield=pmag.getfield(irmunits,coil,treat[0])
                    if rec[1][0]!="-":
                        phi,theta=0.,90.
                    else:
                        phi,theta=0.,-90.
                    meas_type="LT-IRM"
                    MagRec["treatment_dc_field"]='%8.3e'%(labfield)
                    MagRec["treatment_dc_field_phi"]='%7.1f'%(phi)
                    MagRec["treatment_dc_field_theta"]='%7.1f'%(theta)
                if len(rec)>6:
                  code1=rec[6].split(';') # break e.g., 10/15/02;7:45 indo date and time
                  if len(code1)==2: # old format with AM/PM
                    missing=0
                    code2=code1[0].split('/') # break date into mon/day/year
                    code3=rec[7].split(';') # break e.g., AM;C34;200  into time;instr/axes/measuring pos;number of measurements
                    yy=int(code2[2])
                    if yy <90:
                        yyyy=str(2000+yy)
                    else: yyyy=str(1900+yy)
                    mm=int(code2[0])
                    if mm<10:
                        mm="0"+str(mm)
                    else: mm=str(mm)
                    dd=int(code2[1])
                    if dd<10:
                        dd="0"+str(dd)
                    else: dd=str(dd)
                    time=code1[1].split(':')
                    hh=int(time[0])
                    if code3[0]=="PM":hh=hh+12
                    if hh<10:
                        hh="0"+str(hh)
                    else: hh=str(hh)
                    min=int(time[1])
                    if min<10:
                       min= "0"+str(min)
                    else: min=str(min)
                    MagRec["measurement_date"]=yyyy+":"+mm+":"+dd+":"+hh+":"+min+":00.00"
                    MagRec["measurement_time_zone"]='SAN'
                    if inst=="":
                        if code3[1][0]=='C':instcode='SIO-bubba'
                        if code3[1][0]=='G':instcode='SIO-flo'
                    else:
                        instcode=''
                    MagRec["measurement_positions"]=code3[1][2]
                  elif len(code1)>2: # newest format (cryo7 or later)
                    if "LP-AN-ARM" not in methcode:labfield=0
                    fmt='new'
                    date=code1[0].split('/') # break date into mon/day/year
                    yy=int(date[2])
                    if yy <90:
                        yyyy=str(2000+yy)
                    else: yyyy=str(1900+yy)
                    mm=int(date[0])
                    if mm<10:
                        mm="0"+str(mm)
                    else: mm=str(mm)
                    dd=int(date[1])
                    if dd<10:
                        dd="0"+str(dd)
                    else: dd=str(dd)
                    time=code1[1].split(':')
                    hh=int(time[0])
                    if hh<10:
                        hh="0"+str(hh)
                    else: hh=str(hh)
                    min=int(time[1])
                    if min<10:
                       min= "0"+str(min)
                    else: min=str(min)
                    MagRec["measurement_date"]=yyyy+":"+mm+":"+dd+":"+hh+":"+min+":00.00"
                    MagRec["measurement_time_zone"]='SAN'
                    if inst=="":
                        if code1[6][0]=='C':instcode='SIO-bubba'
                        if code1[6][0]=='G':instcode='SIO-flo'
                    else:
                        instcode=''
                    if len(code1)>1:
                        MagRec["measurement_positions"]=code1[6][2]
                    else:
                        MagRec["measurement_positions"]=code1[7]   # takes care of awkward format with bubba and flo being different
                    if user=="":user=code1[5]
                    if code1[2][-1]=='C': 
                        demag="T"
                        if code1[4]=='microT' and float(code1[3])!=0. and "LP-AN-ARM" not in methcode: labfield=float(code1[3])*1e-6
                    if code1[2]=='mT' and methcode!="LP-IRM": 
                        demag="AF"
                        if code1[4]=='microT' and float(code1[3])!=0.: labfield=float(code1[3])*1e-6
                    if code1[4]=='microT' and labfield!=0. and meas_type!="LT-IRM":
                        phi,theta=0.,-90.
                        if demag=="T": meas_type="LT-T-I"
                        if demag=="AF": meas_type="LT-AF-I"
                        MagRec["treatment_dc_field"]='%8.3e'%(labfield)
                        MagRec["treatment_dc_field_phi"]='%7.1f'%(phi)
                        MagRec["treatment_dc_field_theta"]='%7.1f'%(theta)
                    if code1[4]=='' or labfield==0. and meas_type!="LT-IRM":
                        if demag=='T':meas_type="LT-T-Z"
                        if demag=="AF":meas_type="LT-AF-Z"
                        MagRec["treatment_dc_field"]='0'
                if syn==0:
                    MagRec["er_specimen_name"]=rec[0]
                    MagRec["er_synthetic_name"]=""
                    MagRec["er_site_name"]=""
                    if specnum!=0:
                        MagRec["er_sample_name"]=rec[0][:specnum]
                    else:
                        MagRec["er_sample_name"]=rec[0]
                    if "-fsa" in args:
                        samp=pmag.get_dictitem(Samps,'er_sample_name',MagRec['er_sample_name'],'T')
                        if len(samp)>0:
                            MagRec["er_location_name"]=samp[0]["er_location_name"]
                            MagRec["er_site_name"]=samp[0]["er_site_name"]
                        else: 
                            MagRec['er_location_name']=''
                            MagRec["er_site_name"]=''
                    elif int(samp_con)!=6:
                        site=pmag.parse_site(MagRec['er_sample_name'],samp_con,Z)
                        MagRec["er_site_name"]=site
                    if MagRec['er_site_name']=="":
                        print 'No site name found for: ',MagRec['er_specimen_name'],MagRec['er_sample_name']
                    if MagRec["er_location_name"]=="":
                        print 'no location name for: ',MagRec["er_specimen_name"] 
                else:
                    if specnum!=0:
                        MagRec["er_sample_name"]=rec[0][:specnum]
                    else:
                        MagRec["er_sample_name"]=rec[0]
                    MagRec["er_site_name"]=""
                    MagRec["er_synthetic_name"]=MagRec["er_specimen_name"]
                    SynRec["er_synthetic_name"]=MagRec["er_specimen_name"]
                    site=pmag.parse_site(MagRec['er_sample_name'],samp_con,Z)
                    SynRec["synthetic_parent_sample"]=site
                    SynRec["er_citation_names"]="This study"
                    SynRec["synthetic_institution"]=institution
                    SynRec["synthetic_type"]=syntype
                    SynRecs.append(SynRec)
                if float(rec[1])==0:
                    pass 
                elif demag=="AF":
                    if methcode != "LP-AN-ARM":
                        MagRec["treatment_ac_field"]='%8.3e' %(float(rec[1])*1e-3) # peak field in tesla
                        if meas_type=="LT-AF-Z": MagRec["treatment_dc_field"]='0'
                    else: # AARM experiment
                        if treat[1][0]=='0':
                            meas_type="LT-AF-Z:LP-AN-ARM:"
                            MagRec["treatment_ac_field"]='%8.3e' %(peakfield) # peak field in tesla
                            MagRec["treatment_dc_field"]='%8.3e'%(0)
                            if labfield!=0 and methcode!="LP-AN-ARM": print "Warning - inconsistency in mag file with lab field - overriding file with 0"
                        else:
                            meas_type="LT-AF-I:LP-AN-ARM"
                            ipos=int(treat[0])-1
                            MagRec["treatment_dc_field_phi"]='%7.1f' %(dec[ipos])
                            MagRec["treatment_dc_field_theta"]='%7.1f'% (inc[ipos])
                            MagRec["treatment_dc_field"]='%8.3e'%(labfield)
                            MagRec["treatment_ac_field"]='%8.3e' %(peakfield) # peak field in tesla
                elif demag=="T" and methcode == "LP-AN-TRM":
                    MagRec["treatment_temp"]='%8.3e' % (float(treat[0])+273.) # temp in kelvin
                    if treat[1][0]=='0':
                        meas_type="LT-T-Z:LP-AN-TRM"
                        MagRec["treatment_dc_field"]='%8.3e'%(0)
                        MagRec["treatment_dc_field_phi"]='0'
                        MagRec["treatment_dc_field_theta"]='0'
                    else:
                        MagRec["treatment_dc_field"]='%8.3e'%(labfield)
                        if treat[1][0]=='7': # alteration check as final measurement
                                meas_type="LT-PTRM-I:LP-AN-TRM"
                        else:
                                meas_type="LT-T-I:LP-AN-TRM"

                        # find the direction of the lab field in two ways:
                        # (1) using the treatment coding (XX.1=+x, XX.2=+y, XX.3=+z, XX.4=-x, XX.5=-y, XX.6=-z)
                        ipos_code=int(treat[1][0])-1
                        # (2) using the magnetization
                        DEC=float(rec[4])
                        INC=float(rec[5])
                        if INC < 45 and INC > -45:
                            if DEC>315  or DEC<45: ipos_guess=0
                            if DEC>45 and DEC<135: ipos_guess=1
                            if DEC>135 and DEC<225: ipos_guess=3
                            if DEC>225 and DEC<315: ipos_guess=4
                        else:
                            if INC >45: ipos_guess=2
                            if INC <-45: ipos_guess=5
                        # prefer the guess over the code
                        ipos=ipos_guess
                        MagRec["treatment_dc_field_phi"]='%7.1f' %(tdec[ipos])
                        MagRec["treatment_dc_field_theta"]='%7.1f'% (tinc[ipos])
                        # check it 
                        if ipos_guess!=ipos_code and treat[1][0]!='7':
                            print "-E- ERROR: check specimen %s step %s, ATRM measurements, coding does not match the direction of the lab field!"%(rec[0],".".join(list(treat)))
                        

                elif demag=="S": # Shaw experiment
                    if treat[1][1]=='0':
                        if  int(treat[0])!=0:
                            MagRec["treatment_ac_field"]='%8.3e' % (float(treat[0])*1e-3) # AF field in tesla
                            MagRec["treatment_dc_field"]='0'
                            meas_type="LT-AF-Z" # first AF
                        else:
                            meas_type="LT-NO"
                            MagRec["treatment_ac_field"]='0'
                            MagRec["treatment_dc_field"]='0'
                    elif treat[1][1]=='1':
                        if int(treat[0])==0:
                            MagRec["treatment_ac_field"]='%8.3e' %(peakfield) # peak field in tesla
                            MagRec["treatment_dc_field"]='%8.3e'%(arm_labfield)
                            MagRec["treatment_dc_field_phi"]='%7.1f'%(phi)
                            MagRec["treatment_dc_field_theta"]='%7.1f'%(theta)
                            meas_type="LT-AF-I"
                        else:
                            MagRec["treatment_ac_field"]='%8.3e' % ( float(treat[0])*1e-3) # AF field in tesla
                            MagRec["treatment_dc_field"]='0'
                            meas_type="LT-AF-Z"
                    elif treat[1][1]=='2':
                        if int(treat[0])==0:
                            MagRec["treatment_ac_field"]='0'
                            MagRec["treatment_dc_field"]='%8.3e'%(trm_labfield)
                            MagRec["treatment_dc_field_phi"]='%7.1f'%(phi)
                            MagRec["treatment_dc_field_theta"]='%7.1f'%(theta)
                            MagRec["treatment_temp"]='%8.3e' % (trm_peakT)
                            meas_type="LT-T-I"
                        else:
                            MagRec["treatment_ac_field"]='%8.3e' % ( float(treat[0])*1e-3) # AF field in tesla
                            MagRec["treatment_dc_field"]='0'
                            meas_type="LT-AF-Z"
                    elif treat[1][1]=='3':
                        if int(treat[0])==0:
                            MagRec["treatment_ac_field"]='%8.3e' %(peakfield) # peak field in tesla
                            MagRec["treatment_dc_field"]='%8.3e'%(arm_labfield)
                            MagRec["treatment_dc_field_phi"]='%7.1f'%(phi)
                            MagRec["treatment_dc_field_theta"]='%7.1f'%(theta)
                            meas_type="LT-AF-I"
                        else:
                            MagRec["treatment_ac_field"]='%8.3e' % ( float(treat[0])*1e-3) # AF field in tesla
                            MagRec["treatment_dc_field"]='0'
                            meas_type="LT-AF-Z"


                # Cooling rate experient # added by rshaar
                elif demag=="T" and methcode == "LP-CR-TRM":

                    MagRec["treatment_temp"]='%8.3e' % (float(treat[0])+273.) # temp in kelvin
                    if treat[1][0]=='0':
                        meas_type="LT-T-Z:LP-CR-TRM"
                        MagRec["treatment_dc_field"]='%8.3e'%(0)
                        MagRec["treatment_dc_field_phi"]='0'
                        MagRec["treatment_dc_field_theta"]='0'
                    else:
                        MagRec["treatment_dc_field"]='%8.3e'%(labfield)
                        if treat[1][0]=='7': # alteration check as final measurement
                                meas_type="LT-PTRM-I:LP-CR-TRM"
                        else:
                                meas_type="LT-T-I:LP-CR-TRM"
                        MagRec["treatment_dc_field_phi"]='%7.1f' % (phi) # labfield phi
                        MagRec["treatment_dc_field_theta"]='%7.1f' % (theta) # labfield theta
                        
                        indx=int(treat[1][0])-1
                        # alteration check matjed as 0.7 in the measurement file
                        if indx==6:
                           cooling_time= coolling_times_list[-1]
                        else:
                            cooling_time=coolling_times_list[indx]
                        MagRec["measurement_description"]="cooling_rate"+":"+cooling_time+":"+"K/min"


                elif demag!='N':  
                  if len(treat)==1:treat.append('0')
                  MagRec["treatment_temp"]='%8.3e' % (float(treat[0])+273.) # temp in kelvin
                  if trm==0:  # demag=T and not trmaq
                    if treat[1][0]=='0':
                        meas_type="LT-T-Z"
                    else: 
                        MagRec["treatment_dc_field"]='%8.3e' % (labfield) # labfield in tesla (convert from microT)
                        MagRec["treatment_dc_field_phi"]='%7.1f' % (phi) # labfield phi
                        MagRec["treatment_dc_field_theta"]='%7.1f' % (theta) # labfield theta
                        if treat[1][0]=='1':meas_type="LT-T-I" # in-field thermal step
                        if treat[1][0]=='2':
                            meas_type="LT-PTRM-I" # pTRM check
                            pTRM=1
                        if treat[1][0]=='3':
                            MagRec["treatment_dc_field"]='0'  # this is a zero field step
                            meas_type="LT-PTRM-MD" # pTRM tail check
                  else: 
                    labfield=float(treat[1])*1e-6
                    MagRec["treatment_dc_field"]='%8.3e' % (labfield) # labfield in tesla (convert from microT)
                    MagRec["treatment_dc_field_phi"]='%7.1f' % (phi) # labfield phi
                    MagRec["treatment_dc_field_theta"]='%7.1f' % (theta) # labfield theta
                    meas_type="LT-T-I:LP-TRM" # trm acquisition experiment

                            

                MagRec["measurement_csd"]=rec[2]
                MagRec["measurement_magn_moment"]='%10.3e'% (float(rec[3])*1e-3) # moment in Am^2 (from emu)
                MagRec["measurement_dec"]=rec[4]
                MagRec["measurement_inc"]=rec[5]
                MagRec["magic_instrument_codes"]=instcode
                MagRec["er_analyst_mail_names"]=user
                MagRec["er_citation_names"]=citation
                if "LP-IRM-3D" in methcode : meas_type=methcode
                #MagRec["magic_method_codes"]=methcode.strip(':')
                MagRec["magic_method_codes"]=meas_type
                MagRec["measurement_flag"]='g'
                MagRec["er_specimen_name"]=rec[0]
                if 'std' in rec[0]:
                    MagRec["measurement_standard"]='s'
                else:
                    MagRec["measurement_standard"]='u'
                MagRec["measurement_number"]='1'
                #print MagRec['treatment_temp']
                MagRecs.append(MagRec) 
    MagOuts=pmag.measurements_methods(MagRecs,noave)
    pmag.magic_write(meas_file,MagOuts,'magic_measurements')
    print "results put in ",meas_file
    if samp_file!="":
        pmag.magic_write(samp_file,ErSamps,'er_samples')
        print "sample orientations put in ",samp_file
    if len(SynRecs)>0:
        pmag.magic_write(synfile,SynRecs,'er_synthetics')
        print "synthetics put in ",synfile
Exemplo n.º 8
0
def main():
    """
    NAME
        sufar4-asc_magic.py

    DESCRIPTION
        converts ascii files generated by SUFAR ver.4.0 to MagIC formated
        files for use with PmagPy plotting software

    SYNTAX
        sufar4-asc_magic.py -h [command line options]

    OPTIONS
        -h: prints the help message and quits
        -f FILE: specify .asc input file name
        -F MFILE: specify magic_measurements output file
        -Fa AFILE: specify rmag_anisotropy output file
        -Fr RFILE: specify rmag_results output file
        -Fs SFILE: specify er_specimens output file with location, sample, site, etc. information
        -usr USER: specify who made the measurements
        -loc LOC: specify location name for study 
        -ins INST: specify instrument used
        -spc SPEC: specify number of characters to specify specimen from sample
        -ncn NCON:  specify naming convention: default is #2 below
        -k15 : specify static 15 position mode - default is spinning
        -new : replace all existing magic files

    DEFAULTS
        AFILE: rmag_anisotropy.txt
        RFILE: rmag_results.txt
        SFILE: default is to create new er_specimen.txt file
        USER: ""
        LOC: "unknown"
        INST: ""
        SPEC: 0  sample name is same as site (if SPEC is 1, sample is all but last character)
        appends to  'er_specimens.txt, er_samples.txt, er_sites.txt' files
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
            [8] This is a synthetic
            [9] ODP naming convention

    """
    citation = "This study"
    cont = 0
    samp_con, Z = "1", 1
    AniRecSs, AniRecs, SpecRecs, SampRecs, SiteRecs, MeasRecs = [], [], [], [], [], []
    user, locname, specfile = "", "unknown", "er_specimens.txt"
    isspec, inst, specnum = "0", "", 0
    spin, new = 1, 0
    dir_path = "."
    if "-WD" in sys.argv:
        ind = sys.argv.index("-WD")
        dir_path = sys.argv[ind + 1]
    aoutput, routput, moutput = (
        dir_path + "/rmag_anisotropy.txt",
        dir_path + "/rmag_results.txt",
        dir_path + "/magic_measurements.txt",
    )
    if "-h" in sys.argv:
        print main.__doc__
        sys.exit()
    if "-usr" in sys.argv:
        ind = sys.argv.index("-usr")
        user = sys.argv[ind + 1]
    if "-ncn" in sys.argv:
        ind = sys.argv.index("-ncn")
        samp_con = sys.argv[ind + 1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z = samp_con.split("-")[1]
                samp_con = "4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z = samp_con.split("-")[1]
                samp_con = "7"
    if "-k15" in sys.argv:
        spin = 0
    if "-ins" in sys.argv:
        ind = sys.argv.index("-ins")
        inst = sys.argv[ind + 1]
    if "-f" in sys.argv:
        ind = sys.argv.index("-f")
        ascfile = dir_path + "/" + sys.argv[ind + 1]
    if "-F" in sys.argv:
        ind = sys.argv.index("-F")
        moutput = dir_path + "/" + sys.argv[ind + 1]
    if "-Fa" in sys.argv:
        ind = sys.argv.index("-Fa")
        aoutput = dir_path + "/" + sys.argv[ind + 1]
    if "-Fr" in sys.argv:
        ind = sys.argv.index("-Fr")
        routput = dir_path + "/" + sys.argv[ind + 1]
    if "-Fs" in sys.argv:
        ind = sys.argv.index("-Fs")
        specfile = dir_path + "/" + sys.argv[ind + 1]
        isspec = "1"
    elif "-loc" in sys.argv:
        ind = sys.argv.index("-loc")
        locname = sys.argv[ind + 1]
    if "-spc" in sys.argv:
        ind = sys.argv.index("-spc")
        specnum = -(int(sys.argv[ind + 1]))
        if specnum != 0:
            specnum = -specnum
    if isspec == "1":
        specs, file_type = pmag.magic_read(specfile)
    specnames, sampnames, sitenames = [], [], []
    if "-new" not in sys.argv:  # see if there are already specimen,sample, site files lying around
        try:
            SpecRecs, file_type = pmag.magic_read(dir_path + "/er_specimens.txt")
            for spec in SpecRecs:
                if spec["er_specimen_name"] not in specnames:
                    specnames.append(samp["er_specimen_name"])
        except:
            SpecRecs, specs = [], []
        try:
            SampRecs, file_type = pmag.magic_read(dir_path + "/er_samples.txt")
            for samp in SampRecs:
                if samp["er_sample_name"] not in sampnames:
                    sampnames.append(samp["er_sample_name"])
        except:
            sampnames, SampRecs = [], []
        try:
            SiteRecs, file_type = pmag.magic_read(dir_path + "/er_sites.txt")
            for site in SiteRecs:
                if site["er_site_names"] not in sitenames:
                    sitenames.append(site["er_site_name"])
        except:
            sitenames, SiteRecs = [], []
    try:
        input = open(ascfile, "rU")
    except:
        print "Error opening file: ", ascfile
    Data = input.readlines()
    k = 0
    while k < len(Data):
        line = Data[k]
        words = line.split()
        if "ANISOTROPY" in words:  # first line of data for the spec
            MeasRec, AniRec, SpecRec, SampRec, SiteRec = {}, {}, {}, {}, {}
            specname = words[0]
            AniRec["er_specimen_name"] = specname
            if isspec == "1":
                for spec in specs:
                    if spec["er_specimen_name"] == specname:
                        AniRec["er_sample_name"] = spec["er_sample_name"]
                        AniRec["er_site_name"] = spec["er_site_name"]
                        AniRec["er_location_name"] = spec["er_location_name"]
                        break
            elif isspec == "0":
                if specnum != 0:
                    sampname = specname[:specnum]
                else:
                    sampname = specname
                AniRec["er_sample_name"] = sampname
                SpecRec["er_specimen_name"] = specname
                SpecRec["er_sample_name"] = sampname
                SampRec["er_sample_name"] = sampname
                SiteRec["er_sample_name"] = sampname
                SiteRec["site_description"] = "s"
                if samp_con != "9":
                    AniRec["er_site_name"] = pmag.parse_site(AniRec["er_sample_name"], samp_con, Z)
                    SpecRec["er_site_name"] = pmag.parse_site(AniRec["er_sample_name"], samp_con, Z)
                    SampRec["er_site_name"] = pmag.parse_site(AniRec["er_sample_name"], samp_con, Z)
                    SiteRec["er_site_name"] = pmag.parse_site(AniRec["er_sample_name"], samp_con, Z)
                else:
                    AniRec["er_site_name"] = specname
                    SpecRec["er_site_name"] = specname
                    SampRec["er_site_name"] = specname
                    SiteRec["er_site_name"] = specname
                    pieces = specname.split("-")
                    AniRec["er_expedition_name"] = pieces[0]
                    SpecRec["er_expedition_name"] = pieces[0]
                    SampRec["er_expedition_name"] = pieces[0]
                    SiteRec["er_expedition_name"] = pieces[0]
                    location = pieces[1]
                AniRec["er_location_name"] = locname
                SpecRec["er_location_name"] = locname
                SampRec["er_location_name"] = locname
                SiteRec["er_location_name"] = locname
                AniRec["er_citation_names"] = "This study"
                SpecRec["er_citation_names"] = "This study"
                SampRec["er_citation_names"] = "This study"
                SiteRec["er_citation_names"] = "This study"
            AniRec["er_citation_names"] = "This study"
            AniRec["magic_instrument_codes"] = inst
            AniRec["magic_method_codes"] = "LP-X:AE-H:LP-AN-MS"
            AniRec["magic_experiment_names"] = specname + ":" + "LP-AN-MS"
            AniRec["er_analyst_mail_names"] = user
            for key in AniRec.keys():
                MeasRec[key] = AniRec[key]
            MeasRec["measurement_flag"] = "g"
            AniRec["anisotropy_flag"] = "g"
            MeasRec["measurement_standard"] = "u"
            MeasRec["measurement_description"] = "Bulk sucsecptibility measurement"
            AniRec["anisotropy_type"] = "AMS"
            AniRec["anisotropy_unit"] = "Normalized by trace - bulk in measurements table"
            if spin == 1:
                AniRec["anisotropy_n"] = "192"
            else:
                AniRec["anisotropy_n"] = "15"
        if "Azi" in words and isspec == "0":
            SampRec["sample_azimuth"] = words[1]
            labaz = float(words[1])
        if "Dip" in words:
            SampRec["sample_dip"] = "%7.1f" % (-float(words[1]))
            SpecRec["specimen_vol"] = "%8.3e" % (float(words[10]) * 1e-6)  # convert actual volume to m^3 from cm^3
            labdip = float(words[1])
        if "T1" in words and "F1" in words:
            k += 2  # read in fourth line down
            line = Data[k]
            rec = line.split()
            dd = rec[1].split("/")
            dip_direction = int(dd[0]) + 90
            SampRec["sample_bed_dip_direction"] = "%i" % (dip_direction)
            SampRec["sample_bed_dip"] = dd[1]
            bed_dip = float(dd[1])
        if "Mean" in words:
            k += 4  # read in fourth line down
            line = Data[k]
            rec = line.split()
            MeasRec["measurement_chi_volume"] = rec[1]
            sigma = 0.01 * float(rec[2]) / 3.0
            AniRec["anisotropy_sigma"] = "%7.4f" % (sigma)
            AniRec["anisotropy_unit"] = "SI"
        if "factors" in words:
            k += 4  # read in second line down
            line = Data[k]
            rec = line.split()
        if "Specimen" in words:  # first part of specimen data
            AniRec["anisotropy_s1"] = "%7.4f" % (float(words[5]) / 3.0)  # eigenvalues sum to unity - not 3
            AniRec["anisotropy_s2"] = "%7.4f" % (float(words[6]) / 3.0)
            AniRec["anisotropy_s3"] = "%7.4f" % (float(words[7]) / 3.0)
            k += 1
            line = Data[k]
            rec = line.split()
            AniRec["anisotropy_s4"] = "%7.4f" % (float(rec[5]) / 3.0)  # eigenvalues sum to unity - not 3
            AniRec["anisotropy_s5"] = "%7.4f" % (float(rec[6]) / 3.0)
            AniRec["anisotropy_s6"] = "%7.4f" % (float(rec[7]) / 3.0)
            AniRec["anisotropy_tilt_correction"] = "-1"
            AniRecs.append(AniRec)
            AniRecG, AniRecT = {}, {}
            for key in AniRec.keys():
                AniRecG[key] = AniRec[key]
            for key in AniRec.keys():
                AniRecT[key] = AniRec[key]
            sbar = []
            sbar.append(float(AniRec["anisotropy_s1"]))
            sbar.append(float(AniRec["anisotropy_s2"]))
            sbar.append(float(AniRec["anisotropy_s3"]))
            sbar.append(float(AniRec["anisotropy_s4"]))
            sbar.append(float(AniRec["anisotropy_s5"]))
            sbar.append(float(AniRec["anisotropy_s6"]))
            sbarg = pmag.dosgeo(sbar, labaz, labdip)
            AniRecG["anisotropy_s1"] = "%12.10f" % (sbarg[0])
            AniRecG["anisotropy_s2"] = "%12.10f" % (sbarg[1])
            AniRecG["anisotropy_s3"] = "%12.10f" % (sbarg[2])
            AniRecG["anisotropy_s4"] = "%12.10f" % (sbarg[3])
            AniRecG["anisotropy_s5"] = "%12.10f" % (sbarg[4])
            AniRecG["anisotropy_s6"] = "%12.10f" % (sbarg[5])
            AniRecG["anisotropy_tilt_correction"] = "0"
            AniRecs.append(AniRecG)
            if bed_dip != "" and bed_dip != 0:  # have tilt correction
                sbart = pmag.dostilt(sbarg, dip_direction, bed_dip)
                AniRecT["anisotropy_s1"] = "%12.10f" % (sbart[0])
                AniRecT["anisotropy_s2"] = "%12.10f" % (sbart[1])
                AniRecT["anisotropy_s3"] = "%12.10f" % (sbart[2])
                AniRecT["anisotropy_s4"] = "%12.10f" % (sbart[3])
                AniRecT["anisotropy_s5"] = "%12.10f" % (sbart[4])
                AniRecT["anisotropy_s6"] = "%12.10f" % (sbart[5])
                AniRecT["anisotropy_tilt_correction"] = "100"
                AniRecs.append(AniRecT)
            MeasRecs.append(MeasRec)
            if SpecRec["er_specimen_name"] not in specnames:
                SpecRecs.append(SpecRec)
                specnames.append(SpecRec["er_specimen_name"])
            if SampRec["er_sample_name"] not in sampnames:
                SampRecs.append(SampRec)
                sampnames.append(SampRec["er_sample_name"])
            if SiteRec["er_site_name"] not in sitenames:
                SiteRecs.append(SiteRec)
                sitenames.append(SiteRec["er_site_name"])
        k += 1  # skip to next specimen
    pmag.magic_write(aoutput, AniRecs, "rmag_anisotropy")
    print "anisotropy tensors put in ", aoutput
    pmag.magic_write(moutput, MeasRecs, "magic_measurements")
    print "bulk measurements put in ", moutput
    if isspec == "0":
        SpecOut, keys = pmag.fillkeys(SpecRecs)
        output = dir_path + "/er_specimens.txt"
        pmag.magic_write(output, SpecOut, "er_specimens")
        print "specimen info put in ", output
        output = dir_path + "/er_samples.txt"
        SampOut, keys = pmag.fillkeys(SampRecs)
        pmag.magic_write(output, SampOut, "er_samples")
        print "sample info put in ", output
        output = dir_path + "/er_sites.txt"
        SiteOut, keys = pmag.fillkeys(SiteRecs)
        pmag.magic_write(output, SiteOut, "er_sites")
        print "site info put in ", output
    print """"
Exemplo n.º 9
0
def main():
    """
    NAME
        CIT_magic.py
 
    DESCRIPTION
        converts CIT and .sam  format files to magic_measurements format files

    SYNTAX
        CIT_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -usr USER:   identify user, default is ""
        -f FILE: specify .sam format input file, required
        -fsi SITEFILE : specify file with site names and locations [tab delimited magic file]
        -F FILE: specify output  measurements file, default is magic_measurements.txt
        -Fsp FILE: specify output er_specimens.txt file, default is er_specimens.txt
        -Fsi FILE: specify output er_sites.txt file, default is er_sites.txt
        -Fsa FILE: specify output er_samples.txt file, default is er_samples.txt  # LORI
        -n [gm,kg,cc,m3]: specify normalization
        -A: don't average replicate measurements
        -spc NUM : specify number of characters to designate a  specimen, default = 0
        -ncn NCON: specify naming convention
        -loc LOCNAME : specify location/study name, must have either LOCNAME or SITEFILE or be a synthetic
        -mcd [FS-FD:SO-MAG,.....] colon delimited list for method codes applied to all specimens in .sam file
        -dc B PHI THETA: dc lab field (in micro tesla) and phi,theta, default is none
              NB: use PHI, THETA = -1 -1 to signal that it changes, i.e. in anisotropy experiment
        -ac B : peak AF field (in mT) for ARM acquisition, default is none

    INPUT
        Best to put separate experiments (all AF, thermal, thellier, trm aquisition, Shaw, etc.) 

    NOTES:
         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) [default]
            [4-Z] XXXXYYY:  YYY is sample designation with Z characters from site XXX
            [5] all others you will have to either customize your
                self or e-mail [email protected] for help.
 
    """
    #
    #
    norm = 'cc'
    samp_con, Z = '3', 1
    meas_file = 'magic_measurements.txt'
    spec_file = 'er_specimens.txt'
    samp_file = 'er_samples.txt'
    site_file = 'er_sites.txt'
    ErSpecs, ErSamps, ErSites, ErLocs, ErCits = [], [], [], [], []
    MeasRecs = []
    specnum, units, locname = 0, "1", "unknown"
    citation = "This study"
    dir_path = '.'
    args = sys.argv
    if '-WD' in args:
        ind = args.index("-WD")
        dir_path = args[ind + 1]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind = args.index("-usr")
        user = args[ind + 1]
    if '-F' in args:
        ind = args.index("-F")
        meas_file = args[ind + 1]
    if '-Fsp' in args:
        ind = args.index("-Fsp")
        spec_file = args[ind + 1]
    if '-Fsa' in args:
        ind = args.index("-Fsa")
        samp_file = args[ind + 1]
    if '-Fsi' in args:  # LORI addition
        ind = args.index("-Fsi")
        site_file = args[ind + 1]
    if '-loc' in args:
        ind = args.index("-loc")
        locname = args[ind + 1]
    if '-mcd' in args:
        ind = args.index("-mcd")
        methods = args[ind + 1]
    else:
        methods = 'SO-MAG'
    if '-spc' in args:
        ind = args.index("-spc")
        specnum = -int(args[ind + 1])
    if '-n' in args:
        ind = args.index("-n")
        norm = args[ind + 1]
    if "-A" in args:
        avg = 1
    else:
        avg = 0
    if "-ncn" in args:
        ind = args.index("-ncn")
        samp_con = sys.argv[ind + 1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 3-Z where Z is an integer"
                sys.exit()
            else:
                Z = samp_con.split("-")[1]
                samp_con = "4"
    if '-f' in args:
        ind = args.index("-f")
        magfile = args[ind + 1]
    # LJ
    if '-ID' in args:
        ind = args.index('-ID')
        input_dir_path = args[ind + 1]
    else:
        input_dir_path = dir_path
    output_dir_path = dir_path
    # LJ
    magfile = input_dir_path + '/' + magfile
    spec_file = output_dir_path + '/' + spec_file
    samp_file = output_dir_path + '/' + samp_file
    site_file = output_dir_path + '/' + site_file
    meas_file = output_dir_path + '/' + meas_file
    try:
        input = open(magfile, 'r')
    except Exception as ex:
        print "bad sam file name"
        sys.exit()
    File = input.readlines()
    sids, ln, format = [], 0, 'CIT'
    formats = ['CIT', '2G', 'APP', 'JRA']
    ErLocRec = {}
    ErLocRec["er_location_name"] = locname
    ErLocRec["er_citation_name"] = citation
    comment = File[ln]
    if comment == 'CIT':
        format = comment
        ln += 1
    comment = File[ln]
    print comment
    ln += 1
    specimens, samples, sites = [], [], []
    if format == 'CIT':
        line = File[ln].split()
        site_lat = line[0]
        site_lon = line[1]
        ErLocRec["location_begin_lat"] = site_lat
        ErLocRec["location_begin_lon"] = site_lon
        ErLocRec["location_end_lat"] = site_lat
        ErLocRec["location_end_lon"] = site_lon
        ErLocs.append(ErLocRec)
        Cdec = float(line[2])
        for k in range(ln + 1, len(File)):
            line = File[k]
            rec = line.split()
            specimen = rec[0]
            specimens.append(specimen)
    for specimen in specimens:
        ErSpecRec, ErSampRec, ErSiteRec = {}, {}, {}
        if specnum != 0:
            sample = specimen[:specnum]
        else:
            sample = specimen
        site = pmag.parse_site(sample, samp_con, Z)
        ErSpecRec['er_specimen_name'] = specimen
        ErSpecRec['er_sample_name'] = sample
        ErSpecRec['er_site_name'] = site
        ErSpecRec['er_location_name'] = locname
        ErSpecRec['er_citation_name'] = citation
        ErSampRec['er_sample_name'] = sample
        ErSampRec['er_site_name'] = site
        ErSampRec['er_location_name'] = locname
        ErSampRec['er_citation_name'] = citation
        ErSampRec['magic_method_codes'] = methods
        ErSampRec['sample_declination_correction'] = '%7.1f' % (Cdec)
        ErSiteRec['er_site_name'] = site
        ErSiteRec['er_location_name'] = locname
        ErSiteRec['er_citation_name'] = citation
        ErSiteRec['site_lat'] = site_lat
        ErSiteRec['site_lon'] = site_lon
        f = open(input_dir_path + '/' + specimen, 'rU')
        Lines = f.readlines()
        comment = ""
        line = Lines[0].split()
        if len(line) > 2: comment = line[2]
        info = Lines[1].split()
        vol = float(info[-1])
        if vol != 1.0:
            if norm == 'cc': units = "1"
            if norm == 'm3': units = "2"
            ErSampRec['specimen_weight'] = ""
            if units == "1" or "":
                ErSampRec['specimen_volume'] = '%10.3e' % (vol * 1e-6)
            else:
                ErSampRec['specimen_volume'] = '%10.3e' % (vol)
        else:
            if norm == 'cc': units = "1"
            if norm == 'm3': units = "2"
            ErSampRec['specimen_volume'] = ""
            if units == "1" or "":
                ErSampRec['specimen_weight'] = '%10.3e' % (vol * 1e-3)
            else:
                ErSampRec['specimen_weight'] = '%10.3e' % (vol)
        dip = float(info[-2])
        dip_direction = float(info[-3]) + Cdec + 90.
        sample_dip = -float(info[-4])
        sample_azimuth = float(info[-5]) + Cdec - 90.
        if len(info) > 5:
            ErSampRec['sample_height'] = info[-6]
        else:
            ErSampRec['sample_height'] = '0'
        ErSampRec['sample_azimuth'] = '%7.1f' % (sample_azimuth)
        ErSampRec['sample_dip'] = '%7.1f' % (sample_dip)
        ErSampRec['sample_bed_dip'] = '%7.1f' % (dip)
        ErSampRec['sample_bed_dip_direction'] = '%7.1f' % (dip_direction)
        ErSampRec['sample_class'] = ''
        ErSampRec['sample_type'] = ''
        ErSampRec['sample_lithology'] = ''
        if Cdec != 0 or Cdec != "":
            ErSampRec['magic_method_codes'] = 'SO-CMD-NORTH'
        else:
            ErSampRec['magic_method_codes'] = 'SO-MAG'
        for line in Lines[2:len(Lines) - 1]:
            MeasRec = ErSpecRec.copy()
            treat_type = line[0:3]
            treat = line[3:6]
            if treat_type.strip(
            ) == 'NRM' or treat == '   ':  # reverting back.  otherwise breaks examples.
                MeasRec['magic_method_codes'] = 'LT-NO'
                MeasRec['measurement_temp'] = '273'
                MeasRec['treatment_temp'] = '273'
                MeasRec['treatment_dc_field'] = '0'
                MeasRec['treatment_ac_field'] = '0'
            elif treat_type.strip() == 'AF':
                MeasRec['magic_method_codes'] = 'LT-AF-Z'
                MeasRec['measurement_temp'] = '273'
                MeasRec['treatment_temp'] = '273'
                MeasRec['treatment_dc_field'] = '0'
                MeasRec['treatment_ac_field'] = '%10.3e' % (float(treat) *
                                                            1e-3)
            elif treat_type.strip() == 'TT':
                MeasRec['magic_method_codes'] = 'LT-T-Z'
                MeasRec['measurement_temp'] = '273'
                MeasRec['treatment_temp'] = '%7.1f' % (float(treat) + 273)
                MeasRec['treatment_dc_field'] = '0'
                MeasRec['treatment_ac_field'] = '0'
            elif treat_type.strip() == 'LT' or treat_type.strip() == 'LN2':
                MeasRec['magic_method_codes'] = 'LT-LT-Z'
                MeasRec['measurement_temp'] = '273'
                MeasRec['treatment_temp'] = '77'
                MeasRec['treatment_dc_field'] = '0'
                MeasRec['treatment_ac_field'] = '0'
            else:
                print "trouble with your treatment steps"
            MeasRec['measurement_dec'] = line[46:51]
            MeasRec['measurement_inc'] = line[52:58]
            M = '%8.2e' % (float(line[31:39]) * vol * 1e-3)  # convert to Am2
            MeasRec['measurement_magn_moment'] = M
            MeasRec['measurement_x_sd'] = '%8.2e' % (
                float(line[58:67]) * 1e-8)  #(convert e-5emu to Am2)
            MeasRec['measurement_y_sd'] = '%8.2e' % (float(line[67:76]) * 1e-8)
            MeasRec['measurement_z_sd'] = '%8.2e' % (float(line[76:85]) * 1e-8)
            MeasRec['measurement_csd'] = '%7.1f' % (eval(line[41:46]))
            MeasRec['magic_instrument_codes'] = line[85:]
            MeasRec["measurement_positions"] = '1'

            MeasRecs.append(MeasRec)
        ErSpecs.append(ErSpecRec)
        if sample not in samples:
            samples.append(sample)
            ErSamps.append(ErSampRec)
        site = pmag.parse_site(sample, samp_con, Z)
        if site not in sites:
            sites.append(site)
            ErSites.append(ErSiteRec)
    pmag.magic_write(spec_file, ErSpecs, 'er_specimens')
    print 'specimens stored in ', spec_file
    pmag.magic_write(samp_file, ErSamps, 'er_samples')
    print 'samples stored in ', samp_file
    pmag.magic_write(site_file, ErSites, 'er_sites')
    print 'sites stored in ', site_file
    Fixed = pmag.measurements_methods(MeasRecs, avg)
    pmag.magic_write(meas_file, Fixed, 'magic_measurements')
    print 'data stored in ', meas_file
Exemplo n.º 10
0
def main():
    """
    NAME
        kly-asc_magic.py

    DESCRIPTION
        converts ascii files generated by SUFAR ver.1.2 to MagIC formated
        files for use with PmagPy plotting software

    SYNTAX
        kly-asc_magic.py -h [command line options]

    OPTIONS
        -h: prints the help message and quits
        -f FILE: specify .asc input file name
        -Fa AFILE: specify rmag_anisotropy output file
        -Fr RFILE: specify rmag_results output file
        -Fs SFILE: specify er_specimens output file with location, sample, site, etc. information
        -usr USER: specify who made the measurements
        -loc LOC: specify location name for study 
        -ins INST: specify instrument used
        -spc SPEC: specify number of characters to specify specimen from sample
        -ncn NCON:  specify naming convention: default is #2 below

    DEFAULTS
        AFILE: rmag_anisotropy.txt
        RFILE: rmag_results.txt
        SFILE: default is to create new er_specimen.txt file
        USER: ""
        LOC: "unknown"
        INST: "PGL-KLY3"
        SPEC: 0  sample name is same as site (if SPEC is 1, sample is all but last character)
        creates new 'er_specimens.txt' file
        Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length) 
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXXYYY:  YYY is sample designation with Z characters from site XXX
            [5] all others you will have to either customize your 
                self or e-mail [email protected] for help.  

    """
    citation = "This study"
    cont = 0
    samp_con, Z = "1", 1
    ResRecs, SucRecs, SpecRecs, SampRecs, SiteRecs = [], [], [], [], []
    user, locname, specfile = "", "locname", "er_specimens.txt"
    isspec, inst, specnum = "0", "PGL-KLY3", 0
    aoutput, routput = "rmag_anisotropy.txt", "rmag_results.txt"
    dir_path = "."
    if "-h" in sys.argv:
        print main.__doc__
        sys.exit()
    if "-usr" in sys.argv:
        ind = sys.argv.index("-usr")
        user = sys.argv[ind + 1]
    if "-ncn" in sys.argv:
        ind = sys.argv.index("-ncn")
        samp_con = sys.argv[ind + 1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 3-Z where Z is an integer"
                sys.exit()
            else:
                Z = samp_con.split("-")[1]
                samp_con = "4"
    if "-f" in sys.argv:
        ind = sys.argv.index("-f")
        ascfile = sys.argv[ind + 1]
    elif "-i" not in sys.argv:
        print "must specify ascii input file or use interactive option [-i]\n\n "
        print main.__doc__
        sys.exit()
    if "-Fa" in sys.argv:
        ind = sys.argv.index("-Fa")
        aoutput = sys.argv[ind + 1]
    if "-Fr" in sys.argv:
        ind = sys.argv.index("-Fr")
        routput = sys.argv[ind + 1]
    if "-Fs" in sys.argv:
        ind = sys.argv.index("-Fs")
        specfile = sys.argv[ind + 1]
        isspec = "1"
    elif "-loc" in sys.argv:
        ind = sys.argv.index("-loc")
        locname = sys.argv[ind + 1]
        samp_con, Z = pmag.get_samp_con()
        if "-spc" in sys.argv:
            ind = sys.argv.index("-spc")
            specnum = -(int(sys.argv[ind + 1]))
    if "-i" in sys.argv:
        user = raw_input("Who made these measurements? \n Use the earthref mailname please, [] \n")
        if user == "":
            user = ""
        isspec = raw_input(
            " Is there an  existing er_specimen file [1] or do you wish to create one? [0] <return> to skip "
        )
        if isspec == "1":
            specfile = raw_input("Enter er_specimen file name: [er_specimens.txt] ")
            if specfile == "":
                specfile = "er_specimens.txt"
        elif isspec == "0":
            locname = raw_input("Enter location name for this study ")
            samp_con, Z = pmag.get_samp_con()
            ans = raw_input("How many characters to specify specimen [1] ")
            if ans == "":
                specnum = -1
            else:
                specnum = -int(ans)
        aoutput = raw_input("Filename for output [rmag_anisotropy.txt] ")
        if aoutput == "":
            aoutput = "rmag_anisotropy.txt"
        routput = raw_input("Filename for results output [rmag_results.txt] ")
        if routput == "":
            routput = "rmag_results.txt"
        ascfile = raw_input("Enter asc file for processing ")
    if isspec == "1":
        specs, file_type = pmag.magic_read(specfile)
    try:
        input = open(ascfile, "rU")
    except:
        print "Error opening file: ", ascfile
        sys.exit()
    Data = input.readlines()
    k = 0
    while k < len(Data):
        line = Data[k]
        words = line.split()
        if "ANISOTROPY" in words:  # first line of data for the spec
            SucRec, SpecRec, SampRec, SiteRec, ResRec = {}, {}, {}, {}, {}
            specname = words[0]
            SucRec["er_specimen_name"] = specname
            if isspec == "1":
                for spec in specs:
                    if spec["er_specimen_name"] == specname:
                        SucRec["er_sample_name"] = spec["er_sample_name"]
                        SucRec["er_site_name"] = spec["er_site_name"]
                        SucRec["er_location_name"] = spec["er_location_name"]
                        break
            elif isspec == "0":
                SucRec["er_sample_name"] = specname[:specnum]
                SpecRec["er_sample_name"] = specname[:specnum]
                SiteRec["er_sample_name"] = specname[:specnum]
                SucRec["er_site_name"] = pmag.parse_site(SucRec["er_sample_name"], samp_con, Z)
                SpecRec["er_site_name"] = pmag.parse_site(SucRec["er_sample_name"], samp_con, Z)
                SampRec["er_site_name"] = pmag.parse_site(SucRec["er_sample_name"], samp_con, Z)
                SiteRec["er_site_name"] = pmag.parse_site(SucRec["er_sample_name"], samp_con, Z)
                SucRec["er_location_name"] = locname
                SpecRec["er_location_name"] = locname
                SampRec["er_location_name"] = locname
                SiteRec["er_location_name"] = locname
                SpecRec["er_citation_names"] = "This study"
                SampRec["er_citation_names"] = "This study"
                SiteRec["er_citation_names"] = "This study"
                ResRec["er_sample_names"] = SucRec["er_sample_name"]
                ResRec["er_site_names"] = SucRec["er_site_name"]
            SucRec["er_citation_names"] = "This study"
            SucRec["magic_instrument_codes"] = inst
            SucRec["magic_method_codes"] = "LP-X:AE-H:LP-AN-MS"
            SucRec["magic_experiment_names"] = specname + ":" + "LP-AN-MS"
            SucRec["er_analyst_mail_names"] = user
            SucRec["anisotropy_type"] = "AMS"
            SucRec["anisotropy_n"] = "15"
            ResRec["rmag_result_name"] = SucRec["er_specimen_name"] + "Specimen Coordinates"
            ResRec["er_specimen_names"] = SucRec["er_specimen_name"]
            ResRec["magic_experiment_names"] = SucRec["magic_experiment_names"]
            ResRec["anisotropy_type"] = SucRec["anisotropy_type"]
        if "Azi" in words and isspec == "0":
            SampRec["sample_azimuth"] = words[1]
            SampRec["sample_dip"] = "%7.1f" % (-float(words[1]))
            SpecRec["specimen_vol"] = "%8.3e" % (float(words[10]) * 1e-6)  # convert actual volume to m^3 from cm^3
        if "[A/m]" in words:
            k += 2  # read in second line down
            line = Data[k]
            words = line.split()
            SucRec["anisotropy_mean"] = words[1]
            SucRec["anisotropy_sigma"] = words[2]
            SucRec["anisotropy_unit"] = "SI"
            ResRec["anisotropy_ftest"] = words[3]
            ResRec["anisotropy_ftest12"] = words[4]
            ResRec["anisotropy_ftest23"] = words[5]
        if "susceptibilities" in words:
            k += 2  # read in second line down
            line = Data[k]
            words = line.split()
            ResRec["anisotropy_t1"] = "%6.4f" % (float(words[0]) / 3.0)
            ResRec["anisotropy_t2"] = "%6.4f" % (float(words[1]) / 3.0)
            ResRec["anisotropy_t3"] = "%6.4f" % (float(words[2]) / 3.0)
            ResRec["anisotropy_v1_eta_semi_angle"] = words[3]
            ResRec["anisotropy_v2_eta_semi_angle"] = words[4]
            ResRec["anisotropy_v3_eta_semi_angle"] = words[5]
            k += 2  # read in second line down
            line = Data[k]
            words = line.split()
            ResRec["anisotropy_v1_zeta_semi_angle"] = words[4]
            ResRec["anisotropy_v2_zeta_semi_angle"] = words[5]
            ResRec["anisotropy_v3_zeta_semi_angle"] = words[6]
        if "factors" in words:
            k += 4  # read in second line down
            line = Data[k]
            words = line.split()
            ResRec["anisotropy_l"] = words[0]
            ResRec["anisotropy_f"] = words[1]
            ResRec["anisotropy_p"] = words[2]
            ResRec["anisotropy_pp"] = words[3]
            ResRec["anisotropy_t"] = words[4]
        if "Specimen" in words:  # first part of specimen data
            ResRec["anisotropy_v1_dec"] = words[2]
            ResRec["anisotropy_v2_dec"] = words[3]
            ResRec["anisotropy_v3_dec"] = words[4]
            SucRec["anisotropy_s1"] = "%6.4f" % (float(words[5]) / 3.0)  # eigenvalues sum to unity - not 3
            SucRec["anisotropy_s2"] = "%6.4f" % (float(words[6]) / 3.0)
            SucRec["anisotropy_s3"] = "%6.4f" % (float(words[7]) / 3.0)
            k += 1
            line = Data[k]
            words = line.split()
            ResRec["anisotropy_v1_inc"] = words[2]
            ResRec["anisotropy_v2_inc"] = words[3]
            ResRec["anisotropy_v3_inc"] = words[4]
            SucRec["anisotropy_s4"] = "%6.4f" % (float(words[5]) / 3.0)  # eigenvalues sum to unity - not 3
            SucRec["anisotropy_s5"] = "%6.4f" % (float(words[6]) / 3.0)
            SucRec["anisotropy_s6"] = "%6.4f" % (float(words[7]) / 3.0)
            SucRec["anisotropy_tilt_correction"] = "-1"
            ResRec["anisotropy_v1_eta_dec"] = ResRec["anisotropy_v2_dec"]
            ResRec["anisotropy_v1_eta_inc"] = ResRec["anisotropy_v2_inc"]
            ResRec["anisotropy_v1_zeta_dec"] = ResRec["anisotropy_v3_dec"]
            ResRec["anisotropy_v1_zeta_inc"] = ResRec["anisotropy_v3_inc"]
            ResRec["anisotropy_v2_eta_dec"] = ResRec["anisotropy_v1_dec"]
            ResRec["anisotropy_v2_eta_inc"] = ResRec["anisotropy_v1_inc"]
            ResRec["anisotropy_v2_zeta_dec"] = ResRec["anisotropy_v3_dec"]
            ResRec["anisotropy_v2_zeta_inc"] = ResRec["anisotropy_v3_inc"]
            ResRec["anisotropy_v3_eta_dec"] = ResRec["anisotropy_v1_dec"]
            ResRec["anisotropy_v3_eta_inc"] = ResRec["anisotropy_v1_inc"]
            ResRec["anisotropy_v3_zeta_dec"] = ResRec["anisotropy_v2_dec"]
            ResRec["anisotropy_v3_zeta_inc"] = ResRec["anisotropy_v2_inc"]
            ResRec["anisotropy_tilt_correction"] = "-1"
            k += 2
            line = Data[k]
            words = line.split()
            SucRecs.append(SucRec)
            ResRecs.append(ResRec)
            ResRecG = copy.copy(ResRec)
            SucRecG = copy.copy(SucRec)
            ResRecG["rmag_result_name"] = SucRec["er_specimen_name"] + "Geographic Coordinates"
            ResRecG["anisotropy_v1_dec"] = words[2]
            ResRecG["anisotropy_v2_dec"] = words[3]
            ResRecG["anisotropy_v3_dec"] = words[4]
            SucRecG["anisotropy_s1"] = "%6.4f" % (float(words[5]) / 3.0)  # eigenvalues sum to unity - not 3
            SucRecG["anisotropy_s2"] = "%6.4f" % (float(words[6]) / 3.0)
            SucRecG["anisotropy_s3"] = "%6.4f" % (float(words[7]) / 3.0)
            k += 1
            line = Data[k]
            words = line.split()
            ResRecG["anisotropy_v1_inc"] = words[2]
            ResRecG["anisotropy_v2_inc"] = words[3]
            ResRecG["anisotropy_v3_inc"] = words[4]
            SucRecG["anisotropy_s4"] = "%6.4f" % (float(words[5]) / 3.0)  # eigenvalues sum to unity - not 3
            SucRecG["anisotropy_s5"] = "%6.4f" % (float(words[6]) / 3.0)
            SucRecG["anisotropy_s6"] = "%6.4f" % (float(words[7]) / 3.0)
            SucRecG["anisotropy_tilt_correction"] = "0"
            ResRecG["anisotropy_tilt_correction"] = "0"
            Dgeo, Igeo = float(ResRecG["anisotropy_v1_dec"]), float(ResRecG["anisotropy_v1_inc"])
            ResRecG["anisotropy_v1_eta_dec"] = ResRecG["anisotropy_v2_dec"]
            ResRecG["anisotropy_v1_eta_inc"] = ResRecG["anisotropy_v2_inc"]
            ResRecG["anisotropy_v1_zeta_dec"] = ResRecG["anisotropy_v3_dec"]
            ResRecG["anisotropy_v1_zeta_inc"] = ResRecG["anisotropy_v3_inc"]
            ResRecG["anisotropy_v2_eta_dec"] = ResRecG["anisotropy_v1_dec"]
            ResRecG["anisotropy_v2_eta_inc"] = ResRecG["anisotropy_v1_inc"]
            ResRecG["anisotropy_v2_zeta_dec"] = ResRecG["anisotropy_v3_dec"]
            ResRecG["anisotropy_v2_zeta_inc"] = ResRecG["anisotropy_v3_inc"]
            ResRecG["anisotropy_v3_eta_dec"] = ResRecG["anisotropy_v1_dec"]
            ResRecG["anisotropy_v3_eta_inc"] = ResRecG["anisotropy_v1_inc"]
            ResRecG["anisotropy_v3_zeta_dec"] = ResRecG["anisotropy_v2_dec"]
            ResRecG["anisotropy_v3_zeta_inc"] = ResRecG["anisotropy_v2_inc"]
            k += 2
            line = Data[k]
            words = line.split()
            ResRecs.append(ResRecG)
            SucRecs.append(SucRecG)
            SucRecT = copy.copy(SucRecG)
            ResRecT = copy.copy(ResRecG)
            ResRecT["anisotropy_v1_dec"] = words[3]
            ResRecT["anisotropy_v2_dec"] = words[4]
            ResRecT["anisotropy_v3_dec"] = words[5]
            SucRecT["anisotropy_s1"] = "%6.4f" % (float(words[6]) / 3.0)  # eigenvalues sum to unity - not 3
            SucRecT["anisotropy_s2"] = "%6.4f" % (float(words[7]) / 3.0)
            SucRecT["anisotropy_s3"] = "%6.4f" % (float(words[8]) / 3.0)
            k += 1  # skip down 1
            line = Data[k]
            words = line.split()
            ResRecT["anisotropy_v1_inc"] = words[2]
            ResRecT["anisotropy_v2_inc"] = words[3]
            ResRecT["anisotropy_v3_inc"] = words[4]
            Dtilt, Itilt = float(ResRecT["anisotropy_v1_dec"]), float(ResRecT["anisotropy_v1_inc"])
            DipDir, Dip = pmag.get_tilt(Dgeo, Igeo, Dtilt, Itilt)
            SampRec["sample_bed_dip_direction"] = "%7.1f" % (DipDir)
            SampRec["sample_bed_dip"] = "%7.1f" % (Dip)
            SucRecT["anisotropy_s4"] = "%6.4f" % (float(words[5]) / 3.0)  # eigenvalues sum to unity - not 3
            SucRecT["anisotropy_s5"] = "%6.4f" % (float(words[6]) / 3.0)
            SucRecT["anisotropy_s6"] = "%6.4f" % (float(words[7]) / 3.0)
            SucRecT["anisotropy_tilt_correction"] = "100"
            ResRecT["anisotropy_tilt_correction"] = "100"
            ResRecT["anisotropy_v1_eta_dec"] = ResRecT["anisotropy_v2_dec"]
            ResRecT["anisotropy_v1_eta_inc"] = ResRecT["anisotropy_v2_inc"]
            ResRecT["anisotropy_v1_zeta_dec"] = ResRecT["anisotropy_v3_dec"]
            ResRecT["anisotropy_v1_zeta_inc"] = ResRecT["anisotropy_v3_inc"]
            ResRecT["anisotropy_v2_eta_dec"] = ResRecT["anisotropy_v1_dec"]
            ResRecT["anisotropy_v2_eta_inc"] = ResRecT["anisotropy_v1_inc"]
            ResRecT["anisotropy_v2_zeta_dec"] = ResRecT["anisotropy_v3_dec"]
            ResRecT["anisotropy_v2_zeta_inc"] = ResRecT["anisotropy_v3_inc"]
            ResRecT["anisotropy_v3_eta_dec"] = ResRecT["anisotropy_v1_dec"]
            ResRecT["anisotropy_v3_eta_inc"] = ResRecT["anisotropy_v1_inc"]
            ResRecT["anisotropy_v3_zeta_dec"] = ResRecT["anisotropy_v2_dec"]
            ResRecT["anisotropy_v3_zeta_inc"] = ResRecT["anisotropy_v2_inc"]
            SucRecs.append(SucRecT)
            ResRecs.append(ResRecT)
            SpecRecs.append(SpecRec)
            SampRecs.append(SampRec)
            SiteRecs.append(SiteRec)
        k += 1
    pmag.magic_write(aoutput, SucRecs, "rmag_anisotropy")
    print "anisotropy tensors put in ", aoutput
    pmag.magic_write(routput, ResRecs, "rmag_results")
    print "anisotropy results put in ", routput
    if isspec == "0":
        output = "er_specimens.txt"
        pmag.magic_write(output, SpecRecs, "er_specimens")
        print "specimen info put in ", output
        output = "er_samples.txt"
        pmag.magic_write(output, SampRecs, "er_samples")
        print "sample info put in ", output
        output = "er_sites.txt"
        pmag.magic_write(output, SiteRecs, "er_sites")
        print "site info put in ", output
    print """"
Exemplo n.º 11
0
def main():
    """
    NAME
        azdip_magic.py
   
    DESCRIPTION
        takes space delimited AzDip file and converts to MagIC formatted tables
 
    SYNTAX
        azdip_magic.py [command line options]

    OPTIONS
        -f FILE: specify input file
        -Fsa FILE: specify output file, default is: er_samples.txt 
        -ncn NCON:  specify naming convention: default is #1 below
        -mcd: specify sampling method codes as a colon delimited string:  [default is: FS-FD]
             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
        -loc: location name, default="unknown"
        -app appends to existing er_samples.txt file, default is to overwrite

    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 
    
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 
    OUTPUT
            output saved in er_samples.txt  will overwrite any existing files 
    """
    #
    # initialize variables
    #
    DEBUG = 0
    version_num = pmag.get_version()
    orient_file, samp_file, or_con, corr = "orient.txt", "er_samples.txt", "3", "1"
    args = sys.argv
    date, lat, lon = "", "", ""  # date of sampling, latitude (pos North), longitude (pos East)
    bed_dip, bed_dip_dir = "", ""
    participantlist = ""
    sites = []  # list of site names
    Lats, Lons = [], []  # list of latitudes and longitudes
    SampRecs, SiteRecs, ImageRecs, imagelist = [], [], [], []  # lists of Sample records and Site records
    samp_con, Z, average_bedding = "1", 1, "0"
    newbaseline, newbeddir, newbeddip = "", "", ""
    meths = "FS-FD"
    delta_u = "0"
    sclass, lithology, type = "", "", ""
    newclass, newlith, newtype = "", "", ""
    user = ""
    corr == "3"
    DecCorr = 0.0
    location_name = "unknown"
    #
    #
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-f" in args:
        ind = args.index("-f")
        orient_file = sys.argv[ind + 1]
    if "-Fsa" in args:
        ind = args.index("-Fsa")
        samp_file = sys.argv[ind + 1]
    if "-ncn" in args:
        ind = args.index("-ncn")
        samp_con = sys.argv[ind + 1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z = samp_con.split("-")[1]
                samp_con = "4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z = samp_con.split("-")[1]
                samp_con = "7"
    if "-mcd" in args:
        ind = args.index("-mcd")
        meths = sys.argv[ind + 1]
    if "-loc" in args:
        ind = args.index("-loc")
        location_name = sys.argv[ind + 1]
    if "-app" in args:
        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, "rU")
    AzDipDat = azfile.readlines()
    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.0  # 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 = meths.replace(" ", "").split(":")
            OR = 0
            for method in methods:
                type = method.split("-")
                if "SO" in type:
                    OR = 1
            if OR == 0:
                meths = meths + ":SO-NO"
            MagRec["magic_method_codes"] = meths
            site = pmag.parse_site(orec[0], samp_con, Z)  # parse out the site name
            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)
    pmag.magic_write(samp_file, Samps, "er_samples")
    print "Data saved in ", samp_file
Exemplo n.º 12
0
def main():
    """
    NAME
        UR_jr6_magic.py
 
    DESCRIPTION
        converts University of Rome JR6 format files to magic_measurements format files

    SYNTAX
        UR_jr6_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -F FILE: specify output  measurements file, default is magic_measurements.txt
        -Fsa FILE: specify output er_samples.txt file for appending, default is er_samples.txt
        -dc B PHI THETA: dc lab field (in micro tesla) and phi,theta, default is none
              NB: use PHI, THETA = -1 -1 to signal that it changes, i.e. in anisotropy experiment
        -ac B : peak AF field (in mT) for ARM acquisition, default is none
        -A : don't average replicate measurements
        -spc NUM : specify number of characters to designate a  specimen, default = 0
        -loc LOCNAME : specify location/study name, must have either LOCNAME or SAMPFILE or be a synthetic
        -mcd: specify sampling method codes as a colon delimited string:  [default is: FS-FD:SO-POM:SO-SUN]
             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-SUN   orientations are from a sun compass
             SO-MAG   orientations are from a magnetic compass
             SO-MAG-CMD   orientations declination corrected magnetic compass
        -ncn NCON:  specify naming convention: default is #1 below
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.

            [8] synthetic - has no site name
            [9] ODP naming convention


    INPUT
        Put data from separate experiments (all AF, thermal, thellier, trm aquisition, Shaw, etc.)  in separate directory

    """
#        
#
    version_num=pmag.get_version()
    er_location_name=""
    ErSpecs,ErSamps,ErSites,ErLocs,ErCits=[],[],[],[],[]
    MagRecs=[]
    citation="This study"
    dir_path,demag='.','NRM'
    args=sys.argv
    noave=0
    specnum=0
    sampmeths='FS-FD:SO-POM:SO-SUN'
    samp_con,Z="4","2"
    if '-WD' in args:
        ind=args.index("-WD")
        dir_path=args[ind+1]
    meas_file=dir_path+'/'+'magic_measurements.txt'
    samp_file=dir_path+'/'+'er_samples.txt'
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-A" in args: noave=1
    if '-F' in args:
        ind=args.index("-F")
        meas_file=dir_path+'/'+args[ind+1]
    if '-Fsa' in args:
        ind=args.index("-Fsa")
        samp_file=dir_path+'/'+args[ind+1]
        ErSamps,file_type=pmag.magic_read(samp_file)
    if "-ncn" in args:
        ind=args.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
    if "-mcd" in args:
        ind=args.index("-mcd")
        sampmeths=(sys.argv[ind+1])
    if "-loc" in args:
        ind=args.index("-loc")
        er_location_name=args[ind+1]
    if "-spc" in args:
        ind=args.index("-spc")
        specnum=int(args[ind+1])
        if specnum!=0:specnum=-specnum
    if '-LP' in args:
        ind=args.index("-LP")
        codelist=args[ind+1]
        codes=codelist.split(':')
        if "AF" in codes:
            demag='AF' 
            if'-dc' not in args: methcode="LT-AF-Z"
            if'-dc' in args: methcode="LT-AF-I"
        if "T" in codes:
            demag="T"
            if '-dc' not in args: methcode="LT-T-Z"
            if '-dc' in args: methcode="LT-T-I"
        if "I" in codes:
            methcode="LP-IRM"
        if "S" in codes: 
            demag="S"
            methcode="LP-PI-TRM:LP-PI-ALT-AFARM"
            trm_labfield=labfield
            ans=raw_input("DC lab field for ARM step: [50uT] ")
            if ans=="":
                arm_labfield=50e-6
            else: 
                arm_labfield=float(ans)*1e-6
            ans=raw_input("temperature for total trm step: [600 C] ")
            if ans=="":
                trm_peakT=600+273 # convert to kelvin
            else: 
                trm_peakT=float(ans)+273 # convert to kelvin
        if "G" in codes: methcode="LT-AF-G"
	if "D" in codes: methcode="LT-AF-D"
        if "TRM" in codes: 
            demag="T"
            trm=1
    if demag=="T" and "ANI" in codes:
        methcode="LP-AN-TRM"
    if demag=="AF" and "ANI" in codes:
        methcode="LP-AN-ARM"
        if labfield==0: labfield=50e-6
        if peakfield==0: peakfield=.180
    filelist=os.listdir(dir_path) # read in list of files to import
    samples=[]
    MagRecs,SampRecs=[],[]
    for samp in ErSamps:
        if samp['er_sample_name'] not in samples:
            samples.append(samp['er_sample_name'])
            SampRecs.append(samp)
    for file in filelist: # parse each file
        parts=file.split('.')
        if parts[1].upper()=='JR6':
            print 'processing: ',file
            treatment_type,treatment_value,user="","",""
            inst="UR-JR6"
            input=open(dir_path+'/'+file,'rU').readlines()
            for line in input:
                newline=line.replace('-',' -')
                rec=newline.split()
                MagRec,SampRec={},{}
                specimen=rec[0]
                if specnum!=0:
                    SampRec['er_sample_name']=specimen[:specnum]
                else:
                    SampRec['er_sample_name']=specimen
                er_site_name=pmag.parse_site(SampRec['er_sample_name'],samp_con,Z)
                SampRec['er_site_name']=er_site_name
                SampRec['er_location_name']=er_location_name
                for key in SampRec.keys():MagRec[key]=SampRec[key]
                SampRec['sample_azimuth']=rec[7]
                SampRec['sample_dip']='-'+rec[8]
                SampRec['sample_bed_dip_direction']=rec[9]
                SampRec['sample_bed_dip']=rec[10]
                SampRec['magic_method_codes']=sampmeths
                MagRec['er_specimen_name']=specimen
                MagRec['er_analyst_mail_names']=user
                MagRec['magic_software_packages']=version_num
                MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
                MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
                MagRec["treatment_ac_field"]='0'
                MagRec["treatment_dc_field"]='0'
                MagRec["treatment_dc_field_phi"]='0'
                MagRec["treatment_dc_field_theta"]='0'
                MagRec["measurement_flag"]='g' # assume all data are "good"
                MagRec["measurement_standard"]='u' # assume all data are "good"
                MagRec["measurement_csd"]='' # set csd to blank
                MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
                MagRec['magic_method_codes']='LT-NO'
                if rec[2]=='C':
                    temp=float(rec[1])+273.     
                    if temp>298: 
                        MagRec["treatment_temp"]='%8.3e' % (temp) # room temp in kelvin
                        MagRec['magic_method_codes']='LT-T-Z'
                else: # measurement is in oe
                    AC=float(rec[1])*1e-4 # convert to tesla
                    if AC!=0.:
                        MagRec["treatment_ac_field"]='%8.3e' %(AC)
                        MagRec['magic_method_codes']='LT-AF-Z'
                vol=10.8*1e-6 # standard Roma lab volume
                MagRec['magic_instrument_codes']=inst
                MagRec['measurement_number']='1'
                mexp=10**(float(rec[6]))
                x,y,z=mexp*float(rec[3]),mexp*float(rec[4]),mexp*float(rec[5])
                Cart=[x,y,z]
                Dir=pmag.cart2dir(Cart)
                MagRec['measurement_dec']='%7.1f'%(Dir[0])
                MagRec['measurement_inc']='%7.1f'%(Dir[1])
                MagRec['measurement_magn_volume']='%8.3e'%(Dir[2])
                MagRec['measurement_magn_moment']='%8.3e'%(Dir[2]*vol)
                MagRec['measurement_description']='converted A/m to Am^2 using volume of '+str(vol)+' m^3'
                MagRecs.append(MagRec)
                if MagRec['er_sample_name'] not in samples:
                    samples.append(MagRec['er_sample_name'])
                    SampRecs.append(SampRec)
    if len(SampRecs)>0:
        SampOut,keys=pmag.fillkeys(SampRecs)
        pmag.magic_write(samp_file,SampOut,'er_samples')
        print 'samples stored in ',samp_file
    Fixed=pmag.measurements_methods(MagRecs,noave)
    pmag.magic_write(meas_file,Fixed,'magic_measurements')
    print 'data stored in ',meas_file
Exemplo n.º 13
0
def main(command_line=True, **kwargs):
    """
    NAME
        2G_bin_magic.py
   
    DESCRIPTION
        takes the binary 2G format magnetometer files and converts them to magic_measurements, er_samples.txt and er_sites.txt file
 
    SYNTAX
        2G_bin_magic.py [command line options]

    OPTIONS
        -f FILE: specify input 2G (binary) file
        -F FILE: specify magic_measurements output file, default is: magic_measurements.txt
        -Fsa FILE: specify output file, default is: er_samples.txt 
        -Fsi FILE: specify output file, default is: er_sites.txt 
        -ncn NCON:  specify naming convention: default is #2 below
        -ocn OCON:  specify orientation convention, default is #5 below
        -mcd: specify sampling method codes as a colon delimited string:  [default is: FS-FD:SO-POM]
             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
             SO-SUN   orientation with sun compass
        -loc: location name, default="unknown"
        -spc NUM : specify number of characters to designate a  specimen, default = 0     
        -ins INST : specify instsrument name
        -a: average replicate measurements

    INPUT FORMAT
        Input files are horrible mag binary format (who knows why?)
        Orientation convention:
            [1] Lab arrow azimuth= mag_azimuth; Lab arrow dip=-field_dip
                i.e., field_dip is degrees from vertical down - the hade [default]
            [2] Lab arrow azimuth = mag_azimuth-90; Lab arrow dip = -field_dip
                i.e., mag_azimuth is strike and field_dip is hade
            [3] Lab arrow azimuth = mag_azimuth; Lab arrow dip = 90-field_dip
                i.e.,  lab arrow same as field arrow, but field_dip was a hade.
            [4] lab azimuth and dip are same as mag_azimuth, field_dip
            [5] 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] all others you will have to either customize your 
                self or e-mail [email protected] for help.  
 
         Magnetic declination convention:
             Az will use supplied declination to correct azimuth 
    
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 

    OUTPUT
            output saved in magic_measurements.txt & er_samples.txt formatted files
              will overwrite any existing files 
    """
    #
    # initialize variables
    #
    mag_file = ''
    specnum=0
    ub_file,samp_file,or_con,corr,meas_file = "","er_samples.txt","3","1","magic_measurements.txt"
    pos_file,site_file="","er_sites.txt"
    noave=1
    args=sys.argv
    bed_dip,bed_dip_dir="",""
    samp_con,Z,average_bedding="2",1,"0"
    meths='FS-FD'
    sclass,lithology,_type="","",""
    user,inst="",""
    DecCorr=0.
    location_name="unknown"
    months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
    gmeths=""
    #
    #
    dir_path='.'
    if command_line:
        if '-WD' in args:
            ind=args.index("-WD")
            dir_path=sys.argv[ind+1]
        if "-h" in args:
            print main.__doc__
            return False
        if "-f" in args:
            ind=args.index("-f")
            mag_file=sys.argv[ind+1]
        if "-fpos" in args:
            ind=args.index("-fpos")
            pos_file=sys.argv[ind+1]
        if "-F" in args:
            ind=args.index("-F")
            meas_file=sys.argv[ind+1]
        if "-Fsa" in args:
            ind=args.index("-Fsa")
            samp_file=sys.argv[ind+1]
        if "-Fsi" in args:
            ind=args.index("-Fsi")
            site_file=sys.argv[ind+1]
        if "-ocn" in args:
            ind=args.index("-ocn")
            or_con=sys.argv[ind+1]
        if "-ncn" in args:
            ind=args.index("-ncn")
            samp_con=sys.argv[ind+1]
        if "-mcd" in args:
            ind=args.index("-mcd")
            gmeths=(sys.argv[ind+1])
        if "-loc" in args:
            ind=args.index("-loc")
            location_name=(sys.argv[ind+1])
        if "-spc" in args:
            ind=args.index("-spc")
            specnum=int(args[ind+1])

        if "-ins" in args:
            ind=args.index("-ins")
            inst=args[ind+1]
        if "-a" in args:
            noave=0
        #
        ID = False
        if '-ID' in args:
            ind = args.index('-ID')
            ID = args[ind+1]
        #

    if not command_line:
        dir_path = kwargs.get('dir_path', '.')
        mag_file = kwargs.get('mag_file', '')
        pos_file = kwargs.get('pos_file', '')
        meas_file = kwargs.get('meas_file', 'magic_measurements.txt')
        samp_file = kwargs.get('samp_file', 'er_samples.txt')
        site_file = kwargs.get('site_file', 'er_sites.txt')
        or_con = kwargs.get('or_con', '3')
        samp_con = kwargs.get('samp_con', '2')
        corr = kwargs.get('corr', '1')
        gmeths = kwargs.get('gmeths', '')
        location_name = kwargs.get('location_name', '')
        specnum = int(kwargs.get('specnum', 0))
        inst = kwargs.get('inst', '')
        noave = kwargs.get('noave', 1) # default is DO average
        ID = kwargs.get('ID', '')

    # format and fix variables acquired from command line args or input with **kwargs
    if specnum!=0:specnum=-specnum

    if ID:
        input_dir_path = ID
    else:
        input_dir_path = dir_path

    if samp_con:
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                return False, "option [4] must be in form 4-Z where Z is an integer"
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                return False, "option [7] must be in form 7-Z where Z is an integer"
            else:
                Z=samp_con.split("-")[1]
                samp_con="7"
        if "6" in samp_con:
            try:
                Samps,file_type=pmag.magic_read(os.path.join(input_dir_path, 'er_samples.txt'))
            except:
                print "there is no er_samples.txt file in your input directory - you can't use naming convention #6"
                return False, "there is no er_samples.txt file in your input directory - you can't use naming convention #6"
            if file_type == 'bad_file':
                print "there is no er_samples.txt file in your input directory - you can't use naming convention #6"
                return False, "there is no er_samples.txt file in your input directory - you can't use naming convention #6"
                

    if not mag_file:
        print "mag file is required input"
        return False, "mag file is required input"
    output_dir_path = dir_path
    mag_file = os.path.join(input_dir_path, mag_file)
    samp_file = output_dir_path+'/'+samp_file
    site_file = output_dir_path+'/'+site_file
    meas_file= output_dir_path+'/'+meas_file
    samplist=[]
    try:
        Samps,file_type=pmag.magic_read(samp_file)
        for samp in Samps:
            if samp['er_sample_name'] not in samplist: samplist.append(samp['er_sample_name'])
    except:
        Samps=[]
    MagRecs=[]
    try:
        f=open(mag_file,'rU')
        input=f.read()
        f.close()
    except Exception as ex:
        print 'ex', ex
        print "bad mag file"
        return False, "bad mag file"
    firstline,date=1,""
    d=input.split('\xcd')
    for line in d:
                rec=line.split('\x00')
                if firstline==1:
                    firstline=0
                    spec,vol="",1
                    for c in line[15:23]:
                        if c!='\x00':spec=spec+c 
# check for bad sample name
                    test=spec.split('.')
                    date=""
                    if len(test)>1:
                            spec=test[0]
                            kk=24
                            while line[kk]!='\x01' and line[kk]!='\x00':
                                kk+=1
                            vcc=line[24:kk]
                            el=10
                            while rec[el].strip()!='':el+=1
                            date,comments=rec[el+7],[]
                    else:
                        el=9
                        while rec[el]!='\x01':el+=1
                        vcc,date,comments=rec[el-3],rec[el+7],[]
                    specname=spec.lower()
                    print 'importing ',specname
                    el+=8
                    while rec[el].isdigit()==False:
                        comments.append(rec[el])
                        el+=1
                    while rec[el]=="":el+=1
                    az=float(rec[el])
                    el+=1
                    while rec[el]=="":el+=1
                    pl=float(rec[el])
                    el+=1
                    while rec[el]=="":el+=1
                    bed_dip_dir=float(rec[el])
                    el+=1
                    while rec[el]=="":el+=1
                    bed_dip=float(rec[el])
                    el+=1
                    while rec[el]=="":el+=1
                    if rec[el]=='\x01': 
                        bed_dip=180.-bed_dip
                        el+=1
                        while rec[el]=="":el+=1
                    fold_az=float(rec[el])
                    el+=1
                    while rec[el]=="":el+=1
                    fold_pl=rec[el]
                    el+=1
                    while rec[el]=="":el+=1
                    if rec[el]!="" and rec[el]!='\x02' and rec[el]!='\x01':
                        deccorr=float(rec[el])
                        az+=deccorr
                        bed_dip_dir+=deccorr
                        fold_az+=deccorr
                        if bed_dip_dir>=360:bed_dip_dir=bed_dip_dir-360.
                        if az>=360.:az=az-360.
                        if fold_az>=360.:fold_az=fold_az-360.
                    else:
                        deccorr=0
                    if specnum!=0:
                        sample=specname[:specnum]
                    else:
                        sample=specname
                    SampRec={}
                    SampRec["er_sample_name"]=sample
                    SampRec["er_location_name"]=location_name
                    SampRec["er_citation_names"]="This study"
                    labaz,labdip=pmag.orient(az,pl,or_con) # convert to labaz, labpl
        #
        # parse information common to all orientation methods
        #
                    SampRec["sample_bed_dip"]='%7.1f'%(bed_dip)
                    SampRec["sample_bed_dip_direction"]='%7.1f'%(bed_dip_dir)
                    SampRec["sample_dip"]='%7.1f'%(labdip)
                    SampRec["sample_azimuth"]='%7.1f'%(labaz)
                    if vcc.strip()!="":vol=float(vcc)*1e-6 # convert to m^3 from cc
                    SampRec["sample_volume"]='%10.3e'%(vol) # 
                    SampRec["sample_class"]=sclass
                    SampRec["sample_lithology"]=lithology
                    SampRec["sample_type"]=_type
                    SampRec["sample_declination_correction"]='%7.1f'%(deccorr)
                    methods=gmeths.split(':')
                    if deccorr!="0":
                        if 'SO-MAG' in methods:del methods[methods.index('SO-MAG')]
                        methods.append('SO-CMD-NORTH')
                    meths=""
                    for meth in methods:meths=meths+meth+":"
                    meths=meths[:-1]
                    SampRec["magic_method_codes"]=meths
                    if int(samp_con)<6 or int(samp_con) == 7: 
                        site=pmag.parse_site(SampRec["er_sample_name"],samp_con,Z) # parse out the site name
                        SampRec["er_site_name"]=site
                    elif len(Samps)>1:
                        site,location="",""
                        for samp in Samps: 
                            if samp["er_sample_name"] == SampRec["er_sample_name"]:
                                site=samp["er_site_name"]
                                location=samp["er_location_name"]
                                break
                        SampRec["er_location_name"]=samp["er_location_name"]
                        SampRec["er_site_name"]=samp["er_site_name"]
                    if sample not in samplist:
                        samplist.append(sample)
                        Samps.append(SampRec)
                else:
                    MagRec={}
                    MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
                    MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
                    MagRec["treatment_ac_field"]='0'
                    MagRec["treatment_dc_field"]='0'
                    MagRec["treatment_dc_field_phi"]='0'
                    MagRec["treatment_dc_field_theta"]='0'
                    meas_type="LT-NO"
                    MagRec["measurement_flag"]='g'
                    MagRec["measurement_standard"]='u'
                    MagRec["measurement_number"]='1'
                    MagRec["er_specimen_name"]=specname
                    MagRec["er_sample_name"]=SampRec['er_sample_name']
                    MagRec["er_site_name"]=SampRec['er_site_name']
                    MagRec["er_location_name"]=location_name
                    el,demag=1,''
                    treat=rec[el]
                    if treat[-1]=='C':
                        demag='T'
                    elif treat!='NRM':
                        demag='AF'  
                    el+=1
                    while rec[el]=="":el+=1
                    MagRec["measurement_dec"]=rec[el]
                    cdec=float(rec[el])
                    el+=1
                    while rec[el]=="":el+=1
                    MagRec["measurement_inc"]=rec[el]
                    cinc=float(rec[el])
                    el+=1
                    while rec[el]=="":el+=1
                    gdec=rec[el]
                    el+=1
                    while rec[el]=="":el+=1
                    ginc=rec[el]
                    el=skip(2,el,rec) # skip bdec,binc
#                el=skip(4,el,rec) # skip gdec,ginc,bdec,binc
#                print 'moment emu: ',rec[el]
                    MagRec["measurement_magn_moment"]='%10.3e'% (float(rec[el])*1e-3) # moment in Am^2 (from emu)
                    MagRec["measurement_magn_volume"]='%10.3e'% (float(rec[el])*1e-3/vol) # magnetization in A/m
                    el=skip(2,el,rec) # skip to xsig
                    MagRec["measurement_sd_x"]='%10.3e'% (float(rec[el])*1e-3) # convert from emu
                    el=skip(3,el,rec) # skip to ysig
                    MagRec["measurement_sd_y"]='%10.3e'% (float(rec[el])*1e-3) # convert from emu
                    el=skip(3,el,rec) # skip to zsig
                    MagRec["measurement_sd_z"]='%10.3e'% (float(rec[el])*1e-3) # convert from emu
                    el+=1 # skip to positions
                    MagRec["measurement_positions"]=rec[el]
#                    el=skip(5,el,rec) # skip to date
#                    mm=str(months.index(date[0]))
#                    if len(mm)==1:
#                        mm='0'+str(mm)
#                    else:
#                        mm=str(mm)
#                    dstring=date[2]+':'+mm+':'+date[1]+":"+date[3]
#                    MagRec['measurement_date']=dstring
                    MagRec["magic_instrument_codes"]=inst
                    MagRec["er_analyst_mail_names"]=""
                    MagRec["er_citation_names"]="This study"
                    MagRec["magic_method_codes"]=meas_type
                    if demag=="AF":
                        MagRec["treatment_ac_field"]='%8.3e' %(float(treat[:-2])*1e-3) # peak field in tesla
                        meas_type="LT-AF-Z"
                        MagRec["treatment_dc_field"]='0'
                    elif demag=="T":
                        MagRec["treatment_temp"]='%8.3e' % (float(treat[:-1])+273.) # temp in kelvin
                        meas_type="LT-T-Z"
                    MagRec['magic_method_codes']=meas_type
                    MagRecs.append(MagRec) 
    MagOuts=pmag.measurements_methods(MagRecs,noave)
    MagOuts, keylist = pmag.fillkeys(MagOuts) 
    pmag.magic_write(meas_file,MagOuts,'magic_measurements')
    print "Measurements put in ",meas_file
    SampsOut,sampkeys=pmag.fillkeys(Samps)
    pmag.magic_write(samp_file,SampsOut,"er_samples")
    Sites=[]
    for samp in Samps:
        SiteRec={}
        SiteRec['er_site_name']=samp['er_site_name']
        SiteRec['er_location_name']=samp['er_location_name']
        SiteRec['site_definition']='s'
        SiteRec['er_citation_names']='This study'
        if 'sample_class' in samp.keys():SiteRec['site_class']=samp['sample_class']
        if 'sample_lithology' in samp.keys():SiteRec['site_lithology']=samp['sample_lithology']
        if 'sample_type' in samp.keys():SiteRec['site_lithology']=samp['sample_lithology']
        if 'sample_lat' in samp.keys():
            SiteRec['site_lat']=samp['sample_lat']
        else:
            SiteRec['site_lat']="-999"
        if 'sample_lon' in samp.keys():
            SiteRec['site_lon']=samp['sample_lon']
        else:
            SiteRec['site_lon']="-999"
        if 'sample_height' in samp.keys():SiteRec['site_height']=samp['sample_height']
        Sites.append(SiteRec)
    pmag.magic_write(site_file,Sites,'er_sites')
    return True, meas_file
Exemplo n.º 14
0
def main():
    """
    NAME
        FIN_magic.py
 
    DESCRIPTION
        converts FINNISH format files to magic_measurements format files

    SYNTAX
        FIN_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -usr USER:   identify user, default is ""
        -f FILE: specify index file with list of files for importing [default is index.txt]
        -F FILE: specify output  measurements file, default is magic_measurements.txt
        -Fsp FILE: specify output er_specimens.txt file, default is er_specimens.txt
        -Fsi FILE: specify output er_sites.txt file, default is er_sites.txt
        -n [gm,kg,cc,m3]: specify normalization
        -spc NUM : specify number of characters to designate a  specimen, default = 1
        -ncn NCON: specify naming convention [default is #2 below]
        -loc LOCNAME : specify location/study name, must have either LOCNAME or SITEFILE or be a synthetic
        -dc B PHI THETA: dc lab field (in micro tesla) and phi,theta, default is none
              NB: use PHI, THETA = -1 -1 to signal that it changes, i.e. in anisotropy experiment
        -ac B : peak AF field (in mT) for ARM acquisition, default is none

    INPUT
        Best to put separate experiments (all AF, thermal, thellier, trm aquisition, Shaw, etc.) 

    NOTES:
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 
 
    """
#        
#
    norm='cc'
    samp_con,Z='2',1        
    meas_file='magic_measurements.txt'
    spec_file='er_specimens.txt'
    samp_file='er_samples.txt'
    site_file='er_sites.txt'
    magfile='index.txt'
    ErSpecs,ErSamps,ErSites,ErLocs,ErCits=[],[],[],[],[]
    MeasRecs=[]
    specnum,unis,locname=-1,"1","unknown"
    citation="This study"
    dir_path='.'
    args=sys.argv
    labfield,phi,theta="","",""
    if '-WD' in args:
        ind=args.index("-WD")
        dir_path=args[ind+1]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind=args.index("-usr")
        user=args[ind+1]
    if '-F' in args:
        ind=args.index("-F")
        meas_file=args[ind+1]
    if '-Fsp' in args:
        ind=args.index("-Fsp")
        spec_file=args[ind+1]
    if '-Fsa' in args:
        ind=args.index("-Fsa")
        samp_file=args[ind+1]
    if '-loc' in args:
        ind=args.index("-loc")
        locname=args[ind+1]
    if '-spc' in args:
        ind=args.index("-spc")
        specnum=-int(args[ind+1])
    if '-dc' in args:
        ind=args.index("-dc")
        labfield=float(args[ind+1])*1e-6
        phi=args[ind+2]
        theta=args[ind+3]
    if '-n' in args:
        ind=args.index("-n")
        norm=args[ind+1]
    if "-ncn" in args:
        ind=args.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else: 
                Z=samp_con.split("-")[1]
                samp_con="4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="7"
    if '-f' in args:
        ind=args.index("-f")
        magfile=args[ind+1]
    magfile=dir_path+'/'+magfile
    spec_file=dir_path+'/'+spec_file
    samp_file=dir_path+'/'+samp_file
    site_file=dir_path+'/'+site_file
    meas_file=dir_path+'/'+meas_file
    try:
        input=open(magfile,'rU')
    except:
        print "bad sam file name"
        sys.exit()
    Files=input.readlines()
    sids,ln=[],0
    specimens,samples,sites=[],[],[]
    for file in Files:
        Zsteps,Isteps=[],[]
        print 'processing ',file.split()[0]
        data=open(file.split()[0],'rU').readlines()
# parse out header info
        line= data[0]
        k=6
        while k<len(line) and line[k]==' ':k+=1
        inst=line[k:]
        line= data[1]
        rec=line.split(':')
        specimen=rec[1].split()[0].lower()
        if specnum!=0:
            sample=specimen[:specnum]
        else: sample=specimen
        site=pmag.parse_site(sample,samp_con,Z)
        line= data[2]
        rec=line.split(':')
        lithology=rec[1]
        line=data[7]
        rec=line.split() 
        site_lat=rec[0]
        site_lon=rec[1]
#        sample_azimuth=(float(rec[2])-90.)
#        if sample_azimuth<0:sample_azimuth+=360.
##        sample_dip=(90.-float(rec[3]))
        dip=float(rec[5])
        if dip!=0:
            dip_direction=(float(rec[4])-90.)
        else:
            dip_direction=0
        if dip_direction<0:dip_direction+=360.
        sample_azimuth=0
        sample_dip=0 
## the data are in geographic coordinates already
        vol=float(rec[6])
        weight=float(rec[7])
        line= data[8]
        treat_type=line[:2]
        ErSpecRec,ErSampRec,ErSiteRec={},{},{}
        ErSpecRec['er_specimen_name']=specimen
        ErSpecRec['er_sample_name']=sample
        ErSpecRec['er_site_name']=site
        ErSpecRec['er_location_name']=locname
        ErSpecRec['er_citation_name']=citation
        ErSampRec['er_sample_name']=sample
        ErSampRec['er_site_name']=site
        ErSampRec['er_location_name']=locname
        ErSampRec['er_citation_name']=citation
        ErSiteRec['sample_lat']=site_lat
        ErSiteRec['sample_lon']=site_lon
        ErSiteRec['er_site_name']=site
        ErSiteRec['er_location_name']=locname
        ErSiteRec['er_citation_name']=citation
        ErSiteRec['site_lat']=site_lat
        ErSiteRec['site_lon']=site_lon
        if weight!=0:
            ErSpecRec['specimen_weight']='%10.3e'%(weight*1e-3) # convert to kg
        else: 
            ErSpecRec['specimen_weight']=""
        if vol!=0:
            if norm=='cc':units="1"
            if norm=='m3':units="2"
            if units=="1" or "":
                ErSpecRec['specimen_volume']='%10.3e'%(vol*1e-6)
            else: 
                ErSpecRec['specimen_volume']='%10.3e'%(vol)
        else:
            ErSpecRec['specimen_volume']=""
        ErSampRec['sample_azimuth']='%7.1f'%(sample_azimuth)
        ErSampRec['sample_dip']='%7.1f'%(sample_dip)
        ErSampRec['sample_bed_dip']='%7.1f'%(dip)
        ErSampRec['sample_bed_dip_direction']='%7.1f'%(dip_direction)
        ErSampRec['sample_class']=''
        ErSampRec['sample_type']=''
        ErSampRec['sample_lithology']=lithology
        ErSampRec['magic_method_codes']="SO-CMD-NORTH"
        lastrec=data[-1]
        while len(lastrec.split())<2: # stripping off blanks at end
            del data[-1]
            lastrec=data[-1]
        for line in data[9:]:
            MeasRec=ErSpecRec.copy()
            MeasRec['measurement_standard']='u'
            MeasRec['measurement_temp']='273'
            rec=line.split()
            if len(rec)==1:
                rec=line.split('\t')
            treat=rec[0].strip()
            if treat=="0":
                MeasRec['magic_method_codes']='LT-NO'
                MeasRec['treatment_temp']='273'
                MeasRec['treatment_dc_field']='0'
                MeasRec['treatment_dc_field_phi']=''
                MeasRec['treatment_dc_field_theta']=''
                MeasRec['treatment_ac_field']='0'
            else:
                if treat_type.strip()=='AF':
                    MeasRec['magic_method_codes']='LT-AF-Z'
                    MeasRec['treatment_temp']='273'
                    MeasRec['treatment_dc_field']='0'
                    MeasRec['treatment_dc_field_phi']=''
                    MeasRec['treatment_dc_field_theta']=''
                    MeasRec['treatment_ac_field']='%10.3e'%(float(treat)*1e-4) # convert from Oe
                elif treat_type.strip()=='TH':
                    if labfield=="":
                        MeasRec['magic_method_codes']='LT-T-Z'
                        MeasRec['treatment_temp']='%7.1f'%(float(treat)+273)
                        MeasRec['treatment_dc_field']='0'
                        MeasRec['treatment_dc_field_phi']=''
                        MeasRec['treatment_dc_field_theta']=''
                        MeasRec['treatment_ac_field']='0'
                    else:
                        if treat not in Zsteps:
                            print 'first Z: ',treat
                            Zsteps.append(treat)
                            MeasRec['magic_method_codes']='LT-T-Z'
                            MeasRec['treatment_temp']='%7.1f'%(float(treat)+273)
                            MeasRec['treatment_dc_field']='0'
                            MeasRec['treatment_dc_field_phi']=''
                            MeasRec['treatment_dc_field_theta']=''
                            MeasRec['treatment_ac_field']='0'
                        elif treat not in Isteps:
                            print 'first I: ',treat
                            Isteps.append(treat)
                            MeasRec['magic_method_codes']='LT-T-I'
                            MeasRec['treatment_temp']='%7.1f'%(float(treat)+273)
                            MeasRec['treatment_dc_field']='%10.3e'%(labfield)
                            MeasRec['treatment_dc_field_phi']=phi
                            MeasRec['treatment_dc_field_theta']=theta
                            MeasRec['treatment_ac_field']='0'
                        elif treat in Isteps:
                            if float(treat)<float(Zsteps[-1]):
                                print 'pTRM ',treat
                                MeasRec['magic_method_codes']='LT-PTRM-Z'
                                MeasRec['treatment_temp']='%7.1f'%(float(treat)+273)
                                MeasRec['treatment_dc_field']=''
                                MeasRec['treatment_dc_field_phi']=''
                                MeasRec['treatment_dc_field_theta']=''
                                MeasRec['treatment_ac_field']='0'
                            else:
                                print 'pTRM tail ',treat
                                MeasRec['magic_method_codes']='LT-PTRM-MD'
                                MeasRec['treatment_temp']='%7.1f'%(float(treat)+273)
                                MeasRec['treatment_dc_field']=''
                                MeasRec['treatment_dc_field_phi']=''
                                MeasRec['treatment_dc_field_theta']=''
                                MeasRec['treatment_ac_field']='0'
            MeasRec['measurement_dec']=rec[1]
            MeasRec['measurement_inc']=rec[2]
            intens='%8.2e'%(float(rec[3])*1e-3) # convert to A/m 
            MeasRec['measurement_magn_volume']=intens
            MeasRec['measurement_csd']='%7.1f'%(eval(rec[5]))
            MeasRec['magic_instrument_codes']=inst
            MeasRecs.append(MeasRec)
        ErSpecs.append(ErSpecRec)
        if sample not in samples:
            samples.append(sample)
            ErSamps.append(ErSampRec)
        if site not in sites:
            sites.append(site)
            ErSites.append(ErSiteRec)
    pmag.magic_write(spec_file,ErSpecs,'er_specimens')
    print 'specimens stored in ',spec_file
    pmag.magic_write(samp_file,ErSamps,'er_samples')
    print 'samples stored in ',samp_file
    pmag.magic_write(site_file,ErSites,'er_sites')
    Fixed=pmag.measurements_methods(MeasRecs,1)
    pmag.magic_write(meas_file,Fixed,'magic_measurements')
    print 'data stored in ',meas_file
Exemplo n.º 15
0
def main():
    """
    NAME
        2G_bin_magic.py
   
    DESCRIPTION
        takes the binary 2G format magnetometer files and converts them to magic_measurements, er_samples.txt and er_sites.txt file
 
    SYNTAX
        2G_magic.py [command line options]

    OPTIONS
        -f FILE: specify input 2G (binary) file
        -F FILE: specify magic_measurements output file, default is: magic_measurements.txt
        -Fsa FILE: specify output file, default is: er_samples.txt 
        -Fsi FILE: specify output file, default is: er_sies.txt 
        -ncn NCON:  specify naming convention: default is #2 below
        -ocn OCON:  specify orientation convention, default is #5 below
        -mcd: specify sampling method codes as a colon delimited string:  [default is: FS-FD:SO-POM]
             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
             SO-SUN   orientation with sun compass
        -loc: location name, default="unknown"
        -spc NUM : specify number of characters to designate a  specimen, default = 0     
        -ins INST : specify instsrument name
        -a: average replicate measurements

    INPUT FORMAT
        Input files are horrible mag binary format (who knows why?)
        Orientation convention:
            [1] Lab arrow azimuth= mag_azimuth; Lab arrow dip=-field_dip
                i.e., field_dip is degrees from vertical down - the hade [default]
            [2] Lab arrow azimuth = mag_azimuth-90; Lab arrow dip = -field_dip
                i.e., mag_azimuth is strike and field_dip is hade
            [3] Lab arrow azimuth = mag_azimuth; Lab arrow dip = 90-field_dip
                i.e.,  lab arrow same as field arrow, but field_dip was a hade.
            [4] lab azimuth and dip are same as mag_azimuth, field_dip
            [5] 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] all others you will have to either customize your 
                self or e-mail [email protected] for help.  
 
         Magnetic declination convention:
             Az will use supplied declination to correct azimuth 
    
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 

    OUTPUT
            output saved in magic_measurements.txt & er_samples.txt formatted files
              will overwrite any existing files 
    """
    #
    # initialize variables
    #
    specnum = 0
    ub_file, samp_file, or_con, corr, meas_file = "", "er_samples.txt", "3", "1", "magic_measurements.txt"
    pos_file, site_file = "", "er_sites.txt"
    noave = 1
    args = sys.argv
    bed_dip, bed_dip_dir = "", ""
    samp_con, Z, average_bedding = "2", 1, "0"
    meths = "FS-FD"
    sclass, lithology, type = "", "", ""
    user, inst = "", ""
    DecCorr = 0.0
    location_name = "unknown"
    months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    gmeths = ""
    #
    #
    dir_path = "."
    if "-WD" in args:
        ind = args.index("-WD")
        dir_path = sys.argv[ind + 1]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-f" in args:
        ind = args.index("-f")
        mag_file = sys.argv[ind + 1]
    if "-fpos" in args:
        ind = args.index("-fpos")
        pos_file = sys.argv[ind + 1]
    if "-F" in args:
        ind = args.index("-F")
        meas_file = sys.argv[ind + 1]
    if "-Fsa" in args:
        ind = args.index("-Fsa")
        samp_file = sys.argv[ind + 1]
    if "-Fsi" in args:
        ind = args.index("-Fsi")
        site_file = sys.argv[ind + 1]
    if "-ocn" in args:
        ind = args.index("-ocn")
        or_con = sys.argv[ind + 1]
    if "-ncn" in args:
        ind = args.index("-ncn")
        samp_con = sys.argv[ind + 1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z = samp_con.split("-")[1]
                samp_con = "4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z = samp_con.split("-")[1]
                samp_con = "7"
        if "6" in samp_con:
            try:
                Samps, file_type = pmag.magic_read(dir_path + "/er_samples.txt")
            except:
                print "there is no er_samples.txt file available - you can't use naming convention #6"
                sys.exit()
    if "-mcd" in args:
        ind = args.index("-mcd")
        gmeths = sys.argv[ind + 1]
    if "-loc" in args:
        ind = args.index("-loc")
        location_name = sys.argv[ind + 1]
    if "-spc" in args:
        ind = args.index("-spc")
        specnum = int(args[ind + 1])
        if specnum != 0:
            specnum = -specnum
    if "-ins" in args:
        ind = args.index("-ins")
        inst = args[ind + 1]
    if "-a" in args:
        noave = 0
    #
    #
    mag_file = dir_path + "/" + mag_file
    samp_file = dir_path + "/" + samp_file
    site_file = dir_path + "/" + site_file
    meas_file = dir_path + "/" + meas_file
    samplist = []
    try:
        Samps, file_type = pmag.magic_read(samp_file)
        for samp in Samps:
            if samp["er_sample_name"] not in samplist:
                samplist.append(samp["er_sample_name"])
    except:
        Samps = []
    MagRecs = []
    f = open(mag_file, "rU")
    input = f.read()
    f.close()
    firstline, date = 1, ""
    d = input.split("\xcd")
    for line in d:
        rec = line.split("\x00")
        if firstline == 1:
            firstline = 0
            spec, vol = "", 1
            for c in line[15:23]:
                if c != "\x00":
                    spec = spec + c
            # check for bad sample name
            test = spec.split(".")
            date = ""
            if len(test) > 1:
                spec = test[0]
                kk = 24
                while line[kk] != "\x01" and line[kk] != "\x00":
                    kk += 1
                vcc = line[24:kk]
                el = 10
                while rec[el].strip() != "":
                    el += 1
                date, comments = rec[el + 7], []
            else:
                el = 9
                while rec[el] != "\x01":
                    el += 1
                vcc, date, comments = rec[el - 3], rec[el + 7], []
            specname = spec.lower()
            print "importing ", specname
            el += 8
            while rec[el].isdigit() == False:
                comments.append(rec[el])
                el += 1
            while rec[el] == "":
                el += 1
            az = float(rec[el])
            el += 1
            while rec[el] == "":
                el += 1
            pl = float(rec[el])
            el += 1
            while rec[el] == "":
                el += 1
            bed_dip_dir = float(rec[el])
            el += 1
            while rec[el] == "":
                el += 1
            bed_dip = float(rec[el])
            el += 1
            while rec[el] == "":
                el += 1
            if rec[el] == "\x01":
                bed_dip = 180.0 - bed_dip
                el += 1
                while rec[el] == "":
                    el += 1
            fold_az = float(rec[el])
            el += 1
            while rec[el] == "":
                el += 1
            fold_pl = rec[el]
            el += 1
            while rec[el] == "":
                el += 1
            if rec[el] != "" and rec[el] != "\x02" and rec[el] != "\x01":
                deccorr = float(rec[el])
                az += deccorr
                bed_dip_dir += deccorr
                fold_az += deccorr
                if bed_dip_dir >= 360:
                    bed_dip_dir = bed_dip_dir - 360.0
                if az >= 360.0:
                    az = az - 360.0
                if fold_az >= 360.0:
                    fold_az = fold_az - 360.0
            else:
                deccorr = 0
            if specnum != 0:
                sample = specname[:specnum]
            else:
                sample = specname
            SampRec = {}
            SampRec["er_sample_name"] = sample
            SampRec["er_location_name"] = location_name
            SampRec["er_citation_names"] = "This study"
            labaz, labdip = pmag.orient(az, pl, or_con)  # convert to labaz, labpl
            #
            # parse information common to all orientation methods
            #
            SampRec["sample_bed_dip"] = "%7.1f" % (bed_dip)
            SampRec["sample_bed_dip_direction"] = "%7.1f" % (bed_dip_dir)
            SampRec["sample_dip"] = "%7.1f" % (labdip)
            SampRec["sample_azimuth"] = "%7.1f" % (labaz)
            if vcc.strip() != "":
                vol = float(vcc) * 1e-6  # convert to m^3 from cc
            SampRec["sample_volume"] = "%10.3e" % (vol)  #
            SampRec["sample_class"] = sclass
            SampRec["sample_lithology"] = lithology
            SampRec["sample_type"] = type
            SampRec["sample_declination_correction"] = "%7.1f" % (deccorr)
            methods = gmeths.split(":")
            if deccorr != "0":
                if "SO-MAG" in methods:
                    del methods[methods.index("SO-MAG")]
                methods.append("SO-CMD-NORTH")
            meths = ""
            for meth in methods:
                meths = meths + meth + ":"
            meths = meths[:-1]
            SampRec["magic_method_codes"] = meths
            if int(samp_con) < 6:
                site = pmag.parse_site(SampRec["er_sample_name"], samp_con, Z)  # parse out the site name
                SampRec["er_site_name"] = site
            elif len(Samps) > 1:
                site, location = "", ""
                for samp in Samps:
                    if samp["er_sample_name"] == SampRec["er_sample_name"]:
                        site = samp["er_site_name"]
                        location = samp["er_location_name"]
                        break
                SampRec["er_location_name"] = samp["er_location_name"]
                SampRec["er_site_name"] = samp["er_site_name"]
            if sample not in samplist:
                samplist.append(sample)
                Samps.append(SampRec)
        else:
            MagRec = {}
            MagRec["treatment_temp"] = "%8.3e" % (273)  # room temp in kelvin
            MagRec["measurement_temp"] = "%8.3e" % (273)  # room temp in kelvin
            MagRec["treatment_ac_field"] = "0"
            MagRec["treatment_dc_field"] = "0"
            MagRec["treatment_dc_field_phi"] = "0"
            MagRec["treatment_dc_field_theta"] = "0"
            meas_type = "LT-NO"
            MagRec["measurement_flag"] = "g"
            MagRec["measurement_standard"] = "u"
            MagRec["measurement_number"] = "1"
            MagRec["er_specimen_name"] = specname
            MagRec["er_sample_name"] = SampRec["er_sample_name"]
            MagRec["er_site_name"] = SampRec["er_site_name"]
            MagRec["er_location_name"] = location_name
            el, demag = 1, ""
            treat = rec[el]
            if treat[-1] == "C":
                demag = "T"
            elif treat != "NRM":
                demag = "AF"
            el += 1
            while rec[el] == "":
                el += 1
            MagRec["measurement_dec"] = rec[el]
            cdec = float(rec[el])
            el += 1
            while rec[el] == "":
                el += 1
            MagRec["measurement_inc"] = rec[el]
            cinc = float(rec[el])
            el += 1
            while rec[el] == "":
                el += 1
            gdec = rec[el]
            el += 1
            while rec[el] == "":
                el += 1
            ginc = rec[el]
            el = skip(2, el, rec)  # skip bdec,binc
            #                el=skip(4,el,rec) # skip gdec,ginc,bdec,binc
            #                print 'moment emu: ',rec[el]
            MagRec["measurement_magn_moment"] = "%10.3e" % (float(rec[el]) * 1e-3)  # moment in Am^2 (from emu)
            MagRec["measurement_magn_volume"] = "%10.3e" % (float(rec[el]) * 1e-3 / vol)  # magnetization in A/m
            el = skip(2, el, rec)  # skip to xsig
            MagRec["measurement_sd_x"] = "%10.3e" % (float(rec[el]) * 1e-3)  # convert from emu
            el = skip(3, el, rec)  # skip to ysig
            MagRec["measurement_sd_y"] = "%10.3e" % (float(rec[el]) * 1e-3)  # convert from emu
            el = skip(3, el, rec)  # skip to zsig
            MagRec["measurement_sd_z"] = "%10.3e" % (float(rec[el]) * 1e-3)  # convert from emu
            el += 1  # skip to positions
            MagRec["measurement_positions"] = rec[el]
            #                    el=skip(5,el,rec) # skip to date
            #                    mm=str(months.index(date[0]))
            #                    if len(mm)==1:
            #                        mm='0'+str(mm)
            #                    else:
            #                        mm=str(mm)
            #                    dstring=date[2]+':'+mm+':'+date[1]+":"+date[3]
            #                    MagRec['measurement_date']=dstring
            MagRec["magic_instrument_codes"] = inst
            MagRec["er_analyst_mail_names"] = ""
            MagRec["er_citation_names"] = "This study"
            MagRec["magic_method_codes"] = meas_type
            if demag == "AF":
                MagRec["treatment_ac_field"] = "%8.3e" % (float(treat[:-2]) * 1e-3)  # peak field in tesla
                meas_type = "LT-AF-Z"
                MagRec["treatment_dc_field"] = "0"
            elif demag == "T":
                MagRec["treatment_temp"] = "%8.3e" % (float(treat[:-1]) + 273.0)  # temp in kelvin
                meas_type = "LT-T-Z"
            MagRec["magic_method_codes"] = meas_type
            MagRecs.append(MagRec)
    MagOuts = pmag.measurements_methods(MagRecs, noave)
    pmag.magic_write(meas_file, MagOuts, "magic_measurements")
    print "Measurements put in ", meas_file
    SampsOut, sampkeys = pmag.fillkeys(Samps)
    pmag.magic_write(samp_file, SampsOut, "er_samples")
    Sites = []
    for samp in Samps:
        SiteRec = {}
        SiteRec["er_site_name"] = samp["er_site_name"]
        SiteRec["er_location_name"] = samp["er_location_name"]
        SiteRec["site_definition"] = "s"
        SiteRec["er_citation_names"] = "This study"
        if "sample_class" in samp.keys():
            SiteRec["site_class"] = samp["sample_class"]
        if "sample_lithology" in samp.keys():
            SiteRec["site_lithology"] = samp["sample_lithology"]
        if "sample_type" in samp.keys():
            SiteRec["site_lithology"] = samp["sample_lithology"]
        if "sample_lat" in samp.keys():
            SiteRec["site_lat"] = samp["sample_lat"]
        else:
            SiteRec["site_lat"] = "-999"
        if "sample_lon" in samp.keys():
            SiteRec["site_lon"] = samp["sample_lon"]
        else:
            SiteRec["site_lon"] = "-999"
        if "sample_height" in samp.keys():
            SiteRec["site_height"] = samp["sample_height"]
        Sites.append(SiteRec)
    pmag.magic_write(site_file, Sites, "er_sites")
Exemplo n.º 16
0
def main():
    """
    NAME
        UU_magic.py
   
    DESCRIPTION
        takes Fort Hoofddijk (University of Utrecht) format magnetometer files and converts them to magic_measurements and er_samples.txt
 
    SYNTAX
        UU_magic.py [command line options]

    OPTIONS
        -f FILE: specify input file
        -fpos FILE: specify stratigraphic position  file (.saf format)
        -F FILE: specify magic_measurements output file, default is: magic_measurements.txt
        -Fsa FILE: specify output file, default is: er_samples.txt 
        -ncn NCON:  specify naming convention: default is #1 below
        -ocn OCON:  specify orientation convention, default is #1 below
        -mcd: specify sampling method codes as a colon delimited string:  [default is: FS-FD:SO-POM]
             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
             SO-SUN   orientation with sun compass
        -loc: location name, default="unknown"
        -spc NUM : specify number of characters to designate a  specimen, default = 0     
        -ins INST : specify instsrument name

    INPUT FORMAT
        Input files must be colon delimited:
            "file_name", "instrument"
            "specimen name","",az,pl,vol(cc),strike,dip
            treatment,X,Y,Z,CSD,"yy-mm-dd","hh:mm"
        Orientation convention:
            [1] Lab arrow azimuth= mag_azimuth; Lab arrow dip=-dip
                i.e., dip is degrees from vertical down - the hade [default]
            [2] Lab arrow azimuth = mag_azimuth-90; Lab arrow dip = -dip                
                i.e., mag_azimuth is strike and dip is hade
            [3] Lab arrow azimuth = mag_azimuth; Lab arrow dip = dip-90
                e.g. dip is degrees from horizontal of drill direction            
            [4] Lab arrow azimuth = mag_azimuth; Lab arrow dip = dip
            [5] Lab arrow azimuth = mag_azimuth; Lab arrow dip = 90-dip
            [6] all others you will have to either customize your
                self or e-mail [email protected] for help. 
       
         Magnetic declination convention:
             Az is already corrected in file 
    
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 
    OUTPUT
            output saved in magic_measurements.txt & er_samples.txt formatted files
              will overwrite any existing files 
    """
    #
    # initialize variables
    #
    uu_file,samp_file,or_con,corr,meas_file = "","er_samples.txt","1","1","magic_measurements.txt"
    pos_file=""
    specnum=-1
    args=sys.argv
    bed_dip,bed_dip_dir="",""
    samp_con,Z,average_bedding="1",1,"0"
    meths='FS-FD:SO-POM'
    sclass,lithology,type="","",""
    user,inst="",""
    or_con='1'
    corr=="3"
    DecCorr=0.
    location_name="unknown"
    #
    #
    dir_path='.'
    if '-WD' in args:
        ind=args.index("-WD")
        dir_path=sys.argv[ind+1]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-f" in args:
        ind=args.index("-f")
        uu_file=sys.argv[ind+1]
        d=uu_file.split('.')
        if d[1].upper()=="AF":demag="AF"
        if d[1].upper()=="TH":demag="T"
    if "-fpos" in args:
        ind=args.index("-fpos")
        pos_file=sys.argv[ind+1]
    if "-F" in args:
        ind=args.index("-F")
        meas_file=sys.argv[ind+1]
    if "-Fsa" in args:
        ind=args.index("-Fsa")
        samp_file=sys.argv[ind+1]
    if "-ocn" in args:
        ind=args.index("-ocn")
        or_con=sys.argv[ind+1]
    if "-ncn" in args:
        ind=args.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="7"
    if "-mcd" in args:
        ind=args.index("-mcd")
        meths=(sys.argv[ind+1])
    if "-loc" in args:
        ind=args.index("-loc")
        location_name=(sys.argv[ind+1])
    if "-spc" in args:
        ind=args.index("-spc")
        specnum=-int(args[ind+1])
        if specnum!=0:specnum=-specnum
    if "-ins" in args:
        ind=args.index("-ins")
        inst=args[ind+1]
    #
    #
    uu_file=dir_path+'/'+uu_file
    samp_file=dir_path+'/'+samp_file
    meas_file=dir_path+'/'+meas_file
    if pos_file!="":pos_file=dir_path+'/'+pos_file
    samplist=[]
    try:
        SampOut,file_type=pmag.magic_read(samp_file)
        for rec in SampOut:
            if rec['er_sample_name'] not in samplist: samplist.append(rec['er_sample_name'])
    except:
        SampOut=[]
    PosData=[]
    if pos_file != "":
        p=open(pos_file,'rU')
        PosIn=p.readlines()
        p.close()
        for line in PosIn:
            srec=line.split()[0].split(',')
            Prec={'er_site_name':srec[0],'sample_height':srec[1]}
            PosData.append(Prec)
    infile=open(uu_file,'rU')
    Data=infile.readlines()
    infile.close()
    MagRecs=[]
    header=Data[0].split(',')
    if inst=="":inst=header[1].strip('"')
    if inst=='2G DC':
        inst=="FH-2GDC" # Dc Squid machine at Fort Hoofddijk
    else: 
        inst=""
    newsamp=1
    for k in range(1,len(Data)-1):  # step through file, skipping header  and "END" statement
        line=Data[k].split('\n')[0]
        rec=line.split(',')
        if newsamp==1 and rec[0].lower()!='end':
            newsamp=0
            specname=rec[0].strip('"') # take off quotation marks 
            if specnum!=0:
                sample=specname[:specnum]
            else:
                sample=specname
            site=pmag.parse_site(sample,samp_con,Z) # parse out the site name
            SampRec={}
            SampRec["er_sample_name"]=sample
            SampRec["er_location_name"]=location_name
            SampRec["er_citation_names"]="This study"
            labaz,labdip=pmag.orient(float(rec[2]),float(rec[3]),or_con)
            bed_dip=float(rec[6])
            if bed_dip!=0:
                bed_dip_dir=float(rec[5])+90. # assume dip to right of strike
                if bed_dip_dir>=360:bed_dip_dir=bed_dip_dir-360.
            else: 
                bed_dip_dir=float(rec[5]) 
    
    # parse information common to all orientation methods
    #
            SampRec["sample_bed_dip"]='%7.1f'%(bed_dip)
            SampRec["sample_bed_dip_direction"]='%7.1f'%(bed_dip_dir)
            SampRec["sample_dip"]='%7.1f'%(labdip)
            SampRec["sample_azimuth"]='%7.1f'%(labaz)
            vol=float(rec[4])*1e-6
            SampRec["sample_volume"]='%10.3e'%(vol) # convert cc into m^3
            SampRec["sample_class"]=sclass
            SampRec["sample_lithology"]=lithology
            SampRec["sample_type"]=type
            SampRec["magic_method_codes"]=meths
            SampRec["er_site_name"]=site
#
# find position data
#
            if PosData!=[]:
                    for srec in PosData:
                        if srec['er_site_name']==site:
                            SampRec['sample_height']=srec['sample_height']
                            break
            if sample not in samplist:
                samplist.append(sample)
                SampOut.append(SampRec)
        elif rec[0]=='9999': # end of this specimen
            k=k+1 # move on
            newsamp=1
        elif rec[0].lower()!='end' and rec[0]!="":  # got some data
            line=Data[k].split('\n')[0]
            rec=line.split(',')
            MagRec={}
            MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
            MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
            MagRec["treatment_ac_field"]='0'
            MagRec["treatment_dc_field"]='0'
            MagRec["treatment_dc_field_phi"]='0'
            MagRec["treatment_dc_field_theta"]='0'
            meas_type="LT-NO"
            MagRec["measurement_flag"]='g'
            MagRec["measurement_standard"]='u'
            MagRec["measurement_number"]='1'
            MagRec["er_specimen_name"]=specname
            MagRec["er_sample_name"]=sample
            MagRec["er_site_name"]=site
            MagRec["er_location_name"]=location_name
            MagRec["measurement_csd"]=rec[4]
            cart=[]
            cart.append(-float(rec[2])) # appending x,y,z from data record
            cart.append(float(rec[3]))
            cart.append(-float(rec[1]))
            Dir=pmag.cart2dir(cart)
            MagRec["measurement_magn_volume"]='%10.3e'% (float(Dir[2])*1e-6) # moment in A/m (from 10^-6 A/m)
            MagRec["measurement_magn_moment"]='%10.3e'% (float(Dir[2])*vol*1e-6) # moment in Am^2  
            MagRec["measurement_dec"]='%7.1f'%(Dir[0])
            MagRec["measurement_inc"]='%7.1f'%(Dir[1])
            MagRec["magic_instrument_codes"]=inst
            MagRec["er_analyst_mail_names"]=""
            MagRec["er_citation_names"]="This study"
            MagRec["magic_method_codes"]=meas_type
            if demag=="AF":
                MagRec["treatment_ac_field"]='%8.3e' %(float(rec[0])*1e-3) # peak field in tesla
                meas_type="LT-AF-Z"
                MagRec["treatment_dc_field"]='0'
            elif demag=="T":
                MagRec["treatment_temp"]='%8.3e' % (float(rec[0])+273.) # temp in kelvin
                meas_type="LT-T-Z"
            MagRec['magic_method_codes']=meas_type
#            date=rec[5].strip('"').split('-')
#            time=rec[6].strip('"')
#            if int(date[0])<50:  # assume this century 
#                yyyy='20'+date[0]
#            else:
#                yyyy='19'+date[0] # assume last century
#            dstring=yyyy+':'+date[1]+':'+date[2]+":"+time
#            MagRec['measurement_date']=dstring
            MagRecs.append(MagRec) 
    MagOuts=pmag.measurements_methods(MagRecs,0)
    pmag.magic_write(meas_file,MagOuts,'magic_measurements')
    print "Measurements put in ",meas_file
    pmag.magic_write(samp_file,SampOut,"er_samples")
    print "Sample orientation info  saved in ", samp_file
    print "Good bye"
Exemplo n.º 17
0
def main():
    """
    NAME
        IPG_magic.py
 
    DESCRIPTION
        converts PMD (IPG - PaleoMac)  format files to magic_measurements format files

    SYNTAX
        IPG_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -usr USER:   identify user, default is ""
        -f FILE: specify  input file, or
        -F FILE: specify output file, default is magic_measurements.txt
        -Fsa: specify er_samples format file for appending, default is new er_samples.txt
        -spc NUM : specify number of characters to designate a  specimen, default = 1
        -loc LOCNAME : specify location/study name
        -A: don't average replicate measurements
        -ncn NCON: specify naming convention
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 
 
    INPUT
        IPG-PMD format files
    """
    # initialize some stuff
    noave = 0
    methcode, inst = "", ""
    samp_con, Z = "1", ""
    missing = 1
    demag = "N"
    er_location_name = "unknown"
    citation = "This study"
    args = sys.argv
    methcode = "LP-NO"
    specnum = -1
    MagRecs = []
    version_num = pmag.get_version()
    Samps = []  # keeps track of sample orientations
    DIspec = []
    MagFiles = []
    #
    # get command line arguments
    #
    user = ""
    mag_file = ""
    dir_path = "."
    ErSamps = []
    SampOuts = []
    if "-WD" in sys.argv:
        ind = sys.argv.index("-WD")
        dir_path = sys.argv[ind + 1]
    samp_file = dir_path + "/er_samples.txt"
    meas_file = dir_path + "/magic_measurements.txt"
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind = args.index("-usr")
        user = args[ind + 1]
    if "-F" in args:
        ind = args.index("-F")
        meas_file = dir_path + "/" + args[ind + 1]
    if "-Fsa" in args:
        ind = args.index("-Fsa")
        samp_file = dir_path + "/" + args[ind + 1]
        try:
            open(samp_file, "rU")
            ErSamps, file_type = pmag.magic_read(samp_file)
            print "sample information will be appended to ", samp_file
        except:
            print samp_file, " not found: sample information will be stored in new er_samples.txt file"
            samp_file = dir_path + "/er_samples.txt"
    if "-f" in args:
        ind = args.index("-f")
        mag_file = dir_path + "/" + args[ind + 1]
    if "-spc" in args:
        ind = args.index("-spc")
        specnum = int(args[ind + 1])
        if specnum != 0:
            specnum = -specnum
    if "-ncn" in args:
        ind = args.index("-ncn")
        samp_con = sys.argv[ind + 1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z = samp_con.split("-")[1]
                samp_con = "4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z = samp_con.split("-")[1]
                samp_con = "7"
    if "-loc" in args:
        ind = args.index("-loc")
        er_location_name = args[ind + 1]
    if "-A" in args:
        noave = 1
    data = open(mag_file, "rU").readlines()  # read in data from file
    for line in data:
        rec = line.split()
        if "E-" not in rec[1] and "E+" not in rec[1]:  # new specimen
            er_specimen_name = rec[0]
            ErSampRec, ErSiteRec = {}, {}  # make a  sample record
            if specnum != 0:
                er_sample_name = rec[0][:specnum]
            else:
                er_sample_name = rec[0]
            if len(ErSamps) > 0:  # need to copy existing
                for samp in ErSamps:
                    if samp["er_sample_name"] == er_sample_name:
                        ErSampRec = samp  # we'll ammend this one
                    else:
                        SampOuts.append(samp)  # keep all the others
            if int(samp_con) < 6:
                er_site_name = pmag.parse_site(er_sample_name, samp_con, Z)
            else:
                if "er_site_name" in ErSampRec.keys():
                    er_site_name = ErSampREc["er_site_name"]
                if "er_location_name" in ErSampRec.keys():
                    er_location_name = ErSampREc["er_location_name"]
            ErSampRec["er_sample_name"] = er_sample_name
            ErSampRec["sample_azimuth"] = rec[1]
            dip = -float(rec[2])
            ErSampRec["sample_dip"] = "%7.1f" % (dip)
            ErSampRec["sample_bed_dip_direction"] = "%7.1f" % (float(rec[3]) + 90.0)
            ErSampRec["sample_bed_dip"] = rec[4]
            if "er_location_name" not in ErSampRec.keys():
                ErSampRec["er_location_name"] = er_location_name
            if "er_site_name" not in ErSampRec.keys():
                ErSampRec["er_site_name"] = er_site_name
            if "er_citation_names" not in ErSampRec.keys():
                ErSampRec["er_citation_names"] = "This study"
            if "magic_method_codes" not in ErSampRec.keys():
                ErSampRec["magic_method_codes"] = "SO-NO"
            SampOuts.append(ErSampRec)
        elif rec[0][0] == "N" or rec[0][0] == "T" or rec[0][0] == "M":
            if len(rec) > 1:  # skip blank lines at bottom
                MagRec = {}
                #            MagRec['measurement_date']=measdate
                MagRec["er_citation_names"] = "This study"
                MagRec["er_location_name"] = er_location_name
                MagRec["er_site_name"] = er_site_name
                MagRec["er_sample_name"] = er_sample_name
                MagRec["magic_software_packages"] = version_num
                MagRec["treatment_temp"] = "%8.3e" % (273)  # room temp in kelvin
                MagRec["measurement_temp"] = "%8.3e" % (273)  # room temp in kelvin
                MagRec["measurement_flag"] = "g"
                MagRec["measurement_standard"] = "u"
                MagRec["measurement_number"] = "1"
                MagRec["er_specimen_name"] = er_specimen_name
                if rec[0] == "NRM":
                    meas_type = "LT-NO"
                elif rec[0][0] == "M":
                    meas_type = "LT-AF-Z"
                elif rec[0][0] == "T":
                    meas_type = "LT-T-Z"
                else:
                    print "measurement type unknown"
                    sys.exit()
                X = [float(rec[1]), float(rec[2]), float(rec[3])]
                Vec = pmag.cart2dir(X)
                MagRec["measurement_magn_moment"] = "%10.3e" % (Vec[2])  # Am^2
                #            MagRec["measurement_magn_volume"]=rec[4] # A/m
                MagRec["measurement_dec"] = "%7.1f" % (Vec[0])
                MagRec["measurement_inc"] = "%7.1f" % (Vec[1])
                MagRec["treatment_ac_field"] = "0"
                if meas_type != "LT-NO":
                    treat = float(rec[0][1:])
                else:
                    treat = 0
                if meas_type == "LT-AF-Z":
                    MagRec["treatment_ac_field"] = "%8.3e" % (treat * 1e-3)  # convert from mT to tesla
                elif meas_type == "LT-T-Z":
                    MagRec["treatment_temp"] = "%8.3e" % (treat + 273.0)  # temp in kelvin
                MagRec["magic_method_codes"] = meas_type
                MagRecs.append(MagRec)
    MagOuts = pmag.measurements_methods(MagRecs, noave)
    pmag.magic_write(meas_file, MagOuts, "magic_measurements")
    print "results put in ", meas_file
    pmag.magic_write(samp_file, SampOuts, "er_samples")
    print "sample orientations put in ", samp_file
Exemplo n.º 18
0
def main():
    """
    NAME
        agm_magic.py
    
    DESCRIPTION
        converts Micromag agm files to magic format

    SYNTAX
        agm_magic.py [-h] [command line options]

    OPTIONS
        -usr USER:   identify user, default is "" - put in quotation marks!
        -bak:  this is a IRM backfield curve
        -f FILE, specify input file, required
        -fsa SAMPFILE, specify er_samples.txt file relating samples, site and locations names,default is none
        -F MFILE, specify magic measurements formatted output file, default is agm_measurements.txt
        -spn SPEC, specimen name, default is base of input file name, e.g. SPECNAME.agm
        -spc NUM, specify number of characters to designate a  specimen, default = 0
        -Fsp SPECFILE : name of er_specimens.txt file for appending data to
             [default: er_specimens.txt]
        -ncn NCON,: specify naming convention: default is #1 below
        -syn SYN,  synthetic specimen name
        -loc LOCNAME : specify location/study name, 
             should have either LOCNAME or SAMPFILE (unless synthetic)
        -ins INST : specify which instrument was used (e.g, SIO-Maud), default is ""
        -u units:  [cgs,SI], default is cgs
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            [8] specimen is a synthetic - it has no sample, site, location information
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 
    OUTPUT
        MagIC format files: magic_measurements, er_specimens, er_sample, er_site
    """
    citation='This study'
    MeasRecs=[] 
    units='cgs'
    meth="LP-HYS"
    version_num=pmag.get_version()
    args=sys.argv
    fmt='old'
    er_sample_name,er_site_name,er_location_name="","",""
    inst=""
    er_location_name="unknown"
    er_synthetic_name=""
    user=""
    er_site_name=""
    dir_path='.'
    if "-WD" in args:
        ind=args.index("-WD")
        dir_path=args[ind+1]
    specfile=dir_path+'/er_specimens.txt'
    output=dir_path+"/agm_measurements.txt"
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-bak" in args:
        meth="LP-IRM-DCD"
        output=dir_path+"/irm_measurements.txt"
    if "-new" in args: fmt='new'
    if "-usr" in args:
        ind=args.index("-usr")
        user=args[ind+1]
    if '-F' in args:
        ind=args.index("-F")
        output=dir_path+'/'+args[ind+1]
    if '-f' in args:
        ind=args.index("-f")
        agm_file=dir_path+'/'+args[ind+1]
        er_specimen_name=args[ind+1].split('.')[0]
    else: 
        print "agm_file field is required option"
        print main.__doc__
        sys.exit()
    if '-Fsp' in args:
        ind=args.index("-Fsp")
        specfile=dir_path+'/'+args[ind+1]
    specnum,samp_con,Z=0,'1',1
    if "-spc" in args:
        ind=args.index("-spc")
        specnum=int(args[ind+1])
        if specnum!=0:specnum=-specnum
    if "-spn" in args:
        ind=args.index("-spn")
        er_specimen_name=args[ind+1]
    elif "-syn" not in args:
        print "you must specify a specimen name"
        sys.exit()
    if "-syn" in args:
        ind=args.index("-syn")
        er_synthetic_name=args[ind+1]
        er_specimen_name=""
    if "-loc" in args:
        ind=args.index("-loc")
        er_location_name=args[ind+1]
    if "-fsa" in args:
        ind=args.index("-fsa")
        sampfile=dir_path+'/'+args[ind+1]
        Samps,file_type=pmag.magic_read(sampfile)
        print 'sample_file successfully read in'
    if "-ncn" in args:
        ind=args.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="7"
    if "-ins" in args:
        ind=args.index("-ins")
        inst=args[ind+1]
    if "-u" in args:
        ind=args.index("-u")
        units=args[ind+1]
    ErSpecRecs,filetype=pmag.magic_read(specfile)
    ErSpecRec,MeasRec={},{}
    ErSpecRec['er_citation_names']="This study"
    ErSpecRec['er_specimen_name']=er_specimen_name
    ErSpecRec['er_synthetic_name']=er_synthetic_name
    if specnum!=0:
        ErSpecRec["er_sample_name"]=er_specimen_name[:specnum]
    else:
        ErSpecRec["er_sample_name"]=er_specimen_name
    if "-fsa" in args and er_synthetic_name=="":
        for samp in Samps:
            if samp["er_sample_name"] == ErSpecRec["er_sample_name"]:
                ErSpecRec["er_location_name"]=samp["er_location_name"]
                ErSpecRec["er_site_name"]=samp["er_site_name"]
                break
    elif int(samp_con)!=6 and int(samp_con)!=8:
        site=pmag.parse_site(ErSpecRec['er_sample_name'],samp_con,Z)
        ErSpecRec["er_site_name"]=site
        ErSpecRec["er_location_name"]=er_location_name
    ErSpecRec['er_scientist_mail_names']=user.strip()
    insert=1
    for rec in ErSpecRecs:
        if rec['er_specimen_name']==er_specimen_name:
            insert=0
            break
    if insert==1:
        ErSpecRecs.append(ErSpecRec)
        ErSpecRecs,keylist=pmag.fillkeys(ErSpecRecs)
        pmag.magic_write(specfile,ErSpecRecs,'er_specimens')
        print "specimen name put in ",specfile
    f=open(agm_file,'rU')
    Data=f.readlines()
    if "ASCII" not in Data[0]:fmt='new'
    measnum,start=1,""
    if fmt=='new': # new Micromag formatted file
        end=2
        for skip in range(len(Data)):
            line=Data[skip]
            rec=line.split()
            if 'Units' in line:units=rec[-1]
            if "Raw" in rec:
                start=skip+2
            if "Field" in rec and "Moment" in rec and start=="":
                start=skip+2
                break
    else:
        start = 2
        end=1
    for i in range(start,len(Data)-end): # skip header stuff

        MeasRec={}
        for key in ErSpecRec.keys():
            MeasRec[key]=ErSpecRec[key]
        MeasRec['magic_instrument_codes']=inst
        MeasRec['magic_method_codes']=meth
        if 'er_synthetic_name' in MeasRec.keys() and MeasRec['er_synthetic_name']!="":
            MeasRec['magic_experiment_name']=er_synthetic_name+':'+meth
        else:
            MeasRec['magic_experiment_name']=er_specimen_name+':'+meth
        line=Data[i]
        rec=line.split(',') # data comma delimited
        if rec[0]!='\n':
            if units=='cgs':
                field =float(rec[0])*1e-4 # convert from oe to tesla
            else:
                field =float(rec[0]) # field in tesla
            if meth=="LP-HYS":
                MeasRec['measurement_lab_field_dc']='%10.3e'%(field) 
                MeasRec['treatment_dc_field']=''
            else:
                MeasRec['measurement_lab_field_dc']=''
                MeasRec['treatment_dc_field']='%10.3e'%(field) 
            if units=='cgs':
                MeasRec['measurement_magn_moment']='%10.3e'%(float(rec[1])*1e-3) # convert from emu to Am^2
            else:
                MeasRec['measurement_magn_moment']='%10.3e'%(float(rec[1])) # Am^2
            MeasRec['treatment_temp']='273' # temp in kelvin
            MeasRec['measurement_temp']='273' # temp in kelvin
            MeasRec['measurement_flag']='g'
            MeasRec['measurement_standard']='u'
            MeasRec['measurement_number']='%i'%(measnum)
            measnum+=1
            MeasRec['magic_software_packages']=version_num
            MeasRecs.append(MeasRec) 
# now we have to relabel LP-HYS method codes.  initial loop is LP-IMT, minor loops are LP-M  - do this in measurements_methods function
    if meth=='LP-HYS':   
        recnum=0
        while float(MeasRecs[recnum]['measurement_lab_field_dc'])<float(MeasRecs[recnum+1]['measurement_lab_field_dc']) and recnum+1<len(MeasRecs): # this is LP-IMAG
            MeasRecs[recnum]['magic_method_codes']='LP-IMAG'
            MeasRecs[recnum]['magic_experiment_name']=MeasRecs[recnum]['er_specimen_name']+":"+'LP-IMAG'
            recnum+=1
# 
    pmag.magic_write(output,MeasRecs,'magic_measurements')
    print "results put in ",output
Exemplo n.º 19
0
def main():
    """
    NAME
        UB_magic.py
   
    DESCRIPTION
        takes University of Barcelona format magnetometer files and converts them to magic_measurements and er_samples.txt
 
    SYNTAX
        UB_magic.py [command line options]

    OPTIONS
        -f FILE: specify master txt file
        -fpos FILE: specify stratigraphic position  file (.saf format)
        -F FILE: specify magic_measurements output file, default is: magic_measurements.txt
        -Fsa FILE: specify output file, default is: er_samples.txt 
        -ncn NCON:  specify naming convention: default is #2 below
        -ocn OCON:  specify orientation convention, default is #5 below
        -mcd: specify sampling method codes as a colon delimited string:  [default is: FS-FD:SO-POM]
             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
             SO-SUN   orientation with sun compass
        -loc: location name, default="unknown"
        -spc NUM : specify number of characters to designate a  specimen, default = 0     
        -ins INST : specify instsrument name
        -a: average replicate measurements

    INPUT FORMAT
        Input files are horrible 2G binary format (who knows why?)
        Orientation convention:
            [1] Lab arrow azimuth= mag_azimuth; Lab arrow dip=-field_dip
                i.e., field_dip is degrees from vertical down - the hade [default]
            [2] Lab arrow azimuth = mag_azimuth-90; Lab arrow dip = -field_dip
                i.e., mag_azimuth is strike and field_dip is hade
            [3] Lab arrow azimuth = mag_azimuth; Lab arrow dip = 90-field_dip
                e.g. field_dip is degrees from horizontal of drill direction
            [4] lab azimuth and dip are same as mag_azimuth, field_dip
            [5] lab azimuth and dip are same as mag_azimuth, field_dip-90
            [6] all others you will have to either customize your 
                self or e-mail [email protected] for help.  
       
         Magnetic declination convention:
             Az will use supplied declination to correct azimuth 
    
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 
    OUTPUT
            output saved in magic_measurements.txt & er_samples.txt formatted files
              will overwrite any existing files 
    """
    #
    # initialize variables
    #
    specnum=0
    ub_file,samp_file,or_con,corr,meas_file = "","er_samples.txt","3","1","magic_measurements.txt"
    pos_file=""
    noave=1
    args=sys.argv
    bed_dip,bed_dip_dir="",""
    samp_con,Z,average_bedding="2",1,"0"
    meths='FS-FD'
    sclass,lithology,type="","",""
    user,inst="",""
    DecCorr=0.
    location_name="unknown"
    months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
    gmeths=""
    #
    #
    dir_path='.'
    if '-WD' in args:
        ind=args.index("-WD")
        dir_path=sys.argv[ind+1]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-f" in args:
        ind=args.index("-f")
        ub_file=sys.argv[ind+1]
    if "-fpos" in args:
        ind=args.index("-fpos")
        pos_file=sys.argv[ind+1]
    if "-F" in args:
        ind=args.index("-F")
        meas_file=sys.argv[ind+1]
    if "-Fsa" in args:
        ind=args.index("-Fsa")
        samp_file=sys.argv[ind+1]
    if "-ocn" in args:
        ind=args.index("-ocn")
        or_con=sys.argv[ind+1]
    if "-ncn" in args:
        ind=args.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="7"
    if "-mcd" in args:
        ind=args.index("-mcd")
        gmeths=(sys.argv[ind+1])
    if "-loc" in args:
        ind=args.index("-loc")
        location_name=(sys.argv[ind+1])
    if "-spc" in args:
        ind=args.index("-spc")
        specnum=int(args[ind+1])
        if specnum!=0:specnum=-specnum
    if "-ins" in args:
        ind=args.index("-ins")
        inst=args[ind+1]
    if "-a" in args:noave=0
    #
    #
    ub_file=dir_path+'/'+ub_file
    if pos_file!="":pos_file=dir_path+'/'+pos_file
    samp_file=dir_path+'/'+samp_file
    meas_file=dir_path+'/'+meas_file
    samplist=[]
    try:
        SampOut,file_type=pmag.magic_read(samp_file)
        for rec in SampOut:
            if samp['er_sample_name'] not in samplist: samplist.append(samp['er_sample_name'])
    except:
        SampOut=[]
    PosData=[]
    if pos_file != "":
        p=open(pos_file,'rU')
        PosIn=p.readlines()
        p.close()
        for line in PosIn:
            srec=line.split()[0].split(',')
            Prec={'er_site_name':srec[0],'sample_height':srec[1]}
            PosData.append(Prec)
    mastfile=open(ub_file,'rU')
    Files=mastfile.readlines()
    mastfile.close()
    MagRecs,SampRecs=[],[]
    for file in Files:
      cfile=file.split()[0]
      if cfile!='end':
        cfile=dir_path+'/'+file.split()[0]+'.dat'
        f=open(cfile,'rU')
        input=f.read()
        f.close()
        firstline=1
        d=input.split('\xcd')
        for line in d:
                rec=line.split('\x00')
                if firstline==1:
                    firstline=0
                    specname,vol="",1
                    for c in line[15:23]:
                        if c!='\x00':specname=specname+c 
                    print 'importing ',specname
                    el=9
                    while rec[el]!='\x01':el+=1
                    vcc,date,comment=rec[el-3],rec[el+7],rec[el+8]
                    el+=10
                    while rec[el]=="":el+=1
                    az=float(rec[el])
                    el+=1
                    while rec[el]=="":el+=1
                    pl=float(rec[el])
                    el+=1
                    while rec[el]=="":el+=1
                    bed_dip_dir=float(rec[el])
                    el+=1
                    while rec[el]=="":el+=1
                    bed_dip=float(rec[el])
                    el+=1
                    while rec[el]=="":el+=1
                    if rec[el]=='\x01': 
                        bed_dip=180.-bed_dip
                        el+=1
                        while rec[el]=="":el+=1
                    fold_az=float(rec[el])
                    el+=1
                    while rec[el]=="":el+=1
                    fold_pl=rec[el]
                    el+=1
                    while rec[el]=="":el+=1
                    if rec[el]!="":
                        deccorr=float(rec[el])
                        az+=deccorr
                        bed_dip_dir+=deccorr
                        fold_az+=deccorr
                        if bed_dip_dir>=360:bed_dip_dir=bed_dip_dir-360.
                        if az>=360.:az=az-360.
                        if fold_az>=360.:fold_az=fold_az-360.
                    else:
                        deccorr=0
                    if specnum!=0:
                        sample=specname[:specnum]
                    else:
                        sample=specname
                    if sample not in samplist:
                        samplist.append(sample)
                        SampRec={}
                        SampRec["er_sample_name"]=sample
                        SampRec["er_location_name"]=location_name
                        SampRec["er_citation_names"]="This study"
                        labaz,labdip=pmag.orient(az,pl,or_con) # convert to labaz, labpl
        #
        # parse information common to all orientation methods
        #
                        SampRec["sample_bed_dip"]='%7.1f'%(bed_dip)
                        SampRec["sample_bed_dip_direction"]='%7.1f'%(bed_dip_dir)
                        SampRec["sample_dip"]='%7.1f'%(labdip)
                        SampRec["sample_azimuth"]='%7.1f'%(labaz)
                        if vcc!="":vol=float(vcc)*1e-6 # convert to m^3 from cc
                        SampRec["sample_volume"]='%10.3e'%(vol) # 
                        SampRec["sample_class"]=sclass
                        SampRec["sample_lithology"]=lithology
                        SampRec["sample_type"]=type
                        SampRec["sample_declination_correction"]='%7.1f'%(deccorr)
                        methods=gmeths.split(':')
                        if deccorr!="0":
                            if 'SO-MAG' in methods:del methods[methods.index('SO-MAG')]
                            methods.append('SO-CMD-NORTH')
                        meths=""
                        for meth in methods:meths=meths+meth+":"
                        meths=meths[:-1]
                        SampRec["magic_method_codes"]=meths
                        site=pmag.parse_site(SampRec["er_sample_name"],samp_con,Z) # parse out the site name
                        SampRec["er_site_name"]=site
    #
    # find position data
    #
                    if PosData!=[]:
                        SampRec['sample_height']=""
                        for srec in PosData:
                            if srec['er_site_name']==site:
                                SampRec['sample_height']=srec['sample_height']
                                break
                    SampOut.append(SampRec)
                else:
                    MagRec={}
                    MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
                    MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
                    MagRec["treatment_ac_field"]='0'
                    MagRec["treatment_dc_field"]='0'
                    MagRec["treatment_dc_field_phi"]='0'
                    MagRec["treatment_dc_field_theta"]='0'
                    meas_type="LT-NO"
                    MagRec["measurement_flag"]='g'
                    MagRec["measurement_standard"]='u'
                    MagRec["measurement_number"]='1'
                    MagRec["er_specimen_name"]=specname
                    MagRec["er_sample_name"]=SampRec['er_sample_name']
                    MagRec["er_site_name"]=SampRec['er_site_name']
                    MagRec["er_location_name"]=location_name
                    el,demag=1,''
                    treat=rec[el]
                    if treat[-1]=='C':
                        demag='T'
                    elif treat!='NRM':
                        demag='AF'  
                    el+=1
                    while rec[el]=="":el+=1
                    MagRec["measurement_dec"]=rec[el]
                    cdec=float(rec[el])
                    el+=1
                    while rec[el]=="":el+=1
                    MagRec["measurement_inc"]=rec[el]
                    cinc=float(rec[el])
                    el+=1
                    while rec[el]=="":el+=1
                    gdec=rec[el]
                    el+=1
                    while rec[el]=="":el+=1
                    ginc=rec[el]
                    el=skip(2,el,rec) # skip bdec,binc
#                    el=skip(4,el,rec) # skip gdec,ginc,bdec,binc
#                    print 'moment emu: ',rec[el]
                    MagRec["measurement_magn_moment"]='%10.3e'% (float(rec[el])*1e-3) # moment in Am^2 (from emu)
                    MagRec["measurement_magn_volume"]='%10.3e'% (float(rec[el])*1e-3/vol) # magnetization in A/m
                    el=skip(2,el,rec) # skip to xsig
                    MagRec["measurement_sd_x"]='%10.3e'% (float(rec[el])*1e-3) # convert from emu
                    el=skip(3,el,rec) # skip to ysig
                    MagRec["measurement_sd_y"]='%10.3e'% (float(rec[el])*1e-3) # convert from emu
                    el=skip(3,el,rec) # skip to zsig
                    MagRec["measurement_sd_z"]='%10.3e'% (float(rec[el])*1e-3) # convert from emu
                    el+=1 # skip to positions
                    MagRec["measurement_positions"]=rec[el]
                    el=skip(5,el,rec) # skip to date
                    date=rec[el].split()
                    mm=str(months.index(date[0]))
                    if len(mm)==1:
                        mm='0'+str(mm)
                    else:
                        mm=str(mm)
                    dstring=date[2]+':'+mm+':'+date[1]+":"+date[3]
                    MagRec['measurement_date']=dstring
                    MagRec["magic_instrument_codes"]=inst
                    MagRec["er_analyst_mail_names"]="unknown"
                    MagRec["er_citation_names"]="This study"
                    MagRec["magic_method_codes"]=meas_type
                    if demag=="AF":
                        MagRec["treatment_ac_field"]='%8.3e' %(float(treat[:-2])*1e-3) # peak field in tesla
                        meas_type="LT-AF-Z"
                        MagRec["treatment_dc_field"]='0'
                    elif demag=="T":
                        MagRec["treatment_temp"]='%8.3e' % (float(treat[:-1])+273.) # temp in kelvin
                        meas_type="LT-T-Z"
                    MagRec['magic_method_codes']=meas_type
                    MagRecs.append(MagRec) 
    MagOuts=pmag.measurements_methods(MagRecs,noave)
    pmag.magic_write(meas_file,MagOuts,'magic_measurements')
    print "Measurements put in ",meas_file
    pmag.magic_write(samp_file,SampOut,"er_samples")
    print "Sample orientation info  saved in ", samp_file
    print "Good bye"
Exemplo n.º 20
0
def main(command_line=True, **kwargs):
    """
    NAME
        JR6_txt_magic.py
 
    DESCRIPTION
        converts JR6 .txt format files to magic_measurements format files

    SYNTAX
        JR6_txt_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -f FILE: specify  input file, or
        -F FILE: specify output file, default is magic_measurements.txt
        -Fsa: specify er_samples format file for appending, default is new er_samples.txt (Not working yet)
        -spc NUM : specify number of characters to designate a  specimen, default = 1
        -loc LOCNAME : specify location/study name
        -A: don't average replicate measurements
        -ncn NCON: specify sample naming convention (6 and 7 not yet implemented)
        -mcd [SO-MAG,SO-SUN,SO-SIGHT...] supply how these samples were oriented
        -v NUM : specify the volume of the sample, default 2.5cm^3.
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 
    INPUT
        JR6 .txt format file
    """
# initialize some stuff
    noave=0
    volume = 2.5 * 1e-6 # default volume is 2.5 cm^3 (2.5 * 1e-6 meters^3)
    inst=""
    samp_con,Z='1',""
    missing=1
    demag="N"
    er_location_name="unknown"
    citation='This study'
    args=sys.argv
    meth_code="LP-NO"
    specnum=-1
    MagRecs=[]
    version_num=pmag.get_version()
    Samps=[] # keeps track of sample orientations

    user=""
    mag_file=""
    dir_path='.'
    ErSamps=[]
    SampOuts=[]

    samp_file = 'er_samples.txt'
    meas_file = 'magic_measurements.txt'


    #
    # get command line arguments
    #
    
    if command_line:
        if '-WD' in sys.argv:
            ind = sys.argv.index('-WD')
            dir_path=sys.argv[ind+1]
        if '-ID' in sys.argv:
            ind = sys.argv.index('-ID')
            input_dir_path = sys.argv[ind+1]
        else:
            input_dir_path = dir_path
        output_dir_path = dir_path
        if "-h" in args:
            print main.__doc__
            return False
        if '-F' in args:
            ind=args.index("-F")
            meas_file = args[ind+1]
        if '-Fsa' in args:
            ind = args.index("-Fsa")
            samp_file = args[ind+1]
            #try:
            #    open(samp_file,'rU')
            #    ErSamps,file_type=pmag.magic_read(samp_file)
            #    print 'sample information will be appended to ', samp_file 
            #except:
            #    print samp_file,' not found: sample information will be stored in new er_samples.txt file'
            #    samp_file = output_dir_path+'/er_samples.txt'
        if '-f' in args:
            ind = args.index("-f")
            mag_file= args[ind+1]
        if "-spc" in args:
            ind = args.index("-spc")
            specnum = int(args[ind+1])
        if "-ncn" in args:
            ind=args.index("-ncn")
            samp_con=sys.argv[ind+1]
        if "-loc" in args:
            ind=args.index("-loc")
            er_location_name=args[ind+1]
        if "-A" in args: noave=1
        if "-mcd" in args: 
            ind=args.index("-mcd")
            meth_code=args[ind+1]
        if "-v" in args: 
            ind=args.index("-v")
            volume=float(args[ind+1]) * 1e-6

    if not command_line:
        dir_path = kwargs.get('dir_path', '.')
        input_dir_path = kwargs.get('input_dir_path', dir_path)
        output_dir_path = dir_path
        meas_file = kwargs.get('meas_file', 'magic_measurements.txt')
        mag_file = kwargs.get('mag_file')
        samp_file = kwargs.get('samp_file', 'er_samples.txt')
        specnum = kwargs.get('specnum', 1)
        samp_con = kwargs.get('samp_con', '1')
        er_location_name = kwargs.get('er_location_name', '')
        noave = kwargs.get('noave', 0) # default (0) means DO average
        meth_code = kwargs.get('meth_code', "LP-NO")
        volume = float(kwargs.get('volume', 0))
        if not volume:
            volume = 2.5 * 1e-6 #default volume is a 2.5 cm cube, translated to meters cubed
        else:
            #convert cm^3 to m^3
            volume *= 1e-6


    # format variables
    mag_file = input_dir_path+"/" + mag_file
    meas_file = output_dir_path+"/" + meas_file
    samp_file = output_dir_path+"/" + samp_file
    if specnum!=0:
        specnum=-specnum
    if "4" in samp_con:
        if "-" not in samp_con:
            print "option [4] must be in form 4-Z where Z is an integer"
            return False, "option [4] must be in form 4-Z where Z is an integer"
        else:
            Z=samp_con.split("-")[1]
            samp_con="4"
    if "7" in samp_con:
        if "-" not in samp_con:
            print "option [7] must be in form 7-Z where Z is an integer"
            return False, "option [7] must be in form 7-Z where Z is an integer"
        else:
            Z=samp_con.split("-")[1]
            samp_con="7"

    ErSampRec,ErSiteRec={},{}

    # parse data
    data=open(mag_file,'rU')
    line=data.readline()
    line=data.readline()
    line=data.readline()
    while line !='':
        parsedLine=line.split()
        sampleName=parsedLine[0]
        demagLevel=parsedLine[2]
        date=parsedLine[3]
        line=data.readline()
        line=data.readline()
        line=data.readline()
        line=data.readline()
        parsedLine=line.split()
        specimenAngleDec=parsedLine[1]
        specimenAngleInc=parsedLine[2]
        while parsedLine[0] != 'MEAN' :
            line=data.readline() 
            parsedLine=line.split()
            if len(parsedLine) == 0:
                parsedLine=["Hello"]
        Mx=parsedLine[1]
        My=parsedLine[2]
        Mz=parsedLine[3]
        line=data.readline() 
        line=data.readline() 
        parsedLine=line.split()
        splitExp = parsedLine[2].split('A')
        intensityVolStr=parsedLine[1] + splitExp[0]
        intensityVol = float(intensityVolStr)

        # check and see if Prec is too big and messes with the parcing.
        precisionStr=''
        if len(parsedLine) == 6:  #normal line
            precisionStr=parsedLine[5][0:-1]
        else:
            precisionStr=parsedLine[4][0:-1]
            
        precisionPer = float(precisionStr)
        precision=intensityVol*precisionPer/100

        while parsedLine[0] != 'SPEC.' :
            line=data.readline() 
            parsedLine=line.split()
            if len(parsedLine) == 0:
                parsedLine=["Hello"]

        specimenDec=parsedLine[2]    
        specimenInc=parsedLine[3]    
        line=data.readline()
        line=data.readline()
        parsedLine=line.split()
        geographicDec=parsedLine[1]
        geographicInc=parsedLine[2]
    
        # Add data to various MagIC data tables.

        er_specimen_name = sampleName

        if specnum!=0: 
            er_sample_name=er_specimen_name[:specnum]
        else:
            er_sample_name=er_specimen_name

        if int(samp_con)<6:
            er_site_name=pmag.parse_site(er_sample_name,samp_con,Z)
        # else:
        #     if 'er_site_name' in ErSampRec.keys():er_site_name=ErSampRec['er_site_name']
        #     if 'er_location_name' in ErSampRec.keys():er_location_name=ErSampRec['er_location_name']

        # check sample list(SampOuts) to see if sample already exists in list before adding new sample info
        sampleFlag=0
        for sampRec in SampOuts:
            if sampRec['er_sample_name'] == er_sample_name:
                sampleFlag=1
                break
        if sampleFlag == 0:
            ErSampRec['er_sample_name']=er_sample_name
            ErSampRec['sample_azimuth']=specimenAngleDec
            sample_dip=str(float(specimenAngleInc)-90.0) #convert to magic orientation
            ErSampRec['sample_dip']=sample_dip
            ErSampRec['magic_method_codes']=meth_code 
            ErSampRec['er_location_name']=er_location_name
            ErSampRec['er_site_name']=er_site_name
            ErSampRec['er_citation_names']='This study'
            SampOuts.append(ErSampRec.copy())

        MagRec={}
        MagRec['measurement_description']='Date: '+date
        MagRec["er_citation_names"]="This study"
        MagRec['er_location_name']=er_location_name
        MagRec['er_site_name']=er_site_name
        MagRec['er_sample_name']=er_sample_name
        MagRec['magic_software_packages']=version_num
        MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
        MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
        MagRec["measurement_flag"]='g'
        MagRec["measurement_standard"]='u'
        MagRec["measurement_number"]='1'
        MagRec["er_specimen_name"]=er_specimen_name
        MagRec["treatment_ac_field"]='0'
        if demagLevel == 'NRM':
            meas_type="LT-NO"
        elif demagLevel[0] == 'A':
            meas_type="LT-AF-Z"
            treat=float(demagLevel[1:])
            MagRec["treatment_ac_field"]='%8.3e' %(treat*1e-3) # convert from mT to tesla
        elif demagLevel[0] == 'T':
            meas_type="LT-T-Z"
            treat=float(demagLevel[1:])
            MagRec["treatment_temp"]='%8.3e' % (treat+273.) # temp in kelvin
        else:
            print "measurement type unknown", demag_level
            return False, "measurement type unknown"

        MagRec["measurement_magn_moment"]=str(intensityVol*volume) # Am^2
        MagRec["measurement_magn_volume"]=intensityVolStr # A/m
        MagRec["measurement_dec"]=specimenDec
        MagRec["measurement_inc"]=specimenInc
        MagRec['magic_method_codes']=meas_type
        MagRecs.append(MagRec.copy())

        #read lines till end of record
        line=data.readline()
        line=data.readline()
        line=data.readline()
        line=data.readline()
        line=data.readline()

        # read all the rest of the special characters. Some data files not consistantly formatted.
        while (len(line) <=3 and line!=''):
            line=data.readline()
            
        #end of data while loop

    MagOuts=pmag.measurements_methods(MagRecs,noave)
    pmag.magic_write(samp_file,SampOuts,'er_samples') 
    print "sample orientations put in ",samp_file
    pmag.magic_write(meas_file,MagOuts,'magic_measurements')
    print "results put in ",meas_file
    return True, meas_file
Exemplo n.º 21
0
def main():
    """
    NAME
        HUJI_sample_magic.py
   
    DESCRIPTION
        takes tab delimited Hebrew University sample file and converts to MagIC formatted tables
 
    SYNTAX
        HUJI_sample_magic.py [command line options]

    OPTIONS
        -f FILE: specify input file
        -Fsa FILE: specify sample output file, default is: er_samples.txt 
        -Fsi FILE: specify site output file, default is: er_sites.txt 
        -Iso:  import sample orientation info - default is to set sample_az/dip to 0,0
        -ncn NCON:  specify naming convention: default is #1 below
        -mcd: specify sampling method codes as a colon delimited string:  [default is: FS-FD:SO-POM]
             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
        -loc: location name, default="unknown"

    INPUT FORMAT
        Input files must be tab delimited:
            Samp  Az Dip Dip_dir 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 
    
         Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXXYYY:  YYY is sample designation with Z characters from site XXX
            [5] sample = site
            [5] all others you will have to either customize your 
                self or e-mail [email protected] for help.  
    OUTPUT
            output saved in er_samples.txt  will overwrite any existing files 
    """
    #
    # initialize variables
    #
    version_num=pmag.get_version()
    samp_file,or_con,corr = "er_samples.txt","1","1"
    site_file='er_sites.txt'
    args=sys.argv
    date,lat,lon="","",""  # date of sampling, latitude (pos North), longitude (pos East)
    bed_dip,bed_dip_dir="",""
    participantlist=""
    sites=[]   # list of site names
    Lats,Lons=[],[] # list of latitudes and longitudes
    SampRecs,SiteRecs,ImageRecs,imagelist=[],[],[],[]  # lists of Sample records and Site records
    samp_con,Z,average_bedding="1",1,"0"
    newbaseline,newbeddir,newbeddip="","",""
    meths='FS-FD:SO-POM:SO-SUN'
    delta_u="0"
    sclass,lithology,type="","",""
    newclass,newlith,newtype='','',''
    user=""
    or_con='3'
    corr=="3"
    DecCorr=0.
    location_name="unknown"
    ignore=1
    #
    #
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-f" in args:
        ind=args.index("-f")
        orient_file=sys.argv[ind+1]
    else:
        "Must have orientation file name"
        sys.exit() 
    if "-Fsa" in args:
        ind=args.index("-Fsa")
        samp_file=sys.argv[ind+1]
    if "-ncn" in args:
        ind=args.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 3-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
            print samp_con, Z
    if "-mcd" in args:
        ind=args.index("-mcd")
        meths=(sys.argv[ind+1])
    if "-loc" in args:
        ind=args.index("-loc")
        location_name=(sys.argv[ind+1])
    if "-Iso" in args: ignore=0
    #
    # read in file to convert
    #
    azfile=open(orient_file,'rU')
    AzDipDat=azfile.readlines()
    azfile.close()
    SampOut=[]
    SiteOut=[]
    for line in AzDipDat[1:]: 
      orec=line.split()
      if len(orec)>1:
        labaz,labdip=pmag.orient(float(orec[1]),float(orec[2]),or_con)
        bed_dip_dir=(orec[3])
        bed_dip=(orec[4])
        SampRec={}
        SiteRec={}
        SampRec["er_location_name"]=location_name
        SampRec["er_citation_names"]="This study"
        SiteRec["er_location_name"]=location_name
        SiteRec["er_citation_names"]="This study"
        SiteRec["site_class"]=""
        SiteRec["site_lithology"]=""
        SiteRec["site_type"]=""
        SiteRec["site_definition"]="s"
        SiteRec["er_citation_names"]="This study"
    #
    # parse information common to all orientation methods
    #
        SampRec["er_sample_name"]=orec[0]
        SampRec["sample_bed_dip_direction"]=orec[3]
        SampRec["sample_bed_dip"]=orec[4]
        SiteRec["site_bed_dip_direction"]=orec[3]
        SiteRec["site_bed_dip"]=orec[4]
        if ignore==0:
            SampRec["sample_dip"]='%7.1f'%(labdip)
            SampRec["sample_azimuth"]='%7.1f'%(labaz)
        else:
            SampRec["sample_dip"]='0'
            SampRec["sample_azimuth"]='0'
        SampRec["sample_lat"]=orec[5]
        SampRec["sample_lon"]=orec[6]
        SiteRec["site_lat"]=orec[5]
        SiteRec["site_lon"]=orec[6]
        methods=meths.split(":")
        SampRec["magic_method_codes"]=meths
        site=pmag.parse_site(orec[0],samp_con,Z) # parse out the site name
        SampRec["er_site_name"]=site
        SampRec['magic_software_packages']=version_num
        SiteRec["er_site_name"]=site
        SiteRec['magic_software_packages']=version_num
        SampOut.append(SampRec)
        SiteOut.append(SiteRec)
    pmag.magic_write(samp_file,SampOut,"er_samples")
    print "Sample info saved in ", samp_file
    pmag.magic_write(site_file,SiteOut,"er_sites")
    print "Site info saved in ", site_file
Exemplo n.º 22
0
def main(command_line=True, **kwargs):
    """
    NAME
        PMD_magic.py
 
    DESCRIPTION
        converts PMD (Enkin)  format files to magic_measurements format files

    SYNTAX
        PMD_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -f FILE: specify  input file, or
        -F FILE: specify output file, default is magic_measurements.txt
        -Fsa: specify er_samples format file for appending, default is new er_samples.txt
        -spc NUM : specify number of characters to designate a  specimen, default = 1
        -loc LOCNAME : specify location/study name
        -A: don't average replicate measurements
        -ncn NCON: specify naming convention
        -mcd [SO-MAG,SO-SUN,SO-SIGHT...] supply how these samples were oriented
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 
    INPUT
        PMD format files
    """
# initialize some stuff
    noave=0
    inst=""
    samp_con,Z='1',""
    missing=1
    demag="N"
    er_location_name="unknown"
    citation='This study'
    args=sys.argv
    meth_code="LP-NO"
    specnum=-1
    MagRecs=[]
    version_num=pmag.get_version()
    Samps=[] # keeps track of sample orientations
    DIspec=[]
    MagFiles=[]

    user=""
    mag_file=""
    dir_path='.'
    ErSamps=[]
    SampOuts=[]

    samp_file = 'er_samples.txt'
    meas_file = 'magic_measurements.txt'


    #
    # get command line arguments
    #
    
    if command_line:
        if '-WD' in sys.argv:
            ind = sys.argv.index('-WD')
            dir_path=sys.argv[ind+1]
        if '-ID' in sys.argv:
            ind = sys.argv.index('-ID')
            input_dir_path = sys.argv[ind+1]
        else:
            input_dir_path = dir_path
        output_dir_path = dir_path
        if "-h" in args:
            print main.__doc__
            return False
        if '-F' in args:
            ind=args.index("-F")
            meas_file = args[ind+1]
        if '-Fsa' in args:
            ind = args.index("-Fsa")
            samp_file = args[ind+1]
            #try:
            #    open(samp_file,'rU')
            #    ErSamps,file_type=pmag.magic_read(samp_file)
            #    print 'sample information will be appended to ', samp_file 
            #except:
            #    print samp_file,' not found: sample information will be stored in new er_samples.txt file'
            #    samp_file = output_dir_path+'/er_samples.txt'
        if '-f' in args:
            ind = args.index("-f")
            mag_file= args[ind+1]
        if "-spc" in args:
            ind = args.index("-spc")
            specnum = int(args[ind+1])
        if "-ncn" in args:
            ind=args.index("-ncn")
            samp_con=sys.argv[ind+1]
        if "-loc" in args:
            ind=args.index("-loc")
            er_location_name=args[ind+1]
        if "-A" in args: noave=1
        if "-mcd" in args: 
            ind=args.index("-mcd")
            meth_code=args[ind+1]

    if not command_line:
        dir_path = kwargs.get('dir_path', '.')
        input_dir_path = kwargs.get('input_dir_path', dir_path)
        output_dir_path = dir_path
        meas_file = kwargs.get('meas_file', 'magic_measurements.txt')
        mag_file = kwargs.get('mag_file')
        samp_file = kwargs.get('samp_file', 'er_samples.txt')
        specnum = kwargs.get('specnum', 0)
        samp_con = kwargs.get('samp_con', '1')
        er_location_name = kwargs.get('er_location_name', '')
        noave = kwargs.get('noave', 0) # default (0) means DO average
        meth_code = kwargs.get('meth_code', "LP-NO")

    print samp_con
    # format variables
    mag_file = input_dir_path+"/" + mag_file
    meas_file = output_dir_path+"/" + meas_file
    samp_file = output_dir_path+"/" + samp_file
    if specnum!=0:specnum=-specnum
    if "4" in samp_con:
        if "-" not in samp_con:
            print "naming convention option [4] must be in form 4-Z where Z is an integer"
            return False, "naming convention option [4] must be in form 4-Z where Z is an integer"
        else:
            Z=samp_con.split("-")[1]
            samp_con="4"
    if "7" in samp_con:
        if "-" not in samp_con:
            print "option [7] must be in form 7-Z where Z is an integer"
            return False, "naming convention option [7] must be in form 7-Z where Z is an integer"
        else:
            Z=samp_con.split("-")[1]
            samp_con="7"

    # parse data
    data=open(mag_file,'rU').readlines() # read in data from file
    comment=data[0]
    line=data[1].strip()
    line=line.replace("=","= ")  # make finding orientations easier
    rec=line.split() # read in sample orientation, etc.
    er_specimen_name=rec[0]
    ErSampRec,ErSiteRec={},{} # make a  sample record
    if specnum!=0:
        er_sample_name=rec[0][:specnum]
    else:
        er_sample_name=rec[0]
    if len(ErSamps)>0: # need to copy existing
       for samp in ErSamps:
           if samp['er_sample_name']==er_sample_name:
               ErSampRec=samp  # we'll ammend this one
           else:
               SampOuts.append(samp) # keep all the others
    if int(samp_con)<6:
        er_site_name=pmag.parse_site(er_sample_name,samp_con,Z)
    else:
        if 'er_site_name' in ErSampRec.keys():er_site_name=ErSampREc['er_site_name']
        if 'er_location_name' in ErSampRec.keys():er_location_name=ErSampREc['er_location_name']
    az_ind=rec.index('a=')+1
    ErSampRec['er_sample_name']=er_sample_name
    ErSampRec['er_sample_description']=comment
    ErSampRec['sample_azimuth']=rec[az_ind]
    dip_ind=rec.index('b=')+1
    dip=-float(rec[dip_ind])
    ErSampRec['sample_dip']='%7.1f'%(dip)
    strike_ind=rec.index('s=')+1
    ErSampRec['sample_bed_dip_direction']='%7.1f'%(float(rec[strike_ind])+90.)
    bd_ind=rec.index('d=')+1
    ErSampRec['sample_bed_dip']=rec[bd_ind]
    v_ind=rec.index('v=')+1
    vol=rec[v_ind][:-3]
    date=rec[-2]
    time=rec[-1]
    ErSampRec['magic_method_codes']=meth_code
    if 'er_location_name' not in ErSampRec.keys():ErSampRec['er_location_name']=er_location_name
    if 'er_site_name' not in ErSampRec.keys():ErSampRec['er_site_name']=er_site_name
    if 'er_citation_names' not in ErSampRec.keys():ErSampRec['er_citation_names']='This study'
    if 'magic_method_codes' not in ErSampRec.keys():ErSampRec['magic_method_codes']='SO-NO'
    SampOuts.append(ErSampRec)
    for k in range(3,len(data)): # read in data
      line=data[k]
      rec=line.split()
      if len(rec)>1: # skip blank lines at bottom  
        MagRec={}
        MagRec['measurement_description']='Date: '+date+' '+time
        MagRec["er_citation_names"]="This study"
        MagRec['er_location_name']=er_location_name
        MagRec['er_site_name']=er_site_name
        MagRec['er_sample_name']=er_sample_name
        MagRec['magic_software_packages']=version_num
        MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
        MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
        MagRec["measurement_flag"]='g'
        MagRec["measurement_standard"]='u'
        MagRec["measurement_number"]='1'
        MagRec["er_specimen_name"]=er_specimen_name
        if rec[0]=='NRM': 
            meas_type="LT-NO"
        elif rec[0][0]=='M' or rec[0][0]=='H': 
            meas_type="LT-AF-Z"
        elif rec[0][0]=='T': 
            meas_type="LT-T-Z"
        else:
            print "measurement type unknown"
            return False, "measurement type unknown"
        X=[float(rec[1]),float(rec[2]),float(rec[3])]
        Vec=pmag.cart2dir(X)
        MagRec["measurement_magn_moment"]='%10.3e'% (Vec[2]) # Am^2 
        MagRec["measurement_magn_volume"]=rec[4] # A/m 
        MagRec["measurement_dec"]='%7.1f'%(Vec[0])
        MagRec["measurement_inc"]='%7.1f'%(Vec[1])
        MagRec["treatment_ac_field"]='0'
        if meas_type!='LT-NO':
            treat=float(rec[0][1:])
        else:
            treat=0
        if meas_type=="LT-AF-Z":
            MagRec["treatment_ac_field"]='%8.3e' %(treat*1e-3) # convert from mT to tesla
        elif meas_type=="LT-T-Z":
            MagRec["treatment_temp"]='%8.3e' % (treat+273.) # temp in kelvin
        MagRec['magic_method_codes']=meas_type
        MagRecs.append(MagRec) 
    MagOuts=pmag.measurements_methods(MagRecs,noave)
    pmag.magic_write(meas_file,MagOuts,'magic_measurements')
    print "results put in ",meas_file
    pmag.magic_write(samp_file,SampOuts,'er_samples')
    print "sample orientations put in ",samp_file
    return True, meas_file
Exemplo n.º 23
0
def main():
    """
    NAME
        UMICH_magic.py
 
    DESCRIPTION
        converts UMICH .mag format files to magic_measurements format files

    SYNTAX
        UMICH_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -usr USER:   identify user, default is ""
        -f FILE: specify .mag format input file, required
        -fsa SAMPFILE : specify er_samples.txt file relating samples, site and locations names,default is none
        -F FILE: specify output file, default is magic_measurements.txt
        -spc NUM : specify number of characters to designate a  specimen, default = 0
        -loc LOCNAME : specify location/study name, must have either LOCNAME or SAMPFILE or be a synthetic
        -ncn NCON:  specify naming convention: default is #1 below
        -A: don't average replicate measurements
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 
        Format of UMICH .mag files:   
        Spec Treat CSD Intensity Declination Inclination metadata string
        Spec: specimen name
        Treat:  treatment step
            XXX T in Centigrade
            XXX AF in mT
         Intensity assumed to be total moment in 10^3 Am^2 (emu)
         Declination:  Declination in specimen coordinate system
         Inclination:  Declination in specimen coordinate system

         metatdata string:  mm/dd/yy;hh:mm;[dC,mT];xx.xx;UNITS;USER;INST;NMEAS
             hh in 24 hours.  
             dC or mT units of treatment XXX (see Treat above) for thermal or AF respectively
             xx.xxx   DC field
             UNITS of DC field (microT, mT)
             INST:  instrument code, number of axes, number of positions (e.g., G34 is 2G, three axes, 
                    measured in four positions)
             NMEAS: number of measurements in a single position (1,3,200...)
    """
# initialize some stuff
    dir_path='.'
    infile_type="mag"
    noave=0
    methcode,inst="",""
    phi,theta,peakfield,labfield=0,0,0,0
    pTRM,MD,samp_con,Z=0,0,'1',1
    missing=1
    demag="N"
    er_location_name=""
    citation='This study'
    args=sys.argv
    methcode="LP-NO"
    samp_file,ErSamps='',[]
    specnum=0
#
# get command line arguments
#
    meas_file="magic_measurements.txt"
    user=""
    if '-WD' in args:
        ind=args.index("-WD")
        dir_path=args[ind+1]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind=args.index("-usr")
        user=args[ind+1]
    if '-F' in args:
        ind=args.index("-F")
        meas_file=dir_path+'/'+args[ind+1]
    if '-f' in args:
        ind=args.index("-f")
        magfile=dir_path+'/'+args[ind+1]
        try:
            input=open(magfile,'rU')
        except:
            print "bad mag file name"
            sys.exit()
    else: 
        print "mag_file field is required option"
        print main.__doc__
        sys.exit()
    if "-spc" in args:
        ind=args.index("-spc")
        specnum=int(args[ind+1])
        if specnum!=0:specnum=-specnum
    if "-loc" in args:
        ind=args.index("-loc")
        er_location_name=args[ind+1]
    if "-fsa" in args:
        ind=args.index("-fsa")
        samp_file=dir_path+'/'+args[ind+1]
        Samps,file_type=pmag.magic_read(samp_file)
    if "-A" in args: noave=1
    if "-ncn" in args:
        ind=args.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
            samp_con=sys.argv[ind+1]
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="7"
    MagRecs,specs=[],[]
    version_num=pmag.get_version()
    if infile_type=="mag":
        for line in input.readlines():
            instcode=""
            if len(line)>2:
                MagRec={}
                MagRec['er_location_name']=er_location_name
                MagRec['magic_software_packages']=version_num
                MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
                MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
                MagRec["treatment_ac_field"]='0'
                MagRec["treatment_dc_field"]='0'
                MagRec["treatment_dc_field_phi"]='0'
                MagRec["treatment_dc_field_theta"]='0'
                meas_type="LT-NO"
                rec=line.split()
                labfield=0
                code1=rec[6].split(';')
                date=code1[0].split('/') # break date into mon/day/year
                yy=int(date[2])
                if yy <90:
                    yyyy=str(2000+yy)
                else: yyyy=str(1900+yy)
                mm=int(date[0])
                if mm<10:
                    mm="0"+str(mm)
                else: mm=str(mm)
                dd=int(date[1])
                if dd<10:
                    dd="0"+str(dd)
                else: dd=str(dd)
                time=code1[1].split(':')
                hh=int(time[0])
                if hh<10:
                    hh="0"+str(hh)
                else: hh=str(hh)
                min=int(time[1])
                if min<10:
                   min= "0"+str(min)
                else: min=str(min)
                MagRec["measurement_date"]=yyyy+":"+mm+":"+dd+":"+hh+":"+min+":00.00"
                MagRec["measurement_time_zone"]=''
                instcode=''
                if len(code1)>1:
                    MagRec["measurement_positions"]=code1[6][2]
                else:
                    MagRec["measurement_positions"]=code1[7]   # takes care of awkward format with bubba and flo being different
                if user=="":user=code1[5]
                if code1[2][-1]=='C': demag="T"
                if code1[2]=='mT': demag="AF"
                treat=rec[1].split('.')
                if len(treat)==1:treat.append('0')
                if demag=='T' and treat!=0:
                    meas_type="LT-T-Z"
                    MagRec["treatment_temp"]='%8.3e' % (float(treat[0])+273.) # temp in kelvin
                if demag=="AF":
                    meas_type="LT-AF-Z"
                    MagRec["treatment_ac_field"]='%8.3e' % (float(treat[0])*1e-3) # Af field in T
                MagRec["treatment_dc_field"]='0'
                MagRec["er_specimen_name"]=rec[0]
                if rec[0] not in specs:specs.append(rec[0]) # get a list of specimen names
                experiment=rec[0]+":"
                MagRec["er_site_name"]=""
                if specnum!=0:
                    MagRec["er_sample_name"]=rec[0][:specnum]
                else:
                    MagRec["er_sample_name"]=rec[0]
                if "-fsa" in args:
                    for samp in Samps:
                        if samp["er_sample_name"] == MagRec["er_sample_name"]: 
                            MagRec["er_location_name"]=samp["er_location_name"]
                            MagRec["er_site_name"]=samp["er_site_name"]
                            break
                elif int(samp_con)!=6:
                    site=pmag.parse_site(MagRec['er_sample_name'],samp_con,Z)
                    MagRec["er_site_name"]=site
                if MagRec['er_site_name']=="":
                    print 'No site name found for: ',MagRec['er_specimen_name'],MagRec['er_sample_name']
                if MagRec["er_location_name"]=="":
                    print 'no location name for: ',MagRec["er_specimen_name"] 
                if rec[1]==".00":rec[1]="0.00"
                MagRec["measurement_csd"]=rec[2]
                MagRec["measurement_magn_moment"]='%10.3e'% (float(rec[3])*1e-3) # moment in Am^2 (from emu)
                MagRec["measurement_dec"]=rec[4]
                MagRec["measurement_inc"]=rec[5]
                MagRec["magic_instrument_codes"]=instcode
                MagRec["er_analyst_mail_names"]=user
                MagRec["er_citation_names"]=citation
                MagRec["magic_method_codes"]=meas_type
                MagRec["measurement_flag"]='g'
                MagRec["er_specimen_name"]=rec[0]
                MagRec["measurement_number"]='1'
                MagRecs.append(MagRec) 
    MagOuts=[]
    for spec in specs:  # gather all demag types for this specimen
        SpecRecs,meths,measnum=[],[],1
        for rec in MagRecs:
            if rec['er_specimen_name']==spec:
                rec['measurement_number']=str(measnum)
                measnum+=1
                if rec['magic_method_codes'] not in meths:meths.append(rec['magic_method_codes'])
                SpecRecs.append(rec)
        expname=spec
        if "LT-AF-Z" in meths:expname=expname+ ':LP-DIR-AF'
        if "LT-T-Z" in meths:expname=expname+ ':LP-DIR-T'
        for rec in SpecRecs:
            rec['magic_experiment_name']=expname
            MagOuts.append(rec)
    pmag.magic_write(meas_file,MagOuts,'magic_measurements')
    print "results put in ",meas_file
Exemplo n.º 24
0
def main():
    """
    NAME
        orientation_magic.py
   
    DESCRIPTION
        takes tab delimited field notebook information and converts to MagIC formatted tables
 
    SYNTAX
        orientation_magic.py [command line options]

    OPTIONS
        -f FILE: specify input file, default is: orient.txt
        -Fsa FILE: specify output file, default is: er_samples.txt 
        -Fsi FILE: specify output site location file, default is: er_sites.txt 
        -app  append/update these data in existing er_samples.txt, er_sites.txt files
        -ocn OCON:  specify orientation convention, default is #1 below
        -dcn DCON [DEC]: specify declination convention, default is #1 below
            if DCON = 2, you must supply the declination correction 
        -BCN don't correct bedding_dip_dir for magnetic declination -already corrected 
        -ncn NCON:  specify naming convention: default is #1 below
        -a: averages all bedding poles and uses average for all samples: default is NO
        -gmt HRS:  specify hours to subtract from local time to get GMT: default is 0
        -mcd: specify sampling method codes as a colon delimited string:  [default is: FS-FD:SO-POM]
             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

    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)
        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
    
        Orientation convention:
            Samples are oriented in the field with a "field arrow" and measured in the laboratory with a "lab arrow". The lab arrow is the positive X direction of the right handed coordinate system of the specimen measurements. The lab and field arrows may  not be the same. In the MagIC database, we require the orientation (azimuth and plunge) of the X direction of the measurements (lab arrow). Here are some popular conventions that convert the field arrow azimuth (mag_azimuth in the orient.txt file) and dip (field_dip in orient.txt) to the azimuth and plunge  of the laboratory arrow (sample_azimuth and sample_dip in er_samples.txt). The two angles, mag_azimuth and field_dip are explained below. 

            [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] all others you will have to either customize your 
                self or e-mail [email protected] 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  
            [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 [email protected] for help.  
    OUTPUT
            output saved in er_samples.txt and er_sites.txt - will overwrite any existing files 
    """
    #
    # initialize variables
    #
    stratpos=""
    args=sys.argv
    date,lat,lon="","",""  # date of sampling, latitude (pos North), longitude (pos East)
    bed_dip,bed_dip_dir="",""
    participantlist=""
    Lats,Lons=[],[] # list of latitudes and longitudes
    SampOuts,SiteOuts,ImageOuts=[],[],[]  # lists of Sample records and Site records
    samplelist,sitelist,imagelist=[],[],[]
    samp_con,Z,average_bedding,DecCorr="1",1,"0",0.
    newbaseline,newbeddir,newbeddip="","",""
    meths=''
    delta_u="0"
    sclass,lithology,type="","",""
    newclass,newlith,newtype='','',''
    user=""
    BPs=[]# bedding pole declinations, bedding pole inclinations
    #
    #
    dir_path,AddTo='.',0
    if "-WD" in args:
        ind=args.index("-WD")
        dir_path=sys.argv[ind+1]
    orient_file,samp_file,or_con,corr = dir_path+"/orient.txt",dir_path+"/er_samples.txt","1","1"
    site_file=dir_path+"/er_sites.txt"
    image_file=dir_path+"/er_images.txt"
    SampRecs,SiteRecs,ImageRecs=[],[],[]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-f" in args:
        ind=args.index("-f")
        orient_file=dir_path+'/'+sys.argv[ind+1]
    if "-Fsa" in args:
        ind=args.index("-Fsa")
        samp_file=dir_path+'/'+sys.argv[ind+1]
    if "-Fsi" in args:
        ind=args.index("-Fsi")
        site_file=dir_path+'/'+sys.argv[ind+1]
    if '-app' in args:
        AddTo=1
        try:
            SampRecs,file_type=pmag.magic_read(samp_file)
            print 'sample data to be appended to: ', samp_file
        except:
            print 'problem with existing file: ',samp_file, ' will create new.'
        try:
            SiteRecs,file_type=pmag.magic_read(site_file)
            print 'site data to be appended to: ',site_file
        except:
            print 'problem with existing file: ',site_file,' will create new.'
        try:
            ImageRecs,file_type=pmag.magic_read(image_file)
            print 'image data to be appended to: ',image_file
        except:
            print 'problem with existing file: ',image_file,' will create new.'
    if "-ocn" in args:
        ind=args.index("-ocn")
        or_con=sys.argv[ind+1]
    if "-dcn" in args:
        ind=args.index("-dcn")
        corr=sys.argv[ind+1] 
        if corr=="2":
            DecCorr=float(sys.argv[ind+2])
        elif corr=="3":
            DecCorr=0.
    if '-BCN' in args:
        BedCorr=0
    else:
        BedCorr=1
    if "-ncn" in args:
        ind=args.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="7"
    if "-gmt" in args:
        ind=args.index("-gmt")
        delta_u=(sys.argv[ind+1])
    if "-mcd" in args:
        ind=args.index("-mcd")
        meths=(sys.argv[ind+1])
    if "-a" in args: average_bedding="1"
    #
    # read in file to convert
    #
    OrData,location_name=pmag.magic_read(orient_file)
    #
    # step through the data sample by sample
    #
    for OrRec in OrData:
        if 'mag_azimuth' not in OrRec.keys():OrRec['mag_azimuth']=""
        if 'field_dip' not in OrRec.keys():OrRec['field_dip']=""
        if OrRec['mag_azimuth']==" ":OrRec["mag_azimuth"]=""
        if OrRec['field_dip']==" ":OrRec["field_dip"]=""
        if 'sample_description' in OrRec.keys():
            sample_description=OrRec['sample_description']
        else:
            sample_description=""
        if 'sample_igsn' in OrRec.keys():
            sample_igsn=OrRec['sample_igsn']
        else:
            sample_igsn=""
        if 'sample_texture' in OrRec.keys():
            sample_texture=OrRec['sample_texture']
        else:
            sample_texture=""
        if 'sample_cooling_rate' in OrRec.keys():
            sample_cooling_rate=OrRec['sample_cooling_rate']
        else:
            sample_cooling_rate=""
        if 'cooling_rate_corr' in OrRec.keys():
            cooling_rate_corr=OrRec['cooling_rate_corr']
            if 'cooling_rate_mcd' in OrRec.keys():
                cooling_rate_mcd=OrRec['cooling_rate_mcd']
            else:
                cooling_rate_mcd='DA-CR'
        else:
            cooling_rate_corr=""
            cooling_rate_mcd=""
        sample_orientation_flag='g'
        if 'sample_orientation_flag' in OrRec.keys():
            if OrRec['sample_orientation_flag']=='b' or OrRec["mag_azimuth"]=="": 
                sample_orientation_flag='b'
        methcodes=meths  # initialize method codes
        if meths!='':
            if 'method_codes' in OrRec.keys() and OrRec['method_codes'].strip()!="":methcodes=methcodes+":"+OrRec['method_codes'] # add notes 
        else:
            if 'method_codes' in OrRec.keys() and OrRec['method_codes'].strip()!="":methcodes=OrRec['method_codes'] # add notes 
        codes=methcodes.replace(" ","").split(":")
        MagRec={}
        MagRec["er_location_name"]=location_name
        MagRec["er_citation_names"]="This study"
        MagRec['sample_orientation_flag']=sample_orientation_flag
        MagRec['sample_igsn']=sample_igsn
        MagRec['sample_texture']=sample_texture
        MagRec['sample_cooling_rate']=sample_cooling_rate
        MagRec['cooling_rate_corr']=cooling_rate_corr
        MagRec['cooling_rate_mcd']=cooling_rate_mcd
    #
    # parse information common to all orientation methods
    #
        MagRec["er_sample_name"]=OrRec["sample_name"]
        if "IGSN" in OrRec.keys():
            MagRec["sample_igsn"]=OrRec["IGSN"]
        else:
            MagRec["sample_igsn"]=""
        MagRec["sample_height"],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 OrRec.keys() and OrRec['GPS_baseline']!="":newbaseline=OrRec["GPS_baseline"]
        if newbaseline!="":baseline=float(newbaseline)
        if 'participants' in OrRec.keys() and OrRec['participants']!="" and OrRec['participants']!=participantlist: 
            participantlist=OrRec['participants']
        MagRec['er_scientist_mail_names']=participantlist
        newlat=OrRec["lat"]
        if newlat!="":lat=float(newlat)
        if lat=="":
            print "No latitude specified for ! ",sample
            sys.exit()
        MagRec["sample_lat"]='%11.5f'%(lat)
        newlon=OrRec["long"]
        if newlon!="":lon=float(newlon)
        if lon=="":
            print "No longitude specified for ! ",sample
            sys.exit()
        MagRec["sample_lon"]='%11.5f'%(lon)
        if 'bedding_dip_direction' in OrRec.keys(): newbeddir=OrRec["bedding_dip_direction"]
        if newbeddir!="":bed_dip_dir=OrRec['bedding_dip_direction']
        if 'bedding_dip' in 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
        if "sample_class" in OrRec.keys():newclass=OrRec["sample_class"]
        if newclass!="":sclass=newclass
        if sclass=="": sclass="Not Specified"
        MagRec["sample_class"]=sclass
        if "sample_lithology" in OrRec.keys():newlith=OrRec["sample_lithology"]
        if newlith!="":lithology=newlith
        if lithology=="": lithology="Not Specified"
        MagRec["sample_lithology"]=lithology
        if "sample_type" in OrRec.keys():newtype=OrRec["sample_type"]
        if newtype!="":type=newtype
        if type=="": type="Not Specified"
        MagRec["sample_type"]=type
        if labdip!="":
            MagRec["sample_dip"]='%7.1f'%labdip
        else:
            MagRec["sample_dip"]=""
        if "date" in OrRec.keys():
            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+float(mmddyy[0])/12
            sample_date='%i:%s:%s'%(yy,mmddyy[0],mmddyy[1])
            MagRec["sample_date"]=sample_date
        if labaz!="":
            MagRec["sample_azimuth"]='%7.1f'%(labaz)
        else:
            MagRec["sample_azimuth"]=""
        if "stratigraphic_height" in 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
            else:
                MagRec["sample_height"]=stratpos   # keep last record if blank
#
        if corr=="1" and MagRec['sample_azimuth']!="": # get magnetic declination (corrected with igrf value)
            x,y,z,f=pmag.doigrf(lon,lat,0,decimal_year)
            Dir=pmag.cart2dir( (x,y,z)) 
            DecCorr=Dir[0]
        if "bedding_dip" in 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 OrRec.keys():
            if OrRec["bedding_dip_direction"]!="" and BedCorr==1: 
                dd=float(OrRec["bedding_dip_direction"])+DecCorr
                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!="0": 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 OrRec.keys():
            site=OrRec['site_name']
        else:
            site=pmag.parse_site(OrRec["sample_name"],samp_con,Z) # parse out the site name
        MagRec["er_site_name"]=site
        site_description="" # overwrite any prior description
        if 'site_description' in OrRec.keys() and OrRec['site_description']!="":
            site_description=OrRec['site_description'].replace(",",";")
        if "image_name" in OrRec.keys():
            images=OrRec["image_name"].split(":")
            if "image_look" in OrRec.keys():
                looks=OrRec['image_look'].split(":")
            else:
                looks=[]
            if "image_photographer" in 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
    	    SiteRec={}
    	    SiteRec["er_site_name"]=site 
            SiteRec["site_definition"]="s"
    	    SiteRec["er_location_name"]=location_name
    	    SiteRec["er_citation_names"]="This study"
            SiteRec["site_lat"]=MagRec["sample_lat"]
            SiteRec["site_lon"]=MagRec["sample_lon"]
            SiteRec["site_height"]=MagRec["sample_height"]
            SiteRec["site_class"]=MagRec["sample_class"]
            SiteRec["site_lithology"]=MagRec["sample_lithology"]
            SiteRec["site_type"]=MagRec["sample_type"]
            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 corr!='3':
                az=labaz+DecCorr
                if az>360.:az=az-360.
                CMDRec={}
                for key in 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'%(DecCorr)
                if corr=='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 OrRec.keys() and OrRec["mag_az_bs"] !="" and OrRec["mag_az_bs"]!=" ":
                SRec={}
                for key in MagRec.keys():
                    SRec[key]=MagRec[key] # make a copy of MagRec
                labaz=float(OrRec["mag_az_bs"])
                az=labaz+DecCorr
                if az>360.:az=az-360.
                SRec["sample_azimuth"]='%7.1f'%(az)
                SRec["sample_declination_correction"]='%7.1f'%(DecCorr)
                SRec["magic_method_codes"]=methcodes+':SO-SIGHT-BACK:SO-CMD-NORTH'
                SampOuts.append(SRec)
    #
    # check for suncompass data
    #
            if "shadow_angle" in OrRec.keys() and OrRec["shadow_angle"]!="":  # there are sun compass data
                if delta_u=="":
                    delta_u=raw_input("Enter hours to SUBTRACT from time for  GMT: [0] ")
                    if delta_u=="":delta_u="0"
                SunRec,sundata={},{}
                shad_az=float(OrRec["shadow_angle"])
                sundata["date"]='%i:%s:%s:%s'%(yy,mmddyy[0],mmddyy[1],OrRec["hhmm"])
#                if eval(delta_u)<0:
#                        MagRec["sample_time_zone"]='GMT'+delta_u+' hours'
#                else:
#                    MagRec["sample_time_zone"]='GMT+'+delta_u+' hours'
                sundata["delta_u"]=delta_u
                sundata["lon"]='%7.1f'%(lon)   
                sundata["lat"]='%7.1f'%(lat)  
                sundata["shadow_angle"]=OrRec["shadow_angle"]
                sundec=pmag.dosundec(sundata)
                for key in 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
    #
            if "prism_angle" in OrRec.keys() and OrRec["prism_angle"]!="":  # there are diff GPS data   
                GPSRec={}
                for key in 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 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)
            if "GPS_Az" in OrRec.keys() and OrRec["GPS_Az"]!="":  # there are differential GPS Azimuth data   
                GPSRec={}
                for key in 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":  
            fpars=pmag.fisher_mean(BPs)
            print 'over-writing all bedding with average '
    Samps=[]
    for  rec in SampOuts:
        if average_bedding!="0":
            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)
    pmag.magic_write(samp_file,SampsOut,"er_samples")
    pmag.magic_write(site_file,Sites,"er_sites")
    print "Data saved in ", samp_file,' and ',site_file
    if len(ImageOuts)>0:
        Images,keys=pmag.fillkeys(ImageOuts)
        pmag.magic_write(image_file,Images,"er_images")
        print "Image info saved in ",image_file
Exemplo n.º 25
0
def main(command_line=True, **kwargs):
    """
    NAME
        CIT_magic.py

    DESCRIPTION
        converts CIT and .sam  format files to magic_measurements format files

    SYNTAX
        CIT_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -usr USER:   identify user, default is ""
        -f FILE: specify .sam format input file, required
        -fsi SITEFILE : specify file with site names and locations [tab delimited magic file]
        -F FILE: specify output  measurements file, default is magic_measurements.txt
        -Fsp FILE: specify output er_specimens.txt file, default is er_specimens.txt
        -Fsi FILE: specify output er_sites.txt file, default is er_sites.txt
        -Fsa FILE: specify output er_samples.txt file, default is er_samples.txt  # LORI
        -n [gm,kg,cc,m3]: specify normalization
        -A: don't average replicate measurements
        -spc NUM : specify number of characters to designate a  specimen, default = 0
        -ncn NCON: specify naming convention
        -loc LOCNAME : specify location/study name, must have either LOCNAME or SITEFILE or be a synthetic
        -mcd [FS-FD:SO-MAG,.....] colon delimited list for method codes applied to all specimens in .sam file
        -dc B PHI THETA: dc lab field (in micro tesla) and phi,theta, default is none
              NB: use PHI, THETA = -1 -1 to signal that it changes, i.e. in anisotropy experiment
        -ac B : peak AF field (in mT) for ARM acquisition, default is none

    INPUT
        Best to put separate experiments (all AF, thermal, thellier, trm aquisition, Shaw, etc.)

    NOTES:
         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) [default]
            [4-Z] XXXXYYY:  YYY is sample designation with Z characters from site XXX
            [5] all others you will have to either customize your
                self or e-mail [email protected] for help.

    """
    #
    #initialize variables
    norm='cc'
    samp_con,Z='3',1
    meas_file='magic_measurements.txt'
    spec_file='er_specimens.txt'
    samp_file='er_samples.txt'
    site_file='er_sites.txt'
    ErSpecs,ErSamps,ErSites,ErLocs,ErCits=[],[],[],[],[]
    MeasRecs=[]
    specnum,units,locname=0,"1","unknown"
    citation="This study"
    dir_path='.'
    args=sys.argv
    if command_line:
        if '-WD' in args:
            ind=args.index("-WD")
            dir_path=args[ind+1]
        if "-h" in args:
            print main.__doc__
            return False
        if "-usr" in args:
            ind=args.index("-usr")
            user=args[ind+1]
        if '-F' in args:
            ind=args.index("-F")
            meas_file=args[ind+1]
        if '-Fsp' in args:
            ind=args.index("-Fsp")
            spec_file=args[ind+1]
        if '-Fsa' in args:
            ind=args.index("-Fsa")
            samp_file=args[ind+1]
        if '-Fsi' in args:   # LORI addition
            ind=args.index("-Fsi")
            site_file=args[ind+1]
        if '-loc' in args:
            ind=args.index("-loc")
            locname=args[ind+1]
        if '-mcd' in args:
            ind=args.index("-mcd")
            methods=args[ind+1]
        else:
            methods='SO-MAG'
        if '-spc' in args:
            ind=args.index("-spc")
            specnum=-int(args[ind+1])
        if '-n' in args:
            ind=args.index("-n")
            norm=args[ind+1]
        if "-A" in args:
            avg=1
        else:
            avg=0
        if "-ncn" in args:
            ind=args.index("-ncn")
            samp_con=sys.argv[ind+1]
            if "4" in samp_con:
                if "-" not in samp_con:
                    print "option [4] must be in form 4-Z where Z is an integer"
                    return False, "naming convention option [4] must be in form 4-Z where Z is an integer"
                else:
                    Z=samp_con.split("-")[1]
                    samp_con="4"
        if '-f' in args:
            ind=args.index("-f")
            magfile=args[ind+1]
        if '-ID' in args:
            ind = args.index('-ID')
            input_dir_path = args[ind+1]
        else:
            input_dir_path = dir_path
        output_dir_path = dir_path
        # LJ

    # if you are running as a module:
    elif not command_line:
        dir_path = kwargs.get('dir_path', '.')
        user = kwargs.get('user', '')
        meas_file = kwargs.get('meas_file', 'magic_measurements.txt') # outfile
        spec_file = kwargs.get('spec_file', 'er_specimens.txt') # specimen outfile
        samp_file = kwargs.get('samp_file', 'er_samples.txt') # sample outfile
        site_file = kwargs.get('site_file', 'er_sites.txt') # site outfile
        locname = kwargs.get('locname', '')
        methods = kwargs.get('methods', ['SO-MAG'])
        specnum = -int(kwargs.get('specnum', 0))
        norm = kwargs.get('norm', 'cc')
        avg = kwargs.get('avg', 0)  # 0 means do average, 1 means don't
        samp_con = kwargs.get('samp_con', '3')
        magfile = kwargs.get('magfile', '')
        input_dir_path = kwargs.get('input_dir_path', dir_path)
        output_dir_path = dir_path
    # done with module-specific stuff

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

    magfile = os.path.join(input_dir_path, magfile)
    spec_file = os.path.join(output_dir_path, spec_file)
    samp_file = os.path.join(output_dir_path, samp_file)
    site_file = os.path.join(output_dir_path, site_file)
    meas_file= os.path.join(output_dir_path, meas_file)
    try:
        file_input=open(magfile,'r')
    except Exception as ex:
        print "bad sam file name: ", magfile
        return False, "bad sam file name"
    File = file_input.readlines()
    sids,ln,format=[],0,'CIT'
    formats=['CIT','2G','APP','JRA']
    ErLocRec={}
    ErLocRec["er_location_name"]=locname
    ErLocRec["er_citation_names"]=citation
    comment=File[ln]
    if comment=='CIT':
       format=comment
       ln+=1
    comment=File[ln]
    print comment
    ln+=1
    specimens,samples,sites=[],[],[]
    if format=='CIT':
        line=File[ln].split()
        site_lat=line[0]
        site_lon=line[1]
        ErLocRec["location_begin_lat"]=site_lat
        ErLocRec["location_begin_lon"]=site_lon
        ErLocRec["location_end_lat"]=site_lat
        ErLocRec["location_end_lon"]=site_lon
        ErLocs.append(ErLocRec)
        Cdec=float(line[2])
        for k in range(ln+1,len(File)):
            line=File[k]
            rec=line.split()
            specimen=rec[0]
            specimens.append(specimen)
    for specimen in specimens:
        ErSpecRec,ErSampRec,ErSiteRec={},{},{}
        if specnum!=0:
            sample=specimen[:specnum]
        else: sample=specimen
        site=pmag.parse_site(sample,samp_con,Z)
        ErSpecRec['er_specimen_name']=specimen
        ErSpecRec['er_sample_name']=sample
        ErSpecRec['er_site_name']=site
        ErSpecRec['er_location_name']=locname
        ErSpecRec['er_citation_names']=citation
        ErSampRec['er_sample_name']=sample
        ErSampRec['er_site_name']=site
        ErSampRec['er_location_name']=locname
        ErSampRec['er_citation_names']=citation
        ErSampRec['magic_method_codes']=methods
        ErSampRec['sample_declination_correction']='%7.1f'%(Cdec)
        ErSiteRec['er_site_name']=site
        ErSiteRec['er_location_name']=locname
        ErSiteRec['er_citation_names']=citation
        ErSiteRec['site_lat']=site_lat
        ErSiteRec['site_lon']=site_lon
        f=open(input_dir_path+'/'+specimen,'rU')
        Lines=f.readlines()
        comment=""
        line=Lines[0].split()
        if len(line)>2:
            comment=line[2]
        info=Lines[1].split()
        vol=float(info[-1])
        if vol!=1.0:
            if norm=='cc':units="1"
            if norm=='m3':units="2"
            ErSpecRec['specimen_weight']=""
            if units=="1" or "":
                ErSpecRec['specimen_volume']='%10.3e'%(vol*1e-6)
            else:
                ErSpecRec['specimen_volume']='%10.3e'%(vol)
        else:
            if norm=='cc':units="1"
            if norm=='m3':units="2"
            ErSpecRec['specimen_volume']=""
            if units=="1" or "":
                ErSpecRec['specimen_weight']='%10.3e'%(vol*1e-3)
            else:
                ErSpecRec['specimen_weight']='%10.3e'%(vol)
        dip=float(info[-2])
        dip_direction=float(info[-3])+Cdec+90.
        sample_dip=-float(info[-4])
        sample_azimuth=float(info[-5])+Cdec-90.
        if len(info)>5:
            ErSampRec['sample_height']=info[-6]
        else:
            ErSampRec['sample_height']='0'
        ErSampRec['sample_azimuth']='%7.1f'%(sample_azimuth)
        ErSampRec['sample_dip']='%7.1f'%(sample_dip)
        ErSampRec['sample_bed_dip']='%7.1f'%(dip)
        ErSampRec['sample_bed_dip_direction']='%7.1f'%(dip_direction)
        ErSampRec['sample_class']=''
        ErSampRec['sample_type']=''
        ErSampRec['sample_lithology']=''
        if Cdec!=0 or Cdec!="":
            ErSampRec['magic_method_codes']='SO-CMD-NORTH'
        else:
            ErSampRec['magic_method_codes']='SO-MAG'
        for line in Lines[2:len(Lines)]:
            #print 'line:', line
            MeasRec=ErSpecRec.copy()

#           Remove specimen_volume and specimen_weight as they do not exits in the magic_measurement table
            del MeasRec["specimen_volume"]
            del MeasRec["specimen_weight"]

            treat_type=line[0:3]
            treat=line[3:6]
            #print 'treat:', treat
            if treat_type.strip()=='NRM':
                MeasRec['magic_method_codes']='LT-NO'
                MeasRec['measurement_temp']='273'
                MeasRec['treatment_temp']='273'
                MeasRec['treatment_dc_field']='0'
                MeasRec['treatment_ac_field']='0'
            elif treat_type.strip()=='AF':
                MeasRec['magic_method_codes']='LT-AF-Z'
                MeasRec['measurement_temp']='273'
                MeasRec['treatment_temp']='273'
                MeasRec['treatment_dc_field']='0'
                if treat == '   ':
                    MeasRec['treatment_ac_field']='0'
                else:
                    MeasRec['treatment_ac_field']='%10.3e'%(float(treat)*1e-3)
            elif treat_type.strip()=='TT':
                MeasRec['magic_method_codes']='LT-T-Z'
                MeasRec['measurement_temp']='273'
                if treat == '   ':
                    MeasRec['treatment_temp']='273'
                else:
                    MeasRec['treatment_temp']='%7.1f'%(float(treat)+273)
                MeasRec['treatment_dc_field']='0'
                MeasRec['treatment_ac_field']='0'
            elif treat_type.strip()=='LT' or treat_type.strip()=='LN2':
                MeasRec['magic_method_codes']='LT-LT-Z'
                MeasRec['measurement_temp']='273'
                MeasRec['treatment_temp']='77'
                MeasRec['treatment_dc_field']='0'
                MeasRec['treatment_ac_field']='0'
            else:
                print "trouble with your treatment steps"
            MeasRec['measurement_dec']=line[46:51]
            MeasRec['measurement_inc']=line[52:58]
            M='%8.2e'%(float(line[31:39])*vol*1e-3) # convert to Am2
            MeasRec['measurement_magn_moment']=M
            MeasRec['measurement_sd_x']='%8.2e'%(float(line[58:67])*1e-8) #(convert e-5emu to Am2)
            MeasRec['measurement_sd_y']='%8.2e'%(float(line[67:76])*1e-8)
            MeasRec['measurement_sd_z']='%8.2e'%(float(line[76:85])*1e-8)
            MeasRec['measurement_csd']='%7.1f'%(eval(line[41:46]))
            MeasRec['magic_instrument_codes']=line[85:]
            MeasRec["measurement_positions"]='1'
            MeasRec['measurement_standard']='u'

            MeasRecs.append(MeasRec)
        ErSpecs.append(ErSpecRec)
        if sample not in samples:
            samples.append(sample)
            ErSamps.append(ErSampRec)
        site=pmag.parse_site(sample,samp_con,Z)
        if site not in sites:
            sites.append(site)
            ErSites.append(ErSiteRec)
    pmag.magic_write(spec_file,ErSpecs,'er_specimens')
    print 'specimens stored in ',spec_file
    pmag.magic_write(samp_file,ErSamps,'er_samples')
    print 'samples stored in ',samp_file
    pmag.magic_write(site_file,ErSites,'er_sites')
    print 'sites stored in ', site_file
    Fixed=pmag.measurements_methods(MeasRecs,avg)
    pmag.magic_write(meas_file,Fixed,'magic_measurements')
    print 'data stored in ',meas_file
    return True, meas_file
Exemplo n.º 26
0
def main():
    """
    NAME
        LDGO_magic.py
 
    DESCRIPTION
        converts LDGO  format files to magic_measurements format files

    SYNTAX
        LDGO_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -usr USER:   identify user, default is ""
        -f FILE: specify .ldgo format input file, required
        -fsa SAMPFILE : specify er_samples.txt file relating samples, site and locations names,default is none
        -F FILE: specify output file, default is magic_measurements.txt
        -Fsy: specify er_synthetics file, default is er_sythetics.txt
        -Fsa: specify output er_samples file, default is NONE (only for LDGO formatted files)
        -LP [colon delimited list of protocols, include all that apply]
            AF:  af demag
            T: thermal including thellier but not trm acquisition
            S: Shaw method
            I: IRM (acquisition)
            N: NRM only
            TRM: trm acquisition
            ANI: anisotropy experiment
            D: double AF demag
            G: triple AF demag (GRM protocol)
        -V [1,2,3] units of IRM field in volts using ASC coil #1,2 or 3
        -spc NUM : specify number of characters to designate a  specimen, default = 0
        -loc LOCNAME : specify location/study name, must have either LOCNAME or SAMPFILE or be a synthetic
        -syn INST TYPE:  sets these specimens as synthetics created at institution INST and of type TYPE
        -ins INST : specify which demag instrument was used (e.g, SIO-Suzy or SIO-Odette),default is ""
        -dc B PHI THETA: dc lab field (in micro tesla) and phi,theta, default is none
              NB: use PHI, THETA = -1 -1 to signal that it changes, i.e. in anisotropy experiment
        -ac B : peak AF field (in mT) for ARM acquisition, default is none
        -ncn NCON:  specify naming convention: default is #1 below
        -A: don't average replicate measurements
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 
            [8] synthetic - has no site name
    INPUT
        Best to put separate experiments (all AF, thermal, thellier, trm aquisition, Shaw, etc.) in 
           seperate .mag files (eg. af.mag, thermal.mag, etc.)

        Format of LDEO files:   
isaf2.fix       
LAT:   .00  LON:    .00
    ID     TREAT  I  CD    J    CDECL CINCL  GDECL GINCL  BDECL BINCL  SUSC  M/V
________________________________________________________________________________
is031c2       .0  SD  0 461.600 163.9  17.5  337.1  74.5  319.1  74.4    .0   .0
        
        ID: specimen name
        TREAT:  treatment step
        I:  Instrument 
        CD:  Circular standard devation
        J: intensity.  assumed to be total moment in 10^-4 (emu)
        CDECL:  Declination in specimen coordinate system
        CINCL:  Declination in specimen coordinate system
        GDECL:  Declination in geographic coordinate system
        GINCL:  Declination in geographic coordinate system
        BDECL:  Declination in bedding adjusted coordinate system
        BINCL:  Declination in bedding adjusted coordinate system
        SUSC:  magnetic susceptibility (in micro SI)a
        M/V: mass or volume for nomalizing (0 won't normalize)
     
    """
    # initialize some stuff
    noave = 0
    methcode, inst = "LP-NO", ""
    phi, theta, peakfield, labfield = 0, 0, 0, 0
    pTRM, MD, samp_con, Z = 0, 0, '1', 1
    dec = [315, 225, 180, 135, 45, 90, 270, 270, 270, 90, 180, 180, 0, 0, 0]
    inc = [0, 0, 0, 0, 0, -45, -45, 0, 45, 45, 45, -45, -90, -45, 45]
    tdec = [0, 90, 0, 180, 270, 0, 0, 90, 0]
    tinc = [0, 0, 90, 0, 0, -90, 0, 0, 90]
    missing = 1
    demag = "N"
    er_location_name = ""
    citation = 'This study'
    args = sys.argv
    fmt = 'old'
    syn = 0
    synfile = 'er_synthetics.txt'
    samp_file, ErSamps = '', []
    trm = 0
    irm = 0
    specnum = 0
    coil = ""
    #
    # get command line arguments
    #
    meas_file = "magic_measurements.txt"
    user = ""
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind = args.index("-usr")
        user = args[ind + 1]
    if '-F' in args:
        ind = args.index("-F")
        meas_file = args[ind + 1]
    if '-Fsy' in args:
        ind = args.index("-Fsy")
        synfile = args[ind + 1]
    if '-Fsa' in args:
        ind = args.index("-Fsa")
        samp_file = args[ind + 1]
        try:
            open(samp_file, 'rU')
            ErSamps, file_type = pmag.magic_read(samp_file)
            print 'sample information will be appended to new er_samples.txt file'
        except:
            print 'sample information will be stored in new er_samples.txt file'
    if '-f' in args:
        ind = args.index("-f")
        magfile = args[ind + 1]
        try:
            input = open(magfile, 'rU')
        except:
            print "bad mag file name"
            sys.exit()
    else:
        print "mag_file field is required option"
        print main.__doc__
        sys.exit()
    if "-dc" in args:
        ind = args.index("-dc")
        labfield = float(args[ind + 1]) * 1e-6
        phi = float(args[ind + 2])
        theta = float(args[ind + 3])
    if "-ac" in args:
        ind = args.index("-ac")
        peakfield = float(args[ind + 1]) * 1e-3
    if "-spc" in args:
        ind = args.index("-spc")
        specnum = int(args[ind + 1])
        if specnum != 0: specnum = -specnum
    if "-loc" in args:
        ind = args.index("-loc")
        er_location_name = args[ind + 1]
    if "-fsa" in args:
        ind = args.index("-fsa")
        Samps, file_type = pmag.magic_read(args[ind + 1])
    if '-syn' in args:
        syn = 1
        ind = args.index("-syn")
        institution = args[ind + 1]
        syntype = args[ind + 2]
        if '-fsy' in args:
            ind = args.index("-fsy")
            synfile = args[ind + 1]
    if "-ins" in args:
        ind = args.index("-ins")
        inst = args[ind + 1]
    if "-A" in args: noave = 1
    if "-ncn" in args:
        ind = args.index("-ncn")
        samp_con = sys.argv[ind + 1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z = samp_con.split("-")[1]
                samp_con = "4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z = samp_con.split("-")[1]
                samp_con = "4"
    if '-LP' in args:
        ind = args.index("-LP")
        codelist = args[ind + 1]
        codes = codelist.split(':')
        if "AF" in codes:
            demag = 'AF'
            if '-dc' not in args: methcode = "LT-AF-Z"
            if '-dc' in args: methcode = "LT-AF-I"
        if "T" in codes:
            demag = "T"
            if '-dc' not in args: methcode = "LT-T-Z"
            if '-dc' in args: methcode = "LT-T-I"
        if "I" in codes:
            methcode = "LP-IRM"
            irmunits = "mT"
        if "S" in codes:
            demag = "S"
            methcode = "LP-PI-TRM:LP-PI-ALT-AFARM"
            trm_labfield = labfield
            ans = raw_input("DC lab field for ARM step: [50uT] ")
            if ans == "":
                arm_labfield = 50e-6
            else:
                arm_labfield = float(ans) * 1e-6
            ans = raw_input("temperature for total trm step: [600 C] ")
            if ans == "":
                trm_peakT = 600 + 273  # convert to kelvin
            else:
                trm_peakT = float(ans) + 273  # convert to kelvin
        if "G" in codes: methcode = "LT-AF-G"
        if "D" in codes: methcode = "LT-AF-D"
        if "TRM" in codes:
            demag = "T"
            trm = 1
    if "-V" in args:
        methcode = "LP-IRM"
        ind = args.index("-V")
        irmunits = "V"
        coil = args[ind + 1]
        if coil not in ["1", "2", "3"]:
            print main.__doc__
            print 'not a valid coil specification'
            sys.exit()
    if demag == "T" and "ANI" in codes:
        methcode = "LP-AN-TRM"
    if demag == "AF" and "ANI" in codes:
        methcode = "LP-AN-ARM"
        if labfield == 0: labfield = 50e-6
        if peakfield == 0: peakfield = .180
    SynRecs, MagRecs = [], []
    version_num = pmag.get_version()
    if 1:  # ldgo file format
        #
        # find start of data:
        #
        Samps = []  # keeps track of sample orientations
        DIspec = []
        Data, k = input.readlines(), 0
        for k in range(len(Data)):
            rec = Data[k].split()
            if rec[0][0] == "_" or rec[0][0:2] == "!_":
                break
        start = k + 1
        for k in range(start, len(Data)):
            rec = Data[k].split()
            if len(rec) > 0:
                MagRec = {}
                MagRec["treatment_temp"] = '%8.3e' % (273
                                                      )  # room temp in kelvin
                MagRec["measurement_temp"] = '%8.3e' % (
                    273)  # room temp in kelvin
                MagRec["treatment_ac_field"] = '0'
                MagRec["treatment_dc_field"] = '0'
                MagRec["treatment_dc_field_phi"] = '0'
                MagRec["treatment_dc_field_theta"] = '0'
                meas_type = "LT-NO"
                MagRec["measurement_flag"] = 'g'
                MagRec["measurement_standard"] = 'u'
                MagRec["measurement_number"] = '1'
                MagRec["er_specimen_name"] = rec[0]
                if specnum != 0:
                    MagRec["er_sample_name"] = rec[0][:specnum]
                else:
                    MagRec["er_sample_name"] = rec[0]
                site = pmag.parse_site(MagRec['er_sample_name'], samp_con, Z)
                MagRec["er_site_name"] = site
                MagRec["er_location_name"] = er_location_name
                MagRec["measurement_csd"] = rec[3]
                MagRec["measurement_magn_moment"] = '%10.3e' % (
                    float(rec[4]) * 1e-7)  # moment in Am^2 (from 10^-4 emu)
                #
                #if samp_file!="" and MagRec["er_sample_name"] not in Samps:        # create er_samples.txt file with these data
                #    cdec,cinc=float(rec[5]),float(rec[6])
                #    gdec,ginc=float(rec[7]),float(rec[8])
                #    az,pl=pmag.get_azpl(cdec,cinc,gdec,ginc)
                #    bdec,binc=float(rec[9]),float(rec[10])
                #    if rec[7]!=rec[9] and rec[6]!=rec[8]:
                #        dipdir,dip=pmag.get_tilt(gdec,ginc,bdec,binc)
                #    else:
                #        dipdir,dip=0,0
                #    ErSampRec={}
                #    ErSampRec['er_location_name']=MagRec['er_location_name']
                #    ErSampRec['er_sample_name']=MagRec['er_sample_name']
                #    ErSampRec['er_site_name']=MagRec['er_site_name']
                #    ErSampRec['sample_azimuth']='%7.1f'%(az)
                #    ErSampRec['sample_dip']='%7.1f'%(pl)
                #    ErSampRec['sample_bed_dip_direction']='%7.1f'%(dipdir)
                #    ErSampRec['sample_bed_dip']='%7.1f'%(dip)
                #    ErSampRec['sample_description']='az,pl,dip_dir and dip recalculated from [c,g,b][dec,inc] in ldeo file'
                #    ErSampRec['magic_method_codes']='SO-REC'
                #    ErSamps.append(ErSampRec)
                #    Samps.append(ErSampRec['er_sample_name'])
                MagRec["measurement_dec"] = rec[5]
                MagRec["measurement_inc"] = rec[6]
                MagRec["measurement_chi"] = '%10.3e' % (
                    float(rec[11]) * 1e-5
                )  #convert to SI (assume Bartington, 10-5 SI)
                #MagRec["magic_instrument_codes"]=rec[2]
                #MagRec["er_analyst_mail_names"]=""
                MagRec["er_citation_names"] = "This study"
                MagRec["magic_method_codes"] = meas_type
                if demag == "AF":
                    if methcode != "LP-AN-ARM":
                        MagRec["treatment_ac_field"] = '%8.3e' % (
                            float(rec[1]) * 1e-3)  # peak field in tesla
                        meas_type = "LT-AF-Z"
                        MagRec["treatment_dc_field"] = '0'
                    else:  # AARM experiment
                        if treat[1][0] == '0':
                            meas_type = "LT-AF-Z"
                            MagRec["treatment_ac_field"] = '%8.3e' % (
                                peakfield)  # peak field in tesla
                        else:
                            meas_type = "LT-AF-I"
                            ipos = int(treat[0]) - 1
                            MagRec["treatment_dc_field_phi"] = '%7.1f' % (
                                dec[ipos])
                            MagRec["treatment_dc_field_theta"] = '%7.1f' % (
                                inc[ipos])
                            MagRec["treatment_dc_field"] = '%8.3e' % (labfield)
                            MagRec["treatment_ac_field"] = '%8.3e' % (
                                peakfield)  # peak field in tesla
                elif demag == "T":
                    if rec[1][0] == ".": rec[1] = "0" + rec[1]
                    treat = rec[1].split('.')
                    if len(treat) == 1: treat.append('0')
                    MagRec["treatment_temp"] = '%8.3e' % (float(rec[1]) + 273.
                                                          )  # temp in kelvin
                    meas_type = "LT-T-Z"
                    MagRec["treatment_temp"] = '%8.3e' % (
                        float(treat[0]) + 273.)  # temp in kelvin
                    if trm == 0:  # demag=T and not trmaq
                        if treat[1][0] == '0':
                            meas_type = "LT-T-Z"
                        else:
                            MagRec["treatment_dc_field"] = '%8.3e' % (
                                labfield
                            )  # labfield in tesla (convert from microT)
                            MagRec["treatment_dc_field_phi"] = '%7.1f' % (
                                phi)  # labfield phi
                            MagRec["treatment_dc_field_theta"] = '%7.1f' % (
                                theta)  # labfield theta
                            if treat[1][0] == '1':
                                meas_type = "LT-T-I"  # in-field thermal step
                            if treat[1][0] == '2':
                                meas_type = "LT-PTRM-I"  # pTRM check
                                pTRM = 1
                            if treat[1][0] == '3':
                                MagRec[
                                    "treatment_dc_field"] = '0'  # this is a zero field step
                                meas_type = "LT-PTRM-MD"  # pTRM tail check
                    else:
                        meas_type = "LT-T-I"  # trm acquisition experiment
                MagRec['magic_method_codes'] = meas_type
                MagRecs.append(MagRec)
    MagOuts = pmag.measurements_methods(MagRecs, noave)
    pmag.magic_write(meas_file, MagOuts, 'magic_measurements')
    print "results put in ", meas_file
    if samp_file != "":
        pmag.magic_write(samp_file, ErSamps, 'er_samples')
        print "sample orientations put in ", samp_file
    if len(SynRecs) > 0:
        pmag.magic_write(synfile, SynRecs, 'er_synthetics')
        print "synthetics put in ", synfile
Exemplo n.º 27
0
def main():
    """
    NAME
        kly4s_magic.py

    DESCRIPTION
        converts files generated by SIO kly4S labview program to MagIC formated
        files for use with PmagPy plotting software

    SYNTAX
        kly4s_magic.py -h [command line options]

    OPTIONS
        -h: prints the help message and quits
        -i: allows interactive input of input/output filenames
        -f FILE: specify .ams input file name
        -fad AZDIP: specify AZDIP file with orientations, will create er_samples.txt file
        -fsa SFILE: specify existing er_samples.txt file with orientation information
        -fsp SPFILE: specify existing er_specimens.txt file for appending 
        -F MFILE: specify magic_measurements output file
        -Fa AFILE: specify rmag_anisotropy output file
        -ocn ORCON:  specify orientation convention: default is #3 below -only with AZDIP file
        -usr USER: specify who made the measurements
        -loc LOC: specify location name for study 
        -ins INST: specify instrument used
        -spc SPEC: specify number of characters to specify specimen from sample
        -ncn NCON:  specify naming convention: default is #1 below

    DEFAULTS
        MFILE: magic_measurements.txt
        AFILE: rmag_anisotropy.txt
        SPFILE: create new er_specimen.txt file
        USER: ""
        LOC: "unknown" 
        INST: "SIO-KLY4S"
        SPEC: 1  specimen name is same as sample (if SPEC is 1, sample is all but last character)
    NOTES:
        Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length) 
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXXYYY:  YYY is sample designation with Z characters from site XXX
            [5] all others you will have to either customize your 
                self or e-mail [email protected] for help.  
       Orientation convention:
            [1] Lab arrow azimuth= azimuth; Lab arrow dip=-dip
                i.e., dip is degrees from vertical down - the hade [default]
            [2] Lab arrow azimuth = azimuth-90; Lab arrow dip = -dip
                i.e., azimuth is strike and dip is hade
            [3] Lab arrow azimuth = azimuth; Lab arrow dip = dip-90
                e.g. dip is degrees from horizontal of drill direction
            [4] Lab arrow azimuth = azimuth; Lab arrow dip = dip 
            [5] Lab arrow azimuth = azimuth; Lab arrow dip = 90-dip 
            [6] all others you will have to either customize your
                self or e-mail [email protected] for help.

    """
    citation='This study'
    cont=0
    ask=0
    samp_con,Z="1",1
    or_con="3" # see orientation_magic.py help message
    inst,specnum="SIO-KLY4S",0
    AniRecs,SpecRecs,SampRecs,MeasRecs=[],[],[],[]
    user,locname,specfile="","unknown","er_specimens.txt"
    AppSpec=0
    sampfile,measfile='','magic_measurements.txt'
    anisfile='rmag_anisotropy.txt'
    azdipfile=""
    dir_path='.'
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1] 
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-usr' in sys.argv:
        ind=sys.argv.index('-usr')
        user=sys.argv[ind+1] 
    if '-ocn' in sys.argv:
        ind=sys.argv.index('-ocn')
        or_con=sys.argv[ind+1] 
    if "-ncn" in sys.argv:
        ind=sys.argv.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 3-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        amsfile=sys.argv[ind+1] 
    else:
        print main.__doc__
        print 'must specify ascii input file '
        sys.exit()
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        measfile=sys.argv[ind+1] 
    if '-Fa' in sys.argv:
        ind=sys.argv.index('-Fa')
        anisfile=sys.argv[ind+1] 
    if '-Fr' in sys.argv:
        ind=sys.argv.index('-Fr')
        routput=sys.argv[ind+1] 
    if '-fsa' in sys.argv:
        ind=sys.argv.index('-fsa')
        sampfile=sys.argv[ind+1] 
    if '-fsp' in sys.argv:
        ind=sys.argv.index('-fsp')
        specfile=sys.argv[ind+1] 
        AppSpec=1
    if '-fad' in sys.argv:
        ind=sys.argv.index('-fad')
        azdipfile=dir_path+"/"+sys.argv[ind+1]
        azfile=open(azdipfile,'rU')
        AzDipDat=azfile.readlines() 
    if '-loc' in sys.argv:
        ind=sys.argv.index('-loc')
        locname=sys.argv[ind+1] 
    if '-spc' in sys.argv:
        ind=sys.argv.index('-spc')
        specnum=-(int(sys.argv[ind+1]))
        #if specnum!=0:specnum=-specnum
    specfile=dir_path+'/'+specfile
    sampfile=dir_path+'/'+sampfile
    measfile=dir_path+'/'+measfile
    anisfile=dir_path+'/'+anisfile
    amsfile=dir_path+'/'+amsfile
    try:
        input=open(amsfile,'rU')
    except:
        print 'Error opening file: ', amsfile
        sys.exit()
    SpecRecs,speclist=[],[]
    if AppSpec==1:
        try:
            SpecRecs,filetype=pmag.magic_read(specfile) # append new records to existing
            if len(SpecRecs)>0:
                for spec in SpecRecs:
                    if spec['er_specimen_name'] not in speclist:speclist.append(spec['er_specimen_name'])
        except IOError:
            print 'trouble opening ',specfile 
    Data=input.readlines()
    samps=[]
    if sampfile!=dir_path+'/': 
        samps,file_type=pmag.magic_read(sampfile)
        SO_methods=[]
        for rec in samps:
           if "magic_method_codes" in rec.keys():
               methlist=rec["magic_method_codes"].replace(" ","").split(":")
               for meth in methlist:
                   if "SO" in meth and "SO-POM" not in meth and "SO-GT5" not in meth and "SO-ASC" not in meth and "SO-BAD" not in meth:
                       if meth not in SO_methods: SO_methods.append(meth)
    #
        SO_priorities=pmag.set_priorities(SO_methods,ask)
    for line in Data:
      rec=line.split()
      if len(rec)>0:
        AniRec,SpecRec,SampRec,SiteRec,MeasRec={},{},{},{},{}
        specname=rec[0]
        if specnum!=0:
            sampname=specname[:specnum]
        else:
            sampname=specname
        site=pmag.parse_site(sampname,samp_con,Z)
        AniRec['er_location_name']=locname
        AniRec['er_citation_names']="This study"
        AniRec['magic_instrument_codes']=inst
        method_codes=['LP-X','AE-H','LP-AN-MS']
        AniRec['magic_experiment_name']=specname+":"+"LP-AN-MS"
        AniRec['er_analyst_mail_names']=user
        AniRec['er_site_name']=site
        AniRec['er_sample_name']=sampname
        AniRec['er_specimen_name']=specname
        labaz,labdip,bed_dip_direction,bed_dip="","","",""
        if azdipfile!="":
            for key in AniRec.keys():SampRec[key]=AniRec[key]
            for oline in AzDipDat: # look for exact match first
                orec=oline.replace('\n','').split()
                if orec[0].upper() in specname.upper(): # we have a match
                   labaz,labdip=pmag.orient(float(orec[1]),float(orec[2]),or_con)  
                   bed_dip_direction=float(orec[3])-90. # assume dip to right of strike
                   bed_dip=float(orec[4])
                   break
            if labaz=="":  # found no exact match - now look at sample level
                for oline in AzDipDat: 
                    orec=oline.split()
                    if orec[0].upper() == sampname.upper(): # we have a match
                       labaz,labdip=pmag.orient(float(orec[1]),float(orec[2]),or_con)  
                       bed_dip_direction=float(orec[3])-90. # assume dip to right of strike
                       bed_dip=float(orec[4])
                       break
            if labaz=="":  # found no exact match - now look at sample level
                print 'found no orientation data - will use specimen coordinates' 
                raw_input("<return> to continue")
            else:
                for key in AniRec.keys():SampRec[key]=AniRec[key]
                SampRec['sample_azimuth']='%7.1f'%(labaz)
                SampRec['sample_dip']='%7.1f'%(labdip)
                SampRec['sample_bed_dip_direction']='%7.1f'%(bed_dip_direction)
                SampRec['sample_bed_dip']='%7.1f'%(bed_dip)
                SampRecs.append(SampRec)
        elif sampfile!=dir_path+'/':
           redo,p=1,0
           orient={}
           if len(SO_methods)==1:
                az_type=SO_methods[0]
                orient=pmag.find_samp_rec(AniRec["er_sample_name"],samps,az_type)
                if orient['sample_azimuth']!="":
                    method_codes.append(az_type)
                else:
                    print "no orientation data for ",AniRec["er_sample_name"],labaz
                    orient["sample_azimuth"]=""
                    orient["sample_dip"]=""
                    orient["sample_bed_dip_direction"]=""
                    orient["sample_bed_dip"]=""
                    noorient=1
                    method_codes.append("SO-NO")
                    redo=0
                redo=0
           while redo==1:
                if p>=len(SO_priorities):
                    print "no orientation data for ",AniRec["er_sample_name"],labaz
                    orient["sample_azimuth"]=""
                    orient["sample_dip"]=""
                    orient["sample_bed_dip_direction"]=""
                    orient["sample_bed_dip"]=""
                    noorient=1
                    method_codes.append("SO-NO")
                    redo=0
                else:
                    az_type=SO_methods[SO_methods.index(SO_priorities[p])]
                    orient=pmag.find_samp_rec(AniRec["er_sample_name"],samps,az_type)
                    if orient["sample_azimuth"]  !="":
                        method_codes.append(az_type)
                        redo=0
                    noorient=0
                p+=1
           if orient['sample_azimuth']!="":labaz=float(orient['sample_azimuth'])
           if orient['sample_dip']!="":labdip=float(orient['sample_dip'])
           if "sample_bed_dip_direction" in orient.keys() and orient['sample_bed_dip_direction']!="": bed_dip_direction=float(orient['sample_bed_dip_direction'])
           if "sample_bed_dip" in orient.keys() and orient['sample_bed_dip']!="": sample_bed_dip=float(orient['sample_bed_dip'])
        for key in AniRec.keys():SpecRec[key]=AniRec[key]
        for key in AniRec.keys():MeasRec[key]=AniRec[key]
        AniRec['anisotropy_type']="AMS"
        AniRec['anisotropy_n']="192"
        AniRec['anisotropy_s1']=rec[1]
        AniRec['anisotropy_s2']=rec[2]
        AniRec['anisotropy_s3']=rec[3]
        AniRec['anisotropy_s4']=rec[4]
        AniRec['anisotropy_s5']=rec[5]
        AniRec['anisotropy_s6']=rec[6]
        AniRec['anisotropy_sigma']=rec[7]
        AniRec['anisotropy_tilt_correction']='-1'
        AniRec['anisotropy_unit']='Normalized by trace'
        SpecRec['specimen_volume']='%8.3e'%(1e-6*float(rec[12])) # volume from cc to m^3
        MeasRec['measurement_flag']='g' # good
        MeasRec['measurement_standard']='u' # unknown
        date=rec[14].split('/')
        if int(date[2])>80:
           date[2]='19'+date[2]
        else: 
           date[2]='20'+date[2]
        datetime=date[2]+':'+date[0]+':'+date[1]+":"
        datetime=datetime+rec[15]
        MeasRec['measurement_number']='1'
        MeasRec['measurement_date']=datetime 
        MeasRec['measurement_lab_field_ac']='%8.3e'%(4*math.pi*1e-7*float(rec[11])) # convert from A/m to T
        MeasRec['measurement_temp']="300" # assumed room T in kelvin
        MeasRec['measurement_chi_volume']=rec[8]
        MeasRec['measurement_description']='Bulk measurement'
        MeasRec['magic_method_codes']='LP-X'
        if SpecRec['er_specimen_name'] not in speclist: # add to list
            speclist.append(SpecRec['er_specimen_name'])
            SpecRecs.append(SpecRec)
        MeasRecs.append(MeasRec)
        methods=""
        for meth in method_codes:
            methods=methods+meth+":"
        AniRec["magic_method_codes"]=methods[:-1]  # get rid of annoying spaces in Anthony's export files
        AniRecs.append(AniRec)
        if labaz!="": # have orientation info
            AniRecG,AniRecT={},{}
            for key in AniRec.keys():AniRecG[key]=AniRec[key]
            for key in AniRec.keys():AniRecT[key]=AniRec[key]
            sbar=[]
            sbar.append(float(AniRec['anisotropy_s1']))
            sbar.append(float(AniRec['anisotropy_s2']))
            sbar.append(float(AniRec['anisotropy_s3']))
            sbar.append(float(AniRec['anisotropy_s4']))
            sbar.append(float(AniRec['anisotropy_s5']))
            sbar.append(float(AniRec['anisotropy_s6']))
            sbarg=pmag.dosgeo(sbar,labaz,labdip)
            AniRecG["anisotropy_s1"]='%12.10f'%(sbarg[0])
            AniRecG["anisotropy_s2"]='%12.10f'%(sbarg[1])
            AniRecG["anisotropy_s3"]='%12.10f'%(sbarg[2])
            AniRecG["anisotropy_s4"]='%12.10f'%(sbarg[3])
            AniRecG["anisotropy_s5"]='%12.10f'%(sbarg[4])
            AniRecG["anisotropy_s6"]='%12.10f'%(sbarg[5])
            AniRecG["anisotropy_tilt_correction"]='0'
            AniRecs.append(AniRecG)
            if bed_dip!="" and bed_dip!=0: # have tilt correction
                sbart=pmag.dostilt(sbarg,bed_dip_direction,bed_dip)
                AniRecT["anisotropy_s1"]='%12.10f'%(sbart[0])
                AniRecT["anisotropy_s2"]='%12.10f'%(sbart[1])
                AniRecT["anisotropy_s3"]='%12.10f'%(sbart[2])
                AniRecT["anisotropy_s4"]='%12.10f'%(sbart[3])
                AniRecT["anisotropy_s5"]='%12.10f'%(sbart[4])
                AniRecT["anisotropy_s6"]='%12.10f'%(sbart[5])
                AniRecT["anisotropy_tilt_correction"]='100'
                AniRecs.append(AniRecT)
    pmag.magic_write(anisfile,AniRecs,'rmag_anisotropy')
    pmag.magic_write(measfile,MeasRecs,'magic_measurements')
    pmag.magic_write(specfile,SpecRecs,'er_specimens')
    print 'anisotropy data saved in ',anisfile
    print 'measurement data saved in ',measfile
    if AppSpec==1:
        print 'new specimen information  added  to ',specfile
    else:
        print 'specimen information  saved in new ',specfile
    if azdipfile!="":
        sampfile='er_samples.txt'
        pmag.magic_write(sampfile,SampRecs,'er_samples')
        print 'sample data saved in ',sampfile
Exemplo n.º 28
0
def main():
    """
    NAME
        susar4-asc_magic.py

    DESCRIPTION
        converts ascii files generated by SUSAR ver.4.0 to MagIC formated
        files for use with PmagPy plotting software

    SYNTAX
        susar4-asc_magic.py -h [command line options]

    OPTIONS
        -h: prints the help message and quits
        -f FILE: specify .asc input file name
        -F MFILE: specify magic_measurements output file
        -Fa AFILE: specify rmag_anisotropy output file
        -Fr RFILE: specify rmag_results output file
        -Fs SFILE: specify er_specimens output file with location, sample, site, etc. information
        -usr USER: specify who made the measurements
        -loc LOC: specify location name for study 
        -ins INST: specify instrument used
        -spc SPEC: specify number of characters to specify specimen from sample
        -ncn NCON:  specify naming convention: default is #2 below
        -k15 : specify static 15 position mode - default is spinning
        -new : replace all existing magic files

    DEFAULTS
        AFILE: rmag_anisotropy.txt
        RFILE: rmag_results.txt
        SFILE: default is to create new er_specimen.txt file
        USER: ""
        LOC: ""
        INST: ""
        SPEC: 0  sample name is same as site (if SPEC is 1, sample is all but last character)
        appends to  'er_specimens.txt, er_samples.txt, er_sites.txt' files
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 

    """
    citation='This study'
    cont=0
    samp_con,Z="1",1
    AniRecSs,AniRecs,SpecRecs,SampRecs,SiteRecs,MeasRecs=[],[],[],[],[],[]
    user,locname,specfile="","unknown","er_specimens.txt"
    isspec,inst,specnum='0',"PGL-KLY3",0
    spin,new=1,0
    dir_path='.'
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1] 
    aoutput,routput,moutput=dir_path+'/rmag_anisotropy.txt',dir_path+'/rmag_results.txt',dir_path+'/magic_measurements.txt'
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-usr' in sys.argv:
        ind=sys.argv.index('-usr')
        user=sys.argv[ind+1] 
    if "-ncn" in sys.argv:
        ind=sys.argv.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="7"
    if '-k15' in sys.argv:spin=0
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        ascfile=dir_path+'/'+sys.argv[ind+1] 
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        moutput=dir_path+'/'+sys.argv[ind+1] 
    if '-Fa' in sys.argv:
        ind=sys.argv.index('-Fa')
        aoutput=dir_path+'/'+sys.argv[ind+1] 
    if '-Fr' in sys.argv:
        ind=sys.argv.index('-Fr')
        routput=dir_path+'/'+sys.argv[ind+1] 
    if '-Fs' in sys.argv:
        ind=sys.argv.index('-Fs')
        specfile=dir_path+'/'+sys.argv[ind+1] 
        isspec='1'
    elif '-loc' in sys.argv:
        ind=sys.argv.index('-loc')
        locname=sys.argv[ind+1] 
    if '-spc' in sys.argv:
        ind=sys.argv.index('-spc')
        specnum=-(int(sys.argv[ind+1]))
    if isspec=="1": 
        specs,file_type=pmag.magic_read(specfile)
    specnames,sampnames,sitenames=[],[],[]
    if '-new' not in sys.argv: # see if there are already specimen,sample, site files lying around
        try:
            SpecRecs,file_type=pmag.magic_read(dir_path+'/er_specimens.txt')
            for spec in SpecRecs:
                if spec['er_specimen_name'] not in specnames:specnames.append(samp['er_specimen_name'])
        except:
            SpecRecs,specs=[],[]
        try:
            SampRecs,file_type=pmag.magic_read(dir_path+'/er_samples.txt')
            for samp in SampRecs:
                if samp['er_sample_name'] not in sampnames:sampnames.append(samp['er_sample_name'])
        except:
            sampnames,SampRecs=[],[]
        try:
            SiteRecs,file_type=pmag.magic_read(dir_path+'/er_sites.txt')
            for site in SiteRecs:
                if site['er_site_names'] not in sitenames:sitenames.append(site['er_site_name'])
        except:
            sitenames,SiteRecs=[],[]
    try:
        input=open(ascfile,'rU')
    except:
        print 'Error opening file: ', ascfile
    Data=input.readlines()
    k=0
    while k<len(Data):
        line = Data[k]
        words=line.split()
        print words
        if "ANISOTROPY" in words: # first line of data for the spec
            MeasRec,AniRec,SpecRec,SampRec,SiteRec={},{},{},{},{}
            specname=words[0]
            AniRec['er_specimen_name']=specname
            if isspec=="1":
                for spec in specs:
                    if spec['er_specimen_name']==specname:
                        AniRec['er_sample_name']=spec['er_sample_name']
                        AniRec['er_site_name']=spec['er_site_name']
                        AniRec['er_location_name']=spec['er_location_name']
                        break
            elif isspec=="0":
                AniRec['er_sample_name']=specname[:specnum]
		SpecRec['er_specimen_name']=specname
		SpecRec['er_sample_name']=specname[:specnum]
		SampRec['er_sample_name']=specname[:specnum]
		SiteRec['er_sample_name']=specname[:specnum]
		SiteRec['site_description']='s'
                AniRec['er_site_name']=pmag.parse_site(AniRec['er_sample_name'],samp_con,Z)
                SpecRec['er_site_name']=pmag.parse_site(AniRec['er_sample_name'],samp_con,Z)
                SampRec['er_site_name']=pmag.parse_site(AniRec['er_sample_name'],samp_con,Z)
                SiteRec['er_site_name']=pmag.parse_site(AniRec['er_sample_name'],samp_con,Z)
                AniRec['er_location_name']=locname
                SpecRec['er_location_name']=locname
                SampRec['er_location_name']=locname
                SiteRec['er_location_name']=locname
                AniRec['er_citation_names']="This study"
                SpecRec['er_citation_names']="This study"
                SampRec['er_citation_names']="This study"
                SiteRec['er_citation_names']="This study"
            AniRec['er_citation_names']="This study"
            AniRec['magic_instrument_codes']=inst
            AniRec['magic_method_codes']="LP-X:AE-H:LP-AN-MS"
            AniRec['magic_experiment_names']=specname+":"+"LP-AN-MS"
            AniRec['er_analyst_mail_names']=user
            for key in AniRec.keys():MeasRec[key]=AniRec[key]
            MeasRec['measurement_flag']='g'
            AniRec['anisotropy_flag']='g'
            MeasRec['measurement_standard']='u'
            MeasRec['measurement_description']='Bulk sucsecptibility measurement'
            AniRec['anisotropy_type']="AMS"
            AniRec['anisotropy_unit']="Normalized by trace - bulk in measurements table"
            AniRec['anisotropy_unit']='SI'
            if spin==1:
                AniRec['anisotropy_n']="192"
            else:
                AniRec['anisotropy_n']="15"
        if 'Azi' in words and isspec=='0': 
            SampRec['sample_azimuth']=words[1]
            labaz=float(words[1])
        if 'Dip' in words:
            SampRec['sample_dip']='%7.1f'%(-float(words[1]))
            SpecRec['specimen_vol']='%8.3e'%(float(words[10])*1e-6) # convert actual volume to m^3 from cm^3
            labdip=float(words[1])-90.
        if 'T1' in words and 'F1' in words: 
            k+=2 # read in fourth line down
            line=Data[k]
            rec=line.split()
            dd,dip_direction=0,0
            if len(rec)>0:
                dd=rec[1].split('/')
                dip_direction=int(dd[0])+90
            SampRec['sample_bed_dip_direction']='%i'%(dip_direction)
            SampRec['sample_bed_dip']=dd[1]
            bed_dip=float(dd[1])
        if "Mean" in words:
            k+=4 # read in fourth line down
            line=Data[k]
            rec=line.split()
            if len(rec)>0:
                MeasRec['measurement_chi_volume']=rec[1]
                sigma=.01*float(rec[2])/3.
                AniRec['anisotropy_sigma']='%7.4f'%(sigma)
        if "susceptibilities" in words:  # first part of specimen data
            line=Data[k+2]
            rec=line.split()
            AniRec['anisotropy_s1']='%7.4f'%(float(rec[1])/3.) # eigenvalues sum to unity - not 3
            AniRec['anisotropy_s2']='%7.4f'%(float(rec[2])/3.) 
            AniRec['anisotropy_s3']='%7.4f'%(float(rec[3])/3.)
            k+=2
            line=Data[k]
            rec=line.split()
            AniRec['anisotropy_s4']='%7.4f'%(float(rec[0])/3.) # eigenvalues sum to unity - not 3
            AniRec['anisotropy_s5']='%7.4f'%(float(rec[1])/3.) 
            AniRec['anisotropy_s6']='%7.4f'%(float(rec[2])/3.)
            AniRec['anisotropy_tilt_correction']='-1'
            AniRecs.append(AniRec) 
            MeasRecs.append(MeasRec) 
            if SpecRec['er_specimen_name'] not in specnames:
                SpecRecs.append(SpecRec)
                specnames.append(SpecRec['er_specimen_name'])
            if SampRec['er_sample_name'] not in sampnames:
                SampRecs.append(SampRec)
                sampnames.append(SampRec['er_sample_name'])
            if SiteRec['er_site_name'] not in sitenames:
                SiteRecs.append(SiteRec)
                sitenames.append(SiteRec['er_site_name'])
        k+=1 # skip to next specimen
    pmag.magic_write(aoutput,AniRecs,'rmag_anisotropy')
    print "anisotropy tensors put in ",aoutput
    pmag.magic_write(moutput,MeasRecs,'magic_measurements')
    print "bulk measurements put in ",moutput
    if isspec=="0":
        output=dir_path+"/er_specimens.txt"
        pmag.magic_write(output,SpecRecs,'er_specimens')
        print "specimen info put in ",output
        output=dir_path+"/er_samples.txt"
        pmag.magic_write(output,SampRecs,'er_samples')
        print "sample info put in ",output
        output=dir_path+"/er_sites.txt"
        pmag.magic_write(output,SiteRecs,'er_sites')
        print "site info put in ",output
    print """"
Exemplo n.º 29
0
def main():
    """
    NAME
        CIT_magic.py
 
    DESCRIPTION
        converts CalTech (CIT) .sam  format files to magic_measurements format files

    SYNTAX
        CIT_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -usr USER:   identify user, default is ""
        -f FILE: specify .sam format input file, required
        -fsi SITEFILE : specify file with site names and locations [tab delimited magic file]
        -F FILE: specify output  measurements file, default is magic_measurements.txt
        -Fsp FILE: specify output er_specimens.txt file, default is er_specimens.txt
        -Fsi FILE: specify output er_sites.txt file, default is er_sites.txt
        -n [gm,kg,cc,m3]: specify normalization
        -spc NUM : specify number of characters to designate a  specimen, default = 0
        -ncn NCON: specify naming convention
        -loc LOCNAME : specify location/study name, must have either LOCNAME or SITEFILE or be a synthetic
        -dc B PHI THETA: dc lab field (in micro tesla) and phi,theta, default is none
              NB: use PHI, THETA = -1 -1 to signal that it changes, i.e. in anisotropy experiment
        -ac B : peak AF field (in mT) for ARM acquisition, default is none

    INPUT
        Best to put separate experiments (all AF, thermal, thellier, trm aquisition, Shaw, etc.) 

    NOTES:
 
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 
    """
#        
#
    norm='cc'
    samp_con,Z='3',1        
    meas_file='magic_measurements.txt'
    spec_file='er_specimens.txt'
    samp_file='er_samples.txt'
    site_file='er_sites.txt'
    ErSpecs,ErSamps,ErSites,ErLocs,ErCits=[],[],[],[],[]
    MeasRecs=[]
    specnum,units,locname=0,"1","unknown"
    citation="This study"
    dir_path='.'
    args=sys.argv
    if '-WD' in args:
        ind=args.index("-WD")
        dir_path=args[ind+1]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind=args.index("-usr")
        user=args[ind+1]
    if '-F' in args:
        ind=args.index("-F")
        meas_file=args[ind+1]
    if '-Fsp' in args:
        ind=args.index("-Fsp")
        spec_file=args[ind+1]
    if '-Fsa' in args:
        ind=args.index("-Fsa")
        samp_file=args[ind+1]
    if '-loc' in args:
        ind=args.index("-loc")
        locname=args[ind+1]
    if '-spc' in args:
        ind=args.index("-spc")
        specnum=-int(args[ind+1])
    if '-n' in args:
        ind=args.index("-n")
        norm=args[ind+1]
    if "-ncn" in args:
        ind=args.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else: 
                Z=samp_con.split("-")[1]
                samp_con="4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="7"
    if '-f' in args:
        ind=args.index("-f")
        magfile=args[ind+1]
    magfile=dir_path+'/'+magfile
    spec_file=dir_path+'/'+spec_file
    samp_file=dir_path+'/'+samp_file
    site_file=dir_path+'/'+site_file
    meas_file=dir_path+'/'+meas_file
    try:
        input=open(magfile,'r')
    except:
        print "bad sam file name"
        sys.exit()
    File=input.readlines()
    sids,ln,format=[],0,'CIT'
    formats=['CIT','2G','APP','JRA']
    ErLocRec={}
    ErLocRec["er_location_name"]=locname
    ErLocRec["er_citation_name"]=citation
    comment=File[ln]
    if comment=='CIT':
       format=comment
       ln+=1
    comment=File[ln]
    print comment
    ln+=1
    specimens,samples,sites=[],[],[]
    if format=='CIT':
        line=File[ln].split()
        site_lat=line[0]
        site_lon=line[1]
        ErLocRec["location_begin_lat"]=site_lat
        ErLocRec["location_begin_lon"]=site_lon
        ErLocRec["location_end_lat"]=site_lat
        ErLocRec["location_end_lon"]=site_lon
        ErLocs.append(ErLocRec)
        Cdec=float(line[2])
        if len(line)>4:
            fa_az=line[3]
            fa_pl=line[4]
        if len(line)>6:
            bed_dip_dir='%7.1f'%(float(line[5]+90.))
            bed_dip=line[6]
        for k in range(ln+1,len(File)):
            line=File[k]
            rec=line.split()
            specimen=rec[0]
            specimens.append(specimen)
    else:
        print 'file type not yet supported'
        sys.exit()
    for specimen in specimens:
        ErSpecRec,ErSampRec,ErSiteRec={},{},{}
        if specnum!=0:
            sample=specimen[:specnum]
        else: sample=specimen
        site=pmag.parse_site(sample,samp_con,Z)
        ErSpecRec['er_specimen_name']=specimen
        ErSpecRec['er_sample_name']=sample
        ErSpecRec['er_site_name']=site
        ErSpecRec['er_location_name']=locname
        ErSpecRec['er_citation_name']=citation
        ErSampRec['er_sample_name']=sample
        ErSampRec['er_site_name']=site
        ErSampRec['er_location_name']=locname
        ErSampRec['er_citation_name']=citation
        for k in range(ln+1,len(File)):
            line=File[k]
            rec=line.split()
            specimen=rec[0]
            specimens.append(specimen)
    for specimen in specimens:
        ErSpecRec,ErSampRec,ErSiteRec={},{},{}
        if specnum!=0:
            sample=specimen[:specnum]
        else: sample=specimen
        site=pmag.parse_site(sample,samp_con,Z)
        ErSpecRec['er_specimen_name']=specimen
        ErSpecRec['er_sample_name']=sample
        ErSpecRec['er_site_name']=site
        ErSpecRec['er_location_name']=locname
        ErSpecRec['er_citation_name']=citation
        ErSampRec['er_sample_name']=sample
        ErSampRec['er_site_name']=site
        ErSampRec['er_location_name']=locname
        ErSampRec['er_citation_name']=citation
        ErSiteRec['er_site_name']=site
        ErSiteRec['er_location_name']=locname
        ErSiteRec['er_citation_name']=citation
        ErSiteRec['site_lat']=site_lat
        ErSiteRec['site_lon']=site_lon
        f=open(dir_path+'/'+specimen,'rU')
        Lines=f.readlines()
        comment=Lines[0][10:]
        if len(line)>2:comment=line[2]
        info=Lines[1].split()
        vol=float(info[-1])
        if vol!=1.0:
            if norm=='cc':units="1"
            if norm=='m3':units="2"
            ErSampRec['specimen_weight']=""
            if units=="1" or "":
                ErSampRec['specimen_volume']='%10.3e'%(vol*1e-6)
            else: 
                ErSampRec['specimen_volume']='%10.3e'%(vol)
        else:
            if norm=='cc':units="1"
            if norm=='m3':units="2"
            ErSampRec['specimen_volume']=""
            if units=="1" or "":
                ErSampRec['specimen_weight']='%10.3e'%(vol*1e-3)
            else: 
                ErSampRec['specimen_weight']='%10.3e'%(vol)
        dip=float(info[-2])
        dip_direction=float(info[-3])+Cdec+90.
        sample_dip=-float(info[-4])
        sample_azimuth=float(info[-5])+Cdec-90.
        if len(info)>5:
            ErSampRec['sample_height']=info[-6]
        else:
            ErSampRec['sample_height']='0'
        ErSampRec['sample_azimuth']='%7.1f'%(sample_azimuth)
        ErSampRec['sample_dip']='%7.1f'%(sample_dip)
        ErSampRec['sample_bed_dip']='%7.1f'%(dip)
        ErSampRec['sample_bed_dip_direction']='%7.1f'%(dip_direction)
        ErSampRec['sample_class']=''
        ErSampRec['sample_type']=''
        ErSampRec['sample_lithology']=''
        if Cdec!=0 or Cdec!="":
            ErSampRec['magic_method_codes']='SO-CMD-NORTH'
        else:
            ErSampRec['magic_method_codes']='SO-MAG'
        for line in Lines[2:len(Lines)-1]:
            MeasRec=ErSpecRec.copy()
            treat_type=line[0:3]
            treat=line[3:6]
            if treat_type.strip()=='NRM' or treat=="   ":
                MeasRec['magic_method_codes']='LT-NO'
                MeasRec['measurement_temp']='273'
                MeasRec['treatment_temp']='273'
                MeasRec['treatment_dc_field']='0'
                MeasRec['treatment_ac_field']='0'
            elif treat_type.strip()=='AF':
                MeasRec['magic_method_codes']='LT-AF-Z'
                MeasRec['measurement_temp']='273'
                MeasRec['treatment_temp']='273'
                MeasRec['treatment_dc_field']='0'
                MeasRec['treatment_ac_field']='%10.3e'%(float(treat)*1e-3)
            elif treat_type.strip()=='TT':
                MeasRec['magic_method_codes']='LT-T-Z'
                MeasRec['measurement_temp']='273'
                MeasRec['treatment_temp']='%7.1f'%(float(treat)+273)
                MeasRec['treatment_dc_field']='0'
                MeasRec['treatment_ac_field']='0'
            else:
                print "trouble with your treatment steps"
            MeasRec['measurement_dec']=line[46:51]
            MeasRec['measurement_inc']=line[52:58]
            int='%8.2e'%(float(line[31:39])*vol*1e-3) # convert to Am2
            MeasRec['measurement_magn_moment']=int
            MeasRec['measurement_x_sd']='%8.2e'%(float(line[58:67])*1e-8) #(convert e-5emu to Am2)
            MeasRec['measurement_y_sd']='%8.2e'%(float(line[67:76])*1e-8)
            MeasRec['measurement_z_sd']='%8.2e'%(float(line[76:85])*1e-8)
            MeasRec['measurement_csd']='%7.1f'%(eval(line[41:46]))
            MeasRec['magic_instrument_codes']=line[85:]
            MeasRecs.append(MeasRec)
        ErSpecs.append(ErSpecRec)
        if sample not in samples:
            samples.append(sample)
            ErSamps.append(ErSampRec)
        site=pmag.parse_site(sample,samp_con,Z)
        if site not in sites:
            sites.append(site)
            ErSites.append(ErSiteRec)
    pmag.magic_write(spec_file,ErSpecs,'er_specimens')
    print 'specimens stored in ',spec_file
    pmag.magic_write(samp_file,ErSamps,'er_samples')
    print 'samples stored in ',samp_file
    pmag.magic_write(site_file,ErSites,'er_sites')
    Fixed=pmag.measurements_methods(MeasRecs,0)
    pmag.magic_write(meas_file,Fixed,'magic_measurements')
    print 'data stored in ',meas_file
Exemplo n.º 30
0
def main():
    """
    NAME
        mag_magic.py
 
    DESCRIPTION
        converts SIO .mag format files to magic_measurements format files

    SYNTAX
        mag_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -usr USER:   identify user, default is ""
        -f FILE: specify .mag format input file, required
        -fsa SAMPFILE : specify er_samples.txt file relating samples, site and locations names,default is none
        -F FILE: specify output file, default is magic_measurements.txt
        -Fsy: specify er_synthetics file, default is er_sythetics.txt
        -Fsa: specify output er_samples file, default is NONE (only for LDGO formatted files)
        -LP [colon delimited list of protocols, include all that apply]
            AF:  af demag
            S: Shaw method
            T: thermal including thellier but not trm acquisition
            N: NRM only
            TRM: trm acquisition
            ANI: anisotropy experiment
            D: double AF demag
            G: triple AF demag (GRM protocol)
        -spc NUM : specify number of characters to designate a  specimen, default = 0
        -loc LOCNAME : specify location/study name, must have either LOCNAME or SAMPFILE or be a synthetic
        -syn INST TYPE:  sets these specimens as synthetics created at institution INST and of type TYPE
        -ins INST : specify which demag instrument was used (e.g, SIO-Suzy or SIO-Odette),default is ""
        -dc B PHI THETA: dc lab field (in micro tesla) and phi,theta, default is none
              NB: use PHI, THETA = -1 -1 to signal that it changes, i.e. in anisotropy experiment
        -ac B : peak AF field (in mT) for ARM acquisition, default is none
        -FT [SIO,LDGO] : file type.  default is SIO (.mag file format)
        -ncn NCON:  specify naming convention: default is #1 below
        -A: don't average replicate measurements
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail [email protected] for help.
 
            [8] synthetic - has no site name
            [9] ODP naming convention 
    INPUT
        Best to put separate experiments (all AF, thermal, thellier, trm aquisition, Shaw, etc.) in 
           seperate .mag files (eg. af.mag, thermal.mag, etc.)

        Format of SIO .mag files:   
        Spec Treat CSD Intensity Declination Inclination [optional metadata string]
        
        
        Spec: specimen name
        Treat:  treatment step
            XXX T in Centigrade
            XXX AF in mT
            for special experiments:
              Thellier:
                XXX.0  first zero field step
                XXX.1  first in field step [XXX.0 and XXX.1 can be done in any order]
                XXX.2  second in-field step at lower temperature (pTRM check)
                XXX.3  second zero-field step after infield (pTRM check step)
                       XXX.3 MUST be done in this order [XXX.0, XXX.1 [optional XXX.2] XXX.3]
              AARM:
                X.00  baseline step (AF in zero bias field - high peak field)
                X.1   ARM step (in field step)  where
                   X is the step number in the 15 position scheme 
                      (see Appendix to Lecture 13 - Lectures in Paleomagnetism, 2007)
              TRM:
                XXX.YYY  XXX is temperature step of total TRM
                         YYY is dc field in microtesla

              Shaw:
                XXX.YY   XXX is AF field
                    YY=00 is AF of NRM
                    YY=01 is AF of ARM1
                    YY=02 is AF of TRM
                    YY=03 is AF of ARM2
                specify temperature and field of Total TRM step on command line
         
         Intensity assumed to be total moment in 10^3 Am^2 (emu)
         Declination:  Declination in specimen coordinate system
         Inclination:  Declination in specimen coordinate system

         Optional metatdata string:  mm/dd/yy;hh:mm;[dC,mT];xx.xx;UNITS;USER;INST;NMEAS
             hh in 24 hours.  
             dC or mT units of treatment XXX (see Treat above) for thermal or AF respectively
             xx.xxx   DC field
             UNITS of DC field (microT, mT)
             INST:  instrument code, number of axes, number of positions (e.g., G34 is 2G, three axes, 
                    measured in four positions)
             NMEAS: number of measurements in a single position (1,3,200...)
       
      Format of LDGO files:   
        SPEC TREAT INST CSD Intensity CDECL CINCL [GDECL GINCL BDECL BINCL SUSC ]
     
    """
# initialize some stuff
    infile_type="mag"
    noave=0
    methcode,inst="",""
    phi,theta,peakfield,labfield=0,0,0,0
    pTRM,MD,samp_con,Z=0,0,'1',1
    dec=[315,225,180,135,45,90,270,270,270,90,180,180,0,0,0]
    inc=[0,0,0,0,0,-45,-45,0,45,45,45,-45,-90,-45,45]
    missing=1
    demag="N"
    er_location_name=""
    citation='This study'
    args=sys.argv
    methcode="LP-NO"
    fmt='old'
    syn=0
    synfile='er_synthetics.txt'
    samp_file,ErSamps='',[]
    trm=0
    irm=0
    specnum=0
#
# get command line arguments
#
    meas_file="magic_measurements.txt"
    user=""
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind=args.index("-usr")
        user=args[ind+1]
    if '-F' in args:
        ind=args.index("-F")
        meas_file=args[ind+1]
    if '-Fsy' in args:
        ind=args.index("-Fsy")
        synfile=args[ind+1]
    if '-Fsa' in args:
        ind=args.index("-Fsa")
        samp_file=args[ind+1]
        try:
            open(samp_file,'rU')
            ErSamps,file_type=pmag.magic_read(samp_file)
            print 'sample information will be appended to new er_samples.txt file'
        except:
            print 'sample information will be stored in new er_samples.txt file'
    if '-f' in args:
        ind=args.index("-f")
        magfile=args[ind+1]
        try:
            input=open(magfile,'rU')
        except:
            print "bad mag file name"
            sys.exit()
    else: 
        print "mag_file field is required option"
        print main.__doc__
        sys.exit()
    if "-dc" in args:
        ind=args.index("-dc")
        labfield=float(args[ind+1])*1e-6
        phi=float(args[ind+2])
        theta=float(args[ind+3])
    if "-ac" in args:
        ind=args.index("-ac")
        peakfield=float(args[ind+1])*1e-3
    if "-spc" in args:
        ind=args.index("-spc")
        specnum=int(args[ind+1])
        if specnum!=0:specnum=-specnum
    if "-loc" in args:
        ind=args.index("-loc")
        er_location_name=args[ind+1]
    if "-fsa" in args:
        ind=args.index("-fsa")
        Samps,file_type=pmag.magic_read(args[ind+1])
    if '-syn' in args:
        syn=1
        ind=args.index("-syn")
        institution=args[ind+1]
        syntype=args[ind+2]
        if '-fsy' in args:
            ind=args.index("-fsy")
            synfile=args[ind+1]
    if "-ins" in args:
        ind=args.index("-ins")
        inst=args[ind+1]
    if '-FT' in args:
        ind=args.index("-FT")
        FT=args[ind+1]
        if FT=="LDGO":infile_type="ldgo" # default is "mag"
    if "-A" in args: noave=1
    if "-ncn" in args:
        ind=args.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print "option [4] must be in form 4-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print "option [7] must be in form 7-Z where Z is an integer"
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
    if '-LP' in args:
        ind=args.index("-LP")
        codelist=args[ind+1]
        codes=codelist.split(':')
        if "AF" in codes:
            demag='AF' 
            if'-dc' not in args: methcode="LT-AF-Z"
            if'-dc' in args: methcode="LT-AF-I"
        if "T" in codes:
            demag="T"
            if '-dc' not in args: methcode="LT-T-Z"
            if '-dc' in args: methcode="LT-T-I"
        if "I" in codes:
            methcode="LP-IRM"
        if "S" in codes: 
            demag="S"
            methcode="LP-PI-TRM:LP-PI-ALT-AFARM"
            trm_labfield=labfield
            ans=raw_input("DC lab field for ARM step: [50uT] ")
            if ans=="":
                arm_labfield=50e-6
            else: 
                arm_labfield=float(ans)*1e-6
            ans=raw_input("temperature for total trm step: [600 C] ")
            if ans=="":
                trm_peakT=600+273 # convert to kelvin
            else: 
                trm_peakT=float(ans)+273 # convert to kelvin
        if "G" in codes: methcode="LT-AF-G"
	if "D" in codes: methcode="LT-AF-D"
        if "TRM" in codes: 
            demag="T"
            trm=1
    if demag=="T" and "ANI" in codes:
        methcode="LP-AN-TRM"
    if demag=="AF" and "ANI" in codes:
        methcode="LP-AN-ARM"
        if labfield==0: labfield=50e-6
        if peakfield==0: peakfield=.180
    SynRecs,MagRecs=[],[]
    version_num=pmag.get_version()
    if infile_type=="mag":
        for line in input.readlines():
            instcode=""
            if len(line)>2:
                SynRec={}
                MagRec={}
                MagRec['er_location_name']=er_location_name
                MagRec['magic_software_packages']=version_num
                MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
                MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
                MagRec["treatment_ac_field"]='0'
                MagRec["treatment_dc_field"]='0'
                MagRec["treatment_dc_field_phi"]='0'
                MagRec["treatment_dc_field_theta"]='0'
                meas_type="LT-NO"
                rec=line.split()
                if len(rec)>6:
                  code1=rec[6].split(';') # break e.g., 10/15/02;7:45 indo date and time
                  if len(code1)==2: # old format with AM/PM
                    missing=0
                    code2=code1[0].split('/') # break date into mon/day/year
                    code3=rec[7].split(';') # break e.g., AM;C34;200  into time;instr/axes/measuring pos;number of measurements
                    yy=int(code2[2])
                    if yy <90:
                        yyyy=str(2000+yy)
                    else: yyyy=str(1900+yy)
                    mm=int(code2[0])
                    if mm<10:
                        mm="0"+str(mm)
                    else: mm=str(mm)
                    dd=int(code2[1])
                    if dd<10:
                        dd="0"+str(dd)
                    else: dd=str(dd)
                    time=code1[1].split(':')
                    hh=int(time[0])
                    if code3[0]=="PM":hh=hh+12
                    if hh<10:
                        hh="0"+str(hh)
                    else: hh=str(hh)
                    min=int(time[1])
                    if min<10:
                       min= "0"+str(min)
                    else: min=str(min)
                    MagRec["measurement_date"]=yyyy+":"+mm+":"+dd+":"+hh+":"+min+":00.00"
                    MagRec["measurement_time_zone"]='SAN'
                    if inst=="":
                        if code3[1][0]=='C':instcode='SIO-bubba'
                        if code3[1][0]=='G':instcode='SIO-flo'
                    else:
                        instcode=''
                    MagRec["measurement_positions"]=code3[1][2]
                  elif len(code1)>2: # newest format (cryo7 or later)
                    labfield=0
                    fmt='new'
                    date=code1[0].split('/') # break date into mon/day/year
                    yy=int(date[2])
                    if yy <90:
                        yyyy=str(2000+yy)
                    else: yyyy=str(1900+yy)
                    mm=int(date[0])
                    if mm<10:
                        mm="0"+str(mm)
                    else: mm=str(mm)
                    dd=int(date[1])
                    if dd<10:
                        dd="0"+str(dd)
                    else: dd=str(dd)
                    time=code1[1].split(':')
                    hh=int(time[0])
                    if hh<10:
                        hh="0"+str(hh)
                    else: hh=str(hh)
                    min=int(time[1])
                    if min<10:
                       min= "0"+str(min)
                    else: min=str(min)
                    MagRec["measurement_date"]=yyyy+":"+mm+":"+dd+":"+hh+":"+min+":00.00"
                    MagRec["measurement_time_zone"]='SAN'
                    if inst=="":
                        if code1[6][0]=='C':instcode='SIO-bubba'
                        if code1[6][0]=='G':instcode='SIO-flo'
                    else:
                        instcode=''
                    if len(code1)>1:
                        MagRec["measurement_positions"]=code1[6][2]
                    else:
                        MagRec["measurement_positions"]=code1[7]   # takes care of awkward format with bubba and flo being different
                    if user=="":user=code1[5]
                    if code1[2][-1]=='C': demag="T"
                    if code1[2]=='mT':
                        if methcode=="LP-IRM":
                            labfield=float(code1[3])*1e-3
                            if rec[1][0]!="-":
                                phi,theta=0.,90.
                            else:
                                phi,theta=0.,-90.
                            meas_type="LT-IRM"
                            MagRec["treatment_dc_field"]='%8.3e'%(labfield)
                            MagRec["treatment_dc_field_phi"]='%7.1f'%(phi)
                            MagRec["treatment_dc_field_theta"]='%7.1f'%(theta)
                        else:  
                            demag="AF"
                    labfield=float(code1[3])*1e-6
                    if code1[4]=='microT' and labfield!=0.:
                        phi,theta=0.,90.
                        if demag=="T": meas_type="LT-T-I"
                        if demag=="AF": meas_type="LT-AF-I"
                        MagRec["treatment_dc_field"]='%8.3e'%(labfield)
                        MagRec["treatment_dc_field_phi"]='%7.1f'%(phi)
                        MagRec["treatment_dc_field_theta"]='%7.1f'%(theta)
                    if code1[4]=='' or labfield==0.:
                        if demag=='T':meas_type="LT-T-Z"
                        if demag=="AF":meas_type="LT-AF-Z"
                        MagRec["treatment_dc_field"]='0'
                if syn==0:
                    MagRec["er_specimen_name"]=rec[0]
                    MagRec["er_synthetic_name"]=""
                    MagRec["er_site_name"]=""
                    if specnum!=0:
                        MagRec["er_sample_name"]=rec[0][:specnum]
                    else:
                        MagRec["er_sample_name"]=rec[0]
                    if "-fsa" in args:
                        for samp in Samps:
                            if samp["er_sample_name"] == MagRec["er_sample_name"]: 
                                MagRec["er_location_name"]=samp["er_location_name"]
                                MagRec["er_site_name"]=samp["er_site_name"]
                                break
                    elif int(samp_con)!=6:
                        site=pmag.parse_site(MagRec['er_sample_name'],samp_con,Z)
                        MagRec["er_site_name"]=site
                    if MagRec['er_site_name']=="":
                        print 'No site name found for: ',MagRec['er_specimen_name'],MagRec['er_sample_name']
                    if MagRec["er_location_name"]=="":
                        print 'no location name for: ',MagRec["er_specimen_name"] 
                else:
                    if specnum!=0:
                        MagRec["er_sample_name"]=rec[0][:specnum]
                    else:
                        MagRec["er_sample_name"]=rec[0]
                    MagRec["er_site_name"]=""
                    MagRec["er_synthetic_name"]=MagRec["er_specimen_name"]
                    SynRec["er_synthetic_name"]=MagRec["er_specimen_name"]
                    site=pmag.parse_site(MagRec['er_sample_name'],samp_con,Z)
                    SynRec["synthetic_parent_sample"]=site
                    SynRec["er_citation_names"]="This study"
                    SynRec["synthetic_institution"]=institution
                    SynRec["synthetic_type"]=syntype
                    SynRecs.append(SynRec)
                if rec[1]==".00":rec[1]="0.00"
                treat=rec[1].split('.')
                if float(rec[1])==0:
                    pass 
                elif demag=="AF":
                    if methcode != "LP-AN-ARM":
                        MagRec["treatment_ac_field"]='%8.3e' %(float(rec[1])*1e-3) # peak field in tesla
                        meas_type="LT-AF-Z"
                        MagRec["treatment_dc_field"]='0'
                    else: # AARM experiment
                        if treat[1][0]=='0':
                            meas_type="LT-AF-Z"
                            MagRec["treatment_ac_field"]='%8.3e' %(peakfield) # peak field in tesla
                            MagRec["treatment_dc_field"]='%8.3e'%(0)
                            if labfield!=0: print "Warning - inconsistency in mag file with lab field - overriding file with 0"
                        else:
                            meas_type="LT-AF-I"
                            ipos=int(treat[0])-1
                            MagRec["treatment_dc_field_phi"]='%7.1f' %(dec[ipos])
                            MagRec["treatment_dc_field_theta"]='%7.1f'% (inc[ipos])
                            MagRec["treatment_dc_field"]='%8.3e'%(labfield)
                            MagRec["treatment_ac_field"]='%8.3e' %(peakfield) # peak field in tesla
                elif demag=="S": # Shaw experiment
                    if treat[1][1]=='0':
                        if  int(treat[0])!=0:
                            MagRec["treatment_ac_field"]='%8.3e' % (float(treat[0])*1e-3) # AF field in tesla
                            MagRec["treatment_dc_field"]='0'
                            meas_type="LT-AF-Z" # first AF
                        else:
                            meas_type="LT-NO"
                            MagRec["treatment_ac_field"]='0'
                            MagRec["treatment_dc_field"]='0'
                    elif treat[1][1]=='1':
                        if int(treat[0])==0:
                            MagRec["treatment_ac_field"]='%8.3e' %(peakfield) # peak field in tesla
                            MagRec["treatment_dc_field"]='%8.3e'%(arm_labfield)
                            MagRec["treatment_dc_field_phi"]='%7.1f'%(phi)
                            MagRec["treatment_dc_field_theta"]='%7.1f'%(theta)
                            meas_type="LT-AF-I"
                        else:
                            MagRec["treatment_ac_field"]='%8.3e' % ( float(treat[0])*1e-3) # AF field in tesla
                            MagRec["treatment_dc_field"]='0'
                            meas_type="LT-AF-Z"
                    elif treat[1][1]=='2':
                        if int(treat[0])==0:
                            MagRec["treatment_ac_field"]='0'
                            MagRec["treatment_dc_field"]='%8.3e'%(trm_labfield)
                            MagRec["treatment_dc_field_phi"]='%7.1f'%(phi)
                            MagRec["treatment_dc_field_theta"]='%7.1f'%(theta)
                            MagRec["treatment_temp"]='%8.3e' % (trm_peakT)
                            meas_type="LT-T-I"
                        else:
                            MagRec["treatment_ac_field"]='%8.3e' % ( float(treat[0])*1e-3) # AF field in tesla
                            MagRec["treatment_dc_field"]='0'
                            meas_type="LT-AF-Z"
                    elif treat[1][1]=='3':
                        if int(treat[0])==0:
                            MagRec["treatment_ac_field"]='%8.3e' %(peakfield) # peak field in tesla
                            MagRec["treatment_dc_field"]='%8.3e'%(arm_labfield)
                            MagRec["treatment_dc_field_phi"]='%7.1f'%(phi)
                            MagRec["treatment_dc_field_theta"]='%7.1f'%(theta)
                            meas_type="LT-AF-I"
                        else:
                            MagRec["treatment_ac_field"]='%8.3e' % ( float(treat[0])*1e-3) # AF field in tesla
                            MagRec["treatment_dc_field"]='0'
                            meas_type="LT-AF-Z"
                else: 
                  if len(treat)==1:treat.append('0')
                  MagRec["treatment_temp"]='%8.3e' % (float(treat[0])+273.) # temp in kelvin
                  if trm==0:  # demag=T and not trmaq
                    if treat[1][0]=='0':
                        meas_type="LT-T-Z"
                    else: 
                        MagRec["treatment_dc_field"]='%8.3e' % (labfield) # labfield in tesla (convert from microT)
                        MagRec["treatment_dc_field_phi"]='%7.1f' % (phi) # labfield phi
                        MagRec["treatment_dc_field_theta"]='%7.1f' % (theta) # labfield theta
                        if treat[1][0]=='1':meas_type="LT-T-I" # in-field thermal step
                        if treat[1][0]=='2':
                            meas_type="LT-PTRM-I" # pTRM check
                            pTRM=1
                        if treat[1][0]=='3':
                            MagRec["treatment_dc_field"]='0'  # this is a zero field step
                            meas_type="LT-PTRM-MD" # pTRM tail check
                  else: 
                    labfield=float(treat[1])*1e-6
                    MagRec["treatment_dc_field"]='%8.3e' % (labfield) # labfield in tesla (convert from microT)
                    MagRec["treatment_dc_field_phi"]='%7.1f' % (phi) # labfield phi
                    MagRec["treatment_dc_field_theta"]='%7.1f' % (theta) # labfield theta
                    meas_type="LT-T-I:LP-TRM" # trm acquisition experiment
                MagRec["measurement_csd"]=rec[2]
                MagRec["measurement_magn_moment"]='%10.3e'% (float(rec[3])*1e-3) # moment in Am^2 (from emu)
                MagRec["measurement_dec"]=rec[4]
                MagRec["measurement_inc"]=rec[5]
                MagRec["magic_instrument_codes"]=instcode
                MagRec["er_analyst_mail_names"]=user
                MagRec["er_citation_names"]=citation
                MagRec["magic_method_codes"]=meas_type
                MagRec["measurement_flag"]='g'
                MagRec["er_specimen_name"]=rec[0]
                if 'std' in rec[0]:
                    MagRec["measurement_standard"]='s'
                else:
                    MagRec["measurement_standard"]='u'
                MagRec["measurement_number"]='1'
                MagRec["er_specimen_name"],meas_type
                MagRecs.append(MagRec) 
    elif infile_type=="ldgo":
#
# find start of data:
#
        Samps=[] # keeps track of sample orientations
        DIspec=[]
        Data,k=input.readlines(),0
        for k in range(len(Data)):
            rec=Data[k].split()
            if rec[0][0]=="_" or rec[0][0:2]=="!_":
                break
        start=k+1
        for k in range(start,len(Data)):
          rec=Data[k].split()
          if len(rec)>0:
            MagRec={}
            MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
            MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
            MagRec["treatment_ac_field"]='0'
            MagRec["treatment_dc_field"]='0'
            MagRec["treatment_dc_field_phi"]='0'
            MagRec["treatment_dc_field_theta"]='0'
            meas_type="LT-NO"
            MagRec["measurement_flag"]='g'
            MagRec["measurement_standard"]='u'
            MagRec["measurement_number"]='1'
            MagRec["er_specimen_name"]=rec[0]
            if specnum!=0:
                MagRec["er_sample_name"]=rec[0][:specnum]
            else:
                MagRec["er_sample_name"]=rec[0]
            site=pmag.parse_site(MagRec['er_sample_name'],samp_con,Z)
            MagRec["er_site_name"]=site
            MagRec["er_site_name"]=MagRec['er_sample_name'][0:-2]
            MagRec["er_location_name"]=er_location_name
            MagRec["measurement_csd"]=rec[3]
            MagRec["measurement_magn_moment"]='%10.3e'% (float(rec[4])*1e-7) # moment in Am^2 (from 10^-4 emu)
#
            if samp_file!="" and MagRec["er_sample_name"] not in Samps:        # create er_samples.txt file with these data 
                cdec,cinc=float(rec[5]),float(rec[6])
                gdec,ginc=float(rec[7]),float(rec[8])
                az,pl=pmag.get_azpl(cdec,cinc,gdec,ginc)
                bdec,binc=float(rec[9]),float(rec[10])
                if rec[7]!=rec[9] and rec[6]!=rec[8]:
                    dipdir,dip=pmag.get_tilt(gdec,ginc,bdec,binc)
                else:
                    dipdir,dip=0,0
                ErSampRec={}
                ErSampRec['er_location_name']=MagRec['er_location_name']
                ErSampRec['er_sample_name']=MagRec['er_sample_name']
                ErSampRec['er_site_name']=MagRec['er_site_name']
                ErSampRec['sample_azimuth']='%7.1f'%(az)
                ErSampRec['sample_dip']='%7.1f'%(pl)
                ErSampRec['sample_bed_dip_direction']='%7.1f'%(dipdir)
                ErSampRec['sample_bed_dip']='%7.1f'%(dip)
                ErSampRec['sample_description']='az,pl,dip_dir and dip recalculated from [c,g,b][dec,inc] in ldeo file'
                ErSampRec['magic_method_codes']='SO-REC'
                ErSamps.append(ErSampRec)
                Samps.append(ErSampRec['er_sample_name'])
            MagRec["measurement_dec"]=rec[5]
            MagRec["measurement_inc"]=rec[6]
            MagRec["magic_instrument_codes"]=rec[2]
            MagRec["er_analyst_mail_names"]=""
            MagRec["er_citation_names"]="This study"
            MagRec["magic_method_codes"]=meas_type
            if demag=="AF":
                if methcode != "LP-AN-ARM":
                    MagRec["treatment_ac_field"]='%8.3e' %(float(rec[1])*1e-3) # peak field in tesla
                    meas_type="LT-AF-Z"
                    MagRec["treatment_dc_field"]='0'
                else: # AARM experiment
                    if treat[1][0]=='0':
                        meas_type="LT-AF-Z"
                        MagRec["treatment_ac_field"]='%8.3e' %(peakfield) # peak field in tesla
                    else:
                        meas_type="LT-AF-I"
                        ipos=int(treat[0])-1
                        MagRec["treatment_dc_field_phi"]='%7.1f' %(dec[ipos])
                        MagRec["treatment_dc_field_theta"]='%7.1f'% (inc[ipos])
                        MagRec["treatment_dc_field"]='%8.3e'%(labfield)
                        MagRec["treatment_ac_field"]='%8.3e' %(peakfield) # peak field in tesla
            elif demag=="T":
                if rec[1][0]==".":rec[1]="0"+rec[1]
                treat=rec[1].split('.')
                if len(treat)==1:treat.append('0')
                MagRec["treatment_temp"]='%8.3e' % (float(rec[1])+273.) # temp in kelvin
                meas_type="LT-T-Z"
                MagRec["treatment_temp"]='%8.3e' % (float(treat[0])+273.) # temp in kelvin
                if trm==0:  # demag=T and not trmaq
                    if treat[1][0]=='0':
                        meas_type="LT-T-Z"
                    else: 
                        MagRec["treatment_dc_field"]='%8.3e' % (labfield) # labfield in tesla (convert from microT)
                        MagRec["treatment_dc_field_phi"]='%7.1f' % (phi) # labfield phi
                        MagRec["treatment_dc_field_theta"]='%7.1f' % (theta) # labfield theta
                        if treat[1][0]=='1':meas_type="LT-T-I" # in-field thermal step
                        if treat[1][0]=='2':
                            meas_type="LT-PTRM-I" # pTRM check
                            pTRM=1
                        if treat[1][0]=='3':
                            MagRec["treatment_dc_field"]='0'  # this is a zero field step
                            meas_type="LT-PTRM-MD" # pTRM tail check
                else: 
                    meas_type="LT-T-I" # trm acquisition experiment
            MagRec['magic_method_codes']=meas_type
            MagRecs.append(MagRec) 
    MagOuts=pmag.measurements_methods(MagRecs,noave)
    pmag.magic_write(meas_file,MagOuts,'magic_measurements')
    print "results put in ",meas_file
    if samp_file!="":
        pmag.magic_write(samp_file,ErSamps,'er_samples')
        print "sample orientations put in ",samp_file
    if len(SynRecs)>0:
        pmag.magic_write(synfile,SynRecs,'er_synthetics')
        print "synthetics put in ",synfile