def test_update_rbs():
    T = Species("T")
    D = Species("D")
    P = Species("P")
    rbs = RBS("rbs")
    mech = Mechanism(name="mech", mechanism_type="assembly")

    ass = DNAassembly("ass",
                      rbs=None,
                      promoter=None,
                      transcript=T,
                      dna=D,
                      protein=P,
                      mechanisms=[mech])
    ass.update_rbs(rbs)

    #test copying
    assert ass.rbs != rbs
    assert type(ass.rbs) == type(rbs)
    assert ass.rbs.name == rbs.name

    #test resetting transcript
    assert ass.rbs.protein == P

    #test mechanism inheritance
    assert mech.mechanism_type in ass.rbs.mechanisms
def test_old_reaction_interface_non_massaction():
    kb = 100
    ku = 10
    kex = 1.

    G = Species(name="G", material_type="dna") #DNA
    A = Species(name="A", material_type="protein") #Activator
    X = Species(name="X", material_type="protein")

    # hill positive
    with pytest.deprecated_call():
        Reaction([G], [G, X], propensity_type="hillpositive",
                 propensity_params={"k": kex, "n": 2.0, "K": float(kb/ku), "s1": A})

    # proportional hill positive
    with pytest.deprecated_call():
        Reaction([G], [G, X], propensity_type="proportionalhillpositive",
                 propensity_params={"k": kex, "n": 2.0, "K": float(kb/ku), "s1": A, "d": G})

    # hill Negative
    with pytest.deprecated_call():
        Reaction([G], [G, X], propensity_type="hillnegative",
                 propensity_params={"k": kex, "n": 2.0, "K": float(kb/ku), "s1": A})

    # proportional hill negative
    with pytest.deprecated_call():
        Reaction([G], [G, X], propensity_type="proportionalhillnegative",
                 propensity_params={"k": kex, "n": 2.0, "K": float(kb/ku), "s1": A, "d": G})
Exemple #3
0
    def test_contains(self):
        s1 = Species(name='s1', material_type="m1")
        s2 = Species(name='s2', material_type="m2")
        s3 = Species("s3")

        c1 = ComplexSpecies([s1, s2, s1], called_from_complex=True)
        c2 = ComplexSpecies([c1, s3], called_from_complex=True)

        self.assertTrue(s1 in c1)
        self.assertTrue(s2 in c1)
        self.assertFalse(c1 in c1)
        self.assertTrue(s1 in c2)
        self.assertTrue(s2 in c2)
        self.assertTrue(c1 in c2)
        self.assertTrue(s3 in c2)

        #contains checks the direction, position, and parent as well.
        p = OrderedPolymerSpecies([s1, [s2, "reverse"]])
        p2 = OrderedPolymerSpecies([s2, [s2, "reverse"]])
        c3 = ComplexSpecies([p[0], p[1]], called_from_complex=True)
        assert not s1 in c3
        assert not s2 in c3
        assert p[0] in c3
        assert p[1] in c3
        assert not p2[1] in c3
        assert p[0] not in c1
Exemple #4
0
    def test_compile_crn(self):
        from biocrnpyler import ChemicalReactionNetwork
        from biocrnpyler import Species
        from biocrnpyler import Reaction
        from biocrnpyler import Mixture

        a = Species(name='a')
        b = Species(name='b')

        species_list = [a, b]

        def mock_update_reactions():
            rxn = Reaction(inputs=[a], outputs=[b], k=0.1)
            return [rxn]

        rxn = Reaction(inputs=[a], outputs=[b], k=0.1)

        CRN = ChemicalReactionNetwork(species_list, [rxn])

        mixture = Mixture(species=species_list)
        mixture.update_reactions = mock_update_reactions

        crn_from_mixture = mixture.compile_crn()
        self.assertEqual(CRN.species, crn_from_mixture.species)
        self.assertEqual(CRN.reactions, crn_from_mixture.reactions)
def test_update_promoter():
    T = Species("T")
    D = Species("D")
    P = Species("P")
    prom = Promoter("prom")
    mech = Mechanism(name="mech", mechanism_type="assembly")

    ass = DNAassembly("ass",
                      rbs=None,
                      promoter=None,
                      transcript=T,
                      dna=D,
                      protein=P,
                      mechanisms=[mech])
    ass.update_promoter(prom)

    #test copying
    assert ass.promoter != prom
    assert type(ass.promoter) == type(prom)
    assert ass.promoter.name == prom.name

    #test resetting transcript
    assert ass.promoter.transcript == T

    #test mechanism inheritance
    assert mech.mechanism_type in ass.promoter.mechanisms
