Package: braincube-connector
braincube_connector: a python client for BraincubeDescriptionThe python packagebraincube_connectorprovides a tool for datascientists to access their data on Braincube directly from python.InstallationInstall with pip:pipinstallbraincube_connectorConfiguration and AuthenticationSince version2.2.0, the authentication uses a personal access token (PAT).In order to create a PAT, you need to go in your braincube personalmenu > Account > Access tokens > +/AddThe scopes of the token should includeBRAINCUBEandSSO_READ.Then two options exist to pass the PAT to the braincube_connector:Using a configuration dictionary when creating a client:frombraincube_connectorimportclientclient.get_instance(config_dict={"api_key":"<my_personal_access_token>","domain":"mybraincube.com"})Using a configuration file:frombraincube_connectorimportclientclient.get_instance("config_file"="myfile.json")myfile.json{"api_key":"<my_personal_access_token>","domain":"mybraincube.com"}Authentication with an Oauth2 token.Thebraincube_connectorused to support only this type of authentication. This is not the method we encourage
the most since the PAT is available, because the Oauth2 is obtained with thebraincube-token-getterthat is not under active development.
However if you still want to use this method, you need to setup the configuration file (or dictionary) as follows:config.json{"client_id":"app id","client_secret":"app key","domain":"mybraincube.com","verify":true,"oauth2_token":"token value"}By default the connector searches for a PAT and uses the oauth2_token when the PAT is not present in the dictionary.Configuration parametersHere is a list of the settings available in the configuration file:domain(optional ifsso_base_urlandbraincube_base_urlexist): The domain of the braincube to access.sso_base_url(optional ifdomainexists): The base URL of the SSO used to check the validity of your access token.braincube_base_url(optional ifdomainexists): The base URL of the Braincube API used to fetch data from.api_key(optional ifoauth2_tokenexists): a personal access token generated in the braincube account configuration.oauth2_token(optional ifapi_keyexists): an OAuth2 token obtained with thebraincube-token-getter. Used only whenapi_keydoes not exist.verify(optional, default isTrue): IfFalse, the requests do not verify the SSL certificate.Settingverifyto false must be used with care, it's a security threat (seerequests documentationTheclient_id,client_secretfrom the last section are used only by thebraincube_token_getterwhen requesting a new OAuth token.Note:If the client is not initialized manually or if no configuration is passed toget_instance, the package creates a client instance from one of these two files./config.jsonor~/.braincube/config.json(in this priority order) when they exist.UsageClientA client can be inialized manually from a custom configuration file.frombraincube_connectorimportclientclient.get_instance(config_file="pathto/config.json")Note:If the client is not initialized manually, the package creates a client instance from one of these two files./config.jsonor~/.braincube/config.json(in this priority order) if they exist.Features of the connector entities.The connector gives access to different entities(described in more details in the following sections) that share multiple methods:<entity>.get_name(): Returns the name of the entity.<entity>.get_bcid(): Returns the bcId identifier of the entity.<entity>.get_uuid(): Returns the braincube unique uuid identifier of the entity.BraincubeTo obtain a list of all the availableBraincubeentities with a client:frombraincube_connectorimportbraincubebraincube.get_braincube_list()Or to select a specificBraincubeentity from its name:bc=braincube.get_braincube("demo")MemoryBaseThe list of all the memory bases available within aBraincubeis obtained withmb_list=bc.get_memory_base_list()Note:The number of memory bases in a braincube can be numerous,  henceget_memory_base_listallows paginated requestsbc.get_memory_base_list(page=0)To select a unique memory base, go with its bcId:mb=bc.get_memory_base(20)VariableDescriptionsThe variable description are linked to a memory base.var_desc=mb.get_variable(bcid="2000034")For multiple variable descriptions:mb.get_variable_list(page=0)Note:Similarly to memory bases, providing no argument toget_variable_listretrieves all the descriptions available in the memory base.The type of variable is obtained with the functionget_typevar_desc.get_type()DataGroupDataGroup are obtained from a memory base:datagroup=mb.get_datagroup(bcid="10")The list of the available datagroups can also be obtained withmb.get_datagroup_list().A datagroup is a container that includes multiple variables. They are accessed withdatagroup.get_variable_ids()# Gets the variable bcIdsdatagroup.get_variable_list()# Gets the list of VariableDescription objects.EventAn event is a predifined set of conditions in braincube. It is accessed as follows:event=mb.get_event(bcid="10")event_list=mb.get_event_list()The interest of events is that you can access the conditions they contain in order create newfiltersfor aget_datafunction:event.get_conditions()JobDescriptionThe job desciption contains the settings used to build an analysis and gives a proxy to access these parameters easily. A JobDescription is obtained from a memory base as follows:job_desc=mb.get_job(bcid="573")job_list=mb.get_job_list(page=0)The properties are acced with the following methods:get_conditions:Gets a list of the conditions used to select the job variables.job_desc.get_conditions()job_desc.get_conditions(combine=True)# Merge the conditions into onejob_desc.get_conditions(include_events=True)# Includes the conditions from# the job's eventsget_variable_ids:Gets a list of the variables involved in the job, including the target variables and the influence variables.job_desc.get_variable_ids()get_events:Gets a list of the event objects used by the job.job_desc.get_events()get_categories:Gets a list of conditions used to categorise a job's data asgoodorbad. You may have amiddlecategory, it's an old categorisation which will not be used anymore.job_desc.get_categories()get_data:When a job is created on braincube, a separate copy of the data is made. As for now this copy is not available from the webservices. However theget_datamethod collects the job's data from the memory base using the same filters as when the job was created. Be aware that these data might be different from the job's data if the memory base has been updated since the job creation.Similarly to other objectget_data, afiltersparameter is available to add additionalfiltersto the job's conditions.job_desc.get_data()Job rulesThe job rule descriptions are obtained with the methodsget_ruleorget_rule_listeither from a job or a memory base. The only difference being that in the case of a memory baseget_rule_listgets all the rules existing in the memory base whereas for a job, it gets the rules specific to the job under consideration.rule=job.get_rule(bcid="200")rule_list=job.get_rule_list()To access aRuleDescriptionobject's metadata, you can calle theget_metadatafunctionrule.get_metadata()Get variable dataA memory base can also request the data for a custom set of variable ids. Addingfiltersrestricts the returned data to a desired subset of the data. The method is called as follows:data=mb.get_data(["2000001","2000034"],filters=my_filters,label_type="name",dataframe=True)The output format is a dictionary or a pandas DataFrame when thedataframeparameter is set toTrue. The keys/column labels are the variable bcIds or names depending on whetherlabel_typeis set to"bcid"or"name"respectively.Note:By default the dates are not parsed todatetimeobjects in order to speed up theget_datafunction but it is possible to enable the parsing:frombraincube_connectorimportparametersparameters.set_parameter({"parse_date":True})Data filtersTheget_datamethods have the option to restrict the data that are collected by using a set of filters. Thefiltersparameter must be a list conditions (even for a single condition):object.get_data(filters=[{"BETWEEN":["mb20/d2000002",0,10]},{"BETWEEN":["mb20/d2000003",-1,1]}])Here is a selection of the most common types of filters:Equals toSelects data when a variable is equal to{"EQUALS":["mb20/d2000002",2.0]}BetweenSelects the data when a variable belongs to a range.{"BETWEEN":["mb20/d2000003",-1,1]}Lower thanSelects the data when a variable is lower than a certain value.{"LESS":["mb20/d2000003",10]}Note:TheLESS_EQUALSfilter also exists.Greater thanSelects the data when a variable is greater than a certain value.{"GREAT":["mb20/d2000003",10]}Note:TheGREAT_EQUALSfilter also exists.Not:TheNOTcondition creates the opposite of an existing condition.{"Not":[{"filter":...}]}And gateIt is possible to combine filters using aandgate.{"AND":[{"filter1":...},{"filter2":...}]}Notes:AANDfilter can only host two conditions. In order to join more than two filters multipleANDconditions should be nested one into another.When multiple filters are provided in theget_data'sfiltersparameters, they are joined together within the function usingANDgates.Or gate:Similar toANDbut uses aORgate.{"OR":[{"filter1":...},{"filter2":...}]}Advanced UsageThebraincube_connectorprovides a simple interface for the most common features of thebraincube web-servicesorbraindatabut it is not extensive.If you need to access an endpoint ofbraincube webservicesorbraindata, therequest_wsfunction of the library can help you. The function uses the configuration passed to the client creation to manage the authentication.frombraincube_connectorimportclientclient.get_instance(config_dict={...})json_result=client.request_ws("braincube/demo/braindata/mb20/simple")Most braincube requests return a json, but for a few of them it might be better to deactivate the parsing by setting theresponse_as_jsonparameter toFalse. In the latter case,request_wsreturns the response object.json_result=client.request_ws("braincube/demo/braindata/mb20/simple",response_as_json=False)Library parametersThe library parameters can be set to custom values:frombraincube_connectorimportparameters# Change the request pagination size to 10parameters.set_parameter({"page_size":10})# Parse dates to datetime objectsparameters.set_parameter({"parse_date":True})# The Braincube database stores multiple names (`tag`, `standard`, or `local`) for a variable# By default `standard` id used, but you can change it as follows:parameters.set_parameter(({"VariableDescription_name_key":"tag"}))