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

    DESCRIPTION
       plots intensity decay curves for demagnetization experiments

    SYNTAX
        dmag_magic -h [command line options]

    INPUT 
       takes magic formatted magic_measurements.txt files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: magic_measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot, default is by location
        -LT [AF,T,M]: specify lab treatment type, default AF
        -XLP [PI]: exclude specific  lab protocols (for example, method codes like LP-PI)
        -N do not normalize by NRM magnetization
        -sav save plots silently and quit
        -fmt [svg,jpg,png,pdf] set figure format [default is svg]
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    FIG={} # plot dictionary
    FIG['demag']=1 # demag is figure 1
    in_file,plot_key,LT='magic_measurements.txt','er_location_name',"LT-AF-Z"
    XLP=""
    norm=1
    LT='LT-AF-Z'
    units,dmag_key='T','treatment_ac_field'
    plot=0
    fmt='svg'
    if len(sys.argv)>1:
        if '-h' in sys.argv:
            print main.__doc__
            sys.exit()
        if '-N' in sys.argv: norm=0
        if '-sav' in sys.argv: 
            plot=1
        if '-f' in sys.argv:
            ind=sys.argv.index("-f")
            in_file=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')
            plot_by=sys.argv[ind+1]
            if plot_by=='sit':plot_key='er_site_name'
            if plot_by=='sam':plot_key='er_sample_name'
            if plot_by=='spc':plot_key='er_specimen_name'
        if '-XLP' in sys.argv:
            ind=sys.argv.index("-XLP")
            XLP=sys.argv[ind+1] # get lab protocol for excluding
        if '-LT' in sys.argv:
            ind=sys.argv.index("-LT")
            LT='LT-'+sys.argv[ind+1]+'-Z' # get lab treatment for plotting
            if  LT=='LT-T-Z':
                units,dmag_key='K','treatment_temp'
            elif  LT=='LT-AF-Z':
                units,dmag_key='T','treatment_ac_field'
            elif  LT=='LT-M-Z':
                units,dmag_key='J','treatment_mw_energy'
            else:
                units='U'
    data,file_type=pmag.magic_read(in_file)
    sids=pmag.get_specs(data)
    pmagplotlib.plot_init(FIG['demag'],5,5)
    print len(data),' records read from ',in_file
    #
    #
    # find desired intensity data
    #
    #
    plotlist,intlist=[],['measurement_magnitude','measurement_magn_moment','measurement_magn_volume','measurement_magn_mass']
    IntMeths=[]
    FixData=[]
    for  rec in data:
        meths=[]
        methcodes=rec['magic_method_codes'].split(':')
        for meth in methcodes:meths.append(meth.strip())
        for key in rec.keys():
            if key in intlist and rec[key]!="":
                if key not in IntMeths:IntMeths.append(key)
                if rec[plot_key] not in plotlist and LT in meths: plotlist.append(rec[plot_key])
                if 'measurement_flag' not in rec.keys():rec['measurement_flag']='g'
                FixData.append(rec)
        plotlist.sort()
    if len(IntMeths)==0:
        print 'No intensity information found'
        sys.exit()
    data=FixData
    int_key=IntMeths[0] # plot first intensity method found - normalized to initial value anyway - doesn't matter which used
    for plt in plotlist:
        if plot==0: print plt,'plotting by: ',plot_key
        PLTblock=pmag.get_dictitem(data,plot_key,plt,'T') # fish out all the data for this type of plot
        PLTblock=pmag.get_dictitem(PLTblock,'magic_method_codes',LT,'has') # fish out all the dmag for this experiment type
        PLTblock=pmag.get_dictitem(PLTblock,int_key,'','F') # get all with this intensity key non-blank
        if XLP!="":PLTblock=pmag.get_dictitem(PLTblock,'magic_method_codes',XLP,'not') # reject data with XLP in method_code
        if len(PLTblock)>2:
            title=PLTblock[0][plot_key]
            spcs=[]
            for rec in PLTblock:
                if rec['er_specimen_name'] not in spcs:spcs.append(rec['er_specimen_name'])
            for spc in spcs:
                SPCblock=pmag.get_dictitem(PLTblock,'er_specimen_name',spc,'T') # plot specimen by specimen
                INTblock=[]
                for rec in SPCblock:
                    INTblock.append([float(rec[dmag_key]),0,0,float(rec[int_key]),1,rec['measurement_flag']])
                if len(INTblock)>2:
                    pmagplotlib.plotMT(FIG['demag'],INTblock,title,0,units,norm)
            if plot==1:
                files={}
                for key in FIG.keys():
                    files[key]=title+'_'+LT+'.'+fmt
                pmagplotlib.saveP(FIG,files) 
                sys.exit()
            else:
                pmagplotlib.drawFIGS(FIG)
                ans=raw_input(" S[a]ve to save plot, [q]uit,  Return to continue:  ")
                if ans=='q':sys.exit()
                if ans=="a": 
                    files={}
                    for key in FIG.keys():
                        files[key]=title+'_'+LT+'.svg' 
                    pmagplotlib.saveP(FIG,files) 
            pmagplotlib.clearFIG(FIG['demag'])