def test_basic_RBS_CDS_RNAconstruct():
    R = RBS("rbs")
    C = CDS("gfp")
    parameters={"cooperativity":2,"kb":100, "ku":10, "ktx":.05, "ktl":.2, "kdeg":2,"kint":.05}
    mechs = {"translation":Translation_MM(Species("Ribo"))}

    #minimal RNA translation
    x = RNA_construct([R,C],mechanisms = mechs,parameters=parameters)
    y = x.enumerate_components()
    assert(x[0] ==y[0])
    assert(y[1].protein==Species("gfp",material_type="protein"))
    assert(y[0].transcript.parent==x.get_species())

    #minimal RNA transcription
    x = RNA_construct([C,R],mechanisms = mechs,parameters=parameters)
    y = x.enumerate_components()
    assert(y==[x[1]])
    assert(y[0].transcript.parent==x.get_species())

    #minimal RNA transcription
    x = RNA_construct([[R,"reverse"],C],mechanisms = mechs,parameters=parameters)
    y = x.enumerate_components()
    assert(y==[])

    #minimal RNA transcription
    x = RNA_construct([R,[C,"reverse"]],mechanisms = mechs,parameters=parameters)
    y = x.enumerate_components()
    assert(y==[x[0]])
    assert(y[0].transcript.parent==x.get_species())
Exemple #7
0
def test_complex_with_polymer_replacement():
    #These tests show how the order of binding can matter.
    #Best practices is to put everything into a PolymerConformation before doing Complex if PolymerConformations are being used.

    a = Species('A')
    b = Species('B')
    s = Species("S")
    p = OrderedPolymerSpecies([a, b, a])
    pc0 = PolymerConformation(
        polymer=p)  #Put the polymer inside a conformation
    #Bind two monomers together
    pc = Complex([pc0.polymers[0][0],
                  pc0.polymers[0][1]]).parent  #get a PolymerConformation

    assert isinstance(pc, PolymerConformation)

    #create a Complex around an unbound element of p (from within pc)
    c = Complex([s, pc.polymers[0][2], s], ordered=True)
    assert str(c) == str(
        OrderedComplexSpecies([s, p[2], s], called_from_complex=True))
    assert str(pc.polymers[0]) == str(c.parent.polymers[0])
    assert len(c.parent.complexes) > len(pc.complexes)

    #Make the same thing with the replacement first
    #this gives a different final complex than doing things in the previous order
    p2 = OrderedPolymerSpecies([a, b, Complex([s, a, s], ordered=True)])
    pc2 = PolymerConformation(polymer=p2)
    assert str(c.parent) != str(p2)
    assert c.parent.parent != Complex([pc2.polymers[0][0], pc2.polymers[0][1]
                                       ]).parent
    def test_initial_condition_vector(self):
        from biocrnpyler import ChemicalReactionNetwork
        from biocrnpyler import Species
        from biocrnpyler import Reaction

        s1 = Species(name='test_species1')
        s2 = Species(name='test_species2')

        species_list = [s1, s2]

        rx1 = Reaction(inputs=[s1], outputs=[s2], k=0.1)
        rxn_list = [rx1]

        crn = ChemicalReactionNetwork(species=species_list, reactions=rxn_list)

        s3 = Species(name='test_species3')

        init_cond = {s1: 5, s3: 10}

        x0 = crn.initial_condition_vector(init_cond_dict=init_cond)

        not_in_the_list = False
        for key, value in init_cond.items():
            if value not in x0 and key == s3:
                not_in_the_list = True
        self.assertTrue(not_in_the_list)
