Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP - Stochastic Logistic Growth (ABC Toy problem) #1025

Merged
merged 32 commits into from
Jan 26, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
cdbecdb
initial commit of stochastic logistic toy model using spacially impli…
jarthur36 Dec 3, 2019
fdd6685
remove references to mol count and enforce line length limit
jarthur36 Dec 3, 2019
658ef6e
Add missing test and fix a few comments
jarthur36 Dec 3, 2019
7d02068
fix failing test
jarthur36 Dec 3, 2019
31ce1f2
reference new notebook in README
jarthur36 Dec 3, 2019
c441d24
Add rst file for new model
jarthur36 Jan 16, 2020
dd2ab75
add new rst file to toctree
jarthur36 Jan 16, 2020
6fbe7fb
Merge branch 'master' into 890-stochastic-logistic-toy-model
MichaelClerx Apr 14, 2020
e9ad195
Moved notebook
MichaelClerx Apr 14, 2020
8768cf8
Updated copyright notice.
MichaelClerx Apr 14, 2020
05cc311
Updated copyright notice.
MichaelClerx Apr 14, 2020
0ca5232
Fixed notebook name.
MichaelClerx Apr 14, 2020
1f99d35
Tweaks and add random seed
chonlei Nov 26, 2020
ceb16f8
Tiny fix
chonlei Nov 26, 2020
725e235
Adding model description
chonlei Nov 26, 2020
bead114
Adding model description
chonlei Nov 26, 2020
4bb9441
Make ref consistent
chonlei Nov 26, 2020
7a97f53
Adding model description
chonlei Nov 26, 2020
268e379
Fix typos in docs
chonlei Nov 26, 2020
69c8c37
Slight tweaks to the examples
chonlei Nov 26, 2020
2e52a42
Add reference
chonlei Nov 26, 2020
ed864bd
Merge branch 'master' into 890-stochastic-logistic-toy-model
chonlei Nov 26, 2020
e034d71
Non-ASCII issue
chonlei Nov 26, 2020
25f57a0
Fix typo
chonlei Nov 26, 2020
8432e43
Fix Non-ASCII character
chonlei Nov 26, 2020
c24a8ab
Fix bias in simulations
chonlei Nov 26, 2020
384890d
Hide simulate_raw and interpolate_values
chonlei Dec 7, 2020
78f0590
Fix style
chonlei Dec 7, 2020
c68422d
Change names, add comments to tests
chonlei Dec 7, 2020
988ae11
Update docs
chonlei Dec 7, 2020
1c2607e
Move variance check around
chonlei Dec 15, 2020
af3262e
Rearrange tests
chonlei Dec 15, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
192 changes: 192 additions & 0 deletions examples/toy-model-stochastic-logistic-growth.ipynb

Large diffs are not rendered by default.

105 changes: 105 additions & 0 deletions pints/tests/test_toy_stochastic_logistic_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
#!/usr/bin/env python3
#
# Tests if the stochastic degradation (toy) model works.
jarthur36 marked this conversation as resolved.
Show resolved Hide resolved
#
# This file is part of PINTS.
MichaelClerx marked this conversation as resolved.
Show resolved Hide resolved
# Copyright (c) 2017-2019, University of Oxford.
# For licensing information, see the LICENSE file distributed with the PINTS
# software package.
#
import unittest
import numpy as np
import pints
import pints.toy
from pints.toy import StochasticLogisticModel


class TestStochasticLogistic(unittest.TestCase):
chonlei marked this conversation as resolved.
Show resolved Hide resolved
"""
Tests if the stochastic degradation (toy) model works.
jarthur36 marked this conversation as resolved.
Show resolved Hide resolved
"""
def test_start_with_zero(self):
chonlei marked this conversation as resolved.
Show resolved Hide resolved
# Test the special case where the initial population count is zero
model = StochasticLogisticModel(0)
times = [0, 1, 2, 100, 1000]
parameters = [0.1, 50]
values = model.simulate(parameters, times)
self.assertEqual(len(values), len(times))
self.assertTrue(np.all(values == np.zeros(5)))

