Ejemplo n.º 1
0
def get_data_model():
    """
    try to grab the up to date data model document from the EarthRef site.
    if that fails, try to get the data model document from the PmagPy directory on the user's computer.
    if that fails, return False.
    data_model is a set of nested dictionaries that looks like this:
    {'magic_contributions':
        {'group_userid': {'data_status': 'Optional', 'data_type': 'String(10)'}, 'activate': {'data_status': 'Optional', 'data_type': 'String(1)'}, ....},
    'er_synthetics':
        {'synthetic_type': {'data_status': 'Required', 'data_type': 'String(50)'}, 'er_citation_names': {'data_status': 'Required', 'data_type': 'List(500)'}, ...},
    ....
    }
    the top level keys are the file types.
    the second level keys are the possible headers for that file type.
    the third level keys are data_type and data_status for that header.
    """
    print "-I- getting data model, please be patient"
    url = 'http://earthref.org/services/MagIC-data-model.txt'
    offline = True # always get cached data model, as 2.5 is now static
    try:
        data = urllib2.urlopen(url)
    except urllib2.URLError:
        print '-W- Unable to fetch data model online\nTrying to use cached data model instead'
        offline = True
    except httplib.BadStatusLine:
        print '-W- Website: {} not responding\nTrying to use cached data model instead'.format(url)
        offline = True
    if offline:
        data = get_data_offline()
    data_model, file_type = pmag.magic_read(None, data)
    if file_type in ('bad file', 'empty_file'):
        print '-W- Unable to read online data model.\nTrying to use cached data model instead'
        data = get_data_offline()
        data_model, file_type = pmag.magic_read(None, data)
    ref_dicts = [d for d in data_model if d['column_nmb'] != '>>>>>>>>>>']
    file_types = [d['field_name'] for d in data_model if d['column_nmb'] == 'tab delimited']
    file_types.insert(0, file_type)
    complete_ref = {}

    dictionary = {}
    n = 0
    for d in ref_dicts:
        if d['field_name'] in file_types:
            complete_ref[file_types[n]] = dictionary
            n += 1
            dictionary = {}
        else:
            dictionary[d['field_name_oracle']] = {'data_type': d['data_type'], 'data_status': d['data_status']}
    return complete_ref
Ejemplo n.º 2
0
def get_data_model():
    """
    try to grab the up to date data model document from the EarthRef site.
    if that fails, try to get the data model document from the PmagPy directory on the user's computer.
    if that fails, return False.
    data_model is a set of nested dictionaries that looks like this:
    {'magic_contributions': 
        {'group_userid': {'data_status': 'Optional', 'data_type': 'String(10)'}, 'activate': {'data_status': 'Optional', 'data_type': 'String(1)'}, ....}, 
    'er_synthetics':
        {'synthetic_type': {'data_status': 'Required', 'data_type': 'String(50)'}, 'er_citation_names': {'data_status': 'Required', 'data_type': 'List(500)'}, ...},
    ....
    }
    the top level keys are the file types.  
    the second level keys are the possible headers for that file type.
    the third level keys are data_type and data_status for that header.
    """
    print "-I- getting data model, please be patient"
    url = 'http://earthref.org/services/MagIC-data-model.txt'
    offline = False
    try:
        data = urllib2.urlopen(url)
    except urllib2.URLError:
        print '-W- Unable to fetch data model online\nTrying to use cached data model instead'
        offline = True
    except httplib.BadStatusLine:
        print '-W- Website: {} not responding\nTrying to use cached data model instead'.format(url)
        offline = True
    if offline:
        data = get_data_offline()
    data_model, file_type = pmag.magic_read(None, data)
    if file_type in ('bad file', 'empty_file'):
        print '-W- Unable to read online data model.\nTrying to use cached data model instead'
        data = get_data_offline()
        data_model, file_type = pmag.magic_read(None, data)
    ref_dicts = [d for d in data_model if d['column_nmb'] != '>>>>>>>>>>']
    file_types = [d['field_name'] for d in data_model if d['column_nmb'] == 'tab delimited']
    file_types.insert(0, file_type)
    complete_ref = {}

    dictionary = {}
    n = 0
    for d in ref_dicts:
        if d['field_name'] in file_types:
            complete_ref[file_types[n]] = dictionary
            n += 1
            dictionary = {}
        else:
            dictionary[d['field_name_oracle']] = {'data_type': d['data_type'], 'data_status': d['data_status']}
    return complete_ref
Ejemplo n.º 3
0
def main():
    """
    NAME 
        change_case_magic.py

    DESCRIPTION
        picks out key and converts to upper or lower case

    SYNTAX
        change_case_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file 
        -F FILE: specify output magic format file , default is to overwrite input file
        -keys KEY1:KEY2 specify colon delimited list of keys to convert
        -[U,l] : specify [U]PPER or [l]ower case, default is lower 

    """
    dir_path = "./"
    change = "l"
    if "-WD" in sys.argv:
        ind = sys.argv.index("-WD")
        dir_path = sys.argv[ind + 1]
    if "-h" in sys.argv:
        print main.__doc__
        sys.exit()
    if "-f" in sys.argv:
        ind = sys.argv.index("-f")
        magic_file = dir_path + "/" + sys.argv[ind + 1]
    else:
        print main.__doc__
        sys.exit()
    if "-F" in sys.argv:
        ind = sys.argv.index("-F")
        out_file = dir_path + "/" + sys.argv[ind + 1]
    else:
        out_file = magic_file
    if "-keys" in sys.argv:
        ind = sys.argv.index("-keys")
        grab_keys = sys.argv[ind + 1].split(":")
    else:
        print main.__doc__
        sys.exit()
    if "-U" in sys.argv:
        change = "U"
    #
    #
    # get data read in
    Data, file_type = pmag.magic_read(magic_file)
    if len(Data) > 0:
        for grab_key in grab_keys:
            for rec in Data:
                if change == "l":
                    rec[grab_key] = rec[grab_key].lower()
                else:
                    rec[grab_key] = rec[grab_key].upper()
    else:
        print "bad file name"
    pmag.magic_write(out_file, Data, file_type)
Ejemplo n.º 4
0
    def get_data(self):

        Data = {}
        Data_hierarchy = {}
        Data_hierarchy["locations"] = {}
        Data_hierarchy["sites"] = {}
        Data_hierarchy["samples"] = {}
        Data_hierarchy["specimens"] = {}
        Data_hierarchy["sample_of_specimen"] = {}
        Data_hierarchy["site_of_specimen"] = {}
        Data_hierarchy["site_of_sample"] = {}
        Data_hierarchy["location_of_specimen"] = {}
        Data_hierarchy["location_of_sample"] = {}
        Data_hierarchy["location_of_site"] = {}
        try:
            meas_data, file_type = pmag.magic_read(self.WD + "/magic_measurements.txt")
        except:
            print "-E- ERROR: Cant read magic_measurement.txt file. File is corrupted."
            return {}, {}

        sids = pmag.get_specs(meas_data)  # samples ID's

        for s in sids:
            if s not in Data.keys():
                Data[s] = {}
        for rec in meas_data:
            s = rec["er_specimen_name"]
            sample = rec["er_sample_name"]
            site = rec["er_site_name"]
            location = rec["er_location_name"]
            if sample not in Data_hierarchy["samples"].keys():
                Data_hierarchy["samples"][sample] = []

            if site not in Data_hierarchy["sites"].keys():
                Data_hierarchy["sites"][site] = []

            if location not in Data_hierarchy["locations"].keys():
                Data_hierarchy["locations"][location] = []

            if s not in Data_hierarchy["samples"][sample]:
                Data_hierarchy["samples"][sample].append(s)

            if sample not in Data_hierarchy["sites"][site]:
                Data_hierarchy["sites"][site].append(sample)

            if site not in Data_hierarchy["locations"][location]:
                Data_hierarchy["locations"][location].append(site)

            Data_hierarchy["specimens"][s] = sample
            Data_hierarchy["sample_of_specimen"][s] = sample
            Data_hierarchy["site_of_specimen"][s] = site
            Data_hierarchy["site_of_sample"][sample] = site
            Data_hierarchy["location_of_specimen"][s] = location
            Data_hierarchy["location_of_sample"][sample] = location
            Data_hierarchy["location_of_site"][site] = location

        return (Data, Data_hierarchy)
Ejemplo n.º 5
0
def main():
    """
    NAME
        extract_methods.py
 
    DESCRIPTION
        reads in a magic table and creates a file with method codes

    SYNTAX
        extract_methods.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -f FILE: specify magic format input file, default is magic_measurements.txt
        -F FILE: specify method code output file, default is magic_methods.txt
    """
    citation='This study'
    args=sys.argv
    outfile='magic_methods.txt'
    infile='magic_measurements.txt'
#
# get command line arguments
#
    dir_path='.'
    if '-WD' in args:
        ind=args.index("-WD")
        dir_path=args[ind+1]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if '-F' in args:
        ind=args.index("-F")
        outfile=args[ind+1]
    if '-f' in args:
        ind=args.index("-f")
        infile=args[ind+1]
    infile=dir_path+'/'+infile
    outfile=dir_path+'/'+outfile
    data,file_type=pmag.magic_read(infile)
    MethRecs=[]
    methods=[]
    for rec in data:
        meths=rec['magic_method_codes'].split(":")
        for meth in meths:
            if meth not in methods:
                MethRec={}
                methods.append(meth)
                MethRec['magic_method_code']=meth
                MethRecs.append(MethRec)
    pmag.magic_write(outfile,MethRecs,'magic_methods')
Ejemplo n.º 6
0
def main():
    """
    NAME 
        grab_magic_key.py

    DESCRIPTION
        picks out key and saves to file

    SYNTAX
        grab_magic_key.py [command line optins]

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file 
        -key KEY: specify key to print to standard output 

    """
    dir_path="./"
    if '-WD' in sys.argv: 
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        magic_file=dir_path+'/'+sys.argv[ind+1]
    else:
        print main.__doc__
        sys.exit()
    if '-key' in sys.argv:
        ind=sys.argv.index('-key')
        grab_key=sys.argv[ind+1]
    else:
        print main.__doc__
        sys.exit()
    #
    #
    # get data read in
    Data,file_type=pmag.magic_read(magic_file) 
    if len(Data)>0:
        for rec in Data: print rec[grab_key]
    else:
        print 'bad file name'
Ejemplo n.º 7
0
def main():
    """ 
    ODP_fix_sample_names.py
    DESCRIPTION:
        pads core to three digits and makes upper case
    OPTIONS:
        -f FILE, input ODP magic file for sample name conversion 
    """
    dir_path='.'
    if '-WD' in sys.argv:
        ind=sys.argv.index("-WD")
        dir_path=sys.argv[ind+1]
    if '-f' in sys.argv:
        ind=sys.argv.index("-f")
        infile=dir_path+'/'+sys.argv[ind+1]
    else:
        print "must specify -f input_file"
        sys.exit()
    Data,file_type=pmag.magic_read(infile)
    Fixed=[]
    for rec in Data:    
        pieces=rec['er_specimen_name'].split('-')
        if len(pieces)==6:
            while len(pieces[2])<4:pieces[2]='0'+pieces[2] # pad core to be 3 characters
            specimen=""
            for piece in pieces:
                specimen=specimen+piece+'-'
            specimen=specimen[:-1].upper()
            rec['er_specimen_name']=specimen 
            rec['er_sample_name']=specimen 
            rec['er_site_name']=specimen 
            rec['er_location_name']=pieces[1] 
            rec['er_expedition_name']=pieces[0] 
            Fixed.append(rec)
        else:
                print 'problem with this data record: ',rec['er_specimen_name']
                print 'deleting from file ', infile
    pmag.magic_write(infile,Fixed,file_type)
    print 'new specimen names written to: ',infile 
Ejemplo n.º 8
0
 def get_Data(magic_file):
 
     #------------------------------------------------
     # Read magic measurement file and sort to blocks
     #------------------------------------------------
     Data={}
     try:
         meas_data,file_type=pmag.magic_read(magic_file)
     except:
         print "-E- ERROR: Cant read magic_measurement.txt file. File is corrupted."
         return Data
         
     # get list of unique specimen names
     
     #sids=pmag.get_specs(meas_data) # samples ID's
     
     for rec in meas_data:
         s=rec["er_specimen_name"]
         method_codes= rec["magic_method_codes"].strip('\n')
         method_codes.replace(" ","")
         methods=method_codes.split(":")
         if "LP-AN-TRM" in methods:
             if s not in Data.keys():
                 Data[s]={}
             if 'atrmblock' not in Data[s].keys():
                 Data[s]['atrmblock']=[]
             Data[s]['atrmblock'].append(rec)
         
         
         if "LP-AN-ARM" in methods:
             if s not in Data.keys():
                 Data[s]={}
             if 'aarmblock' not in Data[s].keys():
                 Data[s]['aarmblock']=[]
             Data[s]['aarmblock'].append(rec)
     return (Data)        
Ejemplo n.º 9
0
def main():
    """
    NAME
        eqarea_magic.py

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX 
        eqarea_magic.py [command line options]
    
    INPUT 
       takes magic formatted pmag_results, pmag_sites, pmag_samples or pmag_specimens
    
    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file from magic,default='pmag_results.txt'
         supported types=[magic_measurements,pmag_specimens, pmag_samples, pmag_sites, pmag_results, magic_web]
        -obj OBJ: specify  level of plot  [all, sit, sam, spc], default is all
        -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted
                default is geographic, unspecified assumed geographic
        -fmt [svg,png,jpg] format for output plots
        -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors
        -c plot as colour contour 
        -sav save plot and quit quietly
    NOTE
        all: entire file; sit: site; sam: sample; spc: specimen
    """
    FIG = {} # plot dictionary
    FIG['eqarea'] = 1 # eqarea is figure 1
    in_file, plot_key, coord, crd = 'pmag_results.txt', 'all', "0", 'g'
    plotE, contour = 0, 0
    dir_path = '.'
    fmt = 'svg'
    verbose = pmagplotlib.verbose
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path = sys.argv[ind + 1]
    pmagplotlib.plot_init(FIG['eqarea'], 5, 5)
    if '-f' in sys.argv:
        ind = sys.argv.index("-f")
        in_file = dir_path + "/" + sys.argv[ind + 1]
    if '-obj' in sys.argv:
        ind = sys.argv.index('-obj')
        plot_by = sys.argv[ind + 1]
        if plot_by == 'all': plot_key = 'all'
        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 '-c' in sys.argv: contour = 1
    plots = 0
    if '-sav' in sys.argv:
        plots = 1
        verbose = 0
    if '-ell' in sys.argv:
        plotE = 1
        ind = sys.argv.index('-ell')
        ell_type = sys.argv[ind + 1]
        if ell_type == 'F': dist = 'F'
        if ell_type == 'K': dist = 'K'
        if ell_type == 'B': dist = 'B'
        if ell_type == 'Be': dist = 'BE'
        if ell_type == 'Bv':
            dist = 'BV'
            FIG['bdirs'] = 2
            pmagplotlib.plot_init(FIG['bdirs'], 5, 5)
    if '-crd' in sys.argv:
        ind = sys.argv.index("-crd")
        crd = sys.argv[ind + 1]
        if crd == 's': coord = "-1"
        if crd == 'g': coord = "0"
        if crd == 't': coord = "100"
    if '-fmt' in sys.argv:
        ind = sys.argv.index("-fmt")
        fmt = sys.argv[ind + 1]
    Dec_keys = ['site_dec', 'sample_dec', 'specimen_dec', 'measurement_dec', 'average_dec', 'none']
    Inc_keys = ['site_inc', 'sample_inc', 'specimen_inc', 'measurement_inc', 'average_inc', 'none']
    Tilt_keys = ['tilt_correction', 'site_tilt_correction', 'sample_tilt_correction', 'specimen_tilt_correction',
                 'none']
    Dir_type_keys = ['', 'site_direction_type', 'sample_direction_type', 'specimen_direction_type']
    Name_keys = ['er_specimen_name', 'er_sample_name', 'er_site_name', 'pmag_result_name']
    data, file_type = pmag.magic_read(in_file)
    if file_type == 'pmag_results' and plot_key != "all": plot_key = plot_key + 's' # need plural for results table
    if verbose:
        print len(data), ' records read from ', in_file
        #
    #
    # find desired dec,inc data:
    #
    dir_type_key = ''
    #
    # get plotlist if not plotting all records
    #
    plotlist = []
    if plot_key != "all":
        plots = pmag.get_dictitem(data, plot_key, '', 'F')
        for rec in plots:
            if rec[plot_key] not in plotlist:
                plotlist.append(rec[plot_key])
        plotlist.sort()
    else:
        plotlist.append('All')
    for plot in plotlist:
        if verbose: print plot
        DIblock = []
        GCblock = []
        SLblock, SPblock = [], []
        title = plot
        mode = 1
        dec_key, inc_key, tilt_key, name_key, k = "", "", "", "", 0
        if plot != "All":
            odata = pmag.get_dictitem(data, plot_key, plot, 'T')
        else:
            odata = data # data for this obj
        for dec_key in Dec_keys:
            Decs = pmag.get_dictitem(odata, dec_key, '', 'F') # get all records with this dec_key not blank
            if len(Decs) > 0: break
        for inc_key in Inc_keys:
            Incs = pmag.get_dictitem(Decs, inc_key, '', 'F') # get all records with this inc_key not blank
            if len(Incs) > 0: break
        for tilt_key in Tilt_keys:
            if tilt_key in Incs[0].keys(): break # find the tilt_key for these records
        if tilt_key == 'none': # no tilt key in data, need to fix this with fake data which will be unknown tilt
            tilt_key = 'tilt_correction'
            for rec in Incs: rec[tilt_key] = ''
        cdata = pmag.get_dictitem(Incs, tilt_key, coord, 'T') # get all records matching specified coordinate system
        if coord == '0': # geographic
            udata = pmag.get_dictitem(Incs, tilt_key, '', 'T') # get all the blank records - assume geographic
            if len(cdata) == 0: crd = ''
            if len(udata) > 0:
                for d in udata: cdata.append(d)
                crd = crd + 'u'
        for name_key in Name_keys:
            Names = pmag.get_dictitem(cdata, name_key, '', 'F') # get all records with this name_key not blank
            if len(Names) > 0: break
        for dir_type_key in Dir_type_keys:
            Dirs = pmag.get_dictitem(cdata, dir_type_key, '', 'F') # get all records with this direction type
            if len(Dirs) > 0: break
        if dir_type_key == "": dir_type_key = 'direction_type'
        locations, site, sample, specimen = "", "", "", ""
        for rec in cdata: # pick out the data
            if 'er_location_name' in rec.keys() and rec['er_location_name'] != "" and rec[
                'er_location_name'] not in locations: locations = locations + rec['er_location_name'].replace("/",
                                                                                                              "") + "_"
            if 'er_location_names' in rec.keys() and rec['er_location_names'] != "":
                locs = rec['er_location_names'].split(':')
                for loc in locs:
                    if loc not in locations: locations = locations + loc.replace("/", "") + '_'
            if plot_key == 'er_site_name' or plot_key == 'er_sample_name' or plot_key == 'er_specimen_name':
                site = rec['er_site_name']
            if plot_key == 'er_sample_name' or plot_key == 'er_specimen_name':
                sample = rec['er_sample_name']
            if plot_key == 'er_specimen_name':
                specimen = rec['er_specimen_name']
            if plot_key == 'er_site_names' or plot_key == 'er_sample_names' or plot_key == 'er_specimen_names':
                site = rec['er_site_names']
            if plot_key == 'er_sample_names' or plot_key == 'er_specimen_names':
                sample = rec['er_sample_names']
            if plot_key == 'er_specimen_names':
                specimen = rec['er_specimen_names']
            if dir_type_key not in rec.keys() or rec[dir_type_key] == "": rec[dir_type_key] = 'l'
            if 'magic_method_codes' not in rec.keys(): rec['magic_method_codes'] = ""
            DIblock.append([float(rec[dec_key]), float(rec[inc_key])])
            SLblock.append([rec[name_key], rec['magic_method_codes']])
            if rec[tilt_key] == coord and rec[dir_type_key] != 'l' and rec[dec_key] != "" and rec[inc_key] != "":
                GCblock.append([float(rec[dec_key]), float(rec[inc_key])])
                SPblock.append([rec[name_key], rec['magic_method_codes']])
        if len(DIblock) == 0 and len(GCblock) == 0:
            if verbose: print "no records for plotting"
            sys.exit()
        if verbose:
            for k in range(len(SLblock)):
                print '%s %s %7.1f %7.1f' % (SLblock[k][0], SLblock[k][1], DIblock[k][0], DIblock[k][1])
            for k in range(len(SPblock)):
                print '%s %s %7.1f %7.1f' % (SPblock[k][0], SPblock[k][1], GCblock[k][0], GCblock[k][1])
        if len(DIblock) > 0:
            if contour == 0:
                pmagplotlib.plotEQ(FIG['eqarea'], DIblock, title)
            else:
                pmagplotlib.plotEQcont(FIG['eqarea'], DIblock)
        else:
            pmagplotlib.plotNET(FIG['eqarea'])
        if len(GCblock) > 0:
            for rec in GCblock: pmagplotlib.plotC(FIG['eqarea'], rec, 90., 'g')
        if plotE == 1:
            ppars = pmag.doprinc(DIblock) # get principal directions
            nDIs, rDIs, npars, rpars = [], [], [], []
            for rec in DIblock:
                angle = pmag.angle([rec[0], rec[1]], [ppars['dec'], ppars['inc']])
                if angle > 90.:
                    rDIs.append(rec)
                else:
                    nDIs.append(rec)
            if dist == 'B': # do on whole dataset
                etitle = "Bingham confidence ellipse"
                bpars = pmag.dobingham(DIblock)
                for key in bpars.keys():
                    if key != 'n' and verbose: print "    ", key, '%7.1f' % (bpars[key])
                    if key == 'n' and verbose: print "    ", key, '       %i' % (bpars[key])
                npars.append(bpars['dec'])
                npars.append(bpars['inc'])
                npars.append(bpars['Zeta'])
                npars.append(bpars['Zdec'])
                npars.append(bpars['Zinc'])
                npars.append(bpars['Eta'])
                npars.append(bpars['Edec'])
                npars.append(bpars['Einc'])
            if dist == 'F':
                etitle = "Fisher confidence cone"
                if len(nDIs) > 2:
                    fpars = pmag.fisher_mean(nDIs)
                    for key in fpars.keys():
                        if key != 'n' and verbose: print "    ", key, '%7.1f' % (fpars[key])
                        if key == 'n' and verbose: print "    ", key, '       %i' % (fpars[key])
                    mode += 1
                    npars.append(fpars['dec'])
                    npars.append(fpars['inc'])
                    npars.append(fpars['alpha95']) # Beta
                    npars.append(fpars['dec'])
                    isign = abs(fpars['inc']) / fpars['inc']
                    npars.append(fpars['inc'] - isign * 90.) #Beta inc
                    npars.append(fpars['alpha95']) # gamma 
                    npars.append(fpars['dec'] + 90.) # Beta dec
                    npars.append(0.) #Beta inc
                if len(rDIs) > 2:
                    fpars = pmag.fisher_mean(rDIs)
                    if verbose: print "mode ", mode
                    for key in fpars.keys():
                        if key != 'n' and verbose: print "    ", key, '%7.1f' % (fpars[key])
                        if key == 'n' and verbose: print "    ", key, '       %i' % (fpars[key])
                    mode += 1
                    rpars.append(fpars['dec'])
                    rpars.append(fpars['inc'])
                    rpars.append(fpars['alpha95']) # Beta
                    rpars.append(fpars['dec'])
                    isign = abs(fpars['inc']) / fpars['inc']
                    rpars.append(fpars['inc'] - isign * 90.) #Beta inc
                    rpars.append(fpars['alpha95']) # gamma 
                    rpars.append(fpars['dec'] + 90.) # Beta dec
                    rpars.append(0.) #Beta inc
            if dist == 'K':
                etitle = "Kent confidence ellipse"
                if len(nDIs) > 3:
                    kpars = pmag.dokent(nDIs, len(nDIs))
                    if verbose: print "mode ", mode
                    for key in kpars.keys():
                        if key != 'n' and verbose: print "    ", key, '%7.1f' % (kpars[key])
                        if key == 'n' and verbose: print "    ", key, '       %i' % (kpars[key])
                    mode += 1
                    npars.append(kpars['dec'])
                    npars.append(kpars['inc'])
                    npars.append(kpars['Zeta'])
                    npars.append(kpars['Zdec'])
                    npars.append(kpars['Zinc'])
                    npars.append(kpars['Eta'])
                    npars.append(kpars['Edec'])
                    npars.append(kpars['Einc'])
                if len(rDIs) > 3:
                    kpars = pmag.dokent(rDIs, len(rDIs))
                    if verbose: print "mode ", mode
                    for key in kpars.keys():
                        if key != 'n' and verbose: print "    ", key, '%7.1f' % (kpars[key])
                        if key == 'n' and verbose: print "    ", key, '       %i' % (kpars[key])
                    mode += 1
                    rpars.append(kpars['dec'])
                    rpars.append(kpars['inc'])
                    rpars.append(kpars['Zeta'])
                    rpars.append(kpars['Zdec'])
                    rpars.append(kpars['Zinc'])
                    rpars.append(kpars['Eta'])
                    rpars.append(kpars['Edec'])
                    rpars.append(kpars['Einc'])
            else: # assume bootstrap
                if dist == 'BE':
                    if len(nDIs) > 5:
                        BnDIs = pmag.di_boot(nDIs)
                        Bkpars = pmag.dokent(BnDIs, 1.)
                        if verbose: print "mode ", mode
                        for key in Bkpars.keys():
                            if key != 'n' and verbose: print "    ", key, '%7.1f' % (Bkpars[key])
                            if key == 'n' and verbose: print "    ", key, '       %i' % (Bkpars[key])
                        mode += 1
                        npars.append(Bkpars['dec'])
                        npars.append(Bkpars['inc'])
                        npars.append(Bkpars['Zeta'])
                        npars.append(Bkpars['Zdec'])
                        npars.append(Bkpars['Zinc'])
                        npars.append(Bkpars['Eta'])
                        npars.append(Bkpars['Edec'])
                        npars.append(Bkpars['Einc'])
                    if len(rDIs) > 5:
                        BrDIs = pmag.di_boot(rDIs)
                        Bkpars = pmag.dokent(BrDIs, 1.)
                        if verbose: print "mode ", mode
                        for key in Bkpars.keys():
                            if key != 'n' and verbose: print "    ", key, '%7.1f' % (Bkpars[key])
                            if key == 'n' and verbose: print "    ", key, '       %i' % (Bkpars[key])
                        mode += 1
                        rpars.append(Bkpars['dec'])
                        rpars.append(Bkpars['inc'])
                        rpars.append(Bkpars['Zeta'])
                        rpars.append(Bkpars['Zdec'])
                        rpars.append(Bkpars['Zinc'])
                        rpars.append(Bkpars['Eta'])
                        rpars.append(Bkpars['Edec'])
                        rpars.append(Bkpars['Einc'])
                    etitle = "Bootstrapped confidence ellipse"
                elif dist == 'BV':
                    sym = {'lower': ['o', 'c'], 'upper': ['o', 'g'], 'size': 3, 'edgecolor': 'face'}
                    if len(nDIs) > 5:
                        BnDIs = pmag.di_boot(nDIs)
                        pmagplotlib.plotEQsym(FIG['bdirs'], BnDIs, 'Bootstrapped Eigenvectors', sym)
                    if len(rDIs) > 5:
                        BrDIs = pmag.di_boot(rDIs)
                        if len(nDIs) > 5:  # plot on existing plots
                            pmagplotlib.plotDIsym(FIG['bdirs'], BrDIs, sym)
                        else:
                            pmagplotlib.plotEQ(FIG['bdirs'], BrDIs, 'Bootstrapped Eigenvectors')
            if dist == 'B':
                if len(nDIs) > 3 or len(rDIs) > 3: pmagplotlib.plotCONF(FIG['eqarea'], etitle, [], npars, 0)
            elif len(nDIs) > 3 and dist != 'BV':
                pmagplotlib.plotCONF(FIG['eqarea'], etitle, [], npars, 0)
                if len(rDIs) > 3:
                    pmagplotlib.plotCONF(FIG['eqarea'], etitle, [], rpars, 0)
            elif len(rDIs) > 3 and dist != 'BV':
                pmagplotlib.plotCONF(FIG['eqarea'], etitle, [], rpars, 0)
        if verbose: pmagplotlib.drawFIGS(FIG)
        #
        files = {}
        locations = locations[:-1]
        for key in FIG.keys():
            filename = 'LO:_' + locations + '_SI:_' + site + '_SA:_' + sample + '_SP:_' + specimen + '_CO:_' + crd + '_TY:_' + key + '_.' + fmt
            files[key] = filename
        if pmagplotlib.isServer:
            black = '#000000'
            purple = '#800080'
            titles = {}
            titles['eq'] = 'Equal Area Plot'
            FIG = pmagplotlib.addBorders(FIG, titles, black, purple)
            pmagplotlib.saveP(FIG, files)
        elif verbose:
            ans = raw_input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
            if ans == "q": sys.exit()
            if ans == "a":
                pmagplotlib.saveP(FIG, files)
        if plots:
            pmagplotlib.saveP(FIG, files)
