def plot_gps_coordinates_in_meters(measured_gps, true_gps):
    measured_gps = position_tools.PositionTools.lat_lon_to_meters(measured_gps)
    true_gps = position_tools.PositionTools.lat_lon_to_meters([true_gps])

    fig, ax = plt.subplots(1, 1)
    plotting.plot_xy_coordinates(
        ax, measured_gps[0], measured_gps[1], {'marker': 'o', 'color': 'green'}
    )
    plotting.plot_xy_coordinates(
        ax, true_gps[0], true_gps[1],
        {'marker': 'o', 'color': 'red', 'markersize': 16}
    )
    plotting.label_axes(
        ax, 'Raised Stationary GPS Test (2)', 'Latitude (m)', 'Longitude (m)'
    )
    plt.show()
Пример #2
0
def plot_gps_coordinates_in_meters(measured_gps, true_gps):
    measured_gps = position_tools.PositionTools.lat_lon_to_meters(measured_gps)
    true_gps = position_tools.PositionTools.lat_lon_to_meters([true_gps])

    fig, ax = plt.subplots(1, 1)
    plotting.plot_xy_coordinates(ax, measured_gps[0], measured_gps[1], {
        'marker': 'o',
        'color': 'green'
    })
    plotting.plot_xy_coordinates(ax, true_gps[0], true_gps[1], {
        'marker': 'o',
        'color': 'red',
        'markersize': 16
    })
    plotting.label_axes(ax, 'Raised Stationary GPS Test (2)', 'Latitude (m)',
                        'Longitude (m)')
    plt.show()
Пример #3
0
ax.set_xscale('log')
ax.set_ylabel(r'$c_{\tilde \theta}(t)/c_{\theta}(t)$')
ax.set_xlabel(r'$\lambda t/K$')
#ax.legend(title=r'$\tilde \theta$', ncol=2, loc='lower center')
ax.set_ylim(0.95, 1.35)

if False:
    ax = axes[2]
    dfg = df[df['T'] == 1 * N].groupby(['T'])
    for T, dfgg in dfg:
        refcost = float(
            dfgg[np.abs(dfgg['theta0prior'] - theta0) < 1e-3]['cost'])
        ax.errorbar(dfgg['theta0prior'],
                    dfgg['cost'] / refcost,
                    dfgg['costse'] / refcost,
                    label='%g' % (T / N),
                    c=colors_T[Ts.index(T)])
    ax.set_xscale('log')
    ax.set_xlabel(r'prior, $\tilde \theta$')
    ax.set_ylabel(r'$c_{\tilde \theta}(K/\lambda)/c_{\theta}(K/\lambda)$')
    #ax.legend(title=r'$\lambda t/K$', loc='upper center', ncol=2)
    ax.set_ylim(0.95, 1.35)

for ax in axes:
    plotting.despine(ax)
plotting.label_axes(axes, xy=(-0.22, 0.95))

fig.tight_layout()
fig.savefig('figS2.svg')
fig.savefig('figS2.png', dpi=300)
Пример #4
0
            except:
                pass


    axm.set_ylim(evolimmune.to_tau(df.aenv.min()), evolimmune.to_tau(df.aenv.max()))
    axm.set_yscale('log')
    axm.yaxis.set_major_formatter(ticker.ScalarFormatter())
    axm.set_xlabel('$\pi_{env}$')
    axm.set_ylabel(r'$\tau_{env}$')
    axm.grid(which='major', alpha=0.75)
    axm.grid(which='minor', lw=0.4, alpha=0.5)
    axm.set_axisbelow(False)
    plotting.despine(axm, spines='all')
    label_axes.append((i, axlambda))
label_axes = [ax for i, ax in sorted(label_axes)]
plotting.label_axes(label_axes, xy=(-0.6, 1.0), fontsize='large', va='top')
gsglobal.tight_layout(fig, h_pad=1.0, w_pad=2.0)
fig.savefig('SIaltphases.pdf')
fig.savefig('SIaltphases.svg')


