def main(): """ NAME chi_magic.py DESCRIPTION plots magnetic susceptibility as a function of frequency and temperature and AC field SYNTAX chi_magic.py [command line options] OPTIONS -h prints help message and quits -f FILE, specify measurements format file, default "measurements.txt" -T IND, specify temperature step to plot -- NOT IMPLEMENTED -e EXP, specify experiment name to plot -fmt [svg,jpg,png,pdf] set figure format [default is svg] -sav save figure and quit """ if "-h" in sys.argv: print(main.__doc__) return infile = pmag.get_named_arg("-f", "measurements.txt") dir_path = pmag.get_named_arg("-WD", ".") infile = pmag.resolve_file_name(infile, dir_path) fmt = pmag.get_named_arg("-fmt", "svg") save_plots = False interactive = True if "-sav" in sys.argv: interactive = False save_plots = True experiments = pmag.get_named_arg("-e", "") ipmag.chi_magic(infile, dir_path, experiments, fmt, save_plots, interactive)
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('-f', 'pmag_results.txt') crit_file = pmag.get_named_arg('-fcr', '') spec_file = pmag.get_named_arg('-fsp', '') age_file = pmag.get_named_arg('-fa', '') grade = pmag.get_flag_arg_from_sys('-g') latex = pmag.get_flag_arg_from_sys('-tex') WD = pmag.get_named_arg('-WD', os.getcwd()) ipmag.pmag_results_extract(res_file, crit_file, spec_file, age_file, latex, grade, WD)
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, default svg -sav saves plots and quits quietly """ args = sys.argv if "-h" in args: print(main.__doc__) sys.exit() dir_path = pmag.get_named_arg('-WD', '.') fmt = pmag.get_named_arg('-fmt', 'svg') save_plots = False interactive = True if '-sav' in sys.argv: save_plots = True interactive = False infile = pmag.get_named_arg("-f", "specimens.txt") ipmag.dayplot_magic(dir_path, infile, save=save_plots, fmt=fmt, interactive=interactive)
def main(): """ NAME zeq_magic.py DESCRIPTION reads in a MagIC measurements formatted file, makes plots of remanence decay during demagnetization experiments. Reads in prior interpretations saved in a specimens formatted file interpretations in a specimens file. interpretations are saved in the coordinate system used. 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 """ if '-h' in sys.argv: print(main.__doc__) return dir_path = pmag.get_named_arg("-WD", default_val=os.getcwd()) meas_file = pmag.get_named_arg("-f", default_val="measurements.txt") spec_file = pmag.get_named_arg("-fsp", default_val="specimens.txt") specimen = pmag.get_named_arg("-spc", default_val="") samp_file = pmag.get_named_arg("-fsa", default_val="samples.txt") site_file = pmag.get_named_arg("-fsi", default_val="sites.txt") plot_file = pmag.get_named_arg("-Fp", default_val="") crd = pmag.get_named_arg("-crd", default_val="s") fmt = pmag.get_named_arg("-fmt", "svg") specimen = pmag.get_named_arg("-spc", default_val="") interactive = True save_plots = False if "-sav" in sys.argv: interactive = False save_plots = True ipmag.zeq_magic(meas_file, spec_file, crd, dir_path, n_plots="all", save_plots=save_plots, fmt=fmt, interactive=interactive, specimen=specimen)
def main(): """ NAME histplot.py DESCRIPTION makes histograms for data OPTIONS -h prints help message and quits -f input file name -b binsize -fmt [svg,png,pdf,eps,jpg] specify format for image, default is svg -sav save figure and quit -F output file name, default is hist.fmt -N don't normalize -twin plot both normalized and un-normalized y axes -xlab Label of X axis -ylab Label of Y axis INPUT FORMAT single variable SYNTAX histplot.py [command line options] [<file] """ interactive = True save_plots = False if '-sav' in sys.argv: save_plots = True interactive = False if '-h' in sys.argv: print(main.__doc__) sys.exit() fmt = pmag.get_named_arg('-fmt', 'svg') fname = pmag.get_named_arg('-f', '') outfile = pmag.get_named_arg("-F", "") norm = 1 if '-N' in sys.argv: norm = 0 if '-twin' in sys.argv: norm = -1 binsize = pmag.get_named_arg('-b', 0) if '-xlab' in sys.argv: ind = sys.argv.index('-xlab') xlab = sys.argv[ind + 1] else: xlab = 'x' data = [] if not fname: print('-I- Trying to read from stdin... <ctrl>-c to quit') data = np.loadtxt(sys.stdin, dtype=np.float) ipmag.histplot(fname, data, outfile, xlab, binsize, norm, fmt, save_plots, interactive)
def main(): """ NAME histplot.py DESCRIPTION makes histograms for data OPTIONS -h prints help message and quits -f input file name -b binsize -fmt [svg,png,pdf,eps,jpg] specify format for image, default is svg -sav save figure and quit -F output file name, default is hist.fmt -N don't normalize -twin plot both normalized and un-normalized y axes -xlab Label of X axis -ylab Label of Y axis INPUT FORMAT single variable SYNTAX histplot.py [command line options] [<file] """ interactive = True save_plots = False if '-sav' in sys.argv: save_plots = True interactive = False if '-h' in sys.argv: print(main.__doc__) sys.exit() fmt = pmag.get_named_arg('-fmt', 'svg') fname = pmag.get_named_arg('-f', '') outfile = pmag.get_named_arg("-F", "") norm = 1 if '-N' in sys.argv: norm = 0 if '-twin' in sys.argv: norm = - 1 binsize = pmag.get_named_arg('-b', 0) if '-xlab' in sys.argv: ind = sys.argv.index('-xlab') xlab = sys.argv[ind+1] else: xlab = 'x' data = [] if not fname: print('-I- Trying to read from stdin... <ctrl>-c to quit') data = np.loadtxt(sys.stdin, dtype=np.float) ipmag.histplot(fname, data, outfile, xlab, binsize, norm, fmt, save_plots, interactive)
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 a file downloaded from the MagIC database (http://earthref.org/MagIC) OPTIONS -h prints help message and quits -i allows interactive entry of filename -f FILE specifies input file name -sep write location data to separate subdirectories (Location_*), (default False) -O do not overwrite duplicate Location_* directories while downloading -DM data model (2 or 3, default 3) """ 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 = input("Magic txt file for unpacking? ") dir_path = '.' input_dir_path = '.' # non-interactive else: infile = pmag.get_named_arg("-f", reqd=True) # if -O flag is present, overwrite is False overwrite = pmag.get_flag_arg_from_sys("-O", true=False, false=True) # if -sep flag is present, sep is True sep = pmag.get_flag_arg_from_sys("-sep", true=True, false=False) data_model = pmag.get_named_arg("-DM", default_val=3, reqd=False) dir_path = pmag.get_named_arg("-WD", default_val=".", reqd=False) input_dir_path = pmag.get_named_arg("-ID", default_val=".", reqd=False) #if '-ID' not in sys.argv and '-WD' in sys.argv: # input_dir_path = dir_path if "-WD" not in sys.argv and "-ID" not in sys.argv: input_dir_path = os.path.split(infile)[0] if not input_dir_path: input_dir_path = "." ipmag.download_magic(infile, dir_path, input_dir_path, overwrite, True, data_model, sep)
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 a file downloaded from the MagIC database (http://earthref.org/MagIC) OPTIONS -h prints help message and quits -i allows interactive entry of filename -f FILE specifies input file name -sep write location data to separate subdirectories (Location_*), (default False) -O do not overwrite duplicate Location_* directories while downloading -DM data model (2 or 3, default 3) """ 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=input("Magic txt file for unpacking? ") dir_path = '.' input_dir_path = '.' # non-interactive else: infile = pmag.get_named_arg("-f", reqd=True) # if -O flag is present, overwrite is False overwrite = pmag.get_flag_arg_from_sys("-O", true=False, false=True) # if -sep flag is present, sep is True sep = pmag.get_flag_arg_from_sys("-sep", true=True, false=False) data_model = pmag.get_named_arg("-DM", default_val=3, reqd=False) dir_path = pmag.get_named_arg("-WD", default_val=".", reqd=False) input_dir_path = pmag.get_named_arg("-ID", default_val=".", reqd=False) #if '-ID' not in sys.argv and '-WD' in sys.argv: # input_dir_path = dir_path if "-WD" not in sys.argv and "-ID" not in sys.argv: input_dir_path = os.path.split(infile)[0] if not input_dir_path: input_dir_path = "." ipmag.download_magic(infile, dir_path, input_dir_path, overwrite, True, data_model, sep)
def main(): """ NAME zeq_magic.py DESCRIPTION reads in a MagIC measurements formatted file, makes plots of remanence decay during demagnetization experiments. Reads in prior interpretations saved in a specimens formatted file interpretations in a specimens file. interpretations are saved in the coordinate system used. 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 """ if '-h' in sys.argv: print(main.__doc__) return dir_path = pmag.get_named_arg("-WD", default_val=os.getcwd()) meas_file = pmag.get_named_arg( "-f", default_val="measurements.txt") spec_file = pmag.get_named_arg( "-fsp", default_val="specimens.txt") specimen = pmag.get_named_arg( "-spc", default_val="") samp_file = pmag.get_named_arg("-fsa", default_val="samples.txt") site_file = pmag.get_named_arg("-fsi", default_val="sites.txt") plot_file = pmag.get_named_arg("-Fp", default_val="") crd = pmag.get_named_arg("-crd", default_val="s") fmt = pmag.get_named_arg("-fmt", "svg") specimen = pmag.get_named_arg("-spc", default_val="") interactive = True save_plots = False if "-sav" in sys.argv: interactive = False save_plots = True ipmag.zeq_magic(meas_file, spec_file, crd, dir_path, n_plots="all", save_plots=save_plots, fmt=fmt, interactive=interactive, specimen=specimen)
def main(): kwargs = {} # get command line arguments if '-WD' in sys.argv: ind = sys.argv.index('-WD') kwargs['dir_path'] = sys.argv[ind+1] if '-ID' in sys.argv: ind = sys.argv.index('-ID') kwargs['input_dir_path'] = sys.argv[ind+1] if "-h" in sys.argv: help(__name__) sys.exit() if '-F' in sys.argv: ind = sys.argv.index("-F") kwargs['meas_file'] = sys.argv[ind+1] if '-Fsp' in sys.argv: ind = sys.argv.index("-Fsp") kwargs['spec_file'] = sys.argv[ind+1] if '-f' in sys.argv: ind = sys.argv.index("-f") kwargs['jr6_file'] = sys.argv[ind+1] if "-A" in sys.argv: kwargs['noave'] = True if "-lat" in sys.argv: ind = sys.argv.index("-lat") kwargs['lat'] = sys.argv[ind+1] if "-lon" in sys.argv: ind = sys.argv.index("-lon") kwargs['lon'] = sys.argv[ind+1] if "-v" in sys.argv: ind = sys.argv.index("-v") kwargs['volume'] = sys.argv[ind+1] kwargs['dc_field'] = pmag.get_named_arg('-dc', default_val=50e-6) # do conversion convert.iodp_jr6_lore(**kwargs)
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'." ) print( "However, if you are using cartopy for plotting (recommended), you do not need to run install_etopo.py." ) return try: from mpl_toolkits.basemap import basemap_datadir except: print( "-I- Some mapping utilities use the Etopo package for topography and these data sets do not come standard with the Python installation of Basemap. However, if you are using cartopy for plotting (recommended), you do not need to run install_etopo.py." ) print( "-E- Basemap does not appear to be installed, aborting program...") else: # allow user to specify what directory to find the data_files in custom_dir = pmag.get_named_arg('-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 param_argvs(inputs=None): docm = ''' NAME forc_diagram.py DESCRIPTION This is for FORC diagrams, including conventional and irregualar FORCs. OPTIONS -h prints help message and quits -f input file name -sf smooth factor -fmt [svg,png,pdf,eps,jpg] specify format for image, default is svg -sav save figure and quit INPUT FILE: the measured FORC data file must contain the line " Field Moment " before the measured data. SYNTAX forc_diagram.py -f path_to_file/file.txt [command line options] ''' fileAdres, SF = None, None if '-h' in inputs: print(docm) sys.exit(0) save = False if '-sav' in inputs: save = True fmt = pmag.get_named_arg('-fmt', "svg") fileAdres = pmag.get_named_arg('-f', reqd=True) if not os.path.isfile(fileAdres): print('-f file not exist') return SF = pmag.get_named_arg('-sf', reqd=True) try: SF = int(inputs[4]) except: print('-sf has to be int') return return fileAdres, SF, save, fmt
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() pltspec = "" verbose = pmagplotlib.verbose dir_path = pmag.get_named_arg('-WD', '.') dir_path = os.path.realpath(dir_path) meas_file = pmag.get_named_arg('-f', 'measurements.txt') fmt = pmag.get_named_arg('-fmt', 'png') save_plots = False interactive = True if '-sav' in args: verbose = False save_plots = True interactive = False if '-spc' in args: ind = args.index("-spc") pltspec = args[ind+1] verbose = False save_plots = True ipmag.quick_hyst(dir_path, meas_file, save_plots, interactive, fmt, pltspec, verbose)
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() pltspec = "" verbose = pmagplotlib.verbose dir_path = pmag.get_named_arg('-WD', '.') dir_path = os.path.realpath(dir_path) meas_file = pmag.get_named_arg('-f', 'measurements.txt') fmt = pmag.get_named_arg('-fmt', 'png') save_plots = False interactive = True if '-sav' in args: verbose = False save_plots = True interactive = False if '-spc' in args: ind = args.index("-spc") pltspec = args[ind + 1] verbose = False save_plots = True ipmag.quick_hyst(dir_path, meas_file, save_plots, interactive, fmt, pltspec, verbose)
def main(): """ Take out dos problem characters from any file """ filename = pmag.get_named_arg('-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 main(): if '-h' in sys.argv: print(" Help for move_data_files.py:") 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'" ) print( " Alternatively, you may use the full path to the directory of your choice from anywhere in the file system, using the '-d' flag: 'move_data_files.py -d /Users/***/Desktop' where *** is your username" ) print( " **IMPORTANT** If you have a developer install, move_data_files.py won't work. Simply navigate to your PmagPy directory. You can find the data_files directory and all PmagPy notebooks there." ) sys.exit() # create PmagPy-data directory dest = pmag.get_named_arg('-d', '.', False) dest = path.realpath(dest) dest = path.join(dest, 'PmagPy-data') if not path.exists(dest): try: os.mkdir(dest) except FileNotFoundError: pass # get source of data_files source = pmag.get_named_arg('-s', sys.prefix, False) source = path.realpath(source) if source.endswith('data_files') or source.endswith('data_files/'): source = path.split(source)[0] # copy data_files to PmagPy-data directory data_files = path.join(source, 'data_files') copy_directory(data_files, dest) # now try to get notebooks pmagpy_dir = find_pmag_dir.get_pmag_dir() # needs all the notebooks for notebook_location in glob.glob( path.join(source, "data_files", "PmagPy*.ipynb")): notebook_name = os.path.split(notebook_location)[1] shutil.copy(notebook_location, path.join(dest, notebook_name))
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'" ) print( "Alternatively, you may use the full path to the directory of your choice from anywhere in the file system, using the '-d' flag: 'move_data_files.py -d /Users/***/Desktop' where *** is your username" ) sys.exit() # create PmagPy-data directory dest = pmag.get_named_arg('-d', '.', False) dest = path.realpath(dest) dest = path.join(dest, 'PmagPy-data') if not path.exists(dest): try: os.mkdir(dest) except FileNotFoundError: pass # get source of data_files source = pmag.get_named_arg('-s', sys.prefix, False) source = path.realpath(source) if source.endswith('data_files') or source.endswith('data_files/'): source = path.split(source)[0] # copy data_files to PmagPy-data directory data_files = path.join(source, 'data_files') copy_directory(data_files, dest) # now try to get notebooks pmagpy_dir = find_pmag_dir.get_pmag_dir() for notebook in ['PmagPy.ipynb', 'PmagPy-cli.ipynb']: # for pip install notebook_location = path.join(dest, 'data_files', notebook) if path.exists(notebook_location): shutil.copy(path.join(dest, 'data_files', notebook), path.join(dest, notebook)) # for developer install elif pmagpy_dir: if path.exists(path.join(pmagpy_dir, notebook)): shutil.copy(path.join(pmagpy_dir, notebook), path.join(dest, notebook))
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] OPTIONS -DM NUM: MagIC data model number, default 3 -WD DIR: working directory, default current directory EXAMPLE pmag_gui.py -DM 2 -WD projects/my_old_project 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 and (not set_env.IS_FROZEN): app = wx.App(redirect=False) else: app = wx.App(redirect=True) dir_path = pmag.get_named_arg("-WD", None) data_model = pmag.get_named_arg('-DM', None) app.frame = MagMainFrame(DM=data_model, WD=dir_path) 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(): kwargs = {} if '-h' in sys.argv: help(__name__) sys.exit() # if "-WD" in sys.argv: # ind=sys.argv.index("-WD") # kwargs['wd']=sys.argv[ind+1] wd = pmag.get_named_arg('-WD', '.') kwargs['wd'] = wd if "-A" in sys.argv: kwargs['noave'] = True #convert_tdt_files_to_MagIC(wd, **kwargs) convert(**kwargs)
def main(): if '-h' in sys.argv: print(" Help for move_data_files.py:") 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'") print(" Alternatively, you may use the full path to the directory of your choice from anywhere in the file system, using the '-d' flag: 'move_data_files.py -d /Users/***/Desktop' where *** is your username") print(" **IMPORTANT** If you have a developer install, this won\'t work. Simply navigate to your PmagPy directory. You can find data_files, PmagPy.ipynb and PmagPy-cli.ipynb there.") sys.exit() # create PmagPy-data directory dest = pmag.get_named_arg('-d', '.', False) dest = path.realpath(dest) dest = path.join(dest, 'PmagPy-data') if not path.exists(dest): try: os.mkdir(dest) except FileNotFoundError: pass # get source of data_files source = pmag.get_named_arg('-s', sys.prefix, False) source = path.realpath(source) if source.endswith('data_files') or source.endswith('data_files/'): source = path.split(source)[0] # copy data_files to PmagPy-data directory data_files = path.join(source, 'data_files') copy_directory(data_files, dest) # now try to get notebooks pmagpy_dir = find_pmag_dir.get_pmag_dir() for notebook in ['PmagPy.ipynb', 'PmagPy-cli.ipynb']: # for pip install notebook_location = path.join(dest, 'data_files', notebook) if path.exists(notebook_location): shutil.copy(path.join(dest, 'data_files', notebook), path.join(dest, notebook)) # for developer install elif pmagpy_dir: if path.exists(path.join(pmagpy_dir, notebook)): shutil.copy(path.join(pmagpy_dir, notebook), path.join(dest, notebook))
def __init__(self, WD): wx.Frame.__init__(self, None, wx.ID_ANY, self.title) self.panel = wx.Panel(self) self.max_files = 10 self.WD = WD self.create_menu() self.InitUI() self.data_model_num = int(pmag.get_named_arg("-DM", 3)) if "-WD" in sys.argv: ind = sys.argv.index('-WD') self.WD = sys.argv[ind + 1] else: self.WD = "." self.WD = os.path.realpath(self.WD) os.chdir(self.WD)
def __init__(self, WD): wx.Frame.__init__(self, None, wx.ID_ANY, self.title) self.panel = wx.Panel(self) self.max_files = 10 self.WD = WD self.create_menu() self.InitUI() self.data_model_num = int(pmag.get_named_arg("-DM", 3)) if "-WD" in sys.argv: ind = sys.argv.index('-WD') self.WD = sys.argv[ind+1] else: self.WD = "." self.WD = os.path.realpath(self.WD) os.chdir(self.WD)
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] OPTIONS -WD DIR: working directory, default current directory EXAMPLE magic_gui.py -WD projects/my_project 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 and (not set_env.IS_FROZEN): app = wx.App(redirect=False) else: app = wx.App(redirect=True) working_dir = pmag.get_named_arg('-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 main(): kwargs = {} if "-h" in sys.argv: help(__name__) sys.exit() if '-WD' in sys.argv: ind = sys.argv.index("-WD") kwargs['dir_path'] = sys.argv[ind + 1] if '-ID' in sys.argv: ind = sys.argv.index('-ID') kwargs['input_dir_path'] = sys.argv[ind + 1] if "-A" in sys.argv: kwargs['noave'] = 1 if '-f' in sys.argv: ind = sys.argv.index("-f") kwargs['srm_file'] = sys.argv[ind + 1] if '-F' in sys.argv: ind = sys.argv.index("-F") kwargs['meas_file'] = sys.argv[ind + 1] if '-Fsp' in sys.argv: ind = sys.argv.index("-Fsp") kwargs['spec_file'] = sys.argv[ind + 1] if '-Fsi' in sys.argv: ind = sys.argv.index("-Fsi") kwargs['site_file'] = sys.argv[ind + 1] if '-Fsa' in sys.argv: ind = sys.argv.index("-Fsa") kwargs['samp_file'] = sys.argv[ind + 1] if '-Flo' in sys.argv: ind = sys.argv.index("-Flo") kwargs['loc_file'] = sys.argv[ind + 1] if "-lat" in sys.argv: ind = sys.argv.index("-lat") kwargs['lat'] = sys.argv[ind + 1] if "-lon" in sys.argv: ind = sys.argv.index("-lon") kwargs['lon'] = sys.argv[ind + 1] kwargs['comp_depth_key'] = pmag.get_named_arg("-key", 'Depth CSF-B (m)') # do conversion convert.iodp_srm_lore(**kwargs)
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'.") print("However, if you are using cartopy for plotting (recommended), you do not need to run install_etopo.py.") return try: from mpl_toolkits.basemap import basemap_datadir except: print("-I- Some mapping utilities use the Etopo package for topography and these data sets do not come standard with the Python installation of Basemap. However, if you are using cartopy for plotting (recommended), you do not need to run install_etopo.py.") print("-E- Basemap does not appear to be installed, aborting program...") else: # allow user to specify what directory to find the data_files in custom_dir = pmag.get_named_arg('-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(): 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] OPTIONS -DM NUM: MagIC data model number, default 3 -WD DIR: working directory, default current directory EXAMPLE pmag_gui.py -DM 2 -WD projects/my_old_project 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('-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 app = wx.App(redirect=True) working_dir = pmag.get_named_arg('-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(): """ NAME upload_magic.py DESCRIPTION This program will prepare your MagIC text files for uploading to the MagIC database 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 file: file for uploading to MagIC database """ if '-h' in sys.argv: print(main.__doc__) sys.exit() else: data_model_num = pmag.get_named_arg("-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) data_model_num = int(float(data_model_num)) if data_model_num == 2: ipmag.upload_magic2(concat, dir_path) else: ipmag.upload_magic(concat, dir_path)
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 -WD: directory to output files to (default : current directory) Note: if using Windows, all figures will output to current directory -ID: directory to read files from (default : same as -WD) -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 fmt = pmag.get_named_arg('-fmt', 'svg') output_dir_path = pmag.get_named_arg('-WD', '.') input_dir_path = pmag.get_named_arg('-ID', "") if "-h" in args: print(main.__doc__) sys.exit() meas_file = pmag.get_named_arg('-f', 'measurements.txt') spec_file = pmag.get_named_arg('-F', 'specimens.txt') make_plots = True save_plots = False if '-P' in args: make_plots = False if '-sav' in args: save_plots = True pltspec = pmag.get_named_arg('-spc', 0) ipmag.hysteresis_magic(output_dir_path, input_dir_path, spec_file, meas_file, fmt, save_plots, make_plots, pltspec)
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('-WD', '.') inspec = pmag.get_named_arg('-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 s_magic.py DESCRIPTION converts .s format data to measurements format. SYNTAX s_magic.py [command line options] OPTIONS -h prints help message and quits -DM DATA_MODEL_NUM data model number (default is 3) -f SFILE specifies the .s file name -sig last column has sigma -typ Anisotropy type: AMS,AARM,ATRM (default is AMS) -F FILE specifies the specimens formatted file name -usr USER specify username -loc location specify location/study name -spc NUM : specify number of characters to designate a specimen, default = 0 -spn SPECNAME, this specimen has the name SPECNAME -n first column has specimen name -crd [s,g,t], specify coordinate system of data s=specimen,g=geographic,t=tilt adjusted, default is 's' -ncn NCON: naming convention Sample naming convention: [1] XXXXY: where XXXX is an arbitrary length site designation and Y is the single character sample designation. e.g., TG001a is the first sample from site TG001. [default] [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length) [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length) [4-Z] XXXXYYY: YYY is sample designation with Z characters from site XXX [5] sample = site [6] sample, site, location info in er_samples.txt -- NOT CURRENTLY SUPPORTED [7-Z] [XXX]YYY: XXX is site designation with Z characters from samples XXXYYY NB: all others you will have to either customize your self or e-mail [email protected] for help. DEFAULT FILE: specimens.txt INPUT X11,X22,X33,X12,X23,X13 (.s format file) X11,X22,X33,X12,X23,X13,sigma (.s format file with -sig option) SID, X11,X22,X33,X12,X23,X13 (.s format file with -n option) OUTPUT specimens.txt format file NOTE because .s files do not have specimen names or location information, the output MagIC files will have to be changed prior to importing to data base. """ if '-h' in sys.argv: print(main.__doc__) sys.exit() data_model_num = pmag.get_named_arg("-DM", 3) data_model_num = int(float(data_model_num)) sfile = pmag.get_named_arg("-f", reqd=True) if data_model_num == 2: anisfile = pmag.get_named_arg("-F", "rmag_anisotropy.txt") else: anisfile = pmag.get_named_arg("-F", "specimens.txt") location = pmag.get_named_arg("-loc", "unknown") user = pmag.get_named_arg("-usr", "") sitename = pmag.get_named_arg("unknown", "") specnum = pmag.get_named_arg("-spc", 0) specnum = -int(specnum) dir_path = pmag.get_named_arg("-WD", ".") name = pmag.get_flag_arg_from_sys("-n") sigma = pmag.get_flag_arg_from_sys("-sig") spec = pmag.get_named_arg("-spn", "unknown") atype = pmag.get_named_arg("-typ", 'AMS') samp_con = pmag.get_named_arg("-ncn", "1") #if '-sig' in sys.argv: # sigma = 1 #if "-n" in sys.argv: # name = 1 coord_type = pmag.get_named_arg("-crd", 's') convert.s_magic(sfile, anisfile, dir_path, atype, coord_type, sigma, samp_con, specnum, location, spec, sitename, user, data_model_num, name)
def main(): """ NAME strip_magic.py DESCRIPTION plots various parameters versus depth or age SYNTAX strip_magic.py [command line optins] OPTIONS -h prints help message and quits -DM NUM: specify data model num, options 2 (legacy) or 3 (default) -f FILE: specify input magic format file from magic,default='pmag_results.txt' supported types=[pmag_specimens, pmag_samples, pmag_sites, pmag_results, magic_web] -obj [sit,sam,all]: specify object to site,sample,all for pmag_result table, default is all -fmt [svg,png,jpg], format for images - default is svg -x [age,pos]: specify whether age or stratigraphic position -y [dec,inc,int,chi,lat,lon,vdm,vadm] (lat and lon are VGP lat and lon) -Iex: plot the expected inc at lat - only available for results with lat info in file -ts TS amin amax: plot the GPTS for the time interval between amin and amax (numbers in Ma) TS: [ck95, gts04] -mcd method_code, specify method code, default is first one encountered -sav save plot and quit NOTES when x and/or y are not specified, a list of possibilities will be presented to the user for choosing """ if '-h' in sys.argv: print(main.__doc__) sys.exit() xaxis, xplotind, yplotind = "", 0, 0 # (0 for strat pos) yaxis, Xinc = "", "" plot = 0 obj = 'all' data_model_num = int(pmag.get_named_arg("-DM", 3)) # 2.5 keys if data_model_num == 2: supported = [ 'pmag_specimens', 'pmag_samples', 'pmag_sites', 'pmag_results', 'magic_web' ] # available file types Depth_keys = [ 'specimen_core_depth', 'specimen_height', 'specimen_elevation', 'specimen_composite_depth', 'sample_core_depth', 'sample_height', 'sample_elevation', 'sample_composite_depth', 'site_core_depth', 'site_height', 'site_elevation', 'site_composite_depth', 'average_height' ] Age_keys = [ 'specimen_inferred_age', 'sample_inferred_age', 'site_inferred_age', 'average_age' ] Unit_keys = { 'specimen_inferred_age': 'specimen_inferred_age_unit', 'sample_inferred_age': 'sample_inferred_age_unit', 'site_inferred_age': 'site_inferred_age_unit', 'average_age': 'average_age_unit' } Dec_keys = [ 'measurement_dec', 'specimen_dec', 'sample_dec', 'site_dec', 'average_dec' ] Inc_keys = [ 'measurement_inc', 'specimen_inc', 'sample_inc', 'site_inc', 'average_inc' ] Int_keys = [ 'measurement_magnitude', 'measurement_magn_moment', 'measurement_magn_volume', 'measurement_magn_mass', 'specimen_int', 'specimen_int_rel', 'sample_int', 'sample_int_rel', 'site_int', 'site_int_rel', 'average_int', 'average_int_rel' ] Chi_keys = ['measurement_chi_volume', 'measurement_chi_mass'] Lat_keys = ['sample_lat', 'site_lat', 'average_lat'] VLat_keys = ['vgp_lat'] VLon_keys = ['vgp_lon'] Vdm_keys = ['vdm'] Vadm_keys = ['vadm'] method_col_name = "magic_method_codes" else: # 3.0 keys supported = ["specimens", "samples", "sites", "locations"] # available file types Depth_keys = ["height", "core_depth", "elevation", "composite_depth"] Age_keys = ["age"] Unit_keys = {"age": "age"} Chi_keys = ["susc_chi_volume", "susc_chi_mass"] Int_keys = [ "magn_moment", "magn_volume", "magn_mass", "int_abs", "int_rel" ] Inc_keys = ["dir_inc"] Dec_keys = ["dir_dec"] Lat_Keys = ["lat"] VLat_keys = ["vgp_lat", "pole_lat"] VLon_keys = ["vgp_lon", "pole_lon"] Vdm_keys = ["vdm", "pdm"] Vadm_keys = ["vadm", "padm"] method_col_name = "method_codes" # X_keys = [Age_keys, Depth_keys] Y_keys = [ Dec_keys, Inc_keys, Int_keys, Chi_keys, VLat_keys, VLon_keys, Vdm_keys, Vadm_keys ] method, fmt = "", 'svg' FIG = {'strat': 1} plotexp, pTS = 0, 0 dir_path = pmag.get_named_arg("-WD", ".") # default files if data_model_num == 3: res_file = pmag.get_named_arg("-f", "sites.txt") else: res_file = pmag.get_named_arg("-f", "pmag_results.txt") res_file = pmag.resolve_file_name(res_file, dir_path) if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt = sys.argv[ind + 1] if '-obj' in sys.argv: ind = sys.argv.index('-obj') obj = sys.argv[ind + 1] if '-x' in sys.argv: ind = sys.argv.index('-x') xaxis = sys.argv[ind + 1] if '-y' in sys.argv: ind = sys.argv.index('-y') yaxis = sys.argv[ind + 1] if yaxis == 'dec': ykeys = Dec_keys if yaxis == 'inc': ykeys = Inc_keys if yaxis == 'int': ykeys = Int_keys if yaxis == 'chi': ykeys = Chi_keys if yaxis == 'lat': ykeys = VLat_keys if yaxis == 'lon': ykeys = VLon_keys if yaxis == 'vdm': ykeys = Vdm_keys if yaxis == 'vadm': ykeys = Vadm_keys if '-mcd' in sys.argv: ind = sys.argv.index('-mcd') method = sys.argv[ind + 1] if '-ts' in sys.argv: ind = sys.argv.index('-ts') ts = sys.argv[ind + 1] amin = float(sys.argv[ind + 2]) amax = float(sys.argv[ind + 3]) pTS = 1 if '-Iex' in sys.argv: plotexp = 1 if '-sav' in sys.argv: plot = 1 # # # get data read in Results, file_type = pmag.magic_read(res_file) if file_type not in supported: print("Unsupported file type ({}), try again".format(file_type)) sys.exit() PltObjs = ['all'] if data_model_num == 2: if file_type == 'pmag_results': # find out what to plot for rec in Results: resname = rec['pmag_result_name'].split() if 'Sample' in resname and 'sam' not in PltObjs: PltObjs.append('sam') if 'Site' in resname and 'sit' not in PltObjs: PltObjs.append('sit') methcodes = [] # need to know all the measurement types from method_codes if "magic_method_codes" in list(Results[0].keys()): for rec in Results: meths = rec["magic_method_codes"].split(":") for meth in meths: if meth.strip() not in methcodes and 'LP' in meth: # look for the lab treatments methcodes.append(meth.strip()) # # initialize some variables X_unit = "" # Unit for age or depth plotting (meters if depth) Xplots, Yplots = [], [] Xunits = [] yplotind, xplotind = 0, 0 # # step through possible plottable keys # if xaxis == "" or yaxis == "": for key in list(Results[0].keys()): for keys in X_keys: for xkeys in keys: if key in xkeys: for ResRec in Results: if ResRec[key] != "": # only plot something if there is something to plot! Xplots.append(key) break for keys in Y_keys: for pkeys in keys: if key in pkeys: for ResRec in Results: if ResRec[key] != "": Yplots.append(key) break X, Y = [], [] for plt in Xplots: if plt in Age_keys and 'age' not in X: X.append('age') if plt in Depth_keys and 'pos' not in X: X.append('pos') for plt in Yplots: if plt in Dec_keys and 'dec' not in Y: Y.append('dec') if plt in Inc_keys and 'inc' not in Y: Y.append('inc') if plt in Int_keys and 'int' not in Y: Y.append('int') if plt in Chi_keys and 'chi' not in Y: Y.append('chi') if plt in VLat_keys and 'lat' not in Y: Y.append('lat') if plt in VLon_keys and 'lon' not in Y: Y.append('lon') if plt in Vadm_keys and 'vadm' not in Y: Y.append('vadm') if plt in Vdm_keys and 'vdm' not in Y: Y.append('vdm') if file_type == 'pmag_results': print('available objects for plotting: ', PltObjs) print('available X plots: ', X) print('available Y plots: ', Y) print('available method codes: ', methcodes) f = open(dir_path + '/.striprc', 'w') for x in X: f.write('x:' + x + '\n') for y in Y: f.write('y:' + y + '\n') for m in methcodes: f.write('m:' + m + '\n') for obj in PltObjs: f.write('obj:' + obj + '\n') sys.exit() if plotexp == 1: for lkey in Lat_keys: for key in list(Results[0].keys()): if key == lkey: lat = float(Results[0][lkey]) Xinc = [pmag.pinc(lat), -pmag.pinc(lat)] break if Xinc == "": print('can not plot expected inc for site - lat unknown') if method != "" and method not in methcodes: print('your method not available, but these are: ') print(methcodes) print('use ', methcodes[0], '? ^D to quit') if xaxis == 'age': for akey in Age_keys: for key in list(Results[0].keys()): if key == akey: Xplots.append(key) Xunits.append(Unit_keys[key]) if xaxis == 'pos': for dkey in Depth_keys: for key in list(Results[0].keys()): if key == dkey: Xplots.append(key) if len(Xplots) == 0: print('desired X axis information not found') sys.exit() if xaxis == 'age': age_unit = Results[0][Xunits[0]] if len(Xplots) > 1: print('multiple X axis keys found, using: ', Xplots[xplotind]) for ykey in ykeys: for key in list(Results[0].keys()): if key == ykey: Yplots.append(key) if len(Yplots) == 0: print('desired Y axis information not found') sys.exit() if len(Yplots) > 1: print('multiple Y axis keys found, using: ', Yplots[yplotind]) # check if age or depth info if len(Xplots) == 0: print("Must have either age or height info to plot ") sys.exit() # # check for variable to plot # # # determine X axis (age or depth) # if xaxis == "age": plotind = "1" if method == "": try: method = methcodes[0] except IndexError: method = "" if xaxis == 'pos': xlab = "Stratigraphic Height (meters)" else: xlab = "Age (" + age_unit + ")" Xkey = Xplots[xplotind] Ykey = Yplots[yplotind] ylab = Ykey # # collect the data for plotting XY = [] isign = 1. # if float(Results[0][Xkey])/float(Results[-1][Xkey])>0 and float(Results[0][Xkey])<0: # isign=-1. # x axis all same sign and negative, take positive (e.g.,for depth in core) # xlab="Stratigraphic Position (meters)" # else: # isign=1. for rec in Results: if "magic_method_codes" in list(rec.keys()): meths = rec["magic_method_codes"].split(":") if method in meths: # make sure it is desired lab treatment step if obj == 'all' and rec[Xkey].strip() != "": XY.append([isign * float(rec[Xkey]), float(rec[Ykey])]) elif rec[Xkey].strip() != "": name = rec['pmag_result_name'].split() if obj == 'sit' and "Site" in name: XY.append([isign * float(rec[Xkey]), float(rec[Ykey])]) if obj == 'sam' and "Sample" in name: XY.append([isign * float(rec[Xkey]), float(rec[Ykey])]) elif method == "": if obj == 'all' and rec[Xkey].strip() != "": XY.append([isign * float(rec[Xkey]), float(rec[Ykey])]) elif rec[Xkey].strip() != "": name = rec['pmag_result_name'].split() if obj == 'sit' and "Site" in name: XY.append([isign * float(rec[Xkey]), float(rec[Ykey])]) if obj == 'sam' and "Sample" in name: XY.append([isign * float(rec[Xkey]), float(rec[Ykey])]) else: print("Something wrong with your plotting choices") break XY.sort() title = "" if "er_locations_names" in list(Results[0].keys()): title = Results[0]["er_location_names"] if "er_locations_name" in list(Results[0].keys()): title = Results[0]["er_location_name"] labels = [xlab, ylab, title] pmagplotlib.plot_init(FIG['strat'], 10, 5) pmagplotlib.plot_strat(FIG['strat'], XY, labels) # plot them if plotexp == 1: pmagplotlib.plot_hs(FIG['strat'], Xinc, 'b', '--') if yaxis == 'inc' or yaxis == 'lat': pmagplotlib.plot_hs(FIG['strat'], [0], 'b', '-') pmagplotlib.plot_hs(FIG['strat'], [-90, 90], 'g', '-') if pTS == 1: FIG['ts'] = 2 pmagplotlib.plot_init(FIG['ts'], 10, 5) pmagplotlib.plot_ts(FIG['ts'], [amin, amax], ts) files = {} for key in list(FIG.keys()): files[key] = key + '.' + fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' files = {} files['strat'] = xaxis + '_' + yaxis + '_.' + fmt files['ts'] = 'ts.' + fmt titles = {} titles['strat'] = 'Depth/Time Series Plot' titles['ts'] = 'Time Series Plot' FIG = pmagplotlib.add_borders(FIG, titles, black, purple) pmagplotlib.save_plots(FIG, files) elif plot == 1: pmagplotlib.save_plots(FIG, files) else: pmagplotlib.draw_figs(FIG) ans = input(" S[a]ve to save plot, [q]uit without saving: ") if ans == "a": pmagplotlib.save_plots(FIG, files)
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("-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('-WD', '.') inspec = pmag.get_named_arg('-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 chi_magic.py DESCRIPTION plots magnetic susceptibility as a function of frequency and temperature and AC field SYNTAX chi_magic.py [command line options] OPTIONS -h prints help message and quits -f FILE, specify measurements format file, default "measurements.txt" -T IND, specify temperature step to plot -e EXP, specify experiment name to plot -fmt [svg,jpg,png,pdf] set figure format [default is svg] -sav save figure and quit """ if "-h" in sys.argv: print(main.__doc__) return infile = pmag.get_named_arg("-f", "measurements.txt") dir_path = pmag.get_named_arg("-WD", ".") infile = pmag.resolve_file_name(infile, dir_path) fmt = pmag.get_named_arg("-fmt", "svg") show_plots = True if "-sav" in sys.argv: show_plots = False experiments = pmag.get_named_arg("-e", "") # read in data from data model 3 example file chi_data_all = pd.read_csv(infile, sep='\t', header=1) if not experiments: try: experiments = chi_data_all.experiment.unique() except Exception as ex: print(ex) experiments = ["all"] else: experiments = [experiments] plotnum = 0 figs = {} fnames = {} for exp in experiments: if exp == "all": chi_data = chi_data_all chi_data = chi_data_all[chi_data_all.experiment == exp] if len(chi_data) <= 1: print('Not enough data to plot {}'.format(exp)) continue plotnum += 1 pmagplotlib.plot_init(plotnum, 5, 5) # set up plot figs[str(plotnum)] = plotnum fnames[str(plotnum)] = exp + '_temperature.{}'.format(fmt) # get arrays of available temps, frequencies and fields Ts = np.sort(chi_data.meas_temp.unique()) Fs = np.sort(chi_data.meas_freq.unique()) Bs = np.sort(chi_data.meas_field_ac.unique()) # plot chi versus temperature at constant field b = Bs.max() for num, f in enumerate(Fs): this_f = chi_data[chi_data.meas_freq == f] this_f = this_f[this_f.meas_field_ac == b] plt.plot(this_f.meas_temp, 1e6*this_f.susc_chi_volume, label='%i' % (f)+' Hz') plt.legend() plt.xlabel('Temperature (K)') plt.ylabel('$\chi$ ($\mu$SI)') plt.title('B = '+'%7.2e' % (b) + ' T') plotnum += 1 figs[str(plotnum)] = plotnum fnames[str(plotnum)] = exp + '_frequency.{}'.format(fmt) pmagplotlib.plot_init(plotnum, 5, 5) # set up plot ## plot chi versus frequency at constant B b = Bs.max() t = Ts.min() this_t = chi_data[chi_data.meas_temp == t] this_t = this_t[this_t.meas_field_ac == b] plt.semilogx(this_t.meas_freq, 1e6 * this_t.susc_chi_volume, label='%i' % (t)+' K') plt.legend() plt.xlabel('Frequency (Hz)') plt.ylabel('$\chi$ ($\mu$SI)') plt.title('B = '+'%7.2e' % (b) + ' T') if show_plots: pmagplotlib.draw_figs(figs) ans = input( "enter s[a]ve to save files, [return] to quit ") if ans == 'a': pmagplotlib.save_plots(figs, fnames) sys.exit() else: sys.exit() else: pmagplotlib.save_plots(figs, fnames)
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 measurements.txt files OPTIONS -h prints help message and quits -f FILE: specify input file, default is: 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 dir_path = pmag.get_named_arg("-WD", default_val=".") input_dir_path = pmag.get_named_arg('-ID', '') if not input_dir_path: input_dir_path = dir_path in_file = pmag.get_named_arg("-f", default_val="measurements.txt") in_file = pmag.resolve_file_name(in_file, input_dir_path) if "-ID" not in sys.argv: input_dir_path = os.path.split(in_file)[0] plot_by = pmag.get_named_arg("-obj", default_val="loc") LT = pmag.get_named_arg("-LT", "AF") no_norm = pmag.get_flag_arg_from_sys("-N") norm = False if no_norm else True save_plots = pmag.get_flag_arg_from_sys("-sav") fmt = pmag.get_named_arg("-fmt", "svg") XLP = pmag.get_named_arg("-XLP", "") spec_file = pmag.get_named_arg("-fsp", default_val="specimens.txt") samp_file = pmag.get_named_arg("-fsa", default_val="samples.txt") site_file = pmag.get_named_arg("-fsi", default_val="sites.txt") loc_file = pmag.get_named_arg("-flo", default_val="locations.txt") plot(in_file, dir_path, input_dir_path, spec_file, samp_file, site_file, loc_file, plot_by, LT, norm, XLP, save_plots, fmt)
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("-DM", 0))) DM = self.data_model_num # if WD was provided: if WD: self.WD = WD else: WD = pmag.get_named_arg("-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) # if specified directory doesn't exist, try to make it try: if not os.path.exists(self.WD): os.mkdir(self.WD) pw.simple_warning("New directory: {}\nwill be created".format( self.WD)) except FileNotFoundError: pw.simple_warning( "You have provided a directory that does not exist and cannot be created.\n Please pick a different directory." ) print( "-W- You have provided a directory that does not exist and cannot be created.\n Please pick a different directory." )
def main(): """ NAME trmaq_magic.py DESCTIPTION does non-linear trm acquisisiton correction SYNTAX trmaq_magic.py [-h][-i][command line options] OPTIONS -h prints help message and quits -i allows interactive setting of file names -f MFILE, sets magic_measurements input file -ft TSPEC, sets thellier_specimens input file -F OUT, sets output for non-linear TRM acquisition corrected data -sav save figures and quit -fmt [png, svg, pdf] -DM [2, 3] MagIC data model, default 3 DEFAULTS MFILE: trmaq_measurements.txt TSPEC: thellier_specimens.txt OUT: NLT_specimens.txt """ meas_file = 'trmaq_measurements.txt' tspec = "thellier_specimens.txt" output = 'NLT_specimens.txt' data_model_num = int(float(pmag.get_named_arg("-DM", 3))) if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-i' in sys.argv: meas_file = input( "Input magic_measurements file name? [trmaq_measurements.txt] ") if meas_file == "": meas_file = "trmaq_measurements.txt" tspec = input( " thellier_specimens file name? [thellier_specimens.txt] ") if tspec == "": tspec = "thellier_specimens.txt" output = input( "File for non-linear TRM adjusted specimen data: [NLTspecimens.txt] ") if output == "": output = "NLT_specimens.txt" if '-f' in sys.argv: ind = sys.argv.index('-f') meas_file = sys.argv[ind+1] if '-ft' in sys.argv: ind = sys.argv.index('-ft') tspec = sys.argv[ind+1] if '-F' in sys.argv: ind = sys.argv.index('-F') output = sys.argv[ind+1] if '-sav' in sys.argv: save_plots = True else: save_plots = False fmt = pmag.get_named_arg("-fmt", "svg") # PLT = {'aq': 1} if not save_plots: pmagplotlib.plot_init(PLT['aq'], 5, 5) # # get name of file from command line # comment = "" # # meas_data, file_type = pmag.magic_read(meas_file) if 'measurements' not in file_type: print(file_type, "This is not a valid measurements file ") sys.exit() if data_model_num == 2: spec_col = "er_specimen_name" lab_field_dc_col = "specimen_lab_field_dc" int_col = "specimen_int" meth_col = "magic_method_codes" treat_dc_col = "treatment_dc_field" magn_moment_col = "measurement_magn_moment" experiment_col = "magic_experiment_name" outfile_type = "pmag_specimens" else: spec_col = "specimen" lab_field_dc_col = "int_treat_dc_field" int_col = "int_abs" meth_col = "method_codes" treat_dc_col = "treat_dc_field" magn_moment_col = "magn_moment" experiment_col = "experiment" outfile_type = "specimens" sids = pmag.get_specs(meas_data) specimen = 0 # # read in thellier_specimen data # nrm, file_type = pmag.magic_read(tspec) PmagSpecRecs= [] while specimen < len(sids): # # find corresoponding paleointensity data for this specimen # s = sids[specimen] blab, best = "", "" for nrec in nrm: # pick out the Banc data for this spec if nrec[spec_col] == s: try: blab = float(nrec[lab_field_dc_col]) except ValueError: continue best = float(nrec[int_col]) TrmRec = nrec break if blab == "": print("skipping ", s, " : no best ") specimen += 1 else: print(sids[specimen], specimen+1, 'of ', len(sids), 'Best = ', best*1e6) MeasRecs = [] # # find the data from the meas_data file for this specimen # for rec in meas_data: if rec[spec_col] == s: meths = rec[meth_col].split(":") methcodes = [] for meth in meths: methcodes.append(meth.strip()) if "LP-TRM" in methcodes: MeasRecs.append(rec) if len(MeasRecs) < 2: specimen += 1 print('skipping specimen - no trm acquisition data ', s) # # collect info for the PmagSpecRec dictionary # else: TRMs, Bs = [], [] for rec in MeasRecs: Bs.append(float(rec[treat_dc_col])) TRMs.append(float(rec[magn_moment_col])) # calculate best fit parameters through TRM acquisition data, and get new banc NLpars = nlt.NLtrm(Bs, TRMs, best, blab, 0) # Mp, Bp = [], [] for k in range(int(max(Bs)*1e6)): Bp.append(float(k)*1e-6) # predicted NRM for this field npred = nlt.TRM(Bp[-1], NLpars['xopt'] [0], NLpars['xopt'][1]) Mp.append(npred) pmagplotlib.plot_trm( PLT['aq'], Bs, TRMs, Bp, Mp, NLpars, rec[experiment_col]) if not save_plots: pmagplotlib.draw_figs(PLT) print('Banc= ', float(NLpars['banc'])*1e6) trmTC = {} for key in list(TrmRec.keys()): # copy of info from thellier_specimens record trmTC[key] = TrmRec[key] trmTC[int_col] = '%8.3e' % (NLpars['banc']) trmTC[meth_col] = TrmRec[meth_col]+":DA-NL" PmagSpecRecs.append(trmTC) if not save_plots: ans = input("Return for next specimen, s[a]ve plot ") if ans == 'a': Name = {'aq': rec[spec_col]+'_TRM.{}'.format(fmt)} pmagplotlib.save_plots(PLT, Name) else: Name = {'aq': rec[spec_col]+'_TRM.{}'.format(fmt)} pmagplotlib.save_plots(PLT, Name) specimen += 1 pmag.magic_write(output, PmagSpecRecs, outfile_type)
def main(): """ NAME foldtest_magic.py DESCRIPTION does a fold test (Tauxe, 2010) on data INPUT FORMAT pmag_specimens format file, er_samples.txt format file (for bedding) SYNTAX foldtest_magic.py [command line options] OPTIONS -h prints help message and quits -f sites formatted file [default for 3.0 is sites.txt, for 2.5, pmag_sites.txt] -fsa samples formatted file -fsi sites formatted file -exc use criteria to set acceptance criteria (supported only for data model 3) -n NB, set number of bootstraps, default is 1000 -b MIN, MAX, set bounds for untilting, default is -10, 150 -fmt FMT, specify format - default is svg -sav saves plots and quits -DM NUM MagIC data model number (2 or 3, default 3) OUTPUT Geographic: is an equal area projection of the input data in original coordinates Stratigraphic: is an equal area projection of the input data in tilt adjusted coordinates % Untilting: The dashed (red) curves are representative plots of maximum eigenvalue (tau_1) as a function of untilting The solid line is the cumulative distribution of the % Untilting required to maximize tau for all the bootstrapped data sets. The dashed vertical lines are 95% confidence bounds on the % untilting that yields the most clustered result (maximum tau_1). Command line: prints out the bootstrapped iterations and finally the confidence bounds on optimum untilting. If the 95% conf bounds include 0, then a pre-tilt magnetization is indicated If the 95% conf bounds include 100, then a post-tilt magnetization is indicated If the 95% conf bounds exclude both 0 and 100, syn-tilt magnetization is possible as is vertical axis rotation or other pathologies """ if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit kappa = 0 dir_path = pmag.get_named_arg("-WD", ".") nboot = int(float(pmag.get_named_arg("-n", 1000))) # number of bootstraps fmt = pmag.get_named_arg("-fmt", "svg") data_model_num = int(float(pmag.get_named_arg("-DM", 3))) if data_model_num == 3: infile = pmag.get_named_arg("-f", 'sites.txt') orfile = 'samples.txt' site_col = 'site' dec_col = 'dir_dec' inc_col = 'dir_inc' tilt_col = 'dir_tilt_correction' dipkey, azkey = 'bed_dip', 'bed_dip_direction' crit_col = 'criterion' critfile = 'criteria.txt' else: infile = pmag.get_named_arg("-f", 'pmag_sites.txt') orfile = 'er_samples.txt' site_col = 'er_site_name' dec_col = 'site_dec' inc_col = 'site_inc' tilt_col = 'site_tilt_correction' dipkey, azkey = 'sample_bed_dip', 'sample_bed_dip_direction' crit_col = 'pmag_criteria_code' critfile = 'pmag_criteria.txt' if '-sav' in sys.argv: plot = 1 else: plot = 0 if '-b' in sys.argv: ind = sys.argv.index('-b') untilt_min = int(sys.argv[ind+1]) untilt_max = int(sys.argv[ind+2]) else: untilt_min, untilt_max = -10, 150 if '-fsa' in sys.argv: orfile = pmag.get_named_arg("-fsa", "") elif '-fsi' in sys.argv: orfile = pmag.get_named_arg("-fsi", "") if data_model_num == 3: dipkey, azkey = 'bed_dip', 'bed_dip_direction' else: dipkey, azkey = 'site_bed_dip', 'site_bed_dip_direction' else: if data_model_num == 3: orfile = 'sites.txt' else: orfile = 'pmag_sites.txt' orfile = pmag.resolve_file_name(orfile, dir_path) infile = pmag.resolve_file_name(infile, dir_path) critfile = pmag.resolve_file_name(critfile, dir_path) df = pd.read_csv(infile, sep='\t', header=1) # keep only records with tilt_col data = df.copy() data = data[data[tilt_col].notnull()] data = data.where(data.notnull(), "") # turn into pmag data list data = list(data.T.apply(dict)) # get orientation data if data_model_num == 3: # often orientation will be in infile (sites table) if os.path.split(orfile)[1] == os.path.split(infile)[1]: ordata = df[df[azkey].notnull()] ordata = ordata[ordata[dipkey].notnull()] ordata = list(ordata.T.apply(dict)) # sometimes orientation might be in a sample file instead else: ordata = pd.read_csv(orfile, sep='\t', header=1) ordata = list(ordata.T.apply(dict)) else: ordata, file_type = pmag.magic_read(orfile) if '-exc' in sys.argv: crits, file_type = pmag.magic_read(critfile) SiteCrits = [] for crit in crits: if crit[crit_col] == "DE-SITE": SiteCrits.append(crit) #break # get to work # PLTS = {'geo': 1, 'strat': 2, 'taus': 3} # make plot dictionary if not set_env.IS_WIN: pmagplotlib.plot_init(PLTS['geo'], 5, 5) pmagplotlib.plot_init(PLTS['strat'], 5, 5) pmagplotlib.plot_init(PLTS['taus'], 5, 5) if data_model_num == 2: GEOrecs = pmag.get_dictitem(data, tilt_col, '0', 'T') else: GEOrecs = data if len(GEOrecs) > 0: # have some geographic data num_dropped = 0 DIDDs = [] # set up list for dec inc dip_direction, dip for rec in GEOrecs: # parse data dip, dip_dir = 0, -1 Dec = float(rec[dec_col]) Inc = float(rec[inc_col]) orecs = pmag.get_dictitem( ordata, site_col, rec[site_col], 'T') if len(orecs) > 0: if orecs[0][azkey] != "": dip_dir = float(orecs[0][azkey]) if orecs[0][dipkey] != "": dip = float(orecs[0][dipkey]) if dip != 0 and dip_dir != -1: if '-exc' in sys.argv: keep = 1 for site_crit in SiteCrits: crit_name = site_crit['table_column'].split('.')[1] if crit_name and crit_name in rec.keys() and rec[crit_name]: # get the correct operation (<, >=, =, etc.) op = OPS[site_crit['criterion_operation']] # then make sure the site record passes if op(float(rec[crit_name]), float(site_crit['criterion_value'])): keep = 0 if keep == 1: DIDDs.append([Dec, Inc, dip_dir, dip]) else: num_dropped += 1 else: DIDDs.append([Dec, Inc, dip_dir, dip]) if num_dropped: print("-W- Dropped {} records because each failed one or more criteria".format(num_dropped)) else: print('no geographic directional data found') sys.exit() pmagplotlib.plot_eq(PLTS['geo'], DIDDs, 'Geographic') data = np.array(DIDDs) D, I = pmag.dotilt_V(data) TCs = np.array([D, I]).transpose() pmagplotlib.plot_eq(PLTS['strat'], TCs, 'Stratigraphic') if plot == 0: pmagplotlib.draw_figs(PLTS) Percs = list(range(untilt_min, untilt_max)) Cdf, Untilt = [], [] plt.figure(num=PLTS['taus']) print('doing ', nboot, ' iterations...please be patient.....') for n in range(nboot): # do bootstrap data sets - plot first 25 as dashed red line if n % 50 == 0: print(n) Taus = [] # set up lists for taus PDs = pmag.pseudo(DIDDs) if kappa != 0: for k in range(len(PDs)): d, i = pmag.fshdev(kappa) dipdir, dip = pmag.dodirot(d, i, PDs[k][2], PDs[k][3]) PDs[k][2] = dipdir PDs[k][3] = dip for perc in Percs: tilt = np.array([1., 1., 1., 0.01*perc]) D, I = pmag.dotilt_V(PDs*tilt) TCs = np.array([D, I]).transpose() ppars = pmag.doprinc(TCs) # get principal directions Taus.append(ppars['tau1']) if n < 25: plt.plot(Percs, Taus, 'r--') # tilt that gives maximum tau Untilt.append(Percs[Taus.index(np.max(Taus))]) Cdf.append(float(n) / float(nboot)) plt.plot(Percs, Taus, 'k') plt.xlabel('% Untilting') plt.ylabel('tau_1 (red), CDF (green)') Untilt.sort() # now for CDF of tilt of maximum tau plt.plot(Untilt, Cdf, 'g') lower = int(.025*nboot) upper = int(.975*nboot) plt.axvline(x=Untilt[lower], ymin=0, ymax=1, linewidth=1, linestyle='--') plt.axvline(x=Untilt[upper], ymin=0, ymax=1, linewidth=1, linestyle='--') tit = '%i - %i %s' % (Untilt[lower], Untilt[upper], 'Percent Unfolding') print(tit) plt.title(tit) if plot == 0: pmagplotlib.draw_figs(PLTS) ans = input('S[a]ve all figures, <Return> to quit \n ') if ans != 'a': print("Good bye") sys.exit() files = {} for key in list(PLTS.keys()): files[key] = ('foldtest_'+'%s' % (key.strip()[:2])+'.'+fmt) pmagplotlib.save_plots(PLTS, files)
def main(): """ NAME foldtest_magic.py DESCRIPTION does a fold test (Tauxe, 2010) on data INPUT FORMAT pmag_specimens format file, er_samples.txt format file (for bedding) SYNTAX foldtest_magic.py [command line options] OPTIONS -h prints help message and quits -f sites formatted file [default for 3.0 is sites.txt, for 2.5, pmag_sites.txt] -fsa samples formatted file -fsi sites formatted file -exc use criteria to set acceptance criteria (supported only for data model 3) -n NB, set number of bootstraps, default is 1000 -b MIN, MAX, set bounds for untilting, default is -10, 150 -fmt FMT, specify format - default is svg -sav saves plots and quits -DM NUM MagIC data model number (2 or 3, default 3) OUTPUT Geographic: is an equal area projection of the input data in original coordinates Stratigraphic: is an equal area projection of the input data in tilt adjusted coordinates % Untilting: The dashed (red) curves are representative plots of maximum eigenvalue (tau_1) as a function of untilting The solid line is the cumulative distribution of the % Untilting required to maximize tau for all the bootstrapped data sets. The dashed vertical lines are 95% confidence bounds on the % untilting that yields the most clustered result (maximum tau_1). Command line: prints out the bootstrapped iterations and finally the confidence bounds on optimum untilting. If the 95% conf bounds include 0, then a pre-tilt magnetization is indicated If the 95% conf bounds include 100, then a post-tilt magnetization is indicated If the 95% conf bounds exclude both 0 and 100, syn-tilt magnetization is possible as is vertical axis rotation or other pathologies """ if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit kappa = 0 dir_path = pmag.get_named_arg("-WD", ".") nboot = int(float(pmag.get_named_arg("-n", 1000))) # number of bootstraps fmt = pmag.get_named_arg("-fmt", "svg") data_model_num = int(float(pmag.get_named_arg("-DM", 3))) if data_model_num == 3: infile = pmag.get_named_arg("-f", 'sites.txt') orfile = 'samples.txt' site_col = 'site' dec_col = 'dir_dec' inc_col = 'dir_inc' tilt_col = 'dir_tilt_correction' dipkey, azkey = 'bed_dip', 'bed_dip_direction' crit_col = 'criterion' critfile = 'criteria.txt' else: infile = pmag.get_named_arg("-f", 'pmag_sites.txt') orfile = 'er_samples.txt' site_col = 'er_site_name' dec_col = 'site_dec' inc_col = 'site_inc' tilt_col = 'site_tilt_correction' dipkey, azkey = 'sample_bed_dip', 'sample_bed_dip_direction' crit_col = 'pmag_criteria_code' critfile = 'pmag_criteria.txt' if '-sav' in sys.argv: plot = 1 else: plot = 0 if '-b' in sys.argv: ind = sys.argv.index('-b') untilt_min = int(sys.argv[ind + 1]) untilt_max = int(sys.argv[ind + 2]) else: untilt_min, untilt_max = -10, 150 if '-fsa' in sys.argv: orfile = pmag.get_named_arg("-fsa", "") elif '-fsi' in sys.argv: orfile = pmag.get_named_arg("-fsi", "") if data_model_num == 3: dipkey, azkey = 'bed_dip', 'bed_dip_direction' else: dipkey, azkey = 'site_bed_dip', 'site_bed_dip_direction' else: if data_model_num == 3: orfile = 'sites.txt' else: orfile = 'pmag_sites.txt' orfile = pmag.resolve_file_name(orfile, dir_path) infile = pmag.resolve_file_name(infile, dir_path) critfile = pmag.resolve_file_name(critfile, dir_path) df = pd.read_csv(infile, sep='\t', header=1) # keep only records with tilt_col data = df.copy() data = data[data[tilt_col].notnull()] data = data.where(data.notnull(), "") # turn into pmag data list data = list(data.T.apply(dict)) # get orientation data if data_model_num == 3: # often orientation will be in infile (sites table) if os.path.split(orfile)[1] == os.path.split(infile)[1]: ordata = df[df[azkey].notnull()] ordata = ordata[ordata[dipkey].notnull()] ordata = list(ordata.T.apply(dict)) # sometimes orientation might be in a sample file instead else: ordata = pd.read_csv(orfile, sep='\t', header=1) ordata = list(ordata.T.apply(dict)) else: ordata, file_type = pmag.magic_read(orfile) if '-exc' in sys.argv: crits, file_type = pmag.magic_read(critfile) SiteCrits = [] for crit in crits: if crit[crit_col] == "DE-SITE": SiteCrits.append(crit) #break # get to work # PLTS = {'geo': 1, 'strat': 2, 'taus': 3} # make plot dictionary if not set_env.IS_WIN: pmagplotlib.plot_init(PLTS['geo'], 5, 5) pmagplotlib.plot_init(PLTS['strat'], 5, 5) pmagplotlib.plot_init(PLTS['taus'], 5, 5) if data_model_num == 2: GEOrecs = pmag.get_dictitem(data, tilt_col, '0', 'T') else: GEOrecs = data if len(GEOrecs) > 0: # have some geographic data num_dropped = 0 DIDDs = [] # set up list for dec inc dip_direction, dip for rec in GEOrecs: # parse data dip, dip_dir = 0, -1 Dec = float(rec[dec_col]) Inc = float(rec[inc_col]) orecs = pmag.get_dictitem(ordata, site_col, rec[site_col], 'T') if len(orecs) > 0: if orecs[0][azkey] != "": dip_dir = float(orecs[0][azkey]) if orecs[0][dipkey] != "": dip = float(orecs[0][dipkey]) if dip != 0 and dip_dir != -1: if '-exc' in sys.argv: keep = 1 for site_crit in SiteCrits: crit_name = site_crit['table_column'].split('.')[1] if crit_name and crit_name in rec.keys( ) and rec[crit_name]: # get the correct operation (<, >=, =, etc.) op = OPS[site_crit['criterion_operation']] # then make sure the site record passes if op(float(rec[crit_name]), float(site_crit['criterion_value'])): keep = 0 if keep == 1: DIDDs.append([Dec, Inc, dip_dir, dip]) else: num_dropped += 1 else: DIDDs.append([Dec, Inc, dip_dir, dip]) if num_dropped: print( "-W- Dropped {} records because each failed one or more criteria" .format(num_dropped)) else: print('no geographic directional data found') sys.exit() pmagplotlib.plot_eq(PLTS['geo'], DIDDs, 'Geographic') data = np.array(DIDDs) D, I = pmag.dotilt_V(data) TCs = np.array([D, I]).transpose() pmagplotlib.plot_eq(PLTS['strat'], TCs, 'Stratigraphic') if plot == 0: pmagplotlib.draw_figs(PLTS) Percs = list(range(untilt_min, untilt_max)) Cdf, Untilt = [], [] plt.figure(num=PLTS['taus']) print('doing ', nboot, ' iterations...please be patient.....') for n in range( nboot ): # do bootstrap data sets - plot first 25 as dashed red line if n % 50 == 0: print(n) Taus = [] # set up lists for taus PDs = pmag.pseudo(DIDDs) if kappa != 0: for k in range(len(PDs)): d, i = pmag.fshdev(kappa) dipdir, dip = pmag.dodirot(d, i, PDs[k][2], PDs[k][3]) PDs[k][2] = dipdir PDs[k][3] = dip for perc in Percs: tilt = np.array([1., 1., 1., 0.01 * perc]) D, I = pmag.dotilt_V(PDs * tilt) TCs = np.array([D, I]).transpose() ppars = pmag.doprinc(TCs) # get principal directions Taus.append(ppars['tau1']) if n < 25: plt.plot(Percs, Taus, 'r--') # tilt that gives maximum tau Untilt.append(Percs[Taus.index(np.max(Taus))]) Cdf.append(float(n) / float(nboot)) plt.plot(Percs, Taus, 'k') plt.xlabel('% Untilting') plt.ylabel('tau_1 (red), CDF (green)') Untilt.sort() # now for CDF of tilt of maximum tau plt.plot(Untilt, Cdf, 'g') lower = int(.025 * nboot) upper = int(.975 * nboot) plt.axvline(x=Untilt[lower], ymin=0, ymax=1, linewidth=1, linestyle='--') plt.axvline(x=Untilt[upper], ymin=0, ymax=1, linewidth=1, linestyle='--') tit = '%i - %i %s' % (Untilt[lower], Untilt[upper], 'Percent Unfolding') print(tit) plt.title(tit) if plot == 0: pmagplotlib.draw_figs(PLTS) ans = input('S[a]ve all figures, <Return> to quit \n ') if ans != 'a': print("Good bye") sys.exit() files = {} for key in list(PLTS.keys()): files[key] = ('foldtest_' + '%s' % (key.strip()[:2]) + '.' + fmt) pmagplotlib.save_plots(PLTS, files)
def main(): """ NAME revtest_magic.py DESCRIPTION calculates bootstrap statistics to test for antipodality INPUT FORMAT takes dec/inc data from sites table SYNTAX revtest_magic.py [command line options] OPTION -h prints help message and quits -f FILE, sets pmag_sites filename on command line -crd [s,g,t], set coordinate system, default is geographic -exc use criteria file to set acceptance criteria (only available for data model 3) -fmt [svg,png,jpg], sets format for image output -sav saves plot and quits -DM [2, 3] MagIC data model num, default is 3 """ if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit dir_path = pmag.get_named_arg("-WD", ".") coord = pmag.get_named_arg("-crd", "0") # default to geographic coordinates if coord == 's': coord = '-1' elif coord == 'g': coord = '0' elif coord == 't': coord = '100' fmt = pmag.get_named_arg("-fmt", "svg") if '-sav' in sys.argv: plot = 1 data_model = int(float(pmag.get_named_arg("-DM"))) if data_model == 2: infile = pmag.get_named_arg("-f", "pmag_sites.txt") critfile = "pmag_criteria.txt" tilt_corr_col = 'site_tilt_correction' dec_col = "site_dec" inc_col = "site_inc" crit_code_col = "pmag_criteria_code" else: infile = pmag.get_named_arg("-f", "sites.txt") critfile = "criteria.txt" tilt_corr_col = "dir_tilt_correction" dec_col = "dir_dec" inc_col = "dir_inc" crit_code_col = "criterion" D = [] # infile = pmag.resolve_file_name(infile, dir_path) dir_path = os.path.split(infile)[0] critfile = pmag.resolve_file_name(critfile, dir_path) # if data_model == 2: Accept = ['site_k', 'site_alpha95', 'site_n', 'site_n_lines'] else: Accept = [ 'dir_k', 'dir_alpha95', 'dir_n_samples', 'dir_n_specimens_line' ] data, file_type = pmag.magic_read(infile) if 'sites' not in file_type: print("Error opening file", file_type) sys.exit() # ordata,file_type=pmag.magic_read(orfile) SiteCrits = [] if '-exc' in sys.argv and data_model != 2: crits, file_type = pmag.magic_read(critfile) for crit in crits: if crit[crit_code_col] == "DE-SITE": SiteCrit = crit SiteCrits.append(SiteCrit) elif '-exc' in sys.argv and data_model == 2: print( '-W- You have selected the -exc option, which is not available with MagIC data model 2.' ) for rec in data: if rec[tilt_corr_col] == coord: Dec = float(rec[dec_col]) Inc = float(rec[inc_col]) if '-exc' in sys.argv and data_model != 2: fail = False for SiteCrit in SiteCrits: for key in Accept: if key not in SiteCrit['table_column']: continue if key not in rec: continue if SiteCrit['criterion_value'] != "": op = OPS[SiteCrit['criterion_operation']] if not op(float(rec[key]), float(SiteCrit['criterion_value'])): fail = True if not fail: D.append([Dec, Inc, 1.]) else: D.append([Dec, Inc, 1.]) # set up plots CDF = {'X': 1, 'Y': 2, 'Z': 3} pmagplotlib.plot_init(CDF['X'], 5, 5) pmagplotlib.plot_init(CDF['Y'], 5, 5) pmagplotlib.plot_init(CDF['Z'], 5, 5) # # flip reverse mode # D1, D2 = pmag.flip(D) counter, NumSims = 0, 500 # # get bootstrapped means for each data set # if len(D1) < 5 or len(D2) < 5: print('not enough data in two different modes for reversals test') sys.exit() print('doing first mode, be patient') BDI1 = pmag.di_boot(D1) print('doing second mode, be patient') BDI2 = pmag.di_boot(D2) pmagplotlib.plot_com(CDF, BDI1, BDI2, [""]) files = {} for key in list(CDF.keys()): files[key] = 'REV' + '_' + key + '.' + fmt if plot == 0: pmagplotlib.draw_figs(CDF) ans = input("s[a]ve plots, [q]uit: ") if ans == 'a': pmagplotlib.save_plots(CDF, files) else: pmagplotlib.save_plots(CDF, files) sys.exit()
def main(): if "-h" in sys.argv: help(__name__) sys.exit() mag_file = pmag.get_named_arg('-f', reqd=True) dir_path = pmag.get_named_arg('-WD', '.') input_dir_path = pmag.get_named_arg('-ID', '') meas_file = pmag.get_named_arg('-F', 'measurements.txt') spec_file = pmag.get_named_arg('-Fsp', 'specimens.txt') samp_file = pmag.get_named_arg('-Fsa', 'samples.txt') site_file = pmag.get_named_arg('-Fsi', 'sites.txt') loc_file = pmag.get_named_arg('-Flo', 'locations.txt') lat = pmag.get_named_arg('-lat', '') lon = pmag.get_named_arg('-lon', '') specnum = pmag.get_named_arg('-spc', 0) samp_con = pmag.get_named_arg('-ncn', '1') location = pmag.get_named_arg('-loc', 'unknown') noave = 0 if "-A" in sys.argv: noave = 1 meth_code = pmag.get_named_arg('-mcd', "LP-NO") convert.pmd(mag_file, dir_path, input_dir_path, meas_file, spec_file, samp_file, site_file, loc_file, lat, lon, specnum, samp_con, location, noave, meth_code)
def main(): """ NAME mst_magic.py DESCRIPTION converts MsT data (T,M) to measurements format files SYNTAX mst_magic.py [command line options] OPTIONS -h: prints the help message and quits. -usr USER: identify user, default is "" -f FILE: specify T,M format input file, required -spn SPEC: specimen name, required -fsa SFILE: name with sample, site, location information -F FILE: specify output file, default is measurements.txt -dc H: specify applied field during measurement, default is 0.5 T -DM NUM: output to MagIC data model 2.5 or 3, default 3 -syn : This is a synthetic specimen and has no sample/site/location information -spc NUM : specify number of characters to designate a specimen, default = 0 -loc LOCNAME : specify location/study name, must have either LOCNAME or SAMPFILE or be a synthetic -ncn NCON: specify naming convention: default is #1 below Sample naming convention: [1] XXXXY: where XXXX is an arbitrary length site designation and Y is the single character sample designation. e.g., TG001a is the first sample from site TG001. [default] [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length) [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length) [4-Z] XXXX[YYY]: YYY is sample designation with Z characters from site XXX [5] site name same as sample [6] site is entered under a separate column -- NOT CURRENTLY SUPPORTED [7-Z] [XXXX]YYY: XXXX is site designation with Z characters with sample name XXXXYYYY NB: all others you will have to customize your self or e-mail [email protected] for help. INPUT files: T M: T is in Centigrade and M is uncalibrated magnitude """ # # get command line arguments # args = sys.argv if "-h" in args: print(main.__doc__) sys.exit() dir_path = pmag.get_named_arg("-WD", ".") user = pmag.get_named_arg("-usr", "") labfield = pmag.get_named_arg("-dc", '0.5') meas_file = pmag.get_named_arg("-F", "measurements.txt") samp_file = pmag.get_named_arg("-fsa", "samples.txt") try: infile = pmag.get_named_arg("-f", reqd=True) except pmag.MissingCommandLineArgException: print(main.__doc__) print("-f is required option") sys.exit() specnum = int(pmag.get_named_arg("-spc", 0)) location = pmag.get_named_arg("-loc", "") specimen_name = pmag.get_named_arg("-spn", reqd=True) syn = 0 if "-syn" in args: syn = 1 samp_con = pmag.get_named_arg("-ncn", "1") if "-ncn" in args: ind = args.index("-ncn") samp_con = sys.argv[ind+1] data_model_num = int(pmag.get_named_arg("-DM", 3)) convert.mst(infile, specimen_name, dir_path, "", meas_file, samp_file, user, specnum, samp_con, labfield, location, syn, data_model_num)
# bottom = height * .81 # with new aniso_magic elif "ty:_aniso_data" in lower_infile or "ty:_aniso_conf" in lower_infile: left = 0 + width * .215 top = 0 + height * .115 right = width * .86 bottom = height * .875 elif "ty:_aniso_tcdf" in lower_infile: left = 0 + width * .124 top = 0 + height * .155 right = width * .902 bottom = height * .86 else: error_log("Could not crop {}".format(infile)) im.save(infile[:-4] + ".thumb.{}".format(fmt), fmt, dpi=(300, 300)) continue cropped = im.crop((left, top, right, bottom)) #cropped_example.show() cropped.thumbnail((300, 300), Image.ANTIALIAS) cropped.save(infile[:-4] + ".thumb.{}".format(fmt), fmt, dpi=(300, 300)) # Pixels รท DPI = Inches if __name__ == "__main__": if "-h" in sys.argv: print('Make thumbnails for every png in current directory, or use: thumbnails.py -WD <directory>') print('Specify input/output format with: -fmt <format>. Tested formats include [jpg, png]') print('Output files will follow the naming convention: "original_filename.thumb.fmt"') else: make_thumbnails(pmag.get_named_arg("-WD", "."), pmag.get_named_arg("-fmt", "png"))
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('-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 lnp_magic.py DESCRIPTION makes equal area projections site by site from specimen formatted file with Fisher confidence ellipse using McFadden and McElhinny (1988) technique for combining lines and planes SYNTAX lnp_magic [command line options] INPUT takes magic formatted specimens file OUPUT prints site_name n_lines n_planes K alpha95 dec inc R OPTIONS -h prints help message and quits -f FILE: specify input file, default is 'specimens.txt', ('pmag_specimens.txt' for legacy data model 2) -fsa FILE: specify samples file, required to plot by site for data model 3 (otherwise will plot by sample) default is 'samples.txt' -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted default is specimen -fmt [svg,png,jpg] format for plots, default is svg -sav save plots and quit -P: do not plot -F FILE, specify output file of dec, inc, alpha95 data for plotting with plotdi_a and plotdi_e -exc use criteria in criteria table # NOT IMPLEMENTED -DM NUMBER MagIC data model (2 or 3, default 3) """ if '-h' in sys.argv: print(main.__doc__) sys.exit() dir_path = pmag.get_named_arg("-WD", ".") data_model = int(float(pmag.get_named_arg("-DM", 3))) fmt = pmag.get_named_arg("-fmt", 'svg') if data_model == 2: in_file = pmag.get_named_arg('-f', 'pmag_specimens.txt') crit_file = "pmag_criteria.txt" else: in_file = pmag.get_named_arg('-f', 'specimens.txt') samp_file = pmag.get_named_arg('-fsa', 'samples.txt') crit_file = "criteria.txt" in_file = pmag.resolve_file_name(in_file, dir_path) dir_path = os.path.split(in_file)[0] if data_model == 3: samp_file = pmag.resolve_file_name(samp_file, dir_path) if '-crd' in sys.argv: ind = sys.argv.index("-crd") crd = sys.argv[ind+1] if crd == 's': coord = "-1" if crd == 'g': coord = "0" if crd == 't': coord = "100" else: coord = "-1" out_file = pmag.get_named_arg('-F', '') if out_file: out = open(dir_path+'/'+out_file, 'w') if '-P' in sys.argv: make_plots = 0 # do not plot else: make_plots = 1 # do plot if '-sav' in sys.argv: plot = 1 # save plots and quit else: plot = 0 # show plots intereactively (if make_plots) # if data_model == 2: Specs, file_type = pmag.magic_read(in_file) if 'specimens' not in file_type: print('Error opening ', in_file, file_type) sys.exit() else: fnames = {'specimens': in_file, 'samples': samp_file} con = cb.Contribution(dir_path, read_tables=['samples', 'specimens'], custom_filenames=fnames) con.propagate_name_down('site', 'specimens') if 'site' in con.tables['specimens'].df.columns: site_col = 'site' else: site_col = 'sample' tilt_corr_col = "dir_tilt_correction" mad_col = "dir_mad_free" alpha95_col = "dir_alpha95" site_alpha95_col = "dir_alpha95" dec_col = "dir_dec" inc_col = "dir_inc" num_meas_col = "dir_n_measurements" k_col = "dir_k" cols = [site_col, tilt_corr_col, mad_col, alpha95_col, dec_col, inc_col] con.tables['specimens'].front_and_backfill(cols) con.tables['specimens'].df = con.tables['specimens'].df.where(con.tables['specimens'].df.notnull(), "") Specs = con.tables['specimens'].convert_to_pmag_data_list() ## using criteria file was never fully implemented #if '-exc' in sys.argv: # Crits, file_type = pmag.magic_read(pmag.resolve_file_name(crit_file, dir_path)) # for crit in Crits: # if mad_col in crit: # M = float(crit['specimen_mad']) # if num_meas_col in crit: # N = float(crit['specimen_n']) # if site_alpha95_col in crit and 'site' in crit: # acutoff = float(crit['site_alpha95']) # if k_col in crit: # kcutoff = float(crit['site_k']) #else: # Crits = "" sitelist = [] # initialize some variables FIG = {} # plot dictionary FIG['eqarea'] = 1 # eqarea is figure 1 M, N, acutoff, kcutoff = 180., 1, 180., 0. if data_model == 2: site_col = 'er_site_name' tilt_corr_col = "specimen_tilt_correction" mad_col = "specimen_mad" alpha95_col = 'specimen_alpha95' dec_col = "specimen_dec" inc_col = "specimen_inc" num_meas_col = "specimen_n" site_alpha95_col = "site_alpha95" else: # data model 3 pass for rec in Specs: if rec[site_col] not in sitelist: sitelist.append(rec[site_col]) sitelist.sort() if make_plots == 1: EQ = {} EQ['eqarea'] = 1 for site in sitelist: pmagplotlib.plot_init(EQ['eqarea'], 4, 4) print(site) data = [] for spec in Specs: if tilt_corr_col not in list(spec.keys()): spec[tilt_corr_col] = '-1' # assume unoriented if spec[site_col] == site: if mad_col not in list(spec.keys()) or spec[mad_col] == "": if alpha95_col in list(spec.keys()) and spec[alpha95_col] != "": spec[mad_col] = spec[alpha95_col] else: spec[mad_col] = '180' if not spec[num_meas_col]: continue if (float(spec[tilt_corr_col]) == float(coord)) and (float(spec[mad_col]) <= M) and (float(spec[num_meas_col]) >= N): rec = {} for key in list(spec.keys()): rec[key] = spec[key] rec["dec"] = float(spec[dec_col]) rec["inc"] = float(spec[inc_col]) rec["tilt_correction"] = spec[tilt_corr_col] data.append(rec) if len(data) > 2: fpars = pmag.dolnp(data, 'specimen_direction_type') print("Site lines planes kappa a95 dec inc") print(site, fpars["n_lines"], fpars["n_planes"], fpars["K"], fpars["alpha95"], fpars["dec"], fpars["inc"], fpars["R"]) if out_file != "": if float(fpars["alpha95"]) <= acutoff and float(fpars["K"]) >= kcutoff: out.write('%s %s %s\n' % (fpars["dec"], fpars['inc'], fpars['alpha95'])) print('% tilt correction: ', coord) if make_plots == 1: files = {} files['eqarea'] = site+'_'+crd+'_'+'eqarea'+'.'+fmt pmagplotlib.plot_lnp(EQ['eqarea'], site, data, fpars, 'specimen_direction_type') if plot == 0: pmagplotlib.draw_figs(EQ) ans = input( "s[a]ve plot, [q]uit, <return> to continue:\n ") if ans == "a": pmagplotlib.save_plots(EQ, files) if ans == "q": sys.exit() else: pmagplotlib.save_plots(EQ, files) else: print('skipping site - not enough data with specified coordinate system')
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 -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, png 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 -n 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(new.__doc__) return dir_path = pmag.get_named_arg("-WD", ".") if '-ID' in args and dir_path == '.': dir_path = pmag.get_named_arg("-ID", ".") iboot, vec = 1, 0 num_bootstraps = pmag.get_named_arg("-n", 1000) 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) if ivec: vec = 3 #iplot = pmag.get_flag_arg_from_sys("-P", true=0, false=1) isite = pmag.get_flag_arg_from_sys("-sit", true=1, false=0) infile = pmag.get_named_arg('-f', 'specimens.txt') samp_file = pmag.get_named_arg('-fsa', 'samples.txt') site_file = pmag.get_named_arg('-fsi', 'sites.txt') #outfile = pmag.get_named_arg("-F", "rmag_results.txt") fmt = pmag.get_named_arg("-fmt", "png") crd = pmag.get_named_arg("-crd", "s") comp, Dir, PDir = 0, [], [] user = pmag.get_named_arg("-usr", "") if '-B' in args: iboot, ihext = 0, 1 save_plots, verbose, interactive = False, True, True if '-sav' in args: save_plots = True verbose = False interactive = False 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])] ipmag.aniso_magic_nb(infile, samp_file, site_file, verbose, ipar, ihext, ivec, isite, False, iboot, vec, Dir, PDir, crd, num_bootstraps, dir_path, save_plots=save_plots, interactive=interactive, fmt=fmt)
def main(): """ NAME chi_magic.py DESCRIPTION plots magnetic susceptibility as a function of frequency and temperature and AC field SYNTAX chi_magic.py [command line options] OPTIONS -h prints help message and quits -f FILE, specify measurements format file, default "measurements.txt" -T IND, specify temperature step to plot -e EXP, specify experiment name to plot -fmt [svg,jpg,png,pdf] set figure format [default is svg] -sav save figure and quit """ if "-h" in sys.argv: print(main.__doc__) return infile = pmag.get_named_arg("-f", "measurements.txt") dir_path = pmag.get_named_arg("-WD", ".") infile = pmag.resolve_file_name(infile, dir_path) fmt = pmag.get_named_arg("-fmt", "svg") show_plots = True if "-sav" in sys.argv: show_plots = False experiments = pmag.get_named_arg("-e", "") # read in data from data model 3 example file chi_data_all = pd.read_csv(infile, sep='\t', header=1) if not experiments: try: experiments = chi_data_all.experiment.unique() except Exception as ex: print(ex) experiments = ["all"] else: experiments = [experiments] plotnum = 0 figs = {} fnames = {} for exp in experiments: if exp == "all": chi_data = chi_data_all chi_data = chi_data_all[chi_data_all.experiment == exp] if len(chi_data) <= 1: print('Not enough data to plot {}'.format(exp)) continue plotnum += 1 pmagplotlib.plot_init(plotnum, 5, 5) # set up plot figs[str(plotnum)] = plotnum fnames[str(plotnum)] = exp + '_temperature.{}'.format(fmt) # get arrays of available temps, frequencies and fields Ts = np.sort(chi_data.meas_temp.unique()) Fs = np.sort(chi_data.meas_freq.unique()) Bs = np.sort(chi_data.meas_field_ac.unique()) # plot chi versus temperature at constant field b = Bs.max() for num, f in enumerate(Fs): this_f = chi_data[chi_data.meas_freq == f] this_f = this_f[this_f.meas_field_ac == b] plt.plot(this_f.meas_temp, 1e6 * this_f.susc_chi_volume, label='%i' % (f) + ' Hz') plt.legend() plt.xlabel('Temperature (K)') plt.ylabel('$\chi$ ($\mu$SI)') plt.title('B = ' + '%7.2e' % (b) + ' T') plotnum += 1 figs[str(plotnum)] = plotnum fnames[str(plotnum)] = exp + '_frequency.{}'.format(fmt) pmagplotlib.plot_init(plotnum, 5, 5) # set up plot ## plot chi versus frequency at constant B b = Bs.max() t = Ts.min() this_t = chi_data[chi_data.meas_temp == t] this_t = this_t[this_t.meas_field_ac == b] plt.semilogx(this_t.meas_freq, 1e6 * this_t.susc_chi_volume, label='%i' % (t) + ' K') plt.legend() plt.xlabel('Frequency (Hz)') plt.ylabel('$\chi$ ($\mu$SI)') plt.title('B = ' + '%7.2e' % (b) + ' T') if show_plots: pmagplotlib.draw_figs(figs) ans = input("enter s[a]ve to save files, [return] to quit ") if ans == 'a': pmagplotlib.save_plots(figs, fnames) sys.exit() else: sys.exit() else: pmagplotlib.save_plots(figs, fnames)
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('-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("-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)