示例#1
0
    def test_ordered_polymer_species_contains(self):
        a = Species("A")
        b = Species("B")
        bf = Species("B").set_dir("forward")
        c = Complex([a, a])
        p = OrderedPolymerSpecies([bf, b, c])

        #In these cases, parent doesn't matter
        self.assertTrue(a in p[2])
        self.assertTrue(a in c)
        self.assertTrue(b in p)
        self.assertTrue(c in p)

        p2 = OrderedPolymerSpecies([bf, a, c])
        #In these cases parents matter
        self.assertFalse(p[0] in p2)
        self.assertFalse(p2[0] in p)

        #In this case, direciton matters
        self.assertFalse(b in p2)
示例#2
0
    def test_add_species(self):
        species = Species('test_species')
        mixture = Mixture()
        mixture.add_species(species)

        # test that the new mixture only contain one species
        self.assertEqual([species], mixture.added_species)

        # adding invalid species
        with self.assertRaisesRegex(AssertionError,'only Species type is accepted!'):
            mixture.add_species(['ok', 'ok'])
示例#3
0
    def test_species_initialization(self):
        # tests naming convention repr without species type or attributes
        species = Species(name='test_species')
        self.assertEqual(repr(species), species.name)

        # tests material type
        species = Species(name='test_species', material_type="dna")
        self.assertTrue(species.material_type == "dna")

        # tests emtpy attributes
        self.assertTrue(isinstance(species.attributes, list))

        # tests naming convention via repr without attributes
        self.assertEqual(repr(species),
                         species.material_type + "_" + species.name)

        # tests adding attributes
        attr_list = ['atr1', 'atr2']
        species = Species(name='test_species', attributes=attr_list)
        self.assertEqual(attr_list, species.attributes)

        # tests naming convention with attributes and no material
        correct_name = species.name
        for attribute in species.attributes:
            correct_name += "_" + attribute
        self.assertEqual(repr(species), correct_name)

        # tests initial condition by default should be 0
        species = Species(name='test_species')
        self.assertTrue(species.initial_concentration == 0)

        # tests setting correct initial concentration
        initial_concentration = 10
        species = Species(name='test_species',
                          initial_concentration=initial_concentration)
        self.assertEqual(species.initial_concentration, initial_concentration)

        #test OrderedMonomer subclass
        self.assertTrue(species.parent is None)
        self.assertTrue(species.position is None)
        self.assertTrue(species.direction is None)
示例#4
0
    def test_add_species(self):
        from biocrnpyler import Mixture
        from biocrnpyler import Species

        species = Species('test_species')
        mixture = Mixture()
        mixture.add_species(species)

        self.assertEqual([species], mixture.added_species)

        with self.assertRaises(AssertionError):
            mixture.add_species(['ok', 'ok'])
