Code Documentation

Module contents

This module communicate with the Open Targets REST API with a simple client, and requires not knowledge of the API.

class opentargets.OpenTargetsClient(**kwargs)[source]

Bases: object

Main class to use to get data from the Open Targets REST API available at targetvalidation.org (or your private instance)

Init the client and start a connection

Keyword Arguments:
 **kwargs – all params forwarded to opentargets.conn.Connection object
close()[source]
filter_associations(**kwargs)[source]

Retrieve a set of associations by applying a set of filters

Keyword Arguments:
 **kwargs – are passed as parameters to the /public/association/filterby method of the REST API
Returns:Result of the query
Return type:IterableResult
filter_evidence(**kwargs)[source]

Retrieve a set of evidence by applying a set of filters

Keyword Arguments:
 **kwargs – are passed as parameters to the /public/evidence/filterby method of the REST API
Returns:Result of the query
Return type:IterableResult
get_association(association_id, **kwargs)[source]

Retrieve a specific Association object from the REST API provided its ID

Parameters:association_id (str) – Association ID
Keyword Arguments:
 **kwargs – are passed as other parameters to the /public/association method of the REST API
Returns:Result of the query
Return type:IterableResult
get_associations_for_disease(disease, **kwargs)[source]

Same as OpenTargetsClient.filter_associations but accept any string as disease parameter and fires a search if it is not a valid disease identifier

Parameters:disease (str) – a disease identifier or a string to search for a disease mapping
Keyword Arguments:
 **kwargs – are passed as parameters to the /public/association/filterby method of the REST API
Returns:Result of the query
Return type:IterableResult
get_associations_for_target(target, **kwargs)[source]

Same as OpenTargetsClient.filter_associations but accept any string as target parameter and fires a search if it is not an Ensembl Gene identifier

Parameters:target (str) – an Ensembl Gene identifier or a string to search for a gene mapping
Keyword Arguments:
 **kwargs – are passed as parameters to the /public/association/filterby method of the REST API
Returns:Result of the query
Return type:IterableResult
get_evidence(evidence_id, **kwargs)[source]

Retrieve a specific Evidence object from the REST API provided its ID

Parameters:evidence_id
Keyword Arguments:
 **kwargs – are passed as other parameters to the /public/evidence method of the REST API
Returns:Result of the query
Return type:IterableResult
get_evidence_for_disease(disease, **kwargs)[source]

Same as OpenTargetsClient.filter_evidence but accept any string as disease parameter and fires a search if it is not a valid disease identifier

Parameters:disease (str) – a disease identifier or a string to search for a disease mapping
Keyword Arguments:
 **kwargs – are passed as parameters to the /public/evidence/filterby method of the REST API
Returns:Result of the query
Return type:IterableResult
get_evidence_for_target(target, **kwargs)[source]

Same as OpenTargetsClient.filter_evidence but accept any string as target parameter and fires a search if it is not an Ensembl Gene identifier

Parameters:target (str) – an Ensembl Gene identifier or a string to search for a gene mapping
Keyword Arguments:
 **kwargs – are passed as parameters to the /public/evidence/filterby method of the REST API
Returns:Result of the query
Return type:IterableResult
get_stats()[source]

Returns statistics about the data served by the REST API

Returns:Result of the query
Return type:IterableResult
search(query, **kwargs)[source]

Search a string and return a list of objects form the search method of the REST API. E.g. A returned object could be a target or a disease

Parameters:query (str) – string to search for
Keyword Arguments:
 **kwargs – are passed as other parameters to the /public/search method of the REST API
Returns:Result of the query
Return type:IterableResult

Submodules

opentargets.conn module

This module abstracts the connection to the Open Targets REST API to simplify its usage. Can be used directly but requires some knowledge of the API.

class opentargets.conn.Connection(host='https://www.targetvalidation.org', port=443, api_version='latest', auth_app_name=None, auth_secret=None, use_http2=False)[source]

Bases: object

Handler for connection and calls to the Open Targets Validation Platform REST API

Parameters:
  • host (str) – host serving the API
  • port (int) – port to use for connection to the API
  • api_version (str) – api version to point to, default to ‘latest’
  • auth_app_name (str) – app_name if using authentication
  • auth_secret (str) – secret if using authentication
  • use_http2 (bool) – use http2 client
api_endpoint_docs(endpoint)[source]

Returns the documentation available for a given REST API endpoint

Parameters:endpoint (str) – endpoint of the REST API
Returns:documentation for the endpoint parsed from YAML docs
Return type:dict
close()[source]

Close connection to the REST API

get(endpoint, params=None)[source]

makes a GET request :param endpoint: REST API endpoint to call :type endpoint: str :param params: request payload :type params: dict

Returns:request response
Return type:Response
get_api_endpoints()[source]

Get a list of available endpoints

Returns:available endpoints
Return type:list
get_token(expire=60)[source]

Asks for a token to the API :param expire: expiration time for the token :type expire: int

Returns:the token served by the API
Return type:str
ping()[source]

Pings the API as a live check :returns: True if pinging the raw response as a str if the API has a non standard name :rtype: bool

post(endpoint, data=None)[source]

makes a POST request :param endpoint: REST API endpoint to call :type endpoint: str :param data: request payload :type data: dict

Returns:request response
Return type:Response
validate_parameter(endpoint, filter_type, value, method='get')[source]

Validate payload to send to the REST API based on info fetched from the API documentation

