Exemple #1
0
def cache_pugh_diffusivity_alt(**params):
    "the function above applied to the pugh pore"
    if not fields.exists("Dpugh_alt", **params):
        setup_params = dict(params)
        r = setup_params.pop("r")
        ddata_pore = fields.get_fields("pugh_diff_pore", rMolecule=r)
        ddata_bulk = fields.get_fields("pugh_diff_bulk", rMolecule=r)
        if not "cheapest" in setup_params:
            setup_params["cheapest"] = True
        setup = pugh.Setup(x0=None, **setup_params)
        functions = diffusivity_field_alt(setup, r, ddata_pore, ddata_bulk)
        fields.save_functions("Dpugh_alt", params, **functions)
        fields.update()
Exemple #2
0
def cache_pugh_diffusivity_old(**params):
    "the function above applied to the pugh pore"
    if not fields.exists("Dpugh", **params):
        setup_params = dict(params)
        r = setup_params.pop("r")
        ddata_z = fields.get_fields("pugh_diff2D", rMolecule=r)
        ddata_r = fields.get_fields("pugh_diff3D", rMolecule=r, bulkbc=True)
        if not "cheapest" in setup_params:
            setup_params["cheapest"] = True
        setup = pugh.Setup(x0=None, **setup_params)
        functions = diffusivity_field(setup, r, ddata_r, ddata_z)
        fields.save_functions("Dpugh", params, **functions)
        fields.update()
Exemple #3
0
def interpolate_forcefieldS1_explicit(**params):
    # --- load force field and points
    data = fields.get_fields("force3D", **params)
    X = data["x"]
    F = data["F"]
    Fexp = [[1e-12 * f[0], 1e-12 * f[2]] for f in F]
    Fimpl = forcefieldS1_implicit(**params)

    # --- load geometry params
    # TODO: not very general
    xparams = fields.load_file("xforce")["params"]
    Rx0, Ry0 = xparams["Rx"], xparams["Ry"]
    Ry0 = 7.  # FIXME bad hack
    r = params["rMolecule"]
    r0, l0, r1, l1 = (Howorka.params_geo.r0, Howorka.params_geo.l0,
                      Howorka.params_geo.r1, Howorka.params_geo.l1)
    Rx, Ry = params["Rx"], params["Ry"]

    # --- piece together data TODO
    # additional points where implicit model will be used
    hadd = 0.8
    Xadd = uniform_grid([r1+r, Rx], [-Ry, -l1/2-r], hadd) + \
           uniform_grid([r1+r, Rx], [l1/2+r, Ry], hadd) + \
           uniform_grid([0, r1], [Ry0, Ry], hadd) + \
           uniform_grid([0, r1], [-Ry, -Ry0], hadd)
    # points where force is zero
    hdna = 0.4
    Xdna = uniform_grid([r0-r+.01, r1+r-.01], [-l0/2-r, l0/2+r], hdna) + \
           uniform_grid([r1+r, Rx], [-l1/2-r, l1/2+r], hdna)
    Fexpadd = [Fimpl(x) for x in Xadd]
    X += Xadd
    Fexp += Fexpadd
    Fimp = [Fimpl(x0) for x0 in X]
    X += Xdna
    Fdna = [[0., 0.] for x in Xdna]
    Fexp += Fdna
    Fimp += Fdna
    Fexp = np.array(Fexp)
    Fimp = np.array(Fimp)
    x = np.array([t[0] for t in X])
    y = np.array([t[1] for t in X])
    # overwrite explicit calculation far from pore # FIXME bad hack
    yfar = abs(y) > Ry0
    Fexp[yfar, :] = Fimp[yfar, :]

    # --- obtain S1 functions
    mesh = Fimpl.function_space().mesh()
    F = data_to_S1(x, y, mesh, Fexp=Fexp)

    # --- save functions
    uid = fields._unique_id()
    FNAME = NAME + uid
    nanopores.save_functions(FNAME, mesh, meta=params, F=F)
    fields.save_entries(NAME, params, FNAME=FNAME)
    fields.update()
Exemple #4
0
def cache_diffusivity(mode="coupled", **params):
    #name = "D%s-%s" % (geoname, mode)
    name = "Diffusivity"

    if not fields.exists(name, **params):
        if not "cheapest" in params:
            params["cheapest"] = True
        # setup = pugh.Setup(x0=None, **params)
        setup = nanopore.Setup(x0=None, **params)
        r = params["r"]
        #diamPore = setup.geo.params.diamPore

        if mode == "coupled":
            # TODO: make general
            data_z = fields.get_fields("pugh_diff2D", rMolecule=r)
            data_r = diff_profile_plane(r)
        elif mode == "simple":
            data_z = None
            data_r = diff_profile_plane(r)
        elif mode == "profile":
            data_z = fields.get_fields("pugh_diff2D", rMolecule=r)
            #data_z = diff_profile_z_pugh(diamPore=diamPore)
            data_r = diff_profile_trivial(r)
        else:
            raise NotImplementedError

        functions = diffusivity_field(setup,
                                      r,
                                      ddata_z=data_z,
                                      ddata_r=data_r,
                                      boundary="dnab",
                                      poreregion="poreregion")
        params["mode"] = mode
        fields.save_functions(name, params, **functions)
        fields.update()

    return name
