Example #1
0
def main():
    """
    NAME
        cart_dir.py
    
    DESCRIPTION
      converts cartesian coordinates to geomagnetic elements
    
    INPUT (COMMAND LINE ENTRY) 
           x1 x2  x3
        if only two columns, assumes magnitude of unity
    OUTPUT
           declination inclination magnitude
    
    SYNTAX
        cart_dir.py [command line options] [< filename]
    
    OPTIONS 
        -h prints help message and quits
        -i for interactive data entry
        -f FILE to specify input filename
        -F OFILE to specify output filename (also prints to screen)
    
    """
    ofile=""
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        ofile=sys.argv[ind+1]
        outfile=open(ofile,'w')
    if '-i' in sys.argv:
        cont=1
        while cont==1:
            cart=[]
            try:
                ans=raw_input('X: [ctrl-D  to quit] ')
                cart.append(float(ans))
                ans=raw_input('Y: ')
                cart.append(float(ans))
                ans=raw_input('Z: ')
                cart.append(float(ans))
            except:
                print "\n Good-bye \n"
                sys.exit()
            dir= pmag.cart2dir(cart)  # send dir to dir2cart and spit out result
            print '%7.1f %7.1f %10.3e'%(dir[0],dir[1],dir[2])
    elif '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        input=numpy.loadtxt(file) # read from a file
    else:
        input = numpy.loadtxt(sys.stdin,dtype=numpy.float)  # read from standard input
    dir=pmag.cart2dir(input)
    for line in dir:
        print '%7.1f %7.1f %10.3e'%(line[0],line[1],line[2])
        if ofile!="":
           outstring='%7.1f %7.1f %10.8e\n' %(line[0],line[1],line[2]) 
           outfile.write(outstring)
Example #2
0
def spitout(line):
    cart=[]  # initialize list for  dec,inc,intensity
    dat=line.split() # split the data on a space into columns
    for element in dat: # step through dec,inc, int
        cart.append(float(element)) # append floating point variable to "cart"
    dir= pmag.cart2dir(cart)  # send cart to cart2dir
    print '%7.1f %7.1f %10.3e'%(dir[0],dir[1],dir[2])
    return dir
Example #3
0
def Rotate_zijderveld(Zdata, rot_declination):
    if len(Zdata) == 0:
        return ([])
    CART_rot = []
    for i in range(0, len(Zdata)):
        DIR = cart2dir(Zdata[i])
        DIR[0] = (DIR[0] - rot_declination) % 360.
        CART_rot.append(array(dir2cart(DIR)))
    CART_rot = array(CART_rot)
    return (CART_rot)
def Rotate_zijderveld(Zdata,rot_declination):
    if len(Zdata)==0:
        return([])
    CART_rot=[]
    for i in range(0,len(Zdata)):
        DIR=cart2dir(Zdata[i])
        DIR[0]=(DIR[0]-rot_declination)%360.
        CART_rot.append(array(dir2cart(DIR)))
    CART_rot=array(CART_rot)
    return(CART_rot)
Example #5
0
def plotELL(pars,col,lower,plot): #Modified from PmagPy (Tauxe et al., 2016)
    """
    function to calculate points on an ellipse about Pdec,Pdip with angle beta,gamma
    """
    #pylab.figure(num=fignum)
    Pdec,Pinc,beta,Bdec,Binc,gamma,Gdec,Ginc=pars[0],pars[1],pars[2],pars[3],pars[4],pars[5],pars[6],pars[7]
    if beta > 90. or gamma>90:
        beta=180.-beta
        gamma=180.-beta
        Pdec=Pdec-180.
        Pinc=-Pinc
    beta,gamma=beta*rad,gamma*rad # convert to radians
    X_ell,Y_ell,X_up,Y_up,PTS=[],[],[],[],[]
    nums=201
    xnum=float(nums-1.)/2.
# set up t matrix
    t=[[0,0,0],[0,0,0],[0,0,0]]
    X=pmag.dir2cart((Pdec,Pinc,1.0)) # convert to cartesian coordintes
    if lower==1 and X[2]<0:
       for i in range(3):
           X[i]=-X[i]
# set up rotation matrix t
    t[0][2]=X[0]
    t[1][2]=X[1]
    t[2][2]=X[2]
    X=pmag.dir2cart((Bdec,Binc,1.0))
    if lower==1 and X[2]<0:
       for i in range(3):
           X[i]=-X[i]
    t[0][0]=X[0]
    t[1][0]=X[1]
    t[2][0]=X[2]
    X=pmag.dir2cart((Gdec,Ginc,1.0))
    if lower==1 and X[2]<0:
       for i in range(3):
           X[i]=-X[i]
    t[0][1]=X[0]
    t[1][1]=X[1]
    t[2][1]=X[2]
# set up v matrix
    v=[0,0,0]
    for i in range(nums):  # incremental point along ellipse
        psi=float(i)*np.pi/xnum
        v[0]=np.sin(beta)*np.cos(psi) 
        v[1]=np.sin(gamma)*np.sin(psi) 
        v[2]=np.sqrt(1.-v[0]**2 - v[1]**2)
        elli=[0,0,0]
# calculate points on the ellipse
        for j in range(3):
            for k in range(3):
                elli[j]=elli[j] + t[j][k]*v[k]  # cartesian coordinate j of ellipse
        PTS.append(pmag.cart2dir(elli))
        R=np.sqrt( 1.-abs(elli[2]))/(np.sqrt(elli[0]**2+elli[1]**2)) # put on an equal area projection
        if elli[2]<0:
#            for i in range(3): elli[i]=-elli[i]
            X_up.append(elli[1]*R)
            Y_up.append(elli[0]*R)
        else:
            X_ell.append(elli[1]*R)
            Y_ell.append(elli[0]*R)
    if plot==1:
        if X_ell!=[]:plt.plot(X_ell,Y_ell,col,linewidth=2,zorder=5)#pylab.plot(X_ell,Y_ell,col,zorder=3)
        if X_up!=[]:plt.plot(X_up,Y_up,col,linewidth=2,zorder=5)#pylab.plot(X_up,Y_up,'g-',zorder=3)
        #pylab.draw()
    else: 
        return PTS
Example #6
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
Example #7
0
def main(command_line=True, **kwargs):
    """
    NAME
        IODP_jr6_magic.py
 
    DESCRIPTION
        converts shipboard .jr6 format files to magic_measurements format files

    SYNTAX
        IODP_jr6_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 FILE: specify  er_samples.txt file for sample name lookup ,
           default is 'er_samples.txt'
        -loc HOLE : specify hole name (U1456A)
        -A: don't average replicate measurements
 
    INPUT
        JR6 .jr6 format file
    """


    def fix_separation(filename, new_filename):
        old_file = open(filename, 'rU')
        data = old_file.readlines()
        new_data = []
        for line in data:
            new_line = line.replace('-', ' -')
            new_line = new_line.replace('  ', ' ')
            new_data.append(new_line)
        new_file = open(new_filename, 'w')
        for s in new_data:
            new_file.write(s)
        old_file.close()
        new_file.close()
        return new_filename
        

    def old_fix_separation(filename, new_filename):
        old_file = open(filename, 'rU')
        data = old_file.readlines()
        new_data = []
        for line in data:
            new_line = []
            for i in line.split():
                if '-' in i[1:]:
                    lead_char = '-' if i[0] == '-' else ''
                    if lead_char:
                        v = i[1:].split('-')
                    else:
                        v = i.split('-')
                    new_line.append(lead_char + v[0])
                    new_line.append('-' + v[1])
                else:
                    new_line.append(i)
            new_line = (' '.join(new_line)) + '\n'
            new_data.append(new_line)
        new_file = open(new_filename, 'w')
        for s in new_data:
            new_file.write(s)
        new_file.close()
        old_file.close()
        return new_filename


    
