def _build_promconstraint(meth, model_id):
    """Generates an SBML file for the specified model.
        
        :param fba_model_id: an FBA model id
        :type fba_model_id: kbtypes.KBaseFBA.FBAModel
        :ui_name fba_model_id: FBA Model ID
        
        :return: SBML File Downlaod
        :rtype: kbtypes.Unicode
        :output_widget: DownloadFileWidget
        """
    meth.stages = 2  # for reporting progress
    meth.advance("Building model SBML file...")
    
    #grab token and workspace info, setup the client
    userToken, workspaceName = meth.token, meth.workspace_id
    fbaClient = fbaModelServices(url=service.URLS.fba,token=userToken)
    
    # create the model object
    export_model_params = {
        'model': model_id,
        'workspace': workspaceName,
        'format': "sbml"
    }
    
    sbmlfile = fbaClient.export_fbamodel(export_model_params)

    return json.dumps({'data': sbmlfile, 'name': model_id+'.sbml'})
def _reconcile_phenotype(meth, fba_model_id, phenotype_id, out_model_id):
    """Run Gapfilling on an FBA Model [16]

    :param fba_model_id: an FBA model id [16.1]
    :type fba_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name fba_model_id: FBA Model ID
    :param phenotype_id: a phenotype simulation ID [16.2]
    :type phenotype_id: kbtypes.KBasePhenotypes.PhenotypeSimulationSet
    :ui_name phenotype_id: Phenotype Simulation Dataset ID
    :param out_model_id: a name for the generated FBA Model (optional) [16.3]
    :type out_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name out_model_id: Output FBA Model Name
    :return: something
    :rtype: kbtypes.Unicode
    :output_widget: kbaseModelMetaNarrative
    """

    if not out_model_id:
        out_model_id = "model_" + ''.join([chr(random.randrange(0, 26) + ord('A')) for _ in xrange(8)])
    token = os.environ['KB_AUTH_TOKEN']
    workspace = os.environ['KB_WORKSPACE_ID']
    fbaClient = fbaModelServices(service.URLS.fba)
    wildtype_phenotype_reconciliation_params = {
        'auth': token, 
        'model_workspace': workspace,
        'model': fba_model_id,
        'phenotypeSet_workspace': workspace,
        'phenotypeSet': phenotype_id,
        'workspace': workspace, 
        'out_model': out_model_id,
    }
    job_id = fbaClient.queue_wildtype_phenotype_reconciliation(wildtype_phenotype_reconciliation_params)['id']
    return json.dumps({'ws_name': workspace, 'model_id': out_model_id, 'job_id': job_id})
def _reconcile_phenotype(meth, fba_model_id, phenotype_id, out_model_id):
    """Run Gapfilling on an FBA Model [16]

    :param fba_model_id: an FBA model id [16.1]
    :type fba_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name fba_model_id: FBA Model ID
    :param phenotype_id: a phenotype simulation ID [16.2]
    :type phenotype_id: kbtypes.KBasePhenotypes.PhenotypeSimulationSet
    :ui_name phenotype_id: Phenotype Simulation Dataset ID
    :param out_model_id: a name for the generated FBA Model (optional) [16.3]
    :type out_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name out_model_id: Output FBA Model Name
    :return: something
    :rtype: kbtypes.Unicode
    :output_widget: kbaseModelMetaNarrative
    """

    if not out_model_id:
        out_model_id = "model_" + ''.join([chr(random.randrange(0, 26) + ord('A')) for _ in xrange(8)])
    token = os.environ['KB_AUTH_TOKEN']
    workspace = os.environ['KB_WORKSPACE_ID']
    fbaClient = fbaModelServices(service.URLS.fba)
    wildtype_phenotype_reconciliation_params = {
        'auth': token, 
        'model_workspace': workspace,
        'model': fba_model_id,
        'phenotypeSet_workspace': workspace,
        'phenotypeSet': phenotype_id,
        'workspace': workspace, 
        'out_model': out_model_id,
    }
    job_id = fbaClient.queue_wildtype_phenotype_reconciliation(wildtype_phenotype_reconciliation_params)['id']
    return json.dumps({'ws_name': workspace, 'model_id': out_model_id, 'job_id': job_id})
def _view_media(meth, media_id):
    """Bring up a detailed view of a Media set within the narrative. [9]

    :param media_id: Media type [9.1]
    :type media_id: kbtypes.KBaseBiochem.Media
    :ui_name media_id: Media ID
    :return: A Media object
    :rtype: kbtypes.KBaseBiochem.Media
    :output_widget: kbaseMediaViewer
    :embed: True
    """
    meth.stages = 3
    meth.advance("Initializing")
    token, workspace_id = meth.token, meth.workspace_id

    fba = fbaModelServices(service.URLS.fba, token=token)

    meth.advance("Fetching Media from workspace")

    fetch_media_input = {
        'medias' : [media_id],
        'workspaces' : [workspace_id],
        'auth' : token
    }
    media = fba.get_media(fetch_media_input)

    meth.advance("Rendering Media object")

    result = {'metadata' : None, 'media' : media[0]}
    return json.dumps(result)
def _view_media(meth, media_id):
    """Bring up a detailed view of a Media set within the narrative. [9]

    :param media_id: Media type [9.1]
    :type media_id: kbtypes.KBaseBiochem.Media
    :ui_name media_id: Media ID
    :return: A Media object
    :rtype: kbtypes.KBaseBiochem.Media
    :output_widget: kbaseMediaViewer
    :embed: True
    """
    meth.stages = 3
    meth.advance("Initializing")
    token, workspace_id = meth.token, meth.workspace_id

    fba = fbaModelServices(service.URLS.fba, token=token)

    meth.advance("Fetching Media from workspace")

    fetch_media_input = {
        'medias' : [media_id],
        'workspaces' : [workspace_id],
        'auth' : token
    }
    media = fba.get_media(fetch_media_input)

    meth.advance("Rendering Media object")

    result = {'metadata' : None, 'media' : media[0]}
    return json.dumps(result)
def _build_promconstraint(meth, model_id):
    """Generates an SBML file for the specified model.
        
        :param fba_model_id: an FBA model id
        :type fba_model_id: kbtypes.KBaseFBA.FBAModel
        :ui_name fba_model_id: FBA Model ID
        
        :return: SBML File Downlaod
        :rtype: kbtypes.Unicode
        :output_widget: DownloadFileWidget
        """
    meth.stages = 2  # for reporting progress
    meth.advance("Building model SBML file...")
    
    #grab token and workspace info, setup the client
    userToken, workspaceName = meth.token, meth.workspace_id
    fbaClient = fbaModelServices(url=service.URLS.fba,token=userToken)
    
    # create the model object
    export_model_params = {
        'model': model_id,
        'workspace': workspaceName,
        'format': "sbml"
    }
    
    sbmlfile = fbaClient.export_fbamodel(export_model_params)

    return json.dumps({'data': sbmlfile, 'name': model_id+'.sbml'})
Esempio n. 7
0
def _import_seed_genomes(meth, genome_ids):
    """Import genomes from the pubSEED database. 
    
    :param genome_ids: list of genome ids (comma seperated)
    :type genome_ids: kbtypes.Unicode
    :ui_name genome_ids: SEED Genome IDs

    :return: Uploaded SEED Genome
    :rtype: kbtypes.Unicode
    :output_widget: GenomeAnnotation
    """
    #315750.3
    gids = genome_ids.split(',')

    meth.stages = len(gids)+1 # for reporting progress
    meth.advance("Starting...")
    
    #grab token and workspace info, setup the client
    token, ws = meth.token, meth.workspace_id;

    fba = fbaModelServices(url = service.URLS.fba, token = token)

    for gid in gids:
        meth.advance("Loading genome: "+gid);
        fba.genome_to_workspace({'genome': gid, 
                                 'workspace': ws, 
                                 'source': 'seed'})

    return json.dumps({'ws_name': ws, 'ws_id': gids[0]})
def _compare_models(meth, model_ids):
    """Compare two or models and compute core, noncore unique reactions, functional roles with their subsystem information. 
    
    :param model_ids: list of model ids (comma seperated)
    :type model_ids: kbtypes.KBaseFBA.FBAModel
    :ui_name model_ids: Model IDs

    :return: Uploaded Model Comparison Data
    :rtype: kbtypes.Unicode
    :output_widget: compmodels
    """
    mids = model_ids.split(',')

    meth.stages = len(mids)+1 # for reporting progress
    meth.advance("Starting...")
    
    #grab token and workspace info, setup the client
    token, ws = meth.token, meth.workspace_id;
    wss =[]
    fba = fbaModelServices(url = service.URLS.fba, token = token)

    for mid in mids:
        meth.advance("Loading models: "+mid);
        wss.append(ws)

    modelout =fba.compare_models({'models': mids, 
                                  'workspaces': wss,
                                  'workspace': ws})

    comparemod = modelout['model_comparisons']                               
    reactioncomp = modelout['reaction_comparisons']
    #print meth.debug(json.dumps(comparemod))
    #print meth.debug(json.dumps(reactioncomp))
    return json.dumps({'data': comparemod})
Esempio n. 9
0
def _init_clients():
    ws_c = Workspace(ws_url)
    # The KBase web-client instantiated below is being deprecated and no longer works for all functions.
    # A local work-around has been added using kb_sdk and fba_tools
    fba_c = fbaModelServices(fba_url)
    gap_c = LocalFbaModelServices
    return ws_c, fba_c, gap_c
