Beispiel #1
0
 def setUp(self):
     # load a rpSBML file
     self.rpsbml = rpSBML(
         os_path.join(os_path.dirname(__file__), 'data', 'rpsbml.xml'))
     self.gem = rpSBML(
         os_path.join(os_path.dirname(__file__), 'data', 'gem.xml'))
     self.rpsbml_name = 'RetroPath_Pathway_1_1'
     self.rpsbml_score = 0.5684564101634014
     with open(os_path.join(os_path.dirname(__file__), 'data', 'data.json'),
               'r') as f:
         self.data = json_load(f)
Beispiel #2
0
 def test_pfba(self):
     rpsbml = rpSBML(os_path.join('data', 'merged.xml'))
     obj_value, rpsbml = rp_pfba(rpsbml, 'RP1_sink')
     self.assertTrue(rpsbml)
     self.assertAlmostEqual(obj_value, 859.3846153846168)
     # make sure that the results are written to the file
     all_json = rpsbml.genJSON()
     self.assertAlmostEqual(all_json['pathway']['brsynth']['fba_obj_RP1_sink']['value'], 859.3846153846168)
Beispiel #3
0
 def test_fraction(self):
     rpsbml = rpSBML(os_path.join('data', 'merged.xml'))
     obj_value, rpsbml = rp_fraction(rpsbml, 'biomass', 1.0, 'RP1_sink', 1.0)
     self.assertTrue(rpsbml)
     self.assertAlmostEqual(obj_value, 2.3076923076923888)
     # make sure that the results are written to the file
     all_json = rpsbml.genJSON()
     self.assertAlmostEqual(all_json['pathway']['brsynth']['fba_obj_RP1_sink__restricted_biomass']['value'], 2.3076923076923888)
     self.assertAlmostEqual(all_json['pathway']['brsynth']['fba_obj_biomass']['value'], 3.6794124272706443)
Beispiel #4
0
 def test_print_rpSBML(self):
     rpsbml = rpSBML(name='rpSBML_test')
     rpsbml.genericModel('RetroPath_Pathway_test', 'RP_model_test',
                         self.comp_xref, 'MNXC3', 999999, 0)
     rpsbml.createPathway('rp_pathway')
     rpsbml.createPathway('central_species')
     with NamedTemporaryFile() as tempf:
         rpsbml.writeSBML(tempf.name)
         self.assertListEqual(
             list(io_open(tempf.name)),
             list(io_open(os_path.join('data', 'rpSBML_test_sbml.xml'))))
Beispiel #5
0
    def addInChiKey(self, input_sbml, output_sbml):
        """Check the MIRIAM annotation for MetaNetX or CHEBI id's and try to recover the inchikey from cache and add it to MIRIAM

        :param input_sbml: SBML file input
        :param output_sbml: Output SBML file

        :type input_sbml: str
        :type output_sbml: str

        :rtype: bool
        :return: Success or failure of the function
        """
        filename = input_sbml.split('/')[-1].replace('.rpsbml', '').replace(
            '.sbml', '').replace('.xml', '')
        self.logger.debug(filename)
        rpsbml = rpSBML(inFile=input_sbml)
        for spe in rpsbml.getModel().getListOfSpecies():
            inchikey = None
            miriam_dict = rpsbml.readMIRIAMAnnotation(spe.getAnnotation())
            if 'inchikey' in miriam_dict:
                self.logger.info('The species ' + str(spe.id) +
                                 ' already has an inchikey... skipping')
                continue
            try:
                for mnx in miriam_dict['metanetx']:
                    inchikey = self.cid_strc[self.rpcache._checkCIDdeprecated(
                        mnx, self.deprecatedCID_cid)]['inchikey']
                    if inchikey:
                        rpsbml.addUpdateMIRIAM(spe, 'species',
                                               {'inchikey': [inchikey]})
                    else:
                        self.logger.warning('The inchikey is empty for: ' +
                                            str(spe.id))
                    continue
            except KeyError:
                try:
                    for chebi in miriam_dict['chebi']:
                        inchikey = self.cid_strc[
                            self.rpcache._checkCIDdeprecated(
                                self.chebi_cid[chebi],
                                self.deprecatedCID_cid)]['inchikey']
                        if inchikey:
                            rpsbml.addUpdateMIRIAM(spe, 'species',
                                                   {'inchikey': [inchikey]})
                        else:
                            self.logger.warning('The inchikey is empty for: ' +
                                                str(spe.id))
                        continue
                except KeyError:
                    self.logger.warning('Cannot find the inchikey for: ' +
                                        str(spe.id))
        writeSBMLToFile(rpsbml.document, output_sbml)
        return True
