Skip to content

Commit

Permalink
Create MakeTestLSP, a class that makes test LocalSpeciesPopulation ob…
Browse files Browse the repository at this point in the history
…jects. Also clean up some imports of LocalSpeciesPopulation.
  • Loading branch information
artgoldberg committed Jun 4, 2018
1 parent a3a76d8 commit 214f8e7
Show file tree
Hide file tree
Showing 5 changed files with 96 additions and 16 deletions.
1 change: 0 additions & 1 deletion tests/multialgorithm/test_multialgorithm_simulation.py
Expand Up @@ -24,7 +24,6 @@
BiomassComponent, BiomassReaction, StopCondition)
from wc_lang.prepare import PrepareModel, CheckModel
from wc_lang.transform import SplitReversibleReactionsTransform
from wc_sim.multialgorithm.species_populations import LocalSpeciesPopulation
from wc_sim.multialgorithm.make_models import MakeModels
from wc_sim.multialgorithm.model_utilities import ModelUtilities
from wc_sim.multialgorithm.multialgorithm_simulation import MultialgorithmSimulation
Expand Down
52 changes: 37 additions & 15 deletions tests/multialgorithm/test_species_populations.py
@@ -1,4 +1,4 @@
""" Test species_populations.py.
""" Test species_populations.py
:Author: Arthur Goldberg, Arthur.Goldberg@mssm.edu
:Date: 2017-02-04
Expand All @@ -25,7 +25,7 @@
from wc_sim.core.simulation_message import SimulationMessage
from wc_sim.multialgorithm import message_types
from wc_sim.multialgorithm.species_populations import (LOCAL_POP_STORE, Specie, SpeciesPopSimObject,
SpeciesPopulationCache, LocalSpeciesPopulation, AccessSpeciesPopulations)
SpeciesPopulationCache, LocalSpeciesPopulation, MakeTestLSP, AccessSpeciesPopulations)
from wc_sim.multialgorithm.multialgorithm_errors import NegativePopulationError, SpeciesPopulationError
from wc_sim.multialgorithm.submodels.skeleton_submodel import SkeletonSubmodel
from wc_sim.multialgorithm import distributed_properties
Expand All @@ -41,6 +41,7 @@ def specie_l(l):
remote_pop_stores = {store_i(i):None for i in range(1, 4)}
species_ids = [specie_l(l) for l in list(string.ascii_lowercase)[0:5]]


class TestAccessSpeciesPopulations(unittest.TestCase):