def _compare_models(meth, model_ids):
    """Compare two or models and compute core, noncore unique reactions, functional roles with their subsystem information. 
    
    :param model_ids: list of model ids (comma seperated)
    :type model_ids: kbtypes.KBaseFBA.FBAModel
    :ui_name model_ids: Model IDs

    :return: Uploaded Model Comparison Data
    :rtype: kbtypes.Unicode
    :output_widget: compmodels
    """
    mids = model_ids.split(',')

    meth.stages = len(mids)+1 # for reporting progress
    meth.advance("Starting...")
    
    #grab token and workspace info, setup the client
    token, ws = meth.token, meth.workspace_id;
    wss =[]
    fba = fbaModelServices(url = service.URLS.fba, token = token)

    for mid in mids:
        meth.advance("Loading models: "+mid);
        wss.append(ws)

    modelout =fba.compare_models({'models': mids, 
                                  'workspaces': wss,
                                  'workspace': ws})

    comparemod = modelout['model_comparisons']                               
    reactioncomp = modelout['reaction_comparisons']
    #print meth.debug(json.dumps(comparemod))
    #print meth.debug(json.dumps(reactioncomp))
    return json.dumps({'data': comparemod})
Esempio n. 11
0
def _prepare_genome(meth, contig_set, scientific_name, genetic_code, out_genome):
    """Build a Genome object from a ContigSet, creating structural and functional annotations.
    The annotation job may run for an hour or longer. When the annotation job finishes,
    the annotated Genome object will be stored in your workspace. [3]

    :param contig_set: An object with contig data [3.1]
    :type contig_set: kbtypes.KBaseGenomes.ContigSet
    :ui_name contig_set: Contig Set Object
    :param scientific_name: enter the scientific name to assign to your new genome [3.2]
    :type scientific_name: kbtypes.Unicode
    :ui_name scientific_name: Scientific Name
    :param genetic_code: enter the genetic code for your new genome (default is 11) [3.2]
    :type genetic_code: kbtypes.Unicode
    :ui_name genetic_code: Genetic Code
    :param out_genome: Annotated output genome ID. If empty, an ID will be chosen randomly. [3.3]
    :type out_genome: kbtypes.KBaseGenomes.Genome
    :ui_name out_genome: Output Genome ID
    :return: Preparation message
    :rtype: kbtypes.Unicode
    :output_widget: GenomeAnnotation
    """
    if not scientific_name:
        return json.dump({'error': 'output genome name should be defined'})
    if not genetic_code:
        genetic_code = 11
    if not out_genome:
        out_genome = "genome_" + ''.join([chr(random.randrange(0, 26) + ord('A')) for _ in xrange(8)])
    meth.stages = 2
    meth.advance("Annotating the contigs (3-4 minutes)...")
    token = os.environ['KB_AUTH_TOKEN']
    workspace = os.environ['KB_WORKSPACE_ID']
    fbaClient = fbaModelServices(url = service.URLS.fba, token = token)
        # create the model object
    contigset_to_genome_params = {
        'auth': token,
        'ContigSet_ws': workspace,
        'ContigSet_uid': contig_set,
        'workspace': workspace,
        'uid': out_genome,
        'scientific_name': scientific_name,
        'domain': 'Bacteria',
        'genetic_code': genetic_code,
    }
    fbaClient.ContigSet_to_Genome(contigset_to_genome_params)
    wsClient = workspaceService(service.URLS.workspace, token=token)
    genomeData = wsClient.get_objects([{'ref': workspace+'/'+out_genome}])[0]
    genome = genomeData['data']
    meta = genomeData['info'][10]
    if not meta:
        meta = {}
    meta['Scientific name'] = scientific_name
    wsClient.save_objects({'workspace': workspace, 'objects': [{'type': 'KBaseGenomes.Genome', 'name': out_genome, 'data': genome, 'meta': meta}]})
    return json.dumps({'ws_name': workspace, 'ws_id': out_genome})
def _delete_reaction(meth, fba_model_id, reaction_id, output_id):
    """Delete reactions from selected Metabolic Model 
    
    :param fba_model_id: the metabolic model to edit
    :type fba_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name fba_model_id: Metabolic Model

    :param reaction_id: Reactions to be deleted. Add multiple reactions seperated by ; 
    :type reaction_id: kbtypes.Unicode
    :ui_name reaction_id: Reaction(s) ID(s)

    :param output_id: ID of model with deleted reactions
    :type output_id: kbtypes.KBaseFBA.FBAModel
    :ui_name output_id: Edited Model

    :return: Metabolic Model Data
    :rtype: kbtypes.Model
    :output_widget: kbaseModelTabs    
    """
    meth.debug('delete reaction call')

    meth.stages = 2  # for reporting progress
    meth.advance("Starting...")
    
    #grab token and workspace info, setup the client
    token, ws = meth.token, meth.workspace_id;
    #meth.advance("Loading the phenotype set")
    #
    fba = fbaModelServices(service.URLS.fba, token=token)

    meth.debug(output_id)
    if output_id:
        params = {'model': fba_model_id, 
                   'workspace': ws,
                   'reaction' : reaction_id.split(';'), 
                   'removeReaction': 1,
                   'outputid': output_id }
    else:
        params = {'model': fba_model_id, 
                   'workspace': ws,
                   'reaction' : reaction_id.split(';'), 
                   'removeReaction': 1}


    data = fba.adjust_model_reaction(params)

    if output_id:
        data = json.dumps({'id': output_id, 'ws': ws})
    else:
        data = json.dumps({'id': fba_model_id, 'ws': ws})        

    return data
def _delete_reaction(meth, fba_model_id, reaction_id, output_id):
    """Delete reactions from selected Metabolic Model 
    
    :param fba_model_id: the metabolic model to edit
    :type fba_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name fba_model_id: Metabolic Model

    :param reaction_id: Reactions to be deleted. Add multiple reactions seperated by ; 
    :type reaction_id: kbtypes.Unicode
    :ui_name reaction_id: Reaction(s) ID(s)

    :param output_id: ID of model with deleted reactions
    :type output_id: kbtypes.KBaseFBA.FBAModel
    :ui_name output_id: Edited Model

    :return: Metabolic Model Data
    :rtype: kbtypes.Model
    :output_widget: kbaseModelTabs    
    """
    meth.debug('delete reaction call')

    meth.stages = 2  # for reporting progress
    meth.advance("Starting...")
    
    #grab token and workspace info, setup the client
    token, ws = meth.token, meth.workspace_id;
    #meth.advance("Loading the phenotype set")
    #
    fba = fbaModelServices(service.URLS.fba, token=token)

    meth.debug(output_id)
    if output_id:
        params = {'model': fba_model_id, 
                   'workspace': ws,
                   'reaction' : reaction_id.split(';'), 
                   'removeReaction': 1,
                   'outputid': output_id }
    else:
        params = {'model': fba_model_id, 
                   'workspace': ws,
                   'reaction' : reaction_id.split(';'), 
                   'removeReaction': 1}


    data = fba.adjust_model_reaction(params)

    if output_id:
        data = json.dumps({'id': output_id, 'ws': ws})
    else:
        data = json.dumps({'id': fba_model_id, 'ws': ws})        

    return data
def _translate_model_to_new_genome(meth, fba_model_id, proteome_cmp, remove_nogene, output_id):
    """ Functionality to assign a new genome to an imported model. 
    A proteome comparison is done between the orginal model genome 
    and the new desired genome. Metoblic reactions from original model 
    get mapped to genes in the new genome'.  [19]
     
    :param fba_model_id: an FBA model id from first genome [19.1]
    :type fba_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name fba_model_id: FBA Model ID

    :param proteome_cmp: Proteome comparison ID [19.3]
    :type proteome_cmp: kbtypes.GenomeComparison.ProteomeComparison
    :ui_name proteome_cmp: Proteome Comparison ID
    
    :param remove_nogene: specify "yes" if reactions with no genes should be removed
    :type remove_nogene: kbtypes.Unicode
    :ui_name remove_nogene: Remove No-gene Reactions

    :param output_id: ID to which translated model should be saved
    :type output_id: kbtypes.KBaseFBA.FBAModel
    :ui_name output_id: Translated Model ID
    
    :return: Output Translated Model
    :rtype: kbtypes.KBaseFBA.FBAModel
    :output_widget: kbaseModelTabs
    """
    meth.stages = 2  # for reporting progress
    meth.advance("Translating model to new genome...")
    keep = 1;
    if remove_nogene == 'yes':
    	keep = 0;
    	
    token = os.environ['KB_AUTH_TOKEN']
    workspace = os.environ['KB_WORKSPACE_ID']
    fbaClient = fbaModelServices(url = service.URLS.fba, token = token)
    translate_params = {
                         'protcomp' : proteome_cmp,
                         'model' : fba_model_id,
                         'workspace' : workspace,
                         'keep_nogene_rxn': keep,
                         'output_id' : output_id}
    modeldata = fbaClient.translate_fbamodel(translate_params)
    
    return json.dumps({'ws': workspace, 'id': output_id})