# Fig.S2: **Influence of parameter choice on the phase diagram presented in Fig. 2.**
# For every panel the parameter choices are shown on the left and the phase boundaries between **p**roto-adaptive, **i**nnate, **i**nnate **b**et hedging, **m**ixed and **C**RISPR-like strategies are shown on the right. As a reference, lines in lighter color show trade-off and uptake cost for parameter set used in Fig. 2.
# **(A)** Phase diagram for parameters used in Fig. 2.
# **(B)** More expensive active acquisition ($c_{\rm uptake}$ multiplied by a factor of two).
# **(C)** Different functional form for cost of active acqusition: $c_{\rm uptake} = 0.05 \times p_{\rm uptake} + 2 \times p_{\rm uptake}^2$.
# **(D)** More permissive state-dependent costs (costs multiplied by a factor of 0.5).
# **(E)** Less permissive state-dependent costs (costs multiplied by a factor of 1.5).
# **(F)** Higher cost of infection.
# **(G)** Higher cost of immune protection.
# **(H)** Different functional form for cost trade-off, $c_{\rm defense} = 1.4-0.6\times c_{\rm constitutive}+0.2 \times c_{\rm constitutive}^2$
Пример #5
0
          bbox_transform=plt.gcf().transFigure,
          ncol=4)
for ax in analysis.flatten(axes[:-1, :]):
    plt.setp(ax.get_xticklabels(), visible=False)
for ax in analysis.flatten(axes[:, 1:]):
    plt.setp(ax.get_yticklabels(), visible=False)
for ax in axes[-1, :]:
    ax.set_xlabel(varname_to_tex['tauenv'])
for j, var in enumerate(variables):
    axes[j, 0].set_ylabel(varname_to_tex[var])
plotting.label_axes(axes[0, :],
                    labels=[
                        (varname_to_tex['pienv'][1:-1] + r'\, = \, %s' % val)
                        for val in columns
                    ],
                    labelstyle='$%s$',
                    xy=(.5, 0.9),
                    xycoords=('axes fraction', 'figure fraction'),
                    fontweight='bold',
                    fontsize='medium',
                    verticalalignment='top',
                    horizontalalignment='center')
fig.tight_layout(h_pad=1.5, w_pad=1.0, rect=(0.0, 0.0, 1.0, 0.87), pad=0.25)
fig.savefig('SIevol.pdf')
fig.savefig('SIevol.svg')

# **Influence of finite population size on optimal immune strategies from an agent-based simulation with evolving strategy parameters (switching rates and degree of adaptability) as described in the text.**
# For the infinite population, $p$ is only shown for $q > 0$, because for $q = 0$ the value of $p$ is not constrained other than being positive.
# Subplots show the median (solid line) and interquartile range (shaded area) of the strategy parameters at the end of a simulation of $100000$ generations length.
# Both are calculated from 500 independent simulations.
# In each simulation, the strategy parameters evolve from a random initial distribution via mutation and selection.
# Mutations take place with a rate $0.01 \exp(-t/10000)$ per generation and are normally distributed with mean zero and standard deviation $0.25 \exp(-t/10000)$.
Пример #6
0
    xs = odeint(fcompfull, [T1, C], ts, args=(alpha, mu, K2, delta))
    ax.plot(ts, xs[:, 0], color=ls[1].get_color(), ls='--')

    #alpha = 2.4
    mu = -0.5

    ax = axes[3]
    xs = odeint(ftwospecifities, [T1, T2, C], ts, args=(alpha, mu, K1, K2, delta))
    ls = [ax.plot(ts, xs[:, i], linestyles[i], c=colors[i])[0] for i in range(3)]
    xs = odeint(fcompfull, [T1, C], ts, args=(alpha, mu, K1, delta))
    ax.plot(ts, xs[:, 0], color=ls[0].get_color(), ls='--')
    xs = odeint(fcompfull, [T2, C], ts, args=(alpha, mu, K2, delta))
    ax.plot(ts, xs[:, 0], color=ls[1].get_color(), ls='--')

for ax in axes:
    #ax.grid()
    ax.set_ylim(1e0, 1e4)
    ax.set_xlim(min(ts), max(ts))
    ax.set_yscale('log')
    ax.set_yticks(np.logspace(0, 3, 4))
    ax.set_xticks(np.arange(0, 7, 2))
for ax in axarr[:, 0]:
    #ax.set_ylabel('T cell | pMHC number')
    ax.set_ylabel('Number')
for ax in axarr[1, :]:
    ax.set_xlabel('Time in days')