示例#5
0
    def test_species_equality(self):
        # testing species equality
        s1 = Species(name='a', material_type='mat1', attributes=['red'])
        s2 = Species(name='a', material_type='mat1', attributes=['red'])
        # if two species have the same name, material_type and attributes, then they are the same
        self.assertTrue(s1 == s2)

        s3 = Species(name='b', material_type='mat1', attributes=['red'])
        # different species name: not the same species
        self.assertFalse(s1 == s3)

        s4 = Species(name='a', material_type='mat2', attributes=['red'])
        # different material type: not the same species
        self.assertFalse(s1 == s4)

        s5 = Species(name='a',
                     material_type='mat1',
                     attributes=['red', 'large'])
        # different attributes: not the same species
        self.assertFalse(s1 == s5)

        s6 = Species(name='a',
                     material_type='mat1',
                     attributes=['red'],
                     compartment='test_compartment')
        # same species name in different compartments: not the same species
        self.assertFalse(s1 == s6)
    def test_initialization(self):
        from biocrnpyler import CombinatorialPromoter, Protein, Species, Combinatorial_Cooperative_Binding
        #initializing with one regulator that has no list
        newprom = CombinatorialPromoter("testprom","treg1")
        self.assertTrue(newprom.regulators == [Species("treg1",material_type="protein")])
        #initializing with a list of strings
        newprom2 = CombinatorialPromoter("testprom",["treg1","treg2"])
        #it should convert strings into proteins
        self.assertTrue(newprom2.regulators == [Species("treg1",material_type="protein"),
                                                Species("treg2",material_type="protein")])
        #by default, all complexes are tx capable
        print(newprom2.tx_capable_list)
        self.assertTrue(newprom2.tx_capable_list==[{"treg1"},{"treg2"},{"treg1","treg2"}])

        #you should be able to define a tx_capable_list
        newprom3 = CombinatorialPromoter("testprom",["treg1","treg2"],\
                                    tx_capable_list=[["treg1","treg2"],["treg2"]])
        
        self.assertTrue(newprom3.tx_capable_list==[{"treg1","treg2"},{"treg2"}])

        #if you define it with a species in the regulators it should work
        newprom4 = CombinatorialPromoter("testprom",["treg1",Species("treg2",material_type="rna")])
        print(newprom4.tx_capable_list)
        self.assertTrue(newprom4.tx_capable_list == [{"treg1"},{"treg2"},{"treg1","treg2"}])
        self.assertTrue(newprom4.regulators == [Species("treg1",material_type="protein"),
                                                Species("treg2",material_type="rna")])
        #make sure the default mechanism is the correct one
        self.assertTrue(isinstance(newprom4.mechanisms["binding"],Combinatorial_Cooperative_Binding))
示例#7
0
    def test_ordered_polymer_species_initialization(self):
        a = Species("A")
        x = OrderedPolymerSpecies([Species("A"),[Species("B"),"forward"],\
                            Species("C").set_dir("reverse")],attributes=["ooga"])
        #repr
        revtest = OrderedPolymerSpecies([Species("A",direction="forward"),Species("A")])
        r1 = str(revtest)
        revtest.reverse()
        r2 = str(revtest)
        self.assertEqual(type(r1),str)
        self.assertNotEqual(r1,r2)
        #pretty_print
        self.assertEqual(type(x.pretty_print()),str)
        #make sure we're copying
        self.assertEqual(a.parent,None)
        #make sure we're setting the properties of the components
        self.assertEqual(x[0].parent,x)
        self.assertEqual(x[1].parent,x)
        self.assertEqual(x[2].parent,x)
        self.assertEqual(x[1].direction,"forward")
        self.assertEqual(x[2].direction,"reverse")

        self.assertEqual(x[0].position,0)
        self.assertEqual(x[1].position,1)
        self.assertEqual(x[2].position,2)

        #circularity
        x.circular = True
        self.assertEqual(x.circular, True)
        self.assertIn("circular",x.attributes)
        x.circular = False
        self.assertEqual(x.circular, False)
        self.assertNotIn("circular",x.attributes)
示例#8
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.assertRaisesRegexp(ValueError,'chemical_reaction_network.complex requires '
                                                '2 or more species in its constructor'):
            ComplexSpecies([s1])
        
        # Check invalidity of OrderedComplexSpecies with fewer than 2 component
        with self.assertRaisesRegexp(ValueError, 'chemical_reaction_network.complex requires 2 '
                                                 'or more species in its constructor.'):
            OrderedComplexSpecies([s1])
        
        # Check invalidity of multimers with fewer than 2 component
        with self.assertRaisesRegexp(ValueError, 'chemical_reaction_network.complex requires 2 '
                                                 'or more species in its constructor'):
            Multimer(s1, 1)

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

        # Check validity of ComplexSpecies, Multimers and OrderedComplexSpecies with strings instead of 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
        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_2x_"+repr(s1))
        self.assertEqual(repr(c3), repr(m1))
    def test_default_filtering(self):
        #No filter dictionary used in these tests
        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")

        #Always ON for all species
        mech_default_on = GlobalMechanism(name=self.mech_name,
                                          mechanism_type="dummy",
                                          default_on=True)
        self.assertTrue(
            False not in
            [mech_default_on.apply_filter(s) for s in [s1, s2, c1, c2]])

        #Always OFF for all species
        mech_default_off = GlobalMechanism(name=self.mech_name,
                                           mechanism_type="dummy",
                                           default_on=False)
        self.assertTrue(
            True not in
            [mech_default_off.apply_filter(s) for s in [s1, s2, c1, c2]])