Ejemplo n.º 10
0
def main():
    """
    NAME
        pick_AC_specimens.py
    
    DESCRIPTION
        finds whether anisotropy correction yeilds more tightly 
        grouped intensities  than uncorrected data. 
        picks either all corrected or all uncorrected data and 
        puts in pmag_specimen format file
    
    SYNTAX
        pick_AC_specimens.py [-h][-i][-fu TFILE][-fc AFILE][-F FILE]

    OPTIONS
        -h prints help message and quits
        -i allows interactive setting of file names
        -fu TFILE uncorrected pmag_specimen format file with thellier interpretations
            created by thellier_magic_redo.py
        -fc AFILE anisotropy corrected pmag_specimen format file
            created by thellier_magic_redo.py
        -fcr CRIT pmag_criteria.txt format file with acceptance criteria
        -opt SIG use the optimizer_thelpars.txt file for criteria
        -F FILE pmag_specimens format output file with "best" set of data

    DEFAULTS
        TFILE: thellier_specimens.txt
        AFILE: AC_specimens.txt
        FILE: pmag_specimens.txt
    """
    tspec="thellier_specimens.txt"
    aspec="AC_specimens.txt"
    ofile="pmag_specimens.txt"
    critfile="pmag_criteria.txt"
    ACSamplist,Samplist,sigmin=[],[],10000
    GoodSamps,SpecOuts=[],[]
    P={'cdf':1}
    pmagplotlib.plot_init(P['cdf'],5,5)
# get arguments from command line
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-fu' in sys.argv:
        ind=sys.argv.index('-fu')
        tspec=sys.argv[ind+1]
    if '-fc' in sys.argv:
        ind=sys.argv.index('-fc')
        aspec=sys.argv[ind+1]
    if '-fcr' in sys.argv:
        ind=sys.argv.index('-fcr')
        critfile=sys.argv[ind+1]
    if '-opt' in sys.argv:
        ind=sys.argv.index('-opt')
        critfile='optimum_thelpars.txt'
        sigcutoff=sys.argv[ind+1]
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        ofile=sys.argv[ind+1]
    if '-i' in sys.argv:
        file=raw_input(" thellier_specimnens.txt file [thellier_specimens.txt]: ")
        if file!="":tfile=file 
        file=raw_input(" AC_specimnens.txt file [AC_specimens.txt]: ")
        if file!="":afile=file 
        file=raw_input(" pmag_specimnens.txt file [pmag_specimens.txt]: ")
        if file!="":ofile=file 
    # read in pmag_specimens file
    Specs,file_type=pmag.magic_read(tspec)
    Speclist=pmag.get_specs(Specs)
    ACSpecs,file_type=pmag.magic_read(aspec)
    ACspeclist=pmag.get_specs(ACSpecs)
    Crits,file_type=pmag.magic_read(critfile)
    keys=['specimen_int_mad','specimen_drats','specimen_fvds','specimen_b_beta','specimen_Z','specimen_md','specimen_dang']
    accept={}
    for crit in Crits:
        if critfile!='optimum_thelpars.txt':
            if crit['pmag_criteria_code']=='IE-SPEC':
                for key in keys: accept[key]=float(crit[key]) # assign acceptance criteria
                break
        else:
            if float(crit['sample_int_sigma_perc'])==float(sigcutoff):
                for key in keys: accept[key]=float(crit[key])
    Diff=[]
    for aspec in ACSpecs:
            grade,kill=pmag.grade(aspec,accept)
            if grade==len(accept): 
                print 'AC: ',aspec["er_specimen_name"],'%i'%(1e6*float(aspec["specimen_int"]))
                aint=(1e6*float(aspec["specimen_int"]))
                for spec in Specs:
                    if spec["er_specimen_name"]==aspec['er_specimen_name']:
                        print 'UC: ',spec["er_specimen_name"],'%i'%(1e6*float(spec["specimen_int"]))
                        int=(1e6*float(spec["specimen_int"]))
                        Diff.append(100.*abs(aint-int)/aint)
    x,s=pmag.gausspars(Diff)
    print x,s
    Diff.sort()
    print Diff[0],Diff[-1]
    pmagplotlib.plotCDF(P['cdf'],Diff,'% Difference','r')
    pmagplotlib.drawFIGS(P)
    raw_input()
Ejemplo n.º 11
0
def main():
    """
    NAME 
        magic_select.py

    DESCRIPTION
        picks out records and dictitem options saves to magic_special file

    SYNTAX
        magic_select.py [command line optins]

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file 
        -F FILE: specify output magic format file 
        -key KEY string [T,F,has, not, eval,min,max]
           returns records where the value of the key either:
               matches exactly the string (T)
               does not match the string (F)
               contains the string (has)
               does not contain the string (not)
               the value equals the numerical value of the string (eval)
               the value is greater than the numerical value of the string (min)
               the value is less than the numerical value of the string (max)
      NOTES
         for age range: 
             use KEY: age (converts to Ma, takes mid point of low, high if no value for age.
         for paleolat:
             use KEY: model_lat (uses lat, if age<5 Ma, else, model_lat, or attempts calculation from average_inc if no model_lat.) returns estimate in model_lat key

    """
    dir_path="."
    flag=''
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        magic_file=dir_path+'/'+sys.argv[ind+1]
    else:
        print main.__doc__
        sys.exit()
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        outfile=dir_path+'/'+sys.argv[ind+1]
    else:
        print main.__doc__
        sys.exit()
    if '-key' in sys.argv:
        ind=sys.argv.index('-key')
        grab_key=sys.argv[ind+1]
        v=sys.argv[ind+2]
        flag=sys.argv[ind+3]
    else:
        print main.__doc__
        print '-key is required'
        sys.exit()
    #
    # get data read in
    Data,file_type=pmag.magic_read(magic_file) 
    if grab_key =='age': 
        grab_key='average_age'
        Data=pmag.convert_ages(Data)
    if grab_key =='model_lat': 
        Data=pmag.convert_lat(Data)
        Data=pmag.convert_ages(Data)
    Selection=pmag.get_dictitem(Data,grab_key,v,flag)
    if len(Selection)>0:
        pmag.magic_write(outfile,Selection,file_type)
        print len(Selection),' records written to ',outfile
    else:
        print 'no data matched your criteria'
Ejemplo n.º 12
0
def main():
    """
    NAME
        FLA_magic.py

    DESCRIPTION
        import data files from the Univ. Florida, Gainesvile format to magic

    SYNTAX
        FLA_magic.py 

    """
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    meas_type,methcode,instcode,experiment_name,izzi="LT-NO","","","",0
    phi,theta,peakfield,labfield=0,0,0,0
    pTRM,MD,ispec=0,0,0
    dec=[315,225,180,135,45,90,270,270,270,90,180,180,0,0,0]
    inc=[0,0,0,0,0,-45,-45,0,45,45,45,-45,-90,-45,45]
    er_location_name=raw_input("Enter the location name for this study, or <return> for none ")
    if er_location_name=="":
        er_sites_file=raw_input("Enter site location file name, or <return> for none ")
        if er_sites_file=="": 
            er_location_name="none"
        else:
            site_locations,file_type=pmag.magic_read(er_sites_file)
    magfile=raw_input("Enter florida measurement filename for processing  ")
    print "Enter whether [A]F or [T]hermal de-(re)magnetization  "
    ans=raw_input(" <return> for NRMs only  ")
    inst=""
    methcode="LT-NO"
    if ans=="A":
        inst="UFG-AF"
        methcode="LT-AF-Z"
    if ans=="T":
        inst="UFG-thermal"
        methcode="LT-T-Z"
    if ans=="":methcode="LT-NO"  
    input=open(magfile,'r')
    MagRecs=[]
    for line in input.readlines():
        print line
        MagRec={}
        MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
        MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
        MagRec["treatment_ac_field"]='%8.3e' %(peakfield) # peak field in tesla
        MagRec["treatment_dc_field"]='%8.3e' %(labfield) # lab field in tesla
        MagRec["treatment_dc_field_phi"]='%7.1f' %(phi)
        MagRec["treatment_dc_field_theta"]='%7.1f'% (theta)
        rec=line.split()
        MagRec["er_specimen_name"]=rec[0]
        MagRec["er_sample_name"]=rec[0]
        sitetmp=rec[0].split('.') # Florida naming convention splits on '.' between site and sample
        MagRec["er_site_name"]=sitetmp[0]
        MagRec["er_location_name"]="none"
        if er_location_name!="":
            MagRec["er_location_name"]=er_location_name
        else:
            for site in site_locations:
                if site["er_site_name"] == MagRec["er_site_name"]: 
                    MagRec["er_location_name"]=site["er_location_name"]
        if inst=="UFG-AF":
            MagRec["treatment_ac_field"]='%8.3e' % ( float(rec[1])*1e-4) # AF field in tesla from Oersted in Florida convention
            meas_type="LT-AF-Z"
            MagRec["treatment_dc_field"]='0'
        else: 
            MagRec["treatment_temp"]='%8.3e' % (float(rec[1])+273.) # temp in kelvin
            meas_type="LT-T-Z"
        MagRec["measurement_magn_moment"]='%10.3e'% ((float(rec[4])/100)*1e-5) # moment in Am^2 (from 50xA/m and assuming 5cc sample in Florida convention)
        MagRec["measurement_dec"]=rec[7]
        MagRec["measurement_inc"]=rec[8]
        MagRec["magic_method_codes"]=meas_type
        MagRecs.append(MagRec) 
    output=raw_input("Filename for output [magic_measurements.txt] ")
    if output=="":output="magic_measurements.txt"
    MagOuts=pmag.measurements_methods(MagRecs,0)
    pmag.magic_write(output,MagOuts,'magic_measurements')
    print "results put in ",output
Ejemplo n.º 13
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"
Ejemplo n.º 14
0
def main():
    """
    NAME
        chi_magic.py

    DESCRIPTION
        plots magnetic susceptibility as a function of frequency and temperature and AC field

    SYNTAX
        chi_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -i allows interactive setting of FILE and temperature step
        -f FILE, specify magic_measurements format file
        -T IND, specify temperature step to plot
        -e EXP, specify experiment name to plot

    DEFAULTS
         FILE: magic_measurements.txt
         IND: first 
         SPEC: step through one by one
    """
    cont,FTinit,BTinit,k="",0,0,0
    meas_file="magic_measurements.txt"
    spec=""
    Tind,cont=0,""
    EXP=""
    fmt='svg' # default image type for saving
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-i' in sys.argv:
        file=raw_input("Input magic_measurements file name? [magic_measurements.txt]  ")
        if file!="":meas_file=file
    if '-e' in sys.argv:
        ind=sys.argv.index('-e')
        EXP=sys.argv[ind+1]
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        meas_file=sys.argv[ind+1]
    if '-T' in sys.argv:
        ind=sys.argv.index('-T')
        Tind=int(sys.argv[ind+1])
    #
    meas_data,file_type=pmag.magic_read(meas_file)
    #
    # get list of unique experiment names
    #
    # initialize some variables (a continuation flag, plot initialization flags and the experiment counter
    experiment_names=[]
    for rec in meas_data:
        if rec['magic_experiment_name'] not in experiment_names:experiment_names.append(rec['magic_experiment_name'])
    #
    # hunt through by experiment name
    if EXP!="":
        try:
            k=experiment_names.index(EXP)
        except:
            print "Bad experiment name"
            sys.exit()
    while k < len(experiment_names):
        e=experiment_names[k]
        if EXP=="":print e, k+1 , 'out of ',len(experiment_names)
    #
    #  initialize lists of data, susceptibility, temperature, frequency and field
        X,T,F,B=[],[],[],[]
        for rec in  meas_data:
            methcodes=rec['magic_method_codes']
            meths=methcodes.strip().split(':')
            if rec['magic_experiment_name']==e and "LP-X" in meths: # looking for chi measurement
                if 'measurement_temp' not in rec.keys():rec['measurement_temp']='300' # set defaults
                if 'measurement_freq' not in rec.keys():rec['measurement_freq']='0' # set defaults
                if 'measurement_lab_field_ac' not in rec.keys():rec['measurement_lab_field_ac']='0' # set default
                X.append(float(rec['measurement_x']))
                T.append(float(rec['measurement_temp']))
                F.append(float(rec['measurement_freq']))
                B.append(float(rec['measurement_lab_field_ac']))
    #
    # get unique list of Ts,Fs, and Bs
    #
        Ts,Fs,Bs=[],[],[]
        for k in range(len(X)):   # hunt through all the measurements
            if T[k] not in Ts:Ts.append(T[k])  # append if not in list
            if F[k] not in Fs:Fs.append(F[k])
            if B[k] not in Bs:Bs.append(B[k])
        Ts.sort() # sort list of temperatures, frequencies and fields
        Fs.sort()
        Bs.sort()
        if '-x' in sys.argv:
            k=len(experiment_names)+1 # just plot the one
        else:
            k+=1  # increment experiment number
    #
    # plot chi versus T and F holding B constant
    #  
        plotnum=1  # initialize plot number to 1
        if len(X)>2:  # if there are any data to plot, continue
            b=Bs[-1]  # keeping field constant and at maximum
            XTF=[] # initialize list of chi versus Temp and freq
            for f in Fs:   # step through frequencies sequentially
                XT=[]  # initialize list of chi versus temp
                for kk in range(len(X)): # hunt through all the data
                    if F[kk]==f and B[kk]==b:  # select data with given freq and field
                        XT.append([X[kk],T[kk]]) # append to list
                XTF.append(XT) # append list to list of frequencies
            if len(XT)>1: # if there are any temperature dependent data
                pmagplotlib.plot_init(plotnum,5,5) # initialize plot
                pmagplotlib.plotXTF(plotnum,XTF,Fs,e,b) # call the plotting function
                pmagplotlib.drawFIGS({'fig':plotnum})
                plotnum+=1 # increment plot number
            f=Fs[0] # set frequency to minimum
            XTB=[] # initialize list if chi versus Temp and field
            for b in Bs:  # step through field values
                XT=[] # initial chi versus temp list for this field
                for kk in range(len(X)): # hunt through all the data
                    if F[kk]==f and B[kk]==b: # select data with given freq and field  
                        XT.append([X[kk],T[kk]]) # append to list
                XTB.append(XT)
            if len(XT)>1: # if there are any temperature dependent data
                pmagplotlib.plot_init(plotnum,5,5) # set up plot
                pmagplotlib.plotXTB(plotnum,XTB,Bs,e,f) # call the plotting function
                pmagplotlib.drawFIGS({'fig':plotnum})
                plotnum+=1 # increment plot number
            if '-i' in sys.argv: 
                for ind in range(len(Ts)):  # print list of temperatures available
                    print ind,int(Ts[ind]) 
                cont=raw_input("Enter index of desired temperature step, s[a]ve plots, [return] to quit ")
                if cont=='a':
                        files={}
                        PLTS={}
                        for p in range(1,plotnum):
                            key=str(p)
                            files[key]=e+'_'+key+'.'+fmt
                            PLTS[key]=key
                        pmagplotlib.saveP(PLTS,files)
                        cont=raw_input("Enter index of desired temperature step, s[a]ve plots, [return] to quit ")
                if cont=="":cont='q'
            while cont!="q":
                if '-i' in sys.argv:Tind=int(cont) # set temperature index
                b=Bs[-1] # set field to max available
                XF=[] # initial chi versus frequency list
                for kk in range(len(X)): # hunt through the data
                    if T[kk]==Ts[Tind] and B[kk]==b:  # if temperature and field match,
                        XF.append([X[kk],F[kk]]) # append the data
                if len(XF)>1: # if there are any data to plot
                    if FTinit==0: # if not already initialized, initialize plot
                        pmagplotlib.plot_init(plotnum,5,5)
                        FTinit=1 
                        XFplot=plotnum
                        plotnum+=1 # increment plotnum
                    pmagplotlib.plotXFT(XFplot,XF,Ts[Tind],e,b)
                else:
                    print '\n *** Skipping susceptibitily-frequency plot as a function of temperature *** \n'
                f=Fs[0] # set frequency to minimum available
                XB=[] # initialize chi versus field list
                for kk in range(len(X)): # hunt through the data
                    if T[kk]==Ts[Tind] and F[kk]==f:  # if temperature and field match those desired
                        XB.append([X[kk],B[kk]]) # append the data to list
                if len(XB)>1: # if there are any data
                    if BTinit==0: # if plot not already initialized
                        pmagplotlib.plot_init(plotnum,5,5) # do it
                        BTinit=1 
                    pmagplotlib.plotXBT(plotnum,XB,Ts[Tind],e,f) # and call plotting function 
                else:
                    print 'Skipping susceptibitily - AC field plot as a function of temperature'
                if '-i' in sys.argv:
                    for ind in range(len(Ts)): # just in case you forgot, print out a new list of temperatures
                        print ind,int(Ts[ind]) 
                    cont=raw_input("Enter index of next temperature step, s[a]ve plots,  [return] to quit ") # ask for new temp
                    if cont=="":sys.exit()
                    if cont=='a':
                        files={}
                        PLTS={}
                        for p in range(1,plotnum):
                            key=str(p)
                            files[key]=e+'_'+key+'.'+fmt
                            PLTS[key]=p
                        pmagplotlib.saveP(PLTS,files)
                        cont=raw_input("Enter index of desired temperature step, s[a]ve plots, [return] to quit ")
                        if cont=="":sys.exit()
                else:
                    ans=raw_input("enter s[a]ve to save files,  [return] to quit ")
                    if ans=='a': 
                        files={}
                        PLTS={}
                        for p in range(1,plotnum):
                            key=str(p)
                            files[key]=e+'_'+key+'.'+fmt
                            PLTS[key]=p
                        pmagplotlib.saveP(PLTS,files)
                        sys.exit()
                    else:
                        sys.exit()