Exemple #5
0
def save_fig(params, fieldsname):
    figname = fieldsname + '_%.1e_%.1e_%.1e_%.1e_%.1e_%.1e' % (
        params["avgbind1"], params["avgbind2"], params["avgbind3"],
        params["P_bind1"], params["P_bind2"], params["P_bind3"]) + str(
            params["z0"])
    data = f.get_fields(fieldsname, **params)
    t1 = data["t1"]
    a1 = data["a1"]
    t2 = data["t2"]
    a2 = data["a2"]
    t0 = data["t0"]
    a0 = data["a0"]
    print len(t1)
    print len(t2)
    lendata = len(t1) + len(t2)
    for i in range(len(t1)):
        if math.isnan(a1[i]): print 'a1: NaN %i' % i
    plt.figure(figsize=(6, 4), dpi=80)
    plt.plot([3e-6, .7], [0., 0.], linewidth=2, color='lightgreen')
    plt.plot([1., 1e2], [0., 0.], linewidth=2, color='green')
    ax = plt.gca()
    plt.scatter(t1, a1, color='lightgreen', s=8)
    plt.scatter(t2, a2, color='green', s=8)
    plt.scatter(t0,
                a0,
                marker='o',
                s=50,
                facecolors='none',
                edgecolors='#ff0000')
    #ax.text(t1[k],a1[k],'%i'%k,fontsize=9)
    xfmt = FormatStrFormatter('%g')
    ax.set_xlim([1e-6, 500.])
    ax.set_ylim([-2., 25.0])
    ax.set_xscale('log')
    ax.xaxis.set_major_formatter(xfmt)
    ax.invert_yaxis()
    ax.set_xlabel(r'$\tau_{off}$ [ms]', fontsize=15)
    ax.set_ylabel(r'A/I$_0$ [%]', fontsize=15)
    ax.text(.001, -0.03, 'I', fontsize=15)
    ax.text(5., -0.03, 'II', fontsize=15)
    #ax.text(1.,5.,lendata,fontsize=25)
    plt.tight_layout()
    nano.savefigs(name=figname, DIR='/home/lv70496/benjamin/plots/')
    print 'savefig:'
    print figname
Exemple #6
0
 def wrapper(X, cache=True, calc=True, overwrite=False,
             nproc=self.nproc, name=self.name, **params):
     if not cache:
         return f(X, **params)
     if calc:
         # calculate remaining points (in parallel)
         calculate_forcefield(name, X, f, params, self.default, nproc,
                              overwrite=overwrite)
     # load requested data points
     load_params = dict(self.default, **params)
     try:
         result = fields.get_fields(name, **load_params)
         I = [result["x"].index(x) for x in X if x in result["x"]]
     except KeyError:
         print "KeyError, returning nothing."
         result = {}
         I = []
     result = {key: [val[i] for i in I] for key, val in result.items()}
     return Params(result)
Exemple #7
0
def save_fig(params):
	figname = 'type_'+str(params["avgbind1"])+'_'+str(params["avgbind2"])+'_'+str(params["P_bind1"])+'_'+str(params["P_bind2"])+'_'+str(params["z0"])+'.eps'
	data=f.get_fields("rw_2_bind",**params)
	t1 = np.array([])
	t2 = np.array([])
	a1 = np.array([])
	a2 = np.array([])
	T=data["T"]
	J=data["J"]
#	print '#data = %i'%len(T)
	for i in range(len(T)):
	    T_=np.array(T[i])*1e-6
	    J_=np.array(J[i])
	    tau_off=np.sum(T_)
	    amp = (2060.-np.inner(J_,T_)/tau_off)/2060.*100
	    if number: ax.text(tau_off,amp,'%i'%i,fontsize=9)
	    if tau_off<.1:
		t1=np.append(t1,np.array([tau_off]))
		a1=np.append(a1,np.array([amp]))
	    else:
		t2=np.append(t2,np.array([tau_off]))
		a2=np.append(a2,np.array([amp]))



	plt.plot([5e-4,.1],[0.,0.],linewidth=2,color='lightgreen')
	plt.plot([.2,1e2],[0.,0.],linewidth=2,color='green')
	ax=plt.gca()
	plt.scatter(t1,a1,color='lightgreen')
	plt.scatter(t2,a2,color='green')
	ax.set_xlim([1e-4,500.])
	ax.set_ylim([-0.40,4.0])
	ax.set_xscale('log')
	ax.invert_yaxis()
	ax.set_xlabel(r'$\tau_{off}$ [ms]',fontsize=15)
	ax.set_ylabel(r'A/I$_0$ [%]',fontsize=15)
	ax.text(.011,-0.03,'I',fontsize=15)
	ax.text(5.,-0.03,'II',fontsize=15)
	plt.tight_layout()
	nano.savefigs(name=figname,DIR='/home/lv70496/benjamin/plots/')
Exemple #8
0
#params=dict(avgbind1=1e7,avgbind2=3e4,P_bind1=5.e-3,P_bind2=8e-2,z0=hpore/2.+0.)
#params=dict(avgbind1=1e7,avgbind2=1e5,P_bind1=2.e-2,P_bind2=8e-2,z0=hpore/2.+0.) # good if only real translocations count - no type 0 "ood"
params = dict(avgbind1=2e7,
              avgbind2=3e4,
              P_bind1=8.e-2,
              P_bind2=0 * 3e-1,
              z0=hpore / 2. + 0.)
b1 = []
b2 = [[[l1 / 2., 17.], [l1 / 2., 19.]]]
outside = True

for i in range(samples):
    run(params, fieldsname, outcome, outside, b1, b2)
    print '%i out of ' % i + num

print 'field updates'
if outcome == 'type' or outcome == 'both':
    from create_plot_type import *
    f.update()
    save_fig_type(params, fieldsname)
    plt.close("all")
    from create_plot_traj import *
    save_fig_traj(params, fieldsname, 0, False)