Exemple #9
0
    def test_contains_species_monomer(self):
        """Checks if the ComplexSpecies has a monomer (Species) inside of it, 
        but without checking Species.parent or Species.position. In effect, a
        less stringent version of __contains__. This is useful for checking
        complexes containing monomers from Polymers."""

        s1 = Species(name='s1', material_type="m1")
        s2 = Species(name='s2', material_type="m2")
        p = OrderedPolymerSpecies([s1, [s2, "reverse"]])
        p2 = OrderedPolymerSpecies([[s2, "reverse"], s1])
        c2 = ComplexSpecies([p[0], p[1]], called_from_complex=True)

        #Contains parent doesn't matter
        assert c2.contains_species_monomer(s1)
        assert c2.contains_species_monomer(p[0])
        assert c2.contains_species_monomer(p2[0])

        #position doesn't matter
        assert c2.contains_species_monomer(p2[1])

        #Direction does matter (by default)
        assert not c2.contains_species_monomer(s2)

        #Direction does matter (with keyword)
        print("*****")
        print(s2 is p2[0], s2, p2[0])
    def test_write_sbml_file(self):

        import libsbml
        from biocrnpyler import ChemicalReactionNetwork
        from biocrnpyler import Species
        from biocrnpyler import Reaction

        s1 = Species(name='test_species1')
        s2 = Species(name='test_species2')

        species_list = [s1, s2]

        rx1 = Reaction(inputs=[s1], outputs=[s2], k=0.1)
        rxn_list = [rx1]

        crn = ChemicalReactionNetwork(species=species_list, reactions=rxn_list)
        document, _ = crn.generate_sbml_model()
        sbml_string = libsbml.writeSBMLToString(document)

        file_name = 'test_sbml.xml'
        with patch("builtins.open", new=mock_open()) as _file:
            crn.write_sbml_file(file_name)

            _file.assert_called_once_with(file_name, 'w')
            _file().write.assert_called_once_with(sbml_string)
Exemple #11
0
def test_complex_with_polymer():
    a = Species('A')
    b = Species('B')
    c = Complex([a, b])
    d = OrderedPolymerSpecies([a, b, a])

    #Complex in an OrderedPolymerSpecies
    d_c = Complex([d[1], a])

    assert (isinstance(d_c, ComplexSpecies))
    truth = OrderedPolymerSpecies([a, Complex([b, a]), a])
    assert (d_c.parent == truth)

    assert (d[1] not in d_c)  #different parents
    assert (b in d_c)  #b is unbound when put in the Complex

    #Ordered case
    d_co = Complex([d[1], a], ordered=True)
    assert isinstance(d_co, OrderedComplexSpecies)
    truth_o = OrderedPolymerSpecies([a, Complex([b, a], ordered=True), a])
    assert d_co.parent == truth_o

    #Cannot complex two Species inside a PolymerSpecies without puting the PolymerSpecies into a Conformation first
    with pytest.raises(TypeError):
        c = Complex([Species("S"), d[0], d[2]])
Exemple #12
0
    def test_recursive_filtering(self):
        #Test default off via name, attributes, and materials with recursive_species_filtering = True

        s1 = Species("s1", material_type = "m1", attributes = ["a1"])
        s2 = Species("s2", material_type = "m2", attributes = ["a2"])
        c1 = Complex([s1, s2], name = "c1")
        c2 = Complex([c1, s2], name = "c2")

        fd = {"s1":True} #Filter based on name
        mech_default_on_fds1 = GlobalMechanism(name = self.mech_name, mechanism_type = "dummy", 
            default_on = False, filter_dict = fd, recursive_species_filtering = True)
        self.assertTrue(mech_default_on_fds1.apply_filter(s1))
        self.assertFalse(mech_default_on_fds1.apply_filter(s2))
        self.assertTrue(mech_default_on_fds1.apply_filter(c1))
        self.assertTrue(mech_default_on_fds1.apply_filter(c2))

        fd = {"m1":True} #Filter based on material
        mech_default_on_fds1 = GlobalMechanism(name = self.mech_name, mechanism_type = "dummy", 
            default_on = False, filter_dict = fd, recursive_species_filtering = True)
        self.assertTrue(mech_default_on_fds1.apply_filter(s1))
        self.assertFalse(mech_default_on_fds1.apply_filter(s2))
        self.assertTrue(mech_default_on_fds1.apply_filter(c1))
        self.assertTrue(mech_default_on_fds1.apply_filter(c2))

        fd = {"a1":True} #Filter based on attribute
        mech_default_on_fds1 = GlobalMechanism(name = self.mech_name, mechanism_type = "dummy", 
            default_on = False, filter_dict = fd, recursive_species_filtering = True)
        self.assertTrue(mech_default_on_fds1.apply_filter(s1))
        self.assertFalse(mech_default_on_fds1.apply_filter(s2))
        self.assertTrue(mech_default_on_fds1.apply_filter(c1)) #attributes are not inherited through ComplexSpecies, but contained inside
        self.assertTrue(mech_default_on_fds1.apply_filter(c2))