def _translate_model_to_new_genome(meth, fba_model_id, proteome_cmp, remove_nogene, output_id):
    """ Functionality to assign a new genome to an imported model. 
    A proteome comparison is done between the orginal model genome 
    and the new desired genome. Metoblic reactions from original model 
    get mapped to genes in the new genome'.  [19]
     
    :param fba_model_id: an FBA model id from first genome [19.1]
    :type fba_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name fba_model_id: FBA Model ID

    :param proteome_cmp: Proteome comparison ID [19.3]
    :type proteome_cmp: kbtypes.GenomeComparison.ProteomeComparison
    :ui_name proteome_cmp: Proteome Comparison ID
    
    :param remove_nogene: specify "yes" if reactions with no genes should be removed
    :type remove_nogene: kbtypes.Unicode
    :ui_name remove_nogene: Remove No-gene Reactions

    :param output_id: ID to which translated model should be saved
    :type output_id: kbtypes.KBaseFBA.FBAModel
    :ui_name output_id: Translated Model ID
    
    :return: Output Translated Model
    :rtype: kbtypes.KBaseFBA.FBAModel
    :output_widget: kbaseModelTabs
    """
    meth.stages = 2  # for reporting progress
    meth.advance("Translating model to new genome...")
    keep = 1;
    if remove_nogene == 'yes':
    	keep = 0;
    	
    token = os.environ['KB_AUTH_TOKEN']
    workspace = os.environ['KB_WORKSPACE_ID']
    fbaClient = fbaModelServices(url = service.URLS.fba, token = token)
    translate_params = {
                         'protcomp' : proteome_cmp,
                         'model' : fba_model_id,
                         'workspace' : workspace,
                         'keep_nogene_rxn': keep,
                         'output_id' : output_id}
    modeldata = fbaClient.translate_fbamodel(translate_params)
    
    return json.dumps({'ws': workspace, 'id': output_id})
def _compute_pan_genome(meth, genome_set,pangenome_id):
    """ Rapidly compute gene families for a set of phylogenetically close genomes

    :param genome_set: a Genome Set to compute pangenome for
    :type genome_set: kbtypes.KBaseSearch.GenomeSet
    :ui_name genome_set: Genome Set ID
    
    :param pangenome_id: ID for output pangenome
    :type pangenome_id: kbtypes.KBaseGenomes.Pangenome
    :ui_name pangenome_id: Pangenome ID
    
    :return: Generated Pangenome Object
    :rtype: kbtypes.KBaseGenomes.Pangenome
    :output_widget: kbasePanGenome
    """
    meth.stages = 2
    meth.advance("Computing pangenome (20 sec per genome)...")
    usertoken, workspace_id = meth.token, meth.workspace_id

    ws = workspaceService(service.URLS.workspace, token=usertoken)
    data = ws.get_objects([{'ref': workspace_id+'/'+genome_set}])[0]
    genome_set_elements = data['data']['elements']
    genomes = []
    gwss = []
    for key in genome_set_elements:
        array = genome_set_elements[key]['ref'].split('/')
        gwss.append(array[0])
        genomes.append(array[1])

    pangenome_parameters = {
        'genomes':genomes,
        'genome_workspaces':gwss,
        'workspace':workspace_id,
        'auth':usertoken,
        'wsurl':service.URLS.workspace}
    
    if pangenome_id:
        pangenome_parameters['output_id']=pangenome_id
    
    fbaclient = fbaModelServices(url = service.URLS.fba, token=usertoken)
    meta = fbaclient.build_pangenome(pangenome_parameters)
    
    return json.dumps({'ws': workspace_id, 'name':meta[1]})
def _simulate_phenotype(meth, model, phenotypeSet, phenotypeSimulationSet):
    """Simulate the growth of a model on a phenotype set.

    :param model: FBA model
    :type model: kbtypes.KBaseFBA.FBAModel
    :ui_name model: FBA Model
    
    :param phenotypeSet: Phenotype Set
    :type phenotypeSet: kbtypes.KBasePhenotypes.PhenotypeSet
    :ui_name phenotypeSet: Phenotype Set
    
    :param phenotypeSimulationSet: Name for result of phenotype simulation (optional)
    :type phenotypeSimulationSet: kbtypes.KBasePhenotypes.PhenotypeSimulationSet
    :ui_name phenotypeSimulationSet: Phenotype Simulation Result
    
    :return: Generated Phenotype Simulation Set ID
    :rtype: kbtypes.KBasePhenotypes.PhenotypeSimulationSet
    :output_widget: kbaseSimulationSet
    """
    meth.stages = 2  # for reporting progress
    meth.advance("Starting")
    meth.advance("Simulating Phenotypes")
    
    #grab token and workspace info, setup the client
    userToken, workspaceName = meth.token, meth.workspace_id
    fbaClient = fbaModelServices(service.URLS.fba,token=userToken)
    
    # create the model object
    simulate_phenotypes_params = {
        'workspace': workspaceName, 
        'phenotypeSimulationSet': phenotypeSimulationSet,
        'model_workspace': workspaceName,
        'model': model,
        'phenotypeSet_workspace': workspaceName,
        'phenotypeSet': phenotypeSet,
    }

    fba_meta_data = fbaClient.simulate_phenotypes(simulate_phenotypes_params)
    wsobj_id = fba_meta_data[0]
    name = fba_meta_data[1]
    
    return json.dumps({'name': name, 'ws': workspaceName})
def _simulate_phenotype(meth, model, phenotypeSet, phenotypeSimulationSet):
    """Simulate the growth of a model on a phenotype set.

    :param model: FBA model
    :type model: kbtypes.KBaseFBA.FBAModel
    :ui_name model: FBA Model
    
    :param phenotypeSet: Phenotype Set
    :type phenotypeSet: kbtypes.KBasePhenotypes.PhenotypeSet
    :ui_name phenotypeSet: Phenotype Set
    
    :param phenotypeSimulationSet: Name for result of phenotype simulation (optional)
    :type phenotypeSimulationSet: kbtypes.KBasePhenotypes.PhenotypeSimulationSet
    :ui_name phenotypeSimulationSet: Phenotype Simulation Result
    
    :return: Generated Phenotype Simulation Set ID
    :rtype: kbtypes.KBasePhenotypes.PhenotypeSimulationSet
    :output_widget: kbaseSimulationSet
    """
    meth.stages = 2  # for reporting progress
    meth.advance("Starting")
    meth.advance("Simulating Phenotypes")
    
    #grab token and workspace info, setup the client
    userToken, workspaceName = meth.token, meth.workspace_id
    fbaClient = fbaModelServices(service.URLS.fba,token=userToken)
    
    # create the model object
    simulate_phenotypes_params = {
        'workspace': workspaceName, 
        'phenotypeSimulationSet': phenotypeSimulationSet,
        'model_workspace': workspaceName,
        'model': model,
        'phenotypeSet_workspace': workspaceName,
        'phenotypeSet': phenotypeSet,
    }

    fba_meta_data = fbaClient.simulate_phenotypes(simulate_phenotypes_params)
    wsobj_id = fba_meta_data[0]
    name = fba_meta_data[1]
    
    return json.dumps({'name': name, 'ws': workspaceName})
Esempio n. 19
0
def _import_rast_genomes(meth, genome_ids, rast_username, rast_password):
    """Import genomes from the RAST annotation pipeline. 
    
    :param genome_ids: list of genome ids (comma seperated)
    :type genome_ids: kbtypes.Unicode
    :ui_name genome_ids: RAST Genome IDs
    
    :param rast_username: Your RAST Username
    :type rast_username: kbtypes.Unicode
    :ui_name rast_username: RAST Username

    :param rast_password: Your RAST Password
    :type rast_password: kbtypes.Unicode
    :ui_name rast_password: RAST Password

    :return: Uploaded RAST Genome
    :rtype: kbtypes.Unicode
    :output_widget: GenomeAnnotation
    :input_widget: rastGenomeImportInput
    """
    #315750.3
    gids = genome_ids.split(',')

    meth.stages = len(gids)+1 # for reporting progress
    meth.advance("Starting...")
    
    #grab token and workspace info, setup the client
    token, ws = meth.token, meth.workspace_id;

    fba = fbaModelServices(url = service.URLS.fba, token = token)

    for gid in gids:
        meth.advance("Loading genome: "+gid);
        fba.genome_to_workspace({'genome': gid, 
                                 'workspace': ws, 
                                 'sourceLogin': rast_username,
                                 'sourcePassword': rast_password,
                                 'source': 'rast'})


    return json.dumps({'ws_name': ws, 'ws_id': gids[0]})
def _build_promconstraint(meth, genome_id, series_id, regulome_id):
    """Given a gene expression series and a regulome, build a PROM constraint for FBA. [24]

    :param genome_id: Genome ID [24.1]
    :type genome_id: kbtypes.KBaseGenomes.Genome
    :ui_name genome_id: Genome Name
    
    :param series_id: Gene Expression Series ID [24.2]
    :type series_id: kbtypes.KBaseExpression.ExpressionSeries
    :ui_name series_id: Gene Expression Series Name
    
    :param regulome_id: Regulome ID [24.3]
    :type regulome_id: kbtypes.KBaseRegulation.Regulome
    :ui_name regulome_id: Regulome Name
    
    :return: Generated PROM constraint ID
    :rtype: kbtypes.KBaseFBA.PromConstraint
    :output_widget: kbasePromConstraint
    """
    meth.stages = 2  # for reporting progress
    meth.advance("Starting")
    meth.advance("Building your new PROM constraint")
    
    #grab token and workspace info, setup the client
    userToken, workspaceName = meth.token, meth.workspace_id
    fbaClient = fbaModelServices(url=service.URLS.fba,token=userToken)
    
    # create the model object
    build_pc_params = {
        'genome_id': genome_id,
        'series_id': series_id,
        'regulome_id': regulome_id,
        'workspace': workspaceName
    }

    fba_meta_data = fbaClient.create_promconstraint(build_pc_params)
    wsobj_id = fba_meta_data[0]
    name = fba_meta_data[1]
    
    return json.dumps({'name': name, 'ws': workspaceName})
