Exemplo n.º 1
0
def main():
    """
    NAME
       probRo.py

    DESCRIPTION
       Calculates Ro as a test for randomness - if R exceeds Ro given N, then set is not random at 95% level of confindence

    SYNTAX
       probRo.py [command line options]

    OPTIONS
        -h prints this help message
        -Nm number of Monte Carlo simulations (default is 10000)
        -Nmax maximum number for dataset (default is 10)
    """
    Ns,Nm=range(4,11),10000
    files,fmt={},'svg'
    if '-h' in sys.argv: # check if help is needed
        print main.__doc__
        sys.exit() # graceful quit
    if '-Nm' in sys.argv: 
        ind=sys.argv.index('-Nm')
        Nm=int(sys.argv[ind+1])
    if '-Nmax' in sys.argv: 
        ind=sys.argv.index('-Nmax')
        Nmax=int(sys.argv[ind+1])
        Ns=range(3,Nmax+1)
    PLT={'plt':1}
    pmagplotlib.plot_init(PLT['plt'],5,5)
    Ro=[]
    for N in Ns:
        Rs=[]
        n=0
        while n<Nm:
            dirs=pmag.get_unf(N)
            pars=pmag.fisher_mean(dirs)
            Rs.append(pars['r'])
            n+=1
        Rs.sort()
        crit=int(.95*Nm)
        Ro.append(Rs[crit])
    pmagplotlib.plotXY(PLT['plt'],Ns,Ro,'-','N','Ro','')
    pmagplotlib.plotXY(PLT['plt'],Ns,Ro,'ro','N','Ro','')
    pmagplotlib.drawFIGS(PLT)
    for key in PLT.keys():
        files[key]=key+'.'+fmt
    ans=raw_input(" S[a]ve to save plot, [q]uit without saving:  ")
    if ans=="a": pmagplotlib.saveP(PLT,files)
Exemplo n.º 2
0
def main():
    """
    NAME
        biplot_magic.py

    DESCRIPTION
        makes a biplot of specified variables from magic_measurements.txt format file
  
    SYNTAX
        biplot_magic.py [-h] [-i] [command line options]

    INPUT 
        takes magic formated magic_measurments file

    OPTIONS
        -h prints help message and quits
        -i interactively set filename and axes for plotting
        -f FILE: specifies file name, default: magic_measurements.txt
        -fmt [svg,png,jpg], format for images - default is svg
        -x XMETH:key:step, specify method code for X axis (optional key and treatment values)
        -y YMETH:key:step, specify method code for X axis
        -obj OBJ: specify object [loc, sit, sam, spc] for plot, default is whole file
        -n [V,M] plot volume or mass normalized data only
    NOTES
        if nothing is specified for x and y, the user will be presented with options
        key = ['treatment_ac_field','treatment_dc_field',treatment_temp'] 
        step in mT for fields, K for temperatures
           """ 
    #
    file='magic_measurements.txt'
    methx,methy,fmt="","",'.svg'
    plot_key=''
    norm_by=""
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt='.'+sys.argv[ind+1]
    if '-n' in sys.argv:
        ind=sys.argv.index('-n')
        norm_by=sys.argv[ind+1]
    xtreat_key,ytreat_key,xstep,ystep="","","",""
    if '-x' in sys.argv:
        ind=sys.argv.index('-x')
        meths=sys.argv[ind+1].split(':')
        methx=meths[0]
        if len(meths)>1:
            xtreat_key=meths[1]
            xstep=float(meths[2])
    if '-y' in sys.argv:
        ind=sys.argv.index('-y')
        meths=sys.argv[ind+1].split(':')
        methy=meths[0]
        if len(meths)>1:
            ytreat_key=meths[1]
            ystep=float(meths[2])
    if '-obj' in sys.argv: 
        ind=sys.argv.index('-obj')
        plot_by=sys.argv[ind+1]
        if plot_by=='loc':plot_key='er_location_name'
        if plot_by=='sit':plot_key='er_site_name'
        if plot_by=='sam':plot_key='er_sample_name'
        if plot_by=='spc':plot_key='er_specimen_name'

    if '-i' in sys.argv: 
    #
    # get name of file from command line
    #
        file=raw_input("Input magic_measurments file name? [magic_measurements.txt] ")
        if file=="":file="magic_measurements.txt"
    #
    #
    FIG={'fig':1}
    pmagplotlib.plot_init(FIG['fig'],5,5)
    data,file_type=pmag.magic_read(file)
    if file_type!="magic_measurements":
        print file_type,' not correct format for magic_measurments file'
        sys.exit()
    #
    # collect method codes
    methods,plotlist=[],[]
    for rec in  data:
        if plot_key!="":
            if rec[plot_key] not in plotlist:plotlist.append(rec[plot_key])
        elif len(plotlist)==0:
            plotlist.append('All')
        meths=rec['magic_method_codes'].split(':')
        for meth in meths:
            if meth.strip() not in methods and meth.strip()!="LP-":
                methods.append(meth.strip())
    #
    if '-i' in sys.argv:
        print methods
    elif methx =="" or methy=="": 
	print methods
        sys.exit()
    GoOn=1
    while GoOn==1:
        if '-i' in sys.argv:methx=raw_input('Select method for x axis: ')
        if methx not in methods:
            if '-i' in sys.argv:
                print 'try again! method not available'
            else: 
                print main.__doc__
                print '\n must specify X axis method\n'
                sys.exit()
        else:
            if pmagplotlib.verbose: print methx, ' selected for X axis'
            GoOn=0
    GoOn=1
    while GoOn==1:
        if '-i' in sys.argv:methy=raw_input('Select method for y axis: ')
        if methy not in methods:
            if '-i' in sys.argv:
                print 'try again! method not available'
            else: 
                print main.__doc__
                print '\n must specify Y axis method\n'
                sys.exit()
        else:
            if pmagplotlib.verbose: print methy, ' selected for Y axis'
            GoOn=0
    if norm_by=="":
        measkeys=['measurement_magn_mass','measurement_magn_volume','measurement_magn_moment','measurement_magnitude','measurement_chi_volume','measurement_chi_mass','measurement_chi']
    elif norm_by=="V":
        measkeys=['measurement_magn_volume','measurement_chi_volume']
    elif norm_by=="M":
        measkeys=['measurement_magn_mass','measurement_chi_mass']
    xmeaskey,ymeaskey="",""
    plotlist.sort()
    for plot in plotlist: # go through objects
        if pmagplotlib.verbose: print plot
        X,Y=[],[]
        x,y='',''
        for rec in data:
            if plot_key!="" and rec[plot_key]!=plot:
                pass
            else:
                meths=rec['magic_method_codes'].split(':')
                for meth in meths:
                    if meth.strip()==methx:
                        if xmeaskey=="":
                            for key in measkeys:
                                if key in rec.keys() and rec[key]!="":
                                    xmeaskey=key
                                    if pmagplotlib.verbose: print xmeaskey,' being used for plotting X.'
                                    break 
                    if meth.strip()==methy:
                        if ymeaskey=="":
                            for key in measkeys:
                                if key in rec.keys() and rec[key]!="":
                                    ymeaskey=key
                                    if pmagplotlib.verbose: print ymeaskey,' being used for plotting Y'
                                    break 
        if ymeaskey!="" and xmeaskey!="":
            for rec in data:
                x,y='',''
                spec=rec['er_specimen_name'] # get the ydata for this specimen
                if rec[ymeaskey]!="" and methy in rec['magic_method_codes'].split(':'): 
                    if ytreat_key=="" or (ytreat_key in rec.keys() and float(rec[ytreat_key])==ystep):
                        y=float(rec[ymeaskey])
                        for rec in data: # now find the xdata 
                            if rec['er_specimen_name']==spec and rec[xmeaskey]!="" and methx in rec['magic_method_codes'].split(':'): 
                                if xtreat_key=="" or (xtreat_key in rec.keys() and float(rec[xtreat_key])==xstep):
                                    x=float(rec[xmeaskey])
                if x != '' and y!= '':
                    X.append(x)
                    Y.append(y)
        if len(X)>0:
            pmagplotlib.clearFIG(FIG['fig'])
            pmagplotlib.plotXY(FIG['fig'],X,Y,'ro',methx,methy,plot+':Biplot')
            if not pmagplotlib.isServer:
                ans=raw_input('S[a]ve plots, [q]uit,  Return for next plot ' )
                if ans=='a':
                    files={}
                    for key in FIG.keys(): files[key]=plot+'_'+key+fmt
                    pmagplotlib.saveP(FIG,files)
                if ans=='q':
                    print "Good-bye\n"
                    sys.exit()
            else:
                files={}
                for key in FIG.keys(): files[key]=plot+'_'+key+fmt
                if pmagplotlib.isServer:
                    black     = '#000000'
                    purple    = '#800080'
                    titles={}
                    titles['fig']='X Y Plot'
                    FIG = pmagplotlib.addBorders(FIG,titles,black,purple)
                pmagplotlib.saveP(FIG,files)
        else:
            print 'nothing to plot for ',plot
