def main(): """ NAME pmag_results_extract.py DESCRIPTION make a tab delimited output file from pmag_results table SYNTAX pmag_results_extract.py [command line options] OPTIONS -h prints help message and quits -f RFILE, specify pmag_results table; default is pmag_results.txt -fa AFILE, specify er_ages table; default is NONE -fsp SFILE, specify pmag_specimens table, default is NONE -fcr CFILE, specify pmag_criteria table, default is NONE -g include specimen_grade in table - only works for PmagPy generated pmag_specimen formatted files. -tex, output in LaTeX format """ do_help = pmag.get_flag_arg_from_sys('-h') if do_help: print(main.__doc__) return False res_file = pmag.get_named_arg_from_sys('-f', 'pmag_results.txt') crit_file = pmag.get_named_arg_from_sys('-fcr', '') spec_file = pmag.get_named_arg_from_sys('-fsp', '') age_file = pmag.get_named_arg_from_sys('-fa', '') grade = pmag.get_flag_arg_from_sys('-g') latex = pmag.get_flag_arg_from_sys('-tex') WD = pmag.get_named_arg_from_sys('-WD', os.getcwd()) ipmag.pmag_results_extract(res_file, crit_file, spec_file, age_file, latex, grade, WD)
def main(): """ NAME pmag_results_extract.py DESCRIPTION make a tab delimited output file from pmag_results table SYNTAX pmag_results_extract.py [command line options] OPTIONS -h prints help message and quits -f RFILE, specify pmag_results table; default is pmag_results.txt -fa AFILE, specify er_ages table; default is NONE -fsp SFILE, specify pmag_specimens table, default is NONE -fcr CFILE, specify pmag_criteria table, default is NONE -g include specimen_grade in table - only works for PmagPy generated pmag_specimen formatted files. -tex, output in LaTeX format """ do_help = pmag.get_flag_arg_from_sys('-h') if do_help: print main.__doc__ return False res_file = pmag.get_named_arg_from_sys('-f', 'pmag_results.txt') crit_file = pmag.get_named_arg_from_sys('-fcr', '') spec_file = pmag.get_named_arg_from_sys('-fsp', '') age_file = pmag.get_named_arg_from_sys('-fa', '') grade = pmag.get_flag_arg_from_sys('-g') latex = pmag.get_flag_arg_from_sys('-tex') WD = pmag.get_named_arg_from_sys('-WD', os.getcwd()) ipmag.pmag_results_extract(res_file, crit_file, spec_file, age_file, latex, grade, WD)
def __init__(self, WD=None, DM=None, dmodel=None): """ Input working directory, data model number (2.5 or 3), and data model (optional). """ wx.Frame.__init__(self, None, wx.ID_ANY, self.title, name='pmag_gui mainframe') #set icon self.icon = wx.Icon() icon_path = os.path.join(PMAGPY_DIRECTORY, 'programs', 'images', 'PmagPy.ico') if os.path.isfile(icon_path): self.icon.CopyFromBitmap(wx.Bitmap(icon_path, wx.BITMAP_TYPE_ANY)) self.SetIcon(self.icon) else: print("-I- PmagPy icon file not found -- skipping") # if DM was provided: if DM: self.data_model_num = int(float(DM)) # try to get DM from command line args if not DM: self.data_model_num = int( float(pmag.get_named_arg_from_sys("-DM", 0))) DM = self.data_model_num # if WD was provided: if WD: self.WD = WD else: WD = pmag.get_named_arg_from_sys("-WD", '') self.WD = WD self.data_model = dmodel self.FIRST_RUN = True self.panel = wx.Panel(self, name='pmag_gui main panel') self.InitUI() if WD and DM: self.set_dm(self.data_model_num) if WD: self.dir_path.SetValue(self.WD) # for use as module: self.resource_dir = os.getcwd() # set some things self.HtmlIsOpen = False self.Bind(wx.EVT_CLOSE, self.on_menu_exit) # if not specified on the command line, # make the user choose data model num (2 or 3) # and working directory wx.CallAfter(self.get_dm_and_wd, DM, WD)
def __init__(self, WD=None, DM=None, dmodel=None): """ Input working directory, data model number (2.5 or 3), and data model (optional). """ wx.Frame.__init__(self, None, wx.ID_ANY, self.title, name='pmag_gui mainframe') #set icon self.icon = wx.Icon() icon_path = os.path.join(PMAGPY_DIRECTORY, 'programs', 'images', 'PmagPy.ico') if os.path.isfile(icon_path): self.icon.CopyFromBitmap(wx.Bitmap(icon_path, wx.BITMAP_TYPE_ANY)) self.SetIcon(self.icon) else: print("-I- PmagPy icon file not found -- skipping") # if DM was provided: if DM: self.data_model_num = int(float(DM)) # try to get DM from command line args if not DM: self.data_model_num = int(float(pmag.get_named_arg_from_sys("-DM", 0))) DM = self.data_model_num # if WD was provided: if WD: self.WD = WD else: WD = pmag.get_named_arg_from_sys("-WD", '') self.WD = WD self.WD = os.path.realpath(self.WD) self.data_model = dmodel self.FIRST_RUN = True self.panel = wx.Panel(self, name='pmag_gui main panel') self.InitUI() if WD and DM: self.set_dm(self.data_model_num) if WD: self.dir_path.SetValue(self.WD) # for use as module: self.resource_dir = os.getcwd() # set some things self.HtmlIsOpen = False self.Bind(wx.EVT_CLOSE, self.on_menu_exit) # if not specified on the command line, # make the user choose data model num (2 or 3) # and working directory wx.CallAfter(self.get_dm_and_wd, DM, WD)
def main(): try: from mpl_toolkits.basemap import basemap_datadir except: print "-E- Could not import the basemap module..." else: # allow user to specify what directory to find the data_files in custom_dir = pmag.get_named_arg_from_sys('-source-dir', default_val="") if os.path.isdir(custom_dir): data_dir = custom_dir # if user didn't specify a directory, find the etopo20 directory else: # if installed by pip, etopo20 is in sys.prefix pip_data_dir = os.path.join(sys.prefix, 'data_files', 'etopo20') if os.path.isdir(pip_data_dir): data_dir = pip_data_dir else: # if not installed by pip, etopo20 is in the local PmagPy directory from pmagpy import find_pmag_dir pmag_dir = find_pmag_dir.get_pmag_dir() data_dir = os.path.join(pmag_dir, 'data_files', 'etopo20') # if none of those options worked, warn the user: if not os.path.isdir(data_dir): print "-W- Could not find data_files to copy in {}".format( data_dir) print "-I- You can run this program with the command line flag -source-dir to specify the location of the etopo20 directory." print "-I- For example: 'install_etopo.py -source-dir ~/Python/PmagPy/data_files/etopo20'" return print "installing etopo20 files from ", path.join(data_dir, 'etopo20*') print "to the basemap data directory: ", basemap_datadir command = 'cp ' + path.join(data_dir, 'etopo20*') + " " + basemap_datadir os.system(command)
def main(): if '-h' in sys.argv: print "See https://earthref.org/PmagPy/cookbook/#magic_gui.py for a complete tutorial" sys.exit() print '-I- Starting MagIC GUI - please be patient' # if redirect is true, wxpython makes its own output window for stdout/stderr #app = wx.App(redirect=True) # this sends stdout to terminal: app = wx.App(redirect=False) # this sends stdout to wxPython: #app = wx.App(redirect=True) working_dir = pmag.get_named_arg_from_sys('-WD', '.') app.frame = MainFrame(working_dir) ## this causes an error with Canopy Python ## (it works with brew Python) ## need to use these lines for Py2app #if working_dir == '.': # app.frame.on_change_dir_button(None) app.frame.Show() app.frame.Center() ## use for debugging: #if '-i' in sys.argv: # import wx.lib.inspection # wx.lib.inspection.InspectionTool().Show() app.MainLoop()
def main(): if '-h' in sys.argv: help_msg = """ Runs Pmag GUI for uploading, downloading, analyzing and visualizing data. SYNTAX pmag_gui.py [command line options] # or, for Anaconda users: pmag_gui_anaconda [command line options] INFORMATION See https://earthref.org/PmagPy/cookbook/#pmag_gui.py for a complete tutorial """ print(help_msg) sys.exit() print('-I- Starting Pmag GUI - please be patient') # if redirect is true, wxpython makes its own output window for stdout/stderr if 'darwin' in sys.platform: app = wx.App(redirect=False) else: app = wx.App(redirect=True) app.frame = MagMainFrame() working_dir = pmag.get_named_arg_from_sys('-WD', '.') app.frame.Show() app.frame.Center() ## use for debugging: #if '-i' in sys.argv: # import wx.lib.inspection # wx.lib.inspection.InspectionTool().Show() app.MainLoop()
def main(): if '-h' in sys.argv: print( "See https://earthref.org/PmagPy/cookbook/#magic_gui.py for a complete tutorial" ) sys.exit() print('-I- Starting MagIC GUI - please be patient') # if redirect is true, wxpython makes its own output window for stdout/stderr if 'darwin' in sys.platform: app = wx.App(redirect=False) else: app = wx.App(redirect=True) working_dir = pmag.get_named_arg_from_sys('-WD', '') app.frame = MainFrame(working_dir) ## this causes an error with Canopy Python ## (it works with brew Python) ## need to use these lines for Py2app #if working_dir == '.': # app.frame.on_change_dir_button(None) app.frame.Show() app.frame.Center() ## use for debugging: #if '-i' in sys.argv: # import wx.lib.inspection # wx.lib.inspection.InspectionTool().Show() app.MainLoop()
def main(): try: from mpl_toolkits.basemap import basemap_datadir except: print("-E- Could not import the basemap module...") else: # allow user to specify what directory to find the data_files in custom_dir = pmag.get_named_arg_from_sys('-source-dir', default_val="") if os.path.isdir(custom_dir): data_dir = custom_dir # if user didn't specify a directory, find the etopo20 directory else: # if installed by pip, etopo20 is in sys.prefix pip_data_dir = os.path.join(sys.prefix, 'data_files', 'etopo20') if os.path.isdir(pip_data_dir): data_dir = pip_data_dir else: # if not installed by pip, etopo20 is in the local PmagPy directory from pmagpy import find_pmag_dir pmag_dir = find_pmag_dir.get_pmag_dir() data_dir = os.path.join(pmag_dir, 'data_files', 'etopo20') # if none of those options worked, warn the user: if not os.path.isdir(data_dir): print("-W- Could not find data_files to copy in {}".format(data_dir)) print("-I- You can run this program with the command line flag -source-dir to specify the location of the etopo20 directory.") print("-I- For example: 'install_etopo.py -source-dir ~/Python/PmagPy/data_files/etopo20'") return print("installing etopo20 files from ", path.join(data_dir, 'etopo20*')) print("to the basemap data directory: ",basemap_datadir) command = 'cp ' + path.join(data_dir, 'etopo20*') + " "+ basemap_datadir os.system(command)
def main(): if '-h' in sys.argv: help_msg = """ MagIC GUI is for creating and uploading contributions to the MagIC database. Note: if you are starting with a measurement file, it is better to use Pmag GUI instead. MagIC GUI is mainly meant for contributions with specimen-level data and higher. SYNTAX magic_gui.py [command line options] # or, for Anaconda users: magic_gui_anaconda [command line options] INFORMATION See https://earthref.org/PmagPy/cookbook/#magic_gui.py for a complete tutorial """ print(help_msg) sys.exit() print('-I- Starting MagIC GUI - please be patient') # if redirect is true, wxpython makes its own output window for stdout/stderr if 'darwin' in sys.platform: app = wx.App(redirect=False) else: app = wx.App(redirect=True) working_dir = pmag.get_named_arg_from_sys('-WD', '') app.frame = MainFrame(working_dir) app.frame.Show() app.frame.Center() ## use for debugging: #if '-i' in sys.argv: # import wx.lib.inspection # wx.lib.inspection.InspectionTool().Show() app.MainLoop()
def __init__(self, WD=None, DM=None, dmodel=None): """ Input working directory, data model number (2.5 or 3), and data model (optional). """ if not DM: self.data_model_num = int(pmag.get_named_arg_from_sys("-DM", 2.5)) else: self.data_model_num = int(DM) self.data_model = dmodel self.FIRST_RUN = True wx.Frame.__init__(self, None, wx.ID_ANY, self.title, name='pmag_gui mainframe') self.panel = wx.Panel(self, name='pmag_gui main panel') self.InitUI() # for use as module: self.resource_dir = os.getcwd() if not WD: self.get_DIR() # choose directory dialog else: self.WD = WD self.HtmlIsOpen = False self.Bind(wx.EVT_CLOSE, self.on_menu_exit) if self.data_model_num == 2: self.er_magic = builder.ErMagicBuilder(self.WD, data_model=self.data_model) elif self.data_model_num == 3: wx.CallAfter(self.get_wd_data)
def main(): if '-h' in sys.argv: print "Choose the folder where you want the PmagPy data files to be." print "Navigate to that folder, and use the command: 'move_data_files.py -d .'" print "Alternatively, you may use the full path to the directory of your choice from anywhere in the file system: 'move_data_files.py -d /Users/***/Desktop' where *** is your username" sys.exit() dest = pmag.get_named_arg_from_sys('-d', None, True) data_files = path.join(sys.prefix, 'data_files') copy_directory(data_files, dest)
def main(): if '-h' in sys.argv: print("Choose the folder where you want the PmagPy data files to be.") print("Navigate to that folder, and use the command: 'move_data_files.py -d .'") print("Alternatively, you may use the full path to the directory of your choice from anywhere in the file system: 'move_data_files.py -d /Users/***/Desktop' where *** is your username") sys.exit() dest = pmag.get_named_arg_from_sys('-d', None, True) data_files = path.join(sys.prefix, 'data_files') copy_directory(data_files, dest)
def main(): """ Take out dos problem characters from any file """ filename = pmag.get_named_arg_from_sys('-f') if not filename: return with open(filename, 'rb+') as f: content = f.read() f.seek(0) f.write(content.replace(b'\r', b'')) f.truncate()
def __init__(self, WD=None, DM=None, dmodel=None): """ Input working directory, data model number (2.5 or 3), and data model (optional). """ wx.Frame.__init__(self, None, wx.ID_ANY, self.title, name='pmag_gui mainframe') # if DM was provided: if DM: self.data_model_num = int(DM) # try to get DM from command line args if not DM: self.data_model_num = int(pmag.get_named_arg_from_sys("-DM", 0)) DM = self.data_model_num # if you still don't have DM, make the user choose if not DM: from dialogs import demag_dialogs ui_dialog = demag_dialogs.user_input( self, ['data_model'], parse_funcs=[float], heading= "Please input prefered data model (2.5,3.0). Note: 2.5 is for legacy projects only, if you are have new data please use 3.0.", values=[3]) res = ui_dialog.ShowModal() vals = ui_dialog.get_values() self.data_model_num = int(vals[1]['data_model']) self.data_model = dmodel self.FIRST_RUN = True self.panel = wx.Panel(self, name='pmag_gui main panel') self.InitUI() # for use as module: self.resource_dir = os.getcwd() if not WD: self.get_DIR() # choose directory dialog else: self.WD = WD self.HtmlIsOpen = False self.Bind(wx.EVT_CLOSE, self.on_menu_exit) if self.data_model_num == 2: self.er_magic = builder.ErMagicBuilder(self.WD, data_model=self.data_model) elif self.data_model_num == 3: wx.CallAfter(self.get_wd_data)
def main(): if '-h' in sys.argv: print( "Some mapping utilities use the Etopo package for topography and these data sets do not come standard with the Python installation of Basemap. To install these additional files, use: 'install_etopo.py'." ) return try: from mpl_toolkits.basemap import basemap_datadir except: print("-E- Could not import the basemap module...") else: # allow user to specify what directory to find the data_files in custom_dir = pmag.get_named_arg_from_sys('-source-dir', default_val="") if os.path.isdir(custom_dir): data_dir = custom_dir # if user didn't specify a directory, find the etopo20 directory else: # if installed by pip, etopo20 is in sys.prefix pip_data_dir = os.path.join(sys.prefix, 'data_files', 'etopo20') if os.path.isdir(pip_data_dir): data_dir = pip_data_dir else: # if not installed by pip, etopo20 is in the local PmagPy directory from pmagpy import find_pmag_dir pmag_dir = find_pmag_dir.get_pmag_dir() data_dir = os.path.join(pmag_dir, 'data_files', 'etopo20') # if none of those options worked, warn the user: if not os.path.isdir(data_dir): print( "-W- Could not find data_files to copy in {}".format(data_dir)) print( "-I- You can run this program with the command line flag -source-dir to specify the location of the etopo20 directory." ) print( "-I- For example: 'install_etopo.py -source-dir ~/Python/PmagPy/data_files/etopo20'" ) return print("installing etopo20 files from ", path.join(data_dir, 'etopo20*')) print("to the basemap data directory: ", basemap_datadir) if sys.platform in ['win32', 'win64']: command = 'copy ' + path.join(data_dir, 'etopo20*') + " " + basemap_datadir else: command = 'cp ' + path.join(data_dir, 'etopo20*') + " " + basemap_datadir os.system(command)
def main(): """ NAME download_magic.py DESCRIPTION unpacks a magic formatted smartbook .txt file from the MagIC database into the tab delimited MagIC format txt files for use with the MagIC-Py programs. SYNTAX download_magic.py command line options] INPUT takes either the upload.txt file created by upload_magic.py or the file exported by the MagIC v2.2 console software (downloaded from the MagIC database or output by the Console on your PC). OPTIONS -h prints help message and quits -i allows interactive entry of filename -f FILE specifies input file name -O do not overwrite duplicate Location_* directories while downloading """ if '-h' in sys.argv: print main.__doc__ sys.exit() if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path = sys.argv[ind + 1] # interactive entry if '-i' in sys.argv: infile = raw_input("Magic txt file for unpacking? ") dir_path = '.' input_dir_path = '.' # non-interactive else: dataframe = extractor.command_line_dataframe([['O', False, True]]) checked_args = extractor.extract_and_check_args(sys.argv, dataframe) infile, dir_path, input_dir_path, overwrite = extractor.get_vars( ['f', 'WD', 'ID', 'O'], checked_args) data_model = float(pmag.get_named_arg_from_sys("-DM", 2.5)) ipmag.download_magic(infile, dir_path, input_dir_path, overwrite, data_model)
def __init__(self, WD=None): self.data_model_num = int(pmag.get_named_arg_from_sys("-DM", 2.5)) self.FIRST_RUN = True wx.Frame.__init__(self, None, wx.ID_ANY, self.title, name='pmag_gui mainframe') self.panel = wx.Panel(self, name='pmag_gui main panel') self.InitUI() # for use as module: self.resource_dir = os.getcwd() if not WD: self.get_DIR() # choose directory dialog else: self.WD = WD self.HtmlIsOpen = False self.Bind(wx.EVT_CLOSE, self.on_menu_exit) if self.data_model_num == 2: self.er_magic = builder.ErMagicBuilder(self.WD) elif self.data_model_num == 3: self.contribution = nb.Contribution(self.WD)
def main(): """ NAME download_magic.py DESCRIPTION unpacks a magic formatted smartbook .txt file from the MagIC database into the tab delimited MagIC format txt files for use with the MagIC-Py programs. SYNTAX download_magic.py command line options] INPUT takes either the upload.txt file created by upload_magic.py or the file exported by the MagIC v2.2 console software (downloaded from the MagIC database or output by the Console on your PC). OPTIONS -h prints help message and quits -i allows interactive entry of filename -f FILE specifies input file name -O do not overwrite duplicate Location_* directories while downloading """ if '-h' in sys.argv: print main.__doc__ sys.exit() if '-WD' in sys.argv: ind=sys.argv.index('-WD') dir_path=sys.argv[ind+1] # interactive entry if '-i' in sys.argv: infile=raw_input("Magic txt file for unpacking? ") dir_path = '.' input_dir_path = '.' # non-interactive else: dataframe = extractor.command_line_dataframe([['O', False, True]]) checked_args = extractor.extract_and_check_args(sys.argv, dataframe) infile, dir_path, input_dir_path, overwrite = extractor.get_vars(['f', 'WD', 'ID', 'O'], checked_args) data_model = float(pmag.get_named_arg_from_sys("-DM", 2.5)) ipmag.download_magic(infile, dir_path, input_dir_path, overwrite, data_model)
def main(): if '-h' in sys.argv: print "See https://earthref.org/PmagPy/cookbook/#pmag_gui.py for a complete tutorial" sys.exit() from programs import pmag_gui from pmagpy import pmag print '-I- Starting Pmag GUI 3 - please be patient' # if redirect is true, wxpython makes its own output window for stdout/stderr app = wx.App(redirect=True) app.frame = pmag_gui.MagMainFrame(DM=3) working_dir = pmag.get_named_arg_from_sys('-WD', '.') ## this causes an error with Canopy Python ## (it works with brew Python) ## need to use these lines for Py2app if working_dir == '.': app.frame.on_change_dir_button(None) app.frame.Show() app.frame.Center() ## use for debugging: #if '-i' in sys.argv: # import wx.lib.inspection # wx.lib.inspection.InspectionTool().Show() app.MainLoop()
def main(): """ NAME upload_magic.py DESCRIPTION This program will prepare your PMAG text files created by the programs nfo_magic.py, zeq_magic.py, thellier_magic.py, mag_magic, specimens_results_magic.py and so on. it will check for all the MagIC text files and skip the missing ones SYNTAX upload_magic.py INPUT MagIC txt files OPTIONS -h prints help message and quits -all include all the measurement data, default is only those used in interpretations -DM specify which MagIC data model number to use (2 or 3). Default is 3. OUTPUT upload.txt: file for uploading to MagIC database """ if '-h' in sys.argv: print(main.__doc__) sys.exit() else: data_model_num = pmag.get_named_arg_from_sys("-DM", 3) dataframe = extractor.command_line_dataframe([['cat', False, 0], ['F', False, ''], ['f', False, '']]) checked_args = extractor.extract_and_check_args(sys.argv, dataframe) dir_path, concat = extractor.get_vars(['WD', 'cat'], checked_args) if data_model_num == 2: ipmag.upload_magic(concat, dir_path) else: ipmag.upload_magic3(concat, dir_path)
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
def main(): """ NAME atrm_magic.py DESCRIPTION Converts ATRM data to best-fit tensor (6 elements plus sigma) Original program ARMcrunch written to accomodate ARM anisotropy data collected from 6 axial directions (+X,+Y,+Z,-X,-Y,-Z) using the off-axis remanence terms to construct the tensor. A better way to do the anisotropy of ARMs is to use 9,12 or 15 measurements in the Hext rotational scheme. SYNTAX atrm_magic.py [-h][command line options] OPTIONS -h prints help message and quits -usr USER: identify user, default is "" -f FILE: specify input file, default is atrm_measurements.txt -Fa FILE: specify anisotropy output file, default is trm_anisotropy.txt (MagIC 2.5 only) -Fr FILE: specify results output file, default is atrm_results.txt (MagIC 2.5 only) -Fsi FILE: specify output file, default is specimens.txt (MagIC 3 only) -DM DATA_MODEL: specify MagIC 2 or MagIC 3, default is 3 INPUT Input for the present program is a TRM acquisition data with an optional baseline. The order of the measurements is: Decs=[0,90,0,180,270,0,0,90,0] Incs=[0,0,90,0,0,-90,0,0,90] The last two measurements are optional """ # initialize some parameters args = sys.argv user = "" meas_file = "atrm_measurements.txt" rmag_anis = "trm_anisotropy.txt" rmag_res = "atrm_results.txt" dir_path = '.' # # get name of file from command line # if '-WD' in args: ind = args.index('-WD') dir_path = args[ind + 1] if "-h" in args: print(main.__doc__) sys.exit() if "-usr" in args: ind = args.index("-usr") user = sys.argv[ind + 1] if "-f" in args: ind = args.index("-f") meas_file = sys.argv[ind + 1] if "-Fa" in args: ind = args.index("-Fa") rmag_anis = args[ind + 1] if "-Fr" in args: ind = args.index("-Fr") rmag_res = args[ind + 1] data_model_num = int(pmag.get_named_arg_from_sys("-DM", 3)) spec_file = pmag.get_named_arg_from_sys("-Fsi", "specimens.txt") spec_file = os.path.join(dir_path, spec_file) meas_file = dir_path + '/' + meas_file rmag_anis = dir_path + '/' + rmag_anis rmag_res = dir_path + '/' + rmag_res # read in data if data_model_num == 3: meas_data = [] meas_data3, file_type = pmag.magic_read(meas_file) if file_type != 'measurements': print(file_type, "This is not a valid measurements file ") sys.exit() # convert meas_data to 2.5 for rec in meas_data3: meas_map = map_magic.meas_magic3_2_magic2_map meas_data.append(map_magic.mapping(rec, meas_map)) else: meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print(file_type, "This is not a valid magic_measurements file ") sys.exit() meas_data = pmag.get_dictitem( meas_data, 'magic_method_codes', 'LP-AN-TRM', 'has') # # # get sorted list of unique specimen names ssort = [] for rec in meas_data: spec = rec["er_specimen_name"] if spec not in ssort: ssort.append(spec) sids = sorted(ssort) # # # work on each specimen # specimen, npos = 0, 6 RmagSpecRecs, RmagResRecs = [], [] SpecRecs, SpecRecs3 = [], [] while specimen < len(sids): nmeas = 0 s = sids[specimen] RmagSpecRec = {} RmagResRec = {} BX, X = [], [] method_codes = [] Spec0 = "" # # find the data from the meas_data file for this sample # and get dec, inc, int and convert to x,y,z # # fish out data for this specimen name data = pmag.get_dictitem(meas_data, 'er_specimen_name', s, 'T') if len(data) > 5: RmagSpecRec["rmag_anisotropy_name"] = data[0]["er_specimen_name"] RmagSpecRec["er_location_name"] = data[0].get("er_location_name", "") RmagSpecRec["er_specimen_name"] = data[0]["er_specimen_name"] RmagSpecRec["er_sample_name"] = data[0].get("er_sample_name", "") RmagSpecRec["er_site_name"] = data[0].get("er_site_name", "") RmagSpecRec["magic_experiment_names"] = RmagSpecRec["rmag_anisotropy_name"] + ":ATRM" RmagSpecRec["er_citation_names"] = "This study" RmagResRec["rmag_result_name"] = data[0]["er_specimen_name"] + ":ATRM" RmagResRec["er_location_names"] = data[0].get("er_location_names", "") RmagResRec["er_specimen_names"] = data[0]["er_specimen_name"] RmagResRec["er_sample_names"] = data[0].get("er_sample_name", "") RmagResRec["er_site_names"] = data[0].get("er_site_name", "") RmagResRec["magic_experiment_names"] = RmagSpecRec["rmag_anisotropy_name"] + ":ATRM" RmagResRec["er_citation_names"] = "This study" RmagSpecRec["anisotropy_type"] = "ATRM" if "magic_instrument_codes" in list(data[0].keys()): RmagSpecRec["magic_instrument_codes"] = data[0]["magic_instrument_codes"] else: RmagSpecRec["magic_instrument_codes"] = "" RmagSpecRec["anisotropy_description"] = "Hext statistics adapted to ATRM" for rec in data: meths = rec['magic_method_codes'].strip().split(':') Dir = [] Dir.append(float(rec["measurement_dec"])) Dir.append(float(rec["measurement_inc"])) Dir.append(float(rec["measurement_magn_moment"])) if "LT-T-Z" in meths: BX.append(pmag.dir2cart(Dir)) # append baseline steps elif "LT-T-I" in meths: X.append(pmag.dir2cart(Dir)) nmeas += 1 # if len(BX) == 1: for i in range(len(X) - 1): BX.append(BX[0]) # assume first 0 field step as baseline elif len(BX) == 0: # assume baseline is zero for i in range(len(X)): BX.append([0., 0., 0.]) # assume baseline of 0 elif len(BX) != len(X): # if BX isn't just one measurement or one in between every infield step, just assume it is zero print('something odd about the baselines - just assuming zero') for i in range(len(X)): BX.append([0., 0., 0.]) # assume baseline of 0 if nmeas < 6: # must have at least 6 measurements right now - print('skipping specimen ', s, ' too few measurements') specimen += 1 else: # B matrix made from design matrix for positions B, H, tmpH = pmag.designATRM(npos) # # subtract optional baseline and put in a work array # work = numpy.zeros((nmeas, 3), 'f') for i in range(nmeas): for j in range(3): # subtract baseline, if available work[i][j] = X[i][j] - BX[i][j] # # calculate tensor elements # first put ARM components in w vector # w = numpy.zeros((npos * 3), 'f') index = 0 for i in range(npos): for j in range(3): w[index] = work[i][j] index += 1 s = numpy.zeros((6), 'f') # initialize the s matrix for i in range(6): for j in range(len(w)): s[i] += B[i][j] * w[j] trace = s[0] + s[1] + s[2] # normalize by the trace for i in range(6): s[i] = old_div(s[i], trace) a = pmag.s2a(s) #------------------------------------------------------------ # Calculating dels is different than in the Kappabridge # routine. Use trace normalized tensor (a) and the applied # unit field directions (tmpH) to generate model X,Y,Z # components. Then compare these with the measured values. #------------------------------------------------------------ S = 0. comp = numpy.zeros((npos * 3), 'f') for i in range(npos): for j in range(3): index = i * 3 + j compare = a[j][0] * tmpH[i][0] + a[j][1] * \ tmpH[i][1] + a[j][2] * tmpH[i][2] comp[index] = compare for i in range(npos * 3): d = old_div(w[i], trace) - comp[i] # del values S += d * d nf = float(npos * 3. - 6.) # number of degrees of freedom if S > 0: sigma = numpy.sqrt(old_div(S, nf)) else: sigma = 0 hpars = pmag.dohext(nf, sigma, s) # # prepare for output # RmagSpecRec["anisotropy_s1"] = '%8.6f' % (s[0]) RmagSpecRec["anisotropy_s2"] = '%8.6f' % (s[1]) RmagSpecRec["anisotropy_s3"] = '%8.6f' % (s[2]) RmagSpecRec["anisotropy_s4"] = '%8.6f' % (s[3]) RmagSpecRec["anisotropy_s5"] = '%8.6f' % (s[4]) RmagSpecRec["anisotropy_s6"] = '%8.6f' % (s[5]) RmagSpecRec["anisotropy_mean"] = '%8.3e' % (old_div(trace, 3)) RmagSpecRec["anisotropy_sigma"] = '%8.6f' % (sigma) RmagSpecRec["anisotropy_unit"] = "Am^2" RmagSpecRec["anisotropy_n"] = '%i' % (npos) RmagSpecRec["anisotropy_tilt_correction"] = '-1' # used by thellier_gui - must be taken out for uploading RmagSpecRec["anisotropy_F"] = '%7.1f ' % (hpars["F"]) # used by thellier_gui - must be taken out for uploading RmagSpecRec["anisotropy_F_crit"] = hpars["F_crit"] RmagResRec["anisotropy_t1"] = '%8.6f ' % (hpars["t1"]) RmagResRec["anisotropy_t2"] = '%8.6f ' % (hpars["t2"]) RmagResRec["anisotropy_t3"] = '%8.6f ' % (hpars["t3"]) RmagResRec["anisotropy_v1_dec"] = '%7.1f ' % (hpars["v1_dec"]) RmagResRec["anisotropy_v2_dec"] = '%7.1f ' % (hpars["v2_dec"]) RmagResRec["anisotropy_v3_dec"] = '%7.1f ' % (hpars["v3_dec"]) RmagResRec["anisotropy_v1_inc"] = '%7.1f ' % (hpars["v1_inc"]) RmagResRec["anisotropy_v2_inc"] = '%7.1f ' % (hpars["v2_inc"]) RmagResRec["anisotropy_v3_inc"] = '%7.1f ' % (hpars["v3_inc"]) RmagResRec["anisotropy_ftest"] = '%7.1f ' % (hpars["F"]) RmagResRec["anisotropy_ftest12"] = '%7.1f ' % (hpars["F12"]) RmagResRec["anisotropy_ftest23"] = '%7.1f ' % (hpars["F23"]) RmagResRec["result_description"] = 'Critical F: ' + \ hpars["F_crit"] + ';Critical F12/F13: ' + hpars["F12_crit"] if hpars["e12"] > hpars["e13"]: RmagResRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v1_eta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v1_eta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) else: RmagResRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v1_eta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v1_eta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) if hpars["e23"] > hpars['e12']: RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) else: RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["tilt_correction"] = '-1' RmagResRec["anisotropy_type"] = 'ATRM' RmagResRec["magic_method_codes"] = 'LP-AN-TRM:AE-H' RmagSpecRec["magic_method_codes"] = 'LP-AN-TRM:AE-H' RmagResRec["magic_software_packages"] = pmag.get_version() RmagSpecRec["magic_software_packages"] = pmag.get_version() RmagSpecRecs.append(RmagSpecRec) RmagResRecs.append(RmagResRec) specimen += 1 if data_model_num == 3: SpecRec = RmagResRec.copy() SpecRec.update(RmagSpecRec) SpecRecs.append(SpecRec) # finished iterating through specimens, # now we need to write out the data to files if data_model_num == 3: # translate records for rec in SpecRecs: rec3 = map_magic.convert_aniso('magic3', rec) SpecRecs3.append(rec3) # write output to 3.0 specimens file pmag.magic_write(spec_file, SpecRecs3, 'specimens') print("specimen data stored in {}".format(spec_file)) else: # write output to 2.5 rmag_ files pmag.magic_write(rmag_anis, RmagSpecRecs, 'rmag_anisotropy') print("specimen tensor elements stored in ", rmag_anis) pmag.magic_write(rmag_res, RmagResRecs, 'rmag_results') print("specimen statistics and eigenparameters stored in ", rmag_res)
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)
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
def main(): """ NAME zeq_magic.py DESCRIPTION reads in magic_measurements formatted file, makes plots of remanence decay during demagnetization experiments. Reads in prior interpretations saved in a pmag_specimens formatted file [and allows re-interpretations of best-fit lines and planes and saves (revised or new) interpretations in a pmag_specimens file. interpretations are saved in the coordinate system used. Also allows judicious editting of measurements to eliminate "bad" measurements. These are marked as such in the magic_measurements input file. they are NOT deleted, just ignored. ] Bracketed part not yet implemented SYNTAX zeq_magic.py [command line options] OPTIONS -h prints help message and quits -f MEASFILE: sets measurements format input file, default: measurements.txt -fsp SPECFILE: sets specimens format file with prior interpreations, default: specimens.txt -fsa SAMPFILE: sets samples format file sample=>site information, default: samples.txt -fsi SITEFILE: sets sites format file with site=>location informationprior interpreations, default: samples.txt -Fp PLTFILE: sets filename for saved plot, default is name_type.fmt (where type is zijd, eqarea or decay curve) -crd [s,g,t]: sets coordinate system, g=geographic, t=tilt adjusted, default: specimen coordinate system -spc SPEC plots single specimen SPEC, saves plot with specified format with optional -dir settings and quits -dir [L,P,F][beg][end]: sets calculation type for principal component analysis, default is none beg: starting step for PCA calculation end: ending step for PCA calculation [L,P,F]: calculation type for line, plane or fisher mean must be used with -spc option -fmt FMT: set format of saved plot [png,svg,jpg] -A: suppresses averaging of replicate measurements, default is to average -sav: saves all plots without review SCREEN OUTPUT: Specimen, N, a95, StepMin, StepMax, Dec, Inc, calculation type """ # initialize some variables doave, e, b = 1, 0, 0 # average replicates, initial end and beginning step intlist = ['magn_moment', 'magn_volume', 'magn_mass', 'magnitude'] plots, coord = 0, 's' noorient = 0 version_num = pmag.get_version() verbose = pmagplotlib.verbose calculation_type, fmt = "", "svg" user, spec_keys, locname = "", [], '' geo, tilt, ask = 0, 0, 0 PriorRecs = [] # empty list for prior interpretations backup = 0 specimen = "" # can skip everything and just plot one specimen with bounds e,b 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") 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") #meas_file = os.path.join(dir_path, meas_file) #spec_file = os.path.join(dir_path, spec_file) #samp_file = os.path.join(dir_path, samp_file) #site_file = os.path.join(dir_path, site_file) plot_file = pmag.get_named_arg_from_sys("-Fp", default_val="") crd = pmag.get_named_arg_from_sys("-crd", default_val="s") if crd == "s": coord = "-1" elif crd == "t": coord = "100" else: coord = "0" fmt = pmag.get_named_arg_from_sys("-fmt", "svg") specimen = pmag.get_named_arg_from_sys("-spc", default_val="") beg_pca, end_pca = "", "" if '-dir' in sys.argv: ind = sys.argv.index('-dir') direction_type = sys.argv[ind + 1] beg_pca = int(sys.argv[ind + 2]) end_pca = int(sys.argv[ind + 3]) if direction_type == 'L': calculation_type = 'DE-BFL' if direction_type == 'P': calculation_type = 'DE-BFP' if direction_type == 'F': calculation_type = 'DE-FM' if '-A' in sys.argv: doave = 0 if '-sav' in sys.argv: plots, verbose = 1, 0 # first_save = 1 fnames = { 'measurements': meas_file, 'specimens': spec_file, 'samples': samp_file, 'sites': site_file } contribution = nb.Contribution( dir_path, custom_filenames=fnames, read_tables=['measurements', 'specimens', 'samples', 'sites']) # # import specimens 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: # contribution.propagate_name_down('sample','measurements') spec_container = contribution.tables['specimens'] prior_spec_data = spec_container.get_records_for_code( 'LP-DIR', strict_match=False ) # look up all prior directional interpretations # # tie sample names to measurement data # else: spec_container, prior_spec_data = None, [] # # import samples for orientation info # if 'samples' in contribution.tables: # contribution.propagate_name_down('site','measurements') contribution.propagate_cols( col_names=['azimuth', 'dip', 'orientation_flag'], target_df_name='measurements', source_df_name='samples') # # define figure numbers for equal area, zijderveld, # and intensity vs. demagnetiztion step respectively # ZED = {} ZED['eqarea'], ZED['zijd'], ZED['demag'] = 1, 2, 3 pmagplotlib.plot_init(ZED['eqarea'], 6, 6) pmagplotlib.plot_init(ZED['zijd'], 6, 6) pmagplotlib.plot_init(ZED['demag'], 6, 6) # save_pca=0 angle, direction_type, setangle = "", "", 0 # create measurement dataframe # meas_container = contribution.tables['measurements'] meas_data = meas_container.df # meas_data = meas_data[meas_data['method_codes'].str.contains( 'LT-NO|LT-AF-Z|LT-T-Z|LT-M-Z') == True] # fish out steps for plotting meas_data = meas_data[meas_data['method_codes'].str.contains( 'AN|ARM|LP-TRM|LP-PI-ARM') == False] # strip out unwanted experiments intensity_types = [ col_name for col_name in meas_data.columns if col_name in intlist ] # plot first intensity method found - normalized to initial value anyway - # doesn't matter which used int_key = intensity_types[0] # get all the non-null intensity records of the same type meas_data = meas_data[meas_data[int_key].notnull()] if 'flag' not in meas_data.columns: meas_data['flag'] = 'g' # set the default flag to good # need to treat LP-NO specially for af data, treatment should be zero, # otherwise 273. meas_data['treatment'] = meas_data['treat_ac_field'].where( cond=meas_data['treat_ac_field'] != '0', other=meas_data['treat_temp']) meas_data['ZI'] = 1 # initialize these to one meas_data['instrument_codes'] = "" # initialize these to blank # for unusual case of microwave power.... if 'treat_mw_power' in meas_data.columns: meas_data.loc[ meas_data.treat_mw_power != 0, 'treatment'] = meas_data.treat_mw_power * meas_data.treat_mw_time # # get list of unique specimen names from measurement data # # this is a list of all the specimen names specimen_names = meas_data.specimen.unique() specimen_names = specimen_names.tolist() specimen_names.sort() # # set up new DataFrame for this sessions specimen interpretations # data_container = nb.MagicDataFrame(dtype='specimens', columns=specimen_cols) # this is for interpretations from this session current_spec_data = data_container.df locname = 'LookItUp' if specimen == "": k = 0 else: k = specimen_names.index(specimen) # let's look at the data now while k < len(specimen_names): # set the current specimen for plotting this_specimen = specimen_names[k] if verbose and this_specimen != "": print(this_specimen, k + 1, 'out of ', len(specimen_names)) if setangle == 0: angle = "" this_specimen_measurements = meas_data[ meas_data['specimen'].str.contains( this_specimen) == True] # fish out this specimen this_specimen_measurements = this_specimen_measurements[ this_specimen_measurements['flag'].str.contains( 'g') == True] # fish out this specimen if len(this_specimen_measurements) != 0: # if there are measurements # # set up datablock [[treatment,dec, inc, int, direction_type],[....]] # # # figure out the method codes # units, methods, title = "", "", this_specimen # this is a list of all the specimen method codes` meas_meths = this_specimen_measurements.method_codes.unique() tr = pd.to_numeric(this_specimen_measurements.treatment).tolist() if set(tr) == set([0]): k += 1 continue for m in meas_meths: if 'LT-AF-Z' in m: units = 'T' # units include tesla tr[0] = 0 if 'LT-T-Z' in m: units = units + ":K" # units include kelvin if 'LT-M-Z' in m: units = units + ':J' # units include joules tr[0] = 0 units = units.strip(':') # strip off extra colons if 'LP-' in m: methods = methods + ":" + m decs = pd.to_numeric(this_specimen_measurements.dir_dec).tolist() incs = pd.to_numeric(this_specimen_measurements.dir_inc).tolist() # # fix the coordinate system # if coord != '-1': # need to transform coordinates to geographic azimuths = pd.to_numeric(this_specimen_measurements.azimuth ).tolist() # get the azimuths # get the azimuths dips = pd.to_numeric(this_specimen_measurements.dip).tolist() dirs = [decs, incs, azimuths, dips] # this transposes the columns and rows of the list of lists dirs_geo = np.array(list(map(list, list(zip(*dirs))))) decs, incs = pmag.dogeo_V(dirs_geo) if coord == '100': # need to do tilt correction too bed_dip_dirs = pd.to_numeric( this_specimen_measurements.bed_dip_dir).tolist( ) # get the azimuths bed_dips = pd.to_numeric(this_specimen_measurements.bed_dip ).tolist() # get the azimuths dirs = [decs, incs, bed_dip_dirs, bed_dips] # this transposes the columns and rows of the list of lists dirs_tilt = np.array(list(map(list, list(zip(*dirs))))) decs, incs = pmag.dotilt_V(dirs_tilt) title = title + '_t' else: title = title + '_g' if angle == "": angle = decs[0] ints = pd.to_numeric(this_specimen_measurements[int_key]).tolist() ZI = this_specimen_measurements.ZI.tolist() flags = this_specimen_measurements.flag.tolist() codes = this_specimen_measurements.instrument_codes.tolist() datalist = [tr, decs, incs, ints, ZI, flags, codes] # this transposes the columns and rows of the list of lists datablock = list(map(list, list(zip(*datalist)))) pmagplotlib.plotZED(ZED, datablock, angle, title, units) if verbose: pmagplotlib.drawFIGS(ZED) # # collect info for current_specimen_interpretation dictionary # if beg_pca == "" and len(prior_spec_data) != 0: # # find prior interpretation # prior_specimen_interpretations = prior_spec_data[ prior_spec_data['specimen'].str.contains( this_specimen) == True] beg_pcas = pd.to_numeric(prior_specimen_interpretations. meas_step_min.values).tolist() end_pcas = pd.to_numeric(prior_specimen_interpretations. meas_step_max.values).tolist() spec_methods = prior_specimen_interpretations.method_codes.tolist( ) # step through all prior interpretations and plot them for ind in range(len(beg_pcas)): spec_meths = spec_methods[ind].split(':') for m in spec_meths: if 'DE-BFL' in m: calculation_type = 'DE-BFL' # best fit line if 'DE-BFP' in m: calculation_type = 'DE-BFP' # best fit plane if 'DE-FM' in m: calculation_type = 'DE-FM' # fisher mean if 'DE-BFL-A' in m: calculation_type = 'DE-BFL-A' # anchored best fit line start, end = tr.index(beg_pcas[ind]), tr.index( end_pcas[ind] ) # getting the starting and ending points # calculate direction/plane mpars = pmag.domean(datablock, start, end, calculation_type) if mpars["specimen_direction_type"] != "Error": # put it on the plot pmagplotlib.plotDir(ZED, mpars, datablock, angle) if verbose: pmagplotlib.drawFIGS(ZED) else: start, end = int(beg_pca), int(end_pca) # calculate direction/plane mpars = pmag.domean(datablock, start, end, calculation_type) if mpars["specimen_direction_type"] != "Error": # put it on the plot pmagplotlib.plotDir(ZED, mpars, datablock, angle) if verbose: pmagplotlib.drawFIGS(ZED) if plots == 1 or specimen != "": if plot_file == "": basename = title else: basename = plot_file files = {} for key in list(ZED.keys()): files[key] = basename + '_' + key + '.' + fmt pmagplotlib.saveP(ZED, files) if specimen != "": sys.exit() if verbose: recnum = 0 for plotrec in datablock: if units == 'T': print('%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % (plotrec[5], recnum, plotrec[0] * 1e3, " mT", plotrec[3], plotrec[1], plotrec[2], plotrec[6])) if units == "K": print('%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % (plotrec[5], recnum, plotrec[0] - 273, ' C', plotrec[3], plotrec[1], plotrec[2], plotrec[6])) if units == "J": print('%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % (plotrec[5], recnum, plotrec[0], ' J', plotrec[3], plotrec[1], plotrec[2], plotrec[6])) if 'K' in units and 'T' in units: if plotrec[0] >= 1.: print('%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % (plotrec[5], recnum, plotrec[0] - 273, ' C', plotrec[3], plotrec[1], plotrec[2], plotrec[6])) if plotrec[0] < 1.: print('%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % (plotrec[5], recnum, plotrec[0] * 1e3, " mT", plotrec[3], plotrec[1], plotrec[2], plotrec[6])) recnum += 1 # we have a current interpretation elif mpars["specimen_direction_type"] != "Error": # # create a new specimen record for the interpreation for this # specimen this_specimen_interpretation = { col: "" for col in specimen_cols } # this_specimen_interpretation["analysts"]=user this_specimen_interpretation['software_packages'] = version_num this_specimen_interpretation['specimen'] = this_specimen this_specimen_interpretation["method_codes"] = calculation_type this_specimen_interpretation["meas_step_unit"] = units this_specimen_interpretation["meas_step_min"] = tr[start] this_specimen_interpretation["meas_step_max"] = tr[end] this_specimen_interpretation["dir_dec"] = '%7.1f' % ( mpars['specimen_dec']) this_specimen_interpretation["dir_inc"] = '%7.1f' % ( mpars['specimen_inc']) this_specimen_interpretation["dir_dang"] = '%7.1f' % ( mpars['specimen_dang']) this_specimen_interpretation["dir_n_measurements"] = '%i' % ( mpars['specimen_n']) this_specimen_interpretation["dir_tilt_correction"] = coord methods = methods.replace(" ", "") if "T" in units: methods = methods + ":LP-DIR-AF" if "K" in units: methods = methods + ":LP-DIR-T" if "J" in units: methods = methods + ":LP-DIR-M" this_specimen_interpretation["method_codes"] = methods.strip( ':') this_specimen_interpretation[ "experiments"] = this_specimen_measurements.experiment.unique( )[0] # # print some stuff # if calculation_type != 'DE-FM': this_specimen_interpretation["dir_mad_free"] = '%7.1f' % ( mpars['specimen_mad']) this_specimen_interpretation["dir_alpha95"] = '' if verbose: if units == 'K': print( '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation[ "dir_n_measurements"]), float(this_specimen_interpretation[ "dir_mad_free"]), float( this_specimen_interpretation["dir_dang"]), float(this_specimen_interpretation[ "meas_step_min"]) - 273, float(this_specimen_interpretation[ "meas_step_max"]) - 273, float( this_specimen_interpretation["dir_dec"]), float( this_specimen_interpretation["dir_inc"]), calculation_type)) elif units == 'T': print( '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation[ "dir_n_measurements"]), float(this_specimen_interpretation[ "dir_mad_free"]), float( this_specimen_interpretation["dir_dang"]), float(this_specimen_interpretation[ "meas_step_min"]) * 1e3, float(this_specimen_interpretation[ "meas_step_max"]) * 1e3, float( this_specimen_interpretation["dir_dec"]), float( this_specimen_interpretation["dir_inc"]), calculation_type)) elif 'T' in units and 'K' in units: if float(this_specimen_interpretation[ 'meas_step_min']) < 1.0: min = float(this_specimen_interpretation[ 'meas_step_min']) * 1e3 else: min = float(this_specimen_interpretation[ 'meas_step_min']) - 273 if float(this_specimen_interpretation[ 'meas_step_max']) < 1.0: max = float(this_specimen_interpretation[ 'meas_step_max']) * 1e3 else: max = float(this_specimen_interpretation[ 'meas_step_max']) - 273 print( '%s %i %7.1f %i %i %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation[ "dir_n_measurements"]), float(this_specimen_interpretation[ "dir_mad_free"]), float( this_specimen_interpretation["dir_dang"]), min, max, float( this_specimen_interpretation["dir_dec"]), float( this_specimen_interpretation["dir_inc"]), calculation_type)) else: print( '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation[ "dir_n_measurements"]), float(this_specimen_interpretation[ "dir_mad_free"]), float( this_specimen_interpretation["dir_dang"]), float(this_specimen_interpretation[ "meas_step_min"]), float(this_specimen_interpretation[ "meas_step_max"]), float( this_specimen_interpretation["dir_dec"]), float( this_specimen_interpretation["dir_inc"]), calculation_type)) else: this_specimen_interpretation["dir_alpha95"] = '%7.1f' % ( mpars['specimen_alpha95']) this_specimen_interpretation["dir_mad_free"] = '' if verbose: if 'K' in units: print( '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation[ "dir_n_measurments"]), float(this_specimen_interpretation[ "dir_mad_free"]), float( this_specimen_interpretation["dir_dang"]), float(this_specimen_interpretation[ "meas_step_min"]) - 273, float(this_specimen_interpretation[ "meas_step_max"]) - 273, float( this_specimen_interpretation["dir_dec"]), float( this_specimen_interpretation["dir_inc"]), calculation_type)) elif 'T' in units: print( '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation[ "dir_n_measurements"]), float(this_specimen_interpretation[ "dir_alpha95"]), float( this_specimen_interpretation["dir_dang"]), float(this_specimen_interpretation[ "meas_step_min"]) * 1e3, float(this_specimen_interpretation[ "meas_step_max"]) * 1e3, float( this_specimen_interpretation["dir_dec"]), float( this_specimen_interpretation["dir_inc"]), calculation_type)) elif 'T' in units and 'K' in units: if float(this_specimen_interpretation[ 'meas_step_min']) < 1.0: min = float(this_specimen_interpretation[ 'meas_step_min']) * 1e3 else: min = float(this_specimen_interpretation[ 'meas_step_min']) - 273 if float(this_specimen_interpretation[ 'meas_step_max']) < 1.0: max = float(this_specimen_interpretation[ 'meas_step_max']) * 1e3 else: max = float(this_specimen_interpretation[ 'meas_step_max']) - 273 print('%s %i %7.1f %i %i %7.1f %7.1f %s \n' % ( this_specimen_interpretation["specimen"], int(this_specimen_interpretation[ "dir_n_measurements"]), float( this_specimen_interpretation["dir_alpha95"] ), min, max, float(this_specimen_interpretation["dir_dec"]), float(this_specimen_interpretation["dir_inc"]), calculation_type)) else: print( '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation[ "dir_n_measurements"]), float(this_specimen_interpretation[ "dir_alpha95"]), float(this_specimen_interpretation[ "meas_step_min"]), float(this_specimen_interpretation[ "meas_step_max"]), float( this_specimen_interpretation["dir_dec"]), float( this_specimen_interpretation["dir_inc"]), calculation_type)) if verbose: saveit = input("Save this interpretation? [y]/n \n") # START HERE # # if len(current_spec_data)==0: # no interpretations yet for this session # print "no current interpretation" # beg_pca,end_pca="","" # calculation_type="" # get the ones that meet the current coordinate system else: print("no data") if verbose: input('Ready for next specimen ') k += 1
def main(): """ NAME dayplot_magic.py DESCRIPTION makes 'day plots' (Day et al. 1977) and squareness/coercivity, plots 'linear mixing' curve from Dunlop and Carter-Stiglitz (2006). squareness coercivity of remanence (Neel, 1955) plots after Tauxe et al. (2002) SYNTAX dayplot_magic.py [command line options] OPTIONS -h prints help message and quits -f: specify input hysteresis file, default is specimens.txt -fmt [svg,png,jpg] format for output plots -sav saves plots and quits quietly """ args = sys.argv if "-h" in args: print main.__doc__ sys.exit() verbose = pmagplotlib.verbose dir_path = pmag.get_named_arg_from_sys('-WD', '.') fmt = pmag.get_named_arg_from_sys('-fmt', 'svg') if '-sav' in sys.argv: plots = 1 verbose = False else: plots = 0 infile = pmag.get_named_arg_from_sys("-f", "specimens.txt") fnames = {'specimens': infile} con = nb.Contribution(dir_path, read_tables=['specimens'], custom_filenames=fnames) spec_container = con.tables['specimens'] spec_df = spec_container.df # # initialize some variables # define figure numbers for Day,S-Bc,S-Bcr DSC = {} DSC['day'], DSC['S-Bc'], DSC['S-Bcr'], DSC['bcr1-bcr2'] = 1, 2, 3, 4 pmagplotlib.plot_init(DSC['day'], 5, 5) pmagplotlib.plot_init(DSC['S-Bc'], 5, 5) pmagplotlib.plot_init(DSC['S-Bcr'], 5, 5) pmagplotlib.plot_init(DSC['bcr1-bcr2'], 5, 5) S, BcrBc, Bcr2, Bc, hsids, Bcr = [], [], [], [], [], [] Bcr1, Bcr1Bc, S1 = [], [], [] locations = '' if 'location' in spec_df.columns: locations = spec_df['location'].unique() do_rem = bool('rem_bcr' in spec_df.columns) for ind, row in spec_df.iterrows(): if row['hyst_bcr'] and row['hyst_mr_moment']: S.append( float(row['hyst_mr_moment']) / float(row['hyst_ms_moment'])) Bcr.append(float(row['hyst_bcr'])) Bc.append(float(row['hyst_bc'])) BcrBc.append(Bcr[-1] / Bc[-1]) hsids.append(row['specimen']) if do_rem: if row['rem_bcr'] and float(row['rem_bcr']) > 0: try: Bcr1.append(float(row['rem_bcr'])) Bcr1Bc.append(Bcr1[-1] / Bc[-1]) S1.append(S[-1]) Bcr2.append(Bcr[-1]) except ValueError: if verbose: print 'hysteresis data for ', row['specimen'], print ' not found' # # now plot the day and S-Bc, S-Bcr plots # if len(Bcr1) > 0: pmagplotlib.plotDay(DSC['day'], Bcr1Bc, S1, 'ro') pmagplotlib.plotSBcr(DSC['S-Bcr'], Bcr1, S1, 'ro') pmagplotlib.plot_init(DSC['bcr1-bcr2'], 5, 5) pmagplotlib.plotBcr(DSC['bcr1-bcr2'], Bcr1, Bcr2) else: del DSC['bcr1-bcr2'] pmagplotlib.plotDay(DSC['day'], BcrBc, S, 'bs') pmagplotlib.plotSBcr(DSC['S-Bcr'], Bcr, S, 'bs') pmagplotlib.plotSBc(DSC['S-Bc'], Bc, S, 'bs') files = {} if len(locations) > 0: locations = locations[:-1] for key in DSC.keys(): files[ key] = 'LO:_' + locations + '_' + 'SI:__SA:__SP:__TY:_' + key + '_.' + fmt if verbose: pmagplotlib.drawFIGS(DSC) ans = raw_input(" S[a]ve to save plots, return to quit: ") if ans == "a": pmagplotlib.saveP(DSC, files) else: sys.exit() if plots: pmagplotlib.saveP(DSC, files)
def main(): """ NAME dayplot_magic.py DESCRIPTION makes 'day plots' (Day et al. 1977) and squareness/coercivity, plots 'linear mixing' curve from Dunlop and Carter-Stiglitz (2006). squareness coercivity of remanence (Neel, 1955) plots after Tauxe et al. (2002) SYNTAX dayplot_magic.py [command line options] OPTIONS -h prints help message and quits -f: specify input hysteresis file, default is specimens.txt -fmt [svg,png,jpg] format for output plots -sav saves plots and quits quietly """ args = sys.argv if "-h" in args: print(main.__doc__) sys.exit() verbose = pmagplotlib.verbose dir_path = pmag.get_named_arg_from_sys('-WD', '.') fmt = pmag.get_named_arg_from_sys('-fmt', 'svg') if '-sav' in sys.argv: plots = 1 verbose = False else: plots = 0 infile = pmag.get_named_arg_from_sys("-f", "specimens.txt") fnames = {'specimens': infile} con = nb.Contribution(dir_path, read_tables=['specimens'], custom_filenames=fnames) spec_container = con.tables['specimens'] spec_df = spec_container.df # # initialize some variables # define figure numbers for Day,S-Bc,S-Bcr DSC = {} DSC['day'], DSC['S-Bc'], DSC['S-Bcr'], DSC['bcr1-bcr2'] = 1, 2, 3, 4 pmagplotlib.plot_init(DSC['day'], 5, 5) pmagplotlib.plot_init(DSC['S-Bc'], 5, 5) pmagplotlib.plot_init(DSC['S-Bcr'], 5, 5) pmagplotlib.plot_init(DSC['bcr1-bcr2'], 5, 5) S, BcrBc, Bcr2, Bc, hsids, Bcr = [], [], [], [], [], [] Bcr1, Bcr1Bc, S1 = [], [], [] locations = '' if 'location' in spec_df.columns: locations = spec_df['location'].unique() do_rem = bool('rem_bcr' in spec_df.columns) for ind, row in spec_df.iterrows(): if row['hyst_bcr'] and row['hyst_mr_moment']: S.append(old_div(float(row['hyst_mr_moment']), float(row['hyst_ms_moment']))) Bcr.append(float(row['hyst_bcr'])) Bc.append(float(row['hyst_bc'])) BcrBc.append(old_div(Bcr[-1], Bc[-1])) hsids.append(row['specimen']) if do_rem: if row['rem_bcr'] and float(row['rem_bcr']) > 0: try: Bcr1.append(float(row['rem_bcr'])) Bcr1Bc.append(old_div(Bcr1[-1], Bc[-1])) S1.append(S[-1]) Bcr2.append(Bcr[-1]) except ValueError: if verbose: print('hysteresis data for ', row['specimen'], end=' ') print(' not found') # # now plot the day and S-Bc, S-Bcr plots # if len(Bcr1) > 0: pmagplotlib.plotDay(DSC['day'], Bcr1Bc, S1, 'ro') pmagplotlib.plotSBcr(DSC['S-Bcr'], Bcr1, S1, 'ro') pmagplotlib.plot_init(DSC['bcr1-bcr2'], 5, 5) pmagplotlib.plotBcr(DSC['bcr1-bcr2'], Bcr1, Bcr2) else: del DSC['bcr1-bcr2'] pmagplotlib.plotDay(DSC['day'], BcrBc, S, 'bs') pmagplotlib.plotSBcr(DSC['S-Bcr'], Bcr, S, 'bs') pmagplotlib.plotSBc(DSC['S-Bc'], Bc, S, 'bs') files = {} if len(locations) > 0: locations = locations[:-1] for key in list(DSC.keys()): if pmagplotlib.isServer: # use server plot naming convention files[key] = 'LO:_' + locations + '_' + 'SI:__SA:__SP:__TY:_' + key + '_.' + fmt else: # use more readable plot naming convention files[key] = '{}_{}.{}'.format(locations, key, fmt) if verbose: pmagplotlib.drawFIGS(DSC) ans = input(" S[a]ve to save plots, return to quit: ") if ans == "a": pmagplotlib.saveP(DSC, files) else: sys.exit() if plots: pmagplotlib.saveP(DSC, files)
def main(): """ NAME plotXY.py DESCRIPTION Makes simple X,Y plots INPUT FORMAT X,Y data in columns SYNTAX plotxy.py [command line options] OPTIONS -h prints this help message -f FILE to set file name on command line -c col1 col2 specify columns to plot -xsig col3 specify xsigma if desired -ysig col4 specify xsigma if desired -b xmin xmax ymin ymax, sets bounds -sym SYM SIZE specify symbol to plot: default is red dots, 10 pt -S don't plot the symbols -xlab XLAB -ylab YLAB -l connect symbols with lines -fmt [svg,png,pdf,eps] specify output format, default is svg -sav saves plot and quits -poly X plot a degree X polynomial through the data -skip n Number of lines to skip before reading in data """ fmt, plot = 'svg', 0 col1, col2 = 0, 1 sym, size = 'ro', 50 xlab, ylab = '', '' lines = 0 if '-h' in sys.argv: print main.__doc__ sys.exit() if '-f' in sys.argv: ind = sys.argv.index('-f') file = sys.argv[ind + 1] if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt = sys.argv[ind + 1] if '-sav' in sys.argv: plot = 1 if '-c' in sys.argv: ind = sys.argv.index('-c') col1 = int(sys.argv[ind + 1]) - 1 col2 = int(sys.argv[ind + 2]) - 1 if '-xsig' in sys.argv: ind = sys.argv.index('-xsig') col3 = int(sys.argv[ind + 1]) - 1 if '-ysig' in sys.argv: ind = sys.argv.index('-ysig') col4 = int(sys.argv[ind + 1]) - 1 if '-xlab' in sys.argv: ind = sys.argv.index('-xlab') xlab = sys.argv[ind + 1] if '-ylab' in sys.argv: ind = sys.argv.index('-ylab') ylab = sys.argv[ind + 1] if '-b' in sys.argv: ind = sys.argv.index('-b') xmin = float(sys.argv[ind + 1]) xmax = float(sys.argv[ind + 2]) ymin = float(sys.argv[ind + 3]) ymax = float(sys.argv[ind + 4]) if '-poly' in sys.argv: ind = sys.argv.index('-poly') degr = sys.argv[ind + 1] if '-sym' in sys.argv: ind = sys.argv.index('-sym') sym = sys.argv[ind + 1] size = int(sys.argv[ind + 2]) if '-l' in sys.argv: lines = 1 if '-S' in sys.argv: sym = '' skip = int(pmag.get_named_arg_from_sys('-skip', default_val=0)) X, Y = [], [] Xerrs, Yerrs = [], [] f = open(file, 'rU') for num in range(skip): f.readline() data = f.readlines() for line in data: line.replace('\n', '') line.replace('\t', ' ') rec = line.split() X.append(float(rec[col1])) Y.append(float(rec[col2])) if '-xsig' in sys.argv: Xerrs.append(float(rec[col3])) if '-ysig' in sys.argv: Yerrs.append(float(rec[col4])) if '-poly' in sys.argv: pylab.plot(xs, ys) coeffs = numpy.polyfit(X, Y, degr) correl = numpy.corrcoef(X, Y)**2 polynomial = numpy.poly1d(coeffs) xs = numpy.linspace(numpy.min(X), numpy.max(X), 10) ys = polynomial(xs) pylab.plot(xs, ys) print polynomial if degr == '1': print 'R-square value =', '%5.4f' % (correl[0, 1]) if sym != '': pylab.scatter(X, Y, marker=sym[1], c=sym[0], s=size) else: pylab.plot(X, Y) if '-xsig' in sys.argv and '-ysig' in sys.argv: pylab.errorbar(X, Y, xerr=Xerrs, yerr=Yerrs, fmt=None) if '-xsig' in sys.argv and '-ysig' not in sys.argv: pylab.errorbar(X, Y, xerr=Xerrs, fmt=None) if '-xsig' not in sys.argv and '-ysig' in sys.argv: pylab.errorbar(X, Y, yerr=Yerrs, fmt=None) if xlab != '': pylab.xlabel(xlab) if ylab != '': pylab.ylabel(ylab) if lines == 1: pylab.plot(X, Y, 'k-') if '-b' in sys.argv: pylab.axis([xmin, xmax, ymin, ymax]) if plot == 0: pylab.show() else: pylab.savefig('plotXY.' + fmt) print 'Figure saved as ', 'plotXY.' + fmt sys.exit()
def main(): """ NAME aniso_magic.py DESCRIPTION plots anisotropy data with either bootstrap or hext ellipses SYNTAX aniso_magic.py [-h] [command line options] OPTIONS -h plots help message and quits -usr USER: set the user name -f AFILE, specify specimens.txt formatted file for input -fsa SAMPFILE, specify samples.txt file (required to plot by site) -fsi SITEFILE, specify site file (required to include location information) -x Hext [1963] and bootstrap -B DON'T do bootstrap, do Hext -par Tauxe [1998] parametric bootstrap -v plot bootstrap eigenvectors instead of ellipses -sit plot by site instead of entire file -crd [s,g,t] coordinate system, default is specimen (g=geographic, t=tilt corrected) -P don't make any plots - just fill in the specimens, samples, sites tables -sav don't make the tables - just save all the plots -fmt [svg, jpg, eps] format for output images, pdf default -gtc DEC INC dec,inc of pole to great circle [down(up) in green (cyan) -d Vi DEC INC; Vi (1,2,3) to compare to direction DEC INC -nb N; specifies the number of bootstraps - default is 1000 DEFAULTS AFILE: specimens.txt plot bootstrap ellipses of Constable & Tauxe [1987] NOTES minor axis: circles major axis: triangles principal axis: squares directions are plotted on the lower hemisphere for bootstrapped eigenvector components: Xs: blue, Ys: red, Zs: black """ args = sys.argv if "-h" in args: print main.__doc__ sys.exit() #version_num = pmag.get_version() verbose = pmagplotlib.verbose dir_path = pmag.get_named_arg_from_sys("-WD", ".") num_bootstraps = pmag.get_named_arg_from_sys("-nb", 1000) #user = pmag.get_named_arg_from_sys("-usr", "") ipar = pmag.get_flag_arg_from_sys("-par", true=1, false=0) ihext = pmag.get_flag_arg_from_sys("-x", true=1, false=0) ivec = pmag.get_flag_arg_from_sys("-v", true=1, false=0) iplot = pmag.get_flag_arg_from_sys("-P", true=0, false=1) isite = pmag.get_flag_arg_from_sys("-sit", true=1, false=0) iboot, vec = 1, 0 infile = pmag.get_named_arg_from_sys('-f', 'specimens.txt') samp_file = pmag.get_named_arg_from_sys('-fsa', 'samples.txt') site_file = pmag.get_named_arg_from_sys('-fsi', 'sites.txt') #outfile = pmag.get_named_arg_from_sys("-F", "rmag_results.txt") fmt = pmag.get_named_arg_from_sys("-fmt", "pdf") hpars, bpars = [], [] CS, crd = -1, 's' ResRecs = [] comp, Dir, PDir = 0, [], [] if '-B' in args: iboot, ihext = 0, 1 if '-crd' in sys.argv: ind = sys.argv.index('-crd') crd = sys.argv[ind+1] if crd == 'g': CS = 0 if crd == 't': CS = 100 if '-sav' in args: plots = 1 verbose = 0 else: plots = 0 if '-gtc' in args: ind = args.index('-gtc') d, i = float(args[ind+1]), float(args[ind+2]) PDir.append(d) PDir.append(i) if '-d' in args: comp = 1 ind = args.index('-d') vec = int(args[ind+1])-1 Dir = [float(args[ind+2]), float(args[ind+3])] # # set up plots # ANIS = {} initcdf, inittcdf = 0, 0 ANIS['data'], ANIS['conf'] = 1, 2 if iboot == 1: ANIS['tcdf'] = 3 if iplot == 1: inittcdf = 1 pmagplotlib.plot_init(ANIS['tcdf'], 5, 5) if comp == 1 and iplot == 1: initcdf = 1 ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6 pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5) pmagplotlib.plot_init(ANIS['vycdf'], 5, 5) pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5) if iplot == 1: pmagplotlib.plot_init(ANIS['conf'], 5, 5) pmagplotlib.plot_init(ANIS['data'], 5, 5) # read in the data fnames = {'specimens': infile, 'samples': samp_file, 'sites': site_file} con = nb.Contribution(dir_path, read_tables=['specimens', 'samples', 'sites'], custom_filenames=fnames) spec_container = con.tables['specimens'] spec_df = con.propagate_name_down('location', 'specimens') # get only anisotropy records spec_df = spec_container.get_records_for_code('AE-', strict_match=False) if 'aniso_tilt_correction' not in spec_df.columns: spec_df['aniso_tilt_correction'] = None orlist = spec_df['aniso_tilt_correction'].dropna().unique() if CS not in orlist: if len(orlist) > 0: CS = orlist[0] else: CS = -1 if CS == -1: crd = 's' if CS == 0: crd = 'g' if CS == 100: crd = 't' if verbose: print "desired coordinate system not available, using available: ", crd if isite == 1: sitelist = spec_df['site'].unique() sitelist.sort() plt = len(sitelist) else: plt = 1 k = 0 while k < plt: site = "" loc_name = "" sdata, Ss = [], [] # list of S format data if isite == 0: sdata = spec_df if 'location' in sdata.columns: loc_name = ':'.join(sdata['location'].unique()) else: site = sitelist[k] sdata = spec_df[spec_df['site'] == site] if 'location' in sdata.columns: loc_name = sdata['location'][0] csrecs = sdata[sdata['aniso_tilt_correction'] == CS] #anitypes = csrecs['aniso_type'].unique() for name in ['citations', 'location', 'site', 'sample']: if name not in csrecs: csrecs[name] = "" Locs = csrecs['location'].unique() #Sites = csrecs['site'].unique() #Samples = csrecs['sample'].unique() #Specimens = csrecs['specimen'].unique() #Cits = csrecs['citations'].unique() for ind, rec in csrecs.iterrows(): s = [float(i.strip()) for i in rec['aniso_s'].split(':')] if s[0] <= 1.0: Ss.append(s) # protect against crap # tau,Vdirs=pmag.doseigs(s) # do we need fpars somewhere??? # fpars = pmag.dohext(int(rec["aniso_s_n_measurements"]) -6, float(rec["aniso_s_sigma"]), s) # fill in ResRecs (ignoring this for now, grab it from aniso_magic if needed) if len(Ss) > 1: title = "LO:_" + loc_name + '_SI:_' + site + '_SA:__SP:__CO:_' + crd bpars, hpars = pmagplotlib.plotANIS(ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, num_bootstraps) if len(PDir) > 0: pmagplotlib.plotC(ANIS['data'], PDir, 90., 'g') pmagplotlib.plotC(ANIS['conf'], PDir, 90., 'g') if verbose and plots == 0: pmagplotlib.drawFIGS(ANIS) if plots == 1: save(ANIS,fmt,title) if hpars != [] and ihext == 1: HextRec = {} #for key in ResRec.keys():HextRec[key]=ResRec[key] # copy over stuff HextRec["anisotropy_v1_dec"] = '%7.1f'%(hpars["v1_dec"]) HextRec["anisotropy_v2_dec"] = '%7.1f'%(hpars["v2_dec"]) HextRec["anisotropy_v3_dec"] = '%7.1f'%(hpars["v3_dec"]) HextRec["anisotropy_v1_inc"] = '%7.1f'%(hpars["v1_inc"]) HextRec["anisotropy_v2_inc"] = '%7.1f'%(hpars["v2_inc"]) HextRec["anisotropy_v3_inc"] = '%7.1f'%(hpars["v3_inc"]) HextRec["anisotropy_t1"] = '%10.8f'%(hpars["t1"]) HextRec["anisotropy_t2"] = '%10.8f'%(hpars["t2"]) HextRec["anisotropy_t3"] = '%10.8f'%(hpars["t3"]) HextRec["anisotropy_hext_F"] = '%7.1f '%(hpars["F"]) HextRec["anisotropy_hext_F12"] = '%7.1f '%(hpars["F12"]) HextRec["anisotropy_hext_F23"] = '%7.1f '%(hpars["F23"]) HextRec["anisotropy_v1_eta_semi_angle"] = '%7.1f '%(hpars["e12"]) HextRec["anisotropy_v1_eta_dec"] = '%7.1f '%(hpars["v2_dec"]) HextRec["anisotropy_v1_eta_inc"] = '%7.1f '%(hpars["v2_inc"]) HextRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f '%(hpars["e13"]) HextRec["anisotropy_v1_zeta_dec"] = '%7.1f '%(hpars["v3_dec"]) HextRec["anisotropy_v1_zeta_inc"] = '%7.1f '%(hpars["v3_inc"]) HextRec["anisotropy_v2_eta_semi_angle"] = '%7.1f '%(hpars["e12"]) HextRec["anisotropy_v2_eta_dec"] = '%7.1f '%(hpars["v1_dec"]) HextRec["anisotropy_v2_eta_inc"] = '%7.1f '%(hpars["v1_inc"]) HextRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f '%(hpars["e23"]) HextRec["anisotropy_v2_zeta_dec"] = '%7.1f '%(hpars["v3_dec"]) HextRec["anisotropy_v2_zeta_inc"] = '%7.1f '%(hpars["v3_inc"]) HextRec["anisotropy_v3_eta_semi_angle"] = '%7.1f '%(hpars["e12"]) HextRec["anisotropy_v3_eta_dec"] = '%7.1f '%(hpars["v1_dec"]) HextRec["anisotropy_v3_eta_inc"] = '%7.1f '%(hpars["v1_inc"]) HextRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f '%(hpars["e23"]) HextRec["anisotropy_v3_zeta_dec"] = '%7.1f '%(hpars["v2_dec"]) HextRec["anisotropy_v3_zeta_inc"] = '%7.1f '%(hpars["v2_inc"]) HextRec["magic_method_codes"] = 'LP-AN:AE-H' if verbose: print "Hext Statistics: " print " tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I" print HextRec["anisotropy_t1"], HextRec["anisotropy_v1_dec"], print HextRec["anisotropy_v1_inc"], HextRec["anisotropy_v1_eta_semi_angle"], print HextRec["anisotropy_v1_eta_dec"], HextRec["anisotropy_v1_eta_inc"], print HextRec["anisotropy_v1_zeta_semi_angle"], HextRec["anisotropy_v1_zeta_dec"], print HextRec["anisotropy_v1_zeta_inc"] # print HextRec["anisotropy_t2"],HextRec["anisotropy_v2_dec"], print HextRec["anisotropy_v2_inc"], HextRec["anisotropy_v2_eta_semi_angle"], print HextRec["anisotropy_v2_eta_dec"], HextRec["anisotropy_v2_eta_inc"], print HextRec["anisotropy_v2_zeta_semi_angle"], HextRec["anisotropy_v2_zeta_dec"], print HextRec["anisotropy_v2_zeta_inc"] # print HextRec["anisotropy_t3"], HextRec["anisotropy_v3_dec"], print HextRec["anisotropy_v3_inc"], HextRec["anisotropy_v3_eta_semi_angle"], print HextRec["anisotropy_v3_eta_dec"], HextRec["anisotropy_v3_eta_inc"], print HextRec["anisotropy_v3_zeta_semi_angle"], HextRec["anisotropy_v3_zeta_dec"], print HextRec["anisotropy_v3_zeta_inc"] #HextRec['magic_software_packages']=version_num #ResRecs.append(HextRec) if bpars != []: BootRec = {} #for key in ResRec.keys():BootRec[key]=ResRec[key] # copy over stuff BootRec["anisotropy_v1_dec"] = '%7.1f'%(bpars["v1_dec"]) BootRec["anisotropy_v2_dec"] = '%7.1f'%(bpars["v2_dec"]) BootRec["anisotropy_v3_dec"] = '%7.1f'%(bpars["v3_dec"]) BootRec["anisotropy_v1_inc"] = '%7.1f'%(bpars["v1_inc"]) BootRec["anisotropy_v2_inc"] = '%7.1f'%(bpars["v2_inc"]) BootRec["anisotropy_v3_inc"] = '%7.1f'%(bpars["v3_inc"]) BootRec["anisotropy_t1"] = '%10.8f'%(bpars["t1"]) BootRec["anisotropy_t2"] = '%10.8f'%(bpars["t2"]) BootRec["anisotropy_t3"] = '%10.8f'%(bpars["t3"]) BootRec["anisotropy_v1_eta_inc"] = '%7.1f '%(bpars["v1_eta_inc"]) BootRec["anisotropy_v1_eta_dec"] = '%7.1f '%(bpars["v1_eta_dec"]) BootRec["anisotropy_v1_eta_semi_angle"] = '%7.1f '%(bpars["v1_eta"]) BootRec["anisotropy_v1_zeta_inc"] = '%7.1f '%(bpars["v1_zeta_inc"]) BootRec["anisotropy_v1_zeta_dec"] = '%7.1f '%(bpars["v1_zeta_dec"]) BootRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f '%(bpars["v1_zeta"]) BootRec["anisotropy_v2_eta_inc"] = '%7.1f '%(bpars["v2_eta_inc"]) BootRec["anisotropy_v2_eta_dec"] = '%7.1f '%(bpars["v2_eta_dec"]) BootRec["anisotropy_v2_eta_semi_angle"] = '%7.1f '%(bpars["v2_eta"]) BootRec["anisotropy_v2_zeta_inc"] = '%7.1f '%(bpars["v2_zeta_inc"]) BootRec["anisotropy_v2_zeta_dec"] = '%7.1f '%(bpars["v2_zeta_dec"]) BootRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f '%(bpars["v2_zeta"]) BootRec["anisotropy_v3_eta_inc"] = '%7.1f '%(bpars["v3_eta_inc"]) BootRec["anisotropy_v3_eta_dec"] = '%7.1f '%(bpars["v3_eta_dec"]) BootRec["anisotropy_v3_eta_semi_angle"] = '%7.1f '%(bpars["v3_eta"]) BootRec["anisotropy_v3_zeta_inc"] = '%7.1f '%(bpars["v3_zeta_inc"]) BootRec["anisotropy_v3_zeta_dec"] = '%7.1f '%(bpars["v3_zeta_dec"]) BootRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f '%(bpars["v3_zeta"]) BootRec["anisotropy_hext_F"] = '' BootRec["anisotropy_hext_F12"] = '' BootRec["anisotropy_hext_F23"] = '' BootRec["magic_method_codes"] = 'LP-AN:AE-H:AE-BS' # regular bootstrap if ipar == 1: BootRec["magic_method_codes"] = 'LP-AN:AE-H:AE-BS-P' # parametric bootstrap if verbose: print "Boostrap Statistics: " print " tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I" print BootRec["anisotropy_t1"], BootRec["anisotropy_v1_dec"], print BootRec["anisotropy_v1_inc"], BootRec["anisotropy_v1_eta_semi_angle"], print BootRec["anisotropy_v1_eta_dec"], BootRec["anisotropy_v1_eta_inc"], print BootRec["anisotropy_v1_zeta_semi_angle"], BootRec["anisotropy_v1_zeta_dec"], print BootRec["anisotropy_v1_zeta_inc"] # print BootRec["anisotropy_t2"], BootRec["anisotropy_v2_dec"], BootRec["anisotropy_v2_inc"], print BootRec["anisotropy_v2_eta_semi_angle"], BootRec["anisotropy_v2_eta_dec"], print BootRec["anisotropy_v2_eta_inc"], BootRec["anisotropy_v2_zeta_semi_angle"], print BootRec["anisotropy_v2_zeta_dec"], BootRec["anisotropy_v2_zeta_inc"] # print BootRec["anisotropy_t3"], BootRec["anisotropy_v3_dec"], BootRec["anisotropy_v3_inc"], print BootRec["anisotropy_v3_eta_semi_angle"], BootRec["anisotropy_v3_eta_dec"], print BootRec["anisotropy_v3_eta_inc"], BootRec["anisotropy_v3_zeta_semi_angle"], print BootRec["anisotropy_v3_zeta_dec"], BootRec["anisotropy_v3_zeta_inc"] #BootRec['magic_software_packages'] = version_num ResRecs.append(BootRec) k += 1 goon = 1 while goon == 1 and iplot == 1 and verbose: if iboot == 1: print "compare with [d]irection " print " plot [g]reat circle, change [c]oord. system, change [e]llipse calculation, s[a]ve plots, [q]uit " if isite == 1: print " [p]revious, [s]ite, [q]uit, <return> for next " ans = raw_input("") if ans == "q": sys.exit() if ans == "e": iboot, ipar, ihext, ivec = 1, 0, 0, 0 e = raw_input("Do Hext Statistics 1/[0]: ") if e == "1": ihext = 1 e = raw_input("Suppress bootstrap 1/[0]: ") if e == "1": iboot = 0 if iboot == 1: e = raw_input("Parametric bootstrap 1/[0]: ") if e == "1": ipar = 1 e = raw_input("Plot bootstrap eigenvectors: 1/[0]: ") if e == "1": ivec=1 if iplot == 1: if inittcdf == 0: ANIS['tcdf'] = 3 pmagplotlib.plot_init(ANIS['tcdf'], 5, 5) inittcdf = 1 bpars, hpars = pmagplotlib.plotANIS(ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, num_bootstraps) if verbose and plots == 0: pmagplotlib.drawFIGS(ANIS) if ans == "c": print "Current Coordinate system is: " if CS == -1: print " Specimen" if CS == 0: print " Geographic" if CS == 100: print " Tilt corrected" key = raw_input(" Enter desired coordinate system: [s]pecimen, [g]eographic, [t]ilt corrected ") if key == 's': CS = -1 if key == 'g': CS = 0 if key == 't': CS = 100 if CS not in orlist: if len(orlist) > 0: CS = orlist[0] else: CS = -1 if CS == -1: crd = 's' if CS == 0: crd = 'g' if CS == 100: crd = 't' print "desired coordinate system not available, using available: ", crd k -= 1 goon = 0 if ans == "": if isite == 1: goon = 0 else: print "Good bye " sys.exit() if ans == 'd': if initcdf == 0: initcdf = 1 ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6 pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5) pmagplotlib.plot_init(ANIS['vycdf'], 5, 5) pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5) Dir, comp = [], 1 print """ Input: Vi D I to compare eigenvector Vi with direction D/I where Vi=1: principal Vi=2: major Vi=3: minor D= declination of comparison direction I= inclination of comparison direction""" con = 1 while con == 1: try: vdi = raw_input("Vi D I: ").split() vec = int(vdi[0])-1 Dir = [float(vdi[1]), float(vdi[2])] con = 0 except IndexError: print " Incorrect entry, try again " bpars, hpars = pmagplotlib.plotANIS(ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, num_bootstraps) Dir, comp = [], 0 if ans == 'g': con, cnt = 1, 0 while con == 1: try: print " Input: input pole to great circle ( D I) to plot a great circle: " di = raw_input(" D I: ").split() PDir.append(float(di[0])) PDir.append(float(di[1])) con=0 except: cnt += 1 if cnt < 10: print " enter the dec and inc of the pole on one line " else: print "ummm - you are doing something wrong - i give up" sys.exit() pmagplotlib.plotC(ANIS['data'], PDir, 90., 'g') pmagplotlib.plotC(ANIS['conf'], PDir, 90., 'g') if verbose and plots == 0: pmagplotlib.drawFIGS(ANIS) if ans == "p": k -= 2 goon = 0 if ans == "q": k = plt goon = 0 if ans == "s": keepon = 1 site = raw_input(" print site or part of site desired: ") while keepon == 1: try: k = sitelist.index(site) keepon = 0 except: tmplist = [] for qq in range(len(sitelist)): if site in sitelist[qq]: tmplist.append(sitelist[qq]) print site, " not found, but this was: " print tmplist site = raw_input('Select one or try again\n ') k = sitelist.index(site) goon, ans = 0, "" if ans == "a": locs = pmag.makelist(Locs) site_name = "_" if isite: site_name = site title = "LO:_" + locs + '_SI:_' + site_name + '_SA:__SP:__CO:_' + crd save(ANIS, fmt, title) goon = 0 else: if verbose: print 'skipping plot - not enough data points' k += 1 # put rmag_results stuff here #if len(ResRecs)>0: # ResOut,keylist=pmag.fillkeys(ResRecs) # pmag.magic_write(outfile,ResOut,'rmag_results') if verbose: print " Good bye "
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
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
def main(): """ NAME aniso_magic.py DESCRIPTION plots anisotropy data with either bootstrap or hext ellipses SYNTAX aniso_magic.py [-h] [command line options] OPTIONS -h plots help message and quits -usr USER: set the user name -f AFILE, specify specimens.txt formatted file for input -fsa SAMPFILE, specify samples.txt file (required to plot by site) -fsi SITEFILE, specify site file (required to include location information) -x Hext [1963] and bootstrap -B DON'T do bootstrap, do Hext -par Tauxe [1998] parametric bootstrap -v plot bootstrap eigenvectors instead of ellipses -sit plot by site instead of entire file -crd [s,g,t] coordinate system, default is specimen (g=geographic, t=tilt corrected) -P don't make any plots - just fill in the specimens, samples, sites tables -sav don't make the tables - just save all the plots -fmt [svg, jpg, eps] format for output images, pdf default -gtc DEC INC dec,inc of pole to great circle [down(up) in green (cyan) -d Vi DEC INC; Vi (1,2,3) to compare to direction DEC INC -nb N; specifies the number of bootstraps - default is 1000 DEFAULTS AFILE: specimens.txt plot bootstrap ellipses of Constable & Tauxe [1987] NOTES minor axis: circles major axis: triangles principal axis: squares directions are plotted on the lower hemisphere for bootstrapped eigenvector components: Xs: blue, Ys: red, Zs: black """ args = sys.argv if "-h" in args: print(main.__doc__) sys.exit() #version_num = pmag.get_version() verbose = pmagplotlib.verbose dir_path = pmag.get_named_arg_from_sys("-WD", ".") num_bootstraps = pmag.get_named_arg_from_sys("-nb", 1000) #user = pmag.get_named_arg_from_sys("-usr", "") ipar = pmag.get_flag_arg_from_sys("-par", true=1, false=0) ihext = pmag.get_flag_arg_from_sys("-x", true=1, false=0) ivec = pmag.get_flag_arg_from_sys("-v", true=1, false=0) iplot = pmag.get_flag_arg_from_sys("-P", true=0, false=1) isite = pmag.get_flag_arg_from_sys("-sit", true=1, false=0) iboot, vec = 1, 0 infile = pmag.get_named_arg_from_sys('-f', 'specimens.txt') samp_file = pmag.get_named_arg_from_sys('-fsa', 'samples.txt') site_file = pmag.get_named_arg_from_sys('-fsi', 'sites.txt') #outfile = pmag.get_named_arg_from_sys("-F", "rmag_results.txt") fmt = pmag.get_named_arg_from_sys("-fmt", "pdf") hpars, bpars = [], [] CS, crd = -1, 's' ResRecs = [] comp, Dir, PDir = 0, [], [] if '-B' in args: iboot, ihext = 0, 1 if '-crd' in sys.argv: ind = sys.argv.index('-crd') crd = sys.argv[ind + 1] if crd == 'g': CS = 0 if crd == 't': CS = 100 if '-sav' in args: plots = 1 verbose = 0 else: plots = 0 if '-gtc' in args: ind = args.index('-gtc') d, i = float(args[ind + 1]), float(args[ind + 2]) PDir.append(d) PDir.append(i) if '-d' in args: comp = 1 ind = args.index('-d') vec = int(args[ind + 1]) - 1 Dir = [float(args[ind + 2]), float(args[ind + 3])] # # set up plots # ANIS = {} initcdf, inittcdf = 0, 0 ANIS['data'], ANIS['conf'] = 1, 2 if iboot == 1: ANIS['tcdf'] = 3 if iplot == 1: inittcdf = 1 pmagplotlib.plot_init(ANIS['tcdf'], 5, 5) if comp == 1 and iplot == 1: initcdf = 1 ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6 pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5) pmagplotlib.plot_init(ANIS['vycdf'], 5, 5) pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5) if iplot == 1: pmagplotlib.plot_init(ANIS['conf'], 5, 5) pmagplotlib.plot_init(ANIS['data'], 5, 5) # read in the data fnames = {'specimens': infile, 'samples': samp_file, 'sites': site_file} con = nb.Contribution(dir_path, read_tables=['specimens', 'samples', 'sites'], custom_filenames=fnames) con.propagate_location_to_specimens() spec_container = con.tables['specimens'] # get only anisotropy records spec_df = spec_container.get_records_for_code('AE-', strict_match=False) if 'aniso_tilt_correction' not in spec_df.columns: spec_df['aniso_tilt_correction'] = None orlist = spec_df['aniso_tilt_correction'].dropna().unique() if CS not in orlist: if len(orlist) > 0: CS = orlist[0] else: CS = -1 if CS == -1: crd = 's' if CS == 0: crd = 'g' if CS == 100: crd = 't' if verbose: print("desired coordinate system not available, using available: ", crd) if isite == 1: sitelist = spec_df['site'].unique() sitelist.sort() plt = len(sitelist) else: plt = 1 k = 0 while k < plt: site = "" loc_name = "" sdata, Ss = [], [] # list of S format data if isite == 0: sdata = spec_df if 'location' in sdata.columns: loc_name = ':'.join(sdata['location'].unique()) else: site = sitelist[k] sdata = spec_df[spec_df['site'] == site] if 'location' in sdata.columns: loc_name = sdata['location'][0] csrecs = sdata[sdata['aniso_tilt_correction'] == CS] #anitypes = csrecs['aniso_type'].unique() for name in ['citations', 'location', 'site', 'sample']: if name not in csrecs: csrecs[name] = "" Locs = csrecs['location'].unique() #Sites = csrecs['site'].unique() #Samples = csrecs['sample'].unique() #Specimens = csrecs['specimen'].unique() #Cits = csrecs['citations'].unique() for ind, rec in csrecs.iterrows(): s = [float(i.strip()) for i in rec['aniso_s'].split(':')] if s[0] <= 1.0: Ss.append(s) # protect against crap # tau,Vdirs=pmag.doseigs(s) # do we need fpars somewhere??? # fpars = pmag.dohext(int(rec["aniso_s_n_measurements"]) -6, float(rec["aniso_s_sigma"]), s) # fill in ResRecs (ignoring this for now, grab it from aniso_magic if needed) if len(Ss) > 1: if pmagplotlib.isServer: # use server plot naming convention title = "LO:_" + loc_name + '_SI:_' + site + '_SA:__SP:__CO:_' + crd else: # use more readable plot naming convention title = "{}_{}_{}".format(loc_name, site, crd) bpars, hpars = pmagplotlib.plotANIS(ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, num_bootstraps) if len(PDir) > 0: pmagplotlib.plotC(ANIS['data'], PDir, 90., 'g') pmagplotlib.plotC(ANIS['conf'], PDir, 90., 'g') if verbose and plots == 0: pmagplotlib.drawFIGS(ANIS) if plots == 1: save(ANIS, fmt, title) if hpars != [] and ihext == 1: HextRec = {} #for key in ResRec.keys():HextRec[key]=ResRec[key] # copy over stuff HextRec["anisotropy_v1_dec"] = '%7.1f' % (hpars["v1_dec"]) HextRec["anisotropy_v2_dec"] = '%7.1f' % (hpars["v2_dec"]) HextRec["anisotropy_v3_dec"] = '%7.1f' % (hpars["v3_dec"]) HextRec["anisotropy_v1_inc"] = '%7.1f' % (hpars["v1_inc"]) HextRec["anisotropy_v2_inc"] = '%7.1f' % (hpars["v2_inc"]) HextRec["anisotropy_v3_inc"] = '%7.1f' % (hpars["v3_inc"]) HextRec["anisotropy_t1"] = '%10.8f' % (hpars["t1"]) HextRec["anisotropy_t2"] = '%10.8f' % (hpars["t2"]) HextRec["anisotropy_t3"] = '%10.8f' % (hpars["t3"]) HextRec["anisotropy_hext_F"] = '%7.1f ' % (hpars["F"]) HextRec["anisotropy_hext_F12"] = '%7.1f ' % (hpars["F12"]) HextRec["anisotropy_hext_F23"] = '%7.1f ' % (hpars["F23"]) HextRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( hpars["e12"]) HextRec["anisotropy_v1_eta_dec"] = '%7.1f ' % (hpars["v2_dec"]) HextRec["anisotropy_v1_eta_inc"] = '%7.1f ' % (hpars["v2_inc"]) HextRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( hpars["e13"]) HextRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( hpars["v3_dec"]) HextRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( hpars["v3_inc"]) HextRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars["e12"]) HextRec["anisotropy_v2_eta_dec"] = '%7.1f ' % (hpars["v1_dec"]) HextRec["anisotropy_v2_eta_inc"] = '%7.1f ' % (hpars["v1_inc"]) HextRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars["e23"]) HextRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars["v3_dec"]) HextRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars["v3_inc"]) HextRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars["e12"]) HextRec["anisotropy_v3_eta_dec"] = '%7.1f ' % (hpars["v1_dec"]) HextRec["anisotropy_v3_eta_inc"] = '%7.1f ' % (hpars["v1_inc"]) HextRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars["e23"]) HextRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars["v2_dec"]) HextRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars["v2_inc"]) HextRec["magic_method_codes"] = 'LP-AN:AE-H' if verbose: print("Hext Statistics: ") print( " tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I" ) print(HextRec["anisotropy_t1"], HextRec["anisotropy_v1_dec"], end=' ') print(HextRec["anisotropy_v1_inc"], HextRec["anisotropy_v1_eta_semi_angle"], end=' ') print(HextRec["anisotropy_v1_eta_dec"], HextRec["anisotropy_v1_eta_inc"], end=' ') print(HextRec["anisotropy_v1_zeta_semi_angle"], HextRec["anisotropy_v1_zeta_dec"], end=' ') print(HextRec["anisotropy_v1_zeta_inc"]) # print(HextRec["anisotropy_t2"], HextRec["anisotropy_v2_dec"], end=' ') print(HextRec["anisotropy_v2_inc"], HextRec["anisotropy_v2_eta_semi_angle"], end=' ') print(HextRec["anisotropy_v2_eta_dec"], HextRec["anisotropy_v2_eta_inc"], end=' ') print(HextRec["anisotropy_v2_zeta_semi_angle"], HextRec["anisotropy_v2_zeta_dec"], end=' ') print(HextRec["anisotropy_v2_zeta_inc"]) # print(HextRec["anisotropy_t3"], HextRec["anisotropy_v3_dec"], end=' ') print(HextRec["anisotropy_v3_inc"], HextRec["anisotropy_v3_eta_semi_angle"], end=' ') print(HextRec["anisotropy_v3_eta_dec"], HextRec["anisotropy_v3_eta_inc"], end=' ') print(HextRec["anisotropy_v3_zeta_semi_angle"], HextRec["anisotropy_v3_zeta_dec"], end=' ') print(HextRec["anisotropy_v3_zeta_inc"]) #HextRec['magic_software_packages']=version_num #ResRecs.append(HextRec) if bpars != []: BootRec = {} #for key in ResRec.keys():BootRec[key]=ResRec[key] # copy over stuff BootRec["anisotropy_v1_dec"] = '%7.1f' % (bpars["v1_dec"]) BootRec["anisotropy_v2_dec"] = '%7.1f' % (bpars["v2_dec"]) BootRec["anisotropy_v3_dec"] = '%7.1f' % (bpars["v3_dec"]) BootRec["anisotropy_v1_inc"] = '%7.1f' % (bpars["v1_inc"]) BootRec["anisotropy_v2_inc"] = '%7.1f' % (bpars["v2_inc"]) BootRec["anisotropy_v3_inc"] = '%7.1f' % (bpars["v3_inc"]) BootRec["anisotropy_t1"] = '%10.8f' % (bpars["t1"]) BootRec["anisotropy_t2"] = '%10.8f' % (bpars["t2"]) BootRec["anisotropy_t3"] = '%10.8f' % (bpars["t3"]) BootRec["anisotropy_v1_eta_inc"] = '%7.1f ' % ( bpars["v1_eta_inc"]) BootRec["anisotropy_v1_eta_dec"] = '%7.1f ' % ( bpars["v1_eta_dec"]) BootRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( bpars["v1_eta"]) BootRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( bpars["v1_zeta_inc"]) BootRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( bpars["v1_zeta_dec"]) BootRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( bpars["v1_zeta"]) BootRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( bpars["v2_eta_inc"]) BootRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( bpars["v2_eta_dec"]) BootRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( bpars["v2_eta"]) BootRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( bpars["v2_zeta_inc"]) BootRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( bpars["v2_zeta_dec"]) BootRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( bpars["v2_zeta"]) BootRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( bpars["v3_eta_inc"]) BootRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( bpars["v3_eta_dec"]) BootRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( bpars["v3_eta"]) BootRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( bpars["v3_zeta_inc"]) BootRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( bpars["v3_zeta_dec"]) BootRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( bpars["v3_zeta"]) BootRec["anisotropy_hext_F"] = '' BootRec["anisotropy_hext_F12"] = '' BootRec["anisotropy_hext_F23"] = '' BootRec[ "magic_method_codes"] = 'LP-AN:AE-H:AE-BS' # regular bootstrap if ipar == 1: BootRec[ "magic_method_codes"] = 'LP-AN:AE-H:AE-BS-P' # parametric bootstrap if verbose: print("Boostrap Statistics: ") print( " tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I" ) print(BootRec["anisotropy_t1"], BootRec["anisotropy_v1_dec"], end=' ') print(BootRec["anisotropy_v1_inc"], BootRec["anisotropy_v1_eta_semi_angle"], end=' ') print(BootRec["anisotropy_v1_eta_dec"], BootRec["anisotropy_v1_eta_inc"], end=' ') print(BootRec["anisotropy_v1_zeta_semi_angle"], BootRec["anisotropy_v1_zeta_dec"], end=' ') print(BootRec["anisotropy_v1_zeta_inc"]) # print(BootRec["anisotropy_t2"], BootRec["anisotropy_v2_dec"], BootRec["anisotropy_v2_inc"], end=' ') print(BootRec["anisotropy_v2_eta_semi_angle"], BootRec["anisotropy_v2_eta_dec"], end=' ') print(BootRec["anisotropy_v2_eta_inc"], BootRec["anisotropy_v2_zeta_semi_angle"], end=' ') print(BootRec["anisotropy_v2_zeta_dec"], BootRec["anisotropy_v2_zeta_inc"]) # print(BootRec["anisotropy_t3"], BootRec["anisotropy_v3_dec"], BootRec["anisotropy_v3_inc"], end=' ') print(BootRec["anisotropy_v3_eta_semi_angle"], BootRec["anisotropy_v3_eta_dec"], end=' ') print(BootRec["anisotropy_v3_eta_inc"], BootRec["anisotropy_v3_zeta_semi_angle"], end=' ') print(BootRec["anisotropy_v3_zeta_dec"], BootRec["anisotropy_v3_zeta_inc"]) #BootRec['magic_software_packages'] = version_num ResRecs.append(BootRec) k += 1 goon = 1 while goon == 1 and iplot == 1 and verbose: if iboot == 1: print("compare with [d]irection ") print( " plot [g]reat circle, change [c]oord. system, change [e]llipse calculation, s[a]ve plots, [q]uit " ) if isite == 1: print(" [p]revious, [s]ite, [q]uit, <return> for next ") ans = input("") if ans == "q": sys.exit() if ans == "e": iboot, ipar, ihext, ivec = 1, 0, 0, 0 e = input("Do Hext Statistics 1/[0]: ") if e == "1": ihext = 1 e = input("Suppress bootstrap 1/[0]: ") if e == "1": iboot = 0 if iboot == 1: e = input("Parametric bootstrap 1/[0]: ") if e == "1": ipar = 1 e = input("Plot bootstrap eigenvectors: 1/[0]: ") if e == "1": ivec = 1 if iplot == 1: if inittcdf == 0: ANIS['tcdf'] = 3 pmagplotlib.plot_init(ANIS['tcdf'], 5, 5) inittcdf = 1 bpars, hpars = pmagplotlib.plotANIS( ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, num_bootstraps) if verbose and plots == 0: pmagplotlib.drawFIGS(ANIS) if ans == "c": print("Current Coordinate system is: ") if CS == -1: print(" Specimen") if CS == 0: print(" Geographic") if CS == 100: print(" Tilt corrected") key = input( " Enter desired coordinate system: [s]pecimen, [g]eographic, [t]ilt corrected " ) if key == 's': CS = -1 if key == 'g': CS = 0 if key == 't': CS = 100 if CS not in orlist: if len(orlist) > 0: CS = orlist[0] else: CS = -1 if CS == -1: crd = 's' if CS == 0: crd = 'g' if CS == 100: crd = 't' print( "desired coordinate system not available, using available: ", crd) k -= 1 goon = 0 if ans == "": if isite == 1: goon = 0 else: print("Good bye ") sys.exit() if ans == 'd': if initcdf == 0: initcdf = 1 ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6 pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5) pmagplotlib.plot_init(ANIS['vycdf'], 5, 5) pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5) Dir, comp = [], 1 print(""" Input: Vi D I to compare eigenvector Vi with direction D/I where Vi=1: principal Vi=2: major Vi=3: minor D= declination of comparison direction I= inclination of comparison direction""") con = 1 while con == 1: try: vdi = input("Vi D I: ").split() vec = int(vdi[0]) - 1 Dir = [float(vdi[1]), float(vdi[2])] con = 0 except IndexError: print(" Incorrect entry, try again ") bpars, hpars = pmagplotlib.plotANIS( ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, num_bootstraps) Dir, comp = [], 0 if ans == 'g': con, cnt = 1, 0 while con == 1: try: print( " Input: input pole to great circle ( D I) to plot a great circle: " ) di = input(" D I: ").split() PDir.append(float(di[0])) PDir.append(float(di[1])) con = 0 except: cnt += 1 if cnt < 10: print( " enter the dec and inc of the pole on one line " ) else: print( "ummm - you are doing something wrong - i give up" ) sys.exit() pmagplotlib.plotC(ANIS['data'], PDir, 90., 'g') pmagplotlib.plotC(ANIS['conf'], PDir, 90., 'g') if verbose and plots == 0: pmagplotlib.drawFIGS(ANIS) if ans == "p": k -= 2 goon = 0 if ans == "q": k = plt goon = 0 if ans == "s": keepon = 1 site = input(" print site or part of site desired: ") while keepon == 1: try: k = sitelist.index(site) keepon = 0 except: tmplist = [] for qq in range(len(sitelist)): if site in sitelist[qq]: tmplist.append(sitelist[qq]) print(site, " not found, but this was: ") print(tmplist) site = input('Select one or try again\n ') k = sitelist.index(site) goon, ans = 0, "" if ans == "a": locs = pmag.makelist(Locs) site_name = "_" if isite: site_name = site if pmagplotlib.isServer: # use server plot naming convention title = "LO:_" + locs + '_SI:_' + site_name + '_SA:__SP:__CO:_' + crd else: # use more readable plot naming convention title = "{}_{}_{}".format(locs, site_name, crd) save(ANIS, fmt, title) goon = 0 else: if verbose: print('skipping plot - not enough data points') k += 1 # put rmag_results stuff here #if len(ResRecs)>0: # ResOut,keylist=pmag.fillkeys(ResRecs) # pmag.magic_write(outfile,ResOut,'rmag_results') if verbose: print(" Good bye ")
def main(): """ NAME eqarea_magic.py DESCRIPTION makes equal area projections from declination/inclination data SYNTAX eqarea_magic.py [command line options] INPUT takes magic formatted sites, samples, specimens, or measurements OPTIONS -h prints help message and quits -f FILE: specify input magic format file from magic, default='sites.txt' supported types=[measurements, specimens, samples, sites] -fsp FILE: specify specimen file name, (required if you want to plot measurements by sample) default='specimens.txt' -fsa FILE: specify sample file name, (required if you want to plot specimens by site) default='samples.txt' -fsi FILE: specify site file name, default='sites.txt' -obj OBJ: specify level of plot [all, sit, sam, spc], default is all -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted default is geographic, unspecified assumed geographic -fmt [svg,png,jpg] format for output plots -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors -c plot as colour contour -sav save plot and quit quietly NOTE all: entire file; sit: site; sam: sample; spc: specimen """ # initialize some default variables FIG = {} # plot dictionary FIG["eqarea"] = 1 # eqarea is figure 1 plotE = 0 plt = 0 # default to not plotting verbose = pmagplotlib.verbose # extract arguments from sys.argv if "-h" in sys.argv: print main.__doc__ sys.exit() dir_path = pmag.get_named_arg_from_sys("-WD", default_val=os.getcwd()) pmagplotlib.plot_init(FIG["eqarea"], 5, 5) in_file = pmag.get_named_arg_from_sys("-f", default_val="sites.txt") full_in_file = os.path.join(dir_path, in_file) plot_by = pmag.get_named_arg_from_sys("-obj", default_val="all").lower() 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") if plot_by == "all": plot_key = "all" elif plot_by == "sit": plot_key = "site" elif plot_by == "sam": plot_key = "sample" elif plot_by == "spc": plot_key = "specimen" else: plot_key = "all" if "-c" in sys.argv: contour = 1 else: contour = 0 if "-sav" in sys.argv: plt = 1 verbose = 0 if "-ell" in sys.argv: plotE = 1 ind = sys.argv.index("-ell") ell_type = sys.argv[ind + 1] ell_type = pmag.get_named_arg_from_sys("-ell", "F") dist = ell_type.upper() # if dist type is unrecognized, use Fisher if dist not in ["F", "K", "B", "BE", "BV"]: dist = "F" if dist == "BV": FIG["bdirs"] = 2 pmagplotlib.plot_init(FIG["bdirs"], 5, 5) crd = pmag.get_named_arg_from_sys("-crd", default_val="g") if crd == "s": coord = "-1" elif crd == "t": coord = "100" else: coord = "0" fmt = pmag.get_named_arg_from_sys("-fmt", "svg") dec_key = "dir_dec" inc_key = "dir_inc" tilt_key = "dir_tilt_correction" # Dir_type_keys=['','site_direction_type','sample_direction_type','specimen_direction_type'] # fnames = {"specimens": spec_file, "samples": samp_file, "sites": site_file} contribution = nb.Contribution(dir_path, custom_filenames=fnames, single_file=in_file) # the object that contains the DataFrame + useful helper methods: table_name = contribution.tables.keys()[0] data_container = contribution.tables[table_name] # the actual DataFrame: data = data_container.df # uses sample infile to add temporary site_name # column to the specimen table data_container = contribution.tables[table_name] data = data_container.df if (plot_key != "all") and (plot_key not in data.columns): data = contribution.propagate_name_down(plot_key, table_name) # add tilt key into DataFrame columns if it isn't there already if tilt_key not in data.columns: data.loc[:, tilt_key] = None if verbose: print len(data), " records read from ", in_file # find desired dec,inc data: dir_type_key = "" # # get plotlist if not plotting all records # plotlist = [] if plot_key != "all": # return all where plot_key is not blank if plot_key not in data.columns: print 'Can\'t plot by "{}". That header is not in infile: {}'.format(plot_key, in_file) return plots = data[data[plot_key].notnull()] plotlist = plots[plot_key].unique() # grab unique values else: plotlist.append("All") for plot in plotlist: if verbose: print plot if plot == "All": # plot everything at once plot_data = data else: # pull out only partial data plot_data = data[data[plot_key] == plot] DIblock = [] GCblock = [] # SLblock, SPblock = [], [] title = plot mode = 1 k = 0 if dec_key not in plot_data.columns: print "-W- No dec/inc data" continue # get all records where dec & inc values exist plot_data = plot_data[plot_data[dec_key].notnull() & plot_data[inc_key].notnull()] if plot_data.empty: continue # this sorting out is done in get_di_bock # if coord == '0': # geographic, use records with no tilt key (or tilt_key 0) # cond1 = plot_data[tilt_key].fillna('') == coord # cond2 = plot_data[tilt_key].isnull() # plot_data = plot_data[cond1 | cond2] # else: # not geographic coordinates, use only records with correct tilt_key # plot_data = plot_data[plot_data[tilt_key] == coord] # get metadata for naming the plot file locations = data_container.get_name("location", df_slice=plot_data) site = data_container.get_name("site", df_slice=plot_data) sample = data_container.get_name("sample", df_slice=plot_data) specimen = data_container.get_name("specimen", df_slice=plot_data) # make sure method_codes is in plot_data if "method_codes" not in plot_data.columns: plot_data["method_codes"] = "" # get data blocks DIblock = data_container.get_di_block(df_slice=plot_data, tilt_corr=coord, excl=["DE-BFP"]) # SLblock = [[ind, row['method_codes']] for ind, row in plot_data.iterrows()] # get great circles great_circle_data = data_container.get_records_for_code("DE-BFP", incl=True, use_slice=True, sli=plot_data) if len(great_circle_data) > 0: gc_cond = great_circle_data[tilt_key] == coord GCblock = [[float(row[dec_key]), float(row[inc_key])] for ind, row in great_circle_data[gc_cond].iterrows()] # SPblock = [[ind, row['method_codes']] for ind, row in great_circle_data[gc_cond].iterrows()] if len(DIblock) > 0: if contour == 0: pmagplotlib.plotEQ(FIG["eqarea"], DIblock, title) else: pmagplotlib.plotEQcont(FIG["eqarea"], DIblock) else: pmagplotlib.plotNET(FIG["eqarea"]) if len(GCblock) > 0: for rec in GCblock: pmagplotlib.plotC(FIG["eqarea"], rec, 90.0, "g") if len(DIblock) == 0 and len(GCblock) == 0: if verbose: print "no records for plotting" continue # sys.exit() if plotE == 1: ppars = pmag.doprinc(DIblock) # get principal directions nDIs, rDIs, npars, rpars = [], [], [], [] for rec in DIblock: angle = pmag.angle([rec[0], rec[1]], [ppars["dec"], ppars["inc"]]) if angle > 90.0: rDIs.append(rec) else: nDIs.append(rec) if dist == "B": # do on whole dataset etitle = "Bingham confidence ellipse" bpars = pmag.dobingham(DIblock) for key in bpars.keys(): if key != "n" and verbose: print " ", key, "%7.1f" % (bpars[key]) if key == "n" and verbose: print " ", key, " %i" % (bpars[key]) npars.append(bpars["dec"]) npars.append(bpars["inc"]) npars.append(bpars["Zeta"]) npars.append(bpars["Zdec"]) npars.append(bpars["Zinc"]) npars.append(bpars["Eta"]) npars.append(bpars["Edec"]) npars.append(bpars["Einc"]) if dist == "F": etitle = "Fisher confidence cone" if len(nDIs) > 2: fpars = pmag.fisher_mean(nDIs) for key in fpars.keys(): if key != "n" and verbose: print " ", key, "%7.1f" % (fpars[key]) if key == "n" and verbose: print " ", key, " %i" % (fpars[key]) mode += 1 npars.append(fpars["dec"]) npars.append(fpars["inc"]) npars.append(fpars["alpha95"]) # Beta npars.append(fpars["dec"]) isign = abs(fpars["inc"]) / fpars["inc"] npars.append(fpars["inc"] - isign * 90.0) # Beta inc npars.append(fpars["alpha95"]) # gamma npars.append(fpars["dec"] + 90.0) # Beta dec npars.append(0.0) # Beta inc if len(rDIs) > 2: fpars = pmag.fisher_mean(rDIs) if verbose: print "mode ", mode for key in fpars.keys(): if key != "n" and verbose: print " ", key, "%7.1f" % (fpars[key]) if key == "n" and verbose: print " ", key, " %i" % (fpars[key]) mode += 1 rpars.append(fpars["dec"]) rpars.append(fpars["inc"]) rpars.append(fpars["alpha95"]) # Beta rpars.append(fpars["dec"]) isign = abs(fpars["inc"]) / fpars["inc"] rpars.append(fpars["inc"] - isign * 90.0) # Beta inc rpars.append(fpars["alpha95"]) # gamma rpars.append(fpars["dec"] + 90.0) # Beta dec rpars.append(0.0) # Beta inc if dist == "K": etitle = "Kent confidence ellipse" if len(nDIs) > 3: kpars = pmag.dokent(nDIs, len(nDIs)) if verbose: print "mode ", mode for key in kpars.keys(): if key != "n" and verbose: print " ", key, "%7.1f" % (kpars[key]) if key == "n" and verbose: print " ", key, " %i" % (kpars[key]) mode += 1 npars.append(kpars["dec"]) npars.append(kpars["inc"]) npars.append(kpars["Zeta"]) npars.append(kpars["Zdec"]) npars.append(kpars["Zinc"]) npars.append(kpars["Eta"]) npars.append(kpars["Edec"]) npars.append(kpars["Einc"]) if len(rDIs) > 3: kpars = pmag.dokent(rDIs, len(rDIs)) if verbose: print "mode ", mode for key in kpars.keys(): if key != "n" and verbose: print " ", key, "%7.1f" % (kpars[key]) if key == "n" and verbose: print " ", key, " %i" % (kpars[key]) mode += 1 rpars.append(kpars["dec"]) rpars.append(kpars["inc"]) rpars.append(kpars["Zeta"]) rpars.append(kpars["Zdec"]) rpars.append(kpars["Zinc"]) rpars.append(kpars["Eta"]) rpars.append(kpars["Edec"]) rpars.append(kpars["Einc"]) else: # assume bootstrap if dist == "BE": if len(nDIs) > 5: BnDIs = pmag.di_boot(nDIs) Bkpars = pmag.dokent(BnDIs, 1.0) if verbose: print "mode ", mode for key in Bkpars.keys(): if key != "n" and verbose: print " ", key, "%7.1f" % (Bkpars[key]) if key == "n" and verbose: print " ", key, " %i" % (Bkpars[key]) mode += 1 npars.append(Bkpars["dec"]) npars.append(Bkpars["inc"]) npars.append(Bkpars["Zeta"]) npars.append(Bkpars["Zdec"]) npars.append(Bkpars["Zinc"]) npars.append(Bkpars["Eta"]) npars.append(Bkpars["Edec"]) npars.append(Bkpars["Einc"]) if len(rDIs) > 5: BrDIs = pmag.di_boot(rDIs) Bkpars = pmag.dokent(BrDIs, 1.0) if verbose: print "mode ", mode for key in Bkpars.keys(): if key != "n" and verbose: print " ", key, "%7.1f" % (Bkpars[key]) if key == "n" and verbose: print " ", key, " %i" % (Bkpars[key]) mode += 1 rpars.append(Bkpars["dec"]) rpars.append(Bkpars["inc"]) rpars.append(Bkpars["Zeta"]) rpars.append(Bkpars["Zdec"]) rpars.append(Bkpars["Zinc"]) rpars.append(Bkpars["Eta"]) rpars.append(Bkpars["Edec"]) rpars.append(Bkpars["Einc"]) etitle = "Bootstrapped confidence ellipse" elif dist == "BV": sym = {"lower": ["o", "c"], "upper": ["o", "g"], "size": 3, "edgecolor": "face"} if len(nDIs) > 5: BnDIs = pmag.di_boot(nDIs) pmagplotlib.plotEQsym(FIG["bdirs"], BnDIs, "Bootstrapped Eigenvectors", sym) if len(rDIs) > 5: BrDIs = pmag.di_boot(rDIs) if len(nDIs) > 5: # plot on existing plots pmagplotlib.plotDIsym(FIG["bdirs"], BrDIs, sym) else: pmagplotlib.plotEQ(FIG["bdirs"], BrDIs, "Bootstrapped Eigenvectors") if dist == "B": if len(nDIs) > 3 or len(rDIs) > 3: pmagplotlib.plotCONF(FIG["eqarea"], etitle, [], npars, 0) elif len(nDIs) > 3 and dist != "BV": pmagplotlib.plotCONF(FIG["eqarea"], etitle, [], npars, 0) if len(rDIs) > 3: pmagplotlib.plotCONF(FIG["eqarea"], etitle, [], rpars, 0) elif len(rDIs) > 3 and dist != "BV": pmagplotlib.plotCONF(FIG["eqarea"], etitle, [], rpars, 0) for key in FIG.keys(): files = {} filename = pmag.get_named_arg_from_sys("-fname") if filename: filename += "." + fmt else: filename = ( "LO:_" + locations + "_SI:_" + site + "_SA:_" + sample + "_SP:_" + specimen + "_CO:_" + crd + "_TY:_" + key + "_." + fmt ) files[key] = filename if pmagplotlib.isServer: black = "#000000" purple = "#800080" titles = {} titles["eq"] = "Equal Area Plot" FIG = pmagplotlib.addBorders(FIG, titles, black, purple) pmagplotlib.saveP(FIG, files) if plt: pmagplotlib.saveP(FIG, files) continue if verbose: 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) continue
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_from_sys("-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_from_sys("-f", 'measurements.txt') else: in_file = pmag.get_named_arg_from_sys("-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_from_sys("-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 = nb.Contribution(dir_path) meas_df = con.propagate_location_to_measurements() 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)) con.write_table_to_file('measurements') # read in data 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 = [] 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.plotMT(FIG['exp'], INTblock, title, 0, units, norm) files = {} for key in list(FIG.keys()): files[key] = title + '_' + LP + '.' + fmt if plot == 0: pmagplotlib.drawFIGS(FIG) ans = 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'])
def main(): """ NAME atrm_magic.py DESCRIPTION Converts ATRM data to best-fit tensor (6 elements plus sigma) Original program ARMcrunch written to accomodate ARM anisotropy data collected from 6 axial directions (+X,+Y,+Z,-X,-Y,-Z) using the off-axis remanence terms to construct the tensor. A better way to do the anisotropy of ARMs is to use 9,12 or 15 measurements in the Hext rotational scheme. SYNTAX atrm_magic.py [-h][command line options] OPTIONS -h prints help message and quits -usr USER: identify user, default is "" -f FILE: specify input file, default is atrm_measurements.txt -Fa FILE: specify anisotropy output file, default is trm_anisotropy.txt (MagIC 2.5 only) -Fr FILE: specify results output file, default is atrm_results.txt (MagIC 2.5 only) -Fsi FILE: specify output file, default is specimens.txt (MagIC 3 only) -DM DATA_MODEL: specify MagIC 2 or MagIC 3, default is 3 INPUT Input for the present program is a TRM acquisition data with an optional baseline. The order of the measurements is: Decs=[0,90,0,180,270,0,0,90,0] Incs=[0,0,90,0,0,-90,0,0,90] The last two measurements are optional """ # initialize some parameters args = sys.argv user = "" meas_file = "atrm_measurements.txt" rmag_anis = "trm_anisotropy.txt" rmag_res = "atrm_results.txt" dir_path = '.' # # get name of file from command line # if '-WD' in args: ind = args.index('-WD') dir_path = args[ind + 1] if "-h" in args: print(main.__doc__) sys.exit() if "-usr" in args: ind = args.index("-usr") user = sys.argv[ind + 1] if "-f" in args: ind = args.index("-f") meas_file = sys.argv[ind + 1] if "-Fa" in args: ind = args.index("-Fa") rmag_anis = args[ind + 1] if "-Fr" in args: ind = args.index("-Fr") rmag_res = args[ind + 1] data_model_num = int(pmag.get_named_arg_from_sys("-DM", 3)) spec_file = pmag.get_named_arg_from_sys("-Fsi", "specimens.txt") spec_file = os.path.join(dir_path, spec_file) meas_file = dir_path + '/' + meas_file rmag_anis = dir_path + '/' + rmag_anis rmag_res = dir_path + '/' + rmag_res # read in data if data_model_num == 3: meas_data = [] meas_data3, file_type = pmag.magic_read(meas_file) if file_type != 'measurements': print(file_type, "This is not a valid measurements file ") sys.exit() # convert meas_data to 2.5 for rec in meas_data3: meas_map = map_magic.meas_magic3_2_magic2_map meas_data.append(map_magic.mapping(rec, meas_map)) else: meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print(file_type, "This is not a valid magic_measurements file ") sys.exit() meas_data = pmag.get_dictitem(meas_data, 'magic_method_codes', 'LP-AN-TRM', 'has') # # # get sorted list of unique specimen names ssort = [] for rec in meas_data: spec = rec["er_specimen_name"] if spec not in ssort: ssort.append(spec) sids = sorted(ssort) # # # work on each specimen # specimen, npos = 0, 6 RmagSpecRecs, RmagResRecs = [], [] SpecRecs, SpecRecs3 = [], [] while specimen < len(sids): nmeas = 0 s = sids[specimen] RmagSpecRec = {} RmagResRec = {} BX, X = [], [] method_codes = [] Spec0 = "" # # find the data from the meas_data file for this sample # and get dec, inc, int and convert to x,y,z # # fish out data for this specimen name data = pmag.get_dictitem(meas_data, 'er_specimen_name', s, 'T') if len(data) > 5: RmagSpecRec["rmag_anisotropy_name"] = data[0]["er_specimen_name"] RmagSpecRec["er_location_name"] = data[0].get( "er_location_name", "") RmagSpecRec["er_specimen_name"] = data[0]["er_specimen_name"] RmagSpecRec["er_sample_name"] = data[0].get("er_sample_name", "") RmagSpecRec["er_site_name"] = data[0].get("er_site_name", "") RmagSpecRec["magic_experiment_names"] = RmagSpecRec[ "rmag_anisotropy_name"] + ":ATRM" RmagSpecRec["er_citation_names"] = "This study" RmagResRec[ "rmag_result_name"] = data[0]["er_specimen_name"] + ":ATRM" RmagResRec["er_location_names"] = data[0].get( "er_location_names", "") RmagResRec["er_specimen_names"] = data[0]["er_specimen_name"] RmagResRec["er_sample_names"] = data[0].get("er_sample_name", "") RmagResRec["er_site_names"] = data[0].get("er_site_name", "") RmagResRec["magic_experiment_names"] = RmagSpecRec[ "rmag_anisotropy_name"] + ":ATRM" RmagResRec["er_citation_names"] = "This study" RmagSpecRec["anisotropy_type"] = "ATRM" if "magic_instrument_codes" in list(data[0].keys()): RmagSpecRec["magic_instrument_codes"] = data[0][ "magic_instrument_codes"] else: RmagSpecRec["magic_instrument_codes"] = "" RmagSpecRec[ "anisotropy_description"] = "Hext statistics adapted to ATRM" for rec in data: meths = rec['magic_method_codes'].strip().split(':') Dir = [] Dir.append(float(rec["measurement_dec"])) Dir.append(float(rec["measurement_inc"])) Dir.append(float(rec["measurement_magn_moment"])) if "LT-T-Z" in meths: BX.append(pmag.dir2cart(Dir)) # append baseline steps elif "LT-T-I" in meths: X.append(pmag.dir2cart(Dir)) nmeas += 1 # if len(BX) == 1: for i in range(len(X) - 1): BX.append(BX[0]) # assume first 0 field step as baseline elif len(BX) == 0: # assume baseline is zero for i in range(len(X)): BX.append([0., 0., 0.]) # assume baseline of 0 elif len(BX) != len( X ): # if BX isn't just one measurement or one in between every infield step, just assume it is zero print('something odd about the baselines - just assuming zero') for i in range(len(X)): BX.append([0., 0., 0.]) # assume baseline of 0 if nmeas < 6: # must have at least 6 measurements right now - print('skipping specimen ', s, ' too few measurements') specimen += 1 else: # B matrix made from design matrix for positions B, H, tmpH = pmag.designATRM(npos) # # subtract optional baseline and put in a work array # work = numpy.zeros((nmeas, 3), 'f') for i in range(nmeas): for j in range(3): # subtract baseline, if available work[i][j] = X[i][j] - BX[i][j] # # calculate tensor elements # first put ARM components in w vector # w = numpy.zeros((npos * 3), 'f') index = 0 for i in range(npos): for j in range(3): w[index] = work[i][j] index += 1 s = numpy.zeros((6), 'f') # initialize the s matrix for i in range(6): for j in range(len(w)): s[i] += B[i][j] * w[j] trace = s[0] + s[1] + s[2] # normalize by the trace for i in range(6): s[i] = old_div(s[i], trace) a = pmag.s2a(s) #------------------------------------------------------------ # Calculating dels is different than in the Kappabridge # routine. Use trace normalized tensor (a) and the applied # unit field directions (tmpH) to generate model X,Y,Z # components. Then compare these with the measured values. #------------------------------------------------------------ S = 0. comp = numpy.zeros((npos * 3), 'f') for i in range(npos): for j in range(3): index = i * 3 + j compare = a[j][0] * tmpH[i][0] + a[j][1] * \ tmpH[i][1] + a[j][2] * tmpH[i][2] comp[index] = compare for i in range(npos * 3): d = old_div(w[i], trace) - comp[i] # del values S += d * d nf = float(npos * 3. - 6.) # number of degrees of freedom if S > 0: sigma = numpy.sqrt(old_div(S, nf)) else: sigma = 0 hpars = pmag.dohext(nf, sigma, s) # # prepare for output # RmagSpecRec["anisotropy_s1"] = '%8.6f' % (s[0]) RmagSpecRec["anisotropy_s2"] = '%8.6f' % (s[1]) RmagSpecRec["anisotropy_s3"] = '%8.6f' % (s[2]) RmagSpecRec["anisotropy_s4"] = '%8.6f' % (s[3]) RmagSpecRec["anisotropy_s5"] = '%8.6f' % (s[4]) RmagSpecRec["anisotropy_s6"] = '%8.6f' % (s[5]) RmagSpecRec["anisotropy_mean"] = '%8.3e' % (old_div(trace, 3)) RmagSpecRec["anisotropy_sigma"] = '%8.6f' % (sigma) RmagSpecRec["anisotropy_unit"] = "Am^2" RmagSpecRec["anisotropy_n"] = '%i' % (npos) RmagSpecRec["anisotropy_tilt_correction"] = '-1' # used by thellier_gui - must be taken out for uploading RmagSpecRec["anisotropy_F"] = '%7.1f ' % (hpars["F"]) # used by thellier_gui - must be taken out for uploading RmagSpecRec["anisotropy_F_crit"] = hpars["F_crit"] RmagResRec["anisotropy_t1"] = '%8.6f ' % (hpars["t1"]) RmagResRec["anisotropy_t2"] = '%8.6f ' % (hpars["t2"]) RmagResRec["anisotropy_t3"] = '%8.6f ' % (hpars["t3"]) RmagResRec["anisotropy_v1_dec"] = '%7.1f ' % (hpars["v1_dec"]) RmagResRec["anisotropy_v2_dec"] = '%7.1f ' % (hpars["v2_dec"]) RmagResRec["anisotropy_v3_dec"] = '%7.1f ' % (hpars["v3_dec"]) RmagResRec["anisotropy_v1_inc"] = '%7.1f ' % (hpars["v1_inc"]) RmagResRec["anisotropy_v2_inc"] = '%7.1f ' % (hpars["v2_inc"]) RmagResRec["anisotropy_v3_inc"] = '%7.1f ' % (hpars["v3_inc"]) RmagResRec["anisotropy_ftest"] = '%7.1f ' % (hpars["F"]) RmagResRec["anisotropy_ftest12"] = '%7.1f ' % (hpars["F12"]) RmagResRec["anisotropy_ftest23"] = '%7.1f ' % (hpars["F23"]) RmagResRec["result_description"] = 'Critical F: ' + \ hpars["F_crit"] + ';Critical F12/F13: ' + hpars["F12_crit"] if hpars["e12"] > hpars["e13"]: RmagResRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v1_eta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v1_eta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) else: RmagResRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v1_eta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v1_eta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) if hpars["e23"] > hpars['e12']: RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) else: RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["tilt_correction"] = '-1' RmagResRec["anisotropy_type"] = 'ATRM' RmagResRec["magic_method_codes"] = 'LP-AN-TRM:AE-H' RmagSpecRec["magic_method_codes"] = 'LP-AN-TRM:AE-H' RmagResRec["magic_software_packages"] = pmag.get_version() RmagSpecRec["magic_software_packages"] = pmag.get_version() RmagSpecRecs.append(RmagSpecRec) RmagResRecs.append(RmagResRec) specimen += 1 if data_model_num == 3: SpecRec = RmagResRec.copy() SpecRec.update(RmagSpecRec) SpecRecs.append(SpecRec) # finished iterating through specimens, # now we need to write out the data to files if data_model_num == 3: # translate records for rec in SpecRecs: rec3 = map_magic.convert_aniso('magic3', rec) SpecRecs3.append(rec3) # write output to 3.0 specimens file pmag.magic_write(spec_file, SpecRecs3, 'specimens') print("specimen data stored in {}".format(spec_file)) else: # write output to 2.5 rmag_ files pmag.magic_write(rmag_anis, RmagSpecRecs, 'rmag_anisotropy') print("specimen tensor elements stored in ", rmag_anis) pmag.magic_write(rmag_res, RmagResRecs, 'rmag_results') print("specimen statistics and eigenparameters stored in ", rmag_res)
def main(): """ NAME aarm_magic.py DESCRIPTION Converts AARM data to best-fit tensor (6 elements plus sigma) Original program ARMcrunch written to accomodate ARM anisotropy data collected from 6 axial directions (+X,+Y,+Z,-X,-Y,-Z) using the off-axis remanence terms to construct the tensor. A better way to do the anisotropy of ARMs is to use 9,12 or 15 measurements in the Hext rotational scheme. SYNTAX aarm_magic.py [-h][command line options] OPTIONS -h prints help message and quits -usr USER: identify user, default is "" -f FILE: specify input file, default is aarm_measurements.txt -crd [s,g,t] specify coordinate system, requires samples file -fsa FILE: specify er_samples.txt file, default is er_samples.txt (2.5) or samples.txt (3.0) -Fa FILE: specify anisotropy output file, default is arm_anisotropy.txt (MagIC 2.5 only) -Fr FILE: specify results output file, default is aarm_results.txt (MagIC 2.5 only) -Fsi FILE: specify output file, default is specimens.txt (MagIC 3 only) -DM DATA_MODEL: specify MagIC 2 or MagIC 3, default is 3 INPUT Input for the present program is a series of baseline, ARM pairs. The baseline should be the AF demagnetized state (3 axis demag is preferable) for the following ARM acquisition. The order of the measurements is: positions 1,2,3, 6,7,8, 11,12,13 (for 9 positions) positions 1,2,3,4, 6,7,8,9, 11,12,13,14 (for 12 positions) positions 1-15 (for 15 positions) """ # initialize some parameters args = sys.argv if "-h" in args: print(main.__doc__) sys.exit() user = "" meas_file = "aarm_measurements.txt" rmag_anis = "arm_anisotropy.txt" rmag_res = "aarm_results.txt" dir_path = '.' # # get name of file from command line # data_model_num = int(pmag.get_named_arg_from_sys("-DM", 3)) spec_file = pmag.get_named_arg_from_sys("-Fsi", "specimens.txt") if data_model_num == 3: samp_file = pmag.get_named_arg_from_sys("-fsa", "samples.txt") else: samp_file = pmag.get_named_arg_from_sys("-fsa", "er_samples.txt") if '-WD' in args: ind = args.index('-WD') dir_path = args[ind + 1] if "-usr" in args: ind = args.index("-usr") user = sys.argv[ind + 1] if "-f" in args: ind = args.index("-f") meas_file = sys.argv[ind + 1] coord = '-1' if "-crd" in sys.argv: ind = sys.argv.index("-crd") coord = sys.argv[ind + 1] if coord == 's': coord = '-1' if coord == 'g': coord = '0' if coord == 't': coord = '100' if "-Fa" in args: ind = args.index("-Fa") rmag_anis = args[ind + 1] if "-Fr" in args: ind = args.index("-Fr") rmag_res = args[ind + 1] meas_file = dir_path + '/' + meas_file samp_file = dir_path + '/' + samp_file rmag_anis = dir_path + '/' + rmag_anis rmag_res = dir_path + '/' + rmag_res spec_file = os.path.join(dir_path, spec_file) # read in data # read in data if data_model_num == 3: meas_data = [] meas_data3, file_type = pmag.magic_read(meas_file) if file_type != 'measurements': print(file_type, "This is not a valid MagIC 3.0. measurements file ") sys.exit() # convert meas_data to 2.5 for rec in meas_data3: meas_map = map_magic.meas_magic3_2_magic2_map meas_data.append(map_magic.mapping(rec, meas_map)) else: meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print(file_type, "This is not a valid MagIC 2.5 magic_measurements file ") sys.exit() # fish out relevant data meas_data = pmag.get_dictitem(meas_data, 'magic_method_codes', 'LP-AN-ARM', 'has') # figure out how to do this with 3 vs. 2.5 if coord != '-1': # need to read in sample data if data_model_num == 3: samp_data3, file_type = pmag.magic_read(samp_file) if file_type != 'samples': print(file_type, "This is not a valid er_samples file ") print("Only specimen coordinates will be calculated") coord = '-1' else: # translate to 2 samp_data = [] samp_map = map_magic.samp_magic3_2_magic2_map for rec in samp_data3: samp_data.append(map_magic.mapping(rec, samp_map)) else: samp_data, file_type = pmag.magic_read(samp_file) if file_type != 'er_samples': print(file_type, "This is not a valid er_samples file ") print("Only specimen coordinates will be calculated") coord = '-1' # # sort the specimen names # ssort = [] for rec in meas_data: spec = rec["er_specimen_name"] if spec not in ssort: ssort.append(spec) if len(ssort) > 1: sids = sorted(ssort) else: sids = ssort # # work on each specimen # specimen = 0 RmagSpecRecs, RmagResRecs = [], [] SpecRecs, SpecRecs3 = [], [] while specimen < len(sids): s = sids[specimen] data = [] RmagSpecRec = {} RmagResRec = {} method_codes = [] # # find the data from the meas_data file for this sample # data = pmag.get_dictitem(meas_data, 'er_specimen_name', s, 'T') # # find out the number of measurements (9, 12 or 15) # npos = old_div(len(data), 2) if npos == 9: # # get dec, inc, int and convert to x,y,z # # B matrix made from design matrix for positions B, H, tmpH = pmag.designAARM(npos) X = [] for rec in data: Dir = [] Dir.append(float(rec["measurement_dec"])) Dir.append(float(rec["measurement_inc"])) Dir.append(float(rec["measurement_magn_moment"])) X.append(pmag.dir2cart(Dir)) # # subtract baseline and put in a work array # work = numpy.zeros((npos, 3), 'f') for i in range(npos): for j in range(3): work[i][j] = X[2 * i + 1][j] - X[2 * i][j] # # calculate tensor elements # first put ARM components in w vector # w = numpy.zeros((npos * 3), 'f') index = 0 for i in range(npos): for j in range(3): w[index] = work[i][j] index += 1 s = numpy.zeros((6), 'f') # initialize the s matrix for i in range(6): for j in range(len(w)): s[i] += B[i][j] * w[j] trace = s[0] + s[1] + s[2] # normalize by the trace for i in range(6): s[i] = old_div(s[i], trace) a = pmag.s2a(s) #------------------------------------------------------------ # Calculating dels is different than in the Kappabridge # routine. Use trace normalized tensor (a) and the applied # unit field directions (tmpH) to generate model X,Y,Z # components. Then compare these with the measured values. #------------------------------------------------------------ S = 0. comp = numpy.zeros((npos * 3), 'f') for i in range(npos): for j in range(3): index = i * 3 + j compare = a[j][0] * tmpH[i][0] + a[j][1] * \ tmpH[i][1] + a[j][2] * tmpH[i][2] comp[index] = compare for i in range(npos * 3): d = old_div(w[i], trace) - comp[i] # del values S += d * d nf = float(npos * 3 - 6) # number of degrees of freedom if S > 0: sigma = numpy.sqrt(old_div(S, nf)) else: sigma = 0 RmagSpecRec["rmag_anisotropy_name"] = data[0]["er_specimen_name"] RmagSpecRec["er_location_name"] = data[0].get( "er_location_name", "") RmagSpecRec["er_specimen_name"] = data[0]["er_specimen_name"] RmagSpecRec["er_sample_name"] = data[0].get("er_sample_name", "") RmagSpecRec["er_site_name"] = data[0].get("er_site_name", "") RmagSpecRec["magic_experiment_names"] = RmagSpecRec[ "rmag_anisotropy_name"] + ":AARM" RmagSpecRec["er_citation_names"] = "This study" RmagResRec[ "rmag_result_name"] = data[0]["er_specimen_name"] + ":AARM" RmagResRec["er_location_names"] = data[0].get( "er_location_name", "") RmagResRec["er_specimen_names"] = data[0]["er_specimen_name"] RmagResRec["er_sample_names"] = data[0].get("er_sample_name", "") RmagResRec["er_site_names"] = data[0].get("er_site_name", "") RmagResRec["magic_experiment_names"] = RmagSpecRec[ "rmag_anisotropy_name"] + ":AARM" RmagResRec["er_citation_names"] = "This study" if "magic_instrument_codes" in list(data[0].keys()): RmagSpecRec["magic_instrument_codes"] = data[0][ "magic_instrument_codes"] else: RmagSpecRec["magic_instrument_codes"] = "" RmagSpecRec["anisotropy_type"] = "AARM" RmagSpecRec[ "anisotropy_description"] = "Hext statistics adapted to AARM" if coord != '-1': # need to rotate s # set orientation priorities SO_methods = [] for rec in samp_data: if "magic_method_codes" not in rec: rec['magic_method_codes'] = 'SO-NO' if "magic_method_codes" in rec: methlist = rec["magic_method_codes"] for meth in methlist.split(":"): if "SO" in meth and "SO-POM" not in meth.strip(): if meth.strip() not in SO_methods: SO_methods.append(meth.strip()) SO_priorities = pmag.set_priorities(SO_methods, 0) # continue here redo, p = 1, 0 if len(SO_methods) <= 1: az_type = SO_methods[0] orient = pmag.find_samp_rec(RmagSpecRec["er_sample_name"], samp_data, az_type) if orient["sample_azimuth"] != "": method_codes.append(az_type) redo = 0 while redo == 1: if p >= len(SO_priorities): print("no orientation data for ", s) orient["sample_azimuth"] = "" orient["sample_dip"] = "" method_codes.append("SO-NO") redo = 0 else: az_type = SO_methods[SO_methods.index( SO_priorities[p])] orient = pmag.find_samp_rec( RmagSpecRec["er_sample_name"], samp_data, az_type) if orient["sample_azimuth"] != "": method_codes.append(az_type) redo = 0 p += 1 az, pl = orient['sample_azimuth'], orient['sample_dip'] s = pmag.dosgeo(s, az, pl) # rotate to geographic coordinates if coord == '100': sample_bed_dir, sample_bed_dip = orient[ 'sample_bed_dip_direction'], orient['sample_bed_dip'] # rotate to geographic coordinates s = pmag.dostilt(s, sample_bed_dir, sample_bed_dip) hpars = pmag.dohext(nf, sigma, s) # # prepare for output # RmagSpecRec["anisotropy_s1"] = '%8.6f' % (s[0]) RmagSpecRec["anisotropy_s2"] = '%8.6f' % (s[1]) RmagSpecRec["anisotropy_s3"] = '%8.6f' % (s[2]) RmagSpecRec["anisotropy_s4"] = '%8.6f' % (s[3]) RmagSpecRec["anisotropy_s5"] = '%8.6f' % (s[4]) RmagSpecRec["anisotropy_s6"] = '%8.6f' % (s[5]) RmagSpecRec["anisotropy_mean"] = '%8.3e' % (old_div(trace, 3)) RmagSpecRec["anisotropy_sigma"] = '%8.6f' % (sigma) RmagSpecRec["anisotropy_unit"] = "Am^2" RmagSpecRec["anisotropy_n"] = '%i' % (npos) RmagSpecRec["anisotropy_tilt_correction"] = coord # used by thellier_gui - must be taken out for uploading RmagSpecRec["anisotropy_F"] = '%7.1f ' % (hpars["F"]) # used by thellier_gui - must be taken out for uploading RmagSpecRec["anisotropy_F_crit"] = hpars["F_crit"] RmagResRec["anisotropy_t1"] = '%8.6f ' % (hpars["t1"]) RmagResRec["anisotropy_t2"] = '%8.6f ' % (hpars["t2"]) RmagResRec["anisotropy_t3"] = '%8.6f ' % (hpars["t3"]) RmagResRec["anisotropy_v1_dec"] = '%7.1f ' % (hpars["v1_dec"]) RmagResRec["anisotropy_v2_dec"] = '%7.1f ' % (hpars["v2_dec"]) RmagResRec["anisotropy_v3_dec"] = '%7.1f ' % (hpars["v3_dec"]) RmagResRec["anisotropy_v1_inc"] = '%7.1f ' % (hpars["v1_inc"]) RmagResRec["anisotropy_v2_inc"] = '%7.1f ' % (hpars["v2_inc"]) RmagResRec["anisotropy_v3_inc"] = '%7.1f ' % (hpars["v3_inc"]) RmagResRec["anisotropy_ftest"] = '%7.1f ' % (hpars["F"]) RmagResRec["anisotropy_ftest12"] = '%7.1f ' % (hpars["F12"]) RmagResRec["anisotropy_ftest23"] = '%7.1f ' % (hpars["F23"]) RmagResRec["result_description"] = 'Critical F: ' + \ hpars["F_crit"] + ';Critical F12/F13: ' + hpars["F12_crit"] if hpars["e12"] > hpars["e13"]: RmagResRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v1_eta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v1_eta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) else: RmagResRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v1_eta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v1_eta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) if hpars["e23"] > hpars['e12']: RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) else: RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["tilt_correction"] = '-1' RmagResRec["anisotropy_type"] = 'AARM' RmagResRec["magic_method_codes"] = 'LP-AN-ARM:AE-H' RmagSpecRec["magic_method_codes"] = 'LP-AN-ARM:AE-H' RmagResRec["magic_software_packages"] = pmag.get_version() RmagSpecRec["magic_software_packages"] = pmag.get_version() specimen += 1 RmagSpecRecs.append(RmagSpecRec) RmagResRecs.append(RmagResRec) if data_model_num == 3: SpecRec = RmagResRec.copy() SpecRec.update(RmagSpecRec) SpecRecs.append(SpecRec) else: print('skipping specimen ', s, ' only 9 positions supported', '; this has ', npos) specimen += 1 if data_model_num == 3: # translate records for rec in SpecRecs: rec3 = map_magic.convert_aniso('magic3', rec) SpecRecs3.append(rec3) # write output to 3.0 specimens file pmag.magic_write(spec_file, SpecRecs3, 'specimens') print("specimen data stored in {}".format(spec_file)) else: if rmag_anis == "": rmag_anis = "rmag_anisotropy.txt" pmag.magic_write(rmag_anis, RmagSpecRecs, 'rmag_anisotropy') print("specimen tensor elements stored in ", rmag_anis) if rmag_res == "": rmag_res = "rmag_results.txt" pmag.magic_write(rmag_res, RmagResRecs, 'rmag_results') print("specimen statistics and eigenparameters stored in ", rmag_res)
def main(): """ NAME eqarea_magic.py DESCRIPTION makes equal area projections from declination/inclination data SYNTAX eqarea_magic.py [command line options] INPUT takes magic formatted sites, samples, specimens, or measurements OPTIONS -h prints help message and quits -f FILE: specify input magic format file from magic, default='sites.txt' supported types=[measurements, specimens, samples, sites] -fsp FILE: specify specimen file name, (required if you want to plot measurements by sample) default='specimens.txt' -fsa FILE: specify sample file name, (required if you want to plot specimens by site) default='samples.txt' -fsi FILE: specify site file name, default='sites.txt' -obj OBJ: specify level of plot [all, sit, sam, spc], default is all -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted default is geographic, unspecified assumed geographic -fmt [svg,png,jpg] format for output plots -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors -c plot as colour contour -sav save plot and quit quietly NOTE all: entire file; sit: site; sam: sample; spc: specimen """ # initialize some default variables FIG = {} # plot dictionary FIG['eqarea'] = 1 # eqarea is figure 1 plotE = 0 plt = 0 # default to not plotting verbose = pmagplotlib.verbose # extract arguments from sys.argv if '-h' in sys.argv: print(main.__doc__) sys.exit() dir_path = pmag.get_named_arg_from_sys("-WD", default_val=".") pmagplotlib.plot_init(FIG['eqarea'],5,5) in_file = pmag.get_named_arg_from_sys("-f", default_val="sites.txt") in_file = pmag.resolve_file_name(in_file, dir_path) if "-WD" not in sys.argv: dir_path = os.path.split(in_file)[0] #full_in_file = os.path.join(dir_path, in_file) plot_by = pmag.get_named_arg_from_sys("-obj", default_val="all").lower() 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") if plot_by == 'all': plot_key = 'all' elif plot_by == 'sit': plot_key = 'site' elif plot_by == 'sam': plot_key = 'sample' elif plot_by == 'spc': plot_key = 'specimen' else: plot_by = 'all' plot_key = 'all' if '-c' in sys.argv: contour = 1 else: contour = 0 if '-sav' in sys.argv: plt = 1 verbose = 0 if '-ell' in sys.argv: plotE = 1 ind = sys.argv.index('-ell') ell_type = sys.argv[ind+1] ell_type = pmag.get_named_arg_from_sys("-ell", "F") dist = ell_type.upper() # if dist type is unrecognized, use Fisher if dist not in ['F', 'K', 'B', 'BE', 'BV']: dist = 'F' if dist == "BV": FIG['bdirs'] = 2 pmagplotlib.plot_init(FIG['bdirs'],5,5) crd = pmag.get_named_arg_from_sys("-crd", default_val="g") if crd == "s": coord = "-1" elif crd == "t": coord = "100" else: coord = "0" fmt = pmag.get_named_arg_from_sys("-fmt", "svg") dec_key = 'dir_dec' inc_key = 'dir_inc' tilt_key = 'dir_tilt_correction' #Dir_type_keys=['','site_direction_type','sample_direction_type','specimen_direction_type'] # fnames = {"specimens": spec_file, "samples": samp_file, 'sites': site_file} contribution = nb.Contribution(dir_path, custom_filenames=fnames, single_file=in_file) try: contribution.propagate_location_to_samples() contribution.propagate_location_to_specimens() contribution.propagate_location_to_measurements() except KeyError as ex: pass # the object that contains the DataFrame + useful helper methods: table_name = list(contribution.tables.keys())[0] data_container = contribution.tables[table_name] # the actual DataFrame: data = data_container.df if plot_key != "all" and plot_key not in data.columns: print("-E- You can't plot by {} with the data provided".format(plot_key)) return # add tilt key into DataFrame columns if it isn't there already if tilt_key not in data.columns: data.loc[:, tilt_key] = None if verbose: print(len(data), ' records read from ', in_file) # find desired dec,inc data: dir_type_key = '' # # get plotlist if not plotting all records # plotlist=[] if plot_key != "all": # return all where plot_key is not blank if plot_key not in data.columns: print('Can\'t plot by "{}". That header is not in infile: {}'.format(plot_key, in_file)) return plots = data[data[plot_key].notnull()] plotlist = plots[plot_key].unique() # grab unique values else: plotlist.append('All') for plot in plotlist: if verbose: print(plot) if plot == 'All': # plot everything at once plot_data = data else: # pull out only partial data plot_data = data[data[plot_key] == plot] DIblock = [] GCblock = [] # SLblock, SPblock = [], [] title = plot mode = 1 k = 0 if dec_key not in plot_data.columns: print("-W- No dec/inc data") continue # get all records where dec & inc values exist plot_data = plot_data[plot_data[dec_key].notnull() & plot_data[inc_key].notnull()] if plot_data.empty: continue # this sorting out is done in get_di_bock #if coord == '0': # geographic, use records with no tilt key (or tilt_key 0) # cond1 = plot_data[tilt_key].fillna('') == coord # cond2 = plot_data[tilt_key].isnull() # plot_data = plot_data[cond1 | cond2] #else: # not geographic coordinates, use only records with correct tilt_key # plot_data = plot_data[plot_data[tilt_key] == coord] # get metadata for naming the plot file locations = data_container.get_name('location', df_slice=plot_data) site = data_container.get_name('site', df_slice=plot_data) sample = data_container.get_name('sample', df_slice=plot_data) specimen = data_container.get_name('specimen', df_slice=plot_data) # make sure method_codes is in plot_data if 'method_codes' not in plot_data.columns: plot_data['method_codes'] = '' # get data blocks DIblock = data_container.get_di_block(df_slice=plot_data, tilt_corr=coord, excl=['DE-BFP']) #SLblock = [[ind, row['method_codes']] for ind, row in plot_data.iterrows()] # get great circles great_circle_data = data_container.get_records_for_code('DE-BFP', incl=True, use_slice=True, sli=plot_data) if len(great_circle_data) > 0: gc_cond = great_circle_data[tilt_key] == coord GCblock = [[float(row[dec_key]), float(row[inc_key])] for ind, row in great_circle_data[gc_cond].iterrows()] #SPblock = [[ind, row['method_codes']] for ind, row in great_circle_data[gc_cond].iterrows()] if len(DIblock) > 0: if contour == 0: pmagplotlib.plotEQ(FIG['eqarea'], DIblock, title) else: pmagplotlib.plotEQcont(FIG['eqarea'], DIblock) else: pmagplotlib.plotNET(FIG['eqarea']) if len(GCblock)>0: for rec in GCblock: pmagplotlib.plotC(FIG['eqarea'], rec, 90., 'g') if len(DIblock) == 0 and len(GCblock) == 0: if verbose: print("no records for plotting") continue #sys.exit() if plotE == 1: ppars = pmag.doprinc(DIblock) # get principal directions nDIs, rDIs, npars, rpars = [], [], [], [] for rec in DIblock: angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']]) if angle>90.: rDIs.append(rec) else: nDIs.append(rec) if dist=='B': # do on whole dataset etitle="Bingham confidence ellipse" bpars=pmag.dobingham(DIblock) for key in list(bpars.keys()): if key!='n' and verbose: print(" ",key, '%7.1f'%(bpars[key])) if key=='n' and verbose: print(" ",key, ' %i'%(bpars[key])) npars.append(bpars['dec']) npars.append(bpars['inc']) npars.append(bpars['Zeta']) npars.append(bpars['Zdec']) npars.append(bpars['Zinc']) npars.append(bpars['Eta']) npars.append(bpars['Edec']) npars.append(bpars['Einc']) if dist=='F': etitle="Fisher confidence cone" if len(nDIs)>2: fpars=pmag.fisher_mean(nDIs) for key in list(fpars.keys()): if key!='n' and verbose: print(" ",key, '%7.1f'%(fpars[key])) if key=='n' and verbose: print(" ",key, ' %i'%(fpars[key])) mode+=1 npars.append(fpars['dec']) npars.append(fpars['inc']) npars.append(fpars['alpha95']) # Beta npars.append(fpars['dec']) isign=old_div(abs(fpars['inc']),fpars['inc']) npars.append(fpars['inc']-isign*90.) #Beta inc npars.append(fpars['alpha95']) # gamma npars.append(fpars['dec']+90.) # Beta dec npars.append(0.) #Beta inc if len(rDIs)>2: fpars=pmag.fisher_mean(rDIs) if verbose: print("mode ",mode) for key in list(fpars.keys()): if key!='n' and verbose: print(" ",key, '%7.1f'%(fpars[key])) if key=='n' and verbose: print(" ",key, ' %i'%(fpars[key])) mode+=1 rpars.append(fpars['dec']) rpars.append(fpars['inc']) rpars.append(fpars['alpha95']) # Beta rpars.append(fpars['dec']) isign=old_div(abs(fpars['inc']),fpars['inc']) rpars.append(fpars['inc']-isign*90.) #Beta inc rpars.append(fpars['alpha95']) # gamma rpars.append(fpars['dec']+90.) # Beta dec rpars.append(0.) #Beta inc if dist=='K': etitle="Kent confidence ellipse" if len(nDIs)>3: kpars=pmag.dokent(nDIs,len(nDIs)) if verbose: print("mode ",mode) for key in list(kpars.keys()): if key!='n' and verbose: print(" ",key, '%7.1f'%(kpars[key])) if key=='n' and verbose: print(" ",key, ' %i'%(kpars[key])) mode+=1 npars.append(kpars['dec']) npars.append(kpars['inc']) npars.append(kpars['Zeta']) npars.append(kpars['Zdec']) npars.append(kpars['Zinc']) npars.append(kpars['Eta']) npars.append(kpars['Edec']) npars.append(kpars['Einc']) if len(rDIs)>3: kpars=pmag.dokent(rDIs,len(rDIs)) if verbose: print("mode ",mode) for key in list(kpars.keys()): if key!='n' and verbose: print(" ",key, '%7.1f'%(kpars[key])) if key=='n' and verbose: print(" ",key, ' %i'%(kpars[key])) mode+=1 rpars.append(kpars['dec']) rpars.append(kpars['inc']) rpars.append(kpars['Zeta']) rpars.append(kpars['Zdec']) rpars.append(kpars['Zinc']) rpars.append(kpars['Eta']) rpars.append(kpars['Edec']) rpars.append(kpars['Einc']) else: # assume bootstrap if dist=='BE': if len(nDIs)>5: BnDIs=pmag.di_boot(nDIs) Bkpars=pmag.dokent(BnDIs,1.) if verbose: print("mode ",mode) for key in list(Bkpars.keys()): if key!='n' and verbose: print(" ",key, '%7.1f'%(Bkpars[key])) if key=='n' and verbose: print(" ",key, ' %i'%(Bkpars[key])) mode+=1 npars.append(Bkpars['dec']) npars.append(Bkpars['inc']) npars.append(Bkpars['Zeta']) npars.append(Bkpars['Zdec']) npars.append(Bkpars['Zinc']) npars.append(Bkpars['Eta']) npars.append(Bkpars['Edec']) npars.append(Bkpars['Einc']) if len(rDIs)>5: BrDIs=pmag.di_boot(rDIs) Bkpars=pmag.dokent(BrDIs,1.) if verbose: print("mode ",mode) for key in list(Bkpars.keys()): if key!='n' and verbose: print(" ",key, '%7.1f'%(Bkpars[key])) if key=='n' and verbose: print(" ",key, ' %i'%(Bkpars[key])) mode+=1 rpars.append(Bkpars['dec']) rpars.append(Bkpars['inc']) rpars.append(Bkpars['Zeta']) rpars.append(Bkpars['Zdec']) rpars.append(Bkpars['Zinc']) rpars.append(Bkpars['Eta']) rpars.append(Bkpars['Edec']) rpars.append(Bkpars['Einc']) etitle="Bootstrapped confidence ellipse" elif dist=='BV': sym={'lower':['o','c'],'upper':['o','g'],'size':3,'edgecolor':'face'} if len(nDIs)>5: BnDIs=pmag.di_boot(nDIs) pmagplotlib.plotEQsym(FIG['bdirs'],BnDIs,'Bootstrapped Eigenvectors', sym) if len(rDIs)>5: BrDIs=pmag.di_boot(rDIs) if len(nDIs)>5: # plot on existing plots pmagplotlib.plotDIsym(FIG['bdirs'],BrDIs,sym) else: pmagplotlib.plotEQ(FIG['bdirs'],BrDIs,'Bootstrapped Eigenvectors') if dist=='B': if len(nDIs)> 3 or len(rDIs)>3: pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],npars,0) elif len(nDIs)>3 and dist!='BV': pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],npars,0) if len(rDIs)>3: pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],rpars,0) elif len(rDIs)>3 and dist!='BV': pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],rpars,0) for key in list(FIG.keys()): files = {} filename = pmag.get_named_arg_from_sys('-fname') if filename: # use provided filename filename+= '.' + fmt elif pmagplotlib.isServer: # use server plot naming convention filename='LO:_'+locations+'_SI:_'+site+'_SA:_'+sample+'_SP:_'+specimen+'_CO:_'+crd+'_TY:_'+key+'_.'+fmt elif plot_key == 'all': filename = 'all' if 'location' in plot_data.columns: locs = plot_data['location'].unique() loc_string = "_".join([loc.replace(' ', '_') for loc in locs]) filename += "_" + loc_string filename += "_" + crd + "_" + key filename += ".{}".format(fmt) else: # use more readable naming convention filename = '' # fix this if plot_by is location , for example use_names = {'location': [locations], 'site': [locations, site], 'sample': [locations, site, sample], 'specimen': [locations, site, sample, specimen]} use = use_names[plot_key] use.extend([crd, key]) for item in use: #[locations, site, sample, specimen, crd, key]: if item: item = item.replace(' ', '_') filename += item + '_' if filename.endswith('_'): filename = filename[:-1] filename += ".{}".format(fmt) files[key]=filename if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['eq']='Equal Area Plot' FIG = pmagplotlib.addBorders(FIG,titles,black,purple) pmagplotlib.saveP(FIG,files) if plt: pmagplotlib.saveP(FIG,files) continue if verbose: pmagplotlib.drawFIGS(FIG) ans=input(" S[a]ve to save plot, [q]uit, Return to continue: ") if ans == "q": sys.exit() if ans == "a": pmagplotlib.saveP(FIG,files) continue
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)
def main(): """ NAME vgpmap_magic.py DESCRIPTION makes a map of vgps and a95/dp,dm for site means in a sites table SYNTAX vgpmap_magic.py [command line options] OPTIONS -h prints help and quits -eye ELAT ELON [specify eyeball location], default is 90., 0. -f FILE sites format file, [default is sites.txt] -res [c,l,i,h] specify resolution (crude, low, intermediate, high] -etp plot the etopo20 topographpy data (requires high resolution data set) -prj PROJ, specify one of the following: ortho = orthographic lcc = lambert conformal moll = molweide merc = mercator -sym SYM SIZE: choose a symbol and size, examples: ro 5 : small red circles bs 10 : intermediate blue squares g^ 20 : large green triangles -ell plot dp/dm or a95 ellipses -rev RSYM RSIZE : flip reverse poles to normal antipode -S: plot antipodes of all poles -age : plot the ages next to the poles -crd [g,t] : choose coordinate system, default is to plot all site VGPs -fmt [pdf, png, eps...] specify output format, default is pdf -sav save and quit DEFAULTS FILE: pmag_results.txt res: c prj: ortho ELAT,ELON = 0,0 SYM SIZE: ro 8 RSYM RSIZE: g^ 8 """ if '-h' in sys.argv: print(main.__doc__) sys.exit() dir_path = pmag.get_named_arg_from_sys("-WD", ".") # plot: default is 0, if -sav in sys.argv should be 1 plot = pmag.get_flag_arg_from_sys("-sav", true=1, false=0) fmt = pmag.get_named_arg_from_sys("-fmt", "pdf") res = pmag.get_named_arg_from_sys("-res", "c") proj = pmag.get_named_arg_from_sys("-prj", "ortho") anti = pmag.get_flag_arg_from_sys("-S", true=1, false=0) fancy = pmag.get_flag_arg_from_sys("-etp", true=1, false=0) ell = pmag.get_flag_arg_from_sys("-ell", true=1, false=0) ages = pmag.get_flag_arg_from_sys("-age", true=1, false=0) if '-rev' in sys.argv: flip = 1 ind = sys.argv.index('-rev') rsym = (sys.argv[ind + 1]) rsize = int(sys.argv[ind + 2]) else: flip, rsym, rsize = 0, "g^", 8 if '-sym' in sys.argv: ind = sys.argv.index('-sym') sym = (sys.argv[ind + 1]) size = int(sys.argv[ind + 2]) else: sym, size = 'ro', 8 if '-eye' in sys.argv: ind = sys.argv.index('-eye') lat_0 = float(sys.argv[ind + 1]) lon_0 = float(sys.argv[ind + 2]) else: lat_0, lon_0 = 90., 0. crd = pmag.get_named_arg_from_sys("-crd", "") coord_dict = {'g': 0, 't': 100} coord = coord_dict[crd] if crd else "" results_file = pmag.get_named_arg_from_sys("-f", "sites.txt") con = nb.Contribution(dir_path, single_file=results_file) if not list(con.tables.keys()): print("-W - Couldn't read in data") return FIG = {'map': 1} pmagplotlib.plot_init(FIG['map'], 6, 6) # read in er_sites file lats, lons = [], [] Pars = [] dates, rlats, rlons = [], [], [] site_container = con.tables['sites'] site_df = site_container.df # use individual results site_df = site_df[site_df['result_type'] == 'i'] # use records with vgp_lat and vgp_lon cond1, cond2 = site_df['vgp_lat'].notnull(), site_df['vgp_lon'].notnull() Results = site_df[cond1 & cond2] # use tilt correction if coord and 'dir_tilt_correction' in Results.columns: Results = Results[Results['dir_tilt_correction'] == coord] # get location name and average ages location = ":".join(Results['location'].unique()) if 'average_age' in Results.columns and ages == 1: dates = Results['average_age'].unique() # go through rows and extract data for ind, row in Results.iterrows(): lat, lon = float(row['vgp_lat']), float(row['vgp_lon']) if anti == 1: lats.append(-lat) lon = lon + 180. if lon > 360: lon = lon - 360. lons.append(lon) elif flip == 0: lats.append(lat) lons.append(lon) elif flip == 1: if lat < 0: rlats.append(-lat) lon = lon + 180. if lon > 360: lon = lon - 360 rlons.append(lon) else: lats.append(lat) lons.append(lon) ppars = [] ppars.append(lon) ppars.append(lat) ell1, ell2 = "", "" if 'vgp_dm' in list(row.keys()) and row['vgp_dm']: ell1 = float(row['vgp_dm']) if 'vgp_dp' in list(row.keys()) and row['vgp_dp']: ell2 = float(row['vgp_dp']) if 'vgp_alpha95' in list(row.keys()) and row['vgp_alpha95'].notnull(): ell1, ell2 = float(row['vgp_alpha95']), float(row['vgp_alpha95']) if ell1 and ell2: ppars = [] ppars.append(lons[-1]) ppars.append(lats[-1]) ppars.append(ell1) ppars.append(lons[-1]) isign = old_div(abs(lats[-1]), lats[-1]) ppars.append(lats[-1] - isign * 90.) ppars.append(ell2) ppars.append(lons[-1] + 90.) ppars.append(0.) Pars.append(ppars) location = location.strip(':') Opts = { 'latmin': -90, 'latmax': 90, 'lonmin': 0., 'lonmax': 360., 'lat_0': lat_0, 'lon_0': lon_0, 'proj': proj, 'sym': 'bs', 'symsize': 3, 'pltgrid': 0, 'res': res, 'boundinglat': 0. } Opts['details'] = { 'coasts': 1, 'rivers': 0, 'states': 0, 'countries': 0, 'ocean': 1, 'fancy': fancy } # make the base map with a blue triangle at the pole pmagplotlib.plotMAP(FIG['map'], [90.], [0.], Opts) Opts['pltgrid'] = -1 Opts['sym'] = sym Opts['symsize'] = size if len(dates) > 0: Opts['names'] = dates if len(lats) > 0: # add the lats and lons of the poles pmagplotlib.plotMAP(FIG['map'], lats, lons, Opts) Opts['names'] = [] if len(rlats) > 0: Opts['sym'] = rsym Opts['symsize'] = rsize # add the lats and lons of the poles pmagplotlib.plotMAP(FIG['map'], rlats, rlons, Opts) if plot == 0: pmagplotlib.drawFIGS(FIG) if ell == 1: # add ellipses if desired. Opts['details'] = { 'coasts': 0, 'rivers': 0, 'states': 0, 'countries': 0, 'ocean': 0, 'fancy': fancy } Opts['pltgrid'] = -1 # turn off meridian replotting Opts['symsize'] = 2 Opts['sym'] = 'g-' for ppars in Pars: if ppars[2] != 0: PTS = pmagplotlib.plotELL(FIG['map'], ppars, 'g.', 0, 0) elats, elons = [], [] for pt in PTS: elons.append(pt[0]) elats.append(pt[1]) # make the base map with a blue triangle at the pole pmagplotlib.plotMAP(FIG['map'], elats, elons, Opts) if plot == 0: pmagplotlib.drawFIGS(FIG) files = {} for key in list(FIG.keys()): if pmagplotlib.isServer: # use server plot naming convention files[key] = 'LO:_' + location + '_VGP_map.' + fmt else: # use more readable naming convention files[key] = '{}_VGP_map.{}'.format(location, fmt) if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles = {} titles['eq'] = 'LO:_' + location + '_VGP_map' FIG = pmagplotlib.addBorders(FIG, titles, black, purple) pmagplotlib.saveP(FIG, files) elif plot == 0: pmagplotlib.drawFIGS(FIG) ans = input(" S[a]ve to save plot, Return to quit: ") if ans == "a": pmagplotlib.saveP(FIG, files) else: print("Good bye") sys.exit() else: pmagplotlib.saveP(FIG, files)
def main(): """ NAME zeq_magic.py DESCRIPTION reads in magic_measurements formatted file, makes plots of remanence decay during demagnetization experiments. Reads in prior interpretations saved in a pmag_specimens formatted file [and allows re-interpretations of best-fit lines and planes and saves (revised or new) interpretations in a pmag_specimens file. interpretations are saved in the coordinate system used. Also allows judicious editting of measurements to eliminate "bad" measurements. These are marked as such in the magic_measurements input file. they are NOT deleted, just ignored. ] Bracketed part not yet implemented SYNTAX zeq_magic.py [command line options] OPTIONS -h prints help message and quits -f MEASFILE: sets measurements format input file, default: measurements.txt -fsp SPECFILE: sets specimens format file with prior interpreations, default: specimens.txt -fsa SAMPFILE: sets samples format file sample=>site information, default: samples.txt -fsi SITEFILE: sets sites format file with site=>location informationprior interpreations, default: samples.txt -Fp PLTFILE: sets filename for saved plot, default is name_type.fmt (where type is zijd, eqarea or decay curve) -crd [s,g,t]: sets coordinate system, g=geographic, t=tilt adjusted, default: specimen coordinate system -spc SPEC plots single specimen SPEC, saves plot with specified format with optional -dir settings and quits -dir [L,P,F][beg][end]: sets calculation type for principal component analysis, default is none beg: starting step for PCA calculation end: ending step for PCA calculation [L,P,F]: calculation type for line, plane or fisher mean must be used with -spc option -fmt FMT: set format of saved plot [png,svg,jpg] -A: suppresses averaging of replicate measurements, default is to average -sav: saves all plots without review SCREEN OUTPUT: Specimen, N, a95, StepMin, StepMax, Dec, Inc, calculation type """ # initialize some variables doave, e, b = 1, 0, 0 # average replicates, initial end and beginning step intlist = ['magn_moment', 'magn_volume', 'magn_mass', 'magnitude'] plots, coord = 0, 's' noorient = 0 version_num = pmag.get_version() verbose = pmagplotlib.verbose calculation_type, fmt = "", "svg" user, spec_keys, locname = "", [], '' geo, tilt, ask = 0, 0, 0 PriorRecs = [] # empty list for prior interpretations backup = 0 specimen = "" # can skip everything and just plot one specimen with bounds e,b 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") 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") #meas_file = os.path.join(dir_path, meas_file) #spec_file = os.path.join(dir_path, spec_file) #samp_file = os.path.join(dir_path, samp_file) #site_file = os.path.join(dir_path, site_file) plot_file = pmag.get_named_arg_from_sys("-Fp", default_val="") crd = pmag.get_named_arg_from_sys("-crd", default_val="s") if crd == "s": coord = "-1" elif crd == "t": coord = "100" else: coord = "0" fmt = pmag.get_named_arg_from_sys("-fmt", "svg") specimen = pmag.get_named_arg_from_sys("-spc", default_val="") beg_pca, end_pca = "", "" if '-dir' in sys.argv: ind = sys.argv.index('-dir') direction_type = sys.argv[ind + 1] beg_pca = int(sys.argv[ind + 2]) end_pca = int(sys.argv[ind + 3]) if direction_type == 'L': calculation_type = 'DE-BFL' if direction_type == 'P': calculation_type = 'DE-BFP' if direction_type == 'F': calculation_type = 'DE-FM' if '-A' in sys.argv: doave = 0 if '-sav' in sys.argv: plots, verbose = 1, 0 # first_save = 1 fnames = {'measurements': meas_file, 'specimens': spec_file, 'samples': samp_file, 'sites': site_file} contribution = nb.Contribution(dir_path, custom_filenames=fnames, read_tables=[ 'measurements', 'specimens', 'samples', 'sites']) # # import specimens 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: # contribution.propagate_name_down('sample','measurements') spec_container = contribution.tables['specimens'] if 'method_codes' not in spec_container.df.columns: spec_container.df['method_codes'] = None prior_spec_data = spec_container.get_records_for_code( 'LP-DIR', strict_match=False) # look up all prior directional interpretations # # tie sample names to measurement data # else: spec_container, prior_spec_data = None, [] # # import samples for orientation info # if ('samples' in contribution.tables) and ('specimens' in contribution.tables): # contribution.propagate_name_down('site','measurements') contribution.propagate_cols(col_names=[ 'azimuth', 'dip', 'orientation_quality'], target_df_name='measurements', source_df_name='samples') # # define figure numbers for equal area, zijderveld, # and intensity vs. demagnetiztion step respectively # ZED = {} ZED['eqarea'], ZED['zijd'], ZED['demag'] = 1, 2, 3 pmagplotlib.plot_init(ZED['eqarea'], 6, 6) pmagplotlib.plot_init(ZED['zijd'], 6, 6) pmagplotlib.plot_init(ZED['demag'], 6, 6) # save_pca=0 angle, direction_type, setangle = "", "", 0 # create measurement dataframe # meas_container = contribution.tables['measurements'] meas_data = meas_container.df # meas_data = meas_data[meas_data['method_codes'].str.contains( 'LT-NO|LT-AF-Z|LT-T-Z|LT-M-Z') == True] # fish out steps for plotting meas_data = meas_data[meas_data['method_codes'].str.contains( 'AN|ARM|LP-TRM|LP-PI-ARM') == False] # strip out unwanted experiments intensity_types = [ col_name for col_name in meas_data.columns if col_name in intlist] intensity_types = [ col_name for col_name in intensity_types if any(meas_data[col_name])] if not len(intensity_types): print('-W- No intensity columns found') return # plot first non-empty intensity method found - normalized to initial value anyway - # doesn't matter which used int_key = intensity_types[0] # get all the non-null intensity records of the same type meas_data = meas_data[meas_data[int_key].notnull()] if 'flag' not in meas_data.columns: meas_data['flag'] = 'g' # set the default flag to good # need to treat LP-NO specially for af data, treatment should be zero, # otherwise 273. meas_data['treatment'] = meas_data['treat_ac_field'].where( cond=meas_data['treat_ac_field'] != 0, other=meas_data['treat_temp']) meas_data['ZI'] = 1 # initialize these to one meas_data['instrument_codes'] = "" # initialize these to blank # for unusual case of microwave power.... if 'treat_mw_power' in meas_data.columns: meas_data.loc[ (meas_data.treat_mw_power != 0) & (meas_data.treat_mw_power) & (meas_data.treat_mw_time), 'treatment'] = meas_data.treat_mw_power * meas_data.treat_mw_time # # get list of unique specimen names from measurement data # # this is a list of all the specimen names specimen_names = meas_data.specimen.unique() specimen_names = specimen_names.tolist() specimen_names.sort() # # set up new DataFrame for this sessions specimen interpretations # data_container = nb.MagicDataFrame( dtype='specimens', columns=specimen_cols) # this is for interpretations from this session current_spec_data = data_container.df locname = 'LookItUp' if specimen == "": k = 0 else: k = specimen_names.index(specimen) # let's look at the data now while k < len(specimen_names): mpars = None # set the current specimen for plotting this_specimen = specimen_names[k] # reset beginning/end pca if plotting more than one specimen if not specimen: beg_pca, end_pca = "", "" if verbose and this_specimen != "": print(this_specimen, k + 1, 'out of ', len(specimen_names)) if setangle == 0: angle = "" this_specimen_measurements = meas_data[meas_data['specimen'].str.contains( this_specimen) == True] # fish out this specimen this_specimen_measurements = this_specimen_measurements[this_specimen_measurements['flag'].str.contains( 'g') == True] # fish out this specimen if len(this_specimen_measurements) != 0: # if there are measurements # # set up datablock [[treatment,dec, inc, int, direction_type],[....]] # # # figure out the method codes # units, methods, title = "", "", this_specimen # this is a list of all the specimen method codes` meas_meths = this_specimen_measurements.method_codes.unique() tr = pd.to_numeric(this_specimen_measurements.treatment).tolist() if set(tr) == set([0]): k += 1 continue for m in meas_meths: if 'LT-AF-Z' in m: units = 'T' # units include tesla tr[0] = 0 if 'LT-T-Z' in m: units = units + ":K" # units include kelvin if 'LT-M-Z' in m: units = units + ':J' # units include joules tr[0] = 0 units = units.strip(':') # strip off extra colons if 'LP-' in m: methods = methods + ":" + m decs = pd.to_numeric(this_specimen_measurements.dir_dec).tolist() incs = pd.to_numeric(this_specimen_measurements.dir_inc).tolist() # # fix the coordinate system # if coord != '-1': # need to transform coordinates to geographic azimuths = pd.to_numeric( this_specimen_measurements.azimuth).tolist() # get the azimuths # get the azimuths dips = pd.to_numeric(this_specimen_measurements.dip).tolist() dirs = [decs, incs, azimuths, dips] # this transposes the columns and rows of the list of lists dirs_geo = np.array(list(map(list, list(zip(*dirs))))) decs, incs = pmag.dogeo_V(dirs_geo) if coord == '100': # need to do tilt correction too bed_dip_dirs = pd.to_numeric( this_specimen_measurements.bed_dip_dir).tolist() # get the azimuths bed_dips = pd.to_numeric( this_specimen_measurements.bed_dip).tolist() # get the azimuths dirs = [decs, incs, bed_dip_dirs, bed_dips] # this transposes the columns and rows of the list of lists dirs_tilt = np.array(list(map(list, list(zip(*dirs))))) decs, incs = pmag.dotilt_V(dirs_tilt) title = title + '_t' else: title = title + '_g' if angle == "": angle = decs[0] ints = pd.to_numeric(this_specimen_measurements[int_key]).tolist() ZI = this_specimen_measurements.ZI.tolist() flags = this_specimen_measurements.flag.tolist() codes = this_specimen_measurements.instrument_codes.tolist() datalist = [tr, decs, incs, ints, ZI, flags, codes] # this transposes the columns and rows of the list of lists datablock = list(map(list, list(zip(*datalist)))) pmagplotlib.plotZED(ZED, datablock, angle, title, units) if verbose: pmagplotlib.drawFIGS(ZED) # # collect info for current_specimen_interpretation dictionary # # # find prior interpretation # prior_specimen_interpretations = prior_spec_data[prior_spec_data['specimen'].str.contains(this_specimen) == True] if (beg_pca == "") and (len(prior_specimen_interpretations) != 0): if len(prior_specimen_interpretations)>0: beg_pcas = pd.to_numeric( prior_specimen_interpretations.meas_step_min.values).tolist() end_pcas = pd.to_numeric( prior_specimen_interpretations.meas_step_max.values).tolist() spec_methods = prior_specimen_interpretations.method_codes.tolist() # step through all prior interpretations and plot them for ind in range(len(beg_pcas)): spec_meths = spec_methods[ind].split(':') for m in spec_meths: if 'DE-BFL' in m: calculation_type = 'DE-BFL' # best fit line if 'DE-BFP' in m: calculation_type = 'DE-BFP' # best fit plane if 'DE-FM' in m: calculation_type = 'DE-FM' # fisher mean if 'DE-BFL-A' in m: calculation_type = 'DE-BFL-A' # anchored best fit line start, end = tr.index(beg_pcas[ind]), tr.index( end_pcas[ind]) # getting the starting and ending points # calculate direction/plane mpars = pmag.domean( datablock, start, end, calculation_type) if mpars["specimen_direction_type"] != "Error": # put it on the plot pmagplotlib.plotDir(ZED, mpars, datablock, angle) if verbose: pmagplotlib.drawFIGS(ZED) else: try: start, end = int(beg_pca), int(end_pca) except ValueError: beg_pca = 0 end_pca = len(datablock) - 1 start, end = int(beg_pca), int(end_pca) # calculate direction/plane try: mpars = pmag.domean(datablock, start, end, calculation_type) except Exception as ex: print('-I- Problem with {}'.format(this_specimen)) print(' ', ex) print(' Skipping') k += 1 continue if mpars["specimen_direction_type"] != "Error": # put it on the plot pmagplotlib.plotDir(ZED, mpars, datablock, angle) if verbose: pmagplotlib.drawFIGS(ZED) if plots == 1 or specimen != "": if plot_file == "": basename = title else: basename = plot_file files = {} for key in list(ZED.keys()): files[key] = basename + '_' + key + '.' + fmt pmagplotlib.saveP(ZED, files) if specimen != "": sys.exit() if verbose: recnum = 0 for plotrec in datablock: if units == 'T': print('%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % ( plotrec[5], recnum, plotrec[0] * 1e3, " mT", plotrec[3], plotrec[1], plotrec[2], plotrec[6])) if units == "K": print('%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % ( plotrec[5], recnum, plotrec[0] - 273, ' C', plotrec[3], plotrec[1], plotrec[2], plotrec[6])) if units == "J": print('%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % ( plotrec[5], recnum, plotrec[0], ' J', plotrec[3], plotrec[1], plotrec[2], plotrec[6])) if 'K' in units and 'T' in units: if plotrec[0] >= 1.: print('%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % ( plotrec[5], recnum, plotrec[0] - 273, ' C', plotrec[3], plotrec[1], plotrec[2], plotrec[6])) if plotrec[0] < 1.: print('%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % ( plotrec[5], recnum, plotrec[0] * 1e3, " mT", plotrec[3], plotrec[1], plotrec[2], plotrec[6])) recnum += 1 # we have a current interpretation elif mpars["specimen_direction_type"] != "Error": # # create a new specimen record for the interpreation for this # specimen this_specimen_interpretation = { col: "" for col in specimen_cols} # this_specimen_interpretation["analysts"]=user this_specimen_interpretation['software_packages'] = version_num this_specimen_interpretation['specimen'] = this_specimen this_specimen_interpretation["method_codes"] = calculation_type this_specimen_interpretation["meas_step_unit"] = units this_specimen_interpretation["meas_step_min"] = tr[start] this_specimen_interpretation["meas_step_max"] = tr[end] this_specimen_interpretation["dir_dec"] = '%7.1f' % ( mpars['specimen_dec']) this_specimen_interpretation["dir_inc"] = '%7.1f' % ( mpars['specimen_inc']) this_specimen_interpretation["dir_dang"] = '%7.1f' % ( mpars['specimen_dang']) this_specimen_interpretation["dir_n_measurements"] = '%i' % ( mpars['specimen_n']) this_specimen_interpretation["dir_tilt_correction"] = coord methods = methods.replace(" ", "") if "T" in units: methods = methods + ":LP-DIR-AF" if "K" in units: methods = methods + ":LP-DIR-T" if "J" in units: methods = methods + ":LP-DIR-M" this_specimen_interpretation["method_codes"] = methods.strip( ':') this_specimen_interpretation["experiments"] = this_specimen_measurements.experiment.unique()[ 0] # # print some stuff # if calculation_type != 'DE-FM': this_specimen_interpretation["dir_mad_free"] = '%7.1f' % ( mpars['specimen_mad']) this_specimen_interpretation["dir_alpha95"] = '' if verbose: if units == 'K': print('%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation["dir_n_measurements"]), float(this_specimen_interpretation["dir_mad_free"]), float(this_specimen_interpretation["dir_dang"]), float( this_specimen_interpretation["meas_step_min"]) - 273, float(this_specimen_interpretation["meas_step_max"]) - 273, float(this_specimen_interpretation["dir_dec"]), float(this_specimen_interpretation["dir_inc"]), calculation_type)) elif units == 'T': print('%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation["dir_n_measurements"]), float(this_specimen_interpretation["dir_mad_free"]), float(this_specimen_interpretation["dir_dang"]), float( this_specimen_interpretation["meas_step_min"]) * 1e3, float(this_specimen_interpretation["meas_step_max"]) * 1e3, float(this_specimen_interpretation["dir_dec"]), float(this_specimen_interpretation["dir_inc"]), calculation_type)) elif 'T' in units and 'K' in units: if float(this_specimen_interpretation['meas_step_min']) < 1.0: min = float( this_specimen_interpretation['meas_step_min']) * 1e3 else: min = float( this_specimen_interpretation['meas_step_min']) - 273 if float(this_specimen_interpretation['meas_step_max']) < 1.0: max = float( this_specimen_interpretation['meas_step_max']) * 1e3 else: max = float( this_specimen_interpretation['meas_step_max']) - 273 print('%s %i %7.1f %i %i %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation["dir_n_measurements"]), float(this_specimen_interpretation["dir_mad_free"]), float( this_specimen_interpretation["dir_dang"]), min, max, float(this_specimen_interpretation["dir_dec"]), float(this_specimen_interpretation["dir_inc"]), calculation_type)) else: print('%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation["dir_n_measurements"]), float(this_specimen_interpretation["dir_mad_free"]), float(this_specimen_interpretation["dir_dang"]), float( this_specimen_interpretation["meas_step_min"]), float(this_specimen_interpretation["meas_step_max"]), float(this_specimen_interpretation["dir_dec"]), float(this_specimen_interpretation["dir_inc"]), calculation_type)) else: this_specimen_interpretation["dir_alpha95"] = '%7.1f' % ( mpars['specimen_alpha95']) this_specimen_interpretation["dir_mad_free"] = '' if verbose: if 'K' in units: print('%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation["dir_n_measurments"]), float(this_specimen_interpretation["dir_mad_free"]), float(this_specimen_interpretation["dir_dang"]), float( this_specimen_interpretation["meas_step_min"]) - 273, float(this_specimen_interpretation["meas_step_max"]) - 273, float(this_specimen_interpretation["dir_dec"]), float(this_specimen_interpretation["dir_inc"]), calculation_type)) elif 'T' in units: print('%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation["dir_n_measurements"]), float(this_specimen_interpretation["dir_alpha95"]), float(this_specimen_interpretation["dir_dang"]), float( this_specimen_interpretation["meas_step_min"]) * 1e3, float(this_specimen_interpretation["meas_step_max"]) * 1e3, float(this_specimen_interpretation["dir_dec"]), float(this_specimen_interpretation["dir_inc"]), calculation_type)) elif 'T' in units and 'K' in units: if float(this_specimen_interpretation['meas_step_min']) < 1.0: min = float( this_specimen_interpretation['meas_step_min']) * 1e3 else: min = float( this_specimen_interpretation['meas_step_min']) - 273 if float(this_specimen_interpretation['meas_step_max']) < 1.0: max = float( this_specimen_interpretation['meas_step_max']) * 1e3 else: max = float( this_specimen_interpretation['meas_step_max']) - 273 print('%s %i %7.1f %i %i %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation["dir_n_measurements"]), float( this_specimen_interpretation["dir_alpha95"]), min, max, float(this_specimen_interpretation["dir_dec"]), float(this_specimen_interpretation["dir_inc"]), calculation_type)) else: print('%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation["dir_n_measurements"]), float(this_specimen_interpretation["dir_alpha95"]), float( this_specimen_interpretation["meas_step_min"]), float(this_specimen_interpretation["meas_step_max"]), float(this_specimen_interpretation["dir_dec"]), float(this_specimen_interpretation["dir_inc"]), calculation_type)) if verbose: saveit = input("Save this interpretation? [y]/n \n") # START HERE # # if len(current_spec_data)==0: # no interpretations yet for this session # print "no current interpretation" # beg_pca,end_pca="","" # calculation_type="" # get the ones that meet the current coordinate system else: print("no data") if verbose: res = input(' <return> for next specimen, [q]uit ') if res == 'q': return k += 1
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'])
def main(): """ NAME vgpmap_magic.py DESCRIPTION makes a map of vgps and a95/dp,dm for site means in a sites table SYNTAX vgpmap_magic.py [command line options] OPTIONS -h prints help and quits -eye ELAT ELON [specify eyeball location], default is 90., 0. -f FILE sites format file, [default is sites.txt] -res [c,l,i,h] specify resolution (crude, low, intermediate, high] -etp plot the etopo20 topographpy data (requires high resolution data set) -prj PROJ, specify one of the following: ortho = orthographic lcc = lambert conformal moll = molweide merc = mercator -sym SYM SIZE: choose a symbol and size, examples: ro 5 : small red circles bs 10 : intermediate blue squares g^ 20 : large green triangles -ell plot dp/dm or a95 ellipses -rev RSYM RSIZE : flip reverse poles to normal antipode -S: plot antipodes of all poles -age : plot the ages next to the poles -crd [g,t] : choose coordinate system, default is to plot all site VGPs -fmt [pdf, png, eps...] specify output format, default is pdf -sav save and quit DEFAULTS FILE: pmag_results.txt res: c prj: ortho ELAT,ELON = 0,0 SYM SIZE: ro 8 RSYM RSIZE: g^ 8 """ if '-h' in sys.argv: print(main.__doc__) sys.exit() dir_path = pmag.get_named_arg_from_sys("-WD", ".") # plot: default is 0, if -sav in sys.argv should be 1 plot = pmag.get_flag_arg_from_sys("-sav", true=1, false=0) fmt = pmag.get_named_arg_from_sys("-fmt", "pdf") res = pmag.get_named_arg_from_sys("-res", "c") proj = pmag.get_named_arg_from_sys("-prj", "ortho") anti = pmag.get_flag_arg_from_sys("-S", true=1, false=0) fancy = pmag.get_flag_arg_from_sys("-etp", true=1, false=0) ell = pmag.get_flag_arg_from_sys("-ell", true=1, false=0) ages = pmag.get_flag_arg_from_sys("-age", true=1, false=0) if '-rev' in sys.argv: flip = 1 ind = sys.argv.index('-rev') rsym = (sys.argv[ind + 1]) rsize = int(sys.argv[ind + 2]) else: flip, rsym, rsize = 0, "g^", 8 if '-sym' in sys.argv: ind = sys.argv.index('-sym') sym = (sys.argv[ind + 1]) size = int(sys.argv[ind + 2]) else: sym, size = 'ro', 8 if '-eye' in sys.argv: ind = sys.argv.index('-eye') lat_0 = float(sys.argv[ind + 1]) lon_0 = float(sys.argv[ind + 2]) else: lat_0, lon_0 = 90., 0. crd = pmag.get_named_arg_from_sys("-crd", "") coord_dict = {'g': 0, 't': 100} coord = coord_dict[crd] if crd else "" results_file = pmag.get_named_arg_from_sys("-f", "sites.txt") con = nb.Contribution(dir_path, single_file=results_file) if not list(con.tables.keys()): print("-W - Couldn't read in data") return FIG = {'map': 1} pmagplotlib.plot_init(FIG['map'], 6, 6) # read in er_sites file lats, lons = [], [] Pars = [] dates, rlats, rlons = [], [], [] site_container = con.tables['sites'] site_df = site_container.df # use individual results site_df = site_df[site_df['result_type'] == 'i'] # use records with vgp_lat and vgp_lon cond1, cond2 = site_df['vgp_lat'].notnull(), site_df['vgp_lon'].notnull() Results = site_df[cond1 & cond2] # use tilt correction if coord and 'dir_tilt_correction' in Results.columns: Results = Results[Results['dir_tilt_correction'] == coord] # get location name and average ages location = ":".join(Results['location'].unique()) if 'average_age' in Results.columns and ages == 1: dates = Results['average_age'].unique() # go through rows and extract data for ind, row in Results.iterrows(): lat, lon = float(row['vgp_lat']), float(row['vgp_lon']) if anti == 1: lats.append(-lat) lon = lon + 180. if lon > 360: lon = lon - 360. lons.append(lon) elif flip == 0: lats.append(lat) lons.append(lon) elif flip == 1: if lat < 0: rlats.append(-lat) lon = lon + 180. if lon > 360: lon = lon - 360 rlons.append(lon) else: lats.append(lat) lons.append(lon) ppars = [] ppars.append(lon) ppars.append(lat) ell1, ell2 = "", "" if 'vgp_dm' in list(row.keys()) and row['vgp_dm']: ell1 = float(row['vgp_dm']) if 'vgp_dp' in list(row.keys()) and row['vgp_dp']: ell2 = float(row['vgp_dp']) if 'vgp_alpha95' in list(row.keys()) and row['vgp_alpha95'].notnull(): ell1, ell2 = float(row['vgp_alpha95']), float(row['vgp_alpha95']) if ell1 and ell2: ppars = [] ppars.append(lons[-1]) ppars.append(lats[-1]) ppars.append(ell1) ppars.append(lons[-1]) isign = old_div(abs(lats[-1]), lats[-1]) ppars.append(lats[-1] - isign * 90.) ppars.append(ell2) ppars.append(lons[-1] + 90.) ppars.append(0.) Pars.append(ppars) location = location.strip(':') Opts = {'latmin': -90, 'latmax': 90, 'lonmin': 0., 'lonmax': 360., 'lat_0': lat_0, 'lon_0': lon_0, 'proj': proj, 'sym': 'bs', 'symsize': 3, 'pltgrid': 0, 'res': res, 'boundinglat': 0.} Opts['details'] = {'coasts': 1, 'rivers': 0, 'states': 0, 'countries': 0, 'ocean': 1, 'fancy': fancy} # make the base map with a blue triangle at the pole pmagplotlib.plotMAP(FIG['map'], [90.], [0.], Opts) Opts['pltgrid'] = -1 Opts['sym'] = sym Opts['symsize'] = size if len(dates) > 0: Opts['names'] = dates if len(lats) > 0: # add the lats and lons of the poles pmagplotlib.plotMAP(FIG['map'], lats, lons, Opts) Opts['names'] = [] if len(rlats) > 0: Opts['sym'] = rsym Opts['symsize'] = rsize # add the lats and lons of the poles pmagplotlib.plotMAP(FIG['map'], rlats, rlons, Opts) if plot == 0: pmagplotlib.drawFIGS(FIG) if ell == 1: # add ellipses if desired. Opts['details'] = {'coasts': 0, 'rivers': 0, 'states': 0, 'countries': 0, 'ocean': 0, 'fancy': fancy} Opts['pltgrid'] = -1 # turn off meridian replotting Opts['symsize'] = 2 Opts['sym'] = 'g-' for ppars in Pars: if ppars[2] != 0: PTS = pmagplotlib.plotELL(FIG['map'], ppars, 'g.', 0, 0) elats, elons = [], [] for pt in PTS: elons.append(pt[0]) elats.append(pt[1]) # make the base map with a blue triangle at the pole pmagplotlib.plotMAP(FIG['map'], elats, elons, Opts) if plot == 0: pmagplotlib.drawFIGS(FIG) files = {} for key in list(FIG.keys()): if pmagplotlib.isServer: # use server plot naming convention files[key] = 'LO:_' + location + '_VGP_map.' + fmt else: # use more readable naming convention files[key] = '{}_VGP_map.{}'.format(location, fmt) if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles = {} titles['eq'] = 'LO:_' + location + '_VGP_map' FIG = pmagplotlib.addBorders(FIG, titles, black, purple) pmagplotlib.saveP(FIG, files) elif plot == 0: pmagplotlib.drawFIGS(FIG) ans = input(" S[a]ve to save plot, Return to quit: ") if ans == "a": pmagplotlib.saveP(FIG, files) else: print("Good bye") sys.exit() else: pmagplotlib.saveP(FIG, files)
def main(): """ NAME plotXY.py DESCRIPTION Makes simple X,Y plots INPUT FORMAT X,Y data in columns SYNTAX plotxy.py [command line options] OPTIONS -h prints this help message -f FILE to set file name on command line -c col1 col2 specify columns to plot -xsig col3 specify xsigma if desired -ysig col4 specify xsigma if desired -b xmin xmax ymin ymax, sets bounds -sym SYM SIZE specify symbol to plot: default is red dots, 10 pt -S don't plot the symbols -xlab XLAB -ylab YLAB -l connect symbols with lines -fmt [svg,png,pdf,eps] specify output format, default is svg -sav saves plot and quits -poly X plot a degree X polynomial through the data -skip n Number of lines to skip before reading in data """ fmt,plot='svg',0 col1,col2=0,1 sym,size = 'ro',50 xlab,ylab='','' lines=0 if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt=sys.argv[ind+1] if '-sav' in sys.argv:plot=1 if '-c' in sys.argv: ind=sys.argv.index('-c') col1=int(sys.argv[ind+1])-1 col2=int(sys.argv[ind+2])-1 if '-xsig' in sys.argv: ind=sys.argv.index('-xsig') col3=int(sys.argv[ind+1])-1 if '-ysig' in sys.argv: ind=sys.argv.index('-ysig') col4=int(sys.argv[ind+1])-1 if '-xlab' in sys.argv: ind=sys.argv.index('-xlab') xlab=sys.argv[ind+1] if '-ylab' in sys.argv: ind=sys.argv.index('-ylab') ylab=sys.argv[ind+1] if '-b' in sys.argv: ind=sys.argv.index('-b') xmin=float(sys.argv[ind+1]) xmax=float(sys.argv[ind+2]) ymin=float(sys.argv[ind+3]) ymax=float(sys.argv[ind+4]) if '-poly' in sys.argv: ind=sys.argv.index('-poly') degr=sys.argv[ind+1] if '-sym' in sys.argv: ind=sys.argv.index('-sym') sym=sys.argv[ind+1] size=int(sys.argv[ind+2]) if '-l' in sys.argv: lines=1 if '-S' in sys.argv: sym='' skip = int(pmag.get_named_arg_from_sys('-skip', default_val=0)) X,Y=[],[] Xerrs,Yerrs=[],[] f=open(file,'r') for num in range(skip): f.readline() data=f.readlines() for line in data: line.replace('\n','') line.replace('\t',' ') rec=line.split() X.append(float(rec[col1])) Y.append(float(rec[col2])) if '-xsig' in sys.argv:Xerrs.append(float(rec[col3])) if '-ysig' in sys.argv:Yerrs.append(float(rec[col4])) if '-poly' in sys.argv: pylab.plot(xs,ys) coeffs=numpy.polyfit(X,Y,degr) correl=numpy.corrcoef(X,Y)**2 polynomial=numpy.poly1d(coeffs) xs=numpy.linspace(numpy.min(X),numpy.max(X),10) ys=polynomial(xs) pylab.plot(xs,ys) print(polynomial) if degr=='1': print('R-square value =', '%5.4f'%(correl[0,1])) if sym!='': pylab.scatter(X,Y,marker=sym[1],c=sym[0],s=size) else: pylab.plot(X,Y) if '-xsig' in sys.argv and '-ysig' in sys.argv: pylab.errorbar(X,Y,xerr=Xerrs,yerr=Yerrs,fmt=None) if '-xsig' in sys.argv and '-ysig' not in sys.argv: pylab.errorbar(X,Y,xerr=Xerrs,fmt=None) if '-xsig' not in sys.argv and '-ysig' in sys.argv: pylab.errorbar(X,Y,yerr=Yerrs,fmt=None) if xlab!='':pylab.xlabel(xlab) if ylab!='':pylab.ylabel(ylab) if lines==1:pylab.plot(X,Y,'k-') if '-b' in sys.argv:pylab.axis([xmin,xmax,ymin,ymax]) if plot==0: pylab.show() else: pylab.savefig('plotXY.'+fmt) print('Figure saved as ','plotXY.'+fmt) sys.exit()
def main(): """ NAME agm_magic.py DESCRIPTION converts Micromag agm files to magic format SYNTAX agm_magic.py [-h] [command line options] OPTIONS -usr USER: identify user, default is "" - put in quotation marks! -bak: this is a IRM backfield curve -f FILE, specify input file, required -fsa SAMPFILE, specify er_samples.txt file relating samples, site and locations names,default is none -F MFILE, specify magic measurements formatted output file, default is agm_measurements.txt -spn SPEC, specimen name, default is base of input file name, e.g. SPECNAME.agm -spc NUM, specify number of characters to designate a specimen, default = 0 -Fsp SPECFILE : name of er_specimens.txt file for appending data to [default: er_specimens.txt] -ncn NCON,: specify naming convention: default is #1 below -syn SYN, synthetic specimen name -loc LOCNAME : specify location/study name, should have either LOCNAME or SAMPFILE (unless synthetic) -ins INST : specify which instrument was used (e.g, SIO-Maud), default is "" -u units: [cgs,SI], default is cgs Sample naming convention: [1] XXXXY: where XXXX is an arbitrary length site designation and Y is the single character sample designation. e.g., TG001a is the first sample from site TG001. [default] [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length) [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length) [4-Z] XXXX[YYY]: YYY is sample designation with Z characters from site XXX [5] site name same as sample [6] site is entered under a separate column -- NOT CURRENTLY SUPPORTED [7-Z] [XXXX]YYY: XXXX is site designation with Z characters with sample name XXXXYYYY [8] specimen is a synthetic - it has no sample, site, location information NB: all others you will have to customize your self or e-mail [email protected] for help. OUTPUT MagIC format files: magic_measurements, er_specimens, er_sample, er_site """ citation='This study' MeasRecs=[] units='cgs' meth="LP-HYS" version_num=pmag.get_version() args=sys.argv fmt='old' er_sample_name,er_site_name,er_location_name="","","" inst="" er_location_name="unknown" er_synthetic_name="" user="" er_site_name="" dir_path='.' dm=3 if "-WD" in args: ind=args.index("-WD") dir_path=args[ind+1] if "-ID" in args: ind = args.index("-ID") input_dir_path = args[ind+1] else: input_dir_path = dir_path output_dir_path = dir_path specfile = output_dir_path+'/er_specimens.txt' output = output_dir_path+"/agm_measurements.txt" if "-h" in args: print(main.__doc__) sys.exit() if "-bak" in args: meth="LP-IRM-DCD" output = output_dir_path+"/irm_measurements.txt" if "-new" in args: fmt='new' if "-usr" in args: ind=args.index("-usr") user=args[ind+1] if '-F' in args: ind=args.index("-F") output = output_dir_path+'/'+args[ind+1] if '-f' in args: ind=args.index("-f") agm_file= input_dir_path+'/'+args[ind+1] er_specimen_name=args[ind+1].split('.')[0] else: print("agm_file field is required option") print(main.__doc__) sys.exit() if '-Fsp' in args: ind=args.index("-Fsp") specfile= output_dir_path+'/'+args[ind+1] specnum,samp_con,Z=0,'1',1 if "-spc" in args: ind=args.index("-spc") specnum=int(args[ind+1]) if specnum!=0:specnum=-specnum if "-spn" in args: ind=args.index("-spn") er_specimen_name=args[ind+1] #elif "-syn" not in args: # print "you must specify a specimen name" # sys.exit() if "-syn" in args: ind=args.index("-syn") er_synthetic_name=args[ind+1] er_specimen_name="" if "-loc" in args: ind=args.index("-loc") er_location_name=args[ind+1] if "-fsa" in args: ind=args.index("-fsa") sampfile = input_dir_path+'/'+args[ind+1] Samps,file_type=pmag.magic_read(sampfile) print('sample_file successfully read in') if "-ncn" in args: ind=args.index("-ncn") samp_con=sys.argv[ind+1] if "4" in samp_con: if "-" not in samp_con: print("option [4] must be in form 4-Z where Z is an integer") sys.exit() else: Z=samp_con.split("-")[1] samp_con="4" if "7" in samp_con: if "-" not in samp_con: print("option [7] must be in form 7-Z where Z is an integer") sys.exit() else: Z=samp_con.split("-")[1] samp_con="7" if "-ins" in args: ind=args.index("-ins") inst=args[ind+1] if "-u" in args: ind=args.index("-u") units=args[ind+1] dm = pmag.get_named_arg_from_sys("-DM", 2) ErSpecRecs,filetype=pmag.magic_read(specfile) ErSpecRec,MeasRec={},{} ErSpecRec['er_citation_names']="This study" ErSpecRec['er_specimen_name']=er_specimen_name ErSpecRec['er_synthetic_name']=er_synthetic_name if specnum!=0: ErSpecRec["er_sample_name"]=er_specimen_name[:specnum] else: ErSpecRec["er_sample_name"]=er_specimen_name if "-fsa" in args and er_synthetic_name=="": for samp in Samps: if samp["er_sample_name"] == ErSpecRec["er_sample_name"]: ErSpecRec["er_location_name"]=samp["er_location_name"] ErSpecRec["er_site_name"]=samp["er_site_name"] break elif int(samp_con)!=6 and int(samp_con)!=8: site=pmag.parse_site(ErSpecRec['er_sample_name'],samp_con,Z) ErSpecRec["er_site_name"]=site ErSpecRec["er_location_name"]=er_location_name ErSpecRec['er_scientist_mail_names']=user.strip() insert=1 for rec in ErSpecRecs: if rec['er_specimen_name']==er_specimen_name: insert=0 break if insert==1: ErSpecRecs.append(ErSpecRec) ErSpecRecs,keylist=pmag.fillkeys(ErSpecRecs) pmag.magic_write(specfile,ErSpecRecs,'er_specimens') print("specimen name put in ",specfile) f=open(agm_file,'r') Data=f.readlines() if "ASCII" not in Data[0]:fmt='new' measnum,start=1,"" if fmt=='new': # new Micromag formatted file end=2 for skip in range(len(Data)): line=Data[skip] rec=line.split() if 'Units' in line:units=rec[-1] if "Raw" in rec: start=skip+2 if "Field" in rec and "Moment" in rec and start=="": start=skip+2 break else: start = 2 end=1 for i in range(start,len(Data)-end): # skip header stuff MeasRec={} for key in list(ErSpecRec.keys()): MeasRec[key]=ErSpecRec[key] MeasRec['magic_instrument_codes']=inst MeasRec['magic_method_codes']=meth if 'er_synthetic_name' in list(MeasRec.keys()) and MeasRec['er_synthetic_name']!="": MeasRec['magic_experiment_name']=er_synthetic_name+':'+meth else: MeasRec['magic_experiment_name']=er_specimen_name+':'+meth line=Data[i] rec=line.split(',') # data comma delimited if rec[0]!='\n': if units=='cgs': field =float(rec[0])*1e-4 # convert from oe to tesla else: field =float(rec[0]) # field in tesla if meth=="LP-HYS": MeasRec['measurement_lab_field_dc']='%10.3e'%(field) MeasRec['treatment_dc_field']='' else: MeasRec['measurement_lab_field_dc']='' MeasRec['treatment_dc_field']='%10.3e'%(field) if units=='cgs': MeasRec['measurement_magn_moment']='%10.3e'%(float(rec[1])*1e-3) # convert from emu to Am^2 else: MeasRec['measurement_magn_moment']='%10.3e'%(float(rec[1])) # Am^2 MeasRec['treatment_temp']='273' # temp in kelvin MeasRec['measurement_temp']='273' # temp in kelvin MeasRec['measurement_flag']='g' MeasRec['measurement_standard']='u' MeasRec['measurement_number']='%i'%(measnum) measnum+=1 MeasRec['magic_software_packages']=version_num MeasRecs.append(MeasRec) # now we have to relabel LP-HYS method codes. initial loop is LP-IMT, minor loops are LP-M - do this in measurements_methods function if meth=='LP-HYS': recnum=0 while float(MeasRecs[recnum]['measurement_lab_field_dc'])<float(MeasRecs[recnum+1]['measurement_lab_field_dc']) and recnum+1<len(MeasRecs): # this is LP-IMAG MeasRecs[recnum]['magic_method_codes']='LP-IMAG' MeasRecs[recnum]['magic_experiment_name']=MeasRecs[recnum]['er_specimen_name']+":"+'LP-IMAG' recnum+=1 # if int(dm)==2: pmag.magic_write(output,MeasRecs,'magic_measurements') else: print ('MagIC 3 is not supported yet') sys.exit() pmag.magic_write(output,MeasRecs,'measurements') print("results put in ", output)
def main(): """ NAME mk_redo.py DESCRIPTION Makes thellier_redo and zeq_redo files from existing pmag_specimens format file SYNTAX mk_redo.py [-h] [command line options] INPUT takes specimens.txt formatted input file OPTIONS -h: prints help message and quits -f FILE: specify input file, default is 'specimens.txt' -F REDO: specify output file suffix, default is redo so that output filenames are 'thellier_redo' for thellier data and 'zeq_redo' for direction only data OUTPUT makes a thellier_redo or a zeq_redo format file """ if '-h' in sys.argv: print(main.__doc__) sys.exit() zfile, tfile = 'zeq_redo', 'thellier_redo' zredo, tredo = "", "" dir_path = pmag.get_named_arg_from_sys('-WD', '.') inspec = pmag.get_named_arg_from_sys('-f', 'specimens.txt') if '-F' in sys.argv: ind = sys.argv.index('-F') redo = sys.argv[ind + 1] tfile = redo zfile = redo inspec = pmag.resolve_file_name(inspec, dir_path) zfile = pmag.resolve_file_name(zfile, dir_path) tfile = pmag.resolve_file_name(tfile, dir_path) # # read in data # specs = [] prior_spec_data, file_type = pmag.magic_read(inspec) if file_type != 'specimens': print(file_type, " this is not a valid pmag_specimens file") sys.exit() outstrings = [] for spec in prior_spec_data: tmp = spec["method_codes"].split(":") meths = [] for meth in tmp: methods = meth.strip().split('-') for m in methods: if m not in meths: meths.append(m) if 'DIR' in meths: # DE-BFL, DE-BFP or DE-FM specs.append(spec['specimen']) if 'dir_comp' in list(spec.keys( )) and spec['dir_comp'] != "" and spec['dir_comp'] != " ": comp_name = spec['dir_comp'] else: comp_name = string.ascii_uppercase[ specs.count(spec['specimen']) - 1] calculation_type = "DE-BFL" # assume default calculation type is best-fit line if "BFP" in meths: calculation_type = 'DE-BFP' elif "FM" in meths: calculation_type = 'DE-FM' if zredo == "": zredo = open(zfile, "w") outstring = '%s %s %s %s %s \n' % ( spec["specimen"], calculation_type, spec["meas_step_min"], spec["meas_step_max"], comp_name) if outstring not in outstrings: zredo.write(outstring) outstrings.append(outstring) # only writes unique interpretions elif "PI" in meths and "TRM" in meths: # thellier record if tredo == "": tredo = open(tfile, "w") outstring = '%s %i %i \n' % (spec["specimen"], float(spec["meas_step_min"]), float(spec["meas_step_max"])) if outstring not in outstrings: tredo.write(outstring) outstrings.append(outstring) # only writes unique interpretions print('Redo files saved to: ', zfile, tfile)
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
def main(): """ NAME eqarea_magic.py DESCRIPTION makes equal area projections from declination/inclination data SYNTAX eqarea_magic.py [command line options] INPUT takes magic formatted sites, samples, specimens, or measurements OPTIONS -h prints help message and quits -f FILE: specify input magic format file from magic, default='sites.txt' supported types=[measurements, specimens, samples, sites] -fsp FILE: specify specimen file name, (required if you want to plot measurements by sample) default='specimens.txt' -fsa FILE: specify sample file name, (required if you want to plot specimens by site) default='samples.txt' -fsi FILE: specify site file name, default='sites.txt' -obj OBJ: specify level of plot [all, sit, sam, spc], default is all -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted default is geographic, unspecified assumed geographic -fmt [svg,png,jpg] format for output plots -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors -c plot as colour contour -sav save plot and quit quietly NOTE all: entire file; sit: site; sam: sample; spc: specimen """ # initialize some default variables FIG = {} # plot dictionary FIG['eqarea'] = 1 # eqarea is figure 1 plotE = 0 plt = 0 # default to not plotting verbose = pmagplotlib.verbose # extract arguments from sys.argv if '-h' in sys.argv: print(main.__doc__) sys.exit() dir_path = pmag.get_named_arg_from_sys("-WD", default_val=os.getcwd()) pmagplotlib.plot_init(FIG['eqarea'],5,5) in_file = pmag.get_named_arg_from_sys("-f", default_val="sites.txt") full_in_file = os.path.join(dir_path, in_file) plot_by = pmag.get_named_arg_from_sys("-obj", default_val="all").lower() 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") if plot_by == 'all': plot_key = 'all' elif plot_by == 'sit': plot_key = 'site' elif plot_by == 'sam': plot_key = 'sample' elif plot_by == 'spc': plot_key = 'specimen' else: plot_key = 'all' if '-c' in sys.argv: contour = 1 else: contour = 0 if '-sav' in sys.argv: plt = 1 verbose = 0 if '-ell' in sys.argv: plotE = 1 ind = sys.argv.index('-ell') ell_type = sys.argv[ind+1] ell_type = pmag.get_named_arg_from_sys("-ell", "F") dist = ell_type.upper() # if dist type is unrecognized, use Fisher if dist not in ['F', 'K', 'B', 'BE', 'BV']: dist = 'F' if dist == "BV": FIG['bdirs'] = 2 pmagplotlib.plot_init(FIG['bdirs'],5,5) crd = pmag.get_named_arg_from_sys("-crd", default_val="g") if crd == "s": coord = "-1" elif crd == "t": coord = "100" else: coord = "0" fmt = pmag.get_named_arg_from_sys("-fmt", "svg") dec_key = 'dir_dec' inc_key = 'dir_inc' tilt_key = 'dir_tilt_correction' #Dir_type_keys=['','site_direction_type','sample_direction_type','specimen_direction_type'] # fnames = {"specimens": spec_file, "samples": samp_file, 'sites': site_file} contribution = nb.Contribution(dir_path, custom_filenames=fnames, single_file=in_file) # the object that contains the DataFrame + useful helper methods: table_name = list(contribution.tables.keys())[0] data_container = contribution.tables[table_name] # the actual DataFrame: data = data_container.df # uses sample infile to add temporary site_name # column to the specimen table data_container = contribution.tables[table_name] data = data_container.df if (plot_key != "all") and (plot_key not in data.columns): contribution.propagate_location_to_measurements() contribution.propagate_location_to_specimens() # add tilt key into DataFrame columns if it isn't there already if tilt_key not in data.columns: data.loc[:, tilt_key] = None if verbose: print(len(data), ' records read from ', in_file) # find desired dec,inc data: dir_type_key = '' # # get plotlist if not plotting all records # plotlist=[] if plot_key != "all": # return all where plot_key is not blank if plot_key not in data.columns: print('Can\'t plot by "{}". That header is not in infile: {}'.format(plot_key, in_file)) return plots = data[data[plot_key].notnull()] plotlist = plots[plot_key].unique() # grab unique values else: plotlist.append('All') for plot in plotlist: if verbose: print(plot) if plot == 'All': # plot everything at once plot_data = data else: # pull out only partial data plot_data = data[data[plot_key] == plot] DIblock = [] GCblock = [] # SLblock, SPblock = [], [] title = plot mode = 1 k = 0 if dec_key not in plot_data.columns: print("-W- No dec/inc data") continue # get all records where dec & inc values exist plot_data = plot_data[plot_data[dec_key].notnull() & plot_data[inc_key].notnull()] if plot_data.empty: continue # this sorting out is done in get_di_bock #if coord == '0': # geographic, use records with no tilt key (or tilt_key 0) # cond1 = plot_data[tilt_key].fillna('') == coord # cond2 = plot_data[tilt_key].isnull() # plot_data = plot_data[cond1 | cond2] #else: # not geographic coordinates, use only records with correct tilt_key # plot_data = plot_data[plot_data[tilt_key] == coord] # get metadata for naming the plot file locations = data_container.get_name('location', df_slice=plot_data) site = data_container.get_name('site', df_slice=plot_data) sample = data_container.get_name('sample', df_slice=plot_data) specimen = data_container.get_name('specimen', df_slice=plot_data) # make sure method_codes is in plot_data if 'method_codes' not in plot_data.columns: plot_data['method_codes'] = '' # get data blocks DIblock = data_container.get_di_block(df_slice=plot_data, tilt_corr=coord, excl=['DE-BFP']) #SLblock = [[ind, row['method_codes']] for ind, row in plot_data.iterrows()] # get great circles great_circle_data = data_container.get_records_for_code('DE-BFP', incl=True, use_slice=True, sli=plot_data) if len(great_circle_data) > 0: gc_cond = great_circle_data[tilt_key] == coord GCblock = [[float(row[dec_key]), float(row[inc_key])] for ind, row in great_circle_data[gc_cond].iterrows()] #SPblock = [[ind, row['method_codes']] for ind, row in great_circle_data[gc_cond].iterrows()] if len(DIblock) > 0: if contour == 0: pmagplotlib.plotEQ(FIG['eqarea'], DIblock, title) else: pmagplotlib.plotEQcont(FIG['eqarea'], DIblock) else: pmagplotlib.plotNET(FIG['eqarea']) if len(GCblock)>0: for rec in GCblock: pmagplotlib.plotC(FIG['eqarea'], rec, 90., 'g') if len(DIblock) == 0 and len(GCblock) == 0: if verbose: print("no records for plotting") continue #sys.exit() if plotE == 1: ppars = pmag.doprinc(DIblock) # get principal directions nDIs, rDIs, npars, rpars = [], [], [], [] for rec in DIblock: angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']]) if angle>90.: rDIs.append(rec) else: nDIs.append(rec) if dist=='B': # do on whole dataset etitle="Bingham confidence ellipse" bpars=pmag.dobingham(DIblock) for key in list(bpars.keys()): if key!='n' and verbose: print(" ",key, '%7.1f'%(bpars[key])) if key=='n' and verbose: print(" ",key, ' %i'%(bpars[key])) npars.append(bpars['dec']) npars.append(bpars['inc']) npars.append(bpars['Zeta']) npars.append(bpars['Zdec']) npars.append(bpars['Zinc']) npars.append(bpars['Eta']) npars.append(bpars['Edec']) npars.append(bpars['Einc']) if dist=='F': etitle="Fisher confidence cone" if len(nDIs)>2: fpars=pmag.fisher_mean(nDIs) for key in list(fpars.keys()): if key!='n' and verbose: print(" ",key, '%7.1f'%(fpars[key])) if key=='n' and verbose: print(" ",key, ' %i'%(fpars[key])) mode+=1 npars.append(fpars['dec']) npars.append(fpars['inc']) npars.append(fpars['alpha95']) # Beta npars.append(fpars['dec']) isign=old_div(abs(fpars['inc']),fpars['inc']) npars.append(fpars['inc']-isign*90.) #Beta inc npars.append(fpars['alpha95']) # gamma npars.append(fpars['dec']+90.) # Beta dec npars.append(0.) #Beta inc if len(rDIs)>2: fpars=pmag.fisher_mean(rDIs) if verbose: print("mode ",mode) for key in list(fpars.keys()): if key!='n' and verbose: print(" ",key, '%7.1f'%(fpars[key])) if key=='n' and verbose: print(" ",key, ' %i'%(fpars[key])) mode+=1 rpars.append(fpars['dec']) rpars.append(fpars['inc']) rpars.append(fpars['alpha95']) # Beta rpars.append(fpars['dec']) isign=old_div(abs(fpars['inc']),fpars['inc']) rpars.append(fpars['inc']-isign*90.) #Beta inc rpars.append(fpars['alpha95']) # gamma rpars.append(fpars['dec']+90.) # Beta dec rpars.append(0.) #Beta inc if dist=='K': etitle="Kent confidence ellipse" if len(nDIs)>3: kpars=pmag.dokent(nDIs,len(nDIs)) if verbose: print("mode ",mode) for key in list(kpars.keys()): if key!='n' and verbose: print(" ",key, '%7.1f'%(kpars[key])) if key=='n' and verbose: print(" ",key, ' %i'%(kpars[key])) mode+=1 npars.append(kpars['dec']) npars.append(kpars['inc']) npars.append(kpars['Zeta']) npars.append(kpars['Zdec']) npars.append(kpars['Zinc']) npars.append(kpars['Eta']) npars.append(kpars['Edec']) npars.append(kpars['Einc']) if len(rDIs)>3: kpars=pmag.dokent(rDIs,len(rDIs)) if verbose: print("mode ",mode) for key in list(kpars.keys()): if key!='n' and verbose: print(" ",key, '%7.1f'%(kpars[key])) if key=='n' and verbose: print(" ",key, ' %i'%(kpars[key])) mode+=1 rpars.append(kpars['dec']) rpars.append(kpars['inc']) rpars.append(kpars['Zeta']) rpars.append(kpars['Zdec']) rpars.append(kpars['Zinc']) rpars.append(kpars['Eta']) rpars.append(kpars['Edec']) rpars.append(kpars['Einc']) else: # assume bootstrap if dist=='BE': if len(nDIs)>5: BnDIs=pmag.di_boot(nDIs) Bkpars=pmag.dokent(BnDIs,1.) if verbose: print("mode ",mode) for key in list(Bkpars.keys()): if key!='n' and verbose: print(" ",key, '%7.1f'%(Bkpars[key])) if key=='n' and verbose: print(" ",key, ' %i'%(Bkpars[key])) mode+=1 npars.append(Bkpars['dec']) npars.append(Bkpars['inc']) npars.append(Bkpars['Zeta']) npars.append(Bkpars['Zdec']) npars.append(Bkpars['Zinc']) npars.append(Bkpars['Eta']) npars.append(Bkpars['Edec']) npars.append(Bkpars['Einc']) if len(rDIs)>5: BrDIs=pmag.di_boot(rDIs) Bkpars=pmag.dokent(BrDIs,1.) if verbose: print("mode ",mode) for key in list(Bkpars.keys()): if key!='n' and verbose: print(" ",key, '%7.1f'%(Bkpars[key])) if key=='n' and verbose: print(" ",key, ' %i'%(Bkpars[key])) mode+=1 rpars.append(Bkpars['dec']) rpars.append(Bkpars['inc']) rpars.append(Bkpars['Zeta']) rpars.append(Bkpars['Zdec']) rpars.append(Bkpars['Zinc']) rpars.append(Bkpars['Eta']) rpars.append(Bkpars['Edec']) rpars.append(Bkpars['Einc']) etitle="Bootstrapped confidence ellipse" elif dist=='BV': sym={'lower':['o','c'],'upper':['o','g'],'size':3,'edgecolor':'face'} if len(nDIs)>5: BnDIs=pmag.di_boot(nDIs) pmagplotlib.plotEQsym(FIG['bdirs'],BnDIs,'Bootstrapped Eigenvectors', sym) if len(rDIs)>5: BrDIs=pmag.di_boot(rDIs) if len(nDIs)>5: # plot on existing plots pmagplotlib.plotDIsym(FIG['bdirs'],BrDIs,sym) else: pmagplotlib.plotEQ(FIG['bdirs'],BrDIs,'Bootstrapped Eigenvectors') if dist=='B': if len(nDIs)> 3 or len(rDIs)>3: pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],npars,0) elif len(nDIs)>3 and dist!='BV': pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],npars,0) if len(rDIs)>3: pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],rpars,0) elif len(rDIs)>3 and dist!='BV': pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],rpars,0) for key in list(FIG.keys()): files = {} filename = pmag.get_named_arg_from_sys('-fname') if filename: # use provided filename filename+= '.' + fmt elif pmagplotlib.isServer: # use server plot naming convention filename='LO:_'+locations+'_SI:_'+site+'_SA:_'+sample+'_SP:_'+specimen+'_CO:_'+crd+'_TY:_'+key+'_.'+fmt else: # use more readable naming convention filename = '' for item in [locations, site, sample, specimen, crd, key]: if item: item = item.replace(' ', '_') filename += item + '_' if filename.endswith('_'): filename = filename[:-1] filename += ".{}".format(fmt) files[key]=filename if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['eq']='Equal Area Plot' FIG = pmagplotlib.addBorders(FIG,titles,black,purple) pmagplotlib.saveP(FIG,files) if plt: pmagplotlib.saveP(FIG,files) continue if verbose: pmagplotlib.drawFIGS(FIG) ans=input(" S[a]ve to save plot, [q]uit, Return to continue: ") if ans == "q": sys.exit() if ans == "a": pmagplotlib.saveP(FIG,files) continue
def main(): """ NAME plotXY.py DESCRIPTION Makes simple X,Y plots INPUT FORMAT X,Y data in columns SYNTAX plotxy.py [command line options] OPTIONS -h prints this help message -f FILE to set file name on command line -c col1 col2 specify columns to plot -xsig col3 specify xsigma if desired -ysig col4 specify xsigma if desired -b xmin xmax ymin ymax, sets bounds -sym SYM SIZE specify symbol to plot: default is red dots, 10 pt -S don't plot the symbols -xlab XLAB -ylab YLAB -l connect symbols with lines -fmt [svg,png,pdf,eps] specify output format, default is svg -sav saves plot and quits -poly X plot a degree X polynomial through the data -skip n Number of lines to skip before reading in data """ fmt, plot = "svg", 0 col1, col2 = 0, 1 sym, size = "ro", 50 xlab, ylab = "", "" lines = 0 if "-h" in sys.argv: print main.__doc__ sys.exit() if "-f" in sys.argv: ind = sys.argv.index("-f") file = sys.argv[ind + 1] if "-fmt" in sys.argv: ind = sys.argv.index("-fmt") fmt = sys.argv[ind + 1] if "-sav" in sys.argv: plot = 1 if "-c" in sys.argv: ind = sys.argv.index("-c") col1 = int(sys.argv[ind + 1]) - 1 col2 = int(sys.argv[ind + 2]) - 1 if "-xsig" in sys.argv: ind = sys.argv.index("-xsig") col3 = int(sys.argv[ind + 1]) - 1 if "-ysig" in sys.argv: ind = sys.argv.index("-ysig") col4 = int(sys.argv[ind + 1]) - 1 if "-xlab" in sys.argv: ind = sys.argv.index("-xlab") xlab = sys.argv[ind + 1] if "-ylab" in sys.argv: ind = sys.argv.index("-ylab") ylab = sys.argv[ind + 1] if "-b" in sys.argv: ind = sys.argv.index("-b") xmin = float(sys.argv[ind + 1]) xmax = float(sys.argv[ind + 2]) ymin = float(sys.argv[ind + 3]) ymax = float(sys.argv[ind + 4]) if "-poly" in sys.argv: ind = sys.argv.index("-poly") degr = sys.argv[ind + 1] if "-sym" in sys.argv: ind = sys.argv.index("-sym") sym = sys.argv[ind + 1] size = int(sys.argv[ind + 2]) if "-l" in sys.argv: lines = 1 if "-S" in sys.argv: sym = "" skip = int(pmag.get_named_arg_from_sys("-skip", default_val=0)) X, Y = [], [] Xerrs, Yerrs = [], [] f = open(file, "rU") for num in range(skip): f.readline() data = f.readlines() for line in data: line.replace("\n", "") line.replace("\t", " ") rec = line.split() X.append(float(rec[col1])) Y.append(float(rec[col2])) if "-xsig" in sys.argv: Xerrs.append(float(rec[col3])) if "-ysig" in sys.argv: Yerrs.append(float(rec[col4])) if "-poly" in sys.argv: pylab.plot(xs, ys) coeffs = numpy.polyfit(X, Y, degr) correl = numpy.corrcoef(X, Y) ** 2 polynomial = numpy.poly1d(coeffs) xs = numpy.linspace(numpy.min(X), numpy.max(X), 10) ys = polynomial(xs) pylab.plot(xs, ys) print polynomial if degr == "1": print "R-square value =", "%5.4f" % (correl[0, 1]) if sym != "": pylab.scatter(X, Y, marker=sym[1], c=sym[0], s=size) else: pylab.plot(X, Y) if "-xsig" in sys.argv and "-ysig" in sys.argv: pylab.errorbar(X, Y, xerr=Xerrs, yerr=Yerrs, fmt=None) if "-xsig" in sys.argv and "-ysig" not in sys.argv: pylab.errorbar(X, Y, xerr=Xerrs, fmt=None) if "-xsig" not in sys.argv and "-ysig" in sys.argv: pylab.errorbar(X, Y, yerr=Yerrs, fmt=None) if xlab != "": pylab.xlabel(xlab) if ylab != "": pylab.ylabel(ylab) if lines == 1: pylab.plot(X, Y, "k-") if "-b" in sys.argv: pylab.axis([xmin, xmax, ymin, ymax]) if plot == 0: pylab.show() else: pylab.savefig("plotXY." + fmt) print "Figure saved as ", "plotXY." + fmt sys.exit()
def main(): """ NAME vgpmap_magic.py DESCRIPTION makes a map of vgps and a95/dp,dm for site means in a sites table SYNTAX vgpmap_magic.py [command line options] OPTIONS -h prints help and quits -eye ELAT ELON [specify eyeball location], default is 90., 0. -f FILE sites format file, [default is sites.txt] -res [c,l,i,h] specify resolution (crude, low, intermediate, high] -etp plot the etopo20 topographpy data (requires high resolution data set) -prj PROJ, specify one of the following: ortho = orthographic lcc = lambert conformal moll = molweide merc = mercator -sym SYM SIZE: choose a symbol and size, examples: ro 5 : small red circles bs 10 : intermediate blue squares g^ 20 : large green triangles -ell plot dp/dm or a95 ellipses -rev RSYM RSIZE : flip reverse poles to normal antipode -S: plot antipodes of all poles -age : plot the ages next to the poles -crd [g,t] : choose coordinate system, default is to plot all site VGPs -fmt [pdf, png, eps...] specify output format, default is pdf -sav save and quit DEFAULTS FILE: pmag_results.txt res: c prj: ortho ELAT,ELON = 0,0 SYM SIZE: ro 8 RSYM RSIZE: g^ 8 """ if "-h" in sys.argv: print main.__doc__ sys.exit() dir_path = pmag.get_named_arg_from_sys("-WD", ".") # plot: default is 0, if -sav in sys.argv should be 1 plot = pmag.get_flag_arg_from_sys("-sav", true=1, false=0) fmt = pmag.get_named_arg_from_sys("-fmt", "pdf") res = pmag.get_named_arg_from_sys("-res", "c") proj = pmag.get_named_arg_from_sys("-prj", "ortho") anti = pmag.get_flag_arg_from_sys("-S", true=1, false=0) fancy = pmag.get_flag_arg_from_sys("-etp", true=1, false=0) ell = pmag.get_flag_arg_from_sys("-ell", true=1, false=0) ages = pmag.get_flag_arg_from_sys("-age", true=1, false=0) if "-rev" in sys.argv: flip = 1 ind = sys.argv.index("-rev") rsym = sys.argv[ind + 1] rsize = int(sys.argv[ind + 2]) else: flip, rsym, rsize = 0, "g^", 8 if "-sym" in sys.argv: ind = sys.argv.index("-sym") sym = sys.argv[ind + 1] size = int(sys.argv[ind + 2]) else: sym, size = "ro", 8 if "-eye" in sys.argv: ind = sys.argv.index("-eye") lat_0 = float(sys.argv[ind + 1]) lon_0 = float(sys.argv[ind + 2]) else: lat_0, lon_0 = 90.0, 0.0 crd = pmag.get_named_arg_from_sys("-crd", "") coord_dict = {"g": 0, "t": 100} coord = coord_dict[crd] if crd else "" results_file = pmag.get_named_arg_from_sys("-f", "sites.txt") con = nb.Contribution(dir_path, single_file=results_file) if not con.tables.keys(): print "-W - Couldn't read in data" return FIG = {"map": 1} pmagplotlib.plot_init(FIG["map"], 6, 6) # read in er_sites file lats, lons = [], [] Pars = [] dates, rlats, rlons = [], [], [] site_container = con.tables["sites"] site_df = site_container.df # use individual results site_df = site_df[site_df["result_type"] == "i"] # use records with vgp_lat and vgp_lon cond1, cond2 = site_df["vgp_lat"].notnull(), site_df["vgp_lon"].notnull() Results = site_df[cond1 & cond2] # use tilt correction if coord and "dir_tilt_correction" in Results.columns: Results = Results[Results["dir_tilt_correction"] == coord] # get location name and average ages location = ":".join(Results["location"].unique()) if "average_age" in Results.columns and ages == 1: dates = Results["average_age"].unique() # go through rows and extract data for ind, row in Results.iterrows(): lat, lon = float(row["vgp_lat"]), float(row["vgp_lon"]) if anti == 1: lats.append(-lat) lon = lon + 180.0 if lon > 360: lon = lon - 360.0 lons.append(lon) elif flip == 0: lats.append(lat) lons.append(lon) elif flip == 1: if lat < 0: rlats.append(-lat) lon = lon + 180.0 if lon > 360: lon = lon - 360 rlons.append(lon) else: lats.append(lat) lons.append(lon) ppars = [] ppars.append(lon) ppars.append(lat) ell1, ell2 = "", "" if "vgp_dm" in row.keys() and row["vgp_dm"]: ell1 = float(row["vgp_dm"]) if "vgp_dp" in row.keys() and row["vgp_dp"]: ell2 = float(row["vgp_dp"]) if "vgp_alpha95" in row.keys() and row["vgp_alpha95"].notnull(): ell1, ell2 = float(row["vgp_alpha95"]), float(row["vgp_alpha95"]) if ell1 and ell2: ppars = [] ppars.append(lons[-1]) ppars.append(lats[-1]) ppars.append(ell1) ppars.append(lons[-1]) isign = abs(lats[-1]) / lats[-1] ppars.append(lats[-1] - isign * 90.0) ppars.append(ell2) ppars.append(lons[-1] + 90.0) ppars.append(0.0) Pars.append(ppars) location = location.strip(":") Opts = { "latmin": -90, "latmax": 90, "lonmin": 0.0, "lonmax": 360.0, "lat_0": lat_0, "lon_0": lon_0, "proj": proj, "sym": "bs", "symsize": 3, "pltgrid": 0, "res": res, "boundinglat": 0.0, } Opts["details"] = {"coasts": 1, "rivers": 0, "states": 0, "countries": 0, "ocean": 1, "fancy": fancy} # make the base map with a blue triangle at the pole pmagplotlib.plotMAP(FIG["map"], [90.0], [0.0], Opts) Opts["pltgrid"] = -1 Opts["sym"] = sym Opts["symsize"] = size if len(dates) > 0: Opts["names"] = dates if len(lats) > 0: # add the lats and lons of the poles pmagplotlib.plotMAP(FIG["map"], lats, lons, Opts) Opts["names"] = [] if len(rlats) > 0: Opts["sym"] = rsym Opts["symsize"] = rsize # add the lats and lons of the poles pmagplotlib.plotMAP(FIG["map"], rlats, rlons, Opts) if plot == 0: pmagplotlib.drawFIGS(FIG) if ell == 1: # add ellipses if desired. Opts["details"] = {"coasts": 0, "rivers": 0, "states": 0, "countries": 0, "ocean": 0, "fancy": fancy} Opts["pltgrid"] = -1 # turn off meridian replotting Opts["symsize"] = 2 Opts["sym"] = "g-" for ppars in Pars: if ppars[2] != 0: PTS = pmagplotlib.plotELL(FIG["map"], ppars, "g.", 0, 0) elats, elons = [], [] for pt in PTS: elons.append(pt[0]) elats.append(pt[1]) # make the base map with a blue triangle at the pole pmagplotlib.plotMAP(FIG["map"], elats, elons, Opts) if plot == 0: pmagplotlib.drawFIGS(FIG) files = {} for key in FIG.keys(): files[key] = "LO:_" + location + "_VGP_map." + fmt if pmagplotlib.isServer: black = "#000000" purple = "#800080" titles = {} titles["eq"] = "LO:_" + location + "_VGP_map" FIG = pmagplotlib.addBorders(FIG, titles, black, purple) pmagplotlib.saveP(FIG, files) elif plot == 0: pmagplotlib.drawFIGS(FIG) ans = raw_input(" S[a]ve to save plot, Return to quit: ") if ans == "a": pmagplotlib.saveP(FIG, files) else: print "Good bye" sys.exit() else: pmagplotlib.saveP(FIG, files)
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_from_sys("-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_from_sys("-f", 'measurements.txt') else: in_file = pmag.get_named_arg_from_sys("-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_from_sys("-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 = nb.Contribution(dir_path) meas_df = con.propagate_location_to_measurements() 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)) con.write_table_to_file('measurements') # read in data 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 = [] 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.plotMT(FIG['exp'], INTblock, title, 0, units, norm) files = {} for key in list(FIG.keys()): files[key] = title + '_' + LP + '.' + fmt if plot == 0: pmagplotlib.drawFIGS(FIG) ans = 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'])
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'])