Ejemplo n.º 15
0
def main():
    """
    NAME
        zeq_magic_redo.py
   
    DESCRIPTION
        Calculate principal components through demagnetization data using bounds and calculation type stored in "redo" file
  
    SYNTAX
        zeq_magic_redo.py [command line options]

    OPTIONS
        -h prints help message
        -usr USER:   identify user, default is ""
        -f: specify input file, default is magic_measurements.txt
        -F: specify output file, default is zeq_specimens.txt
        -fre  REDO: specify redo file, default is "zeq_redo"
        -fsa  SAMPFILE: specify er_samples format file, default is "er_samples.txt"
        -A : don't average replicate measurements, default is yes
        -crd [s,g,t] : 
             specify coordinate system [s,g,t]  [default is specimen coordinates]
                 are specimen, geographic, and tilt corrected respectively
             NB: you must have a SAMPFILE in this directory to rotate from specimen coordinates
        -leg:  attaches "Recalculated from original measurements; supercedes published results. " to comment field
    INPUTS
        zeq_redo format file is:
        specimen_name calculation_type[DE-BFL,DE-BFL-A,DE-BFL-O,DE-BFP,DE-FM]  step_min step_max component_name[A,B,C]
    """
    dir_path='.'
    INCL=["LT-NO","LT-AF-Z","LT-T-Z","LT-M-Z"] # looking for demag data
    beg,end,pole,geo,tilt,askave,save=0,0,[],0,0,0,0
    user,doave,comment= "",1,""
    geo,tilt=0,0
    version_num=pmag.get_version()
    args=sys.argv
    if '-WD' in args:
        ind=args.index('-WD')
        dir_path=args[ind+1]
    meas_file,pmag_file,mk_file= dir_path+"/"+"magic_measurements.txt",dir_path+"/"+"zeq_specimens.txt",dir_path+"/"+"zeq_redo"
    samp_file,coord=dir_path+"/"+"er_samples.txt",""
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind=args.index("-usr")
        user=sys.argv[ind+1]
    if "-A" in args:doave=0
    if "-leg" in args: comment="Recalculated from original measurements; supercedes published results. "
    if "-f" in args:
        ind=args.index("-f")
        meas_file=dir_path+'/'+sys.argv[ind+1]
    if "-F" in args:
        ind=args.index("-F")
        pmag_file=dir_path+'/'+sys.argv[ind+1]
    if "-fre" in args:
        ind=args.index("-fre")
        mk_file=dir_path+"/"+args[ind+1]
    try:
        mk_f=open(mk_file,'rU')
    except:
        print "Bad redo file"
        sys.exit()
    mkspec,skipped=[],[]
    speclist=[]
    for line in mk_f.readlines():
        tmp=line.split()
        mkspec.append(tmp)
        speclist.append(tmp[0])
    if "-fsa" in args:
        ind=args.index("-fsa")
        samp_file=dir_path+'/'+sys.argv[ind+1]
    if "-crd" in args:
        ind=args.index("-crd")
        coord=sys.argv[ind+1]
        if coord=="g":geo,tilt=1,0
        if coord=="t":geo,tilt=1,1
#
# now get down to bidness
    if geo==1:
        samp_data,file_type=pmag.magic_read(samp_file)
        if file_type != 'er_samples':
            print file_type
            print "This is not a valid er_samples file " 
            sys.exit()
    # set orientation priorities
        SO_methods=[]
        for rec in samp_data:
           if "magic_method_codes" in rec:
               methlist=rec["magic_method_codes"]
               for meth in methlist.split(":"):
                   if "SO" in meth and "SO-POM" not in meth.strip():
                       if meth.strip() not in SO_methods: SO_methods.append(meth.strip())
        SO_priorities=pmag.set_priorities(SO_methods,0)
    #
    #
    #

    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()
    #
    # sort the specimen names
    #
    k = 0
    print 'Processing ',len(speclist), ' specimens - please wait'
    PmagSpecs=[]
    while k < len(speclist):
        s=speclist[k]
        recnum=0
        PmagSpecRec={}
        method_codes,inst_codes=[],[]
    # find the data from the meas_data file for this sample
    #
    #  collect info for the PmagSpecRec dictionary
    #
        meas_meth=[]
        for rec in  meas_data: # copy of vital stats to PmagSpecRec from first spec record in demag block
           skip=1
           if rec["er_specimen_name"]==s: 
               methods=rec["magic_method_codes"].split(":")
               if len(set(methods) & set(INCL))>0:
                   PmagSpecRec["er_analyst_mail_names"]=user
                   PmagSpecRec["magic_software_packages"]=version_num
                   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"]
                   PmagSpecRec["er_citation_names"]="This study"
                   if "magic_experiment_name" not in rec.keys(): rec["magic_experiment_name"]=""
                   PmagSpecRec["magic_experiment_names"]=rec["magic_experiment_name"]
                   if "magic_instrument_codes" not in rec.keys(): rec["magic_instrument_codes"]=""
                   inst=rec['magic_instrument_codes'].split(":")
                   for I in inst:
                       if I not in inst_codes:  # copy over instruments
                           inst_codes.append(I)
                   meths=rec["magic_method_codes"].split(":")
                   for meth in meths:
                       if meth.strip() not in meas_meth:meas_meth.append(meth)
                   if "LP-DIR-AF" in meas_meth or "LT-AF-Z" in meas_meth: 
                       PmagSpecRec["measurement_step_unit"]="T"
                       if "LP-DIR-AF" not in method_codes:method_codes.append("LP-DIR-AF") 
                   if "LP-DIR-T" in meas_meth or "LT-T-Z" in meas_meth: 
                       PmagSpecRec["measurement_step_unit"]="K"
                       if "LP-DIR-T" not in method_codes:method_codes.append("LP-DIR-T") 
                   if "LP-DIR-M" in meas_meth or "LT-M-Z" in meas_meth: 
                       PmagSpecRec["measurement_step_unit"]="J"
                       if "LP-DIR-M" not in method_codes:method_codes.append("LP-DIR-M") 
        if PmagSpecRec=={}:
            print 'no data found for specimen:  ',s
            print 'delete from zeq_redo input file...., then try again'
            sys.exit()
    #
    #
        data,units=pmag.find_dmag_rec(s,meas_data)
    #
        datablock=data
        noskip=1
        if len(datablock) <2 or s not in speclist : 
            noskip=0
            k+=1
#            print 'skipping ', s,len(datablock)
        if noskip:
        #
        # find replicate measurements at given treatment step and average them
        #
#            step_meth,avedata=pmag.vspec(data)
#
#            if len(avedata) != len(datablock):
#                if doave==1: 
#                    method_codes.append("DE-VM")
#                    datablock=avedata
        #
        # do geo or stratigraphic correction now
        #
            if geo==1:
       # find top priority orientation method
                redo,p=1,0
                if len(SO_methods)<=1:
                    az_type=SO_methods[0]
                    orient=pmag.find_samp_rec(PmagSpecRec["er_sample_name"],samp_data,az_type)
                    if orient["sample_azimuth"]  !="": method_codes.append(az_type)
                    redo=0
                while redo==1:
                    if p>=len(SO_priorities):
                        print "no orientation data for ",s
                        orient["sample_azimuth"]=""
                        orient["sample_dip"]=""
                        method_codes.append("SO-NO")
                        redo=0
                    else:
                        az_type=SO_methods[SO_methods.index(SO_priorities[p])]
                        orient=pmag.find_samp_rec(PmagSpecRec["er_sample_name"],samp_data,az_type)
                        if orient["sample_azimuth"]  !="":
                            method_codes.append(az_type)
                            redo=0
                    p+=1
        #
        #  if tilt selected,  get stratigraphic correction
        #
                tiltblock,geoblock=[],[]
                for rec in datablock:
                    if "sample_azimuth" in orient.keys() and orient["sample_azimuth"]!="":
                        d_geo,i_geo=pmag.dogeo(rec[1],rec[2],orient["sample_azimuth"],orient["sample_dip"])
                        geoblock.append([rec[0],d_geo,i_geo,rec[3],rec[4],rec[5]])
                        if tilt==1 and "sample_bed_dip_direction" in orient.keys(): 
                            d_tilt,i_tilt=pmag.dotilt(d_geo,i_geo,orient["sample_bed_dip_direction"],orient["sample_bed_dip"])
                            tiltblock.append([rec[0],d_tilt,i_tilt,rec[3],rec[4],rec[5]])
                        elif tilt==1:
                            if PmagSpecRec["er_sample_name"] not in skipped:
                                print 'no tilt correction for ', PmagSpecRec["er_sample_name"],' skipping....'
                                skipped.append(PmagSpecRec["er_sample_name"])
                    else:
                        if PmagSpecRec["er_sample_name"] not in skipped:
                            print 'no geographic correction for ', PmagSpecRec["er_sample_name"],' skipping....'
                            skipped.append(PmagSpecRec["er_sample_name"])
    #
    #	get beg_pca, end_pca, pca
            if PmagSpecRec['er_sample_name'] not in skipped:
                compnum=-1
                for spec in mkspec:
                    if spec[0]==s:
                        CompRec={}
                        for key in PmagSpecRec.keys():CompRec[key]=PmagSpecRec[key]
                        compnum+=1
                        calculation_type=spec[1]
                        beg=float(spec[2])
                        end=float(spec[3])
                        if len(spec)>4:
                            comp_name=spec[4]
                        else:
                            comp_name=string.uppercase[compnum]
                        CompRec['specimen_comp_name']=comp_name
                        if beg < float(datablock[0][0]):beg=float(datablock[0][0])
                        if end > float(datablock[-1][0]):end=float(datablock[-1][0])
                        for l  in range(len(datablock)):
                            if datablock[l][0]==beg:beg_pca=l
                            if datablock[l][0]==end:end_pca=l
                        if geo==1 and tilt==0:
                            mpars=pmag.domean(geoblock,beg_pca,end_pca,calculation_type)
                            if mpars["specimen_direction_type"]!="Error":
                                CompRec["specimen_dec"]='%7.1f ' %(mpars["specimen_dec"])
                                CompRec["specimen_inc"]='%7.1f ' %(mpars["specimen_inc"])
                                CompRec["specimen_tilt_correction"]='0'
                        if geo==1 and tilt==1:
                            mpars=pmag.domean(tiltblock,beg_pca,end_pca,calculation_type)
                            if mpars["specimen_direction_type"]!="Error":
                                CompRec["specimen_dec"]='%7.1f ' %(mpars["specimen_dec"])
                                CompRec["specimen_inc"]='%7.1f ' %(mpars["specimen_inc"])
                                CompRec["specimen_tilt_correction"]='100'
                        if geo==0 and tilt==0: 
                            mpars=pmag.domean(datablock,beg_pca,end_pca,calculation_type)
                            if mpars["specimen_direction_type"]!="Error":
                                CompRec["specimen_dec"]='%7.1f ' %(mpars["specimen_dec"])
                                CompRec["specimen_inc"]='%7.1f ' %(mpars["specimen_inc"])
                                CompRec["specimen_tilt_correction"]='-1'
                        if mpars["specimen_direction_type"]=="Error": 
                            pass
                        else: 
                            CompRec["measurement_step_min"]='%8.3e '%(datablock[beg_pca][0])
                            try:
                                CompRec["measurement_step_max"]='%8.3e '%(datablock[end_pca][0] )
                            except:
                                print 'error in end_pca ',PmagSpecRec['er_specimen_name']
                            CompRec["specimen_correction"]='u'
                            if calculation_type!='DE-FM':
                                CompRec["specimen_mad"]='%7.1f '%(mpars["specimen_mad"])
                                CompRec["specimen_alpha95"]=""
                            else:
                                CompRec["specimen_mad"]=""
                                CompRec["specimen_alpha95"]='%7.1f '%(mpars["specimen_alpha95"])
                            CompRec["specimen_n"]='%i '%(mpars["specimen_n"])
                            CompMeths=[]
                            for meth in method_codes:
                                if meth not in CompMeths:CompMeths.append(meth)
                            if calculation_type not in CompMeths:CompMeths.append(calculation_type)
                            if geo==1: CompMeths.append("DA-DIR-GEO")
                            if tilt==1: CompMeths.append("DA-DIR-TILT")
                            if "DE-BFP" not in calculation_type:
                                CompRec["specimen_direction_type"]='l'
                            else:
                                CompRec["specimen_direction_type"]='p'
                            CompRec["magic_method_codes"]=""
                            if len(CompMeths) != 0:
                                methstring=""
                                for meth in CompMeths:
                                    methstring=methstring+ ":" +meth
                                CompRec["magic_method_codes"]=methstring.strip(':')
                            CompRec["specimen_description"]=comment
                            if len(inst_codes) != 0:
                                inststring=""
                                for inst in inst_codes:
                                    inststring=inststring+ ":" +inst
                                CompRec["magic_instrument_codes"]=inststring.strip(':')
                            PmagSpecs.append(CompRec)
            k+=1
    pmag.magic_write(pmag_file,PmagSpecs,'pmag_specimens')
    print "Recalculated specimen data stored in ",pmag_file
Ejemplo n.º 16
0
def main():
    """
    NAME
        scalc_magic.py

    DESCRIPTION
       calculates Sb from pmag_results files

    SYNTAX 
        scalc_magic -h [command line options]
    
    INPUT 
       takes magic formatted pmag_results table
       pmag_result_name must start with "VGP: Site"
       must have average_lat if spin axis is reference
    
    OPTIONS
        -h prints help message and quits
        -f FILE: specify input results file, default is 'pmag_results.txt'
        -c cutoff:  specify VGP colatitude cutoff value
        -k cutoff: specify kappa cutoff
        -crd [s,g,t]: specify coordinate system, default is geographic
        -v : use the VanDammme criterion 
        -a: use antipodes of reverse data: default is to use only normal
        -C: use all data without regard to polarity
        -r:  use reverse data only
        -p: do relative to principle axis
        -b: do bootstrap confidence bounds

     OUTPUT:
         if option -b used: N,  S_B, lower and upper bounds
         otherwise: N,  S_B, cutoff
    """
    in_file='pmag_results.txt'
    coord,kappa,cutoff="0",1.,90.
    nb,anti,spin,v,boot=1000,0,1,0,0
    coord_key='tilt_correction'
    rev=0
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index("-f")
        in_file=sys.argv[ind+1]
    if '-c' in sys.argv:
        ind=sys.argv.index('-c')
        cutoff=float(sys.argv[ind+1])
    if '-k' in sys.argv:
        ind=sys.argv.index('-k')
        kappa=float(sys.argv[ind+1])
    if '-crd' in sys.argv:
        ind=sys.argv.index("-crd")
        coord=sys.argv[ind+1]
        if coord=='s':coord="-1"
        if coord=='g':coord="0"
        if coord=='t':coord="100"
    if '-a' in sys.argv: anti=1
    if '-C' in sys.argv: cutoff=180. # no cutoff
    if '-r' in sys.argv: rev=1
    if '-p' in sys.argv: spin=0
    if '-v' in sys.argv: v=1
    if '-b' in sys.argv: boot=1
    data,file_type=pmag.magic_read(in_file)
    #
    #
    # find desired vgp lat,lon, kappa,N_site data:
    #
    #
    #
    A,Vgps,Pvgps=180.,[],[]
    VgpRecs=pmag.get_dictitem(data,'vgp_lat','','F') # get all non-blank vgp latitudes
    VgpRecs=pmag.get_dictitem(VgpRecs,'vgp_lon','','F') # get all non-blank vgp longitudes
    SiteRecs=pmag.get_dictitem(VgpRecs,'data_type','i','T') # get VGPs (as opposed to averaged)
    SiteRecs=pmag.get_dictitem(SiteRecs,coord_key,coord,'T') # get right coordinate system
    for rec in SiteRecs:
            if anti==1:
                if 90.-abs(float(rec['vgp_lat']))<=cutoff and float(rec['average_k'])>=kappa: 
                    if float(rec['vgp_lat'])<0:
                        rec['vgp_lat']='%7.1f'%(-1*float(rec['vgp_lat']))
                        rec['vgp_lon']='%7.1f'%(float(rec['vgp_lon'])-180.)
                    Vgps.append(rec)
                    Pvgps.append([float(rec['vgp_lon']),float(rec['vgp_lat'])])
            elif rev==0: # exclude normals
                if 90.-(float(rec['vgp_lat']))<=cutoff and float(rec['average_k'])>=kappa: 
                    Vgps.append(rec)
                    Pvgps.append([float(rec['vgp_lon']),float(rec['vgp_lat'])])
            else: # include normals
                if 90.-abs(float(rec['vgp_lat']))<=cutoff and float(rec['average_k'])>=kappa: 
                    if float(rec['vgp_lat'])<0:
                        rec['vgp_lat']='%7.1f'%(-1*float(rec['vgp_lat']))
                        rec['vgp_lon']='%7.1f'%(float(rec['vgp_lon'])-180.)
                        Vgps.append(rec)
                        Pvgps.append([float(rec['vgp_lon']),float(rec['vgp_lat'])])
    if spin==0: # do transformation to pole
        ppars=pmag.doprinc(Pvgps)
        for vgp in Vgps:
            vlon,vlat=pmag.dodirot(float(vgp['vgp_lon']),float(vgp['vgp_lat']),ppars['dec'],ppars['inc'])
            vgp['vgp_lon']=vlon
            vgp['vgp_lat']=vlat
            vgp['average_k']="0"
    S_B= pmag.get_Sb(Vgps)
    A=cutoff
    if v==1:
        thetamax,A=181.,180.
        vVgps,cnt=[],0
        for vgp in Vgps:vVgps.append(vgp) # make a copy of Vgps
        while thetamax>A:
            thetas=[]
            A=1.8*S_B+5
            cnt+=1
            for vgp in vVgps:thetas.append(90.-(float(vgp['vgp_lat'])))
            thetas.sort()
            thetamax=thetas[-1]
            if thetamax<A:break
            nVgps=[]
            for  vgp in vVgps:
                if 90.-(float(vgp['vgp_lat']))<thetamax:nVgps.append(vgp)
            vVgps=[]
            for vgp in nVgps:vVgps.append(vgp)
            S_B= pmag.get_Sb(vVgps)
        Vgps=[]
        for vgp in vVgps:Vgps.append(vgp) # make a new Vgp list
    SBs=[]
    if boot==1:
        for i in range(nb): # now do bootstrap 
            BVgps=[]
            if i%100==0: print i,' out of ',nb
            for k in range(len(Vgps)):
                ind=random.randint(0,len(Vgps)-1)
                random.jumpahead(int(ind*1000))
                BVgps.append(Vgps[ind])
            SBs.append(pmag.get_Sb(BVgps))
        SBs.sort()
        low=int(.025*nb)
        high=int(.975*nb)
        print len(Vgps),'%7.1f _ %7.1f ^ %7.1f %7.1f'%(S_B,SBs[low],SBs[high],A)
    else:
        print len(Vgps),'%7.1f  %7.1f '%(S_B,A)