Exemple #13
0
    def test_compile_crn(self):
        a = Species(name='a')
        b = Species(name='b')

        species_list = [a, b]

        rxn = Reaction.from_massaction(inputs=[a], outputs=[b], k_forward=0.1)

        CRN = ChemicalReactionNetwork(species_list, [rxn])

        # create a component
        component = Component("comp")

        # creating a mock update function to decouple the update process from the rest of the code
        def mock_update_reactions():
            rxn = Reaction.from_massaction(inputs=[a], outputs=[b], k_forward=0.1)
            return [rxn]

        def mock_update_species():
            return [a, b]

        component.update_species = mock_update_species
        component.update_reactions = mock_update_reactions

        mixture = Mixture(components=[component])

        crn_from_mixture = mixture.compile_crn()
        # test that the mixture has the same species as the manually build CRN object
        self.assertEqual(set(CRN.species), set(crn_from_mixture.species))
        # test that the mixture has the same reactions as the manually build CRN object
        self.assertEqual(CRN.reactions, crn_from_mixture.reactions)
def test_general_propensity():
    S1, S2, S3 = Species("S1"), Species("S2"), Species("S3")
    # create some parameters
    k1 = ParameterEntry("k1", 1.11)
    k2 = ParameterEntry("k2", 2.22)

    gn1 = GeneralPropensity('k1*2 - k2/S1^2', propensity_species=[S1], propensity_parameters=[k1, k2])
    assert str(S1) in gn1.propensity_dict['species']
    assert k1.parameter_name in gn1.propensity_dict['parameters']
    assert k2.parameter_name in gn1.propensity_dict['parameters']
    assert gn1.pretty_print() == 'k1*2 - k2/S1^2\n  k1=1.11\n  k2=2.22\n'

    gn2 = GeneralPropensity('S1^2 + S2^2 + S3^2', propensity_species=[S1, S2, S3], propensity_parameters=[])
    assert str(S1) in gn1.propensity_dict['species']
    assert k1.parameter_name not in gn2.propensity_dict['parameters']

    with pytest.raises(TypeError, match='propensity_species must be a list of Species!'):
        GeneralPropensity('S1^2 + S2^2 + S3^2', propensity_species=[k1], propensity_parameters=[])

    with pytest.raises(TypeError, match='propensity_parameter must be a list of ParameterEntry!'):
        GeneralPropensity('S1^2 + S2^2 + S3^2', propensity_species=[], propensity_parameters=[S2])

    test_formula = 'S3^2'
    with pytest.raises(ValueError, match=f'must be part of the formula'):
        GeneralPropensity(test_formula, propensity_species=[S1], propensity_parameters=[])

    test_formula = 'k2*S3^2'
    with pytest.raises(ValueError, match=f'must be part of the formula'):
        GeneralPropensity(test_formula, propensity_species=[S3], propensity_parameters=[k1])
Exemple #15
0
    def test_species_initialization(self):

        s1 = Species(name='s1')
        s2 = Species(name='s2', material_type="m2")

        # Check invalidity of ComplexSpecies with fewer than 2 component
        with self.assertRaisesRegex(
                ValueError, 'chemical_reaction_network.complex requires '
                '2 or more species in its constructor'):
            ComplexSpecies([s1], called_from_complex=True)

        # Check invalidity of OrderedComplexSpecies with fewer than 2 component
        with self.assertRaisesRegex(
                ValueError, 'chemical_reaction_network.complex requires 2 '
                'or more species in its constructor.'):
            OrderedComplexSpecies([s1], called_from_complex=True)

        # Check invalidity of multimers with fewer than 2 component
        with self.assertRaisesRegex(
                ValueError, 'chemical_reaction_network.complex requires 2 '
                'or more species in its constructor'):
            Multimer(s1, 1, called_from_complex=True)

        # Check the naming conventions
        oc1 = OrderedComplexSpecies([s2, s1], called_from_complex=True)
        c1 = ComplexSpecies([s2, s1], called_from_complex=True)
        m1 = Multimer(s1, 2, called_from_complex=True)
        c3 = ComplexSpecies([s1, s1], called_from_complex=True)

        # Check invalidity of ComplexSpecies, Multimers and OrderedComplexSpecies with strings instead of species
        with self.assertRaisesRegex(
                TypeError,
                'recieved a non-species as a member of the list species'):
            self.assertEqual(OrderedComplexSpecies([s2, "s1"]), oc1)
            self.assertEqual(ComplexSpecies([s2, "s1"]), c1)
            self.assertEqual(Multimer("s1", 2), m1)

        # ComplexSpecies should sort the species added alphabetically by representation
        #an extra underscore is added at the end of the representation to deal with embedded complexes.
        self.assertEqual(repr(c1),
                         "complex_" + repr(s2) + "_" + repr(s1) + "_")

        # OrderedComplexSpecies do not sort their internal species
        self.assertEqual(repr(oc1),
                         "ordered_complex_" + repr(s2) + "_" + repr(s1) + "_")

        # Multimers are just complexes with multiplicity
        self.assertEqual(repr(m1), "complex_" + repr(s1) + "_2x_")
        self.assertEqual(repr(c3), repr(m1))

        # Nested list creation of ComplexSpecies
        c1 = ComplexSpecies([s1, [s2, s1]], called_from_complex=True)
        c2 = ComplexSpecies([s1, s2, s1], called_from_complex=True)
        self.assertEqual(c1, c2)

        c1 = OrderedComplexSpecies([s1, [s2, s1]], called_from_complex=True)
        c2 = OrderedComplexSpecies([s1, s2, s1], called_from_complex=True)
        c3 = OrderedComplexSpecies([s1, [s1, s2]], called_from_complex=True)
        self.assertEqual(c1, c2)
        self.assertFalse(c1 == c3)
