当前位置: 首页>>代码示例>>Python>>正文


Python client.Workspace类代码示例

本文整理汇总了Python中biokbase.workspace.client.Workspace的典型用法代码示例。如果您正苦于以下问题:Python Workspace类的具体用法?Python Workspace怎么用?Python Workspace使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Workspace类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_probanno

    def get_probanno(self, ctx, input):
        # ctx is the context object
        # return variables are: output
        #BEGIN get_probanno
        ''' Convert a probabilistic annotation object into a human-readbable table.

            @param ctx Current context object
            @param input Dictionary with input parameters for function
            @return Dictionary keyed by gene to a list of tuples with roleset and likelihood
            @raise WrongVersionError when ProbAnno object version number is invalid
        '''

        input = self._checkInputArguments(ctx, input,
                                          ['probanno', 'probanno_workspace'],
                                          { 'probanno_version': None }
                                          )

        wsClient = Workspace(self.config["workspace_url"], token=ctx['token'])
        probAnnoObjectId = make_object_identity(input["probanno_workspace"], input["probanno"], input['probanno_version'])
        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)
        output = probAnnoObject["data"]["roleset_probabilities"]

        #END get_probanno

        # At some point might do deeper type checking...
        if not isinstance(output, dict):
            raise ValueError('Method get_probanno return value ' +
                             'output is not type dict as required.')
        # return the results
        return [output]
开发者ID:kbase,项目名称:probabilistic_annotation,代码行数:35,代码来源:Impl.py

示例2: download_workspace_data

def download_workspace_data(ws_url, source_ws, source_obj, working_dir,
                            logger):
    ws = Workspace(ws_url, token=TOKEN)
    objdata = ws.get_objects([{'ref': source_ws + '/' + source_obj}])[0]
    info = objdata['info']
    if info[2].split('-')[0] != 'KBaseFile.AssemblyFile':
        raise ValueError(
            'This method only works on the KBaseFile.AssemblyFile type')
    shock_url = objdata['data']['assembly_file']['file']['url']
    shock_id = objdata['data']['assembly_file']['file']['id']
    ref = str(info[6]) + '/' + str(info[0]) + '/' + str(info[4])
    source = objdata['data'].get('source')

    outfile = os.path.join(working_dir, source_obj)
    shock_node = shock_url + '/node/' + shock_id + '/?download'
    headers = {'Authorization': 'OAuth ' + TOKEN}
    with open(outfile, 'w') as f:
        response = requests.get(shock_node, stream=True, headers=headers)
        if not response.ok:
            try:
                err = json.loads(response.content)['error'][0]
            except:
                logger.error("Couldn't parse response error content: " +
                             response.content)
                response.raise_for_status()
            raise Exception(str(err))
        for block in response.iter_content(1024):
            if not block:
                break
            f.write(block)

    return shock_url, shock_id, ref, source
开发者ID:brettin,项目名称:transform,代码行数:32,代码来源:trns_transform_KBaseFile_AssemblyFile_to_KBaseGenomes_ContigSet.py

示例3: TophatCall

    def TophatCall(self, ctx, params):
        # ctx is the context object
        # return variables are: returnVal
        # BEGIN TophatCall
        ws_client = Workspace(url=self.__WS_URL, token=user_token)
        hs = HandleService(url=self.__HS_URL, token=user_token)
        try:
            ### Make a function to download the workspace object  and prepare dict of genome ,lib_type

            self.__LOGGER.info("Downloading RNASeq Sample file")
            try:
                ret = ws_client.get_objects(
                    [
                        {"name": params["sample_id"], "workspace": params["ws_id"]},
                        {"name": params["reference"], "workspace": params["ws_id"]},
                        {"name": params["bowtie_index"], "workspace": params["ws_id"]},
                        {"name": params["annotation_gtf"], "workspace": params["ws_id"]},
                    ]
                )
            except Exception, e:
                raise KBaseRNASeqException("Error Downloading objects from the workspace ")

                # Download reads from the JSON object
            genome = params["reference"]
            if "data" in reads:
                # if 'metadata' in reads['data']:
                # genome = reads['data']['metadata']['ref_genome']
                if "singleend_sample" in reads["data"]:
                    lib_type = "SingleEnd"
                    # cmdstring =
                elif "pairedend_sample" in reads["data"]:
                    lib_type = "PairedEnd"
开发者ID:r2sunita,项目名称:KBaseRNASeq,代码行数:32,代码来源:KBaseRNASeqImpl.py

示例4: delete_narrative

def delete_narrative(ws_id, auth_token, url=ci_ws):
    """
    Deletes a workspace with the given id. Throws a ServerError if the user given
    by auth_token isn't allowed to do so.
    """
    ws_client = Workspace(url=url, token=auth_token.token)
    ws_client.delete_workspace({'id': ws_id})