示例#10
0
    def test_update_species(self):
        species = Species(name='H2O')
        mixture = Mixture(species=[species])

        self.assertTrue(species in mixture.update_species())

        dna = DNA(name='test_DNA')
        mixture.add_components(dna)

        crn_list = mixture.update_species()

        for s_dna in dna.update_species():
            self.assertTrue(s_dna in crn_list)
def test_species_initial_condition_defaulting():

    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=str(S2))
    key3 = ParameterKey(mechanism="initial concentration",
                        part_id=mixture_name,
                        name=str(S3))

    C = ChemicalComplex([S1, S2],
                        name="C",
                        parameters={
                            key1: .11,
                            key2: .22
                        },
                        initial_concentration=.33)
    M = Mixture(name=mixture_name,
                components=[C],
                parameters={
                    key1: 1.1,
                    key2: 2.2,
                    key3: 3.3
                })

    #Initial condition found under the Species name, in the Component, not Mixture
    assert parameter_to_value(M.get_initial_concentration(S1, C)[S1]) == .11
    assert parameter_to_value(M.get_initial_concentration(S2, C)[S2]) == .22
    assert parameter_to_value(M.get_initial_concentration(S3, C)[S3]) == .33
示例#12
0
def test_merging_weighted_species():
    s1 = Species(name='a')

    ws1 = WeightedSpecies(species=s1, stoichiometry=2)
    ws2 = WeightedSpecies(species=s1, stoichiometry=5)
    ws_list = [ws1, ws2]

    freq_dict = WeightedSpecies._count_weighted_species(ws_list)
    assert len(freq_dict) == 1
    ws_merged = list(freq_dict.values())
    assert ws_merged[0] == 7

    s2 = Species(name='b')

    ws1 = WeightedSpecies(species=s1, stoichiometry=2)
    ws2 = WeightedSpecies(species=s2, stoichiometry=5)
    ws_list = [ws1, ws2]
    freq_dict = WeightedSpecies._count_weighted_species(ws_list)
    assert len(freq_dict) == 2

    ws_merged = list(freq_dict.values())
    assert ws_merged[0] == 2
    assert ws_merged[1] == 5
示例#13
0
    def test_compile_crn(self):
        a = Species(name='a')
        b = Species(name='b')

        species_list = [a, b]

        # creating a mock update function to decouple the update process from the rest of the code
        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()
        # test that the mixture has the same species as the manually build CRN object
        self.assertEqual(CRN.species, 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)
示例#14
0
    def test_add_components(self):

        mixture = Mixture()
        # test that new mixture has no components
        self.assertTrue(len(mixture.components) == 0)
        component = Component('test_comp')
        mixture.add_components(component)
        # test that the new components was added to the mixture
        self.assertTrue(component in mixture.components)

        species = Species('test_species')
        # species are invalid components
        with self.assertRaisesRegexp(AssertionError,f'the object: {species} passed into mixture as component must be of the class Component'):
            mixture.add_components(species)
示例#15
0
    def test_add_species_to_crn(self):
        species = Species(name='H2O')
        mixture = Mixture(species=[species])
        mixture.add_species_to_crn(species, None)

        self.assertTrue(species in mixture.crn.species)

        dna = DNA(name='test_DNA')
        mixture.add_components(dna)

        mixture.add_species_to_crn(dna.update_species(), dna)

        for s_dna in dna.update_species():
            self.assertTrue(s_dna in mixture.crn.species)