Ejemplo n.º 17
0
def main():
    """ 
    ODP_samples_magic.py
    OPTIONS:
        -f FILE, input csv file
        -Fsa FILE, output er_samples.txt file for updating, default is to overwrite er_samples.txt`
    """
    samp_out="er_samples.txt"
    dir_path='.'
    if "-WD" in sys.argv:
        ind=sys.argv.index("-WD")
        dir_path=sys.argv[ind+1]
    if "-h" in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index("-f")
        samp_file=sys.argv[ind+1]
    else:
        print "must specify -f samp_file"
        sys.exit()
    samp_file=dir_path+'/'+samp_file
    Samps=[]
    if '-Fsa' in sys.argv:
        ind=sys.argv.index("-Fsa")
        samp_out=dir_path+'/'+sys.argv[ind+1]
        Samps,file_type=pmag.magic_read(samp_out)
        print len(Samps), ' read in from: ',samp_out
    input=open(samp_file,"rU").readlines()
    keys=input[0].replace('\n','').split(',')
    ErSamples,samples=[],[]
    for line in input[1:]:
        ODPRec,SampRec={},{}
        rec=line.replace('\n','').split(',')
        for k in range(len(keys)):ODPRec[keys[k]]=rec[k]
        SampRec['er_sample_alternatives']=ODPRec['Text Id']
        label=ODPRec['Label Id'].split()
        if len(label)>1 and 'PMAG' not in label[0]:
            interval=label[1].split('/')[0]
            pieces=label[0].split('-')
            core=pieces[2]
            while len(core)<4:core='0'+core
            SampRec['magic_method_codes']='FS-C-DRILL-IODP:FS-SS-C:SO-V'
            SampRec['er_sample_name']=pieces[0]+'-'+pieces[1]+'-'+core+'-'+pieces[3]+'-'+pieces[4]+'-'+interval
            SampRec['er_site_name']=SampRec['er_sample_name']
            pieces=SampRec['er_sample_name'].split('-')
            SampRec['er_expedition_name']=pieces[0]
            SampRec['er_location_name']=pieces[1]
            SampRec['er_citation_names']="This study"
            SampRec['sample_dip']="0"
            SampRec['sample_azimuth']="0"
            SampRec['sample_core_depth']=ODPRec['Top Depth (m)']
            dates=ODPRec['Sample Date Logged'].split()
            mmddyy=dates[0].split('/')
            yyyy='20'+mmddyy[2] 
            mm=mmddyy[0]
            if len(mm)==1:mm='0'+mm
            dd=mmddyy[1]
            if len(dd)==1:dd='0'+dd
            date=yyyy+':'+mm+':'+dd+':'+dates[1]+":00.00"
            SampRec['sample_date']=date
            ErSamples.append(SampRec)
            samples.append(SampRec['er_sample_name'])
    if len(Samps)>0:
        for samp in Samps:
           if samp['er_sample_name'] not in samples:
               ErSamples.append(samp)
    Recs,keys=pmag.fillkeys(ErSamples)
    pmag.magic_write(samp_out,Recs,'er_samples')
    print('sample information written to er_samples.txt')              
Ejemplo n.º 18
0
def main():
    """
    NAME
        download_magic.py

    DESCRIPTION	
        unpacks a magic formatted smartbook .txt file from the MagIC database into the
        tab delimited MagIC format txt files for use with the MagIC-Py programs.

    SYNTAX
        download_magic.py command line options]

    INPUT
        takes either the upload.txt file created by upload_magic.py or the file
        exported by the MagIC v2.2 console software (downloaded from the MagIC database
        or output by the Console on your PC).

    OPTIONS
        -h prints help message and quits
        -i allows interactive entry of filename
        -f FILE specifies input file name
    """
    dir_path='.'
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    if '-i' in sys.argv:
        file=raw_input("Magic txt file for unpacking? ")
    elif '-f' in sys.argv:
        ind=sys.argv.index("-f")
        file=sys.argv[ind+1]
    else:
        print main.__doc__
        sys.exit()
    f=open(dir_path+'/'+file,'rU')
    File=f.readlines()
    LN=0
    type_list=[]
    filenum=0
    while LN<len(File)-1:
        line=File[LN]
        file_type=line.split('\t')[1]
        file_type=file_type.lower()
        if file_type=='delimited':file_type=Input[skip].split('\t')[2]
        if file_type[-1]=="\n":file_type=file_type[:-1]
        print 'working on: ',repr(file_type)
        if file_type not in type_list:
            type_list.append(file_type)
        else:
            filenum+=1 
        LN+=1
        line=File[LN]
        keys=line.replace('\n','').split('\t')
        LN+=1
        Recs=[]
        while LN<len(File):
            line=File[LN]
            if line[:4]==">>>>" and len(Recs)>0:
                if filenum==0:
                    outfile=dir_path+"/"+file_type.strip()+'.txt'
                else:
                    outfile=dir_path+"/"+file_type.strip()+'_'+str(filenum)+'.txt' 
                NewRecs=[]
                for rec in Recs:
                    if 'magic_method_codes' in rec.keys():
                        meths=rec['magic_method_codes'].split(":")
                        if len(meths)>0:
                            methods=""
                            for meth in meths: methods=methods+meth.strip()+":" # get rid of nasty spaces!!!!!!
                            rec['magic_method_codes']=methods[:-1]
                    NewRecs.append(rec)
                pmag.magic_write(outfile,Recs,file_type)
                print file_type," data put in ",outfile
                if file_type =='pmag_specimens' and 'magic_measurements.txt' in File and 'measurement_step_min' in File and 'measurement_step_max' in File: # sort out zeq_specimens and thellier_specimens
                    os.system('mk_redo.py')
                    os.system('zeq_magic_redo.py')
                    os.system('thellier_magic_redo.py')
                    type_list.append('zeq_specimens')
                    type_list.append('thellier_specimens')
                Recs=[]
                LN+=1
                break
            else:
                rec=line.split('\t')
                Rec={}
                if len(rec)==len(keys):
                    for k in range(len(rec)):
                       Rec[keys[k]]=rec[k]
                    Recs.append(Rec)
                else:
                    print 'WARNING:  problem in file with line: '
                    print line
                    print 'skipping....'
                LN+=1
    if len(Recs)>0:
        if filenum==0:
            outfile=dir_path+"/"+file_type.strip()+'.txt'
        else:
            outfile=dir_path+"/"+file_type.strip()+'_'+str(filenum)+'.txt' 
        NewRecs=[]
        for rec in Recs:
            if 'magic_method_codes' in rec.keys():
                meths=rec['magic_method_codes'].split(":")
                if len(meths)>0:
                    methods=""
                    for meth in meths: methods=methods+meth.strip()+":" # get rid of nasty spaces!!!!!!
                    rec['magic_method_codes']=methods[:-1]
            NewRecs.append(rec)
        pmag.magic_write(outfile,Recs,file_type)
        print file_type," data put in ",outfile
# look through locations table and create separate directories for each location
    locs,locnum=[],1
    if 'er_locations' in type_list:
        locs,file_type=pmag.magic_read(dir_path+'/er_locations.txt')
    if len(locs)>0: # at least one location
        for loc in locs:
            print 'location_'+str(locnum)+": ",loc['er_location_name']
            lpath=dir_path+'/Location_'+str(locnum)
            locnum+=1
            try:
                os.mkdir(lpath)
            except:
                print 'directory ',lpath,' already exists - overwrite everything [y/n]?'
                ans=raw_input()
                if ans=='n':sys.exit()
            for f in type_list:
                print 'unpacking: ',dir_path+'/'+f+'.txt'
                recs,file_type=pmag.magic_read(dir_path+'/'+f+'.txt')
                print len(recs),' read in'
                if 'results' not in f:
                    lrecs=pmag.get_dictitem(recs,'er_location_name',loc['er_location_name'],'T')
                    if len(lrecs)>0:
                        pmag.magic_write(lpath+'/'+f+'.txt',lrecs,file_type)
                        print len(lrecs),' stored in ',lpath+'/'+f+'.txt'
                else:
                    lrecs=pmag.get_dictitem(recs,'er_location_names',loc['er_location_name'],'T')
                    if len(lrecs)>0:
                        pmag.magic_write(lpath+'/'+f+'.txt',lrecs,file_type)
                        print len(lrecs),' stored in ',lpath+'/'+f+'.txt'
Ejemplo n.º 19
0
def main():
    """
    NAME
        kly4s_magic.py

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

    SYNTAX
        kly4s_magic.py -h [command line options]

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

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

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

    SYNTAX
        UCSC_leg_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -usr USER:   identify user, default is ""
        -f FILE: specify  input file, or
        -fin INDEX: specify  index file for reading whole directory: default is index.txt
        -F FILE: specify output file, default is magic_measurements.txt
        -Fsa: specify er_samples format file for appending, default is new er_samples.txt
        -spc NUM : specify number of characters to designate a  specimen, default = 1
        -loc LOCNAME : specify location/study name
        -A: don't average replicate measurements
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXXYYY:  YYY is sample designation with Z characters from site XXX
            [5] sample = site
            [6] all others you will have to either customize your
                self or e-mail [email protected] for help.
 
    INPUT
        Format of UCSC legacy files:   
         
        Spec Treat CDec CInc GDec GInc SDec SInc Int [optional A95]
          Treat is HX where X is AF field in Oe, TX where X is T in C,  or NRM
        
         Intensity assumed to be total moment in (emu/cc) with a 10cc specimen volume
         CDec:  Declination in specimen coordinate system
         CInc:  Declination in specimen coordinate system
         GDec:  Declination in geographic coordinate system
         GInc:  Declination in geographic coordinate system
         SDec:  Declination in stratigraphic coordinate system
         SInc:  Declination in stratigraphic coordinate system
   index file:  must be formatted:
         FILENAME  SITE
    """
# initialize some stuff
    noave=0
    methcode,inst="",""
    samp_con,Z='4',3
    missing=1
    demag="N"
    er_location_name=""
    citation='This study'
    args=sys.argv
    methcode="LP-NO"
    specnum=-1
    MagRecs=[]
    version_num=pmag.get_version()
    Samps=[] # keeps track of sample orientations
    DIspec=[]
    MagFiles=[]
#
# get command line arguments
#
    user=""
    mag_file=""
    ind_file=""
    dir_path='.'
    ErSamps,ErSites=[],[]
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    samp_file=dir_path+'/er_samples.txt'
    site_file=dir_path+'/er_sites.txt'
    meas_file=dir_path+"/magic_measurements.txt"
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind=args.index("-usr")
        user=args[ind+1]
    if '-F' in args:
        ind=args.index("-F")
        meas_file=dir_path+'/'+args[ind+1]
    if '-Fsi' in args:
        ind=args.index("-Fsi")
        site_file=dirpath+'.'+args[ind+1]
    try:
        open(site_file,'rU')
        ErSites,file_type=pmag.magic_read(site_file)
        print 'site information will be appended to ', site_file 
    except:
        print site_file,' not found: site information will be stored in new er_sites.txt file'
        site_file=dir_path+'/er_sites.txt'
    if '-Fsa' in args:
        ind=args.index("-Fsa")
        samp_file=dirpath+'/'+args[ind+1]
    try:
        open(samp_file,'rU')
        ErSamps,file_type=pmag.magic_read(samp_file)
        print 'sample information will be appended to ', samp_file 
    except:
        print samp_file,' not found: sample information will be stored in new er_samples.txt file'
        samp_file=dir_path+'/er_samples.txt'
    if '-f' in args:
        ind=args.index("-f")
        mag_file=args[ind+1]
        site=mag_file.split('.')[0]
        magfile=dir_path+'/'+mag_file
        try:
            input=open(magfile,'rU')
            MagFiles.append([magfile,site])
        except:
            print "bad input file name"
            sys.exit()
    elif '-fin' in args:
        ind=args.index("-fin")
        ind_file=args[ind+1]
        ind_file=dir_path+'/'+ind_file
        try:
            index_file=open(ind_file,'rU')
        except:
            print "bad index file name"
            sys.exit()
    elif '-fin' not in args:
        ind_file=dir_path+'/index.txt'
        try:
            index_file=open(ind_file,'rU')
        except:
            print "bad index file name"
            sys.exit()
    if ind_file!="": 
        Files=index_file.readlines()
        for file in Files:
            rec=file.split()
            MagFiles.append(rec)
    if "-spc" in args:
        ind=args.index("-spc")
        specnum=int(args[ind+1])
        if specnum!=0:specnum=-specnum
    if "-loc" in args:
        ind=args.index("-loc")
        er_location_name=args[ind+1]
    else:
        print "-loc  is required option"
        print main.__doc__
        sys.exit()
    if "-A" in args: noave=1
    Sites=[]
    for file in MagFiles:
        site=file[1] # attach site name either from file name or from index file
        if site not in Sites:
            Sites.append(site)
            ErSiteRec={'er_location_name': er_location_name,'er_site_name':site,'er_citation_names':citation,'site_definition':'s','site_lat':'','site_lon':"",'site_class':"",'site_lithology':"",'site_type':""}
            ErSites.append(ErSiteRec)
        print 'processing file: ',file[0],' for site: ',site
        data=open(dir_path+'/'+file[0],'rU').readlines() # read in data from file
        firstrec=data[0].split()
        if firstrec[0]=='FILE': # this file has a header, must look for start of data
            for k in range(len(data)):
                if data[k][0]=='-': break    
        else:
            k=-1
        while k<len(data)-1:
            k+=1
            line=data[k]
            if len(line)>2: # skip stupid terminal lines
                line=line.replace(' T  ',' T') # make columns consistent
                line=line.replace(' H  ',' H') # make columns consistent
                line=line.replace(' T ',' T') # make columns consistent
                line=line.replace(' H ',' H') # make columns consistent
                rec=line.split()
                if len(rec)<2: break # skip junk
                MagRec={}
                MagRec['er_location_name']=er_location_name
                MagRec['magic_software_packages']=version_num
                MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
                MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
                MagRec["treatment_ac_field"]='0'
                meas_type="LT-NO"
                MagRec["measurement_flag"]='g'
                MagRec["measurement_standard"]='u'
                MagRec["measurement_number"]='1'
                MagRec["er_specimen_name"]=rec[0]
                if specnum!=0:
                    MagRec["er_sample_name"]=rec[0][:specnum]
                else:
                    MagRec["er_sample_name"]=rec[0]
     #           site=pmag.parse_site(MagRec['er_sample_name'],samp_con,Z)
                MagRec["er_site_name"]=site
                MagRec["measurement_magn_moment"]='%10.3e'% (float(rec[8])*1e-4) # # int is in emu/cc; assuming 10cc, this converts to Am^2 
    #
                if samp_file!="" and MagRec["er_sample_name"] not in Samps:        # create er_samples.txt file with these data 
                    cdec,cinc=float(rec[2]),float(rec[3])
                    gdec,ginc=float(rec[4]),float(rec[5])
                    az,pl=pmag.get_azpl(cdec,cinc,gdec,ginc)
                    bdec,binc=float(rec[6]),float(rec[7])
                    if rec[4]!=rec[6] and rec[5]!=rec[7]:
                        dipdir,dip=pmag.get_tilt(gdec,ginc,bdec,binc)
                    else:
                        dipdir,dip=0,0
                    ErSampRec={}
                    ErSampRec['er_citation_names']='This study'
                    ErSampRec['er_location_name']=MagRec['er_location_name']
                    ErSampRec['er_site_name']=MagRec['er_site_name']
                    ErSampRec['er_sample_name']=MagRec['er_sample_name']
                    ErSampRec['sample_azimuth']='%7.1f'%(az)
                    ErSampRec['sample_dip']='%7.1f'%(pl)
                    ErSampRec['sample_bed_dip_direction']='%7.1f'%(dipdir)
                    ErSampRec['sample_bed_dip']='%7.1f'%(dip)
                    ErSampRec['sample_description']='az,pl,dip_dir and dip recalculated from [c,g,b][dec,inc] in UCSC legacy file'
                    ErSampRec['magic_method_codes']='SO-NO'
                    ErSamps.append(ErSampRec)
                    Samps.append(ErSampRec['er_sample_name'])
                MagRec["measurement_dec"]=rec[2]
                MagRec["measurement_inc"]=rec[3]
                MagRec["er_analyst_mail_names"]=""
                MagRec["er_citation_names"]="This study"
                demag=rec[1][0]
                if demag!='N':
                    treat=float(rec[1][1:])
                else:
                    treat=0
                if demag=="H":
                    MagRec["treatment_ac_field"]='%8.3e' %(treat*1e-4) # convert from oe to tesla
                    meas_type="LT-AF-Z"
                elif demag=="T":
                    MagRec["treatment_temp"]='%8.3e' % (treat+273.) # temp in kelvin
                    meas_type="LT-T-Z"
                MagRec['magic_method_codes']=meas_type
                MagRecs.append(MagRec) 
    MagOuts=pmag.measurements_methods(MagRecs,noave)
    pmag.magic_write(meas_file,MagOuts,'magic_measurements')
    print "results put in ",meas_file
    pmag.magic_write(samp_file,ErSamps,'er_samples')
    print "sample orientations put in ",samp_file
    pmag.magic_write(site_file,ErSites,'er_sites')
    print "site names put in ",site_file