def _build_promconstraint(meth, genome_id, series_id, regulome_id):
    """Given a gene expression series and a regulome, build a PROM constraint for FBA. [24]

    :param genome_id: Genome ID [24.1]
    :type genome_id: kbtypes.KBaseGenomes.Genome
    :ui_name genome_id: Genome Name
    
    :param series_id: Gene Expression Series ID [24.2]
    :type series_id: kbtypes.KBaseExpression.ExpressionSeries
    :ui_name series_id: Gene Expression Series Name
    
    :param regulome_id: Regulome ID [24.3]
    :type regulome_id: kbtypes.KBaseRegulation.Regulome
    :ui_name regulome_id: Regulome Name
    
    :return: Generated PROM constraint ID
    :rtype: kbtypes.KBaseFBA.PromConstraint
    :output_widget: kbasePromConstraint
    """
    meth.stages = 2  # for reporting progress
    meth.advance("Starting")
    meth.advance("Building your new PROM constraint")
    
    #grab token and workspace info, setup the client
    userToken, workspaceName = meth.token, meth.workspace_id
    fbaClient = fbaModelServices(url=service.URLS.fba,token=userToken)
    
    # create the model object
    build_pc_params = {
        'genome_id': genome_id,
        'series_id': series_id,
        'regulome_id': regulome_id,
        'workspace': workspaceName
    }

    fba_meta_data = fbaClient.create_promconstraint(build_pc_params)
    wsobj_id = fba_meta_data[0]
    name = fba_meta_data[1]
    
    return json.dumps({'name': name, 'ws': workspaceName})
def _build_media(meth, media):
    """Assemble a set of compounds to use as a media set for performing FBA on a metabolic model. [8]

    :param base_media: Base media type [8.1]
    :type base_media: kbtypes.KBaseBiochem.Media
    :ui_name base_media: Media ID
    :return: Metadata from new Media object
    :rtype: kbtypes.KBaseBiochem.Media
    :input_widget: kbaseBuildMediaInput
    :output_widget: kbaseMediaViewer
    :embed: True
    """
    meth.stages = 3

    meth.advance("Initializing")
    token, workspace_id = meth.token, meth.workspace_id

    fba = fbaModelServices(service.URLS.fba, token=token)

    media = json.loads(media)
    media['auth'] = token
    media['workspace'] = workspace_id

    meth.advance("Submitting Media to workspace")

    media_meta = fba.addmedia(media)

    meth.advance("Rendering new Media object")
    fetch_media_input = {
        'medias' : [media['name']],
        'workspaces' : [workspace_id],
        'auth' : token
    }
    new_media = fba.get_media(fetch_media_input)

    result = {'metadata': media_meta, 'media' : new_media[0] }
    return json.dumps(result)
def _build_media(meth, media):
    """Assemble a set of compounds to use as a media set for performing FBA on a metabolic model. [8]

    :param base_media: Base media type [8.1]
    :type base_media: kbtypes.KBaseBiochem.Media
    :ui_name base_media: Media ID
    :return: Metadata from new Media object
    :rtype: kbtypes.KBaseBiochem.Media
    :input_widget: kbaseBuildMediaInput
    :output_widget: kbaseMediaViewer
    :embed: True
    """
    meth.stages = 3

    meth.advance("Initializing")
    token, workspace_id = meth.token, meth.workspace_id

    fba = fbaModelServices(service.URLS.fba, token=token)

    media = json.loads(media)
    media['auth'] = token
    media['workspace'] = workspace_id

    meth.advance("Submitting Media to workspace")

    media_meta = fba.addmedia(media)

    meth.advance("Rendering new Media object")
    fetch_media_input = {
        'medias' : [media['name']],
        'workspaces' : [workspace_id],
        'auth' : token
    }
    new_media = fba.get_media(fetch_media_input)

    result = {'metadata': media_meta, 'media' : new_media[0] }
    return json.dumps(result)
def _compare_genomes(meth, pangenome_id):
    """Genome Comparison analysis based on the PanGenome input. 
    
    :param pangenome_id: Pangenome ID 
    :type pangenome_id: kbtypes.KBaseGenomes.Pangenome
    :ui_name pangenome_id: Pangenome ID

    :return: Uploaded Genome Comparison Data
    :rtype: kbtypes.KBaseGenomes.GenomeComparison
    :output_widget: kbaseGenomeComparisonViewer
    """
    meth.stages = 2
    meth.advance("Comparing all genomes in pangenome (1-2 minutes)...")
    
    #grab token and workspace info, setup the client
    token, ws = meth.token, meth.workspace_id;
    wss =[]
    fba = fbaModelServices(url = service.URLS.fba, token = token)

    meta = fba.compare_genomes({'pangenome_id': pangenome_id, 
                                'pangenome_ws': ws,
                                'workspace': ws })
    
    return json.dumps({'ws': meth.workspace_id, 'id':meta[1]})
Esempio n. 25
0
from biokbase.fbaModelServices.Client import fbaModelServices
import optparse
import subprocess
import sys

usage = """%prog object_type input_id_type output_id_type <input_ids, ;-delimited>
E.g. %prog compound ModelSEED name "cpd00001;cpd00002"
"""
description = """ Convert one type of alias into another. """
parser = optparse.OptionParser(usage=usage, description=description)
(options, args) = parser.parse_args()

if len(args) < 4:
    p = subprocess.Popen(["python", sys.argv[0], "-h"], stdout=subprocess.PIPE)
    stdout, stderr = p.communicate()
    print stdout
    exit(1)

fbaClient = fbaModelServices("http://localhost:7036")

input_params = { "object_type" : args[0],
                 "input_id_type" : args[1],
                 "output_id_type" : args[2],
                 "input_ids" : args[3].split(";")
                 }

aliaslist = fbaClient.get_alias(input_params)

for aliases in aliaslist:
    print aliases
def _genome_to_fba_model(meth, genome_id, fba_model_id):
    """Given an annotated Genome, build a draft metabolic model which can be analyzed with FBA. [6]

    :param genome_id: Source genome name [6.1]
    :type genome_id: kbtypes.KBaseGenomes.Genome
    :ui_name genome_id: Genome Name
    
    :param fba_model_id: select a name for the generated metabolic model (optional) [6.2]
    :type fba_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name fba_model_id: Output Metabolic Model Name
    
    :return: Generated Metabolic Model ID
    :rtype: kbtypes.KBaseFBA.FBAModel
    :output_widget: kbaseModelTabs
    """
    """
    Old output widget that was used:
    :output_widget: kbaseModelMetaNarrative
    
    Options that we should expose at some point:
    :param fba_model_template_id: specify a custom template for building the model (optional) [6.3]
    :type fba_model_template_id: kbtypes.Unicode
    :ui_name fba_model_template_id: FBA Model Template
    :param prob_annot: set to 1 to indicate that probabilistic annotations should be used (optional) [6.4]
    :type prob_annot: kbtypes.Unicode
    :ui_name prob_annot: Use Probabilitstic Annotations?
    :param core_model: set to 1 to indicate that a core metabolic model should be constructed instead of a full genome scale model (optional) [6.5]
    :type core_model: kbtypes.Unicode
    :ui_name core_model: Core Model Only?
    """
    meth.stages = 2  # for reporting progress
    meth.advance("Starting")
    meth.advance("Building your new FBA model")
    
    #grab token and workspace info, setup the client
    userToken, workspaceName = meth.token, meth.workspace_id
    fbaClient = fbaModelServices(service.URLS.fba,token=userToken)
    
    # create the model object
    build_fba_params = {
        'genome': genome_id,
        'workspace': workspaceName
    }
    if fba_model_id:
        fba_model_id = fba_model_id.strip()
        build_fba_params['model']=fba_model_id
    
    #if core_model:
    #    build_fba_params['coremodel']=1
    #if prob_annot:
    #    build_fba_params['probannoOnly']=1
        
    # other options that are not exposed
     #selecting a model template
    fba_meta_data = fbaClient.genome_to_fbamodel(build_fba_params)
    model_wsobj_id = fba_meta_data[0]
    model_name = fba_meta_data[1]
    
    # fetch the model via fba client
    #get_models_params = {
    #    'models' : [model_name],
    #      'workspaces' : [workspaceName]
    #}
    #modeldata = fbaClient.get_models(get_models_params)
    #meth.advance("Displaying your new FBA model details")
    return json.dumps({'id': model_name, 'ws': workspaceName})