示例#16
0
    def test_deg_tagged_degredation(self):

        M = Mixture(parameters = {"kdeg":1, "kb":1, "ku":1})

        protease = Species("P")
        tagged_protein = Species("X", attributes = ["degtagged"])
        untagged_protein = Species("Y")

        #compare deg_Tagged_Degredation to MichaelisMenten
        MM = MichaelisMenten(name = "name", mechanism_type = "type")
        
        dtd = Deg_Tagged_Degredation(protease)
        #test default global mechanism parameters
        self.assertTrue(dtd.recursive_species_filtering is False)
        self.assertTrue(dtd.default_on is False)
        self.assertTrue("degtagged" in dtd.filter_dict)
        self.assertTrue(dtd.filter_dict["degtagged"] is True)
        self.assertTrue(len(dtd.filter_dict)==1)

        #test default functionality on a tagged species
        species = dtd.update_species(tagged_protein, M)
        rxns = dtd.update_reactions(tagged_protein, M)
        species_mm = MM.update_species(Enzyme = protease, Sub = tagged_protein, Prod = None)
        rxns_mm = MM.update_reactions(Enzyme = protease, Sub = tagged_protein, Prod = None, kb=1, ku=1, kcat=1)

        #species
        self.assertTrue(species_mm == species)
        #reactions
        self.assertTrue(all([str(rxns[i]) == str(rxns_mm[i]) for i in range(len(rxns))]))

        #Overwrite default_on, recursive_species_filtering, and filter_dict
        dtd2 = Deg_Tagged_Degredation(protease, default_on = True, recursive_species_filtering = True, filter_dict = {"test":True})
        self.assertTrue(dtd2.recursive_species_filtering is True)
        self.assertTrue(dtd2.default_on is True)
        self.assertTrue("degtagged" not in dtd2.filter_dict)
        self.assertTrue("test" in dtd2.filter_dict and dtd2.filter_dict["test"] is True)
        self.assertTrue(len(dtd2.filter_dict)==1)
def test_CombinatorialComplex_compute_species_to_add():
    X, Y, Z = Species("X"), Species("Y"), Species("Z")
    C = Complex([X, X, Y, Z])
    CC = CombinatorialComplex(final_states = [C])

    #A single X, Y, and Z should be added
    species_to_add = CC.compute_species_to_add(X, C)
    assert set(species_to_add) == set([X, Y, Z])
    assert species_to_add.count(X) == 1 and species_to_add.count(Y) == 1 and species_to_add.count(Z) == 1

    #Two X's, and Z should be added
    species_to_add = CC.compute_species_to_add(Y, C)
    assert set(species_to_add) == set([X, Z])
    assert species_to_add.count(X) == 2 and species_to_add.count(Z) == 1

    #Try with s0 as a ComplexSpecies
    species_to_add = CC.compute_species_to_add(Complex([X, X]), C)
    assert set(species_to_add) == set([Y, Z])
    assert species_to_add.count(Y) == 1 and species_to_add.count(Z) == 1

    #If sf is not a ComplexSpecies, there is an error
    with pytest.raises(ValueError):
        species_to_add = CC.compute_species_to_add(C, X)

    #In the following cases, sf cannot be created by adding species to s0, so None is returned

    #C contains more species than Complex([X, X])
    species_to_add = CC.compute_species_to_add(C, Complex([X, Y]))
    assert species_to_add is None
    #C contains more species than Complex([X, X])
    species_to_add = CC.compute_species_to_add(C, Complex([X, X]))
    assert species_to_add is None
    #S is not in C
    species_to_add = CC.compute_species_to_add(Species("S"), C)
    assert species_to_add is None
    species_to_add = CC.compute_species_to_add(Complex([Species("S"), X]), C)
    assert species_to_add is None