Exemplo n.º 3
0
def main():
    """
    NAME
        plot_geomagia.py

    DESCRIPTION
        makes a map  and VADM plot of geomagia download file 

    SYNTAX
        plot_geomagia.py  [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE, specify geomagia download file
        -res [c,l,i,h] specify resolution (crude,low,intermediate,high)
        -etp plot the etopo20 topographic mesh
        -pad [LAT LON]  pad bounding box by LAT/LON  (default is [.5 .5] degrees)
        -grd SPACE specify grid spacing
        -prj [lcc] , specify projection (lcc=lambert conic conformable), default is mercator
        -o color ocean blue/land green (default is not)
        -d plot details of rivers, boundaries, etc.
        -sav save plot and quit quietly
        -fmt [png,svg,eps,jpg,pdf] specify format for output, default is pdf
    DEFAULTS
        resolution: intermediate
        saved images are in pdf
    """
    dir_path='.'
    names,res,proj,locs,padlon,padlat,fancy,gridspace,details=[],'l','lcc','',0,0,0,15,1
    Age_bounds=[-5000,2000]
    Lat_bounds=[20,45]
    Lon_bounds=[15,55]
    fmt='pdf'
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        sites_file=sys.argv[ind+1]
    if '-res' in sys.argv:
        ind = sys.argv.index('-res')
        res=sys.argv[ind+1]
    if '-etp' in sys.argv:fancy=1
    if '-o' in sys.argv:ocean=1
    if '-d' in sys.argv:details=1
    if '-prj' in sys.argv:
        ind = sys.argv.index('-prj')
        proj=sys.argv[ind+1]
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    verbose=pmagplotlib.verbose
    if '-sav' in sys.argv:
        verbose=0
    if '-pad' in sys.argv:
        ind = sys.argv.index('-pad')
        padlat=float(sys.argv[ind+1])
        padlon=float(sys.argv[ind+2])
    if '-grd' in sys.argv:
        ind = sys.argv.index('-grd')
        gridspace=float(sys.argv[ind+1])
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    sites_file=dir_path+'/'+sites_file
    geo_in=open(sites_file,'rU').readlines()
    Age,AgeErr,Vadm,VadmErr,slats,slons=[],[],[],[],[],[]
    for line in geo_in[2:]: # skip top two rows`
        rec=line.split()
        if float(rec[0])>Age_bounds[0] and float(rec[0])<Age_bounds[1] \
           and float(rec[12])>Lat_bounds[0] and float(rec[12]) < Lat_bounds[1]\
            and float(rec[13])>Lon_bounds[0] and float(rec[13])<Lon_bounds[1]:
            Age.append(float(rec[0]))
            AgeErr.append(float(rec[1]))
            Vadm.append(10.*float(rec[6]))
            VadmErr.append(10.*float(rec[7]))
            slats.append(float(rec[12]))
            slons.append(float(rec[13]))
    FIGS={'map':1,'vadms':2}
    pmagplotlib.plot_init(FIGS['map'],6,6)
    pmagplotlib.plot_init(FIGS['vadms'],6,6)
    Opts={'res':res,'proj':proj,'loc_name':locs,'padlon':padlon,'padlat':padlat,'latmin':numpy.min(slats)-padlat,'latmax':numpy.max(slats)+padlat,'lonmin':numpy.min(slons)-padlon,'lonmax':numpy.max(slons)+padlon,'sym':'ro','boundinglat':0.,'pltgrid':1}
    Opts['lon_0']=int(0.5*(numpy.min(slons)+numpy.max(slons)))
    Opts['lat_0']=int(0.5*(numpy.min(slats)+numpy.max(slats)))
    Opts['gridspace']=gridspace
    if details==1:
        Opts['details']={'coasts':1,'rivers':0,'states':1,'countries':1,'ocean':1}
    else:
        Opts['details']={'coasts':1,'rivers':0,'states':0,'countries':0,'ocean':1}
    Opts['details']['fancy']=fancy
    pmagplotlib.plotMAP(FIGS['map'],slats,slons,Opts)
    pmagplotlib.plotXY(FIGS['vadms'],Age,Vadm,sym='bo',xlab='Age (Years CE)',ylab=r'VADM (ZAm$^2$)')
    if verbose:pmagplotlib.drawFIGS(FIGS)
    files={}
    for key in FIGS.keys():
        files[key]=key+'.'+fmt
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['map']='Map'
        titles['vadms']='VADMs'
        FIG = pmagplotlib.addBorders(FIGS,titles,black,purple)
        pmagplotlib.saveP(FIGS,files)
    elif verbose:
        ans=raw_input(" S[a]ve to save plot, Return to quit:  ")
        if ans=="a":
            pmagplotlib.saveP(FIGS,files)
    else:
        pmagplotlib.saveP(FIGS,files)
Exemplo n.º 4
0
def main():
    """
    NAME
        site_edit_magic.py

    DESCRIPTION
       makes equal area projections site by site
         from pmag_specimens.txt file with
         Fisher confidence ellipse using McFadden and McElhinny (1988)
         technique for combining lines and planes
         allows testing and reject specimens for bad orientations

    SYNTAX
        site_edit_magic.py [command line options]

    OPTIONS
       -h: prints help and quits
       -f: specify pmag_specimen format file, default is pmag_specimens.txt
       -fsa: specify er_samples.txt file
       -exc: use existing pmag_criteria.txt file
       -N: reset all sample flags to good
    
    OUPUT
       edited er_samples.txt file

    """
    dir_path='.'
    FIG={} # plot dictionary
    FIG['eqarea']=1 # eqarea is figure 1
    in_file='pmag_specimens.txt'
    sampfile='er_samples.txt'
    out_file=""
    fmt,plot='svg',1
    Crits=""
    M,N=180.,1
    repeat=''
    renew=0
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    if '-f' in sys.argv:
        ind=sys.argv.index("-f")
        in_file=sys.argv[ind+1]
    if '-fsa' in sys.argv:
        ind=sys.argv.index("-fsa")
        sampfile=sys.argv[ind+1]
    if '-exc' in sys.argv:
        Crits,file_type=pmag.magic_read(dir_path+'/pmag_criteria.txt')
        for crit in Crits:
            if crit['pmag_criteria_code']=='DE-SPEC':
                M=float(crit['specimen_mad'])
                N=float(crit['specimen_n'])
    if '-fmt' in sys.argv:
        ind=sys.argv.index("-fmt")
        fmt=sys.argv[ind+1]
    if '-N' in sys.argv: renew=1
