- 
                Notifications
    
You must be signed in to change notification settings  - Fork 34
 
WIP - Stochastic Logistic Growth (ABC Toy problem) #1025
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
          
     Merged
      
      
    
  
     Merged
                    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 fdd6685
              
                remove references to mol count and enforce line length limit
              
              
                jarthur36 658ef6e
              
                Add missing test and fix a few comments
              
              
                jarthur36 7d02068
              
                fix failing test
              
              
                jarthur36 31ce1f2
              
                reference new notebook in README
              
              
                jarthur36 c441d24
              
                Add rst file for new model
              
              
                jarthur36 dd2ab75
              
                add new rst file to toctree
              
              
                jarthur36 6fbe7fb
              
                Merge branch 'master' into 890-stochastic-logistic-toy-model
              
              
                MichaelClerx e9ad195
              
                Moved notebook
              
              
                MichaelClerx 8768cf8
              
                Updated copyright notice.
              
              
                MichaelClerx 05cc311
              
                Updated copyright notice.
              
              
                MichaelClerx 0ca5232
              
                Fixed notebook name.
              
              
                MichaelClerx 1f99d35
              
                Tweaks and add random seed
              
              
                chonlei ceb16f8
              
                Tiny fix
              
              
                chonlei 725e235
              
                Adding model description
              
              
                chonlei bead114
              
                Adding model description
              
              
                chonlei 4bb9441
              
                Make ref consistent
              
              
                chonlei 7a97f53
              
                Adding model description
              
              
                chonlei 268e379
              
                Fix typos in docs
              
              
                chonlei 69c8c37
              
                Slight tweaks to the examples
              
              
                chonlei 2e52a42
              
                Add reference
              
              
                chonlei ed864bd
              
                Merge branch 'master' into 890-stochastic-logistic-toy-model
              
              
                chonlei e034d71
              
                Non-ASCII issue
              
              
                chonlei 25f57a0
              
                Fix typo
              
              
                chonlei 8432e43
              
                Fix Non-ASCII character
              
              
                chonlei c24a8ab
              
                Fix bias in simulations
              
              
                chonlei 384890d
              
                Hide simulate_raw and interpolate_values
              
              
                chonlei 78f0590
              
                Fix style
              
              
                chonlei c68422d
              
                Change names, add comments to tests
              
              
                chonlei 988ae11
              
                Update docs
              
              
                chonlei 1c2607e
              
                Move variance check around
              
              
                chonlei af3262e
              
                Rearrange tests
              
              
                chonlei File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
      
      Oops, something went wrong.
      
    
  
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | 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. | ||
| # | ||
| # This file is part of PINTS. | ||
                
      
                  MichaelClerx marked this conversation as resolved.
               
              
                Outdated
          
            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.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| """ | ||
| Tests if the stochastic degradation (toy) model works. | ||
                
      
                  jarthur36 marked this conversation as resolved.
               
              
                Outdated
          
            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.
               
              
                Outdated
          
            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() | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| # | ||
| # Stochastic degradation toy model. | ||
                
      
                  chonlei marked this conversation as resolved.
               
              
                Outdated
          
            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.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| """ | ||
| Returns raw times, mol counts when reactions occur | ||
                
      
                  jarthur36 marked this conversation as resolved.
               
              
                Outdated
          
            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.
               
              
                Outdated
          
            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.
               
              
                Outdated
          
            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.
               
              
                Outdated
          
            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.
               
              
                Outdated
          
            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) | ||
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.