def pass_test_CombinatorialConformation_compute_complexes_to_add_to_polymer():
    X, Y, Z = Species("X"), Species("Y"), Species("Z")
    p0 = OrderedPolymerSpecies([X])
    p1 = OrderedPolymerSpecies([X, Y, Z])
    p2 = OrderedPolymerSpecies([Z, Y, X])
    p3 = OrderedPolymerSpecies([Complex([X, X]), Y, Complex([X, Z])])

    CC = CombinatorialConformation(initial_states=[], final_states=[])

    #An empty list is returned if the Polymers are the same ("Nothing to add")
    complexes_to_add = CC.compute_complexes_to_add_to_polymer(p0, p0)
    assert len(complexes_to_add) == 0

    #None is returned if the Polymers cannot be converted
    complexes_to_add = CC.compute_complexes_to_add_to_polymer(p0, p1)
    assert complexes_to_add == None
    complexes_to_add = CC.compute_complexes_to_add_to_polymer(p1, p2)
    assert complexes_to_add == None

    #Basic Case
    complexes_to_add = CC.compute_complexes_to_add_to_polymer(p1, p3)
    assert len(complexes_to_add) == 2
    assert (0, [X]) in complexes_to_add and (2, [X]) in complexes_to_add

    #Nested Complex Case
    p4 = OrderedPolymerSpecies(
        [Complex([X, X]), Y, Complex([Z, Complex([X, X])])])
    complexes_to_add = CC.compute_complexes_to_add_to_polymer(p1, p4)
    assert len(complexes_to_add) == 2
    assert (0, [X]) in complexes_to_add and (2, [Complex([X, X])
                                                 ]) in complexes_to_add

    #These cases should give errors
    with pytest.raises(ValueError):
        CC.compute_complexes_to_add_to_polymer(X, p4)
    with pytest.raises(ValueError):
        CC.compute_complexes_to_add_to_polymer(p1, X)
示例#19
0
    def test_add_attribute(self):
        from biocrnpyler import Species

        species = Species(name='test_species')

        with self.assertRaises(AssertionError):
            species.add_attribute({'k': 'v'})

        species.add_attribute('attribute')
示例#20
0
    def test_add_attribute(self):
        species = Species(name='test_species')
        # an attribute must be a string
        with self.assertRaisesRegexp(AssertionError,f'must be an alpha-numeric string'):
            species.add_attribute({'k': 'v'})

        species.add_attribute('attribute')
        # testing whether a valid attribute has been added to the attribute list
        self.assertTrue('attribute' in species.attributes)
    def test_update_species(self):
        from biocrnpyler import CombinatorialPromoter, Protein, Species, Combinatorial_Cooperative_Binding, \
                                    DNAassembly,Transcription_MM, Translation_MM, Complex
        #make a complicated promoter
        newprom = CombinatorialPromoter("testprom",["treg1",Species("treg2",material_type="rna")],\
                                tx_capable_list = [["treg1","treg2"]],cooperativity={"testprom_treg2":1},leak=True)

        sp_rnap = Species("RNAP",material_type="protein")
        ribosome = Species("Ribo", material_type = "protein")

        newdna = DNAassembly("testDNA",promoter=newprom)
        newdna.add_mechanisms({"transcription":Transcription_MM(rnap = sp_rnap), "translation":Translation_MM(ribosome = ribosome)})
        newdna.update_parameters(parameters={"cooperativity":2,"kb":100, "ku":10, "ktx":.05, "ktl":.2, "kdeg":2})

        #Promoters are copied when added to DNAassemblies
        newprom_copy = newdna.promoter
        newprom_spec = newprom_copy.update_species()

        sp_treg1 = Species("treg1",material_type="protein")
        sp_treg2 = Species("treg2",material_type="rna")

        sp_dna = Species("testDNA",material_type="dna")
        
        sp_rna = Species("testDNA",material_type="rna")
        cp_dna_rnap = Complex([sp_dna,sp_rnap])
        cp_dna_treg1 = Complex([sp_dna,sp_treg1,sp_treg1])
        cp_dna_treg2 = Complex([sp_dna,sp_treg2])
        cp_dna_treg1_rnap = Complex([cp_dna_treg1,sp_rnap])
        cp_dna_treg2_rnap = Complex([cp_dna_treg2,sp_rnap])
        cp_dna_treg1_treg2 = Complex([sp_dna,sp_treg1,sp_treg1,sp_treg2])
        cp_dna_treg1_treg2_rnap = Complex([cp_dna_treg1_treg2,sp_rnap])

        knownspecies = [sp_dna,sp_rnap,sp_rna,cp_dna_rnap,cp_dna_treg1,\
                            cp_dna_treg2,cp_dna_treg1_treg2,cp_dna_treg1_rnap, \
                                cp_dna_treg2_rnap,cp_dna_treg1_treg2_rnap,sp_treg1,sp_treg2]

        #these are the species that should come out
        test_set = set([str(a) for a in newprom_spec])

        mistake_found = False
        error_txt = ""
        for known_spec in knownspecies:
            #go through and check each species if it's in the set generated by the promoter
            if(str(known_spec) not in test_set):
                error_txt += "\ncouldn't find "+str(known_spec)
                mistake_found = True
        
        if mistake_found:
            raise ValueError(f"Mistake found in Species output:{error_txt}. Returned Species: {test_set}.")
        #we should have the correct length of species
        self.assertTrue(len(test_set)==len(knownspecies))
        self.assertTrue(not mistake_found)
