Пример #1
0
def main():
    """
    NAME
        biplot_magic.py

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

    INPUT 
        takes magic formated magic_measurments file

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

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

    DESCRIPTION
       plots intensity decay curves for demagnetization experiments

    SYNTAX 
        dmag_magic -h [command line options]
    
    INPUT 
       takes magic formatted magic_measurements.txt files
    
    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: magic_measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot, default is by location
        -LT [AF,T,M]: specify lab treatment type, default AF
        -XLP [PI]: exclude specific  lab protocols (for example, method codes like LP-PI)
        -N do not normalize by NRM magnetization
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    FIG={} # plot dictionary
    FIG['demag']=1 # demag is figure 1
    in_file,plot_key,LT='magic_measurements.txt','er_location_name',"LT-AF-Z"
    XLP=""
    norm=1
    LT='LT-AF-Z'
    units,dmag_key='T','treatment_ac_field'
    plot_key='er_location_name'
    if len(sys.argv)>1:
        if '-h' in sys.argv:
            print main.__doc__
            sys.exit()
        if '-N' in sys.argv: norm=0
        if '-f' in sys.argv:
            ind=sys.argv.index("-f")
            in_file=sys.argv[ind+1]
        if '-obj' in sys.argv:
            ind=sys.argv.index('-obj')
            plot_by=sys.argv[ind+1]
            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 '-XLP' in sys.argv:
            ind=sys.argv.index("-XLP")
            XLP=sys.argv[ind+1] # get lab protocol for excluding
        if '-LT' in sys.argv:
            ind=sys.argv.index("-LT")
            LT='LT-'+sys.argv[ind+1]+'-Z' # get lab treatment for plotting
            if  LT=='LT-T-Z':
                units,dmag_key='K','treatment_temp'
            elif  LT=='LT-AF-Z':
                units,dmag_key='T','treatment_ac_field'
            elif  LT=='LT-M-Z':
                units,dmag_key='J','treatment_mw_energy'
            else:
                units='U'
    data,file_type=pmag.magic_read(in_file)
    sids=pmag.get_specs(data)
    pmagplotlib.plot_init(FIG['demag'],5,5)
    print len(data),' records read from ',in_file
    #
    #
    # find desired intensity data
    #
    # get plotlist
    #
    plotlist,intlist=[],['measurement_magnitude','measurement_magn_moment','measurement_magn_volume','measurement_magn_mass']
    IntMeths=[]
    FixData=[]
    for  rec in data:
        meths=[]
        methcodes=rec['magic_method_codes'].split(':')
        for meth in methcodes:meths.append(meth.strip())
        for key in rec.keys():
            if key in intlist and rec[key]!="":
                if key not in IntMeths:IntMeths.append(key)
                if rec[plot_key] not in plotlist and LT in meths: plotlist.append(rec[plot_key])
                if 'measurement_flag' not in rec.keys():rec['measurement_flag']='g'
                FixData.append(rec)
        plotlist.sort()
    if len(IntMeths)==0:
        print 'No intensity information found'
        sys.exit()
    data=FixData
    int_key=IntMeths[0] # plot first intensity method found - normalized to initial value anyway - doesn't matter which used
    for plot in plotlist:
        print plot,'plotting by: ',plot_key
        PLTblock=pmag.get_dictitem(data,plot_key,plot,'T') # fish out all the data for this type of plot
        PLTblock=pmag.get_dictitem(PLTblock,'magic_method_codes',LT,'has') # fish out all the dmag for this experiment type
        PLTblock=pmag.get_dictitem(PLTblock,int_key,'','F') # get all with this intensity key non-blank
        if XLP!="":PLTblock=pmag.get_dictitem(PLTblock,'magic_method_codes',XLP,'not') # reject data with XLP in method_code
        if len(PLTblock)>2:
            title=PLTblock[0][plot_key]
            spcs=[]
            for rec in PLTblock:
                if rec['er_specimen_name'] not in spcs:spcs.append(rec['er_specimen_name'])
            for spc in spcs:
                SPCblock=pmag.get_dictitem(PLTblock,'er_specimen_name',spc,'T') # plot specimen by specimen
                INTblock=[]
                for rec in SPCblock:
                    INTblock.append([float(rec[dmag_key]),0,0,float(rec[int_key]),1,rec['measurement_flag']])
                if len(INTblock)>2:
                    pmagplotlib.plotMT(FIG['demag'],INTblock,title,0,units,norm)
            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]=title+'_'+LT+'.svg' 
                pmagplotlib.saveP(FIG,files) 
            pmagplotlib.clearFIG(FIG['demag'])
Пример #3
0
def main():
    """
    NAME
        thellier_magic.py
    
    DESCRIPTION
        plots Thellier-Thellier, allowing interactive setting of bounds
        and customizing of selection criteria.  Saves and reads interpretations
        from a pmag_specimen formatted table, default: thellier_specimens.txt

    SYNTAX 
        thellier_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f MEAS, set magic_measurements input file
        -fsp PRIOR, set pmag_specimen prior interpretations file
        -fan ANIS, set rmag_anisotropy file for doing the anisotropy corrections
        -fcr CRIT, set criteria file for grading.  
        -fmt [svg,png,jpg], format for images - default is svg
        -sav,  saves plots with out review (default format)
        -spc SPEC, plots single specimen SPEC, saves plot with specified format
            with optional -b bounds adn quits
        -b BEG END: sets  bounds for calculation
           BEG: starting step for slope calculation
           END: ending step for slope calculation
        -z use only z component difference for pTRM calculation
        
    DEFAULTS
        MEAS: magic_measurements.txt
        REDO: thellier_redo
        CRIT: NONE
        PRIOR: NONE
  
    OUTPUT 
        figures:
            ALL:  numbers refer to temperature steps in command line window
            1) Arai plot:  closed circles are zero-field first/infield
                           open circles are infield first/zero-field
                           triangles are pTRM checks
                           squares are pTRM tail checks
                           VDS is vector difference sum
                           diamonds are bounds for interpretation
            2) Zijderveld plot:  closed (open) symbols are X-Y (X-Z) planes
                                 X rotated to NRM direction
            3) (De/Re)Magnetization diagram:
                           circles are NRM remaining
                           squares are pTRM gained
            4) equal area projections:
 			   green triangles are pTRM gained direction
                           red (purple) circles are lower(upper) hemisphere of ZI step directions 
                           blue (cyan) squares are lower(upper) hemisphere IZ step directions 
            5) Optional:  TRM acquisition
            6) Optional: TDS normalization
        command line window:
            list is: temperature step numbers, temperatures (C), Dec, Inc, Int (units of magic_measuements)
                     list of possible commands: type letter followed by return to select option
                     saving of plots creates .svg format files with specimen_name, plot type as name
    """ 
#
#   initializations
#
    meas_file,critout,inspec="magic_measurements.txt","","thellier_specimens.txt"
    first=1
    inlt=0
    version_num=pmag.get_version()
    TDinit,Tinit,field,first_save=0,0,-1,1
    user,comment,AniSpec,locname="",'',"",""
    ans,specimen,recnum,start,end=0,0,0,0,0
    plots,pmag_out,samp_file,style=0,"","","svg"
    verbose=pmagplotlib.verbose 
    fmt='.'+style
#
# default acceptance criteria
#
    accept=pmag.default_criteria(0)[0] # set the default criteria
#
# parse command line options
#
    Zdiff,anis=0,0
    spc,BEG,END="","",""
    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]
    if '-fsp' in sys.argv:
        ind=sys.argv.index('-fsp')
        inspec=sys.argv[ind+1]
    if '-fan' in sys.argv:
        ind=sys.argv.index('-fan')
        anisfile=sys.argv[ind+1]
        anis=1
        anis_data,file_type=pmag.magic_read(anisfile)
        if verbose: print "Anisotropy data read in from ", anisfile
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt='.'+sys.argv[ind+1]
    if '-sav' in sys.argv: 
        plots=1
        verbose=0
    if '-z' in sys.argv: Zdiff=1
    if '-spc' in sys.argv:
        ind=sys.argv.index('-spc')
        spc=sys.argv[ind+1]
        if '-b' in sys.argv:
            ind=sys.argv.index('-b')
            BEG=int(sys.argv[ind+1])
            END=int(sys.argv[ind+2])
    if '-fcr' in sys.argv:
        ind=sys.argv.index('-fcr')
        critout=sys.argv[ind+1]
        crit_data,file_type=pmag.magic_read(critout)
        if file_type!='pmag_criteria':
            if verbose: print 'bad pmag_criteria file, using no acceptance criteria'
            accept=pmag.default_criteria(1)[0]
        else:
            if verbose: print "Acceptance criteria read in from ", critout
            accept={'pmag_criteria_code':'ACCEPTANCE','er_citation_names':'This study'}
            for critrec in crit_data:
                if 'sample_int_sigma_uT' in critrec.keys(): # accommodate Shaar's new criterion
                    critrec['sample_int_sigma']='%10.3e'%(eval(critrec['sample_int_sigma_uT'])*1e-6)
                for key in critrec.keys():
                    if key not in accept.keys() and critrec[key]!='':
                        accept[key]=critrec[key]
    try:
        open(inspec,'rU')
        PriorRecs,file_type=pmag.magic_read(inspec)
        if file_type != 'pmag_specimens':
            print file_type
            print file_type,inspec," is not a valid pmag_specimens file " 
            sys.exit()
        for rec in PriorRecs:
            if 'magic_software_packages' not in rec.keys():rec['magic_software_packages']=""
    except IOError:
        PriorRecs=[]
        if verbose:print "starting new specimen interpretation file: ",inspec
    meas_data,file_type=pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print file_type
        print file_type,"This is not a valid magic_measurements file " 
        sys.exit()
    backup=0
    # define figure numbers for arai, zijderveld and 
    #   de-,re-magization diagrams
    AZD={}
    AZD['deremag'], AZD['zijd'],AZD['arai'],AZD['eqarea']=1,2,3,4
    pmagplotlib.plot_init(AZD['arai'],5,5)
    pmagplotlib.plot_init(AZD['zijd'],5,5)
    pmagplotlib.plot_init(AZD['deremag'],5,5)
    pmagplotlib.plot_init(AZD['eqarea'],5,5)
    #
    #
    #
    # get list of unique specimen names
    #
    CurrRec=[]
    sids=pmag.get_specs(meas_data)
    # get plots for specimen s - default is just to step through arai diagrams
    #
    if spc!="": specimen =sids.index(spc)
    while specimen < len(sids):
        methcodes=[]
       
        if verbose:
            print sids[specimen],specimen+1, 'of ', len(sids)
        MeasRecs=[]
        s=sids[specimen]
        datablock,trmblock,tdsrecs=[],[],[]
        PmagSpecRec={}
        if first==0:
           for key in keys:PmagSpecRec[key]="" # make sure all new records have same set of keys
        PmagSpecRec["er_analyst_mail_names"]=user
        PmagSpecRec["specimen_correction"]='u'
    #
    # find the data from the meas_data file for this specimen
    #
        for rec in meas_data:
            if rec["er_specimen_name"]==s:
                MeasRecs.append(rec)
                if "magic_method_codes" not in rec.keys():
                    rec["magic_method_codes"]=""
                methods=rec["magic_method_codes"].split(":")
                meths=[]
                for meth in methods:
                    meths.append(meth.strip()) # take off annoying spaces
                methods=""
                for meth in meths:
                    if meth.strip() not in methcodes and "LP-" in meth:methcodes.append(meth.strip())
                    methods=methods+meth+":"
                methods=methods[:-1]
                rec["magic_method_codes"]=methods 
                if "LP-PI-TRM" in meths: datablock.append(rec)
                if "LP-TRM" in meths: trmblock.append(rec)
                if "LP-TRM-TD" in meths: tdsrecs.append(rec)
        if len(trmblock)>2 and inspec!="":
            if Tinit==0:
                Tinit=1
                AZD['TRM']=5
                pmagplotlib.plot_init(AZD['TRM'],5,5)
        elif Tinit==1: # clear the TRM figure if not needed
            pmagplotlib.clearFIG(AZD['TRM'])
        if len(tdsrecs)>2:
            if TDinit==0:
                TDinit=1
                AZD['TDS']=6
                pmagplotlib.plot_init(AZD['TDS'],5,5)
        elif TDinit==1: # clear the TDS figure if not needed
            pmagplotlib.clearFIG(AZD['TDS'])
        if len(datablock) <4:
           if backup==0:
               specimen+=1
               if verbose:
                   print 'skipping specimen - moving forward ', s
           else:
               specimen-=1
               if verbose:
                   print 'skipping specimen - moving backward ', s
    #
    #  collect info for the PmagSpecRec dictionary
    #
        else:
           rec=datablock[0]
           PmagSpecRec["er_citation_names"]="This study"
           PmagSpecRec["er_specimen_name"]=s
           PmagSpecRec["er_sample_name"]=rec["er_sample_name"]
           PmagSpecRec["er_site_name"]=rec["er_site_name"]
           PmagSpecRec["er_location_name"]=rec["er_location_name"]
           locname=rec['er_location_name'].replace('/','-')
           if "er_expedition_name" in rec.keys():PmagSpecRec["er_expedition_name"]=rec["er_expedition_name"]
           if "magic_instrument_codes" not in rec.keys():rec["magic_instrument_codes"]=""
           PmagSpecRec["magic_instrument_codes"]=rec["magic_instrument_codes"]
           PmagSpecRec["measurement_step_unit"]="K"
           if "magic_experiment_name" not in rec.keys():
               rec["magic_experiment_name"]=""
           else:
               PmagSpecRec["magic_experiment_names"]=rec["magic_experiment_name"]
    
           meths=rec["magic_method_codes"].split()
       # sort data into types
           araiblock,field=pmag.sortarai(datablock,s,Zdiff)
           first_Z=araiblock[0]
           GammaChecks=araiblock[5]
           if len(first_Z)<3:
               if backup==0:
                   specimen+=1
                   if verbose:
                       print 'skipping specimen - moving forward ', s
               else:
                   specimen-=1
                   if verbose:
                       print 'skipping specimen - moving backward ', s
           else:
               backup=0
               zijdblock,units=pmag.find_dmag_rec(s,meas_data)
               recnum=0
               if verbose:
                   print "index step Dec   Inc  Int       Gamma"
                   for plotrec in zijdblock:
                       if GammaChecks!="":
                           gamma=""
                           for g in GammaChecks:
                               if g[0]==plotrec[0]-273:
                                   gamma=g[1]
                                   break
                       if gamma!="":
                           print '%i     %i %7.1f %7.1f %8.3e %7.1f' % (recnum,plotrec[0]-273,plotrec[1],plotrec[2],plotrec[3],gamma)
                       else:
                           print '%i     %i %7.1f %7.1f %8.3e ' % (recnum,plotrec[0]-273,plotrec[1],plotrec[2],plotrec[3])
                       recnum += 1
               pmagplotlib.plotAZ(AZD,araiblock,zijdblock,s,units[0])
               if verbose:pmagplotlib.drawFIGS(AZD)
               if len(tdsrecs)>2: # a TDS experiment
                   tdsblock=[] # make a list for the TDS  data
                   Mkeys=['measurement_magnitude','measurement_magn_moment','measurement_magn_volume','measuruement_magn_mass']
                   mkey,k="",0
                   while mkey=="" and k<len(Mkeys)-1: # find which type of intensity
                       key= Mkeys[k]
                       if key in tdsrecs[0].keys() and tdsrecs[0][key]!="": mkey=key
                       k+=1
                   if mkey=="":break # get outta here
                   Tnorm=""
                   for tdrec in tdsrecs:
                       meths=tdrec['magic_method_codes'].split(":")
                       for meth in meths: meth.replace(" ","") # strip off potential nasty spaces
                       if  'LT-T-I' in meths and Tnorm=="": # found first total TRM 
                           Tnorm=float(tdrec[mkey]) # normalize by total TRM 
                           tdsblock.append([273,zijdblock[0][3]/Tnorm,1.]) # put in the zero step
                       if  'LT-T-Z' in meths and Tnorm!="": # found a LP-TRM-TD demag step, now need complementary LT-T-Z from zijdblock
                           step=float(tdrec['treatment_temp'])
                           Tint=""
                           if mkey!="":
                               Tint=float(tdrec[mkey])
                           if Tint!="":
                               for zrec in zijdblock:
                                   if zrec[0]==step:  # found matching
                                       tdsblock.append([step,zrec[3]/Tnorm,Tint/Tnorm])
                                       break
                   if len(tdsblock)>2: 
                       pmagplotlib.plotTDS(AZD['TDS'],tdsblock,s+':LP-PI-TDS:')
                       if verbose:pmagplotlib(drawFIGS(AZD)) 
                   else: 
                       print "Something wrong here"
               if anis==1:   # look up anisotropy data for this specimen
                   AniSpec=""
                   for aspec in anis_data:
                       if aspec["er_specimen_name"]==PmagSpecRec["er_specimen_name"]:
                           AniSpec=aspec
                           if verbose: print 'Found anisotropy record...'
                           break
               if inspec !="":
                   if verbose: print 'Looking up saved interpretation....'
                   found = 0
                   for k in range(len(PriorRecs)):
                       try:
                         if PriorRecs[k]["er_specimen_name"]==s:
                           found =1
                           CurrRec.append(PriorRecs[k])
                           for j in range(len(zijdblock)):
                               if float(zijdblock[j][0])==float(PriorRecs[k]["measurement_step_min"]):start=j
                               if float(zijdblock[j][0])==float(PriorRecs[k]["measurement_step_max"]):end=j
                           pars,errcode=pmag.PintPars(datablock,araiblock,zijdblock,start,end,accept)
                           pars['measurement_step_unit']="K"
                           pars['experiment_type']='LP-PI-TRM'
                           del PriorRecs[k]  # put in CurrRec, take out of PriorRecs
                           if errcode!=1:
                               pars["specimen_lab_field_dc"]=field
                               pars["specimen_int"]=-1*field*pars["specimen_b"]
                               pars["er_specimen_name"]=s
                               if verbose:
                                   print 'Saved interpretation: '
                               pars,kill=pmag.scoreit(pars,PmagSpecRec,accept,'',verbose)
                               pmagplotlib.plotB(AZD,araiblock,zijdblock,pars)
                               if verbose:pmagplotlib.drawFIGS(AZD)
                               if len(trmblock)>2:
                                   blab=field
                                   best=pars["specimen_int"]
                                   Bs,TRMs=[],[]
                                   for trec in trmblock:
                                       Bs.append(float(trec['treatment_dc_field']))
                                       TRMs.append(float(trec['measurement_magn_moment']))
                                   NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc
                                   Mp,Bp=[],[]
                                   for k in  range(int(max(Bs)*1e6)):
                                       Bp.append(float(k)*1e-6)
                                       npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field
                                       Mp.append(npred)
                                   pmagplotlib.plotTRM(AZD['TRM'],Bs,TRMs,Bp,Mp,NLpars,trec['magic_experiment_name'])
                                   PmagSpecRec['specimen_int']=NLpars['banc'] 
                                   if verbose:
                                       print 'Banc= ',float(NLpars['banc'])*1e6
                                       pmagplotlib.drawFIGS(AZD)
                               mpars=pmag.domean(araiblock[1],start,end,'DE-BFL')
                               if verbose:
                                       print 'pTRM direction= ','%7.1f'%(mpars['specimen_dec']),' %7.1f'%(mpars['specimen_inc']),' MAD:','%7.1f'%(mpars['specimen_mad'])
                               if AniSpec!="":
                                   CpTRM=pmag.Dir_anis_corr([mpars['specimen_dec'],mpars['specimen_inc']],AniSpec)
                                   AniSpecRec=pmag.doaniscorr(PmagSpecRec,AniSpec)
                                   if verbose:
                                       print 'Anisotropy corrected TRM direction= ','%7.1f'%(CpTRM[0]),' %7.1f'%(CpTRM[1])
                                       print 'Anisotropy corrected intensity= ',float(AniSpecRec['specimen_int'])*1e6
                           else:
                               print 'error on specimen ',s
                       except:
                         pass
                   if verbose and found==0: print  '    None found :(  ' 
               if spc!="":
                   if BEG!="": 
                       pars,errcode=pmag.PintPars(datablock,araiblock,zijdblock,BEG,END,accept)
                       pars['measurement_step_unit']="K"
                       pars["specimen_lab_field_dc"]=field
                       pars["specimen_int"]=-1*field*pars["specimen_b"]
                       pars["er_specimen_name"]=s
                       pars['specimen_grade']='' # ungraded
                       pmagplotlib.plotB(AZD,araiblock,zijdblock,pars)
                       if verbose:pmagplotlib.drawFIGS(AZD)
                       if len(trmblock)>2:
                           if inlt==0:
                               inlt=1
                           blab=field
                           best=pars["specimen_int"]
                           Bs,TRMs=[],[]
                           for trec in trmblock:
                               Bs.append(float(trec['treatment_dc_field']))
                               TRMs.append(float(trec['measurement_magn_moment']))
                           NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc
    #
                           Mp,Bp=[],[]
                           for k in  range(int(max(Bs)*1e6)):
                               Bp.append(float(k)*1e-6)
                               npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field
                   files={}
                   for key in AZD.keys():
                       files[key]=s+'_'+key+fmt 
                   pmagplotlib.saveP(AZD,files)
                   sys.exit()
               if verbose:
                   ans='b'
                   while ans != "":
                       print """
               s[a]ve plot, set [b]ounds for calculation, [d]elete current interpretation, [p]revious, [s]ample, [q]uit:
               """
                       ans=raw_input('Return for next specimen \n')
                       if ans=="": 
                           specimen +=1
                       if ans=="d": 
                           save_redo(PriorRecs,inspec)
                           CurrRec=[]
                           pmagplotlib.plotAZ(AZD,araiblock,zijdblock,s,units[0])
                           if verbose:pmagplotlib.drawFIGS(AZD)
                       if ans=='a':
                           files={}
                           for key in AZD.keys():
                               files[key]="LO:_"+locname+'_SI:_'+PmagSpecRec['er_site_name']+'_SA:_'+PmagSpecRec['er_sample_name']+'_SP:_'+s+'_CO:_s_TY:_'+key+fmt
                           pmagplotlib.saveP(AZD,files)
                           ans=""
                       if ans=='q':
                           print "Good bye"
                           sys.exit()
                       if ans=='p':
                           specimen =specimen -1
                           backup = 1
                           ans=""
                       if ans=='s':
                           keepon=1
                           spec=raw_input('Enter desired specimen name (or first part there of): ')
                           while keepon==1:
                               try:
                                   specimen =sids.index(spec)
                                   keepon=0
                               except:
                                   tmplist=[]
                                   for qq in range(len(sids)):
                                       if spec in sids[qq]:tmplist.append(sids[qq])
                                   print specimen," not found, but this was: "
                                   print tmplist
                                   spec=raw_input('Select one or try again\n ')
                           ans=""
                       if  ans=='b':
                           if end==0 or end >=len(zijdblock):end=len(zijdblock)-1
                           GoOn=0
                           while GoOn==0:
                               answer=raw_input('Enter index of first point for calculation: ['+str(start)+']  ')
                               try:
                                   start=int(answer)
                                   answer=raw_input('Enter index  of last point for calculation: ['+str(end)+']  ')
                                   end=int(answer)
                                   if start >=0 and start <len(zijdblock)-2 and end >0 and end <len(zijdblock) or start>=end:
                                       GoOn=1
                                   else:
                                       print "Bad endpoints - try again! "
                                       start,end=0,len(zijdblock)
                               except ValueError:
                                   print "Bad endpoints - try again! "
                                   start,end=0,len(zijdblock)
                           s=sids[specimen] 
                           pars,errcode=pmag.PintPars(datablock,araiblock,zijdblock,start,end,accept)
                           pars['measurement_step_unit']="K"
                           pars["specimen_lab_field_dc"]=field
                           pars["specimen_int"]=-1*field*pars["specimen_b"]
                           pars["er_specimen_name"]=s
                           pars,kill=pmag.scoreit(pars,PmagSpecRec,accept,'',0)
                           PmagSpecRec['specimen_scat']=pars['specimen_scat']
                           PmagSpecRec['specimen_frac']='%5.3f'%(pars['specimen_frac'])
                           PmagSpecRec['specimen_gmax']='%5.3f'%(pars['specimen_gmax'])
                           PmagSpecRec["measurement_step_min"]='%8.3e' % (pars["measurement_step_min"])
                           PmagSpecRec["measurement_step_max"]='%8.3e' % (pars["measurement_step_max"])
                           PmagSpecRec["measurement_step_unit"]="K"
                           PmagSpecRec["specimen_int_n"]='%i'%(pars["specimen_int_n"])
                           PmagSpecRec["specimen_lab_field_dc"]='%8.3e'%(pars["specimen_lab_field_dc"])
                           PmagSpecRec["specimen_int"]='%9.4e '%(pars["specimen_int"])
                           PmagSpecRec["specimen_b"]='%5.3f '%(pars["specimen_b"])
                           PmagSpecRec["specimen_q"]='%5.1f '%(pars["specimen_q"])
                           PmagSpecRec["specimen_f"]='%5.3f '%(pars["specimen_f"])
                           PmagSpecRec["specimen_fvds"]='%5.3f'%(pars["specimen_fvds"])
                           PmagSpecRec["specimen_b_beta"]='%5.3f'%(pars["specimen_b_beta"])
                           PmagSpecRec["specimen_int_mad"]='%7.1f'%(pars["specimen_int_mad"])
                           PmagSpecRec["specimen_Z"]='%7.1f'%(pars["specimen_Z"])
                           PmagSpecRec["specimen_gamma"]='%7.1f'%(pars["specimen_gamma"])
                           PmagSpecRec["specimen_grade"]=pars["specimen_grade"]
                           if pars["method_codes"]!="":
                               tmpcodes=pars["method_codes"].split(":")
                               for t in tmpcodes:
                                   if t.strip() not in methcodes:methcodes.append(t.strip())
                           PmagSpecRec["specimen_dec"]='%7.1f'%(pars["specimen_dec"])
                           PmagSpecRec["specimen_inc"]='%7.1f'%(pars["specimen_inc"])
                           PmagSpecRec["specimen_tilt_correction"]='-1'
                           PmagSpecRec["specimen_direction_type"]='l'
                           PmagSpecRec["direction_type"]='l' # this is redundant, but helpful - won't be imported
                           PmagSpecRec["specimen_int_dang"]='%7.1f '%(pars["specimen_int_dang"])
                           PmagSpecRec["specimen_drats"]='%7.1f '%(pars["specimen_drats"])
                           PmagSpecRec["specimen_drat"]='%7.1f '%(pars["specimen_drat"])
                           PmagSpecRec["specimen_int_ptrm_n"]='%i '%(pars["specimen_int_ptrm_n"])
                           PmagSpecRec["specimen_rsc"]='%6.4f '%(pars["specimen_rsc"])
                           PmagSpecRec["specimen_md"]='%i '%(int(pars["specimen_md"]))
                           if PmagSpecRec["specimen_md"]=='-1':PmagSpecRec["specimen_md"]=""
                           PmagSpecRec["specimen_b_sigma"]='%5.3f '%(pars["specimen_b_sigma"])
                           if "IE-TT" not in  methcodes:methcodes.append("IE-TT")
                           methods=""
                           for meth in methcodes:
                               methods=methods+meth+":"
                           PmagSpecRec["magic_method_codes"]=methods[:-1]
                           PmagSpecRec["specimen_description"]=comment
                           PmagSpecRec["magic_software_packages"]=version_num
                           pmagplotlib.plotAZ(AZD,araiblock,zijdblock,s,units[0])
                           pmagplotlib.plotB(AZD,araiblock,zijdblock,pars)
                           if verbose:pmagplotlib.drawFIGS(AZD)
                           if len(trmblock)>2:
                               blab=field
                               best=pars["specimen_int"]
                               Bs,TRMs=[],[]
                               for trec in trmblock:
                                   Bs.append(float(trec['treatment_dc_field']))
                                   TRMs.append(float(trec['measurement_magn_moment']))
                               NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc
                               Mp,Bp=[],[]
                               for k in  range(int(max(Bs)*1e6)):
                                   Bp.append(float(k)*1e-6)
                                   npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field
                                   Mp.append(npred)
                               pmagplotlib.plotTRM(AZD['TRM'],Bs,TRMs,Bp,Mp,NLpars,trec['magic_experiment_name'])
                               if verbose:
                                   print 'Non-linear TRM corrected intensity= ',float(NLpars['banc'])*1e6
                           if verbose:pmagplotlib.drawFIGS(AZD)
                           pars["specimen_lab_field_dc"]=field
                           pars["specimen_int"]=-1*field*pars["specimen_b"]
                           pars,kill=pmag.scoreit(pars,PmagSpecRec,accept,'',verbose)
                           saveit=raw_input("Save this interpretation? [y]/n \n")
                           if saveit!='n':
                               PriorRecs.append(PmagSpecRec) # put back an interpretation
                               specimen+=1
                               save_redo(PriorRecs,inspec)
                           ans=""
               elif plots==1:
                   specimen+=1
                   if fmt != ".pmag":
                       files={}
                       for key in AZD.keys():
                           files[key]="LO:_"+locname+'_SI:_'+PmagSpecRec['er_site_name']+'_SA:_'+PmagSpecRec['er_sample_name']+'_SP:_'+s+'_CO:_s_TY:_'+key+'_'+fmt
                       if pmagplotlib.isServer:
                           black     = '#000000'
                           purple    = '#800080'
                           titles={}
                           titles['deremag']='DeReMag Plot'
                           titles['zijd']='Zijderveld Plot'
                           titles['arai']='Arai Plot'
                           AZD = pmagplotlib.addBorders(AZD,titles,black,purple)
                       pmagplotlib.saveP(AZD,files)
    #                   pmagplotlib.combineFigs(s,files,3)
                   else:  # save in pmag format 
                       script="grep "+s+" output.mag | thellier -mfsi"
                       script=script+' %8.4e'%(field)
                       min='%i'%((pars["measurement_step_min"]-273))
                       Max='%i'%((pars["measurement_step_max"]-273))
                       script=script+" "+min+" "+Max
                       script=script+" |plotxy;cat mypost >>thellier.ps\n"
                       pltf.write(script)
                       pmag.domagicmag(outf,MeasRecs)
        if len(CurrRec)>0:
            for rec in CurrRec:
                PriorRecs.append(rec)
        CurrRec=[]
    if plots!=1 and verbose:
        ans=raw_input(" Save last plot? 1/[0] ")
        if ans=="1":
            if fmt != ".pmag":
                files={}
                for key in AZD.keys():
                    files[key]=s+'_'+key+fmt
                pmagplotlib.saveP(AZD,files)
        else:
            print "\n Good bye\n"
            sys.exit()
        if len(CurrRec)>0:PriorRecs.append(CurrRec) # put back an interpretation
        if len(PriorRecs)>0:
            save_redo(PriorRecs,inspec)
            print 'Updated interpretations saved in ',inspec
    if verbose:
        print "Good bye"
Пример #4
0
def main():
    """
    NAME
        lowrie_magic.py

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

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

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

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

    DESCRIPTION
        calculates hystereis parameters and saves them in rmag_hystereis format file
        makes plots if option selected

    SYNTAX
        hysteresis_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -usr USER:   identify user, default is ""
        -f: specify input file, default is agm_measurements.txt
        -fh: specify rmag_hysteresis.txt input file
        -F: specify output file, default is rmag_hysteresis.txt
        -P: do not make the plots
        -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,rmag_out,rmag_file="","agm_measurements.txt","rmag_hysteresis.txt",""
    pltspec=""
    dir_path='.'
    fmt='svg'
    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 '-F' in args:
        ind=args.index("-F")
        rmag_out=args[ind+1]
    if '-fh' in args:
        ind=args.index("-fh")
        rmag_file=args[ind+1]
        rmag_file=dir_path+'/'+rmag_file
    if '-P' in args:
        PLT=0
        irm_init,imag_init=-1,-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]
    rmag_out=dir_path+'/'+rmag_out
    meas_file=dir_path+'/'+meas_file
    rmag_rem=dir_path+"/rmag_remanence.txt"
    #
    #
    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={}
    if verbose:
        if verbose and PLT:print "Plots may be on top of each other - use mouse to place "
    if PLT:
        HDD['hyst'],HDD['deltaM'],HDD['DdeltaM']=1,2,3
        pmagplotlib.plot_init(HDD['DdeltaM'],5,5)
        pmagplotlib.plot_init(HDD['deltaM'],5,5)
        pmagplotlib.plot_init(HDD['hyst'],5,5)
        imag_init=0
        irm_init=0
    else:
        HDD['hyst'],HDD['deltaM'],HDD['DdeltaM'],HDD['irm'],HDD['imag']=0,0,0,0,0
    #
    if rmag_file!="":hyst_data,file_type=pmag.magic_read(rmag_file)
    #
    # get list of unique experiment names and specimen names
    #
    experiment_names,sids=[],[]
    for rec in meas_data: 
      meths=rec['magic_method_codes'].split(':')
      methods=[]
      for meth in meths:
        methods.append(meth.strip())
      if 'LP-HYS' in methods:
        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'])
    #
    k=0
    locname=''
    if pltspec!="":
        k=sids.index(pltspec)
        print sids[k]
    while k < len(sids):
        s=sids[k]
        if verbose and PLT:print s, k+1 , 'out of ',len(sids)
    #
    #
        B,M,Bdcd,Mdcd=[],[],[],[] #B,M for hysteresis, Bdcd,Mdcd for irm-dcd data
        Bimag,Mimag=[],[] #Bimag,Mimag for initial magnetization curves
        first_dcd_rec,first_rec,first_imag_rec=1,1,1
        for rec in  meas_data:
            methcodes=rec['magic_method_codes'].split(':')
            meths=[]
            for meth in methcodes:
                meths.append(meth.strip()) 
            if rec['er_specimen_name']==s and "LP-HYS" in meths:
                B.append(float(rec['measurement_lab_field_dc']))
                M.append(float(rec['measurement_magn_moment']))
                if first_rec==1:
                    e=rec['magic_experiment_name']
                    HystRec={}
                    first_rec=0
                    if "er_location_name" in rec.keys():
                        HystRec["er_location_name"]=rec["er_location_name"]
                        locname=rec['er_location_name'].replace('/','-')
                    if "er_sample_name" in rec.keys():HystRec["er_sample_name"]=rec["er_sample_name"]
                    if "er_site_name" in rec.keys():HystRec["er_site_name"]=rec["er_site_name"]
                    if "er_synthetic_name" in rec.keys() and rec['er_synthetic_name']!="":
                        HystRec["er_synthetic_name"]=rec["er_synthetic_name"]
                    else:
                        HystRec["er_specimen_name"]=rec["er_specimen_name"]
            if rec['er_specimen_name']==s and "LP-IRM-DCD" in meths:
                Bdcd.append(float(rec['treatment_dc_field']))
                Mdcd.append(float(rec['measurement_magn_moment']))
                if first_dcd_rec==1:
                    RemRec={}
                    irm_exp=rec['magic_experiment_name']
                    first_dcd_rec=0
                    if "er_location_name" in rec.keys():RemRec["er_location_name"]=rec["er_location_name"]
                    if "er_sample_name" in rec.keys():RemRec["er_sample_name"]=rec["er_sample_name"]
                    if "er_site_name" in rec.keys():RemRec["er_site_name"]=rec["er_site_name"]
                    if "er_synthetic_name" in rec.keys() and rec['er_synthetic_name']!="":
                        RemRec["er_synthetic_name"]=rec["er_synthetic_name"]
                    else:
                        RemRec["er_specimen_name"]=rec["er_specimen_name"]
            if rec['er_specimen_name']==s and "LP-IMAG" in meths:
                if first_imag_rec==1:
                    imag_exp=rec['magic_experiment_name']
                    first_imag_rec=0
                Bimag.append(float(rec['measurement_lab_field_dc']))
                Mimag.append(float(rec['measurement_magn_moment']))
    #
    # now plot the hysteresis curve
    #
        if len(B)>0: 
            hmeths=[]
            for meth in meths: hmeths.append(meth)
            hpars=pmagplotlib.plotHDD(HDD,B,M,e) 
            if verbose and PLT:pmagplotlib.drawFIGS(HDD)
    #
    # get prior interpretations from hyst_data
            if rmag_file!="":
                hpars_prior={}
                for rec in hyst_data:
                    if rec['magic_experiment_names']==e:
                        if rec['hysteresis_bcr'] !="" and rec['hysteresis_mr_moment']!="": 
                            hpars_prior['hysteresis_mr_moment']=rec['hysteresis_mr_moment']
                            hpars_prior['hysteresis_ms_moment']=rec['hysteresis_ms_moment']
                            hpars_prior['hysteresis_bc']=rec['hysteresis_bc']
                            hpars_prior['hysteresis_bcr']=rec['hysteresis_bcr']
                            break
                if verbose:pmagplotlib.plotHPARS(HDD,hpars_prior,'ro')
            else:
                if verbose:pmagplotlib.plotHPARS(HDD,hpars,'bs')
                HystRec['hysteresis_mr_moment']=hpars['hysteresis_mr_moment']
                HystRec['hysteresis_ms_moment']=hpars['hysteresis_ms_moment']
                HystRec['hysteresis_bc']=hpars['hysteresis_bc']
                HystRec['hysteresis_bcr']=hpars['hysteresis_bcr']
                HystRec['magic_experiment_names']=e
                HystRec['magic_software_packages']=version_num
                if hpars["magic_method_codes"] not in hmeths:hmeths.append(hpars["magic_method_codes"])
                methods=""
                for meth in hmeths:
                    methods=methods+meth.strip()+":"
                HystRec["magic_method_codes"]=methods[:-1]
                HystRec["er_citation_names"]="This study"
                HystRecs.append(HystRec)
    #
        if len(Bdcd)>0: 
            rmeths=[]
            for meth in meths: rmeths.append(meth)
            if verbose and PLT:print 'plotting IRM'
            if irm_init==0:
                HDD['irm']=5
                pmagplotlib.plot_init(HDD['irm'],5,5)
                irm_init=1
            rpars=pmagplotlib.plotIRM(HDD['irm'],Bdcd,Mdcd,irm_exp) 
            RemRec['remanence_mr_moment']=rpars['remanence_mr_moment']
            RemRec['remanence_bcr']=rpars['remanence_bcr']
            RemRec['magic_experiment_names']=irm_exp
            if rpars["magic_method_codes"] not in meths:meths.append(rpars["magic_method_codes"])
            methods=""
            for meth in rmeths:
                methods=methods+meth.strip()+":"
            RemRec["magic_method_codes"]=methods[:-1]
            RemRec["er_citation_names"]="This study"
            RemRecs.append(RemRec)
        else: 
            if irm_init:pmagplotlib.clearFIG(HDD['irm'])
        if len(Bimag)>0: 
            if verbose:print 'plotting initial magnetization curve'