# 
    if in_file[0]!="/":in_file=dir_path+'/'+in_file
    if sampfile[0]!="/":sampfile=dir_path+'/'+sampfile
    crd='s'
    Specs,file_type=pmag.magic_read(in_file)
    if file_type!='pmag_specimens':
        print ' bad pmag_specimen input file'
        sys.exit()
    Samps,file_type=pmag.magic_read(sampfile)
    if file_type!='er_samples':
        print ' bad er_samples input file'
        sys.exit()
    SO_methods=[]
    for rec in Samps:
       if 'sample_orientation_flag' not in rec.keys(): rec['sample_orientation_flag']='g'
       if 'sample_description' not in rec.keys(): rec['sample_description']=''
       if renew==1:
          rec['sample_orientation_flag']='g'
          description=rec['sample_description']
          if '#' in description:
               newdesc=""
               c=0
               while description[c]!='#' and c<len(description)-1: # look for first pound sign
                   newdesc=newdesc+description[c]
                   c+=1
               while description[c]=='#': 
                   c+=1# skip first set of pound signs
               while description[c]!='#':c+=1 # find second set of pound signs
               while description[c]=='#' and c<len(description)-1:c+=1 # skip second set of pound signs
               while c<len(description)-1: # look for first pound sign
                   newdesc=newdesc+description[c]
                   c+=1
               rec['sample_description']=newdesc # edit out old comment about orientations
       if "magic_method_codes" in rec:
           methlist=rec["magic_method_codes"]
           for meth in methlist.split(":"):
               if "SO" in meth.strip() and "SO-POM" not in meth.strip():
                   if meth.strip() not in SO_methods: SO_methods.append(meth.strip())
    pmag.magic_write(sampfile,Samps,'er_samples')
    SO_priorities=pmag.set_priorities(SO_methods,0)
    sitelist=[]
    for rec in Specs:
        if rec['er_site_name'] not in sitelist: sitelist.append(rec['er_site_name'])
    sitelist.sort()
    EQ={} 
    EQ['eqarea']=1
    pmagplotlib.plot_init(EQ['eqarea'],5,5)
    k=0
    while k<len(sitelist):
        site=sitelist[k]
        print site
        data=[]
        ThisSiteSpecs=pmag.get_dictitem(Specs,'er_site_name',site,'T')
        ThisSiteSpecs=pmag.get_dictitem(ThisSiteSpecs,'specimen_tilt_correction','-1','T') # get all the unoriented data
        for spec in ThisSiteSpecs:
                if spec['specimen_mad']!="" and spec['specimen_n']!="" and float(spec['specimen_mad'])<=M and float(spec['specimen_n'])>=N: 
# good spec, now get orientation....
                    redo,p=1,0
                    if len(SO_methods)<=1:
                        az_type=SO_methods[0]
                        orient=pmag.find_samp_rec(spec["er_sample_name"],Samps,az_type)
                        redo=0
                    while redo==1:
                        if p>=len(SO_priorities):
                            print "no orientation data for ",spec['er_sample_name']
                            orient["sample_azimuth"]=""
                            orient["sample_dip"]=""
                            redo=0
                        else:
                            az_type=SO_methods[SO_methods.index(SO_priorities[p])]
                            orient=pmag.find_samp_rec(spec["er_sample_name"],Samps,az_type)
                            if orient["sample_azimuth"]  !="":
                                redo=0
                        p+=1
                    if orient['sample_azimuth']!="":
                        rec={}
                        for key in spec.keys():rec[key]=spec[key]
                        rec['dec'],rec['inc']=pmag.dogeo(float(spec['specimen_dec']),float(spec['specimen_inc']),float(orient['sample_azimuth']),float(orient['sample_dip']))
                        rec["tilt_correction"]='1'
                        crd='g'
                        rec['sample_azimuth']=orient['sample_azimuth']
                        rec['sample_dip']=orient['sample_dip']
                        data.append(rec)
        if len(data)>2:
            print 'specimen, dec, inc, n_meas/MAD,| method codes '
            for i  in range(len(data)):
                print '%s: %7.1f %7.1f %s / %s | %s' % (data[i]['er_specimen_name'], data[i]['dec'], data[i]['inc'], data[i]['specimen_n'], data[i]['specimen_mad'], data[i]['magic_method_codes'])

            fpars=pmag.dolnp(data,'specimen_direction_type')
            print "\n Site lines planes  kappa   a95   dec   inc"
            print site, fpars["n_lines"], fpars["n_planes"], fpars["K"], fpars["alpha95"], fpars["dec"], fpars["inc"], fpars["R"]
            if out_file!="":
                if float(fpars["alpha95"])<=acutoff and float(fpars["K"])>=kcutoff:
                    out.write('%s %s %s\n'%(fpars["dec"],fpars['inc'],fpars['alpha95']))
            pmagplotlib.plotLNP(EQ['eqarea'],site,data,fpars,'specimen_direction_type')
            pmagplotlib.drawFIGS(EQ)
            if k!=0 and repeat!='y':
                ans=raw_input("s[a]ve plot, [q]uit, [e]dit specimens, [p]revious site, <return> to continue:\n ")
            elif k==0 and repeat!='y':
                ans=raw_input("s[a]ve plot, [q]uit, [e]dit specimens, <return> to continue:\n ")
            if ans=="p": k-=2
            if ans=="a":
                files={}
                files['eqarea']=site+'_'+crd+'_eqarea'+'.'+fmt
                pmagplotlib.saveP(EQ,files)
            if ans=="q": sys.exit()
            if ans=="e" and Samps==[]:
                print "can't edit samples without orientation file, sorry"
            elif ans=="e": 
#                k-=1
                testspec=raw_input("Enter name of specimen to check: ")
                for spec in data:
                    if spec['er_specimen_name']==testspec:
# first test wrong direction of drill arrows (flip drill direction in opposite direction and re-calculate d,i
                        d,i=pmag.dogeo(float(spec['specimen_dec']),float(spec['specimen_inc']),float(spec['sample_azimuth'])-180.,-float(spec['sample_dip']))
                        XY=pmag.dimap(d,i)
                        pmagplotlib.plotXY(EQ['eqarea'],[XY[0]],[XY[1]],sym='g^')
# first test wrong end of compass (take az-180.)
                        d,i=pmag.dogeo(float(spec['specimen_dec']),float(spec['specimen_inc']),float(spec['sample_azimuth'])-180.,float(spec['sample_dip']))
                        XY=pmag.dimap(d,i)
                        pmagplotlib.plotXY(EQ['eqarea'],[XY[0]],[XY[1]],sym='kv')
# did the sample spin in the hole?  
# now spin around specimen's z
                        X_up,Y_up,X_d,Y_d=[],[],[],[]
                        for incr in range(0,360,5):
                            d,i=pmag.dogeo(float(spec['specimen_dec'])+incr,float(spec['specimen_inc']),float(spec['sample_azimuth']),float(spec['sample_dip']))
                            XY=pmag.dimap(d,i)
                            if i>=0:
                                X_d.append(XY[0])
                                Y_d.append(XY[1])
                            else:
                                X_up.append(XY[0])
                                Y_up.append(XY[1])
                        pmagplotlib.plotXY(EQ['eqarea'],X_d,Y_d,sym='b.')
                        pmagplotlib.plotXY(EQ['eqarea'],X_up,Y_up,sym='c.')
                        pmagplotlib.drawFIGS(EQ)
                        break
                print "Triangle: wrong arrow for drill direction."
                print "Delta: wrong end of compass."
                print "Small circle:  wrong mark on sample. [cyan upper hemisphere]"
                deleteme=raw_input("Mark this sample as bad? y/[n]  ")
                if deleteme=='y':
                    reason=raw_input("Reason: [1] broke, [2] wrong drill direction, [3] wrong compass direction, [4] bad mark, [5] displaced block [6] other ")
                    if reason=='1':
                       description=' sample broke while drilling'
                    if reason=='2':
                       description=' wrong drill direction '
                    if reason=='3':
                       description=' wrong compass direction '
                    if reason=='4':
                       description=' bad mark in field'
                    if reason=='5':
                       description=' displaced block'
                    if reason=='6':
                       description=raw_input('Enter brief reason for deletion:   ')
                    for samp in Samps:
                        if samp['er_sample_name']==spec['er_sample_name']:
                            samp['sample_orientation_flag']='b'
                            samp['sample_description']=samp['sample_description']+' ## direction deleted because: '+description+'##' # mark description
                    pmag.magic_write(sampfile,Samps,'er_samples')
                repeat=raw_input("Mark another sample, this site? y/[n]  ")
                if repeat=='y': k-=1
        else:
            print 'skipping site - not enough data with specified coordinate system'
        k+=1 
    print "sample flags stored in ",sampfile
