code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def set_xylims(self, lims, axes=None, panel='top', **kws): panel = self.get_panel(panel) # print("Stacked set_xylims ", panel, self.panel) panel.set_xylims(lims, axes=axes, **kws)
set xy limits
def set_title(self,s, panel='top'): "set plot title" panel = self.get_panel(panel) panel.set_title(sf set_title(self,s, panel='top'): "set plot title" panel = self.get_panel(panel) panel.set_title(s)
set plot title
def set_ylabel(self,s, panel='top'): "set plot xlabel" panel = self.get_panel(panel) panel.set_ylabel(sf set_ylabel(self,s, panel='top'): "set plot xlabel" panel = self.get_panel(panel) panel.set_ylabel(s)
set plot xlabel
def save_figure(self, event=None, panel='top'): panel = self.get_panel(panel) panel.save_figure(event=event)
save figure image to file
def toggle_grid(self, event=None, show=None): "toggle grid on top/bottom panels" if show is None: show = not self.panel.conf.show_grid for p in (self.panel, self.panel_bot): p.conf.enable_grid(showf toggle_grid(self, event=None, show=None): "toggle grid on top/bottom panels" if show is None: show = not self.panel.conf.show_grid for p in (self.panel, self.panel_bot): p.conf.enable_grid(show)
toggle grid on top/bottom panels
def onThemeColor(self, color, item): bconf = self.panel_bot.conf if item == 'grid': bconf.set_gridcolor(color) elif item == 'bg': bconf.set_bgcolor(color) elif item == 'frame': bconf.set_framecolor(color) elif item == 'text': bconf.set_textcolor(color) bconf.canvas.draw()
pass theme colors to bottom panel
def onMargins(self, left=0.1, top=0.1, right=0.1, bottom=0.1): bconf = self.panel_bot.conf l, t, r, b = bconf.margins bconf.set_margins(left=left, top=t, right=right, bottom=b) bconf.canvas.draw()
pass left/right margins on to bottom panel
def set_viewlimits(self, panel='top'): this_panel = self.get_panel(panel) xmin, xmax, ymin, ymax = this_panel.conf.set_viewlimits()[0] # print("Set ViewLimits ", xmin, xmax, ymin, ymax) # make top/bottom panel follow xlimits if this_panel == self.panel: other = self.panel_bot for _ax in other.fig.get_axes(): _ax.set_xlim((xmin, xmax), emit=True) other.draw()
update xy limits of a plot, as used with .update_line()
def bot_yformatter(self, val, type=''): fmt = '%1.5g' ax = self.panel_bot.axes.yaxis ticks = ax.get_major_locator()() dtick = ticks[1] - ticks[0] if dtick > 29999: fmt = '%1.5g' elif dtick > 1.99: fmt = '%1.0f' elif dtick > 0.099: fmt = '%1.1f' elif dtick > 0.0099: fmt = '%1.2f' elif dtick > 0.00099: fmt = '%1.3f' elif dtick > 0.000099: fmt = '%1.4f' elif dtick > 0.0000099: fmt = '%1.5f' s = fmt % val s.strip() s = s.replace('+', '') while s.find('e0')>0: s = s.replace('e0','e') while s.find('-0')>0: s = s.replace('-0','-') return s
custom formatter for FuncFormatter() and bottom panel
def add_entry_points(self, names): names = util.return_set(names) self.entry_point_names.update(names)
adds `names` to the internal collection of entry points to track `names` can be a single object or an iterable but must be a string or iterable of strings.
def set_entry_points(self, names): names = util.return_set(names) self.entry_point_names = names
sets the internal collection of entry points to be equal to `names` `names` can be a single object or an iterable but must be a string or iterable of strings.
def remove_entry_points(self, names): names = util.return_set(names) util.remove_from_set(self.entry_point_names, names)
removes `names` from the set of entry points to track. `names` can be a single object or an iterable.
def collect_plugins(self, entry_points=None, verify_requirements=False, return_dict=False): if entry_points is None: entry_points = self.entry_point_names else: entry_points = util.return_set(entry_points) plugins = [] plugin_names = [] for name in entry_points: for entry_point in pkg_resources.iter_entry_points(name): if (hasattr(entry_point, 'resolve') and hasattr(entry_point, 'require')): if verify_requirements: entry_point.require() plugin = entry_point.resolve() else: plugin = entry_point.load() plugins.append(plugin) plugin_names.append(entry_point.name) if return_dict: return {n: v for n, v in zip(plugin_names, plugins)} return plugins, plugin_names
collects the plugins from the `entry_points`. If `entry_points` is not explicitly defined, this method will pull from the internal state defined using the add/set entry points methods. `entry_points` can be a single object or an iterable, but must be either a string or an iterable of strings. returns a list of plugins or an empty list.
def clean_texmath(txt): s = "%s " % txt out = [] i = 0 while i < len(s)-1: if s[i] == '\\' and s[i+1] in ('n', 't'): if s[i+1] == 'n': out.append('\n') elif s[i+1] == 't': out.append('\t') i += 1 elif s[i] == '$': j = s[i+1:].find('$') if j < 0: j = len(s) out.append(s[i:j+2]) i += j+2 else: out.append(s[i]) i += 1 if i > 5000: break return ''.join(out).strip()
clean tex math string, preserving control sequences (incluing \n, so also '\nu') inside $ $, while allowing \n and \t to be meaningful in the text string
def to_absolute_paths(paths): abspath = os.path.abspath paths = return_set(paths) absolute_paths = {abspath(x) for x in paths} return absolute_paths
helper method to change `paths` to absolute paths. Returns a `set` object `paths` can be either a single object or iterable
def update(self, line=None): if line: markercolor = self.markercolor if markercolor is None: markercolor=self.color # self.set_markeredgecolor(markercolor, line=line) # self.set_markerfacecolor(markercolor, line=line) self.set_label(self.label, line=line) self.set_color(self.color, line=line) self.set_style(self.style, line=line) self.set_drawstyle(self.drawstyle, line=line) self.set_marker(self.marker,line=line) self.set_markersize(self.markersize, line=line) self.set_linewidth(self.linewidth, line=line)
set a matplotlib Line2D to have the current properties
def _init_trace(self, n, color, style, linewidth=2.5, zorder=None, marker=None, markersize=6): while n >= len(self.traces): self.traces.append(LineProperties()) line = self.traces[n] label = "trace %i" % (n+1) line.label = label line.drawstyle = 'default' if zorder is None: zorder = 5 * (n+1) line.zorder = zorder if color is not None: line.color = color if style is not None: line.style = style if linewidth is not None: line.linewidth = linewidth if marker is not None: line.marker = marker if markersize is not None: line.markersize = markersize self.traces[n] = line
used for building set of traces
def set_margins(self, left=0.1, top=0.1, right=0.1, bottom=0.1, delay_draw=False): "set margins" self.margins = (left, top, right, bottom) if self.panel is not None: self.panel.gridspec.update(left=left, top=1-top, right=1-right, bottom=bottom) for ax in self.canvas.figure.get_axes(): ax.update_params() ax.set_position(ax.figbox) if not delay_draw: self.canvas.draw() if callable(self.margin_callback): self.margin_callback(left=left, top=top, right=right, bottom=bottomf set_margins(self, left=0.1, top=0.1, right=0.1, bottom=0.1, delay_draw=False): "set margins" self.margins = (left, top, right, bottom) if self.panel is not None: self.panel.gridspec.update(left=left, top=1-top, right=1-right, bottom=bottom) for ax in self.canvas.figure.get_axes(): ax.update_params() ax.set_position(ax.figbox) if not delay_draw: self.canvas.draw() if callable(self.margin_callback): self.margin_callback(left=left, top=top, right=right, bottom=bottom)
set margins
def set_gridcolor(self, color): self.gridcolor = color for ax in self.canvas.figure.get_axes(): for i in ax.get_xgridlines()+ax.get_ygridlines(): i.set_color(color) i.set_zorder(-1) if callable(self.theme_color_callback): self.theme_color_callback(color, 'grid')
set color for grid
def set_bgcolor(self, color): self.bgcolor = color for ax in self.canvas.figure.get_axes(): if matplotlib.__version__ < '2.0': ax.set_axis_bgcolor(color) else: ax.set_facecolor(color) if callable(self.theme_color_callback): self.theme_color_callback(color, 'bg')
set color for background of plot
def set_framecolor(self, color): self.framecolor = color self.canvas.figure.set_facecolor(color) if callable(self.theme_color_callback): self.theme_color_callback(color, 'frame')
set color for outer frame
def set_textcolor(self, color): self.textcolor = color self.relabel() if callable(self.theme_color_callback): self.theme_color_callback(color, 'text')
set color for labels and axis text
def enable_grid(self, show=None, delay_draw=False): "enable/disable grid display" if show is not None: self.show_grid = show axes = self.canvas.figure.get_axes() ax0 = axes[0] for i in ax0.get_xgridlines() + ax0.get_ygridlines(): i.set_color(self.gridcolor) i.set_zorder(-1) axes[0].grid(self.show_grid) for ax in axes[1:]: ax.grid(False) if not delay_draw: self.canvas.draw(f enable_grid(self, show=None, delay_draw=False): "enable/disable grid display" if show is not None: self.show_grid = show axes = self.canvas.figure.get_axes() ax0 = axes[0] for i in ax0.get_xgridlines() + ax0.get_ygridlines(): i.set_color(self.gridcolor) i.set_zorder(-1) axes[0].grid(self.show_grid) for ax in axes[1:]: ax.grid(False) if not delay_draw: self.canvas.draw()
enable/disable grid display
def set_axes_style(self, style=None, delay_draw=False): if style is not None: self.axes_style = style axes0 = self.canvas.figure.get_axes()[0] _sty = self.axes_style.lower() if _sty in ('fullbox', 'full'): _sty = 'box' if _sty == 'leftbot': _sty = 'open' if _sty == 'box': axes0.xaxis.set_ticks_position('both') axes0.yaxis.set_ticks_position('both') axes0.spines['top'].set_visible(True) axes0.spines['right'].set_visible(True) elif _sty == 'open': axes0.xaxis.set_ticks_position('bottom') axes0.yaxis.set_ticks_position('left') axes0.spines['top'].set_visible(False) axes0.spines['right'].set_visible(False) elif _sty == 'bottom': axes0.xaxis.set_ticks_position('bottom') axes0.spines['top'].set_visible(False) axes0.spines['left'].set_visible(False) axes0.spines['right'].set_visible(False) if not delay_draw: self.canvas.draw()
set axes style: one of 'box' / 'fullbox' : show all four axes borders 'open' / 'leftbot' : show left and bottom axes 'bottom' : show bottom axes only
def set_legend_location(self, loc, onaxis): "set legend location" self.legend_onaxis = 'on plot' if not onaxis: self.legend_onaxis = 'off plot' if loc == 'best': loc = 'upper right' if loc in self.legend_abbrevs: loc = self.legend_abbrevs[loc] if loc in self.legend_locs: self.legend_loc = lof set_legend_location(self, loc, onaxis): "set legend location" self.legend_onaxis = 'on plot' if not onaxis: self.legend_onaxis = 'off plot' if loc == 'best': loc = 'upper right' if loc in self.legend_abbrevs: loc = self.legend_abbrevs[loc] if loc in self.legend_locs: self.legend_loc = loc
set legend location
def unzoom(self, full=False, delay_draw=False): if full: self.zoom_lims = self.zoom_lims[:1] self.zoom_lims = [] elif len(self.zoom_lims) > 0: self.zoom_lims.pop() self.set_viewlimits() if not delay_draw: self.canvas.draw()
unzoom display 1 level or all the way
def set_logscale(self, xscale='linear', yscale='linear', delay_draw=False): "set log or linear scale for x, y axis" self.xscale = xscale self.yscale = yscale for axes in self.canvas.figure.get_axes(): try: axes.set_yscale(yscale, basey=10) except: axes.set_yscale('linear') try: axes.set_xscale(xscale, basex=10) except: axes.set_xscale('linear') if not delay_draw: self.process_data(f set_logscale(self, xscale='linear', yscale='linear', delay_draw=False): "set log or linear scale for x, y axis" self.xscale = xscale self.yscale = yscale for axes in self.canvas.figure.get_axes(): try: axes.set_yscale(yscale, basey=10) except: axes.set_yscale('linear') try: axes.set_xscale(xscale, basex=10) except: axes.set_xscale('linear') if not delay_draw: self.process_data()
set log or linear scale for x, y axis
def add_text(self, text, x, y, **kws): self.panel.add_text(text, x, y, **kws)
add text to plot
def add_arrow(self, x1, y1, x2, y2, **kws): self.panel.add_arrow(x1, y1, x2, y2, **kws)
add arrow to plot
def plot(self, x, y, **kw): self.panel.plot(x, y, **kw)
plot after clearing current plot
def oplot(self, x, y, **kw): self.panel.oplot(x, y, **kw)
generic plotting method, overplotting any existing plot
def scatterplot(self, x, y, **kw): self.panel.scatterplot(x, y, **kw)
plot after clearing current plot
def update_line(self, t, x, y, **kw): self.panel.update_line(t, x, y, **kw)
overwrite data for trace t
def add_plugin_directories(self, paths, except_blacklisted=True): self.directory_manager.add_directories(paths, except_blacklisted)
Adds `directories` to the set of plugin directories. `directories` may be either a single object or a iterable. `directories` can be relative paths, but will be converted into absolute paths based on the current working directory. if `except_blacklisted` is `True` all `directories` in that are blacklisted will be removed
def set_plugin_directories(self, paths, except_blacklisted=True): self.directory_manager.set_directories(paths, except_blacklisted)
Sets the plugin directories to `directories`. This will delete the previous state stored in `self.plugin_directories` in favor of the `directories` passed in. `directories` may be either a single object or an iterable. `directories` can contain relative paths but will be converted into absolute paths based on the current working directory. if `except_blacklisted` is `True` all `directories` in blacklisted that are blacklisted will be removed
def add_plugin_filepaths(self, filepaths, except_blacklisted=True): self.file_manager.add_plugin_filepaths(filepaths, except_blacklisted)
Adds `filepaths` to internal state. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable If `except_blacklisted` is `True`, all `filepaths` that have been blacklisted will not be added.
def set_plugin_filepaths(self, filepaths, except_blacklisted=True): self.file_manager.set_plugin_filepaths(filepaths, except_blacklisted)
Sets internal state to `filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable. If `except_blacklisted` is `True`, all `filepaths` that have been blacklisted will not be set.
def add_blacklisted_directories(self, directories, rm_black_dirs_from_stored_dirs=True): add_black_dirs = self.directory_manager.add_blacklisted_directories add_black_dirs(directories, rm_black_dirs_from_stored_dirs)
Adds `directories` to be blacklisted. Blacklisted directories will not be returned or searched recursively when calling the `collect_directories` method. `directories` may be a single instance or an iterable. Recommend passing in absolute paths, but method will try to convert to absolute paths based on the current working directory. If `remove_from_stored_directories` is true, all `directories` will be removed from internal state.
def set_blacklisted_directories(self, directories, rm_black_dirs_from_stored_dirs=True): set_black_dirs = self.directory_manager.set_blacklisted_directories set_black_dirs(directories, rm_black_dirs_from_stored_dirs)
Sets the `directories` to be blacklisted. Blacklisted directories will not be returned or searched recursively when calling `collect_directories`. This will replace the previously stored set of blacklisted paths. `directories` may be a single instance or an iterable. Recommend passing in absolute paths. Method will try to convert to absolute path based on current working directory.
def add_blacklisted_filepaths(self, filepaths, remove_from_stored=True): self.file_manager.add_blacklisted_filepaths(filepaths, remove_from_stored)
Add `filepaths` to blacklisted filepaths. If `remove_from_stored` is `True`, any `filepaths` in internal state will be automatically removed.
def collect_filepaths(self, directories): plugin_filepaths = set() directories = util.to_absolute_paths(directories) for directory in directories: filepaths = util.get_filepaths_from_dir(directory) filepaths = self._filter_filepaths(filepaths) plugin_filepaths.update(set(filepaths)) plugin_filepaths = self._remove_blacklisted(plugin_filepaths) return plugin_filepaths
Collects and returns every filepath from each directory in `directories` that is filtered through the `file_filters`. If no `file_filters` are present, passes every file in directory as a result. Always returns a `set` object `directories` can be a object or an iterable. Recommend using absolute paths.
def add_plugin_filepaths(self, filepaths, except_blacklisted=True): filepaths = util.to_absolute_paths(filepaths) if except_blacklisted: filepaths = util.remove_from_set(filepaths, self.blacklisted_filepaths) self.plugin_filepaths.update(filepaths)
Adds `filepaths` to the `self.plugin_filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable If `except_blacklisted` is `True`, all `filepaths` that have been blacklisted will not be added.
def set_plugin_filepaths(self, filepaths, except_blacklisted=True): filepaths = util.to_absolute_paths(filepaths) if except_blacklisted: filepaths = util.remove_from_set(filepaths, self.blacklisted_filepaths) self.plugin_filepaths = filepaths
Sets `filepaths` to the `self.plugin_filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable. If `except_blacklisted` is `True`, all `filepaths` that have been blacklisted will not be set.
def remove_plugin_filepaths(self, filepaths): filepaths = util.to_absolute_paths(filepaths) self.plugin_filepaths = util.remove_from_set(self.plugin_filepaths, filepaths)
Removes `filepaths` from `self.plugin_filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if not passed in. `filepaths` can be a single object or an iterable.
def set_file_filters(self, file_filters): file_filters = util.return_list(file_filters) self.file_filters = file_filters
Sets internal file filters to `file_filters` by tossing old state. `file_filters` can be single object or iterable.
def add_file_filters(self, file_filters): file_filters = util.return_list(file_filters) self.file_filters.extend(file_filters)
Adds `file_filters` to the internal file filters. `file_filters` can be single object or iterable.
def remove_file_filters(self, file_filters): self.file_filters = util.remove_from_list(self.file_filters, file_filters)
Removes the `file_filters` from the internal state. `file_filters` can be a single object or an iterable.
def add_blacklisted_filepaths(self, filepaths, remove_from_stored=True): filepaths = util.to_absolute_paths(filepaths) self.blacklisted_filepaths.update(filepaths) if remove_from_stored: self.plugin_filepaths = util.remove_from_set(self.plugin_filepaths, filepaths)
Add `filepaths` to blacklisted filepaths. If `remove_from_stored` is `True`, any `filepaths` in `plugin_filepaths` will be automatically removed. Recommend passing in absolute filepaths but method will attempt to convert to absolute filepaths based on current working directory.
def set_blacklisted_filepaths(self, filepaths, remove_from_stored=True): filepaths = util.to_absolute_paths(filepaths) self.blacklisted_filepaths = filepaths if remove_from_stored: self.plugin_filepaths = util.remove_from_set(self.plugin_filepaths, filepaths)
Sets internal blacklisted filepaths to filepaths. If `remove_from_stored` is `True`, any `filepaths` in `self.plugin_filepaths` will be automatically removed. Recommend passing in absolute filepaths but method will attempt to convert to absolute filepaths based on current working directory.
def remove_blacklisted_filepaths(self, filepaths): filepaths = util.to_absolute_paths(filepaths) black_paths = self.blacklisted_filepaths black_paths = util.remove_from_set(black_paths, filepaths)
Removes `filepaths` from blacklisted filepaths Recommend passing in absolute filepaths but method will attempt to convert to absolute filepaths based on current working directory.
def _remove_blacklisted(self, filepaths): filepaths = util.remove_from_set(filepaths, self.blacklisted_filepaths) return filepaths
internal helper method to remove the blacklisted filepaths from `filepaths`.
def _filter_filepaths(self, filepaths): if self.file_filters: plugin_filepaths = set() for file_filter in self.file_filters: plugin_paths = file_filter(filepaths) plugin_filepaths.update(plugin_paths) else: plugin_filepaths = filepaths return plugin_filepaths
helps iterate through all the file parsers each filter is applied individually to the same set of `filepaths`
def plot(self,x,y,panel=None,**kws): if panel is None: panel = self.current_panel opts = {} opts.update(self.default_panelopts) opts.update(kws) self.panels[panel].plot(x ,y, **opts)
plot after clearing current plot
def oplot(self,x,y,panel=None,**kw): if panel is None: panel = self.current_panel opts = {} opts.update(self.default_panelopts) opts.update(kws) self.panels[panel].oplot(x, y, **opts)
generic plotting method, overplotting any existing plot
def update_line(self, t, x, y, panel=None, **kw): if panel is None: panel = self.current_panel self.panels[panel].update_line(t, x, y, **kw)
overwrite data for trace t
def set_xylims(self, lims, axes=None, panel=None): if panel is None: panel = self.current_panel self.panels[panel].set_xylims(lims, axes=axes, **kw)
overwrite data for trace t
def clear(self,panel=None): if panel is None: panel = self.current_panel self.panels[panel].clear()
clear plot
def unzoom_all(self,event=None,panel=None): if panel is None: panel = self.current_panel self.panels[panel].unzoom_all(event=event)
zoom out full data range
def unzoom(self,event=None,panel=None): if panel is None: panel = self.current_panel self.panels[panel].unzoom(event=event)
zoom out 1 level, or to full data range
def set_title(self,s,panel=None): "set plot title" if panel is None: panel = self.current_panel self.panels[panel].set_title(sf set_title(self,s,panel=None): "set plot title" if panel is None: panel = self.current_panel self.panels[panel].set_title(s)
set plot title
def set_xlabel(self,s,panel=None): "set plot xlabel" if panel is None: panel = self.current_panel self.panels[panel].set_xlabel(sf set_xlabel(self,s,panel=None): "set plot xlabel" if panel is None: panel = self.current_panel self.panels[panel].set_xlabel(s)
set plot xlabel
def set_ylabel(self,s,panel=None): "set plot xlabel" if panel is None: panel = self.current_panel self.panels[panel].set_ylabel(sf set_ylabel(self,s,panel=None): "set plot xlabel" if panel is None: panel = self.current_panel self.panels[panel].set_ylabel(s)
set plot xlabel
def save_figure(self,event=None,panel=None): if panel is None: panel = self.current_panel self.panels[panel].save_figure(event=event)
save figure image to file
def rgb(color,default=(0,0,0)): c = color.lower() if c[0:1] == '#' and len(c)==7: r,g,b = c[1:3], c[3:5], c[5:] r,g,b = [int(n, 16) for n in (r, g, b)] return (r,g,b) if c.find(' ')>-1: c = c.replace(' ','') if c.find('gray')>-1: c = c.replace('gray','grey') if c in x11_colors.keys(): return x11_colors[c] return default
return rgb tuple for named color in rgb.txt or a hex color
def register_custom_colormaps(): if not HAS_MPL: return () makemap = LinearSegmentedColormap.from_list for name, val in custom_colormap_data.items(): cm1 = np.array(val).transpose().astype('f8')/256.0 cm2 = cm1[::-1] nam1 = name nam2 = '%s_r' % name register_cmap(name=nam1, cmap=makemap(nam1, cm1, 256), lut=256) register_cmap(name=nam2, cmap=makemap(nam2, cm2, 256), lut=256) return ('stdgamma', 'red', 'green', 'blue', 'red_heat', 'green_heat', 'blue_heat', 'magenta', 'yellow', 'cyan')
registers custom color maps
def plot_residual(self, x, y1, y2, label1='Raw data', label2='Fit/theory', xlabel=None, ylabel=None, show_legend=True, **kws): panel = self.get_panel('top') panel.plot(x, y1, label=label1, **kws) panel = self.get_panel('top') panel.oplot(x, y2, label=label2, ylabel=ylabel, show_legend=show_legend, **kws) panel = self.get_panel('bottom') panel.plot(x, (y2-y1), ylabel='residual', show_legend=False, **kws) if xlabel is not None: self.xlabel = xlabel if self.xlabel is not None: self.panel_bot.set_xlabel(self.xlabel)
plot after clearing current plot
def onCMapSave(self, event=None, col='int'): file_choices = 'PNG (*.png)|*.png' ofile = 'Colormap.png' dlg = wx.FileDialog(self, message='Save Colormap as...', defaultDir=os.getcwd(), defaultFile=ofile, wildcard=file_choices, style=wx.FD_SAVE|wx.FD_CHANGE_DIR) if dlg.ShowModal() == wx.ID_OK: self.cmap_panels[0].cmap_canvas.print_figure(dlg.GetPath(), dpi=600)
save color table image
def save_figure(self,event=None, transparent=True, dpi=600): if self.panel is not None: self.panel.save_figure(event=event, transparent=transparent, dpi=dpi)
save figure image to file
def plugin_valid(self, filename): filename = os.path.basename(filename) for regex in self.regex_expressions: if regex.match(filename): return True return False
Checks if the given filename is a valid plugin for this Strategy
def auto_reply_message(self): if self._auto_reply is None: r = requests.get('https://outlook.office.com/api/v2.0/me/MailboxSettings/AutomaticRepliesSetting', headers=self._headers) check_response(r) self._auto_reply = r.json().get('InternalReplyMessage') return self._auto_reply
The account's Internal auto reply message. Setting the value will change the auto reply message of the account, automatically setting the status to enabled (but not altering the schedule).
def get_message(self, message_id): r = requests.get('https://outlook.office.com/api/v2.0/me/messages/' + message_id, headers=self._headers) check_response(r) return Message._json_to_message(self, r.json())
Gets message matching provided id. the Outlook email matching the provided message_id. Args: message_id: A string for the intended message, provided by Outlook Returns: :class:`Message <pyOutlook.core.message.Message>`
def get_messages(self, page=0): endpoint = 'https://outlook.office.com/api/v2.0/me/messages' if page > 0: endpoint = endpoint + '/?%24skip=' + str(page) + '0' log.debug('Getting messages from endpoint: {} with Headers: {}'.format(endpoint, self._headers)) r = requests.get(endpoint, headers=self._headers) check_response(r) return Message._json_to_messages(self, r.json())
Get first 10 messages in account, across all folders. Keyword Args: page (int): Integer representing the 'page' of results to fetch Returns: List[:class:`Message <pyOutlook.core.message.Message>`]
def new_email(self, body='', subject='', to=list): return Message(self.access_token, body, subject, to)
Creates a :class:`Message <pyOutlook.core.message.Message>` object. Keyword Args: body (str): The body of the email subject (str): The subject of the email to (List[Contact]): A list of recipients to email Returns: :class:`Message <pyOutlook.core.message.Message>`
def send_email(self, body=None, subject=None, to=list, cc=None, bcc=None, send_as=None, attachments=None): email = Message(self.access_token, body, subject, to, cc=cc, bcc=bcc, sender=send_as) if attachments is not None: for attachment in attachments: email.attach(attachment.get('bytes'), attachment.get('name')) email.send()
Sends an email in one method, a shortcut for creating an instance of :class:`Message <pyOutlook.core.message.Message>` . Args: body (str): The body of the email subject (str): The subject of the email to (list): A list of :class:`Contacts <pyOutlook.core.contact.Contact>` cc (list): A list of :class:`Contacts <pyOutlook.core.contact.Contact>` which will be added to the 'Carbon Copy' line bcc (list): A list of :class:`Contacts <pyOutlook.core.contact.Contact>` while be blindly added to the email send_as (Contact): A :class:`Contact <pyOutlook.core.contact.Contact>` whose email the OutlookAccount has access to attachments (list): A list of dictionaries with two parts [1] 'name' - a string which will become the file's name [2] 'bytes' - the bytes of the file.
def get_folders(self): endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' r = requests.get(endpoint, headers=self._headers) if check_response(r): return Folder._json_to_folders(self, r.json())
Returns a list of all folders for this account Returns: List[:class:`Folder <pyOutlook.core.folder.Folder>`]
def get_folder_by_id(self, folder_id): endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + folder_id r = requests.get(endpoint, headers=self._headers) check_response(r) return_folder = r.json() return Folder._json_to_folder(self, return_folder)
Retrieve a Folder by its Outlook ID Args: folder_id: The ID of the :class:`Folder <pyOutlook.core.folder.Folder>` to retrieve Returns: :class:`Folder <pyOutlook.core.folder.Folder>`
def _get_messages_from_folder_name(self, folder_name): r = requests.get('https://outlook.office.com/api/v2.0/me/MailFolders/' + folder_name + '/messages', headers=self._headers) check_response(r) return Message._json_to_messages(self, r.json())
Retrieves all messages from a folder, specified by its name. This only works with "Well Known" folders, such as 'Inbox' or 'Drafts'. Args: folder_name (str): The name of the folder to retrieve Returns: List[:class:`Message <pyOutlook.core.message.Message>` ]
def parent_folder(self): # type: () -> Folder if self.__parent_folder is None: self.__parent_folder = self.account.get_folder_by_id(self.__parent_folder_id) return self.__parent_folder
Returns the :class:`Folder <pyOutlook.core.folder.Folder>` this message is in >>> account = OutlookAccount('') >>> message = account.get_messages()[0] >>> message.parent_folder Inbox >>> message.parent_folder.unread_count 19 Returns: :class:`Folder <pyOutlook.core.folder.Folder>`
def api_representation(self, content_type): payload = dict(Subject=self.subject, Body=dict(ContentType=content_type, Content=self.body)) if self.sender is not None: payload.update(From=self.sender.api_representation()) # A list of strings can also be provided for convenience. If provided, convert them into Contacts if any(isinstance(item, str) for item in self.to): self.to = [Contact(email=email) for email in self.to] # Turn each contact into the JSON needed for the Outlook API recipients = [contact.api_representation() for contact in self.to] payload.update(ToRecipients=recipients) # Conduct the same process for CC and BCC if needed if self.cc: if any(isinstance(email, str) for email in self.cc): self.cc = [Contact(email) for email in self.cc] cc_recipients = [contact.api_representation() for contact in self.cc] payload.update(CcRecipients=cc_recipients) if self.bcc: if any(isinstance(email, str) for email in self.bcc): self.bcc = [Contact(email) for email in self.bcc] bcc_recipients = [contact.api_representation() for contact in self.bcc] payload.update(BccRecipients=bcc_recipients) if self._attachments: payload.update(Attachments=[attachment.api_representation() for attachment in self._attachments]) payload.update(Importance=str(self.importance)) return dict(Message=payload)
Returns the JSON representation of this message required for making requests to the API. Args: content_type (str): Either 'HTML' or 'Text'
def _make_api_call(self, http_type, endpoint, extra_headers = None, data=None): # type: (str, str, dict, Any) -> None headers = {"Authorization": "Bearer " + self.account.access_token, "Content-Type": "application/json"} if extra_headers is not None: headers.update(extra_headers) log.debug('Making Outlook API request for message (ID: {}) with Headers: {} Data: {}' .format(self.message_id, headers, data)) if http_type == 'post': r = requests.post(endpoint, headers=headers, data=data) elif http_type == 'delete': r = requests.delete(endpoint, headers=headers) elif http_type == 'patch': r = requests.patch(endpoint, headers=headers, data=data) else: raise NotImplemented check_response(r)
Internal method to handle making calls to the Outlook API and logging both the request and response Args: http_type: (str) 'post' or 'delete' endpoint: (str) The endpoint the request will be made to headers: A dict of headers to send to the requests module in addition to Authorization and Content-Type data: The data to provide to the requests module Raises: MiscError: For errors that aren't a 401 AuthError: For 401 errors
def send(self, content_type='HTML'): payload = self.api_representation(content_type) endpoint = 'https://outlook.office.com/api/v1.0/me/sendmail' self._make_api_call('post', endpoint=endpoint, data=json.dumps(payload))
Takes the recipients, body, and attachments of the Message and sends. Args: content_type: Can either be 'HTML' or 'Text', defaults to HTML.
def forward(self, to_recipients, forward_comment=None): # type: (Union[List[Contact], List[str]], str) -> None payload = dict() if forward_comment is not None: payload.update(Comment=forward_comment) # A list of strings can also be provided for convenience. If provided, convert them into Contacts if any(isinstance(recipient, str) for recipient in to_recipients): to_recipients = [Contact(email=email) for email in to_recipients] # Contact() will handle turning itself into the proper JSON format for the API to_recipients = [contact.api_representation() for contact in to_recipients] payload.update(ToRecipients=to_recipients) endpoint = 'https://outlook.office.com/api/v2.0/me/messages/{}/forward'.format(self.message_id) self._make_api_call('post', endpoint=endpoint, data=json.dumps(payload))
Forward Message to recipients with an optional comment. Args: to_recipients: A list of :class:`Contacts <pyOutlook.core.contact.Contact>` to send the email to. forward_comment: String comment to append to forwarded email. Examples: >>> john = Contact('[email protected]') >>> betsy = Contact('[email protected]') >>> email = Message() >>> email.forward([john, betsy]) >>> email.forward([john], 'Hey John')
def reply(self, reply_comment): payload = '{ "Comment": "' + reply_comment + '"}' endpoint = 'https://outlook.office.com/api/v2.0/me/messages/' + self.message_id + '/reply' self._make_api_call('post', endpoint, data=payload)
Reply to the Message. Notes: HTML can be inserted in the string and will be interpreted properly by Outlook. Args: reply_comment: String message to send with email.
def reply_all(self, reply_comment): payload = '{ "Comment": "' + reply_comment + '"}' endpoint = 'https://outlook.office.com/api/v2.0/me/messages/{}/replyall'.format(self.message_id) self._make_api_call('post', endpoint, data=payload)
Replies to everyone on the email, including those on the CC line. With great power, comes great responsibility. Args: reply_comment: The string comment to send to everyone on the email.
def move_to(self, folder): if isinstance(folder, Folder): self.move_to(folder.id) else: self._move_to(folder)
Moves the email to the folder specified by the folder parameter. Args: folder: A string containing the folder ID the message should be moved to, or a Folder instance
def attach(self, file_bytes, file_name): try: file_bytes = base64.b64encode(file_bytes) except TypeError: file_bytes = base64.b64encode(bytes(file_bytes, 'utf-8')) self._attachments.append( Attachment(get_valid_filename(file_name), file_bytes.decode('utf-8')) )
Adds an attachment to the email. The filename is passed through Django's get_valid_filename which removes invalid characters. From the documentation for that function: >>> get_valid_filename("john's portrait in 2004.jpg") 'johns_portrait_in_2004.jpg' Args: file_bytes: The bytes of the file to send (if you send a string, ex for CSV, pyOutlook will attempt to convert that into bytes before base64ing the content). file_name: The name of the file, as a string and leaving out the extension, that should be sent
def tricolor_white_bg(self, img): tmp = 0.5*(1.0 - (img - img.min())/(img.max() - img.min())) out = tmp*0.0 out[:,:,0] = tmp[:,:,1] + tmp[:,:,2] out[:,:,1] = tmp[:,:,0] + tmp[:,:,2] out[:,:,2] = tmp[:,:,0] + tmp[:,:,1] return out
transforms image from RGB with (0,0,0) showing black to RGB with 0,0,0 showing white takes the Red intensity and sets the new intensity to go from (0, 0.5, 0.5) (for Red=0) to (0, 0, 0) (for Red=1) and so on for the Green and Blue maps. Thus the image will be transformed from old intensity new intensity (0.0, 0.0, 0.0) (black) (1.0, 1.0, 1.0) (white) (1.0, 1.0, 1.0) (white) (0.0, 0.0, 0.0) (black) (1.0, 0.0, 0.0) (red) (1.0, 0.5, 0.5) (red) (0.0, 1.0, 0.0) (green) (0.5, 1.0, 0.5) (green) (0.0, 0.0, 1.0) (blue) (0.5, 0.5, 1.0) (blue)
def rgb2cmy(self, img, whitebg=False): tmp = img*1.0 if whitebg: tmp = (1.0 - (img - img.min())/(img.max() - img.min())) out = tmp*0.0 out[:,:,0] = (tmp[:,:,1] + tmp[:,:,2])/2.0 out[:,:,1] = (tmp[:,:,0] + tmp[:,:,2])/2.0 out[:,:,2] = (tmp[:,:,0] + tmp[:,:,1])/2.0 return out
transforms image from RGB to CMY
def plugin_valid(self, filepath): plugin_valid = False for extension in self.extensions: if filepath.endswith(".{}".format(extension)): plugin_valid = True break return plugin_valid
checks to see if plugin ends with one of the approved extensions
def api_representation(self): return dict(EmailAddress=dict(Name=self.name, Address=self.email))
Returns the JSON formatting required by Outlook's API for contacts
def set_focused(self, account, is_focused): # type: (OutlookAccount, bool) -> bool endpoint = 'https://outlook.office.com/api/v2.0/me/InferenceClassification/Overrides' if is_focused: classification = 'Focused' else: classification = 'Other' data = dict(ClassifyAs=classification, SenderEmailAddress=dict(Address=self.email)) r = requests.post(endpoint, headers=account._headers, data=json.dumps(data)) # Will raise an error if necessary, otherwise returns True result = check_response(r) self.focused = is_focused return result
Emails from this contact will either always be put in the Focused inbox, or always put in Other, based on the value of is_focused. Args: account (OutlookAccount): The :class:`OutlookAccount <pyOutlook.core.main.OutlookAccount>` the override should be set for is_focused (bool): Whether this contact should be set to Focused, or Other. Returns: True if the request was successful
def image2wxbitmap(img): "PIL image 2 wx bitmap" if is_wxPhoenix: wximg = wx.Image(*img.size) else: wximg = wx.EmptyImage(*img.size) wximg.SetData(img.tobytes()) return wximg.ConvertToBitmap(f image2wxbitmap(img): "PIL image 2 wx bitmap" if is_wxPhoenix: wximg = wx.Image(*img.size) else: wximg = wx.EmptyImage(*img.size) wximg.SetData(img.tobytes()) return wximg.ConvertToBitmap()
PIL image 2 wx bitmap
def set_contrast_levels(self, contrast_level=0): for cmap_panel, img_panel in zip((self.cmap_panels[0], self.cmap_panels[1]), (self.img1_panel, self.img2_panel)): conf = img_panel.conf img = img_panel.conf.data if contrast_level is None: contrast_level = 0 conf.contrast_level = contrast_level clevels = [contrast_level, 100.0-contrast_level] jmin = imin = img.min() jmax = imax = img.max() cmap_panel.imin_val.SetValue('%.4g' % imin) cmap_panel.imax_val.SetValue('%.4g' % imax) jmin, jmax = np.percentile(img, clevels) conf.int_lo[0] = imin conf.int_hi[0] = imax conf.cmap_lo[0] = xlo = (jmin-imin)*conf.cmap_range/(imax-imin) conf.cmap_hi[0] = xhi = (jmax-imin)*conf.cmap_range/(imax-imin) cmap_panel.cmap_hi.SetValue(xhi) cmap_panel.cmap_lo.SetValue(xlo) cmap_panel.islider_range.SetLabel('Shown: [ %.4g : %.4g ]' % (jmin, jmax)) cmap_panel.redraw_cmap() img_panel.redraw()
enhance contrast levels, or use full data range according to value of self.panel.conf.contrast_level
def get_valid_filename(s): s = str(s).strip().replace(' ', '_') return re.sub(r'(?u)[^-\w.]', '', s)
Shamelessly taken from Django. https://github.com/django/django/blob/master/django/utils/text.py Return the given string converted to a string that can be used for a clean filename. Remove leading and trailing spaces; convert other spaces to underscores; and remove anything that is not an alphanumeric, dash, underscore, or dot. >>> get_valid_filename("john's portrait in 2004.jpg") 'johns_portrait_in_2004.jpg'
def check_response(response): status_code = response.status_code if 100 < status_code < 299: return True elif status_code == 401 or status_code == 403: message = get_response_data(response) raise AuthError('Access Token Error, Received ' + str(status_code) + ' from Outlook REST Endpoint with the message: {}'.format(message)) elif status_code == 400: message = get_response_data(response) raise RequestError('The request made to the Outlook API was invalid. Received the following message: {}'. format(message)) else: message = get_response_data(response) raise APIError('Encountered an unknown error from the Outlook API: {}'.format(message))
Checks that a response is successful, raising the appropriate Exceptions otherwise.
def get_plugins(self, filter_function=None): plugins = self.plugins if filter_function is not None: plugins = filter_function(plugins) return plugins
Gets out the plugins from the internal state. Returns a list object. If the optional filter_function is supplied, applies the filter function to the arguments before returning them. Filters should be callable and take a list argument of plugins.
def _get_instance(self, klasses): return [x for x in self.plugins if isinstance(x, klasses)]
internal method that gets every instance of the klasses out of the internal plugin state.
def get_instances(self, filter_function=IPlugin): if isinstance(filter_function, (list, tuple)): return self._get_instance(filter_function) elif inspect.isclass(filter_function): return self._get_instance(filter_function) elif filter_function is None: return self.plugins else: return filter_function(self.plugins)
Gets instances out of the internal state using the default filter supplied in filter_function. By default, it is the class IPlugin. Can optionally pass in a list or tuple of classes in for `filter_function` which will accomplish the same goal. lastly, a callable can be passed in, however it is up to the user to determine if the objects are instances or not.
def register_classes(self, classes): classes = util.return_list(classes) for klass in classes: IPlugin.register(klass)
Register classes as plugins that are not subclassed from IPlugin. `classes` may be a single object or an iterable.
def _instance_parser(self, plugins): plugins = util.return_list(plugins) for instance in plugins: if inspect.isclass(instance): self._handle_class_instance(instance) else: self._handle_object_instance(instance)
internal method to parse instances of plugins. Determines if each class is a class instance or object instance and calls the appropiate handler method.