Ejemplo n.º 21
0
def main():
    """
    NAME 
        strip_magic.py

    DESCRIPTION
        plots various parameters versus depth or age

    SYNTAX
        strip_magic.py [command line optins]

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file from magic,default='pmag_results.txt'
         supported types=[pmag_specimens, pmag_samples, pmag_sites, pmag_results, magic_web]
        -obj [sit,sam,all]: specify object to site,sample,all for pmag_result table, default is all
        -fmt [svg,png,jpg], format for images - default is svg
        -x [age,pos]:  specify whether age or stratigraphic position
        -y [dec,inc,int,chi,lat,lon,vdm,vadm]
           (lat and lon are VGP lat and lon)
        -Iex: plot the expected inc at lat - only available for results with lat info in file
        -ts TS amin amax: plot the GPTS for the time interval between amin and amax (numbers in Ma)
           TS: [ck95, gts04] 
        -mcd method_code, specify method code, default is first one encountered
    NOTES
        when x and/or y are not specified, a list of possibilities will be presented to the user for choosing

    """
    xaxis,xplotind,yplotind="",0,0 # (0 for strat pos)
    yaxis,Xinc="", "" 
    obj='all'
    supported=['pmag_specimens', 'pmag_samples', 'pmag_sites', 'pmag_results','magic_web']
    Depth_keys=['specimen_core_depth','specimen_height','specimen_elevation','specimen_composite_depth', 'sample_core_depth','sample_height','sample_elevation','sample_composite_depth', 'site_core_depth','site_height','site_elevation','site_composite_depth','average_height']
    Age_keys=['specimen_inferred_age','sample_inferred_age','site_inferred_age','average_age']
    Unit_keys={'specimen_inferred_age':'specimen_inferred_age_unit','sample_inferred_age':'sample_inferred_age_unit','site_inferred_age':'site_inferred_age_unit','average_age':'average_age_unit'}
    Dec_keys=['measurement_dec','specimen_dec','sample_dec','site_dec','average_dec']
    Inc_keys=['measurement_inc','specimen_inc','sample_inc','site_inc','average_inc']
    Int_keys=['measurement_magnitude','measurement_magn_moment','measurement_magn_volume','measurement_magn_mass','specimen_int','specimen_int_rel','sample_int','sample_int_rel','site_int','site_int_rel','average_int','average_int_rel']
    Chi_keys=['measurement_chi_volume','measurement_chi_mass']
    Lat_keys=['sample_lat','site_lat','average_lat']
    VLat_keys=['vgp_lat']
    VLon_keys=['vgp_lon']
    Vdm_keys=['vdm']
    Vadm_keys=['vadm']
    X_keys=[Age_keys,Depth_keys]
    Y_keys=[Dec_keys,Inc_keys,Int_keys,Chi_keys,VLat_keys,VLon_keys,Vdm_keys,Vadm_keys]
    method,fmt="",'svg'
    FIG={'strat':1}
    plotexp,pTS=0,0
    dir_path="./"
    if '-WD' in sys.argv: 
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    res_file=dir_path+'/pmag_results.txt'
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        res_file=dir_path+'/'+sys.argv[ind+1]
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if '-obj' in sys.argv:
        ind=sys.argv.index('-obj')
        obj=sys.argv[ind+1]
    if '-x' in sys.argv:
        ind=sys.argv.index('-x')
        xaxis=sys.argv[ind+1]
    if '-y' in sys.argv:
        ind=sys.argv.index('-y')
        yaxis=sys.argv[ind+1]
        if yaxis=='dec':ykeys=Dec_keys
        if yaxis=='inc':ykeys=Inc_keys
        if yaxis=='int':ykeys=Int_keys
        if yaxis=='chi':ykeys=Chi_keys
        if yaxis=='lat':ykeys=VLat_keys
        if yaxis=='lon':ykeys=VLon_keys
        if yaxis=='vdm':ykeys=Vdm_keys
        if yaxis=='vadm':ykeys=Vadm_keys
    if '-mcd' in sys.argv:
        ind=sys.argv.index('-mcd')
        method=sys.argv[ind+1]
    if '-ts' in sys.argv:
        ind=sys.argv.index('-ts')
        ts=sys.argv[ind+1]
        amin=float(sys.argv[ind+2])
        amax=float(sys.argv[ind+3])
        pTS=1
    if '-Iex' in sys.argv: plotexp=1
    #
    #
    # get data read in
    Results,file_type=pmag.magic_read(res_file) 
    if file_type not in supported:
        print "Unsupported file type, try again"
        sys.exit()
    PltObjs=['all']
    if file_type=='pmag_results': # find out what to plot
        for rec in Results:
            resname=rec['pmag_result_name'].split()
            if 'Sample' in resname and 'sam' not in PltObjs:PltObjs.append('sam')
            if 'Site' in resname and 'sit' not in PltObjs:PltObjs.append('sit')
    methcodes=[]
    if "magic_method_codes" in Results[0].keys(): # need to know all the measurement types from method_codes
        for rec in Results:
            meths=rec["magic_method_codes"].split(":")
            for meth in meths:
                if meth.strip() not in methcodes and 'LP' in meth: methcodes.append(meth.strip()) # look for the lab treatments
    #
    # initialize some variables
    X_unit="" # Unit for age or depth plotting (meters if depth)
    Xplots,Yplots=[],[]
    Xunits=[]
    yplotind,xplotind=0,0
    #
    # step through possible plottable keys
    #
    if xaxis=="" or yaxis=="":
        for key in Results[0].keys():
            for keys in  X_keys:
                for xkeys in keys: 
                    if key in xkeys:
                        for ResRec in Results:
                            if ResRec[key]!="":
                                Xplots.append(key) # only plot something if there is something to plot!
                                break
            for keys in  Y_keys:
                for pkeys in keys: 
                    if key in pkeys:
                        for ResRec in Results:
                            if ResRec[key]!="":
                                Yplots.append(key)
                                break
        X,Y=[],[]
        for plt in Xplots:
            if plt in Age_keys and 'age' not in X: X.append('age')
            if plt in Depth_keys and 'pos' not in X:X.append('pos')
        for plt in Yplots:
            if plt in Dec_keys and 'dec' not in Y:Y.append('dec')
            if plt in Inc_keys and 'inc' not in Y:Y.append('inc')
            if plt in Int_keys and 'int' not in Y:Y.append('int')
            if plt in Chi_keys and 'chi' not in Y:Y.append('chi')
            if plt in VLat_keys and 'lat' not in Y:Y.append('lat')
            if plt in VLon_keys and 'lon' not in Y:Y.append('lon')
            if plt in Vadm_keys and 'vadm' not in Y:Y.append('vadm')
            if plt in Vdm_keys and 'vdm' not in Y:Y.append('vdm')
        if file_type=='pmag_results':
            print 'available objects for plotting: ',PltObjs
        print 'available X plots: ',X
        print 'available Y plots: ',Y
        print 'available method codes: ',methcodes
        f=open(dir_path+'/.striprc','w')
        for x in X:
           f.write('x:'+x+'\n') 
        for y in Y:
           f.write('y:'+y+'\n') 
        for m in methcodes:
           f.write('m:'+m+'\n') 
        for obj in PltObjs:
           f.write('obj:'+obj+'\n') 
        sys.exit()
    if plotexp==1:
        for lkey in Lat_keys:
            for key in Results[0].keys():
                if key==lkey:    
                    lat=float(Results[0][lkey])
                    Xinc=[pmag.pinc(lat),-pmag.pinc(lat)]
                    break
        if Xinc=="":
            print 'can not plot expected inc for site - lat unknown'
    if method!="" and method not in methcodes:
        print 'your method not available, but these are:  '
        print methcodes
        print 'use ',methocodes[0],'? ^D to quit' 
    if xaxis=='age':
        for akey in Age_keys:
            for key in Results[0].keys():
                if key==akey:
                    Xplots.append(key)
                    Xunits.append(Unit_keys[key])
    if xaxis=='pos':
        for dkey in Depth_keys:
            for key in Results[0].keys():
                if key==dkey: 
                    Xplots.append(key)
    if len(Xplots)==0:
        print 'desired X axis  information not found'
        sys.exit()
    if xaxis=='age':age_unit=Results[0][Xunits[0]]
    if len(Xplots)>1:
        print 'multiple X axis  keys found, using: ',Xplots[xplotind]
    for ykey in ykeys: 
        for key in Results[0].keys():
            if key==ykey:Yplots.append(key)
    if len(Yplots)==0:
        print 'desired Y axis  information not found'
        sys.exit()
    if len(Yplots)>1:
        print 'multiple Y axis  keys found, using: ',Yplots[yplotind]
    
    # check if age or depth info        
    if len(Xplots)==0:
        print "Must have either age or height info to plot "
        sys.exit()
    #
    # check for variable to plot
    #
    #
    # determine X axis (age or depth)
    #
    if xaxis=="age": plotind="1"
    if method=="":method=methcodes[0]
    if xaxis=='pos':
        xlab="Stratigraphic Height (meters)" 
    else:
        xlab="Age ("+age_unit+")"
    Xkey=Xplots[xplotind]
    Ykey=Yplots[yplotind]
    ylab=Ykey
    #
    # collect the data for plotting
    XY=[]
    isign=1.
#    if float(Results[0][Xkey])/float(Results[-1][Xkey])>0 and float(Results[0][Xkey])<0: 
#        isign=-1. # x axis all same sign and negative, take positive (e.g.,for depth in core)
#        xlab="Stratigraphic Position (meters)" 
#    else:
#        isign=1.
    for rec in Results:
        if "magic_method_codes" in rec.keys():
            meths=rec["magic_method_codes"].split(":")
            if method in meths: # make sure it is desired lab treatment step
                if obj=='all' and rec[Xkey].strip()!="":
                    XY.append([isign*float(rec[Xkey]),float(rec[Ykey])])
                elif rec[Xkey].strip()!="":
                    name=rec['pmag_result_name'].split()
                    if obj=='sit' and "Site" in name: XY.append([isign*float(rec[Xkey]),float(rec[Ykey])])
                    if obj=='sam' and "Sample" in name: XY.append([isign*float(rec[Xkey]),float(rec[Ykey])])
        elif method =="":
            if obj=='all' and rec[Xkey].strip()!="":
                XY.append([isign*float(rec[Xkey]),float(rec[Ykey])])
            elif rec[Xkey].strip()!="":
                name=rec['pmag_result_name'].split()
                if obj=='sit' and "Site" in name: XY.append([isign*float(rec[Xkey]),float(rec[Ykey])])
                if obj=='sam' and "Sample" in name: XY.append([isign*float(rec[Xkey]),float(rec[Ykey])])
        else:  
            print "Something wrong with your plotting choices"
            break
    XY.sort()
    title=""
    if "er_locations_names" in Results[0].keys(): title=Results[0]["er_location_names"]
    if "er_locations_name" in Results[0].keys(): title=Results[0]["er_location_name"]
    labels=[xlab,ylab,title]
    pmagplotlib.plot_init(FIG['strat'],10,5)
    pmagplotlib.plotSTRAT(FIG['strat'],XY,labels) # plot them
    if plotexp==1: pmagplotlib.plotHs(FIG['strat'],Xinc,'b','--')
    if yaxis=='inc' or yaxis=='lat':
        pmagplotlib.plotHs(FIG['strat'],[0],'b','-')
        pmagplotlib.plotHs(FIG['strat'],[-90,90],'g','-')
    if pTS==1: 
        FIG['ts']=2
        pmagplotlib.plot_init(FIG['ts'],10,5)
        pmagplotlib.plotTS(FIG['ts'],[amin,amax],ts)
    files={}
    for key in FIG.keys():
        files[key]=key+'.'+fmt 
    if pmagplotlib.isServer: 
        black     = '#000000'
        purple    = '#800080'
        files={}
        files['strat']=xaxis+'_'+yaxis+'_.'+fmt
        files['ts']='ts.'+fmt
        titles={}
        titles['strat']='Depth/Time Series Plot'
        titles['ts']='Time Series Plot'
        FIG = pmagplotlib.addBorders(FIG,titles,black,purple)
        pmagplotlib.saveP(FIG,files)
    else:
        ans=raw_input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans=="a": pmagplotlib.saveP(FIG,files) 
Ejemplo n.º 22
0
def main():
    """
    NAME
        thellier_magic_redo.py

    DESCRIPTION
        Calculates paleointensity parameters for thellier-thellier type data using bounds
        stored in the "redo" file

    SYNTAX
        thellier_magic_redo [command line options]

    OPTIONS
        -h prints help message
        -usr USER:   identify user, default is ""
        -fcr CRIT, set criteria for grading
        -f IN: specify input file, default is magic_measurements.txt
        -fre REDO: specify redo file, default is "thellier_redo"
        -F OUT: specify output file, default is thellier_specimens.txt
        -leg:  attaches "Recalculated from original measurements; supercedes published results. " to comment field
        -CR PERC TYPE: apply a blanket cooling rate correction if none supplied in the er_samples.txt file 
            PERC should be a percentage of original (say reduce to 90%)
            TYPE should be one of the following:
               EG (for educated guess); PS (based on pilots); TRM (based on comparison of two TRMs) 
        -ANI:  perform anisotropy correction
        -fsa SAMPFILE: er_samples.txt file with cooling rate correction information, default is NO CORRECTION
        -Fcr  CRout: specify pmag_specimen format file for cooling rate corrected data
        -fan ANIFILE: specify rmag_anisotropy format file, default is rmag_anisotropy.txt 
        -Fac  ACout: specify pmag_specimen format file for anisotropy corrected data
                 default is AC_specimens.txt
        -fnl NLTFILE: specify magic_measurments format file, default is magic_measurements.txt
        -Fnl NLTout: specify pmag_specimen format file for non-linear trm corrected data
                 default is NLT_specimens.txt
        -z use z component differenences for pTRM calculation

    INPUT
        a thellier_redo file is Specimen_name Tmin Tmax (where Tmin and Tmax are in Centigrade)
    """
    dir_path = "."
    critout = ""
    version_num = pmag.get_version()
    field, first_save = -1, 1
    spec, recnum, start, end = 0, 0, 0, 0
    crfrac = 0
    NltRecs, PmagSpecs, AniSpecRecs, NltSpecRecs, CRSpecs = [], [], [], [], []
    meas_file, pmag_file, mk_file = "magic_measurements.txt", "thellier_specimens.txt", "thellier_redo"
    anis_file = "rmag_anisotropy.txt"
    anisout, nltout = "AC_specimens.txt", "NLT_specimens.txt"
    crout = "CR_specimens.txt"
    nlt_file = ""
    samp_file = ""
    comment, user = "", "unknown"
    anis, nltrm = 0, 0
    jackknife = 0  # maybe in future can do jackknife
    args = sys.argv
    Zdiff = 0
    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 = sys.argv[ind + 1]
    if "-leg" in args:
        comment = "Recalculated from original measurements; supercedes published results. "
    cool = 0
    if "-CR" in args:
        cool = 1
        ind = args.index("-CR")
        crfrac = 0.01 * float(sys.argv[ind + 1])
        crtype = "DA-CR-" + sys.argv[ind + 2]
    if "-Fcr" in args:
        ind = args.index("-Fcr")
        crout = sys.argv[ind + 1]
    if "-f" in args:
        ind = args.index("-f")
        meas_file = sys.argv[ind + 1]
    if "-F" in args:
        ind = args.index("-F")
        pmag_file = sys.argv[ind + 1]
    if "-fre" in args:
        ind = args.index("-fre")
        mk_file = args[ind + 1]
    if "-fsa" in args:
        ind = args.index("-fsa")
        samp_file = dir_path + "/" + args[ind + 1]
        Samps, file_type = pmag.magic_read(samp_file)
        SampCRs = pmag.get_dictitem(Samps, "cooling_rate_corr", "", "F")  # get samples cooling rate corrections
        cool = 1
        if file_type != "er_samples":
            print "not a valid er_samples.txt file"
            sys.exit()
    #
    #
    if "-ANI" in args:
        anis = 1
        ind = args.index("-ANI")
        if "-Fac" in args:
            ind = args.index("-Fac")
            anisout = args[ind + 1]
        if "-fan" in args:
            ind = args.index("-fan")
            anis_file = args[ind + 1]
    #
    if "-NLT" in args:
        if "-Fnl" in args:
            ind = args.index("-Fnl")
            nltout = args[ind + 1]
        if "-fnl" in args:
            ind = args.index("-fnl")
            nlt_file = args[ind + 1]
    if "-z" in args:
        Zdiff = 1
    if "-fcr" in sys.argv:
        ind = args.index("-fcr")
        critout = sys.argv[ind + 1]
    #
    #  start reading in data:
    #
    meas_file = dir_path + "/" + meas_file
    mk_file = dir_path + "/" + mk_file
    accept = pmag.default_criteria(1)[0]  # set criteria to none
    if critout != "":
        critout = dir_path + "/" + critout
        crit_data, file_type = pmag.magic_read(critout)
        if file_type != "pmag_criteria":
            print "bad pmag_criteria file, using no acceptance criteria"
        print "Acceptance criteria read in from ", critout
        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]
    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()
    try:
        mk_f = open(mk_file, "rU")
    except:
        print "Bad redo file"
        sys.exit()
    mkspec = []
    speclist = []
    for line in mk_f.readlines():
        tmp = line.split()
        mkspec.append(tmp)
        speclist.append(tmp[0])
    if anis == 1:
        anis_file = dir_path + "/" + anis_file
        anis_data, file_type = pmag.magic_read(anis_file)
        if file_type != "rmag_anisotropy":
            print file_type
            print file_type, "This is not a valid rmag_anisotropy file "
            sys.exit()
    if nlt_file == "":
        nlt_data = pmag.get_dictitem(
            meas_data, "magic_method_codes", "LP-TRM", "has"
        )  # look for trm acquisition data in the meas_data file
    else:
        nlt_file = dir_path + "/" + nlt_file
        nlt_data, file_type = pmag.magic_read(nlt_file)
    if len(nlt_data) > 0:
        nltrm = 1
    #
    # sort the specimen names and step through one by one
    #
    sids = pmag.get_specs(meas_data)
    #
    print "Processing ", len(speclist), " specimens - please wait "
    while spec < len(speclist):
        s = speclist[spec]
        recnum = 0
        datablock = []
        PmagSpecRec = {}
        PmagSpecRec["er_analyst_mail_names"] = user
        PmagSpecRec["er_citation_names"] = "This study"
        PmagSpecRec["magic_software_packages"] = version_num
        methcodes, inst_code = [], ""
        #
        # find the data from the meas_data file for this specimen
        #
        datablock = pmag.get_dictitem(meas_data, "er_specimen_name", s, "T")
        datablock = pmag.get_dictitem(
            datablock, "magic_method_codes", "LP-PI-TRM", "has"
        )  # pick out the thellier experiment data
        if len(datablock) > 0:
            for rec in datablock:
                if "magic_instrument_codes" not in rec.keys():
                    rec["magic_instrument_codes"] = "unknown"
            #
            #  collect info for the PmagSpecRec dictionary
            #
            rec = datablock[0]
            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"]
            PmagSpecRec["measurement_step_unit"] = "K"
            PmagSpecRec["specimen_correction"] = "u"
            if "er_expedition_name" in rec.keys():
                PmagSpecRec["er_expedition_name"] = rec["er_expedition_name"]
            if "magic_instrument_codes" not in rec.keys():
                PmagSpecRec["magic_instrument_codes"] = "unknown"
            else:
                PmagSpecRec["magic_instrument_codes"] = rec["magic_instrument_codes"]
            if "magic_experiment_name" not in rec.keys():
                rec["magic_experiment_name"] = ""
            else:
                PmagSpecRec["magic_experiment_names"] = rec["magic_experiment_name"]
            meths = rec["magic_experiment_name"].split(":")
            for meth in meths:
                if meth.strip() not in methcodes and "LP-" in meth:
                    methcodes.append(meth.strip())
            #
            # sort out the data into first_Z, first_I, ptrm_check, ptrm_tail
            #
            araiblock, field = pmag.sortarai(datablock, s, Zdiff)
            first_Z = araiblock[0]
            first_I = araiblock[1]
            ptrm_check = araiblock[2]
            ptrm_tail = araiblock[3]
            if len(first_I) < 3 or len(first_Z) < 4:
                spec += 1
                print "skipping specimen ", s
            else:
                #
                # get start, end
                #
                for redospec in mkspec:
                    if redospec[0] == s:
                        b, e = float(redospec[1]), float(redospec[2])
                        break
                if e > float(first_Z[-1][0]):
                    e = float(first_Z[-1][0])
                for recnum in range(len(first_Z)):
                    if first_Z[recnum][0] == b:
                        start = recnum
                    if first_Z[recnum][0] == e:
                        end = recnum
                nsteps = end - start
                if nsteps > 2:
                    zijdblock, units = pmag.find_dmag_rec(s, meas_data)
                    pars, errcode = pmag.PintPars(datablock, araiblock, zijdblock, start, end, accept)
                    if "specimen_scat" in pars.keys():
                        PmagSpecRec["specimen_scat"] = pars["specimen_scat"]
                    if "specimen_frac" in pars.keys():
                        PmagSpecRec["specimen_frac"] = "%5.3f" % (pars["specimen_frac"])
                    if "specimen_gmax" in pars.keys():
                        PmagSpecRec["specimen_gmax"] = "%5.3f" % (pars["specimen_gmax"])
                    pars["measurement_step_unit"] = units
                    pars["specimen_lab_field_dc"] = field
                    pars["specimen_int"] = -1 * field * pars["specimen_b"]
                    PmagSpecRec["measurement_step_min"] = "%8.3e" % (pars["measurement_step_min"])
                    PmagSpecRec["measurement_step_max"] = "%8.3e" % (pars["measurement_step_max"])
                    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"])
                    if pars["method_codes"] != "" and pars["method_codes"] not in methcodes:
                        methcodes.append(pars["method_codes"])
                    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_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.strip(":")
                    PmagSpecRec["magic_software_packages"] = version_num
                    PmagSpecRec["specimen_description"] = comment
                    if critout != "":
                        kill = pmag.grade(PmagSpecRec, accept, "specimen_int")
                        if len(kill) > 0:
                            Grade = "F"  # fails
                        else:
                            Grade = "A"  # passes
                        PmagSpecRec["specimen_grade"] = Grade
                    else:
                        PmagSpecRec["specimen_grade"] = ""  # not graded
                    if nltrm == 0 and anis == 0 and cool != 0:  # apply cooling rate correction
                        SCR = pmag.get_dictitem(
                            SampCRs, "er_sample_name", PmagSpecRec["er_sample_name"], "T"
                        )  # get this samples, cooling rate correction
                        CrSpecRec = pmag.cooling_rate(PmagSpecRec, SCR, crfrac, crtype)
                        if CrSpecRec["er_specimen_name"] != "none":
                            CrSpecs.append(CrSpecRec)
                    PmagSpecs.append(PmagSpecRec)
                    NltSpecRec = ""
                    #
                    # check on non-linear TRM correction
                    #
                    if nltrm == 1:
                        #
                        # find the data from the nlt_data list for this specimen
                        #
                        TRMs, Bs = [], []
                        NltSpecRec = ""
                        NltRecs = pmag.get_dictitem(
                            nlt_data, "er_specimen_name", PmagSpecRec["er_specimen_name"], "has"
                        )  # fish out all the NLT data for this specimen
                        if len(NltRecs) > 2:
                            for NltRec in NltRecs:
                                Bs.append(float(NltRec["treatment_dc_field"]))
                                TRMs.append(float(NltRec["measurement_magn_moment"]))
                            NLTpars = nlt.NLtrm(
                                Bs,
                                TRMs,
                                float(PmagSpecRec["specimen_int"]),
                                float(PmagSpecRec["specimen_lab_field_dc"]),
                                0,
                            )
                            if NLTpars["banc"] > 0:
                                NltSpecRec = {}
                                for key in PmagSpecRec.keys():
                                    NltSpecRec[key] = PmagSpecRec[key]
                                NltSpecRec["specimen_int"] = "%9.4e" % (NLTpars["banc"])
                                NltSpecRec["magic_method_codes"] = PmagSpecRec["magic_method_codes"] + ":DA-NL"
                                NltSpecRec["specimen_correction"] = "c"
                                NltSpecRec["specimen_grade"] = PmagSpecRec["specimen_grade"]
                                NltSpecRec["magic_software_packages"] = version_num
                                print NltSpecRec["er_specimen_name"], " Banc= ", float(NLTpars["banc"]) * 1e6
                                if anis == 0 and cool != 0:
                                    SCR = pmag.get_dictitem(
                                        SampCRs, "er_sample_name", NltSpecRec["er_sample_name"], "T"
                                    )  # get this samples, cooling rate correction
                                    CrSpecRec = pmag.cooling_rate(NltSpecRec, SCR, crfrac, crtype)
                                    if CrSpecRec["er_specimen_name"] != "none":
                                        CrSpecs.append(CrSpecRec)
                                NltSpecRecs.append(NltSpecRec)
                        #
                        # check on anisotropy correction
                        if anis == 1:
                            if NltSpecRec != "":
                                Spc = NltSpecRec
                            else:  # find uncorrected data
                                Spc = PmagSpecRec
                            AniSpecs = pmag.get_dictitem(
                                anis_data, "er_specimen_name", PmagSpecRec["er_specimen_name"], "T"
                            )
                            if len(AniSpecs) > 0:
                                AniSpec = AniSpecs[0]
                                AniSpecRec = pmag.doaniscorr(Spc, AniSpec)
                                AniSpecRec["specimen_grade"] = PmagSpecRec["specimen_grade"]
                                AniSpecRec["magic_instrument_codes"] = PmagSpecRec["magic_instrument_codes"]
                                AniSpecRec["specimen_correction"] = "c"
                                AniSpecRec["magic_software_packages"] = version_num
                                if cool != 0:
                                    SCR = pmag.get_dictitem(
                                        SampCRs, "er_sample_name", AniSpecRec["er_sample_name"], "T"
                                    )  # get this samples, cooling rate correction
                                    CrSpecRec = pmag.cooling_rate(AniSpecRec, SCR, crfrac, crtype)
                                    if CrSpecRec["er_specimen_name"] != "none":
                                        CrSpecs.append(CrSpecRec)
                                AniSpecRecs.append(AniSpecRec)
                    elif anis == 1:
                        AniSpecs = pmag.get_dictitem(
                            anis_data, "er_specimen_name", PmagSpecRec["er_specimen_name"], "T"
                        )
                        if len(AniSpecs) > 0:
                            AniSpec = AniSpecs[0]
                            AniSpecRec = pmag.doaniscorr(PmagSpecRec, AniSpec)
                            AniSpecRec["specimen_grade"] = PmagSpecRec["specimen_grade"]
                            AniSpecRec["magic_instrument_codes"] = PmagSpecRec["magic_instrument_codes"]
                            AniSpecRec["specimen_correction"] = "c"
                            AniSpecRec["magic_software_packages"] = version_num
                            if crfrac != 0:
                                CrSpecRec = {}
                                for key in AniSpecRec.keys():
                                    CrSpecRec[key] = AniSpecRec[key]
                                inten = frac * float(CrSpecRec["specimen_int"])
                                CrSpecRec["specimen_int"] = "%9.4e " % (
                                    inten
                                )  # adjust specimen intensity by cooling rate correction
                                CrSpecRec["magic_method_codes"] = CrSpecRec["magic_method_codes"] + ":DA-CR-" + crtype
                                CRSpecs.append(CrSpecRec)
                            AniSpecRecs.append(AniSpecRec)
                spec += 1
        else:
            print "skipping ", s
            spec += 1
    pmag_file = dir_path + "/" + pmag_file
    pmag.magic_write(pmag_file, PmagSpecs, "pmag_specimens")
    print "uncorrected thellier data saved in: ", pmag_file
    if anis == 1 and len(AniSpecRecs) > 0:
        anisout = dir_path + "/" + anisout
        pmag.magic_write(anisout, AniSpecRecs, "pmag_specimens")
        print "anisotropy corrected data saved in: ", anisout
    if nltrm == 1 and len(NltSpecRecs) > 0:
        nltout = dir_path + "/" + nltout
        pmag.magic_write(nltout, NltSpecRecs, "pmag_specimens")
        print "non-linear TRM corrected data saved in: ", nltout
    if crfrac != 0:
        crout = dir_path + "/" + crout
        pmag.magic_write(crout, CRSpecs, "pmag_specimens")
        print "cooling rate corrected data saved in: ", crout