Exemplo n.º 2
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 '-dpi' in sys.argv:
        ind = sys.argv.index('-dpi')
        dpi = '.' + sys.argv[ind + 1]
    else:
        dpi = 100
    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:
                # make sure all new records have same set of keys
                PmagSpecRec[key] = ""
        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.plot_arai_zij(AZD, araiblock, zijdblock, s,
                                          units[0])
                if verbose:
                    pmagplotlib.draw_figs(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
                    # find which type of intensity
                    while mkey == "" and k < len(Mkeys) - 1:
                        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:
                            # strip off potential nasty spaces
                            meth.replace(" ", "")
                        if 'LT-T-I' in meths and Tnorm == "":  # found first total TRM
                            # normalize by total TRM
                            Tnorm = float(tdrec[mkey])
                            # put in the zero step
                            tdsblock.append([273, zijdblock[0][3] / Tnorm, 1.])
                        # found a LP-TRM-TD demag step, now need complementary LT-T-Z from zijdblock
                        if 'LT-T-Z' in meths and Tnorm != "":
                            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.plot_tds(AZD['TDS'], tdsblock,
                                             s + ':LP-PI-TDS:')
                        if verbose:
                            pmagplotlib(draw_figs(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'
                                # put in CurrRec, take out of PriorRecs
                                del PriorRecs[k]
                                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.plot_b(AZD, araiblock,
                                                       zijdblock, pars)
                                    if verbose:
                                        pmagplotlib.draw_figs(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'])
                                            )
                                        # calculate best fit parameters through TRM acquisition data, and get new banc
                                        NLpars = nlt.NLtrm(
                                            Bs, TRMs, best, blab, 0)
                                        Mp, Bp = [], []
                                        for k in range(int(max(Bs) * 1e6)):
                                            Bp.append(float(k) * 1e-6)
                                            # predicted NRM for this field
                                            npred = nlt.TRM(
                                                Bp[-1], NLpars['xopt'][0],
                                                NLpars['xopt'][1])
                                            Mp.append(npred)
                                        pmagplotlib.plot_trm(
                                            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.draw_figs(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.plot_b(AZD, araiblock, zijdblock, pars)
                        if verbose:
                            pmagplotlib.draw_figs(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']))
                            # calculate best fit parameters through TRM acquisition data, and get new banc
                            NLpars = nlt.NLtrm(Bs, TRMs, best, blab, 0)
                            #
                            Mp, Bp = [], []
                            for k in range(int(max(Bs) * 1e6)):
                                Bp.append(float(k) * 1e-6)
                                # predicted NRM for this field
                                npred = nlt.TRM(Bp[-1], NLpars['xopt'][0],
                                                NLpars['xopt'][1])
                    files = {}
                    for key in AZD.keys():
                        files[key] = s + '_' + key + fmt
                    pmagplotlib.save_plots(AZD, files, dpi=dpi)
                    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 = input('Return for next specimen \n')
                        if ans == "":
                            specimen += 1
                        if ans == "d":
                            save_redo(PriorRecs, inspec)
                            CurrRec = []
                            pmagplotlib.plot_arai_zij(AZD, araiblock,
                                                      zijdblock, s, units[0])
                            if verbose:
                                pmagplotlib.draw_figs(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.save_plots(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 = 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 = 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 = input(
                                    'Enter index of first point for calculation: ['
                                    + str(start) + ']  ')
                                try:
                                    start = int(answer)
                                    answer = 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'
                            # this is redundant, but helpful - won't be imported
                            PmagSpecRec["direction_type"] = 'l'
                            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.plot_arai_zij(AZD, araiblock,
                                                      zijdblock, s, units[0])
                            pmagplotlib.plot_b(AZD, araiblock, zijdblock, pars)
                            if verbose:
                                pmagplotlib.draw_figs(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']))
                                # calculate best fit parameters through TRM acquisition data, and get new banc
                                NLpars = nlt.NLtrm(Bs, TRMs, best, blab, 0)
                                Mp, Bp = [], []
                                for k in range(int(max(Bs) * 1e6)):
                                    Bp.append(float(k) * 1e-6)
                                    # predicted NRM for this field
                                    npred = nlt.TRM(Bp[-1], NLpars['xopt'][0],
                                                    NLpars['xopt'][1])
                                    Mp.append(npred)
                                pmagplotlib.plot_trm(
                                    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.draw_figs(AZD)
                            pars["specimen_lab_field_dc"] = field
                            pars["specimen_int"] = -1 * field * pars[
                                "specimen_b"]
                            pars, kill = pmag.scoreit(pars, PmagSpecRec,
                                                      accept, '', verbose)
                            saveit = input(
                                "Save this interpretation? [y]/n \n")
                            if saveit != 'n':
                                # put back an interpretation
                                PriorRecs.append(PmagSpecRec)
                                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.add_borders(
                                AZD, titles, black, purple)
                        pmagplotlib.save_plots(AZD, files, dpi=dpi)
    #                   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 = input(" Save last plot? 1/[0] ")
        if ans == "1":
            if fmt != ".pmag":
                files = {}
                for key in AZD.keys():
                    files[key] = s + '_' + key + fmt
                pmagplotlib.save_plots(AZD, files, dpi=dpi)
        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")
Exemplo n.º 3
0
def main():
    """
    NAME
        lowrie_magic.py

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

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

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

    SYNTAX
        hysteresis_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f: specify input file, default is agm_measurements.txt
        -F: specify specimens.txt output file
        -P: do not make the plots
        -spc SPEC: specify specimen name to plot and quit
        -sav save all plots and quit
        -fmt [png,svg,eps,jpg]
    """
    args=sys.argv
    PLT=1
    plots=0
    fmt=pmag.get_named_arg_from_sys('-fmt','svg')
    dir_path=pmag.get_named_arg_from_sys('-WD','.')
    dir_path=os.path.realpath(dir_path)
    verbose=pmagplotlib.verbose
    version_num=pmag.get_version()
    user=pmag.get_named_arg_from_sys('-usr','')
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    meas_file=pmag.get_named_arg_from_sys('-f','agm_measurements.txt')
    spec_file=pmag.get_named_arg_from_sys('-F','specimens.txt')
    if '-P' in args:
        PLT=0
        irm_init,imag_init=-1,-1
    if '-sav' in args:
        verbose=0
        plots=1
    pltspec=pmag.get_named_arg_from_sys('-spc',0)
    if pltspec:
        #pltspec= args[ind+1]
        verbose=0
        plots=1
    spec_file=dir_path+'/'+spec_file
    meas_file=dir_path+'/'+meas_file
    SpecRecs=[]
    #
    #
    meas_data,file_type=pmag.magic_read(meas_file)
    if file_type!='measurements':
        print(main.__doc__)
        print('bad file')
        sys.exit()
    #
    # initialize some variables
    # define figure numbers for hyst,deltaM,DdeltaM curves
    HystRecs,RemRecs=[],[]
    HDD={}
    if verbose:
        if verbose and PLT:print("Plots may be on top of each other - use mouse to place ")
    if PLT:
        HDD['hyst'],HDD['deltaM'],HDD['DdeltaM']=1,2,3
        pmagplotlib.plot_init(HDD['DdeltaM'],5,5)
        pmagplotlib.plot_init(HDD['deltaM'],5,5)
        pmagplotlib.plot_init(HDD['hyst'],5,5)
        imag_init=0
        irm_init=0
    else:
        HDD['hyst'],HDD['deltaM'],HDD['DdeltaM'],HDD['irm'],HDD['imag']=0,0,0,0,0
    #
    if spec_file: prior_data,file_type=pmag.magic_read(spec_file)
    #
    # get list of unique experiment names and specimen names
    #
    experiment_names,sids=[],[]
    hys_data=pmag.get_dictitem(meas_data,'method_codes','LP-HYS','has')
    dcd_data=pmag.get_dictitem(meas_data,'method_codes','LP-IRM-DCD','has')
    imag_data=pmag.get_dictitem(meas_data,'method_codes','LP-IMAG','has')
    for rec in hys_data:
        if rec['experiment'] not in experiment_names:experiment_names.append(rec['experiment'])
        if rec['specimen'] not in sids:sids.append(rec['specimen'])
    #
    k=0
    if pltspec:
        k=sids.index(pltspec)
        print(sids[k])
    while k < len(sids):
        specimen=sids[k]
        HystRec={'specimen':specimen,'experiment':""} # initialize a new specimen hysteresis record
        if verbose and PLT:print(specimen, k+1 , 'out of ',len(sids))
    #
    #
        B,M,Bdcd,Mdcd=[],[],[],[] #B,M for hysteresis, Bdcd,Mdcd for irm-dcd data
        Bimag,Mimag=[],[] #Bimag,Mimag for initial magnetization curves
        spec_data=pmag.get_dictitem(hys_data,'specimen',specimen,'T') # fish out all the LP-HYS data for this specimen
        if len(spec_data)>0:
            meths=spec_data[0]['method_codes'].split(':')
            e=spec_data[0]['experiment']
            HystRec['experiment']=spec_data[0]['experiment']
            for rec in  spec_data:
                B.append(float(rec['meas_field_dc']))
                M.append(float(rec['magn_moment']))
        spec_data=pmag.get_dictitem(dcd_data,'specimen',specimen,'T') # fish out all the data for this specimen
        if len(spec_data)>0:
            HystRec['experiment']=HystRec['experiment']+':'+spec_data[0]['experiment']
            irm_exp=spec_data[0]['experiment']
            for rec in  spec_data:
                Bdcd.append(float(rec['treat_dc_field']))
                Mdcd.append(float(rec['magn_moment']))
        spec_data=pmag.get_dictitem(imag_data,'specimen',specimen,'T') # fish out all the data for this specimen
        if len(spec_data)>0:
            imag_exp=spec_data[0]['experiment']
            for rec in  spec_data:
                Bimag.append(float(rec['meas_field_dc']))
                Mimag.append(float(rec['magn_moment']))
    #
    # now plot the hysteresis curve
    #
        if len(B)>0:
            hmeths=[]
            for meth in meths: hmeths.append(meth)

            hpars=pmagplotlib.plotHDD(HDD,B,M,e)
            if verbose and PLT:pmagplotlib.drawFIGS(HDD)
    #
            if verbose:pmagplotlib.plotHPARS(HDD,hpars,'bs')
            HystRec['hyst_mr_moment']=hpars['hysteresis_mr_moment']
            HystRec['hyst_ms_moment']=hpars['hysteresis_ms_moment']
            HystRec['hyst_bc']=hpars['hysteresis_bc']
            HystRec['hyst_bcr']=hpars['hysteresis_bcr']
            HystRec['susc_h']=hpars['hysteresis_xhf']
            HystRec['experiments']=e
            HystRec['software_packages']=version_num
            if hpars["magic_method_codes"] not in hmeths:hmeths.append(hpars["magic_method_codes"])
            methods=""
            for meth in hmeths:
                methods=methods+meth.strip()+":"
            HystRec["method_codes"]=methods[:-1]
            HystRec["citations"]="This study"
    #
        if len(Bdcd)>0:
            rmeths=[]
            for meth in meths: rmeths.append(meth)
            if verbose and PLT:print('plotting IRM')
            if irm_init==0:
                HDD['irm']=5
                pmagplotlib.plot_init(HDD['irm'],5,5)
                irm_init=1
            rpars=pmagplotlib.plotIRM(HDD['irm'],Bdcd,Mdcd,irm_exp)
            HystRec['rem_mr_moment']=rpars['remanence_mr_moment']
            HystRec['rem_bcr']=rpars['remanence_bcr']
            HystRec['experiments']=specimen+':'+irm_exp
            if rpars["magic_method_codes"] not in meths:meths.append(rpars["magic_method_codes"])
            methods=""
            for meth in rmeths:
                methods=methods+meth.strip()+":"
            HystRec["method_codes"]=HystRec['method_codes']+':'+methods[:-1]
            HystRec["citations"]="This study"
        else:
            if irm_init:pmagplotlib.clearFIG(HDD['irm'])
        if len(Bimag)>0:
            if verbose and PLT:print('plotting initial magnetization curve')
# first normalize by Ms
            Mnorm=[]
            for m in Mimag: Mnorm.append(old_div(m,float(hpars['hysteresis_ms_moment'])))
            if imag_init==0:
                HDD['imag']=4
                pmagplotlib.plot_init(HDD['imag'],5,5)
                imag_init=1
            pmagplotlib.plotIMAG(HDD['imag'],Bimag,Mnorm,imag_exp)
        else:
            if imag_init:pmagplotlib.clearFIG(HDD['imag'])
        if len(list(HystRec.keys()))>0:HystRecs.append(HystRec)
    #
        files={}
        if plots:
            if pltspec:s=pltspec
            files={}
            for key in list(HDD.keys()):
                files[key]=s+'_'+key+'.'+fmt
            pmagplotlib.saveP(HDD,files)
            if pltspec:sys.exit()
        if verbose and PLT:
            pmagplotlib.drawFIGS(HDD)
            ans=input("S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ")
            if ans=="a":
                files={}
                for key in list(HDD.keys()):
                    files[key]=specimen+'_'+key+'.'+fmt
                pmagplotlib.saveP(HDD,files)
            if ans=='':k+=1
            if ans=="p":
                del HystRecs[-1]
                k-=1
            if  ans=='q':
                print("Good bye")
                sys.exit()
            if ans=='s':
                keepon=1
                specimen=input('Enter desired specimen name (or first part there of): ')
                while keepon==1:
                    try:
                        k =sids.index(specimen)
                        keepon=0
                    except:
                        tmplist=[]
                        for qq in range(len(sids)):
                            if specimen in sids[qq]:tmplist.append(sids[qq])
                        print(specimen," not found, but this was: ")
                        print(tmplist)
                        specimen=input('Select one or try again\n ')
                        k =sids.index(specimen)
        else:
            k+=1
        if len(B)==0 and len(Bdcd)==0:
            if verbose:print('skipping this one - no hysteresis data')
            k+=1
    if len(HystRecs)>0:
    #  go through prior_data, clean out prior results and save combined file as spec_file
        SpecRecs,keys=[],list(HystRecs[0].keys())
        if len(prior_data)>0:
            prior_keys=list(prior_data[0].keys())
        else: prior_keys=[]
        for rec in prior_data:
            for key in keys:
                if key not in list(rec.keys()):rec[key]=""
            if  'LP-HYS' not in rec['method_codes']:
                SpecRecs.append(rec)
        for rec in HystRecs:
            for key in prior_keys:
                if key not in list(rec.keys()):rec[key]=""
            prior=pmag.get_dictitem(prior_data,'specimen',rec['specimen'],'T')
            if len(prior)>0 and 'sample' in list(prior[0].keys()):
                rec['sample']=prior[0]['sample'] # pull sample name from prior specimens table
            SpecRecs.append(rec)
        pmag.magic_write(spec_file,SpecRecs,"specimens")
        if verbose:print("hysteresis parameters saved in ",spec_file)
Exemplo n.º 5
0
def main():
    """
    NAME
        microwave_magic.py
    
    DESCRIPTION
        plots microwave paleointensity data, allowing interactive setting of bounds.
        Saves and reads interpretations
        from a pmag_specimen formatted table, default: microwave_specimens.txt

    SYNTAX 
        microwave_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f MEAS, set magic_measurements input file
        -fsp PRIOR, set pmag_specimen prior interpretations file
        -fcr CRIT, set criteria file for grading.  
        -fmt [svg,png,jpg], format for images - default is svg
        -sav,  saves plots with out review (default format)
        -spc SPEC, plots single specimen SPEC, saves plot with specified format
            with optional -b bounds adn quits
        -b BEG END: sets  bounds for calculation
           BEG: starting step for slope calculation
           END: ending step for slope calculation
        
    DEFAULTS
        MEAS: magic_measurements.txt
        CRIT: NONE
        PRIOR: microwave_specimens.txt
  
    OUTPUT 
        figures:
            ALL:  numbers refer to temperature steps in command line window
            1) Arai plot:  closed circles are zero-field first/infield
                           open circles are infield first/zero-field
                           triangles are pTRM checks
                           squares are pTRM tail checks
                           VDS is vector difference sum
                           diamonds are bounds for interpretation
            2) Zijderveld plot:  closed (open) symbols are X-Y (X-Z) planes
                                 X rotated to NRM direction
            3) (De/Re)Magnetization diagram:
                           circles are NRM remaining
                           squares are pTRM gained
        command line window:
            list is: temperature step numbers, power (J), Dec, Inc, Int (units of magic_measuements)
                     list of possible commands: type letter followed by return to select option
                     saving of plots creates .svg format files with specimen_name, plot type as name
    """
    #
    #   initializations
    #
    meas_file, critout, inspec = "magic_measurements.txt", "", "microwave_specimens.txt"
    inlt = 0
    version_num = pmag.get_version()
    Tinit, DCZ, field, first_save = 0, 0, -1, 1
    user, comment = "", ''
    ans, specimen, recnum, start, end = 0, 0, 0, 0, 0
    plots, pmag_out, samp_file, style = 0, "", "", "svg"
    fmt = '.' + style
    #
    # default acceptance criteria
    #
    accept_keys = [
        'specimen_int_ptrm_n', 'specimen_md', 'specimen_fvds',
        'specimen_b_beta', 'specimen_dang', 'specimen_drats', 'specimen_Z'
    ]
    accept = {}
    accept['specimen_int_ptrm_n'] = 2
    accept['specimen_md'] = 10
    accept['specimen_fvds'] = 0.35
    accept['specimen_b_beta'] = .1
    accept['specimen_int_mad'] = 7
    accept['specimen_dang'] = 10
    accept['specimen_drats'] = 10
    accept['specimen_Z'] = 10
    #
    # parse command line options
    #
    spc, BEG, END = "", "", ""
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        meas_file = sys.argv[ind + 1]
    if '-fsp' in sys.argv:
        ind = sys.argv.index('-fsp')
        inspec = sys.argv[ind + 1]
    if '-fcr' in sys.argv:
        ind = sys.argv.index('-fcr')
        critout = sys.argv[ind + 1]
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = '.' + sys.argv[ind + 1]
    if '-spc' in sys.argv:
        ind = sys.argv.index('-spc')
        spc = sys.argv[ind + 1]
        if '-b' in sys.argv:
            ind = sys.argv.index('-b')
            BEG = int(sys.argv[ind + 1])
            END = int(sys.argv[ind + 2])
    if critout != "":
        crit_data, file_type = pmag.magic_read(critout)
        if pmagplotlib.verbose:
            print "Acceptance criteria read in from ", critout
        accept = {}
        accept['specimen_int_ptrm_n'] = 2.0
        for critrec in crit_data:
            if critrec["pmag_criteria_code"] == "IE-SPEC":
                for key in accept_keys:
                    if key not in critrec.keys():
                        accept[key] = -1
                    else:
                        accept[key] = float(critrec[key])
    try:
        open(inspec, 'rU')
        PriorRecs, file_type = pmag.magic_read(inspec)
        if file_type != 'pmag_specimens':
            print file_type
            print file_type, inspec, " is not a valid pmag_specimens file "
            sys.exit()
        for rec in PriorRecs:
            if 'magic_software_packages' not in rec.keys():
                rec['magic_software_packages'] = ""
    except IOError:
        PriorRecs = []
        if pmagplotlib.verbose:
            print "starting new specimen interpretation file: ", inspec
    meas_data, file_type = pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print file_type
        print file_type, "This is not a valid magic_measurements file "
        sys.exit()
    backup = 0
    # define figure numbers for arai, zijderveld and
    #   de-,re-magization diagrams
    AZD = {}
    AZD['deremag'], AZD['zijd'], AZD['arai'], AZD['eqarea'] = 1, 2, 3, 4
    pmagplotlib.plot_init(AZD['arai'], 4, 4)
    pmagplotlib.plot_init(AZD['zijd'], 4, 4)
    pmagplotlib.plot_init(AZD['deremag'], 4, 4)
    pmagplotlib.plot_init(AZD['eqarea'], 4, 4)
    #
    #
    #
    # get list of unique specimen names
    #
    CurrRec = []
    sids = pmag.get_specs(meas_data)
    # get plots for specimen s - default is just to step through arai diagrams
    #
    if spc != "": specimen = sids.index(spc)
    while specimen < len(sids):
        methcodes = []
        if pmagplotlib.verbose and spc != "":
            print sids[specimen], specimen + 1, 'of ', len(sids)
        MeasRecs = []
        s = sids[specimen]
        datablock, trmblock = [], []
        PmagSpecRec = {}
        PmagSpecRec["er_analyst_mail_names"] = user
        PmagSpecRec["specimen_correction"] = 'u'
        #
        # find the data from the meas_data file for this specimen
        #
        for rec in meas_data:
            if rec["er_specimen_name"] == s:
                MeasRecs.append(rec)
                methods = rec["magic_method_codes"].split(":")
                meths = []
                for meth in methods:
                    meths.append(meth.strip())  # take off annoying spaces
                methods = ""
                for meth in meths:
                    if meth.strip() not in methcodes and "LP-" in meth:
                        methcodes.append(meth.strip())
                    methods = methods + meth + ":"
                methods = methods[:-1]
                rec["magic_method_codes"] = methods
                if "LP-PI-M" in meths: datablock.append(rec)
                if "LP-MRM" in meths: trmblock.append(rec)
        if len(trmblock) > 2 and inspec != "":
            if Tinit == 0:
                Tinit = 1
                AZD['MRM'] = 4
                pmagplotlib.plot_init(AZD['MRM'], 4, 4)
            elif Tinit == 1:
                pmagplotlib.clearFIG(AZD['MRM'])
        if len(datablock) < 4:
            if backup == 0:
                specimen += 1
                if pmagplotlib.verbose:
                    print 'skipping specimen - moving forward ', s
            else:
                specimen -= 1
                if pmagplotlib.verbose:
                    print 'skipping specimen - moving backward ', s
    #
    #  collect info for the PmagSpecRec dictionary
    #
        else:
            rec = datablock[0]
            PmagSpecRec["er_citation_names"] = "This study"
            PmagSpecRec["er_specimen_name"] = s
            PmagSpecRec["er_sample_name"] = rec["er_sample_name"]
            PmagSpecRec["er_site_name"] = rec["er_site_name"]
            PmagSpecRec["er_location_name"] = rec["er_location_name"]
            if "magic_instrument_codes" not in rec.keys():
                rec["magic_instrument_codes"] = ""
            PmagSpecRec["magic_instrument_codes"] = rec[
                "magic_instrument_codes"]
            PmagSpecRec["measurement_step_unit"] = "J"
            if "magic_experiment_name" not in rec.keys():
                rec["magic_experiment_name"] = ""
            else:
                PmagSpecRec["magic_experiment_names"] = rec[
                    "magic_experiment_name"]

            meths = rec["magic_method_codes"].split(':')
            # sort data into types
            if "LP-PI-M-D" in meths:  # this is a double heating experiment
                exp_type = "LP-PI-M-D"
            elif "LP-PI-M-S" in meths:
                exp_type = "LP-PI-M-S"
            else:
                print "experiment type not supported yet "
                break
            araiblock, field = pmag.sortmwarai(datablock, exp_type)
            first_Z = araiblock[0]
            first_I = araiblock[1]
            GammaChecks = araiblock[-3]
            ThetaChecks = araiblock[-2]
            DeltaChecks = araiblock[-1]
            if len(first_Z) < 3:
                if backup == 0:
                    specimen += 1
                    if pmagplotlib.verbose:
                        print 'skipping specimen - moving forward ', s
                else:
                    specimen -= 1
                    if pmagplotlib.verbose:
                        print 'skipping specimen - moving backward ', s
            else:
                backup = 0
                zijdblock, units = pmag.find_dmag_rec(s, meas_data)
                if exp_type == "LP-PI-M-D":
                    recnum = 0
                    print "ZStep Watts  Dec Inc  Int"
                    for plotrec in zijdblock:
                        if pmagplotlib.verbose:
                            print '%i  %i %7.1f %7.1f %8.3e ' % (
                                recnum, plotrec[0], plotrec[1], plotrec[2],
                                plotrec[3])
                            recnum += 1
                    recnum = 1
                    if GammaChecks != "":
                        print "IStep Watts  Gamma"
                        for gamma in GammaChecks:
                            if pmagplotlib.verbose:
                                print '%i %i %7.1f ' % (recnum, gamma[0],
                                                        gamma[1])
                            recnum += 1
                if exp_type == "LP-PI-M-S":
                    if pmagplotlib.verbose:
                        print "IStep Watts  Theta"
                        kk = 0
                        for theta in ThetaChecks:
                            kk += 1
                            print '%i  %i %7.1f ' % (kk, theta[0], theta[1])
                    if pmagplotlib.verbose:
                        print "Watts  Delta"
                        for delta in DeltaChecks:
                            print '%i %7.1f ' % (delta[0], delta[1])
                pmagplotlib.plotAZ(AZD, araiblock, zijdblock, s, units[0])
                if inspec != "":
                    if pmagplotlib.verbose:
                        print 'Looking up saved interpretation....'
                    found = 0
                    for k in range(len(PriorRecs)):
                        try:
                            if PriorRecs[k]["er_specimen_name"] == s:
                                found = 1
                                CurrRec.append(PriorRecs[k])
                                for j in range(len(araiblock[0])):
                                    if float(araiblock[0][j][0]) == float(
                                            PriorRecs[k]
                                        ["measurement_step_min"]):
                                        start = j
                                    if float(araiblock[0][j][0]) == float(
                                            PriorRecs[k]
                                        ["measurement_step_max"]):
                                        end = j
                                pars, errcode = pmag.PintPars(
                                    araiblock, zijdblock, start, end)
                                pars['measurement_step_unit'] = "J"
                                del PriorRecs[
                                    k]  # put in CurrRec, take out of PriorRecs
                                if errcode != 1:
                                    pars["specimen_lab_field_dc"] = field
                                    pars["specimen_int"] = -1 * field * pars[
                                        "specimen_b"]
                                    pars["er_specimen_name"] = s
                                    if pmagplotlib.verbose:
                                        print 'Saved interpretation: '
                                    pars = pmag.scoreit(
                                        pars, PmagSpecRec, accept, '', 0)
                                    pmagplotlib.plotB(AZD, araiblock,
                                                      zijdblock, pars)
                                    if len(trmblock) > 2:
                                        blab = field
                                        best = pars["specimen_int"]
                                        Bs, TRMs = [], []
                                        for trec in trmblock:
                                            Bs.append(
                                                float(
                                                    trec['treatment_dc_field'])
                                            )
                                            TRMs.append(
                                                float(trec[
                                                    'measurement_magn_moment'])
                                            )
                                        NLpars = nlt.NLtrm(
                                            Bs, TRMs, best, blab, 0
                                        )  # calculate best fit parameters through TRM acquisition data, and get new banc
                                        Mp, Bp = [], []
                                        for k in range(int(max(Bs) * 1e6)):
                                            Bp.append(float(k) * 1e-6)
                                            npred = nlt.TRM(
                                                Bp[-1], NLpars['xopt'][0],
                                                NLpars['xopt'][1]
                                            )  # predicted NRM for this field
                                            Mp.append(npred)
                                        pmagplotlib.plotTRM(
                                            AZD['MRM'], Bs, TRMs, Bp, Mp,
                                            NLpars,
                                            trec['magic_experiment_name'])
                                        print npred
                                        print 'Banc= ', float(
                                            NLpars['banc']) * 1e6
                                        if pmagplotlib.verbose:
                                            print 'Banc= ', float(
                                                NLpars['banc']) * 1e6
                                        pmagplotlib.drawFIGS(AZD)
                                else:
                                    print 'error on specimen ', s
                        except:
                            pass
                    if pmagplotlib.verbose and found == 0:
                        print '    None found :(  '
                if spc != "":
                    if BEG != "":
                        pars, errcode = pmag.PintPars(araiblock, zijdblock,
                                                      BEG, END)
                        pars['measurement_step_unit'] = "J"
                        pars["specimen_lab_field_dc"] = field
                        pars["specimen_int"] = -1 * field * pars["specimen_b"]
                        pars["er_specimen_name"] = s
                        pars['specimen_grade'] = ''  # ungraded
                        pmagplotlib.plotB(AZD, araiblock, zijdblock, pars)
                        if len(trmblock) > 2:
                            if inlt == 0:
                                donlt()
                                inlt = 1
                            blab = field
                            best = pars["specimen_int"]
                            Bs, TRMs = [], []
                            for trec in trmblock:
                                Bs.append(float(trec['treatment_dc_field']))
                                TRMs.append(
                                    float(trec['measurement_magn_moment']))
                            NLpars = nlt.NLtrm(
                                Bs, TRMs, best, blab, 0
                            )  # calculate best fit parameters through TRM acquisition data, and get new banc
                            #
                            Mp, Bp = [], []
                            for k in range(int(max(Bs) * 1e6)):
                                Bp.append(float(k) * 1e-6)
                                npred = nlt.TRM(
                                    Bp[-1], NLpars['xopt'][0], NLpars['xopt']
                                    [1])  # predicted NRM for this field
                    files = {}
                    for key in AZD.keys():
                        files[key] = s + '_' + key + fmt
                    pmagplotlib.saveP(AZD, files)
                    sys.exit()
                if plots == 0:
                    ans = 'b'
                    while ans != "":
                        print """
               s[a]ve plot, set [b]ounds for calculation, [d]elete current interpretation, [p]revious, [s]ample, [q]uit:
               """
                        ans = raw_input('Return for next specimen \n')
                        if ans == "":
                            specimen += 1
                        if ans == "d":
                            save_redo(PriorRecs, inspec)
                            CurrRec = []
                            pmagplotlib.plotAZ(AZD, araiblock, zijdblock, s,
                                               units[0])
                            pmagplotlib.drawFIGS(AZD)
                        if ans == 'a':
                            files = {}
                            for key in AZD.keys():
                                files[key] = s + '_' + key + fmt
                            pmagplotlib.saveP(AZD, files)
                            ans = ""
                        if ans == 'q':
                            print "Good bye"
                            sys.exit()
                        if ans == 'p':
                            specimen = specimen - 1
                            backup = 1
                            ans = ""
                        if ans == 's':
                            keepon = 1
                            spec = raw_input(
                                'Enter desired specimen name (or first part there of): '
                            )
                            while keepon == 1:
                                try:
                                    specimen = sids.index(spec)
                                    keepon = 0
                                except:
                                    tmplist = []
                                    for qq in range(len(sids)):
                                        if spec in sids[qq]:
                                            tmplist.append(sids[qq])
                                    print specimen, " not found, but this was: "
                                    print tmplist
                                    spec = raw_input(
                                        'Select one or try again\n ')
                            ans = ""
                        if ans == 'b':
                            if end == 0 or end >= len(araiblock[0]):
                                end = len(araiblock[0]) - 1
                            GoOn = 0
                            while GoOn == 0:
                                print 'Enter index of first point for calculation: ', '[', start, ']'
                                answer = raw_input('return to keep default  ')
                                if answer != "": start = int(answer)
                                print 'Enter index  of last point for calculation: ', '[', end, ']'
                                answer = raw_input('return to keep default  ')
                                if answer != "":
                                    end = int(answer)
                                if start >= 0 and start < len(araiblock[
                                        0]) - 2 and end > 0 and end < len(
                                            araiblock[0]) and start < end:
                                    GoOn = 1
                                else:
                                    print "Bad endpoints - try again! "
                                    start, end = 0, len(araiblock)
                            s = sids[specimen]
                            pars, errcode = pmag.PintPars(
                                araiblock, zijdblock, start, end)
                            pars['measurement_step_unit'] = "J"
                            pars["specimen_lab_field_dc"] = field
                            pars["specimen_int"] = -1 * field * pars[
                                "specimen_b"]
                            pars["er_specimen_name"] = s
                            pars = pmag.scoreit(pars, PmagSpecRec, accept, '',
                                                0)
                            PmagSpecRec["measurement_step_min"] = '%8.3e' % (
                                pars["measurement_step_min"])
                            PmagSpecRec["measurement_step_max"] = '%8.3e' % (
                                pars["measurement_step_max"])
                            PmagSpecRec["measurement_step_unit"] = "J"
                            PmagSpecRec["specimen_int_n"] = '%i' % (
                                pars["specimen_int_n"])
                            PmagSpecRec["specimen_lab_field_dc"] = '%8.3e' % (
                                pars["specimen_lab_field_dc"])
                            PmagSpecRec["specimen_int"] = '%8.3e ' % (
                                pars["specimen_int"])
                            PmagSpecRec["specimen_b"] = '%5.3f ' % (
                                pars["specimen_b"])
                            PmagSpecRec["specimen_q"] = '%5.1f ' % (
                                pars["specimen_q"])
                            PmagSpecRec["specimen_f"] = '%5.3f ' % (
                                pars["specimen_f"])
                            PmagSpecRec["specimen_fvds"] = '%5.3f' % (
                                pars["specimen_fvds"])
                            PmagSpecRec["specimen_b_beta"] = '%5.3f' % (
                                pars["specimen_b_beta"])
                            PmagSpecRec["specimen_int_mad"] = '%7.1f' % (
                                pars["specimen_int_mad"])
                            PmagSpecRec["specimen_Z"] = '%7.1f' % (
                                pars["specimen_Z"])
                            if pars["method_codes"] != "":
                                tmpcodes = pars["method_codes"].split(":")
                                for t in tmpcodes:
                                    if t.strip() not in methcodes:
                                        methcodes.append(t.strip())
                            PmagSpecRec["specimen_dec"] = '%7.1f' % (
                                pars["specimen_dec"])
                            PmagSpecRec["specimen_inc"] = '%7.1f' % (
                                pars["specimen_inc"])
                            PmagSpecRec["specimen_tilt_correction"] = '-1'
                            PmagSpecRec["specimen_direction_type"] = 'l'
                            PmagSpecRec[
                                "direction_type"] = 'l'  # this is redudant, but helpful - won't be imported
                            PmagSpecRec["specimen_dang"] = '%7.1f ' % (
                                pars["specimen_dang"])
                            PmagSpecRec["specimen_drats"] = '%7.1f ' % (
                                pars["specimen_drats"])
                            PmagSpecRec["specimen_int_ptrm_n"] = '%i ' % (
                                pars["specimen_int_ptrm_n"])
                            PmagSpecRec["specimen_rsc"] = '%6.4f ' % (
                                pars["specimen_rsc"])
                            PmagSpecRec["specimen_md"] = '%i ' % (int(
                                pars["specimen_md"]))
                            if PmagSpecRec["specimen_md"] == '-1':
                                PmagSpecRec["specimen_md"] = ""
                            PmagSpecRec["specimen_b_sigma"] = '%5.3f ' % (
                                pars["specimen_b_sigma"])
                            if "IE-TT" not in methcodes:
                                methcodes.append("IE-TT")
                            methods = ""
                            for meth in methcodes:
                                methods = methods + meth + ":"
                            PmagSpecRec["magic_method_codes"] = methods[:-1]
                            PmagSpecRec["specimen_description"] = comment
                            PmagSpecRec[
                                "magic_software_packages"] = version_num
                            pmagplotlib.plotAZ(AZD, araiblock, zijdblock, s,
                                               units[0])
                            pmagplotlib.plotB(AZD, araiblock, zijdblock, pars)
                            if len(trmblock) > 2:
                                blab = field
                                best = pars["specimen_int"]
                                Bs, TRMs = [], []
                                for trec in trmblock:
                                    Bs.append(float(
                                        trec['treatment_dc_field']))
                                    TRMs.append(
                                        float(trec['measurement_magn_moment']))
                                NLpars = nlt.NLtrm(
                                    Bs, TRMs, best, blab, 0
                                )  # calculate best fit parameters through TRM acquisition data, and get new banc
                                Mp, Bp = [], []
                                for k in range(int(max(Bs) * 1e6)):
                                    Bp.append(float(k) * 1e-6)
                                    npred = nlt.TRM(
                                        Bp[-1], NLpars['xopt'][0],
                                        NLpars['xopt']
                                        [1])  # predicted NRM for this field
                                    Mp.append(npred)
                                pmagplotlib.plotTRM(
                                    AZD['MRM'], Bs, TRMs, Bp, Mp, NLpars,
                                    trec['magic_experiment_name'])
                                print 'Banc= ', float(NLpars['banc']) * 1e6
                            pmagplotlib.drawFIGS(AZD)
                            pars["specimen_lab_field_dc"] = field
                            pars["specimen_int"] = -1 * field * pars[
                                "specimen_b"]
                            saveit = raw_input(
                                "Save this interpretation? [y]/n \n")
                            if saveit != 'n':
                                specimen += 1
                                PriorRecs.append(
                                    PmagSpecRec)  # put back an interpretation
                                save_redo(PriorRecs, inspec)
                            ans = ""
                else:
                    specimen += 1
                    if fmt != ".pmag":
                        basename = s + '_microwave' + fmt
                        files = {}
                        for key in AZD.keys():
                            files[key] = s + '_' + key + fmt
                        if pmagplotlib.isServer:
                            black = '#000000'
                            purple = '#800080'
                            titles = {}
                            titles['deremag'] = 'DeReMag Plot'
                            titles['zijd'] = 'Zijderveld Plot'
                            titles['arai'] = 'Arai Plot'
                            AZD = pmagplotlib.addBorders(
                                AZD, titles, black, purple)
                        pmagplotlib.saveP(AZD, files)
    #                   pmagplotlib.combineFigs(s,files,3)
        if len(CurrRec) > 0:
            for rec in CurrRec:
                PriorRecs.append(rec)
        CurrRec = []
    if plots != 1:
        ans = raw_input(" Save last plot? 1/[0] ")
        if ans == "1":
            if fmt != ".pmag":
                files = {}
                for key in AZD.keys():
                    files[key] = s + '_' + key + fmt
                pmagplotlib.saveP(AZD, files)
        if len(CurrRec) > 0:
            PriorRecs.append(CurrRec)  # put back an interpretation
        if len(PriorRecs) > 0:
            save_redo(PriorRecs, inspec)
            print 'Updated interpretations saved in ', inspec
    if pmagplotlib.verbose:
        print "Good bye"
Exemplo n.º 6
0
def main():
    """
    NAME
        dmag_magic.py

    DESCRIPTION
       plots intensity decay curves for demagnetization experiments

    SYNTAX
        dmag_magic -h [command line options]

    INPUT
       takes magic formatted magic_measurements.txt files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: magic_measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot, default is by location
        -LT [AF,T,M]: specify lab treatment type, default AF
        -XLP [PI]: exclude specific  lab protocols (for example, method codes like LP-PI)
        -N do not normalize by NRM magnetization
        -sav save plots silently and quit
        -fmt [svg,jpg,png,pdf] set figure format [default is svg]
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    FIG = {}  # plot dictionary
    FIG['demag'] = 1  # demag is figure 1
    in_file, plot_key, LT = 'magic_measurements.txt', 'er_location_name', "LT-AF-Z"
    XLP = ""
    norm = 1
    LT = 'LT-AF-Z'
    units, dmag_key = 'T', 'treatment_ac_field'
    plot = 0
    fmt = 'svg'
    if len(sys.argv) > 1:
        if '-h' in sys.argv:
            print(main.__doc__)
            sys.exit()
        if '-N' in sys.argv: norm = 0
        if '-sav' in sys.argv:
            plot = 1
        if '-f' in sys.argv:
            ind = sys.argv.index("-f")
            in_file = 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')
            plot_by = sys.argv[ind + 1]
            if plot_by == 'sit': plot_key = 'er_site_name'
            if plot_by == 'sam': plot_key = 'er_sample_name'
            if plot_by == 'spc': plot_key = 'er_specimen_name'
        if '-XLP' in sys.argv:
            ind = sys.argv.index("-XLP")
            XLP = sys.argv[ind + 1]  # get lab protocol for excluding
        if '-LT' in sys.argv:
            ind = sys.argv.index("-LT")
            LT = 'LT-' + sys.argv[ind +
                                  1] + '-Z'  # get lab treatment for plotting
            if LT == 'LT-T-Z':
                units, dmag_key = 'K', 'treatment_temp'
            elif LT == 'LT-AF-Z':
                units, dmag_key = 'T', 'treatment_ac_field'
            elif LT == 'LT-M-Z':
                units, dmag_key = 'J', 'treatment_mw_energy'
            else:
                units = 'U'
    data, file_type = pmag.magic_read(in_file)
    sids = pmag.get_specs(data)
    pmagplotlib.plot_init(FIG['demag'], 5, 5)
    print(len(data), ' records read from ', in_file)
    #
    #
    # find desired intensity data
    #
    #
    plotlist, intlist = [], [
        'measurement_magnitude', 'measurement_magn_moment',
        'measurement_magn_volume', 'measurement_magn_mass'
    ]
    IntMeths = []
    FixData = []
    for rec in data:
        meths = []
        methcodes = rec['magic_method_codes'].split(':')
        for meth in methcodes:
            meths.append(meth.strip())
        for key in rec.keys():
            if key in intlist and rec[key] != "":
                if key not in IntMeths: IntMeths.append(key)
                if rec[plot_key] not in plotlist and LT in meths:
                    plotlist.append(rec[plot_key])
                if 'measurement_flag' not in rec.keys():
                    rec['measurement_flag'] = 'g'
                FixData.append(rec)
        plotlist.sort()
    if len(IntMeths) == 0:
        print('No intensity information found')
        sys.exit()
    data = FixData
    int_key = IntMeths[
        0]  # plot first intensity method found - normalized to initial value anyway - doesn't matter which used
    for plt in plotlist:
        if plot == 0: print(plt, 'plotting by: ', plot_key)
        PLTblock = pmag.get_dictitem(
            data, plot_key, plt,
            'T')  # fish out all the data for this type of plot
        PLTblock = pmag.get_dictitem(
            PLTblock, 'magic_method_codes', LT,
            'has')  # fish out all the dmag for this experiment type
        PLTblock = pmag.get_dictitem(
            PLTblock, int_key, '',
            'F')  # get all with this intensity key non-blank
        if XLP != "":
            PLTblock = pmag.get_dictitem(
                PLTblock, 'magic_method_codes', XLP,
                'not')  # reject data with XLP in method_code
        if len(PLTblock) > 2:
            title = PLTblock[0][plot_key]
            spcs = []
            for rec in PLTblock:
                if rec['er_specimen_name'] not in spcs:
                    spcs.append(rec['er_specimen_name'])
            for spc in spcs:
                SPCblock = pmag.get_dictitem(PLTblock, 'er_specimen_name', spc,
                                             'T')  # plot specimen by specimen
                INTblock = []
                for rec in SPCblock:
                    INTblock.append([
                        float(rec[dmag_key]), 0, 0,
                        float(rec[int_key]), 1, rec['measurement_flag']
                    ])
                if len(INTblock) > 2:
                    pmagplotlib.plotMT(FIG['demag'], INTblock, title, 0, units,
                                       norm)
            if plot == 1:
                files = {}
                for key in FIG.keys():
                    files[key] = title + '_' + LT + '.' + fmt
                pmagplotlib.saveP(FIG, files)
                sys.exit()
            else:
                pmagplotlib.drawFIGS(FIG)
                ans = raw_input(
                    " S[a]ve to save plot, [q]uit,  Return to continue:  ")
                if ans == 'q': sys.exit()
                if ans == "a":
                    files = {}
                    for key in FIG.keys():
                        files[key] = title + '_' + LT + '.' + fmt
                    pmagplotlib.saveP(FIG, files)
            pmagplotlib.clearFIG(FIG['demag'])
Exemplo n.º 7
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 '-dpi' in sys.argv:
        ind=sys.argv.index('-dpi')
        dpi='.'+sys.argv[ind+1]
    else: dpi=100
    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,dpi=dpi)
                   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,dpi=dpi)
    #                   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,dpi=dpi)
        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"
Exemplo n.º 8
0
def main():
    """
    NAME
        hysteresis_magic.py

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

    SYNTAX
        hysteresis_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f: specify input file, default is agm_measurements.txt
        -F: specify specimens.txt output file
        -P: do not make the plots
        -spc SPEC: specify specimen name to plot and quit
        -sav save all plots and quit
        -fmt [png,svg,eps,jpg]
    """
    args = sys.argv
    PLT = 1
    plots = 0
    fmt = pmag.get_named_arg_from_sys('-fmt', 'svg')
    dir_path = pmag.get_named_arg_from_sys('-WD', '.')
    dir_path = os.path.realpath(dir_path)
    verbose = pmagplotlib.verbose
    version_num = pmag.get_version()
    user = pmag.get_named_arg_from_sys('-usr', '')
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    meas_file = pmag.get_named_arg_from_sys('-f', 'agm_measurements.txt')
    spec_file = pmag.get_named_arg_from_sys('-F', 'specimens.txt')
    if '-P' in args:
        PLT = 0
        irm_init, imag_init = -1, -1
    if '-sav' in args:
        verbose = 0
        plots = 1
    pltspec = pmag.get_named_arg_from_sys('-spc', 0)
    if pltspec:
        #pltspec= args[ind+1]
        verbose = 0
        plots = 1
    spec_file = dir_path + '/' + spec_file
    meas_file = dir_path + '/' + meas_file
    SpecRecs = []
    #
    #
    meas_data, file_type = pmag.magic_read(meas_file)
    if file_type != 'measurements':
        print(main.__doc__)
        print('bad file')
        sys.exit()
    #
    # initialize some variables
    # define figure numbers for hyst,deltaM,DdeltaM curves
    HystRecs, RemRecs = [], []
    HDD = {}
    if verbose:
        if verbose and PLT:
            print("Plots may be on top of each other - use mouse to place ")
    if PLT:
        HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'] = 1, 2, 3
        pmagplotlib.plot_init(HDD['DdeltaM'], 5, 5)
        pmagplotlib.plot_init(HDD['deltaM'], 5, 5)
        pmagplotlib.plot_init(HDD['hyst'], 5, 5)
        imag_init = 0
        irm_init = 0
    else:
        HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'], HDD['irm'], HDD[
            'imag'] = 0, 0, 0, 0, 0
    #
    if spec_file: prior_data, file_type = pmag.magic_read(spec_file)
    #
    # get list of unique experiment names and specimen names
    #
    experiment_names, sids = [], []
    hys_data = pmag.get_dictitem(meas_data, 'method_codes', 'LP-HYS', 'has')
    dcd_data = pmag.get_dictitem(meas_data, 'method_codes', 'LP-IRM-DCD',
                                 'has')
    imag_data = pmag.get_dictitem(meas_data, 'method_codes', 'LP-IMAG', 'has')
    for rec in hys_data:
        if rec['experiment'] not in experiment_names:
            experiment_names.append(rec['experiment'])
        if rec['specimen'] not in sids: sids.append(rec['specimen'])
    #
    k = 0
    if pltspec:
        k = sids.index(pltspec)
        print(sids[k])
    while k < len(sids):
        specimen = sids[k]
        HystRec = {
            'specimen': specimen,
            'experiment': ""
        }  # initialize a new specimen hysteresis record
        if verbose and PLT: print(specimen, k + 1, 'out of ', len(sids))
        #
        #
        B, M, Bdcd, Mdcd = [], [], [], [
        ]  #B,M for hysteresis, Bdcd,Mdcd for irm-dcd data
        Bimag, Mimag = [], []  #Bimag,Mimag for initial magnetization curves
        spec_data = pmag.get_dictitem(
            hys_data, 'specimen', specimen,
            'T')  # fish out all the LP-HYS data for this specimen
        if len(spec_data) > 0:
            meths = spec_data[0]['method_codes'].split(':')
            e = spec_data[0]['experiment']
            HystRec['experiment'] = spec_data[0]['experiment']
            for rec in spec_data:
                B.append(float(rec['meas_field_dc']))
                M.append(float(rec['magn_moment']))
        spec_data = pmag.get_dictitem(
            dcd_data, 'specimen', specimen,
            'T')  # fish out all the data for this specimen
        if len(spec_data) > 0:
            HystRec['experiment'] = HystRec['experiment'] + ':' + spec_data[0][
                'experiment']
            irm_exp = spec_data[0]['experiment']
            for rec in spec_data:
                Bdcd.append(float(rec['treat_dc_field']))
                Mdcd.append(float(rec['magn_moment']))
        spec_data = pmag.get_dictitem(
            imag_data, 'specimen', specimen,
            'T')  # fish out all the data for this specimen
        if len(spec_data) > 0:
            imag_exp = spec_data[0]['experiment']
            for rec in spec_data:
                Bimag.append(float(rec['meas_field_dc']))
                Mimag.append(float(rec['magn_moment']))
    #
    # now plot the hysteresis curve
    #
        if len(B) > 0:
            hmeths = []
            for meth in meths:
                hmeths.append(meth)

            hpars = pmagplotlib.plotHDD(HDD, B, M, e)
            if verbose and PLT: pmagplotlib.drawFIGS(HDD)
            #
            if verbose: pmagplotlib.plotHPARS(HDD, hpars, 'bs')
            HystRec['hyst_mr_moment'] = hpars['hysteresis_mr_moment']
            HystRec['hyst_ms_moment'] = hpars['hysteresis_ms_moment']
            HystRec['hyst_bc'] = hpars['hysteresis_bc']
            HystRec['hyst_bcr'] = hpars['hysteresis_bcr']
            HystRec['hyst_xhf'] = hpars['hysteresis_xhf']
            HystRec['experiments'] = e
            HystRec['software_packages'] = version_num
            if hpars["magic_method_codes"] not in hmeths:
                hmeths.append(hpars["magic_method_codes"])
            methods = ""
            for meth in hmeths:
                methods = methods + meth.strip() + ":"
            HystRec["method_codes"] = methods[:-1]
            HystRec["citations"] = "This study"
    #
        if len(Bdcd) > 0:
            rmeths = []
            for meth in meths:
                rmeths.append(meth)
            if verbose and PLT: print('plotting IRM')
            if irm_init == 0:
                HDD['irm'] = 5
                pmagplotlib.plot_init(HDD['irm'], 5, 5)
                irm_init = 1
            rpars = pmagplotlib.plotIRM(HDD['irm'], Bdcd, Mdcd, irm_exp)
            HystRec['rem_mr_moment'] = rpars['remanence_mr_moment']
            HystRec['rem_bcr'] = rpars['remanence_bcr']
            HystRec['experiments'] = specimen + ':' + irm_exp
            if rpars["magic_method_codes"] not in meths:
                meths.append(rpars["magic_method_codes"])
            methods = ""
            for meth in rmeths:
                methods = methods + meth.strip() + ":"
            HystRec[
                "method_codes"] = HystRec['method_codes'] + ':' + methods[:-1]
            HystRec["citations"] = "This study"
        else:
            if irm_init: pmagplotlib.clearFIG(HDD['irm'])
        if len(Bimag) > 0:
            if verbose and PLT: print('plotting initial magnetization curve')
            # first normalize by Ms
            Mnorm = []
            for m in Mimag:
                Mnorm.append(old_div(m, float(hpars['hysteresis_ms_moment'])))
            if imag_init == 0:
                HDD['imag'] = 4
                pmagplotlib.plot_init(HDD['imag'], 5, 5)
                imag_init = 1
            pmagplotlib.plotIMAG(HDD['imag'], Bimag, Mnorm, imag_exp)
        else:
            if imag_init: pmagplotlib.clearFIG(HDD['imag'])
        if len(list(HystRec.keys())) > 0: HystRecs.append(HystRec)
        #
        files = {}
        if plots:
            if pltspec:
                s = pltspec
            else:
                s = specimen
            files = {}
            for key in list(HDD.keys()):
                files[key] = s + '_' + key + '.' + fmt
            pmagplotlib.saveP(HDD, files)
            if pltspec: sys.exit()
        if verbose and PLT:
            pmagplotlib.drawFIGS(HDD)
            ans = input(
                "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n "
            )
            if ans == "a":
                files = {}
                for key in list(HDD.keys()):
                    files[key] = specimen + '_' + key + '.' + fmt
                pmagplotlib.saveP(HDD, files)
            if ans == '': k += 1
            if ans == "p":
                del HystRecs[-1]
                k -= 1
            if ans == 'q':
                print("Good bye")
                sys.exit()
            if ans == 's':
                keepon = 1
                specimen = input(
                    'Enter desired specimen name (or first part there of): ')
                while keepon == 1:
                    try:
                        k = sids.index(specimen)
                        keepon = 0
                    except:
                        tmplist = []
                        for qq in range(len(sids)):
                            if specimen in sids[qq]: tmplist.append(sids[qq])
                        print(specimen, " not found, but this was: ")
                        print(tmplist)
                        specimen = input('Select one or try again\n ')
                        k = sids.index(specimen)
        else:
            k += 1
        if len(B) == 0 and len(Bdcd) == 0:
            if verbose: print('skipping this one - no hysteresis data')
            k += 1
    if len(HystRecs) > 0:
        #  go through prior_data, clean out prior results and save combined file as spec_file
        SpecRecs, keys = [], list(HystRecs[0].keys())
        if len(prior_data) > 0:
            prior_keys = list(prior_data[0].keys())
        else:
            prior_keys = []
        for rec in prior_data:
            for key in keys:
                if key not in list(rec.keys()): rec[key] = ""
            if 'LP-HYS' not in rec['method_codes']:
                SpecRecs.append(rec)
        for rec in HystRecs:
            for key in prior_keys:
                if key not in list(rec.keys()): rec[key] = ""
            prior = pmag.get_dictitem(prior_data, 'specimen', rec['specimen'],
                                      'T')
            if len(prior) > 0 and 'sample' in list(prior[0].keys()):
                rec['sample'] = prior[0][
                    'sample']  # pull sample name from prior specimens table
            SpecRecs.append(rec)
        # drop unnecessary/duplicate rows
        dir_path = os.path.split(spec_file)[0]
        con = nb.Contribution(dir_path, read_tables=[])
        con.add_magic_table_from_data('specimens', SpecRecs)
        con.tables['specimens'].drop_duplicate_rows(ignore_cols=[
            'specimen', 'sample', 'citations', 'software_packages'
        ])
        con.tables['specimens'].df = con.tables[
            'specimens'].df.drop_duplicates()
        con.write_table_to_file('specimens', custom_name=spec_file)
        # old way:
        ##pmag.magic_write(spec_file,SpecRecs,"specimens")
        if verbose: print("hysteresis parameters saved in ", spec_file)
Exemplo n.º 9
0
def main():
    """
    NAME
        irmaq_magic.py

    DESCRIPTION
       plots IRM acquisition curves from magic_measurements file

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

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

    SYNTAX
        lowrie -h [command line options]

    INPUT
       takes SIO formatted input files

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

    DESCRIPTION
       plots intensity decay curves for demagnetization experiments

    SYNTAX
        dmag_magic -h [command line options]

    INPUT
       takes magic formatted magic_measurements.txt files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: magic_measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot,
               default is by location
        -LT [AF,T,M]: specify lab treatment type, default AF
        -XLP [PI]: exclude specific  lab protocols,
               (for example, method codes like LP-PI)
        -N do not normalize by NRM magnetization
        -sav save plots silently and quit
        -fmt [svg,jpg,png,pdf] set figure format [default is svg]
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    # initialize variables from command line + defaults
    FIG = {}  # plot dictionary
    FIG['demag'] = 1  # demag is figure 1
    in_file = pmag.get_named_arg_from_sys("-f", default_val="measurements.txt")
    plot_by = pmag.get_named_arg_from_sys("-obj", default_val="loc")
    name_dict = {'loc': 'location', 'sit': 'site',
                 'sam': 'sample', 'spc': 'specimen'}
    plot_key = name_dict[plot_by]
    LT = "LT-" + pmag.get_named_arg_from_sys("-LT", "AF") + "-Z"
    if LT == "LT-T-Z":
        units, dmag_key = 'K', 'treat_temp'
    elif LT == "LT-AF-Z":
        units, dmag_key = 'T', 'treat_ac_field'
    elif LT == 'LT-M-Z':
        units, dmag_key = 'J', 'treat_mw_energy'
    else:
        units = 'U'
    no_norm = pmag.get_flag_arg_from_sys("-N")
    norm = 0 if no_norm else 1
    no_plot = pmag.get_flag_arg_from_sys("-sav")
    plot = 0 if no_plot else 1
    fmt = pmag.get_named_arg_from_sys("-fmt", "svg")
    XLP = pmag.get_named_arg_from_sys("-XLP", "")
    dir_path = pmag.get_named_arg_from_sys("-WD", os.getcwd())
    spec_file = pmag.get_named_arg_from_sys("-fsp", default_val="specimens.txt")
    samp_file = pmag.get_named_arg_from_sys("-fsa", default_val="samples.txt")
    site_file = pmag.get_named_arg_from_sys("-fsi", default_val="sites.txt")

    # create contribution and add required headers
    fnames = {"specimens": spec_file, "samples": samp_file, 'sites': site_file}
    contribution = nb.Contribution(dir_path, single_file=in_file,
                                   custom_filenames=fnames)
    file_type = contribution.tables.keys()[0]
    print len(contribution.tables['measurements'].df), ' records read from ', in_file
    # add plot_key into measurements table
    if plot_key not in contribution.tables['measurements'].df.columns:
        contribution.propagate_name_down(plot_key, 'measurements')
    data_container = contribution.tables[file_type]
    # pare down to only records with useful data
    # grab records that have the requested code
    data_slice = data_container.get_records_for_code(LT)
    # and don't have the offending code
    data = data_container.get_records_for_code(XLP, incl=False, use_slice=True,
                                               sli=data_slice, strict_match=False)

    # make sure quality is in the dataframe
    if 'quality' not in data.columns:
        data['quality'] = 'g'
    # get intensity key and make sure intensity data is not blank
    intlist = ['magn_moment', 'magn_volume', 'magn_mass']
    IntMeths = [col_name for col_name in data.columns if col_name in intlist]
    # get rid of any entirely blank intensity columns
    for col_name in IntMeths:
        if not data[col_name].any():
            data.drop(col_name, axis=1, inplace=True)
    IntMeths = [col_name for col_name in data.columns if col_name in intlist]
    if len(IntMeths) == 0:
        print 'No intensity headers found'
        sys.exit()

    int_key = IntMeths[0] # plot first intensity method found - normalized to initial value anyway - doesn't matter which used
    data = data[data[int_key].notnull()]
    # make list of individual plots
    # by default, will be by location_name
    plotlist = data[plot_key].unique()
    plotlist.sort()
    pmagplotlib.plot_init(FIG['demag'], 5, 5)
    # iterate through and plot the data
    for plt in plotlist:
        plot_data = data[data[plot_key] == plt].copy()
        if plot:
            print plt, 'plotting by: ', plot_key
        if len(plot_data) > 2:
            title = plt
            spcs = []
            spcs = plot_data['specimen'].unique()
            for spc in spcs:
                INTblock = []
                spec_data = plot_data[plot_data['specimen'] == spc]
                for ind, rec in spec_data.iterrows():
                    INTblock.append([float(rec[dmag_key]), 0, 0, float(rec[int_key]), 1, rec['quality']])
                if len(INTblock) > 2:
                    pmagplotlib.plotMT(FIG['demag'], INTblock,
                                       title, 0, units, norm)

            if not plot:
                files = {}
                for key in FIG.keys():
                    files[key] = title + '_' + LT + '.' + fmt
                pmagplotlib.saveP(FIG, files)
                #sys.exit()
            else:
                pmagplotlib.drawFIGS(FIG)
                prompt = " S[a]ve to save plot, [q]uit,  Return to continue:  "
                ans = raw_input(prompt)
                if ans == 'q':
                    sys.exit()
                if ans == "a":
                    files = {}
                    for key in FIG.keys():
                        files[key] = title + '_' + LT + '.' + fmt
                    pmagplotlib.saveP(FIG, files)
            pmagplotlib.clearFIG(FIG['demag'])
Exemplo n.º 12
0
def main():
    """
    NAME
        microwave_magic.py
    
    DESCRIPTION
        plots microwave paleointensity data, allowing interactive setting of bounds.
        Saves and reads interpretations
        from a pmag_specimen formatted table, default: microwave_specimens.txt

    SYNTAX 
        microwave_magic.py [command line options]

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

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

    SYNTAX
        lowrie_magic.py -h [command line options]

    INPUT
       takes measurements formatted input files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is magic_measurements.txt
        -N do not normalize by maximum magnetization
        -fmt [svg, pdf, eps, png] specify fmt, default is svg
        -sav saves plots and quits
        -DM [2, 3] MagIC data model number
    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if len(sys.argv) <= 1:
        print(main.__doc__)
        print('you must supply a file name')
        sys.exit()
    FIG = {}  # plot dictionary
    FIG['lowrie'] = 1  # demag is figure 1
    pmagplotlib.plot_init(FIG['lowrie'], 6, 6)
    norm = 1  # default is to normalize by maximum axis
    in_file = pmag.get_named_arg("-f", "measurements.txt")
    dir_path = pmag.get_named_arg("-WD", ".")
    in_file = pmag.resolve_file_name(in_file, dir_path)
    data_model = pmag.get_named_arg("-DM", 3)
    data_model = int(float(data_model))
    fmt = pmag.get_named_arg("-fmt", "svg")
    if '-N' in sys.argv:
        norm = 0  # don't normalize
    if '-sav' in sys.argv:
        plot = 1  # silently save and quit
    else:
        plot = 0 # generate plots
    print(in_file)
    # read in data
    PmagRecs, file_type = pmag.magic_read(in_file)
    if data_model == 2 and file_type != "magic_measurements":
        print('bad input file', file_type)
        sys.exit()
    if data_model == 3 and file_type != "measurements":
        print('bad input file', file_type)
        sys.exit()

    if data_model == 2:
        meth_code_col = 'magic_method_codes'
        spec_col = 'er_specimen_name'
        dec_col = "measurement_dec"
        inc_col = 'measurement_inc'
        moment_col = 'measurement_magn_moment'
        temp_col = 'treatment_temp'
    else:
        meth_code_col = 'method_codes'
        spec_col = 'specimen'
        dec_col = 'dir_dec'
        inc_col = 'dir_inc'
        moment_col = 'magn_moment'
        temp_col = "treat_temp"

    PmagRecs = pmag.get_dictitem(
        PmagRecs, meth_code_col, 'LP-IRM-3D', 'has')  # get all 3D IRM records

    if len(PmagRecs) == 0:
        print('no records found with the method code LP-IRM-3D')
        sys.exit()

    specs = pmag.get_dictkey(PmagRecs, spec_col, '')
    sids = []
    for spec in specs:
        if spec not in sids:
            sids.append(spec)  # get list of unique specimen names
    for spc in sids:  # step through the specimen names
        print(spc)
        specdata = pmag.get_dictitem(
            PmagRecs, spec_col, spc, 'T')  # get all this one's data

        DIMs, Temps = [], []
        for dat in specdata:  # step through the data
            DIMs.append([float(dat[dec_col]), float(
                dat[inc_col]), float(dat[moment_col])])
            Temps.append(float(dat[temp_col])-273.)
        carts = pmag.dir2cart(DIMs).transpose()
        if norm == 1:  # want to normalize
            nrm = (DIMs[0][2])  # normalize by NRM
            ylab = "M/M_o"
        else:
            nrm = 1.  # don't normalize
            ylab = "Magnetic moment (Am^2)"
        xlab = "Temperature (C)"
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, abs(carts[0]) / nrm, sym='r-')
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, abs(carts[0]) / nrm, sym='ro')  # X direction
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, abs(carts[1]) / nrm, sym='c-')
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, abs(carts[1]) / nrm, sym='cs')  # Y direction
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, abs(carts[2]) / nrm, sym='k-')
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, abs(carts[2]) / nrm, sym='k^', title=spc, xlab=xlab, ylab=ylab)  # Z direction
        files = {'lowrie': 'lowrie:_'+spc+'_.'+fmt}
        if plot == 0:
            pmagplotlib.draw_figs(FIG)
            ans = input('S[a]ve figure? [q]uit, <return> to continue   ')
            if ans == 'a':
                pmagplotlib.save_plots(FIG, files)
            elif ans == 'q':
                sys.exit()
        else:
            pmagplotlib.save_plots(FIG, files)
        pmagplotlib.clearFIG(FIG['lowrie'])
Exemplo n.º 14
0
def main():
    """
    NAME
        lowrie_magic.py

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

    SYNTAX
        lowrie_magic.py -h [command line options]

    INPUT
       takes measurements formatted input files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is magic_measurements.txt
        -N do not normalize by maximum magnetization
        -fmt [svg, pdf, eps, png] specify fmt, default is svg
        -sav saves plots and quits
        -DM [2, 3] MagIC data model number
    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if len(sys.argv) <= 1:
        print(main.__doc__)
        print('you must supply a file name')
        sys.exit()
    FIG = {}  # plot dictionary
    FIG['lowrie'] = 1  # demag is figure 1
    pmagplotlib.plot_init(FIG['lowrie'], 6, 6)
    norm = 1  # default is to normalize by maximum axis
    in_file = pmag.get_named_arg("-f", "measurements.txt")
    dir_path = pmag.get_named_arg("-WD", ".")
    in_file = pmag.resolve_file_name(in_file, dir_path)
    data_model = pmag.get_named_arg("-DM", 3)
    data_model = int(float(data_model))
    fmt = pmag.get_named_arg("-fmt", "svg")
    if '-N' in sys.argv:
        norm = 0  # don't normalize
    if '-sav' in sys.argv:
        plot = 1  # silently save and quit
    else:
        plot = 0  # generate plots
    print(in_file)
    # read in data
    PmagRecs, file_type = pmag.magic_read(in_file)
    if data_model == 2 and file_type != "magic_measurements":
        print('bad input file', file_type)
        sys.exit()
    if data_model == 3 and file_type != "measurements":
        print('bad input file', file_type)
        sys.exit()

    if data_model == 2:
        meth_code_col = 'magic_method_codes'
        spec_col = 'er_specimen_name'
        dec_col = "measurement_dec"
        inc_col = 'measurement_inc'
        moment_col = 'measurement_magn_moment'
        temp_col = 'treatment_temp'
    else:
        meth_code_col = 'method_codes'
        spec_col = 'specimen'
        dec_col = 'dir_dec'
        inc_col = 'dir_inc'
        moment_col = 'magn_moment'
        temp_col = "treat_temp"

    PmagRecs = pmag.get_dictitem(PmagRecs, meth_code_col, 'LP-IRM-3D',
                                 'has')  # get all 3D IRM records

    if len(PmagRecs) == 0:
        print('no records found with the method code LP-IRM-3D')
        sys.exit()

    specs = pmag.get_dictkey(PmagRecs, spec_col, '')
    sids = []
    for spec in specs:
        if spec not in sids:
            sids.append(spec)  # get list of unique specimen names
    for spc in sids:  # step through the specimen names
        print(spc)
        specdata = pmag.get_dictitem(PmagRecs, spec_col, spc,
                                     'T')  # get all this one's data

        DIMs, Temps = [], []
        for dat in specdata:  # step through the data
            DIMs.append([
                float(dat[dec_col]),
                float(dat[inc_col]),
                float(dat[moment_col])
            ])
            Temps.append(float(dat[temp_col]) - 273.)
        carts = pmag.dir2cart(DIMs).transpose()
        if norm == 1:  # want to normalize
            nrm = (DIMs[0][2])  # normalize by NRM
            ylab = "M/M_o"
        else:
            nrm = 1.  # don't normalize
            ylab = "Magnetic moment (Am^2)"
        xlab = "Temperature (C)"
        pmagplotlib.plot_xy(FIG['lowrie'],
                            Temps,
                            abs(carts[0]) / nrm,
                            sym='r-')
        pmagplotlib.plot_xy(FIG['lowrie'],
                            Temps,
                            abs(carts[0]) / nrm,
                            sym='ro')  # X direction
        pmagplotlib.plot_xy(FIG['lowrie'],
                            Temps,
                            abs(carts[1]) / nrm,
                            sym='c-')
        pmagplotlib.plot_xy(FIG['lowrie'],
                            Temps,
                            abs(carts[1]) / nrm,
                            sym='cs')  # Y direction
        pmagplotlib.plot_xy(FIG['lowrie'],
                            Temps,
                            abs(carts[2]) / nrm,
                            sym='k-')
        pmagplotlib.plot_xy(FIG['lowrie'],
                            Temps,
                            abs(carts[2]) / nrm,
                            sym='k^',
                            title=spc,
                            xlab=xlab,
                            ylab=ylab)  # Z direction
        files = {'lowrie': 'lowrie:_' + spc + '_.' + fmt}
        if plot == 0:
            pmagplotlib.draw_figs(FIG)
            ans = input('S[a]ve figure? [q]uit, <return> to continue   ')
            if ans == 'a':
                pmagplotlib.save_plots(FIG, files)
            elif ans == 'q':
                sys.exit()
        else:
            pmagplotlib.save_plots(FIG, files)
        pmagplotlib.clearFIG(FIG['lowrie'])
Exemplo n.º 15
0
def main():
    """
    NAME
        quick_hyst.py

    DESCRIPTION
        makes plots of hysteresis data

    SYNTAX
        quick_hyst.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f: specify input file, default is measurements.txt
        -spc SPEC: specify specimen name to plot and quit
        -sav save all plots and quit
        -fmt [png,svg,eps,jpg]
    """
    args = sys.argv
    if "-h" in args:
        print main.__doc__
        sys.exit()
    plots = 0
    pltspec = ""
    verbose = pmagplotlib.verbose
    # version_num = pmag.get_version()
    dir_path = pmag.get_named_arg_from_sys("-WD", ".")
    dir_path = os.path.realpath(dir_path)
    meas_file = pmag.get_named_arg_from_sys("-f", "measurements.txt")
    fmt = pmag.get_named_arg_from_sys("-fmt", "png")
    if "-sav" in args:
        verbose = 0
        plots = 1
    if "-spc" in args:
        ind = args.index("-spc")
        pltspec = args[ind + 1]
        verbose = 0
        plots = 1
    #
    con = nb.Contribution(dir_path, read_tables=["measurements"], custom_filenames={"measurements": meas_file})
    # get as much name data as possible (used for naming plots)
    if not "measurements" in con.tables:
        print "-W- No measurement file found"
        return
    con.propagate_name_down("location", "measurements")

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

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

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

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

        # get all records with non-blank values in any intlist column
        # find intensity data
        for int_column in intlist:
            if int_column in spec.columns:
                int_col = int_column
                break
        meas_data = spec[spec[int_column].notnull()]
        if len(meas_data) == 0:
            break
        #
        c = ["k-", "b-", "c-", "g-", "m-", "r-", "y-"]
        cnum = 0
        Temps = []
        xlab, ylab, title = "", "", ""
        Temps = meas_data["treat_temp"].unique()
        for t in Temps:
            print "working on t: ", t
            t_data = meas_data[meas_data["treat_temp"] == t]
            m = int_col
            B = t_data["meas_field_dc"].astype(float).values
            M = t_data[m].astype(float).values
            # now plot the hysteresis curve(s)
            #
            if len(B) > 0:
                B = numpy.array(B)
                M = numpy.array(M)
                if t == Temps[-1]:
                    xlab = "Field (T)"
                    ylab = m
                    title = "Hysteresis: " + s
                if t == Temps[0]:
                    pmagplotlib.clearFIG(HDD["hyst"])
                pmagplotlib.plotXY(HDD["hyst"], B, M, sym=c[cnum], xlab=xlab, ylab=ylab, title=title)
                pmagplotlib.plotXY(
                    HDD["hyst"], [1.1 * B.min(), 1.1 * B.max()], [0, 0], sym="k-", xlab=xlab, ylab=ylab, title=title
                )
                pmagplotlib.plotXY(
                    HDD["hyst"], [0, 0], [1.1 * M.min(), 1.1 * M.max()], sym="k-", xlab=xlab, ylab=ylab, title=title
                )
                if verbose:
                    pmagplotlib.drawFIGS(HDD)
                cnum += 1
                if cnum == len(c):
                    cnum = 0
        #
        files = {}
        if plots:
            if pltspec != "":
                s = pltspec
            for key in HDD.keys():
                if synth == "":
                    files[key] = (
                        "LO:_" + locname + "_SI:_" + site + "_SA:_" + sample + "_SP:_" + s + "_TY:_" + key + "_." + fmt
                    )
                else:
                    files[key] = "SY:_" + synth + "_TY:_" + key + "_." + fmt
            pmagplotlib.saveP(HDD, files)
            if pltspec != "":
                sys.exit()
        if verbose:
            pmagplotlib.drawFIGS(HDD)
            ans = raw_input("S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ")
            if ans == "a":
                files = {}
                for key in HDD.keys():
                    files[key] = (
                        "LO:_" + locname + "_SI:_" + site + "_SA:_" + sample + "_SP:_" + s + "_TY:_" + key + "_." + fmt
                    )
                pmagplotlib.saveP(HDD, files)
            if ans == "":
                k += 1
            if ans == "p":
                del HystRecs[-1]
                k -= 1
            if ans == "q":
                print "Good bye"
                sys.exit()
            if ans == "s":
                keepon = 1
                specimen = raw_input("Enter desired specimen name (or first part there of): ")
                while keepon == 1:
                    try:
                        k = sids.index(specimen)
                        keepon = 0
                    except:
                        tmplist = []
                        for qq in range(len(sids)):
                            if specimen in sids[qq]:
                                tmplist.append(sids[qq])
                        print specimen, " not found, but this was: "
                        print tmplist
                        specimen = raw_input("Select one or try again\n ")
                        k = sids.index(specimen)
        else:
            k += 1
        if len(B) == 0:
            if verbose:
                print "skipping this one - no hysteresis data"
            k += 1
Exemplo n.º 16
0
def main():
    """
    NAME
        thellier_magic.py

    DESCRIPTION
        plots Thellier-Thellier data in version 3.0 format
        Reads saved interpretations from a specimen formatted table, default: specimens.txt

    SYNTAX
        thellier_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f MEAS, set measurements input file, default is 'measurements.txt'
        -fsp PRIOR, set specimens.txt prior interpretations file, default is 'specimens.txt'
        -fcr CRIT, set criteria file for grading.  # not yet implemented
        -fmt [svg,png,jpg], format for images - default is svg
        -sav,  saves plots with out review (in format specified by -fmt key or default)
        -spc SPEC, plots single specimen SPEC, saves plot with specified format
            with optional -b bounds and quits
        -b BEG END: sets  bounds for calculation
           BEG: starting step number for slope calculation
           END: ending step number for slope calculation
        -z use only z component difference for pTRM calculation

    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 measuements)
                     list of possible commands: type letter followed by return to select option
                     saving of plots creates image files with specimen, plot type as name
    """
#
#   initializations
#
    version_num=pmag.get_version()
    verbose=pmagplotlib.verbose
#
# default acceptance criteria
#
    accept=pmag.default_criteria(0)[0] # set the default criteria
#
# parse command line options
#
    plots,fmt,Zdiff=0,'svg',0
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg_from_sys("-WD", default_val=os.getcwd())
    meas_file = pmag.get_named_arg_from_sys("-f", default_val="measurements.txt")
    spec_file=pmag.get_named_arg_from_sys("-fsp", default_val="specimens.txt")
    crit_file=pmag.get_named_arg_from_sys("-fcr", default_val="criteria.txt")
    spec_file=os.path.join(dir_path,spec_file)
    meas_file=os.path.join(dir_path,meas_file)
    crit_file=os.path.join(dir_path,crit_file)
    fmt = pmag.get_named_arg_from_sys("-fmt", "svg")
    if '-sav' in sys.argv: plots,verbose=1,0
    if '-z' in sys.argv: Zdiff=1
    specimen=pmag.get_named_arg_from_sys("-spc",default_val="")
    if '-b' in sys.argv:
        ind=sys.argv.index('-b')
        start=int(sys.argv[ind+1])
        end=int(sys.argv[ind+2])
    else:
        start,end="",""
    fnames = {'measurements': meas_file, 'specimens': spec_file, 'criteria': crit_file}
    contribution = nb.Contribution(dir_path, custom_filenames=fnames, read_tables=['measurements', 'specimens', 'criteria'])
#
#   import  prior interpretations  from specimen file
#
    specimen_cols = ['analysts', 'aniso_ftest', 'aniso_ftest12', 'aniso_ftest23', 'aniso_s', 'aniso_s_mean', 'aniso_s_n_measurements', 'aniso_s_sigma', 'aniso_s_unit', 'aniso_tilt_correction', 'aniso_type', 'aniso_v1', 'aniso_v2', 'aniso_v3', 'citations', 'description', 'dir_alpha95', 'dir_comp', 'dir_dec', 'dir_inc', 'dir_mad_free', 'dir_n_measurements', 'dir_tilt_correction', 'experiments', 'geologic_classes', 'geologic_types', 'hyst_bc', 'hyst_bcr', 'hyst_mr_moment', 'hyst_ms_moment', 'int_abs', 'int_b', 'int_b_beta', 'int_b_sigma', 'int_corr', 'int_dang', 'int_drats', 'int_f', 'int_fvds', 'int_gamma', 'int_mad_free', 'int_md', 'int_n_measurements', 'int_n_ptrm', 'int_q', 'int_rsc', 'int_treat_dc_field', 'lithologies', 'meas_step_max', 'meas_step_min', 'meas_step_unit', 'method_codes', 'sample', 'software_packages', 'specimen']
    if 'specimens' in contribution.tables:
        spec_container = contribution.tables['specimens']
        prior_spec_data=spec_container.get_records_for_code('LP-PI-TRM',strict_match=False) # look up all prior intensity interpretations
    else:
           spec_container, prior_spec_data = None, []
    backup=0
    #
    Mkeys = ['magn_moment', 'magn_volume', 'magn_mass']
#
#   create measurement dataframe
#
    meas_container = contribution.tables['measurements']
    meas_data = meas_container.df
#
    meas_data['method_codes']=meas_data['method_codes'].str.replace(" ","") # get rid of nasty spaces
    meas_data= meas_data[meas_data['method_codes'].str.contains('LP-PI-TRM|LP-TRM|LP-TRM-TD')==True] # fish out zero field steps for plotting
    intensity_types = [col_name for col_name in meas_data.columns if col_name in Mkeys]
    int_key = intensity_types[0] # plot first intensity method found - normalized to initial value anyway - doesn't matter which used
    meas_data = meas_data[meas_data[int_key].notnull()] # get all the non-null intensity records of the same type
    if 'flag' not in meas_data.columns: meas_data['flag'] = 'g' # set the default flag to good
    meas_data = meas_data[meas_data['flag'].str.contains('g')==True] # only the 'good' measurements
    thel_data = meas_data[meas_data['method_codes'].str.contains('LP-PI-TRM')==True] # get all the Thellier data
    trm_data = meas_data[meas_data['method_codes'].str.contains('LP-TRM')==True] # get all the TRM acquisition data
    td_data = meas_data[meas_data['method_codes'].str.contains('LP-TRM-TD')==True] # get all the TD data
    anis_data = meas_data[meas_data['method_codes'].str.contains('LP-AN')==True] # get all the anisotropy data
#
# get list of unique specimen names from measurement data
#
    specimen_names= meas_data.specimen.unique() # this is a Series of all the specimen names
    specimen_names= specimen_names.tolist() # turns it into a list
    specimen_names.sort() # sorts by specimen name
#
# set up new DataFrame for this sessions specimen interpretations
#
    spec_container = nb.MagicDataFrame(dtype='specimens', columns=specimen_cols)
    current_spec_data = spec_container.df # this is for interpretations from this session
    if specimen=="": # do all specimens
        k = 0
    else:
        k=specimen_names.index(specimen) # just do this one
    # define figure numbers for arai, zijderveld and
    #   de-,re-magnetization 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)
    if len(trm_data)>0:
        AZD['TRM']=5
        pmagplotlib.plot_init(AZD['TRM'],5,5)
    if len(td_data)>0:
        AZD['TDS']=6
        pmagplotlib.plot_init(AZD['TDS'],5,5)
    #
    while k < len(specimen_names):
        this_specimen=specimen_names[k] # set the current specimen for plotting
        if verbose and  this_specimen!="":print(this_specimen, k+1 , 'out of ',len(specimen_names))
#
#    set up datablocks
#
        thelblock= thel_data[thel_data['specimen'].str.contains(this_specimen)==True] # fish out this specimen
        trmblock= trm_data[trm_data['specimen'].str.contains(this_specimen)==True] # fish out this specimen
        tdsrecs= td_data[td_data['specimen'].str.contains(this_specimen)==True] # fish out this specimen
        anisblock= anis_data[anis_data['specimen'].str.contains(this_specimen)==True] # fish out the anisotropy data
        prior_specimen_interpretations= prior_spec_data[prior_spec_data['specimen'].str.contains(this_specimen)==True] # fish out prior interpretation
#
# sort data into types
#
        araiblock,field=pmag.sortarai(thelblock,this_specimen,Zdiff,version=3)
        first_Z=araiblock[0]
        GammaChecks=araiblock[5]
        if len(first_Z)<3:
           if backup==0:
                   k+=1
                   if verbose:
                       print('skipping specimen - moving forward ', this_specimen)
           else:
                   k-=1
                   if verbose:
                       print('skipping specimen - moving backward ', this_specimen)
        else:
               backup=0
               zijdblock,units=pmag.find_dmag_rec(this_specimen,thelblock,version=3)
               if start=="" and len(prior_specimen_interpretations)>0:
                   if verbose: print('Looking up saved interpretation....')
#
# get prior interpretation steps
#
                   beg_int=pd.to_numeric(prior_specimen_interpretations.meas_step_min.values).tolist()[0]
                   end_int=pd.to_numeric(prior_specimen_interpretations.meas_step_max.values).tolist()[0]
               else: beg_int,end_int="",""
               recnum=0
               if verbose: print("index step Dec   Inc  Int       Gamma")
               for plotrec in zijdblock:
                   if plotrec[0]==beg_int:start=recnum # while we are at it, collect these bounds
                   if plotrec[0]==end_int:end=recnum
                   if verbose:
                       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
               for fig in list(AZD.keys()):pmagplotlib.clearFIG(AZD[fig]) # clear all figures
               pmagplotlib.plotAZ(AZD,araiblock,zijdblock,this_specimen,units[0])
               if verbose:pmagplotlib.drawFIGS(AZD)
               pars,errcode=pmag.PintPars(thelblock,araiblock,zijdblock,start,end,accept,version=3)
               pars['measurement_step_unit']="K"
               pars['experiment_type']='LP-PI-TRM'
#
# work on saving interpretations stuff later
#
               if errcode!=1: # no problem in PintPars
                    pars["specimen_lab_field_dc"]=field
                    pars["specimen_int"]=-1*field*pars["specimen_b"]
                    pars["er_specimen_name"]=this_specimen
                    #pars,kill=pmag.scoreit(pars,this_specimen_interpretation,accept,'',verbose) # deal with this later
                    pars["specimen_grade"]='None'
                    pars['measurement_step_min']=pars['meas_step_min']
                    pars['measurement_step_max']=pars['meas_step_max']
                    if pars['measurement_step_unit']=='K':
                        outstr= "specimen     Tmin  Tmax  N  lab_field  B_anc  b  q  f(coe)  Fvds  beta  MAD  Dang  Drats  Nptrm  Grade  R  MD%  sigma  Gamma_max \n"
                        pars_out= (this_specimen,(pars["meas_step_min"]-273),(pars["meas_step_max"]-273),(pars["specimen_int_n"]),1e6*(pars["specimen_lab_field_dc"]),1e6*(pars["specimen_int"]),pars["specimen_b"],pars["specimen_q"],pars["specimen_f"],pars["specimen_fvds"],pars["specimen_b_beta"],pars["int_mad_free"],pars["int_dang"],pars["int_drats"],pars["int_n_ptrm"],pars["specimen_grade"],np.sqrt(pars["specimen_rsc"]),int(pars["int_md"]), pars["specimen_b_sigma"],pars['specimen_gamma'])
                        outstring= '%s %4.0f %4.0f %i %4.1f %4.1f %5.3f %5.1f %5.3f %5.3f %5.3f  %7.1f %7.1f %7.1f %s %s %6.3f %i %5.3f %7.1f' % pars_out +'\n'
                    elif pars['measurement_step_unit']=='J':
                        outstr= "specimen     Wmin  Wmax  N  lab_field  B_anc  b  q  f(coe)  Fvds  beta  MAD  Dang  Drats  Nptrm  Grade  R  MD%  sigma  ThetaMax DeltaMax GammaMax\n"
                        pars_out= (this_specimen,(pars["meas_step_min"]),(pars["meas_step_max"]),(pars["specimen_int_n"]),1e6*(pars["specimen_lab_field_dc"]),1e6*(pars["specimen_int"]),pars["specimen_b"],pars["specimen_q"],pars["specimen_f"],pars["specimen_fvds"],pars["specimen_b_beta"],pars["specimen_int_mad"],pars["specimen_int_dang"],pars["specimen_drats"],pars["specimen_int_ptrm_n"],pars["specimen_grade"],np.sqrt(pars["specimen_rsc"]),int(pars["specimen_md"]), pars["specimen_b_sigma"],pars["specimen_theta"],pars["specimen_delta"],pars["specimen_gamma"])
                        outstring= '%s %4.0f %4.0f %i %4.1f %4.1f %5.3f %5.1f %5.3f %5.3f %5.3f  %7.1f %7.1f %7.1f %s %s %6.3f %i %5.3f %7.1f %7.1f %7.1f' % pars_out +'\n'
                    print(outstr)
                    print(outstring)
                    pmagplotlib.plotB(AZD,araiblock,zijdblock,pars)
                    mpars=pmag.domean(araiblock[1],start,end,'DE-BFL')
                    if verbose:
                        pmagplotlib.drawFIGS(AZD)
                        print('pTRM direction= ','%7.1f'%(mpars['specimen_dec']),' %7.1f'%(mpars['specimen_inc']),' MAD:','%7.1f'%(mpars['specimen_mad']))
               if len(anisblock)>0:  # this specimen has anisotropy data
                           if verbose: print('Found anisotropy record... but ignoring for now ')
               if plots==1:
                   if fmt != "pmag":
                       files={}
                       for key in list(AZD.keys()):
                           files[key]='SP:_'+this_specimen+'_TY:_'+key+'_'+'.'+fmt
                       if pmagplotlib.isServer:
                           black     = '#000000'
                           purple    = '#800080'
                           titles={}
                           titles['deremag']='DeReMag Plot'
                           titles['zijd']='Zijderveld Plot'
                           titles['arai']='Arai Plot'
                           titles['TRM']='TRM Acquisition data'
                           AZD = pmagplotlib.addBorders(AZD,titles,black,purple)
                       pmagplotlib.saveP(AZD,files)
                   else:  # save in pmag format
                       print('pmag format no longer supported')
                       #script="grep "+this_specimen+" 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 specimen!="": sys.exit() # syonara
               if verbose:
                   ans=input('Return for next specimen, q to quit:  ')
                   if ans=='q':sys.exit()
               k+=1 # moving on
Exemplo n.º 17
0
def main():
    """
    NAME
        dmag_magic.py

    DESCRIPTION
       plots intensity decay curves for demagnetization experiments

    SYNTAX
        dmag_magic -h [command line options]

    INPUT
       takes magic formatted magic_measurements.txt files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: magic_measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot,
               default is by location
        -LT [AF,T,M]: specify lab treatment type, default AF
        -XLP [PI]: exclude specific  lab protocols,
               (for example, method codes like LP-PI)
        -N do not normalize by NRM magnetization
        -sav save plots silently and quit
        -fmt [svg,jpg,png,pdf] set figure format [default is svg]
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    # initialize variables from command line + defaults
    FIG = {}  # plot dictionary
    FIG['demag'] = 1  # demag is figure 1
    in_file = pmag.get_named_arg_from_sys("-f", default_val="measurements.txt")
    plot_by = pmag.get_named_arg_from_sys("-obj", default_val="loc")
    name_dict = {
        'loc': 'location',
        'sit': 'site',
        'sam': 'sample',
        'spc': 'specimen'
    }
    plot_key = name_dict[plot_by]
    LT = "LT-" + pmag.get_named_arg_from_sys("-LT", "AF") + "-Z"
    if LT == "LT-T-Z":
        units, dmag_key = 'K', 'treat_temp'
    elif LT == "LT-AF-Z":
        units, dmag_key = 'T', 'treat_ac_field'
    elif LT == 'LT-M-Z':
        units, dmag_key = 'J', 'treat_mw_energy'
    else:
        units = 'U'
    no_norm = pmag.get_flag_arg_from_sys("-N")
    norm = 0 if no_norm else 1
    no_plot = pmag.get_flag_arg_from_sys("-sav")
    plot = 0 if no_plot else 1
    fmt = pmag.get_named_arg_from_sys("-fmt", "svg")
    XLP = pmag.get_named_arg_from_sys("-XLP", "")
    dir_path = pmag.get_named_arg_from_sys("-WD", os.getcwd())
    spec_file = pmag.get_named_arg_from_sys("-fsp",
                                            default_val="specimens.txt")
    samp_file = pmag.get_named_arg_from_sys("-fsa", default_val="samples.txt")
    site_file = pmag.get_named_arg_from_sys("-fsi", default_val="sites.txt")

    # create contribution and add required headers
    fnames = {"specimens": spec_file, "samples": samp_file, 'sites': site_file}
    contribution = nb.Contribution(dir_path,
                                   single_file=in_file,
                                   custom_filenames=fnames)
    file_type = list(contribution.tables.keys())[0]
    print(len(contribution.tables['measurements'].df), ' records read from ',
          in_file)
    # add plot_key into measurements table
    if plot_key not in contribution.tables['measurements'].df.columns:
        #contribution.propagate_name_down(plot_key, 'measurements')
        contribution.propagate_location_to_measurements()
    data_container = contribution.tables[file_type]
    # pare down to only records with useful data
    # grab records that have the requested code
    data_slice = data_container.get_records_for_code(LT)
    # and don't have the offending code
    data = data_container.get_records_for_code(XLP,
                                               incl=False,
                                               use_slice=True,
                                               sli=data_slice,
                                               strict_match=False)

    # make sure quality is in the dataframe
    if 'quality' not in data.columns:
        data['quality'] = 'g'
    # get intensity key and make sure intensity data is not blank
    intlist = ['magn_moment', 'magn_volume', 'magn_mass']
    IntMeths = [col_name for col_name in data.columns if col_name in intlist]
    # get rid of any entirely blank intensity columns
    for col_name in IntMeths:
        if not data[col_name].any():
            data.drop(col_name, axis=1, inplace=True)
    IntMeths = [col_name for col_name in data.columns if col_name in intlist]
    if len(IntMeths) == 0:
        print('No intensity headers found')
        sys.exit()

    int_key = IntMeths[
        0]  # plot first intensity method found - normalized to initial value anyway - doesn't matter which used
    data = data[data[int_key].notnull()]
    # make list of individual plots
    # by default, will be by location_name
    plotlist = data[plot_key].unique()
    plotlist.sort()
    pmagplotlib.plot_init(FIG['demag'], 5, 5)
    # iterate through and plot the data
    for plt in plotlist:
        plot_data = data[data[plot_key] == plt].copy()
        if plot:
            print(plt, 'plotting by: ', plot_key)
        if len(plot_data) > 2:
            title = plt
            spcs = []
            spcs = plot_data['specimen'].unique()
            for spc in spcs:
                INTblock = []
                spec_data = plot_data[plot_data['specimen'] == spc]
                for ind, rec in spec_data.iterrows():
                    INTblock.append([
                        float(rec[dmag_key]), 0, 0,
                        float(rec[int_key]), 1, rec['quality']
                    ])
                if len(INTblock) > 2:
                    pmagplotlib.plotMT(FIG['demag'], INTblock, title, 0, units,
                                       norm)

            if not plot:
                files = {}
                for key in list(FIG.keys()):
                    files[key] = title + '_' + LT + '.' + fmt
                pmagplotlib.saveP(FIG, files)
                #sys.exit()
            else:
                pmagplotlib.drawFIGS(FIG)
                prompt = " S[a]ve to save plot, [q]uit,  Return to continue:  "
                ans = input(prompt)
                if ans == 'q':
                    sys.exit()
                if ans == "a":
                    files = {}
                    for key in list(FIG.keys()):
                        files[key] = title + '_' + LT + '.' + fmt
                    pmagplotlib.saveP(FIG, files)
            pmagplotlib.clearFIG(FIG['demag'])
Exemplo n.º 18
0
def main():
    """
    NAME
        irmaq_magic.py

    DESCRIPTION
       plots IRM acquisition curves from measurements file

    SYNTAX
        irmaq_magic [command line options]

    INPUT
       takes magic formatted magic_measurements.txt files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: magic_measurements.txt/measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot, default is by location
        -N ; do not normalize by last point - use original units
        -fmt [png,jpg,eps,pdf] set plot file format [default is svg]
        -sav save plot[s] and quit
        -DM MagIC data model number, default is 3
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    FIG = {}  # plot dictionary
    FIG['exp'] = 1  # exp is figure 1
    dir_path = './'
    plot, fmt = 0, 'svg'
    units = 'T',
    XLP = []
    norm = 1
    LP = "LP-IRM"
    if len(sys.argv) > 1:
        if '-h' in sys.argv:
            print(main.__doc__)
            sys.exit()
        data_model = int(pmag.get_named_arg("-DM", 3))
        if '-N' in sys.argv:
            norm = 0
        if '-sav' in sys.argv:
            plot = 1
        if '-fmt' in sys.argv:
            ind = sys.argv.index("-fmt")
            fmt = sys.argv[ind + 1]
        if data_model == 3:
            in_file = pmag.get_named_arg("-f", 'measurements.txt')
        else:
            in_file = pmag.get_named_arg("-f", 'magic_measurements.txt')
        if '-WD' in sys.argv:
            ind = sys.argv.index('-WD')
            dir_path = sys.argv[ind + 1]
        dir_path = os.path.realpath(dir_path)
        in_file = pmag.resolve_file_name(in_file, dir_path)
        if '-WD' not in sys.argv:
            dir_path = os.path.split(in_file)[0]
        plot_by = pmag.get_named_arg("-obj", "loc")
        if data_model == 3:
            plot_key = 'location'
            if plot_by == 'sit':
                plot_key = 'site'
            if plot_by == 'sam':
                plot_key = 'sample'
            if plot_by == 'spc':
                plot_key = 'specimen'
        else:
            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'

    # set defaults and get more information if needed
    if data_model == 3:
        dmag_key = 'treat_dc_field'
    else:
        dmag_key = 'treatment_dc_field'
    #
    if data_model == 3 and plot_key != 'specimen':
        # gonna need to read in more files
        print('-W- You are trying to plot measurements by {}'.format(plot_key))
        print(
            '    By default, this information is not available in your measurement file.'
        )
        print(
            '    Trying to acquire this information from {}'.format(dir_path))
        con = cb.Contribution(dir_path)
        meas_df = con.propagate_location_to_measurements()
        if meas_df is None:
            print('-W- No data found in {}'.format(dir_path))
            return
        if plot_key not in meas_df.columns:
            print('-W- Could not find required data.')
            print('    Try a different plot key.')
            return
        else:
            print('-I- Found {} information, continuing with plotting'.format(
                plot_key))
        # need to take the data directly from the contribution here, to keep
        # location/site/sample columns in the measurements table
        data = con.tables['measurements'].convert_to_pmag_data_list()
        file_type = "measurements"
    else:
        data, file_type = pmag.magic_read(in_file)
    # read in data
    sids = pmag.get_specs(data)
    pmagplotlib.plot_init(FIG['exp'], 6, 6)
    #
    #
    # find desired intensity data
    #
    # get plotlist
    #
    plotlist = []
    if data_model == 3:
        intlist = ['magn_moment', 'magn_volume', 'magn_mass', 'magnitude']
    else:
        intlist = [
            'measurement_magnitude', 'measurement_magn_moment',
            'measurement_magn_volume', 'measurement_magn_mass'
        ]
    IntMeths = []
    # get all the records with this lab protocol
    #print('data', len(data))
    #print('data[0]', data[0])
    if data_model == 3:
        data = pmag.get_dictitem(data, 'method_codes', LP, 'has')
    else:
        data = pmag.get_dictitem(data, 'magic_method_codes', LP, 'has')
    Ints = {}
    NoInts, int_key = 1, ""
    for key in intlist:
        # get all non-blank data for intensity type
        Ints[key] = pmag.get_dictitem(data, key, '', 'F')
        if len(Ints[key]) > 0:
            NoInts = 0
            if int_key == "":
                int_key = key
    if NoInts == 1:
        print('No intensity information found')
        sys.exit()
    for rec in Ints[int_key]:
        if rec[plot_key] not in plotlist:
            plotlist.append(rec[plot_key])
    plotlist.sort()
    for plt in plotlist:
        print(plt)
        INTblock = []
        # get data with right intensity info whose plot_key matches plot
        data = pmag.get_dictitem(Ints[int_key], plot_key, plt, 'T')
        # get a list of specimens with appropriate data
        sids = pmag.get_specs(data)
        if len(sids) > 0:
            title = data[0][plot_key]
        for s in sids:
            INTblock = []
            # get data for each specimen
            if data_model == 3:
                sdata = pmag.get_dictitem(data, 'specimen', s, 'T')
            else:
                sdata = pmag.get_dictitem(data, 'er_specimen_name', s, 'T')
            for rec in sdata:
                INTblock.append(
                    [float(rec[dmag_key]), 0, 0,
                     float(rec[int_key]), 1, 'g'])
            pmagplotlib.plot_mag(FIG['exp'], INTblock, title, 0, units, norm)
        files = {}
        for key in list(FIG.keys()):
            files[key] = title + '_' + LP + '.' + fmt
        if plot == 0:
            pmagplotlib.draw_figs(FIG)
            ans = input(" S[a]ve to save plot, [q]uit,  Return to continue:  ")
            if ans == 'q':
                sys.exit()
            if ans == "a":
                pmagplotlib.save_plots(FIG, files)
            if plt != plotlist[
                    -1]:  # if it isn't the last plot, init the next one
                pmagplotlib.plot_init(FIG['exp'], 6, 6)
        else:
            pmagplotlib.save_plots(FIG, files)
        pmagplotlib.clearFIG(FIG['exp'])
Exemplo n.º 19
0
def main():
    """
    NAME
        hysteresis_magic.py

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

    SYNTAX
        hysteresis_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -usr USER:   identify user, default is ""
        -f: specify input file, default is agm_measurements.txt
        -fh: specify rmag_hysteresis.txt input file
        -F: specify output file, default is rmag_hysteresis.txt
        -P: do not make the plots
        -spc SPEC: specify specimen name to plot and quit
        -sav save all plots and quit
        -fmt [png,svg,eps,jpg]
    """
    args=sys.argv
    PLT=1
    plots=0
    user,meas_file,rmag_out,rmag_file="","agm_measurements.txt","rmag_hysteresis.txt",""
    pltspec=""
    dir_path='.'
    fmt='svg'
    verbose=pmagplotlib.verbose
    version_num=pmag.get_version()
    if '-WD' in args:
        ind=args.index('-WD')
        dir_path=args[ind+1]
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    if "-usr" in args:
        ind=args.index("-usr")
        user=args[ind+1]
    if '-f' in args:
        ind=args.index("-f")
        meas_file=args[ind+1]
    if '-F' in args:
        ind=args.index("-F")
        rmag_out=args[ind+1]
    if '-fh' in args:
        ind=args.index("-fh")
        rmag_file=args[ind+1]
        rmag_file=dir_path+'/'+rmag_file
    if '-P' in args:
        PLT=0
        irm_init,imag_init=-1,-1
    if '-sav' in args:
        verbose=0
        plots=1
    if '-spc' in args:
        ind=args.index("-spc")
        pltspec= args[ind+1]
        verbose=0
        plots=1
    if '-fmt' in args:
        ind=args.index("-fmt")
        fmt=args[ind+1]
    rmag_out=dir_path+'/'+rmag_out
    meas_file=dir_path+'/'+meas_file
    rmag_rem=dir_path+"/rmag_remanence.txt"
    #
    #
    meas_data,file_type=pmag.magic_read(meas_file)
    if file_type!='magic_measurements':
        print(main.__doc__)
        print('bad file')
        sys.exit()
    #
    # initialize some variables
    # define figure numbers for hyst,deltaM,DdeltaM curves
    HystRecs,RemRecs=[],[]
    HDD={}
    if verbose:
        if verbose and PLT:print("Plots may be on top of each other - use mouse to place ")
    if PLT:
        HDD['hyst'],HDD['deltaM'],HDD['DdeltaM']=1,2,3
        pmagplotlib.plot_init(HDD['DdeltaM'],5,5)
        pmagplotlib.plot_init(HDD['deltaM'],5,5)
        pmagplotlib.plot_init(HDD['hyst'],5,5)
        imag_init=0
        irm_init=0
    else:
        HDD['hyst'],HDD['deltaM'],HDD['DdeltaM'],HDD['irm'],HDD['imag']=0,0,0,0,0
    #
    if rmag_file!="":hyst_data,file_type=pmag.magic_read(rmag_file)
    #
    # get list of unique experiment names and specimen names
    #
    experiment_names,sids=[],[]
    for rec in meas_data:
      meths=rec['magic_method_codes'].split(':')
      methods=[]
      for meth in meths:
        methods.append(meth.strip())
      if 'LP-HYS' in methods:
        if 'er_synthetic_name' in list(rec.keys()) and rec['er_synthetic_name']!="":
            rec['er_specimen_name']=rec['er_synthetic_name']
        if rec['magic_experiment_name'] not in experiment_names:experiment_names.append(rec['magic_experiment_name'])
        if rec['er_specimen_name'] not in sids:sids.append(rec['er_specimen_name'])
    #
    k=0
    locname=''
    if pltspec!="":
        k=sids.index(pltspec)
        print(sids[k])
    while k < len(sids):
        s=sids[k]
        if verbose and PLT:print(s, k+1 , 'out of ',len(sids))
    #
    #
        B,M,Bdcd,Mdcd=[],[],[],[] #B,M for hysteresis, Bdcd,Mdcd for irm-dcd data
        Bimag,Mimag=[],[] #Bimag,Mimag for initial magnetization curves
        first_dcd_rec,first_rec,first_imag_rec=1,1,1
        for rec in  meas_data:
            methcodes=rec['magic_method_codes'].split(':')
            meths=[]
            for meth in methcodes:
                meths.append(meth.strip())
            if rec['er_specimen_name']==s and "LP-HYS" in meths:
                B.append(float(rec['measurement_lab_field_dc']))
                M.append(float(rec['measurement_magn_moment']))
                if first_rec==1:
                    e=rec['magic_experiment_name']
                    HystRec={}
                    first_rec=0
                    if "er_location_name" in list(rec.keys()):
                        HystRec["er_location_name"]=rec["er_location_name"]
                        locname=rec['er_location_name'].replace('/','-')
                    if "er_sample_name" in list(rec.keys()):HystRec["er_sample_name"]=rec["er_sample_name"]
                    if "er_site_name" in list(rec.keys()):HystRec["er_site_name"]=rec["er_site_name"]
                    if "er_synthetic_name" in list(rec.keys()) and rec['er_synthetic_name']!="":
                        HystRec["er_synthetic_name"]=rec["er_synthetic_name"]
                    else:
                        HystRec["er_specimen_name"]=rec["er_specimen_name"]
            if rec['er_specimen_name']==s and "LP-IRM-DCD" in meths:
                Bdcd.append(float(rec['treatment_dc_field']))
                Mdcd.append(float(rec['measurement_magn_moment']))
                if first_dcd_rec==1:
                    RemRec={}
                    irm_exp=rec['magic_experiment_name']
                    first_dcd_rec=0
                    if "er_location_name" in list(rec.keys()):RemRec["er_location_name"]=rec["er_location_name"]
                    if "er_sample_name" in list(rec.keys()):RemRec["er_sample_name"]=rec["er_sample_name"]
                    if "er_site_name" in list(rec.keys()):RemRec["er_site_name"]=rec["er_site_name"]
                    if "er_synthetic_name" in list(rec.keys()) and rec['er_synthetic_name']!="":
                        RemRec["er_synthetic_name"]=rec["er_synthetic_name"]
                    else:
                        RemRec["er_specimen_name"]=rec["er_specimen_name"]
            if rec['er_specimen_name']==s and "LP-IMAG" in meths:
                if first_imag_rec==1:
                    imag_exp=rec['magic_experiment_name']
                    first_imag_rec=0
                Bimag.append(float(rec['measurement_lab_field_dc']))
                Mimag.append(float(rec['measurement_magn_moment']))
    #
    # now plot the hysteresis curve
    #
        if len(B)>0:
            hmeths=[]
            for meth in meths: hmeths.append(meth)
            hpars=pmagplotlib.plotHDD(HDD,B,M,e)
            if verbose and PLT:pmagplotlib.drawFIGS(HDD)
    #
    # get prior interpretations from hyst_data
            if rmag_file!="":
                hpars_prior={}
                for rec in hyst_data:
                    if rec['magic_experiment_names']==e:
                        if rec['hysteresis_bcr'] !="" and rec['hysteresis_mr_moment']!="":
                            hpars_prior['hysteresis_mr_moment']=rec['hysteresis_mr_moment']
                            hpars_prior['hysteresis_ms_moment']=rec['hysteresis_ms_moment']
                            hpars_prior['hysteresis_bc']=rec['hysteresis_bc']
                            hpars_prior['hysteresis_bcr']=rec['hysteresis_bcr']
                            break
                if verbose:pmagplotlib.plotHPARS(HDD,hpars_prior,'ro')
            else:
                if verbose:pmagplotlib.plotHPARS(HDD,hpars,'bs')
                HystRec['hysteresis_mr_moment']=hpars['hysteresis_mr_moment']
                HystRec['hysteresis_ms_moment']=hpars['hysteresis_ms_moment']
                HystRec['hysteresis_bc']=hpars['hysteresis_bc']
                HystRec['hysteresis_bcr']=hpars['hysteresis_bcr']
                HystRec['hysteresis_xhf']=hpars['hysteresis_xhf']
                HystRec['magic_experiment_names']=e
                HystRec['magic_software_packages']=version_num
                if hpars["magic_method_codes"] not in hmeths:hmeths.append(hpars["magic_method_codes"])
                methods=""
                for meth in hmeths:
                    methods=methods+meth.strip()+":"
                HystRec["magic_method_codes"]=methods[:-1]
                HystRec["er_citation_names"]="This study"
                HystRecs.append(HystRec)
    #
        if len(Bdcd)>0:
            rmeths=[]
            for meth in meths: rmeths.append(meth)
            if verbose and PLT:print('plotting IRM')
            if irm_init==0:
                HDD['irm']=5
                pmagplotlib.plot_init(HDD['irm'],5,5)
                irm_init=1
            rpars=pmagplotlib.plotIRM(HDD['irm'],Bdcd,Mdcd,irm_exp)
            RemRec['remanence_mr_moment']=rpars['remanence_mr_moment']
            RemRec['remanence_bcr']=rpars['remanence_bcr']
            RemRec['magic_experiment_names']=irm_exp
            if rpars["magic_method_codes"] not in meths:meths.append(rpars["magic_method_codes"])
            methods=""
            for meth in rmeths:
                methods=methods+meth.strip()+":"
            RemRec["magic_method_codes"]=methods[:-1]
            RemRec["er_citation_names"]="This study"
            RemRecs.append(RemRec)
        else:
            if irm_init:pmagplotlib.clearFIG(HDD['irm'])
        if len(Bimag)>0:
            if verbose:print('plotting initial magnetization curve')
# first normalize by Ms
            Mnorm=[]
            for m in Mimag: Mnorm.append(old_div(m,float(hpars['hysteresis_ms_moment'])))
            if imag_init==0:
                HDD['imag']=4
                pmagplotlib.plot_init(HDD['imag'],5,5)
                imag_init=1
            pmagplotlib.plotIMAG(HDD['imag'],Bimag,Mnorm,imag_exp)
        else:
            if imag_init:pmagplotlib.clearFIG(HDD['imag'])
    #
        files={}
        if plots:
            if pltspec!="":s=pltspec
            files={}
            for key in list(HDD.keys()):
                files[key]=locname+'_'+s+'_'+key+'.'+fmt
            pmagplotlib.saveP(HDD,files)
            if pltspec!="":sys.exit()
        if verbose and PLT:
            pmagplotlib.drawFIGS(HDD)
            ans=input("S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ")
            if ans=="a":
                files={}
                for key in list(HDD.keys()):
                    files[key]=locname+'_'+s+'_'+key+'.'+fmt
                pmagplotlib.saveP(HDD,files)
            if ans=='':k+=1
            if ans=="p":
                del HystRecs[-1]
                k-=1
            if  ans=='q':
                print("Good bye")
                sys.exit()
            if ans=='s':
                keepon=1
                specimen=input('Enter desired specimen name (or first part there of): ')
                while keepon==1:
                    try:
                        k =sids.index(specimen)
                        keepon=0
                    except:
                        tmplist=[]
                        for qq in range(len(sids)):
                            if specimen in sids[qq]:tmplist.append(sids[qq])
                        print(specimen," not found, but this was: ")
                        print(tmplist)
                        specimen=input('Select one or try again\n ')
                        k =sids.index(specimen)
        else:
            k+=1
        if len(B)==0 and len(Bdcd)==0:
            if verbose:print('skipping this one - no hysteresis data')
            k+=1
    if rmag_out=="" and ans=='s' and verbose:
        really=input(" Do you want to overwrite the existing rmag_hystersis.txt file? 1/[0] ")
        if really=="":
            print('i thought not - goodbye')
            sys.exit()
        rmag_out="rmag_hysteresis.txt"
    if len(HystRecs)>0:
        pmag.magic_write(rmag_out,HystRecs,"rmag_hysteresis")
        if verbose:print("hysteresis parameters saved in ",rmag_out)
    if len(RemRecs)>0:
        pmag.magic_write(rmag_rem,RemRecs,"rmag_remanence")
        if verbose:print("remanence parameters saved in ",rmag_rem)
Exemplo n.º 20
0
def main():
    """
    NAME
        irmaq_magic.py

    DESCRIPTION
       plots IRM acquisition curves from measurements file

    SYNTAX
        irmaq_magic [command line options]

    INPUT
       takes magic formatted magic_measurements.txt files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: magic_measurements.txt/measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot, default is by location
        -N ; do not normalize by last point - use original units
        -fmt [png,jpg,eps,pdf] set plot file format [default is svg]
        -sav save plot[s] and quit
        -DM MagIC data model number, default is 3
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    FIG = {}  # plot dictionary
    FIG['exp'] = 1  # exp is figure 1
    dir_path = './'
    plot, fmt = 0, 'svg'
    units = 'T',
    XLP = []
    norm = 1
    LP = "LP-IRM"
    if len(sys.argv) > 1:
        if '-h' in sys.argv:
            print(main.__doc__)
            sys.exit()
        data_model = int(pmag.get_named_arg("-DM", 3))
        if '-N' in sys.argv:
            norm = 0
        if '-sav' in sys.argv:
            plot = 1
        if '-fmt' in sys.argv:
            ind = sys.argv.index("-fmt")
            fmt = sys.argv[ind + 1]
        if data_model == 3:
            in_file = pmag.get_named_arg("-f", 'measurements.txt')
        else:
            in_file = pmag.get_named_arg("-f", 'magic_measurements.txt')
        if '-WD' in sys.argv:
            ind = sys.argv.index('-WD')
            dir_path = sys.argv[ind + 1]
        dir_path = os.path.realpath(dir_path)
        in_file = pmag.resolve_file_name(in_file, dir_path)
        if '-WD' not in sys.argv:
            dir_path = os.path.split(in_file)[0]
        plot_by = pmag.get_named_arg("-obj", "loc")
        if data_model == 3:
            plot_key = 'location'
            if plot_by == 'sit':
                plot_key = 'site'
            if plot_by == 'sam':
                plot_key = 'sample'
            if plot_by == 'spc':
                plot_key = 'specimen'
        else:
            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'

    # set defaults and get more information if needed
    if data_model == 3:
        dmag_key = 'treat_dc_field'
    else:
        dmag_key = 'treatment_dc_field'
    #
    if data_model == 3 and plot_key != 'specimen':
        # gonna need to read in more files
        print('-W- You are trying to plot measurements by {}'.format(plot_key))
        print('    By default, this information is not available in your measurement file.')
        print('    Trying to acquire this information from {}'.format(dir_path))
        con = cb.Contribution(dir_path)
        meas_df = con.propagate_location_to_measurements()
        if meas_df is None:
            print('-W- No data found in {}'.format(dir_path))
            return
        if plot_key not in meas_df.columns:
            print('-W- Could not find required data.')
            print('    Try a different plot key.')
            return
        else:
            print('-I- Found {} information, continuing with plotting'.format(plot_key))
        # need to take the data directly from the contribution here, to keep
        # location/site/sample columns in the measurements table
        data = con.tables['measurements'].convert_to_pmag_data_list()
        file_type = "measurements"
    else:
        data, file_type = pmag.magic_read(in_file)
    # read in data
    sids = pmag.get_specs(data)
    pmagplotlib.plot_init(FIG['exp'], 6, 6)
    #
    #
    # find desired intensity data
    #
    # get plotlist
    #
    plotlist = []
    if data_model == 3:
        intlist = ['magn_moment', 'magn_volume', 'magn_mass', 'magnitude']
    else:
        intlist = ['measurement_magnitude', 'measurement_magn_moment',
                    'measurement_magn_volume', 'measurement_magn_mass']
    IntMeths = []
    # get all the records with this lab protocol
    #print('data', len(data))
    #print('data[0]', data[0])
    if data_model == 3:
        data = pmag.get_dictitem(data, 'method_codes', LP, 'has')
    else:
        data = pmag.get_dictitem(data, 'magic_method_codes', LP, 'has')
    Ints = {}
    NoInts, int_key = 1, ""
    for key in intlist:
        # get all non-blank data for intensity type
        Ints[key] = pmag.get_dictitem(data, key, '', 'F')
        if len(Ints[key]) > 0:
            NoInts = 0
            if int_key == "":
                int_key = key
    if NoInts == 1:
        print('No intensity information found')
        sys.exit()
    for rec in Ints[int_key]:
        if rec[plot_key] not in plotlist:
            plotlist.append(rec[plot_key])
    plotlist.sort()
    for plt in plotlist:
        print(plt)
        INTblock = []
        # get data with right intensity info whose plot_key matches plot
        data = pmag.get_dictitem(Ints[int_key], plot_key, plt, 'T')
        # get a list of specimens with appropriate data
        sids = pmag.get_specs(data)
        if len(sids) > 0:
            title = data[0][plot_key]
        for s in sids:
            INTblock = []
            # get data for each specimen
            if data_model == 3:
                sdata = pmag.get_dictitem(data, 'specimen', s, 'T')
            else:
                sdata = pmag.get_dictitem(data, 'er_specimen_name', s, 'T')
            for rec in sdata:
                INTblock.append([float(rec[dmag_key]), 0, 0,
                                 float(rec[int_key]), 1, 'g'])
            pmagplotlib.plot_mag(FIG['exp'], INTblock, title, 0, units, norm)
        files = {}
        for key in list(FIG.keys()):
            files[key] = title + '_' + LP + '.' + fmt
        if plot == 0:
            pmagplotlib.draw_figs(FIG)
            ans = input(" S[a]ve to save plot, [q]uit,  Return to continue:  ")
            if ans == 'q':
                sys.exit()
            if ans == "a":
                pmagplotlib.save_plots(FIG, files)
            if plt != plotlist[-1]: # if it isn't the last plot, init the next one
                pmagplotlib.plot_init(FIG['exp'], 6, 6)
        else:
            pmagplotlib.save_plots(FIG, files)
        pmagplotlib.clearFIG(FIG['exp'])
Exemplo n.º 21
0
def plot(in_file="measurements.txt", dir_path=".", input_dir_path="",
         spec_file="specimens.txt", samp_file="samples.txt",
         site_file="sites.txt", loc_file="locations.txt",
         plot_by="loc", LT="AF", norm=True, XLP="",
         save_plots=True, fmt="svg"):

    """
    plots intensity decay curves for demagnetization experiments

    Parameters
    ----------
    in_file : str, default "measurements.txt"
    dir_path : str
        output directory, default "."
    input_dir_path : str
        input file directory (if different from dir_path), default ""
    spec_file : str
        input specimen file name, default "specimens.txt"
    samp_file: str
        input sample file name, default "samples.txt"
    site_file : str
        input site file name, default "sites.txt"
    loc_file : str
        input location file name, default "locations.txt"
    plot_by : str
        [spc, sam, sit, loc] (specimen, sample, site, location), default "loc"
    LT : str
        lab treatment [T, AF, M], default AF
    norm : bool
        normalize by NRM magnetization, default True
    XLP : str
        exclude specific  lab protocols, (for example, method codes like LP-PI)
        default ""
    save_plots : bool
        plot and save non-interactively, default True
    fmt : str
        ["png", "svg", "pdf", "jpg"], default "svg"

    Returns
    ---------
    type - Tuple : (True or False indicating if conversion was sucessful, file name(s) written)

    """
    dir_path = os.path.realpath(dir_path)
    if not input_dir_path:
        input_dir_path = dir_path
    input_dir_path = os.path.realpath(input_dir_path)

    # format plot_key
    name_dict = {'loc': 'location', 'sit': 'site',
                 'sam': 'sample', 'spc': 'specimen'}
    if plot_by not in name_dict.values():
        try:
            plot_key = name_dict[plot_by]
        except KeyError:
            print('Unrecognized plot_by {}, falling back to plot by location'.format(plot_by))
            plot_key = "loc"
    else:
        plot_key = plot_by


    # figure out what kind of experiment
    LT = "LT-" + LT + "-Z"
    print('LT', LT)
    if LT == "LT-T-Z":
        units, dmag_key = 'K', 'treat_temp'
    elif LT == "LT-AF-Z":
        units, dmag_key = 'T', 'treat_ac_field'
    elif LT == 'LT-M-Z':
        units, dmag_key = 'J', 'treat_mw_energy'
    else:
        units = 'U'


    # init
    FIG = {}  # plot dictionary
    FIG['demag'] = 1  # demag is figure 1
    # create contribution and add required headers
    fnames = {"specimens": spec_file, "samples": samp_file,
              'sites': site_file, 'locations': loc_file}
    if not os.path.exists(pmag.resolve_file_name(in_file, input_dir_path)):
        print('-E- Could not find {}'.format(in_file))
        return False, []
    contribution = cb.Contribution(input_dir_path, single_file=in_file,
                                   custom_filenames=fnames)
    file_type = list(contribution.tables.keys())[0]
    print(len(contribution.tables['measurements'].df), ' records read from ', in_file)
    # add plot_key into measurements table
    if plot_key not in contribution.tables['measurements'].df.columns:
        #contribution.propagate_name_down(plot_key, 'measurements')
        contribution.propagate_location_to_measurements()
    data_container = contribution.tables[file_type]
    # pare down to only records with useful data
    # grab records that have the requested code
    data_slice = data_container.get_records_for_code(LT)
    # and don't have the offending code
    data = data_container.get_records_for_code(XLP, incl=False, use_slice=True,
                                               sli=data_slice, strict_match=False)

    # make sure quality is in the dataframe
    if 'quality' not in data.columns:
        data['quality'] = 'g'
    # get intensity key and make sure intensity data is not blank
    intlist = ['magn_moment', 'magn_volume', 'magn_mass']
    IntMeths = [col_name for col_name in data.columns if col_name in intlist]
    # get rid of any entirely blank intensity columns
    for col_name in IntMeths:
        if not data[col_name].any():
            data.drop(col_name, axis=1, inplace=True)
    IntMeths = [col_name for col_name in data.columns if col_name in intlist]
    if len(IntMeths) == 0:
        print('-E- No intensity headers found')
        return False, []

    int_key = IntMeths[0] # plot first intensity method found - normalized to initial value anyway - doesn't matter which used
    data = data[data[int_key].notnull()]
    # make list of individual plots
    # by default, will be by location_name
    plotlist = data[plot_key].unique()
    plotlist.sort()
    pmagplotlib.plot_init(FIG['demag'], 5, 5)
    last_plot = False
    # iterate through and plot the data
    for plt in plotlist:
        if plt == plotlist[-1]:
            last_plot = True
        plot_data = data[data[plot_key] == plt].copy()
        if not save_plots:
            print(plt, 'plotting by: ', plot_key)
        if len(plot_data) > 2:
            title = plt
            spcs = []
            spcs = plot_data['specimen'].unique()
            for spc in spcs:
                INTblock = []
                spec_data = plot_data[plot_data['specimen'] == spc]
                for ind, rec in spec_data.iterrows():
                    INTblock.append([float(rec[dmag_key]), 0, 0, float(rec[int_key]), 1, rec['quality']])
                if len(INTblock) > 2:
                    pmagplotlib.plot_mag(FIG['demag'], INTblock,
                                       title, 0, units, norm)

            if save_plots:
                files = {}
                for key in list(FIG.keys()):
                    if pmagplotlib.isServer:
                        files[key] = title + '_' + LT + '.' + fmt
                        incl_dir = False
                    else: # if not server, include directory in output path
                        files[key] = os.path.join(dir_path, title + '_' + LT + '.' + fmt)
                        incl_dir = True

                pmagplotlib.save_plots(FIG, files, incl_directory=incl_dir)
            else:
                pmagplotlib.draw_figs(FIG)
                prompt = " S[a]ve to save plot, [q]uit,  Return to continue:  "
                ans = input(prompt)
                if ans == 'q':
                    return True, []
                if ans == "a":
                    files = {}
                    for key in list(FIG.keys()):
                        if pmagplotlib.isServer:
                            files[key] = title + '_' + LT + '.' + fmt
                            incl_dir = False
                        else: # if not server, include directory in output path
                            files[key] = os.path.join(dir_path, title + '_' + LT + '.' + fmt)
                            incl_dir = True
                    pmagplotlib.save_plots(FIG, files, incl_directory=incl_dir)
            pmagplotlib.clearFIG(FIG['demag'])
    if last_plot:
        return True, []
Exemplo n.º 22
0
def main():
    """
    NAME
        biplot_magic.py

    DESCRIPTION
        makes a biplot of specified variables from magic_measurements.txt format file

    SYNTAX
        biplot_magic.py [-h] [-i] [command line options]

    INPUT
        takes magic formated magic_measurments file

    OPTIONS
        -h prints help message and quits
        -i interactively set filename and axes for plotting
        -f FILE: specifies file name, default: magic_measurements.txt
        -fmt [svg,png,jpg], format for images - default is svg
        -sav figure and quit
        -x XMETH:key:step, specify method code for X axis (optional key and treatment values)
        -y YMETH:key:step, specify method code for X axis
        -obj OBJ: specify object [loc, sit, sam, spc] for plot, default is whole file
        -n [V,M] plot volume or mass normalized data only
    NOTES
        if nothing is specified for x and y, the user will be presented with options
        key = ['treatment_ac_field','treatment_dc_field',treatment_temp']
        step in mT for fields, K for temperatures
           """
    #
    file = 'magic_measurements.txt'
    methx, methy, fmt = "", "", '.svg'
    plot_key = ''
    norm_by = ""
    #plot=0
    no_plot = pmag.get_flag_arg_from_sys('-sav')
    if not no_plot:
        do_plot = True
    else:
        do_plot = False
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        file = sys.argv[ind + 1]
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = '.' + sys.argv[ind + 1]
    if '-n' in sys.argv:
        ind = sys.argv.index('-n')
        norm_by = sys.argv[ind + 1]
    xtreat_key, ytreat_key, xstep, ystep = "", "", "", ""
    if '-x' in sys.argv:
        ind = sys.argv.index('-x')
        meths = sys.argv[ind + 1].split(':')
        methx = meths[0]
        if len(meths) > 1:
            xtreat_key = meths[1]
            xstep = float(meths[2])
    if '-y' in sys.argv:
        ind = sys.argv.index('-y')
        meths = sys.argv[ind + 1].split(':')
        methy = meths[0]
        if len(meths) > 1:
            ytreat_key = meths[1]
            ystep = float(meths[2])
    if '-obj' in sys.argv:
        ind = sys.argv.index('-obj')
        plot_by = sys.argv[ind + 1]
        if plot_by == 'loc': plot_key = 'er_location_name'
        if plot_by == 'sit': plot_key = 'er_site_name'
        if plot_by == 'sam': plot_key = 'er_sample_name'
        if plot_by == 'spc': plot_key = 'er_specimen_name'
    if '-h' in sys.argv:
        do_plot = False
    if '-i' in sys.argv:
        #
        # get name of file from command line
        #
        file = input(
            "Input magic_measurments file name? [magic_measurements.txt] ")
        if file == "": file = "magic_measurements.txt"
    #
    #
    FIG = {'fig': 1}
    pmagplotlib.plot_init(FIG['fig'], 5, 5)
    data, file_type = pmag.magic_read(file)
    if file_type != "magic_measurements":
        print(file_type, ' not correct format for magic_measurments file')
        sys.exit()
    #
    # collect method codes
    methods, plotlist = [], []
    for rec in data:
        if plot_key != "":
            if rec[plot_key] not in plotlist: plotlist.append(rec[plot_key])
        elif len(plotlist) == 0:
            plotlist.append('All')
        meths = rec['magic_method_codes'].split(':')
        for meth in meths:
            if meth.strip() not in methods and meth.strip() != "LP-":
                methods.append(meth.strip())
    #
    if '-i' in sys.argv:
        print(methods)
    elif methx == "" or methy == "":
        print(methods)
        sys.exit()
    GoOn = 1
    while GoOn == 1:
        if '-i' in sys.argv: methx = input('Select method for x axis: ')
        if methx not in methods:
            if '-i' in sys.argv:
                print('try again! method not available')
            else:
                print(main.__doc__)
                print('\n must specify X axis method\n')
                sys.exit()
        else:
            if pmagplotlib.verbose: print(methx, ' selected for X axis')
            GoOn = 0
    GoOn = 1
    while GoOn == 1:
        if '-i' in sys.argv: methy = input('Select method for y axis: ')
        if methy not in methods:
            if '-i' in sys.argv:
                print('try again! method not available')
            else:
                print(main.__doc__)
                print('\n must specify Y axis method\n')
                sys.exit()
        else:
            if pmagplotlib.verbose: print(methy, ' selected for Y axis')
            GoOn = 0
    if norm_by == "":
        measkeys = [
            'measurement_magn_mass', 'measurement_magn_volume',
            'measurement_magn_moment', 'measurement_magnitude',
            'measurement_chi_volume', 'measurement_chi_mass', 'measurement_chi'
        ]
    elif norm_by == "V":
        measkeys = ['measurement_magn_volume', 'measurement_chi_volume']
    elif norm_by == "M":
        measkeys = ['measurement_magn_mass', 'measurement_chi_mass']
    xmeaskey, ymeaskey = "", ""
    plotlist.sort()
    for plot in plotlist:  # go through objects
        if pmagplotlib.verbose:
            print(plot)
        X, Y = [], []
        x, y = '', ''
        for rec in data:
            if plot_key != "" and rec[plot_key] != plot:
                pass
            else:
                meths = rec['magic_method_codes'].split(':')
                for meth in meths:
                    if meth.strip() == methx:
                        if xmeaskey == "":
                            for key in measkeys:
                                if key in list(rec.keys()) and rec[key] != "":
                                    xmeaskey = key
                                    if pmagplotlib.verbose:
                                        print(xmeaskey,
                                              ' being used for plotting X.')
                                    break
                    if meth.strip() == methy:
                        if ymeaskey == "":
                            for key in measkeys:
                                if key in list(rec.keys()) and rec[key] != "":
                                    ymeaskey = key
                                    if pmagplotlib.verbose:
                                        print(ymeaskey,
                                              ' being used for plotting Y')
                                    break
        if ymeaskey != "" and xmeaskey != "":
            for rec in data:
                x, y = '', ''
                spec = rec[
                    'er_specimen_name']  # get the ydata for this specimen
                if rec[ymeaskey] != "" and methy in rec[
                        'magic_method_codes'].split(':'):
                    if ytreat_key == "" or (ytreat_key in list(rec.keys()) and
                                            float(rec[ytreat_key]) == ystep):
                        y = float(rec[ymeaskey])
                        for rec in data:  # now find the xdata
                            if rec['er_specimen_name'] == spec and rec[
                                    xmeaskey] != "" and methx in rec[
                                        'magic_method_codes'].split(':'):
                                if xtreat_key == "" or (
                                        xtreat_key in list(rec.keys())
                                        and float(rec[xtreat_key]) == xstep):
                                    x = float(rec[xmeaskey])
                if x != '' and y != '':
                    X.append(x)
                    Y.append(y)
        if len(X) > 0:
            pmagplotlib.clearFIG(FIG['fig'])
            pmagplotlib.plotXY(FIG['fig'],
                               X,
                               Y,
                               sym='ro',
                               xlab=methx,
                               ylab=methy,
                               title=plot + ':Biplot')
            if not pmagplotlib.isServer and do_plot:
                pmagplotlib.drawFIGS(FIG)
                ans = input('S[a]ve plots, [q]uit,  Return for next plot ')
                if ans == 'a':
                    files = {}
                    for key in list(FIG.keys()):
                        files[key] = plot + '_' + key + fmt
                    pmagplotlib.saveP(FIG, files)
                if ans == 'q':
                    print("Good-bye\n")
                    sys.exit()
            else:
                files = {}
                for key in list(FIG.keys()):
                    files[key] = plot + '_' + key + fmt
                if pmagplotlib.isServer:
                    black = '#000000'
                    purple = '#800080'
                    titles = {}
                    titles['fig'] = 'X Y Plot'
                    FIG = pmagplotlib.addBorders(FIG, titles, black, purple)
                pmagplotlib.saveP(FIG, files)
        else:
            print('nothing to plot for ', plot)
Exemplo n.º 23
0
def main():
    """
    NAME
        lowrie.py

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

    SYNTAX
        lowrie -h [command line options]

    INPUT
       takes SIO formatted input files

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

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

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

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

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

    DESCRIPTION
       plots IRM acquisition curves from magic_measurements file

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

    DESCRIPTION
        makes plots of hysteresis data

    SYNTAX
        quick_hyst.py [command line options]

    OPTIONS
        -h prints help message and quits
        -usr USER:   identify user, default is ""
        -f: specify input file, default is magic_measurements.txt
        -spc SPEC: specify specimen name to plot and quit
        -sav save all plots and quit
        -fmt [png,svg,eps,jpg]
    """
    args = sys.argv
    PLT = 1
    plots = 0
    user, meas_file = "", "magic_measurements.txt"
    pltspec = ""
    dir_path = '.'
    fmt = 'png'
    verbose = pmagplotlib.verbose
    version_num = pmag.get_version()
    if '-WD' in args:
        ind = args.index('-WD')
        dir_path = args[ind+1]
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    if "-usr" in args:
        ind = args.index("-usr")
        user = args[ind+1]
    if '-f' in args:
        ind = args.index("-f")
        meas_file = args[ind+1]
    if '-sav' in args:
        verbose = 0
        plots = 1
    if '-spc' in args:
        ind = args.index("-spc")
        pltspec = args[ind+1]
        verbose = 0
        plots = 1
    if '-fmt' in args:
        ind = args.index("-fmt")
        fmt = args[ind+1]
    meas_file = dir_path+'/'+meas_file
    #
    #
    meas_data, file_type = pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print(main.__doc__)
        print('bad file')
        sys.exit()
    #
    # initialize some variables
    # define figure numbers for hyst,deltaM,DdeltaM curves
    HystRecs, RemRecs = [], []
    HDD = {}
    HDD['hyst'] = 1
    pmagplotlib.plot_init(HDD['hyst'], 5, 5)
    #
    # get list of unique experiment names and specimen names
    #
    experiment_names, sids = [], []
    hyst_data = pmag.get_dictitem(
        meas_data, 'magic_method_codes', 'LP-HYS', 'has')  # get all hysteresis data
    for rec in hyst_data:
        if 'er_synthetic_name' in rec.keys() and rec['er_synthetic_name'] != "":
            rec['er_specimen_name'] = rec['er_synthetic_name']
        if rec['magic_experiment_name'] not in experiment_names:
            experiment_names.append(rec['magic_experiment_name'])
        if rec['er_specimen_name'] not in sids:
            sids.append(rec['er_specimen_name'])
        if 'measurement_temp' not in rec.keys():
            # assume room T measurement unless otherwise specified
            rec['measurement_temp'] = '300'
    #
    k = 0
    if pltspec != "":
        k = sids.index(pltspec)
    intlist = ['measurement_magnitude', 'measurement_magn_moment',
               'measurement_magn_volume', 'measurement_magn_mass']
    while k < len(sids):
        locname, site, sample, synth = '', '', '', ''
        s = sids[k]
        hmeths = []
        if verbose:
            print(s, k+1, 'out of ', len(sids))
    #
    #
        B, M = [], []  # B,M for hysteresis, Bdcd,Mdcd for irm-dcd data
        # get all measurements for this specimen
        spec = pmag.get_dictitem(hyst_data, 'er_specimen_name', s, 'T')
        if 'er_location_name' in spec[0].keys():
            locname = spec[0]['er_location_name']
        if 'er_site_name' in spec[0].keys():
            site = spec[0]['er_site_name']
        if 'er_sample_name' in spec[0].keys():
            sample = spec[0]['er_sample_name']
        if 'er_synthetic_name' in spec[0].keys():
            synth = spec[0]['er_synthetic_name']
        for m in intlist:
            # get all non-blank data for this specimen
            meas_data = pmag.get_dictitem(spec, m, '', 'F')
            if len(meas_data) > 0:
                break
        c = ['k-', 'b-', 'c-', 'g-', 'm-', 'r-', 'y-']
        cnum = 0
        if len(meas_data) > 0:
            Temps = []
            xlab, ylab, title = '', '', ''
            for rec in meas_data:
                if rec['measurement_temp'] not in Temps:
                    Temps.append(rec['measurement_temp'])
            for t in Temps:
                print('working on t: ', t)
                t_data = pmag.get_dictitem(
                    meas_data, 'measurement_temp', t, 'T')
                B, M = [], []
                for rec in t_data:
                    B.append(float(rec['measurement_lab_field_dc']))
                    M.append(float(rec[m]))
    # now plot the hysteresis curve(s)
    #
                if len(B) > 0:
                    B = numpy.array(B)
                    M = numpy.array(M)
                    if t == Temps[-1]:
                        xlab = 'Field (T)'
                        ylab = m
                        title = 'Hysteresis: '+s
                    if t == Temps[0]:
                        pmagplotlib.clearFIG(HDD['hyst'])
                    pmagplotlib.plot_xy(
                        HDD['hyst'], B, M, sym=c[cnum], xlab=xlab, ylab=ylab, title=title)
                    pmagplotlib.plot_xy(HDD['hyst'], [
                                        1.1*B.min(), 1.1*B.max()], [0, 0], sym='k-', xlab=xlab, ylab=ylab, title=title)
                    pmagplotlib.plot_xy(HDD['hyst'], [0, 0], [
                                        1.1*M.min(), 1.1*M.max()], sym='k-', xlab=xlab, ylab=ylab, title=title)
                    if verbose:
                        pmagplotlib.draw_figs(HDD)
                    cnum += 1
                    if cnum == len(c):
                        cnum = 0
    #
        files = {}
        if plots:
            if pltspec != "":
                s = pltspec
            files = {}
            for key in HDD.keys():
                if pmagplotlib.isServer:  # use server plot naming convention
                    if synth == '':
                        filename = "LO:_"+locname+'_SI:_'+site + \
                            '_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt
                    else:
                        filename = 'SY:_'+synth+'_TY:_'+key+'_.'+fmt
                    files[key] = filename
                else:  # use more readable plot naming convention
                    if synth == '':
                        filename = ''
                        for item in [locname, site, sample, s, key]:
                            if item:
                                item = item.replace(' ', '_')
                                filename += item + '_'
                        if filename.endswith('_'):
                            filename = filename[:-1]
                        filename += ".{}".format(fmt)
                    else:
                        filename = synth+'_'+key+'.fmt'
                    files[key] = filename

            pmagplotlib.save_plots(HDD, files)
            if pltspec != "":
                sys.exit()
        if verbose:
            pmagplotlib.draw_figs(HDD)
            ans = raw_input(
                "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ")
            if ans == "a":
                files = {}
                for key in HDD.keys():
                    if pmagplotlib.isServer:
                        print('server')
                        files[key] = "LO:_"+locname+'_SI:_'+site + \
                            '_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt
                    else:
                        print('not server')
                        filename = ''
                        for item in [locname, site, sample, s, key]:
                            if item:
                                item = item.replace(' ', '_')
                                filename += item + '_'
                        if filename.endswith('_'):
                            filename = filename[:-1]
                        filename += ".{}".format(fmt)
                        files[key] = filename
                print('files', files)
                pmagplotlib.save_plots(HDD, files)
            if ans == '':
                k += 1
            if ans == "p":
                del HystRecs[-1]
                k -= 1
            if ans == 'q':
                print("Good bye")
                sys.exit()
            if ans == 's':
                keepon = 1
                specimen = raw_input(
                    'Enter desired specimen name (or first part there of): ')
                while keepon == 1:
                    try:
                        k = sids.index(specimen)
                        keepon = 0
                    except:
                        tmplist = []
                        for qq in range(len(sids)):
                            if specimen in sids[qq]:
                                tmplist.append(sids[qq])
                        print(specimen, " not found, but this was: ")
                        print(tmplist)
                        specimen = raw_input('Select one or try again\n ')
                        k = sids.index(specimen)
        else:
            k += 1
        if len(B) == 0:
            if verbose:
                print('skipping this one - no hysteresis data')
            k += 1
Exemplo n.º 28
0
def main():
    """
    NAME
        thellier_magic.py

    DESCRIPTION
        plots Thellier-Thellier data in version 3.0 format
        Reads saved interpretations from a specimen formatted table, default: specimens.txt

    SYNTAX
        thellier_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f MEAS, set measurements input file, default is 'measurements.txt'
        -fsp PRIOR, set specimens.txt prior interpretations file, default is 'specimens.txt'
        -fcr CRIT, set criteria file for grading.  # not yet implemented
        -fmt [svg,png,jpg], format for images - default is svg
        -sav,  saves plots with out review (in format specified by -fmt key or default)
        -spc SPEC, plots single specimen SPEC, saves plot with specified format
            with optional -b bounds and quits
        -b BEG END: sets  bounds for calculation
           BEG: starting step number for slope calculation
           END: ending step number for slope calculation
        -z use only z component difference for pTRM calculation

    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 measuements)
                     list of possible commands: type letter followed by return to select option
                     saving of plots creates image files with specimen, plot type as name
    """
    #
    #   initializations
    #
    version_num = pmag.get_version()
    verbose = pmagplotlib.verbose
    #
    # default acceptance criteria
    #
    accept = pmag.default_criteria(0)[0]  # set the default criteria
    #
    # parse command line options
    #
    plots, fmt, Zdiff = 0, 'svg', 0
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg_from_sys("-WD", default_val=os.getcwd())
    meas_file = pmag.get_named_arg_from_sys("-f",
                                            default_val="measurements.txt")
    spec_file = pmag.get_named_arg_from_sys("-fsp",
                                            default_val="specimens.txt")
    crit_file = pmag.get_named_arg_from_sys("-fcr", default_val="criteria.txt")
    spec_file = os.path.join(dir_path, spec_file)
    meas_file = os.path.join(dir_path, meas_file)
    crit_file = os.path.join(dir_path, crit_file)
    fmt = pmag.get_named_arg_from_sys("-fmt", "svg")
    if '-sav' in sys.argv: plots, verbose = 1, 0
    if '-z' in sys.argv: Zdiff = 1
    specimen = pmag.get_named_arg_from_sys("-spc", default_val="")
    if '-b' in sys.argv:
        ind = sys.argv.index('-b')
        start = int(sys.argv[ind + 1])
        end = int(sys.argv[ind + 2])
    else:
        start, end = "", ""
    fnames = {
        'measurements': meas_file,
        'specimens': spec_file,
        'criteria': crit_file
    }
    contribution = nb.Contribution(
        dir_path,
        custom_filenames=fnames,
        read_tables=['measurements', 'specimens', 'criteria'])
    #
    #   import  prior interpretations  from specimen file
    #
    specimen_cols = [
        'analysts', 'aniso_ftest', 'aniso_ftest12', 'aniso_ftest23', 'aniso_s',
        'aniso_s_mean', 'aniso_s_n_measurements', 'aniso_s_sigma',
        'aniso_s_unit', 'aniso_tilt_correction', 'aniso_type', 'aniso_v1',
        'aniso_v2', 'aniso_v3', 'citations', 'description', 'dir_alpha95',
        'dir_comp', 'dir_dec', 'dir_inc', 'dir_mad_free', 'dir_n_measurements',
        'dir_tilt_correction', 'experiments', 'geologic_classes',
        'geologic_types', 'hyst_bc', 'hyst_bcr', 'hyst_mr_moment',
        'hyst_ms_moment', 'int_abs', 'int_b', 'int_b_beta', 'int_b_sigma',
        'int_corr', 'int_dang', 'int_drats', 'int_f', 'int_fvds', 'int_gamma',
        'int_mad_free', 'int_md', 'int_n_measurements', 'int_n_ptrm', 'int_q',
        'int_rsc', 'int_treat_dc_field', 'lithologies', 'meas_step_max',
        'meas_step_min', 'meas_step_unit', 'method_codes', 'sample',
        'software_packages', 'specimen'
    ]
    if 'specimens' in contribution.tables:
        spec_container = contribution.tables['specimens']
        prior_spec_data = spec_container.get_records_for_code(
            'LP-PI-TRM',
            strict_match=False)  # look up all prior intensity interpretations
    else:
        spec_container, prior_spec_data = None, []
    backup = 0
    #
    Mkeys = ['magn_moment', 'magn_volume', 'magn_mass']
    #
    #   create measurement dataframe
    #
    meas_container = contribution.tables['measurements']
    meas_data = meas_container.df
    #
    meas_data['method_codes'] = meas_data['method_codes'].str.replace(
        " ", "")  # get rid of nasty spaces
    meas_data = meas_data[meas_data['method_codes'].str.contains(
        'LP-PI-TRM|LP-TRM|LP-TRM-TD') ==
                          True]  # fish out zero field steps for plotting
    intensity_types = [
        col_name for col_name in meas_data.columns if col_name in Mkeys
    ]
    int_key = intensity_types[
        0]  # plot first intensity method found - normalized to initial value anyway - doesn't matter which used
    meas_data = meas_data[meas_data[int_key].notnull(
    )]  # get all the non-null intensity records of the same type
    if 'flag' not in meas_data.columns:
        meas_data['flag'] = 'g'  # set the default flag to good
    meas_data = meas_data[meas_data['flag'].str.contains('g') ==
                          True]  # only the 'good' measurements
    thel_data = meas_data[meas_data['method_codes'].str.contains('LP-PI-TRM')
                          == True]  # get all the Thellier data
    trm_data = meas_data[meas_data['method_codes'].str.contains('LP-TRM') ==
                         True]  # get all the TRM acquisition data
    td_data = meas_data[meas_data['method_codes'].str.contains('LP-TRM-TD') ==
                        True]  # get all the TD data
    anis_data = meas_data[meas_data['method_codes'].str.contains('LP-AN') ==
                          True]  # get all the anisotropy data
    #
    # get list of unique specimen names from measurement data
    #
    specimen_names = meas_data.specimen.unique(
    )  # this is a Series of all the specimen names
    specimen_names = specimen_names.tolist()  # turns it into a list
    specimen_names.sort()  # sorts by specimen name
    #
    # set up new DataFrame for this sessions specimen interpretations
    #
    spec_container = nb.MagicDataFrame(dtype='specimens',
                                       columns=specimen_cols)
    current_spec_data = spec_container.df  # this is for interpretations from this session
    if specimen == "":  # do all specimens
        k = 0
    else:
        k = specimen_names.index(specimen)  # just do this one
    # define figure numbers for arai, zijderveld and
    #   de-,re-magnetization 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)
    if len(trm_data) > 0:
        AZD['TRM'] = 5
        pmagplotlib.plot_init(AZD['TRM'], 5, 5)
    if len(td_data) > 0:
        AZD['TDS'] = 6
        pmagplotlib.plot_init(AZD['TDS'], 5, 5)
    #
    while k < len(specimen_names):
        this_specimen = specimen_names[
            k]  # set the current specimen for plotting
        if verbose and this_specimen != "":
            print(this_specimen, k + 1, 'out of ', len(specimen_names))
        #
        #    set up datablocks
        #
        thelblock = thel_data[thel_data['specimen'].str.contains(this_specimen)
                              == True]  # fish out this specimen
        trmblock = trm_data[trm_data['specimen'].str.contains(this_specimen) ==
                            True]  # fish out this specimen
        tdsrecs = td_data[td_data['specimen'].str.contains(this_specimen) ==
                          True]  # fish out this specimen
        anisblock = anis_data[anis_data['specimen'].str.contains(this_specimen)
                              == True]  # fish out the anisotropy data
        prior_specimen_interpretations = prior_spec_data[
            prior_spec_data['specimen'].str.contains(
                this_specimen) == True]  # fish out prior interpretation
        #
        # sort data into types
        #
        araiblock, field = pmag.sortarai(thelblock,
                                         this_specimen,
                                         Zdiff,
                                         version=3)
        first_Z = araiblock[0]
        GammaChecks = araiblock[5]
        if len(first_Z) < 3:
            if backup == 0:
                k += 1
                if verbose:
                    print('skipping specimen - moving forward ', this_specimen)
            else:
                k -= 1
                if verbose:
                    print('skipping specimen - moving backward ',
                          this_specimen)
        else:
            backup = 0
            zijdblock, units = pmag.find_dmag_rec(this_specimen,
                                                  thelblock,
                                                  version=3)
            if start == "" and len(prior_specimen_interpretations) > 0:
                if verbose: print('Looking up saved interpretation....')
                #
                # get prior interpretation steps
                #
                beg_int = pd.to_numeric(prior_specimen_interpretations.
                                        meas_step_min.values).tolist()[0]
                end_int = pd.to_numeric(prior_specimen_interpretations.
                                        meas_step_max.values).tolist()[0]
            else:
                beg_int, end_int = "", ""
            recnum = 0
            if verbose: print("index step Dec   Inc  Int       Gamma")
            for plotrec in zijdblock:
                if plotrec[0] == beg_int:
                    start = recnum  # while we are at it, collect these bounds
                if plotrec[0] == end_int: end = recnum
                if verbose:
                    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
            for fig in list(AZD.keys()):
                pmagplotlib.clearFIG(AZD[fig])  # clear all figures
            pmagplotlib.plotAZ(AZD, araiblock, zijdblock, this_specimen,
                               units[0])
            if verbose: pmagplotlib.drawFIGS(AZD)
            pars, errcode = pmag.PintPars(thelblock,
                                          araiblock,
                                          zijdblock,
                                          start,
                                          end,
                                          accept,
                                          version=3)
            pars['measurement_step_unit'] = "K"
            pars['experiment_type'] = 'LP-PI-TRM'
            #
            # work on saving interpretations stuff later
            #
            if errcode != 1:  # no problem in PintPars
                pars["specimen_lab_field_dc"] = field
                pars["specimen_int"] = -1 * field * pars["specimen_b"]
                pars["er_specimen_name"] = this_specimen
                #pars,kill=pmag.scoreit(pars,this_specimen_interpretation,accept,'',verbose) # deal with this later
                pars["specimen_grade"] = 'None'
                pars['measurement_step_min'] = pars['meas_step_min']
                pars['measurement_step_max'] = pars['meas_step_max']
                if pars['measurement_step_unit'] == 'K':
                    outstr = "specimen     Tmin  Tmax  N  lab_field  B_anc  b  q  f(coe)  Fvds  beta  MAD  Dang  Drats  Nptrm  Grade  R  MD%  sigma  Gamma_max \n"
                    pars_out = (this_specimen, (pars["meas_step_min"] - 273),
                                (pars["meas_step_max"] -
                                 273), (pars["specimen_int_n"]),
                                1e6 * (pars["specimen_lab_field_dc"]),
                                1e6 * (pars["specimen_int"]),
                                pars["specimen_b"], pars["specimen_q"],
                                pars["specimen_f"], pars["specimen_fvds"],
                                pars["specimen_b_beta"], pars["int_mad_free"],
                                pars["int_dang"], pars["int_drats"],
                                pars["int_n_ptrm"], pars["specimen_grade"],
                                np.sqrt(pars["specimen_rsc"]),
                                int(pars["int_md"]), pars["specimen_b_sigma"],
                                pars['specimen_gamma'])
                    outstring = '%s %4.0f %4.0f %i %4.1f %4.1f %5.3f %5.1f %5.3f %5.3f %5.3f  %7.1f %7.1f %7.1f %s %s %6.3f %i %5.3f %7.1f' % pars_out + '\n'
                elif pars['measurement_step_unit'] == 'J':
                    outstr = "specimen     Wmin  Wmax  N  lab_field  B_anc  b  q  f(coe)  Fvds  beta  MAD  Dang  Drats  Nptrm  Grade  R  MD%  sigma  ThetaMax DeltaMax GammaMax\n"
                    pars_out = (
                        this_specimen, (pars["meas_step_min"]),
                        (pars["meas_step_max"]), (pars["specimen_int_n"]),
                        1e6 * (pars["specimen_lab_field_dc"]),
                        1e6 * (pars["specimen_int"]), pars["specimen_b"],
                        pars["specimen_q"], pars["specimen_f"],
                        pars["specimen_fvds"], pars["specimen_b_beta"],
                        pars["specimen_int_mad"], pars["specimen_int_dang"],
                        pars["specimen_drats"], pars["specimen_int_ptrm_n"],
                        pars["specimen_grade"], np.sqrt(pars["specimen_rsc"]),
                        int(pars["specimen_md"]), pars["specimen_b_sigma"],
                        pars["specimen_theta"], pars["specimen_delta"],
                        pars["specimen_gamma"])
                    outstring = '%s %4.0f %4.0f %i %4.1f %4.1f %5.3f %5.1f %5.3f %5.3f %5.3f  %7.1f %7.1f %7.1f %s %s %6.3f %i %5.3f %7.1f %7.1f %7.1f' % pars_out + '\n'
                print(outstr)
                print(outstring)
                pmagplotlib.plotB(AZD, araiblock, zijdblock, pars)
                mpars = pmag.domean(araiblock[1], start, end, 'DE-BFL')
                if verbose:
                    pmagplotlib.drawFIGS(AZD)
                    print('pTRM direction= ',
                          '%7.1f' % (mpars['specimen_dec']),
                          ' %7.1f' % (mpars['specimen_inc']), ' MAD:',
                          '%7.1f' % (mpars['specimen_mad']))
            if len(anisblock) > 0:  # this specimen has anisotropy data
                if verbose:
                    print('Found anisotropy record... but ignoring for now ')
            if plots == 1:
                if fmt != "pmag":
                    files = {}
                    for key in list(AZD.keys()):
                        files[
                            key] = 'SP:_' + this_specimen + '_TY:_' + key + '_' + '.' + fmt
                    if pmagplotlib.isServer:
                        black = '#000000'
                        purple = '#800080'
                        titles = {}
                        titles['deremag'] = 'DeReMag Plot'
                        titles['zijd'] = 'Zijderveld Plot'
                        titles['arai'] = 'Arai Plot'
                        titles['TRM'] = 'TRM Acquisition data'
                        AZD = pmagplotlib.addBorders(AZD, titles, black,
                                                     purple)
                    pmagplotlib.saveP(AZD, files)
                else:  # save in pmag format
                    print('pmag format no longer supported')
                    #script="grep "+this_specimen+" 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 specimen != "": sys.exit()  # syonara
            if verbose:
                ans = input('Return for next specimen, q to quit:  ')
                if ans == 'q': sys.exit()
            k += 1  # moving on
Exemplo n.º 29
0
def main():
    """
    NAME
        hysteresis_magic.py

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

    SYNTAX
        hysteresis_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -usr USER:   identify user, default is ""
        -f: specify input file, default is agm_measurements.txt
        -fh: specify rmag_hysteresis.txt input file
        -F: specify output file, default is rmag_hysteresis.txt
        -P: do not make the plots
        -spc SPEC: specify specimen name to plot and quit
        -sav save all plots and quit
        -fmt [png,svg,eps,jpg]
    """
    args = sys.argv
    PLT = 1
    plots = 0
    user, meas_file, rmag_out, rmag_file = "", "agm_measurements.txt", "rmag_hysteresis.txt", ""
    pltspec = ""
    dir_path = '.'
    fmt = 'svg'
    verbose = pmagplotlib.verbose
    version_num = pmag.get_version()
    if '-WD' in args:
        ind = args.index('-WD')
        dir_path = args[ind + 1]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind = args.index("-usr")
        user = args[ind + 1]
    if '-f' in args:
        ind = args.index("-f")
        meas_file = args[ind + 1]
    if '-F' in args:
        ind = args.index("-F")
        rmag_out = args[ind + 1]
    if '-fh' in args:
        ind = args.index("-fh")
        rmag_file = args[ind + 1]
        rmag_file = dir_path + '/' + rmag_file
    if '-P' in args:
        PLT = 0
        irm_init, imag_init = -1, -1
    if '-sav' in args:
        verbose = 0
        plots = 1
    if '-spc' in args:
        ind = args.index("-spc")
        pltspec = args[ind + 1]
        verbose = 0
        plots = 1
    if '-fmt' in args:
        ind = args.index("-fmt")
        fmt = args[ind + 1]
    rmag_out = dir_path + '/' + rmag_out
    meas_file = dir_path + '/' + meas_file
    rmag_rem = dir_path + "/rmag_remanence.txt"
    #
    #
    meas_data, file_type = pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print main.__doc__
        print 'bad file'
        sys.exit()
    #
    # initialize some variables
    # define figure numbers for hyst,deltaM,DdeltaM curves
    HystRecs, RemRecs = [], []
    HDD = {}
    if verbose:
        if verbose and PLT:
            print "Plots may be on top of each other - use mouse to place "
    if PLT:
        HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'] = 1, 2, 3
        pmagplotlib.plot_init(HDD['DdeltaM'], 5, 5)
        pmagplotlib.plot_init(HDD['deltaM'], 5, 5)
        pmagplotlib.plot_init(HDD['hyst'], 5, 5)
        imag_init = 0
        irm_init = 0
    else:
        HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'], HDD['irm'], HDD[
            'imag'] = 0, 0, 0, 0, 0
    #
    if rmag_file != "": hyst_data, file_type = pmag.magic_read(rmag_file)
    #
    # get list of unique experiment names and specimen names
    #
    experiment_names, sids = [], []
    for rec in meas_data:
        meths = rec['magic_method_codes'].split(':')
        methods = []
        for meth in meths:
            methods.append(meth.strip())
        if 'LP-HYS' in methods:
            if 'er_synthetic_name' in rec.keys(
            ) and rec['er_synthetic_name'] != "":
                rec['er_specimen_name'] = rec['er_synthetic_name']
            if rec['magic_experiment_name'] not in experiment_names:
                experiment_names.append(rec['magic_experiment_name'])
            if rec['er_specimen_name'] not in sids:
                sids.append(rec['er_specimen_name'])
    #
    k = 0
    locname = ''
    if pltspec != "":
        k = sids.index(pltspec)
        print sids[k]
    while k < len(sids):
        s = sids[k]
        if verbose and PLT: print s, k + 1, 'out of ', len(sids)
        #
        #
        B, M, Bdcd, Mdcd = [], [], [], [
        ]  #B,M for hysteresis, Bdcd,Mdcd for irm-dcd data
        Bimag, Mimag = [], []  #Bimag,Mimag for initial magnetization curves
        first_dcd_rec, first_rec, first_imag_rec = 1, 1, 1
        for rec in meas_data:
            methcodes = rec['magic_method_codes'].split(':')
            meths = []
            for meth in methcodes:
                meths.append(meth.strip())
            if rec['er_specimen_name'] == s and "LP-HYS" in meths:
                B.append(float(rec['measurement_lab_field_dc']))
                M.append(float(rec['measurement_magn_moment']))
                if first_rec == 1:
                    e = rec['magic_experiment_name']
                    HystRec = {}
                    first_rec = 0
                    if "er_location_name" in rec.keys():
                        HystRec["er_location_name"] = rec["er_location_name"]
                        locname = rec['er_location_name'].replace('/', '-')
                    if "er_sample_name" in rec.keys():
                        HystRec["er_sample_name"] = rec["er_sample_name"]
                    if "er_site_name" in rec.keys():
                        HystRec["er_site_name"] = rec["er_site_name"]
                    if "er_synthetic_name" in rec.keys(
                    ) and rec['er_synthetic_name'] != "":
                        HystRec["er_synthetic_name"] = rec["er_synthetic_name"]
                    else:
                        HystRec["er_specimen_name"] = rec["er_specimen_name"]
            if rec['er_specimen_name'] == s and "LP-IRM-DCD" in meths:
                Bdcd.append(float(rec['treatment_dc_field']))
                Mdcd.append(float(rec['measurement_magn_moment']))
                if first_dcd_rec == 1:
                    RemRec = {}
                    irm_exp = rec['magic_experiment_name']
                    first_dcd_rec = 0
                    if "er_location_name" in rec.keys():
                        RemRec["er_location_name"] = rec["er_location_name"]
                    if "er_sample_name" in rec.keys():
                        RemRec["er_sample_name"] = rec["er_sample_name"]
                    if "er_site_name" in rec.keys():
                        RemRec["er_site_name"] = rec["er_site_name"]
                    if "er_synthetic_name" in rec.keys(
                    ) and rec['er_synthetic_name'] != "":
                        RemRec["er_synthetic_name"] = rec["er_synthetic_name"]
                    else:
                        RemRec["er_specimen_name"] = rec["er_specimen_name"]
            if rec['er_specimen_name'] == s and "LP-IMAG" in meths:
                if first_imag_rec == 1:
                    imag_exp = rec['magic_experiment_name']
                    first_imag_rec = 0
                Bimag.append(float(rec['measurement_lab_field_dc']))
                Mimag.append(float(rec['measurement_magn_moment']))
    #
    # now plot the hysteresis curve
    #
        if len(B) > 0:
            hmeths = []
            for meth in meths:
                hmeths.append(meth)
            hpars = pmagplotlib.plotHDD(HDD, B, M, e)
            if verbose and PLT: pmagplotlib.drawFIGS(HDD)
            #
            # get prior interpretations from hyst_data
            if rmag_file != "":
                hpars_prior = {}
                for rec in hyst_data:
                    if rec['magic_experiment_names'] == e:
                        if rec['hysteresis_bcr'] != "" and rec[
                                'hysteresis_mr_moment'] != "":
                            hpars_prior['hysteresis_mr_moment'] = rec[
                                'hysteresis_mr_moment']
                            hpars_prior['hysteresis_ms_moment'] = rec[
                                'hysteresis_ms_moment']
                            hpars_prior['hysteresis_bc'] = rec['hysteresis_bc']
                            hpars_prior['hysteresis_bcr'] = rec[
                                'hysteresis_bcr']
                            break
                if verbose: pmagplotlib.plotHPARS(HDD, hpars_prior, 'ro')
            else:
                if verbose: pmagplotlib.plotHPARS(HDD, hpars, 'bs')
                HystRec['hysteresis_mr_moment'] = hpars['hysteresis_mr_moment']
                HystRec['hysteresis_ms_moment'] = hpars['hysteresis_ms_moment']
                HystRec['hysteresis_bc'] = hpars['hysteresis_bc']
                HystRec['hysteresis_bcr'] = hpars['hysteresis_bcr']
                HystRec['hysteresis_xhf'] = hpars['hysteresis_xhf']
                HystRec['magic_experiment_names'] = e
                HystRec['magic_software_packages'] = version_num
                if hpars["magic_method_codes"] not in hmeths:
                    hmeths.append(hpars["magic_method_codes"])
                methods = ""
                for meth in hmeths:
                    methods = methods + meth.strip() + ":"
                HystRec["magic_method_codes"] = methods[:-1]
                HystRec["er_citation_names"] = "This study"
                HystRecs.append(HystRec)
    #
        if len(Bdcd) > 0:
            rmeths = []
            for meth in meths:
                rmeths.append(meth)
            if verbose and PLT: print 'plotting IRM'
            if irm_init == 0:
                HDD['irm'] = 5
                pmagplotlib.plot_init(HDD['irm'], 5, 5)
                irm_init = 1
            rpars = pmagplotlib.plotIRM(HDD['irm'], Bdcd, Mdcd, irm_exp)
            RemRec['remanence_mr_moment'] = rpars['remanence_mr_moment']
            RemRec['remanence_bcr'] = rpars['remanence_bcr']
            RemRec['magic_experiment_names'] = irm_exp
            if rpars["magic_method_codes"] not in meths:
                meths.append(rpars["magic_method_codes"])
            methods = ""
            for meth in rmeths:
                methods = methods + meth.strip() + ":"
            RemRec["magic_method_codes"] = methods[:-1]
            RemRec["er_citation_names"] = "This study"
            RemRecs.append(RemRec)
        else:
            if irm_init: pmagplotlib.clearFIG(HDD['irm'])
        if len(Bimag) > 0:
            if verbose: print 'plotting initial magnetization curve'
            # first normalize by Ms
            Mnorm = []
            for m in Mimag:
                Mnorm.append(m / float(hpars['hysteresis_ms_moment']))
            if imag_init == 0:
                HDD['imag'] = 4
                pmagplotlib.plot_init(HDD['imag'], 5, 5)
                imag_init = 1
            pmagplotlib.plotIMAG(HDD['imag'], Bimag, Mnorm, imag_exp)
        else:
            if imag_init: pmagplotlib.clearFIG(HDD['imag'])
    #
        files = {}
        if plots:
            if pltspec != "": s = pltspec
            files = {}
            for key in HDD.keys():
                files[key] = locname + '_' + s + '_' + key + '.' + fmt
            pmagplotlib.saveP(HDD, files)
            if pltspec != "": sys.exit()
        if verbose and PLT:
            pmagplotlib.drawFIGS(HDD)
            ans = raw_input(
                "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n "
            )
            if ans == "a":
                files = {}
                for key in HDD.keys():
                    files[key] = locname + '_' + s + '_' + key + '.' + fmt
                pmagplotlib.saveP(HDD, files)
            if ans == '': k += 1
            if ans == "p":
                del HystRecs[-1]
                k -= 1
            if ans == 'q':
                print "Good bye"
                sys.exit()
            if ans == 's':
                keepon = 1
                specimen = raw_input(
                    'Enter desired specimen name (or first part there of): ')
                while keepon == 1:
                    try:
                        k = sids.index(specimen)
                        keepon = 0
                    except:
                        tmplist = []
                        for qq in range(len(sids)):
                            if specimen in sids[qq]: tmplist.append(sids[qq])
                        print specimen, " not found, but this was: "
                        print tmplist
                        specimen = raw_input('Select one or try again\n ')
                        k = sids.index(specimen)
        else:
            k += 1
        if len(B) == 0 and len(Bdcd) == 0:
            if verbose: print 'skipping this one - no hysteresis data'
            k += 1
    if rmag_out == "" and ans == 's' and verbose:
        really = raw_input(
            " Do you want to overwrite the existing rmag_hystersis.txt file? 1/[0] "
        )
        if really == "":
            print 'i thought not - goodbye'
            sys.exit()
        rmag_out = "rmag_hysteresis.txt"
    if len(HystRecs) > 0:
        pmag.magic_write(rmag_out, HystRecs, "rmag_hysteresis")
        if verbose: print "hysteresis parameters saved in ", rmag_out
    if len(RemRecs) > 0:
        pmag.magic_write(rmag_rem, RemRecs, "rmag_remanence")
        if verbose: print "remanence parameters saved in ", rmag_rem
Exemplo n.º 30
0
def main():
    """
    NAME
        biplot_magic.py

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

    INPUT 
        takes magic formated magic_measurments file

    OPTIONS
        -h prints help message and quits
        -i interactively set filename and axes for plotting
        -f FILE: specifies file name, default: magic_measurements.txt
        -fmt [svg,png,jpg], format for images - default is svg
        -sav figure and quit
        -x XMETH:key:step, specify method code for X axis (optional key and treatment values)
        -y YMETH:key:step, specify method code for X axis
        -obj OBJ: specify object [loc, sit, sam, spc] for plot, default is whole file
        -n [V,M] plot volume or mass normalized data only
    NOTES
        if nothing is specified for x and y, the user will be presented with options
        key = ['treatment_ac_field','treatment_dc_field',treatment_temp'] 
        step in mT for fields, K for temperatures
           """ 
    #
    file='magic_measurements.txt'
    methx,methy,fmt="","",'.svg'
    plot_key=''
    norm_by=""
    #plot=0
    no_plot = pmag.get_flag_arg_from_sys('-sav')
    if not no_plot:
        do_plot = True
    else:
        do_plot = False
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt='.'+sys.argv[ind+1]
    if '-n' in sys.argv:
        ind=sys.argv.index('-n')
        norm_by=sys.argv[ind+1]
    xtreat_key,ytreat_key,xstep,ystep="","","",""
    if '-x' in sys.argv:
        ind=sys.argv.index('-x')
        meths=sys.argv[ind+1].split(':')
        methx=meths[0]
        if len(meths)>1:
            xtreat_key=meths[1]
            xstep=float(meths[2])
    if '-y' in sys.argv:
        ind=sys.argv.index('-y')
        meths=sys.argv[ind+1].split(':')
        methy=meths[0]
        if len(meths)>1:
            ytreat_key=meths[1]
            ystep=float(meths[2])
    if '-obj' in sys.argv: 
        ind=sys.argv.index('-obj')
        plot_by=sys.argv[ind+1]
        if plot_by=='loc':plot_key='er_location_name'
        if plot_by=='sit':plot_key='er_site_name'
        if plot_by=='sam':plot_key='er_sample_name'
        if plot_by=='spc':plot_key='er_specimen_name'
    if '-h' in sys.argv:
        do_plot = False
    if '-i' in sys.argv: 
    #
    # get name of file from command line
    #
        file=raw_input("Input magic_measurments file name? [magic_measurements.txt] ")
        if file=="":file="magic_measurements.txt"
    #
    #
    FIG={'fig':1}
    pmagplotlib.plot_init(FIG['fig'],5,5)
    data,file_type=pmag.magic_read(file)
    if file_type!="magic_measurements":
        print file_type,' not correct format for magic_measurments file'
        sys.exit()
    #
    # collect method codes
    methods,plotlist=[],[]
    for rec in  data:
        if plot_key!="":
            if rec[plot_key] not in plotlist:plotlist.append(rec[plot_key])
        elif len(plotlist)==0:
            plotlist.append('All')
        meths=rec['magic_method_codes'].split(':')
        for meth in meths:
            if meth.strip() not in methods and meth.strip()!="LP-":
                methods.append(meth.strip())
    #
    if '-i' in sys.argv:
        print methods
    elif methx =="" or methy=="": 
	print methods
        sys.exit()
    GoOn=1
    while GoOn==1:
        if '-i' in sys.argv:methx=raw_input('Select method for x axis: ')
        if methx not in methods:
            if '-i' in sys.argv:
                print 'try again! method not available'
            else: 
                print main.__doc__
                print '\n must specify X axis method\n'
                sys.exit()
        else:
            if pmagplotlib.verbose: print methx, ' selected for X axis'
            GoOn=0
    GoOn=1
    while GoOn==1:
        if '-i' in sys.argv:methy=raw_input('Select method for y axis: ')
        if methy not in methods:
            if '-i' in sys.argv:
                print 'try again! method not available'
            else: 
                print main.__doc__
                print '\n must specify Y axis method\n'
                sys.exit()
        else:
            if pmagplotlib.verbose: print methy, ' selected for Y axis'
            GoOn=0
    if norm_by=="":
        measkeys=['measurement_magn_mass','measurement_magn_volume','measurement_magn_moment','measurement_magnitude','measurement_chi_volume','measurement_chi_mass','measurement_chi']
    elif norm_by=="V":
        measkeys=['measurement_magn_volume','measurement_chi_volume']
    elif norm_by=="M":
        measkeys=['measurement_magn_mass','measurement_chi_mass']
    xmeaskey,ymeaskey="",""
    plotlist.sort()
    for plot in plotlist: # go through objects
        if pmagplotlib.verbose:
            print plot
        X,Y=[],[]
        x,y='',''
        for rec in data:
            if plot_key!="" and rec[plot_key]!=plot:
                pass
            else:
                meths=rec['magic_method_codes'].split(':')
                for meth in meths:
                    if meth.strip()==methx:
                        if xmeaskey=="":
                            for key in measkeys:
                                if key in rec.keys() and rec[key]!="":
                                    xmeaskey=key
                                    if pmagplotlib.verbose:
                                        print xmeaskey,' being used for plotting X.'
                                    break 
                    if meth.strip()==methy:
                        if ymeaskey=="":
                            for key in measkeys:
                                if key in rec.keys() and rec[key]!="":
                                    ymeaskey=key
                                    if pmagplotlib.verbose:
                                        print ymeaskey,' being used for plotting Y'
                                    break 
        if ymeaskey!="" and xmeaskey!="":
            for rec in data:
                x,y='',''
                spec=rec['er_specimen_name'] # get the ydata for this specimen
                if rec[ymeaskey]!="" and methy in rec['magic_method_codes'].split(':'): 
                    if ytreat_key=="" or (ytreat_key in rec.keys() and float(rec[ytreat_key])==ystep):
                        y=float(rec[ymeaskey])
                        for rec in data: # now find the xdata 
                            if rec['er_specimen_name']==spec and rec[xmeaskey]!="" and methx in rec['magic_method_codes'].split(':'): 
                                if xtreat_key=="" or (xtreat_key in rec.keys() and float(rec[xtreat_key])==xstep):
                                    x=float(rec[xmeaskey])
                if x != '' and y!= '':
                    X.append(x)
                    Y.append(y)
        if len(X)>0:
            pmagplotlib.clearFIG(FIG['fig'])
            pmagplotlib.plotXY(FIG['fig'],X,Y,sym='ro',xlab=methx,ylab=methy,title=plot+':Biplot')
            if not pmagplotlib.isServer and do_plot:
                pmagplotlib.drawFIGS(FIG)
                ans=raw_input('S[a]ve plots, [q]uit,  Return for next plot ' )
                if ans=='a':
                    files={}
                    for key in FIG.keys(): files[key]=plot+'_'+key+fmt
                    pmagplotlib.saveP(FIG,files)
                if ans=='q':
                    print "Good-bye\n"
                    sys.exit()
            else:
                files={}
                for key in FIG.keys(): files[key]=plot+'_'+key+fmt
                if pmagplotlib.isServer:
                    black     = '#000000'
                    purple    = '#800080'
                    titles={}
                    titles['fig']='X Y Plot'
                    FIG = pmagplotlib.addBorders(FIG,titles,black,purple)
                pmagplotlib.saveP(FIG,files)
        else:
            print 'nothing to plot for ',plot
Exemplo n.º 31
0
def main():
    """
    NAME
        quick_hyst.py

    DESCRIPTION
        makes plots of hysteresis data

    SYNTAX
        quick_hyst.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f: specify input file, default is measurements.txt
        -spc SPEC: specify specimen name to plot and quit
        -sav save all plots and quit
        -fmt [png,svg,eps,jpg]
    """
    args = sys.argv
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    plots = 0
    pltspec = ""
    verbose = pmagplotlib.verbose
    #version_num = pmag.get_version()
    dir_path = pmag.get_named_arg_from_sys('-WD', '.')
    dir_path = os.path.realpath(dir_path)
    meas_file = pmag.get_named_arg_from_sys('-f', 'measurements.txt')
    fmt = pmag.get_named_arg_from_sys('-fmt', 'png')
    if '-sav' in args:
        verbose = 0
        plots = 1
    if '-spc' in args:
        ind = args.index("-spc")
        pltspec = args[ind + 1]
        verbose = 0
        plots = 1
    #
    con = nb.Contribution(dir_path,
                          read_tables=['measurements'],
                          custom_filenames={'measurements': meas_file})
    # get as much name data as possible (used for naming plots)
    if not 'measurements' in con.tables:
        print("-W- No measurement file found")
        return
    con.propagate_location_to_measurements()

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

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

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

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

        # get all records with non-blank values in any intlist column
        # find intensity data
        for int_column in intlist:
            if int_column in spec.columns:
                int_col = int_column
                break
        meas_data = spec[spec[int_column].notnull()]
        if len(meas_data) == 0:
            break
        #
        c = ['k-', 'b-', 'c-', 'g-', 'm-', 'r-', 'y-']
        cnum = 0
        Temps = []
        xlab, ylab, title = '', '', ''
        Temps = meas_data['treat_temp'].unique()
        for t in Temps:
            print('working on t: ', t)
            t_data = meas_data[meas_data['treat_temp'] == t]
            m = int_col
            B = t_data['meas_field_dc'].astype(float).values
            M = t_data[m].astype(float).values
            # now plot the hysteresis curve(s)
            #
            if len(B) > 0:
                B = numpy.array(B)
                M = numpy.array(M)
                if t == Temps[-1]:
                    xlab = 'Field (T)'
                    ylab = m
                    title = 'Hysteresis: ' + s
                if t == Temps[0]:
                    pmagplotlib.clearFIG(HDD['hyst'])
                pmagplotlib.plotXY(HDD['hyst'],
                                   B,
                                   M,
                                   sym=c[cnum],
                                   xlab=xlab,
                                   ylab=ylab,
                                   title=title)
                pmagplotlib.plotXY(HDD['hyst'], [1.1 * B.min(), 1.1 * B.max()],
                                   [0, 0],
                                   sym='k-',
                                   xlab=xlab,
                                   ylab=ylab,
                                   title=title)
                pmagplotlib.plotXY(HDD['hyst'], [0, 0],
                                   [1.1 * M.min(), 1.1 * M.max()],
                                   sym='k-',
                                   xlab=xlab,
                                   ylab=ylab,
                                   title=title)
                if verbose:
                    pmagplotlib.drawFIGS(HDD)
                cnum += 1
                if cnum == len(c):
                    cnum = 0

#
        files = {}
        if plots:
            if pltspec != "":
                s = pltspec
            for key in list(HDD.keys()):
                if pmagplotlib.isServer:
                    if synth == '':
                        files[
                            key] = "LO:_" + locname + '_SI:_' + site + '_SA:_' + sample + '_SP:_' + s + '_TY:_' + key + '_.' + fmt
                    else:
                        files[
                            key] = 'SY:_' + synth + '_TY:_' + key + '_.' + fmt
                else:
                    if synth == '':
                        filename = ''
                        for item in [locname, site, sample, s, key]:
                            if item:
                                item = item.replace(' ', '_')
                                filename += item + '_'
                        if filename.endswith('_'):
                            filename = filename[:-1]
                        filename += ".{}".format(fmt)
                        files[key] = filename
                    else:
                        files[key] = "{}_{}.{}".format(synth, key, fmt)

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

                pmagplotlib.saveP(HDD, files)
            if ans == '':
                k += 1
            if ans == "p":
                del HystRecs[-1]
                k -= 1
            if ans == 'q':
                print("Good bye")
                sys.exit()
            if ans == 's':
                keepon = 1
                specimen = input(
                    'Enter desired specimen name (or first part there of): ')
                while keepon == 1:
                    try:
                        k = sids.index(specimen)
                        keepon = 0
                    except:
                        tmplist = []
                        for qq in range(len(sids)):
                            if specimen in sids[qq]:
                                tmplist.append(sids[qq])
                        print(specimen, " not found, but this was: ")
                        print(tmplist)
                        specimen = input('Select one or try again\n ')
                        k = sids.index(specimen)
        else:
            k += 1
        if len(B) == 0:
            if verbose:
                print('skipping this one - no hysteresis data')
            k += 1
Exemplo n.º 32
0
def main():
    """
    NAME
        quick_hyst.py

    DESCRIPTION
        makes plots of hysteresis data

    SYNTAX
        quick_hyst.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f: specify input file, default is measurements.txt
        -spc SPEC: specify specimen name to plot and quit
        -sav save all plots and quit
        -fmt [png,svg,eps,jpg]
    """
    args = sys.argv
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    plots = 0
    pltspec = ""
    verbose = pmagplotlib.verbose
    #version_num = pmag.get_version()
    dir_path = pmag.get_named_arg('-WD', '.')
    dir_path = os.path.realpath(dir_path)
    meas_file = pmag.get_named_arg('-f', 'measurements.txt')
    fmt = pmag.get_named_arg('-fmt', 'png')
    if '-sav' in args:
        verbose = 0
        plots = 1
    if '-spc' in args:
        ind = args.index("-spc")
        pltspec = args[ind+1]
        verbose = 0
        plots = 1
    #
    con = cb.Contribution(dir_path, read_tables=['measurements'],
                          custom_filenames={'measurements': meas_file})
    # get as much name data as possible (used for naming plots)
    if not 'measurements' in con.tables:
        print("-W- No measurement file found")
        return
    con.propagate_location_to_measurements()

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

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

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

    while k < len(sids):
        locname, site, sample, synth = '', '', '', ''
        s = sids[k]
        if verbose:
            print(s, k + 1, 'out of ', len(sids))
        # B, M for hysteresis, Bdcd,Mdcd for irm-dcd data
        B, M = [], []
        # get all measurements for this specimen
        spec = hyst_data[hyst_data['specimen'] == s]
        # get names
        if 'location' in spec:
            locname = spec['location'].iloc[0]
        if 'site' in spec:
            site = spec['sample'].iloc[0]
        if 'sample' in spec:
            sample = spec['sample'].iloc[0]
        # get all records with non-blank values in any intlist column
        # find intensity data
        for int_column in intlist:
            if int_column in spec.columns:
                int_col = int_column
                break
        meas_data = spec[spec[int_column].notnull()]
        if len(meas_data) == 0:
            break
        #
        c = ['k-', 'b-', 'c-', 'g-', 'm-', 'r-', 'y-']
        cnum = 0
        Temps = []
        xlab, ylab, title = '', '', ''
        Temps = meas_data['treat_temp'].unique()
        for t in Temps:
            print('working on t: ', t)
            t_data = meas_data[meas_data['treat_temp'] == t]
            m = int_col
            B = t_data['meas_field_dc'].astype(float).values
            M = t_data[m].astype(float).values
            # now plot the hysteresis curve(s)
            #
            if len(B) > 0:
                B = numpy.array(B)
                M = numpy.array(M)
                if t == Temps[-1]:
                    xlab = 'Field (T)'
                    ylab = m
                    title = 'Hysteresis: ' + s
                if t == Temps[0]:
                    pmagplotlib.clearFIG(HDD['hyst'])
                pmagplotlib.plot_xy(HDD['hyst'],B,M,sym=c[cnum],xlab=xlab,ylab=ylab,title=title)
                pmagplotlib.plot_xy(HDD['hyst'],[1.1*B.min(),1.1*B.max()],[0,0],sym='k-',xlab=xlab,ylab=ylab,title=title)
                pmagplotlib.plot_xy(HDD['hyst'],[0,0],[1.1*M.min(),1.1*M.max()],sym='k-',xlab=xlab,ylab=ylab,title=title)
                if verbose and not set_env.IS_WIN:
                    pmagplotlib.draw_figs(HDD)
                cnum += 1
                if cnum == len(c):
                    cnum = 0
  #
        files = {}
        if plots:
            if pltspec != "":
                s = pltspec
            for key in list(HDD.keys()):
                if pmagplotlib.isServer:
                    if synth == '':
                        files[key] = "LO:_"+locname+'_SI:_'+site+'_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt
                    else:
                        files[key] = 'SY:_'+synth+'_TY:_'+key+'_.'+fmt
                else:
                    if synth == '':
                        filename = ''
                        for item in [locname, site, sample, s, key]:
                            if item:
                                item = item.replace(' ', '_')
                                filename += item + '_'
                        if filename.endswith('_'):
                            filename = filename[:-1]
                        filename += ".{}".format(fmt)
                        files[key] = filename
                    else:
                        files[key] = "{}_{}.{}".format(synth, key, fmt)

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

                pmagplotlib.save_plots(HDD, files)
            if ans == '':
                k += 1
            if ans == "p":
                del HystRecs[-1]
                k -= 1
            if ans == 'q':
                print("Good bye")
                sys.exit()
            if ans == 's':
                keepon = 1
                specimen = input('Enter desired specimen name (or first part there of): ')
                while keepon == 1:
                    try:
                        k = sids.index(specimen)
                        keepon = 0
                    except:
                        tmplist = []
                        for qq in range(len(sids)):
                            if specimen in sids[qq]:
                                tmplist.append(sids[qq])
                        print(specimen, " not found, but this was: ")
                        print(tmplist)
                        specimen = input('Select one or try again\n ')
                        k = sids.index(specimen)
        else:
            k += 1
        if len(B) == 0:
            if verbose:
                print('skipping this one - no hysteresis data')
            k += 1