def __init__(self, name='q_value', track=False):
# Tf graph input
self.ai = Learner(True)
self.saver = tf.train.Saver()
self.saver.restore(self.ai.s,"models/narrow-deep-pipe.ckpt")
self.theta = 0
self.im = None
self.fig = None
self.sensor = 0
self.smoothing = True
matplotlib.rcParams['xtick.direction'] = 'out'
matplotlib.rcParams['ytick.direction'] = 'out'
python类rcParams()的实例源码
def DipoleDipolefun(i):
matplotlib.rcParams['font.size'] = 14
plt.figure(figsize=(10, 3))
ntx = xr.size-2
plt.plot(xr[:-1]+dxr*0.5, np.zeros_like(xr[:-1]), 'ko')
plt.plot(xr[i]+dxr[i]*0.5, np.zeros(1), 'ro')
# for i in range(ntx):
if i < ntx-nmax+1:
txmid = xr[i]+dxr[i]*0.5
rxmid = xr[i+1:i+1+nmax]+dxr[i+1:i+1+nmax]*0.5
mid = (txmid+rxmid)*0.5
plt.plot(rxmid, np.zeros(rxmid.size), 'go')
plt.plot(mid, np.arange(nmax)+1., 'bo')
plt.plot(np.r_[txmid, mid[-1]], np.r_[0, nmax], 'k:')
for j in range(nmax):
plt.plot(np.r_[rxmid[j], mid[j]], np.r_[0, j+1], 'k:')
else:
txmid = xr[i]+dxr[i]*0.5
rxmid = xr[i+1:ntx+1]+dxr[i+1:ntx+1]*0.5
mid = (txmid+rxmid)*0.5
plt.plot((txmid+rxmid)*0.5, np.arange(mid.size)+1., 'bo')
plt.plot(rxmid, np.zeros(rxmid.size), 'go')
plt.plot(np.r_[txmid, mid[-1]], np.r_[0, mid.size], 'k:')
for j in range(ntx-i):
plt.plot(np.r_[rxmid[j], mid[j]], np.r_[0, j+1], 'k:')
plt.xlabel("X (m)")
plt.ylabel("N-spacing")
plt.xlim(xr.min(), xr.max())
plt.ylim(nmax+1, -1)
plt.show()
return
def DipoleDipolefun(i):
"""
Plotting function to display all receivers and pseudolocations
of a dipole-dipole survey for each source i
:param int i: source index
"""
matplotlib.rcParams['font.size'] = 14
plt.figure(figsize=(10, 3))
nmax = 8
xr = np.linspace(-40, 40, 20)
ntx = xr.size-2
dxr = np.diff(xr)
plt.plot(xr[:-1]+dxr*0.5, np.zeros_like(xr[:-1]), 'ko')
plt.plot(xr[i]+dxr[i]*0.5, np.zeros(1), 'ro')
# for i in range(ntx):
if i < ntx-nmax+1:
txmid = xr[i]+dxr[i]*0.5
rxmid = xr[i+1:i+1+nmax]+dxr[i+1:i+1+nmax]*0.5
mid = (txmid+rxmid)*0.5
plt.plot(rxmid, np.zeros(rxmid.size), 'go')
plt.plot(mid, np.arange(nmax)+1., 'bo')
plt.plot(np.r_[txmid, mid[-1]], np.r_[0, nmax], 'k:')
for j in range(nmax):
plt.plot(np.r_[rxmid[j], mid[j]], np.r_[0, j+1], 'k:')
else:
txmid = xr[i]+dxr[i]*0.5
rxmid = xr[i+1:ntx+1]+dxr[i+1:ntx+1]*0.5
mid = (txmid+rxmid)*0.5
plt.plot((txmid+rxmid)*0.5, np.arange(mid.size)+1., 'bo')
plt.plot(rxmid, np.zeros(rxmid.size), 'go')
plt.plot(np.r_[txmid, mid[-1]], np.r_[0, mid.size], 'k:')
for j in range(ntx-i):
plt.plot(np.r_[rxmid[j], mid[j]], np.r_[0, j+1], 'k:')
plt.xlabel("X (m)")
plt.ylabel("N-spacing")
plt.xlim(xr.min(), xr.max())
plt.ylim(nmax+1, -1)
plt.show()
def _setup():
# The baseline images are created in this locale, so we should use
# it during all of the tests.
try:
locale.setlocale(locale.LC_ALL, str('en_US.UTF-8'))
except locale.Error:
try:
locale.setlocale(locale.LC_ALL, str('English_United States.1252'))
except locale.Error:
warnings.warn(
"Could not set locale to English/United States. "
"Some date-related tests may fail")
plt.switch_backend('Agg') # use Agg backend for these test
if mpl.get_backend().lower() != "agg":
msg = ("Using a wrong matplotlib backend ({0}), "
"which will not produce proper images")
raise Exception(msg.format(mpl.get_backend()))
# These settings *must* be hardcoded for running the comparison
# tests
mpl.rcdefaults() # Start with all defaults
mpl.rcParams['text.hinting'] = True
mpl.rcParams['text.antialiased'] = True
mpl.rcParams['text.hinting_factor'] = 8
# make sure we don't carry over bad plots from former tests
msg = ("no of open figs: {} -> find the last test with ' "
"python tests.py -v' and add a '@cleanup' decorator.")
assert len(plt.get_fignums()) == 0, msg.format(plt.get_fignums())
def __init__(self,aqc_info,BB_X,BB_Y):
self.acq_info = aqc_info
# Initial instructions
self.text_start = 'Press Spacebar to start recording'
self.text_stop = 'Press Spacebar to stop recording'
# remove toolbar
mpl.rcParams['toolbar'] = 'None'
# Create new figure and an axes which fills it...
# set figure width in inches
fig_width = 12
# set fig ratio based on size of bboard rectange whose corners are sensors
self.fig = plt.figure(figsize=(fig_width, fig_width*BB_Y/BB_X))
self.fig.canvas.set_window_title(aqc_name(self.acq_info))
# frameon determines whether background of frame will be drawn
ax = self.fig.add_axes([0, 0, 1, 1], frameon=False)
ax.set_xlim(-BB_X/2, BB_X/2), ax.set_xticks([])
ax.set_ylim(-BB_Y/2, BB_Y/2), ax.set_yticks([])
# create a scatter object at initial position 0,0
self.scat = ax.scatter(0, 0, s=200, lw=0.5, facecolors='green')
# create text box
self.text_h = ax.text(0.02, 0.98, self.text_start, verticalalignment='top',horizontalalignment='left',
transform=ax.transAxes, fontsize=12, bbox=dict(facecolor='white'), gid = 'notrec')
# create timer object
if self.acq_info['acq_time'] != 'inf':
acq_time_ms = int(self.acq_info['acq_time'])*1000
self.acq_timer = self.fig.canvas.new_timer(interval=acq_time_ms)
self.acq_timer.add_callback(self.t_event)
# attach keypress event handler to figure canvas
self.fig.canvas.mpl_connect('key_press_event', self.onkeypress)
def resetplot():
import matplotlib
import pylab as plt
kw = {}
for p in ['bottom', 'top', 'left', 'right', 'hspace', 'wspace']:
kw[p] = matplotlib.rcParams['figure.subplot.' + p]
plt.subplots_adjust(**kw)
def plot(self, linewidth=None, startarrows=True, endarrows=True):
"""Plots the field line and arrows."""
if linewidth == None:
linewidth = matplotlib.rcParams['lines.linewidth']
x, y = zip(*self.x)
pyplot.plot(x, y, '-k', linewidth=linewidth)
n = int(len(x)/2) if len(x) < 225 else 75
if startarrows:
pyplot.arrow(x[n], y[n], (x[n+1]-x[n])/100., (y[n+1]-y[n])/100.,
fc="k", ec="k",
head_width=0.1*linewidth, head_length=0.1*linewidth)
if len(x) < 225 or not endarrows:
return
pyplot.arrow(x[-n], y[-n],
(x[-n+1]-x[-n])/100., (y[-n+1]-y[-n])/100.,
fc="k", ec="k",
head_width=0.1*linewidth, head_length=0.1*linewidth)
def __init__(self):
mpl.rcParams['figure.figsize'] = (9.6, 7.2)
mpl.rcParams['lines.linewidth'] = 1.8 # line width in points
mpl.rcParams['lines.markeredgewidth'] = 0.3 # the line width around the marker symbol
mpl.rcParams['lines.markersize'] = 7 # markersize, in points
mpl.rcParams['grid.alpha'] = 0.5 # transparency, between 0.0 and 1.0
mpl.rcParams['grid.linestyle'] = '-' # simple line
mpl.rcParams['grid.linewidth'] = 0.4 # in points
def paper_plots_p4():
import matplotlib
matplotlib.rcParams['ps.useafm'] = True
matplotlib.rcParams['pdf.use14corefonts'] = True
matplotlib.rcParams['text.usetex'] = True
im_e, fmaps_e = testplot_p4(r=0)
im_r, fmaps_r = testplot_p4(r=1)
plot_p4(fmaps_e, fontsize=10, labelpad_factor_1=.3, labelpad_factor_2=.6, figsize=(1.6, 1.6))
plt.savefig('./p4_fmap_e_mini.eps', format='eps', dpi=600)
plot_p4(fmaps_r, fontsize=10, labelpad_factor_1=.3, labelpad_factor_2=.6, figsize=(1.6, 1.6))
plt.savefig('./p4_fmap_r_mini.eps', format='eps', dpi=600)
def plot_actions(cue=0):
mpl.rcParams['axes.labelsize'] = 'large'
d_map = {3:1, 8:2, 14:3, 23:4}
df = pd.read_pickle('data.pkl').reset_index()
df = df.loc[df['cue'] == cue]
g = sns.FacetGrid(df, col='subject',
col_wrap=6, size=1.5, ylim=(0, 5), aspect=1.5)
g.map(plt.plot, 'action')
g.set(xticks=[], yticks=[0,1,2,3], yticklabels=['3', '8', '14', '23'])
g.set(ylim=(-0.5, 4))
g.set_ylabels('choice')
g.fig.tight_layout()
g.fig.subplots_adjust(top=0.93)
subjects = df['subject'].unique()
for ax, subject in zip(g.axes, subjects):
df_subject = df.loc[df['subject'] == subject]
df_subject.reset_index(inplace=True)
df_wins = df_subject.loc[df_subject['reward'] > 0]
df_lose = df_subject.loc[df_subject['reward'] < 0]
pos_win = df_wins.loc[df_wins['subject'] == subject].index
pos_lose = df_lose.loc[df_lose['subject'] == subject].index
ax.eventplot(pos_win, lineoffsets=3.5, linelength=0.75,
linewidths=0.4)
ax.eventplot(pos_lose, lineoffsets=3.5, linelength=0.75,
color='r', linewidths=0.4)
plt.tight_layout()
plt.savefig('actions_0.pdf')
plt.show()
globals().update(locals())
def __init__(self, data_model, data_view, parent=None):
super(BaseVisualizer, self).__init__(parent=parent)
self._model = None
self._view = None
self.options = {}
self.set_data_source(data_model, data_view)
self.set_defaults()
self.setup_figure()
self.function = self.draw
mpl.rcParams["axes.formatter.useoffset"] = "False"
def get_color_cycle():
if mpl_ge_150:
cyl = mpl.rcParams['axes.prop_cycle']
# matplotlib 1.5 verifies that axes.prop_cycle *is* a cycler
# but no garuantee that there's a `color` key.
# so users could have a custom rcParmas w/ no color...
try:
return [x['color'] for x in cyl]
except KeyError:
pass # just return axes.color style below
return mpl.rcParams['axes.color_cycle']
def setup(context="notebook", style="ticks", palette="sweet",
font="sans-serif", font_scale=1, rc=None):
"""Set aesthetic figure parameters.
Each set of parameters can be set directly or temporarily, see the
referenced functions below for more information.
Parameters
----------
context : string or dict
Plotting context parameters, see :func:`plotting_context`
style : string or dict
Axes style parameters, see :func:`axes_style`
palette : string or sequence
Color palette, see :func:`color_palette`
font : string
Font family, see matplotlib font manager.
font_scale : float, optional
Separate scaling factor to independently scale the size of the
font elements.
rc : dict or None
Dictionary of rc parameter mappings to override the above.
"""
set_context(context, font_scale)
set_style(style, rc={"font.family": font})
set_palette(palette=palette)
if rc is not None:
mpl.rcParams.update(rc)
def reset_defaults():
"""Restore all RC params to default settings."""
mpl.rcParams.update(mpl.rcParamsDefault)
def reset_orig():
"""Restore all RC params to original settings (respects custom rc)."""
mpl.rcParams.update(_orig_rc_params)
def set_context(context=None, font_scale=1, rc=None):
"""Set the plotting context parameters.
This affects things like the size of the labels, lines, and other
elements of the plot, but not the overall style. The base context
is "notebook", and the other contexts are "paper", "talk", and "poster",
which are version of the notebook parameters scaled by .8, 1.3, and 1.6,
respectively.
Parameters
----------
context : dict, None, or one of {paper, notebook, talk, poster}
A dictionary of parameters or the name of a preconfigured set.
font_scale : float, optional
Separate scaling factor to independently scale the size of the
font elements.
rc : dict, optional
Parameter mappings to override the values in the preset seaborn
context dictionaries. This only updates parameters that are
considered part of the context definition.
Examples
--------
>>> set_context("paper")
>>> set_context("talk", font_scale=1.4)
>>> set_context("talk", rc={"lines.linewidth": 2})
See Also
--------
plotting_context : return a dictionary of rc parameters, or use in
a ``with`` statement to temporarily set the context.
set_style : set the default parameters for figure style
set_palette : set the default color palette for figures
"""
context_object = plotting_context(context, font_scale, rc)
mpl.rcParams.update(context_object)
def __enter__(self):
rc = mpl.rcParams
self._orig = {k: rc[k] for k in self._keys}
self._set(self)
def set_palette(palette, n_colors=None, desat=None):
"""Set the matplotlib color cycle using a seaborn palette.
Parameters
----------
palette : hls | husl | matplotlib colormap | seaborn color palette
Palette definition. Should be something that :func:`color_palette`
can process.
n_colors : int
Number of colors in the cycle. The default number of colors will depend
on the format of ``palette``, see the :func:`color_palette`
documentation for more information.
desat : float
Proportion to desaturate each color by.
Examples
--------
>>> set_palette("Reds")
>>> set_palette("Set1", 8, .75)
See Also
--------
color_palette : build a color palette or set the color cycle temporarily
in a ``with`` statement.
set_context : set parameters to scale plot elements
set_style : set the default parameters for figure style
"""
colors = palettes.color_palette(palette, n_colors, desat)
if mpl_ge_150:
from cycler import cycler
cyl = cycler('color', colors)
mpl.rcParams['axes.prop_cycle'] = cyl
else:
mpl.rcParams["axes.color_cycle"] = list(colors)
mpl.rcParams["patch.facecolor"] = colors[0]
def plot_results(self, plot_path=None, ylim=None):
# Plotting parameters
label_size = 18
mpl.rcParams['xtick.labelsize'] = label_size
mpl.rcParams['ytick.labelsize'] = label_size
plot_params = dict()
plot_params['ms'] = 10
plot_params['linewidth'] = 3
# Plot training bound on the perplexity
f = plt.figure(figsize=[12, 12])
plt.errorbar(self.epochs_eval, [self.lower_bound_train_all[i] for i in self.epochs_eval],
[self.lower_bound_train_all_std[i] for i in self.epochs_eval], marker='d', color='b',
label='Train', **plot_params)
plt.plot(self.epochs_eval, self.lower_bound_valid_all, "-rh", label="Valid", **plot_params)
plt.plot(self.epochs_eval, self.lower_bound_test_all, "-k^", label="Test", **plot_params)
plt.xlabel('Epochs', fontsize=20)
plt.grid('on')
plt.title('ELBO', fontsize=24, y=1.01)
plt.legend(loc="lower right", handlelength=3, fontsize=20)
if ylim is not None:
plt.ylim(ylim)
if plot_path is not None:
plt.savefig(plot_path + "_epochs.png", format='png', bbox_inches='tight', dpi=200)
plt.close(f)
# Plot norm of the updates
f = plt.figure(figsize=[12, 12])
plt.errorbar(self.epochs_eval, [self.mean_norm_all[i] for i in self.epochs_eval],
[self.std_norm_all[i] for i in self.epochs_eval], marker='d', color='m', **plot_params)
plt.grid('on')
plt.title('Norm of the updates', fontsize=24, y=1.01)
if plot_path is not None:
plt.savefig(plot_path + "_norm.png", format='png', bbox_inches='tight', dpi=200)
plt.close(f)
def plot_results(self, plot_path=None, ylim=None):
# Plotting parameters
label_size = 18
mpl.rcParams['xtick.labelsize'] = label_size
mpl.rcParams['ytick.labelsize'] = label_size
plot_params = dict()
plot_params['ms'] = 10
plot_params['linewidth'] = 3
# Plot training bound on the perplexity
f = plt.figure(figsize=[12, 12])
plt.errorbar(self.epochs_eval, [self.elbo_seq_train_all[i] for i in self.epochs_eval],
[self.elbo_seq_train_all_std[i] for i in self.epochs_eval], marker='d', color='b',
label='Train', **plot_params)
plt.plot(self.epochs_eval, self.elbo_seq_valid_all, "-rh", label="Valid", **plot_params)
plt.plot(self.epochs_eval, self.elbo_seq_test_all, "-k^", label="Test", **plot_params)
plt.xlabel('Epochs', fontsize=20)
# plt.ylabel('log()', fontsize=20)
plt.grid('on')
plt.title('ELBO sequence', fontsize=24, y=1.01)
plt.legend(loc="upper right", handlelength=3, fontsize=20)
if ylim is not None:
plt.ylim(ylim)
if plot_path is not None:
plt.savefig(plot_path + "_epochs.png", format='png', bbox_inches='tight', dpi=200)
plt.close(f)
# Plot norm of the updates
f = plt.figure(figsize=[12, 12])
plt.errorbar(self.epochs_eval, [self.mean_norm_all[i] for i in self.epochs_eval],
[self.std_norm_all[i] for i in self.epochs_eval], marker='d', color='m', **plot_params)
plt.grid('on')
plt.title('Norm of the updates', fontsize=24, y=1.01)
if plot_path is not None:
plt.savefig(plot_path + "_norm.png", format='png', bbox_inches='tight', dpi=200)
plt.close(f)