Ejemplo n.º 23
0
def main():
    """
    NAME
        combine_magic.py

    DESCRIPTION
        Combines magic format files of the same type together.

    SYNTAX
        combine_magic.py [-h] [-i] -out filename -in file1 file2 ....

    OPTIONS
        -h prints help message
        -i allows interactive  entry of input and output filenames
        -F specify output file name [must come BEFORE input file names]
        -f specify input file names [ must come last]
    """ 
    #
    #  set up magic meta data type requirements
    #
    filenames=[]
    datasets=[]
    dir_path='.'
    #
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    if "-h" in sys.argv:
       print main.__doc__
       sys.exit() 
    if "-F" in sys.argv:
        ind=sys.argv.index("-F")
        output=dir_path+'/'+sys.argv[ind+1]
    if "-f" in sys.argv:
        ind=sys.argv.index("-f")
        for k in range(ind+1,len(sys.argv)):
            filenames.append(dir_path+'/'+sys.argv[k])
        for infile in filenames:
            dataset,file_type=pmag.magic_read(infile)
            print "File ",infile," read in with ",len(dataset), " records"
            for rec in dataset:
                datasets.append(rec)
    if '-i' in sys.argv:
        quit,dataset,datasets=0,[],[]
        while quit==0:
            infile=raw_input('\n\n Enter magic files for combining, <return>  when done: ')
            if infile=='':
                quit = 1
                break
            dataset,file_type=pmag.magic_read(infile)
            print "File ",infile," read in with ",len(dataset), " records"
            for rec in dataset:
                datasets.append(rec)
    #
    # collect all the keys from all the files
    #
    Recs,keys=pmag.fillkeys(datasets)
    #
    # write out the datasets into a combined file
    #
    pmag.magic_write(output,Recs,file_type)
    print "All records stored in ",output
Ejemplo n.º 24
0
def main():
    """
    NAME
        thellier_magic_redo.py

    DESCRIPTION
        Calculates paleointensity parameters for thellier-thellier type data using bounds
        stored in the "redo" file

    SYNTAX
        thellier_magic_redo [command line options]

    OPTIONS
        -h prints help message
        -usr USER:   identify user, default is ""
        -fcr CRIT, set criteria for grading
        -f IN: specify input file, default is magic_measurements.txt
        -fre REDO: specify redo file, default is "thellier_redo"
        -F OUT: specify output file, default is thellier_specimens.txt
        -leg:  attaches "Recalculated from original measurements; supercedes published results. " to comment field
        -CR PERC TYPE: apply a cooling rate correction.  
            PERC should be a percentage of original (say reduce to 90%)
            TYPE should be one of the following:
               EG (for educated guess); PS (based on pilots); TRM (based on comparison of two TRMs) 
        -Fcr  CRout: specify pmag_specimen format file for cooling rate corrected data
        -ANI: there are anisotropy data to correct thellier results
        -fan ANIFILE: specify rmag_anisotropy format file, default is rmag_anisotropy.txt 
        -Fac  ACout: specify pmag_specimen format file for anisotropy corrected data
                 default is AC_specimens.txt
        -NLT: there are non-linear trm data in the measurements file to correct thellier results
        -fnl NLTFILE: specify magic_measurments format file, default is magic_measurements.txt
        -Fnl NLTout: specify pmag_specimen format file for non-linear trm corrected data
                 default is NLT_specimens.txt
        -z use z component differenences for pTRM calculation
    """
    dir_path='.'
    critout=""
    version_num=pmag.get_version()
    field,first_save=-1,1
    spec,recnum,start,end=0,0,0,0
    frac=0
    NltRecs,PmagSpecs,AniSpecRecs,NltSpecRecs,CRSpecs=[],[],[],[],[]
    meas_file,pmag_file,mk_file="magic_measurements.txt","thellier_specimens.txt","thellier_redo"
    anis_file="rmag_anisotropy.txt"
    anisout,nltout="AC_specimens.txt","NLT_specimens.txt"
    crout="CR_specimens.txt"
    nlt_file=""
    
    comment,user="","unknown"
    anis,nltrm=0,0
    jackknife=0 # maybe in future can do jackknife
    args=sys.argv
    Zdiff=0
    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=sys.argv[ind+1]
    if "-leg" in args: comment="Recalculated from original measurements; supercedes published results. "
    if "-CR" in args:
        ind=args.index("-CR")
        frac=.01*float(sys.argv[ind+1])
        crtype=sys.argv[ind+2]
    if "-Fcr" in args:
        ind=args.index("-Fcr")
        crout=sys.argv[ind+1]
    if "-f" in args:
        ind=args.index("-f")
        meas_file=sys.argv[ind+1]
    if "-F" in args:
        ind=args.index("-F")
        pmag_file=sys.argv[ind+1]
    if "-fre" in args:
        ind=args.index("-fre")
        mk_file=args[ind+1]
    #
    #
    if "-ANI" in args:
        anis=1
        ind=args.index("-ANI")
        if "-Fac" in args:
            ind=args.index("-Fac")
            anisout=args[ind+1]
        if "-fan" in args:
            ind=args.index("-fan")
            anis_file=args[ind+1]
    #
    if "-NLT" in args:
        nltrm=1
        if "-Fnl" in args:
            ind=args.index("-Fnl")
            nltout=args[ind+1]
        if "-fnl" in args:
            ind=args.index("-fnl")
            nlt_file=args[ind+1]
    if "-z" in args: Zdiff=1
    if '-fcr' in sys.argv: 
        ind=args.index("-fcr")
        critout=sys.argv[ind+1]
#
#  start reading in data:
#
    meas_file=dir_path+"/"+meas_file
    mk_file=dir_path+"/"+mk_file
    critout=dir_path+"/"+critout
    try:
        open(critout,'rU')
        accept_keys=['specimen_int_ptrm_n','specimen_md','specimen_fvds','specimen_b_beta','specimen_dang','specimen_drats','specimen_Z']
        crit_data,file_type=pmag.magic_read(critout)
        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])
    except:
        critout="" # no acceptance criteria specified
    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()
    try:
        mk_f=open(mk_file,'rU')
    except:
        print "Bad redo file"
        sys.exit()
    mkspec=[]
    speclist=[]
    for line in mk_f.readlines():
        tmp=line.split()
        mkspec.append(tmp)
        speclist.append(tmp[0])
    if anis==1:
        anis_file=dir_path+"/"+anis_file 
        anis_data,file_type=pmag.magic_read(anis_file)
        if file_type != 'rmag_anisotropy':
            print file_type
            print file_type,"This is not a valid rmag_anisotropy file "
            sys.exit()
    if nlt_file=="":
        nlt_data=meas_data  # look for trm acquisition data in the meas_data file
    else:
        nlt_file=dir_path+"/"+nlt_file 
        nlt_data,file_type=pmag.magic_read(nlt_file)
#
# sort the specimen names and step through one by one
#
    sids=pmag.get_specs(meas_data)
# 
    print 'Processing ',len(speclist),' specimens - please wait '
    while spec < len(speclist):
        s=speclist[spec]
        recnum=0
        datablock=[]
        PmagSpecRec={}
        PmagSpecRec["er_analyst_mail_names"]=user
        PmagSpecRec["er_citation_names"]="This study"
        PmagSpecRec["magic_software_packages"]=version_num
        methcodes,inst_code=[],""
    #
    # find the data from the meas_data file for this specimen
    #
        for rec in meas_data:
            if rec["er_specimen_name"].lower()==s.lower(): 
                if "magic_instrument_codes" not in rec.keys():
                    rec["magic_instrument_codes"]="unknown"
                meths=rec["magic_method_codes"]
                for meth in meths:meth.strip()   # get rid of annoying spaces in method codes
                if "LP-PI-TRM" in meths: datablock.append(rec)
    #
    #  collect info for the PmagSpecRec dictionary
    #
        if len(datablock)>0:
            rec=datablock[0]
            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"]
            PmagSpecRec["measurement_step_unit"]="K"
            PmagSpecRec["specimen_correction"]='u'
            if "magic_instrument_codes" not in rec.keys():
                PmagSpecRec["magic_instrument_codes"]="unknown"
            else:
                PmagSpecRec["magic_instrument_codes"]=rec["magic_instrument_codes"]
            if "magic_experiment_name" not in rec.keys():
                rec["magic_experiment_name"]=""
            else:
                PmagSpecRec["magic_experiment_names"]=rec["magic_experiment_name"]
            meths=rec["magic_experiment_name"].split(":")
            for meth in meths:
                if meth.strip() not in methcodes and "LP-" in meth:methcodes.append(meth.strip())
    #
    # sort out the data into first_Z, first_I, ptrm_check, ptrm_tail
    #
            araiblock,field=pmag.sortarai(datablock,s,Zdiff)
            first_Z=araiblock[0]
            first_I=araiblock[1]
            ptrm_check=araiblock[2]
            ptrm_tail=araiblock[3]
            if len(first_I)<3 or len(first_Z)<4:
                spec+=1
                print 'skipping specimen ', s 
            else:
    #
    # get start, end
    #
                for redospec in mkspec:
                    if redospec[0]==s:
    	                b,e=float(redospec[1]),float(redospec[2])
                        break
                if e > float(first_Z[-1][0]):e=float(first_Z[-1][0])
                for recnum in range(len(first_Z)):
            	    if first_Z[recnum][0]==b:start=recnum
            	    if first_Z[recnum][0]==e:end=recnum
                nsteps=end-start
                if nsteps>2:
                    zijdblock,units=pmag.find_dmag_rec(s,meas_data)
                    pars,errcode=pmag.PintPars(araiblock,zijdblock,start,end)
                    pars['measurement_step_unit']=units
                    pars["specimen_lab_field_dc"]=field
                    pars["specimen_int"]=-1*field*pars["specimen_b"]
                    PmagSpecRec["measurement_step_min"]='%8.3e' % (pars["measurement_step_min"])
                    PmagSpecRec["measurement_step_max"]='%8.3e' % (pars["measurement_step_max"])
                    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"])
                    if pars["method_codes"]!="" and pars["method_codes"] not in methcodes: methcodes.append(pars["method_codes"])
                    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["magic_software_packages"]=version_num
                    PmagSpecRec["specimen_description"]=comment
                    if critout!="":
                        score,kill=pmag.grade(PmagSpecRec,accept)
                        Grade=""
                        if score==len(accept.keys()):Grade='A'
                        if score==len(accept.keys())-1:Grade='B'
                        if score==len(accept.keys())-2:Grade='C'
                        if score==len(accept.keys())-3:Grade='D'
                        if score<=len(accept.keys())-4:Grade='F'
                        PmagSpecRec["specimen_grade"]=Grade
                    else:
                        PmagSpecRec["specimen_grade"]=""
                    if nltrm==0 and anis==0 and frac!=0: # apply cooling rate correction
                        CrSpecRec={}
                        for key in PmagSpecRec.keys():CrSpecRec[key]=PmagSpecRec[key]
                        inten=frac*float(CrSpecRec['specimen_int'])
                        CrSpecRec["specimen_int"]='%9.4e '%(inten) # adjust specimen intensity by cooling rate correction
                        CrSpecRec['magic_method_codes'] = CrSpecRec['magic_method_codes']+':DA-CR-'+crtype
                        CrSpecRec["specimen_correction"]='c'
                        CRSpecs.append(CrSpecRec)
                    PmagSpecs.append(PmagSpecRec)
                    NltSpecRec=""
    #
    # check on non-linear TRM correction
    #
                    if nltrm==1:
    #
    # find the data from the nlt_data list for this specimen
    #
                        TRMs,Bs=[],[]
                        NltSpecRec=""
                        NltRecs=[]
                        for NltRec in nlt_data:
                            if NltRec['er_specimen_name']==PmagSpecRec["er_specimen_name"]:
                                meths=NltRec["magic_method_codes"].split(":")
                                for meth in meths:meth.strip()
                                if "LP-TRM" in meths: NltRecs.append(NltRec)
                        if len(NltRecs) > 2:
                            for NltRec in NltRecs:
                                Bs.append(float(NltRec['treatment_dc_field']))
                                TRMs.append(float(NltRec['measurement_magn_moment']))
                            NLTpars=nlt.NLtrm(Bs,TRMs,float(PmagSpecRec['specimen_int']),float(PmagSpecRec['specimen_lab_field_dc']),0) 
                            if NLTpars['banc']>0:
                                NltSpecRec={}
                                for key in PmagSpecRec.keys():
                                    NltSpecRec[key]=PmagSpecRec[key]
                                NltSpecRec['specimen_int']='%9.4e'%(NLTpars['banc'])  
                                NltSpecRec['magic_method_codes']=PmagSpecRec["magic_method_codes"]+":DA-NL"
                                NltSpecRec["specimen_correction"]='c'
                                NltSpecRec['specimen_grade']=PmagSpecRec['specimen_grade']
                                NltSpecRec["magic_software_packages"]=version_num
                                print NltSpecRec['er_specimen_name'],  ' Banc= ',float(NLTpars['banc'])*1e6
                                if anis==0 and frac!=0:
                                    CrSpecRec={}
                                    for key in NltSpecRec.keys():CrSpecRec[key]=NltSpecRec[key]
                                    inten=frac*float(CrSpecRec['specimen_int'])
                                    CrSpecRec["specimen_int"]='%9.4e '%(inten) # adjust specimen intensity by cooling rate correction
                                    CrSpecRec['magic_method_codes'] = CrSpecRec['magic_method_codes']+':DA-CR-'+crtype
                                    CRSpecs.append(CrSpecRec)
                                NltSpecRecs.append(NltSpecRec)
    #
    # check on anisotropy correction
                        if anis==1:
                            if NltSpecRec!="":  
                                Spc=NltSpecRec
                            else: # find uncorrected data
                                Spc=PmagSpecRec
                            for AniSpec in anis_data:
                                if AniSpec["er_specimen_name"]==PmagSpecRec["er_specimen_name"]:
                                    AniSpecRec=pmag.thellier_anis_corr(Spc,AniSpec)
                                    AniSpecRec['specimen_grade']=PmagSpecRec['specimen_grade']
                                    inst_codes=Spc["magic_instrument_codes"]
                                    if "magic_instrument_codes" in AniSpec.keys():
                                        if inst_codes=="unknown":
                                            inst_codes=AniSpec["magic_instrument_codes"]
                                        else:
                                            inst_codes=inst_codes+":"+AniSpec["magic_instrument_codes"]
                                    AniSpecRec["magic_instrument_codes"]=inst_codes
                                    AniSpecRec["specimen_correction"]='c'
                                    AniSpecRec["magic_software_packages"]=version_num
                                    if frac!=0:
                                        CrSpecRec={}
                                        for key in AniSpecRec.keys():CrSpecRec[key]=AniSpecRec[key]
                                        inten=frac*float(CrSpecRec['specimen_int'])
                                        CrSpecRec["specimen_int"]='%9.4e '%(inten) # adjust specimen intensity by cooling rate correction
                                        CrSpecRec['magic_method_codes'] = CrSpecRec['magic_method_codes']+':DA-CR-'+crtype
                                        CRSpecs.append(CrSpecRec)
                                    AniSpecRecs.append(AniSpecRec) 
                                    break
                    elif anis==1:
                        for AniSpec in anis_data:
                            if AniSpec["er_specimen_name"]==PmagSpecRec["er_specimen_name"]:
                                AniSpecRec=pmag.thellier_anis_corr(PmagSpecRec,AniSpec)
                                AniSpecRec['specimen_grade']=PmagSpecRec['specimen_grade']
                                inst_codes=PmagSpecRec["magic_instrument_codes"]
                                if "magic_instrument_codes" in AniSpec.keys():
                                    if inst_codes=="unknown":
                                        inst_codes=AniSpec["magic_instrument_codes"]
                                    else:
                                        inst_codes=inst_codes+":"+AniSpec["magic_instrument_codes"]
                                AniSpecRec["magic_instrument_codes"]=inst_codes
                                AniSpecRec["specimen_correction"]='c'
                                AniSpecRec["magic_software_packages"]=version_num
                                if frac!=0:
                                    CrSpecRec={}
                                    for key in AniSpecRec.keys():CrSpecRec[key]=AniSpecRec[key]
                                    inten=frac*float(CrSpecRec['specimen_int'])
                                    CrSpecRec["specimen_int"]='%9.4e '%(inten) # adjust specimen intensity by cooling rate correction
                                    CrSpecRec['magic_method_codes'] = CrSpecRec['magic_method_codes']+':DA-CR-'+crtype
                                    CRSpecs.append(CrSpecRec)
                                AniSpecRecs.append(AniSpecRec) 
                                break
                spec +=1
        else:
            print "skipping ",s
            spec+=1
    pmag_file=dir_path+'/'+pmag_file
    pmag.magic_write(pmag_file,PmagSpecs,'pmag_specimens')
    if anis==1:
        anisout=dir_path+'/'+anisout
        pmag.magic_write(anisout,AniSpecRecs,'pmag_specimens')
    if nltrm==1:
        nltout=dir_path+'/'+nltout
        pmag.magic_write(nltout,NltSpecRecs,'pmag_specimens')
    if frac!=0:
        crout=dir_path+'/'+crout
        pmag.magic_write(crout,CRSpecs,'pmag_specimens')