def _genome_to_fba_model(meth, genome_id, fba_model_id):
    """Given an annotated Genome, build a draft metabolic model which can be analyzed with FBA. [6]

    :param genome_id: Source genome name [6.1]
    :type genome_id: kbtypes.KBaseGenomes.Genome
    :ui_name genome_id: Genome Name
    
    :param fba_model_id: select a name for the generated metabolic model (optional) [6.2]
    :type fba_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name fba_model_id: Output Metabolic Model Name
    
    :return: Generated Metabolic Model ID
    :rtype: kbtypes.KBaseFBA.FBAModel
    :output_widget: kbaseModelTabs
    """
    """
    Old output widget that was used:
    :output_widget: kbaseModelMetaNarrative
    
    Options that we should expose at some point:
    :param fba_model_template_id: specify a custom template for building the model (optional) [6.3]
    :type fba_model_template_id: kbtypes.Unicode
    :ui_name fba_model_template_id: FBA Model Template
    :param prob_annot: set to 1 to indicate that probabilistic annotations should be used (optional) [6.4]
    :type prob_annot: kbtypes.Unicode
    :ui_name prob_annot: Use Probabilitstic Annotations?
    :param core_model: set to 1 to indicate that a core metabolic model should be constructed instead of a full genome scale model (optional) [6.5]
    :type core_model: kbtypes.Unicode
    :ui_name core_model: Core Model Only?
    """
    meth.stages = 2  # for reporting progress
    meth.advance("Starting")
    meth.advance("Building your new FBA model")
    
    #grab token and workspace info, setup the client
    userToken, workspaceName = meth.token, meth.workspace_id
    fbaClient = fbaModelServices(service.URLS.fba,token=userToken)
    
    # create the model object
    build_fba_params = {
        'genome': genome_id,
        'workspace': workspaceName
    }
    if fba_model_id:
        fba_model_id = fba_model_id.strip()
        build_fba_params['model']=fba_model_id
    
    #if core_model:
    #    build_fba_params['coremodel']=1
    #if prob_annot:
    #    build_fba_params['probannoOnly']=1
        
    # other options that are not exposed
     #selecting a model template
    fba_meta_data = fbaClient.genome_to_fbamodel(build_fba_params)
    model_wsobj_id = fba_meta_data[0]
    model_name = fba_meta_data[1]
    
    # fetch the model via fba client
    #get_models_params = {
    #    'models' : [model_name],
    #      'workspaces' : [workspaceName]
    #}
    #modeldata = fbaClient.get_models(get_models_params)
    #meth.advance("Displaying your new FBA model details")
    return json.dumps({'id': model_name, 'ws': workspaceName})
Esempio n. 28
0
    def calculate(self, ctx, input):
        # ctx is the context object
        # return variables are: output
        #BEGIN calculate
        ''' Compute reaction probabilities from a probabilistic annotation.

            The input dictionary must contain the following keys:
            probanno: Name of ProbAnno object to input
            probanno_workspace: Workspace from which to grab the ProbAnno object
            rxnprobs: Name of RxnProbs object
            rxnprobs_workspace: Workspace to which to save the RxnProbs object

            The following keys are optional:
            verbose: Print lots of messages on the progress of the algorithm
            template_model: Name of TemplateModel object
            template_workspace: Workspace from which to grab TemplateModel object

            @param ctx Current context object
            @param input Dictionary with input parameters for function
            @return Object info for RxnProbs object
            @raise WrongVersionError when ProbAnno object version number is invalid
            @raise ValueError when template_workspace input argument is not specified
        '''

        # Sanity check on input arguments
        input = self._checkInputArguments(ctx, input, 
                                          ["probanno", "probanno_workspace", "rxnprobs", "rxnprobs_workspace"], 
                                          { "verbose" : False ,
                                            "template_model" : None,
                                            "template_workspace" : None
                                          }
                                         )

        # Make sure the static database files are ready.
        self._checkDatabaseFiles(ctx)

        # Set log level to INFO when verbose parameter is enabled.
        if input['verbose']:
            ctx.set_log_level(log.DEBUG)
        
        # Create a workspace client.
        wsClient = Workspace(self.config["workspace_url"], token=ctx['token'])
        
        # Get the ProbAnno object from the specified workspace.
        probannoObjectId = make_object_identity(input["probanno_workspace"], input["probanno"])
        objectList = wsClient.get_objects( [ probannoObjectId ] )
        probannoObject = objectList[0]
        if probannoObject['info'][2] != ProbAnnoType:
            message = "ProbAnno object type %s is not %s for object %s" %(probannoObject['info'][2], ProbAnnoType, probannoObject['info'][1])
            ctx.log_err(message)
            raise WrongVersionError(message)
        genome = probannoObject["data"]["genome"]
        
        # Create a temporary directory for storing intermediate files when debug is turned on.
        if ctx.get_log_level() >= log.DEBUG2:
            workFolder = tempfile.mkdtemp("", "calculate-%s-" %(genome), self.config["work_folder_path"])
            ctx.log_debug('Intermediate files saved in '+workFolder)
        else:
            workFolder = None

        # When a template model is specified, use it to build dictionaries for roles,
        # complexes, and reactions instead of retrieving from static database files.
        complexesToRoles = None
        reactionsToComplexes = None
        if input["template_model"] is not None or input["template_workspace"] is not None:
            if not(input["template_model"] is not None and input["template_workspace"] is not None) :
                message = "Template model workspace is required if template model ID is provided"
                ctx.log_err(message)
                raise ValueError(message)

            # Create a dictionary to map a complex to a list of roles and a dictionary
            # to map a reaction to a list of complexes.  The dictionaries are specific to
            # the specified template model instead of covering everything in the central
            # data model.
            complexesToRoles = dict()
            reactionsToComplexes = dict()

            # Get the list of RoleComplexReactions for the template model from the
            # fba modeling service.  The RoleComplexReactions structure has a list
            # of ComplexReactions structures for the given role.  And each ComplexReactions
            # structure has a list of reactions for the given complex.
            fbaClient = fbaModelServices(self.config['fbamodeling_url'], token=ctx['token'])
            roleComplexReactionsList = fbaClient.role_to_reactions( { 'templateModel': input['template_model'], 'workspace': input['template_workspace'] } )

            # Build the two dictionaries from the returned list.
            for rcr in roleComplexReactionsList:
                for complex in rcr['complexes']:
                    complexId = re.sub(r'cpx0*(\d+)', r'kb|cpx.\1', complex['name']) # Convert ModelSEED format to KBase format
                    if complexId in complexesToRoles:
                        complexesToRoles[complexId].append(rcr['name'])
                    else:
                        complexesToRoles[complexId] = [ rcr['name'] ]
                    for reaction in complex['reactions']:
                        reactionId = reaction['reaction']
                        if reactionId in reactionsToComplexes:
                            reactionsToComplexes[reactionId].append(complexId)
                        else:
                            reactionsToComplexes[reactionId] = [ complexId ]

        # Calculate per-gene role probabilities.
        roleProbs = self._rolesetProbabilitiesToRoleProbabilities(ctx, input, genome, probannoObject["data"]["roleset_probabilities"], workFolder)

        # Calculate whole cell role probabilities.
        # Note - eventually workFolder will be replaced with a rolesToReactions call
        totalRoleProbs = self._totalRoleProbabilities(ctx, input, genome, roleProbs, workFolder)

        # Calculate complex probabilities.
        complexProbs = self._complexProbabilities(ctx, input, genome, totalRoleProbs, workFolder, complexesToRequiredRoles = complexesToRoles)

        # Calculate reaction probabilities.
        reactionProbs = self._reactionProbabilities(ctx, input, genome, complexProbs, workFolder, rxnsToComplexes = reactionsToComplexes)

        # If the reaction probabilities were not calculated using the data from the fba modeling service
        # via the template model, we need to convert from the KBase ID format to the ModelSEED format.
        if input["template_model"] is None:
            reactionList = list()
            for index in range(len(reactionProbs)):
                reactionList.append(reactionProbs[index][0])
            EntityAPI = CDMI_EntityAPI(self.config["cdmi_url"])
            numAttempts = 4
            while numAttempts > 0:
                try:
                    numAttempts -= 1
                    reactionData = EntityAPI.get_entity_Reaction( reactionList, [ "source_id" ] )
                    if len(reactionList) == len(reactionData):
                        numAttempts = 0
                except HTTPError as e:
                    pass
            for index in range(len(reactionProbs)):
                rxnId = reactionProbs[index][0]
                reactionProbs[index][0] = reactionData[rxnId]['source_id']
 
        # Create a reaction probability object
        objectData = dict()
        objectData["genome"] = probannoObject["data"]["genome"]
        objectData['genome_workspace'] = probannoObject['data']['genome_workspace']
        if input["template_model"] is None:
            objectData['template_model'] = 'None'
        else:
            objectData["template_model"] = input["template_model"]
        if input["template_workspace"] is None:
            objectData['template_workspace'] = 'None'
        else:
            objectData["template_workspace"] = input["template_workspace"]
        objectData["probanno"] = input['probanno']
        objectData['probanno_workspace'] = input['probanno_workspace']
        objectData["id"] = input["rxnprobs"]
        objectData["reaction_probabilities"] = reactionProbs

        objectMetaData = { "num_reaction_probs": len(objectData["reaction_probabilities"]) }
        objectProvData = dict()
        objectProvData['time'] = timestamp(0)
        objectProvData['service'] = os.environ['KB_SERVICE_NAME']
        objectProvData['service_ver'] = ServiceVersion
        objectProvData['method'] = 'calculate'
        objectProvData['method_params'] = input.items()
        objectProvData['input_ws_objects'] = [ '%s/%s/%d' %(probannoObject['info'][7], probannoObject['info'][1], probannoObject['info'][4]) ]
        objectSaveData = dict();
        objectSaveData['type'] = RxnProbsType
        objectSaveData['name'] = input["rxnprobs"]
        objectSaveData['data'] = objectData
        objectSaveData['meta'] = objectMetaData
        objectSaveData['provenance'] = [ objectProvData ]
        objectInfo = wsClient.save_objects( { 'workspace': input["rxnprobs_workspace"], 'objects': [ objectSaveData ] } )
        output = objectInfo[0]
        
        #END calculate

        # At some point might do deeper type checking...
        if not isinstance(output, list):
            raise ValueError('Method calculate return value ' +
                             'output is not type list as required.')
        # return the results
        return [output]
