Exemplo n.º 1
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
        -sav save plots and quit
    """
    fmt, plot = "svg", 0
    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 "-sav" in sys.argv:
            plot = 1  # don't normalize
        if "-fmt" in sys.argv:  # sets input filename
            ind = sys.argv.index("-fmt")
            fmt = sys.argv[ind + 1]
        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.0  # 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
        files = {"lowrie": "lowrie:_" + spc + "_." + fmt}
        if plot == 0:
            pmagplotlib.drawFIGS(FIG)
            ans = raw_input("S[a]ve figure? [q]uit, <return> to continue   ")
            if ans == "a":
                pmagplotlib.saveP(FIG, files)
            elif ans == "q":
                sys.exit()
        else:
            pmagplotlib.saveP(FIG, files)
        pmagplotlib.clearFIG(FIG["lowrie"])
Exemplo n.º 2
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
        -sav save plots and quit
    """
    fmt, plot = 'svg', 0
    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 '-sav' in sys.argv:
            plot = 1  # don't normalize
        if '-fmt' in sys.argv:  # sets input filename
            ind = sys.argv.index("-fmt")
            fmt = sys.argv[ind + 1]
        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 = pmag.open_file(in_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,
                           old_div(abs(carts[0]), nrm),
                           sym='r-')
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[0]), nrm),
                           sym='ro')  # X direction
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[1]), nrm),
                           sym='c-')
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[1]), nrm),
                           sym='cs')  # Y direction
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[2]), nrm),
                           sym='k-')
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[2]), nrm),
                           sym='k^',
                           title=spc,
                           xlab=xlab,
                           ylab=ylab)  # Z direction
        files = {'lowrie': 'lowrie:_' + spc + '_.' + fmt}
        if plot == 0:
            pmagplotlib.drawFIGS(FIG)
            ans = input('S[a]ve figure? [q]uit, <return> to continue   ')
            if ans == 'a':
                pmagplotlib.saveP(FIG, files)
            elif ans == 'q':
                sys.exit()
        else:
            pmagplotlib.saveP(FIG, files)
        pmagplotlib.clearFIG(FIG['lowrie'])
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
        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
    print 'verbose?', 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
    print 'verbose', verbose
    #
    #
    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