Exemplo n.º 5
0
def main():
    """
    NAME
        lowrie.py

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

    SYNTAX 
        lowrie -h [command line options]
    
    INPUT 
       takes SIO formatted input files
    
    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file
        -N do not normalize by maximum magnetization
        -fmt [svg, pdf, eps, png] specify fmt, default is svg
    """
    fmt='svg'
    FIG={} # plot dictionary
    FIG['lowrie']=1 # demag is figure 1
    pmagplotlib.plot_init(FIG['lowrie'],6,6)
    norm=1 # default is to normalize by maximum axis
    if len(sys.argv)>1:
        if '-h' in sys.argv:
            print main.__doc__
            sys.exit()
        if '-N' in sys.argv: norm=0 # don't normalize
        if '-f' in sys.argv: # sets input filename
            ind=sys.argv.index("-f")
            in_file=sys.argv[ind+1]
        else:
            print main.__doc__
            print 'you must supply a file name'
            sys.exit() 
    else:
        print main.__doc__
        print 'you must supply a file name'
        sys.exit() 
    data=open(in_file).readlines() # open the SIO format file
    PmagRecs=[] # set up a list for the results
    keys=['specimen','treatment','csd','M','dec','inc']
    for line in data:
        PmagRec={}
        rec=line.replace('\n','').split()
        for k in range(len(keys)): 
            PmagRec[keys[k]]=rec[k]
        PmagRecs.append(PmagRec)
    specs=pmag.get_dictkey(PmagRecs,'specimen','')
    sids=[]
    for spec in specs:
        if spec not in sids:sids.append(spec) # get list of unique specimen names
    for spc in sids:  # step through the specimen names
        print spc
        specdata=pmag.get_dictitem(PmagRecs,'specimen',spc,'T') # get all this one's data
        DIMs,Temps=[],[]
        for dat in specdata: # step through the data
            DIMs.append([float(dat['dec']),float(dat['inc']),float(dat['M'])*1e-3])
            Temps.append(float(dat['treatment']))
        carts=pmag.dir2cart(DIMs).transpose()
        #if norm==1: # want to normalize
        #    nrm=max(max(abs(carts[0])),max(abs(carts[1])),max(abs(carts[2]))) # by maximum of x,y,z values
        #    ylab="M/M_max"
        if norm==1: # want to normalize
            nrm=(DIMs[0][2]) # normalize by NRM
            ylab="M/M_o"
        else: 
            nrm=1. # don't normalize
            ylab="Magnetic moment (Am^2)"
        xlab="Temperature (C)"
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[0])/nrm,sym='r-')
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[0])/nrm,sym='ro') # X direction
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[1])/nrm,sym='c-')
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[1])/nrm,sym='cs') # Y direction
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[2])/nrm,sym='k-')
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[2])/nrm,sym='k^',title=spc,xlab=xlab,ylab=ylab) # Z direction
        pmagplotlib.drawFIGS(FIG)
        ans=raw_input('S[a]ve figure? [q]uit, <return> to continue   ')
        if ans=='a':
            files={'lowrie':'lowrie:_'+spc+'_.'+fmt}
            pmagplotlib.saveP(FIG,files)
        elif ans=='q':
            sys.exit()
        pmagplotlib.clearFIG(FIG['lowrie'])
Exemplo n.º 6
0
def main():
    """
    NAME
        curie.py

    DESCTIPTION
        plots and interprets curie temperature data.
        the 1st derivative is calculated from smoothed M-T curve
            (convolution with trianfular window with width= <-w> degrees)
        the 2nd derivative is calculated from smoothed 1st derivative curve
            ( using the same sliding window width)
        the estinated curie temp. is the maximum of the 2nd derivative

        - the temperature steps should be in multiples of 1.0 degrees

    INPUT
        T,M
  
    SYNTAX
        curie.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE, sets M,T input file (required)
        -w size of sliding window in degrees (default - 3 degrees)
        -t <min> <max> temperature range (optional)

    example:
    curie.py -f ex2.1 -w 30 -t 300 700

    """
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        meas_file=sys.argv[ind+1]
    else:
        print "missing -f\n"
        sys.exit()
    if '-w' in sys.argv:
        ind=sys.argv.index('-w')    
        window_len=int(sys.argv[ind+1])       
    else:
        window_len=3
    if '-t' in sys.argv:
        ind=sys.argv.index('-t')    
        t_begin=int(sys.argv[ind+1])       
        t_end=int(sys.argv[ind+2])
    else:
        t_begin=''      
        t_end=''


    # read data from file
    Data=numpy.loadtxt(meas_file,dtype=numpy.float)
    T=Data.transpose()[0]
    M=Data.transpose()[1]
    # cut the data if -t is one of the flags
    if t_begin:
        while T[0]<t_begin:
            M.pop(0);T.pop(0)
        while T[-1]>t_end:
            M.pop(-1);T.pop(-1)
        
            
    # prepare the signal:
    # from M(T) array with unequal deltaT
    # to M(T) array with deltaT=(1 degree).
    # if delataT is larger, then points are added using linear fit between
    # consecutive data points.
    # exit if deltaT is not integer
    i=0
    while i<(len(T)-1):
        if (T[i+1]-T[i])%1>0.001:
            print "delta T should be integer, this program will not work!"
            print "temperature range:",T[i],T[i+1]
            sys.exit()
        if (T[i+1]-T[i])==0.:
            M[i]=average([M[i],M[i+1]])
            M.pop(i+1);T.pop(i+1)
        elif (T[i+1]-T[i])<0.:
            M.pop(i+1);T.pop(i+1)
            print "check data in T=%.0f ,M[T] is ignored"%(T[i])
        elif (T[i+1]-T[i])>1.:
            slope,b=polyfit([T[i],T[i+1]],[M[i],M[i+1]],1)
            for j in range(int(T[i+1])-int(T[i])-1):
                M.insert(i+1,slope*(T[i]+1.)+b)
                T.insert(i+1,(T[i]+1.))
                i=i+1
        i=i+1

    # calculate the smoothed signal
    M=array(M,'f')
    T=array(T,'f')
    M_smooth=[]
    M_smooth=smooth(M,window_len)

    #plot the original data and the smooth data
    PLT={'M_T':1,'der1':2,'der2':3,'Curie':4} 
    pmagplotlib.plot_init(PLT['M_T'],5,5)
    string='M-T (sliding window=%i)'%int(window_len)
    pmagplotlib.plotXY(PLT['M_T'],T,M_smooth,sym='-')
    pmagplotlib.plotXY(PLT['M_T'],T,M,sym='--',xlab='Temperature C',ylab='Magnetization',title=string)
    
    #calculate first derivative
    d1,T_d1=[],[]
    for i in range(len(M_smooth)-1):
        Dy=M_smooth[i-1]-M_smooth[i+1]
        Dx=T[i-1]-T[i+1]
        d1.append(Dy/Dx)
    T_d1=T[1:len(T-1)]
    d1=array(d1,'f')
    d1_smooth=smooth(d1,window_len)

    #plot the first derivative
    pmagplotlib.plot_init(PLT['der1'],5,5)
    string='1st dervative (sliding window=%i)'%int(window_len)
    pmagplotlib.plotXY(PLT['der1'],T_d1,d1_smooth,sym='-',xlab='Temperature C',title=string)
    pmagplotlib.plotXY(PLT['der1'],T_d1,d1,sym='b--')

    #calculate second derivative
    d2,T_d2=[],[]
    for i in range(len(d1_smooth)-1):
        Dy=d1_smooth[i-1]-d1_smooth[i+1]
        Dx=T[i-1]-T[i+1]
        #print Dy/Dx
        d2.append(Dy/Dx)
    T_d2=T[2:len(T-2)]
    d2=array(d2,'f')
    d2_smooth=smooth(d2,window_len)
    
    #plot the second derivative
    pmagplotlib.plot_init(PLT['der2'],5,5)
    string='2nd dervative (sliding window=%i)'%int(window_len)
    pmagplotlib.plotXY(PLT['der2'],T_d2,d2,sym='-',xlab='Temperature C',title=string)
    d2=list(d2)
    print 'second deriative maximum is at T=%i'%int(T_d2[d2.index(max(d2))])

    # calculate Curie temperature for different width of sliding windows
    curie,curie_1=[],[]
    wn=range(5,50,1)
    for win in wn:
        # calculate the smoothed signal
        M_smooth=[]
        M_smooth=smooth(M,win)
        #calculate first derivative
        d1,T_d1=[],[]
        for i in range(len(M_smooth)-1):
            Dy=M_smooth[i-1]-M_smooth[i+1]
            Dx=T[i-1]-T[i+1]
            d1.append(Dy/Dx)
        T_d1=T[1:len(T-1)]
        d1=array(d1,'f')
        d1_smooth=smooth(d1,win)
        #calculate second derivative
        d2,T_d2=[],[]
        for i in range(len(d1_smooth)-1):
            Dy=d1_smooth[i-1]-d1_smooth[i+1]
            Dx=T[i-1]-T[i+1]
            d2.append(Dy/Dx)
        T_d2=T[2:len(T-2)]
        d2=array(d2,'f')
        d2_smooth=smooth(d2,win)
        d2=list(d2)
        d2_smooth=list(d2_smooth)
        curie.append(T_d2[d2.index(max(d2))])    
        curie_1.append(T_d2[d2_smooth.index(max(d2_smooth))])    

    #plot Curie temp for different sliding window length
    pmagplotlib.plot_init(PLT['Curie'],5,5)
    pmagplotlib.plotXY(PLT['Curie'],wn,curie,sym='.',xlab='Sliding Window Width (degrees)',ylab='Curie Temp',title='Curie Statistics')    
    pmagplotlib.drawFIGS(PLT)
    ans=raw_input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
    if ans=="q": sys.exit()
    if ans=="a":
        files = {}
        for key in PLT.keys():
            files[key]=str(key) + ".svg"
        pmagplotlib.saveP(PLT,files)