示例#22
0
def test_promoter_terminator_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"))
    }

    #minimal RNA transcription
    x = DNA_construct([P, T], mechanisms=mechs, parameters=parameters)
    y = x.enumerate_components()
    assert (y[0] == x[0])  #correct promoter is returned
    assert (
        x[0].transcript == y[1].get_species()
    )  #promoter in the DNA_construct has the correct transcript species
    assert (y[1].promoter == x[0]
            )  #rna is linked back to the DNA_construct's promoter
    assert (y[1].promoter == y[0]
            )  #correct promoter is returned by enumerate_constructs

    #"incoherent" transcription
    x = DNA_construct([[P, "reverse"], T],
                      mechanisms=mechs,
                      parameters=parameters)
    y = x.enumerate_components()
    assert (y == [x[0]])  #correct promoter is returned

    #transcription in reverse works as well
    x = DNA_construct([T, [P, "reverse"]],
                      mechanisms=mechs,
                      parameters=parameters)
    y = x.enumerate_components()
    assert (y[0] == x[1])  #correct promoter is returned
    assert (
        x[1].transcript == y[1].get_species()
    )  #promoter in the DNA_construct has the correct transcript species
    assert (y[1].promoter == x[1]
            )  #rna is linked back to the DNA_construct's promoter
    assert (y[1].promoter == y[0]
            )  #correct promoter is returned by enumerate_constructs
示例#23
0
    def test_complex_set_equality(self):
        from biocrnpyler import Reaction
        from biocrnpyler import Species

        rxn1 = Reaction(inputs=[], outputs=[], k=0.1)
        rxn2 = Reaction(inputs=[], outputs=[], k=0.1)

        rtn = Reaction.complex_set_equality(c1=rxn1.inputs,
                                            c1_coefs=rxn1.input_coefs,
                                            c2=rxn2.inputs,
                                            c2_coefs=rxn2.output_coefs)
        self.assertTrue(rtn)

        sp1 = Species(name='test_species_a')
        sp2 = Species(name='test_species_b')

        rxn1 = Reaction(inputs=[sp1], outputs=[], k=0.1)
        rxn2 = Reaction(inputs=[sp2], outputs=[], k=0.1)

        rtn2 = Reaction.complex_set_equality(c1=rxn1.inputs,
                                             c1_coefs=rxn1.input_coefs,
                                             c2=rxn2.inputs,
                                             c2_coefs=rxn2.output_coefs)
        self.assertFalse(rtn2)
示例#24
0
    def test_reaction_protection(self):
        #tests that Reactions cannot be changed once they are in a CRN
        S = Species("S")
        S2 = Species("S2")
        R = Reaction.from_massaction([S], [S2], k_forward=1.0)
        R2 = Reaction.from_massaction([S2], [S], k_forward=1.0)
        CRN = ChemicalReactionNetwork([S, S2], [R])

        #Internal reactions copied correctly to return
        assert R in CRN.reactions
        assert not R is CRN._reactions[0]

        #Returned list does not effect internal reactions
        CRN.reactions[0] = R2
        assert R2 not in CRN.reactions

        #add reactions effects internal reaction list
        CRN.add_reactions(R2)
        assert R2 in CRN.reactions
        assert not R2 is CRN._reactions[1]

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

        #test bypassing reaction protection
        CRN = ChemicalReactionNetwork([], [])
        CRN.add_reactions([R], copy_reactions=False)
        assert R is CRN._reactions[0]
        assert S in CRN.species

        #test bypassing reaction protection
        CRN = ChemicalReactionNetwork([], [])
        CRN.add_reactions([R], add_species=False)
        assert not S in CRN.species