Ejemplo n.º 25
0
def main():
    """
    NAME
        sort_specimens.py

    DESCRIPTION
        Reads in a pmag_specimen formatted file and separates it into different components (A,B...etc.)

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

    INPUT
        takes pmag_specimens.txt formatted input file

    OPTIONS
        -h: prints help message and quits
        -f FILE: specify input file, default is 'pmag_specimens.txt'

    OUTPUT
        makes pmag_specimen formatted files with input filename plus _X_Y 
        where X is the component name and Y is s,g,t for coordinate system
    """
    dir_path='.'
    inspec="pmag_specimens.txt"
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        inspec=sys.argv[ind+1]
    basename=inspec.split('.')[:-1]
    inspec=dir_path+"/"+inspec
    ofile_base=dir_path+"/"+basename[0]
#
# read in data
#
    prior_spec_data,file_type=pmag.magic_read(inspec)
    if file_type != 'pmag_specimens':
        print  file_type, " this is not a valid pmag_specimens file"
        sys.exit()
# get list of specimens in file, components, coordinate systems available
    specs,comps,coords=[],[],[]
    for spec in prior_spec_data:
        if spec['er_specimen_name'] not in specs:specs.append(spec['er_specimen_name'])
        if 'specimen_comp_name' not in spec.keys():spec['specimen_comp_name']='A'
        if 'specimen_tilt_correction'  not in spec.keys():spec['tilt_correction']='-1' # assume specimen coordinates
        if spec['specimen_comp_name'] not in comps:comps.append(spec['specimen_comp_name'])
        if spec['specimen_tilt_correction'] not in coords:coords.append(spec['specimen_tilt_correction'])
# work on separating out components, coordinate systems by specimen
    for coord in coords:
        print coord
        for comp in comps:
            print comp
            speclist=[]
            for spec in prior_spec_data:
                if spec['specimen_tilt_correction']==coord and spec['specimen_comp_name']==comp:speclist.append(spec)
            ofile=ofile_base+'_'+coord+'_'+comp+'.txt'
            pmag.magic_write(ofile,speclist,'pmag_specimens')
            print 'coordinate system: ',coord,' component name: ',comp,' saved in ',ofile
Ejemplo n.º 26
0
def main():
    """
    NAME
        core_depthplot.py

    DESCRIPTION
        plots various measurements versus core_depth or age.  plots data flagged as 'FS-SS-C' as discrete samples.

    SYNTAX
        core_depthplot.py [command line optins]

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic_measurments format file from magi
        -fsum FILE: specify input LIMS database (IODP) core summary csv file
        -fwig FILE: specify input depth,wiggle to plot, in magic format with sample_core_depth key for depth
        -fsa FILE: specify input er_samples format file from magic for depth
        -fa FILE: specify input er_ages format file from magic for age
              NB: must have either -fsa OR -fa (not both)
        -fsp FILE sym size: specify input zeq_specimen format file from magic, sym and size
              NB: PCAs will have specified color, while fisher means will be white with specified color as the edgecolor
        -fres FILE specify input pmag_results file from magic, sym and size
        -LP [AF,T,ARM,IRM, X] step [in mT,C,mT,mT, mass/vol] to plot
        -S do not plot blanket treatment data (if this is set, you don't need the -LP)
        -sym SYM SIZE, symbol, size for continuous points (e.g., ro 5, bs 10, g^ 10 for red dot, blue square, green triangle), default is blue dot at 5 pt
        -D do not plot declination
        -M do not plot magnetization
        -log  plot magnetization  on a log scale
        -L do not connect dots with a line
        -I do not plot inclination
        -d min max [in m] depth range to plot
        -n normalize by weight in er_specimen table
        -Iex: plot the expected inc at lat - only available for results with lat info in file
        -ts TS amin amax: plot the GPTS for the time interval between amin and amax (numbers in Ma)
           TS: [ck95, gts04, gts12]
        -ds [mbsf,mcd] specify depth scale, mbsf default
        -fmt [svg, eps, pdf, png] specify output format for plot (default: svg)
        -sav save plot silently

     DEFAULTS:
         Measurements file: magic_measurements.txt
         Samples file: er_samples.txt
         NRM step
         Summary file: none
    """
    meas_file='magic_measurements.txt'
    intlist=['measurement_magnitude','measurement_magn_moment','measurement_magn_volume','measurement_magn_mass']
    samp_file='er_samples.txt'
    depth_scale='sample_core_depth'
    wt_file=''
    verbose=pmagplotlib.verbose
    width=10
    sym,size='bo',5
    Ssym,Ssize='cs',5
    method,fmt="LT-NO",'.svg'
    step=0
    pcol=3
    pel=3
    pltD,pltI,pltM,pltL,pltS=1,1,1,1,1
    logit=0
    maxInt=-1000
    minInt=1e10
    maxSuc=-1000
    minSuc=10000
    plotexp,pTS=0,0
    dir_path="."
    sum_file=""
    suc_file=""
    age_file=""
    spc_file=""
    res_file=""
    ngr_file=""
    wig_file=""
    title,location="",""
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    norm=0
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-L' in sys.argv:
        pltL=0
    if '-S' in sys.argv: pltS=0 # don't plot the bulk measurements at all
    if '-D' in sys.argv:
        pltD=0
        pcol-=1
        pel-=1
        width-=2
    if '-I' in sys.argv:
        pltI=0
        pcol-=1
        pel-=1
        width-=2
    if '-M' in sys.argv:
        pltM=0
        pcol-=1
        pel-=1
        width-=2
    if '-log' in sys.argv:logit=1
    if '-ds' in sys.argv and 'mcd' in sys.argv:depth_scale='sample_composite_depth'
    if '-sym' in sys.argv:
        ind=sys.argv.index('-sym')
        sym=sys.argv[ind+1]
        size=float(sys.argv[ind+2])
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        meas_file=sys.argv[ind+1]
    if '-fsa' in sys.argv:
        ind=sys.argv.index('-fsa')
        samp_file=sys.argv[ind+1]
        if '-fa' in sys.argv:
            print(main.__doc__)
            print('only -fsa OR -fa - not both')
            sys.exit()
    elif '-fa' in sys.argv:
        ind=sys.argv.index('-fa')
        age_file=sys.argv[ind+1]
    if '-fsp' in sys.argv:
        ind=sys.argv.index('-fsp')
        spc_file=dir_path+'/'+sys.argv[ind+1]
        spc_sym=sys.argv[ind+2]
        spc_size=float(sys.argv[ind+3])
    if '-fres' in sys.argv:
        ind=sys.argv.index('-fres')
        res_file=dir_path+'/'+sys.argv[ind+1]
        res_sym=sys.argv[ind+2]
        res_size=float(sys.argv[ind+3])
    if '-fwig' in sys.argv:
        ind=sys.argv.index('-fwig')
        wig_file=dir_path+'/'+sys.argv[ind+1]
        pcol+=1
        width+=2
    if '-fsum' in sys.argv:
        ind=sys.argv.index('-fsum')
        sum_file=dir_path+'/'+sys.argv[ind+1]
    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 '-LP' in sys.argv:
        ind=sys.argv.index('-LP')
        meth=sys.argv[ind+1]
        if meth=="AF":
            step=round(float(sys.argv[ind+2])*1e-3,6)
            method='LT-AF-Z'
        elif meth== 'T':
            step=round(float(sys.argv[ind+2])+273,6)
            method='LT-T-Z'
        elif meth== 'ARM':
            method='LT-AF-I'
            step=round(float(sys.argv[ind+2])*1e-3,6)
        elif meth== 'IRM':
            method='LT-IRM'
            step=round(float(sys.argv[ind+2])*1e-3,6)
        elif meth== 'X':
            method='LP-X'
            pcol+=1
            if sys.argv[ind+2]=='mass':
                suc_key='measurement_chi_mass'
            elif sys.argv[ind+2]=='vol':
                suc_key='measurement_chi_volume'
            else:
                print('error in susceptibility units')
                sys.exit()
        else:
           print('method not supported')
           sys.exit()
    if '-n' in sys.argv:
        ind=sys.argv.index('-n')
        wt_file=dir_path+'/'+sys.argv[ind+1]
        norm=1
    dmin,dmax=-1,-1
    if '-d' in sys.argv:
        ind=sys.argv.index('-d')
        dmin=float(sys.argv[ind+1])
        dmax=float(sys.argv[ind+2])
    if '-ts' in sys.argv:
        ind=sys.argv.index('-ts')
        ts=sys.argv[ind+1]
        amin=float(sys.argv[ind+2])
        amax=float(sys.argv[ind+3])
        pTS=1
        pcol+=1
        width+=2
    #
    #
    # get data read in
    meas_file=dir_path+'/'+meas_file
    if age_file=="":
        samp_file=dir_path+'/'+samp_file
        Samps,file_type=pmag.magic_read(samp_file)
    else:
        depth_scale='age'
        age_file=dir_path+'/'+age_file
        Samps,file_type=pmag.magic_read(age_file)
        age_unit=""
    if spc_file!="":Specs,file_type=pmag.magic_read(spc_file)
    if res_file!="":Results,file_type=pmag.magic_read(res_file)
    if norm==1:
        ErSpecs,file_type=pmag.magic_read(wt_file)
        print(len(ErSpecs), ' specimens read in from ',wt_file)
    Cores=[]
    core_depth_key="Top depth cored CSF (m)"
    if sum_file!="":
        input=open(sum_file,'r').readlines()
        if "Core Summary" in input[0]:
            headline=1
        else:
            headline=0
        keys=input[headline].replace('\n','').split(',')
        if "Core Top (m)" in keys:core_depth_key="Core Top (m)"
        if "Core Label" in keys:core_label_key="Core Label"
        if "Core label" in keys:core_label_key="Core label"
        for line in input[2:]:
            if 'TOTALS' not in line:
                CoreRec={}
                for k in range(len(keys)):CoreRec[keys[k]]=line.split(',')[k]
                Cores.append(CoreRec)
        if len(Cores)==0:
            print('no Core depth information available: import core summary file')
            sum_file=""
    Data=[]
    if depth_scale=='sample_core_depth':
        ylab="Depth (mbsf)"
    elif depth_scale=='age':
        ylab="Age"
    else:
        ylab="Depth (mcd)"
    # collect the data for plotting declination
    Depths,Decs,Incs,Ints=[],[],[],[]
    SDepths,SDecs,SIncs,SInts=[],[],[],[]
    SSucs=[]
    samples=[]
    methods,steps,m2=[],[],[]
    if pltS: # plot the bulk measurement data
        Meas,file_type=pmag.magic_read(meas_file)
        meas_key='measurement_magn_moment'
        print(len(Meas), ' measurements read in from ',meas_file)
        for m in intlist: # find the intensity key with data
            meas_data=pmag.get_dictitem(Meas,m,'','F') # get all non-blank data for this specimen
            if len(meas_data)>0:
                meas_key=m
                break
        m1=pmag.get_dictitem(Meas,'magic_method_codes',method,'has') # fish out the desired method code
        if method=='LT-T-Z':
            m2=pmag.get_dictitem(m1,'treatment_temp',str(step),'eval') # fish out the desired step
        elif 'LT-AF' in method:
            m2=pmag.get_dictitem(m1,'treatment_ac_field',str(step),'eval')
        elif 'LT-IRM' in method:
            m2=pmag.get_dictitem(m1,'treatment_dc_field',str(step),'eval')
        elif 'LT-X' in method:
            m2=pmag.get_dictitem(m1,suc_key,'','F')
        if len(m2)>0:
          for rec in m2: # fish out depths and weights
            D=pmag.get_dictitem(Samps,'er_sample_name',rec['er_sample_name'],'T')
            if not D:  # if using an age_file, you may need to sort by site
                D=pmag.get_dictitem(Samps,'er_site_name',rec['er_site_name'],'T')
            depth=pmag.get_dictitem(D,depth_scale,'','F')
            if len(depth)>0:
                if ylab=='Age': ylab=ylab+' ('+depth[0]['age_unit']+')' # get units of ages - assume they are all the same!

                rec['core_depth'] = float(depth[0][depth_scale])
                rec['magic_method_codes'] = rec['magic_method_codes']+':'+depth[0]['magic_method_codes']
                if norm==1:
                    specrecs=pmag.get_dictitem(ErSpecs,'er_specimen_name',rec['er_specimen_name'],'T')
                    specwts=pmag.get_dictitem(specrecs,'specimen_weight',"",'F')
                    if len(specwts)>0:
                        rec['specimen_weight'] = specwts[0]['specimen_weight']
                        Data.append(rec) # fish out data with core_depth and (if needed) weights
                else:
                    Data.append(rec) # fish out data with core_depth and (if needed) weights
                if title=="":
                   pieces=rec['er_sample_name'].split('-')
                   location=rec['er_location_name']
                   title=location

        SData=pmag.sort_diclist(Data,'core_depth')
        for rec in SData: # fish out bulk measurement data from desired depths
            if dmax==-1 or float(rec['core_depth'])<dmax and float(rec['core_depth'])>dmin:
                Depths.append((rec['core_depth']))
                if method=="LP-X":
                    SSucs.append(float(rec[suc_key]))
                else:
                   if pltD==1:Decs.append(float(rec['measurement_dec']))
                   if pltI==1:Incs.append(float(rec['measurement_inc']))
                   if norm==0 and pltM==1:Ints.append(float(rec[meas_key]))
                   if norm==1 and pltM==1:Ints.append(old_div(float(rec[meas_key]),float(rec['specimen_weight'])))
            if len(SSucs)>0:
                maxSuc=max(SSucs)
                minSuc=min(SSucs)
            if len(Ints)>1:
                maxInt=max(Ints)
                minInt=min(Ints)
        if len(Depths)==0:
            print('no bulk measurement data matched your request')
    SpecDepths,SpecDecs,SpecIncs=[],[],[]
    FDepths,FDecs,FIncs=[],[],[]
    if spc_file!="": # add depths to spec data
        print('spec file found')
        BFLs=pmag.get_dictitem(Specs,'magic_method_codes','DE-BFL','has')  # get all the discrete data with best fit lines
        for spec in BFLs:
            if location=="":
               location=spec['er_location_name']
            samp=pmag.get_dictitem(Samps,'er_sample_name',spec['er_sample_name'],'T')
            if len(samp)>0 and depth_scale in list(samp[0].keys()) and samp[0][depth_scale]!="":
              if ylab=='Age': ylab=ylab+' ('+samp[0]['age_unit']+')' # get units of ages - assume they are all the same!
              if dmax==-1 or float(samp[0][depth_scale])<dmax and float(samp[0][depth_scale])>dmin: # filter for depth
                SpecDepths.append(float(samp[0][depth_scale])) # fish out data with core_depth
                SpecDecs.append(float(spec['specimen_dec'])) # fish out data with core_depth
                SpecIncs.append(float(spec['specimen_inc'])) # fish out data with core_depth
            else:
                print('no core_depth found for: ',spec['er_specimen_name'])
        FMs=pmag.get_dictitem(Specs,'magic_method_codes','DE-FM','has')  # get all the discrete data with best fit lines
        for spec in FMs:
            if location=="":
               location=spec['er_location_name']
            samp=pmag.get_dictitem(Samps,'er_sample_name',spec['er_sample_name'],'T')
        if len(samp)>0 and depth_scale in list(samp[0].keys()) and samp[0][depth_scale]!="":
              if ylab=='Age': ylab=ylab+' ('+samp[0]['age_unit']+')' # get units of ages - assume they are all the same!
              if dmax==-1 or float(samp[0][depth_scale])<dmax and float(samp[0][depth_scale])>dmin: # filter for depth
                FDepths.append(float(samp[0][depth_scale]))# fish out data with core_depth
                FDecs.append(float(spec['specimen_dec'])) # fish out data with core_depth
                FIncs.append(float(spec['specimen_inc'])) # fish out data with core_depth
            else:
                print('no core_depth found for: ',spec['er_specimen_name'])
    ResDepths,ResDecs,ResIncs=[],[],[]
    if 'age' in depth_scale: # set y-key
        res_scale='average_age'
    else:
        res_scale='average_height'
    if res_file!="": #creates lists of Result Data
        for res in Results:
            meths=res['magic_method_codes'].split(":")
            if 'DE-FM' in meths:
              if dmax==-1 or float(res[res_scale])<dmax and float(res[res_scale])>dmin: # filter for depth
                ResDepths.append(float(res[res_scale])) # fish out data with core_depth
                ResDecs.append(float(res['average_dec'])) # fish out data with core_depth
                ResIncs.append(float(res['average_inc'])) # fish out data with core_depth
                Susc,Sus_depths=[],[]
    if dmin==-1:
        if len(Depths)>0: dmin,dmax=Depths[0],Depths[-1]
        if len(FDepths)>0: dmin,dmax=Depths[0],Depths[-1]
        if pltS==1 and len(SDepths)>0:
            if SDepths[0]<dmin:dmin=SDepths[0]
            if SDepths[-1]>dmax:dmax=SDepths[-1]
        if len(SpecDepths)>0:
            if min(SpecDepths)<dmin:dmin=min(SpecDepths)
            if max(SpecDepths)>dmax:dmax=max(SpecDepths)
        if len(ResDepths)>0:
            if min(ResDepths)<dmin:dmin=min(ResDepths)
            if max(ResDepths)>dmax:dmax=max(ResDepths)
    if suc_file!="":
        sucdat=open(suc_file,'r').readlines()
        keys=sucdat[0].replace('\n','').split(',') # splits on underscores
        for line in sucdat[1:]:
            SucRec={}
            for k in range(len(keys)):SucRec[keys[k]]=line.split(',')[k]
            if float(SucRec['Top Depth (m)'])<dmax and float(SucRec['Top Depth (m)'])>dmin and SucRec['Magnetic Susceptibility (80 mm)']!="":
                Susc.append(float(SucRec['Magnetic Susceptibility (80 mm)']))
                if Susc[-1]>maxSuc:maxSuc=Susc[-1]
                if Susc[-1]<minSuc:minSuc=Susc[-1]
                Sus_depths.append(float(SucRec['Top Depth (m)']))
    WIG,WIG_depths=[],[]
    if wig_file!="":
        wigdat,file_type=pmag.magic_read(wig_file)
        swigdat=pmag.sort_diclist(wigdat,depth_scale)
        keys=list(wigdat[0].keys())
        for key in keys:
            if key!=depth_scale:
                plt_key=key
                break
        for wig in swigdat:
            if float(wig[depth_scale])<dmax and float(wig[depth_scale])>dmin:
                WIG.append(float(wig[plt_key]))
                WIG_depths.append(float(wig[depth_scale]))
    tint=4.5
    plt=1
    if len(Decs)>0 and len(Depths)>0 or (len(SpecDecs)>0 and len(SpecDepths)>0) or (len(ResDecs)>0 and len(ResDepths)>0) or (len(SDecs)>0 and len(SDepths)>0) or (len(SInts)>0 and len(SDepths)>0) or (len(SIncs)>0 and len(SDepths)>0):
        pylab.figure(1,figsize=(width,8))
        version_num=pmag.get_version()
        pylab.figtext(.02,.01,version_num)
        if pltD==1:
            ax=pylab.subplot(1,pcol,plt)
            if pltL==1:
                pylab.plot(Decs,Depths,'k')
            if len(Decs)>0:
                pylab.plot(Decs,Depths,sym,markersize=size)
            if len(Decs)==0 and pltL==1 and len(SDecs)>0:
                pylab.plot(SDecs,SDepths,'k')
            if len(SDecs)>0:
                pylab.plot(SDecs,SDepths,Ssym,markersize=Ssize)
            if spc_file!="":
                pylab.plot(SpecDecs,SpecDepths,spc_sym,markersize=spc_size)
            if spc_file!="" and len(FDepths)>0:
                pylab.scatter(FDecs,FDepths,marker=spc_sym[-1],edgecolor=spc_sym[0],facecolor='white',s=spc_size**2)
            if res_file!="":
                pylab.plot(ResDecs,ResDepths,res_sym,markersize=res_size)
            if sum_file!="":
                for core in Cores:
                     depth=float(core[core_depth_key])
                     if depth>dmin and depth<dmax:
                        pylab.plot([0,360.],[depth,depth],'b--')
                        if pel==plt:pylab.text(360,depth+tint,core[core_label_key])
            if pel==plt:
                pylab.axis([0,400,dmax,dmin])
            else:
                pylab.axis([0,360.,dmax,dmin])
            pylab.xlabel('Declination')
            pylab.ylabel(ylab)
            plt+=1
            pmagplotlib.delticks(ax) # dec xticks are too crowded otherwise
    if pltI==1:
            pylab.subplot(1,pcol,plt)
            if pltL==1:pylab.plot(Incs,Depths,'k')
            if len(Incs)>0:pylab.plot(Incs,Depths,sym,markersize=size)
            if len(Incs)==0 and pltL==1 and len(SIncs)>0:pylab.plot(SIncs,SDepths,'k')
            if len(SIncs)>0:pylab.plot(SIncs,SDepths,Ssym,markersize=Ssize)
            if spc_file!="" and len(SpecDepths)>0:pylab.plot(SpecIncs,SpecDepths,spc_sym,markersize=spc_size)
            if spc_file!="" and len(FDepths)>0:
                pylab.scatter(FIncs,FDepths,marker=spc_sym[-1],edgecolor=spc_sym[0],facecolor='white',s=spc_size**2)
            if res_file!="":pylab.plot(ResIncs,ResDepths,res_sym,markersize=res_size)
            if sum_file!="":
                for core in Cores:
                     depth=float(core[core_depth_key])
                     if depth>dmin and depth<dmax:
                         if pel==plt:pylab.text(90,depth+tint,core[core_label_key])
                         pylab.plot([-90,90],[depth,depth],'b--')
            pylab.plot([0,0],[dmax,dmin],'k-')
            if pel==plt:
                pylab.axis([-90,110,dmax,dmin])
            else:
                pylab.axis([-90,90,dmax,dmin])
            pylab.xlabel('Inclination')
            pylab.ylabel('')
            plt+=1
    if pltM==1 and len(Ints)>0 or len(SInts)>0:
            pylab.subplot(1,pcol,plt)
            for pow in range(-10,10):
                if maxInt*10**pow>1:break
            if logit==0:
                for k in range(len(Ints)):
                    Ints[k]=Ints[k]*10**pow
                for k in range(len(SInts)):
                    SInts[k]=SInts[k]*10**pow
                if pltL==1 and len(Ints)>0: pylab.plot(Ints,Depths,'k')
                if len(Ints)>0:pylab.plot(Ints,Depths,sym,markersize=size)
                if len(Ints)==0 and pltL==1 and len(SInts)>0:pylab.plot(SInts,SDepths,'k-')
                if len(SInts)>0:pylab.plot(SInts,SDepths,Ssym,markersize=Ssize)
                if sum_file!="":
                    for core in Cores:
                         depth=float(core[core_depth_key])
                         pylab.plot([0,maxInt*10**pow+.1],[depth,depth],'b--')
                         if depth>dmin and depth<dmax:pylab.text(maxInt*10**pow-.2*maxInt*10**pow,depth+tint,core[core_label_key])
                pylab.axis([0,maxInt*10**pow+.1,dmax,dmin])
                if norm==0:
                    pylab.xlabel('%s %i %s'%('Intensity (10^-',pow,' Am^2)'))
                else:
                    pylab.xlabel('%s %i %s'%('Intensity (10^-',pow,' Am^2/kg)'))
            else:
                if pltL==1: pylab.semilogx(Ints,Depths,'k')
                if len(Ints)>0:pylab.semilogx(Ints,Depths,sym,markersize=size)
                if len(Ints)==0 and pltL==1 and len(SInts)>0:pylab.semilogx(SInts,SDepths,'k')
                if len(Ints)==0 and pltL==1 and len(SInts)>0:pylab.semilogx(SInts,SDepths,'k')
                if len(SInts)>0:pylab.semilogx(SInts,SDepths,Ssym,markersize=Ssize)
                if sum_file!="":
                    for core in Cores:
                         depth=float(core[core_depth_key])
                         pylab.semilogx([minInt,maxInt],[depth,depth],'b--')
                         if depth>dmin and depth<dmax:pylab.text(maxInt-.2*maxInt,depth+tint,core[core_label_key])
                pylab.axis([0,maxInt,dmax,dmin])
                if norm==0:
                    pylab.xlabel('Intensity (Am^2)')
                else:
                    pylab.xlabel('Intensity (Am^2/kg)')
            plt+=1
    if suc_file!="" or len(SSucs)>0:
            pylab.subplot(1,pcol,plt)
            if len(Susc)>0:
                if pltL==1:pylab.plot(Susc,Sus_depths,'k')
                if logit==0:pylab.plot(Susc,Sus_depths,sym,markersize=size)
                if logit==1:pylab.semilogx(Susc,Sus_depths,sym,markersize=size)
            if len(SSucs)>0:
                if logit==0:pylab.plot(SSucs,SDepths,sym,markersize=size)
                if logit==1:pylab.semilogx(SSucs,SDepths,sym,markersize=size)
            if sum_file!="":
                for core in Cores:
                     depth=float(core[core_depth_key])
                     if logit==0:pylab.plot([minSuc,maxSuc],[depth,depth],'b--')
                     if logit==1:pylab.semilogx([minSuc,maxSuc],[depth,depth],'b--')
            pylab.axis([minSuc,maxSuc,dmax,dmin])
            pylab.xlabel('Susceptibility')
            plt+=1
    if wig_file!="":
            pylab.subplot(1,pcol,plt)
            pylab.plot(WIG,WIG_depths,'k')
            if sum_file!="":
                for core in Cores:
                     depth=float(core[core_depth_key])
                     pylab.plot([WIG[0],WIG[-1]],[depth,depth],'b--')
            pylab.axis([min(WIG),max(WIG),dmax,dmin])
            pylab.xlabel(plt_key)
            plt+=1
    if pTS==1:
            ax1=pylab.subplot(1,pcol,plt)
            ax1.axis([-.25,1.5,amax,amin])
            plt+=1
            TS,Chrons=pmag.get_ts(ts)
            X,Y,Y2=[0,1],[],[]
            cnt=0
            if amin<TS[1]: # in the Brunhes
                Y=[amin,amin] # minimum age
                Y1=[TS[1],TS[1]] # age of the B/M boundary
                ax1.fill_between(X,Y,Y1,facecolor='black') # color in Brunhes, black
            for d in TS[1:]:
                pol=cnt%2
                cnt+=1
                if d<=amax and d>=amin:
                   ind=TS.index(d)
                   Y=[TS[ind],TS[ind]]
                   Y1=[TS[ind+1],TS[ind+1]]
                   if pol: ax1.fill_between(X,Y,Y1,facecolor='black') # fill in every other time
            ax1.plot([0,1,1,0,0],[amin,amin,amax,amax,amin],'k-')
            ax2=ax1.twinx()
            pylab.ylabel("Age (Ma): "+ts)
            for k in range(len(Chrons)-1):
                c=Chrons[k]
                cnext=Chrons[k+1]
                d=cnext[1]-old_div((cnext[1]-c[1]),3.)
                if d>=amin and d<amax:
                    ax2.plot([1,1.5],[c[1],c[1]],'k-') # make the Chron boundary tick
                    ax2.text(1.05,d,c[0]) #
            ax2.axis([-.25,1.5,amax,amin])
    figname=location+'_m:_'+method+'_core-depthplot'+fmt
    pylab.title(location)
    if verbose:
        pylab.draw()
        ans=input("S[a]ve plot? ")
        if ans=='a':
            pylab.savefig(figname)
            print('Plot saved as ',figname)
    elif plots:
        pylab.savefig(figname)
        print('Plot saved as ',figname)
    sys.exit()
