sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1 value |
|---|---|---|
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.
"""
# 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() | Looks at the bounds of the plotted data and zooms accordingly, leaving some
space around the data. | entailment |
def click_estimate_slope():
"""
Takes two clicks and returns the slope.
Right-click aborts.
"""
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]) | Takes two clicks and returns the slope.
Right-click aborts. | entailment |
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.
"""
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 | 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. | entailment |
def click_estimate_difference():
"""
Takes two clicks and returns the difference vector [dx, dy].
Right-click aborts.
"""
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]] | Takes two clicks and returns the difference vector [dx, dy].
Right-click aborts. | entailment |
def copy_figure_to_clipboard(figure='gcf'):
"""
Copies the specified figure to the system clipboard. Specifying 'gcf'
will use the current figure.
"""
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.") | Copies the specified figure to the system clipboard. Specifying 'gcf'
will use the current figure. | entailment |
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)
"""
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) | 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) | entailment |
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()
"""
# 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 | 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() | entailment |
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()
"""
_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() | 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() | entailment |
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.
"""
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 | 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. | entailment |
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()
"""
_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() | 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() | entailment |
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.
"""
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) | 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. | entailment |
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'
"""
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() | 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' | entailment |
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.
"""
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() | This will bleed nearest neighbor pixels into each other with
the specified weight factors. | entailment |
def image_undo():
"""
Undoes the last coarsen or smooth command.
"""
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() | Undoes the last coarsen or smooth command. | entailment |
def image_set_aspect(aspect=1.0, axes="gca"):
"""
sets the aspect ratio of the current zoom level of the imshow image
"""
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) | sets the aspect ratio of the current zoom level of the imshow image | entailment |
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]
"""
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) | Set's the first image's extent, then redraws.
Examples:
x = [1,4]
y = [33.3, 22] | entailment |
def image_scale(xscale=1.0, yscale=1.0, axes="gca"):
"""
Scales the image extent.
"""
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) | Scales the image extent. | entailment |
def image_click_xshift(axes = "gca"):
"""
Takes a starting and ending point, then shifts the image y by this amount
"""
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") | Takes a starting and ending point, then shifts the image y by this amount | entailment |
def image_click_yshift(axes = "gca"):
"""
Takes a starting and ending point, then shifts the image y by this amount
"""
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") | Takes a starting and ending point, then shifts the image y by this amount | entailment |
def image_shift(xshift=0, yshift=0, axes="gca"):
"""
This will shift an image to a new location on x and y.
"""
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() | This will shift an image to a new location on x and y. | entailment |
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.
"""
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() | 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. | entailment |
def integrate_shown_data(scale=1, fyname=1, autozero=0, **kwargs):
"""
Numerically integrates the data visible on the current/specified axes using
scale*fun.integrate_data(x,y). Modifies the visible data using
manipulate_shown_data(**kwargs)
autozero is the number of data points used to estimate the background
for subtraction. If autozero = 0, no background subtraction is performed.
"""
def I(x,y):
xout, iout = _fun.integrate_data(x, y, autozero=autozero)
print("Total =", scale*iout[-1])
return xout, scale*iout
if fyname==1: fyname = "$"+str(scale)+"\\times \\int dx$"
manipulate_shown_data(I, fxname=None, fyname=fyname, **kwargs) | Numerically integrates the data visible on the current/specified axes using
scale*fun.integrate_data(x,y). Modifies the visible data using
manipulate_shown_data(**kwargs)
autozero is the number of data points used to estimate the background
for subtraction. If autozero = 0, no background subtraction is performed. | entailment |
def manipulate_shown_data(f, input_axes="gca", output_axes=None, fxname=1, fyname=1, clear=1, pause=False, **kwargs):
"""
Loops over the visible data on the specified axes and modifies it based on
the function f(xdata, ydata), which must return new_xdata, new_ydata
input_axes which axes to pull the data from
output_axes which axes to dump the manipulated data (None for new figure)
fxname the name of the function on x
fyname the name of the function on y
1 means "use f.__name__"
0 or None means no change.
otherwise specify a string
**kwargs are sent to axes.plot
"""
# get the axes
if input_axes == "gca": a1 = _pylab.gca()
else: a1 = input_axes
# get the xlimits
xmin, xmax = a1.get_xlim()
# get the name to stick on the x and y labels
if fxname==1: fxname = f.__name__
if fyname==1: fyname = f.__name__
# get the output axes
if output_axes == None:
_pylab.figure(a1.figure.number+1)
a2 = _pylab.axes()
else:
a2 = output_axes
if clear: a2.clear()
# loop over the data
for line in a1.get_lines():
# if it's a line, do the manipulation
if isinstance(line, _mpl.lines.Line2D):
# get the data
x, y = line.get_data()
# trim the data according to the current zoom level
x, y = _fun.trim_data(xmin, xmax, x, y)
# do the manipulation
new_x, new_y = f(x,y)
# plot the new
_s.plot.xy.data(new_x, new_y, clear=0, label=line.get_label().replace("_", "-"), axes=a2, **kwargs)
# pause after each curve if we're supposed to
if pause:
_pylab.draw()
input("<enter> ")
# set the labels and title.
if fxname in [0,None]: a2.set_xlabel(a1.get_xlabel())
else: a2.set_xlabel(fxname+"("+a1.get_xlabel()+")")
if fyname in [0,None]: a2.set_ylabel(a1.get_ylabel())
else: a2.set_ylabel(fyname+"("+a1.get_ylabel()+")")
_pylab.draw() | Loops over the visible data on the specified axes and modifies it based on
the function f(xdata, ydata), which must return new_xdata, new_ydata
input_axes which axes to pull the data from
output_axes which axes to dump the manipulated data (None for new figure)
fxname the name of the function on x
fyname the name of the function on y
1 means "use f.__name__"
0 or None means no change.
otherwise specify a string
**kwargs are sent to axes.plot | entailment |
def manipulate_shown_xdata(fx, fxname=1, **kwargs):
"""
This defines a function f(xdata,ydata) returning fx(xdata), ydata and
runs manipulate_shown_data() with **kwargs sent to this. See
manipulate_shown_data() for more info.
"""
def f(x,y): return fx(x), y
f.__name__ = fx.__name__
manipulate_shown_data(f, fxname=fxname, fyname=None, **kwargs) | This defines a function f(xdata,ydata) returning fx(xdata), ydata and
runs manipulate_shown_data() with **kwargs sent to this. See
manipulate_shown_data() for more info. | entailment |
def manipulate_shown_ydata(fy, fyname=1, **kwargs):
"""
This defines a function f(xdata,ydata) returning xdata, fy(ydata) and
runs manipulate_shown_data() with **kwargs sent to this. See
manipulate_shown_data() for more info.
"""
def f(x,y): return x, fy(y)
f.__name__ = fy.__name__
manipulate_shown_data(f, fxname=None, fyname=fyname, **kwargs) | This defines a function f(xdata,ydata) returning xdata, fy(ydata) and
runs manipulate_shown_data() with **kwargs sent to this. See
manipulate_shown_data() for more info. | entailment |
def _print_figures(figures, arguments='', file_format='pdf', target_width=8.5, target_height=11.0, target_pad=0.5):
"""
figure printing loop designed to be launched in a separate thread.
"""
for fig in figures:
# get the temp path
temp_path = _os.path.join(_settings.path_home, "temp")
# make the temp folder
_settings.MakeDir(temp_path)
# output the figure to postscript
path = _os.path.join(temp_path, "graph."+file_format)
# get the dimensions of the figure in inches
w=fig.get_figwidth()
h=fig.get_figheight()
# we're printing to 8.5 x 11, so aim for 7.5 x 10
target_height = target_height-2*target_pad
target_width = target_width -2*target_pad
# depending on the aspect we scale by the vertical or horizontal value
if 1.0*h/w > target_height/target_width:
# scale down according to the vertical dimension
new_h = target_height
new_w = w*target_height/h
else:
# scale down according to the hozo dimension
new_w = target_width
new_h = h*target_width/w
fig.set_figwidth(new_w)
fig.set_figheight(new_h)
# save it
fig.savefig(path, bbox_inches=_pylab.matplotlib.transforms.Bbox(
[[-target_pad, new_h-target_height-target_pad],
[target_width-target_pad, target_height-target_pad]]))
# set it back
fig.set_figheight(h)
fig.set_figwidth(w)
if not arguments == '':
c = _settings['instaprint'] + ' ' + arguments + ' "' + path + '"'
else:
c = _settings['instaprint'] + ' "' + path + '"'
print(c)
_os.system(c) | figure printing loop designed to be launched in a separate thread. | entailment |
def instaprint(figure='gcf', arguments='', threaded=False, file_format='pdf'):
"""
Quick function that saves the specified figure as a postscript and then
calls the command defined by spinmob.prefs['instaprint'] with this
postscript file as the argument.
figure='gcf' can be 'all', a number, or a list of numbers
"""
global _settings
if 'instaprint' not in _settings.keys():
print("No print command setup. Set the user variable settings['instaprint'].")
return
if figure=='gcf': figure=[_pylab.gcf().number]
elif figure=='all': figure=_pylab.get_fignums()
if not getattr(figure,'__iter__',False): figure = [figure]
print("figure numbers in queue:", figure)
figures=[]
for n in figure: figures.append(_pylab.figure(n))
# now run the ps printing command
if threaded:
# store the canvas type of the last figure
canvas_type = type(figures[-1].canvas)
# launch the aforementioned function as a separate thread
_thread.start_new_thread(_print_figures, (figures,arguments,file_format,))
# wait until the thread is running
_time.sleep(0.25)
# wait until the canvas type has returned to normal
t0 = _time.time()
while not canvas_type == type(figures[-1].canvas) and _time.time()-t0 < 5.0:
_time.sleep(0.1)
if _time.time()-t0 >= 5.0:
print("WARNING: Timed out waiting for canvas to return to original state!")
# bring back the figure and command line
_pylab.draw()
else:
_print_figures(figures, arguments, file_format)
_pylab.draw() | Quick function that saves the specified figure as a postscript and then
calls the command defined by spinmob.prefs['instaprint'] with this
postscript file as the argument.
figure='gcf' can be 'all', a number, or a list of numbers | entailment |
def raise_figure_window(f=0):
"""
Raises the supplied figure number or figure window.
"""
if _fun.is_a_number(f): f = _pylab.figure(f)
f.canvas.manager.window.raise_() | Raises the supplied figure number or figure window. | entailment |
def set_figure_window_geometry(fig='gcf', position=None, size=None):
"""
This will currently only work for Qt4Agg and WXAgg backends.
postion = [x, y]
size = [width, height]
fig can be 'gcf', a number, or a figure object.
"""
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:
w = fig.canvas.window()
if not size == None:
w.resize(size[0],size[1])
if not position == None:
w.move(position[0], position[1])
# WXAgg backend. Probably would work for other Qt stuff.
elif _pylab.get_backend().find('WX') >= 0:
w = fig.canvas.Parent
if not size == None:
w.SetSize(size)
if not position == None:
w.SetPosition(position) | This will currently only work for Qt4Agg and WXAgg backends.
postion = [x, y]
size = [width, height]
fig can be 'gcf', a number, or a figure object. | entailment |
def set_yticks(start, step, axes="gca"):
"""
This will generate a tick array and apply said array to the axis
"""
if axes=="gca": axes = _pylab.gca()
# first get one of the tick label locations
xposition = axes.yaxis.get_ticklabels()[0].get_position()[0]
# get the bounds
ymin, ymax = axes.get_ylim()
# get the starting tick
nstart = int(_pylab.floor((ymin-start)/step))
nstop = int(_pylab.ceil((ymax-start)/step))
ticks = []
for n in range(nstart,nstop+1): ticks.append(start+n*step)
axes.set_yticks(ticks)
# set the x-position
for t in axes.yaxis.get_ticklabels():
x, y = t.get_position()
t.set_position((xposition, y))
_pylab.draw() | This will generate a tick array and apply said array to the axis | entailment |
def set_xticks(start, step, axes="gca"):
"""
This will generate a tick array and apply said array to the axis
"""
if axes=="gca": axes = _pylab.gca()
# first get one of the tick label locations
yposition = axes.xaxis.get_ticklabels()[0].get_position()[1]
# get the bounds
xmin, xmax = axes.get_xlim()
# get the starting tick
nstart = int(_pylab.floor((xmin-start)/step))
nstop = int(_pylab.ceil((xmax-start)/step))
ticks = []
for n in range(nstart,nstop+1): ticks.append(start+n*step)
axes.set_xticks(ticks)
# set the y-position
for t in axes.xaxis.get_ticklabels():
x, y = t.get_position()
t.set_position((x, yposition))
_pylab.draw() | This will generate a tick array and apply said array to the axis | entailment |
def coarsen_line(line, level=2, exponential=False, draw=True):
"""
Coarsens the specified line (see spinmob.coarsen_data() for more information).
Parameters
----------
line
Matplotlib line instance.
level=2
How strongly to coarsen.
exponential=False
If True, use the exponential method (great for log-x plots).
draw=True
Redraw when complete.
"""
# get the actual data values
xdata = line.get_xdata()
ydata = line.get_ydata()
xdata,ydata = _fun.coarsen_data(xdata, ydata, level=level, exponential=exponential)
# don't do anything if we don't have any data left
if len(ydata) == 0: print("There's nothing left in "+str(line)+"!")
# otherwise set the data with the new arrays
else: line.set_data(xdata, ydata)
# we refresh in real time for giggles
if draw: _pylab.draw() | Coarsens the specified line (see spinmob.coarsen_data() for more information).
Parameters
----------
line
Matplotlib line instance.
level=2
How strongly to coarsen.
exponential=False
If True, use the exponential method (great for log-x plots).
draw=True
Redraw when complete. | entailment |
def coarsen_all_traces(level=2, exponential=False, axes="all", figure=None):
"""
This function does nearest-neighbor coarsening of the data. See
spinmob.fun.coarsen_data for more information.
Parameters
----------
level=2
How strongly to coarsen.
exponential=False
If True, use the exponential method (great for log-x plots).
axes="all"
Which axes to coarsen.
figure=None
Which figure to use.
"""
if axes=="gca": axes=_pylab.gca()
if axes=="all":
if not figure: f = _pylab.gcf()
axes = f.axes
if not _fun.is_iterable(axes): axes = [axes]
for a in axes:
# get the lines from the plot
lines = a.get_lines()
# loop over the lines and trim the data
for line in lines:
if isinstance(line, _mpl.lines.Line2D):
coarsen_line(line, level, exponential, draw=False)
_pylab.draw() | This function does nearest-neighbor coarsening of the data. See
spinmob.fun.coarsen_data for more information.
Parameters
----------
level=2
How strongly to coarsen.
exponential=False
If True, use the exponential method (great for log-x plots).
axes="all"
Which axes to coarsen.
figure=None
Which figure to use. | entailment |
def line_math(fx=None, fy=None, axes='gca'):
"""
applies function fx to all xdata and fy to all ydata.
"""
if axes=='gca': axes = _pylab.gca()
lines = axes.get_lines()
for line in lines:
if isinstance(line, _mpl.lines.Line2D):
xdata, ydata = line.get_data()
if not fx==None: xdata = fx(xdata)
if not fy==None: ydata = fy(ydata)
line.set_data(xdata,ydata)
_pylab.draw() | applies function fx to all xdata and fy to all ydata. | entailment |
def export_figure(dpi=200, figure="gcf", path=None):
"""
Saves the actual postscript data for the figure.
"""
if figure=="gcf": figure = _pylab.gcf()
if path==None: path = _s.dialogs.Save("*.*", default_directory="save_plot_default_directory")
if path=="":
print("aborted.")
return
figure.savefig(path, dpi=dpi) | Saves the actual postscript data for the figure. | entailment |
def save_plot(axes="gca", path=None):
"""
Saves the figure in my own ascii format
"""
global line_attributes
# choose a path to save to
if path==None: path = _s.dialogs.Save("*.plot", default_directory="save_plot_default_directory")
if path=="":
print("aborted.")
return
if not path.split(".")[-1] == "plot": path = path+".plot"
f = file(path, "w")
# if no argument was given, get the current axes
if axes=="gca": axes=_pylab.gca()
# now loop over the available lines
f.write("title=" +axes.title.get_text().replace('\n', '\\n')+'\n')
f.write("xlabel="+axes.xaxis.label.get_text().replace('\n','\\n')+'\n')
f.write("ylabel="+axes.yaxis.label.get_text().replace('\n','\\n')+'\n')
for l in axes.lines:
# write the data header
f.write("trace=new\n")
f.write("legend="+l.get_label().replace('\n', '\\n')+"\n")
for a in line_attributes: f.write(a+"="+str(_pylab.getp(l, a)).replace('\n','')+"\n")
# get the data
x = l.get_xdata()
y = l.get_ydata()
# loop over the data
for n in range(0, len(x)): f.write(str(float(x[n])) + " " + str(float(y[n])) + "\n")
f.close() | Saves the figure in my own ascii format | entailment |
def save_figure_raw_data(figure="gcf", **kwargs):
"""
This will just output an ascii file for each of the traces in the shown figure.
**kwargs are sent to dialogs.Save()
"""
# choose a path to save to
path = _s.dialogs.Save(**kwargs)
if path=="": return "aborted."
# if no argument was given, get the current axes
if figure=="gcf": figure = _pylab.gcf()
for n in range(len(figure.axes)):
a = figure.axes[n]
for m in range(len(a.lines)):
l = a.lines[m]
x = l.get_xdata()
y = l.get_ydata()
p = _os.path.split(path)
p = _os.path.join(p[0], "axes" + str(n) + " line" + str(m) + " " + p[1])
print(p)
# loop over the data
f = open(p, 'w')
for j in range(0, len(x)):
f.write(str(x[j]) + "\t" + str(y[j]) + "\n")
f.close() | This will just output an ascii file for each of the traces in the shown figure.
**kwargs are sent to dialogs.Save() | entailment |
def get_line_color(self, increment=1):
"""
Returns the current color, then increments the color by what's specified
"""
i = self.line_colors_index
self.line_colors_index += increment
if self.line_colors_index >= len(self.line_colors):
self.line_colors_index = self.line_colors_index-len(self.line_colors)
if self.line_colors_index >= len(self.line_colors): self.line_colors_index=0 # to be safe
return self.line_colors[i] | Returns the current color, then increments the color by what's specified | entailment |
def get_marker(self, increment=1):
"""
Returns the current marker, then increments the marker by what's specified
"""
i = self.markers_index
self.markers_index += increment
if self.markers_index >= len(self.markers):
self.markers_index = self.markers_index-len(self.markers)
if self.markers_index >= len(self.markers): self.markers_index=0 # to be safe
return self.markers[i] | Returns the current marker, then increments the marker by what's specified | entailment |
def get_linestyle(self, increment=1):
"""
Returns the current marker, then increments the marker by what's specified
"""
i = self.linestyles_index
self.linestyles_index += increment
if self.linestyles_index >= len(self.linestyles):
self.linestyles_index = self.linestyles_index-len(self.linestyles)
if self.linestyles_index >= len(self.linestyles): self.linestyles_index=0 # to be safe
return self.linestyles[i] | Returns the current marker, then increments the marker by what's specified | entailment |
def get_face_color(self, increment=1):
"""
Returns the current face, then increments the face by what's specified
"""
i = self.face_colors_index
self.face_colors_index += increment
if self.face_colors_index >= len(self.face_colors):
self.face_colors_index = self.face_colors_index-len(self.face_colors)
if self.face_colors_index >= len(self.face_colors): self.face_colors_index=0 # to be safe
return self.face_colors[i] | Returns the current face, then increments the face by what's specified | entailment |
def get_edge_color(self, increment=1):
"""
Returns the current face, then increments the face by what's specified
"""
i = self.edge_colors_index
self.edge_colors_index += increment
if self.edge_colors_index >= len(self.edge_colors):
self.edge_colors_index = self.edge_colors_index-len(self.edge_colors)
if self.edge_colors_index >= len(self.edge_colors): self.edge_colors_index=0 # to be safe
return self.edge_colors[i] | Returns the current face, then increments the face by what's specified | entailment |
def apply(self, axes="gca"):
"""
Applies the style cycle to the lines in the axes specified
"""
if axes == "gca": axes = _pylab.gca()
self.reset()
lines = axes.get_lines()
for l in lines:
l.set_color(self.get_line_color(1))
l.set_mfc(self.get_face_color(1))
l.set_marker(self.get_marker(1))
l.set_mec(self.get_edge_color(1))
l.set_linestyle(self.get_linestyle(1))
_pylab.draw() | Applies the style cycle to the lines in the axes specified | entailment |
def _send_message(session, user_id, message=None, image_files=None):
"""
https://vk.com/dev/messages.send
"""
assert any([message, image_files])
attachment_items = None
if image_files:
attachment_items = Photo._upload_messages_photos_for_group(session, user_id, image_files)
message_id = session.fetch("messages.send", user_id=user_id, message=message, attachment=attachment_items, random_id=random.randint(1, 10**6))
return message_id | https://vk.com/dev/messages.send | entailment |
def get_dialog(session, unread=False, important=False, unanswered=False):
"""
https://vk.com/dev/messages.getDialogs
"""
response = session.fetch("messages.getDialogs", unread=unread, important=important, unanswered=unanswered)
dialog_json_items = response["items"]
return (Message.from_json(session, dialog_json["message"]) for dialog_json in dialog_json_items) | https://vk.com/dev/messages.getDialogs | entailment |
def get_members(self, sort='id_asc'):
"""
:param: sort {id_asc, id_desc, time_asc, time_desc} string
Docs: https://vk.com/dev/groups.getMembers
"""
return self._session.fetch_items("groups.getMembers", User.from_json, 1000, group_id=self.id, sort=sort, fields=User.__slots__ + User.USER_FIELDS) | :param: sort {id_asc, id_desc, time_asc, time_desc} string
Docs: https://vk.com/dev/groups.getMembers | entailment |
def _get_user_groups(session, user_id, filter):
"""
https://vk.com/dev/groups.get
:param filter: {admin, editor, moder, groups, publics, events}
:yield: Groups
"""
return session.fetch_items('groups.get', Group.from_json, count=1000, user_id=user_id, filter=filter, extended=1, fields=",".join(Group.GROUP_FIELDS)) | https://vk.com/dev/groups.get
:param filter: {admin, editor, moder, groups, publics, events}
:yield: Groups | entailment |
def copy_spline_array(a):
"""
This returns an instance of a new spline_array with all the fixins, and the data from a.
"""
b = spline_array()
b.x_splines = a.x_splines
b.y_splines = a.y_splines
b.max_y_splines = a.max_y_splines
b.xmin = a.xmin
b.xmax = a.xmax
b.ymin = a.ymin
b.ymax = a.ymax
b.xlabel = a.xlabel
b.ylabel = a.ylabel
b.zlabel = a.zlabel
b.simple = a.simple
b.generate_y_values()
return b | This returns an instance of a new spline_array with all the fixins, and the data from a. | entailment |
def splot(axes="gca", smoothing=5000, degree=5, presmoothing=0, plot=True, spline_class=spline_single, interactive=True, show_derivative=1):
"""
gets the data from the plot and feeds it into splint
returns an instance of spline_single
axes="gca" which axes to get the data from.
smoothing=5000 spline_single smoothing parameter
presmoothing=0 spline_single data presmoothing factor (nearest neighbor)
plot=True should we plot the result?
spline_class=spline_single which data class to use?
interactive=False should we spline fit interactively or just make a spline_single?
"""
if axes=="gca": axes = _pylab.gca()
xlabel = axes.xaxis.label.get_text()
ylabel = axes.yaxis.label.get_text()
xdata = axes.get_lines()[0].get_xdata()
ydata = axes.get_lines()[0].get_ydata()
if interactive:
return splinteractive(xdata, ydata, smoothing, degree, presmoothing, spline_class, xlabel, ylabel)
else:
return spline_class(xdata, ydata, smoothing, degree, presmoothing, plot, xlabel, ylabel) | gets the data from the plot and feeds it into splint
returns an instance of spline_single
axes="gca" which axes to get the data from.
smoothing=5000 spline_single smoothing parameter
presmoothing=0 spline_single data presmoothing factor (nearest neighbor)
plot=True should we plot the result?
spline_class=spline_single which data class to use?
interactive=False should we spline fit interactively or just make a spline_single? | entailment |
def evaluate(self, x, derivative=0, smooth=0, simple='auto'):
"""
smooth=0 is how much to smooth the spline data
simple='auto' is whether we should just use straight interpolation
you may want smooth > 0 for this, when derivative=1
"""
if simple=='auto': simple = self.simple
# make it into an array if it isn't one, and remember that we did
is_array = True
if not type(x) == type(_pylab.array([])):
x = _pylab.array([x])
is_array = False
if simple:
# loop over all supplied x data, and come up with a y for each
y = []
for n in range(0, len(x)):
# get a window of data around x
if smooth:
[xtemp, ytemp, etemp] = _fun.trim_data(self.xdata, self.ydata, None, [x[n]-smooth, x[n]+smooth])
else:
i1 = _fun.index_nearest(x[n], self.xdata)
# if the nearest data point is lower than x, use the next point to interpolate
if self.xdata[i1] <= x[n] or i1 <= 0: i2 = i1+1
else: i2 = i1-1
# if we're at the max, extrapolate
if i2 >= len(self.xdata):
print(x[n], "is out of range. extrapolating")
i2 = i1-1
x1 = self.xdata[i1]
y1 = self.ydata[i1]
x2 = self.xdata[i2]
y2 = self.ydata[i2]
slope = (y2-y1)/(x2-x1)
xtemp = _numpy.array([x[n]])
ytemp = _numpy.array([y1 + (x[n]-x1)*slope])
# calculate the slope based on xtemp and ytemp (if smoothing)
# or just use the raw slope if smoothing=0
if derivative == 1:
if smooth:
y.append((_numpy.average(xtemp*ytemp)-_numpy.average(xtemp)*_numpy.average(ytemp)) /
(_numpy.average(xtemp*xtemp)-_numpy.average(xtemp)**2))
else:
y.append(slope)
# otherwise just average (even with one element)
elif derivative==0:
y.append(_numpy.average(ytemp))
if is_array: return _numpy.array(y)
else: return y[0]
if smooth:
y = []
for n in range(0, len(x)):
# take 20 data points from x+/-smooth
xlow = max(self.xmin,x[n]-smooth)
xhi = min(self.xmax,x[n]+smooth)
xdata = _pylab.linspace(xlow, xhi, 20)
ydata = _interpolate.splev(xdata, self.pfit, derivative)
y.append(_numpy.average(ydata))
if is_array: return _numpy.array(y)
else: return y[0]
else:
return _interpolate.splev(x, self.pfit, derivative) | smooth=0 is how much to smooth the spline data
simple='auto' is whether we should just use straight interpolation
you may want smooth > 0 for this, when derivative=1 | entailment |
def evaluate(self, x, y, x_derivative=0, smooth=0, simple='auto'):
"""
this evaluates the 2-d spline by doing linear interpolation of the curves
"""
if simple=='auto': simple = self.simple
# find which values y is in between
for n in range(0, len(self.y_values)-1):
# if it's in between, interpolate!
if self.y_values[n] <= y and self.y_values[n+1] >= y:
y1 = self.y_values[n]
y2 = self.y_values[n+1]
z1 = self.x_splines[y1].evaluate(x, x_derivative, smooth, simple)
z2 = self.x_splines[y2].evaluate(x, x_derivative, smooth, simple)
return z1 + (y-y1)*(z2-z1)/(y2-y1)
print("YARG! The y value "+str(y)+" is out of interpolation range!")
if y >= self.y_values[-1]: return self.x_splines[self.y_values[-1]].evaluate(x, x_derivative, smooth, simple)
else : return self.x_splines[self.y_values[0]].evaluate(x, x_derivative, smooth, simple) | this evaluates the 2-d spline by doing linear interpolation of the curves | entailment |
def plot_fixed_x(self, x_values, x_derivative=0, steps=1000, smooth=0, simple='auto', ymin="auto", ymax="auto", format=True, clear=1):
"""
plots the data at fixed x-value, so z vs x
"""
if simple=='auto': simple=self.simple
# get the min and max
if ymin=="auto": ymin = self.ymin
if ymax=="auto": ymax = self.ymax
if clear: _pylab.gca().clear()
if not type(x_values) in [type([]), type(_pylab.array([]))]: x_values = [x_values]
for x in x_values:
# define a new simple function to plot, then plot it
def f(y): return self.evaluate(x, y, x_derivative, smooth, simple)
_pylab_help.plot_function(f, ymin, ymax, steps, 0, False)
# label it
a = _pylab.gca()
a.set_xlabel(self.ylabel)
if x_derivative: a.set_ylabel(str(x_derivative)+" "+str(self.xlabel)+" derivative of "+self.zlabel)
else: a.set_ylabel(self.zlabel)
a.set_title(self._path+"\nSpline array plot at fixed x = "+self.xlabel)
a.get_lines()[-1].set_label("x ("+self.xlabel+") = "+str(x))
if format: _s.format_figure()
return a | plots the data at fixed x-value, so z vs x | entailment |
def plot_fixed_y(self, y_values, x_derivative=0, steps=1000, smooth=0, simple='auto', xmin="auto", xmax="auto", format=True, clear=1):
"""
plots the data at a fixed y-value, so z vs y
"""
if simple=='auto': simple=self.simple
# get the min and max
if xmin=="auto": xmin = self.xmin
if xmax=="auto": xmax = self.xmax
if clear: _pylab.gca().clear()
if not type(y_values) in [type([]), type(_pylab.array([]))]: y_values = [y_values]
for y in y_values:
# define a new simple function to plot, then plot it
def f(x): return self.evaluate(x, y, x_derivative, smooth, simple)
_pylab_help.plot_function(f, xmin, xmax, steps, 0, True)
# label it
a = _pylab.gca()
th = "th"
if x_derivative == 1: th = "st"
if x_derivative == 2: th = "nd"
if x_derivative == 3: th = "rd"
if x_derivative: a.set_ylabel(str(x_derivative)+th+" "+self.xlabel+" derivative of "+self.zlabel+" spline")
else: a.set_ylabel(self.zlabel)
a.set_xlabel(self.xlabel)
a.set_title(self._path+"\nSpline array plot at fixed y "+self.ylabel)
a.get_lines()[-1].set_label("y ("+self.ylabel+") = "+str(y))
if format: _s.format_figure()
return a | plots the data at a fixed y-value, so z vs y | entailment |
def get_window(self):
"""
Returns the object's parent window. Returns None if no window found.
"""
x = self
while not x._parent == None and \
not isinstance(x._parent, Window):
x = x._parent
return x._parent | Returns the object's parent window. Returns None if no window found. | entailment |
def sleep(self, seconds=0.05, dt=0.01):
"""
A "smooth" version of time.sleep(): waits for the time to pass but
processes events every dt as well.
Note this requires that the object is either a window or embedded
somewhere within a window.
"""
t0 = _t.time()
while _t.time()-t0 < seconds:
# Pause a bit to avoid heavy CPU
_t.sleep(dt)
# process events
self.process_events() | A "smooth" version of time.sleep(): waits for the time to pass but
processes events every dt as well.
Note this requires that the object is either a window or embedded
somewhere within a window. | entailment |
def block_events(self):
"""
Prevents the widget from sending signals.
"""
self._widget.blockSignals(True)
self._widget.setUpdatesEnabled(False) | Prevents the widget from sending signals. | entailment |
def unblock_events(self):
"""
Allows the widget to send signals.
"""
self._widget.blockSignals(False)
self._widget.setUpdatesEnabled(True) | Allows the widget to send signals. | entailment |
def print_message(self, message="heya!"):
"""
If self.log is defined to be an instance of TextLog, it print the
message there. Otherwise use the usual "print" to command line.
"""
if self.log == None: print(message)
else: self.log.append_text(message) | If self.log is defined to be an instance of TextLog, it print the
message there. Otherwise use the usual "print" to command line. | entailment |
def save_gui_settings(self, *a):
"""
Saves just the current configuration of the controls if the
autosettings_path is set.
"""
# only if we're supposed to!
if self._autosettings_path:
# Get the gui settings directory
gui_settings_dir = _os.path.join(_cwd, 'egg_settings')
# make sure the directory exists
if not _os.path.exists(gui_settings_dir): _os.mkdir(gui_settings_dir)
# make a path with a sub-directory
path = _os.path.join(gui_settings_dir, self._autosettings_path)
# for saving header info
d = _d.databox()
# add all the controls settings
for x in self._autosettings_controls: self._store_gui_setting(d, x)
# save the file
d.save_file(path, force_overwrite=True) | Saves just the current configuration of the controls if the
autosettings_path is set. | entailment |
def load_gui_settings(self, lazy_only=False):
"""
Loads the settings (if we're supposed to).
Parameters
----------
lazy_only=False
If True, it will only load the settings into self._lazy_load, and
not try to update the value. Presumably the widget will apply these
settings later, e.g., when enough tabs exist to set the current
tab in TabArea.
"""
# only do this if we're supposed to
if self._autosettings_path is not None:
# Get the gui settings directory
gui_settings_dir = _os.path.join(_cwd, 'egg_settings')
# assemble the path with a sub-directory
path = _os.path.join(gui_settings_dir, self._autosettings_path)
# databox just for loading a cfg file
d = _d.databox()
# if the settings path exists
if _os.path.exists(path):
# Load the settings
d.load_file(path, header_only=True, quiet=True)
# Store the settings in the lazy dictionary
self._lazy_load.update(d.headers)
# Loop over the settings we're supposed to change
# Note without specifying d, this will try to pop
# the value off of self._lazy_load. If
#
if not lazy_only:
for x in self._autosettings_controls:
self._load_gui_setting(x) | Loads the settings (if we're supposed to).
Parameters
----------
lazy_only=False
If True, it will only load the settings into self._lazy_load, and
not try to update the value. Presumably the widget will apply these
settings later, e.g., when enough tabs exist to set the current
tab in TabArea. | entailment |
def _load_gui_setting(self, key, d=None):
"""
Safely reads the header setting and sets the appropriate control
value.
Parameters
----------
key
Key string of the format 'self.controlname'.
d = None
Databox instance or dictionary, presumably containing the aforementioned
key. If d=None, pops the value from self._lazy_load.
"""
# Whether we should pop the value from the dictionary when we set it.
pop_value = False
# If d is None, assume we're using the lazy load settings.
if d == None:
d = self._lazy_load
pop_value = True
# If we have a databox, take the header dictionary
if not type(d) == dict: d = d.headers
# only do this if the key exists
if key in d:
try:
# Try to set the value
eval(key).set_value(d[key])
# If this fails, perhaps the element does not yet exist
# For example, TabArea may not have all the tabs created
# and cannot set the active tab until later.
# If it's here, it worked, so pop if necessary
if pop_value: d.pop(key)
except:
print("ERROR: Could not load gui setting "+repr(key)) | Safely reads the header setting and sets the appropriate control
value.
Parameters
----------
key
Key string of the format 'self.controlname'.
d = None
Databox instance or dictionary, presumably containing the aforementioned
key. If d=None, pops the value from self._lazy_load. | entailment |
def _store_gui_setting(self, databox, name):
"""
Stores the gui setting in the header of the supplied databox.
hkeys in the file are set to have the format
"self.controlname"
"""
try: databox.insert_header(name, eval(name + ".get_value()"))
except: print("ERROR: Could not store gui setting "+repr(name)) | Stores the gui setting in the header of the supplied databox.
hkeys in the file are set to have the format
"self.controlname" | entailment |
def place_object(self, object, column=None, row=None, column_span=1, row_span=1, alignment=1):
"""
This adds either one of our simplified objects or a QWidget to the
grid at the specified position, appends the object to self.objects.
alignment=0 Fill the space.
alignment=1 Left-justified.
alignment=2 Right-justified.
If column isn't specified, the new object will be placed in a new column.
"""
# pick a column
if column==None:
column = self._auto_column
self._auto_column += 1
# pick a row
if row==None: row = self._auto_row
# create the object
self.objects.append(object)
# add the widget to the layout
try:
object._widget
widget = object._widget
# allows the user to specify a standard widget
except: widget = object
self._layout.addWidget(widget, row, column,
row_span, column_span,
_g.Qt.QtCore.Qt.Alignment(alignment))
# try to store the parent object (self) in the placed object
try: object.set_parent(self)
except: None
return object | This adds either one of our simplified objects or a QWidget to the
grid at the specified position, appends the object to self.objects.
alignment=0 Fill the space.
alignment=1 Left-justified.
alignment=2 Right-justified.
If column isn't specified, the new object will be placed in a new column. | entailment |
def remove_object(self, object=0, delete=True):
"""
Removes the supplied object from the grid. If object is an integer,
it removes the n'th object.
"""
if type(object) in [int, int]: n = object
else: n = self.objects.index(object)
# pop it from the list
object = self.objects.pop(n)
# remove it from the GUI and delete it
if hasattr_safe(object, '_widget'):
self._layout.removeWidget(object._widget)
object._widget.hide()
if delete: object._widget.deleteLater()
else:
self._layout.removeWidget(object)
object.hide()
if delete: object.deleteLater() | Removes the supplied object from the grid. If object is an integer,
it removes the n'th object. | entailment |
def set_column_stretch(self, column=0, stretch=10):
"""
Sets the column stretch. Larger numbers mean it will expand more to
fill space.
"""
self._layout.setColumnStretch(column, stretch)
return self | Sets the column stretch. Larger numbers mean it will expand more to
fill space. | entailment |
def set_row_stretch(self, row=0, stretch=10):
"""
Sets the row stretch. Larger numbers mean it will expand more to fill
space.
"""
self._layout.setRowStretch(row, stretch)
return self | Sets the row stretch. Larger numbers mean it will expand more to fill
space. | entailment |
def new_autorow(self, row=None):
"""
Sets the auto-add row. If row=None, increments by 1
"""
if row==None: self._auto_row += 1
else: self._auto_row = row
self._auto_column=0
return self | Sets the auto-add row. If row=None, increments by 1 | entailment |
def place_docker(self, docker, area='top'):
"""
IN DEVELOPMENT
Places a DockWindow instance at the specified area ('top', 'bottom',
'left', 'right', or None)
"""
# map of options
m = dict(top = _g.QtCore.Qt.TopDockWidgetArea,
bottom = _g.QtCore.Qt.BottomDockWidgetArea,
left = _g.QtCore.Qt.LeftDockWidgetArea,
right = _g.QtCore.Qt.RightDockWidgetArea)
# set the parent
docker.set_parent(self)
# events
docker._window.resizeEvent = self._event_resize
docker._window.moveEvent = self._event_move
# Keep it in the window
docker._window.setFeatures(docker._window.DockWidgetMovable)
# set it
self._window.addDockWidget(m[area], docker._window)
return docker | IN DEVELOPMENT
Places a DockWindow instance at the specified area ('top', 'bottom',
'left', 'right', or None) | entailment |
def _save_settings(self):
"""
Saves all the parameters to a text file.
"""
if self._autosettings_path == None: return
# Get the gui settings directory
gui_settings_dir = _os.path.join(_cwd, 'egg_settings')
# make sure the directory exists
if not _os.path.exists(gui_settings_dir): _os.mkdir(gui_settings_dir)
# make a path with a sub-directory
path = _os.path.join(gui_settings_dir, self._autosettings_path)
# Create a Qt settings object
settings = _g.QtCore.QSettings(path, _g.QtCore.QSettings.IniFormat)
settings.clear()
# Save values
if hasattr_safe(self._window, "saveState"):
settings.setValue('State',self._window.saveState())
settings.setValue('Geometry', self._window.saveGeometry()) | Saves all the parameters to a text file. | entailment |
def _load_settings(self):
"""
Loads all the parameters from a databox text file. If path=None,
loads from self._autosettings_path.
"""
if self._autosettings_path == None: return
# Get the gui settings directory
gui_settings_dir = _os.path.join(_cwd, 'egg_settings')
# make a path with a sub-directory
path = _os.path.join(gui_settings_dir, self._autosettings_path)
# make sure the directory exists
if not _os.path.exists(path): return
# Create a Qt settings object
settings = _g.QtCore.QSettings(path, _g.QtCore.QSettings.IniFormat)
# Load it up! (Extra steps required for windows command line execution)
if settings.contains('State') and hasattr_safe(self._window, "restoreState"):
x = settings.value('State')
if hasattr(x, "toByteArray"): x = x.toByteArray()
self._window.restoreState(x)
if settings.contains('Geometry'):
x = settings.value('Geometry')
if hasattr(x, "toByteArray"): x = x.toByteArray()
self._window.restoreGeometry(x) | Loads all the parameters from a databox text file. If path=None,
loads from self._autosettings_path. | entailment |
def show(self, block_command_line=False, block_timing=0.05):
"""
Shows the window and raises it.
If block_command_line is 0, this will start the window up and allow you
to monkey with the command line at the same time. Otherwise, the
window will block the command line and process events every
block_timing seconds.
"""
self._is_open = True
self._window.show()
self._window.raise_()
# start the blocking loop
if block_command_line:
# stop when the window closes
while self._is_open:
_a.processEvents()
_t.sleep(block_timing)
# wait a moment in case there is some shutdown stuff.
_t.sleep(0.5)
return self | Shows the window and raises it.
If block_command_line is 0, this will start the window up and allow you
to monkey with the command line at the same time. Otherwise, the
window will block the command line and process events every
block_timing seconds. | entailment |
def set_checked(self, value=True, block_events=False):
"""
This will set whether the button is checked.
Setting block_events=True will temporarily disable signals
from the button when setting the value.
"""
if block_events: self._widget.blockSignals(True)
self._widget.setChecked(value)
if block_events: self._widget.blockSignals(False)
return self | This will set whether the button is checked.
Setting block_events=True will temporarily disable signals
from the button when setting the value. | entailment |
def click(self):
"""
Pretends to user clicked it, sending the signal and everything.
"""
if self.is_checkable():
if self.is_checked(): self.set_checked(False)
else: self.set_checked(True)
self.signal_clicked.emit(self.is_checked())
else:
self.signal_clicked.emit(True)
return self | Pretends to user clicked it, sending the signal and everything. | entailment |
def set_style(self, *args, **kwargs):
"""
Provides access to any number of style sheet settings via
self._widget.SetStyleSheet()
*args can be any element between semicolons, e.g.
self.set_stylesheet('text-align: right; padding-left: 5px')
**kwargs can be any key-value pair, replacing '-' with '_' in the key, e.g.
self.set_stylesheet(text_align='right', padding_left='5px')
See QLabel.SetStyleSheet() documentation.
"""
# assemble the string
s = "QLabel {"
for a in args: s = s+a+"; "
for k in list(kwargs.keys()): s = s+k.replace("_","-")+": "+kwargs[k]+"; "
s = s+"}"
# set it!
self._widget.setStyleSheet(s)
return self | Provides access to any number of style sheet settings via
self._widget.SetStyleSheet()
*args can be any element between semicolons, e.g.
self.set_stylesheet('text-align: right; padding-left: 5px')
**kwargs can be any key-value pair, replacing '-' with '_' in the key, e.g.
self.set_stylesheet(text_align='right', padding_left='5px')
See QLabel.SetStyleSheet() documentation. | entailment |
def set_value(self, value, block_events=False):
"""
Sets the current value of the number box.
Setting block_events=True will temporarily block the widget from
sending any signals when setting the value.
"""
if block_events: self.block_events()
self._widget.setValue(value)
if block_events: self.unblock_events() | Sets the current value of the number box.
Setting block_events=True will temporarily block the widget from
sending any signals when setting the value. | entailment |
def set_step(self, value, block_events=False):
"""
Sets the step of the number box.
Setting block_events=True will temporarily block the widget from
sending any signals when setting the value.
"""
if block_events: self.block_events()
self._widget.setSingleStep(value)
if block_events: self.unblock_events() | Sets the step of the number box.
Setting block_events=True will temporarily block the widget from
sending any signals when setting the value. | entailment |
def get_text(self, index=None):
"""
Gets text from a given index. If index=None, returns the current value
self.get_text(self.get_value())
"""
if index==None:
return self.get_text(self.get_value())
else:
return str(self._widget.itemText(index)) | Gets text from a given index. If index=None, returns the current value
self.get_text(self.get_value()) | entailment |
def get_all_items(self):
"""
Returns all items in the combobox dictionary.
"""
return [self._widget.itemText(k) for k in range(self._widget.count())] | Returns all items in the combobox dictionary. | entailment |
def add_tab(self, title="Yeah!", block_events=True):
"""
Adds a tab to the area, and creates the layout for this tab.
"""
self._widget.blockSignals(block_events)
# create a widget to go in the tab
tab = GridLayout()
self.tabs.append(tab)
tab.set_parent(self)
# create and append the tab to the list
self._widget.addTab(tab._widget, title)
# try to lazy set the current tab
if 'self' in self._lazy_load and self.get_tab_count() > self._lazy_load['self']:
v = self._lazy_load.pop('self')
self.set_current_tab(v)
self._widget.blockSignals(False)
return tab | Adds a tab to the area, and creates the layout for this tab. | entailment |
def remove_tab(self, tab=0):
"""
Removes the tab by index.
"""
# pop it from the list
t = self.tabs.pop(tab)
# remove it from the gui
self._widget.removeTab(tab)
# return it in case someone cares
return t | Removes the tab by index. | entailment |
def get_value(self, column=0, row=0):
"""
Returns a the value at column, row.
"""
x = self._widget.item(row, column)
if x==None: return x
else: return str(self._widget.item(row,column).text()) | Returns a the value at column, row. | entailment |
def set_value(self, column=0, row=0, value='', block_events=False):
"""
Sets the value at column, row. This will create elements dynamically,
and in a totally stupid while-looping way.
Setting block_events=True will temporarily block the widget from
sending any signals when setting the value.
"""
if block_events: self.block_events()
# dynamically resize
while column > self._widget.columnCount()-1: self._widget.insertColumn(self._widget.columnCount())
while row > self._widget.rowCount() -1: self._widget.insertRow( self._widget.rowCount())
# set the value
self._widget.setItem(row, column, _g.Qt.QtGui.QTableWidgetItem(str(value)))
if block_events: self.unblock_events()
return self | Sets the value at column, row. This will create elements dynamically,
and in a totally stupid while-looping way.
Setting block_events=True will temporarily block the widget from
sending any signals when setting the value. | entailment |
def set_column_width(self, n=0, width=120):
"""
Sets the n'th column width in pixels.
"""
self._widget.setColumnWidth(n, width)
return self | Sets the n'th column width in pixels. | entailment |
def set_header_visibility(self, column=False, row=False):
"""
Sets whether we can see the column and row headers.
"""
if row: self._widget.verticalHeader().show()
else: self._widget.verticalHeader().hide()
if column: self._widget.horizontalHeader().show()
else: self._widget.horizontalHeader().hide()
return self | Sets whether we can see the column and row headers. | entailment |
def set_row_height(self, n=0, height=18):
"""
Sets the n'th row height in pixels.
"""
self._widget.setRowHeight(n, height)
return self | Sets the n'th row height in pixels. | entailment |
def _clean_up_key(self, key):
"""
Returns the key string with no naughty characters.
"""
for n in self.naughty: key = key.replace(n, '_')
return key | Returns the key string with no naughty characters. | entailment |
def _cell_changed(self, *a):
"""
Called whenever a cell is changed. Updates the dictionary.
"""
# block all signals during the update (to avoid re-calling this)
self.block_events()
# loop over the rows
for n in range(self.get_row_count()):
# get the keys and values (as text)
key = self.get_value(0,n)
value = self.get_value(1,n)
# get rid of the None's
if key == None:
key = ''
self.set_value(0,n, '')
if value == None:
value = ''
self.set_value(1,n, '')
# if it's not an empty entry make sure it's valid
if not key == '':
# clean up the key
key = self._clean_up_key(key)
# now make sure the value is python-able
try:
eval(value)
self._widget.item(n,1).setData(_g.QtCore.Qt.BackgroundRole, _g.Qt.QtGui.QColor('white'))
except:
self._widget.item(n,1).setData(_g.QtCore.Qt.BackgroundRole, _g.Qt.QtGui.QColor('pink'))
# unblock all signals
self.unblock_events() | Called whenever a cell is changed. Updates the dictionary. | entailment |
def get_item(self, key):
"""
Returns the value associated with the key.
"""
keys = list(self.keys())
# make sure it exists
if not key in keys:
self.print_message("ERROR: '"+str(key)+"' not found.")
return None
try:
x = eval(self.get_value(1,keys.index(key)))
return x
except:
self.print_message("ERROR: '"+str(self.get_value(1,keys.index(key)))+"' cannot be evaluated.")
return None | Returns the value associated with the key. | entailment |
def keys(self):
"""
Returns a sorted list of keys
"""
keys = list()
for n in range(len(self)):
# only append the valid keys
key = self.get_value()
if not key in ['', None]: keys.append(key)
return keys | Returns a sorted list of keys | entailment |
def set_item(self, key, value):
"""
Sets the item by key, and refills the table sorted.
"""
keys = list(self.keys())
# if it exists, update
if key in keys:
self.set_value(1,keys.index(key),str(value))
# otherwise we have to add an element
else:
self.set_value(0,len(self), str(key))
self.set_value(1,len(self)-1, str(value)) | Sets the item by key, and refills the table sorted. | entailment |
def update(self, dictionary=None, **kwargs):
"""
Adds/overwrites all the keys and values from the dictionary.
"""
if not dictionary == None: kwargs.update(dictionary)
for k in list(kwargs.keys()): self[k] = kwargs[k] | Adds/overwrites all the keys and values from the dictionary. | entailment |
def get_text(self):
"""
Returns the current text.
"""
if self._multiline: return str(self._widget.toPlainText())
else: return str(self._widget.text()) | Returns the current text. | entailment |
def set_text(self, text="YEAH."):
"""
Sets the current value of the text box.
"""
# Make sure the text is actually different, so as not to
# trigger a value changed signal
s = str(text)
if not s == self.get_text(): self._widget.setText(str(text))
return self | Sets the current value of the text box. | entailment |
def set_colors(self, text='black', background='white'):
"""
Sets the colors of the text area.
"""
if self._multiline: self._widget.setStyleSheet("QTextEdit {background-color: "+str(background)+"; color: "+str(text)+"}")
else: self._widget.setStyleSheet("QLineEdit {background-color: "+str(background)+"; color: "+str(text)+"}") | Sets the colors of the text area. | entailment |
def block_events(self):
"""
Special version of block_events that loops over all tree elements.
"""
# block events in the usual way
BaseObject.block_events(self)
# loop over all top level parameters
for i in range(self._widget.topLevelItemCount()):
self._widget.topLevelItem(i).param.blockSignals(True)
return self | Special version of block_events that loops over all tree elements. | entailment |
def unblock_events(self):
"""
Special version of unblock_events that loops over all tree elements as well.
"""
# unblock events in the usual way
BaseObject.unblock_events(self)
# loop over all top level parameters
for i in range(self._widget.topLevelItemCount()):
self._widget.topLevelItem(i).param.blockSignals(False)
return self | Special version of unblock_events that loops over all tree elements as well. | entailment |
def connect_any_signal_changed(self, function):
"""
Connects the "anything changed" signal for all of the tree to the
specified function.
Parameters
----------
function
Function to connect to this signal.
"""
# loop over all top level parameters
for i in range(self._widget.topLevelItemCount()):
# make sure there is only one connection!
try:
self._widget.topLevelItem(i).param.sigTreeStateChanged.connect(
function, type=_g.QtCore.Qt.UniqueConnection)
except:
pass
return self | Connects the "anything changed" signal for all of the tree to the
specified function.
Parameters
----------
function
Function to connect to this signal. | entailment |
def connect_signal_changed(self, name, function):
"""
Connects a changed signal from the parameters of the specified name
to the supplied function.
"""
x = self._find_parameter(name.split("/"))
# if it pooped.
if x==None: return None
# connect it
x.sigValueChanged.connect(function)
# Keep track of the functions
if name in self._connection_lists: self._connection_lists[name].append(function)
else: self._connection_lists[name] = [function]
return self | Connects a changed signal from the parameters of the specified name
to the supplied function. | entailment |
def block_user_signals(self, name, ignore_error=False):
"""
Temporarily disconnects the user-defined signals for the specified
parameter name.
Note this only affects those connections made with
connect_signal_changed(), and I do not recommend adding new connections
while they're blocked!
"""
x = self._find_parameter(name.split("/"), quiet=ignore_error)
# if it pooped.
if x==None: return None
# disconnect it from all its functions
if name in self._connection_lists:
for f in self._connection_lists[name]: x.sigValueChanged.disconnect(f)
return self | Temporarily disconnects the user-defined signals for the specified
parameter name.
Note this only affects those connections made with
connect_signal_changed(), and I do not recommend adding new connections
while they're blocked! | entailment |
def unblock_user_signals(self, name, ignore_error=False):
"""
Reconnects the user-defined signals for the specified
parameter name (blocked with "block_user_signal_changed")
Note this only affects those connections made with
connect_signal_changed(), and I do not recommend adding new connections
while they're blocked!
"""
x = self._find_parameter(name.split("/"), quiet=ignore_error)
# if it pooped.
if x==None: return None
# reconnect it to all its functions
if name in self._connection_lists:
for f in self._connection_lists[name]: x.sigValueChanged.connect(f)
return self | Reconnects the user-defined signals for the specified
parameter name (blocked with "block_user_signal_changed")
Note this only affects those connections made with
connect_signal_changed(), and I do not recommend adding new connections
while they're blocked! | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.