# first normalize by Ms
            Mnorm=[]
            for m in Mimag: Mnorm.append(m/float(hpars['hysteresis_ms_moment']))
            if imag_init==0:
                HDD['imag']=4
                pmagplotlib.plot_init(HDD['imag'],5,5)
                imag_init=1
            pmagplotlib.plotIMAG(HDD['imag'],Bimag,Mnorm,imag_exp) 
        else: 
            if imag_init:pmagplotlib.clearFIG(HDD['imag'])
    #
        files={}
        if plots:
            if pltspec!="":s=pltspec
            files={}
            for key in HDD.keys():
                files[key]=locname+'_'+s+'_'+key+'.'+fmt
            pmagplotlib.saveP(HDD,files)
            if pltspec!="":sys.exit()
        if verbose and PLT:
            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]=locname+'_'+s+'_'+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 and len(Bdcd)==0:
    	    if verbose:print 'skipping this one - no hysteresis data'
       	    k+=1
    if rmag_out=="" and ans=='s' and verbose:
        really=raw_input(" Do you want to overwrite the existing rmag_hystersis.txt file? 1/[0] ")
        if really=="":
    	    print 'i thought not - goodbye'
    	    sys.exit()
        rmag_out="rmag_hysteresis.txt"
    if len(HystRecs)>0 and verbose:
        pmag.magic_write(rmag_out,HystRecs,"rmag_hysteresis")
        print "hysteresis parameters saved in ",rmag_out
    if len(RemRecs)>0 and verbose:
        pmag.magic_write(rmag_rem,RemRecs,"rmag_remanence")
        print "remanence parameters saved in ",rmag_rem