示例#25
0
    def test_reaction_initialization(self):
        # warns if both input and output species are empty
        mak = MassAction(k_forward=0.1)
        with self.assertWarns(Warning):
            Reaction(inputs=[], outputs=[], propensity_type=mak)

        # test for invalid propensity type
        with self.assertRaises(ValueError):
            Reaction(inputs=[], outputs=[], propensity_type=Species)

        # input must be a valid species object
        with self.assertRaises(TypeError):
            Reaction(inputs=['a'], outputs=[], propensity_type=mak)
        # output must be a valid species object
        with self.assertRaises(TypeError):
            Reaction(inputs=[], outputs=['b'], propensity_type=mak)

        rxn = Reaction.from_massaction(inputs=[], outputs=[], k_forward=0.1, k_reverse=1)
        # test whether the reaction is registered as reversible
        self.assertTrue(rxn.is_reversible)
        # test whether the reaction is registered as massaction
        self.assertTrue(isinstance(rxn.propensity_type, MassAction))

        # test WeightedSpecies inputs
        sp1 = Species(name='test_species_a')
        sp2 = Species(name='test_species_b')
        chem_com_sp1 = WeightedSpecies(species=sp1, stoichiometry=2)
        chem_com_sp2 = WeightedSpecies(species=sp2, stoichiometry=1)
        Reaction(inputs=[chem_com_sp1], outputs=[chem_com_sp2], propensity_type=MassAction(k_forward=1))

        # test different input and output lists
        Reaction(inputs=[chem_com_sp1], outputs=[sp2], propensity_type=MassAction(k_forward=1))

        # mixing WeightedSpecies and Species is not allowed
        with self.assertRaises(TypeError):
            Reaction(inputs=[chem_com_sp1, sp2], outputs=[sp1], propensity_type=MassAction(k_forward=1))
示例#26
0
    def test_add_components(self):
        from biocrnpyler import Mixture
        from biocrnpyler import Component
        from biocrnpyler import Species

        mixture = Mixture()
        self.assertTrue(len(mixture.components) == 0)
        component = Component('test_comp')
        mixture.add_components(component)

        self.assertTrue(component in mixture.components)

        species = Species('test_species')
        with self.assertRaises(AssertionError):
            mixture.add_components(species)
示例#27
0
    def test_rna_degredation_mm(self):

        M = Mixture(parameters = {"kdeg":1, "kb":1, "ku":1})

        rnaase = Species("P")
        rna = Species("X", material_type = "rna")

        #compare deg_Tagged_Degredation to MichaelisMenten
        MM = MichaelisMenten(name = "name", mechanism_type = "type")
        
        rdmm = Degredation_mRNA_MM(rnaase)
        #test default global mechanism parameters
        self.assertTrue(rdmm.recursive_species_filtering is True)
        self.assertTrue(rdmm.default_on is False)
        self.assertTrue("rna" in rdmm.filter_dict)
        self.assertTrue(rdmm.filter_dict["rna"] is True)
        self.assertTrue(len(rdmm.filter_dict)==2)

        #test default functionality on a tagged species
        species = rdmm.update_species(rna, M)
        rxns = rdmm.update_reactions(rna, M)
        species_mm = MM.update_species(Enzyme = rnaase, Sub = rna, Prod = None)
        rxns_mm = MM.update_reactions(Enzyme = rnaase, Sub = rna, Prod = None, kb=1, ku=1, kcat=1)

        #species
        self.assertTrue(species_mm == species)
        #reactions
        self.assertTrue(all([str(rxns[i]) == str(rxns_mm[i]) for i in range(len(rxns))]))

        #Overwrite default_on, recursive_species_filtering, and filter_dict
        rdmm2 = Degredation_mRNA_MM(rnaase, default_on = True, recursive_species_filtering = False, filter_dict = {"test":True})
        self.assertTrue(rdmm2.recursive_species_filtering is False)
        self.assertTrue(rdmm2.default_on is True)
        self.assertTrue("rna" not in rdmm2.filter_dict)
        self.assertTrue("test" in rdmm2.filter_dict and rdmm2.filter_dict["test"] is True)
        self.assertTrue(len(rdmm2.filter_dict)==1)