MODEL_FILENAME = os.path.join(os.path.dirname(__file__), 'fixtures',
Expand Down Expand Up @@ -411,6 +412,29 @@ def test_mass(self):
self.assertIn("molecular weight not available for '{}'".format(unknown_species),
str(context.exception))

def test_make_test_lsp(self):
make_test_lsp = MakeTestLSP()
self.assertEqual(make_test_lsp.num_species, MakeTestLSP.DEFAULT_NUM_SPECIES)
self.assertEqual(make_test_lsp.all_pops, MakeTestLSP.DEFAULT_ALL_POPS)
self.assertEqual(make_test_lsp.all_mol_weights, MakeTestLSP.DEFAULT_ALL_MOL_WEIGHTS)
kwargs = dict(
num_species=7,
all_pops=3E4,
all_mol_weights=1000
)
make_test_lsp = MakeTestLSP(**kwargs)
self.assertEqual(make_test_lsp.num_species, kwargs['num_species'])
self.assertEqual(make_test_lsp.all_pops, kwargs['all_pops'])
self.assertEqual(make_test_lsp.all_mol_weights, kwargs['all_mol_weights'])
self.assertEqual(make_test_lsp.local_species_pop.read_one(0, 'specie_1[comp_id]'), kwargs['all_pops'])
name = 'foo'
make_test_lsp_3 = MakeTestLSP(name=name, initial_population=make_test_lsp.initial_population)
self.assertEqual(make_test_lsp_3.initial_population, make_test_lsp.initial_population)
make_test_lsp_4 = MakeTestLSP(initial_population=make_test_lsp.initial_population,
molecular_weights=make_test_lsp.molecular_weights)
self.assertEqual(make_test_lsp_4.initial_population, make_test_lsp.initial_population)
self.assertEqual(make_test_lsp_4.molecular_weights, make_test_lsp.molecular_weights)

"""
todo: test the distributed property MASS
def test_mass(self):
Expand All @@ -427,12 +451,10 @@ def test_mass(self):
class TestSpeciesPopulationCache(unittest.TestCase):

def setUp(self):
species_nums = range(1, 5)
self.species_ids = list(map(lambda x: "specie_{}".format(x), species_nums))
self.init_populations = dict(zip(self.species_ids, [0]*len(self.species_ids)))
self.molecular_weights = self.init_populations
local_species_population = LocalSpeciesPopulation('name', self.init_populations,
self.molecular_weights)
kwargs = dict(num_species=4, all_pops=0, all_mol_weights=0)
make_test_lsp = MakeTestLSP(**kwargs)
self.species_ids = make_test_lsp.species_ids
local_species_population = make_test_lsp.local_species_pop

remote_pop_stores = {store_i(i):None for i in range(1, 4)}
self.an_ASP = AccessSpeciesPopulations(local_species_population, remote_pop_stores)
Expand All @@ -455,10 +477,10 @@ def test_species_population_cache_exceptions(self):
self.assertIn("some species are stored in the AccessSpeciesPopulations's local store: "
"['specie_0'].", str(context.exception))

self.species_population_cache.cache_population(0, {"specie_1": 3})
self.species_population_cache.cache_population(0, {"specie_1[comp_id]": 3})
with self.assertRaises(SpeciesPopulationError) as context:
self.species_population_cache.cache_population(-1, {"specie_1": 3})
self.assertIn("cache_population: caching an earlier population: specie_id: specie_1; "
self.species_population_cache.cache_population(-1, {"specie_1[comp_id]": 3})
self.assertIn("cache_population: caching an earlier population: specie_id: specie_1[comp_id]; "
"current time: -1 <= previous time 0.", str(context.exception))

with self.assertRaises(SpeciesPopulationError) as context:
Expand All @@ -467,8 +489,8 @@ def test_species_population_cache_exceptions(self):
str(context.exception))

with self.assertRaises(SpeciesPopulationError) as context:
self.species_population_cache.read_one(1, 'specie_1')
self.assertIn("cache age of 1 too big for read at time 1 of specie 'specie_1'",
self.species_population_cache.read_one(1, 'specie_1[comp_id]')
self.assertIn("cache age of 1 too big for read at time 1 of specie 'specie_1[comp_id]'",
str(context.exception))

with self.assertRaises(SpeciesPopulationError) as context:
Expand All @@ -477,8 +499,8 @@ def test_species_population_cache_exceptions(self):
str(context.exception))

with self.assertRaises(SpeciesPopulationError) as context:
self.species_population_cache.read(1, ['specie_1'])
self.assertIn(".read: species ['specie_1'] not reading recently cached value(s)",
self.species_population_cache.read(1, ['specie_1[comp_id]'])
self.assertIn(".read: species ['specie_1[comp_id]'] not reading recently cached value(s)",
str(context.exception))


Expand Down
1 change: 1 addition & 0 deletions wc_sim/multialgorithm/dynamic_components.py
Expand Up @@ -14,6 +14,7 @@
from obj_model import utils
from wc_lang.core import Species, SpeciesType, Compartment
from wc_sim.multialgorithm.multialgorithm_errors import MultialgorithmError
from wc_sim.multialgorithm.species_populations import LocalSpeciesPopulation


class DynamicCompartment(object):
Expand Down
1 change: 1 addition & 0 deletions wc_sim/multialgorithm/multialgorithm_checkpointing.py
Expand Up @@ -16,6 +16,7 @@
from wc_sim.core.sim_metadata import SimulationMetadata
from wc_sim.multialgorithm.submodels.ssa import SSASubmodel
from wc_sim.multialgorithm.multialgorithm_errors import MultialgorithmError
from wc_sim.multialgorithm.species_populations import LocalSpeciesPopulation


class MultialgorithmCheckpoint(Checkpoint):
Expand Down
57 changes: 57 additions & 0 deletions wc_sim/multialgorithm/species_populations.py
Expand Up @@ -932,6 +932,63 @@ def __str__(self):
return '\n'.join(state)


class MakeTestLSP(object):
""" Make a LocalSpeciesPopulation for testing
Because a LocalSpeciesPopulation takes about 10 lines of code to make, and they're
widely needed for testing wc_sim, provide a configurable class that creates a test LSP.
Attributes:
local_species_pop (:obj:`LocalSpeciesPopulation`): the `LocalSpeciesPopulation` created
"""
DEFAULT_NUM_SPECIES = 10
DEFAULT_ALL_POPS = 1E6
DEFAULT_ALL_MOL_WEIGHTS = 50
def __init__(self, name=None, initial_population=None, molecular_weights=None, initial_fluxes=None,
retain_history=True, **kwargs):
""" Initialize a `MakeTestLSP` object
All initialized arguments are applied to the local species population being created.
Valid keys in `kwargs` are `num_species`, `all_pops`, and `all_mol_weights`, which default to
`MakeTestLSP.DEFAULT_NUM_SPECIES`, `MakeTestLSP.DEFAULT_ALL_POPS`, and
`MakeTestLSP.DEFAULT_ALL_MOL_WEIGHTS`, respectively. These make a uniform population of
num_species, with population of all_pops, and molecular weights of all_mol_weights
Args:
name (:obj:`str`, optional): the name of the local species population being created
initial_population (:obj:`dict` of `float`, optional): initial population for some species;
dict: specie_id -> initial_population
molecular_weights (:obj:`dict` of `float`, optional): map: specie_id -> molecular_weight,
provided for computing the mass of lists of species in a `LocalSpeciesPopulation`
initial_fluxes (:obj:`dict` of `float`, optional): map: specie_id -> initial_flux;
initial fluxes for all species whose populations are estimated by a continuous
submodel. Fluxes are ignored for species not specified in initial_population.
retain_history (:obj:`bool`, optional): whether to retain species population history
"""
name = 'test_lsp' if name is None else name
if initial_population is None:
self.num_species = kwargs['num_species'] if 'num_species' in kwargs else MakeTestLSP.DEFAULT_NUM_SPECIES
self.species_nums = list(range(0, self.num_species))
self.all_pops = kwargs['all_pops'] if 'all_pops' in kwargs else MakeTestLSP.DEFAULT_ALL_POPS
comp_id = 'comp_id'
self.species_ids = list(map(lambda x: "specie_{}[{}]".format(x, comp_id), self.species_nums))
self.initial_population = dict(zip(self.species_ids, [self.all_pops]*len(self.species_nums)))
else:
self.initial_population = initial_population
self.species_ids = list(initial_population.keys())

if molecular_weights is None:
if 'all_mol_weights' in kwargs:
self.all_mol_weights = kwargs['all_mol_weights']
else:
self.all_mol_weights = MakeTestLSP.DEFAULT_ALL_MOL_WEIGHTS
self.molecular_weights = dict(zip(self.species_ids, [self.all_mol_weights]*len(self.species_ids)))
else:
self.molecular_weights = molecular_weights
self.local_species_pop = LocalSpeciesPopulation(name, self.initial_population, self.molecular_weights,
initial_fluxes=initial_fluxes, retain_history=initial_fluxes)


# TODO(Arthur): cover after MVP wc_sim done
class SpeciesPopSimObject(LocalSpeciesPopulation, ApplicationSimulationObject,
metaclass=AppSimObjAndABCMeta): # pragma: no cover
Expand Down

0 comments on commit 214f8e7

Please sign in to comment.