def _run_fba(meth, fba_model_id, media_id, fba_result_id, geneko, rxnko, defaultmaxflux, defaultminuptake, defaultmaxuptake, minimizeFlux, maximizeObjective, allreversible, prom):
    """Run Flux Balance Analysis on a metabolic model. [10]

    :param fba_model_id: the metabolic model you wish to run [10.1]
    :type fba_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name fba_model_id: Metabolic Model
    
    :param media_id: the media condition in which to run FBA (optional, default is an artificial complete media) [10.2]
    :type media_id: kbtypes.KBaseBiochem.Media
    :ui_name media_id: Media
    
    :param fba_result_id: select a name for the FBA result object (optional) [10.3]
    :type fba_result_id: kbtypes.KBaseFBA.FBA
    :ui_name fba_result_id: Output FBA Result Name
    
    :param geneko: specify gene knockouts by the gene's feature ID delimited by semicolons(;) (optional) [10.4]
    :type geneko: kbtypes.Unicode
    :ui_name geneko: Gene Knockouts
    
    :param rxnko: specify reaction knockouts by reaction ID delimited by semicolons(;) (optional) [10.5]
    :type rxnko: kbtypes.Unicode
    :ui_name rxnko: Reaction Knockouts
    
    :param defaultmaxflux: specify the default maximum intracellular flux (optional) [10.6]
    :type defaultmaxflux: kbtypes.Unicode
    :ui_name defaultmaxflux: Default Maximum flux
    :default defaultmaxflux: 100
    
    :param defaultminuptake: specify the default minumum nutrient uptake flux (optional) [10.7]
    :type defaultminuptake: kbtypes.Unicode
    :ui_name defaultminuptake: Default Min Uptake
    :default defaultminuptake: -100
    
    :param defaultmaxuptake: specify the default maximum nutrient uptake flux (optional) [10.8]
    :type defaultmaxuptake: kbtypes.Unicode
    :ui_name defaultmaxuptake: Default Max Uptake
    :default defaultmaxuptake: 0
    
    :param minimizeFlux: set to 'yes' or '1' to run FBA by minimizing flux (optional) [10.9]
    :type minimizeFlux: kbtypes.Unicode
    :ui_name minimizeFlux: Minimize Flux?
    :default minimizeFlux: no
    
    :param maximizeObjective: set to 'no' or '0' to run FBA without maximizing the objective function (optional) [10.10]
    :type maximizeObjective: kbtypes.Unicode
    :ui_name maximizeObjective: Maximize Objective?
    :default maximizeObjective: yes
    
    :param allreversible: set to 'yes' or '1' to allow all model reactions to be reversible (optional) [10.11]
    :type allreversible: kbtypes.Unicode
    :ui_name allreversible: All rxns reversible?
    :default allreversible: no
    
    :param prom: specify the PROM constraint to apply for regulation of the metabolic model  (optional) [10.12]
    :type prom: kbtypes.KBaseFBA.PromConstraint
    :ui_name prom: PROM constraint
    
    :return: something 
    :rtype: kbtypes.Unicode
    :output_widget: kbaseFbaTabsNarrative
    """
    
    ## !! Important note!  the default values set here are for display only, so we actually revert to the
    ## default values in the FBA modeling service.  Thus, if default values are updated there, the default values
    ## displayed to the end user will be incorrect!
    
    meth.stages = 3
    meth.advance("Setting up and validating FBA parameters")
    
    #grab token and workspace info, setup the client
    userToken, workspaceName = meth.token, meth.workspace_id;
    fbaClient = fbaModelServices(service.URLS.fba, token=userToken)
    
    # setup the parameters
    """
    bool minimizeflux - a flag indicating if flux variability should be run (an optional argument: default is '0')
    typedef structure {
        fbamodel_id model;
        workspace_id model_workspace;
        FBAFormulation formulation;
        bool fva;
        bool simulateko;
        bool minimizeflux;
        bool findminmedia;
        string notes;
        fba_id fba;
        workspace_id workspace;
        string auth;
        bool overwrite;
        bool add_to_model;
    } runfba_params;

    typedef structure {
        media_id media;
        list<compound_id> additionalcpds;
	promconstraint_id promconstraint;
	workspace_id promconstraint_workspace;
        workspace_id media_workspace;
        float objfraction;
        bool allreversible;
        bool maximizeObjective;
        list<term> objectiveTerms;
        list<feature_id> geneko;
        list<reaction_id> rxnko;
        list<bound> bounds;
        list<constraint> constraints;
        mapping<string,float> uptakelim;
        float defaultmaxflux;
        float defaultminuptake;
        float defaultmaxuptake;
        bool simplethermoconst;
        bool thermoconst;
        bool nothermoerror;
        bool minthermoerror;
    } FBAFormulation;
    """
    
    # handle and/or validate parameters...
    if not fba_model_id:
        raise Exception("Error in running FBA: model name was not specified")
    
    if media_id:
        fba_formulation = {
            'media' : media_id,
            'media_workspace' : workspaceName,
        }
    else:
        fba_formulation = {}
        
    fba_params = {
        'model' : fba_model_id,
        'model_workspace' : workspaceName,
        'formulation' : fba_formulation,
        'workspace' : workspaceName,
        'notes' : "ran from the narrative"
    }
    fba_result_id = fba_result_id.strip()
    if fba_result_id:
        fba_params['fba'] = fba_result_id
    if geneko:
        fba_params['simulateko'] = 0
        fba_params['formulation']['geneko']=geneko.split(";")
    if rxnko:
        fba_params['simulateko'] = 0
        fba_params['formulation']['rxnko']=rxnko.split(";")
    if maximizeObjective=='0' or maximizeObjective=='false' or maximizeObjective=='no':
        fba_params['formulation']['maximizeObjective'] = 0
    else:
        fba_params['formulation']['maximizeObjective'] = 1
        
    if minimizeFlux=='1' or minimizeFlux=='true' or minimizeFlux=='yes':
        fba_params['minimizeflux'] = 1
    else:
        fba_params['minimizeflux'] = 0
        
    if allreversible=='1' or allreversible=='true' or allreversible=='yes':   
        fba_params['formulation']['allreversible'] = 1
    else:  
        fba_params['formulation']['allreversible'] = 0
        
    if prom:
        fba_params['formulation']['promconstraint'] = prom
        fba_params['formulation']['promconstraint_workspace'] = workspaceName

    if defaultmaxflux:
        try:
            fba_params['formulation']['defaultmaxflux'] = float(defaultmaxflux)
        except:
            raise Exception("Default maximum flux must be a valid number.")
    else:
        fba_params['formulation']['defaultmaxflux'] = 100
    if defaultminuptake:
        try:
            fba_params['formulation']['defaultminuptake'] = float(defaultminuptake)
        except:
            raise Exception("Default minimum uptake must be a valid number.")
    else:
        fba_params['formulation']['defaultminuptake'] = -100
    if defaultmaxflux:
        try:
            fba_params['formulation']['defaultmaxuptake'] = float(defaultmaxuptake)
        except:
            raise Exception("Default maximum uptake must be a valid number.")
    else:
        fba_params['formulation']['defaultmaxuptake'] = 0
    
    meth.debug(json.dumps(fba_params))

    meth.advance("Running FBA")
    fbaClient = fbaModelServices(url=service.URLS.fba,token=userToken)
    result_meta = fbaClient.runfba(fba_params)
    generated_fba_id = result_meta[0]
    
    #meth.advance("Retrieving FBA results")
    #get_fbas_params = {
    #    'fbas' : [generated_fba_id],
    #    'workspaces' : [workspaceName]
    #}
    #fbadata = fbaClient.get_fbas(get_fbas_params)
    
    # a hack: get object info so we can have the object name (instead of the id number)
    ws = workspaceService(service.URLS.workspace, token=userToken)
    meth.advance("Loading the model")
    get_objects_params = [{
        'ref' : workspaceName+"/"+generated_fba_id
    }]
    info = ws.get_object_info(get_objects_params,0)
    
    return json.dumps({ "ids":[info[0][1]],"workspaces":[workspaceName] })
def _gapfill_fba(meth, fba_model_id, media_id,source_model_id,int_sol, output_model_id):
    """Run Gapfilling on an metabolic model.  Gapfill attempts to identify the minimal number of reactions
    needed to add to your metabolic model in order for the model to predict growth in the
    given media condition (or in complete media if no Media is provided).  Gapfilling is
    an optimization procedure that can produce many possible solutions.  After a gapfilling
    job is submitted and run, you can view the results by viewing a metabolic model details,
    and incorporate the new reactions by running the Integrate Gapfill Solution function. [12]

    :param fba_model_id: the metabolic model to gapfill [12.1]
    :type fba_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name fba_model_id: Metabolic Model
    
    :param media_id: the media condition in which to gapfill [12.2]
    :type media_id: kbtypes.KBaseBiochem.Media
    :ui_name media_id: Media
    
    :param source_model_id: model to gapfill from
    :type source_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name source_model_id: Source Gapfill Model
    
    :param int_sol: automatically integrate solution (yes/no)
    :type int_sol: kbtypes.Unicode
    :ui_name int_sol: Integrate Solution
    
    :param output_model_id: select a name for the model result object (optional)
    :type output_model_id: kbtypes.Unicode
    :ui_name output_model_id: Output Model ID
    
    :return: Metabolic Model Data
    :rtype: kbtypes.Model
    :output_widget: kbaseModelTabs
    """
    
    # setting the output id appears to not work, so for now we leave it out
    
    
    meth.stages = 2
    meth.advance("Running gapfill on model...")
    
    #grab token and workspace info, setup the client
    userToken, workspaceName = meth.token, meth.workspace_id;

    fbaclient = fbaModelServices(url=service.URLS.fba, token=userToken)
    
    fba_formulation = {}
    if (media_id):
        fba_formulation = {
            'media' : media_id,
            'media_workspace' : workspaceName
        }
    
    gapfill_formulation = {
        'formulation' : fba_formulation,
    }
    gapfill_params = {
        'model' : fba_model_id,
        'model_workspace' : workspaceName,
        'formulation' : gapfill_formulation,
        'workspace' : workspaceName,
        'fastgapfill' : 1,
    }
    
    if(int_sol):
        gapfill_params['integrate_solution'] = int_sol;
        if (gapfill_params['integrate_solution'] == 'yes'):
            gapfill_params['integrate_solution'] = 1;

    if(output_model_id):
        gapfill_params['out_model'] = output_model_id;
        
    if(source_model_id):
        gapfill_params['source_model'] = source_model_id;
        gapfill_params['source_model_ws'] = workspaceName;
    
    output = fbaclient.gapfill_model(gapfill_params);

    if output_model_id:
        data = json.dumps({'id': output_model_id, 'ws': workspaceName})
    else:
        data = json.dumps({'id': fba_model_id, 'ws': workspaceName})

    return data