plotting.label_axes(axes, labelstyle='%s', xy=(-0.13, 1.0), fontweight='bold', fontsize=10, va='top')
fig.tight_layout(pad=0.25)
fig.savefig('fig3.svg')
fig.savefig('fig3.png', dpi=300)
Пример #7
0
            except:
                pass

    axm.set_ylim(evolimmune.to_tau(df.aenv.min()),
                 evolimmune.to_tau(df.aenv.max()))
    axm.set_yscale('log')
    axm.yaxis.set_major_formatter(ticker.ScalarFormatter())
    axm.set_xlabel('$\pi_{env}$')
    axm.set_ylabel(r'$\tau_{env}$')
    axm.grid(which='major', alpha=0.75)
    axm.grid(which='minor', lw=0.4, alpha=0.5)
    axm.set_axisbelow(False)
    plotting.despine(axm, spines='all')
    label_axes.append((i, axlambda))
label_axes = [ax for i, ax in sorted(label_axes)]
plotting.label_axes(label_axes, xy=(-0.6, 1.0), fontsize='large', va='top')
gsglobal.tight_layout(fig, h_pad=1.0, w_pad=2.0)
fig.savefig('SIaltphases.pdf')
fig.savefig('SIaltphases.svg')

# Fig.S2: **Influence of parameter choice on the phase diagram presented in Fig. 2.**
# For every panel the parameter choices are shown on the left and the phase boundaries between **p**roto-adaptive, **i**nnate, **i**nnate **b**et hedging, **m**ixed and **C**RISPR-like strategies are shown on the right. As a reference, lines in lighter color show trade-off and uptake cost for parameter set used in Fig. 2.
# **(A)** Phase diagram for parameters used in Fig. 2.
# **(B)** More expensive active acquisition ($c_{\rm uptake}$ multiplied by a factor of two).
# **(C)** Different functional form for cost of active acqusition: $c_{\rm uptake} = 0.05 \times p_{\rm uptake} + 2 \times p_{\rm uptake}^2$.
# **(D)** More permissive state-dependent costs (costs multiplied by a factor of 0.5).
# **(E)** Less permissive state-dependent costs (costs multiplied by a factor of 1.5).
# **(F)** Higher cost of infection.
# **(G)** Higher cost of immune protection.
# **(H)** Different functional form for cost trade-off, $c_{\rm defense} = 1.4-0.6\times c_{\rm constitutive}+0.2 \times c_{\rm constitutive}^2$
Пример #8
0
ax.set_xscale('log')
ax.set_xlabel(r'$\lambda t_e/K \theta$' +
              '\n remembered encounters per\n eff. number of pathogens')
ax.set_ylabel('relative cost gap\n' + '$(c - c_\infty)/ (c_0 - c_\infty)$')
ax.legend(handles, Ks, title=r'$K$', ncol=1, loc='lower left')
ax.set_xticks(np.logspace(-2, 2, 5, base=10))
ax.set_xlim(5e-3, 2e2)

for ax in axes[:2]:
    ax.set_xticks(np.logspace(0, 4, 5, base=10))
    ax.set_xlim(2.0, 2e4)

for ax in axes:
    ax.set_ylim(0, 1.05)
    plotting.despine(ax)
plotting.label_axes(fig, xy=(-0.25, 1.0))

fig.tight_layout()
fig.savefig('fig3.svg')
fig.savefig('fig3.png', dpi=300)

fig, ax = plt.subplots(figsize=(3.5, 2.75))
theta0s = sorted(dfmean.theta0.unique())
theta0_to_color = dict(zip(theta0s, colors[:len(theta0s)]))
Ks = np.asarray(dfmean.K.unique(), dtype=int)
lss = ['o', 's', 'x', '+', '>']
K_to_ls = dict(zip(Ks, lss[:len(Ks)]))
handles = []