开发者ID:danielolson5,项目名称:narrative,代码行数:7,代码来源:narrative_test_helper.py

示例5: associateReads

 def associateReads(self, ctx, params):
     # ctx is the context object
     # return variables are: returnVal
     # BEGIN associateReads
     user_token = ctx["token"]
     ws_client = Workspace(url=self.__WS_URL, token=user_token)
     out = dict()
     out["metadata"] = {
         k: v
         for k, v in params.iteritems()
         if not k in ("ws_id", "analysis_id", "genome_id", "singleend_sample", "pairedend_sample") and v is not None
     }
     self.__LOGGER.info("Uploading RNASeqSample {0}".format(out["metadata"]["sample_id"]))
     if "genome_id" in params and params["genome_id"] is not None:
         out["metadata"]["genome_id"] = script_util.get_obj_info(
             self.__LOGGER, self.__WS_URL, [params["genome_id"]], params["ws_id"], user_token
         )[0]
     if "analysis_id" in params and params["analysis_id"] is not None:
         g_ref = script_util.get_obj_info(
             self.__LOGGER, self.__WS_URL, [params["analysis_id"]], params["ws_id"], user_token
         )[0]
         out["analysis_id"] = g_ref
     if "singleend_sample" in params and params["singleend_sample"] is not None:
         try:
             s_res = ws_client.get_objects([{"name": params["singleend_sample"], "workspace": params["ws_id"]}])
             out["singleend_sample"] = s_res[0]["data"]
             print out["singleend_sample"]
         except Exception, e:
             raise KBaseRNASeqException(
                 "Error Downloading SingleEndlibrary object from the workspace {0},{1}".format(
                     params["singleend_sample"], e
                 )
             )
开发者ID:r2sunita,项目名称:KBaseRNASeq,代码行数:33,代码来源:KBaseRNASeqImpl.py

示例6: get_object_from_ref

def get_object_from_ref(ref):
    objid = int(ref.split("/")[1])
    WS_URL = "https://ci.kbase.us/services/ws/"
    from biokbase.workspace.client import Workspace

    ws = Workspace(WS_URL)
    return ws.get_objects([dict(workspace=os.environ["KB_WORKSPACE_ID"], objid=objid)])[0]["data"]
开发者ID:aitatanit,项目名称:metatlas,代码行数:7,代码来源:kbase_utils.py

示例7: get_object_uid

def get_object_uid(name):
    WS_URL = "https://ci.kbase.us/services/ws/"
    from biokbase.workspace.client import Workspace

    ws = Workspace(WS_URL)
    info = ws.get_objects([dict(workspace=os.environ["KB_WORKSPACE_ID"], name=name)])[0]["info"]
    return "%s/%s/%s" % (info[6], info[0], info[4])
开发者ID:aitatanit,项目名称:metatlas,代码行数:7,代码来源:kbase_utils.py

示例8: create

    def create(self, ctx, params):
        # ctx is the context object
        # return variables are: info
        #BEGIN create

        print('Creating KBase Report.')

        # check that the basic parameters are set
        if 'report' not in params:
            raise ValueError('Field "report" must be defined to save a report')
        if 'workspace_name' not in params:
            raise ValueError('Field "workspace_name" must be defined to save a report')

        # setup proper provenance for the report
        provenance = [{}]
        if 'provenance' in ctx:
            provenance = ctx['provenance']

        # generate a random report name
        reportName = 'report_'+str(uuid.uuid4())
        if 'prefix' in params:
            reportName = params['prefix'] + reportName


        print('Report Name' + reportName)

        # let any workspace errors just percolate up for now
        ws = Workspace(self.workspaceURL, token=ctx['token'])
        report_info = ws.save_objects({
                'workspace':params['workspace_name'],
                'objects':[
                    {
                        'type':'KBaseReport.Report',
                        'data':params['report'],
                        'name':reportName,
                        'meta':{},
                        'hidden':1,
                        'provenance':provenance
                    }
                ]
            })[0]

        info = {
            'ref'  : str(report_info[6]) + '/' + str(report_info[0]) + '/' + str(report_info[4]),
            'name' : report_info[1]
        }

        #END create

        # At some point might do deeper type checking...
        if not isinstance(info, dict):
            raise ValueError('Method create return value ' +
                             'info is not type dict as required.')
        # return the results
        return [info]
开发者ID:msneddon,项目名称:KBaseReport,代码行数:55,代码来源:OLD-KBaseReportImpl.py

示例9: upload_narrative