Beispiel #6
0
 def test_createReturnFluxParameter(self):
     #return feature
     param = self.rpsbml.createReturnFluxParameter(None,
                                                   parameter_id='B_999999')
     self.assertEqual(param.id, 'B_999999')
     self.assertEqual(param.value, 999999.0)
     #create feature
     new = rpSBML('test')
     new.createModel('test_name', 'test_id')
     param = new.createReturnFluxParameter(8888.0)
     self.assertEqual(param.id, 'B_8888_0')
     self.assertEqual(param.value, 8888.0)
Beispiel #7
0
def runFBA(
        sbml_path,
        gem_sbml,
        outFile,
        sim_type,
        source_reaction,
        target_reaction,
        source_coefficient,
        target_coefficient,
        is_max,
        fraction_of,
        dont_merge=True,
        pathway_id='rp_pathway',
        objective_id=None,
        compartment_id='MNXC3',
        # fill_orphan_species=False,
        species_group_id='central_species',
        sink_species_group_id='rp_sink_species',
        logger=None):
    """Single rpSBML simulation

    :param file_name: The name of the model
    :param sbml_path: Path to the rpSBML file
    :param gem_sbml: Path to the GEM file
    :param sim_type: The type of simulation to use. Available simulation types include: fraction, fba, rpfba
    :param source_reaction: The reaction id of the source reaction.
    :param target_reaction: The reaction id of the target reaction. Note that if fba or rpfba options are used, then these are ignored
    :param source_coefficient: The source coefficient
    :param target_coefficient: The target coefficient
    :param is_max: Maximise or minimise the objective
    :param fraction_of: The fraction of the optimum. Note that this value is ignored is fba is used
    :param tmpOutputFolder: The path to the output document
    :param dont_merge: Output the merged model (Default: True)
    :param pathway_id: The id of the heterologous pathway (Default: rp_pathway)
    :param objective_id: Overwrite the auto-generated id of the results (Default: None)
    :param compartment_id: The SBML compartment id (Default: MNXC3)
    :param fill_orphan_species: Add pseudo reactions that consume/produce single parent species. Note in development
    :param species_group_id: The id of the central species (Default: central_species)
    :param sink_species_group_id: The id of the sink species (Default: rp_sink_species)

    :type inputTar: str
    :type gem_sbml: str
    :type sim_type: str
    :type source_reaction: str
    :type target_reaction: str
    :type source_coefficient: float
    :type target_coefficient: float
    :type is_max: bool
    :type fraction_of: float
    :type tmpOutputFolder: str
    :type dont_merge: bool
    :type num_workers: int
    :type pathway_id: str
    :type objective_id: str
    :type compartment_id: str
    :type fill_orphan_species: bool
    :type species_group_id: str
    :type sink_species_group_id: str

    :return: Succcess or failure of the function
    :rtype: bool
    """

    logger = logger or logging.getLogger(__name__)

    logger.info('--------- ' + str(outFile) + ' ------------')

    rpsbml = rpSBML(sbml_path, logger=logger)
    # Save the central species
    groups = rpsbml.getModel().getPlugin('groups')
    central = groups.getGroup(species_group_id)
    sink_group = groups.getGroup(sink_species_group_id)
    rp_group = groups.getGroup(pathway_id)
    cent_spe = [str(i.getIdRef()) for i in central.getListOfMembers()]
    sink_spe = [str(i.getIdRef()) for i in sink_group.getListOfMembers()]
    rp_reac = [str(i.getIdRef()) for i in rp_group.getListOfMembers()]
    logger.debug('old central species: ' + str(cent_spe))
    logger.debug('old sink species: ' + str(sink_spe))
    logger.debug('old rp reactions: ' + str(rp_reac))

    rpsbml_gem = rpSBML(gem_sbml, logger=logger)
    species_source_target, reactions_convert = rpSBML.mergeModels(
        rpsbml, rpsbml_gem, logger)
    # NOTE: reactions_convert is organised with key being the rpsbml reaction and value being the rpsbml_gem value`
    # BUG: when merging the RP1_sink (very rare cases) can be recognised if another reaction contains the same species as a reactant
    ## under such as scenario the algorithm will consider that they are the same -- TODO: overwrite it
    if target_reaction in reactions_convert:
        logger.warning('The target_reaction (' + str(target_reaction) +
                       ') has been detected in model ' + str(outFile) +
                       ', ignoring this model...')
        return False
    rev_reactions_convert = {v: k for k, v in reactions_convert.items()}
    logger.debug('species_source_target: ' + str(species_source_target))
    logger.debug('reactions_convert: ' + str(reactions_convert))
    logger.debug('rev_reactions_convert: ' + str(rev_reactions_convert))

    # TO TEST MERGE: TO REMOVE
    # rpsbml_gem.modelName = 'test'
    # rpsbml_gem.writeSBML('/home/mdulac/workspace/Galaxy-SynBioCAD/rpFBA/rpFBA_image/tmp_out/')
    ####### fraction of reaction ######
    # Choose the good function according to 'sim_type' argument
    sim_func = globals()['rp_' + sim_type]
    obj_val, rpsbml_gem = sim_func(rpsbml_gem, source_reaction,
                                   source_coefficient, target_reaction,
                                   target_coefficient, fraction_of, is_max,
                                   pathway_id, objective_id, logger)
    # ####### FBA ########
    # elif sim_type=='fba':
    #     obj_val,rpsbml_gem = fba(rpsbml_gem,
    #                                   source_reaction, source_coefficient,
    #                                   target_reaction, target_coefficient,
    #                                   fraction_of,
    #                                   is_max,
    #                                   pathway_id, objective_id)
    # ####### pFBA #######
    # elif sim_type=='pfba':
    #     obj_val,rpsbml_gem = pfba(rpsbml_gem,
    #                                   source_reaction, source_coefficient,
    #                                   target_reaction, target_coefficient,
    #                                   fraction_of,
    #                                   is_max,
    #                                   pathway_id, objective_id)
    # else:
    #     logger.error('Cannot recognise sim_type: '+str(sim_type))
    '''
    ###### multi objective #####
    elif sim_type=='multi_fba':
        rpfba.runMultiObjective(reactions, coefficients, is_max, pathway_id)
    '''
    if dont_merge:
        logger.info('Returning model with heterologous pathway only')
        groups = rpsbml_gem.getModel().getPlugin('groups')
        rp_pathway = groups.getGroup(pathway_id)
        logger.debug('---- Reactions ----')
        for member in rp_pathway.getListOfMembers():
            #### reaction annotation
            logger.debug(member.getIdRef())
            reacFBA = rpsbml_gem.getModel().getReaction(member.getIdRef())
            logger.debug(reacFBA)
            try:
                #reacIN = rpsbml.model.getReaction(reactions_convert[member.getIdRef()])
                reacIN = rpsbml.getModel().getReaction(
                    rev_reactions_convert[member.getIdRef()])
            except KeyError:
                reacIN = rpsbml.getModel().getReaction(member.getIdRef())
            logger.debug(reacIN)
            logger.debug(reacFBA.getAnnotation())
            reacIN.setAnnotation(reacFBA.getAnnotation())
            #### species TODO: only for shadow price
        #### add groups ####
        source_groups = rpsbml_gem.getModel().getPlugin('groups')
        target_groups = rpsbml.getModel().getPlugin('groups')
        target_groupsID = [i.getId() for i in target_groups.getListOfGroups()]
        for source_group in source_groups.getListOfGroups():
            logger.info('Replacing group id: ' + str(source_group.getId()))
            if source_group.getId() == species_group_id:
                target_group = target_groups.getGroup(source_group.getId())
                # TODO: #### replace the new potentially incorect central species with the normal ones #####
                # delete all the previous members
                logger.info('Removing central_species')
                for i in range(target_group.getNumMembers()):
                    logger.debug('Deleting group member: ' +
                                 str(target_group.getMember(0).getIdRef()))
                    target_group.removeMember(0)
                # add the new ones
                for cs in cent_spe:
                    logger.info('Creating new member: ' + str(cs))
                    newM = target_group.createMember()
                    newM.setIdRef(cs)
            elif source_group.getId() == sink_species_group_id:
                target_group = target_groups.getGroup(source_group.getId())
                logger.info('Removing sink species')
                for i in range(target_group.getNumMembers()):
                    logger.info('Deleting group member: ' +
                                str(target_group.getMember(0).getIdRef()))
                    target_group.removeMember(0)
                #add the new ones
                for cs in sink_spe:
                    logger.info('Creating new member: ' + str(cs))
                    newM = target_group.createMember()
                    newM.setIdRef(cs)
            elif source_group.getId() in target_groupsID:
                target_group = target_groups.getGroup(source_group.getId())
                target_group.setAnnotation(source_group.getAnnotation())
            '''
            elif source_group.getId()==pathway_id:
                target_group = target_groups.getGroup(source_group.getId())
                logger.debug('Removing rp ractions')
                for i in range(target_group.getNumMembers()):
                    logger.debug('Deleting group member: '+str(target_group.getMember(0).getIdRef()))
                    target_group.removeMember(0)
                #add the new ones
                for cs in rp_reac:
                    logger.debug('Creating new member: '+str(cs))
                    newM = target_group.createMember()
                    newM.setIdRef(cs)
            '''
        #### add objectives ####
        source_fbc = rpsbml_gem.getModel().getPlugin('fbc')
        target_fbc = rpsbml.getModel().getPlugin('fbc')
        target_objID = [i.getId() for i in target_fbc.getListOfObjectives()]
        for source_obj in source_fbc.getListOfObjectives():
            source_obj_id = source_obj.getId()
            if source_obj.getId() in target_objID:
                target_obj = target_fbc.getObjective(source_obj.getId())
                target_obj.setAnnotation(source_obj.getAnnotation())
                for target_fluxObj in target_obj.getListOfFluxObjectives():
                    for source_fluxObj in source_obj.getListOfFluxObjectives():
                        if target_fluxObj.getReaction(
                        ) == source_fluxObj.getReaction():
                            target_fluxObj.setAnnotation(
                                source_fluxObj.getAnnotation())
            else:
                target_fbc.addObjective(source_obj)
        #rpsbml.createMultiFluxObj('obj_RP1_sink', ['RP1_sink'], [1])
        target_fbc.setActiveObjectiveId(
            source_obj_id)  #tmp random assigenement of objective
        rpsbml.writeSBML(outFile)
    else:
        logger.info('Returning the full model')
        rpsbml_gem.writeSBML(outFile)
    return True
Beispiel #8
0
 def test_initWithNothing(self):
     rpsbml = rpSBML()
     self.assertEqual(rpsbml.getName(), 'dummy')
Beispiel #9
0
 def test_initWithModelName(self):
     rpsbml = rpSBML(name=self.rpsbml.getName())
     self.assertEqual(rpsbml.getName(), self.rpsbml_name)
Beispiel #10
0
 def test_initWithDocument(self):
     rpsbml = rpSBML(document=self.rpsbml.getDocument())
     self.assertEqual(rpsbml.getName(), self.rpsbml_name)
Beispiel #11
0
 def test_initEmpty(self):
     rpSBML('rpSBML_test')
Beispiel #12
0
 def setUp(self):
     # load a rpSBML file
     rpsbml = rpSBML(
         os_path.join(os_path.dirname(__file__), 'data', 'rpsbml.xml'))
     self.rpgraph = rpGraph(rpsbml)