if outcome == 'traj' or outcome == 'both':
    if outcome != 'both':
        from create_plot_traj import *
        f.update()
    for i in range(len(fields.get_fields(fieldsname, **params)["X"])):
        save_fig_traj(params, fieldsname, i, True)
Exemple #9
0
    Fy = np.load('Fy.npy')
    Fz = np.load('Fz.npy')
    Ja = np.load('Ja.npy')
except:
    import os
    import nanopores.tools.fields as fields
    HOME = os.path.expanduser("~")
    PAPERDIR = os.path.join(HOME, "papers", "paper-howorka")
    FIGDIR = os.path.join(PAPERDIR, "figures", "")

    DATADIR = os.path.join(HOME, "Dropbox", "nanopores", "fields")

    fields.set_dir(DATADIR)

    params = dict(Nmax=500000.)
    data = fields.get_fields("pugh_force", **params)

    x = data["x"]
    #Fel=data["Fel"]
    #Fdrag=data["Fdrag"]
    J = data["J"]
    F = data["F"]

    xq = list(x)
    #Felq=list(Fel)
    #Fdragq=list(Fdrag)
    Jq = list(J)
    Fq = list(F)
    # diagonal mirror
    for i in range(len(x)):
        if x[i][0] != x[i][1]:
Exemple #10
0
import nanopores.tools.fields as f
HOME = os.path.expanduser("~")
PAPERDIR = os.path.join(HOME, "papers", "paper-howorka")
FIGDIR = os.path.join(PAPERDIR, "figures", "")
DATADIR = os.path.join(HOME, "Dropbox", "nanopores", "fields")
f.set_dir(DATADIR)

plt.plot([5e-4, .1], [0., 0.], linewidth=2, color='lightgreen')
plt.plot([.2, 1e2], [0., 0.], linewidth=2, color='green')
ax = plt.gca()
number = (len(sys.argv) == 2)

geop = nano.Params(pughpore.params)
hpore = geop.hpore
params = dict(avgbind=1e7, P_bind=3.e-4, z0=hpore / 2. + 5.)
data = f.get_fields("randomwalk2", **params)
t1 = np.array([])
t2 = np.array([])
a1 = np.array([])
a2 = np.array([])
T = data["T"]
J = data["J"]
print '#data = %i' % len(T)
for i in range(len(T)):
    T_ = np.array(T[i]) * 1e-6
    J_ = np.array(J[i])
    tau_off = np.sum(T_)
    amp = (2060. - np.inner(J_, T_) / tau_off) / 2060. * 100
    if number: ax.text(tau_off, amp, '%i' % i, fontsize=9)
    if tau_off < .1:
        t1 = np.append(t1, np.array([tau_off]))
Exemple #11
0
#h2 = up.h2
#h1 = up.h1
#h4 = up.h4
#rMolecule = up.rMolecule
#eps = 0.1
#r = rMolecule + eps
#
#fac = np.array([.5*l0*1.2,.5*l0,.5*l1-r,.5*l1-r,
#                .5*l2-r,.5*l3-r,.5*l3-r,.5*l3-r,.5*l3-r,.5*l3-r])
#heights = np.array([.5*hpore+5.,.5*hpore+rMolecule,.5*hpore,.5*(hpore-h1),
#              .5*hpore-h1,.5*hpore-h2,-.5*hpore+.75*(hpore-h2),
#              -.5*hpore+.5*(hpore-h2),-.5*hpore+.25*(hpore-h2),-.5*hpore])
#height=heights[6]

params = dict(bulkcon=1000.)
data = fields.get_fields("pugh", **params)
x = data["x"]
Fel = data["Fel"]
Fdrag = data["Fdrag"]
J = data["J"]
F = data["F"]

xq = list(x)
Felq = list(Fel)
Fdragq = list(Fdrag)
Jq = list(J)
Fq = list(F)
# diagonal mirror
for i in range(len(x)):
    if x[i][0] != x[i][1]:
        xq.append([x[i][1], x[i][0], x[i][2]])
Exemple #12
0
PAPERDIR = os.path.join(HOME, "papers", "paper-howorka")
FIGDIR = os.path.join(PAPERDIR, "figures", "")
DATADIR = os.path.join(HOME, "Dropbox", "nanopores", "fields")
fields.set_dir(DATADIR)
old = ['events3_onlyone_%i' % i for i in [1, 2, 3, 4, 5]]
new = ['events3_onlyone_%i_new' % i for i in [1, 2, 3, 4, 5]]

hpore = 46.
params = dict(avgbind1=2e7,
              avgbind2=3e4,
              P_bind1=8.e-2,
              P_bind2=0 * 3e-1,
              z0=hpore / 2. + 0.)