def test_start_with_one(self):
chonlei marked this conversation as resolved.
Show resolved Hide resolved
# Run small simulation
model = pints.toy.StochasticLogisticModel(1)
times = [0, 1, 2, 100, 1000]
parameters = [0.1, 50]
values = model.simulate(parameters, times)
self.assertEqual(len(values), len(times))
self.assertEqual(values[0], 1)
self.assertEqual(values[-1], 50)
self.assertTrue(np.all(values[1:] >= values[:-1]))

def test_suggested(self):
model = pints.toy.StochasticLogisticModel(1)
times = model.suggested_times()
parameters = model.suggested_parameters()
self.assertTrue(len(times) == 101)
self.assertTrue(np.all(parameters > 0))

def test_simulate(self):
times = np.linspace(0, 100, 101)
model = StochasticLogisticModel(1)
params = [0.1, 50]
time, mol_count = model.simulate_raw([0.1, 50])
values = model.interpolate_mol_counts(time, mol_count, times, params)
self.assertTrue(len(time), len(mol_count))

# Test output of Gillespie algorithm
self.assertTrue(np.all(mol_count ==
np.array(range(1, 51))))

# Check simulate function returns expected values
self.assertTrue(np.all(values[np.where(times < time[1])] == 1))

# Check interpolation function works as expected
temp_time = np.array([np.random.uniform(time[0], time[1])])
self.assertTrue(model.interpolate_mol_counts(time, mol_count,
temp_time, params)[0] == 1)
temp_time = np.array([np.random.uniform(time[1], time[2])])
self.assertTrue(model.interpolate_mol_counts(time, mol_count,
temp_time, params)[0] == 2)

def test_mean_variance(self):
# test mean
model = pints.toy.StochasticLogisticModel(1)
v_mean = model.mean([1, 10], [5, 10])
self.assertEqual(v_mean[0], 10 / (1 + 9 * np.exp(-5)))
self.assertEqual(v_mean[1], 10 / (1 + 9 * np.exp(-10)))

chonlei marked this conversation as resolved.
Show resolved Hide resolved
def test_errors(self):
model = pints.toy.StochasticLogisticModel(1)
# parameters, times cannot be negative
chonlei marked this conversation as resolved.
Show resolved Hide resolved
times = np.linspace(0, 100, 101)
parameters = [-0.1, 50]
self.assertRaises(ValueError, model.simulate, parameters, times)
self.assertRaises(ValueError, model.mean, parameters, times)

parameters = [0.1, -50]
self.assertRaises(ValueError, model.simulate, parameters, times)
self.assertRaises(ValueError, model.mean, parameters, times)

times_2 = np.linspace(-10, 10, 21)
parameters_2 = [0.1, 50]
self.assertRaises(ValueError, model.simulate, parameters_2, times_2)
self.assertRaises(ValueError, model.mean, parameters_2, times_2)

# this model should have 2 parameters
parameters_3 = [0.1]
self.assertRaises(ValueError, model.simulate, parameters_3, times)
self.assertRaises(ValueError, model.mean, parameters_3, times)

# Initial value can't be negative
self.assertRaises(ValueError, pints.toy.StochasticLogisticModel, -1)


if __name__ == '__main__':
unittest.main()
1 change: 1 addition & 0 deletions pints/toy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,4 @@
from ._sir_model import SIRModel # noqa
from ._twisted_gaussian_banana import TwistedGaussianLogPDF # noqa
from ._stochastic_degradation_model import StochasticDegradationModel # noqa
from ._stochastic_logistic_model import StochasticLogisticModel # noqa
131 changes: 131 additions & 0 deletions pints/toy/_stochastic_logistic_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
#
# Stochastic degradation toy model.
chonlei marked this conversation as resolved.
Show resolved Hide resolved
#
# This file is part of PINTS.
# Copyright (c) 2017-2019, University of Oxford.
# For licensing information, see the LICENSE file distributed with the PINTS
# software package.
#
from __future__ import absolute_import, division
from __future__ import print_function, unicode_literals
import numpy as np
from scipy.interpolate import interp1d
import pints

from . import ToyModel