Ejemplo n.º 27
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
Ejemplo n.º 28
0
def main():
    """
    NAME
        lnp_magic.py

    DESCRIPTION
       makes equal area projections site by site
         from pmag_specimen formatted file with
         Fisher confidence ellipse using McFadden and McElhinny (1988)
         technique for combining lines and planes

    SYNTAX
        lnp_magic [command line options]

    INPUT
       takes magic formatted pmag_specimens file
    
    OUPUT
        prints site_name n_lines n_planes K alpha95 dec inc R

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is 'pmag_specimens.txt'
        -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted
                default is specimen
        -fmt [svg,png,jpg] format for plots, default is svg
        -P: do not plot
        -F FILE, specify output file of dec, inc, alpha95 data for plotting with plotdi_a and plotdi_e
        -exc use criteria in pmag_criteria.txt
    """
    dir_path='.'
    FIG={} # plot dictionary
    FIG['eqarea']=1 # eqarea is figure 1
    in_file,plot_key,coord='pmag_specimens.txt','er_site_name',"-1"
    out_file=""
    fmt,plot='svg',1
    Crits=""
    M,N=180.,1
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    if '-f' in sys.argv:
        ind=sys.argv.index("-f")
        in_file=sys.argv[ind+1]
    if '-exc' in sys.argv:
        Crits,file_type=pmag.magic_read(dir_path+'/pmag_criteria.txt')
        for crit in Crits:
            if crit['pmag_criteria_code']=='DE-SPEC':
                M=float(crit['specimen_mad'])
                N=float(crit['specimen_n'])
    if '-F' in sys.argv:
        ind=sys.argv.index("-F")
        out_file=sys.argv[ind+1]
        out=open(dir_path+'/'+out_file,'w')
    if '-crd' in sys.argv:
        ind=sys.argv.index("-crd")
        crd=sys.argv[ind+1]
        if crd=='s':coord="-1"
        if crd=='g':coord="0"
        if crd=='t':coord="100"
    if '-fmt' in sys.argv:
        ind=sys.argv.index("-fmt")
        fmt=sys.argv[ind+1]
    if '-P' in sys.argv:plot=0
# 
    in_file=dir_path+'/'+in_file
    Specs,file_type=pmag.magic_read(in_file)
    sitelist=[]
    for rec in Specs:
        if rec['er_site_name'] not in sitelist: sitelist.append(rec['er_site_name'])
    sitelist.sort()
    if plot==1:
        import pmagplotlib
        EQ={} 
        EQ['eqarea']=1
        pmagplotlib.plot_init(EQ['eqarea'],4,4)
    for site in sitelist:
        print site
        data=[]
        for spec in Specs:
           if 'specimen_tilt_correction' not in spec.keys():spec['specimen_tilt_correction']='-1' # assume unoriented
           if spec['er_site_name']==site:
              if 'specimen_mad' not in spec.keys() or spec['specimen_mad']=="":
                   if 'specimen_alpha95' in spec.keys() and spec['specimen_alpha95']!="":
                       spec['specimen_mad']=spec['specimen_alpha95']
                   else:
                       spec['specimen_mad']='180'
              if spec['specimen_tilt_correction']==coord and float(spec['specimen_mad'])<=M and float(spec['specimen_n'])>=N: 
                   rec={}
                   for key in spec.keys():rec[key]=spec[key]
                   rec["dec"]=float(spec['specimen_dec'])
                   rec["inc"]=float(spec['specimen_inc'])
                   rec["tilt_correction"]=spec['specimen_tilt_correction']
                   data.append(rec)
        if len(data)>2:
            fpars=pmag.dolnp(data,'specimen_direction_type')
            print "Site lines planes  kappa   a95   dec   inc"
            print site, fpars["n_lines"], fpars["n_planes"], fpars["K"], fpars["alpha95"], fpars["dec"], fpars["inc"], fpars["R"]
            if out_file!="":
                if float(fpars["alpha95"])<=acutoff and float(fpars["K"])>=kcutoff:
                    out.write('%s %s %s\n'%(fpars["dec"],fpars['inc'],fpars['alpha95']))
            print '% tilt correction: ',coord
            if plot==1:
                pmagplotlib.plotLNP(EQ['eqarea'],site,data,fpars,'specimen_direction_type')
                ans=raw_input("s[a]ve plot, [q]uit, <return> to continue:\n ")
                if ans=="a":
                    files={}
                    files['eqarea']=site+'_'+crd+'_'+'eqarea'+'.'+fmt
                    pmagplotlib.saveP(EQ,files)
                if ans=="q": sys.exit()
        else:
            print 'skipping site - not enough data with specified coordinate system'
Ejemplo n.º 29
0
def main():
    """
    NAME
        MsT_magic.py
 
    DESCRIPTION
        converts MsT data (T,M) to magic_measurements format files

    SYNTAX
        MsT_magic.py [command line options]

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

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

    DESCRIPTION
        makes a map of vgps and a95/dp,dm for site means in a pmag_results table
 
    SYNTAX
        vgpmap_magic.py [command line options]

    OPTIONS
        -h prints help and quits
        -eye  ELAT ELON [specify eyeball location], default is 90., 0.
        -f FILE pmag_results format file, [default is pmag_results.txt] 
        -res [c,l,i,h] specify resolution (crude, low, intermediate, high]
        -prj PROJ,  specify one of the following:
             ortho = orthographic
             lcc = lambert conformal
             moll = molweide
             merc = mercator
        -sym SYM SIZE: choose a symbol and size, examples: 
            ro 5 : small red circles
            bs 10 : intermediate blue squares
            g^ 20 : large green triangles
        -ell  plot dp/dm or a95 ellipses
        -rev RSYM RSIZE : flip reverse poles to normal antipode 
        -S:  plot antipodes of all poles
        -age : plot the ages next to the poles
        -crd [g,t] : choose coordinate system, default is to plot all site VGPs
    
    DEFAULTS
        FILE: pmag_results.txt
        res:  c
        prj: mercator 
        ELAT,ELON = 0,0
        SYM SIZE: ro 8
        RSYM RSIZE: g^ 8
    
    """
    dir_path='.'
    res,ages='c',0
    proj='npstere'
    results_file='pmag_results.txt'
    ell,flip=0,0
    lat_0,lon_0=90.,0.
    fmt='pdf'
    sym,size='ro',8
    rsym,rsize='g^',8
    anti=0
    coord=""
    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 '-S' in sys.argv:anti=1
    if '-res' in sys.argv:
        ind = sys.argv.index('-res')
        res=sys.argv[ind+1]
    if '-prj' in sys.argv:
        ind = sys.argv.index('-prj')
        proj=sys.argv[ind+1]
    if '-rev' in sys.argv: 
        flip=1
        ind = sys.argv.index('-rev')
        rsym=(sys.argv[ind+1])
        rsize=int(sys.argv[ind+2])
    if '-sym' in sys.argv:
        ind = sys.argv.index('-sym')
        sym=(sys.argv[ind+1])
        size=int(sys.argv[ind+2])
    if '-eye' in sys.argv:
        ind = sys.argv.index('-eye')
        lat_0=float(sys.argv[ind+1])
        lon_0=float(sys.argv[ind+2])
    if '-ell' in sys.argv: ell=1
    if '-age' in sys.argv: ages=1
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        results_file=sys.argv[ind+1]
    if '-crd' in sys.argv:
        ind = sys.argv.index('-crd')
        crd=sys.argv[ind+1]
        if crd=='g':coord='0'
        if crd=='t':coord='100'
    results_file=dir_path+'/'+results_file
    data,file_type=pmag.magic_read(results_file)
    if file_type!='pmag_results':
        print "bad results file"
        sys.exit()
    FIG={'map':1}
    pmagplotlib.plot_init(FIG['map'],6,6)
    # read in er_sites file
    lats,lons,dp,dm,a95=[],[],[],[],[]
    Pars=[]
    dates,rlats,rlons=[],[],[]
    Results=[]
    for rec in data:
        if 'pmag_result_name' in rec.keys():
            name=rec['pmag_result_name'].split()
            if 'Site' in name:
                if coord=="" or rec['tilt_correction']==coord:Results.append(rec)
        elif coord=="" or rec['tilt_correction']==coord:Results.append(rec)
    for rec in Results:
        if 'vgp_lat' in rec.keys() and rec['vgp_lat']!="" and  'vgp_lon' in rec.keys() and rec['vgp_lon']!="":
            if 'average_age' in rec.keys() and rec['average_age']!="" and ages==1:
                dates.append(rec['average_age'])
            lat=float(rec['vgp_lat'])
            lon=float(rec['vgp_lon'])
            if flip==0:
                lats.append(lat)
                lons.append(lon)
            elif flip==1:
                if lat<0:
                    rlats.append(-lat)
                    lon=lon+180.
                    if lon>360:lon=lon-360.
                    rlons.append(lon)
                else:
                    lats.append(lat)
                    lons.append(lon)
            elif anti==1:
                lats.append(-lat)
                lon=lon+180.
                if lon>360:lon=lon-360.
                lons.append(lon)
            ppars=[]
            ppars.append(lon)
            ppars.append(lat)
            ell1,ell2="",""
            if 'vgp_dm' in rec.keys() and rec['vgp_dm']!="":ell1=float(rec['vgp_dm'])
            if 'vgp_dp' in rec.keys() and rec['vgp_dp']!="":ell2=float(rec['vgp_dp'])
            if 'vgp_alpha95' in rec.keys() and rec['vgp_alpha95']!="":ell1,ell2=float(rec['vgp_alpha95']),float(rec['vgp_alpha95'])
            if ell1!="" and ell2!="":
                ppars=[]
                ppars.append(lons[-1])
                ppars.append(lats[-1])
                ppars.append(ell1)
                ppars.append(lons[-1])
                isign=abs(lats[-1])/lats[-1]
                ppars.append(lats[-1]-isign*90.)
                ppars.append(ell2)
                ppars.append(lons[-1]+90.)
                ppars.append(0.)
                Pars.append(ppars)
    Opts={'latmin':-90,'latmax':90,'lonmin':0.,'lonmax':360.,'lat_0':lat_0,'lon_0':lon_0,'proj':proj,'sym':'bs','symsize':3,'pltgrid':0,'res':res,'boundinglat':0.}
    Opts['details']={'coasts':1,'rivers':0, 'states':0, 'countries':0,'ocean':1}
    pmagplotlib.plotMAP(FIG['map'],[90.],[0.],Opts) # make the base map with a blue triangle at the pole`
    Opts['details']={'coasts':0,'rivers':0, 'states':0, 'countries':0,'ocean':0}
    Opts['pltgrid']=-1
    Opts['sym']=sym
    Opts['symsize']=size
    if len(dates)>0:Opts['names']=dates
    if len(lats)>0:pmagplotlib.plotMAP(FIG['map'],lats,lons,Opts) # add the lats and lons of the poles
    Opts['names']=[]
    if len(rlats)>0:
        Opts['sym']=rsym
        Opts['symsize']=rsize
        pmagplotlib.plotMAP(FIG['map'],rlats,rlons,Opts) # add the lats and lons of the poles
    pmagplotlib.drawFIGS(FIG)
    if ell==1: # add ellipses if desired.
        Opts['details']={'coasts':0,'rivers':0, 'states':0, 'countries':0,'ocean':0}
        Opts['pltgrid']=-1 # turn off meridian replotting
        Opts['symsize']=2
        Opts['sym']='g-'
        for ppars in Pars:
            if ppars[2]!=0:
                PTS=pmagplotlib.plotELL(FIG['map'],ppars,'g.',0,0)
                elats,elons=[],[]
                for pt in PTS:
                    elons.append(pt[0])
                    elats.append(pt[1])
                pmagplotlib.plotMAP(FIG['map'],elats,elons,Opts) # make the base map with a blue triangle at the pole`
                pmagplotlib.drawFIGS(FIG)
    files={}
    for key in FIG.keys():
        files[key]='VGP_map'+'.'+fmt
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='VGP Map'
        FIG = pmagplotlib.addBorders(FIG,titles,black,purple)
        pmagplotlib.saveP(FIG,files)
    else:
        ans=raw_input(" S[a]ve to save plot, Return to quit:  ")
        if ans=="a":
            pmagplotlib.saveP(FIG,files)
        else:
            print "Good bye"
            sys.exit()
Ejemplo n.º 31
0
def main():
    """
    NAME
       plotxy_magic.py

    DESCRIPTION
       Makes simple X,Y plots 

    INPUT FORMAT
       Any MagIC formatted file

    SYNTAX
       plotxy_magic.py [command line options] 

    OPTIONS
        -h prints this help message
        -f FILE to set file name on command rec 
        -c col1 col2 specify columns names to plot
        -sym SYM SIZE specify symbol and size to plot: default is red dots
        -S   don't plot symbols
        -xlab XLAB
        -ylab YLAB
        -l  connect symbols with lines
        -b xmin xmax ymin ymax, sets bounds
#        -b [key:max:min,key:max:min,etc.] leave or min blank for no cutoff
    """
    col1, col2 = 0, 1
    sym, size = "ro", 20
    xlab, ylab = "", ""
    lines = 0
    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]
    else:
        "-f option is a required field"
        print main.__doc__
        sys.exit()
    if "-c" in sys.argv:
        ind = sys.argv.index("-c")
        col1 = sys.argv[ind + 1]
        col2 = sys.argv[ind + 2]
    else:
        "Column headers a required field"
        print main.__doc__
        sys.exit()
    if "-xlab" in sys.argv:
        ind = sys.argv.index("-xlab")
        xlab = sys.argv[ind + 1]
    if "-ylab" in sys.argv:
        ind = sys.argv.index("-ylab")
        ylab = sys.argv[ind + 1]
    #    if '-b' in sys.argv:
    #        ind=sys.argv.index('-b')
    #        bounds=sys.argv[ind+1].split(',')
    if "-b" in sys.argv:
        ind = sys.argv.index("-b")
        xmin = float(sys.argv[ind + 1])
        xmax = float(sys.argv[ind + 2])
        ymin = float(sys.argv[ind + 3])
        ymax = float(sys.argv[ind + 4])
    if "-sym" in sys.argv:
        ind = sys.argv.index("-sym")
        sym = sys.argv[ind + 1]
        size = int(sys.argv[ind + 2])
    if "-l" in sys.argv:
        lines = 1
    if "-S" in sys.argv:
        sym = ""
    X, Y = [], []
    data, file_type = pmag.magic_read(file)
    print file_type
    for rec in data:
        if col1 not in rec.keys() or col2 not in rec.keys():
            print col1, " and/or ", col2, " not in file headers"
            print "try again"
            sys.exit()
        if rec[col1] != "" and rec[col2] != "":
            skip = 0
            if "-crit" in sys.argv:
                for crit in bounds:
                    crits = crit.split(":")
                    crit_key = crits[0]
                    crit_min = crits[1]
                    crit_max = crits[2]
                    if rec[crit_key] == "":
                        skip = 1
                    else:
                        if crit_min != "" and float(rec[crit_key]) < float(crit_min):
                            skip = 1
                        if crit_max != "" and float(rec[crit_key]) > float(crit_min):
                            skip = 1
            if skip == 0:
                X.append(float(rec[col1]))
                Y.append(float(rec[col2]))
    if len(X) == 0:
        print col1, " and/or ", col2, " have no data "
        print "try again"
        sys.exit()
    else:
        print len(X), " data points"
    if sym != "":
        pylab.scatter(X, Y, c=sym[0], marker=sym[1], s=size)
    if xlab != "":
        pylab.xlabel(xlab)
    if ylab != "":
        pylab.ylabel(ylab)
    if lines == 1:
        pylab.plot(X, Y, "k-")
    if "-b" in sys.argv:
        pylab.axis([xmin, xmax, ymin, ymax])
    pylab.draw()
    ans = raw_input("Press return to quit  ")
    sys.exit()