for i in range(5):
    print i
    data = fields.get_fields(old[i], **params)
    for k in range(len(data["X"])):
        if k % 10 == 0:
            print k
        saveX = [np.array(data["X"][k])]
        saveY = [np.array(data["Y"][k])]
        saveZ = [np.array(data["Z"][k])]
        fields.save_fields(new[i], params, X=saveX, Y=saveY, Z=saveZ)
    fields.save_fields(new[i],
                       params,
                       a=data["a"],
                       ood=data["ood"],
                       J=data["J"],
                       t=data["t"],
                       b1=data["b1"],
                       Fzavg=data["Fzavg"],
Exemple #13
0
# (c) 2016 Gregor Mitscha-Baude
import matplotlib.pyplot as plt
import numpy as np
import nanopores.tools.fields as fields
import os
import nanopores

DATADIR = os.path.join(nanopores.HOME, "Dropbox", "nanopores", "fields")
FIGDIR = os.path.join(nanopores.HOME, "Dropbox", "nanopores", "figures")
FIGDIR = os.path.join(nanopores.HOME, "papers", "pnps-numerics", "figures")
fields.set_dir(DATADIR)
fields.update()
#data = fields.get_fields("howorka_velo1", Nmax=1e4)
data = fields.get_fields("howorka_velo3D_2")

#z = [x[2] for x in data["x"]]
z = [x[0] for x in data["x"]]
data, z = fields._sorted(data, z)

## modify
i = 0
rad = lambda x: sum(t**2 for t in x)
#rad = lambda x: x[2]
#v0 = [rad(x) for x in data["v0"]]
#v1 = [rad(x) for x in data["v1"]]
z.pop(-1)
data["v0"].pop(-1)
data["v1"].pop(-1)

plt.plot(z, [x[0] for x in data["v0"]],
         "o-",
def save_fig_filter(params, fieldsname, i):
    data = f.get_fields(fieldsname, **params)
    T_ = data["T"][i].load()

    J_ = data["J"][i].load()
    T = np.array([])
    J = np.array([])

    for k in range(T_.shape[0]):
        time = T_[k]
        if time == 1.:
            T = np.append(T, 1.)
            J = np.append(J, J_[k])
        else:
            vec = np.ones(int(time))
            T = np.append(T, vec)
            J = np.append(J, J_[k] * vec)

    T = np.append(T, np.ones(1000000))
    J = np.append(J, np.ones(1000000) * J[0])

    for k in range(1, T.shape[0]):
        T[k] += T[k - 1]


#    T*=1e-9
    J *= 1e12

    zero = J[0]
    J -= zero
    from scipy import signal
    b, a = signal.bessel(2, 2873. / (5e8), analog=False)
    sig_ff = signal.lfilter(b, a, J)
    amp = data["a"][i]
    ftime = np.min(np.where(sig_ff > 1e-10)) - 1
    ampf = abs(np.sum(sig_ff[:ftime])) / float(ftime) / curr * 100
    print 'without filter: %.1f' % amp
    print 'with    filter: %.1f' % ampf
    tau_off = float(ftime)

    plt.title('Current signal')
    ax = plt.gca()
    if tau_off < 1e3:
        t = np.linspace(0., tau_off, 3)
        fac = 1.
        ax.set_xlabel('time [$ns$]')
    elif tau_off < 1e6 and tau_off >= 1e3:
        t = np.linspace(0., tau_off * 1e-3, 3)
        fac = 1e-3
        ax.set_xlabel(r'time [$\mu s$]')
    else:
        t = np.linspace(0., tau_off * 1e-6, 3)
        fac = 1e-6
        ax.set_xlabel('time [$ms$]')
    T = T * fac
    plt.plot(T, J + zero, color='#000000')
    plt.plot(T, sig_ff + zero, linewidth=2., color='#ff6600')
    yt = np.linspace(580., 760, 4)
    ax.set_ylabel(r'A [$pA$]')
    ax.set_yticks(yt)
    ax.set_xticks(t)
    xfmt = FormatStrFormatter('%.1f')
    ax.xaxis.set_major_formatter(xfmt)
    ax.set_xlim([-4e-2 * tau_off * fac, (1. + 4e-2) * tau_off * fac])

    plt.tight_layout()
    plt.show()
Exemple #15
0
def save_fig_type(params, fieldsname):
    plotlin = False
    #    cmap=matplotlib.cm.get_cmap('plasma')
    data = f.get_fields(fieldsname, **params)
    figname = fieldsname + '_%.1e_%.1e_%.1e_%.1e' % (
        params["avgbind1"], params["avgbind2"], params["P_bind1"],
        params["P_bind2"]) + str(params["z0"])
    t = data["t"]
    tdata = np.array(t)
    a = data["a"]
    ood = data["ood"]
    lendata = len(t)
    fac = 1.
    if max(t) < 1e-2:
        fac = 1e3
        t = [x * 1e3 for x in t]

    P_bind1 = params["P_bind1"]
    P_bind2 = params["P_bind2"]
    avgbind1 = params["avgbind1"] * 1e-6
    avgbind2 = params["avgbind2"] * 1e-6

    color2 = 'green'
    color1 = 'lightgreen'
    color3 = 'red'

    if plotlin:
        plt.figure(figsize=(10, 5), dpi=80)
    else:
        plt.figure(figsize=(7, 5), dpi=80)
    if plotlin:
        gs = gridspec.GridSpec(2,
                               3,
                               width_ratios=[4, 2, 1],
                               height_ratios=[1, 2.5])
    else:
        gs = gridspec.GridSpec(2,
                               2,
                               width_ratios=[4, 1],
                               height_ratios=[1, 2.5])
    gs.update(wspace=0., hspace=0.)

    minperc = 0.
    maxperc = 30.
    plt1 = plt.subplot(gs[1, 0])
    for k in range(lendata):
        if ood[k] == 0:
            type1 = plt1.scatter([t[k]], [a[k]], color=color2, s=8)
        else:
            type0 = plt1.scatter([t[k]], [a[k]], color=color3, s=8)
    xfmt = FormatStrFormatter('%g')
    plt1.set_xlim([.2 * min(t), max(t) * 5.])
    plt1.set_ylim([minperc, maxperc])
    plt1.set_xscale('log')
    plt1.xaxis.set_major_formatter(xfmt)
    plt1.invert_yaxis()
    plt1.set_ylabel(r'A/I$_0$ [%]', fontsize=15)
    #    plt1.text(.2,23.,str(float(np.where(tdata>0.2)[0].shape[0])/float(tdata.shape[0]))+'='+str(np.where(tdata>0.2)[0].shape[0])+'/'+str(tdata.shape[0]),fontsize=9)
    if fac == 1.:
        if P_bind1 != 0.:
            plt1.text(avgbind1 * .5,
                      27.,
                      'Long binding',
                      fontsize=9,
                      horizontalalignment='center')
            k = 0.5
#            plt1.add_patch(matplotlib.patches.Rectangle((avgbind1*10**(-k*2),0.),avgbind1*(10**(k)-10**(-k)),maxperc,facecolor=cmap(.7),alpha=.15))
        if P_bind2 != 0.:
            plt1.text(0.002,
                      27.,
                      'Short binding',
                      fontsize=9,
                      horizontalalignment='center')
            k = 1.0
#            plt1.add_patch(matplotlib.patches.Rectangle((avgbind2*100*10**(-k),0.),avgbind2*(10**(k)-10**(-k)),maxperc,facecolor=cmap(.4),alpha=.15))
#            plt1.add_patch(matplotlib.patches.Rectangle((0.01,0.),0.99,maxperc,facecolor=cmap(.4),alpha=.15))
        plt1.set_xlabel(r'$\tau_{off}$ [ms]', fontsize=15)  #,x=.76)
    else:
        plt1.set_xlabel(ur'$\tau_{off}$ [µs]', fontsize=15)  #,x=.76)
    if plotlin:
        plt2 = plt.subplot(gs[1, 1])
        for k in range(lendata):
            if ood[k] == 0:
                type1 = plt2.scatter([t[k]], [a[k]], color=color2, s=8)
            else:
                type0 = plt2.scatter([t[k]], [a[k]], color=color3, s=8)
        plt2.invert_yaxis()
        plt2.set_ylim([maxperc, minperc])
        plt2.set_xlim([-2e-2 * max(t), max(t) * (1. + 2e-2)])
        plt2.axes.get_yaxis().set_visible(False)
        plt2.axes.get_xaxis().major.locator.set_params(nbins=6)
        plt3 = plt.subplot(gs[1, 2])
    else:
        plt3 = plt.subplot(gs[1, 1])
    n, bins, patches = plt3.hist(np.array(a),
                                 15,
                                 normed=1,
                                 orientation='horizontal',
                                 color=color1,
                                 alpha=.5)
    plt3.invert_yaxis()
    plt3.set_xlim([0., max(n) * 1.2])
    plt3.set_ylim([maxperc, minperc])
    plt3.axes.get_xaxis().set_visible(False)
    plt3.axes.get_yaxis().set_visible(False)

    if plotlin:
        plt4 = plt.subplot(gs[0, 1])
        n, bins, patches = plt4.hist(np.array(t),
                                     20,
                                     normed=1,
                                     color=color1,
                                     alpha=.5)
        plt4.set_xlim([-2e-2 * max(t), max(t) * (1. + 2e-2)])
        plt4.axes.get_xaxis().set_visible(False)
        plt4.axes.get_yaxis().set_visible(False)
    else:
        plt4 = plt.subplot(gs[0, 0])
        n, bins, patches = plt4.hist(map(lambda x: math.log10(x), np.array(t)),
                                     25,
                                     normed=1,
                                     color=color1,
                                     alpha=.5,
                                     align='mid')
        plt4.set_xlim([math.log10(.2 * min(t)), math.log10(max(t) * 5.)])
        plt4.axes.get_xaxis().set_visible(False)
        plt4.axes.get_yaxis().set_visible(False)

    plt.legend([type1, type0],
               ['successful translocation', 'did not translocate'],
               scatterpoints=4,
               loc=(.6, 0.50))
    plt.tight_layout()
    nano.savefigs(name=figname, DIR='/home/bstadlbau/plots/', pdf=True)
    print 'savefig:'
    print figname
Exemple #16
0
def save_fig_filter(params, fieldsname, i):
    data = f.get_fields(fieldsname, **params)
    T_ = data["T"][i].load()

    J_ = data["J"][i].load()
    T = np.array([])
    J = np.array([])

    for k in range(T_.shape[0]):
        time = T_[k]
        if time == 1.:
            T = np.append(T, 1.)
            J = np.append(J, J_[k])
        else:
            vec = np.ones(int(time))
            T = np.append(T, vec)
            J = np.append(J, J_[k] * vec)

    T = np.append(T, np.ones(1000000))
    J = np.append(J, np.ones(1000000) * J[0])

    for k in range(1, T.shape[0]):
        T[k] += T[k - 1]

#    T*=1e-9
    J *= 1e12

    zero = J[0]
    J -= zero
    from scipy import signal
    b, a = signal.bessel(2, 1. / 5. * 1e-3, analog=False)
    sig_ff = signal.lfilter(b, a, J)
    amp = data["a"][i]
    ftime = np.min(np.where(sig_ff > 1e-10)) - 1
    ampf = abs(np.sum(sig_ff[:ftime])) / float(ftime) / curr * 100
    print 'without filter: %.1f' % amp
    print 'with    filter: %.1f' % ampf
    tau_off = float(ftime)
    figname = fieldsname + '_filter_' + '%.8f' % (
        tau_off * 1e-6) + '_%04d' % i + '_%.1e_%.1e_%.1e_%.1e' % (
            params["avgbind1"], params["avgbind2"], params["P_bind1"],
            params["P_bind2"]) + str(params["z0"])
    af = [ampf]
    tf = [tau_off]
    f.save_fields(fieldsname, params, tf5=tf, af5=af)

    plt.figure(figsize=(6, 4), dpi=80)
    plt.title('Current signal')
    ax = plt.gca()
    if tau_off < 1e3:
        t = np.linspace(0., tau_off, 3)
        fac = 1.
        ax.set_xlabel('time [$ns$]')
    elif tau_off < 1e6 and tau_off >= 1e3:
        t = np.linspace(0., tau_off * 1e-3, 3)
        fac = 1e-3
        ax.set_xlabel(r'time [$\mu s$]')
    else:
        t = np.linspace(0., tau_off * 1e-6, 3)
        fac = 1e-6
        ax.set_xlabel('time [$ms$]')
    T = T * fac
    plt.plot(T, J + zero, color='#000000', label='Original')
    plt.plot(T, sig_ff + zero, linewidth=2., color='#ff6600', label='Filtered')
    plt.legend(loc='best')
    yt = np.linspace(580., 760, 4)
    ax.set_ylabel(r'A [$pA$]')
    ax.set_yticks(yt)
    ax.set_xticks(t)
    xfmt = FormatStrFormatter('%.1f')
    ax.xaxis.set_major_formatter(xfmt)
    ax.set_xlim([-4e-2 * tau_off * fac, (1. + 4e-2) * tau_off * fac])

    plt.tight_layout()
    nano.savefigs(name=figname, DIR='/home/bstadlbau/plots/')
    print 'savefig: %s' % figname
    plt.close("all")
Exemple #17
0
import nanopores.tools.fields as f
f.set_dir(DATADIR)

def zsorted(data, field):
    z = [x[2] for x in data["x"]]
    J = data[field]
    I = sorted(range(len(z)), key=lambda k: z[k])
    z1 = [z[i] for i in I]
    J1 = [J[i] for i in I]
    return z1, J1

geop = nano.Params(pughpore.params)
rMolecule = geop.rMolecule
N = 2e4

data = f.get_fields("pugh_diffusivity2D", rMolecule=rMolecule)#, h=4., Nmax=N)
Z, D = zsorted(data, "D")
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
import numpy as np
#D=np.load('D.npy')
#Z=np.load('D_Z.npy')
D = np.array(D)
Z = np.array(Z)

a, b = -7.3, 7.3
D_N = np.zeros(Z.shape[0])
for i in range(Z.shape[0]):
    if Z[i] >a and Z[i]<b:
        D_N[i]=np.mean(np.array([D[j] for j in np.arange(i-3,i+4)]))
    else:
Exemple #18
0
h4 =        geop.h4
rMolecule = geop.rMolecule
params=dict(avgbind1=17.2e6,avgbind2=3e4,P_bind1=0.193,P_bind2=3e-1,z0=hpore/2.+0.)
#params=dict(avgbind1=17.2e6,avgbind2=3e4,P_bind1=0.020,P_bind2=3e-1,z0=hpore/2.+0.)
#b1 = [[[l3/2.,-hpore/2.],[l3/2.,hpore/2.-h2],[l2/2.,hpore/2.-h2],[l2/2.,hpore/2.-h1],[l1/2.,hpore/2.-h1],[l1/2.,hpore/2.]]]
#b2 = [[[2.5, hpore/2.-h2-24.], [2.5, hpore/2.-h2-32.]]]
b2 = [[[l3/2.,-hpore/2.],[l3/2.,hpore/2.-h2],[l2/2.,hpore/2.-h2],[l2/2.,hpore/2.-h1],[l1/2.,hpore/2.-h1],[l1/2.,hpore/2.]]]
b1 = []
#b2 = []
outside=True
#outside=False

for i in range(samples):
	run(params,fieldsname,outcome,outside,b1,b2)
	print '%i out of '%i+num 
try: fields.get_fields(fieldsname,**params)["b1"]
except: fields.save_fields(fieldsname,params,b1=b1)
try: fields.get_fields(fieldsname,**params)["b2"]
except: fields.save_fields(fieldsname,params,b2=b2)

print 'field updates'
if outcome=='type' or outcome=='both':
    from create_plot_type import *
    f.update()
    save_fig_type(params,fieldsname)
    plt.close("all")
    from create_plot_traj import *
    save_fig_traj(params,fieldsname,0,False)

if outcome=='traj' or outcome=='both':
    if outcome!='both':
Exemple #19
0
# (c) 2016 Gregor Mitscha-Baude
import nanopores.tools.fields as f
import matplotlib.pyplot as plot
import folders

f.update()
for h in [2., 4.]:
    field = f.get_fields("pughcenter", bulkcon=1e3, Qmol=8, h=h)
    z = [x[2] for x in field["x"]]
    J = [j * 1e12 for j in field["J"]]
    I = sorted(range(len(z)), key=lambda k: z[k])
    z1 = [z[i] for i in I]
    J1 = [J[i] for i in I]
    for i in I:
        print z[i], J[i]

    plot.plot(z1, J1, "s-", label="molecule, h=%s" % h)
    plot.xlabel("z position of molecule [nm]")
    plot.ylabel("current [pA]")
    plot.title("current at -100mV for molecule along pore center")

for h in []:  #[1., 2., 3., 4.]:
    Jopen = f.get_fields("pughopen", Qmol=8, h=h)["J"][0]
    plot.plot(z1, [2. * Jopen * 1e12] * len(z1), "--", label="open, h=%s" % h)

plot.legend()
plot.show()
Exemple #20
0
            value[:] = f(x)

        def value_shape(self):
            return value_shape

    f1.interpolate(expr())
    return f1


params = dict(
    Qmol=-3,
    rMolecule=0.5,
)

# load force field and points
data = fields.get_fields("force3D", **params)
X = data["x"]
F = data["F"]
xparams = fields.load_file("xforce")["params"]
Rx, Ry = xparams["Rx"], xparams["Ry"]
# 2D field
Fimpl, Felimpl, Fdragimpl, meshimpl, _ = \
    forcefield2D.load_forcefield_implicit(**params)

Fexp = [[1e-12 * f[0], 1e-12 * f[2]] for f in F]


# add additional points where implicit model will be used
def uniform_grid(xi, yi, h):
    Lx = xi[1] - xi[0]
    Ly = yi[1] - yi[0]
Exemple #21
0
def save_fig_traj(params,fieldsname,i,showtraj):
    data=f.get_fields(fieldsname,**params)
    b1 =data["b1"]
    b2 =data["b2"]
    if showtraj:
        X = data["X"][i]
        Y = data["Y"][i]
        Z = data["Z"][i]
        T = data["T"][i]
        J = data["J"][i]
        J=J.load()
        T=T.load()
        curr = 7.523849e-10
        bind1 = np.where(T>1e6)[0]
        bind2 = np.intersect1d(np.where(T<=1e6)[0],np.where(T>100.)[0])
        amplitude = curr-np.inner(J,T)/np.sum(T)
        for k in range(1,T.shape[0]):
            T[k]=T[k]+T[k-1]
        tau_off=T[-1]
        J=J*1e12
        figname = fieldsname+'_traj_'+'%.8f'%(tau_off*1e-6)+'_%04d'%i+'_%.1e_%.1e_%.1e_%.1e'%(params["avgbind1"],params["avgbind2"],params["P_bind1"],params["P_bind2"])+str(params["z0"])
    else:
        figname = fieldsname+'_bindzones'+'_%.1e_%.1e_%.1e_%.1e'%(params["avgbind1"],params["avgbind2"],params["P_bind1"],params["P_bind2"])+str(params["z0"])

    if showtraj:
        fig=plt.figure(figsize=(8,5),dpi=80)
    else:
        fig=plt.figure(figsize=(3,5),dpi=80)
    color2='#ff0000'
    color1='#ff9900'
    color3='#00ff00'

    #b1 = [[[l1/2.,17.],[l1/2.,19.]],[[l3/2.,-hpore/2.],[l3/2.,hpore/2.-h2],[l2/2.,hpore/2.-h2],[l2/2.,14.]]]
    for seq in b1:
        x= [p[0] for p in seq]
        xm=[-p[0] for p in seq]
        y= [p[1] for p in seq]
        plt.plot(x,y,color=color1,linewidth=2.)
        plt.plot(xm,y,color=color1,linewidth=2.)
    #b2 = [[[l3/2.-.5,-3.],[l3/2.-.5,11.]]]
    for seq in b2:
        x= [p[0] for p in seq]
        xm=[-p[0] for p in seq]
        y= [p[1] for p in seq]
        plt.plot(x,y,color=color2,linewidth=2.)
        plt.plot(xm,y,color=color2,linewidth=2.)
    if showtraj:
        plt.plot(X,Z,linewidth=1.,c='#0000ff')
        longer = plt.scatter(X[bind1],Z[bind1],s=200,marker='h',c=color2,linewidth=0.)
        shorter = plt.scatter(X[bind2],Z[bind2],s=100,marker='h',c=color1,linewidth=0.)
        start = plt.scatter([X[0]],[Z[0]],s=200,marker='x',c=color3,linewidth=2.)
        patches=[start]
        labels=['Start']
    if showtraj and len(bind1)>0:
        patches=patches+[longer]
        labels+=['Longer bindings']
    if showtraj and len(bind2)>0:
        patches=patches+[shorter]
        labels+=['Shorter bindings']
    if showtraj:
        plt.legend(patches,labels,scatterpoints=1,loc=(.42,.15))
    ax=plt.gca()
    ax.set_aspect('equal')
    if showtraj:
        ax.set_xlim([20.,-55.])
        ax.set_ylim([-25.,40.])
    else:
        ax.set_xlim([20.,-20.])
        ax.set_ylim([-25.,40.])
    ax.set_xticks([])
    ax.set_yticks([])
    plt.axis('off')
    plot_polygon(ax,polygon(rmem=60.))


    if showtraj:
        plt.axes([.55,.5,.2,.3])
        plt.title('Current signal')
        ax=plt.gca()
        if tau_off<1e3:
            t = np.linspace(0.,tau_off,3)
            fac=1.
            ax.set_xlabel('time [$ns$]')
        elif tau_off<1e6 and tau_off>=1e3:
            t = np.linspace(0.,tau_off*1e-3,3)
            fac = 1e-3
            ax.set_xlabel(r'time [$\mu s$]')
        else:
            t = np.linspace(0.,tau_off*1e-6,3)
            fac = 1e-6
            ax.set_xlabel('time [$ms$]')
        T=T*fac
        plt.plot(T,J,color='#000000')
        yt = np.linspace(580.,760,4)
        ax.set_ylabel(r'A [$pA$]')
        ax.set_yticks(yt)
        ax.set_xticks(t)
        xfmt=FormatStrFormatter('%.1f')
        ax.xaxis.set_major_formatter(xfmt)
        ax.set_xlim([-4e-2*tau_off*fac,(1.+4e-2)*tau_off*fac])


    plt.tight_layout()
#    nano.savefigs(name=figname,DIR='/home/bstadlbau/plots/')
    plt.show()
    print 'savefig: %s'%figname
    plt.close("all")
Exemple #22
0
from matplotlib import pyplot as plt
import numpy as np
import os
from nanopores.tools import fields
from scipy.interpolate import interp1d

HOME = os.path.expanduser("~")
DATADIR = os.path.join(HOME, "Dropbox", "nanopores", "fields")

fields.set_dir(DATADIR)

data = fields.get_fields("pugh_diff3D_cross", bulkbc=True, rMolecule=2.0779)


def smooth3(l):
    A = np.array(l)
    B = A[:]
    ker = np.array([1. / 3, 1. / 3, 1. / 3])
    n = int(ker.shape[0] / 2.)
    for i in range(n, A.shape[0] - n):
        B[i] = np.inner(A[i - n:i + n + 1], ker)
    return list(B)


def smooth5(l):
    A = np.array(l)
    B = A[:]
    ker = np.array([.2, .2, .2, .2, .2])
    n = int(ker.shape[0] / 2.)
    for i in range(n, A.shape[0] - n):
        B[i] = np.inner(A[i - n:i + n + 1], ker)
Exemple #23
0
    z1 = [z[i] for i in I]
    J1 = [J[i] for i in I]
    return z1, J1

def plot_D_data(data, label=None, num=None):
    fig, ax = plt.subplots(figsize=(5, 4), num=num)
    Z, D = zsorted(data, "D")
    # plot
    ax.plot(Z, D, ".-", label=label)
    ax.set_xlabel("z position of molecule [nm]")
    ax.set_ylabel(r"D/D0")
    ax.set_title("rel. diffusivity (2D model)")
    ax.legend(loc="best")

f.update()
data = f.get_fields("pugh_diff2D_backup", rMolecule=0.11)
                    #rMolecule=2.0779)
plot_D_data(data, "D")
#plt.show()
#exit()

# points
H = 50.
Z = np.linspace(-H, H, 96)
X = [[0.,0.,z] for z in Z]

fig_big, ax_big = plt.subplots(figsize=(10, 8), num="all")
fig_small, ax_small = plt.subplots(figsize=(6, 4), num="small")
# get data
for r in [0.152, 0.167, 0.25, 2.0779]:
Exemple #24
0
def load_results(name, **params):
    data = fields.get_fields(name, **params)
    data = nanopores.Params({k: _load(data[k]) for k in data})
    print "Found %d simulated events." % len(data.times)
    return data
Exemple #25
0
import numpy as np
import nanopores.tools.fields as f
import matplotlib.pyplot as plt
import os

HOME = os.path.expanduser("~")
PAPERDIR = os.path.join(HOME, "papers", "paper-howorka")
FIGDIR = os.path.join(PAPERDIR, "figures", "")

DATADIR = os.path.join(HOME, "Dropbox", "nanopores", "fields")
import nanopores.tools.fields as f
f.set_dir(DATADIR)
h = 2.
field = f.get_fields("pughcenter", bulkcon=1e3, Qmol=8, h=h)
z = [x[2] for x in field["x"]]
J = [j * 1e12 for j in field["J"]]
I = sorted(range(len(z)), key=lambda k: z[k])
z1 = [z[i] for i in I]
J1 = [J[i] for i in I]
from scipy.interpolate import interp1d
Jf = interp1d(z1, J1)
if __name__ == '__main__':
    plt.plot(z1, J1, "s-", label="molecule, h=%s" % h)
    plt.xlabel("z position of molecule [nm]")
    plt.ylabel("current [pA]")
    plt.title("current at -100mV for molecule along pore center")
    plt.legend()
    plt.tight_layout()
    plt.show()
    X = np.linspace(-30., 30., 200)
    plt.plot(X, Jf(X))
Exemple #26
0
DATADIR = os.path.join(HOME, "Dropbox", "nanopores", "fields")
f.set_dir_mega()

number = False

geop = nano.Params(pughpore.params)
hpore = geop.hpore
fieldsname = 'events3_onlyone_5'
params = dict(avgbind1=2e7,
              avgbind2=3e4,
              P_bind1=8.e-2,
              P_bind2=0 * 3e-1,
              z0=hpore / 2. + 0.)

#cmap=matplotlib.cm.get_cmap('viridis')
data = f.get_fields(fieldsname, **params)
figname = fieldsname + '_%.1e_%.1e_%.1e_%.1e' % (
    params["avgbind1"], params["avgbind2"], params["P_bind1"],
    params["P_bind2"]) + str(params["z0"])
t = data["t"]
tdata = np.array(t)
a = data["a"]
ood = data["ood"]
lendata = len(t)
fac = 1.
if max(t) < 1e-2:
    fac = 1e3
    t = [x * 1e3 for x in t]

P_bind1 = params["P_bind1"]
P_bind2 = params["P_bind2"]
Exemple #27
0
import os
import nanopores.tools.fields as f
HOME = os.path.expanduser("~")
PAPERDIR = os.path.join(HOME, "papers", "paper-howorka")
FIGDIR = os.path.join(PAPERDIR, "figures", "")
DATADIR = os.path.join(HOME, "Dropbox", "nanopores", "fields")
f.set_dir(DATADIR)

hpore = 46.
#fieldsname='number_of_collisions_all'
fieldsname = 'number_of_collisions'
params = dict(avgbind1=2e7, avgbind2=3e4, P_bind1=0., P_bind2=0.,
              z0=23.)  # old one interval lengths(4,8,13)
#params=dict(avgbind1=23e6,avgbind2=3e4,P_bind1=0*0.035,P_bind2=0*3e-1,z0=hpore/2.+0.) # for binding everywhere

data = f.get_fields(fieldsname, **params)
data2 = f.get_fields(fieldsname + '2', **params)
data3 = f.get_fields(fieldsname + '3', **params)
Nc = np.array(data["Nc"])
Nc2 = np.array(data2["Nc"])
Nc3 = np.array(data3["Nc"])
lam = np.mean(Nc)
lam2 = np.mean(Nc2)
lam3 = np.mean(Nc3)
k = np.arange(0, 21)


def P(k):
    return pow(lam, k) / (factorial(k)) * exp(-lam)