code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
response = session.fetch('friends.get', user_id=user_id, count=1) return response["count"]
def _get_friends_count(session, user_id)
https://vk.com/dev/friends.get
5.560742
3.787636
1.46813
# time array t = _n.linspace(0,10,number_of_points) return(t, [_n.cos(t)*(1.0+0.2*_n.random.random(number_of_points)), _n.sin(t +0.5*_n.random.random(number_of_points))])
def acquire_fake_data(number_of_points=1000)
This function generates some fake data and returns two channels of data in the form time_array, [channel1, channel2]
4.64013
4.442301
1.044533
d = databox(**kwargs) d.load_file(path=path, first_data_line=first_data_line, filters=filters, text=text, default_directory=default_directory, header_only=header_only) if not quiet: print("\nloaded", d.path, "\n") if transpose: return d.transpose() return d
def load(path=None, first_data_line='auto', filters='*.*', text='Select a file, FACEHEAD.', default_directory='default_directory', quiet=True, header_only=False, transpose=False, **kwargs)
Loads a data file into the databox data class. Returns the data object. Most keyword arguments are sent to databox.load() so check there for documentation.(if their function isn't obvious). Parameters ---------- path=None Supply a path to a data file; None means use a dialog. first_data_line="auto" Specify the index of the first data line, or have it figure this out automatically. filters="*.*" Specify file filters. text="Select a file, FACEHEAD." Window title text. default_directory="default_directory" Which directory to start in (by key). This lives in spinmob.settings. quiet=True Don't print stuff while loading. header_only=False Load only the header information. transpose = False Return databox.transpose(). Additioinal optional keyword arguments are sent to spinmob.data.databox(), so check there for more information.
3.023457
2.85844
1.057729
if paths == None: paths = _s.dialogs.load_multiple(filters, text, default_directory) if paths is None : return datas = [] for path in paths: if _os.path.isfile(path): datas.append(load(path=path, first_data_line=first_data_line, filters=filters, text=text, default_directory=default_directory, header_only=header_only, transpose=transpose, **kwargs)) return datas
def load_multiple(paths=None, first_data_line="auto", filters="*.*", text="Select some files, FACEHEAD.", default_directory="default_directory", quiet=True, header_only=False, transpose=False, **kwargs)
Loads a list of data files into a list of databox data objects. Returns said list. Parameters ---------- path=None Supply a path to a data file; None means pop up a dialog. first_data_line="auto" Specify the index of the first data line, or have it figure this out automatically. filters="*.*" Specify file filters. text="Select some files, FACEHEAD." Window title text. default_directory="default_directory" Which directory to start in (by key). This lives in spinmob.settings. quiet=True Don't print stuff while loading. header_only=False Load only the header information. transpose = False Return databox.transpose(). Optional keyword arguments are sent to spinmob.data.load(), so check there for more information.
2.802027
2.967143
0.944352
print("\nDatabox Instance", self.path) print("\nHeader") for h in self.hkeys: print(" "+h+":", self.h(h)) s = "\nColumns ("+str(len(self.ckeys))+"): " for c in self.ckeys: s = s+c+", " print(s[:-2])
def more_info(self)
Prints out more information about the databox.
6.101858
4.817057
1.266719
# start with numpy globbies = dict(_n.__dict__) globbies.update(_special.__dict__) # update with required stuff globbies.update({'h':self.h, 'c':self.c, 'd':self, 'self':self}) # update with user stuff globbies.update(self.extra_globals) return globbies
def _globals(self)
Returns the globals needed for eval() statements.
7.044634
6.153746
1.144772
# loop over the columns and pop the data point = [] for k in self.ckeys: point.append(self[k][n]) return point
def get_data_point(self, n)
Returns the n'th data point (starting at 0) from all columns. Parameters ---------- n Index of data point to return.
9.601918
10.118237
0.948972
# loop over the columns and pop the data popped = [] for k in self.ckeys: # first convert to a list data = list(self.c(k)) # pop the data popped.append(data.pop(n)) # now set this column again self.insert_column(_n.array(data), k) return popped
def pop_data_point(self, n)
This will remove and return the n'th data point (starting at 0) from all columns. Parameters ---------- n Index of data point to pop.
7.215225
7.456254
0.967674
if not len(new_data) == len(self.columns) and not len(self.columns)==0: print("ERROR: new_data must have as many elements as there are columns.") return # otherwise, we just auto-add this data point as new columns elif len(self.columns)==0: for i in range(len(new_data)): self[i] = [new_data[i]] # otherwise it matches length so just insert it. else: for i in range(len(new_data)): # get the array and turn it into a list data = list(self[i]) # append or insert if index is None: data.append( new_data[i]) else: data.insert(index, new_data[i]) # reconvert to an array self[i] = _n.array(data) return self
def insert_data_point(self, new_data, index=None)
Inserts a data point at index n. Parameters ---------- new_data A list or array of new data points, one for each column. index Where to insert the point(s) in each column. None => append.
4.506601
4.382635
1.028286
# add any extra user-supplied global variables for the eventual eval() call. if not g==None: self.extra_globals.update(g) # If the script is not a list of scripts, return the script value. # This is the termination of a recursive call. if not _s.fun.is_iterable(script): # special case if script is None: return None # get the expression and variables dictionary [expression, v] = self._parse_script(script) # if there was a problem parsing the script if v is None: print("ERROR: Could not parse '"+script+"'") return None # get all the numpy stuff too g = self._globals() g.update(v) # otherwise, evaluate the script using python's eval command return eval(expression, g) # Otherwise, this is a list of (lists of) scripts. Make the recursive call. output = [] for s in script: output.append(self.execute_script(s)) return output
def execute_script(self, script, g=None)
Runs a script, returning the result. Parameters ---------- script String script to be evaluated (see below). g=None Optional dictionary of additional globals for the script evaluation. These will automatically be inserted into self.extra_globals. Usage ----- Scripts are of the form: "3.0 + x/y - d[0] where x=3.0*c('my_column')+h('setting'); y=d[1]" By default, "d" refers to the databox object itself, giving access to everything and enabling complete control over the universe. Meanwhile, c() and h() give quick reference to d.c() and d.h() to get columns and header lines. Additionally, these scripts can see all of the numpy functions like sin, cos, sqrt, etc. If you would like access to additional globals in a script, there are a few options in addition to specifying the g parametres. You can set self.extra_globals to the appropriate globals dictionary or add globals using self.insert_global(). Setting g=globals() will automatically insert all of your current globals into this databox instance. There are a few shorthand scripts available as well. You can simply type a column name such as 'my_column' or a column number like 2. However, I only added this functionality as a shortcut, and something like "2.0*a where a=my_column" will not work unless 'my_column is otherwise defined. I figure since you're already writing a complicated script in that case, you don't want to accidentally shortcut your way into using a column instead of a constant! Use "2.0*a where a=c('my_column')" instead.
6.59757
6.191565
1.065574
if n > 1000: print("This script ran recursively 1000 times!") a = input("<enter> or (q)uit: ") if a.strip().lower() in ['q', 'quit']: script = None if script is None: return [None, None] # check if the script is simply an integer if type(script) in [int,int]: if script<0: script = script+len(self.ckeys) return ["___"+str(script), {"___"+str(script):self[script]}] # the scripts would like to use calls like "h('this')/3.0*c('that')", # so to make eval() work we should add these functions to a local list # first split up by "where" split_script = script.split(" where ") ######################################## # Scripts without a "where" statement: ######################################## # if it's a simple script, like "column0" or "c(3)/2.0" if len(split_script) is 1: if self.debug: print("script of length 1") # try to evaluate the script # first try to evaluate it as a simple column label if n==0 and script in self.ckeys: # only try this on the zero'th attempt # if this is a recursive call, there can be ambiguities if the # column names are number strings return ['___', {'___':self[script]}] # Otherwise, evaluate it. try: b = eval(script, self._globals()) return ['___', {'___':b}] except: print() print("ERROR: Could not evaluate '"+str(script)+"'") return [None, None] ####################################### # Full-on fancy scripts ####################################### # otherwise it's a complicated script like "c(1)-a/2 where a=h('this')" # tidy up the expression expression = split_script[0].strip() # now split the variables list up by , varsplit = split_script[1].split(';') # loop over the entries in the list of variables, storing the results # of evaluation in the "stuff" dictionary stuff = dict() for var in varsplit: # split each entry by the "=" sign s = var.split("=") if len(s) == 1: print(s, "has no '=' in it") return [None, None] # tidy up into "variable" and "column label" v = s[0].strip() c = s[1].strip() # now try to evaluate c, given our current globbies # recursively call this sub-script. At the end of all this mess # we want the final return value to be the first expression # and a full dictionary of variables to fill it [x,y] = self._parse_script(c, n+1) # if it's not working, just quit out. if y is None: return [None, None] stuff[v] = y[x] # at this point we've found or generated the list return [expression, stuff]
def _parse_script(self, script, n=0)
This takes a script such as "a/b where a=c('current'), b=3.3" and returns ["a/b", {"a":self.columns["current"], "b":3.3}] You can also just use an integer for script to reference columns by number or use the column label as the script. n is for internal use. Don't use it. In fact, don't use this function, user.
6.641183
6.341677
1.047228
for k in source_databox.hkeys: self.insert_header(k, source_databox.h(k)) return self
def copy_headers(self, source_databox)
Loops over the hkeys of the source_databox, updating this databoxes' header.
6.574328
3.774716
1.741675
for k in source_databox.ckeys: self.insert_column(source_databox[k], k) return self
def copy_columns(self, source_databox)
Loops over the ckeys of the source_databox, updating this databoxes' columns.
7.71536
3.917408
1.969506
self.copy_headers(source_databox) self.copy_columns(source_databox) return self
def copy_all(self, source_databox)
Copies the header and columns from source_databox to this databox.
3.96234
2.480062
1.597678
for a in args: kwargs[a.__name__] = a self.extra_globals.update(kwargs)
def insert_globals(self, *args, **kwargs)
Appends or overwrites the supplied object in the self.extra_globals. Use this to expose execute_script() or _parse_script() etc... to external objects and functions. Regular arguments are assumed to have a __name__ attribute (as is the case for functions) to use as the key, and keyword arguments will just be added as dictionary elements.
6.227234
5.421045
1.148715
#if hkey is '': return # if it's an integer, use the hkey from the list if type(hkey) in [int, int]: hkey = self.hkeys[hkey] # set the data self.headers[str(hkey)] = value if not hkey in self.hkeys: if index is None: self.hkeys.append(str(hkey)) else: self.hkeys.insert(index, str(hkey)) return self
def insert_header(self, hkey, value, index=None)
This will insert/overwrite a value to the header and hkeys. Parameters ---------- hkey Header key. Will be appended to self.hkeys if non existent, or inserted at the specified index. If hkey is an integer, uses self.hkeys[hkey]. value Value of the header. index=None If specified (integer), hkey will be inserted at this location in self.hkeys.
3.442678
3.410079
1.00956
d = other_databox if not hasattr(other_databox, '_is_spinmob_databox'): return False # Proceed by testing things one at a time, returning false if one fails if headers: # Same number of elements if not len(self.hkeys) == len(d.hkeys): return False # Elements if header_order and not self.hkeys == d.hkeys: return False # Each value for k in self.hkeys: # Make sure the key exists if not k in d.hkeys: return False # Make sure it's the same. if not self.h(k) == d.h(k): return False if columns: # Same number of columns if not len(self.ckeys) == len(d.ckeys): return False # If we're checking columns by ckeys if ckeys: # Columns if column_order and not self.ckeys == d.ckeys: return False # Each value of each array for k in self.ckeys: # Make sure the key exists if not k in d.ckeys: return False # Check the values if not (_n.array(self[k]) == _n.array(d[k])).all(): return False # Otherwise we're ignoring ckeys else: for n in range(len(self.ckeys)): if not (_n.array(self[n]) == _n.array(d[n])).all(): return False # Passes all tests return True
def is_same_as(self, other_databox, headers=True, columns=True, header_order=True, column_order=True, ckeys=True)
Tests that the important (i.e. savable) information in this databox is the same as that of the other_databox. Parameters ---------- other_databox Databox with which to compare. headers=True Make sure all header elements match. columns=True Make sure every element of every column matches. header_order=True Whether the order of the header elements must match. column_order=True Whether the order of the columns must match. This is only a sensible concern if ckeys=True. ckeys=True Whether the actual ckeys matter, or just the ordered columns of data. Note the == symbol runs this function with everything True.
2.984674
2.954936
1.010064
# try the integer approach first to allow negative values if type(hkey) is not str: try: return self.headers.pop(self.hkeys.pop(hkey)) except: if not ignore_error: print("ERROR: pop_header() could not find hkey "+str(hkey)) return None else: try: # find the key integer and pop it hkey = self.hkeys.index(hkey) # pop it! return self.headers.pop(self.hkeys.pop(hkey)) except: if not ignore_error: print("ERROR: pop_header() could not find hkey "+str(hkey)) return
def pop_header(self, hkey, ignore_error=False)
This will remove and return the specified header value. Parameters ---------- hkey Header key you wish to pop. You can specify either a key string or an index. ignore_error=False Whether to quietly ignore any errors (i.e., hkey not found).
3.41654
3.215331
1.062578
# try the integer approach first to allow negative values if type(ckey) is not str: return self.columns.pop(self.ckeys.pop(ckey)) else: # find the key integer and pop it ckey = self.ckeys.index(ckey) # if we didn't find the column, quit if ckey < 0: print("Column does not exist (yes, we looked).") return # pop it! return self.columns.pop(self.ckeys.pop(ckey))
def pop_column(self, ckey)
This will remove and return the data in the specified column. You can specify either a key string or an index.
5.326495
4.856784
1.096712
# if it's an integer, use the ckey from the list if type(ckey) in [int, int]: ckey = self.ckeys[ckey] # append/overwrite the column value self.columns[ckey] = _n.array(data_array) if not ckey in self.ckeys: if index is None: self.ckeys.append(ckey) else: self.ckeys.insert(index, ckey) return self
def insert_column(self, data_array, ckey='temp', index=None)
This will insert/overwrite a new column and fill it with the data from the the supplied array. Parameters ---------- data_array Data; can be a list, but will be converted to numpy array ckey Name of the column; if an integer is supplied, uses self.ckeys[ckey] index Where to insert this column. None => append to end.
3.887341
3.528868
1.101583
if not type(ckey) is str: print("ERROR: ckey should be a string!") return if ckey in self.ckeys: print("ERROR: ckey '"+ckey+"' already exists!") return return self.insert_column(data_array, ckey)
def append_column(self, data_array, ckey='temp')
This will append a new column and fill it with the data from the the supplied array. Parameters ---------- data_array Data; can be a list, but will be converted to numpy array ckey Name of the column.
3.357322
3.758226
0.893326
self.hkeys[self.hkeys.index(old_name)] = new_name self.headers[new_name] = self.headers.pop(old_name) return self
def rename_header(self, old_name, new_name)
This will rename the header. The supplied names need to be strings.
2.862775
2.792301
1.025239
if type(column) is not str: column = self.ckeys[column] self.ckeys[self.ckeys.index(column)] = new_name self.columns[new_name] = self.columns.pop(column) return self
def rename_column(self, column, new_name)
This will rename the column. The supplied column can be an integer or the old column name.
2.995438
2.735089
1.095189
conditions = list(conditions) # if necessary, evaluate string scripts for n in range(len(conditions)): if type(conditions[n]) is str: conditions[n] = self.execute_script(conditions[n]) # make a new databox with the same options and headers new_databox = databox(delimiter=self.delimiter) new_databox.copy_headers(self) # trim it up, send it out. cs = _s.fun.trim_data_uber(self, conditions) for n in range(len(cs)): new_databox.append_column(cs[n], self.ckeys[n]) return new_databox
def trim(self, *conditions)
Removes data points not satisfying the supplied conditions. Conditions can be truth arrays (having the same length as the columns!) or scripted strings. Example Workflow ---------------- d1 = spinmob.data.load() d2 = d1.trim( (2<d1[0]) & (d1[0]<10) | (d1[3]==22), 'sin(d[2])*h("gain")<32.2') Note this will not modify the databox, rather it will generate a new one with the same header information and return it.
6.679868
6.220761
1.073802
# Create an empty databox with the same headers and delimiter. d = databox(delimter=self.delimiter) self.copy_headers(d) # Get the transpose z = _n.array(self[:]).transpose() # Build the columns of the new databox for n in range(len(z)): d['c'+str(n)] = z[n] return d
def transpose(self)
Returns a copy of this databox with the columns as rows. Currently requires that the databox has equal-length columns.
9.074361
6.817252
1.331088
if keys is None: keys = list(dictionary.keys()) for k in keys: self.insert_header(k, dictionary[k]) return self
def update_headers(self, dictionary, keys=None)
Updates the header with the supplied dictionary. If keys=None, it will be unsorted. Otherwise it will loop over the supplied keys (a list) in order.
3.217918
3.154553
1.020087
# If not arguments, print everything if len(args) + len(kwargs) == 0: print("Columns") if len(self.ckeys)==0: print (' No columns of data yet.') # Loop over the ckeys and display their information for n in range(len(self.ckeys)): print(' '+str(n)+': '+str(self.ckeys[n])+' '+str(_n.shape(self[n]))) return # Otherwise, find n elif len(args): n = args[0] elif len(kwargs): for k in kwargs: n = kwargs[k] # Nothing to do here. if len(self.columns) == 0: return None # if it's a string, use it as a key for the dictionary if type(n) is str: return self.columns[n] # if it's a list, return the specified columns if type(n) in [list, tuple, range]: output = [] for i in n: output.append(self[i]) return output # If it's a slice, do the slice thing if type(n) is slice: start = n.start stop = n.stop step = n.step # Fix up the unspecifieds if start == None: start = 0 if stop == None or stop>len(self): stop = len(self) if step == None: step = 1 # Return what was asked for return self[range(start, stop, step)] # Otherwise assume it's an integer return self.columns[self.ckeys[n]]
def c(self, *args, **kwargs)
Takes a single argument or keyword argument, and returns the specified column. If the argument (or keyword argument) is an integer, return the n'th column, otherwise return the column based on key. If no arguments are supplied, simply print the column information.
4.218482
4.034827
1.045517
# If not arguments, print everything if len(args) + len(kwargs) == 0: print("Headers") for n in range(len(self.hkeys)): print(' '+str(n)+': '+str(self.hkeys[n])+' = '+repr(self.h(n))) return # first loop over kwargs if there are any to set header elements for k in list(kwargs.keys()): self.insert_header(k, kwargs[k]) # Meow search for a key if specified if len(args): # this can be shortened. Eventually, it'd be nice to get a tuple back! hkey = args[0] # if this is an index if type(hkey) in [int, int]: return self.headers[self.hkeys[hkey]] # if this is an exact match elif hkey in self.hkeys: return self.headers[hkey] # Look for a fragment. else: for k in self.hkeys: if k.find(hkey) >= 0: return self.headers[k] print() print("ERROR: Couldn't find '"+str(hkey) + "' in header.") print("Possible values:") for k in self.hkeys: print(k) print() return None
def h(self, *args, **kwargs)
This function searches through hkeys for one *containing* a key string supplied by args[0] and returns that header value. Also can take integers, returning the key'th header value. kwargs can be specified to set header elements. Finally, if called with no arguments or keyword arguments, this simply prints the header information.
4.702803
4.272462
1.100724
if len(kwargs)==0: return self # Set settings for k in list(kwargs.keys()): self[k] = kwargs[k] # Plot if we're supposed to. if self['autoplot'] and not self._initializing: self.plot() return self
def set(self, **kwargs)
Changes a setting or multiple settings. Can also call self() or change individual parameters with self['parameter'] = value
5.932146
5.200557
1.140675
s = '' if self.results and self.results[1] is not None: s = s + "\n# FIT RESULTS (reduced chi squared = {:s})\n".format(str(self.reduced_chi_squareds())) for n in range(len(self._pnames)): s = s + "{:10s} = {:G}\n".format(self._pnames[n], self.results[0][n]) elif self.results and self.results[1] is None: s = s + "\n# FIT DID NOT CONVERGE\n" for n in range(len(self._pnames)): s = s + "{:10s} = {:G}\n".format(self._pnames[n], self.results[0][n]) else: s = s + "\n# NO FIT RESULTS\n" print(s)
def print_fit_parameters(self)
Just prints them out in a way that's easy to copy / paste into python.
2.667313
2.618834
1.018512
# initialize everything self._pnames = [] self._cnames = [] self._pguess = [] self._constants = [] # Update the globals self._globals.update(kwargs) # store these for later self._f_raw = f self._bg_raw = bg # break up the constant names and initial values. if c: for s in c.split(','): # split by '=' and see if there is an initial value s = s.split('=') # add the name to the list self._cnames.append(s[0].strip()) # if there is a guess value, add this (or 1.0) if len(s) > 1: self._constants.append(float(s[1])) else: self._constants.append(1.0) # break up the parameter names and initial values. for s in p.split(','): # split by '=' and see if there is an initial value s = s.split('=') # add the name to the list self._pnames.append(s[0].strip()) # if there is a guess value, add this (or 1.0) if len(s) > 1: self._pguess.append(float(s[1])) else: self._pguess.append(1.0) # use the internal settings we just set to create the functions self._update_functions() if self['autoplot']: self.plot() return self
def set_functions(self, f='a*x*cos(b*x)+c', p='a=-0.2, b, c=3', c=None, bg=None, **kwargs)
Sets the function(s) used to describe the data. Parameters ---------- f=['a*x*cos(b*x)+c', 'a*x+c'] This can be a string function, a defined function my_function(x,a,b), or a list of some combination of these two types of objects. The length of such a list must be equal to the number of data sets supplied to the fit routine. p='a=1.5, b' This must be a comma-separated string list of parameters used to fit. If an initial guess value is not specified, 1.0 will be used. If a function object is supplied, it is assumed that this string lists the parameter names in order. c=None Fit _constants; like p, but won't be allowed to float during the fit. This can also be None. bg=None Can be functions in the same format as f describing a background (which can be subtracted during fits, etc) Additional keyword arguments are added to the globals used when evaluating the functions.
2.953397
2.913267
1.013775
self.f = [] self.bg = [] self._fnames = [] self._bgnames = [] self._odr_models = [] # Like f, but different parameters, for use in ODR f = self._f_raw bg = self._bg_raw # make sure f and bg are lists of matching length if not _s.fun.is_iterable(f) : f = [f] if not _s.fun.is_iterable(bg): bg = [bg] while len(bg) < len(f): bg.append(None) # get a comma-delimited string list of parameter names for the "normal" function pstring = 'x, ' + ', '.join(self._pnames) # get the comma-delimited string for the ODR function pstring_odr = 'x, ' for n in range(len(self._pnames)): pstring_odr = pstring_odr+'p['+str(n)+'], ' # update the globals for the functions # the way this is done, we must redefine the functions # every time we change a constant for cname in self._cnames: self._globals[cname] = self[cname] # loop over all the functions and create the master list for n in range(len(f)): # if f[n] is a string, define a function on the fly. if isinstance(f[n], str): # "Normal" least squares function (y-error bars only) self.f.append( eval('lambda ' + pstring + ': ' + f[n], self._globals)) self._fnames.append(f[n]) # "ODR" compatible function (for x-error bars), based on self.f self._odr_models.append( _odr.Model(eval('lambda p,x: self.f[n]('+pstring_odr+')', dict(self=self, n=n)))) # Otherwise, just append it. else: self.f.append(f[n]) self._fnames.append(f[n].__name__) # if bg[n] is a string, define a function on the fly. if isinstance(bg[n], str): self.bg.append(eval('lambda ' + pstring + ': ' + bg[n], self._globals)) self._bgnames.append(bg[n]) else: self.bg.append(bg[n]) if bg[n] is None: self._bgnames.append("None") else: self._bgnames.append(bg[n].__name__) # update the format of all the settings for k in list(self._settings.keys()): self[k] = self[k] # make sure we don't think our fit results are valid! self.clear_results()
def _update_functions(self)
Uses internal settings to update the functions.
3.902488
3.834463
1.017741
self._set_data_globals.update(kwargs) return eval(script, self._set_data_globals)
def evaluate_script(self, script, **kwargs)
Evaluates the supplied script (python-executable string). Useful for testing your scripts! globals already include all of numpy objects plus self = self f = self.f bg = self.bg and all the current guess parameters and constants kwargs are added to globals for script evaluation.
6.893299
6.318126
1.091035
if self.results is None: print("No fit results to use! Run fit() first.") return # loop over the results and set the guess values for n in range(len(self._pguess)): self._pguess[n] = self.results[0][n] if self['autoplot']: self.plot() return self
def set_guess_to_fit_result(self)
If you have a fit result, set the guess parameters to the fit parameters.
6.817015
6.413488
1.062918
# get the data xdatas, ydatas, eydatas = self.get_data() # get the trim limits (trimits) xmins = self['xmin'] xmaxs = self['xmax'] ymins = self['ymin'] ymaxs = self['ymax'] coarsen = self['coarsen'] # make sure we have one limit for each data set if type(xmins) is not list: xmins = [xmins] *len(xdatas) if type(xmaxs) is not list: xmaxs = [xmaxs] *len(xdatas) if type(ymins) is not list: ymins = [ymins] *len(xdatas) if type(ymaxs) is not list: ymaxs = [ymaxs] *len(xdatas) if type(coarsen) is not list: coarsen = [coarsen]*len(xdatas) # this should cover all the data sets (dimensions should match!) xdata_massaged = [] ydata_massaged = [] eydata_massaged = [] #exdata_massaged = [] for n in range(len(xdatas)): x = xdatas[n] y = ydatas[n] ey = eydatas[n] #ex = exdatas[n] # coarsen the data if do_coarsen: x = _s.fun.coarsen_array(x, self['coarsen'][n], 'mean') y = _s.fun.coarsen_array(y, self['coarsen'][n], 'mean') ey = _n.sqrt(_s.fun.coarsen_array(ey**2, self['coarsen'][n], 'mean')/self['coarsen'][n]) # if not ex == None: # ex = _n.sqrt(_s.fun.coarsen_array(ex**2, self['coarsen'][n], 'mean')/self['coarsen'][n]) if do_trim: # Create local mins and maxes xmin = xmins[n] ymin = ymins[n] xmax = xmaxs[n] ymax = ymaxs[n] # handle "None" limits if xmin is None: xmin = min(x) if xmax is None: xmax = max(x) if ymin is None: ymin = min(y) if ymax is None: ymax = max(y) # trim the data [xt, yt, eyt] = _s.fun.trim_data_uber([x, y, ey], [x>=xmin, x<=xmax, y>=ymin, y<=ymax]) # Catch the over-trimmed case if(len(xt)==0): self._error("\nDATA SET "+str(n)+": OOPS! OOPS! Specified limits (xmin, xmax, ymin, ymax) eliminate all data! Ignoring.") else: x = xt y = yt ey = eyt #ex = ext # store the result xdata_massaged.append(x) ydata_massaged.append(y) eydata_massaged.append(ey) #exdata_massaged.append(ex) return xdata_massaged, ydata_massaged, eydata_massaged
def get_processed_data(self, do_coarsen=True, do_trim=True)
This will coarsen and then trim the data sets according to settings. Returns processed xdata, ydata, eydata. Parameters ---------- do_coarsen=True Whether we should coarsen the data do_trim=True Whether we should trim the data Settings -------- xmin, xmax, ymin, ymax Limits on x and y data points for trimming. coarsen Break the data set(s) into this many groups of points, and average each group into one point, propagating errors.
2.596892
2.517691
1.031458
self._xdata_massaged, self._ydata_massaged, self._eydata_massaged = self.get_processed_data() # # Create the odr data. # self._odr_datas = [] # for n in range(len(self._xdata_massaged)): # # Only exdata can be None; make sure it's zeros at least. # ex = self._exdata_massaged[n] # if ex == None: ex = _n.zeros(len(self._eydata_massaged[n])) # self._odr_datas.append(_odr.RealData(self._xdata_massaged[n], # self._ydata_massaged[n], # sx=ex, # sy=self._eydata_massaged[n])) return self
def _massage_data(self)
Processes the data and stores it.
3.530379
3.354766
1.052347
if len(self._set_xdata)==0 or len(self._set_ydata)==0: return self._error("No data. Please use set_data() prior to fitting.") if self._f_raw is None: return self._error("No functions. Please use set_functions() prior to fitting.") # Do the processing once, to increase efficiency self._massage_data() # Send the keyword arguments to the settings self.set(**kwargs) # do the actual optimization self.results = _opt.leastsq(self._studentized_residuals_concatenated, self._pguess, full_output=1) # plot if necessary if self['autoplot']: self.plot() return self
def fit(self, **kwargs)
This will try to determine fit parameters using scipy.optimize.leastsq algorithm. This function relies on a previous call of set_data() and set_functions(). Notes ----- results of the fit algorithm are stored in self.results. See scipy.optimize.leastsq for more information. Optional keyword arguments are sent to self.set() prior to fitting.
7.420122
6.467694
1.147259
# first set all the keyword argument values self.set(**kwargs) # get everything into one big list pnames = list(args) + list(kwargs.keys()) # move each pname to the constants for pname in pnames: if not pname in self._pnames: self._error("Naughty. '"+pname+"' is not a valid fit parameter name.") else: n = self._pnames.index(pname) # use the fit result if it exists if self.results: value = self.results[0][n] # otherwise use the guess value else: value = self._pguess[n] # make the switcheroo if type(self._pnames) is not list: self._pnames = list(self._pnames) if type(self._pguess) is not list: self._pguess = list(self._pguess) if type(self._cnames) is not list: self._cnames = list(self._cnames) if type(self._constants) is not list: self._constants = list(self._constants) self._pnames.pop(n) self._pguess.pop(n) self._cnames.append(pname) self._constants.append(value) # update self._update_functions() return self
def fix(self, *args, **kwargs)
Turns parameters to constants. As arguments, parameters must be strings. As keyword arguments, they can be set at the same time. Note this will NOT work when specifying a non-string fit function, because there is no flexibility in the number of arguments. To get around this, suppose you've defined a function stuff(x,a,b). Instead of sending the stuff object to self.set_functions() directly, make it a string function, e.g.: self.set_functions('stuff(x,a,b)', 'a,b', stuff=stuff)
3.566967
3.33584
1.069286
# first set all the keyword argument values self.set(**kwargs) # get everything into one big list cnames = list(args) + list(kwargs.keys()) # move each pname to the constants for cname in cnames: if not cname in self._cnames: self._error("Naughty. '"+cname+"' is not a valid constant name.") else: n = self._cnames.index(cname) # make the switcheroo if type(self._pnames) is not list: self._pnames = list(self._pnames) if type(self._pguess) is not list: self._pguess = list(self._pguess) if type(self._cnames) is not list: self._cnames = list(self._cnames) if type(self._constants) is not list: self._constants = list(self._constants) self._pnames.append(self._cnames.pop(n)) self._pguess.append(self._constants.pop(n)) # update self._update_functions() return self
def free(self, *args, **kwargs)
Turns a constant into a parameter. As arguments, parameters must be strings. As keyword arguments, they can be set at the same time.
3.641537
3.424621
1.06334
if p is None: p = self.results[0] output = [] for n in range(len(self.f)): output.append(self._evaluate_f(n, self._xdata_massaged[n], p) ) return output
def _evaluate_all_functions(self, xdata, p=None)
This returns a list of function outputs given the stored data sets. This function relies on a previous call of set_data(). p=None means use the fit results
6.109316
5.839299
1.046241
# by default, use the fit values, otherwise, use the guess values. if p is None and self.results is not None: p = self.results[0] elif p is None and self.results is None: p = self._pguess # assemble the arguments for the function args = (xdata,) + tuple(p) # evaluate this function. return self.f[n](*args)
def _evaluate_f(self, n, xdata, p=None)
Evaluates a single function n for arbitrary xdata and p tuple. p=None means use the fit results
5.780433
5.071003
1.139899
# by default, use the fit values, otherwise, use the guess values. if p is None and self.results is not None: p = self.results[0] elif p is None and self.results is None: p = self._pguess # return None if there is no background function if self.bg[n] is None: return None # assemble the arguments for the function args = (xdata,) + tuple(p) # evaluate the function return self.bg[n](*args)
def _evaluate_bg(self, n, xdata, p=None)
Evaluates a single background function n for arbitrary xdata and p tuple. p=None means use the fit results
4.628568
3.982908
1.162107
# If we have weird stuff if not _s.fun.is_a_number(v) or not _s.fun.is_a_number(e) \ or v in [_n.inf, _n.nan, _n.NAN] or e in [_n.inf, _n.nan, _n.NAN]: return str(v)+pm+str(e) # Normal values. try: sig_figs = -int(_n.floor(_n.log10(abs(e))))+1 return str(_n.round(v, sig_figs)) + pm + str(_n.round(e, sig_figs)) except: return str(v)+pm+str(e)
def _format_value_error(self, v, e, pm=" +/- ")
Returns a string v +/- e with the right number of sig figs.
3.523631
3.35204
1.05119
if len(self._set_xdata)==0 or len(self._set_ydata)==0: return if p is None: if self.results is None: p = self._pguess else: p = self.results[0] # evaluate the function for all the data, returns a list! f = self._evaluate_all_functions(self._xdata_massaged, p) # get the full residuals list residuals = [] for n in range(len(f)): numerator = self._ydata_massaged[n]-f[n] denominator = _n.absolute(self._eydata_massaged[n]) residuals.append(numerator/denominator) return residuals
def _studentized_residuals_fast(self, p=None)
Returns a list of studentized residuals, (ydata - model)/error This function relies on a previous call to set_data(), and assumes self._massage_data() has been called (to increase speed). Parameters ---------- p=None Function parameters to use. None means use the fit results; if no fit, use guess results.
4.848478
4.708878
1.029646
if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None if p is None: p = self.results[0] # get the residuals rs = self.studentized_residuals(p) # Handle the none case if rs == None: return None # square em and sum em. cs = [] for r in rs: cs.append(sum(r**2)) return cs
def chi_squareds(self, p=None)
Returns a list of chi squared for each data set. Also uses ydata_massaged. p=None means use the fit results
6.459478
6.204464
1.041102
chi2s = self.chi_squareds(p) if chi2s == None: return None return sum(self.chi_squareds(p))
def chi_squared(self, p=None)
Returns the total chi squared (summed over all massaged data sets). p=None means use the fit results.
4.804676
4.133112
1.162484
if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None # Temporary hack: get the studentized residuals, which uses the massaged data # This should later be changed to get_massaged_data() r = self.studentized_residuals() # Happens if data / functions not defined if r == None: return # calculate the number of points N = 0.0 for i in range(len(r)): N += len(r[i]) return N-len(self._pnames)
def degrees_of_freedom(self)
Returns the number of degrees of freedom.
9.446973
8.793167
1.074354
if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None if p is None: p = self.results[0] r = self.studentized_residuals(p) # In case it's not possible to calculate if r is None: return # calculate the number of points N = 0 for i in range(len(r)): N += len(r[i]) # degrees of freedom dof_per_point = self.degrees_of_freedom()/N for n in range(len(r)): r[n] = sum(r[n]**2)/(len(r[n])*dof_per_point) return r
def reduced_chi_squareds(self, p=None)
Returns the reduced chi squared for each massaged data set. p=None means use the fit results.
4.192336
4.105969
1.021034
if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None if p is None: p = self.results[0] chi2 = self.chi_squared(p) dof = self.degrees_of_freedom() if not _s.fun.is_a_number(chi2) or not _s.fun.is_a_number(dof): return None return _n.divide(self.chi_squared(p), self.degrees_of_freedom())
def reduced_chi_squared(self, p=None)
Returns the reduced chi squared for all massaged data sets. p=None means use the fit results.
3.898383
3.889371
1.002317
if not self.results: self._error("You must complete a fit first.") return r = self.reduced_chi_squareds() # loop over the eydata and rescale for n in range(len(r)): self["scale_eydata"][n] *= _n.sqrt(r[n]) # the fit is no longer valid self.clear_results() # replot if self['autoplot']: self.plot() return self
def autoscale_eydata(self)
Rescales the error so the next fit will give reduced chi squareds of 1. Each data set will be scaled independently, and you may wish to run this a few times until it converges.
8.861539
7.582839
1.168631
# Use the xdata itself for the function if self['fpoints'][n] in [None, 0]: return _n.array(xdata) # Otherwise, generate xdata with the number of fpoints # do exponential ranging if xscale is log if self['xscale'][n] == 'log': return _n.logspace(_n.log10(min(xdata)), _n.log10(max(xdata)), self['fpoints'][n], True, 10.0) # otherwise do linear spacing else: return _n.linspace(min(xdata), max(xdata), self['fpoints'][n])
def _get_xdata_for_function(self, n, xdata)
Generates the x-data for plotting the function. Parameters ---------- n Which data set we're using xdata Data set upon which to base this Returns ------- float
4.700216
4.974291
0.944902
if len(self._set_xdata)==0 or len(self._set_ydata)==0: self._error("No data. Please use set_data() and plot() prior to trimming.") return if _s.fun.is_a_number(n): n = [n] elif isinstance(n,str): n = list(range(len(self._set_xdata))) # loop over the specified plots for i in n: try: if x: xmin, xmax = _p.figure(self['first_figure']+i).axes[1].get_xlim() self['xmin'][i] = xmin self['xmax'][i] = xmax if y: ymin, ymax = _p.figure(self['first_figure']+i).axes[1].get_ylim() self['ymin'][i] = ymin self['ymax'][i] = ymax except: self._error("Data "+str(i)+" is not currently plotted.") # now show the update. self.clear_results() if self['autoplot']: self.plot() return self
def trim(self, n='all', x=True, y=True)
This will set xmin and xmax based on the current zoom-level of the figures. n='all' Which figure to use for setting xmin and xmax. 'all' means all figures. You may also specify a list. x=True Trim the x-range y=True Trim the y-range
4.016689
3.894585
1.031352
if len(self._set_xdata)==0 or len(self._set_ydata)==0: self._error("No data. Please use set_data() and plot() prior to zooming.") return if _s.fun.is_a_number(n): n = [n] elif isinstance(n,str): n = list(range(len(self._set_xdata))) # loop over the specified plots for i in n: self['xmin'][i] = None self['xmax'][i] = None self['ymin'][i] = None self['ymax'][i] = None # now show the update. self.clear_results() if self['autoplot']: self.plot() return self
def untrim(self, n='all')
Removes xmin, xmax, ymin, and ymax. Parameters ---------- n='all' Which data set to perform this action upon. 'all' means all data sets, or you can specify a list.
5.527553
5.192823
1.06446
if len(self._set_xdata)==0 or len(self._set_ydata)==0: self._error("No data. Please use set_data() and plot() prior to zooming.") return # get the data xdata, ydata, eydata = self.get_data() if _s.fun.is_a_number(n): n = [n] elif isinstance(n,str): n = list(range(len(xdata))) # loop over the specified plots for i in n: fig = self['first_figure']+i try: xmin, xmax = _p.figure(fig).axes[1].get_xlim() xc = 0.5*(xmin+xmax) xs = 0.5*abs(xmax-xmin) self['xmin'][i] = xc - xfactor*xs self['xmax'][i] = xc + xfactor*xs ymin, ymax = _p.figure(fig).axes[1].get_ylim() yc = 0.5*(ymin+ymax) ys = 0.5*abs(ymax-ymin) self['ymin'][i] = yc - yfactor*ys self['ymax'][i] = yc + yfactor*ys except: self._error("Data "+str(fig)+" is not currently plotted.") # now show the update. self.clear_results() if self['autoplot']: self.plot() return self
def zoom(self, n='all', xfactor=2.0, yfactor=2.0)
This will scale the chosen data set's plot range by the specified xfactor and yfactor, respectively, and set the trim limits xmin, xmax, ymin, ymax accordingly Parameters ---------- n='all' Which data set to perform this action upon. 'all' means all data sets, or you can specify a list. xfactor=2.0 Factor by which to scale the x range. yfactor=2.0 Factor by which to scale the y range.
3.613839
3.607132
1.001859
# this will temporarily fix the deprecation warning import warnings import matplotlib.cbook warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation) _s.tweaks.raise_figure_window(data_set+self['first_figure']) return _p.ginput(**kwargs)
def ginput(self, data_set=0, **kwargs)
Pops up the figure for the specified data set. Returns value from pylab.ginput(). kwargs are sent to pylab.ginput()
11.419871
12.183866
0.937295
# Handle the None for x or y if x is None: # If x is none, y can be either [1,2] or [[1,2],[1,2]] if _fun.is_iterable(y[0]): # make an array of arrays to match x = [] for n in range(len(y)): x.append(list(range(len(y[n])))) else: x = list(range(len(y))) if y is None: # If x is none, y can be either [1,2] or [[1,2],[1,2]] if _fun.is_iterable(x[0]): # make an array of arrays to match y = [] for n in range(len(x)): y.append(list(range(len(x[n])))) else: y = list(range(len(x))) # At this point they should be matched, but may still be 1D # Default behavior: if all elements are numbers in both, assume they match if _fun.elements_are_numbers(x) and _fun.elements_are_numbers(y): x = [x] y = [y] # Second default behavior: shared array [1,2,3], [[1,2,1],[1,2,1]] or vis versa if _fun.elements_are_numbers(x) and not _fun.elements_are_numbers(y): x = [x]*len(y) if _fun.elements_are_numbers(y) and not _fun.elements_are_numbers(x): y = [y]*len(x) # Clean up any remaining Nones for n in range(len(x)): if x[n] is None: x[n] = list(range(len(y[n]))) if y[n] is None: y[n] = list(range(len(x[n]))) return x, y
def _match_data_sets(x,y)
Makes sure everything is the same shape. "Intelligently".
2.666129
2.644542
1.008163
# Simplest case, ex is None or a number if not _fun.is_iterable(ex): # Just make a matched list of Nones if ex is None: ex = [ex]*len(x) # Make arrays of numbers if _fun.is_a_number(ex): value = ex # temporary storage ex = [] for n in range(len(x)): ex.append([value]*len(x[n])) # Otherwise, ex is iterable # Default behavior: If the elements are all numbers and the length matches # that of the first x-array, assume this is meant to match all the x # data sets if _fun.elements_are_numbers(ex) and len(ex) == len(x[0]): ex = [ex]*len(x) # The user may specify a list of some iterable and some not. Assume # in this case that at least the lists are the same length for n in range(len(x)): # do nothing to the None's # Inflate single numbers to match if _fun.is_a_number(ex[n]): ex[n] = [ex[n]]*len(x[n]) return ex
def _match_error_to_data_set(x, ex)
Inflates ex to match the dimensionality of x, "intelligently". x is assumed to be a 2D array.
6.622777
6.228205
1.063352
_pylab.ioff() # generate the data the easy way try: rdata = _n.real(data) idata = _n.imag(data) if edata is None: erdata = None eidata = None else: erdata = _n.real(edata) eidata = _n.imag(edata) # generate the data the hard way. except: rdata = [] idata = [] if edata is None: erdata = None eidata = None else: erdata = [] eidata = [] for n in range(len(data)): rdata.append(_n.real(data[n])) idata.append(_n.imag(data[n])) if not edata is None: erdata.append(_n.real(edata[n])) eidata.append(_n.imag(edata[n])) if 'xlabel' not in kwargs: kwargs['xlabel'] = 'Real' if 'ylabel' not in kwargs: kwargs['ylabel'] = 'Imaginary' xy_data(rdata, idata, eidata, erdata, draw=False, **kwargs) if draw: _pylab.ion() _pylab.draw() _pylab.show()
def complex_data(data, edata=None, draw=True, **kwargs)
Plots the imaginary vs real for complex data. Parameters ---------- data Array of complex data edata=None Array of complex error bars draw=True Draw the plot after it's assembled? See spinmob.plot.xy.data() for additional optional keyword arguments.
2.056198
2.029394
1.013208
datas = [] labels = [] if escript is None: errors = None else: errors = [] for d in ds: datas.append(d(script)) labels.append(_os.path.split(d.path)[-1]) if not escript is None: errors.append(d(escript)) complex_data(datas, errors, label=labels, **kwargs) if "draw" in kwargs and not kwargs["draw"]: return _pylab.ion() _pylab.draw() _pylab.show() return ds
def complex_databoxes(ds, script='d[1]+1j*d[2]', escript=None, **kwargs)
Uses databoxes and specified script to generate data and send to spinmob.plot.complex_data() Parameters ---------- ds List of databoxes script='d[1]+1j*d[2]' Complex-valued script for data array. escript=None Complex-valued script for error bars See spinmob.plot.complex.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts.
4.221303
4.44505
0.949664
ds = _data.load_multiple(paths=paths) if len(ds) == 0: return if 'title' not in kwargs: kwargs['title'] = _os.path.split(ds[0].path)[0] return complex_databoxes(ds, script=script, **kwargs)
def complex_files(script='d[1]+1j*d[2]', escript=None, paths=None, **kwargs)
Loads files and plots complex data in the real-imaginary plane. Parameters ---------- script='d[1]+1j*d[2]' Complex-valued script for data array. escript=None Complex-valued script for error bars paths=None List of paths to open. None means use a dialog See spinmob.plot.complex.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog.
5.981081
5.403835
1.106822
kwargs2 = dict(xlabel='Real', ylabel='Imaginary') kwargs2.update(kwargs) function(f, xmin, xmax, steps, p, g, erange, plotter=xy_data, complex_plane=True, draw=True, **kwargs2)
def complex_function(f='1.0/(1+1j*x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, **kwargs)
Plots function(s) in the complex plane over the specified range. Parameters ---------- f='1.0/(1+1j*x)' Complex-valued function or list of functions to plot. These can be string functions or single-argument python functions; additional globals can be supplied by g. xmin=-1, xmax=1, steps=200 Range over which to plot and how many points to plot p='x' If using strings for functions, p is the independent parameter name. g=None Optional dictionary of extra globals. Try g=globals()! erange=False Use exponential spacing of the x data? See spinmob.plot.xy.data() for additional optional keyword arguments.
5.09589
5.076021
1.003914
_pylab.ioff() # set up the figure and axes if figure == 'gcf': f = _pylab.gcf() if clear: f.clear() axes1 = _pylab.subplot(211) axes2 = _pylab.subplot(212,sharex=axes1) # Make sure the dimensionality of the data sets matches xdata, ydata = _match_data_sets(xdata, ydata) exdata = _match_error_to_data_set(xdata, exdata) eydata = _match_error_to_data_set(ydata, eydata) # convert to magnitude and phase m = [] p = [] em = [] ep = [] # Note this is a loop over data sets, not points. for l in range(len(ydata)): m.append(_n.abs(ydata[l])) p.append(_n.angle(ydata[l])) # get the mag - phase errors if eydata[l] is None: em.append(None) ep.append(None) else: er = _n.real(eydata[l]) ei = _n.imag(eydata[l]) em.append(0.5*((er+ei) + (er-ei)*_n.cos(p[l])) ) ep.append(0.5*((er+ei) - (er-ei)*_n.cos(p[l]))/m[l] ) # convert to degrees if phase=='degrees': p[-1] = p[-1]*180.0/_n.pi if not ep[l] is None: ep[l] = ep[l]*180.0/_n.pi if phase=='degrees': plabel = plabel + " (degrees)" else: plabel = plabel + " (radians)" if 'xlabel' in kwargs: xlabel=kwargs.pop('xlabel') else: xlabel='' if 'ylabel' in kwargs: kwargs.pop('ylabel') if 'autoformat' not in kwargs: kwargs['autoformat'] = True autoformat = kwargs['autoformat'] kwargs['autoformat'] = False kwargs['xlabel'] = '' xy_data(xdata, m, em, exdata, ylabel=mlabel, axes=axes1, clear=0, xscale=xscale, yscale=mscale, draw=False, **kwargs) kwargs['autoformat'] = autoformat kwargs['xlabel'] = xlabel xy_data(xdata, p, ep, exdata, ylabel=plabel, axes=axes2, clear=0, xscale=xscale, yscale=pscale, draw=False, **kwargs) axes2.set_title('') if draw: _pylab.ion() _pylab.draw() _pylab.show()
def magphase_data(xdata, ydata, eydata=None, exdata=None, xscale='linear', mscale='linear', pscale='linear', mlabel='Magnitude', plabel='Phase', phase='degrees', figure='gcf', clear=1, draw=True, **kwargs)
Plots the magnitude and phase of complex ydata vs xdata. Parameters ---------- xdata Real-valued x-axis data ydata Complex-valued y-axis data eydata=None Complex-valued y-error exdata=None Real-valued x-error xscale='linear' 'log' or 'linear' scale of the x axis mscale='linear' 'log' or 'linear' scale of the magnitude axis pscale='linear' 'log' or 'linear' scale of the phase axis mlabel='Magnitude' y-axis label for magnitude plot plabel='Phase' y-axis label for phase plot phase='degrees' 'degrees' or 'radians' for the phase axis figure='gcf' Plot on the specified figure instance or 'gcf' for current figure. clear=1 Clear the figure? draw=True Draw the figure when complete? See spinmob.plot.xy.data() for additional optional keyword arguments.
2.602958
2.614351
0.995642
databoxes(ds, xscript, yscript, eyscript, exscript, plotter=magphase_data, g=g, **kwargs)
def magphase_databoxes(ds, xscript=0, yscript='d[1]+1j*d[2]', eyscript=None, exscript=None, g=None, **kwargs)
Use databoxes and scripts to generate data and plot the complex magnitude and phase versus xdata. Parameters ---------- ds List of databoxes xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error g=None Optional dictionary of globals for the scripts See spinmob.plot.magphase.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts.
3.91271
4.729657
0.827271
return files(xscript, yscript, eyscript, exscript, plotter=magphase_databoxes, paths=paths, g=g, **kwargs)
def magphase_files(xscript=0, yscript='d[1]+1j*d[2]', eyscript=None, exscript=None, paths=None, g=None, **kwargs)
This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata's magnitude and phase versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error paths=None List of paths to open. g=None Optional dictionary of globals for the scripts See spinmob.plot.magphase.data() for additional optional arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog.
5.17098
7.777546
0.66486
function(f, xmin, xmax, steps, p, g, erange, plotter=magphase_data, **kwargs)
def magphase_function(f='1.0/(1+1j*x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, **kwargs)
Plots function(s) magnitude and phase over the specified range. Parameters ---------- f='1.0/(1+1j*x)' Complex-valued function or list of functions to plot. These can be string functions or single-argument python functions; additional globals can be supplied by g. xmin=-1, xmax=1, steps=200 Range over which to plot and how many points to plot p='x' If using strings for functions, p is the independent parameter name. g=None Optional dictionary of extra globals. Try g=globals()! erange=False Use exponential spacing of the x data? See spinmob.plot.xy.data() for additional optional keyword arguments.
5.450623
5.776501
0.943586
_pylab.ioff() # Make sure the dimensionality of the data sets matches xdata, ydata = _match_data_sets(xdata, ydata) exdata = _match_error_to_data_set(xdata, exdata) eydata = _match_error_to_data_set(ydata, eydata) # convert to real imag, and get error bars rdata = [] idata = [] erdata = [] eidata = [] for l in range(len(ydata)): rdata.append(_n.real(ydata[l])) idata.append(_n.imag(ydata[l])) if eydata[l] is None: erdata.append(None) eidata.append(None) else: erdata.append(_n.real(eydata[l])) eidata.append(_n.imag(eydata[l])) # set up the figure and axes if figure == 'gcf': f = _pylab.gcf() if clear: f.clear() axes1 = _pylab.subplot(211) axes2 = _pylab.subplot(212,sharex=axes1) if 'xlabel' in kwargs : xlabel=kwargs.pop('xlabel') else: xlabel='' if 'ylabel' in kwargs : kwargs.pop('ylabel') if 'tall' not in kwargs: kwargs['tall'] = False if 'autoformat' not in kwargs: kwargs['autoformat'] = True autoformat = kwargs['autoformat'] kwargs['autoformat'] = False kwargs['xlabel'] = '' xy_data(xdata, rdata, eydata=erdata, exdata=exdata, ylabel=rlabel, axes=axes1, clear=0, xscale=xscale, yscale=rscale, draw=False, **kwargs) kwargs['autoformat'] = autoformat kwargs['xlabel'] = xlabel xy_data(xdata, idata, eydata=eidata, exdata=exdata, ylabel=ilabel, axes=axes2, clear=0, xscale=xscale, yscale=iscale, draw=False, **kwargs) axes2.set_title('') if draw: _pylab.ion() _pylab.draw() _pylab.show()
def realimag_data(xdata, ydata, eydata=None, exdata=None, xscale='linear', rscale='linear', iscale='linear', rlabel='Real', ilabel='Imaginary', figure='gcf', clear=1, draw=True, **kwargs)
Plots the real and imaginary parts of complex ydata vs xdata. Parameters ---------- xdata Real-valued x-axis data ydata Complex-valued y-axis data eydata=None Complex-valued y-error exdata=None Real-valued x-error xscale='linear' 'log' or 'linear' scale of the x axis rscale='linear' 'log' or 'linear' scale of the real axis iscale='linear' 'log' or 'linear' scale of the imaginary axis rlabel='Magnitude' y-axis label for real value plot ilabel='Phase' y-axis label for imaginary value plot figure='gcf' Plot on the specified figure instance or 'gcf' for current figure. clear=1 Clear the figure? draw=True Draw the figure when completed? See spinmob.plot.xy.data() for additional optional keyword arguments.
2.354725
2.396792
0.982449
databoxes(ds, xscript, yscript, eyscript, exscript, plotter=realimag_data, g=g, **kwargs)
def realimag_databoxes(ds, xscript=0, yscript="d[1]+1j*d[2]", eyscript=None, exscript=None, g=None, **kwargs)
Use databoxes and scripts to generate data and plot the real and imaginary ydata versus xdata. Parameters ---------- ds List of databoxes xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error g=None Optional dictionary of globals for the scripts See spinmob.plot.realimag.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts.
4.230903
5.014441
0.843744
return files(xscript, yscript, eyscript, exscript, plotter=realimag_databoxes, paths=paths, g=g, **kwargs)
def realimag_files(xscript=0, yscript="d[1]+1j*d[2]", eyscript=None, exscript=None, paths=None, g=None, **kwargs)
This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata's real and imaginary parts versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error paths=None List of paths to open. g=None Optional dictionary of globals for the scripts See spinmob.plot.realimag.data() for additional optional arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog.
5.305488
8.007433
0.66257
function(f, xmin, xmax, steps, p, g, erange, plotter=realimag_data, **kwargs)
def realimag_function(f='1.0/(1+1j*x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, **kwargs)
Plots function(s) real and imaginary parts over the specified range. Parameters ---------- f='1.0/(1+1j*x)' Complex-valued function or list of functions to plot. These can be string functions or single-argument python functions; additional globals can be supplied by g. xmin=-1, xmax=1, steps=200 Range over which to plot and how many points to plot p='x' If using strings for functions, p is the independent parameter name. g=None Optional dictionary of extra globals. Try g=globals()! erange=False Use exponential spacing of the x data? See spinmob.plot.xy.data() for additional optional keyword arguments.
5.228639
5.997972
0.871734
databoxes(ds, xscript, yscript, eyscript, exscript, plotter=xy_data, g=g, **kwargs)
def xy_databoxes(ds, xscript=0, yscript='d[1]', eyscript=None, exscript=None, g=None, **kwargs)
Use databoxes and scripts to generate and plot ydata versus xdata. Parameters ---------- ds List of databoxes xscript=0 Script for x data yscript='d[1]' Script for y data eyscript=None Script for y error exscript=None Script for x error g=None Optional dictionary of globals for the scripts See spinmob.plot.xy.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts.
3.972083
4.681725
0.848423
return files(xscript, yscript, eyscript, exscript, plotter=xy_databoxes, paths=paths, g=g, **kwargs)
def xy_files(xscript=0, yscript='d[1]', eyscript=None, exscript=None, paths=None, g=None, **kwargs)
This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]' Script for y data eyscript=None Script for y error exscript=None Script for x error paths=None List of paths to open. g=None Optional dictionary of globals for the scripts See spinmob.plot.xy.data() for additional optional arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog.
5.171615
8.319957
0.621592
function(f, xmin, xmax, steps, p, g, erange, plotter=xy_data, **kwargs)
def xy_function(f='sin(x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, **kwargs)
Plots function(s) over the specified range. Parameters ---------- f='sin(x)' Function or list of functions to plot. These can be string functions or single-argument python functions; additional globals can be supplied by g. xmin=-1, xmax=1, steps=200 Range over which to plot and how many points to plot p='x' If using strings for functions, p is the independent parameter name. g=None Optional dictionary of extra globals. Try g=globals()! erange=False Use exponential spacing of the x data? See spinmob.plot.xy.data() for additional optional keyword arguments.
5.304897
5.071482
1.046025
if 'delimiter' in kwargs: delimiter = kwargs.pop('delimiter') else: delimiter = None if 'filters' in kwargs: filters = kwargs.pop('filters') else: filters = '*.*' ds = _data.load_multiple(paths=paths, delimiter=delimiter, filters=filters) if ds is None or len(ds) == 0: return # generate a default title (the directory) if 'title' not in kwargs: kwargs['title']=_os.path.split(ds[0].path)[0] # run the databox plotter plotter(ds, xscript=xscript, yscript=yscript, eyscript=eyscript, exscript=exscript, g=g, **kwargs) return ds
def files(xscript=0, yscript=1, eyscript=None, exscript=None, g=None, plotter=xy_databoxes, paths=None, **kwargs)
This will load a bunch of data files, generate data based on the supplied scripts, and then plot this data using the specified databox plotter. xscript, yscript, eyscript, exscript scripts to generate x, y, and errors g optional dictionary of globals optional: filters="*.*" to set the file filters for the dialog. **kwargs are sent to plotter()
3.265539
3.193198
1.022655
global _colormap # Set interpolation to something more relevant for every day science if not 'interpolation' in kwargs.keys(): kwargs['interpolation'] = 'nearest' _pylab.ioff() fig = _pylab.gcf() if clear: fig.clear() _pylab.axes() # generate the 3d axes X = _n.array(X) Y = _n.array(Y) Z = _n.array(Z) # assume X and Y are the bin centers and figure out the bin widths x_width = abs(float(X[-1] - X[0])/(len(Z[0])-1)) y_width = abs(float(Y[-1] - Y[0])/(len(Z)-1)) # reverse the Z's # Transpose and reverse Z = Z.transpose() Z = Z[-1::-1] # get rid of the label and title kwargs xlabel='' ylabel='' title ='' if 'xlabel' in kwargs: xlabel = kwargs.pop('xlabel') if 'ylabel' in kwargs: ylabel = kwargs.pop('ylabel') if 'title' in kwargs: title = kwargs.pop('title') _pylab.imshow(Z, extent=[X[0]-x_width/2.0, X[-1]+x_width/2.0, Y[0]-y_width/2.0, Y[-1]+y_width/2.0], **kwargs) cb = _pylab.colorbar() _pt.image_set_clim(zmin,zmax) _pt.image_set_aspect(aspect) cb.set_label(clabel) a = _pylab.gca() a.set_xlabel(xlabel) a.set_ylabel(ylabel) #_pt.close_sliders() #_pt.image_sliders() # title history = _fun.get_shell_history() for n in range(0, min(shell_history, len(history))): title = title + "\n" + history[n].split('\n')[0].strip() title = title + '\nPlot created ' + _time.asctime() a.set_title(title.strip()) if autoformat: _pt.image_format_figure(fig) _pylab.ion() _pylab.show() #_pt.raise_figure_window() #_pt.raise_pyshell() _pylab.draw() # add the color sliders if colormap: if _colormap: _colormap.close() _colormap = _pt.image_colormap(colormap, image=a.images[0])
def image_data(Z, X=[0,1.0], Y=[0,1.0], aspect=1.0, zmin=None, zmax=None, clear=1, clabel='z', autoformat=True, colormap="Last Used", shell_history=0, **kwargs)
Generates an image plot. Parameters ---------- Z 2-d array of z-values X=[0,1.0], Y=[0,1.0] 1-d array of x-values (only the first and last element are used) See matplotlib's imshow() for additional optional arguments.
3.442843
3.547691
0.970446
default_kwargs = dict(clabel=str(f), xlabel='x', ylabel='y') default_kwargs.update(kwargs) # aggregate globals if not g: g = {} for k in list(globals().keys()): if k not in g: g[k] = globals()[k] if type(f) == str: f = eval('lambda ' + p + ': ' + f, g) # generate the grid x and y coordinates xones = _n.linspace(1,1,ysteps) x = _n.linspace(xmin, xmax, xsteps) xgrid = _n.outer(xones, x) yones = _n.linspace(1,1,xsteps) y = _n.linspace(ymin, ymax, ysteps) ygrid = _n.outer(y, yones) # now get the z-grid try: # try it the fast numpy way. Add 0 to assure dimensions zgrid = f(xgrid, ygrid) + xgrid*0.0 except: print("Notice: function is not rocking hardcore. Generating grid the slow way...") # manually loop over the data to generate the z-grid zgrid = [] for ny in range(0, len(y)): zgrid.append([]) for nx in range(0, len(x)): zgrid[ny].append(f(x[nx], y[ny])) zgrid = _n.array(zgrid) # now plot! image_data(zgrid.transpose(), x, y, **default_kwargs)
def image_function(f='sin(5*x)*cos(5*y)', xmin=-1, xmax=1, ymin=-1, ymax=1, xsteps=100, ysteps=100, p='x,y', g=None, **kwargs)
Plots a 2-d function over the specified range Parameters ---------- f='sin(5*x)*cos(5*y)' Takes two inputs and returns one value. Can also be a string function such as sin(x*y) xmin=-1, xmax=1, ymin=-1, ymax=1 Range over which to generate/plot the data xsteps=100, ysteps=100 How many points to plot on the specified range p='x,y' If using strings for functions, this is a string of parameters. g=None Optional additional globals. Try g=globals()! See spinmob.plot.image.data() for additional optional keyword arguments.
3.893913
3.826847
1.017525
if 'delimiter' in kwargs: delimiter = kwargs.pop('delimiter') else: delimiter = None d = _data.load(paths=path, delimiter = delimiter) if d is None or len(d) == 0: return # allows the user to overwrite the defaults default_kwargs = dict(xlabel = str(xscript), ylabel = str(yscript), title = d.path, clabel = str(zscript)) default_kwargs.update(kwargs) # get the data X = d(xscript, g) Y = d(yscript, g) Z = _n.array(d(zscript, g)) # Z = Z.transpose() # plot! image_data(Z, X, Y, **default_kwargs)
def image_file(path=None, zscript='self[1:]', xscript='[0,1]', yscript='d[0]', g=None, **kwargs)
Loads an data file and plots it with color. Data file must have columns of the same length! Parameters ---------- path=None Path to data file. zscript='self[1:]' Determines how to get data from the columns xscript='[0,1]', yscript='d[0]' Determine the x and y arrays used for setting the axes bounds g=None Optional dictionary of globals for the scripts See spinmob.plot.image.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts.
4.430364
4.566982
0.970086
if not g: g = {} for k in list(globals().keys()): if k not in g: g[k] = globals()[k] # if the x-axis is a log scale, use erange if erange: r = _fun.erange(tmin, tmax, steps) else: r = _n.linspace(tmin, tmax, steps) # make sure it's a list so we can loop over it if not type(fy) in [type([]), type(())]: fy = [fy] if not type(fx) in [type([]), type(())]: fx = [fx] # loop over the list of functions xdatas = [] ydatas = [] labels = [] for fs in fx: if type(fs) == str: a = eval('lambda ' + p + ': ' + fs, g) a.__name__ = fs else: a = fs x = [] for z in r: x.append(a(z)) xdatas.append(x) labels.append(a.__name__) for n in range(len(fy)): fs = fy[n] if type(fs) == str: a = eval('lambda ' + p + ': ' + fs, g) a.__name__ = fs else: a = fs y = [] for z in r: y.append(a(z)) ydatas.append(y) labels[n] = labels[n]+', '+a.__name__ # plot! xy_data(xdatas, ydatas, label=labels, **kwargs)
def parametric_function(fx='sin(t)', fy='cos(t)', tmin=-1, tmax=1, steps=200, p='t', g=None, erange=False, **kwargs)
Plots the parametric function over the specified range Parameters ---------- fx='sin(t)', fy='cos(t)' Functions or (matching) lists of functions to plot; can be string functions or python functions taking one argument tmin=-1, tmax=1, steps=200 Range over which to plot, and how many points to plot p='t' If using strings for functions, p is the parameter name g=None Optional dictionary of extra globals. Try g=globals()! erange=False Use exponential spacing of the t data? See spinmob.plot.xy.data() for additional optional keyword arguments.
2.648294
2.542077
1.041783
for key in list(self.keys()): self.iterators[key] = _itertools.cycle(self[key]) return self
def reset(self)
Resets the style cycle.
8.483645
7.139599
1.188252
if axes=="gca": axes = _pylab.gca() axes.text(x, y, text, transform=axes.transAxes, **kwargs) if draw: _pylab.draw()
def add_text(text, x=0.01, y=0.01, axes="gca", draw=True, **kwargs)
Adds text to the axes at the specified position. **kwargs go to the axes.text() function.
2.345048
2.948413
0.795359
# Disable auto-updating by default. _pylab.ioff() if axes=="gca": axes = _pylab.gca() # get the current bounds x10, x20 = axes.get_xlim() y10, y20 = axes.get_ylim() # Autoscale using pylab's technique (catches the error bars!) axes.autoscale(enable=True, tight=True) # Add padding if axes.get_xscale() == 'linear': x1, x2 = axes.get_xlim() xc = 0.5*(x1+x2) xs = 0.5*(1+x_space)*(x2-x1) axes.set_xlim(xc-xs, xc+xs) if axes.get_yscale() == 'linear': y1, y2 = axes.get_ylim() yc = 0.5*(y1+y2) ys = 0.5*(1+y_space)*(y2-y1) axes.set_ylim(yc-ys, yc+ys) # If we weren't supposed to zoom x or y, reset them if not zoomx: axes.set_xlim(x10, x20) if not zoomy: axes.set_ylim(y10, y20) if draw: _pylab.ion() _pylab.draw()
def auto_zoom(zoomx=True, zoomy=True, axes="gca", x_space=0.04, y_space=0.04, draw=True)
Looks at the bounds of the plotted data and zooms accordingly, leaving some space around the data.
2.426212
2.464751
0.984364
c1 = _pylab.ginput() if len(c1)==0: return None c2 = _pylab.ginput() if len(c2)==0: return None return (c1[0][1]-c2[0][1])/(c1[0][0]-c2[0][0])
def click_estimate_slope()
Takes two clicks and returns the slope. Right-click aborts.
2.763185
2.160094
1.279196
c1 = _pylab.ginput() if len(c1)==0: return None c2 = _pylab.ginput() if len(c2)==0: return None return 2*(c2[0][1]-c1[0][1])/(c2[0][0]-c1[0][0])**2
def click_estimate_curvature()
Takes two clicks and returns the curvature, assuming the first click was the minimum of a parabola and the second was some other point. Returns the second derivative of the function giving this parabola. Right-click aborts.
2.911
2.428825
1.198522
c1 = _pylab.ginput() if len(c1)==0: return None c2 = _pylab.ginput() if len(c2)==0: return None return [c2[0][0]-c1[0][0], c2[0][1]-c1[0][1]]
def click_estimate_difference()
Takes two clicks and returns the difference vector [dx, dy]. Right-click aborts.
2.900104
2.223172
1.304489
try: import pyqtgraph as _p # Get the current figure if necessary if figure is 'gcf': figure = _s.pylab.gcf() # Store the figure as an image path = _os.path.join(_s.settings.path_home, "clipboard.png") figure.savefig(path) # Set the clipboard. I know, it's weird to use pyqtgraph, but # This covers both Qt4 and Qt5 with their Qt4 wrapper! _p.QtGui.QApplication.instance().clipboard().setImage(_p.QtGui.QImage(path)) except: print("This function currently requires pyqtgraph to be installed.")
def copy_figure_to_clipboard(figure='gcf')
Copies the specified figure to the system clipboard. Specifying 'gcf' will use the current figure.
6.977283
6.914317
1.009107
if neighbors: def D(x,y): return _fun.derivative_fit(x,y,neighbors) else: def D(x,y): return _fun.derivative(x,y) if fyname==1: fyname = '$\\partial_{x(\\pm'+str(neighbors)+')}$' manipulate_shown_data(D, fxname=None, fyname=fyname, **kwargs)
def differentiate_shown_data(neighbors=1, fyname=1, **kwargs)
Differentiates the data visible on the specified axes using fun.derivative_fit() (if neighbors > 0), and derivative() otherwise. Modifies the visible data using manipulate_shown_data(**kwargs)
5.710102
3.868456
1.476067
# get the axes if axes=="gca": axes = _pylab.gca() # get the range for trimming _pylab.sca(axes) xmin,xmax = axes.get_xlim() ymin,ymax = axes.get_ylim() # update the kwargs if 'first_figure' not in kwargs: kwargs['first_figure'] = axes.figure.number+1 # loop over the lines fitters = [] for l in axes.lines: # get the trimmed data x,y = l.get_data() x,y = _s.fun.trim_data_uber([x,y],[xmin<x,x<xmax,ymin<y,y<ymax]) # create a fitter fitters.append(_s.data.fitter(**kwargs).set_functions(f=f, p=p)) fitters[-1].set_data(x,y) fitters[-1].fit() fitters[-1].autoscale_eydata().fit() if verbose: print(fitters[-1]) print("<click the graph to continue>") if not axes.lines[-1] == l: fitters[-1].ginput(timeout=0) return fitters
def fit_shown_data(f="a*x+b", p="a=1, b=2", axes="gca", verbose=True, **kwargs)
Fast-and-loos quick fit: Loops over each line of the supplied axes and fits with the supplied function (f) and parameters (p). Assumes uniform error and scales this such that the reduced chi^2 is 1. Returns a list of fitter objects **kwargs are sent to _s.data.fitter()
4.659133
4.191475
1.111573
_pylab.ioff() if figure == None: figure = _pylab.gcf() if modify_geometry: if tall: set_figure_window_geometry(figure, (0,0), (550,700)) else: set_figure_window_geometry(figure, (0,0), (550,400)) legend_position=1.01 # first, find overall bounds of all axes. ymin = 1.0 ymax = 0.0 xmin = 1.0 xmax = 0.0 for axes in figure.get_axes(): (x,y,dx,dy) = axes.get_position().bounds if y < ymin: ymin = y if y+dy > ymax: ymax = y+dy if x < xmin: xmin = x if x+dx > xmax: xmax = x+dx # Fraction of the figure's width and height to use for all the plots. w = 0.55 h = 0.75 # buffers on left and bottom edges bb = 0.15 bl = 0.15 xscale = w / (xmax-xmin) yscale = h / (ymax-ymin) # save this for resetting current_axes = _pylab.gca() # loop over the axes for axes in figure.get_axes(): # Get the axes bounds (x,y,dx,dy) = axes.get_position().bounds y = bb + (y-ymin)*yscale dy = dy * yscale x = bl + (x-xmin)*xscale dx = dx * xscale axes.set_position([x,y,dx,dy]) # set the position of the legend _pylab.axes(axes) # set the current axes if len(axes.lines)>0: _pylab.legend(loc=[legend_position, 0], borderpad=0.02, prop=_FontProperties(size=7)) # set the label spacing in the legend if axes.get_legend(): axes.get_legend().labelsep = 0.01 axes.get_legend().set_visible(1) # set up the title label axes.title.set_horizontalalignment('right') axes.title.set_size(8) axes.title.set_position([1.5,1.02]) axes.title.set_visible(1) #axes.yaxis.label.set_horizontalalignment('center') #axes.xaxis.label.set_horizontalalignment('center') _pylab.axes(current_axes) if draw: _pylab.ion() _pylab.draw()
def format_figure(figure=None, tall=False, draw=True, modify_geometry=True)
This formats the figure in a compact way with (hopefully) enough useful information for printing large data sets. Used mostly for line and scatter plots with long, information-filled titles. Chances are somewhat slim this will be ideal for you but it very well might and is at least a good starting point. figure=None specify a figure object. None will use gcf()
2.930225
2.990189
0.979947
if type(fig)==str: fig = _pylab.gcf() elif _fun.is_a_number(fig): fig = _pylab.figure(fig) # Qt4Agg backend. Probably would work for other Qt stuff if _pylab.get_backend().find('Qt') >= 0: size = fig.canvas.window().size() pos = fig.canvas.window().pos() return [[pos.x(),pos.y()], [size.width(),size.height()]] else: print("get_figure_window_geometry() only implemented for QtAgg backend.") return None
def get_figure_window_geometry(fig='gcf')
This will currently only work for Qt4Agg and WXAgg backends. Returns position, size postion = [x, y] size = [width, height] fig can be 'gcf', a number, or a figure object.
4.859912
4.358427
1.115061
_pylab.ioff() if figure == None: figure = _pylab.gcf() set_figure_window_geometry(figure, (0,0), (550,470)) axes = figure.axes[0] # set up the title label axes.title.set_horizontalalignment('right') axes.title.set_size(8) axes.title.set_position([1.27,1.02]) axes.title.set_visible(1) if draw: _pylab.ion() _pylab.draw()
def image_format_figure(figure=None, draw=True)
This formats the figure in a compact way with (hopefully) enough useful information for printing large data sets. Used mostly for line and scatter plots with long, information-filled titles. Chances are somewhat slim this will be ideal for you but it very well might and is at least a good starting point. figure=None specify a figure object. None will use gcf()
3.857692
4.374578
0.881843
if axes=="gca": axes = _pylab.gca() # make these axes current _pylab.axes(axes) # loop over all the lines_pylab. for n in range(0,len(axes.lines)): if n > limit-1 and not n==len(axes.lines)-1: axes.lines[n].set_label("_nolegend_") if n == limit-1 and not n==len(axes.lines)-1: axes.lines[n].set_label("...") _pylab.legend(**kwargs)
def impose_legend_limit(limit=30, axes="gca", **kwargs)
This will erase all but, say, 30 of the legend entries and remake the legend. You'll probably have to move it back into your favorite position at this point.
4.503969
4.475401
1.006383
if image == "auto": image = _pylab.gca().images[0] Z = _n.array(image.get_array()) # store this image in the undo list global image_undo_list image_undo_list.append([image, Z]) if len(image_undo_list) > 10: image_undo_list.pop(0) # images have transposed data image.set_array(_fun.coarsen_matrix(Z, ylevel, xlevel, method)) # update the plot _pylab.draw()
def image_coarsen(xlevel=0, ylevel=0, image="auto", method='average')
This will coarsen the image data by binning each xlevel+1 along the x-axis and each ylevel+1 points along the y-axis type can be 'average', 'min', or 'max'
4.383852
4.846025
0.904628
if image == "auto": image = _pylab.gca().images[0] Z = _n.array(image.get_array()) # store this image in the undo list global image_undo_list image_undo_list.append([image, Z]) if len(image_undo_list) > 10: image_undo_list.pop(0) # get the diagonal smoothing level (eliptical, and scaled down by distance) dlevel = ((xlevel**2+ylevel**2)/2.0)**(0.5) # don't touch the first column new_Z = [Z[0]*1.0] for m in range(1,len(Z)-1): new_Z.append(Z[m]*1.0) for n in range(1,len(Z[0])-1): new_Z[-1][n] = (Z[m,n] + xlevel*(Z[m+1,n]+Z[m-1,n]) + ylevel*(Z[m,n+1]+Z[m,n-1]) \ + dlevel*(Z[m+1,n+1]+Z[m-1,n+1]+Z[m+1,n-1]+Z[m-1,n-1]) ) \ / (1.0+xlevel*2+ylevel*2 + dlevel*4) # don't touch the last column new_Z.append(Z[-1]*1.0) # images have transposed data image.set_array(_n.array(new_Z)) # update the plot _pylab.draw()
def image_neighbor_smooth(xlevel=0.2, ylevel=0.2, image="auto")
This will bleed nearest neighbor pixels into each other with the specified weight factors.
2.987139
3.048033
0.980022
if len(image_undo_list) <= 0: print("no undos in memory") return [image, Z] = image_undo_list.pop(-1) image.set_array(Z) _pylab.draw()
def image_undo()
Undoes the last coarsen or smooth command.
5.436756
5.346339
1.016912
if axes is "gca": axes = _pylab.gca() e = axes.get_images()[0].get_extent() axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)
def image_set_aspect(aspect=1.0, axes="gca")
sets the aspect ratio of the current zoom level of the imshow image
2.899302
2.911367
0.995856
if axes == "gca": axes = _pylab.gca() # get the current plot limits xlim = axes.get_xlim() ylim = axes.get_ylim() # get the old extent extent = axes.images[0].get_extent() # calculate the fractional extents x0 = extent[0] y0 = extent[2] xwidth = extent[1]-x0 ywidth = extent[3]-y0 frac_x1 = (xlim[0]-x0)/xwidth frac_x2 = (xlim[1]-x0)/xwidth frac_y1 = (ylim[0]-y0)/ywidth frac_y2 = (ylim[1]-y0)/ywidth # set the new if not x == None: extent[0] = x[0] extent[1] = x[1] if not y == None: extent[2] = y[0] extent[3] = y[1] # get the new zoom window x0 = extent[0] y0 = extent[2] xwidth = extent[1]-x0 ywidth = extent[3]-y0 x1 = x0 + xwidth*frac_x1 x2 = x0 + xwidth*frac_x2 y1 = y0 + ywidth*frac_y1 y2 = y0 + ywidth*frac_y2 # set the extent axes.images[0].set_extent(extent) # rezoom us axes.set_xlim(x1,x2) axes.set_ylim(y1,y2) # draw image_set_aspect(1.0)
def image_set_extent(x=None, y=None, axes="gca")
Set's the first image's extent, then redraws. Examples: x = [1,4] y = [33.3, 22]
2.002662
2.065166
0.969734
if axes == "gca": axes = _pylab.gca() e = axes.images[0].get_extent() x1 = e[0]*xscale x2 = e[1]*xscale y1 = e[2]*yscale y2 = e[3]*yscale image_set_extent([x1,x2],[y1,y2], axes)
def image_scale(xscale=1.0, yscale=1.0, axes="gca")
Scales the image extent.
2.713868
2.534239
1.070881
if axes == "gca": axes = _pylab.gca() try: p1 = _pylab.ginput() p2 = _pylab.ginput() xshift = p2[0][0]-p1[0][0] e = axes.images[0].get_extent() e[0] = e[0] + xshift e[1] = e[1] + xshift axes.images[0].set_extent(e) _pylab.draw() except: print("whoops")
def image_click_xshift(axes = "gca")
Takes a starting and ending point, then shifts the image y by this amount
2.565487
2.542536
1.009027
if axes == "gca": axes = _pylab.gca() try: p1 = _pylab.ginput() p2 = _pylab.ginput() yshift = p2[0][1]-p1[0][1] e = axes.images[0].get_extent() e[2] = e[2] + yshift e[3] = e[3] + yshift axes.images[0].set_extent(e) _pylab.draw() except: print("whoops")
def image_click_yshift(axes = "gca")
Takes a starting and ending point, then shifts the image y by this amount
2.623692
2.595547
1.010843
if axes=="gca": axes = _pylab.gca() e = axes.images[0].get_extent() e[0] = e[0] + xshift e[1] = e[1] + xshift e[2] = e[2] + yshift e[3] = e[3] + yshift axes.images[0].set_extent(e) _pylab.draw()
def image_shift(xshift=0, yshift=0, axes="gca")
This will shift an image to a new location on x and y.
2.011163
2.034089
0.988729
if axes=="gca": axes=_pylab.gca() image = axes.images[0] if zmin=='auto': zmin = _n.min(image.get_array()) if zmax=='auto': zmax = _n.max(image.get_array()) if zmin==None: zmin = image.get_clim()[0] if zmax==None: zmax = image.get_clim()[1] image.set_clim(zmin, zmax) _pylab.draw()
def image_set_clim(zmin=None, zmax=None, axes="gca")
This will set the clim (range) of the colorbar. Setting zmin or zmax to None will not change them. Setting zmin or zmax to "auto" will auto-scale them to include all the data.
2.007813
2.281195
0.880158