ax.plot(dfmean['relcounts'],
        dfmean['rcg'],
Пример #9
0
for i in range(len(npzs)):
    for j in range(2):
        costs = [1.0]
        costs.extend(mecosts[i][:, j] / c0)
        l, = ax.plot(bins[i] / lambda_,
                     costs,
                     label='%g' % tauc[i] if j == 0 else None,
                     ls=lss[j],
                     color=colors[i + 8])
        if i == 0:
            ls.append(l)
leg1 = ax.legend(title=r'$\tau_c$', ncol=1, loc='upper left')
leg = ax.legend(title='attrition',
                handles=ls,
                labels=['yes', 'no'],
                loc='lower center',
                ncol=2)
for handle in leg.legendHandles:
    handle.set_color('k')
ax.add_artist(leg1)
ax.set_ylabel('Relative cost $c/c_0$')

ax.set_xlim(0.0, 60)
ax.set_ylim(0.0, 1.0)
ax.set_xlabel('Age in years')

plotting.label_axes(fig)
fig.tight_layout()
fig.savefig('fig5.svg')
fig.savefig('fig5.png', dpi=300)
Пример #10
0
    
    ax = axes[1]
    corr = (ps[:, 3]-E1*E2)/((E1*(1-E1))**.5 * (E2*(1-E2))**.5)
    ax.plot(nus, corr)
    ax.set_ylabel('protection\ncorrelation coefficient')
    ax.set_xlabel(r'non-additivity of costs $\nu$')
    ax.set_ylim(-1.02, 1.02)
    for ax in axes:
        ax.locator_params(nbins=5)
        ax.grid()
        plotting.despine(ax)
    fig.tight_layout()
    return fig


# In[6]:

fig = plot_pcov(ps)
plotting.label_axes(fig, xy=(-0.15, 0.97))
fig.savefig('SIniinfection.pdf')
fig.savefig('SIniinfection.svg')


# **Optimal protection strategy against two equally frequent pathogens $\pi_{\rm env, 1} = \pi_{\rm env, 2} = 0.4$ as a function of the degree of non-additivity of the cost of infection $\nu$.**
# **(A)** Fraction of population protected against a particular pathogen. **(B)** Pearson correlation coefficient between the protection states against the two pathogens. As costs are non-additive, the problem no longer factorizes and the optimal strategy no longer chooses protections against different pathogens independently. However, here the optimal strategy treats each pathogen almost indendently, as measured by the low correlation coefficient. With an increasing cost of co-infection, more protection is needed, in agreement with our intuition that co-infection leads to higher effective costs. Parameters: $c_{\rm infection} = 2$, $c_{\rm defense} = c_{\rm constitutive} = 1$, optimization of the distribution over protection states respecting the probability simplex constraints using an accelerated projected gradient algorithm as described in [Mayer et.al. 2015].

# In[ ]:



Пример #11
0
           label='Experiment')
ts = [4.0, 7.0]
T6s = []
Ks = np.logspace(-.5, 3.5)
for K in Ks:
    xs = odeint(fsaturation, [T0, C0], ts, args=(alpha, mu, K, delta))
    T6s.append(xs[-1, 0])
ax.plot(Ks, np.array(T6s) / T0, c=colors[0], label='Model')
leg = ax.legend(loc='lower left')
leg.legendHandles[1].set_color('.2')
ax.set_xscale('log')
ax.set_yscale('log')
ax.xaxis.set_major_formatter(formatter)
ax.yaxis.set_major_formatter(formatter)
ax.set_xlim(5e-1, 2e3)
ax.set_xlabel('rel. pMHC concentration\nfor half max. response')
ax.set_ylabel('Fold expansion')

for ax in axes:
    ax.set_ylim(0.5, 3e2)
if not talk:
    plotting.label_axes(axes,
                        labelstyle='%s',
                        xy=(-0.3, 0.94),
                        fontweight='bold',
                        fontsize=10)

fig.tight_layout(pad=0.25, w_pad=0.0)
fig.savefig('fig2%s.png' % ('talk' if talk else ''), dpi=300)
fig.savefig('fig2%s.svg' % ('talk' if talk else ''))
Пример #12
0
        ax.margins(x=xmargin, y=ymargin*dlim)
        plotting.despine(ax, spines='all')
        ax.grid()
        ax.locator_params(axis='y', nbins=5)
ax.legend(loc='upper center', title='population size', bbox_to_anchor=(0.54, 1),
           bbox_transform=plt.gcf().transFigure, ncol=4)
for ax in analysis.flatten(axes[:-1, :]):
    plt.setp(ax.get_xticklabels(), visible=False)
for ax in analysis.flatten(axes[:, 1:]):
    plt.setp(ax.get_yticklabels(), visible=False)
for ax in axes[-1, :]:
    ax.set_xlabel(varname_to_tex['tauenv'])
for j, var in enumerate(variables):
    axes[j, 0].set_ylabel(varname_to_tex[var])
plotting.label_axes(axes[0, :], labels=[(varname_to_tex['pienv'][1:-1] + r'\, = \, %s' % val) for val in columns],
                    labelstyle='$%s$',
                    xy=(.5, 0.9), xycoords=('axes fraction', 'figure fraction'), fontweight = 'bold', fontsize='medium',
                    verticalalignment='top', horizontalalignment='center')