def test_instantiation():
    #Instantiate from strings
    ass = DNAassembly(name="ass", rbs="rbs", promoter="prom")
    assert type(ass.promoter) is Promoter and ass.promoter.name == "prom"
    assert type(ass.rbs) is RBS and ass.rbs.name == "rbs"
    assert type(ass.transcript) is Species and ass.transcript.name == ass.name
    assert type(ass.protein) is Species and ass.protein.name == ass.name
    assert type(ass.dna) is Species and ass.dna.name == ass.name

    #Instantiate with rbs = None
    ass = DNAassembly(name="ass", rbs=None, promoter="prom")
    assert ass.rbs is None

    #Instantiate with prom = None
    ass = DNAassembly(name="ass", rbs="rbs", promoter=None)
    assert ass.promoter is None
    assert type(ass.rbs) is RBS and ass.rbs.name == "rbs"
    assert type(ass.protein) is Species and ass.protein.name == ass.name

    #instantiate with transcript = Species
    T = Species("T")
    ass = DNAassembly(name="ass", rbs="rbs", promoter="prom", transcript=T)
    assert ass.transcript == T

    #instantiate with dna = Species
    D = Species("D")
    ass = DNAassembly(name="ass", rbs="rbs", promoter="prom", dna=D)
    assert ass.dna == D

    #instantiate with protein = Species
    P = Species("P")
    ass = DNAassembly(name="ass", rbs="rbs", promoter="prom", protein=P)
    assert ass.protein == P
Exemple #17
0
    def test_species_protection(self):
        #tests that Species cannot be changed once they are in a CRN
        S = Species("S")
        S2 = Species("S2")
        CRN = ChemicalReactionNetwork([S], [])

        #Internal species copied correctly to return
        assert S in CRN.species

        #assert species are copied
        assert not S is CRN._species[0]

        #Returned list does not effect internal species
        CRN.species[0] = S2
        assert S2 not in CRN.species

        #add species effects internal species list
        CRN.add_species(S2)
        assert S2 in CRN.species
        #assert correct copying
        assert S2 is not CRN._species[1]

        with self.assertRaisesRegex(
                AttributeError,
                "The species in a CRN cannot be removed or modified*"):
            CRN.species = []

        #Test bypassing species protection
        CRN = ChemicalReactionNetwork([], [])
        CRN.add_species([S], copy_species=False)
        assert S is CRN._species[0]
Exemple #18
0
def test_propensity_dict_hill():
    d = Species('d')
    s1 = Species('s1')
    k = ParameterEntry(parameter_value='1', parameter_name='k')
    K = ParameterEntry(parameter_value='2', parameter_name='K')
    n = ParameterEntry(parameter_value='3', parameter_name='n')

    #Should store the ParameterEntry in this case
    P1 = Hill(k=k, K=K, n=n, s1=s1, d=d)
    assert P1.propensity_dict["parameters"]["k"] == k
    assert P1.propensity_dict["parameters"]["K"] == K
    assert P1.propensity_dict["parameters"]["n"] == n
    #assert the getters work (should return values instead of ParameterEntries)
    assert P1.k == k.value
    assert P1.K == K.value
    assert P1.n == n.value

    #Should store a numerical value in this case
    P2 = Hill(k=k.value, K=K.value, n=n.value, s1=s1, d=d)
    assert P2.propensity_dict["parameters"]["k"] == k.value
    assert P2.propensity_dict["parameters"]["K"] == K.value
    assert P2.propensity_dict["parameters"]["n"] == n.value
    #assert the getters work
    assert P2.k == k.value
    assert P2.K == K.value
    assert P2.n == n.value