Exemplo n.º 5
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
        -sav figure and quit
        -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=""
    #plot=0
    no_plot = pmag.get_flag_arg_from_sys('-sav')
    if not no_plot:
        do_plot = True
    else:
        do_plot = False
    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 '-h' in sys.argv:
        do_plot = False
    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,sym='ro',xlab=methx,ylab=methy,title=plot+':Biplot')
            if not pmagplotlib.isServer and do_plot:
                pmagplotlib.drawFIGS(FIG)
                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.º 6
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
        -f: specify input file, default is 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
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    plots = 0
    pltspec = ""
    verbose = pmagplotlib.verbose
    #version_num = pmag.get_version()
    dir_path = pmag.get_named_arg_from_sys('-WD', '.')
    dir_path = os.path.realpath(dir_path)
    meas_file = pmag.get_named_arg_from_sys('-f', 'measurements.txt')
    fmt = pmag.get_named_arg_from_sys('-fmt', 'png')
    if '-sav' in args:
        verbose = 0
        plots = 1
    if '-spc' in args:
        ind = args.index("-spc")
        pltspec = args[ind + 1]
        verbose = 0
        plots = 1
    #
    con = nb.Contribution(dir_path,
                          read_tables=['measurements'],
                          custom_filenames={'measurements': meas_file})
    # get as much name data as possible (used for naming plots)
    if not 'measurements' in con.tables:
        print("-W- No measurement file found")
        return
    con.propagate_location_to_measurements()

    if 'measurements' not in con.tables:
        print(main.__doc__)
        print('bad file')
        sys.exit()
    meas_container = con.tables['measurements']
    #meas_df = meas_container.df

    #
    # initialize some variables
    # define figure numbers for hyst,deltaM,DdeltaM curves
    HystRecs = []
    HDD = {}
    HDD['hyst'] = 1
    pmagplotlib.plot_init(HDD['hyst'], 5, 5)
    #
    # get list of unique experiment names and specimen names
    #
    sids = []
    hyst_data = meas_container.get_records_for_code('LP-HYS')
    #experiment_names = hyst_data['experiment_name'].unique()
    if not len(hyst_data):
        print("-W- No hysteresis data found")
        return
    sids = hyst_data['specimen'].unique()

    # if 'treat_temp' is provided, use that value, otherwise assume 300
    hyst_data['treat_temp'].where(hyst_data['treat_temp'].notnull(),
                                  '300',
                                  inplace=True)
    # start at first specimen, or at provided specimen ('-spc')
    k = 0
    if pltspec != "":
        try:
            print(sids)
            k = list(sids).index(pltspec)
        except ValueError:
            print('-W- No specimen named: {}.'.format(pltspec))
            print('-W- Please provide a valid specimen name')
            return
    intlist = ['magn_moment', 'magn_volume', 'magn_mass']

    while k < len(sids):
        locname, site, sample, synth = '', '', '', ''
        s = sids[k]
        if verbose:
            print(s, k + 1, 'out of ', len(sids))
        # B, M for hysteresis, Bdcd,Mdcd for irm-dcd data
        B, M = [], []
        # get all measurements for this specimen
        spec = hyst_data[hyst_data['specimen'] == s]
        # get names
        if 'location' in spec:
            locname = spec['location'][0]
        if 'site' in spec:
            site = spec['sample'][0]
        if 'sample' in spec:
            sample = spec['sample'][0]

        # get all records with non-blank values in any intlist column
        # find intensity data
        for int_column in intlist:
            if int_column in spec.columns:
                int_col = int_column
                break
        meas_data = spec[spec[int_column].notnull()]
        if len(meas_data) == 0:
            break
        #
        c = ['k-', 'b-', 'c-', 'g-', 'm-', 'r-', 'y-']
        cnum = 0
        Temps = []
        xlab, ylab, title = '', '', ''
        Temps = meas_data['treat_temp'].unique()
        for t in Temps:
            print('working on t: ', t)
            t_data = meas_data[meas_data['treat_temp'] == t]
            m = int_col
            B = t_data['meas_field_dc'].astype(float).values
            M = t_data[m].astype(float).values
            # 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
            for key in list(HDD.keys()):
                if pmagplotlib.isServer:
                    if synth == '':
                        files[
                            key] = "LO:_" + locname + '_SI:_' + site + '_SA:_' + sample + '_SP:_' + s + '_TY:_' + key + '_.' + fmt
                    else:
                        files[
                            key] = 'SY:_' + synth + '_TY:_' + key + '_.' + fmt
                else:
                    if synth == '':
                        filename = ''
                        for item in [locname, site, sample, s, key]:
                            if item:
                                item = item.replace(' ', '_')
                                filename += item + '_'
                        if filename.endswith('_'):
                            filename = filename[:-1]
                        filename += ".{}".format(fmt)
                        files[key] = filename
                    else:
                        files[key] = "{}_{}.{}".format(synth, key, fmt)

            pmagplotlib.saveP(HDD, files)
            if pltspec != "":
                sys.exit()
        if verbose:
            pmagplotlib.drawFIGS(HDD)
            ans = input(
                "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n "
            )
            if ans == "a":
                files = {}
                for key in list(HDD.keys()):
                    if pmagplotlib.isServer:  # use server plot naming convention
                        files[
                            key] = "LO:_" + locname + '_SI:_' + site + '_SA:_' + sample + '_SP:_' + s + '_TY:_' + key + '_.' + fmt
                    else:  # use more readable plot naming convention
                        filename = ''
                        for item in [locname, site, sample, s, key]:
                            if item:
                                item = item.replace(' ', '_')
                                filename += item + '_'
                        if filename.endswith('_'):
                            filename = filename[:-1]
                        filename += ".{}".format(fmt)
                        files[key] = filename

                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 = 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 = 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
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
        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)
        -sav save figures and quit
        -fmt [svg,jpg,eps,png,pdf] set format for figure output [default: svg]

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

    """
    plot,fmt=0,'svg'
    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=''
    if '-sav' in sys.argv:plot=1
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]


    # read data from file
    Data=numpy.loadtxt(meas_file,dtype=numpy.float)
    T=Data.transpose()[0]
    M=Data.transpose()[1]
    T=list(T)
    M=list(M)
    # 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(old_div(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 derivative (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(old_div(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 derivative (sliding window=%i)'%int(window_len)
    pmagplotlib.plotXY(PLT['der2'],T_d2,d2,sym='-',xlab='Temperature C',title=string)
    d2=list(d2)
    print('second derivative 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=list(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(old_div(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(old_div(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')
    files = {}
    for key in list(PLT.keys()): files[key]=str(key) + "." +fmt
    if plot==0:
        pmagplotlib.drawFIGS(PLT)
        ans=input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
        if ans=="q": sys.exit()
        if ans=="a": pmagplotlib.saveP(PLT,files)
    else: pmagplotlib.saveP(PLT,files)
    sys.exit()
Exemplo n.º 9
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)
        -sav save figures and quit
        -fmt [svg,jpg,eps,png,pdf] set format for figure output [default: svg]

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

    """
    plot,fmt=0,'svg'
    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=''
    if '-sav' in sys.argv:plot=1
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]


    # read data from file
    Data=numpy.loadtxt(meas_file,dtype=numpy.float)
    T=Data.transpose()[0]
    M=Data.transpose()[1]
    T=list(T)
    M=list(M)
    # 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 derivative (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 derivative (sliding window=%i)'%int(window_len)
    pmagplotlib.plotXY(PLT['der2'],T_d2,d2,sym='-',xlab='Temperature C',title=string)
    d2=list(d2)
    print 'second derivative 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')
    files = {}
    for key in PLT.keys(): files[key]=str(key) + "." +fmt
    if plot==0:
        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": pmagplotlib.saveP(PLT,files)
    else: pmagplotlib.saveP(PLT,files)
    sys.exit()