Пример #7
0
def main():
    """
    NAME
        irmaq_magic.py

    DESCRIPTION
       plots IRM acquisition curves from magic_measurements file

    SYNTAX 
        irmaq_magic [command line options]
    
    INPUT 
       takes magic formatted magic_measurements.txt files
    
    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: magic_measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot, default is by location
        -N ; do not normalize by last point - use original units
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    FIG={} # plot dictionary
    FIG['exp']=1 # exp is figure 1
    in_file,plot_key,LP='magic_measurements.txt','er_location_name',"LP-IRM"
    units,dmag_key='T','treatment_dc_field'
    XLP=[]
    norm=1
    if len(sys.argv)>1:
        if '-h' in sys.argv:
            print main.__doc__
            sys.exit()
        if '-N' in sys.argv:norm=0
        if '-f' in sys.argv:
            ind=sys.argv.index("-f")
            in_file=sys.argv[ind+1]
        if '-obj' in sys.argv:
            ind=sys.argv.index('-obj')
            plot_by=sys.argv[ind+1]
            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 '-LP' in sys.argv:
#            ind=sys.argv.index("-LT")
#            LP='LP-'+sys.argv[ind+1] # get lab protocol for plotting
    data,file_type=pmag.magic_read(in_file)
    sids=pmag.get_specs(data)
    pmagplotlib.plot_init(FIG['exp'],6,6)
    print len(data),' records read from ',in_file
    #
    #
    # find desired intensity data
    #
    # get plotlist
    #
    plotlist,intlist=[],['measurement_magnitude','measurement_magn_moment','measurement_magn_volume','measurement_magn_mass']
    IntMeths=[]
    for  rec in data:
        meths=[]
        methcodes=rec['magic_method_codes'].split(':')
        for meth in methcodes:meths.append(meth.strip())
        for key in rec.keys():
            if key in intlist and rec[key]!="":
                if key not in IntMeths:IntMeths.append(key)
                if rec[plot_key] not in plotlist and LP in meths: plotlist.append(rec[plot_key])
        plotlist.sort()
    if len(IntMeths)==0:
        print 'No intensity information found'
        sys.exit()
    int_key=IntMeths[0] # plot first intensity method found - normalized to initial value anyway - doesn't matter which used
    for plot in plotlist:
        print plot
        for spec in sids:
            INTblock=[]
            for rec in data:
                if 'measurement_flag' not in rec.keys():rec['measurement_flag']='g'
                if rec[plot_key]==plot and int_key in rec.keys() and rec[int_key]!="" and rec['er_specimen_name']==spec:
                    meths=[]
                    methcodes=rec['magic_method_codes'].split(':')
                    for meth in methcodes:
                        LPtest=meth.split('-')
                        if XLP not in LPtest: meths.append(meth.strip())
                    if len(meths)>0 and LP in meths or 'LT-NO' in meths: 
                        title=rec[plot_key]
                        INTblock.append([float(rec[dmag_key]),0,0,float(rec[int_key]),1,rec['measurement_flag']])
            Sdata=INTblock.sort()
            if len(INTblock)>2: pmagplotlib.plotMT(FIG['exp'],INTblock,title,0,units,norm)
        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]=title+'_'+LP+'.svg' 
            pmagplotlib.saveP(FIG,files) 
        pmagplotlib.clearFIG(FIG['exp'])
Пример #8
0
def main():
    """
    NAME
        irmaq_magic.py

    DESCRIPTION
       plots IRM acquisition curves from magic_measurements file

    SYNTAX 
        irmaq_magic [command line options]
    
    INPUT 
       takes magic formatted magic_measurements.txt files
    
    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: magic_measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot, default is by location
        -N ; do not normalize by last point - use original units
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    FIG={} # plot dictionary
    FIG['exp']=1 # exp is figure 1
    dir_path='./'
    units,dmag_key='T','treatment_dc_field'
    XLP=[]
    norm=1
    in_file,plot_key,LP='magic_measurements.txt','er_location_name',"LP-IRM"
    if len(sys.argv)>1:
        if '-h' in sys.argv:
            print main.__doc__
            sys.exit()
        if '-N' in sys.argv:norm=0
        if '-f' in sys.argv:
            ind=sys.argv.index("-f")
            in_file=sys.argv[ind+1]
        if '-WD' in sys.argv:
            ind=sys.argv.index('-WD')
            dir_path=sys.argv[ind+1]
            in_file=dir_path+'/'+in_file
        if '-obj' in sys.argv:
            ind=sys.argv.index('-obj')
            plot_by=sys.argv[ind+1]
            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'
    data,file_type=pmag.magic_read(in_file)
    sids=pmag.get_specs(data)
    pmagplotlib.plot_init(FIG['exp'],6,6)
    #
    #
    # find desired intensity data
    #
    # get plotlist
    #
    plotlist,intlist=[],['measurement_magnitude','measurement_magn_moment','measurement_magn_volume','measurement_magn_mass']
    IntMeths=[]
    data=pmag.get_dictitem(data,'magic_method_codes',LP,'has') # get all the records with this lab protocol
    Ints={}
    NoInts,int_key=1,""
    for key in intlist:
       Ints[key]=pmag.get_dictitem(data,key,'','F') # get all non-blank data for intensity type
       if len(Ints[key])>0:
           NoInts=0 
           if int_key=="":int_key=key
    if NoInts==1:
        print 'No intensity information found'
        sys.exit()
    for  rec in Ints[int_key]:
        if rec[plot_key] not in plotlist: plotlist.append(rec[plot_key])
    plotlist.sort()
    for plot in plotlist:
        print plot
        INTblock=[]
        data=pmag.get_dictitem(Ints[int_key],plot_key,plot,'T') # get data with right intensity info whose plot_key matches plot
        sids=pmag.get_specs(data) # get a list of specimens with appropriate data
        if len(sids)>0: 
            title=data[0][plot_key]
        for s in sids:
            INTblock=[]
            sdata=pmag.get_dictitem(data,'er_specimen_name',s,'T') # get data for each specimen
            for rec in sdata:
                INTblock.append([float(rec[dmag_key]),0,0,float(rec[int_key]),1,'g'])
            pmagplotlib.plotMT(FIG['exp'],INTblock,title,0,units,norm)
        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]=title+'_'+LP+'.svg' 
            pmagplotlib.saveP(FIG,files) 
        pmagplotlib.clearFIG(FIG['exp'])