def test_initial_condition_in_crn():
    S = Species("S")
    S2 = Species("S2")
    S3 = Species("S3")

    CRN = ChemicalReactionNetwork(species=[S, S2, S3], reactions=[])

    #No Initial Concentration Dict
    assert S not in CRN.initial_concentration_dict

    #test setter
    CRN.initial_concentration_dict = {S: 10, S2: 10}
    assert S in CRN.initial_concentration_dict
    assert CRN.initial_concentration_dict[S] == 10

    #Test setter overwriting
    CRN.initial_concentration_dict = {S: 11, S3: 10}
    assert S2 in CRN.initial_concentration_dict
    assert CRN.initial_concentration_dict[S] == 11
    assert CRN.initial_concentration_dict[S2] == 10
    assert CRN.initial_concentration_dict[S3] == 10

    #Test setter reset
    CRN.initial_concentration_dict = None
    assert S not in CRN.initial_concentration_dict
    assert S2 not in CRN.initial_concentration_dict
    assert S3 not in CRN.initial_concentration_dict
def test_species_initial_condition_in_mixture():

    S1 = Species("S1")
    S2 = Species("S2")

    C = ChemicalComplex([S1, S2], name="C")
    S3 = C.get_species()

    mixture_name = "M"
    key1 = ParameterKey(mechanism="initial concentration",
                        part_id=mixture_name,
                        name=str(S1))
    key2 = ParameterKey(mechanism="initial concentration",
                        part_id=mixture_name,
                        name=C.name)

    M = Mixture(name=mixture_name,
                components=[C],
                parameters={
                    key1: 10,
                    key2: 2.2
                })

    #Initial condition found under the Species name
    assert parameter_to_value(M.get_initial_concentration(S1)[S1]) == 10

    #Initial condition defaults to 0
    assert parameter_to_value(M.get_initial_concentration(S2)[S2]) == 0

    #Initial condition found under the Component name
    assert parameter_to_value(M.get_initial_concentration(S3, C)[S3]) == 2.2
    def test_get_all_species_containing(self):
        from biocrnpyler import ChemicalReactionNetwork
        from biocrnpyler import Species
        from biocrnpyler import Reaction

        s1 = Species(name='test_species1')
        s2 = Species(name='test_species2')

        species_list = [s1, s2]

        rx1 = Reaction(inputs=[s1], outputs=[s2], k=0.1)
        rxn_list = [rx1]

        crn = ChemicalReactionNetwork(species=species_list, reactions=rxn_list)

        s3 = Species(name='test_species3')

        with self.assertRaises(ValueError):
            crn.get_all_species_containing(species=species_list)

        rtn_species_list = crn.get_all_species_containing(species=s3)
        self.assertEqual(rtn_species_list, [])

        rtn_species_list = crn.get_all_species_containing(species=s1)
        self.assertEqual(rtn_species_list, [s1])

        rtn_species_list = crn.get_all_species_containing(
            species=s1, return_as_strings=True)
        self.assertEqual(rtn_species_list, [repr(s1)])
Exemple #22
0
def test_One_Step_Binding():
    osb = One_Step_Binding()
    binder = Species("S1")
    bindee = Species("S2")
    c_fake = Species("C")
    c1 = Complex([binder, bindee])

    #Test Update Species
    assert len(osb.update_species(binder, bindee, cooperativity=1)) == 3
    assert c1 in osb.update_species(binder, bindee, cooperativity=1)
    assert c_fake in osb.update_species(binder, bindee, complex_species=c_fake)

    #Test Update Reactions
    assert len(osb.update_reactions(binder, bindee, kb=1.0, ku=1.0)) == 1
    assert len(
        osb.update_reactions(
            binder,
            bindee,
            kb=1.0,
            ku=1.0,
            complex_species=c_fake,
        )) == 1

    #Also works with lists
    assert len(osb.update_species([binder], [bindee])) == 3
    assert len(osb.update_reactions([binder], [bindee], kb=1.0, ku=1.0)) == 1