# initialize some stuff
    noave=0
    volume=2.5**3 #default volume is a 2.5cm cube
    inst=""
    samp_con,Z='5',""
    missing=1
    demag="N"
    er_location_name="unknown"
    citation='This study'
    args=sys.argv
    meth_code="LP-NO"
    version_num=pmag.get_version()
    dir_path='.'
    MagRecs=[]
    samp_file = 'er_samples.txt'
    meas_file = 'magic_measurements.txt'
    mag_file = ''
    #
    # 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]
            if samp_file[0]!='/':
                samp_file = os.path.join(input_dir_path, samp_file)
            try:
                open(samp_file,'rU')
                ErSamps,file_type=pmag.magic_read(samp_file)
            except:
                print samp_file,' not found: '
                print '   download csv file and import to MagIC with IODP_samples_magic.py'
        if '-f' in args:
            ind = args.index("-f")
            mag_file= args[ind+1]
        if "-loc" in args:
            ind=args.index("-loc")
            er_location_name=args[ind+1]
        if "-A" in args:
            noave=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', 1)
        samp_con = kwargs.get('samp_con', '1')
        if len(str(samp_con)) > 1:
            samp_con, Z = samp_con.split('-')
        else:
            Z = ''
        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")


    # format variables
    meth_code=meth_code+":FS-C-DRILL-IODP:SP-SS-C:SO-V"
    meth_code=meth_code.strip(":")
    if mag_file:
        mag_file = os.path.join(input_dir_path, mag_file)
    samp_file = os.path.join(input_dir_path, samp_file)
    meas_file = os.path.join(output_dir_path, meas_file)

    # validate variables
    if not mag_file:
        print "You must provide an IODP_jr6 format file"
        return False, "You must provide an IODP_jr6 format file"
    if not os.path.exists(mag_file):
        print 'The input file you provided: {} does not exist.\nMake sure you have specified the correct filename AND correct input directory name.'.format(os.path.join(input_dir_path, mag_file))
        return False, 'The input file you provided: {} does not exist.\nMake sure you have specified the correct filename AND correct input directory name.'.format(magfile)
    if not os.path.exists(samp_file):
        print 'samp_file', samp_file
        print "Your input directory:\n{}\nmust contain an er_samples.txt file, or you must explicitly provide one".format(input_dir_path)
        return False, "Your input directory:\n{}\nmust contain an er_samples.txt file, or you must explicitly provide one".format(input_dir_path)
    
    # parse data
    temp = os.path.join(output_dir_path, 'temp.txt')
    fix_separation(mag_file, temp)
    #os.rename('temp.txt', mag_file)
    #data = open(mag_file, 'rU').readlines()
    data=pd.read_csv(temp, delim_whitespace=True,header=None)
    os.remove(temp)
    samples,filetype = pmag.magic_read(samp_file)
    data.columns=['specname','step','negz','y','x','expon','sample_azimuth','sample_dip','sample_bed_dip_direction','sample_bed_dip','bed_dip_dir2','bed_dip2','param1','param2','param3','param4','measurement_csd']
    cart=np.array([data['x'],data['y'],-data['negz']]).transpose()
    dir= pmag.cart2dir(cart).transpose()
    data['measurement_dec']=dir[0]
    data['measurement_inc']=dir[1]
    data['measurement_magn_volume']=dir[2]*(10.0**data['expon']) # A/m  - data in A/m
    data['measurement_flag']='g'
    data['measurement_standard']='u'
    data['measurement_number']='1'
    data['measurement_temp']='273'
    data['er_location_name']=er_location_name
    for rowNum, row in data.iterrows():
        MagRec={}
        spec_text_id=row['specname'].split('_')[1]
        SampRecs=pmag.get_dictitem(samples,'er_sample_alternatives',spec_text_id,'has') # retrieve sample record for this specimen
        if len(SampRecs)>0: # found one
            MagRec['er_specimen_name']=SampRecs[0]['er_sample_name']
            MagRec['er_sample_name']=MagRec['er_specimen_name']
            MagRec['er_site_name']=MagRec['er_specimen_name']
            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["measurement_flag"]='g'
            MagRec["measurement_standard"]='u'
            MagRec["measurement_number"]='1'
            MagRec["treatment_ac_field"]='0'
            volume=float(SampRecs[0]['sample_volume'])
            moment=row['measurement_magn_volume'] * volume 
            MagRec["measurement_magn_moment"]=str(moment)
            MagRec["measurement_magn_volume"]=str(row['measurement_magn_volume'])
            MagRec["measurement_dec"]='%7.1f'%(row['measurement_dec'])
            MagRec["measurement_inc"]='%7.1f'%(row['measurement_inc'])
            if row['step'] == 'NRM':
                meas_type="LT-NO"
            elif row['step'][0:2] == 'AD':
                meas_type="LT-AF-Z"
                treat=float(row['step'][2:])
                MagRec["treatment_ac_field"]='%8.3e' %(treat*1e-3) # convert from mT to tesla
            elif row['step'][0] == 'TD':
                meas_type="LT-T-Z"
                treat=float(row['step'][2:])
                MagRec["treatment_temp"]='%8.3e' % (treat+273.) # temp in kelvin
            elif row['step'][0:3]=='ARM': # 
                meas_type="LT-AF-I"
                treat=float(row['step'][3:])
                MagRec["treatment_ac_field"]='%8.3e' %(treat*1e-3) # convert from mT to tesla
                MagRec["treatment_dc_field"]='%8.3e' %(50e-6) # assume 50uT DC field
                MagRec["measurement_description"]='Assumed DC field - actual unknown'
            elif row['step'][0:3]=='IRM': # 
                meas_type="LT-IRM"
                treat=float(row['step'][3:])
                MagRec["treatment_dc_field"]='%8.3e' %(treat*1e-3) # convert from mT to tesla
            else:
                print 'unknown treatment type for ',row
                return False, 'unknown treatment type for ',row
            MagRec['magic_method_codes']=meas_type
            MagRecs.append(MagRec.copy())
        else:
            print 'sample name not found: ',row['specname']
    MagOuts=pmag.measurements_methods(MagRecs,noave)
    file_created, error_message = pmag.magic_write(meas_file,MagOuts,'magic_measurements')
    if file_created:
        return True, meas_file
    else:
        return False, 'Results not written to file'