Exemplo n.º 7
0
def main():
    """
    NAME 
        plot_magic_keys.py

    DESCRIPTION
        picks out keys and makes and xy plot

    SYNTAX
        plot_magic_keys.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file 
        -xkey KEY: specify key for X 
        -ykey KEY: specify key  for Y
        -b xmin xmax ymin ymax, sets bounds

    """
    dir_path="./"
    if '-WD' in sys.argv: 
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        magic_file=dir_path+'/'+sys.argv[ind+1]
    else:
        print main.__doc__
        sys.exit()
    if '-xkey' in sys.argv:
        ind=sys.argv.index('-xkey')
        xkey=sys.argv[ind+1]
        if '-ykey' in sys.argv:
            ind=sys.argv.index('-ykey')
            ykey=sys.argv[ind+1]
    else:
        print main.__doc__
        sys.exit()
    if '-b' in sys.argv:
        ind=sys.argv.index('-b')
        xmin=float(sys.argv[ind+1])
        xmax=float(sys.argv[ind+2])
        ymin=float(sys.argv[ind+3])
        ymax=float(sys.argv[ind+4])
    #
    #
    # get data read in
    X,Y=[],[]
    Data,file_type=pmag.magic_read(magic_file) 
    if len(Data)>0:
        for rec in Data: 
            if xkey in rec.keys() and rec[xkey]!="" and ykey in rec.keys() and rec[ykey]!="":
                try:
                    X.append(float(rec[xkey]))
                    Y.append(float(rec[ykey]))
                except:
                    pass
        FIG={'fig':1}
        pmagplotlib.plot_init(FIG['fig'],5,5)
        if '-b' in sys.argv:
            pmagplotlib.plotXY(FIG['fig'],X,Y,sym='ro',xlab=xkey,ylab=ykey,xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax )
        else:
            pmagplotlib.plotXY(FIG['fig'],X,Y,sym='ro',xlab=xkey,ylab=ykey)
        pmagplotlib.drawFIGS(FIG)
        ans=raw_input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
        if ans=="q": sys.exit()
        if ans=="a":
            files = {}
            for key in FIG.keys():
                files[key]=str(key) + ".svg"
                pmagplotlib.saveP(FIG,files)
        sys.exit()
    else:
        print 'no data to plot'
Exemplo n.º 8
0
def main():
    """
    NAME
        lowrie_magic.py

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

    SYNTAX 
        lowrie -h [command line options]
    
    INPUT 
       takes magic_measurements formatted input files
    
    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is magic_measurements.txt
        -N do not normalize by maximum magnetization
        -fmt [svg, pdf, eps, png] specify fmt, default is svg
    """
    fmt='svg'
    FIG={} # plot dictionary
    FIG['lowrie']=1 # demag is figure 1
    pmagplotlib.plot_init(FIG['lowrie'],6,6)
    norm=1 # default is to normalize by maximum axis
    in_file,dir_path='magic_measurements.txt','.'
    if len(sys.argv)>1:
        if '-WD' in sys.argv:
            ind=sys.argv.index('-WD')
            dir_path=sys.argv[ind+1]
        if '-h' in sys.argv:
            print main.__doc__
            sys.exit()
        if '-N' in sys.argv: norm=0 # don't normalize
        if '-f' in sys.argv: # sets input filename
            ind=sys.argv.index("-f")
            in_file=sys.argv[ind+1]
    else:
        print main.__doc__
        print 'you must supply a file name'
        sys.exit() 
    in_file=dir_path+'/'+in_file
    print in_file
    PmagRecs,file_type=pmag.magic_read(in_file)
    if file_type!="magic_measurements":
         print 'bad input file'
         sys.exit()
    PmagRecs=pmag.get_dictitem(PmagRecs,'magic_method_codes','LP-IRM-3D','has') # get all 3D IRM records
    if len(PmagRecs)==0:
        print 'no records found'
        sys.exit()
    specs=pmag.get_dictkey(PmagRecs,'er_specimen_name','')
    sids=[]
    for spec in specs:
        if spec not in sids:sids.append(spec) # get list of unique specimen names
    for spc in sids:  # step through the specimen names
        print spc
        specdata=pmag.get_dictitem(PmagRecs,'er_specimen_name',spc,'T') # get all this one's data
        DIMs,Temps=[],[]
        for dat in specdata: # step through the data
            DIMs.append([float(dat['measurement_dec']),float(dat['measurement_inc']),float(dat['measurement_magn_moment'])])
            Temps.append(float(dat['treatment_temp'])-273.)
        carts=pmag.dir2cart(DIMs).transpose()
        if norm==1: # want to normalize
            nrm=(DIMs[0][2]) # normalize by NRM
            ylab="M/M_o"
        else: 
            nrm=1. # don't normalize
            ylab="Magnetic moment (Am^2)"
        xlab="Temperature (C)"
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[0])/nrm,sym='r-')
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[0])/nrm,sym='ro') # X direction
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[1])/nrm,sym='c-')
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[1])/nrm,sym='cs') # Y direction
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[2])/nrm,sym='k-')
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[2])/nrm,sym='k^',title=spc,xlab=xlab,ylab=ylab) # Z direction
        pmagplotlib.drawFIGS(FIG)
        ans=raw_input('S[a]ve figure? [q]uit, <return> to continue   ')
        if ans=='a':
            files={'lowrie':'lowrie:_'+spc+'_.'+fmt}
            pmagplotlib.saveP(FIG,files)
        elif ans=='q':
            sys.exit()
        pmagplotlib.clearFIG(FIG['lowrie'])