Пример #9
0
def main():
    """
    NAME
        quick_hyst.py

    DESCRIPTION
        makes plots of hysteresis data

    SYNTAX
        quick_hyst.py [command line options]

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

    SYNTAX 
        microwave_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f MEAS, set magic_measurements input file
        -fsp PRIOR, set pmag_specimen prior interpretations file
        -fcr CRIT, set criteria file for grading.  
        -fmt [svg,png,jpg], format for images - default is svg
        -sav,  saves plots with out review (default format)
        -spc SPEC, plots single specimen SPEC, saves plot with specified format
            with optional -b bounds adn quits
        -b BEG END: sets  bounds for calculation
           BEG: starting step for slope calculation
           END: ending step for slope calculation
        
    DEFAULTS
        MEAS: magic_measurements.txt
        CRIT: NONE
        PRIOR: microwave_specimens.txt
  
    OUTPUT 
        figures:
            ALL:  numbers refer to temperature steps in command line window
            1) Arai plot:  closed circles are zero-field first/infield
                           open circles are infield first/zero-field
                           triangles are pTRM checks
                           squares are pTRM tail checks
                           VDS is vector difference sum
                           diamonds are bounds for interpretation
            2) Zijderveld plot:  closed (open) symbols are X-Y (X-Z) planes
                                 X rotated to NRM direction
            3) (De/Re)Magnetization diagram:
                           circles are NRM remaining
                           squares are pTRM gained
        command line window:
            list is: temperature step numbers, power (J), Dec, Inc, Int (units of magic_measuements)
                     list of possible commands: type letter followed by return to select option
                     saving of plots creates .svg format files with specimen_name, plot type as name
    """ 