class StochasticLogisticModel(pints.ForwardModel, ToyModel):
r"""
chonlei marked this conversation as resolved.
Show resolved Hide resolved

*Extends:* :class:`pints.ForwardModel`, :class:`pints.toy.ToyModel`.
"""

def __init__(self, initial_molecule_count=2):
super(StochasticLogisticModel, self).__init__()
self._n0 = float(initial_molecule_count)
if self._n0 < 0:
raise ValueError('Initial molecule count cannot be negative.')

def n_parameters(self):
""" See :meth:`pints.ForwardModel.n_parameters()`. """
return 2

def simulate_raw(self, parameters):
chonlei marked this conversation as resolved.
Show resolved Hide resolved
"""
Returns raw times, mol counts when reactions occur
jarthur36 marked this conversation as resolved.
Show resolved Hide resolved
"""
parameters = np.asarray(parameters)
if len(parameters) != self.n_parameters():
raise ValueError('This model should have only 2 parameters.')
b = parameters[0]
k = parameters[1]
if b <= 0:
raise ValueError('Rate constant must be positive.')

# Initial time and count
t = 0
a = self._n0

# Run stochastic logistic birth-only algorithm, calculating time until next
# reaction and increasing population count by 1 at that time
mol_count = [a]
time = [t]
while a < k:
r = np.random.uniform(0, 1)
t += np.log(1/r) / (a * b * (1 - a / k))
jarthur36 marked this conversation as resolved.
Show resolved Hide resolved
a = a + 1
time.append(t)
mol_count.append(a)
return time, mol_count

def interpolate_mol_counts(self, time, mol_count, output_times, parameters):
jarthur36 marked this conversation as resolved.
Show resolved Hide resolved
"""
Takes raw times and inputs and mol counts and outputs interpolated
values at output_times
"""
# Interpolate as step function, decreasing mol_count by 1 at each
# reaction time point
interp_func = interp1d(time, mol_count, kind='previous')

# Compute molecule count values at given time points using f1
# at any time beyond the last reaction, molecule count = 0
values = interp_func(output_times[np.where(output_times <= time[-1])])
zero_vector = np.full(
len(output_times[np.where(output_times > time[-1])])
, parameters[1])
values = np.concatenate((values, zero_vector))
return values

def simulate(self, parameters, times):
""" See :meth:`pints.ForwardModel.simulate()`. """
times = np.asarray(times)
if np.any(times < 0):
raise ValueError('Negative times are not allowed.')
if self._n0 == 0:
return np.zeros(times.shape)

# run Gillespie
time, mol_count = self.simulate_raw(parameters)

# interpolate
values = self.interpolate_mol_counts(time, mol_count, times, parameters)
return values

def mean(self, parameters, times):
MichaelClerx marked this conversation as resolved.
Show resolved Hide resolved
r"""
Returns the deterministic mean of infinitely many stochastic
simulations, which follows :math:`A(0) \exp(-kt)`.
jarthur36 marked this conversation as resolved.
Show resolved Hide resolved
"""
parameters = np.asarray(parameters)
if len(parameters) != self.n_parameters():
raise ValueError('This model should have only 2 parameters.')

b = parameters[0]
if b <= 0:
raise ValueError('Rate constant must be positive.')

k = parameters[1]
if k <= 0:
raise ValueError("Carrying capacity must be positive")

times = np.asarray(times)
if np.any(times < 0):
raise ValueError('Negative times are not allowed.')

return (self._n0 * k) / (self._n0 + np.exp(-b * times) * (k - self._n0))

def variance(self, parameters, times):
MichaelClerx marked this conversation as resolved.
Show resolved Hide resolved
r"""
Returns the deterministic variance of infinitely many stochastic
simulations.
"""
return NotImplementedError()
jarthur36 marked this conversation as resolved.
Show resolved Hide resolved

def suggested_parameters(self):
""" See :meth:`pints.toy.ToyModel.suggested_parameters()`. """
return np.array([0.1, 50])

def suggested_times(self):
""" See "meth:`pints.toy.ToyModel.suggested_times()`."""
return np.linspace(0, 100, 101)