Exemplo n.º 9
0
def main():
    """
    NAME
        site_edit_magic.py

    DESCRIPTION
       makes equal area projections site by site
         from zeq_specimens_g.txt file with
         Fisher confidence ellipse using McFadden and McElhinny (1988)
         technique for combining lines and planes
         allows testing and reject specimens for bad orientations

    SYNTAX
        site_edit_magic.py [command line options]

    OPTIONS
       -h: prints help and quits
       -f: specify pmag_specimen format file, default is zeq_specimens_s.txt
       -fsa: specify er_samples.txt file
       -exc: use existing pmag_criteria.txt file
       -N: reset all sample flags to good
    
    OUPUT
       edited er_samples.txt file

    """
    dir_path = "."
    FIG = {}  # plot dictionary
    FIG["eqarea"] = 1  # eqarea is figure 1
    in_file = "zeq_specimens_s.txt"
    sampfile = "er_samples.txt"
    out_file = ""
    fmt, plot = "svg", 1
    Crits = ""
    M, N = 180.0, 1
    repeat = ""
    renew = 0
    if "-h" in sys.argv:
        print main.__doc__
        sys.exit()
    if "-WD" in sys.argv:
        ind = sys.argv.index("-WD")
        dir_path = sys.argv[ind + 1]
    if "-f" in sys.argv:
        ind = sys.argv.index("-f")
        in_file = sys.argv[ind + 1]
    if "-fsa" in sys.argv:
        ind = sys.argv.index("-fsa")
        sampfile = sys.argv[ind + 1]
    if "-exc" in sys.argv:
        Crits, file_type = pmag.magic_read(dir_path + "/pmag_criteria.txt")
        for crit in Crits:
            if crit["pmag_criteria_code"] == "DE-SPEC":
                M = float(crit["specimen_mad"])
                N = float(crit["specimen_n"])
    if "-fmt" in sys.argv:
        ind = sys.argv.index("-fmt")
        fmt = sys.argv[ind + 1]
    if "-N" in sys.argv:
        renew = 1
    #
    in_file = dir_path + "/" + in_file
    sampfile = dir_path + "/" + sampfile
    Specs, file_type = pmag.magic_read(in_file)
    if file_type != "pmag_specimens":
        print " bad pmag_specimen input file"
        sys.exit()
    Samps, file_type = pmag.magic_read(sampfile)
    if file_type != "er_samples":
        print " bad er_samples input file"
        sys.exit()
    SO_methods = []
    for rec in Samps:
        if "sample_orientation_flag" not in rec.keys():
            rec["sample_orientation_flag"] = "g"
        if "sample_description" not in rec.keys():
            rec["sample_description"] = ""
        if renew == 1:
            rec["sample_orientation_flag"] = "g"
            description = rec["sample_description"]
            if "#" in description:
                newdesc = ""
                c = 0
                while description[c] != "#" and c < len(description) - 1:  # look for first pound sign
                    newdesc = newdesc + description[c]
                    c += 1
                while description[c] == "#":
                    c += 1  # skip first set of pound signs
                while description[c] != "#":
                    c += 1  # find second set of pound signs
                while description[c] == "#" and c < len(description) - 1:
                    c += 1  # skip second set of pound signs
                while c < len(description) - 1:  # look for first pound sign
                    newdesc = newdesc + description[c]
                    c += 1
                rec["sample_description"] = newdesc  # edit out old comment about orientations
        if "magic_method_codes" in rec:
            methlist = rec["magic_method_codes"]
            for meth in methlist.split(":"):
                if "SO" in meth.strip() and "SO-POM" not in meth.strip():
                    if meth.strip() not in SO_methods:
                        SO_methods.append(meth.strip())
    pmag.magic_write(sampfile, Samps, "er_samples")
    SO_priorities = pmag.set_priorities(SO_methods, 0)
    sitelist = []
    for rec in Specs:
        if rec["er_site_name"] not in sitelist:
            sitelist.append(rec["er_site_name"])
    sitelist.sort()
    EQ = {}
    EQ["eqarea"] = 1
    pmagplotlib.plot_init(EQ["eqarea"], 5, 5)
    k = 0
    while k < len(sitelist):
        site = sitelist[k]
        print site
        data = []
        for spec in Specs:
            if spec["er_site_name"] == site:
                if (
                    spec["specimen_mad"] != ""
                    and spec["specimen_n"] != ""
                    and float(spec["specimen_mad"]) <= M
                    and float(spec["specimen_n"]) >= N
                ):
                    # good spec, now get orientation....
                    redo, p = 1, 0
                    if len(SO_methods) <= 1:
                        az_type = SO_methods[0]
                        orient = pmag.find_samp_rec(spec["er_sample_name"], Samps, az_type)
                        redo = 0
                    while redo == 1:
                        if p >= len(SO_priorities):
                            print "no orientation data for ", spec["er_sample_name"]
                            orient["sample_azimuth"] = ""
                            orient["sample_dip"] = ""
                            redo = 0
                        else:
                            az_type = SO_methods[SO_methods.index(SO_priorities[p])]
                            orient = pmag.find_samp_rec(spec["er_sample_name"], Samps, az_type)
                            if orient["sample_azimuth"] != "":
                                redo = 0
                        p += 1
                    if orient["sample_azimuth"] != "":
                        rec = {}
                        for key in spec.keys():
                            rec[key] = spec[key]
                        rec["dec"], rec["inc"] = pmag.dogeo(
                            float(spec["specimen_dec"]),
                            float(spec["specimen_inc"]),
                            float(orient["sample_azimuth"]),
                            float(orient["sample_dip"]),
                        )
                        rec["tilt_correction"] = "1"
                        rec["sample_azimuth"] = orient["sample_azimuth"]
                        rec["sample_dip"] = orient["sample_dip"]
                        data.append(rec)
        if len(data) > 2:
            print "specimen, dec, inc, n_meas/MAD,| method codes "
            for i in range(len(data)):
                print "%s: %7.1f %7.1f %s / %s | %s" % (
                    data[i]["er_specimen_name"],
                    data[i]["dec"],
                    data[i]["inc"],
                    data[i]["specimen_n"],
                    data[i]["specimen_mad"],
                    data[i]["magic_method_codes"],
                )

            fpars = pmag.dolnp(data, "specimen_direction_type")
            print "\n Site lines planes  kappa   a95   dec   inc"
            print site, fpars["n_lines"], fpars["n_planes"], fpars["K"], fpars["alpha95"], fpars["dec"], fpars[
                "inc"
            ], fpars["R"]
            if out_file != "":
                if float(fpars["alpha95"]) <= acutoff and float(fpars["K"]) >= kcutoff:
                    out.write("%s %s %s\n" % (fpars["dec"], fpars["inc"], fpars["alpha95"]))
            pmagplotlib.plotLNP(EQ["eqarea"], site, data, fpars, "specimen_direction_type")
            if k != 0 and repeat != "y":
                ans = raw_input("s[a]ve plot, [q]uit, [e]dit specimens, [p]revious site, <return> to continue:\n ")
            elif k == 0 and repeat != "y":
                ans = raw_input("s[a]ve plot, [q]uit, [e]dit specimens, <return> to continue:\n ")
            if ans == "p":
                k -= 2
            if ans == "a":
                files = {}
                files["eqarea"] = site + "_" + crd + "_" + "eqarea" + "." + fmt
                pmagplotlib.saveP(EQ, files)
            if ans == "q":
                sys.exit()
            if ans == "e" and Samps == []:
                print "can't edit samples without orientation file, sorry"
            elif ans == "e":
                #                k-=1
                testspec = raw_input("Enter name of specimen to check: ")
                for spec in data:
                    if spec["er_specimen_name"] == testspec:
                        # first test wrong direction of drill arrows (flip drill direction in opposite direction and re-calculate d,i
                        d, i = pmag.dogeo(
                            float(spec["specimen_dec"]),
                            float(spec["specimen_inc"]),
                            float(spec["sample_azimuth"]) - 180.0,
                            -float(spec["sample_dip"]),
                        )
                        XY = pmag.dimap(d, i)
                        pmagplotlib.plotXY(EQ["eqarea"], [XY[0]], [XY[1]], "g^", "", "", "")
                        # first test wrong end of compass (take az-180.)
                        d, i = pmag.dogeo(
                            float(spec["specimen_dec"]),
                            float(spec["specimen_inc"]),
                            float(spec["sample_azimuth"]) - 180.0,
                            float(spec["sample_dip"]),
                        )
                        XY = pmag.dimap(d, i)
                        pmagplotlib.plotXY(EQ["eqarea"], [XY[0]], [XY[1]], "kv", "", "", "")
                        # did the sample spin in the hole?
                        # now spin around specimen's z
                        X_up, Y_up, X_d, Y_d = [], [], [], []
                        for incr in range(0, 360, 5):
                            d, i = pmag.dogeo(
                                float(spec["specimen_dec"]) + incr,
                                float(spec["specimen_inc"]),
                                float(spec["sample_azimuth"]),
                                float(spec["sample_dip"]),
                            )
                            XY = pmag.dimap(d, i)
                            if i >= 0:
                                X_d.append(XY[0])
                                Y_d.append(XY[1])
                            else:
                                X_up.append(XY[0])
                                Y_up.append(XY[1])
                        pmagplotlib.plotXY(EQ["eqarea"], X_d, Y_d, "b.", "", "", "")
                        pmagplotlib.plotXY(EQ["eqarea"], X_up, Y_up, "c.", "", "", "")
                        pmagplotlib.drawFIGS(EQ)
                        break
                print "Triangle: wrong arrow for drill direction."
                print "Delta: wrong end of compass."
                print "Small circle:  wrong mark on sample. [cyan upper hemisphere]"
                deleteme = raw_input("Mark this sample as bad? y/[n]  ")
                if deleteme == "y":
                    reason = raw_input(
                        "Reason: [1] broke, [2] wrong drill direction, [3] wrong compass direction, [4] bad mark, [5] displaced block [6] other "
                    )
                    if reason == "1":
                        description = " sample broke while drilling"
                    if reason == "2":
                        description = " wrong drill direction "
                    if reason == "3":
                        description = " wrong compass direction "
                    if reason == "4":
                        description = " bad mark in field"
                    if reason == "5":
                        description = " displaced block"
                    if reason == "6":
                        description = raw_input("Enter brief reason for deletion:   ")
                    for samp in Samps:
                        if samp["er_sample_name"] == spec["er_sample_name"]:
                            samp["sample_orientation_flag"] = "b"
                            samp["sample_description"] = (
                                samp["sample_description"] + " ## direction deleted because: " + description + "##"
                            )  # mark description
                    pmag.magic_write(sampfile, Samps, "er_samples")
                repeat = raw_input("Mark another sample, this site? y/[n]  ")
                if repeat == "y":
                    k -= 1
        else:
            print "skipping site - not enough data with specified coordinate system"
        k += 1
    print "sample flags stored in ", sampfile