def _integrate_gapfill(meth, fba_model_id, gapfill_id, output_model_id):
    """Integrate a Gapfill solution into your metabolic model [13]

    :param fba_model_id: the metabolic model to integrate gapfill solutions into [13.1]
    :type fba_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name fba_model_id: Metabolic Model
    
    :param gapfill_id: select the ID of the gapfill solution (found in the Gapfilling tab in the model viewer, usually in the form 'modelId.gf.2.gfsol.1') [13.2]
    :type gapfill_id: kbtypes.KBaseFBA.Gapfilling
    :ui_name gapfill_id: Gapfill ID
    :default gapfill_id: e.g model.gf.2.gfsol.1

    :param output_model_id: select a name for the gapfilled object (optional) [13.3]
    :type output_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name output_model_id: Output Model Result Name
    
    :output_widget: kbaseIntegrateGapfillOutput
    
    :return: gapfilled model ID
    :rtype: kbtypes.Unicode
    """
    meth.stages = 2
    meth.advance("Setting up parameters")
    
    #grab token and workspace info, setup the client
    userToken, workspaceName = meth.token, meth.workspace_id;
    fbaClient = fbaModelServices(service.URLS.fba, token=userToken)

    """
    typedef structure {
        fbamodel_id model;
        workspace_id model_workspace;
        list<gapfillsolution_id> gapfillSolutions;
        list<gapgensolution_id> gapgenSolutions;
        fbamodel_id out_model;
        workspace_id workspace;
        string auth;
        bool overwrite;
    } integrate_reconciliation_solutions_params;
    """
    integrate_params = {
        'model' : fba_model_id,
        'model_workspace' : workspaceName,
        'gapfillSolutions' : [gapfill_id],
        'gapgenSolutions' : [],
        'workspace' : workspaceName
    }
    
    # get the model to determine the number of reactions
    wsClient = workspaceService(service.URLS.workspace, token=userToken)
    firstReactionList = wsClient.get_object_subset([{'ref':workspaceName+"/"+fba_model_id, 'included':["/modelreactions/[*]/id"]}])
    #meth.debug(json.dumps(firstReactionList));

    output_model_id = output_model_id.strip()
    if (output_model_id):
        integrate_params['out_model'] = output_model_id
    else:
        output_model_id = fba_model_id

    # funcdef integrate_reconciliation_solutions(integrate_reconciliation_solutions_params input) returns (object_metadata modelMeta);
    meth.advance("Integrating the gapfill solution")
    model_meta = fbaClient.integrate_reconciliation_solutions(integrate_params)
    finalReactionList = wsClient.get_object_subset([{'ref':workspaceName+"/"+output_model_id, 'included':["/modelreactions/[*]/id"]}])

    return json.dumps( {
        "workspaceName":workspaceName,
        "originalModel":fba_model_id,
        "originalModelRef":str(firstReactionList[0]['info'][6])+"/"+str(firstReactionList[0]['info'][0])+"/"+str(firstReactionList[0]['info'][4]),
        "startingNumRxns":len(firstReactionList[0]['data']['modelreactions']),
        "newModel":output_model_id,
        "newModelRef":str(finalReactionList[0]['info'][6])+"/"+str(finalReactionList[0]['info'][0])+"/"+str(finalReactionList[0]['info'][4]),
        "endingNumRxns":len(finalReactionList[0]['data']['modelreactions'])
        })
def _gapfill_fba(meth, fba_model_id, media_id,source_model_id,int_sol, output_model_id):
    """Run Gapfilling on an metabolic model.  Gapfill attempts to identify the minimal number of reactions
    needed to add to your metabolic model in order for the model to predict growth in the
    given media condition (or in complete media if no Media is provided).  Gapfilling is
    an optimization procedure that can produce many possible solutions.  After a gapfilling
    job is submitted and run, you can view the results by viewing a metabolic model details,
    and incorporate the new reactions by running the Integrate Gapfill Solution function. [12]

    :param fba_model_id: the metabolic model to gapfill [12.1]
    :type fba_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name fba_model_id: Metabolic Model
    
    :param media_id: the media condition in which to gapfill [12.2]
    :type media_id: kbtypes.KBaseBiochem.Media
    :ui_name media_id: Media
    
    :param source_model_id: model to gapfill from
    :type source_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name source_model_id: Source Gapfill Model
    
    :param int_sol: automatically integrate solution (yes/no)
    :type int_sol: kbtypes.Unicode
    :ui_name int_sol: Integrate Solution
    
    :param output_model_id: select a name for the model result object (optional)
    :type output_model_id: kbtypes.Unicode
    :ui_name output_model_id: Output Model ID
    
    :return: Metabolic Model Data
    :rtype: kbtypes.Model
    :output_widget: kbaseModelTabs
    """
    
    # setting the output id appears to not work, so for now we leave it out
    
    
    meth.stages = 2
    meth.advance("Running gapfill on model...")
    
    #grab token and workspace info, setup the client
    userToken, workspaceName = meth.token, meth.workspace_id;

    fbaclient = fbaModelServices(url=service.URLS.fba, token=userToken)
    
    fba_formulation = {}
    if (media_id):
        fba_formulation = {
            'media' : media_id,
            'media_workspace' : workspaceName
        }
    
    gapfill_formulation = {
        'formulation' : fba_formulation,
    }
    gapfill_params = {
        'model' : fba_model_id,
        'model_workspace' : workspaceName,
        'formulation' : gapfill_formulation,
        'workspace' : workspaceName,
        'fastgapfill' : 1,
    }
    
    if(int_sol):
        gapfill_params['integrate_solution'] = int_sol;
        if (gapfill_params['integrate_solution'] == 'yes'):
            gapfill_params['integrate_solution'] = 1;

    if(output_model_id):
        gapfill_params['out_model'] = output_model_id;
        
    if(source_model_id):
        gapfill_params['source_model'] = source_model_id;
        gapfill_params['source_model_ws'] = workspaceName;
    
    output = fbaclient.gapfill_model(gapfill_params);

    if output_model_id:
        data = json.dumps({'id': output_model_id, 'ws': workspaceName})
    else:
        data = json.dumps({'id': fba_model_id, 'ws': workspaceName})

    return data