def test_reaction_list_flattening():
    sp1 = Species(name='test_species_a')
    sp2 = Species(name='test_species_b')
    k_f = 1
    mak = MassAction(k_forward=k_f)
    rxn1 = Reaction(inputs=[sp1, [sp1, sp2]], outputs=[[sp2, sp2], sp1], propensity_type=mak)
    rxn2 = Reaction(inputs=[sp1, sp1, sp2], outputs=[sp1, sp2, sp2], propensity_type=mak)
    assert rxn1 == rxn2
Exemple #24
0
def test_get_complex():
    p = OrderedPolymerSpecies([Species("m1"), Species("m2"), Species("m3")])
    c1 = ComplexSpecies([p[0], p[1], Species("S")], called_from_complex=True)
    pc = PolymerConformation(complexes=[c1])

    assert str(pc.get_complex(c1)) == str(
        c1
    )  #these are not technically equal because they have different parents
Exemple #25
0
def test_process_initial_concentration_dict():
    A = Species('A')
    B = Species('B')
    C = Species('C')
    initial_concentration = {A: 10, B: 25.34, str(C): 77.24}
    processed = process_initial_concentration_dict(initial_concentration)
    for (key_old, key_new) in zip(initial_concentration.keys(),
                                  processed.keys()):
        assert str(key_old) == key_new
def test_proportional_hill_positive_rate_formula():
    in_d = Species('d')
    in_s1 = Species('s1')
    in_k = 1
    in_K = 5
    in_n = 2
    philpos = ProportionalHillPositive(k=in_k, s1=in_s1, K=in_K, n=in_n, d=in_d)

    assert philpos._get_rate_formula(philpos.propensity_dict) == f"{in_k}*{in_d}*{in_s1}^{in_n} / ( {in_K}^{in_n} + {in_s1}^{in_n} )"
def test_proportional_hill_negative_rate_formula():
    in_d = Species('d')
    in_s1 = Species('s1')
    in_k = 1
    in_K = 5
    in_n = 2
    philneg = ProportionalHillNegative(k=in_k, s1=in_s1, K=in_K, n=in_n, d=in_d)

    assert philneg._get_rate_formula(philneg.propensity_dict) == f"{in_k}*{in_d} / ( 1 + ({in_s1}/{in_K})^{in_n} )"
Exemple #28
0
def test_from_polymer_conformation():
    #tests the classmethod .from_polymer_conformation

    #Produce a PolymerConformation
    p1 = OrderedPolymerSpecies([Species("m1"), Species("m2"), Species("m3")])
    c1 = ComplexSpecies([p1[0], p1[1]], called_from_complex=True)
    pc1 = PolymerConformation(complexes=[c1])

    #This Complex uses the polymer inside the pc1 so there is only a single polymer in the final PolymerConformation
    c1b = ComplexSpecies([pc1.polymers[0][0], pc1.polymers[0][2]],
                         called_from_complex=True)
    c1bb = ComplexSpecies([p1[0], p1[2]])
    pc1b = PolymerConformation.from_polymer_conformation([pc1], [c1b])

    #This is correct (and checking ordering effects don't matter)
    assert pc1b == PolymerConformation([c1, c1bb]) == PolymerConformation(
        [c1bb, c1])

    #This is incorrect because of polymers being copied into conformations
    assert pc1b != PolymerConformation([c1, c1b])

    #This Complex uses the old Polymer Instance which will represent the binding to a new, identical, PolymerSpecies
    #all three of the following therefore should be the same
    c1c = ComplexSpecies([p1[0], p1[2]], called_from_complex=True)
    pc1c = PolymerConformation.from_polymer_conformation([pc1], [c1c])

    p1d = OrderedPolymerSpecies([Species("m1"), Species("m2"), Species("m3")])
    c1d = ComplexSpecies([p1d[0], p1d[2]], called_from_complex=True)
    pc1d = PolymerConformation.from_polymer_conformation([pc1], [c1c])

    #Create directly
    pc1e = PolymerConformation([c1d, c1])
    pc1er = PolymerConformation([c1, c1d])  #Order shouldn't matter

    assert pc1c == pc1d == pc1e == pc1er

    #Test from multiple PolymerConformations
    p2 = OrderedPolymerSpecies([Species("m1"), Species("m2"), Species("m4")])
    c2 = ComplexSpecies([p2[0], p2[1]], called_from_complex=True)
    pc2 = PolymerConformation(complexes=[c2])
    #Create a PolymerConformation that links the two Polymers together
    c3 = ComplexSpecies([p1[0], p1[1]], called_from_complex=True)
    pc3 = PolymerConformation([c3])

    #Add an additional binding site connecting pc2 and pc3
    c4 = ComplexSpecies([pc3.polymers[0][0], pc2.polymers[0][1]
                         ])  #get the conformations polymers due to copying
    pc4 = PolymerConformation.from_polymer_conformation([pc2, pc3], [c4])
    c4b = ComplexSpecies([p1[0], p2[1]])

    assert pc4 == PolymerConformation([c2, c3, c4b]) == PolymerConformation(
        [c4b, c2, c3])  #And order doesn't matter
    assert pc4 != PolymerConformation(
        [c2, c3, c4])  #This should be different due to copying

    #The following should produce errors
    with pytest.raises(TypeError):
        pc1b = PolymerConformation.from_polymer_conformation(pc1, [c1b])
    with pytest.raises(TypeError):
        pc1b = PolymerConformation.from_polymer_conformation([c1b], [c1b])