Exemplo n.º 10
0
def main():
    """
    NAME
        curie_magic.py

    DESCTIPTION
        plots and interprets curie temperature data.
        the 1st derivative is calculated from smoothed M-T curve
            (convolution with trianfular window with width= <-w> degrees)
        the 2nd derivative is calculated from smoothed 1st derivative curve
            ( using the same sliding window width)
        the estinated curie temp. is the maximum of the 2nd derivative

        - the temperature steps should be in multiples of 1.0 degrees

    INPUT
        magic_measurements formatted file
  
    SYNTAX
        curie_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE, sets M,T magic_measurements formatted file, default is MsT_measurements.txt
        -F RMAG, sets Rmag_results format file for appending results, default is not
        -w size of sliding window in degrees (default - 3 degrees)
        -t <min> <max> temperature range (optional)

    """
    fmt,dir_path='svg','.'
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    meas_file=dir_path+'/MsT_measurements.txt'
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        meas_file=dir_path+'/'+sys.argv[ind+1]
    Results,rmag_file=[],""
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        rmag_file=dir_path+'/'+sys.argv[ind+1]
        try:
            Results,file_type=pmag.magic_read(rmag_file)
            if file_type!='rmag_results':
                print 'bad results file, starting new one'
        except:
            pass
    if '-w' in sys.argv:
        ind=sys.argv.index('-w')    
        window_len=int(sys.argv[ind+1])       
    else:
        window_len=3
    if '-t' in sys.argv:
        ind=sys.argv.index('-t')    
        t_begin=int(sys.argv[ind+1])       
        t_end=int(sys.argv[ind+2])
    else:
        t_begin=''      
        t_end=''

    # read data from file
    Data,file_type=pmag.magic_read(meas_file)
    if file_type!='magic_measurements':
        print 'bad measurements file'
        sys.exit()
    specs=[]
    for rec in Data:
        specname=""
        if 'er_specimen_name' in rec.keys() and rec['er_specimen_name']!="": 
            specname=rec['er_specimen_name']
        else: 
            rec['er_specimen_name']=""
        if 'er_synthetic_name' in rec.keys() and rec['er_synthetic_name']!="": 
            specname=rec['er_synthetic_name']
        else: 
            rec['er_synthetic_name']=""
        if specname not in specs:specs.append(specname)
    for spec in specs:
        print 'processing: ',spec
        M,T,curieT=[],[],0
        for rec in Data:
          if rec['er_specimen_name'] or rec['er_synthetic_name']==spec: 
            location,sample,site="","",""
            if 'er_location_name' in rec.keys():location=rec['er_location_name']
            if 'er_sample_name' in rec.keys():sample=rec['er_sample_name']
            if 'er_site_name' in rec.keys():site=rec['er_site_name']
            syn=""
            if 'er_synthetic_name' in rec.keys():syn=rec['er_synthetic_name']
            meths=rec['magic_method_codes'].strip().split(':')
            expnames=rec['magic_experiment_name'].strip().split(':')
            if 'LP-MW-I' in meths and 'Curie' in expnames:
                method=rec['magic_method_codes']
                expname=rec['magic_experiment_name']
                T.append(float(rec['measurment_temp'])-273)
                M.append(float(rec['measurement_magnitude']))
        # cut the data if -t is one of the flags
        if len(M)<10:
            print 'not enough data for processing'
            sys.exit()
        if t_begin:
            while T[0]<t_begin:
                M.pop(0);T.pop(0)
            while T[-1]>t_end:
                M.pop(-1);T.pop(-1)
                
        # prepare the signal:
        # from M(T) array with unequal deltaT
        # to M(T) array with deltaT=(1 degree).
        # if delataT is larger, then points are added using linear fit between
        # consecutive data points.
        # exit if deltaT is not integer
        i=0
        while i<(len(T)-1):
            if (T[i+1]-T[i])%1>0.001:
                print "delta T should be integer, this program will not work!"
                print "temperature range:",T[i],T[i+1]
                sys.exit()
            if (T[i+1]-T[i])==0.:
                M[i]=average([M[i],M[i+1]])
                M.pop(i+1);T.pop(i+1)
            elif (T[i+1]-T[i])<0.:
                M.pop(i+1);T.pop(i+1)
                print "check data in T=%.0f ,M[T] is ignored"%(T[i])
            elif (T[i+1]-T[i])>1.:
                slope,b=polyfit([T[i],T[i+1]],[M[i],M[i+1]],1)
                for j in range(int(T[i+1])-int(T[i])-1):
                    M.insert(i+1,slope*(T[i]+1.)+b)
                    T.insert(i+1,(T[i]+1.))
                    i=i+1
            i=i+1
    
        # calculate the smoothed signal
        M=array(M,'f')
        T=array(T,'f')
        M_smooth=[]
        M_smooth=smooth(M,window_len)
    
        #plot the original data and the smooth data
        PLT={'M_T':1,'der1':2,'der2':3,'Curie':4} 
        pmagplotlib.plot_init(PLT['M_T'],5,5)
        string='M-T (sliding window=%i)'%int(window_len)
        pmagplotlib.plotXY(PLT['M_T'],T,M,'--','Temperature C','Magnetization',string)
        plot(T,M_smooth,'-')
    
        #calculate first derivative
        d1,T_d1=[],[]
        for i in range(len(M_smooth)-1):
            Dy=M_smooth[i-1]-M_smooth[i+1]
            Dx=T[i-1]-T[i+1]
            d1.append(Dy/Dx)
        T_d1=T[1:len(T-1)]
        d1=array(d1,'f')
        d1_smooth=smooth(d1,window_len)
    
        #plot the first derivative
        pmagplotlib.plot_init(PLT['der1'],5,5)
        string='1st dervative (sliding window=%i)'%int(window_len)
        pmagplotlib.plotXY(PLT['der1'],T_d1,d1_smooth,'-','temperatue C','',string)
        plot(T_d1,d1,'--b')
    
        #calculate second derivative
        d2,T_d2=[],[]
        for i in range(len(d1_smooth)-1):
            Dy=d1_smooth[i-1]-d1_smooth[i+1]
            Dx=T[i-1]-T[i+1]
            #print Dy/Dx
            d2.append(Dy/Dx)
        T_d2=T[2:len(T-2)]
        d2=array(d2,'f')
        d2_smooth=smooth(d2,window_len)
        
        #plot the second derivative
        pmagplotlib.plot_init(PLT['der2'],5,5)
        string='2nd dervative (sliding window=%i)'%int(window_len)
        pmagplotlib.plotXY(PLT['der2'],T_d2,d2,'-','temperatue C','',string)
        d2=list(d2)
        print 'second deriative maximum is at T=%i'%int(T_d2[d2.index(max(d2))])
    
        # calculate Curie temperature for different width of sliding windows
        curie,curie_1=[],[]
        wn=range(5,50,1)
        for win in wn:
            # calculate the smoothed signal
            M_smooth=[]
            M_smooth=smooth(M,win)
            #calculate first derivative
            d1,T_d1=[],[]
            for i in range(len(M_smooth)-1):
                Dy=M_smooth[i-1]-M_smooth[i+1]
                Dx=T[i-1]-T[i+1]
                d1.append(Dy/Dx)
            T_d1=T[1:len(T-1)]
            d1=array(d1,'f')
            d1_smooth=smooth(d1,win)
            #calculate second derivative
            d2,T_d2=[],[]
            for i in range(len(d1_smooth)-1):
                Dy=d1_smooth[i-1]-d1_smooth[i+1]
                Dx=T[i-1]-T[i+1]
                d2.append(Dy/Dx)
            T_d2=T[2:len(T-2)]
            d2=array(d2,'f')
            d2_smooth=smooth(d2,win)
            d2=list(d2)
            d2_smooth=list(d2_smooth)
            curie.append(T_d2[d2.index(max(d2))])    
            if curie[-1]>curieT:curieT=curie[-1] # find maximum curie T
            curie_1.append(T_d2[d2_smooth.index(max(d2_smooth))])    
    
        #plot Curie temp for different sliding window length
        pmagplotlib.plot_init(PLT['Curie'],5,5)
        pmagplotlib.plotXY(PLT['Curie'],wn,curie,'.','sliding window width (degrees)','curie temp','Inferred Curie Temperatures')    
        print 'Curie T is: ',curieT
        pmagplotlib.drawFIGS(PLT)
        files={}
        for key in PLT.keys():
             files[key]=spec+'_'+key+'.'+fmt
        ans=raw_input(" S[a]ve to save plot, [q]uit, or return to continue: ")
        if ans=='q':sys.exit()
        if ans=='a':
            pmagplotlib.saveP(PLT,files)
        if rmag_file!="":
            ResRec={}
            ResRec['rmag_result_name']='Curie T: '+spec
            ResRec['er_location_names']=location
            ResRec['er_sample_names']=sample
            ResRec['er_site_names']=site
            ResRec['er_synthetic_names']=syn
            if syn!="": 
                ResRec['er_specimen_names']=spec
            else:
                ResRec['er_specimen_names']=""
            ResRec['magic_experiment_names']=expname
            ResRec['magic_method_codes']=method+':SM-2DMAX'
            ResRec['critical_temp']='%10.1f'%(curieT)
            ResRec['critical_temp_type']="Curie"
            ResRec['er_citation_names']="This study"
            Results.append(ResRec)
    if len(Results)>0 and rmag_file!="":
        ResOuts,keys=pmag.fillkeys(Results)
        pmag.magic_write(rmag_file,ResOuts,'rmag_results')
        print 'Results stored in ',rmag_file