def _run_fba(meth, fba_model_id, media_id, fba_result_id, geneko, rxnko, defaultmaxflux, defaultminuptake, defaultmaxuptake, minimizeFlux, maximizeObjective, allreversible, prom):
    """Run Flux Balance Analysis on a metabolic model. [10]

    :param fba_model_id: the metabolic model you wish to run [10.1]
    :type fba_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name fba_model_id: Metabolic Model
    
    :param media_id: the media condition in which to run FBA (optional, default is an artificial complete media) [10.2]
    :type media_id: kbtypes.KBaseBiochem.Media
    :ui_name media_id: Media
    
    :param fba_result_id: select a name for the FBA result object (optional) [10.3]
    :type fba_result_id: kbtypes.KBaseFBA.FBA
    :ui_name fba_result_id: Output FBA Result Name
    
    :param geneko: specify gene knockouts by the gene's feature ID delimited by semicolons(;) (optional) [10.4]
    :type geneko: kbtypes.Unicode
    :ui_name geneko: Gene Knockouts
    
    :param rxnko: specify reaction knockouts by reaction ID delimited by semicolons(;) (optional) [10.5]
    :type rxnko: kbtypes.Unicode
    :ui_name rxnko: Reaction Knockouts
    
    :param defaultmaxflux: specify the default maximum intracellular flux (optional) [10.6]
    :type defaultmaxflux: kbtypes.Unicode
    :ui_name defaultmaxflux: Default Maximum flux
    :default defaultmaxflux: 100
    
    :param defaultminuptake: specify the default minumum nutrient uptake flux (optional) [10.7]
    :type defaultminuptake: kbtypes.Unicode
    :ui_name defaultminuptake: Default Min Uptake
    :default defaultminuptake: -100
    
    :param defaultmaxuptake: specify the default maximum nutrient uptake flux (optional) [10.8]
    :type defaultmaxuptake: kbtypes.Unicode
    :ui_name defaultmaxuptake: Default Max Uptake
    :default defaultmaxuptake: 0
    
    :param minimizeFlux: set to 'yes' or '1' to run FBA by minimizing flux (optional) [10.9]
    :type minimizeFlux: kbtypes.Unicode
    :ui_name minimizeFlux: Minimize Flux?
    :default minimizeFlux: no
    
    :param maximizeObjective: set to 'no' or '0' to run FBA without maximizing the objective function (optional) [10.10]
    :type maximizeObjective: kbtypes.Unicode
    :ui_name maximizeObjective: Maximize Objective?
    :default maximizeObjective: yes
    
    :param allreversible: set to 'yes' or '1' to allow all model reactions to be reversible (optional) [10.11]
    :type allreversible: kbtypes.Unicode
    :ui_name allreversible: All rxns reversible?
    :default allreversible: no
    
    :param prom: specify the PROM constraint to apply for regulation of the metabolic model  (optional) [10.12]
    :type prom: kbtypes.KBaseFBA.PromConstraint
    :ui_name prom: PROM constraint
    
    :return: something 
    :rtype: kbtypes.Unicode
    :output_widget: kbaseFbaTabsNarrative
    """
    
    ## !! Important note!  the default values set here are for display only, so we actually revert to the
    ## default values in the FBA modeling service.  Thus, if default values are updated there, the default values
    ## displayed to the end user will be incorrect!
    
    meth.stages = 3
    meth.advance("Setting up and validating FBA parameters")
    
    #grab token and workspace info, setup the client
    userToken, workspaceName = meth.token, meth.workspace_id;
    fbaClient = fbaModelServices(service.URLS.fba, token=userToken)
    
    # setup the parameters
    """
    bool minimizeflux - a flag indicating if flux variability should be run (an optional argument: default is '0')
    typedef structure {
        fbamodel_id model;
        workspace_id model_workspace;
        FBAFormulation formulation;
        bool fva;
        bool simulateko;
        bool minimizeflux;
        bool findminmedia;
        string notes;
        fba_id fba;
        workspace_id workspace;
        string auth;
        bool overwrite;
        bool add_to_model;
    } runfba_params;

    typedef structure {
        media_id media;
        list<compound_id> additionalcpds;
	promconstraint_id promconstraint;
	workspace_id promconstraint_workspace;
        workspace_id media_workspace;
        float objfraction;
        bool allreversible;
        bool maximizeObjective;
        list<term> objectiveTerms;
        list<feature_id> geneko;
        list<reaction_id> rxnko;
        list<bound> bounds;
        list<constraint> constraints;
        mapping<string,float> uptakelim;
        float defaultmaxflux;
        float defaultminuptake;
        float defaultmaxuptake;
        bool simplethermoconst;
        bool thermoconst;
        bool nothermoerror;
        bool minthermoerror;
    } FBAFormulation;
    """
    
    # handle and/or validate parameters...
    if not fba_model_id:
        raise Exception("Error in running FBA: model name was not specified")
    
    if media_id:
        fba_formulation = {
            'media' : media_id,
            'media_workspace' : workspaceName,
        }
    else:
        fba_formulation = {}
        
    fba_params = {
        'model' : fba_model_id,
        'model_workspace' : workspaceName,
        'formulation' : fba_formulation,
        'workspace' : workspaceName,
        'notes' : "ran from the narrative"
    }
    fba_result_id = fba_result_id.strip()
    if fba_result_id:
        fba_params['fba'] = fba_result_id
    if geneko:
        fba_params['simulateko'] = 0
        fba_params['formulation']['geneko']=geneko.split(";")
    if rxnko:
        fba_params['simulateko'] = 0
        fba_params['formulation']['rxnko']=rxnko.split(";")
    if maximizeObjective=='0' or maximizeObjective=='false' or maximizeObjective=='no':
        fba_params['formulation']['maximizeObjective'] = 0
    else:
        fba_params['formulation']['maximizeObjective'] = 1
        
    if minimizeFlux=='1' or minimizeFlux=='true' or minimizeFlux=='yes':
        fba_params['minimizeflux'] = 1
    else:
        fba_params['minimizeflux'] = 0
        
    if allreversible=='1' or allreversible=='true' or allreversible=='yes':   
        fba_params['formulation']['allreversible'] = 1
    else:  
        fba_params['formulation']['allreversible'] = 0
        
    if prom:
        fba_params['formulation']['promconstraint'] = prom
        fba_params['formulation']['promconstraint_workspace'] = workspaceName

    if defaultmaxflux:
        try:
            fba_params['formulation']['defaultmaxflux'] = float(defaultmaxflux)
        except:
            raise Exception("Default maximum flux must be a valid number.")
    else:
        fba_params['formulation']['defaultmaxflux'] = 100
    if defaultminuptake:
        try:
            fba_params['formulation']['defaultminuptake'] = float(defaultminuptake)
        except:
            raise Exception("Default minimum uptake must be a valid number.")
    else:
        fba_params['formulation']['defaultminuptake'] = -100
    if defaultmaxflux:
        try:
            fba_params['formulation']['defaultmaxuptake'] = float(defaultmaxuptake)
        except:
            raise Exception("Default maximum uptake must be a valid number.")
    else:
        fba_params['formulation']['defaultmaxuptake'] = 0
    
    meth.debug(json.dumps(fba_params))

    meth.advance("Running FBA")
    fbaClient = fbaModelServices(url=service.URLS.fba,token=userToken)
    result_meta = fbaClient.runfba(fba_params)
    generated_fba_id = result_meta[0]
    
    #meth.advance("Retrieving FBA results")
    #get_fbas_params = {
    #    'fbas' : [generated_fba_id],
    #    'workspaces' : [workspaceName]
    #}
    #fbadata = fbaClient.get_fbas(get_fbas_params)
    
    # a hack: get object info so we can have the object name (instead of the id number)
    ws = workspaceService(service.URLS.workspace, token=userToken)
    meth.advance("Loading the model")
    get_objects_params = [{
        'ref' : workspaceName+"/"+generated_fba_id
    }]
    info = ws.get_object_info(get_objects_params,0)
    
    return json.dumps({ "ids":[info[0][1]],"workspaces":[workspaceName] })
def _integrate_gapfill(meth, fba_model_id, gapfill_id, output_model_id):
    """Integrate a Gapfill solution into your metabolic model [13]

    :param fba_model_id: the metabolic model to integrate gapfill solutions into [13.1]
    :type fba_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name fba_model_id: Metabolic Model
    
    :param gapfill_id: select the ID of the gapfill solution (found in the Gapfilling tab in the model viewer, usually in the form 'modelId.gf.2.gfsol.1') [13.2]
    :type gapfill_id: kbtypes.KBaseFBA.Gapfilling
    :ui_name gapfill_id: Gapfill ID
    :default gapfill_id: e.g model.gf.2.gfsol.1

    :param output_model_id: select a name for the gapfilled object (optional) [13.3]
    :type output_model_id: kbtypes.KBaseFBA.FBAModel
    :ui_name output_model_id: Output Model Result Name
    
    :output_widget: kbaseIntegrateGapfillOutput
    
    :return: gapfilled model ID
    :rtype: kbtypes.Unicode
    """
    meth.stages = 2
    meth.advance("Setting up parameters")
    
    #grab token and workspace info, setup the client
    userToken, workspaceName = meth.token, meth.workspace_id;
    fbaClient = fbaModelServices(service.URLS.fba, token=userToken)

    """
    typedef structure {
        fbamodel_id model;
        workspace_id model_workspace;
        list<gapfillsolution_id> gapfillSolutions;
        list<gapgensolution_id> gapgenSolutions;
        fbamodel_id out_model;
        workspace_id workspace;
        string auth;
        bool overwrite;
    } integrate_reconciliation_solutions_params;
    """
    integrate_params = {
        'model' : fba_model_id,
        'model_workspace' : workspaceName,
        'gapfillSolutions' : [gapfill_id],
        'gapgenSolutions' : [],
        'workspace' : workspaceName
    }
    
    # get the model to determine the number of reactions
    wsClient = workspaceService(service.URLS.workspace, token=userToken)
    firstReactionList = wsClient.get_object_subset([{'ref':workspaceName+"/"+fba_model_id, 'included':["/modelreactions/[*]/id"]}])
    #meth.debug(json.dumps(firstReactionList));

    output_model_id = output_model_id.strip()
    if (output_model_id):
        integrate_params['out_model'] = output_model_id
    else:
        output_model_id = fba_model_id

    # funcdef integrate_reconciliation_solutions(integrate_reconciliation_solutions_params input) returns (object_metadata modelMeta);
    meth.advance("Integrating the gapfill solution")
    model_meta = fbaClient.integrate_reconciliation_solutions(integrate_params)
    finalReactionList = wsClient.get_object_subset([{'ref':workspaceName+"/"+output_model_id, 'included':["/modelreactions/[*]/id"]}])

    return json.dumps( {
        "workspaceName":workspaceName,
        "originalModel":fba_model_id,
        "originalModelRef":str(firstReactionList[0]['info'][6])+"/"+str(firstReactionList[0]['info'][0])+"/"+str(firstReactionList[0]['info'][4]),
        "startingNumRxns":len(firstReactionList[0]['data']['modelreactions']),
        "newModel":output_model_id,
        "newModelRef":str(finalReactionList[0]['info'][6])+"/"+str(finalReactionList[0]['info'][0])+"/"+str(finalReactionList[0]['info'][4]),
        "endingNumRxns":len(finalReactionList[0]['data']['modelreactions'])
        })