Exemplo n.º 10
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 list(rec.keys()): rec['sample_orientation_flag']='g'
       if 'sample_description' not in list(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 list(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=input("s[a]ve plot, [q]uit, [e]dit specimens, [p]revious site, <return> to continue:\n ")
            elif k==0 and repeat!='y':
                ans=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=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=input("Mark this sample as bad? y/[n]  ")
                if deleteme=='y':
                    reason=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=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=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.º 11
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
        -sav save plots and quit
    """
    fmt, plot = 'svg', 0
    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 '-sav' in sys.argv:
            plot = 1  # don't normalize
        if '-fmt' in sys.argv:  # sets input filename
            ind = sys.argv.index("-fmt")
            fmt = sys.argv[ind + 1]
        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 = pmag.open_file(in_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, old_div(
            abs(carts[0]), nrm), sym='r-')
        pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(
            abs(carts[0]), nrm), sym='ro')  # X direction
        pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(
            abs(carts[1]), nrm), sym='c-')
        pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(
            abs(carts[1]), nrm), sym='cs')  # Y direction
        pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(
            abs(carts[2]), nrm), sym='k-')
        pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(
            abs(carts[2]), nrm), sym='k^', title=spc, xlab=xlab, ylab=ylab)  # Z direction
        files = {'lowrie': 'lowrie:_' + spc + '_.' + fmt}
        if plot == 0:
            pmagplotlib.drawFIGS(FIG)
            ans = input('S[a]ve figure? [q]uit, <return> to continue   ')
            if ans == 'a':
                pmagplotlib.saveP(FIG, files)
            elif ans == 'q':
                sys.exit()
        else:
            pmagplotlib.saveP(FIG, files)
        pmagplotlib.clearFIG(FIG['lowrie'])
Exemplo n.º 12
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 list(rec.keys()) and rec[xkey]!="" and ykey in list(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=input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
        if ans=="q": sys.exit()
        if ans=="a":
            files = {}
            for key in list(FIG.keys()):
                files[key]=str(key) + ".svg"
                pmagplotlib.saveP(FIG,files)
        sys.exit()
    else:
        print('no data to plot')
Exemplo n.º 13
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, 'r').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 list(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 = input(" S[a]ve to save plot, Return to quit:  ")
        if ans == "a":
            pmagplotlib.saveP(FIGS, files)
    else:
        pmagplotlib.saveP(FIGS, files)
Exemplo n.º 14
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
        -f: specify input file, default is 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
    if "-h" in args:
        print main.__doc__
        sys.exit()
    plots = 0
    pltspec = ""
    verbose = pmagplotlib.verbose
    # version_num = pmag.get_version()
    dir_path = pmag.get_named_arg_from_sys("-WD", ".")
    dir_path = os.path.realpath(dir_path)
    meas_file = pmag.get_named_arg_from_sys("-f", "measurements.txt")
    fmt = pmag.get_named_arg_from_sys("-fmt", "png")
    if "-sav" in args:
        verbose = 0
        plots = 1
    if "-spc" in args:
        ind = args.index("-spc")
        pltspec = args[ind + 1]
        verbose = 0
        plots = 1
    #
    con = nb.Contribution(dir_path, read_tables=["measurements"], custom_filenames={"measurements": meas_file})
    # get as much name data as possible (used for naming plots)
    if not "measurements" in con.tables:
        print "-W- No measurement file found"
        return
    con.propagate_name_down("location", "measurements")

    if "measurements" not in con.tables:
        print main.__doc__
        print "bad file"
        sys.exit()
    meas_container = con.tables["measurements"]
    # meas_df = meas_container.df

    #
    # initialize some variables
    # define figure numbers for hyst,deltaM,DdeltaM curves
    HystRecs = []
    HDD = {}
    HDD["hyst"] = 1
    pmagplotlib.plot_init(HDD["hyst"], 5, 5)
    #
    # get list of unique experiment names and specimen names
    #
    sids = []
    hyst_data = meas_container.get_records_for_code("LP-HYS")
    # experiment_names = hyst_data['experiment_name'].unique()
    if not len(hyst_data):
        print "-W- No hysteresis data found"
        return
    sids = hyst_data["specimen"].unique()

    # if 'treat_temp' is provided, use that value, otherwise assume 300
    hyst_data["treat_temp"].where(hyst_data["treat_temp"], "300", inplace=True)
    # start at first specimen, or at provided specimen ('-spc')
    k = 0
    if pltspec != "":
        try:
            print sids
            k = list(sids).index(pltspec)
        except ValueError:
            print "-W- No specimen named: {}.".format(pltspec)
            print "-W- Please provide a valid specimen name"
            return
    intlist = ["magn_moment", "magn_volume", "magn_mass"]

    while k < len(sids):
        locname, site, sample, synth = "", "", "", ""
        s = sids[k]
        if verbose:
            print s, k + 1, "out of ", len(sids)
        # B, M for hysteresis, Bdcd,Mdcd for irm-dcd data
        B, M = [], []
        # get all measurements for this specimen
        spec = hyst_data[hyst_data["specimen"] == s]
        # get names
        if "location" in spec:
            locname = spec["location"][0]
        if "site" in spec:
            site = spec["sample"][0]
        if "sample" in spec:
            sample = spec["sample"][0]

        # get all records with non-blank values in any intlist column
        # find intensity data
        for int_column in intlist:
            if int_column in spec.columns:
                int_col = int_column
                break
        meas_data = spec[spec[int_column].notnull()]
        if len(meas_data) == 0:
            break
        #
        c = ["k-", "b-", "c-", "g-", "m-", "r-", "y-"]
        cnum = 0
        Temps = []
        xlab, ylab, title = "", "", ""
        Temps = meas_data["treat_temp"].unique()
        for t in Temps:
            print "working on t: ", t
            t_data = meas_data[meas_data["treat_temp"] == t]
            m = int_col
            B = t_data["meas_field_dc"].astype(float).values
            M = t_data[m].astype(float).values
            # 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
            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
Exemplo n.º 15
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
    print('verbose', verbose)
    #
    #
    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 pmagplotlib.isServer:  # use server plot naming convention
                    if synth == '':
                        filename = "LO:_" + locname + '_SI:_' + site + '_SA:_' + sample + '_SP:_' + s + '_TY:_' + key + '_.' + fmt
                    else:
                        filename = 'SY:_' + synth + '_TY:_' + key + '_.' + fmt
                    files[key] = filename
                else:  # use more readable plot naming convention
                    if synth == '':
                        filename = ''
                        for item in [locname, site, sample, s, key]:
                            if item:
                                item = item.replace(' ', '_')
                                filename += item + '_'
                        if filename.endswith('_'):
                            filename = filename[:-1]
                        filename += ".{}".format(fmt)
                    else:
                        filename = synth + '_' + key + '.fmt'
                    files[key] = filename

            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():
                    if pmagplotlib.isServer:
                        print('server')
                        files[
                            key] = "LO:_" + locname + '_SI:_' + site + '_SA:_' + sample + '_SP:_' + s + '_TY:_' + key + '_.' + fmt
                    else:
                        print('not server')
                        filename = ''
                        for item in [locname, site, sample, s, key]:
                            if item:
                                item = item.replace(' ', '_')
                                filename += item + '_'
                        if filename.endswith('_'):
                            filename = filename[:-1]
                        filename += ".{}".format(fmt)
                        files[key] = filename
                print('files', files)
                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
Exemplo n.º 16
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
        -sav figure and quit
        -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 = ""
    #plot=0
    no_plot = pmag.get_flag_arg_from_sys('-sav')
    if not no_plot:
        do_plot = True
    else:
        do_plot = False
    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 '-h' in sys.argv:
        do_plot = False
    if '-i' in sys.argv:
        #
        # get name of file from command line
        #
        file = 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 = 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 = 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 list(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 list(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 list(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 list(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,
                               sym='ro',
                               xlab=methx,
                               ylab=methy,
                               title=plot + ':Biplot')
            if not pmagplotlib.isServer and do_plot:
                pmagplotlib.drawFIGS(FIG)
                ans = input('S[a]ve plots, [q]uit,  Return for next plot ')
                if ans == 'a':
                    files = {}
                    for key in list(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 list(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.º 17
0
def main():
    """
    NAME
        lowrie_magic.py

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

    SYNTAX 
        lowrie_magic.py -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
        -sav saves plots and quits
    """
    fmt, plot = 'svg', 0
    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 '-sav' in sys.argv: plot = 1  # don't normalize
        if '-fmt' in sys.argv:  # sets input filename
            ind = sys.argv.index("-fmt")
            fmt = sys.argv[ind + 1]
        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,
                           old_div(abs(carts[0]), nrm),
                           sym='r-')
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[0]), nrm),
                           sym='ro')  # X direction
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[1]), nrm),
                           sym='c-')
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[1]), nrm),
                           sym='cs')  # Y direction
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[2]), nrm),
                           sym='k-')
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[2]), nrm),
                           sym='k^',
                           title=spc,
                           xlab=xlab,
                           ylab=ylab)  # Z direction
        files = {'lowrie': 'lowrie:_' + spc + '_.' + fmt}
        if plot == 0:
            pmagplotlib.drawFIGS(FIG)
            ans = input('S[a]ve figure? [q]uit, <return> to continue   ')
            if ans == 'a':
                pmagplotlib.saveP(FIG, files)
            elif ans == 'q':
                sys.exit()
        else:
            pmagplotlib.saveP(FIG, files)
        pmagplotlib.clearFIG(FIG['lowrie'])
Exemplo n.º 18
0
def main():
    """
    NAME
        lowrie_magic.py

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

    SYNTAX 
        lowrie_magic.py -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
        -sav saves plots and quits
    """
    fmt,plot='svg',0
    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 '-sav' in sys.argv: plot=1 # don't normalize
        if '-fmt' in sys.argv: # sets input filename
            ind=sys.argv.index("-fmt")
            fmt=sys.argv[ind+1]
        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
        files={'lowrie':'lowrie:_'+spc+'_.'+fmt}
        if plot==0:
            pmagplotlib.drawFIGS(FIG)
            ans=raw_input('S[a]ve figure? [q]uit, <return> to continue   ')
            if ans=='a':
                pmagplotlib.saveP(FIG,files)
            elif ans=='q':
                sys.exit()
        else:
            pmagplotlib.saveP(FIG,files)
        pmagplotlib.clearFIG(FIG['lowrie'])
Exemplo n.º 19
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.º 20
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
        -f: specify input file, default is 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
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    plots = 0
    pltspec = ""
    verbose = pmagplotlib.verbose
    #version_num = pmag.get_version()
    dir_path = pmag.get_named_arg_from_sys('-WD', '.')
    dir_path = os.path.realpath(dir_path)
    meas_file = pmag.get_named_arg_from_sys('-f', 'measurements.txt')
    fmt = pmag.get_named_arg_from_sys('-fmt', 'png')
    if '-sav' in args:
        verbose = 0
        plots = 1
    if '-spc' in args:
        ind = args.index("-spc")
        pltspec = args[ind+1]
        verbose = 0
        plots = 1
    #
    con = nb.Contribution(dir_path, read_tables=['measurements'],
                          custom_filenames={'measurements': meas_file})
    # get as much name data as possible (used for naming plots)
    if not 'measurements' in con.tables:
        print("-W- No measurement file found")
        return
    con.propagate_location_to_measurements()

    if 'measurements' not in con.tables:
        print(main.__doc__)
        print('bad file')
        sys.exit()
    meas_container = con.tables['measurements']
    #meas_df = meas_container.df

    #
    # initialize some variables
    # define figure numbers for hyst,deltaM,DdeltaM curves
    HystRecs = []
    HDD = {}
    HDD['hyst'] = 1
    pmagplotlib.plot_init(HDD['hyst'], 5, 5)
    #
    # get list of unique experiment names and specimen names
    #
    sids = []
    hyst_data = meas_container.get_records_for_code('LP-HYS')
    #experiment_names = hyst_data['experiment_name'].unique()
    if not len(hyst_data):
        print("-W- No hysteresis data found")
        return
    sids = hyst_data['specimen'].unique()

    # if 'treat_temp' is provided, use that value, otherwise assume 300
    hyst_data['treat_temp'].where(hyst_data['treat_temp'].notnull(), '300', inplace=True)
    # start at first specimen, or at provided specimen ('-spc')
    k = 0
    if pltspec != "":
        try:
            print(sids)
            k = list(sids).index(pltspec)
        except ValueError:
            print('-W- No specimen named: {}.'.format(pltspec))
            print('-W- Please provide a valid specimen name')
            return
    intlist = ['magn_moment', 'magn_volume', 'magn_mass']

    while k < len(sids):
        locname, site, sample, synth = '', '', '', ''
        s = sids[k]
        if verbose:
            print(s, k + 1, 'out of ', len(sids))
        # B, M for hysteresis, Bdcd,Mdcd for irm-dcd data
        B, M = [], []
        # get all measurements for this specimen
        spec = hyst_data[hyst_data['specimen'] == s]
        # get names
        if 'location' in spec:
            locname = spec['location'][0]
        if 'site' in spec:
            site = spec['sample'][0]
        if 'sample' in spec:
            sample = spec['sample'][0]

        # get all records with non-blank values in any intlist column
        # find intensity data
        for int_column in intlist:
            if int_column in spec.columns:
                int_col = int_column
                break
        meas_data = spec[spec[int_column].notnull()]
        if len(meas_data) == 0:
            break
        #
        c = ['k-', 'b-', 'c-', 'g-', 'm-', 'r-', 'y-']
        cnum = 0
        Temps = []
        xlab, ylab, title = '', '', ''
        Temps = meas_data['treat_temp'].unique()
        for t in Temps:
            print('working on t: ', t)
            t_data = meas_data[meas_data['treat_temp'] == t]
            m = int_col
            B = t_data['meas_field_dc'].astype(float).values
            M = t_data[m].astype(float).values
            # 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
            for key in list(HDD.keys()):
                if pmagplotlib.isServer:
                    if synth == '':
                        files[key] = "LO:_"+locname+'_SI:_'+site+'_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt
                    else:
                        files[key] = 'SY:_'+synth+'_TY:_'+key+'_.'+fmt
                else:
                    if synth == '':
                        filename = ''
                        for item in [locname, site, sample, s, key]:
                            if item:
                                item = item.replace(' ', '_')
                                filename += item + '_'
                        if filename.endswith('_'):
                            filename = filename[:-1]
                        filename += ".{}".format(fmt)
                        files[key] = filename
                    else:
                        files[key] = "{}_{}.{}".format(synth, key, fmt)

            pmagplotlib.saveP(HDD, files)
            if pltspec != "":
                sys.exit()
        if verbose:
            pmagplotlib.drawFIGS(HDD)
            ans = input("S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ")
            if ans == "a":
                files = {}
                for key in list(HDD.keys()):
                    if pmagplotlib.isServer: # use server plot naming convention
                        files[key] = "LO:_"+locname+'_SI:_'+site+'_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt
                    else: # use more readable plot naming convention
                        filename = ''
                        for item in [locname, site, sample, s, key]:
                            if item:
                                item = item.replace(' ', '_')
                                filename += item + '_'
                        if filename.endswith('_'):
                            filename = filename[:-1]
                        filename += ".{}".format(fmt)
                        files[key] = filename

                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 = 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 = 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