Exemplo n.º 11
0
def main():
    """
    NAME
        quick_hyst.py

    DESCRIPTION
        makes plots of hysteresis data

    SYNTAX
        quick_hyst.py [command line options]

    OPTIONS
        -h prints help message and quits
        -usr USER:   identify user, default is ""
        -f: specify input file, default is magic_measurements.txt
        -spc SPEC: specify specimen name to plot and quit
        -sav save all plots and quit
        -fmt [png,svg,eps,jpg]
    """
    args=sys.argv
    PLT=1
    plots=0
    user,meas_file="","magic_measurements.txt"
    pltspec=""
    dir_path='.'
    fmt='png'
    verbose=pmagplotlib.verbose
    version_num=pmag.get_version()
    if '-WD' in args:
        ind=args.index('-WD')
        dir_path=args[ind+1]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind=args.index("-usr")
        user=args[ind+1]
    if '-f' in args:
        ind=args.index("-f")
        meas_file=args[ind+1]
    if '-sav' in args:
        verbose=0
        plots=1
    if '-spc' in args:
        ind=args.index("-spc")
        pltspec= args[ind+1]
        verbose=0
        plots=1
    if '-fmt' in args:
        ind=args.index("-fmt")
        fmt=args[ind+1]
    meas_file=dir_path+'/'+meas_file
    #
    #
    meas_data,file_type=pmag.magic_read(meas_file)
    if file_type!='magic_measurements':
        print main.__doc__
        print 'bad file'
        sys.exit()
    #
    # initialize some variables
    # define figure numbers for hyst,deltaM,DdeltaM curves
    HystRecs,RemRecs=[],[]
    HDD={}
    HDD['hyst']=1
    pmagplotlib.plot_init(HDD['hyst'],5,5)
    #
    # get list of unique experiment names and specimen names
    #
    experiment_names,sids=[],[]
    hyst_data=pmag.get_dictitem(meas_data,'magic_method_codes','LP-HYS','has') # get all hysteresis data
    for rec in hyst_data:
        if 'er_synthetic_name' in rec.keys() and rec['er_synthetic_name']!="":
            rec['er_specimen_name']=rec['er_synthetic_name']
        if rec['magic_experiment_name'] not in experiment_names:experiment_names.append(rec['magic_experiment_name'])
        if rec['er_specimen_name'] not in sids:sids.append(rec['er_specimen_name'])
        if 'measurement_temp' not in rec.keys(): rec['measurement_temp']='300' # assume room T measurement unless otherwise specified
    #
    k=0
    if pltspec!="":
        k=sids.index(pltspec)
    intlist=['measurement_magnitude','measurement_magn_moment','measurement_magn_volume','measurement_magn_mass']
    while k < len(sids):
        locname,site,sample,synth='','','',''
        s=sids[k]
        hmeths=[]
        if verbose:print s, k+1 , 'out of ',len(sids)
    #
    #
        B,M=[],[] #B,M for hysteresis, Bdcd,Mdcd for irm-dcd data
        spec=pmag.get_dictitem(hyst_data,'er_specimen_name',s,'T') # get all measurements for this specimen
        if 'er_location_name' in spec[0].keys():
            locname=spec[0]['er_location_name']
        if 'er_site_name' in spec[0].keys():
            site=spec[0]['er_site_name']
        if 'er_sample_name' in spec[0].keys():
            sample=spec[0]['er_sample_name']
        if 'er_synthetic_name' in spec[0].keys():
            synth=spec[0]['er_synthetic_name']
        for m in intlist:
            meas_data=pmag.get_dictitem(spec,m,'','F') # get all non-blank data for this specimen
            if len(meas_data)>0: break
        c=['k-','b-','c-','g-','m-','r-','y-']
        cnum=0
        if len(meas_data)>0:
            Temps=[]
            xlab,ylab,title='','',''
            for rec in meas_data: 
                if rec['measurement_temp'] not  in Temps:Temps.append(rec['measurement_temp'])
            for t in Temps:
              print 'working on t: ',t
              t_data=pmag.get_dictitem(meas_data,'measurement_temp',t,'T')
              B,M=[],[]
              for rec in t_data: 
                B.append(float(rec['measurement_lab_field_dc']))
                M.append(float(rec[m]))
    # now plot the hysteresis curve(s)
    #
              if len(B)>0: 
                    B=numpy.array(B)
                    M=numpy.array(M)
                    if t==Temps[-1]:
                        xlab='Field (T)'
                        ylab=m
                        title='Hysteresis: '+s
                    if t==Temps[0]:
                        pmagplotlib.clearFIG(HDD['hyst'])
                    pmagplotlib.plotXY(HDD['hyst'],B,M,sym=c[cnum],xlab=xlab,ylab=ylab,title=title) 
                    pmagplotlib.plotXY(HDD['hyst'],[1.1*B.min(),1.1*B.max()],[0,0],sym='k-',xlab=xlab,ylab=ylab,title=title) 
                    pmagplotlib.plotXY(HDD['hyst'],[0,0],[1.1*M.min(),1.1*M.max()],sym='k-',xlab=xlab,ylab=ylab,title=title) 
                    if verbose:pmagplotlib.drawFIGS(HDD)
                    cnum+=1
                    if cnum==len(c):cnum=0
    #
        files={}
        if plots:
            if pltspec!="":s=pltspec
            files={}
            for key in HDD.keys():
                if synth=='':
                    files[key]="LO:_"+locname+'_SI:_'+site+'_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt
                else:
                    files[key]='SY:_'+synth+'_TY:_'+key+'_.'+fmt
            pmagplotlib.saveP(HDD,files)
            if pltspec!="":sys.exit()
        if verbose:
            pmagplotlib.drawFIGS(HDD)
            ans=raw_input("S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ")
            if ans=="a":
                files={}
                for key in HDD.keys():
                    files[key]="LO:_"+locname+'_SI:_'+site+'_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt
                pmagplotlib.saveP(HDD,files)
            if ans=='':k+=1
            if ans=="p":
       	        del HystRecs[-1]
    	        k-=1
            if  ans=='q': 
    	        print "Good bye"
    	        sys.exit()
            if ans=='s':
                keepon=1
                specimen=raw_input('Enter desired specimen name (or first part there of): ')
                while keepon==1:
                    try:
                        k =sids.index(specimen)
                        keepon=0
                    except:
                        tmplist=[]
                        for qq in range(len(sids)):
                            if specimen in sids[qq]:tmplist.append(sids[qq])
                        print specimen," not found, but this was: "
                        print tmplist
                        specimen=raw_input('Select one or try again\n ')
                        k =sids.index(specimen)
        else:
            k+=1
        if len(B)==0:
    	    if verbose:print 'skipping this one - no hysteresis data'
       	    k+=1