Example #8
0
def main(command_line=True, **kwargs):
    """
    NAME
        BGC_magic.py

    DESCRIPTION
        converts Berkeley Geochronology Center (BGC) format files to magic_measurements format files

    SYNTAX
        BGC_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)
        -loc LOCNAME : specify location/study name
        -site SITENAME : specify site name
        -A: don't average replicate measurements
        -mcd [SO-MAG,SO-SUN,SO-SIGHT...] supply how these samples were oriented
        -v NUM : specify the volume in cc of the sample, default 2.5^3cc. Will use vol in data file if volume!=0 in file.

    INPUT
        BGC paleomag format file
    """
    # initialize some stuff
    noave = 0
    volume = 0.025 ** 3  # default volume is a 2.5cm cube
    # inst=""
    # samp_con,Z='1',""
    # missing=1
    # demag="N"
    er_location_name = "unknown"
    er_site_name = "unknown"
    # citation='This study'
    args = sys.argv
    meth_code = "LP-NO"
    # specnum=1
    version_num = pmag.get_version()

    mag_file = ""
    dir_path = "."
    MagRecs = []
    SampOuts = []

    samp_file = "er_samples.txt"
    meas_file = "magic_measurements.txt"
    meth_code = ""
    #
    # 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 "-loc" in args:
            ind = args.index("-loc")
            er_location_name = args[ind + 1]
        if "-site" in args:
            ind = args.index("-site")
            er_site_name = args[ind + 1]
        if "-A" in args:
            noave = 1
        if "-mcd" in args:
            ind = args.index("-mcd")
            meth_code = args[ind + 1]
            # samp_con='5'
        if "-v" in args:
            ind = args.index("-v")
            volume = float(args[ind + 1]) * 1e-6  # enter volume in cc, convert to m^3
    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")
        er_location_name = kwargs.get("er_location_name", "")
        er_site_name = kwargs.get("er_site_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 = 0.025 ** 3  # default volume is a 2.5 cm cube, translated to meters cubed
        else:
            # convert cm^3 to m^3
            volume *= 1e-6

    # format variables
    if not mag_file:
        return False, "You must provide a BCG format file"
    mag_file = os.path.join(input_dir_path, mag_file)
    meas_file = os.path.join(output_dir_path, meas_file)
    samp_file = os.path.join(output_dir_path, samp_file)

    ErSampRec = {}

    # parse data

    # Open up the BGC file and read the header information
    print "mag_file in BGC_magic", mag_file
    pre_data = open(mag_file, "rU")
    line = pre_data.readline()
    line_items = line.split(" ")
    sample_name = line_items[2]
    sample_name = sample_name.replace("\n", "")
    line = pre_data.readline()
    line = pre_data.readline()
    line_items = line.split("\t")
    sample_azimuth = float(line_items[1])
    sample_dip = 90.0 - float(line_items[2])
    sample_bed_dip = line_items[3]
    sample_bed_azimuth = line_items[4]
    sample_lon = line_items[5]
    sample_lat = line_items[6]
    tmp_volume = line_items[7]
    if tmp_volume != 0.0:
        volume = float(tmp_volume) * 1e-6
    pre_data.close()

    data = pd.read_csv(mag_file, sep="\t", header=3, index_col=False)

    #    print "\ndata\n", data

    cart = np.array([data["X"], data["Y"], data["Z"]]).transpose()
    direction = pmag.cart2dir(cart).transpose()

    data["measurement_dec"] = direction[0]
    data["measurement_inc"] = direction[1]
    data["measurement_magn_moment"] = direction[2] * 1000 * volume  # the data are in EMU - this converts to Am^2
    data["measurement_magn_volume"] = direction[2] * 1000  # EMU  - data converted to A/m

    # DGEOs, IGEOs = [], []
    # print "len(data)=",len(data)
    # for ind in range(len(data)):
    #    dgeo,igeo=pmag.dogeo(data.ix[ind]['measurement_dec'],data.ix[ind]['measurement_inc'],90-sample_azimuth,sample_dip)
    #    DGEOs.append(dgeo)
    #    IGEOs.append(igeo)
    # data['specimen_dec']=DGEOs
    # data['specimen_inc']=IGEOs
    # data['specimen_tilt']='1'

    # print "data specimn_dec=",DGEOs
    # print "data specimn_inc=",IGEOs

    # Configure the er_sample table

    ErSampRec["er_sample_name"] = sample_name
    ErSampRec["sample_azimuth"] = sample_azimuth
    ErSampRec["sample_dip"] = sample_dip
    ErSampRec["sample_bed_dip_direction"] = sample_bed_azimuth
    ErSampRec["sample_bed_dip"] = sample_bed_dip
    ErSampRec["sample_lat"] = sample_lat
    ErSampRec["sample_lon"] = sample_lon
    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())

    # Configure the magic_measurements table

    for rowNum, row in data.iterrows():
        MagRec = {}
        MagRec["measurement_description"] = "Date: " + str(row["Date"]) + " Time: " + str(row["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"] = 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"] = sample_name
        MagRec["treatment_ac_field"] = "0"
        if row["DM Val"] == "0":
            meas_type = "LT-NO"
        elif int(row["DM Type"]) > 0.0:
            meas_type = "LT-AF-Z"
            treat = float(row["DM Val"])
            MagRec["treatment_ac_field"] = "%8.3e" % (treat * 1e-3)  # convert from mT to tesla
        elif int(row["DM Type"]) == -1:
            meas_type = "LT-T-Z"
            treat = float(row["DM Val"])
            MagRec["treatment_temp"] = "%8.3e" % (treat + 273.0)  # temp in kelvin
        else:
            print "measurement type unknown:", row["DM Type"], " in row ", rowNum
        MagRec["measurement_magn_moment"] = str(row["measurement_magn_moment"])
        MagRec["measurement_magn_volume"] = str(row["measurement_magn_volume"])
        MagRec["measurement_dec"] = str(row["measurement_dec"])
        MagRec["measurement_inc"] = str(row["measurement_inc"])
        MagRec["magic_method_codes"] = meas_type
        MagRec["measurement_csd"] = "0.0"  # added due to magic.write error
        MagRec["measurement_positions"] = "1"  # added due to magic.write error
        MagRecs.append(MagRec.copy())
    pmag.magic_write(samp_file, SampOuts, "er_samples")
    print "sample orientations put in ", samp_file
    MagOuts = pmag.measurements_methods(MagRecs, noave)
    pmag.magic_write(meas_file, MagOuts, "magic_measurements")
    print "results put in ", meas_file
    print "exit!"
    return True, meas_file
Example #9
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
Example #10
0
 def average_duplicates(duplicates):
     '''
     avarage replicate measurements.
     '''
     carts_s,carts_g,carts_t=[],[],[]   
     for rec in duplicates:
         moment=float(rec['moment'])
         if 'dec_s' in rec.keys() and 'inc_s' in rec.keys():
             if rec['dec_s']!="" and rec['inc_s']!="":
                 dec_s=float(rec['dec_s'])
                 inc_s=float(rec['inc_s'])
                 cart_s=pmag.dir2cart([dec_s,inc_s,moment])
                 carts_s.append(cart_s)
         if 'dec_g' in rec.keys() and 'inc_g' in rec.keys():
             if rec['dec_g']!="" and rec['inc_g']!="":
                 dec_g=float(rec['dec_g'])
                 inc_g=float(rec['inc_g'])
                 cart_g=pmag.dir2cart([dec_g,inc_g,moment])
                 carts_g.append(cart_g)
         if 'dec_t' in rec.keys() and 'inc_t' in rec.keys():
             if rec['dec_t']!="" and rec['inc_t']!="":
                 dec_t=float(rec['dec_t'])
                 inc_t=float(rec['inc_t'])
                 cart_t=pmag.dir2cart([dec_t,inc_t,moment])
                 carts_t.append(cart_t)
     if len(carts_s)>0:                               
         carts=scipy.array(carts_s)
         x_mean=scipy.mean(carts[:,0])
         y_mean=scipy.mean(carts[:,1])
         z_mean=scipy.mean(carts[:,2])
         mean_dir=pmag.cart2dir([x_mean,y_mean,z_mean])
         mean_dec_s="%.2f"%mean_dir[0]
         mean_inc_s="%.2f"%mean_dir[1]
         mean_moment="%10.3e"%mean_dir[2]
     else:
         mean_dec_s,mean_inc_s="",""
     if len(carts_g)>0:                               
         carts=scipy.array(carts_g)
         x_mean=scipy.mean(carts[:,0])
         y_mean=scipy.mean(carts[:,1])
         z_mean=scipy.mean(carts[:,2])
         mean_dir=pmag.cart2dir([x_mean,y_mean,z_mean])
         mean_dec_g="%.2f"%mean_dir[0]
         mean_inc_g="%.2f"%mean_dir[1]
         mean_moment="%10.3e"%mean_dir[2]
     else:
         mean_dec_g,mean_inc_g="",""
         
     if len(carts_t)>0:                               
         carts=scipy.array(carts_t)
         x_mean=scipy.mean(carts[:,0])
         y_mean=scipy.mean(carts[:,1])
         z_mean=scipy.mean(carts[:,2])
         mean_dir=pmag.cart2dir([x_mean,y_mean,z_mean])
         mean_dec_t="%.2f"%mean_dir[0]
         mean_inc_t="%.2f"%mean_dir[1]
         mean_moment="%10.3e"%mean_dir[2]
     else:
         mean_dec_t,mean_inc_t="",""
                                                                     
     meanrec={}
     for key in duplicates[0].keys():
         if key in ['dec_s','inc_s','dec_g','inc_g','dec_t','inc_t','moment']:
             continue
         else:
             meanrec[key]=duplicates[0][key]
     meanrec['dec_s']=mean_dec_s
     meanrec['dec_g']=mean_dec_g
     meanrec['dec_t']=mean_dec_t
     meanrec['inc_s']=mean_inc_s
     meanrec['inc_g']=mean_inc_g
     meanrec['inc_t']=mean_inc_t
     meanrec['moment']=mean_moment
     return meanrec
Example #11
0
def main(command_line=True, **kwargs):
    """
    NAME
        IODP_jr6_magic.py
 
    DESCRIPTION
        converts shipboard .jr6 format files to magic_measurements format files

    SYNTAX
        IODP_jr6_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 FILE: specify  er_samples.txt file for sample name lookup ,
           default is 'er_samples.txt'
        -loc HOLE : specify hole name (U1456A)
        -A: don't average replicate measurements
 
    INPUT
        JR6 .jr6 format file
    """

    def fix_separation(filename, new_filename):
        old_file = open(filename, "rU")
        data = old_file.readlines()
        new_data = []
        for line in data:
            new_line = line.replace("-", " -")
            new_line = new_line.replace("  ", " ")
            new_data.append(new_line)
        new_file = open(new_filename, "w")
        for s in new_data:
            new_file.write(s)
        old_file.close()
        new_file.close()
        return new_filename

    def old_fix_separation(filename, new_filename):
        old_file = open(filename, "rU")
        data = old_file.readlines()
        new_data = []
        for line in data:
            new_line = []
            for i in line.split():
                if "-" in i[1:]:
                    lead_char = "-" if i[0] == "-" else ""
                    if lead_char:
                        v = i[1:].split("-")
                    else:
                        v = i.split("-")
                    new_line.append(lead_char + v[0])
                    new_line.append("-" + v[1])
                else:
                    new_line.append(i)
            new_line = (" ".join(new_line)) + "\n"
            new_data.append(new_line)
        new_file = open(new_filename, "w")
        for s in new_data:
            new_file.write(s)
        new_file.close()
        old_file.close()
        return new_filename

    # initialize some stuff
    noave = 0
    volume = 2.5 ** 3  # default volume is a 2.5cm cube
    inst = ""
    samp_con, Z = "5", ""
    missing = 1
    demag = "N"
    er_location_name = "unknown"
    citation = "This study"
    args = sys.argv
    meth_code = "LP-NO"
    version_num = pmag.get_version()
    dir_path = "."
    MagRecs = []
    samp_file = "er_samples.txt"
    meas_file = "magic_measurements.txt"
    mag_file = ""
    #
    # 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]
            if samp_file[0] != "/":
                samp_file = os.path.join(input_dir_path, samp_file)
            try:
                open(samp_file, "rU")
                ErSamps, file_type = pmag.magic_read(samp_file)
            except:
                print samp_file, " not found: "
                print "   download csv file and import to MagIC with IODP_samples_magic.py"
        if "-f" in args:
            ind = args.index("-f")
            mag_file = args[ind + 1]
        if "-loc" in args:
            ind = args.index("-loc")
            er_location_name = args[ind + 1]
        if "-A" in args:
            noave = 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", 1)
        samp_con = kwargs.get("samp_con", "1")
        if len(str(samp_con)) > 1:
            samp_con, Z = samp_con.split("-")
        else:
            Z = ""
        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")

    # format variables
    meth_code = meth_code + ":FS-C-DRILL-IODP:SP-SS-C:SO-V"
    meth_code = meth_code.strip(":")
    if mag_file:
        mag_file = os.path.join(input_dir_path, mag_file)
    samp_file = os.path.join(input_dir_path, samp_file)
    meas_file = os.path.join(output_dir_path, meas_file)

    # validate variables
    if not mag_file:
        print "You must provide an IODP_jr6 format file"
        return False, "You must provide an IODP_jr6 format file"
    if not os.path.exists(mag_file):
        print "The input file you provided: {} does not exist.\nMake sure you have specified the correct filename AND correct input directory name.".format(
            mag_file
        )
        return (
            False,
            "The input file you provided: {} does not exist.\nMake sure you have specified the correct filename AND correct input directory name.".format(
                mag_file
            ),
        )
    if not os.path.exists(samp_file):
        print "Your input directory:\n{}\nmust contain an er_samples.txt file, or you must explicitly provide one".format(
            input_dir_path
        )
        return (
            False,
            "Your input directory:\n{}\nmust contain an er_samples.txt file, or you must explicitly provide one".format(
                input_dir_path
            ),
        )

    # parse data
    temp = os.path.join(output_dir_path, "temp.txt")
    fix_separation(mag_file, temp)
    samples, filetype = pmag.magic_read(samp_file)
    lines = open(temp, "rU").readlines()
    os.remove(temp)
    for line in lines:
        MagRec = {}
        line = line.split()
        spec_text_id = line[0].split("_")[1]
        SampRecs = pmag.get_dictitem(samples, "er_sample_alternatives", spec_text_id, "has")
        if len(SampRecs) > 0:  # found one
            MagRec["er_specimen_name"] = SampRecs[0]["er_sample_name"]
            MagRec["er_sample_name"] = MagRec["er_specimen_name"]
            MagRec["er_site_name"] = MagRec["er_specimen_name"]
            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["measurement_flag"] = "g"
            MagRec["measurement_standard"] = "u"
            MagRec["measurement_number"] = "1"
            MagRec["treatment_ac_field"] = "0"

            volume = float(SampRecs[0]["sample_volume"])
            x = float(line[4])
            y = float(line[3])
            negz = float(line[2])
            cart = np.array([x, y, -negz]).transpose()
            direction = pmag.cart2dir(cart).transpose()
            expon = float(line[5])
            magn_volume = direction[2] * (10.0 ** expon)
            moment = magn_volume * volume

            MagRec["measurement_magn_moment"] = str(moment)
            MagRec["measurement_magn_volume"] = str(magn_volume)  # str(direction[2] * (10.0 ** expon))
            MagRec["measurement_dec"] = "%7.1f" % (direction[0])
            MagRec["measurement_inc"] = "%7.1f" % (direction[1])

            step = line[1]
            if step == "NRM":
                meas_type = "LT-NO"
            elif step[0:2] == "AD":
                meas_type = "LT-AF-Z"
                treat = float(step[2:])
                MagRec["treatment_ac_field"] = "%8.3e" % (treat * 1e-3)  # convert from mT to tesla
            elif step[0:2] == "TD":
                meas_type = "LT-T-Z"
                treat = float(step[2:])
                MagRec["treatment_temp"] = "%8.3e" % (treat + 273.0)  # temp in kelvin
            elif step[0:3] == "ARM":  #
                meas_type = "LT-AF-I"
                treat = float(row["step"][3:])
                MagRec["treatment_ac_field"] = "%8.3e" % (treat * 1e-3)  # convert from mT to tesla
                MagRec["treatment_dc_field"] = "%8.3e" % (50e-6)  # assume 50uT DC field
                MagRec["measurement_description"] = "Assumed DC field - actual unknown"
            elif step[0:3] == "IRM":  #
                meas_type = "LT-IRM"
                treat = float(step[3:])
                MagRec["treatment_dc_field"] = "%8.3e" % (treat * 1e-3)  # convert from mT to tesla
            else:
                print "unknown treatment type for ", row
                return False, "unknown treatment type for ", row

            MagRec["magic_method_codes"] = meas_type
            MagRecs.append(MagRec.copy())

        else:
            print "sample name not found: ", row["specname"]
    MagOuts = pmag.measurements_methods(MagRecs, noave)
    file_created, error_message = pmag.magic_write(meas_file, MagOuts, "magic_measurements")
    if file_created:
        return True, meas_file
    else:
        return False, "Results not written to file"
Example #12
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
Example #13
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
Example #14
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
Example #15
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"
Example #16
0
def main():
    """
    NAME 
        ani_depthplot.py

    DESCRIPTION
        plots tau, V3_inc, P and chi versus core_depth

    SYNTAX
        ani_depthplot.py [command line optins]

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input rmag_anisotropy format file from magic
        -fb FILE: specify input magic_measurements format file from magic
        -fsa FILE: specify input er_samples format file from magic 
        -fa FILE: specify input er_ages format file from magic 
        -d min max [in m] depth range to plot
        -ds [mcd,mbsf], specify depth scale, default is mbsf
        -sav save plot without review
        -fmt specfiy format for figures - default is svg
     DEFAULTS:
         Anisotropy file: rmag_anisotropy.txt
         Bulk susceptibility file: magic_measurements.txt
         Samples file: er_samples.txt
    """
    fmt='.svg'
    dir_path="./"
    pcol=3
    verbose=pmagplotlib.verbose
    plots=0
    age_file=""
    if '-WD' in sys.argv: 
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    ani_file=dir_path+'/rmag_anisotropy.txt'
    meas_file=dir_path+'/magic_measurements.txt'
    samp_file=dir_path+'/er_samples.txt'
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        ani_file=dir_path+'/'+sys.argv[ind+1]
    if '-fb' in sys.argv:
        ind=sys.argv.index('-fb')
        meas_file=dir_path+'/'+sys.argv[ind+1]
    if '-fsa' in sys.argv:
        ind=sys.argv.index('-fsa')
        samp_file=dir_path+'/'+sys.argv[ind+1]
        if '-fa' in sys.argv:
            print main.__doc__
            print 'only -fsa OR -fa - not both'
            sys.exit()
    elif '-fa' in sys.argv:
        ind=sys.argv.index('-fa')
        age_file=dir_path+"/"+sys.argv[ind+1]
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt='.'+sys.argv[ind+1]
    dmin,dmax=-1,-1
    if '-d' in sys.argv:
        ind=sys.argv.index('-d')
        dmin=float(sys.argv[ind+1])
        dmax=float(sys.argv[ind+2])
    if '-ds' in sys.argv and 'mcd' in sys.argv: # sets depth scale to meters composite depth (as opposed to meters below sea floor)
        depth_scale='sample_composite_depth'
    elif age_file=="":
        depth_scale='sample_core_depth'
    else:
        depth_scale='age'
    if '-sav' in sys.argv:
        plots=1
        verbose=0
    #
    # get data read in
    isbulk=0 # tests if there are bulk susceptibility measurements
    AniData,file_type=pmag.magic_read(ani_file)  # read in tensor elements
    if age_file=="":
        Samps,file_type=pmag.magic_read(samp_file)  # read in sample depth info from er_sample.txt format file
    else:
        Samps,file_type=pmag.magic_read(age_file)  # read in sample age info from er_ages.txt format file
        age_unit=Samps[0]['age_unit']
    for s in Samps:s['er_sample_name']=s['er_sample_name'].upper() # change to upper case for every sample name
    Meas,file_type=pmag.magic_read(meas_file) 
    if file_type=='magic_measurements':isbulk=1
    Data=[]
    Bulks=[]
    BulkDepths=[]
    for rec in AniData:
        samprecs=pmag.get_dictitem(Samps,'er_sample_name',rec['er_sample_name'].upper(),'T') # look for depth record for this sample
        sampdepths=pmag.get_dictitem(samprecs,depth_scale,'','F') # see if there are non-blank depth data
        if dmax!=-1:
            sampdepths=pmag.get_dictitem(sampdepths,depth_scale,dmax,'max') # fishes out records within depth bounds
            sampdepths=pmag.get_dictitem(sampdepths,depth_scale,dmin,'min')
        if len(sampdepths)>0: # if there are any....
            rec['core_depth'] = sampdepths[0][depth_scale] # set the core depth of this record
            Data.append(rec) # fish out data with core_depth
            if isbulk:  # if there are bulk data
                chis=pmag.get_dictitem(Meas,'er_specimen_name',rec['er_specimen_name'],'T')
                chis=pmag.get_dictitem(chis,'measurement_chi_volume','','F') # get the non-zero values for this specimen
                if len(chis)>0: # if there are any....
                    Bulks.append(1e6*float(chis[0]['measurement_chi_volume'])) # put in microSI
                    BulkDepths.append(float(sampdepths[0][depth_scale]))
    if len(Bulks)>0: # set min and max bulk values
        bmin=min(Bulks)
        bmax=max(Bulks)
    xlab="Depth (m)"
    if len(Data)>0:
        location=Data[0]['er_location_name']
    else:
        print 'no data to plot'
        sys.exit()
    # collect the data for plotting tau and V3_inc
    Depths,Tau1,Tau2,Tau3,V3Incs,P=[],[],[],[],[],[]
    Axs=[] # collect the plot ids
    if len(Bulks)>0: pcol+=1
    s1=pmag.get_dictkey(Data,'anisotropy_s1','f') # get all the s1 values from Data as floats
    s2=pmag.get_dictkey(Data,'anisotropy_s2','f')
    s3=pmag.get_dictkey(Data,'anisotropy_s3','f')
    s4=pmag.get_dictkey(Data,'anisotropy_s4','f')
    s5=pmag.get_dictkey(Data,'anisotropy_s5','f')
    s6=pmag.get_dictkey(Data,'anisotropy_s6','f')
    Depths=pmag.get_dictkey(Data,'core_depth','f')
    Ss=numpy.array([s1,s4,s5,s4,s2,s6,s5,s6,s3]).transpose() # make an array
    Ts=numpy.reshape(Ss,(len(Ss),3,-1)) # and re-shape to be n-length array of 3x3 sub-arrays
    for k in range(len(Depths)):
        tau,Evecs= pmag.tauV(Ts[k]) # get the sorted eigenvalues and eigenvectors
        v3=pmag.cart2dir(Evecs[2])[1] # convert to inclination of the minimum eigenvector
        V3Incs.append(v3)
        Tau1.append(tau[0])
        Tau2.append(tau[1])
        Tau3.append(tau[2])
        P.append(tau[0]/tau[2])
    if len(Depths)>0:
        if dmax==-1:
            dmax=max(Depths)
            dmin=min(Depths)
        tau_max=max(Tau1)
        tau_min=min(Tau3)
        P_max=max(P)
        P_min=min(P)
        #dmax=dmax+.05*dmax
        #dmin=dmin-.05*dmax
        pylab.figure(1,figsize=(10,8)) # make the figure
        version_num=pmag.get_version()
        pylab.figtext(.02,.01,version_num) # attach the pmagpy version number
        ax=pylab.subplot(1,pcol,1) # make the first column
        Axs.append(ax)
        ax.plot(Tau1,Depths,'rs') 
        ax.plot(Tau2,Depths,'b^') 
        ax.plot(Tau3,Depths,'ko') 
        ax.axis([tau_min,tau_max,dmax,dmin])
        ax.set_xlabel('Eigenvalues')
        if depth_scale=='sample_core_depth':
            ax.set_ylabel('Depth (mbsf)')
        elif depth_scale=='age':
            ax.set_ylabel('Age ('+age_unit+')')
        else:
            ax.set_ylabel('Depth (mcd)')
        ax2=pylab.subplot(1,pcol,2) # make the second column
        ax2.plot(P,Depths,'rs') 
        ax2.axis([P_min,P_max,dmax,dmin])
        ax2.set_xlabel('P')
        ax2.set_title(location)
        Axs.append(ax2)
        ax3=pylab.subplot(1,pcol,3)
        Axs.append(ax3)
        ax3.plot(V3Incs,Depths,'ko') 
        ax3.axis([0,90,dmax,dmin])
        ax3.set_xlabel('V3 Inclination')
        if pcol==4:
            ax4=pylab.subplot(1,pcol,4)
            Axs.append(ax4)
            ax4.plot(Bulks,BulkDepths,'bo') 
            ax4.axis([bmin-1,bmax+1,dmax,dmin])
            ax4.set_xlabel('Bulk Susc. (uSI)')
        for x in Axs:pmagplotlib.delticks(x) # this makes the x-tick labels more reasonable - they were overcrowded using the defaults
        figname=location+'_ani-depthplot'+fmt
        if verbose:
            pylab.draw()
            ans=raw_input("S[a]ve plot? Return to quit ")
            if ans=='a':
                pylab.savefig(figname)
                print 'Plot saved as ',figname
        elif plots:
            pylab.savefig(figname)
            print 'Plot saved as ',figname
        sys.exit()
           
    else:
        print "No data points met your criteria - try again"
Example #17
0
def plotELL(pars,col,lower,plot):
    """
    function to calculate points on an ellipse about Pdec,Pdip with angle beta,gamma
    """
    rad=np.pi/180.
    Pdec,Pinc,beta,Bdec,Binc,gamma,Gdec,Ginc=pars[0],pars[1],pars[2],pars[3],pars[4],pars[5],pars[6],pars[7]
    if beta > 90. or gamma>90:
        beta=180.-beta
        gamma=180.-beta
        Pdec=Pdec-180.
        Pinc=-Pinc
    beta,gamma=beta*rad,gamma*rad # convert to radians
    X_ell,Y_ell,X_up,Y_up,PTS=[],[],[],[],[]
    nums=201
    xnum=float(nums-1.)/2.
# set up t matrix
    t=[[0,0,0],[0,0,0],[0,0,0]]
    X=pmag.dir2cart((Pdec,Pinc,1.0)) # convert to cartesian coordintes
    if lower==1 and X[2]<0:
       for i in range(3):
           X[i]=-X[i]
# set up rotation matrix t
    t[0][2]=X[0]
    t[1][2]=X[1]
    t[2][2]=X[2]
    X=pmag.dir2cart((Bdec,Binc,1.0))
    if lower==1 and X[2]<0:
       for i in range(3):
           X[i]=-X[i]
    t[0][0]=X[0]
    t[1][0]=X[1]
    t[2][0]=X[2]
    X=pmag.dir2cart((Gdec,Ginc,1.0))
    if lower==1 and X[2]<0:
       for i in range(3):
           X[i]=-X[i]
    t[0][1]=X[0]
    t[1][1]=X[1]
    t[2][1]=X[2]
# set up v matrix
    v=[0,0,0]
    for i in range(nums):  # incremental point along ellipse
        psi=float(i)*np.pi/xnum
        v[0]=np.sin(beta)*np.cos(psi)
        v[1]=np.sin(gamma)*np.sin(psi)
        v[2]=np.sqrt(1.-v[0]**2 - v[1]**2)
        elli=[0,0,0]
# calculate points on the ellipse
        for j in range(3):
            for k in range(3):
                elli[j]=elli[j] + t[j][k]*v[k]  # cartesian coordinate j of ellipse
        PTS.append(pmag.cart2dir(elli))
        R=np.sqrt( 1.-abs(elli[2]))/(np.sqrt(elli[0]**2+elli[1]**2)) # put on an equal area projection
        if elli[2]<0:
#            for i in range(3): elli[i]=-elli[i]
            X_up.append(elli[1]*R)
            Y_up.append(elli[0]*R)
            # Adding None values stops plotting of an additional straight line 
            # between the points where the ellipse crosses the edge of the stereonet
            X_ell.append(None)
            Y_ell.append(None)            
        else:
            X_ell.append(elli[1]*R)
            Y_ell.append(elli[0]*R)
    if plot==1:
        if X_ell!=[]:plt.plot(X_ell,Y_ell,color=col, linewidth=2, zorder=6)
        if X_up!=[]:plt.plot(X_up,Y_up,color=col,linewidth=2,linestyle=':')
    else:
        return PTS
Example #18
0
def dokent(data, NN):  #From PmagPy (Tauxe et al., 2016)
    """
    gets Kent  parameters for data ([D,I],N)
    """
    X, kpars = [], {}
    N = len(data)
    if N < 2:
        return kpars
#
#  get fisher mean and convert to co-inclination (theta)/dec (phi) in radians
#
    fpars = pmag.fisher_mean(data)
    pbar = fpars["dec"] * np.pi / 180.
    tbar = (90. - fpars["inc"]) * np.pi / 180.
    #
    #   initialize matrices
    #
    H = [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]
    w = [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]
    b = [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]
    gam = [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]
    xg = []
    #
    #  set up rotation matrix H
    #
    H = [[
        np.cos(tbar) * np.cos(pbar), -np.sin(pbar),
        np.sin(tbar) * np.cos(pbar)
    ], [
        np.cos(tbar) * np.sin(pbar),
        np.cos(pbar),
        np.sin(pbar) * np.sin(tbar)
    ], [-np.sin(tbar), 0., np.cos(tbar)]]
    #
    #  get cartesian coordinates of data
    #
    for rec in data:
        X.append(pmag.dir2cart([rec[0], rec[1], 1.]))
#
#   put in T matrix
#
    T = pmag.Tmatrix(X)
    for i in range(3):
        for j in range(3):
            T[i][j] = old_div(T[i][j], float(NN))
#
# compute B=H'TH
#
    for i in range(3):
        for j in range(3):
            for k in range(3):
                w[i][j] += T[i][k] * H[k][j]
    for i in range(3):
        for j in range(3):
            for k in range(3):
                b[i][j] += H[k][i] * w[k][j]
#
# choose a rotation w about North pole to diagonalize upper part of B
#
    psi = 0.5 * np.arctan(2. * b[0][1] / (b[0][0] - b[1][1]))
    w = [[np.cos(psi), -np.sin(psi), 0], [np.sin(psi),
                                          np.cos(psi), 0], [0., 0., 1.]]
    for i in range(3):
        for j in range(3):
            gamtmp = 0.
            for k in range(3):
                gamtmp += H[i][k] * w[k][j]
            gam[i][j] = gamtmp
    for i in range(N):
        xg.append([0., 0., 0.])
        for k in range(3):
            xgtmp = 0.
            for j in range(3):
                xgtmp += gam[j][k] * X[i][j]
            xg[i][k] = xgtmp
# compute asymptotic ellipse parameters
#
    xmu, sigma1, sigma2 = 0., 0., 0.
    for i in range(N):
        xmu += xg[i][2]
        sigma1 = sigma1 + xg[i][0]**2
        sigma2 = sigma2 + xg[i][1]**2
    xmu = old_div(xmu, float(N))
    sigma1 = old_div(sigma1, float(N))
    sigma2 = old_div(sigma2, float(N))
    g = -2.0 * np.log(0.05) / (float(NN) * xmu**2)
    if np.sqrt(sigma1 * g) < 1:
        eta = np.arcsin(np.sqrt(sigma1 * g))
    if np.sqrt(sigma2 * g) < 1:
        zeta = np.arcsin(np.sqrt(sigma2 * g))
    if np.sqrt(sigma1 * g) >= 1.:
        eta = old_div(np.pi, 2.)
    if np.sqrt(sigma2 * g) >= 1.:
        zeta = old_div(np.pi, 2.)
#
#  convert Kent parameters to directions,angles
#
    kpars["dec"] = fpars["dec"]
    kpars["inc"] = fpars["inc"]
    kpars["n"] = NN
    ZDir = pmag.cart2dir([gam[0][1], gam[1][1], gam[2][1]])
    EDir = pmag.cart2dir([gam[0][0], gam[1][0], gam[2][0]])
    kpars["Zdec"] = ZDir[0]
    kpars["Zinc"] = ZDir[1]
    kpars["Edec"] = EDir[0]
    kpars["Einc"] = EDir[1]
    if kpars["Zinc"] < 0:
        kpars["Zinc"] = -kpars["Zinc"]
        kpars["Zdec"] = (kpars["Zdec"] + 180.) % 360.
    if kpars["Einc"] < 0:
        kpars["Einc"] = -kpars["Einc"]
        kpars["Edec"] = (kpars["Edec"] + 180.) % 360.
    kpars["Zeta"] = zeta * 180. / np.pi
    kpars["Eta"] = eta * 180. / np.pi
    return kpars
Example #19
0
def main():
    """
    NAME
        igrf.py

    DESCRIPTION
        This program calculates igrf field values 
    using the routine of Malin and  Barraclough (1981) 
    based on d/igrfs from 1900 to 2010.
    between 1900 and 1000BCE, it uses CALS3K.4 or ARCH3K.1 
    Prior to 1000BCE, it uses CALS10k-4b
    Calculates reference field vector at  specified location and time.

  
    SYNTAX
       igrf.py [-h] [-i] -f FILE  [< filename]

    OPTIONS:
       -h prints help message and quits
       -i for interactive data entry
       -f FILE  specify file name with input data 
       -F FILE  specify output file name
       -ages MIN MAX INCR: specify age minimum in years (+/- AD), maximum and increment, default is line by line
       -loc LAT LON;  specify location, default is line by line
       -alt ALT;  specify altitude in km, default is sealevel (0)
       -plt; make a plot of the time series
       -fmt [pdf,jpg,eps,svg]  specify format for output figure  (default is svg)
       -mod [arch3k,cals3k] specify model for 3ka to 1900 AD, default is cals3k.4b
    
    INPUT FORMAT 
      interactive entry:
           date: decimal year
           alt:  altitude in km
           lat: positive north
           lon: positive east
       for file entry:
           space delimited string: date  alt   lat long

    OUTPUT  FORMAT
        Declination Inclination Intensity (nT) date alt lat long
    """
    plt,fmt=0,'svg'
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if len(sys.argv)!=0 and '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-mod' in sys.argv:
        ind=sys.argv.index('-mod')
        mod3k=sys.argv[ind+1]
    else: mod3k=''
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        input=numpy.loadtxt(file)
    elif '-i' in sys.argv:
        while 1:
          try:
            line=[]
            line.append(float(raw_input("Decimal year: <cntrl-D to quit> ")))
            alt=raw_input("Elevation in km [0] ")
            if alt=="":alt="0"
            line.append(float(alt))
            line.append(float(raw_input("Latitude (positive north) ")))
            line.append(float(raw_input("Longitude (positive east) ")))
            if mod3k=='':
                x,y,z,f=pmag.doigrf(line[3]%360.,line[2],line[1],line[0])
            else:
                x,y,z,f=pmag.doigrf(line[3]%360.,line[2],line[1],line[0],mod3k=mod3k)
            Dir=pmag.cart2dir((x,y,z))
            print '%7.1f %7.1f %8.0f'%(Dir[0],Dir[1],f)           
          except EOFError:
            print "\n Good-bye\n"
            sys.exit()
    elif '-ages' in sys.argv:
        ind=sys.argv.index('-ages')
        agemin=float(sys.argv[ind+1])
        agemax=float(sys.argv[ind+2])
        ageincr=float(sys.argv[ind+3])
        if '-loc' in sys.argv:
            ind=sys.argv.index('-loc')
            lat=float(sys.argv[ind+1])
            lon=float(sys.argv[ind+2])
        else: 
            print "must specify lat/lon if using age range option"
            sys.exit()
        if '-alt' in sys.argv:
            ind=sys.argv.index('-alt')
            alt=float(sys.argv[ind+1])
        else: alt=0
        ages=numpy.arange(agemin,agemax,ageincr)
        lats=numpy.ones(len(ages))*lat
        lons=numpy.ones(len(ages))*lon
        alts=numpy.ones(len(ages))*alt
        input=numpy.array([ages,alts,lats,lons]).transpose()
    else:
        input=numpy.loadtxt(sys.stdin,dtype=numpy.float)
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        outfile=sys.argv[ind+1]
        out=open(outfile,'w')
    else:outfile=""
    if '-plt' in sys.argv:
        plt=1
        import matplotlib
        matplotlib.use("TkAgg")
        import pylab
        pylab.ion()
        Ages,Decs,Incs,Ints,VADMs=[],[],[],[],[]
    for line in input:
        if mod3k=='':
            x,y,z,f=pmag.doigrf(line[3]%360.,line[2],line[1],line[0])
        else:
            x,y,z,f=pmag.doigrf(line[3]%360.,line[2],line[1],line[0],mod3k=mod3k)
        Dir=pmag.cart2dir((x,y,z))
        if outfile!="":
            out.write('%7.1f %7.1f %8.0f %7.1f %7.1f %7.1f %7.1f\n'%(Dir[0],Dir[1],f,line[0],line[1],line[2],line[3]))           
        elif plt:
            Ages.append(line[0])
            if Dir[0]>180: Dir[0]=Dir[0]-360.0
            Decs.append(Dir[0])
            Incs.append(Dir[1])
            Ints.append(f*1e-3)
            VADMs.append(pmag.b_vdm(f*1e-9,line[2])*1e-21)
        else:
            print '%7.1f %7.1f %8.0f %7.1f %7.1f %7.1f %7.1f'%(Dir[0],Dir[1],f,line[0],line[1],line[2],line[3])           
    if plt:
        fig=pylab.figure(num=1,figsize=(7,9))
        fig.add_subplot(411)
        pylab.plot(Ages,Decs)
        pylab.ylabel('Declination ($^{\circ}$)')
        fig.add_subplot(412)
        pylab.plot(Ages,Incs)
        pylab.ylabel('Inclination ($^{\circ}$)')
        fig.add_subplot(413)
        pylab.plot(Ages,Ints)
        pylab.ylabel('Intensity ($\mu$T)')
        fig.add_subplot(414)
        pylab.plot(Ages,VADMs)
        pylab.ylabel('VADMs (ZAm$^2$)')
        pylab.xlabel('Ages')
        pylab.draw()
        ans=raw_input("S[a]ve to save figure, <Return>  to quit  ")
        if ans=='a':
            pylab.savefig('igrf.'+fmt)
            print 'Figure saved as: ','igrf.'+fmt
        sys.exit()
Example #20
0
def plotELL(pars, col, lower, plot):
    """
    function to calculate points on an ellipse about Pdec,Pdip with angle beta,gamma
    """
    rad = np.pi / 180.
    Pdec, Pinc, beta, Bdec, Binc, gamma, Gdec, Ginc = pars[0], pars[1], pars[
        2], pars[3], pars[4], pars[5], pars[6], pars[7]
    if beta > 90. or gamma > 90:
        beta = 180. - beta
        gamma = 180. - beta
        Pdec = Pdec - 180.
        Pinc = -Pinc
    beta, gamma = beta * rad, gamma * rad  # convert to radians
    X_ell, Y_ell, X_up, Y_up, PTS = [], [], [], [], []
    nums = 201
    xnum = float(nums - 1.) / 2.
    # set up t matrix
    t = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    X = pmag.dir2cart((Pdec, Pinc, 1.0))  # convert to cartesian coordintes
    if lower == 1 and X[2] < 0:
        for i in range(3):
            X[i] = -X[i]
# set up rotation matrix t
    t[0][2] = X[0]
    t[1][2] = X[1]
    t[2][2] = X[2]
    X = pmag.dir2cart((Bdec, Binc, 1.0))
    if lower == 1 and X[2] < 0:
        for i in range(3):
            X[i] = -X[i]
    t[0][0] = X[0]
    t[1][0] = X[1]
    t[2][0] = X[2]
    X = pmag.dir2cart((Gdec, Ginc, 1.0))
    if lower == 1 and X[2] < 0:
        for i in range(3):
            X[i] = -X[i]
    t[0][1] = X[0]
    t[1][1] = X[1]
    t[2][1] = X[2]
    # set up v matrix
    v = [0, 0, 0]
    for i in range(nums):  # incremental point along ellipse
        psi = float(i) * np.pi / xnum
        v[0] = np.sin(beta) * np.cos(psi)
        v[1] = np.sin(gamma) * np.sin(psi)
        v[2] = np.sqrt(1. - v[0]**2 - v[1]**2)
        elli = [0, 0, 0]
        # calculate points on the ellipse
        for j in range(3):
            for k in range(3):
                elli[j] = elli[j] + t[j][k] * v[
                    k]  # cartesian coordinate j of ellipse
        PTS.append(pmag.cart2dir(elli))
        R = np.sqrt(1. - abs(elli[2])) / (np.sqrt(elli[0]**2 + elli[1]**2)
                                          )  # put on an equal area projection
        if elli[2] < 0:
            #            for i in range(3): elli[i]=-elli[i]
            X_up.append(elli[1] * R)
            Y_up.append(elli[0] * R)
            # Adding None values stops plotting of an additional straight line
            # between the points where the ellipse crosses the edge of the stereonet
            X_ell.append(None)
            Y_ell.append(None)
        else:
            X_ell.append(elli[1] * R)
            Y_ell.append(elli[0] * R)
    if plot == 1:
        if X_ell != []:
            plt.plot(X_ell, Y_ell, color=col, linewidth=2, zorder=6)
        if X_up != []:
            plt.plot(X_up, Y_up, color=col, linewidth=2, linestyle=':')
    else:
        return PTS
 def calculate_aniso_parameters(B,K):
 
     aniso_parameters={}
     S_bs=dot(B,K)
     
     # normalize by trace
     trace=S_bs[0]+S_bs[1]+S_bs[2]
     S_bs=S_bs/trace
     s1,s2,s3,s4,s5,s6=S_bs[0],S_bs[1],S_bs[2],S_bs[3],S_bs[4],S_bs[5]
     s_matrix=[[s1,s4,s6],[s4,s2,s5],[s6,s5,s3]]
     
     # calculate eigen vector,
     t,evectors=eig(s_matrix)
     # sort vectors
     t=list(t)
     t1=max(t)
     ix_1=t.index(t1)
     t3=min(t)
     ix_3=t.index(t3)
     for tt in range(3):
         if t[tt]!=t1 and t[tt]!=t3:
             t2=t[tt]
             ix_2=t.index(t2)
             
     v1=[evectors[0][ix_1],evectors[1][ix_1],evectors[2][ix_1]]
     v2=[evectors[0][ix_2],evectors[1][ix_2],evectors[2][ix_2]]
     v3=[evectors[0][ix_3],evectors[1][ix_3],evectors[2][ix_3]]
 
 
     DIR_v1=pmag.cart2dir(v1)
     DIR_v2=pmag.cart2dir(v2)
     DIR_v3=pmag.cart2dir(v3)
 
                         
     aniso_parameters['anisotropy_s1']="%f"%s1
     aniso_parameters['anisotropy_s2']="%f"%s2
     aniso_parameters['anisotropy_s3']="%f"%s3
     aniso_parameters['anisotropy_s4']="%f"%s4
     aniso_parameters['anisotropy_s5']="%f"%s5
     aniso_parameters['anisotropy_s6']="%f"%s6
     aniso_parameters['anisotropy_degree']="%f"%(t1/t3)
     aniso_parameters['anisotropy_t1']="%f"%t1
     aniso_parameters['anisotropy_t2']="%f"%t2
     aniso_parameters['anisotropy_t3']="%f"%t3
     aniso_parameters['anisotropy_v1_dec']="%.1f"%DIR_v1[0]
     aniso_parameters['anisotropy_v1_inc']="%.1f"%DIR_v1[1]
     aniso_parameters['anisotropy_v2_dec']="%.1f"%DIR_v2[0]
     aniso_parameters['anisotropy_v2_inc']="%.1f"%DIR_v2[1]
     aniso_parameters['anisotropy_v3_dec']="%.1f"%DIR_v3[0]
     aniso_parameters['anisotropy_v3_inc']="%.1f"%DIR_v3[1]
 
     # modified from pmagpy:
     if len(K)/3==9 or len(K)/3==6 or len(K)/3==15:
         n_pos=len(K)/3
         tmpH = Matrices[n_pos]['tmpH']
         a=s_matrix
         S=0.
         comp=zeros((n_pos*3),'f')
         for i in range(n_pos):
             for j in range(3):
                 index=i*3+j
                 compare=a[j][0]*tmpH[i][0]+a[j][1]*tmpH[i][1]+a[j][2]*tmpH[i][2]
                 comp[index]=compare
         for i in range(n_pos*3):
             d=K[i]/trace - comp[i] # del values
             S+=d*d
         nf=float(n_pos*3-6) # number of degrees of freedom
         if S >0: 
             sigma=math.sqrt(S/nf)
         hpars=pmag.dohext(nf,sigma,[s1,s2,s3,s4,s5,s6])
         
         aniso_parameters['anisotropy_sigma']="%f"%sigma
         aniso_parameters['anisotropy_ftest']="%f"%hpars["F"]
         aniso_parameters['anisotropy_ftest12']="%f"%hpars["F12"]
         aniso_parameters['anisotropy_ftest23']="%f"%hpars["F23"]
         aniso_parameters['result_description']="Critical F: %s"%(hpars['F_crit'])
         aniso_parameters['anisotropy_F_crit']="%f"%float(hpars['F_crit'])
         aniso_parameters['anisotropy_n']=n_pos
         
     return(aniso_parameters)