Exemple #29
0
def test_single_polymer_single_complex_instantiation():
    p = OrderedPolymerSpecies([Species("m1"), Species("m2"), Species("m3")])
    c1 = ComplexSpecies([p[0], p[1], Species("S")], called_from_complex=True)
    pc = PolymerConformation(complexes=[c1])
    #Test naming convention
    assert str(pc) == f"conformation__{p}_np0l0p0l1_{c1}_"

    p2 = OrderedPolymerSpecies([Species("m1"), Species("m2"), Species("m4")])
    c2 = ComplexSpecies([p[0], p2[0]], called_from_complex=True)

    #In these cases, TypeErrors should be raised
    with pytest.raises(ValueError):
        #Emtpy complexes is not allowed
        pc2 = PolymerConformation(complexes=[])

    with pytest.raises(ValueError):
        #set a PolymerConformation as a parent of the Species.
        S = Species("S")
        S.parent = pc
        c3 = ComplexSpecies([p[0], S], called_from_complex=True)
        pc2 = PolymerConformation(complexes=[c3])

    with pytest.raises(ValueError):
        #Cannot place an entire polymer into a Complex
        S = Species("S")
        S.parent = pc
        c3 = ComplexSpecies([p, S], called_from_complex=True)
        pc2 = PolymerConformation(complexes=[c3])
def test_combinatorial_enumeration_DNAconstruct():
    P = Promoter("pconst")  #constitutive promoter
    T = Terminator("term")
    parameters = {
        "cooperativity": 2,
        "kb": 100,
        "ku": 10,
        "ktx": .05,
        "ktl": .2,
        "kdeg": 2,
        "kint": .05
    }
    mechs = {
        "transcription":
        Transcription_MM(Species("RNAP", material_type="protein"))
    }

    #circular construct
    x = DNA_construct([P, P, T],
                      mechanisms=mechs,
                      parameters=parameters,
                      circular=True)
    y = x.combinatorial_enumeration()
    prom_positions = []
    dna_species = {}
    for prom_comp in y:
        if (prom_comp.position not in dna_species):
            dna_species[prom_comp.position] = [prom_comp.dna_to_bind.parent]
        else:
            dna_species[prom_comp.position] += [prom_comp.dna_to_bind.parent]

    p1_bound = Complex(
        [x.get_species()[0],
         Species("RNAP", material_type="protein")]).parent
    p2_bound = Complex(
        [x.get_species()[1],
         Species("RNAP", material_type="protein")]).parent
    both_bound = Complex(
        [p1_bound[1], Species("RNAP", material_type="protein")]).parent
    assert (x.get_species() in dna_species[0]
            )  #unbound polymer found in combinatorial enumeration
    assert (p2_bound in dna_species[0]
            )  #proper bound polymer found in combinatorial enumeration
    assert (x.get_species() in dna_species[1]
            )  #unbound polymer found in combinatorial enumeration
    assert (p1_bound in dna_species[1]
            )  #proper bound polymer found in combinatorial enumeration
    assert (
        both_bound not in dna_species[0]
    )  #dna with both promoters bound is not in combinatorial enumeration
    assert (
        both_bound not in dna_species[1]
    )  #dna with both promoters bound is not in combinatorial enumeration
    assert (len(y) == 4)