def upload_narrative(nar_file, auth_token, user_id, url=ci_ws, set_public=False):
    """
    Uploads a Narrative from a downloaded object file.
    This file needs to be in JSON format, and it expects all
    data and info that is usually returned by the Workspace.get_objects
    method.

    Returns a dict of three elements:
        ws: the id of the workspace that was created
        obj: the id of the narrative object
        ref: the above two joined together into an object ref (for convenience)
    """

    # read the file
    f = open(nar_file, 'r')
    nar = json.loads(f.read())
    f.close()

    # do some setup.
    current_nar_metadata = ws_metadata
    current_nar_metadata['narrative_nice_name'] = nar['data']['metadata']['name']
    ws_client = Workspace(url=url, token=auth_token)

    # create the new workspace for the narrative
    ws_info = ws_client.create_workspace({
        'workspace': '{}:{}'.format(user_id, str(time.time()).replace('.', '')),
        'meta': current_nar_metadata,
        'globalread': 'r' if set_public else 'n'
    })
    ws_id = ws_info[0]

    # setup and save the narrative object
    metadata = nar['info'][10]
    ws_save_obj = {
        'type': 'KBaseNarrative.Narrative',
        'data': nar['data'],
        'name': nar['info'][1],
        'meta': nar['info'][10],
        'provenance': [{
            'script': 'upload_narrative_test.py',
            'description': 'Temporary Narrative uploaded for automated testing'
        }]
    }
    obj_info = ws_client.save_objects({'id': ws_id,
                                       'objects': [ws_save_obj]})

    # tweak the workspace's metadata to properly present its narrative
    ws_client.alter_workspace_metadata({'wsi': {'id': ws_id}, 'new': {'narrative': obj_info[0][0]}})
    return {
        'ws': ws_info[0],
        'obj': obj_info[0][0],
        'refstr': '{}/{}'.format(ws_info[0], obj_info[0][0]),
        'ref': NarrativeRef({'wsid': ws_info[0], 'objid': obj_info[0][0]})
    }
开发者ID:briehl,项目名称:narrative,代码行数:54,代码来源:util.py

示例10: get_obj_info

def get_obj_info(logger,ws_url,objects,ws_id,token):
    """
    function to get the workspace object id from a object name
    """
    ret = []
    ws_client=Workspace(url=ws_url, token=token)
    for obj in  objects:
    	try:
            obj_infos = ws_client.get_object_info_new({"objects": [{'name': obj, 'workspace': ws_id}]})
            ret.append("{0}/{1}/{2}".format(obj_infos[0][6],obj_infos[0][0],obj_infos[0][4]))
        except Exception, e:
                     logger.error("Couldn't retrieve %s:%s from the workspace , %s " %(ws_id,obj,e))
开发者ID:briehl,项目名称:KBaseRNASeq,代码行数:12,代码来源:script_util.py

示例11: handler

def handler (args) :
    ###
    # download ws object and convert them to csv
    wsd = Workspace(url=args.ws_url, token=os.environ.get('KB_AUTH_TOKEN'))
    indata = wsd.get_object({'id' : args.inobj_id,
                  #'type' : 'KBaseExpression.ExpressionSeries', 
                  'workspace' : args.ws_id})['data']

    if indata is None:
        raise Exception("Object {} not found in workspace {}".format(args.inobj_id, args.ws_id))


    ###
    # execute filtering
    flt_cmd_lst = ['mys_example', "-i", "{}-{}".format(os.getpid(),args.exp_fn) ]
    if (args.method     is not None): 
        flt_cmd_lst.append('-m')
        flt_cmd_lst.append(args.method)
    if (args.p_value    is not None): 
        flt_cmd_lst.append('-p')
        flt_cmd_lst.append(args.p_value)
    if (args.num_genes  is not None): 
        flt_cmd_lst.append('-n')
        flt_cmd_lst.append(args.num_genes)
    if (args.flt_out_fn is not None): 
        flt_cmd_lst.append('-o')
        flt_cmd_lst.append("{}-{}".format(os.getpid(),args.flt_out_fn))

    p1 = Popen(flt_cmd_lst, stdout=PIPE)
    out_str = p1.communicate()
    # print output message for error tracking
    if out_str[0] is not None : print out_str[0]
    if out_str[1] is not None : print >> sys.stderr, out_str[1]
    flt_cmd = " ".join(flt_cmd_lst)
   
    ###
    # put it back to workspace
    #fif = open("{}-{}".format(os.getpid(),args.flt_out_fn), 'r')
    #fif.readline(); # skip header
    
    # assume only one genome id
    outdata = {}
    outdata['key'] = indata['key']
    outdata['value'] = "{}{}".format(indata['value'], indata['value'])
    data_list = []
    data_list.append({'type' : 'MyService.PairString', 'data' : outdata, 'name' : args.outobj_id, 'meta' : {'org.series' : args.inobj_id}})
    wsd.save_objects({'workspace' : args.ws_id, 'objects' : data_list})

    if(args.del_tmps is "true") :
        os.remove("{}-{}".format(os.getpid(), args.exp_fn))
        os.remove("{}-{}".format(os.getpid(), args.flt_out_fn))