#
#   initializations
#
    meas_file,critout,inspec="magic_measurements.txt","","microwave_specimens.txt"
    inlt=0
    version_num=pmag.get_version()
    Tinit,DCZ,field,first_save=0,0,-1,1
    user,comment="",''
    ans,specimen,recnum,start,end=0,0,0,0,0
    plots,pmag_out,samp_file,style=0,"","","svg"
    fmt='.'+style
#
# default acceptance criteria
#
    accept_keys=['specimen_int_ptrm_n','specimen_md','specimen_fvds','specimen_b_beta','specimen_dang','specimen_drats','specimen_Z']
    accept={}
    accept['specimen_int_ptrm_n']=2
    accept['specimen_md']=10
    accept['specimen_fvds']=0.35
    accept['specimen_b_beta']=.1
    accept['specimen_int_mad']=7
    accept['specimen_dang']=10
    accept['specimen_drats']=10
    accept['specimen_Z']=10
#
# parse command line options
#
    spc,BEG,END="","",""
    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]
    if '-fsp' in sys.argv:
        ind=sys.argv.index('-fsp')
        inspec=sys.argv[ind+1]
    if '-fcr' in sys.argv:
        ind=sys.argv.index('-fcr')
        critout=sys.argv[ind+1]
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt='.'+sys.argv[ind+1]
    if '-spc' in sys.argv:
        ind=sys.argv.index('-spc')
        spc=sys.argv[ind+1]
        if '-b' in sys.argv:
            ind=sys.argv.index('-b')
            BEG=int(sys.argv[ind+1])
            END=int(sys.argv[ind+2])
    if critout!="":
        crit_data,file_type=pmag.magic_read(critout)
        if pmagplotlib.verbose:
            print "Acceptance criteria read in from ", critout
        accept={}
        accept['specimen_int_ptrm_n']=2.0
        for critrec in crit_data:
            if critrec["pmag_criteria_code"]=="IE-SPEC": 
                for key in accept_keys:
                    if key not in critrec.keys():
                        accept[key]=-1
                    else:
                        accept[key]=float(critrec[key])
    try:
        open(inspec,'rU')
        PriorRecs,file_type=pmag.magic_read(inspec)
        if file_type != 'pmag_specimens':
            print file_type
            print file_type,inspec," is not a valid pmag_specimens file " 
            sys.exit()
        for rec in PriorRecs:
            if 'magic_software_packages' not in rec.keys():rec['magic_software_packages']=""
    except IOError:
        PriorRecs=[]
        if pmagplotlib.verbose:print "starting new specimen interpretation file: ",inspec
    meas_data,file_type=pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print file_type
        print file_type,"This is not a valid magic_measurements file " 
        sys.exit()
    backup=0
    # define figure numbers for arai, zijderveld and 
    #   de-,re-magization diagrams
    AZD={}
    AZD['deremag'], AZD['zijd'],AZD['arai'],AZD['eqarea']=1,2,3,4
    pmagplotlib.plot_init(AZD['arai'],4,4)
    pmagplotlib.plot_init(AZD['zijd'],4,4)
    pmagplotlib.plot_init(AZD['deremag'],4,4)
    pmagplotlib.plot_init(AZD['eqarea'],4,4)
    #
    #
    #
    # get list of unique specimen names
    #
    CurrRec=[]
    sids=pmag.get_specs(meas_data)
    # get plots for specimen s - default is just to step through arai diagrams
    #
    if spc!="": specimen =sids.index(spc)
    while specimen < len(sids):
        methcodes=[]
        if pmagplotlib.verbose and spc!="":
            print sids[specimen],specimen+1, 'of ', len(sids)
        MeasRecs=[]
        s=sids[specimen]
        datablock,trmblock=[],[]
        PmagSpecRec={}
        PmagSpecRec["er_analyst_mail_names"]=user
        PmagSpecRec["specimen_correction"]='u'
    #
    # find the data from the meas_data file for this specimen
    #
        for rec in meas_data:
            if rec["er_specimen_name"]==s:
                MeasRecs.append(rec)
                methods=rec["magic_method_codes"].split(":")
                meths=[]
                for meth in methods:
                    meths.append(meth.strip()) # take off annoying spaces
                methods=""
                for meth in meths:
                    if meth.strip() not in methcodes and "LP-" in meth:methcodes.append(meth.strip())
                    methods=methods+meth+":"
                methods=methods[:-1]
                rec["magic_method_codes"]=methods 
                if "LP-PI-M" in meths: datablock.append(rec)
                if "LP-MRM" in meths: trmblock.append(rec)
        if len(trmblock)>2 and inspec!="":
            if Tinit==0:
                Tinit=1
                AZD['MRM']=4
                pmagplotlib.plot_init(AZD['MRM'],4,4)
            elif Tinit==1:
                pmagplotlib.clearFIG(AZD['MRM'])
        if len(datablock) <4:
           if backup==0:
               specimen+=1
               if pmagplotlib.verbose:
                   print 'skipping specimen - moving forward ', s
           else:
               specimen-=1
               if pmagplotlib.verbose:
                   print 'skipping specimen - moving backward ', s
    #
    #  collect info for the PmagSpecRec dictionary
    #
        else:
           rec=datablock[0]
           PmagSpecRec["er_citation_names"]="This study"
           PmagSpecRec["er_specimen_name"]=s
           PmagSpecRec["er_sample_name"]=rec["er_sample_name"]
           PmagSpecRec["er_site_name"]=rec["er_site_name"]
           PmagSpecRec["er_location_name"]=rec["er_location_name"]
           if "magic_instrument_codes" not in rec.keys():rec["magic_instrument_codes"]=""
           PmagSpecRec["magic_instrument_codes"]=rec["magic_instrument_codes"]
           PmagSpecRec["measurement_step_unit"]="J"
           if "magic_experiment_name" not in rec.keys():
               rec["magic_experiment_name"]=""
           else:
               PmagSpecRec["magic_experiment_names"]=rec["magic_experiment_name"]
    
           meths=rec["magic_method_codes"].split(':')
       # sort data into types
           if "LP-PI-M-D" in meths: # this is a double heating experiment
               exp_type="LP-PI-M-D"
           elif "LP-PI-M-S" in meths:
               exp_type="LP-PI-M-S"
           else:
               print "experiment type not supported yet "
               break
           araiblock,field=pmag.sortmwarai(datablock,exp_type)
           first_Z=araiblock[0]
           first_I=araiblock[1]
           GammaChecks=araiblock[-3]
           ThetaChecks=araiblock[-2]
           DeltaChecks=araiblock[-1]
           if len(first_Z)<3:
               if backup==0:
                   specimen+=1
                   if pmagplotlib.verbose:
                       print 'skipping specimen - moving forward ', s
               else:
                   specimen-=1
                   if pmagplotlib.verbose:
                       print 'skipping specimen - moving backward ', s
           else:
               backup=0
               zijdblock,units=pmag.find_dmag_rec(s,meas_data)
               if exp_type=="LP-PI-M-D":
                   recnum=0
                   print "ZStep Watts  Dec Inc  Int"
                   for plotrec in zijdblock:
                       if pmagplotlib.verbose:
                           print '%i  %i %7.1f %7.1f %8.3e ' % (recnum,plotrec[0],plotrec[1],plotrec[2],plotrec[3])
                           recnum += 1
                   recnum = 1
                   if GammaChecks!="":
                       print "IStep Watts  Gamma"
                       for gamma in GammaChecks:
                           if pmagplotlib.verbose: print '%i %i %7.1f ' % (recnum, gamma[0],gamma[1])
                           recnum += 1
               if exp_type=="LP-PI-M-S":
                   if pmagplotlib.verbose:
                       print "IStep Watts  Theta"
                       kk=0
                       for theta in ThetaChecks:
                           kk+=1
                           print '%i  %i %7.1f ' % (kk,theta[0],theta[1])
                   if pmagplotlib.verbose:
                       print "Watts  Delta"
                       for delta in DeltaChecks:
                           print '%i %7.1f ' % (delta[0],delta[1])
               pmagplotlib.plotAZ(AZD,araiblock,zijdblock,s,units[0])
               if inspec !="":
                   if pmagplotlib.verbose: print 'Looking up saved interpretation....'
                   found = 0
                   for k in range(len(PriorRecs)):
                       try:
                         if PriorRecs[k]["er_specimen_name"]==s:
                           found =1
                           CurrRec.append(PriorRecs[k])
                           for j in range(len(araiblock[0])):
                               if float(araiblock[0][j][0])==float(PriorRecs[k]["measurement_step_min"]):start=j
                               if float(araiblock[0][j][0])==float(PriorRecs[k]["measurement_step_max"]):end=j
                           pars,errcode=pmag.PintPars(araiblock,zijdblock,start,end)
                           pars['measurement_step_unit']="J"
                           del PriorRecs[k]  # put in CurrRec, take out of PriorRecs
                           if errcode!=1:
                               pars["specimen_lab_field_dc"]=field
                               pars["specimen_int"]=-1*field*pars["specimen_b"]
                               pars["er_specimen_name"]=s
                               if pmagplotlib.verbose:
                                   print 'Saved interpretation: '
                               pars=pmag.scoreit(pars,PmagSpecRec,accept,'',0)
                               pmagplotlib.plotB(AZD,araiblock,zijdblock,pars)
                               if len(trmblock)>2:
                                   blab=field
                                   best=pars["specimen_int"]
                                   Bs,TRMs=[],[]
                                   for trec in trmblock:
                                       Bs.append(float(trec['treatment_dc_field']))
                                       TRMs.append(float(trec['measurement_magn_moment']))
                                   NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc
                                   Mp,Bp=[],[]
                                   for k in  range(int(max(Bs)*1e6)):
                                       Bp.append(float(k)*1e-6)
                                       npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field
                                       Mp.append(npred)
                                   pmagplotlib.plotTRM(AZD['MRM'],Bs,TRMs,Bp,Mp,NLpars,trec['magic_experiment_name'])
                                   print npred
                                   print 'Banc= ',float(NLpars['banc'])*1e6
                                   if pmagplotlib.verbose:
                                       print 'Banc= ',float(NLpars['banc'])*1e6
                                   pmagplotlib.drawFIGS(AZD)
                           else:
                               print 'error on specimen ',s
                       except:
                         pass
                   if pmagplotlib.verbose and found==0: print  '    None found :(  ' 
               if spc!="":
                   if BEG!="":
                       pars,errcode=pmag.PintPars(araiblock,zijdblock,BEG,END)
                       pars['measurement_step_unit']="J"
                       pars["specimen_lab_field_dc"]=field
                       pars["specimen_int"]=-1*field*pars["specimen_b"]
                       pars["er_specimen_name"]=s
                       pars['specimen_grade']='' # ungraded
                       pmagplotlib.plotB(AZD,araiblock,zijdblock,pars)
                       if len(trmblock)>2:
                           if inlt==0:
                               donlt()
                               inlt=1
                           blab=field
                           best=pars["specimen_int"]
                           Bs,TRMs=[],[]
                           for trec in trmblock:
                               Bs.append(float(trec['treatment_dc_field']))
                               TRMs.append(float(trec['measurement_magn_moment']))
                           NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc
    #
                           Mp,Bp=[],[]
                           for k in  range(int(max(Bs)*1e6)):
                               Bp.append(float(k)*1e-6)
                               npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field
                   files={}
                   for key in AZD.keys():
                       files[key]=s+'_'+key+fmt 
                   pmagplotlib.saveP(AZD,files)
                   sys.exit()
               if plots==0:
                   ans='b'
                   while ans != "":
                       print """
               s[a]ve plot, set [b]ounds for calculation, [d]elete current interpretation, [p]revious, [s]ample, [q]uit:
               """
                       ans=raw_input('Return for next specimen \n')
                       if ans=="": 
                           specimen +=1
                       if ans=="d": 
                           save_redo(PriorRecs,inspec)
                           CurrRec=[]
                           pmagplotlib.plotAZ(AZD,araiblock,zijdblock,s,units[0])
                           pmagplotlib.drawFIGS(AZD)
                       if ans=='a':
                           files={}
                           for key in AZD.keys():
                               files[key]=s+'_'+key+fmt 
                           pmagplotlib.saveP(AZD,files)
                           ans=""
                       if ans=='q':
                           print "Good bye"
                           sys.exit()
                       if ans=='p':
                           specimen =specimen -1
                           backup = 1
                           ans=""
                       if ans=='s':
                           keepon=1
                           spec=raw_input('Enter desired specimen name (or first part there of): ')
                           while keepon==1:
                               try:
                                   specimen =sids.index(spec)
                                   keepon=0
                               except:
                                   tmplist=[]
                                   for qq in range(len(sids)):
                                       if spec in sids[qq]:tmplist.append(sids[qq])
                                   print specimen," not found, but this was: "
                                   print tmplist
                                   spec=raw_input('Select one or try again\n ')
                           ans=""
                       if  ans=='b':
                           if end==0 or end >=len(araiblock[0]):end=len(araiblock[0])-1
                           GoOn=0
                           while GoOn==0:
                               print 'Enter index of first point for calculation: ','[',start,']'
                               answer=raw_input('return to keep default  ')
                               if answer != "":start=int(answer)
                               print 'Enter index  of last point for calculation: ','[',end,']'
                               answer=raw_input('return to keep default  ')
                               if answer != "":
                                   end=int(answer)
                               if start >=0 and start <len(araiblock[0])-2 and end >0 and end <len(araiblock[0]) and start<end:
                                   GoOn=1
                               else:
                                   print "Bad endpoints - try again! "
                                   start,end=0,len(araiblock)
                           s=sids[specimen]
                           pars,errcode=pmag.PintPars(araiblock,zijdblock,start,end)
                           pars['measurement_step_unit']="J"
                           pars["specimen_lab_field_dc"]=field
                           pars["specimen_int"]=-1*field*pars["specimen_b"]
                           pars["er_specimen_name"]=s
                           pars=pmag.scoreit(pars,PmagSpecRec,accept,'',0)
                           PmagSpecRec["measurement_step_min"]='%8.3e' % (pars["measurement_step_min"])
                           PmagSpecRec["measurement_step_max"]='%8.3e' % (pars["measurement_step_max"])
                           PmagSpecRec["measurement_step_unit"]="J"
                           PmagSpecRec["specimen_int_n"]='%i'%(pars["specimen_int_n"])
                           PmagSpecRec["specimen_lab_field_dc"]='%8.3e'%(pars["specimen_lab_field_dc"])
                           PmagSpecRec["specimen_int"]='%8.3e '%(pars["specimen_int"])
                           PmagSpecRec["specimen_b"]='%5.3f '%(pars["specimen_b"])
                           PmagSpecRec["specimen_q"]='%5.1f '%(pars["specimen_q"])
                           PmagSpecRec["specimen_f"]='%5.3f '%(pars["specimen_f"])
                           PmagSpecRec["specimen_fvds"]='%5.3f'%(pars["specimen_fvds"])
                           PmagSpecRec["specimen_b_beta"]='%5.3f'%(pars["specimen_b_beta"])
                           PmagSpecRec["specimen_int_mad"]='%7.1f'%(pars["specimen_int_mad"])
                           PmagSpecRec["specimen_Z"]='%7.1f'%(pars["specimen_Z"])
                           if pars["method_codes"]!="":
                               tmpcodes=pars["method_codes"].split(":")
                               for t in tmpcodes:
                                   if t.strip() not in methcodes:methcodes.append(t.strip())
                           PmagSpecRec["specimen_dec"]='%7.1f'%(pars["specimen_dec"])
                           PmagSpecRec["specimen_inc"]='%7.1f'%(pars["specimen_inc"])
                           PmagSpecRec["specimen_tilt_correction"]='-1'
                           PmagSpecRec["specimen_direction_type"]='l'
                           PmagSpecRec["direction_type"]='l' # this is redudant, but helpful - won't be imported
                           PmagSpecRec["specimen_dang"]='%7.1f '%(pars["specimen_dang"])
                           PmagSpecRec["specimen_drats"]='%7.1f '%(pars["specimen_drats"])
                           PmagSpecRec["specimen_int_ptrm_n"]='%i '%(pars["specimen_int_ptrm_n"])
                           PmagSpecRec["specimen_rsc"]='%6.4f '%(pars["specimen_rsc"])
                           PmagSpecRec["specimen_md"]='%i '%(int(pars["specimen_md"]))
                           if PmagSpecRec["specimen_md"]=='-1':PmagSpecRec["specimen_md"]=""
                           PmagSpecRec["specimen_b_sigma"]='%5.3f '%(pars["specimen_b_sigma"])
                           if "IE-TT" not in  methcodes:methcodes.append("IE-TT")
                           methods=""
                           for meth in methcodes:
                               methods=methods+meth+":"
                           PmagSpecRec["magic_method_codes"]=methods[:-1]
                           PmagSpecRec["specimen_description"]=comment
                           PmagSpecRec["magic_software_packages"]=version_num
                           pmagplotlib.plotAZ(AZD,araiblock,zijdblock,s,units[0])
                           pmagplotlib.plotB(AZD,araiblock,zijdblock,pars)
                           if len(trmblock)>2:
                               blab=field
                               best=pars["specimen_int"]
                               Bs,TRMs=[],[]
                               for trec in trmblock:
                                   Bs.append(float(trec['treatment_dc_field']))
                                   TRMs.append(float(trec['measurement_magn_moment']))
                               NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc
                               Mp,Bp=[],[]
                               for k in  range(int(max(Bs)*1e6)):
                                   Bp.append(float(k)*1e-6)
                                   npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field
                                   Mp.append(npred)
                               pmagplotlib.plotTRM(AZD['MRM'],Bs,TRMs,Bp,Mp,NLpars,trec['magic_experiment_name'])
                               print 'Banc= ',float(NLpars['banc'])*1e6
                           pmagplotlib.drawFIGS(AZD)
                           pars["specimen_lab_field_dc"]=field
                           pars["specimen_int"]=-1*field*pars["specimen_b"]
                           saveit=raw_input("Save this interpretation? [y]/n \n")
                           if saveit!='n':
                               specimen+=1
                               PriorRecs.append(PmagSpecRec) # put back an interpretation
                               save_redo(PriorRecs,inspec)
                           ans=""
               else:
                   specimen+=1
                   if fmt != ".pmag":
                       basename=s+'_microwave'+fmt
                       files={}
                       for key in AZD.keys():
                           files[key]=s+'_'+key+fmt 
                       if pmagplotlib.isServer:
                           black     = '#000000'
                           purple    = '#800080'
                           titles={}
                           titles['deremag']='DeReMag Plot'
                           titles['zijd']='Zijderveld Plot'
                           titles['arai']='Arai Plot'
                           AZD = pmagplotlib.addBorders(AZD,titles,black,purple)
                       pmagplotlib.saveP(AZD,files)
    #                   pmagplotlib.combineFigs(s,files,3)
        if len(CurrRec)>0:
            for rec in CurrRec:
                PriorRecs.append(rec)
        CurrRec=[]
    if plots!=1:
        ans=raw_input(" Save last plot? 1/[0] ")
        if ans=="1":
            if fmt != ".pmag":
                files={}
                for key in AZD.keys():
                    files[key]=s+'_'+key+fmt
                pmagplotlib.saveP(AZD,files)
        if len(CurrRec)>0:PriorRecs.append(CurrRec) # put back an interpretation
        if len(PriorRecs)>0:
            save_redo(PriorRecs,inspec)
            print 'Updated interpretations saved in ',inspec
    if pmagplotlib.verbose:
        print "Good bye"