Parameters:
  • endpoint (str) – endpoint of the REST API
  • filter_type (str) – the parameter sent for the request
  • value – the value sent for the request
  • method (HTTPMethods) – request method, either HTTPMethods.GET or HTTPMethods.POST. Defaults to HTTPMethods.GET
Raises
AttributeError: if validation is not passed
class opentargets.conn.HTTPMethods[source]

Bases: object

GET = 'get'
POST = 'post'
class opentargets.conn.IterableResult(conn, method='get')[source]

Bases: object

Proxy over the Connection class that allows to iterate over all the items returned from a quer. It will automatically handle making multiple calls for pagination if needed.

Requires a Connection :param conn: a Connection instance :type conn: Connection :param method: HTTP method to use for the calls :type method: HTTPMethods

filter(**kwargs)[source]

Applies a set of filters to the current query Keyword Args

**kwargs: passed to the REST API
Returns:an IterableResult with applied filters
Return type:IterableResult
to_csv(**kwargs)[source]

Create a csv file from a flattened version of the response.

Keyword Arguments:
 **kwargs – forwarded to pandas.DataFrame.to_csv
Returns:output of pandas.DataFrame.to_csv

Notes

Requires Pandas to be installed.

Raises:ImportError – if Pandas is not available
to_dataframe(compress_lists=False, **kwargs)[source]

Create a Pandas dataframe from a flattened version of the response.

Parameters:compress_lists – if a value is a list, serialise it to a string with ‘|’ as separator
Keyword Arguments:
 **kwargs – forwarded to pandas.DataFrame.from_dict
Returns:A DataFrame with all the data coming from the query in the REST API
Return type:pandas.DataFrame

Notes

Requires Pandas to be installed.

Raises:ImportError – if Pandas is not available
to_excel(excel_writer, **kwargs)[source]

Create a excel (xls) file from a flattened version of the response.

Keyword Arguments:
 **kwargs – forwarded to pandas.DataFrame.to_excel
Returns:output of pandas.DataFrame.to_excel

Notes

Requires Pandas and xlwt to be installed.

Raises:ImportError – if Pandas or xlwt are not available
to_file(filename, compress=True, progress_bar=False)[source]
to_json(iterable=True, **kwargs)[source]
Parameters:iterable – If True will yield a json string for each result and convert them dinamically as they are fetched from the api. If False gets all the results and returns a singl json string.
Keyword Arguments:
 **kwargs – forwarded to json.dumps
Returns:an iterator of json strings or a single json string
to_namedtuple()[source]
Converts dictionary in the data to namedtuple. Useful for interactive data exploration on IPython
and similar tools
Returns:an iterator of namedtupled
Return type:iterator
class opentargets.conn.IterableResultSimpleJSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: json.encoder.JSONEncoder

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (‘, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

default(o)[source]

extends JsonEncoder to support IterableResult

class opentargets.conn.Response(response)[source]

Bases: object

Handler for responses coming from the api

Parameters:
  • response – a response coming from a requests call
  • content_type (str) – content type of the response
opentargets.conn.compress_list_values(d, sep='|')[source]
Parameters:
  • d (dict) – dictionary
  • sep (str) – separator char used to join list element
Returns:

dictionary with compressed lists

Return type:

dict

opentargets.conn.dict_to_namedtuple(d, named_tuple_class_name='Result', rename=True)[source]

Converts a dictionary to a namedtuple :param d: dictionary :type d: dict :param named_tuple_class_name: Name of the namedtuple class :param rename: rename unsafe fields. Defaults to True :type rename: bool

Returns:the converted namedtuple
Return type:namedtuple
opentargets.conn.dict_to_nested_namedtuple(d, named_tuple_class_name='Result')[source]

Recursively converts a dictionary to a namedtuple :param d: dictionary :type d: dict :param named_tuple_class_name: Name of the namedtuple class

Returns:the converted namedtuple
Return type:namedtuple
opentargets.conn.flatten(d, parent_key='', separator='.')[source]

Takes a nested dictionary as input and generate a flat one with keys separated by the separator

Parameters:
  • d (dict) – dictionary
  • parent_key (str) – a prefix for all flattened keys
  • separator (str) – separator between nested keys
Returns:

a flattened dictionary

Return type:

dict

opentargets.statistics module

class opentargets.statistics.HarmonicSumScorer(buffer=100)[source]

Bases: object

An HarmonicSumScorer will ingest any number of numeric score, keep in memory the top max number defined by the buffer and calculate an harmonic sum of those :param buffer: number of element to keep in memory to compute the harmonic sum

add(score)[source]

add a score to the pool of values :param score: a number to add to the pool ov values. is converted to float :type score: float

static harmonic_sum(data, scale_factor=1, cap=None)[source]

Returns an harmonic sum for the data passed :param data: list of floats to compute the harmonic sum from :type data: list :param scale_factor: a scaling factor to multiply to each datapoint. Defaults to 1 :type scale_factor: float :param cap: if not None, never return an harmonic sum higher than the cap value. :type cap: float

Returns:the harmonic sum of the data passed
Return type:harmonic_sum (float)
refresh()[source]

Store the minimum value of the pool

score(*args, **kwargs)[source]

Returns an harmonic sum for the pool of values :param *args: forwarded to HarmonicSumScorer.harmonic_sum

Keyword Args
**kwargs: forwarded to HarmonicSumScorer.harmonic_sum
Returns:the harmonic sum of the pool of values
Return type:harmonic_sum (float)