Commit 0a6250b2 authored by Marina Diaz Uzquiano's avatar Marina Diaz Uzquiano

Wrapper created by David Navarro Riaño

parents
build/
dist/
class Constants:
MAIN_PATH = "https://disnet.ctb.upm.es/api/disnet"
PATH_BIO = "/bio"
PATH_DISEASES = "/diseases"
PATH_GENES = "/genes"
PATH_VARIANTS = "/variants"
PATH_PATHWAYS = "/pathways"
PATH_PROTEINS = "/proteins"
PATH_PPIS = "/ppis"
PATH_PHARMA = "/pharma"
PATH_PHENOTYPES = "/phenotypes"
PATH_DRUGS = "/drugs"
PATH_TARGETS = "/targets"
PATH_PHENO = "/pheno"
PATH_SOURCES = "/sources"
PATH_SNAPSHOTS = "/snapshots"
PATH_DISNET_DISEASES = "/disnet-diseases"
PATH_SYMPTOMS = "/symptoms"
PATH_METADATA = "/metadata"
SLASH = "/"
QUESTION_MARK = "?"
QUESTION_MARK_SOURCE_EQUALS = "?source="
AMPERSAND_SOURCE_EQUALS = "&source="
AMPERSAND_SNAPSHOT_EQUALS = "&snapshot="
AMPERSAND_NAME_EQUALS = "&name="
QUESTION_MARK_NAME_EQUALS = "?name="
AMPERSAND_EXACT_MATCH_EQUALS = "&exact-match="
SLASH_URL = "/url"
SLASH_INTERACTIONS = "/interactions"
QUESTION_MARK_ID_EQUALS = "?id="
PATH_MAPS = "/maps"
PATH_CUI_MAPS = "/cui-maps"
PATH_DISNET_ID_MAPS = "/disnet-id-maps"
\ No newline at end of file
"""Contains the custom Exceptions for the different errors that may occur"""
class NoResultFoundException(Exception):
"""Raised when requesting data from the API and either the response code is 404 or the dataset is empty"""
def __init__(self, message: str = ""):
self.message = message
print("===========================")
print("RESULTS NOT FOUND IN YOUR SEARCH")
print("===========================")
Exception.__init__(self, str(self.message))
class WrongOptionChosen(Exception):
"""Raised when the parameter passed to the function is not one of the possible options to choose"""
def __init__(self, message: str = ""):
self.message = message
print("===========================")
print("YOU ENTERED A WRONG OPTION, CHECK BELOW THE POSSIBLE OPTIONS TO INPUT:")
print("===========================")
Exception.__init__(self, str(self.message))
import DISNET.objects.DrugObject as d
import DISNET.services.ServiceBio as s
import DISNET.services.ServicePharma as p
def main():
serPhar = p.ServicePharma()
drug = serPhar.getAllDrugs()[0]
print(drug)
if __name__ == "__main__":
main()
class DiseaseAvailableListRestApi:
"""Class to instance objects of DiseaseAvailableList for the Metadata objects"""
def __init__(self, albumId: (str, int), source: str, version: str, numberDiseases: (int, str),
useDiseaseSafeList: bool):
self.__albumId = str(albumId)
self.__source = str(source)
self.__version = str(version)
self.__numberDiseases = int(numberDiseases)
self.__useDiseaseSafeList = useDiseaseSafeList
def getAlbumId(self) -> str:
"""Returns the id of the album"""
return self.__albumId
def getSource(self) -> str:
"""Returns the source"""
return self.__source
def getVersion(self) -> str:
"""Returns the version"""
return self.__version
def getNumberDiseases(self) -> int:
"""Returns the number of diseases"""
return self.__numberDiseases
def getUseDiseaseSafeList(self) -> bool:
"""Returns if the safe list should be used"""
return self.__useDiseaseSafeList
def __str__(self) -> str:
return "DiseaseAvailableListRestApi: [albumId: " + self.__albumId + ", source: " + self.__source + \
", version: " + self.__version + ", numberDiseases: " + str(self.__numberDiseases) + \
", useDiseaseSafeList: " + str(self.__useDiseaseSafeList) + "]"
def __repr__(self)->str:
"""overrides the method for custom representation"""
return str(self)
\ No newline at end of file
import DISNET.metadata.TvpRestApi as TvpRestApi
import DISNET.metadata.DiseaseAvailableListRestApi as DiseaseAvailableListRestApi
import DISNET.metadata.MetamapRestApi as MetamapRestApi
class MetadataObject:
"""Class to instance Metadata type objects"""
def __init__(self,
tvpRestApi: TvpRestApi.TvpRestApi,
diseaseAvailableListRestApi: DiseaseAvailableListRestApi.DiseaseAvailableListRestApi,
metamapRestApi: MetamapRestApi.MetamapRestApi):
self.__tvpRestApi = tvpRestApi
self.__diseaseAvailableListRestApi = diseaseAvailableListRestApi
self.__metamapRestApi = metamapRestApi
def getTvpRestApi(self) -> TvpRestApi.TvpRestApi:
"""Returns the Tvp of the Metadata"""
return self.__tvpRestApi
def getDiseaseAvailableListRestApi(self) -> DiseaseAvailableListRestApi.DiseaseAvailableListRestApi:
"""Returns the lis of available diseases of the metadata"""
return self.__diseaseAvailableListRestApi
def getMetamapRestApi(self) -> MetamapRestApi.MetamapRestApi:
"""Returns the Metamap of the Metadata"""
return self.__metamapRestApi
def __str__(self):
"""Returns the string representation of the Metadata"""
return str(self.__tvpRestApi) + " " + str(self.__diseaseAvailableListRestApi) + " " + str(self.__metamapRestApi)
def __repr__(self)->str:
"""overrides the method for custom representation"""
return str(self)
\ No newline at end of file
class MetamapRestApi:
"""Class to instance objects of type Metamap"""
def __init__(self, sources :list[str], options :str, conceptLocation :bool, semanticTypes :list[str]):
self.__sources = sources
self.__options = options
self.__conceptLocation = conceptLocation
self.__semanticTypes = semanticTypes
def getOptions(self)->str:
"""Returns the options of the Metamap"""
return self.__options
def getConceptLocation(self)->bool:
"""Returns if the concept location is enabled"""
return self.__conceptLocation
def getSources(self)->list[str]:
"""Returns the sources of the Metamap"""
return self.__sources
def getSemanticTypes(self )->list[str]:
"""Returns the semantic types of the Metamap"""
return self.__semanticTypes
def __str__(self):
"""Returns the string representation of the Metamap"""
return "MetamapRestApi: [sources: " + str(self.__sources) +\
", options: " + str(self.__options) + ", concept_location: " + str(self.__conceptLocation) +\
", semanticTypes: " + str(self.__semanticTypes) + "]"
def __repr__(self)->str:
"""overrides the method for custom representation"""
return str(self)
class TvpRestApi:
"""Class to instance objects of type TvpRestApi"""
def __init__(self, nonRepeatedTerms:(str,int), termsFound:(str,int), validatedNonRepeatedTerms:(str,int)):
self.__nonRepeatedTerms = int(nonRepeatedTerms)
self.__termsFound = int(termsFound)
self.__validatedNonRepeatedTerms = int(validatedNonRepeatedTerms)
def getNonRepeatedTerms(self)->int:
"""Returns the number of non-repeated terms"""
return self.__nonRepeatedTerms
def getTermsFound(self)->int:
"""Returns the number of terms found"""
return self.__termsFound
def getValidatedNonRepeatedTerms(self)->int:
"""Returns the number of validated non-repeated terms"""
return self.__validatedNonRepeatedTerms
def __str__(self)->str:
return "TvpRestApi: [nonRepeatedTerms: " + str(self.__nonRepeatedTerms) +\
", termsFound: " + str(self.__termsFound) + ", validatedNonRepeatedTerms: " + \
str(self.__validatedNonRepeatedTerms) + "]"
def __repr__(self)->str:
"""overrides the method for custom representation"""
return str(self)
import DISNET.objects.DisnetObject as DisnetObject
class CuiMapObject(DisnetObject.DisnetObject):
"""Class to instance objects of type Cui Map"""
def __init__(self, id: (str, int), vocabulary: str, source: str):
DisnetObject.DisnetObject.__init__(self, id)
self.__vocabulary = vocabulary
self.__source = source
def getVocabulary(self) -> (str, int):
"""Returns the vocabulary"""
return self.__vocabulary
def getSource(self) -> (str, int):
"""Returns the source"""
return self.__source
def info(self) -> str:
"""Returns the information of the Disease as a string"""
return "CuiMap: [source: + " + self.__source + ", cui: " + self.getId() + ", vocabulary: " + self.__vocabulary + "]"
def __eq__(self, other) -> bool:
"""Equals to other Disease"""
if isinstance(other, CuiMapObject):
equalID = self.getId() == other.getId()
equalName = self.__source == other.getSource()
equalVocab = self.__vocabulary == other.getVocabulary()
return equalID and equalName and equalVocab
else:
return False
import DISNET.objects.DisnetObject as DisnetObject
class DiseaseObject(DisnetObject.DisnetObject):
"""Class to instance objects of type Disease"""
def __init__(self, id: (str, int), name: str):
DisnetObject.DisnetObject.__init__(self, id)
self.__name = name
def getName(self) -> (str, int):
"""Returns the name of the Disease"""
return self.__name
def info(self) -> str:
"""Returns the information of the Disease as a string"""
return "DiseaseObject: [name: " + self.__name + ", id: " + self.getId() + "]"
def __eq__(self, other) -> bool:
"""Equals to other Disease"""
if isinstance(other, DiseaseObject):
equalID = self.getId() == other.getId()
equalName = self.__name == other.getName()
return equalID and equalName
else:
return False
import DISNET.objects.DisnetObject as DisnetObject
class DisnetIdMapObject(DisnetObject.DisnetObject):
"""Class to instance objects of type Disnet Id Map"""
def __init__(self, id: (str, int), vocabulary: str, source: str):
DisnetObject.DisnetObject.__init__(self, id)
self.__vocabulary = vocabulary
self.__source = source
def getVocabulary(self) -> (str, int):
"""Returns the vocabulary"""
return self.__vocabulary
def getSource(self) -> (str, int):
"""Returns the source"""
return self.__source
def info(self) -> str:
"""Returns the information of the Disease as a string"""
return "DisnetIdMap: [source: + " + self.__source + ", disnetId: " + self.getId() + ", vocabulary: " + self.__vocabulary + "]"
def __eq__(self, other) -> bool:
"""Equals to other Disease"""
if isinstance(other, DisnetIdMapObject):
equalID = self.getId() == other.getId()
equalName = self.__source == other.getSource()
equalVocab = self.__vocabulary == other.getVocabulary()
return equalID and equalName and equalVocab
else:
return False
from abc import ABC, abstractmethod
class DisnetObject(ABC):
"""Parent for the different DISNET objects"""
def __init__(self, id:(str, int)):
self.__id = id
def getId(self)->(str,int):
"""Return the id of the Object"""
return self.__id
def __str__(self)->str:
"""overrides the method for custom representation"""
return self.info()
def __repr__(self)->str:
"""overrides the method for custom representation"""
return str(self)
@abstractmethod
def info(self):
"""Each child must implement its representation"""
pass
import DISNET.objects.DisnetObject as DisnetObject
class DrugObject(DisnetObject.DisnetObject):
"""Class to instance objects of type Drug"""
def __init__(self, id: (str, int), name: str, molecularType: str = None, chemicalStructure: str = None,
inchiKey: str = None):
DisnetObject.DisnetObject.__init__(self, id)
self.__name = name
self.__molecularType = molecularType
self.__chemicalStructure = chemicalStructure
self.__inchiKey = inchiKey
def getName(self) -> str:
"""Returns the name of the Drug"""
return self.__name
def getMolecularType(self) -> str:
"""Returns the molecular type of the Drug"""
return self.__molecularType
def getChemicalStructure(self) -> str:
"""Returns the chemical structure of the Drug"""
return self.__chemicalStructure
def getInchiKey(self) -> str:
"""Returns the inchi key of the Drug"""
return self.__inchiKey
def info(self) -> str:
"""Returns the information of the Drug as a string"""
return "DrugObject: [name: " + str(self.__name) + ", id: " + str(self.getId()) + ", molecularType: " + \
str(self.__molecularType) + ", chemicalStructure: " + str(self.__chemicalStructure) + \
", inchiKey: " + str(self.__inchiKey) + "]"
def __eq__(self, other) -> bool:
"""Equals to other Drug"""
if isinstance(other, DrugObject):
equalName = self.__name == other.getName()
equalID = self.getId() == other.getId()
return equalName and equalID
else:
return False
import DISNET.objects.DisnetObject as DisnetObject
class GeneObject(DisnetObject.DisnetObject):
"""Class to instance objects of type Gene"""
def __init__(self, id: (str, int), name: str, symbol: str):
DisnetObject.DisnetObject.__init__(self, id)
self.__name = name
self.__symbol = symbol
def getName(self) -> str:
"""Returns the name of the Gene"""
return self.__name
def getSymbol(self) -> str:
"""Returns the symbol of the Gene"""
return self.__symbol
def info(self) -> str:
"""Returns the information of the Gene as a string"""
return "GeneObject: [name: " + self.__name + ", id: " + str(self.getId()) + ", symbol: " + \
str(self.__symbol) + "]"
def __eq__(self, other) -> bool:
"""Equals to other Gene"""
if isinstance(other, GeneObject):
equalName = self.__name == other.getName()
equalID = self.getId() == other.getId()
equalSymbol = self.__symbol == other.getSymbol()
return equalID and equalName and equalSymbol
else:
return False
import DISNET.objects.DisnetObject as DisnetObject
import DISNET.objects.ProteinObject as ProteinObject
class PPISObject(DisnetObject.DisnetObject):
"""Class to instance objects of type PPIS"""
def __init__(self, protein1: ProteinObject.ProteinObject, protein2: ProteinObject.ProteinObject):
DisnetObject.DisnetObject.__init__(self, protein1.getId() + protein2.getId() + "")
self.__protein1 = protein1
self.__protein2 = protein1
def getProtein1(self) -> ProteinObject.ProteinObject:
"""Returns the first protein of the PPIS"""
return self.__protein1
def getProtein2(self) -> ProteinObject.ProteinObject:
"""Returns the second protein of the PPIS"""
return self.__protein2
def info(self) -> str:
"""Returns the information of the PPIS as a string"""
return "PPISObject: [protein1: " + str(self.__protein1) + ", protein2: " + str(self.__protein2) + "]"
def __eq__(self, other) -> bool:
"""Equals to other PPIS"""
if isinstance(other, PPISObject):
equalP1 = self.__protein1.getId() == other.getProtein1().getId()
equalID = self.getId() == other.getId()
equalP2 = self.__protein2.getId() == other.getProtein2().getId()
return equalID and equalP1 and equalP2
else:
return False
import DISNET.objects.DisnetObject as DisnetObject
class PathwayObject(DisnetObject.DisnetObject):
"""Class to instance objects of type Pathway"""
def __init__(self, id: (str, int), name: str):
DisnetObject.DisnetObject.__init__(self, id)
self.__name = name
def getName(self) -> str:
"""Returns the name of the Pathway"""
return self.__name
def info(self) -> str:
"""Returns the information of the Pathway as a string"""
return "PathwayObject: [name: " + self.__name + ", id: " + self.getId() + "]"
def __eq__(self, other) -> bool:
"""Equals to other Pathway"""
if isinstance(other, PathwayObject):
equalName = self.__name == other.getName()
equalID = self.getId() == other.getId()
return equalID and equalName
else:
return False
import DISNET.objects.DisnetObject as DisnetObject
class PhenotypeObject(DisnetObject.DisnetObject):
"""Class to instance objects of type Phenotype"""
def __init__(self, id: (str, int), name: str):
DisnetObject.DisnetObject.__init__(self, id)
self.__name = name
def getName(self) -> str:
"""Returns the name of the Phenotype"""
return self.__name
def info(self) -> str:
"""Returns the information of the Phenotype as a string"""
return "PhenotypeObject: [name: " + self.__name + ", id: " + self.getId() + "]"
def __eq__(self, other) -> bool:
"""Equals to other Phenotype"""
if isinstance(other, PhenotypeObject):
equalName = self.__name == other.getName()
equalID = self.getId() == other.getId()
return equalID and equalName
else:
return False
import DISNET.objects.DisnetObject as DisnetObject
class ProteinObject(DisnetObject.DisnetObject):
"""Class to instance objects of type Protein"""
def __init__(self, id:str):
DisnetObject.DisnetObject.__init__(self, id)
def info(self):
"""Returns the information of the Protein as a string"""
return "ProteinObject: [id: " + self.getId() + "]"
def __eq__(self, other)->bool:
"""Equals to other Protein"""
if isinstance(other, ProteinObject):
return self.getId() == other.getId()
else:
return False
import DISNET.objects.DisnetObject as DisnetObject
class SymptomObject(DisnetObject.DisnetObject):
"""Class to instance objects of type Symptom"""
def __init__(self, cui: str, name: str, semanticTypes: list[str]):
DisnetObject.DisnetObject.__init__(self, cui)
self.__name = name
self.__semanticTypes = semanticTypes
def getName(self) -> str:
"""Returns the name of the Symptom"""
return self.__name
def getSemanticTypes(self) -> list[str]:
"""Returns the semantic types of the Symptom"""
return self.__semanticTypes
def info(self) -> str:
"""Returns the information of the Symptom as a string"""
return "SymptomObject: [name: " + self.__name + ", cui: " + self.getId() + ", semanticTypes: " + \
str(self.__semanticTypes) + "]"
def __eq__(self, other) -> bool:
"""Compares to other Symptom"""
if isinstance(other, SymptomObject):
equalName = self.__name == other.getName()
equalCui = self.getId() == other.getId()
equalSemanticTypes = self.__semanticTypes == other.getSemanticTypes()
return equalCui and equalName and equalSemanticTypes
else:
return False
import DISNET.objects.DisnetObject as DisnetObject
class TargetObject(DisnetObject.DisnetObject):
"""Class to instance objects of type Target"""
def __init__(self, id: (str, int), name: str, targetType: str = None, organismName: str = None):
DisnetObject.DisnetObject.__init__(self, id)
self.__name = name
self.__targetType = targetType
self.__organismName = organismName
def getName(self) -> str:
"""Returns the name of the target"""
return self.__name
def getTargetType(self) -> str:
"""Returns the target type"""
return self.__targetType
def getOrganismName(self) -> str:
"""Returns the organism name"""
return self.__organismName
def info(self):
"""Returns the information of the Target as a string"""
return "TargetObject: [name: " + self.__name + ", id: " + self.getId() + ", organismName: " + \
self.__organismName + ", targetType: " + self.__targetType + "]"
def __eq__(self, other) -> bool:
"""Equals to other Target"""
if isinstance(other, TargetObject):
equalName = self.__name == other.getName()
equalID = self.getId() == other.getId()
return equalID and equalName
else:
return False
import DISNET.objects.DisnetObject as DisnetObject
class VariantObject(DisnetObject.DisnetObject):
"""Class to instance objects of type Variant"""
def __init__(self, id: (str, int), chromosome: str, chroposition: str, consequence: str):
DisnetObject.DisnetObject.__init__(self, id)
self.__chromosome = chromosome
self.__chroposition = chroposition
self.__consequence = consequence
def getChromosome(self) -> str:
"""Returns the chromosome of the Variant"""
return self.__chromosome
def getChroposition(self) -> str:
"""Returns the Chromosome Position of the Variant"""
return self.__chroposition
def getConsequence(self) -> str:
"""Returns the consequence of the Variant"""
return self.__consequence
def info(self) -> str:
"""Returns the information of the Variant as a string"""
return "VariantObject: [id: " + self.getId() + ", chromosome: " + str(self.__chromosome) + \
", chroposition: " + str(self.__chroposition) + ", consequence: " + str(self.__consequence) + "]"
def __eq__(self, other) -> bool:
"""Equals to other Variant"""
if isinstance(other, VariantObject):
equalChromosome = self.__chromosome == other.getChromosome()
equalID = self.getId() == other.getId()
equalChroposition = self.__chroposition == other.getChroposition()
equalConsequence = self.__consequence == other.getConsequence()
return equalID and equalChromosome and equalChroposition and equalConsequence
else:
return False
This diff is collapsed.
import requests
import DISNET.Exceptions as E
from abc import ABC
class ServiceDisnet(ABC):
"""Parent class for the different services in the different layers of the API.
It is an abstract class
"""
def __init__(self):
pass
def connection(self, url: str) -> dict:
"""Method to make the connection to the specified url, it returns the response in a Json format.
:param url: the specified url to make the get requests to.
:raises NoResultFoundException: when the response code is not 200 or when the data set is empty.
"""
urlMod = url.replace(' ', '%20')
response = requests.get(urlMod)
responseJson = response.json()
if (response.status_code == 200 and responseJson["data"]):
return responseJson
else:
raise E.NoResultFoundException()
import DISNET.services.ServiceDisnet as ServiceDisnet
import DISNET.objects.CuiMapObject as CuiMapObject
import DISNET.objects.DisnetIdMapObject as DisnetIdMapObject
import DISNET.Constants as Constants
C = Constants.Constants # easier access to constants
class ServiceMapping(ServiceDisnet.ServiceDisnet):
"""Class to instance objects to access methods related to the Mapping layer.
It inherits from the ServiceDisnet class
"""
def __init__(self):
ServiceDisnet.ServiceDisnet.__init__(self)
def getDisnetIdsByCui(self, cui: (int,str)) -> list[DisnetIdMapObject.DisnetIdMapObject]:
"""Method to get all the mappings of a specified cui.
:param cui: cui of the disease to map
:raises NoResultsFoundException: when no results are found
"""
url = C.MAIN_PATH + C.PATH_MAPS + C.SLASH + cui + C.PATH_DISNET_ID_MAPS
responseJson = self.connection(url)
return self.__getAllDisnetIdMappings(responseJson)
def getCuisByDisnetId(self, disnetId: (int,str)) -> list[CuiMapObject.CuiMapObject]:
"""Method to get all the cui mappings of a specified id.
:param id: id of the disease to map
:raises NoResultsFoundException: when no results are found
"""
url = C.MAIN_PATH + C.PATH_MAPS + C.SLASH + disnetId + C.PATH_CUI_MAPS
responseJson = self.connection(url)
return self.__getAllCuisMappings(responseJson)
def __getAllDisnetIdMappings(self, responseJson):
"""Method to get all the Disnet Id Mappings from the response received in other methods
:param response: json containing the response of the get petition
"""
returnList = []
listIdMapsJson = responseJson["data"]
for idMapJson in listIdMapsJson:
disnetId = idMapJson["disnetId"]
vocabulary = idMapJson["vocabulary"]
source = idMapJson["source"]
disnetIdMap = DisnetIdMapObject.DisnetIdMapObject(disnetId,vocabulary,source)
returnList.append(disnetIdMap)
return returnList
def __getAllCuisMappings(self, responseJson):
"""Method to get all the cui Mappings from the response received in other methods
:param response: json containing the response of the get petition
"""
returnList = []
listCuiMapsJson = responseJson["data"]
for cuiMapJson in listCuiMapsJson:
cui = cuiMapJson["cui"]
vocabulary = cuiMapJson["vocabulary"]
source = cuiMapJson["source"]
disnetIdMap = CuiMapObject.CuiMapObject(cui,vocabulary,source)
returnList.append(disnetIdMap)
return returnList
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
# Empaquetado e importación de la librería
<h2> Generación del archivo wheel </h2>
Una vez pasada la parte de implementación se procede a explicar la parte de empaquetado de la librería para su posterior uso. El objetivo del empaquetado es el de lograr un archivo .whl (wheel) que luego podrá ser instalado en cualquier environment para poder importar la librería DISNET en cualquier proyecto. Un archivo wheel es un tipo de extensión diseñada para reemplazar a los antiguos archivos egg. Estos archivos whl facilitan la instalación de paquetes en proyectos Python. En este caso se desea generar un archivo wheel para que luego pueda ser utilizado por el futuro programador en su proyecto instalandolo e importando la librería de DISNET que contendrá.
Previamente se debe asegurar que se respeta la jerarquía de archivos explicada anteriormente y que el archivo setup.py está bien configurado. Es muy importante que cada paquete que contenga la libreria incluya un archivo "__init__.py" vacío, ya que de lo contrario no se podrán localizar los paquetes a pesar de haber sido indicados en el setup y, cuando se vaya a utilizar la librería, dará un error relacionado con que no encuentra el paquete especificado.
Se procede a explicar el procedimiento realizado en un terminal de ubuntu, luego será de manera análoga en otros sistemas unix.
Primero se ha de situar el terminal en la carpeta base del proyecto, es decir en este caso en el directorio DISNET-Base. En esta carpeta deben estar los archivos setup.py, un archivo __init__.py, y el README.md además del paquete tests y el paquete DISNET. Una vez dentro de dicha carpeta se debe ejcutar el siguiente comando:
`$ python setup.py bdist_wheel`
Este comando ejecutará el archivo setup.py y creará el archivo wheel a demas de una serie de carpetas y archivos que no son relevantes para el proposito descrito en esta sección. Este archivo whl mencionado se encontrará en la carpeta DISNET-Base/dist/. El archivo que se genera dentro de la carpeta dst en este ejemplo es el siguiente:
<i> DISNET-0.1-py3-none-any.whl </i>
Los archivos generados como resultado del comando anterior tienen un tipo de nomenclatura especial y por tanto si se cambiase el nombre al archivo generaría fallos a la hora de instalarlo.
<h2> Instalación </h2>
Se va a proceder a explicar el proceso de instalación del paquete whl generado en la seccón anterior. Para ello se van a hacer una serie de suposiciones previas. Una de estas suposiciones será que el sistema donde se va a proceder a instalar dicho paquete tiene un environnement de anaconda creado con python instalado. El proceso será similar para otras situaciones o gestores de environments.
El primer paso seá el de obtener el archivo wheel, otra suposición que se hará es que se ha descargado de la página web de DISNET y por tanto se encuentra en la carpeta de descargas (Download) en el directorio home (~)
A continuación se deberá abrir un terminal y activar el environment supuesto anteriormente. En esta suposición el environment se llamará ejemplo (como ya se ha comentado en este supuesto se utiliza anaconda pero el proceso sería similar para otros gestores de envs). Para activarlo se utilizará el siguiente comando en el terminal:
`$ conda activate ejemplo`
Posteriormente se deberá mover el terminal a la carpeta donde se encuentra el archivo wheel, en este caso como ya se ha mencionado estará en la ruta "~/Downloads/", y para proceder a ese directorio se utiliza:
`(ejemplo)$ cd ~/Downloads/`
Por último para poder instalar el paquete wheel en el env se utilizará el comando pip install nombredelarchivo.whl, que en este supuesto será:
`(ejemplo)$ pip install DISNET-0.1-py3-none-any.whl`
Una vez realizados estos pasos se tendrá la librería instalada (junto con la librería requests ya que fue indicado en el setup.py como requisito) en el environment
Podemos desactivar el env seleccionado con:
`$ conda deactivate ejemplo`
<h2> Uso y ejemplos </h2>
Una vez instalado correctamente el archivo wheel se puede proceder a importarlo en el proyecto deseado. Para esto el IDE en el cual se está trabajando se debe haber configurado correctamente el environment utilizado anteriormente, el cual contiene el paquete instalado.
Una vez configurado el IDE y el proyecto ya se podrá importar la librería DISNET. Para realizar importaciones primero se debe saber el servicio que se desea utilizar, en este caso se va a suponer un programa que va hacer uso del servicio ServicePhenotype:
```python
import DISNET.services.ServicePhenotype as ServicePhenotype
```
Se ha importado la clase como ServicePhenotype ya que de esta forma no será necesario escribir la ruta cada vez que se use.
Aparte del servicio también se importan los objetos que se desee manipular. Por ejemplo se supondrá que se desea utilizar DiseaseObject, y para su importación:
```python
import DISNET.objects.DiseaseObject as DiseaseObject
```
Al igual que antes para simplificar su uso se muestra la importación cómo DiseaseObject para evitar repeticiones innecesarias.
Una vez realizados los imports se procede a mostrar el funcionamiento del programa sugerido anteriormente. Este programa consistirá en un método main() que hará una petición a la API para obtener todas las enfermedades. Una vez obtenidas buscará los síntomas asociados a cada una de ellas, mostrando por pantalla dicha información. Para llevar a cabo la tarea descrita se necesitará una instancia del servicio correspondiente (ServicePhenotype) para poder llamar al los métodos requeridos (getAllDiseases() y getSymptomsByDiseaseID()).
```Python
main(self):
servPheno = ServicePhenotype.ServicePhenotype()
listDiseases = servPheno.getAllDiseases()
for disease in listDiseases:
#para cada disease se puede obtener los sintomas
print("para la enferemedad " + disease + " se tienen los siguientes sintomas: ")
print(servPheno.getSymptomsByDiseaseID(disease.getId()))
```
Cuando se trabaja con este tipo de programas se deberá tener en cuenta que pueden existir situaciones en las que una enfermedad no tenga síntomas registrados o que directamente el servidor esté caído y devuelva un error 404. La librería está programada para lanzar en estos casos la excepción NoResultsFound. Será responsabilidad del usuario de la librería cotrolar esta excepción y para ello se puede utilizar un try except de Python de la siguiente manera:
```Python
try:
except NoResultsFoundException:
print("ERROR: La búsqueda no ha generado resultados")
```
from setuptools import setup
setup(name='DISNET',
version='0.1',
description='Aplicación para el acceso a la api de DISNET',
url='',
author='David Navarro Riaño',
author_email='david.navarror@alumnos.upm.es',
license='UPM',
packages=['DISNET','DISNET.metadata','DISNET.objects','DISNET.services','tests'],
install_requires=['requests']
)
import unittest
import DISNET.services.ServicePhenotype as ServicePhenotype
import DISNET.services.ServiceBio as ServiceBio
import DISNET.services.ServicePharma as ServicePharma
import DISNET.Exceptions as Exceptions
import DISNET.services.ServiceMapping as ServiceMapping
class Tests(unittest.TestCase):
def test_ServicePhenotype(self):
S = ServicePhenotype.ServicePhenotype()
sources = S.getSources()
diseases = S.getAllDiseases()
S.getAllSymptoms()
self.assertIn("wikipedia",sources, "wikipedia is part of the set of sources")
source = "wikipedia"
snapshots = S.getSnapshotsBySource(source)
with self.assertRaises(Exceptions.NoResultFoundException):
S.getSnapshotsBySource("NOTASOURCE")
self.assertIn("2021-01-01", snapshots, "2021-01-01 is part of the set of snapshots")
snapshot = "2020-01-01"
diseases = S.getAllDiseases(source, snapshot)
disease = diseases[0]
self.assertEqual(disease.getId(), "DIS010790", "the first disease id is DIS010790")
diseaseList = S.getDiseaseByDiseaseName(disease.getName(), True, source, snapshot)
disease2 = diseaseList[0]
self.assertEqual(disease2, disease)
urls = S.getURLsDisease(disease.getId(), source, snapshot)
url = urls[0]
self.assertEqual("http://en.wikipedia.org/wiki/(von_Zumbusch)_acute_generalized_pustular_psoriasis",url)
symptoms = S.getAllSymptoms(source, snapshot)
symptom = symptoms[0]
self.assertEqual(symptom.getId(), "C0013604", "first symptom is C0700129")
diseaseSymptom = S.getSymptomsByDiseaseID(disease.getId(), source, snapshot)
self.assertIn(diseaseSymptom[0],symptoms,"disease symptom must be in all symptoms")
sympname = S.getSymptomsBySymptomName(diseaseSymptom[0].getName(),True,source,snapshot)
self.assertEqual(diseaseSymptom[0].getId(),sympname[0].getId())
diseases = S.getDiseasesBySymptomCUI(diseaseSymptom[0].getId())
meta = S.getMetaData(source,snapshot)
def test_ServiceBio(self):
S = ServiceBio.ServiceBio()
diseases = S.getAllDiseases()
disease = diseases[0]
pathways = S.getAllPathways()
pathway = pathways[0]
genes = S.getAllGenes()
gene = genes[0]
variants = S.getAllVariants()
variant = variants[0]
proteins = S.getAllProteins()
protein = proteins[0]
ppis = S.getAllPPIS()
diseasebyName = S.getDiseaseByDiseaseName(disease.getName(),True)
self.assertEqual(diseasebyName[0],disease)
diseaseGenes = S.getGenesByDiseaseId(disease.getId())
self.assertIn(diseaseGenes[0], genes)
diseaseVariants = S.getVariantsByDiseaseId("C0001175")
genebyid = S.getGeneByGeneID(gene.getId())
self.assertEqual(gene,genebyid)
diseasesbygene = S.getDiseasesByGeneId(gene.getId())
self.assertIn(diseasesbygene[0],diseases)
proteinsbygene = S.getProteinsByGeneID(gene.getId())
self.assertIn(proteinsbygene[0],proteins)
pathwaybygene = S.getPathwaysByGeneID("1232")
self.assertIn(pathwaybygene[0],pathways)
variantsbygene = S.getVariantsByGeneId(72)
self.assertIn(variantsbygene[0],variants)
variantbyid = S.getVariantByVariantID(variant.getId())
self.assertEqual(variantbyid,variant)
diseasesbyvariant = S.getDiseasesByVariantId(variant.getId())
self.assertIn(diseasesbyvariant[0], diseases)
genesbyvariant = S.getGenesByVariantId(variant.getId())
self.assertIn(genesbyvariant[0],genes)
pathwaybyid = S.getPathwayByPathwayID(pathway.getId())
self.assertEqual(pathway,pathwaybyid)
genesbypathway = S.getGenesByPathwayId(pathway.getId())
self.assertIn(genesbypathway[0],genes)
genesbyprotein = S.getGenesByProteinId(protein.getId())
self.assertIn(genesbyprotein[0],genes)
def test_ServicePharma(self):
S = ServicePharma.ServicePharma()
diseases = S.getAllDiseases()
disease = diseases[0]
phenotypes = S.getAllPhenotypes()
pheno = phenotypes[0]
drugs = S.getAllDrugs()
drug = drugs[0]
targets = S.getAllTargets()
target = targets[0]
diseasebyname = S.getDiseaseByDiseaseName(disease.getName(),True)
self.assertEqual(diseasebyname[0],disease)
diseasebyid = S.getDiseaseByDiseaseID(disease.getId())
self.assertEqual(diseasebyid,disease)
drugsbydisease = S.getDrugsByDiseaseId("C0000786")
self.assertIn(drugsbydisease[0],drugs)
phenobyname = S.getPhenotypeByPhenotypeName(pheno.getName(),True)
self.assertEqual(phenobyname[0],pheno)
phenobyid = S.getPhenotypeByPhenotypeID(pheno.getId())
self.assertEqual(phenobyid,pheno)
drugsbypheno = S.getDrugsByPhenotypeId("C0000731")
self.assertIn(drugsbypheno[0],drugs)
drugsbyname = S.getDrugsByDrugName(drug.getName(),True)
self.assertEqual(drugsbyname[0],drug)
drugbyid = S.getDrugByDrugID(drug.getId())
self.assertEqual(drug,drugbyid)
diseasesbydrug = S.getDiseasesByDrugID("CHEMBL100116")
self.assertIn(diseasesbydrug[0], diseases)
phenosbydrug = S.getPhenotypesByDrugsID("CHEMBL99946")
self.assertIn(phenosbydrug[0], phenotypes)
targetsbydrug = S.getTargetsByDrugID("CHEMBL42")
self.assertIn(targetsbydrug[0],targets)
interactionbydrug = S.getInteractingDrugsByDrugsID("CHEMBL42")
phenobyinteraction = S.getPhenotypesByDDI("CHEMBL42","CHEMBL1213252")
targetbyname = S.getTargetByTargetName(target.getName(),True)
self.assertEqual(targetbyname[0],target)
targetbyid = S.getTargetByTargetID(target.getId())
self.assertEqual(targetbyid,target)
drugsbytarget = S.getDrugsByTargetId("CHEMBL234")
self.assertIn(drugsbytarget[0],drugs)
def test_ServiceMapping(self):
smap = ServiceMapping.ServiceMapping()
disnetIds = smap.getDisnetIdsByCui("C0000737")
disnetIdMap = disnetIds[0]
self.assertEqual(disnetIdMap.getId(),"DIS000005")
cuis = smap.getCuisByDisnetId("DIS000005")
cui = cuis[0]
self.assertEqual(cui.getId(),"C0000737")
if __name__ == '__main__':
unittest.main()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment