本文整理汇总了Python中GeneralUtil.python.PlotUtilities.legend方法的典型用法代码示例。如果您正苦于以下问题:Python PlotUtilities.legend方法的具体用法?Python PlotUtilities.legend怎么用?Python PlotUtilities.legend使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类GeneralUtil.python.PlotUtilities
的用法示例。
在下文中一共展示了PlotUtilities.legend方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: FEC_AlreadySplit
# 需要导入模块: from GeneralUtil.python import PlotUtilities [as 别名]
# 或者: from GeneralUtil.python.PlotUtilities import legend [as 别名]
def FEC_AlreadySplit(Appr,Retr,
XLabel = "Separation (nm)",
YLabel = "Force (pN)",
ConversionOpts=def_conversion_opts,
PlotLabelOpts=dict(),
PreProcess=False,
NFilterPoints=50,
LegendOpts=dict(loc='best'),
**kwargs):
"""
Args:
XLabel: label for x axis
YLabel: label for y axis
ConversionOpts: see FEC_Util.SplitAndProcess
PlotLabelOpts: see arguments after filtering of ApproachRetractCurve
PreProcess: if true, pre-processes the approach and retract separately
(ie: to zero and flip the y axis).
NFilterPoints: see FEC_Util.SplitAndProcess, for Savitsky-golay
PreProcess: passed to
"""
ApprCopy = FEC_Util.UnitConvert(Appr,**ConversionOpts)
RetrCopy = FEC_Util.UnitConvert(Retr,**ConversionOpts)
if (PreProcess):
ApprCopy,RetrCopy = FEC_Util.PreProcessApproachAndRetract(ApprCopy,
RetrCopy,
**kwargs)
_ApproachRetractCurve(ApprCopy,RetrCopy,
NFilterPoints=NFilterPoints,**PlotLabelOpts)
PlotUtilities.lazyLabel(XLabel,YLabel,"")
PlotUtilities.legend(**LegendOpts)
示例2: run
# 需要导入模块: from GeneralUtil.python import PlotUtilities [as 别名]
# 或者: from GeneralUtil.python.PlotUtilities import legend [as 别名]
def run(base="./"):
"""
"""
out_base = base
data_base = base + "data/"
data_file = "../FigurePerformance_CS/data/Scores.pkl"
force=False
cache_file = base + "cache.pkl"
fec_file = data_base + "multiple.csv.pkl"
name = "FEATHER"
final_out_hist = "{:s}{:s}_distances.pdf".format(out_base,
name.replace(" ","_"))
l = CheckpointUtilities.getCheckpoint(cache_file,get_feather_run,force,
data_file)
# make the distance histogram figure for the presenation
fig = PlotUtilities.figure((10,5))
make_distance_figure(l,data_file,fec_file)
PlotUtilities.legend(loc='upper right')
PlotUtilities.savefig(fig,final_out_hist.replace(".pdf","_pres.pdf"))
# make the distance histogram figure
fig = PlotUtilities.figure((16,6))
make_distance_figure(l,data_file,fec_file)
PlotUtilities.legend(loc='upper right')
PlotUtilities.label_tom(fig,loc=(-0.1,1.0),fontsize=18)
PlotUtilities.savefig(fig,final_out_hist)
示例3: TomPlot
# 需要导入模块: from GeneralUtil.python import PlotUtilities [as 别名]
# 或者: from GeneralUtil.python.PlotUtilities import legend [as 别名]
def TomPlot(LandscapeObj,OutBase,UnfoldObj,RefoldObj,idx,f_one_half_N=0e-12):
# get a forward and reverse
ToX = lambda x: x * 1e9
ToForceY = lambda y: y * 1e12
fig = PlotUtilities.figure(figsize=(8,4))
plt.subplot(1,2,1)
SubplotArgs = dict(alpha=0.4,linewidth=0.5)
FilterN = 500
Unfold = FEC_Util.GetFilteredForce(UnfoldObj[idx],FilterN)
Refold = FEC_Util.GetFilteredForce(RefoldObj[idx],FilterN)
UnfoldX = ToX(Unfold.Extension)
UnfoldY = ToForceY(Unfold.Force)
FoldX = ToX(Refold.Extension)
FoldY = ToForceY(Refold.Force)
plt.plot(UnfoldX,UnfoldY,color='r',label="Unfolding",
**SubplotArgs)
plt.plot(FoldX,FoldY,color='b',label="Refolding",
**SubplotArgs)
fontdict = dict(fontsize=13)
x_text_dict = dict(x=60, y=22.5, s="2 nm", fontdict=fontdict,
withdash=False,
rotation="horizontal")
y_text_dict = dict(x=59, y=27, s="5 pN", fontdict=fontdict, withdash=False,
rotation="vertical")
PlotUtilities.ScaleBar(x_kwargs=dict(x=[60,62],y=[24,24]),
y_kwargs=dict(x=[60,60],y=[25,30]),
text_x=x_text_dict,text_y=y_text_dict)
PlotUtilities.legend(loc=[0.4,0.8],**fontdict)
plt.subplot(1,2,2)
Obj = IWT_Util.TiltedLandscape(LandscapeObj,f_one_half_N=f_one_half_N)
plt.plot(Obj.landscape_ext_nm,Obj.OffsetTilted_kT)
plt.xlim([56,69])
plt.ylim([-1,4])
yoffset = 1
x_text_dict = dict(x=58.5, y=yoffset+1.5, s="2 nm", fontdict=fontdict,
withdash=False,rotation="horizontal")
y_text_dict = dict(x=57, y=yoffset+2.5, s=r"1 k$_\mathrm{b}$T",
fontdict=fontdict, withdash=False,
rotation="vertical")
PlotUtilities.ScaleBar(x_kwargs=dict(x=[58,60],
y=[yoffset+1.75,yoffset+1.75]),
y_kwargs=dict(x=[58,58],y=[yoffset+2,yoffset+3]),
text_x=x_text_dict,text_y=y_text_dict,
kill_axis=True)
PlotUtilities.savefig(fig,OutBase + "TomMockup" + str(idx) + ".png",
subplots_adjust=dict(bottom=-0.1))
# save out the data exactly as we want to plot it
common = dict(delimiter=",")
ext = str(idx) + ".txt"
np.savetxt(X=np.c_[UnfoldX,UnfoldY],fname=OutBase+"Unfold" + ext,**common)
np.savetxt(X=np.c_[FoldX,FoldY],fname=OutBase+"Fold"+ext,**common)
np.savetxt(X=np.c_[Obj.landscape_ext_nm,Obj.OffsetTilted_kT],
fname=OutBase+"Landscape"+ext,**common)
示例4: run
# 需要导入模块: from GeneralUtil.python import PlotUtilities [as 别名]
# 或者: from GeneralUtil.python.PlotUtilities import legend [as 别名]
def run():
"""
<Description>
Args:
param1: This is the first param.
Returns:
This is a description of what is returned.
"""
n_samples = int(1e4)
sigma = 1
loc_arr = [-3,-1,0.5]
n_bins = 50
ylim = [0,0.6]
n_cols = 3+1
xlim = [-12,12]
bins = np.linspace(*xlim,endpoint=True,num=n_bins)
fig = PlotUtilities.figure((12,7))
plt.subplot(1,n_cols,1)
bhattacharya,x1,x2 = plot_bhattacharya(sigma,n_samples,bins=bins,
loc=-9)
plt.xlim(xlim)
PlotUtilities.tickAxisFont()
PlotUtilities.xlabel("Distribution Value")
PlotUtilities.ylabel("Probability")
PlotUtilities.legend(frameon=False)
plt.ylim(ylim)
title = p_label(bhattacharya,x1,x2)
PlotUtilities.title(title)
for i,loc in enumerate(loc_arr):
plt.subplot(1,n_cols,(i+2))
bhattacharya,x1,x2 = plot_bhattacharya(sigma,n_samples,bins,
loc=loc)
title = p_label(bhattacharya,x1,x2)
PlotUtilities.title(title)
plt.xlim(xlim)
plt.ylim(ylim)
PlotUtilities.tickAxisFont()
PlotUtilities.no_y_label()
PlotUtilities.legend(frameon=False)
PlotUtilities.xlabel("")
PlotUtilities.savefig(fig,"bcc.pdf",subplots_adjust=dict(wspace=0.1))
示例5: _main_figure
# 需要导入模块: from GeneralUtil.python import PlotUtilities [as 别名]
# 或者: from GeneralUtil.python.PlotUtilities import legend [as 别名]
def _main_figure(trials):
xlim = [500,1e6]
ylim=[1e-2,5e2]
style_data,style_pred = style_data_and_pred()
colors = algorithm_colors()
# picturing 3x2, where we show the 'in the weeds' plots...
plt.subplot(1,2,1)
for i,learner_trials in enumerate(trials):
TimePlot.\
plot_learner_slope_versus_loading_rate(learner_trials,
style_data=style_data[i],
style_pred=style_pred[i])
PlotUtilities.legend(loc="upper left",frameon=False)
PlotUtilities.title("")
plt.xlim(xlim)
plt.ylim(ylim)
plt.subplot(1,2,2)
TimePlot.plot_learner_prediction_time_comparison(trials,color=colors)
plt.ylim([1e3,3e6])
PlotUtilities.legend(loc="lower right",frameon=False)
PlotUtilities.title("")
示例6: run
# 需要导入模块: from GeneralUtil.python import PlotUtilities [as 别名]
# 或者: from GeneralUtil.python.PlotUtilities import legend [as 别名]
def run():
"""
<Description>
Args:
param1: This is the first param.
Returns:
This is a description of what is returned.
"""
learners = Learners.get_learners()
positives_directory = InputOutput.get_positives_directory()
positive_categories = InputOutput.\
get_categories(positives_directory=positives_directory,
use_simulated=True)
curve_numbers = [1,2,5,10,30,50,100,150,200]
cache_data_dir = "../_1ReadDataToCache/cache/"
cache_dir = "./cache/"
GenUtilities.ensureDirExists(cache_dir)
force = False
times = CheckpointUtilities.getCheckpoint(cache_dir + "all_timer.pkl",
cache_all_learners,force,
learners,positive_categories,
curve_numbers,
cache_data_dir,cache_dir,force)
out_base = "./out/"
GenUtilities.ensureDirExists(out_base)
# sort the times by their loading rates
max_time = max([l.max_time_trial() for l in times])
min_time = min([l.min_time_trial() for l in times])
# plot the Theta(n) coefficient for each
fig = PlotUtilities.figure()
TimePlot.plot_learner_prediction_time_comparison(times)
PlotUtilities.legend(loc="lower right",frameon=True)
PlotUtilities.savefig(fig,out_base + "compare.png")
for learner_trials in times:
base_name = out_base + learner_trials.learner.description
# plot the timing veruses loading rate and number of points
fig = PlotUtilities.figure()
TimePlot.plot_learner_versus_loading_rate_and_number(learner_trials)
fudge_x_low = 10
fudge_x_high = 2
fudge_y = 1.5
plt.ylim([min_time/fudge_y,max_time*fudge_y])
plt.xlim([1/fudge_x_low,max(curve_numbers)*fudge_x_high])
plt.yscale('log')
plt.xscale('log')
PlotUtilities.legend(loc="upper left",frameon=True)
PlotUtilities.savefig(fig, base_name + "_all_trials.png")
# plot the slopes
fig = PlotUtilities.figure()
TimePlot.plot_learner_slope_versus_loading_rate(learner_trials)
PlotUtilities.legend(loc="lower right",frameon=True)
PlotUtilities.savefig(fig, base_name + "_slopes.png")
示例7: run
# 需要导入模块: from GeneralUtil.python import PlotUtilities [as 别名]
# 或者: from GeneralUtil.python.PlotUtilities import legend [as 别名]
def run():
"""
Creates a graph of looping rate versus time for our fret data
"""
# write down the numerator (number in high fret) and denominator
# (total number) for the third sample, which was digested after
# 1 minute in looping buffer
Numer3 = [19,185,282,261,340,315,301,276,290,245]
Denom3 = [642,473,538,428,450,424,381,365,371,303]
off = 3
Times3 = [0,off+0,off+4,off+8,off+17,off+23,off+31,off+35,off+44,off+53]
# ibid, example fourth sample, which was 90 minutes
Numer4 = [21,175,349,435,470,495,552,536,504,524,455]
Denom4 = [922,811,906,869,809,728,757,696,663,674,639]
offFour = off
Times4 = [0,offFour+0,offFour+3,offFour+8,offFour+11,offFour+20,
offFour+25,offFour+33,offFour+37,offFour+47,offFour+59]
# Followsing times and data taken by Group B on single species DNA
RatiosMisMatch = [0,0.110000000000000,0.250000000000000,0.330000000000000,
0.430000000000000,0.440000000000000,0.450000000000000,
0.500000000000000,0.480000000000000,0.450000000000000]
TimesMisMatch = [0,1,2,6,7,11,13,18,27,33]
# get the population ratio
Ratio3 = np.array(Numer3)/np.array(Denom3)
Ratio4 = np.array(Numer4)/np.array(Denom4)
# fit the exponential 'decays'
MaxTau = 10
MinTau = 1
ThreeX,ThreeY,ThreeParams,ThreeStd = GetExponentialFit(MinTau,MaxTau,
Times3,Ratio3)
FourX,FourY,FourParams,FourStd = GetExponentialFit(MinTau,MaxTau,
Times4,Ratio4)
# get the decays for the Mismatch
MisX,MisY,MisParams,MisStd = GetExponentialFit(MinTau,MaxTau,
TimesMisMatch,RatiosMisMatch)
# make our figure
fig = pPlotUtil.figure()
LabelFunc = lambda descr,params : descr + "\n" + \
r'$\tau$ =' + '{:.1f} min'.format(params[0]) +"\n" +\
'f$_{saturated}$' + '={:.2f}'.format(params[1])
LabelThree = LabelFunc("1 minute looping",ThreeParams)
LabelFour = LabelFunc("90 minute looping",FourParams)
LegendLoc = "lower right"
XLabel = "Time (minutes)"
YLabel = "Population fraction in high fret"
LazyOpts = dict(frameon=True,loc=LegendLoc)
pPlotUtil.lazyLabel(XLabel,YLabel,
"Lower pre-digestion looping time sample circularizes faster",
**LazyOpts)
# add the y limits before saving, to allow for space for the legend
MaxT = max(np.max(Times3),np.max(Times4))*1.1
MaxY = 1.05
Limits = lambda: plt.ylim([-0.1,MaxY]) and plt.xlim([-1,MaxT])
plt.plot(Times3,Ratio3,'ro',label=LabelThree)
plt.plot(ThreeX,ThreeY,'r-',linewidth=2)
Limits()
pPlotUtil.LegendAndSave(fig,"Out1.png",loc=LegendLoc)
plt.plot(Times4,Ratio4,'bs',label=LabelFour)
plt.plot(FourX,FourY,'b--',linewidth=2)
Limits()
pPlotUtil.LegendAndSave(fig,"Out2.png",loc=LegendLoc)
# add in the mismatch
plt.plot(TimesMisMatch,RatiosMisMatch,'go',label=LabelFunc("Single Species",
MisParams))
plt.plot(MisX,MisY,'g-.')
Limits()
pPlotUtil.legend(frameon=True,loc=LegendLoc)
pPlotUtil.savefig(fig,"Out3.png")
# make the mismatch graph
fig = pPlotUtil.figure()
plt.plot(TimesMisMatch,RatiosMisMatch,'go',label=LabelFunc("Single Species",
MisParams))
plt.plot(MisX,MisY,'g-.')
pPlotUtil.lazyLabel(XLabel,YLabel,
"Single fast-folding species",**LazyOpts)
Limits()
pPlotUtil.savefig(fig,"Out4_MisMatch.png")
示例8: LegendAndSave
# 需要导入模块: from GeneralUtil.python import PlotUtilities [as 别名]
# 或者: from GeneralUtil.python.PlotUtilities import legend [as 别名]
def LegendAndSave(Fig,SaveName,LegendLoc="upper right"):
pPlotUtil.legend(loc=LegendLoc,frameon=True)
pPlotUtil.savefig(Fig,SaveName,close=False)
示例9: make_metric_plot
# 需要导入模块: from GeneralUtil.python import PlotUtilities [as 别名]
# 或者: from GeneralUtil.python.PlotUtilities import legend [as 别名]
def make_metric_plot(metrics,
xlim_dist=[1e-5,2],
xlim_load=[1e-2,1e5],
xlim_rupture=[-120,320]):
colors = Plotting.algorithm_colors()
n_rows = 3
n_cols = 3
legend_locs = ['upper right','upper left','upper left']
titles = ["FEATHER","Fovea","Wavelet"]
legend_loading = [None,None,None]
legend_kwargs_style = dict(fontsize=8,handlelength=0.75,handletextpad=0.25)
for i,m in enumerate(metrics):
offset = n_rows * i
# the first column gets the algorithm label; the first row gets the
# metric label
kw_tmp = dict(title_kwargs=dict(fontweight='bold',color='b',fontsize=9),
legend_kwargs=legend_kwargs_style)
if offset == 0:
title_dist = "Location error"
title_load = r"Loading rate (NuG2 + $\mathbf{\alpha_3}$D)"
title_rupture_force = r"Rupture force (NuG2 + $\mathbf{\alpha_3}$D)"
else:
title_dist,title_load,title_rupture_force = "","",""
# only have an x label on the last row
last_row = (offset/n_rows == n_rows-1)
if (last_row):
xlabel_dist = "Relative Error ($\mathbf{x_k}$)"
xlabel_load = "Loading Rate (pN/s)"
xlabel_rupture_force = \
PlotUtilities.variable_string("F_R")
else:
xlabel_dist, xlabel_load,xlabel_rupture_force = "","",""
n_string = r"N_{\mathrm{" + "{:s}".format(titles[i]) + "}}"
ylabel_dist = PlotUtilities.variable_string(n_string)
color_pred=colors[i]
color_true = 'g'
# get the formatting dictionaries for the various plots
distance_histogram_kw= \
Plotting.event_error_kwargs(m,color_pred=color_pred,
label_bool=False)
true_style_histogram = Plotting.\
_histogram_true_style(color_true=color_true,label="true")
pred_style_histogram = Plotting.\
_histogram_predicted_style(color_pred=color_pred,label="predicted")
# get the binning for the rupture force and loading rates
true,pred = m.true,m.pred
ruptures_true,loading_true = \
Learning.get_rupture_in_pN_and_loading_in_pN_per_s(true)
ruptures_pred,loading_pred = \
Learning.get_rupture_in_pN_and_loading_in_pN_per_s(pred)
_lim_force_plot,_bins_rupture_plot,_lim_load_plot,_bins_load_plot = \
Learning.limits_and_bins_force_and_load(ruptures_pred,ruptures_true,
loading_true,loading_pred,
limit=False)
# # make the 'just the distance' figures
ax_dist = plt.subplot(n_rows,n_cols,(offset+1))
Plotting.histogram_event_distribution(use_q_number=True,
**distance_histogram_kw)
PlotUtilities.lazyLabel(xlabel_dist,ylabel_dist,title_dist,
loc=legend_locs[i],legendBgColor='w',
frameon=False,**kw_tmp)
PlotUtilities.ylabel(ylabel_dist,fontweight='bold')
plt.xlim(xlim_dist)
if not last_row:
PlotUtilities.no_x_label(ax_dist)
tick_style_log()
# # make the loading rate histogram
ax_load = plt.subplot(n_rows,n_cols,(offset+2))
Plotting.loading_rate_histogram(pred,bins=_bins_load_plot,
**pred_style_histogram)
Plotting.loading_rate_histogram(true,bins=_bins_load_plot,
**true_style_histogram)
plt.xscale('log')
plt.yscale('log')
PlotUtilities.lazyLabel(xlabel_load,"",title_load,
legendBgColor='w',
loc='upper left',frameon=False,**kw_tmp)
plt.xlim(xlim_load)
if not last_row:
PlotUtilities.no_x_label(ax_load)
# get the locations
if legend_loading[i] is not None:
PlotUtilities.legend(loc=(legend_loading[i]),**legend_kwargs_style)
PlotUtilities.no_y_label(ax_load)
tick_style_log()
# # make the rupture force histogram
ax_rupture = plt.subplot(n_rows,n_cols,(offset+3))
Plotting.rupture_force_histogram(pred,bins=_bins_rupture_plot,
**pred_style_histogram)
Plotting.rupture_force_histogram(true,bins=_bins_rupture_plot,
**true_style_histogram)
PlotUtilities.lazyLabel(xlabel_rupture_force,"",title_rupture_force,
useLegend=False,**kw_tmp)
plt.xlim(xlim_rupture)
plt.yscale('log')
if not last_row:
PlotUtilities.no_x_label(ax_rupture)
PlotUtilities.no_y_label(ax_rupture)
tick_style_log(change_x=False)
# set all the y limits for this row
#.........这里部分代码省略.........
示例10: make_pedagogical_plot
# 需要导入模块: from GeneralUtil.python import PlotUtilities [as 别名]
# 或者: from GeneralUtil.python.PlotUtilities import legend [as 别名]
def make_pedagogical_plot(data_to_plot,kw,out_name="./iwt_diagram"):
heatmap_data = data_to_plot.heatmap_data
data = landscape_data(data_to_plot.landscape)
fig = PlotUtilities.figure((3.25,5))
# # ploy the heat map
ax_heat = plt.subplot(3,1,1)
heatmap_plot(heatmap_data,data.amino_acids_per_nm(),
kw_heatmap=kw['kw_heatmap'])
xlim_fec = plt.xlim()
PlotUtilities.no_x_label(ax_heat)
ax_heat.set_ylim([0,150])
PlotUtilities.no_x_label(ax_heat)
PlotUtilities.no_y_label(ax_heat)
fontsize_scalebar = 6
common_kw = dict(color='w',fontsize=fontsize_scalebar)
x_font,y_font = Scalebar.\
font_kwargs_modified(x_kwargs=common_kw,
y_kwargs=common_kw)
heat_kw_common = dict(line_kwargs=dict(color='w',linewidth=1.5))
x_heat_kw = dict(width=15,unit="nm",font_kwargs=x_font,**heat_kw_common)
y_heat_kw = dict(height=30,unit='pN ',font_kwargs=y_font,**heat_kw_common)
# add a scale bar for the heatmap...
scale_bar_x = 0.83
Scalebar.crossed_x_and_y_relative(scale_bar_x,0.55,ax=ax_heat,
x_kwargs=x_heat_kw,
y_kwargs=y_heat_kw)
jcp_fig_util.add_helical_boxes(ax=ax_heat,ymax_box=0.9,alpha=1.0,
font_color='w',offset_bool=True)
# # plot the energy landscape...
ax_correction = plt.subplot(3,1,2)
plot_with_corrections(data)
PlotUtilities.no_x_label(ax_correction)
PlotUtilities.lazyLabel("","Energy (kcal/mol)","")
ax_correction.set_xlim(xlim_fec)
offset_y_pedagogy = 0.42
setup_pedagogy_ticks(ax_correction,scale_bar_x,x_heat_kw,y_heat_kw,
offset_y=offset_y_pedagogy)
legend_font_size = 9
legend = PlotUtilities.legend(handlelength=1.5,loc=(0.15,0.07),ncol=3,
fontsize=legend_font_size,handletextpad=0.4)
for i,text in enumerate(legend.get_texts()):
plt.setp(text, color = kwargs_correction()[i]['color'])
# make the inset plot
axins = zoomed_inset_axes(ax_correction, zoom=3, loc=2,
borderpad=0.8)
plot_with_corrections(data)
xlim_box = [1,5]
ylim_box = [-3,28]
plt.xlim(xlim_box)
plt.ylim(ylim_box)
PlotUtilities.no_x_anything(axins)
PlotUtilities.no_y_anything(axins)
# add in scale bars
kw_common = dict(line_kwargs=dict(linewidth=0.75,color='k'))
common_font_inset = dict(fontsize=fontsize_scalebar)
x_kwargs = dict(verticalalignment='top',**common_font_inset)
x_font,y_font = Scalebar.\
font_kwargs_modified(x_kwargs=x_kwargs,
y_kwargs=dict(horizontalalignment='right',
**common_font_inset))
# set up the font, offset ('fudge') the text from the lines
fudge_x = dict(x=0,y=-0.5)
fudge_y = dict(x=0,y=0.1)
Scalebar.crossed_x_and_y_relative(0.55,0.66,ax=axins,
x_kwargs=dict(width=2,unit="nm",
font_kwargs=x_font,
fudge_text_pct=fudge_x,
**kw_common),
y_kwargs=dict(height=8,unit='kcal/\nmol',
font_kwargs=y_font,
fudge_text_pct=fudge_y,
**kw_common))
# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
color_box = 'rebeccapurple'
PlotUtilities.color_frame('rebeccapurple',ax=axins)
Annotations.add_rectangle(ax_correction,xlim_box,ylim_box,edgecolor=color_box)
ax_correction.set_xlim(xlim_fec)
ax_energy = plt.subplot(3,1,3)
plot_landscape(data,xlim_fec,kw_landscape=kw['kw_landscape'],
plot_derivative=False,label_deltaG=" ")
ax_energy.set_xlim(xlim_fec)
setup_pedagogy_ticks(ax_energy,scale_bar_x,x_heat_kw,y_heat_kw,
offset_y=offset_y_pedagogy)
# add in the equation notation
strings,colors = [],[]
labels = kwargs_labels()
# add in the appropriate symbols
strings = ["$\Delta G$ = ",labels[0]," + ",labels[1]," - ",labels[2]]
colors_labels = [c['color'] for c in kwargs_correction()]
colors = ["k"] + [item for list in [[c,"k"] for c in colors_labels]
for item in list]
x,y = Scalebar.x_and_y_to_abs(x_rel=0.08,y_rel=0.85,ax=ax_energy)
Annotations.rainbow_text(x,y,strings=strings,colors=colors,
ax=ax_energy,size=legend_font_size)
PlotUtilities.legend(handlelength=0.5,loc=(0.03,0.8))
PlotUtilities.no_x_label(ax_energy)
PlotUtilities.save_png_and_svg(fig,out_name)
示例11: PlotFits
# 需要导入模块: from GeneralUtil.python import PlotUtilities [as 别名]
# 或者: from GeneralUtil.python.PlotUtilities import legend [as 别名]
def PlotFits(Corrected,ListOfSepAndFits,TransitionForces,ExpectedContourLength,
OutDir):
"""
Plots the WLC fits into ./Out/
Args:
Corrected: list of tuples, each of which is an approach/corrected
TimeSepForce Object
ListOfSepAndFits: see output of GetWLCFits
TransitionForces: see output of GetTransitionForces
ExpectedContourLength: expected contour length, in meters
OutDir: base directory for output
"""
# get all of the transition forces
ExpectedContourLengthNm = ExpectedContourLength * 1e9
# POST: have everything corrected, fit...
MaxX = ExpectedContourLengthNm*3
set_y_lim = lambda : plt.ylim([-50,170])
set_x_lim = lambda : plt.xlim([-10,MaxX])
LegendOpts = dict(loc='upper right',frameon=True)
# note: we want to pre-process (convert to sensible units etc) but no
# need to correct (ie: flip and such)
FilterSpatialResolution = 0.5e-9
for i,(ApproachCorrected,RetractCorrected) in enumerate(Corrected):
SepNear,FitObj = ListOfSepAndFits[i]
# get the number of filter points needed for whatever spatial resolution
# we want
NFilterPoints = 10
PlotOptions = dict(LegendOpts=LegendOpts,
NFilterPoints=NFilterPoints)
# get the WLC prediction for the region we fit
SepPred = np.linspace(0,max(SepNear),num=50)
WLC_Pred = FitObj.Predict(SepPred)
# convert to plotting units
ToYUnits = lambda y : y*1e12
ToXUnits = lambda x: x*1e9
WLC_Force_pN = ToYUnits(WLC_Pred)
WLC_Separation_nm = ToXUnits(SepPred)
# Get the fit parameters
L0,Lp,_,_ = FitObj.Params()
fig = pPlotUtil.figure()
SaveNameIncremental = lambda j : \
"{:s}Out/FEC{:d}_{:d}.png".format(OutDir,i,j)
FEC_Plot.FEC_AlreadySplit(ApproachCorrected,RetractCorrected,
**PlotOptions)
set_y_lim()
set_x_lim()
pPlotUtil.LegendAndSave(fig,SaveNameIncremental(0),**LegendOpts)
plt.plot(WLC_Separation_nm,
WLC_Force_pN,linewidth=1.5,color='g',linestyle='-',
label="WLC: L0={:4.1f}nm".format(L0*1e9))
pPlotUtil.LegendAndSave(fig,SaveNameIncremental(1),**LegendOpts)
ContourLengthLabel = r"""L$_0$={:4.1f}nm""".\
format(ExpectedContourLengthNm)
plt.axvline(ExpectedContourLengthNm,label=ContourLengthLabel,
linewidth=5.0,color='g',linestyle='--')
plt.axhline(65,label=r'F$_{\rm Overstretch}$=65pN',
linewidth=5.0,color='k',linestyle='-')
plt.axhline(ToYUnits(np.median(TransitionForces[i])),linestyle='--')
pPlotUtil.legend(**LegendOpts)
pPlotUtil.savefig(fig,SaveNameIncremental(2),**LegendOpts)
plt.close(fig)
示例12: run
# 需要导入模块: from GeneralUtil.python import PlotUtilities [as 别名]
# 或者: from GeneralUtil.python.PlotUtilities import legend [as 别名]
def run():
"""
<Description>
Args:
param1: This is the first param.
Returns:
This is a description of what is returned.
"""
base_data_dir = FEC_Util.default_data_root()
directory = base_data_dir + "4Patrick/CuratedData/DNA/Hairpin-68nt/" + \
"2017-2-17-velocity-assay-single-attachments-no-adhesion" + \
"-1000nm-s-needs-to-be-redone/"
out_dir = "./out/"
force = False
files,force_extension_curves = \
FEC_Util.read_and_cache_pxp(directory,force=force)
force_extension_curves = [f for f in force_extension_curves]
# split everything
curves_split= \
[Analysis.split_FEC_by_meta(f) for f in force_extension_curves]
# zero everything (of curves split, by reference)
n_filter= lambda f: int(f.retract.Force.size*0.01)
kwargs = dict(zero_separation_at_zero_force=True)
[FEC_Util.zero_split_fec_approach_and_retract(f,NFilterPoints=n_filter(f),
**kwargs)
for f in curves_split]
# get just the retracts
curves_retract = [ fec.retract for fec in curves_split]
curves_approach = [ fec.approach for fec in curves_split]
# XXX debugging...
ex = curves_retract[2]
surface_idx = 1300
max_idx = np.argmax(ex.Force)
zeroed_force = ex.Force[surface_idx:max_idx]
zeroed_separation = ex.Separation[surface_idx:max_idx]
# ranges are for L0...
max_sep = max(zeroed_separation)
range_L0 = slice(0,max_sep,max_sep/50)
brute_dict = dict(ranges=[range_L0])
fjc_kwargs = dict(Lp=2.22e-9,kbT=4.1e-21,K0=1200e-12)
ret,model_x,model_y = fit_fjc_contour(zeroed_separation,zeroed_force,
brute_dict=brute_dict,**fjc_kwargs)
print(ret)
plt.plot(zeroed_separation,zeroed_force)
plt.plot(model_x,model_y)
plt.show()
exit(1)
# plot as a 2-d histogram
# filter to 1% of the size of the signal (should be loading-rate proof)
histogram_filter_func = lambda o: int(np.ceil(o.Force.size * 0.01))
fig = PlotUtilities.figure()
max_separation_nanometers = 60
FEC_Plot.heat_map_fec(curves_retract,n_filter_func= None,num_bins=(200,200),
separation_max=max_separation_nanometers)
# XXX need to fix zeroing
# limits in <nm,pN> for <x,y>
plt.xlim([-10,60])
plt.ylim([-30,60])
n_base_pairs = 68
# see (XXX need zotero citation)
# http://www.sciencedirect.com/science/article/pii/S0378437112008771
rise_nm_per_bp = 0.676
contour_length_nm = n_base_pairs *rise_nm_per_bp
style_contour = dict(color='w',linestyle='--',linewidth=4)
label_contour = r"L$_0$" +"={:.1f} nm ({:d}bp)".format(contour_length_nm,
n_base_pairs)
plt.axvline(contour_length_nm,label=label_contour,**style_contour)
PlotUtilities.legend(loc='lower center',frameon=True,facecolor='w')
PlotUtilities.savefig(fig,out_dir + "./out_histogram.png")
# plot each curve individually
for i,(appr,retract) in enumerate(zip(curves_approach,curves_retract)):
fig = PlotUtilities.figure()
FEC_Plot.FEC_AlreadySplit(appr,retract,
NFilterPoints=histogram_filter_func(retract))
# use sensible units, <x,y> are <nm,pN>
plt.xlim([-25,75])
plt.ylim([-30,100])
_,src_file = ntpath.split(appr.Meta.SourceFile)
save_name = "{:s}fec_{:d}_{:s}_{:s}.png".\
format(out_dir,i,src_file,appr.Meta.Name)
PlotUtilities.savefig(fig,save_name)
示例13: run
# 需要导入模块: from GeneralUtil.python import PlotUtilities [as 别名]
# 或者: from GeneralUtil.python.PlotUtilities import legend [as 别名]
def run():
"""
Runs contour length analysis
"""
OutFile = ""
Limit = 2
FullNames = ["2016_7_10_1ng_ul_50C_4hour_depo_circ_dna_Strept_tip_I.pxp",
"2016_7_10_1ng_ul_50C_4hour_depo_circ_dna_Strept_tip_II.pxp"]
DataArray = []
for i,Name in enumerate(FullNames):
DataArray.extend(pCheckUtil.getCheckpoint("Tmp{:d}.pkl".format(i),
ReadInData,False,Name))
NoTriggerDistance = 200e-9
for Tmp in DataArray:
idx = 0
Corrected,_ = CorrectForcePullByMetaInformation(Tmp)
Sep = Tmp.Separation
Tmp = Corrected
# work with the corrected version
Approach,Retract = FEC_Util.GetApproachRetract(Tmp)
EntireRetract = FEC_Util.\
GetFECPullingRegion(Retract,MetersAfterTouchoff=None,
Correct=True)
FilterFactor =10
NFilterPoints = int(np.ceil(EntireRetract.Force.size/FilterFactor))
FilteredForce = FEC_Util.GetFilteredForce(EntireRetract,NFilterPoints)
FilteredForceGradient = SavitskyFilter(np.gradient(FilteredForce.Force),
NFilterPoints)
OnlyPositive = FilteredForceGradient[np.where(FilteredForceGradient>0)]
q75, q25 = np.percentile(OnlyPositive, [75 ,25])
iqr = q75-q25
IsOutlier = lambda x: x > q75 + 1.5 * iqr
FirstOutlier = np.where(IsOutlier(FilteredForceGradient))[0][0]
MaxIdx = np.argmax(FilteredForceGradient)
IdxArr = np.arange(0,FilteredForceGradient.size)
SeparationRelativeRetract = EntireRetract.Separation
SeparationRelativeRetract -= SeparationRelativeRetract[0]
# first worm like chain ends where we past the max no longer an outlier
Outliers = np.where( ~IsOutlier(FilteredForceGradient) &
(IdxArr > FirstOutlier) &
(SeparationRelativeRetract > NoTriggerDistance))
EndOfFirstWLC = Outliers[0][0]
MetersAfterTouchoff = SeparationRelativeRetract[EndOfFirstWLC]
NearSurface = FEC_Util.\
GetFECPullingRegion(Retract,
MetersAfterTouchoff=MetersAfterTouchoff)
Bounds = GetBoundsDict(**dict(Lp=[20e-9,60e-9],
L0=[100e-9,700e-9],
K0=[1000e-12,1400e-12],
kbT=[0,np.inf]))
SepNear = NearSurface.Separation
ForceNear = NearSurface.Force
Fit = BoundedWlcFit(SepNear,ForceNear,VaryL0=True,VaryLp=True,Ns=20,
Bounds=Bounds)
Pred = Fit.Predict(SepNear)
# the fit was to 'NearSurface', which is zeroed. There can be an offset
# due to hydrodynamic drag on the cantilever (typically <20pN)
# to find this (in order for the retract-offsetted WLC fit to match),
# we each
Appr,Retr = FEC_Util.SplitAndProcess(Tmp)
# how much of the retract should we use to figure out the zero?
fraction = 0.05
N = int(np.ceil(fraction*Retr.Force.size))
# get the two zeros, and offset the fit by their different (retract
# should almost certainly be higher)
ZeroAppr = np.median(Appr.Force[:N])
ZeroRetr = np.median(Retr.Force[-N:])
Offset = ZeroRetr - ZeroAppr
# offset the WLC
Pred += Offset
# plot the data and the prediction
fig = pPlotUtil.figure()
FEC_Plot.FEC(Tmp)
# now plot some meta information. The expected overstretch
ExpectedOverstretch_pN = 65
plt.axhline(ExpectedOverstretch_pN,
linewidth=3.0,color='k',linestyle="--",label="65pN")
ToNm = lambda x: x*1e9
ToPn = lambda x: x*1e12
# get the contour length (L0) and the persistence length (Lp) in nm
# and as integers (ie: dont care about 2%
L0_nm = int(ToNm(Fit.Info.ParamVals.ParamDict["L0"].Value))
Lp_nm = int(ToNm(Fit.Info.ParamVals.ParamDict["Lp"].Value))
# plot the WLC prediction, label...
"""
plt.plot(ToNm(SepNear),ToPn(Pred),color='g',linestyle='--',
linewidth=5.0,
label="WLC (Extensible)\n")
"""
pPlotUtil.legend(frameon=True)
# note: limits are in nm and pN
MaxY_pN = np.max(ToPn(Pred[np.where(np.isfinite(Pred))]))
MaxY_pN = max(MaxY_pN,ToPn(np.max(Retr.Force)))
MinY_pN = -MaxY_pN/5
plt.ylim([-40,MaxY_pN])
plt.xlim([-20,plt.xlim()[-1]])
Name = "WLC" + Tmp.Meta.Name
pPlotUtil.savefig(fig,Name + ".png")
示例14: run
# 需要导入模块: from GeneralUtil.python import PlotUtilities [as 别名]
# 或者: from GeneralUtil.python.PlotUtilities import legend [as 别名]
def run():
"""
Biolever long from http://probe.olympus-global.com/en/product/bl_rc150vb_hw/
"""
Levers = [
Cantilever(Name="Biolever A ('Short')",
Length=60e-6,
# radius as the thickness
Radius=0.18e-6,
# height from tip height
Height=7e-6),
Cantilever(Name="Biolever B ('Long')",
Length=100e-6,
# radius as the thickness
Radius=0.18e-6,
# height from tip height
Height=7e-6),
Cantilever(Name="Biolever Mini",
Length=38e-6,
# radius as half the width
Radius=0.2e-6,
# height from tip height
Height=7e-6),
# See:
# omega.albany.edu:8008/calc3/vector-functions-dir/dna-solution-m2h.html
Cantilever(Name="DNA",
# 0.338nm/np for 201 bp
Length=0.338e-9*201,
Radius=1e-9,
Height=2e-9)
]
# get the force in SI units
Velocities = np.logspace(-9,-6)
Forces = []
for o in Levers:
Forces.append(o.FrictionPerEta * Velocities)
# Plot everything in pN and nm/s
VelNmPerSec = Velocities * 1e9
fig = pPlotUtil.figure(figsize=(8,8))
ax = plt.subplot(1,1,1)
ax.set_yscale('log')
pPlotUtil.lazyLabel("Velocity (nm/s)","Force (pN)",
"V~1um/s in water likely to " +
"rupture circular DNA",loc='lower right',frameon=True)
plt.ylim([1e-4,1e3])
for i,f in enumerate(Forces):
ForcePn = f *1e12
plt.plot(VelNmPerSec,ForcePn,label="Drag on " + Levers[i].Name)
pPlotUtil.LegendAndSave(fig,"Drag{:d}.png".format(i),
loc="lower right")
# write down the rupture force in pN based on
"""
Hatch, K., Danilowicz, C., Coljee, V., and Prentiss, M. (2008).
Demonstration that the shear force required to separate short
double-stranded DNA does not increase significantly with sequence length
for sequences longer than 25 base pairs. Phys. Rev. E 78, 011920.
"""
RuptureForce = 20
plt.axhline(RuptureForce,linewidth=3.0,linestyle="--",
label="{:d}pN (Circular Rupture)".format(RuptureForce))
TargetVel = 150
pPlotUtil.legend(loc="lower right",frameon=True)
pPlotUtil.savefig(fig,"DragForceAtVelocities.png")
示例15: run
# 需要导入模块: from GeneralUtil.python import PlotUtilities [as 别名]
# 或者: from GeneralUtil.python.PlotUtilities import legend [as 别名]
#.........这里部分代码省略.........
# get the iwt tx
n_bins = 200
energy_landscape_unfolding = CheckpointUtilities.\
getCheckpoint("./landscape.pkl",
InverseWeierstrass.FreeEnergyAtZeroForce,force_iwt,
final_unfolding_iwt,NumBins=n_bins)
# make a heat map of all retracts
fig = PlotUtilities.figure()
FEC_Plot.heat_map_fec([r.retract for r in good_splits])
PlotUtilities.title("FEC Heat map, aligned by L0, N={:d}".\
format(len(good_splits)))
PlotUtilities.savefig(fig,out_dir + "heat.png")
# make a heat map of just the region for the unfolding iwt
fig = PlotUtilities.figure()
FEC_Plot.heat_map_fec(final_rupture_only)
PlotUtilities.title("FEC Final unfolding heat map, aligned by L0, N={:d}".\
format(len(good_splits)))
PlotUtilities.savefig(fig,out_dir + "heat_unfolding.png")
# make a heat map of the unfolding and refolding experiment data
fig = PlotUtilities.figure(figsize=(4,7))
plt.subplot(2,1,1)
FEC_Plot.heat_map_fec(unfolding_objs)
plt.subplot(2,1,2)
FEC_Plot.heat_map_fec(refolding_objs)
PlotUtilities.savefig(fig,out_dir + "heat_refolding.png")
# get the refolding one
energy_landscape_bidirectional_folding = CheckpointUtilities.\
getCheckpoint("./landscape_bidirectional.pkl",
InverseWeierstrass.FreeEnergyAtZeroForce,force_iwt,
unfolding_objs,RefoldingObjs=refolding_objs,
NumBins=100)
energy_landscape_bidirectional_only_unfolding = CheckpointUtilities.\
getCheckpoint("./landscape_bidirectional_only_unfold.pkl",
InverseWeierstrass.FreeEnergyAtZeroForce,force_iwt,
unfolding_objs,RefoldingObjs=[],
NumBins=100)
energy_landscape_bidirectional_only_refolding = CheckpointUtilities.\
getCheckpoint("./landscape_bidirectional_only_refold.pkl",
InverseWeierstrass.FreeEnergyAtZeroForce,force_iwt,
refolding_objs,RefoldingObjs=[],
NumBins=100)
make_energy_landscape_plots(out_dir +"bi_",
energy_landscape_bidirectional_folding)
make_energy_landscape_plots(out_dir +"same_",
energy_landscape_unfolding)
make_energy_landscape_plots(out_dir +"bi_only_unfold",
energy_landscape_bidirectional_only_unfolding)
make_energy_landscape_plots(out_dir +"bi_only_refold",
energy_landscape_bidirectional_only_refolding)
# plot each unfolding/refolding pair, along with their velocities...
kw_unfold = dict(style_data=dict(color='b',alpha=0.3))
kw_fold = dict(style_data=dict(color='r',alpha=0.3))
to_y = lambda x: x*1e12
to_x = lambda x: x*1e9
for i,(un,re) in enumerate(zip(unfolding_objs,refolding_objs)):
# get the separation changes
min_v,max_v = min(un.Separation),max(un.Separation)
fudge = (max_v-min_v)*0.1
# using separation ('x value') as plotted y here, so use to_x
ylim = to_x(np.array([min_v-fudge,max_v+fudge]))
fig = PlotUtilities.figure(figsize=(4,7))
plt.subplot(2,1,1)
FEC_Plot._fec_base_plot(x=un.Time,y=to_y(un.Force),**kw_unfold)
FEC_Plot._fec_base_plot(x=re.Time,y=to_y(re.Force),**kw_fold)
PlotUtilities.lazyLabel("","Force","")
plt.subplot(2,1,2)
FEC_Plot._fec_base_plot(x=un.Time,y=to_x(un.Separation),label="unfold",
**kw_unfold)
FEC_Plot._fec_base_plot(x=re.Time,y=to_x(re.Separation),label="refold",
**kw_fold)
PlotUtilities.lazyLabel("","Separation","")
PlotUtilities.no_x_label()
plt.ylim(ylim)
sep_unfold = to_x(un.ZFunc(un))
plt.plot(un.Time,sep_unfold,color='k',linestyle='--')
plt.plot(re.Time,to_x(re.ZFunc(re)),label="Schedule",
color='k',linestyle=':')
plt.ylim(ylim)
PlotUtilities.lazyLabel("Time","Separation","")
PlotUtilities.legend()
name = out_dir + "unfolding_vs_time_{:d}.png".format(i)
PlotUtilities.savefig(fig,name)
# make the plots we want
for i,(ex,ex_unfold) in enumerate(zip(examples,unfolding_retracts)):
name = out_dir + "{:d}".format(i)
kw = dict(filter_fraction=1e-3)
hairpin_plots(ex,out_path=name,**kw)
# plot the unfolding force vs sep
fig = PlotUtilities.figure()
FEC_Plot._fec_base_plot(x=ex_unfold.Separation,y=ex_unfold.Force)
PlotUtilities.lazyLabel("Sep (nm)","Force (pN)","")
PlotUtilities.savefig(fig,name + "_unfold.png")
# plot the folding and refolding force vs time..
fig = PlotUtilities.figure()
FEC_Plot._fec_base_plot(x=unfolding_objs[i].Time,
y=to_y(unfolding_objs[i].Force))
FEC_Plot._fec_base_plot(x=refolding_objs[i].Time,
y=to_y(refolding_objs[i].Force))
PlotUtilities.lazyLabel("Time (s)","Force (pN)","")
PlotUtilities.savefig(fig,name + "_bidirectional_fold.png")