开发者ID:sjyoo,项目名称:loader,代码行数:51,代码来源:upload_handler.py

示例12: export_genome_annotation_as_genbank

    def export_genome_annotation_as_genbank(self, ctx, params):
        """
        A method designed especially for download, this calls 'genome_annotation_to_genbank' to do
        the work, but then packages the output with WS provenance and object info into
        a zip file and saves to shock.
        :param params: instance of type "ExportParams" -> structure:
           parameter "input_ref" of String
        :returns: instance of type "ExportOutput" -> structure: parameter
           "shock_id" of String
        """
        # ctx is the context object
        # return variables are: output
        #BEGIN export_genome_annotation_as_genbank

         # validate parameters
        if 'input_ref' not in params:
            raise ValueError('Cannot export GenomeAnnotation- not input_ref field defined.')

        # get WS metadata to get ws_name and obj_name
        ws = Workspace(url=self.workspaceURL)
        info = ws.get_object_info_new({'objects':[{'ref': params['input_ref'] }],'includeMetadata':0, 'ignoreErrors':0})[0]

        # export to a file
        file = self.genome_annotation_to_genbank(ctx, { 
                            'genome_ref': params['input_ref'], 
                            'new_genbank_file_name': info[1]+'.gbk' })[0]

        # create the output directory and move the file there
        export_package_dir = os.path.join(self.sharedFolder, info[1])
        os.makedirs(export_package_dir)
        shutil.move(file['path'], os.path.join(export_package_dir, os.path.basename(file['path'])))

        # package it up and be done
        dfUtil = DataFileUtil(self.callback_url)
        package_details = dfUtil.package_for_download({
                                    'file_path': export_package_dir,
                                    'ws_refs': [ params['input_ref'] ]
                                })

        output = { 'shock_id': package_details['shock_id'] }

        #END export_genome_annotation_as_genbank

        # At some point might do deeper type checking...
        if not isinstance(output, dict):
            raise ValueError('Method export_genome_annotation_as_genbank return value ' +
                             'output is not type dict as required.')
        # return the results
        return [output]
开发者ID:kbaseapps,项目名称:GenomeAnnotationFileUtil,代码行数:49,代码来源:GenomeAnnotationFileUtilImpl.py

示例13: test_cleanup

 def test_cleanup(self):
     ''' Cleanup objects created by tests. '''
     
     # Delete all of the objects in the test workspace.
     wsClient = Workspace(self._config["workspace_url"], token=self._token)
     listObjectsParams = dict()
     listObjectsParams['workspaces'] = [ self._config['test_ws'] ]
     objectList = wsClient.list_objects(listObjectsParams)
     deleteList = list()
     for object in objectList:
         deleteList.append( { 'wsid': object[6], 'objid': object[0], 'ver': object[4] })
     wsClient.delete_objects(deleteList)
     objectList = wsClient.list_objects(listObjectsParams)
     for object in objectList:
         print 'After delete Object %s %s' %(object[1], object[4])
开发者ID:kbase,项目名称:probabilistic_annotation,代码行数:15,代码来源:test-python-client.py

示例14: get_genome

def get_genome(genome_id=None,workspace_id=None,token=None,workspace_url=None):
	#download genome object from workspace
	if workspace_url is None:
		workspace_url='https://ci.kbase.us/services/ws'

	
	#print token
	#print genome_id
	#print workspace_id
	
	workspace_client=Workspace(url=workspace_url, token=token)
	genome=workspace_client.get_object({'id':genome_id, 'workspace':workspace_id, 'type':'KBaseGenomes.Genome'})
	#genome = workspace_client.get_object({'id' : 'Bifidobacterium_animalis_subsp._lactis_AD011', 'type' : 'KBaseGenomes.Genome',  'workspace' : 'plane83:1436884411390'})
	

	return genome
开发者ID:kbase,项目名称:genome_util,代码行数:16,代码来源:script_util.py

示例15: upload_workspace_data

def upload_workspace_data(cs, ws_url, source_ref, target_ws, obj_name):
    ws = Workspace(ws_url, token=TOKEN)
    type_ = ws.translate_from_MD5_types([CS_MD5_TYPE])[CS_MD5_TYPE][0]
    ws.save_objects(
        {'workspace': target_ws,
         'objects': [{'name': obj_name,
                      'type': type_,
                      'data': cs,
                      'provenance': [{'script': SCRIPT_NAME,
                                      'script_ver': __VERSION__,
                                      'input_ws_objects': [source_ref],
                                      }]
                      }
                     ]
         }
    )
开发者ID:brettin,项目名称:transform,代码行数:16,代码来源:trns_transform_KBaseFile_AssemblyFile_to_KBaseGenomes_ContigSet.py


注:本文中的biokbase.workspace.client.Workspace类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。