示例#28
0
def test_degenerate_polymer_conformation():
    S = Species("S")
    p = OrderedPolymerSpecies([S, S, S])
    pc = PolymerConformation(polymer=p)

    c1 = Complex([pc.polymers[0][0], pc.polymers[0][1]])
    pc1 = c1.parent

    c2 = Complex([pc.polymers[0][1], pc.polymers[0][2]])
    pc2 = c2.parent

    c3 = Complex([pc.polymers[0][0], pc.polymers[0][2]])
    pc3 = c3.parent

    assert pc1 != pc2 != pc3
    def test_update_species(self):
        from biocrnpyler import CombinatorialPromoter, Protein, Species, Combinatorial_Cooperative_Binding, \
                                    DNAassembly,Transcription_MM, Translation_MM, Multimer, ComplexSpecies
        #make a complicated promoter
        newprom = CombinatorialPromoter("testprom",["treg1",Species("treg2",material_type="rna")],\
                                tx_capable_list = [["treg1","treg2"]],cooperativity={"testprom_treg2":1},leak=True)

        newdna = DNAassembly("testDNA", promoter=newprom)
        newdna.update_mechanisms(mechanisms={
            "transcription": Transcription_MM(),
            "translation": Translation_MM()
        })
        newdna.update_parameters(
            parameters={
                "cooperativity": 2,
                "kb": 100,
                "ku": 10,
                "ktx": .05,
                "ktl": .2,
                "kdeg": 2
            })
        newprom_spec = newprom.update_species()

        sp_treg1 = Species("treg1", material_type="protein")
        sp_treg2 = Species("treg2", material_type="rna")
        #mu_treg2 = Multimer(sp_treg2,2)

        sp_dna = Species("testDNA", material_type="dna")
        sp_rnap = Species("RNAP", material_type="protein")
        sp_rna = Species("testDNA", material_type="rna")
        cp_dna_rnap = ComplexSpecies([sp_dna, sp_rnap])
        cp_dna_treg1 = ComplexSpecies([sp_dna, sp_treg1, sp_treg1])
        cp_dna_treg2 = ComplexSpecies([sp_dna, sp_treg2])
        cp_dna_treg1_rnap = ComplexSpecies([cp_dna_treg1, sp_rnap])
        cp_dna_treg2_rnap = ComplexSpecies([cp_dna_treg2, sp_rnap])
        cp_dna_treg1_treg2 = ComplexSpecies(
            [sp_dna, sp_treg1, sp_treg1, sp_treg2])
        cp_dna_treg1_treg2_rnap = ComplexSpecies([cp_dna_treg1_treg2, sp_rnap])

        knownspecies = [sp_dna,sp_rnap,sp_rna,cp_dna_rnap,cp_dna_treg1,\
                            cp_dna_treg2,cp_dna_treg1_treg2,cp_dna_treg1_rnap, \
                                cp_dna_treg2_rnap,cp_dna_treg1_treg2_rnap]

        #these are the species that should come out
        test_set = set([str(a) for a in newprom_spec])
        mistake_found = False
        #we should have the correct length of species
        self.assertTrue(len(test_set) == len(knownspecies))
        for known_spec in knownspecies:
            #go through and check each species if it's in the set generated by the promoter
            if (str(known_spec) not in test_set):
                print("couldn't find " + str(known_spec))
                mistake_found = True
                break
        self.assertTrue(not mistake_found)
示例#30
0
def test_weighted_species_init():
    s1 = Species(name='a')
    # normal operations
    ws1 = WeightedSpecies(species=s1)
    assert ws1.species == s1
    assert ws1.stoichiometry == 1

    with pytest.raises(ValueError,
                       match='Stoichiometry must be positive integer!'):
        WeightedSpecies(species=s1, stoichiometry=0)

    with pytest.raises(ValueError,
                       match='Stoichiometry must be positive integer!'):
        WeightedSpecies(species=s1, stoichiometry=-1)

    ws2 = WeightedSpecies(species=s1, stoichiometry=1.34)
    assert ws2.stoichiometry == 1