fig.tight_layout(h_pad=1.5, w_pad=1.0, rect=(0.0, 0.0, 1.0, 0.87), pad=0.25)
fig.savefig('SIevol.pdf')
fig.savefig('SIevol.svg')


# **Influence of finite population size on optimal immune strategies from an agent-based simulation with evolving strategy parameters (switching rates and degree of adaptability) as described in the text.**
# For the infinite population, $p$ is only shown for $q > 0$, because for $q = 0$ the value of $p$ is not constrained other than being positive.
# Subplots show the median (solid line) and interquartile range (shaded area) of the strategy parameters at the end of a simulation of $100000$ generations length.
# Both are calculated from 500 independent simulations.
# In each simulation, the strategy parameters evolve from a random initial distribution via mutation and selection.
# Mutations take place with a rate $0.01 \exp(-t/10000)$ per generation and are normally distributed with mean zero and standard deviation $0.25 \exp(-t/10000)$.
# The bound constraints on the parameters were enforced by setting the strategy parameters to the boundary value if outside after a mutation.
# Costs of different immune states as in Fig. 2.
    ax = axes[0]
    ax.plot(nus, E1)
    ax.set_xlim(min(nus), max(nus))
    ax.set_ylabel('fraction protected')

    ax = axes[1]
    corr = (ps[:, 3] - E1 * E2) / ((E1 * (1 - E1))**.5 * (E2 * (1 - E2))**.5)
    ax.plot(nus, corr)
    ax.set_ylabel('protection\ncorrelation coefficient')
    ax.set_xlabel(r'non-additivity of costs $\nu$')
    ax.set_ylim(-1.02, 1.02)
    for ax in axes:
        ax.locator_params(nbins=5)
        ax.grid()
        plotting.despine(ax)
    fig.tight_layout()
    return fig


# In[6]:

fig = plot_pcov(ps)
plotting.label_axes(fig, xy=(-0.15, 0.97))
fig.savefig('SIniinfection.pdf')
fig.savefig('SIniinfection.svg')

# **Optimal protection strategy against two equally frequent pathogens $\pi_{\rm env, 1} = \pi_{\rm env, 2} = 0.4$ as a function of the degree of non-additivity of the cost of infection $\nu$.**
# **(A)** Fraction of population protected against a particular pathogen. **(B)** Pearson correlation coefficient between the protection states against the two pathogens. As costs are non-additive, the problem no longer factorizes and the optimal strategy no longer chooses protections against different pathogens independently. However, here the optimal strategy treats each pathogen almost indendently, as measured by the low correlation coefficient. With an increasing cost of co-infection, more protection is needed, in agreement with our intuition that co-infection leads to higher effective costs. Parameters: $c_{\rm infection} = 2$, $c_{\rm defense} = c_{\rm constitutive} = 1$, optimization of the distribution over protection states respecting the probability simplex constraints using an accelerated projected gradient algorithm as described in [Mayer et.al. 2015].

# In[ ]:
Пример #14
0
fig, axes = plt.subplots(figsize=(1.75, 3.1), nrows=3, sharex=True)
plot_kinetics(Cfactor=2e6,
              T0=1e2,
              alpha=2.47,
              mu=3.1,
              K=1e1,
              delta=0.23,
              tau=0.5,
              axes=axes,
              lspmhc='-',
              arrows=False)
axes[2].set_xticks(np.arange(0, 8, 2))
axes[2].set_yticks(10**np.arange(2, 7, 2))
axes[1].set_yticks(10**np.arange(2, 7, 2))
plotting.label_axes(axes, xy=(-0.65, 0.95), labelstyle='%s', fontweight='bold')
fig.tight_layout(pad=0.1)

fig.savefig('fig4ABC%s.png' % ('talk' if talk else ''), dpi=300)
fig.savefig('fig4ABC%s.svg' % ('talk' if talk else ''))

fig, axes = plt.subplots(figsize=(1.75, 2.9), nrows=2)
Cfactor = 2e6
T6s = []
ax = axes[0]
protocols = [(res.x, 'Optimal'), (5.0**np.arange(N), 'Experiment')]
colorsh = ['k', colors[1]]
for i, (x, label) in enumerate(protocols):
    x /= np.sum(x)
    T6 = Tday6(x, xt)
    print(T6)