From 82c6169323b4bee339d0f0022508f9d2f42af1c3 Mon Sep 17 00:00:00 2001 From: vdancik Date: Fri, 6 Dec 2019 13:51:19 -0500 Subject: [PATCH 1/4] Update gene_transformer_api.yml --- gene_transformer_api.yml | 75 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 69 insertions(+), 6 deletions(-) diff --git a/gene_transformer_api.yml b/gene_transformer_api.yml index 5704c62..eb47e19 100644 --- a/gene_transformer_api.yml +++ b/gene_transformer_api.yml @@ -1,10 +1,10 @@ swagger: '2.0' info: - title: API for remove-gene filter - version: 1.2.0 - description: API for remove-gene filter. + title: API for gene-list transformers + version: 1.3.0 + description: API for gene-list transformers. host: sharpener.ncats.io -basePath: /remove_genes_filter +basePath: / schemes: - "https" @@ -39,6 +39,14 @@ paths: type: array items: $ref: '#/definitions/gene_info' + 400: + description: bad request + schema: + $ref: '#/definitions/error_msg' + 500: + description: internal server error + schema: + $ref: '#/definitions/error_msg' definitions: @@ -102,6 +110,9 @@ definitions: Additional information about the gene and provenance about gene-list membership. Sharpener will use myGene.info to add 'gene_symbol', 'synonyms', and 'gene_name' to every gene. Multiple synonyms are separated by semicolons. + source: + type: string + description: Name of a transformer that added gene to the gene list. required: - gene_id @@ -110,13 +121,20 @@ definitions: properties: name: type: string + description: Name of the attribute. value: type: string + description: Value of the attribute. source: type: string + description: Transformer that produced the attribute's value. + url: + type: string + description: URL for additional information. required: - - name - - value + - name + - value + - source property: type: object @@ -135,6 +153,12 @@ definitions: name: type: string description: Name of the transformer. + label: + type: string + description: Short label for GUI display. + version: + type: string + description: Transformer's version. function: type: string description: Function of the transformer, one of 'producer', 'expander', 'filter'. @@ -142,6 +166,22 @@ definitions: description: type: string description: Description of the transformer. + properties: + type: object + description: Additional metadata for the transformer. + properties: + list_predicate: + type: string + description: BioLink-model predicate describing relationship between input and output gene lists. + member_predicate: + type: string + description: BioLink-model predicate describing relationship between input and output genes. + source_url: + type: string + description: URL for underlying data or a wrapped service. + method: + type: string + description: A method used to generate output gene lists. parameters: type: array items: @@ -174,11 +214,23 @@ definitions: default: type: string description: Default value of the parameter. + biolink_class: + type: string + description: >- + Biolink class of the paramater. Applicable to producers only and only one parameter + can have a biolink class. allowed_values: type: array items: type: string description: Allowed values for the parameter. + allowed_range: + type: array + items: + type: number + description: Allowed range for values of the parameter. + minItems: 2 + maxItems: 2 suggested_values: type: string description: Suggested value range for the parameter. @@ -190,3 +242,14 @@ definitions: - type - default + error_msg: + type: object + properties: + status: + type: integer + title: + type: string + detail: + type: string + type: + type: string From 9ecb1d8dae338bb2d6d715c10788dd11a43b17e1 Mon Sep 17 00:00:00 2001 From: vdancik Date: Fri, 6 Dec 2019 14:12:42 -0500 Subject: [PATCH 2/4] autogenerate python flask server --- .gitignore | 38 ++ gene_transformer_api.yml | 6 +- python-flask-server/.dockerignore | 72 ++++ python-flask-server/.gitignore | 64 ++++ python-flask-server/.swagger-codegen-ignore | 23 ++ python-flask-server/.swagger-codegen/VERSION | 1 + python-flask-server/.travis.yml | 13 + python-flask-server/Dockerfile | 16 + python-flask-server/README.md | 49 +++ python-flask-server/git_push.sh | 52 +++ python-flask-server/requirements.txt | 3 + python-flask-server/setup.py | 35 ++ .../swagger_server/__init__.py | 0 .../swagger_server/__main__.py | 16 + .../swagger_server/controllers/__init__.py | 0 .../controllers/transformer_controller.py | 34 ++ python-flask-server/swagger_server/encoder.py | 20 + .../swagger_server/models/__init__.py | 14 + .../swagger_server/models/attribute.py | 156 ++++++++ .../swagger_server/models/base_model_.py | 69 ++++ .../swagger_server/models/error_msg.py | 142 +++++++ .../swagger_server/models/gene_info.py | 152 ++++++++ .../models/gene_info_identifiers.py | 178 +++++++++ .../swagger_server/models/model_property.py | 94 +++++ .../swagger_server/models/parameter.py | 272 ++++++++++++++ .../swagger_server/models/transformer_info.py | 276 ++++++++++++++ .../models/transformer_info_properties.py | 150 ++++++++ .../models/transformer_query.py | 98 +++++ .../swagger_server/swagger/swagger.yaml | 350 ++++++++++++++++++ .../swagger_server/test/__init__.py | 16 + .../test/test_transformer_controller.py | 46 +++ python-flask-server/swagger_server/util.py | 141 +++++++ python-flask-server/test-requirements.txt | 6 + python-flask-server/tox.ini | 10 + 34 files changed, 2609 insertions(+), 3 deletions(-) create mode 100644 python-flask-server/.dockerignore create mode 100644 python-flask-server/.gitignore create mode 100644 python-flask-server/.swagger-codegen-ignore create mode 100644 python-flask-server/.swagger-codegen/VERSION create mode 100644 python-flask-server/.travis.yml create mode 100644 python-flask-server/Dockerfile create mode 100644 python-flask-server/README.md create mode 100644 python-flask-server/git_push.sh create mode 100644 python-flask-server/requirements.txt create mode 100644 python-flask-server/setup.py create mode 100644 python-flask-server/swagger_server/__init__.py create mode 100644 python-flask-server/swagger_server/__main__.py create mode 100644 python-flask-server/swagger_server/controllers/__init__.py create mode 100644 python-flask-server/swagger_server/controllers/transformer_controller.py create mode 100644 python-flask-server/swagger_server/encoder.py create mode 100644 python-flask-server/swagger_server/models/__init__.py create mode 100644 python-flask-server/swagger_server/models/attribute.py create mode 100644 python-flask-server/swagger_server/models/base_model_.py create mode 100644 python-flask-server/swagger_server/models/error_msg.py create mode 100644 python-flask-server/swagger_server/models/gene_info.py create mode 100644 python-flask-server/swagger_server/models/gene_info_identifiers.py create mode 100644 python-flask-server/swagger_server/models/model_property.py create mode 100644 python-flask-server/swagger_server/models/parameter.py create mode 100644 python-flask-server/swagger_server/models/transformer_info.py create mode 100644 python-flask-server/swagger_server/models/transformer_info_properties.py create mode 100644 python-flask-server/swagger_server/models/transformer_query.py create mode 100644 python-flask-server/swagger_server/swagger/swagger.yaml create mode 100644 python-flask-server/swagger_server/test/__init__.py create mode 100644 python-flask-server/swagger_server/test/test_transformer_controller.py create mode 100644 python-flask-server/swagger_server/util.py create mode 100644 python-flask-server/test-requirements.txt create mode 100644 python-flask-server/tox.ini diff --git a/.gitignore b/.gitignore index a1c2a23..af93335 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,41 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* + +#sbt-produced files +java-play-framework-server/target/ +java-play-framework-server/project/target/ +java-play-framework-server/project/project/target/ + +#eclipse-related files +java-play-framework-server/bin/ +java-play-framework-server/.settings +java-play-framework-server/.project +java-play-framework-server/.classpath +java-play-framework-server/.cache-main + +#python-related files +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST +venv/ \ No newline at end of file diff --git a/gene_transformer_api.yml b/gene_transformer_api.yml index eb47e19..b4e5b9a 100644 --- a/gene_transformer_api.yml +++ b/gene_transformer_api.yml @@ -1,10 +1,10 @@ swagger: '2.0' info: - title: API for gene-list transformers + title: BigGIM gene-expression correlation version: 1.3.0 - description: API for gene-list transformers. + description: Gene-list expander based on gene-expression correlation using BigGIM (http://biggim.ncats.io/api/). host: sharpener.ncats.io -basePath: / +basePath: /expression_correlation schemes: - "https" diff --git a/python-flask-server/.dockerignore b/python-flask-server/.dockerignore new file mode 100644 index 0000000..cdd823e --- /dev/null +++ b/python-flask-server/.dockerignore @@ -0,0 +1,72 @@ +.travis.yaml +.swagger-codegen-ignore +README.md +tox.ini +git_push.sh +test-requirements.txt +setup.py + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ +venv/ +.python-version + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints diff --git a/python-flask-server/.gitignore b/python-flask-server/.gitignore new file mode 100644 index 0000000..a655050 --- /dev/null +++ b/python-flask-server/.gitignore @@ -0,0 +1,64 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ +venv/ +.python-version + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints diff --git a/python-flask-server/.swagger-codegen-ignore b/python-flask-server/.swagger-codegen-ignore new file mode 100644 index 0000000..c5fa491 --- /dev/null +++ b/python-flask-server/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/python-flask-server/.swagger-codegen/VERSION b/python-flask-server/.swagger-codegen/VERSION new file mode 100644 index 0000000..752a79e --- /dev/null +++ b/python-flask-server/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.4.8 \ No newline at end of file diff --git a/python-flask-server/.travis.yml b/python-flask-server/.travis.yml new file mode 100644 index 0000000..dd6c445 --- /dev/null +++ b/python-flask-server/.travis.yml @@ -0,0 +1,13 @@ +# ref: https://docs.travis-ci.com/user/languages/python +language: python +python: + - "3.2" + - "3.3" + - "3.4" + - "3.5" + #- "3.5-dev" # 3.5 development branch + #- "nightly" # points to the latest development branch e.g. 3.6-dev +# command to install dependencies +install: "pip install -r requirements.txt" +# command to run tests +script: nosetests diff --git a/python-flask-server/Dockerfile b/python-flask-server/Dockerfile new file mode 100644 index 0000000..eb5704f --- /dev/null +++ b/python-flask-server/Dockerfile @@ -0,0 +1,16 @@ +FROM python:3-alpine + +RUN mkdir -p /usr/src/app +WORKDIR /usr/src/app + +COPY requirements.txt /usr/src/app/ + +RUN pip3 install --no-cache-dir -r requirements.txt + +COPY . /usr/src/app + +EXPOSE 8080 + +ENTRYPOINT ["python3"] + +CMD ["-m", "swagger_server"] \ No newline at end of file diff --git a/python-flask-server/README.md b/python-flask-server/README.md new file mode 100644 index 0000000..088cf30 --- /dev/null +++ b/python-flask-server/README.md @@ -0,0 +1,49 @@ +# Swagger generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a swagger-enabled Flask server. + +This example uses the [Connexion](https://github.com/zalando/connexion) library on top of Flask. + +## Requirements +Python 3.5.2+ + +## Usage +To run the server, please execute the following from the root directory: + +``` +pip3 install -r requirements.txt +python3 -m swagger_server +``` + +and open your browser to here: + +``` +http://localhost:8080/expression_correlation/ui/ +``` + +Your Swagger definition lives here: + +``` +http://localhost:8080/expression_correlation/swagger.json +``` + +To launch the integration tests, use tox: +``` +sudo pip install tox +tox +``` + +## Running with Docker + +To run the server on a Docker container, please execute the following from the root directory: + +```bash +# building the image +docker build -t swagger_server . + +# starting up a container +docker run -p 8080:8080 swagger_server +``` \ No newline at end of file diff --git a/python-flask-server/git_push.sh b/python-flask-server/git_push.sh new file mode 100644 index 0000000..160f6f2 --- /dev/null +++ b/python-flask-server/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/python-flask-server/requirements.txt b/python-flask-server/requirements.txt new file mode 100644 index 0000000..1cf2462 --- /dev/null +++ b/python-flask-server/requirements.txt @@ -0,0 +1,3 @@ +connexion == 1.1.15 +python_dateutil == 2.6.0 +setuptools >= 21.0.0 diff --git a/python-flask-server/setup.py b/python-flask-server/setup.py new file mode 100644 index 0000000..d3c88c0 --- /dev/null +++ b/python-flask-server/setup.py @@ -0,0 +1,35 @@ +# coding: utf-8 + +import sys +from setuptools import setup, find_packages + +NAME = "swagger_server" +VERSION = "1.0.0" + +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools + +REQUIRES = ["connexion"] + +setup( + name=NAME, + version=VERSION, + description="BigGIM gene-expression correlation", + author_email="", + url="", + keywords=["Swagger", "BigGIM gene-expression correlation"], + install_requires=REQUIRES, + packages=find_packages(), + package_data={'': ['swagger/swagger.yaml']}, + include_package_data=True, + entry_points={ + 'console_scripts': ['swagger_server=swagger_server.__main__:main']}, + long_description="""\ + Gene-list expander based on gene-expression correlation using BigGIM (http://biggim.ncats.io/api/). + """ +) + diff --git a/python-flask-server/swagger_server/__init__.py b/python-flask-server/swagger_server/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/python-flask-server/swagger_server/__main__.py b/python-flask-server/swagger_server/__main__.py new file mode 100644 index 0000000..7093c81 --- /dev/null +++ b/python-flask-server/swagger_server/__main__.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python3 + +import connexion + +from swagger_server import encoder + + +def main(): + app = connexion.App(__name__, specification_dir='./swagger/') + app.app.json_encoder = encoder.JSONEncoder + app.add_api('swagger.yaml', arguments={'title': 'BigGIM gene-expression correlation'}) + app.run(port=8080) + + +if __name__ == '__main__': + main() diff --git a/python-flask-server/swagger_server/controllers/__init__.py b/python-flask-server/swagger_server/controllers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/python-flask-server/swagger_server/controllers/transformer_controller.py b/python-flask-server/swagger_server/controllers/transformer_controller.py new file mode 100644 index 0000000..c6ca2c0 --- /dev/null +++ b/python-flask-server/swagger_server/controllers/transformer_controller.py @@ -0,0 +1,34 @@ +import connexion +import six + +from swagger_server.models.error_msg import ErrorMsg # noqa: E501 +from swagger_server.models.gene_info import GeneInfo # noqa: E501 +from swagger_server.models.transformer_info import TransformerInfo # noqa: E501 +from swagger_server.models.transformer_query import TransformerQuery # noqa: E501 +from swagger_server import util + + +def transform_post(query): # noqa: E501 + """transform_post + + # noqa: E501 + + :param query: Performs transformer query. + :type query: dict | bytes + + :rtype: List[GeneInfo] + """ + if connexion.request.is_json: + query = TransformerQuery.from_dict(connexion.request.get_json()) # noqa: E501 + return 'do some magic!' + + +def transformer_info_get(): # noqa: E501 + """Retrieve transformer info + + Provides information about the transformer. # noqa: E501 + + + :rtype: TransformerInfo + """ + return 'do some magic!' diff --git a/python-flask-server/swagger_server/encoder.py b/python-flask-server/swagger_server/encoder.py new file mode 100644 index 0000000..61ba472 --- /dev/null +++ b/python-flask-server/swagger_server/encoder.py @@ -0,0 +1,20 @@ +from connexion.apps.flask_app import FlaskJSONEncoder +import six + +from swagger_server.models.base_model_ import Model + + +class JSONEncoder(FlaskJSONEncoder): + include_nulls = False + + def default(self, o): + if isinstance(o, Model): + dikt = {} + for attr, _ in six.iteritems(o.swagger_types): + value = getattr(o, attr) + if value is None and not self.include_nulls: + continue + attr = o.attribute_map[attr] + dikt[attr] = value + return dikt + return FlaskJSONEncoder.default(self, o) diff --git a/python-flask-server/swagger_server/models/__init__.py b/python-flask-server/swagger_server/models/__init__.py new file mode 100644 index 0000000..8aba92a --- /dev/null +++ b/python-flask-server/swagger_server/models/__init__.py @@ -0,0 +1,14 @@ +# coding: utf-8 + +# flake8: noqa +from __future__ import absolute_import +# import models into model package +from swagger_server.models.attribute import Attribute +from swagger_server.models.error_msg import ErrorMsg +from swagger_server.models.gene_info import GeneInfo +from swagger_server.models.gene_info_identifiers import GeneInfoIdentifiers +from swagger_server.models.model_property import ModelProperty +from swagger_server.models.parameter import Parameter +from swagger_server.models.transformer_info import TransformerInfo +from swagger_server.models.transformer_info_properties import TransformerInfoProperties +from swagger_server.models.transformer_query import TransformerQuery diff --git a/python-flask-server/swagger_server/models/attribute.py b/python-flask-server/swagger_server/models/attribute.py new file mode 100644 index 0000000..206ee99 --- /dev/null +++ b/python-flask-server/swagger_server/models/attribute.py @@ -0,0 +1,156 @@ +# coding: utf-8 + +from __future__ import absolute_import +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server import util + + +class Attribute(Model): + """NOTE: This class is auto generated by the swagger code generator program. + + Do not edit the class manually. + """ + + def __init__(self, name: str=None, value: str=None, source: str=None, url: str=None): # noqa: E501 + """Attribute - a model defined in Swagger + + :param name: The name of this Attribute. # noqa: E501 + :type name: str + :param value: The value of this Attribute. # noqa: E501 + :type value: str + :param source: The source of this Attribute. # noqa: E501 + :type source: str + :param url: The url of this Attribute. # noqa: E501 + :type url: str + """ + self.swagger_types = { + 'name': str, + 'value': str, + 'source': str, + 'url': str + } + + self.attribute_map = { + 'name': 'name', + 'value': 'value', + 'source': 'source', + 'url': 'url' + } + + self._name = name + self._value = value + self._source = source + self._url = url + + @classmethod + def from_dict(cls, dikt) -> 'Attribute': + """Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The attribute of this Attribute. # noqa: E501 + :rtype: Attribute + """ + return util.deserialize_model(dikt, cls) + + @property + def name(self) -> str: + """Gets the name of this Attribute. + + Name of the attribute. # noqa: E501 + + :return: The name of this Attribute. + :rtype: str + """ + return self._name + + @name.setter + def name(self, name: str): + """Sets the name of this Attribute. + + Name of the attribute. # noqa: E501 + + :param name: The name of this Attribute. + :type name: str + """ + if name is None: + raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 + + self._name = name + + @property + def value(self) -> str: + """Gets the value of this Attribute. + + Value of the attribute. # noqa: E501 + + :return: The value of this Attribute. + :rtype: str + """ + return self._value + + @value.setter + def value(self, value: str): + """Sets the value of this Attribute. + + Value of the attribute. # noqa: E501 + + :param value: The value of this Attribute. + :type value: str + """ + if value is None: + raise ValueError("Invalid value for `value`, must not be `None`") # noqa: E501 + + self._value = value + + @property + def source(self) -> str: + """Gets the source of this Attribute. + + Transformer that produced the attribute's value. # noqa: E501 + + :return: The source of this Attribute. + :rtype: str + """ + return self._source + + @source.setter + def source(self, source: str): + """Sets the source of this Attribute. + + Transformer that produced the attribute's value. # noqa: E501 + + :param source: The source of this Attribute. + :type source: str + """ + if source is None: + raise ValueError("Invalid value for `source`, must not be `None`") # noqa: E501 + + self._source = source + + @property + def url(self) -> str: + """Gets the url of this Attribute. + + URL for additional information. # noqa: E501 + + :return: The url of this Attribute. + :rtype: str + """ + return self._url + + @url.setter + def url(self, url: str): + """Sets the url of this Attribute. + + URL for additional information. # noqa: E501 + + :param url: The url of this Attribute. + :type url: str + """ + + self._url = url diff --git a/python-flask-server/swagger_server/models/base_model_.py b/python-flask-server/swagger_server/models/base_model_.py new file mode 100644 index 0000000..97999c3 --- /dev/null +++ b/python-flask-server/swagger_server/models/base_model_.py @@ -0,0 +1,69 @@ +import pprint + +import six +import typing + +from swagger_server import util + +T = typing.TypeVar('T') + + +class Model(object): + # swaggerTypes: The key is attribute name and the + # value is attribute type. + swagger_types = {} + + # attributeMap: The key is attribute name and the + # value is json key in definition. + attribute_map = {} + + @classmethod + def from_dict(cls: typing.Type[T], dikt) -> T: + """Returns the dict as a model""" + return util.deserialize_model(dikt, cls) + + def to_dict(self): + """Returns the model properties as a dict + + :rtype: dict + """ + result = {} + + for attr, _ in six.iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model + + :rtype: str + """ + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-flask-server/swagger_server/models/error_msg.py b/python-flask-server/swagger_server/models/error_msg.py new file mode 100644 index 0000000..b9ffc60 --- /dev/null +++ b/python-flask-server/swagger_server/models/error_msg.py @@ -0,0 +1,142 @@ +# coding: utf-8 + +from __future__ import absolute_import +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server import util + + +class ErrorMsg(Model): + """NOTE: This class is auto generated by the swagger code generator program. + + Do not edit the class manually. + """ + + def __init__(self, status: int=None, title: str=None, detail: str=None, type: str=None): # noqa: E501 + """ErrorMsg - a model defined in Swagger + + :param status: The status of this ErrorMsg. # noqa: E501 + :type status: int + :param title: The title of this ErrorMsg. # noqa: E501 + :type title: str + :param detail: The detail of this ErrorMsg. # noqa: E501 + :type detail: str + :param type: The type of this ErrorMsg. # noqa: E501 + :type type: str + """ + self.swagger_types = { + 'status': int, + 'title': str, + 'detail': str, + 'type': str + } + + self.attribute_map = { + 'status': 'status', + 'title': 'title', + 'detail': 'detail', + 'type': 'type' + } + + self._status = status + self._title = title + self._detail = detail + self._type = type + + @classmethod + def from_dict(cls, dikt) -> 'ErrorMsg': + """Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The error_msg of this ErrorMsg. # noqa: E501 + :rtype: ErrorMsg + """ + return util.deserialize_model(dikt, cls) + + @property + def status(self) -> int: + """Gets the status of this ErrorMsg. + + + :return: The status of this ErrorMsg. + :rtype: int + """ + return self._status + + @status.setter + def status(self, status: int): + """Sets the status of this ErrorMsg. + + + :param status: The status of this ErrorMsg. + :type status: int + """ + + self._status = status + + @property + def title(self) -> str: + """Gets the title of this ErrorMsg. + + + :return: The title of this ErrorMsg. + :rtype: str + """ + return self._title + + @title.setter + def title(self, title: str): + """Sets the title of this ErrorMsg. + + + :param title: The title of this ErrorMsg. + :type title: str + """ + + self._title = title + + @property + def detail(self) -> str: + """Gets the detail of this ErrorMsg. + + + :return: The detail of this ErrorMsg. + :rtype: str + """ + return self._detail + + @detail.setter + def detail(self, detail: str): + """Sets the detail of this ErrorMsg. + + + :param detail: The detail of this ErrorMsg. + :type detail: str + """ + + self._detail = detail + + @property + def type(self) -> str: + """Gets the type of this ErrorMsg. + + + :return: The type of this ErrorMsg. + :rtype: str + """ + return self._type + + @type.setter + def type(self, type: str): + """Sets the type of this ErrorMsg. + + + :param type: The type of this ErrorMsg. + :type type: str + """ + + self._type = type diff --git a/python-flask-server/swagger_server/models/gene_info.py b/python-flask-server/swagger_server/models/gene_info.py new file mode 100644 index 0000000..fe3ba9d --- /dev/null +++ b/python-flask-server/swagger_server/models/gene_info.py @@ -0,0 +1,152 @@ +# coding: utf-8 + +from __future__ import absolute_import +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server.models.attribute import Attribute # noqa: F401,E501 +from swagger_server.models.gene_info_identifiers import GeneInfoIdentifiers # noqa: F401,E501 +from swagger_server import util + + +class GeneInfo(Model): + """NOTE: This class is auto generated by the swagger code generator program. + + Do not edit the class manually. + """ + + def __init__(self, gene_id: str=None, identifiers: GeneInfoIdentifiers=None, attributes: List[Attribute]=None, source: str=None): # noqa: E501 + """GeneInfo - a model defined in Swagger + + :param gene_id: The gene_id of this GeneInfo. # noqa: E501 + :type gene_id: str + :param identifiers: The identifiers of this GeneInfo. # noqa: E501 + :type identifiers: GeneInfoIdentifiers + :param attributes: The attributes of this GeneInfo. # noqa: E501 + :type attributes: List[Attribute] + :param source: The source of this GeneInfo. # noqa: E501 + :type source: str + """ + self.swagger_types = { + 'gene_id': str, + 'identifiers': GeneInfoIdentifiers, + 'attributes': List[Attribute], + 'source': str + } + + self.attribute_map = { + 'gene_id': 'gene_id', + 'identifiers': 'identifiers', + 'attributes': 'attributes', + 'source': 'source' + } + + self._gene_id = gene_id + self._identifiers = identifiers + self._attributes = attributes + self._source = source + + @classmethod + def from_dict(cls, dikt) -> 'GeneInfo': + """Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The gene_info of this GeneInfo. # noqa: E501 + :rtype: GeneInfo + """ + return util.deserialize_model(dikt, cls) + + @property + def gene_id(self) -> str: + """Gets the gene_id of this GeneInfo. + + Id of the gene. # noqa: E501 + + :return: The gene_id of this GeneInfo. + :rtype: str + """ + return self._gene_id + + @gene_id.setter + def gene_id(self, gene_id: str): + """Sets the gene_id of this GeneInfo. + + Id of the gene. # noqa: E501 + + :param gene_id: The gene_id of this GeneInfo. + :type gene_id: str + """ + if gene_id is None: + raise ValueError("Invalid value for `gene_id`, must not be `None`") # noqa: E501 + + self._gene_id = gene_id + + @property + def identifiers(self) -> GeneInfoIdentifiers: + """Gets the identifiers of this GeneInfo. + + + :return: The identifiers of this GeneInfo. + :rtype: GeneInfoIdentifiers + """ + return self._identifiers + + @identifiers.setter + def identifiers(self, identifiers: GeneInfoIdentifiers): + """Sets the identifiers of this GeneInfo. + + + :param identifiers: The identifiers of this GeneInfo. + :type identifiers: GeneInfoIdentifiers + """ + + self._identifiers = identifiers + + @property + def attributes(self) -> List[Attribute]: + """Gets the attributes of this GeneInfo. + + Additional information about the gene and provenance about gene-list membership. Sharpener will use myGene.info to add 'gene_symbol', 'synonyms', and 'gene_name' to every gene. Multiple synonyms are separated by semicolons. # noqa: E501 + + :return: The attributes of this GeneInfo. + :rtype: List[Attribute] + """ + return self._attributes + + @attributes.setter + def attributes(self, attributes: List[Attribute]): + """Sets the attributes of this GeneInfo. + + Additional information about the gene and provenance about gene-list membership. Sharpener will use myGene.info to add 'gene_symbol', 'synonyms', and 'gene_name' to every gene. Multiple synonyms are separated by semicolons. # noqa: E501 + + :param attributes: The attributes of this GeneInfo. + :type attributes: List[Attribute] + """ + + self._attributes = attributes + + @property + def source(self) -> str: + """Gets the source of this GeneInfo. + + Name of a transformer that added gene to the gene list. # noqa: E501 + + :return: The source of this GeneInfo. + :rtype: str + """ + return self._source + + @source.setter + def source(self, source: str): + """Sets the source of this GeneInfo. + + Name of a transformer that added gene to the gene list. # noqa: E501 + + :param source: The source of this GeneInfo. + :type source: str + """ + + self._source = source diff --git a/python-flask-server/swagger_server/models/gene_info_identifiers.py b/python-flask-server/swagger_server/models/gene_info_identifiers.py new file mode 100644 index 0000000..bd629af --- /dev/null +++ b/python-flask-server/swagger_server/models/gene_info_identifiers.py @@ -0,0 +1,178 @@ +# coding: utf-8 + +from __future__ import absolute_import +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server import util + + +class GeneInfoIdentifiers(Model): + """NOTE: This class is auto generated by the swagger code generator program. + + Do not edit the class manually. + """ + + def __init__(self, entrez: str=None, hgnc: str=None, mim: str=None, ensembl: List[str]=None, mygene_info: str=None): # noqa: E501 + """GeneInfoIdentifiers - a model defined in Swagger + + :param entrez: The entrez of this GeneInfoIdentifiers. # noqa: E501 + :type entrez: str + :param hgnc: The hgnc of this GeneInfoIdentifiers. # noqa: E501 + :type hgnc: str + :param mim: The mim of this GeneInfoIdentifiers. # noqa: E501 + :type mim: str + :param ensembl: The ensembl of this GeneInfoIdentifiers. # noqa: E501 + :type ensembl: List[str] + :param mygene_info: The mygene_info of this GeneInfoIdentifiers. # noqa: E501 + :type mygene_info: str + """ + self.swagger_types = { + 'entrez': str, + 'hgnc': str, + 'mim': str, + 'ensembl': List[str], + 'mygene_info': str + } + + self.attribute_map = { + 'entrez': 'entrez', + 'hgnc': 'hgnc', + 'mim': 'mim', + 'ensembl': 'ensembl', + 'mygene_info': 'mygene_info' + } + + self._entrez = entrez + self._hgnc = hgnc + self._mim = mim + self._ensembl = ensembl + self._mygene_info = mygene_info + + @classmethod + def from_dict(cls, dikt) -> 'GeneInfoIdentifiers': + """Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The gene_info_identifiers of this GeneInfoIdentifiers. # noqa: E501 + :rtype: GeneInfoIdentifiers + """ + return util.deserialize_model(dikt, cls) + + @property + def entrez(self) -> str: + """Gets the entrez of this GeneInfoIdentifiers. + + Entrez gene id (CURIE). # noqa: E501 + + :return: The entrez of this GeneInfoIdentifiers. + :rtype: str + """ + return self._entrez + + @entrez.setter + def entrez(self, entrez: str): + """Sets the entrez of this GeneInfoIdentifiers. + + Entrez gene id (CURIE). # noqa: E501 + + :param entrez: The entrez of this GeneInfoIdentifiers. + :type entrez: str + """ + + self._entrez = entrez + + @property + def hgnc(self) -> str: + """Gets the hgnc of this GeneInfoIdentifiers. + + HGNC gene id (CURIE). # noqa: E501 + + :return: The hgnc of this GeneInfoIdentifiers. + :rtype: str + """ + return self._hgnc + + @hgnc.setter + def hgnc(self, hgnc: str): + """Sets the hgnc of this GeneInfoIdentifiers. + + HGNC gene id (CURIE). # noqa: E501 + + :param hgnc: The hgnc of this GeneInfoIdentifiers. + :type hgnc: str + """ + + self._hgnc = hgnc + + @property + def mim(self) -> str: + """Gets the mim of this GeneInfoIdentifiers. + + OMIM gene id (CURIE). # noqa: E501 + + :return: The mim of this GeneInfoIdentifiers. + :rtype: str + """ + return self._mim + + @mim.setter + def mim(self, mim: str): + """Sets the mim of this GeneInfoIdentifiers. + + OMIM gene id (CURIE). # noqa: E501 + + :param mim: The mim of this GeneInfoIdentifiers. + :type mim: str + """ + + self._mim = mim + + @property + def ensembl(self) -> List[str]: + """Gets the ensembl of this GeneInfoIdentifiers. + + ENSEMBL gene id (CURIE). # noqa: E501 + + :return: The ensembl of this GeneInfoIdentifiers. + :rtype: List[str] + """ + return self._ensembl + + @ensembl.setter + def ensembl(self, ensembl: List[str]): + """Sets the ensembl of this GeneInfoIdentifiers. + + ENSEMBL gene id (CURIE). # noqa: E501 + + :param ensembl: The ensembl of this GeneInfoIdentifiers. + :type ensembl: List[str] + """ + + self._ensembl = ensembl + + @property + def mygene_info(self) -> str: + """Gets the mygene_info of this GeneInfoIdentifiers. + + myGene.info primary id. # noqa: E501 + + :return: The mygene_info of this GeneInfoIdentifiers. + :rtype: str + """ + return self._mygene_info + + @mygene_info.setter + def mygene_info(self, mygene_info: str): + """Sets the mygene_info of this GeneInfoIdentifiers. + + myGene.info primary id. # noqa: E501 + + :param mygene_info: The mygene_info of this GeneInfoIdentifiers. + :type mygene_info: str + """ + + self._mygene_info = mygene_info diff --git a/python-flask-server/swagger_server/models/model_property.py b/python-flask-server/swagger_server/models/model_property.py new file mode 100644 index 0000000..ef84c45 --- /dev/null +++ b/python-flask-server/swagger_server/models/model_property.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +from __future__ import absolute_import +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server import util + + +class ModelProperty(Model): + """NOTE: This class is auto generated by the swagger code generator program. + + Do not edit the class manually. + """ + + def __init__(self, name: str=None, value: str=None): # noqa: E501 + """ModelProperty - a model defined in Swagger + + :param name: The name of this ModelProperty. # noqa: E501 + :type name: str + :param value: The value of this ModelProperty. # noqa: E501 + :type value: str + """ + self.swagger_types = { + 'name': str, + 'value': str + } + + self.attribute_map = { + 'name': 'name', + 'value': 'value' + } + + self._name = name + self._value = value + + @classmethod + def from_dict(cls, dikt) -> 'ModelProperty': + """Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The _property of this ModelProperty. # noqa: E501 + :rtype: ModelProperty + """ + return util.deserialize_model(dikt, cls) + + @property + def name(self) -> str: + """Gets the name of this ModelProperty. + + + :return: The name of this ModelProperty. + :rtype: str + """ + return self._name + + @name.setter + def name(self, name: str): + """Sets the name of this ModelProperty. + + + :param name: The name of this ModelProperty. + :type name: str + """ + if name is None: + raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 + + self._name = name + + @property + def value(self) -> str: + """Gets the value of this ModelProperty. + + + :return: The value of this ModelProperty. + :rtype: str + """ + return self._value + + @value.setter + def value(self, value: str): + """Sets the value of this ModelProperty. + + + :param value: The value of this ModelProperty. + :type value: str + """ + if value is None: + raise ValueError("Invalid value for `value`, must not be `None`") # noqa: E501 + + self._value = value diff --git a/python-flask-server/swagger_server/models/parameter.py b/python-flask-server/swagger_server/models/parameter.py new file mode 100644 index 0000000..3f3f3fb --- /dev/null +++ b/python-flask-server/swagger_server/models/parameter.py @@ -0,0 +1,272 @@ +# coding: utf-8 + +from __future__ import absolute_import +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server import util + + +class Parameter(Model): + """NOTE: This class is auto generated by the swagger code generator program. + + Do not edit the class manually. + """ + + def __init__(self, name: str=None, type: str=None, default: str=None, biolink_class: str=None, allowed_values: List[str]=None, allowed_range: List[float]=None, suggested_values: str=None, lookup_url: str=None): # noqa: E501 + """Parameter - a model defined in Swagger + + :param name: The name of this Parameter. # noqa: E501 + :type name: str + :param type: The type of this Parameter. # noqa: E501 + :type type: str + :param default: The default of this Parameter. # noqa: E501 + :type default: str + :param biolink_class: The biolink_class of this Parameter. # noqa: E501 + :type biolink_class: str + :param allowed_values: The allowed_values of this Parameter. # noqa: E501 + :type allowed_values: List[str] + :param allowed_range: The allowed_range of this Parameter. # noqa: E501 + :type allowed_range: List[float] + :param suggested_values: The suggested_values of this Parameter. # noqa: E501 + :type suggested_values: str + :param lookup_url: The lookup_url of this Parameter. # noqa: E501 + :type lookup_url: str + """ + self.swagger_types = { + 'name': str, + 'type': str, + 'default': str, + 'biolink_class': str, + 'allowed_values': List[str], + 'allowed_range': List[float], + 'suggested_values': str, + 'lookup_url': str + } + + self.attribute_map = { + 'name': 'name', + 'type': 'type', + 'default': 'default', + 'biolink_class': 'biolink_class', + 'allowed_values': 'allowed_values', + 'allowed_range': 'allowed_range', + 'suggested_values': 'suggested_values', + 'lookup_url': 'lookup_url' + } + + self._name = name + self._type = type + self._default = default + self._biolink_class = biolink_class + self._allowed_values = allowed_values + self._allowed_range = allowed_range + self._suggested_values = suggested_values + self._lookup_url = lookup_url + + @classmethod + def from_dict(cls, dikt) -> 'Parameter': + """Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The parameter of this Parameter. # noqa: E501 + :rtype: Parameter + """ + return util.deserialize_model(dikt, cls) + + @property + def name(self) -> str: + """Gets the name of this Parameter. + + Name of the parameter. # noqa: E501 + + :return: The name of this Parameter. + :rtype: str + """ + return self._name + + @name.setter + def name(self, name: str): + """Sets the name of this Parameter. + + Name of the parameter. # noqa: E501 + + :param name: The name of this Parameter. + :type name: str + """ + if name is None: + raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 + + self._name = name + + @property + def type(self) -> str: + """Gets the type of this Parameter. + + Type of the parameter, one of 'Boolean', 'int', 'double', 'string'. # noqa: E501 + + :return: The type of this Parameter. + :rtype: str + """ + return self._type + + @type.setter + def type(self, type: str): + """Sets the type of this Parameter. + + Type of the parameter, one of 'Boolean', 'int', 'double', 'string'. # noqa: E501 + + :param type: The type of this Parameter. + :type type: str + """ + allowed_values = ["Boolean", "int", "double", "string"] # noqa: E501 + if type not in allowed_values: + raise ValueError( + "Invalid value for `type` ({0}), must be one of {1}" + .format(type, allowed_values) + ) + + self._type = type + + @property + def default(self) -> str: + """Gets the default of this Parameter. + + Default value of the parameter. # noqa: E501 + + :return: The default of this Parameter. + :rtype: str + """ + return self._default + + @default.setter + def default(self, default: str): + """Sets the default of this Parameter. + + Default value of the parameter. # noqa: E501 + + :param default: The default of this Parameter. + :type default: str + """ + if default is None: + raise ValueError("Invalid value for `default`, must not be `None`") # noqa: E501 + + self._default = default + + @property + def biolink_class(self) -> str: + """Gets the biolink_class of this Parameter. + + Biolink class of the paramater. Applicable to producers only and only one parameter can have a biolink class. # noqa: E501 + + :return: The biolink_class of this Parameter. + :rtype: str + """ + return self._biolink_class + + @biolink_class.setter + def biolink_class(self, biolink_class: str): + """Sets the biolink_class of this Parameter. + + Biolink class of the paramater. Applicable to producers only and only one parameter can have a biolink class. # noqa: E501 + + :param biolink_class: The biolink_class of this Parameter. + :type biolink_class: str + """ + + self._biolink_class = biolink_class + + @property + def allowed_values(self) -> List[str]: + """Gets the allowed_values of this Parameter. + + Allowed values for the parameter. # noqa: E501 + + :return: The allowed_values of this Parameter. + :rtype: List[str] + """ + return self._allowed_values + + @allowed_values.setter + def allowed_values(self, allowed_values: List[str]): + """Sets the allowed_values of this Parameter. + + Allowed values for the parameter. # noqa: E501 + + :param allowed_values: The allowed_values of this Parameter. + :type allowed_values: List[str] + """ + + self._allowed_values = allowed_values + + @property + def allowed_range(self) -> List[float]: + """Gets the allowed_range of this Parameter. + + Allowed range for values of the parameter. # noqa: E501 + + :return: The allowed_range of this Parameter. + :rtype: List[float] + """ + return self._allowed_range + + @allowed_range.setter + def allowed_range(self, allowed_range: List[float]): + """Sets the allowed_range of this Parameter. + + Allowed range for values of the parameter. # noqa: E501 + + :param allowed_range: The allowed_range of this Parameter. + :type allowed_range: List[float] + """ + + self._allowed_range = allowed_range + + @property + def suggested_values(self) -> str: + """Gets the suggested_values of this Parameter. + + Suggested value range for the parameter. # noqa: E501 + + :return: The suggested_values of this Parameter. + :rtype: str + """ + return self._suggested_values + + @suggested_values.setter + def suggested_values(self, suggested_values: str): + """Sets the suggested_values of this Parameter. + + Suggested value range for the parameter. # noqa: E501 + + :param suggested_values: The suggested_values of this Parameter. + :type suggested_values: str + """ + + self._suggested_values = suggested_values + + @property + def lookup_url(self) -> str: + """Gets the lookup_url of this Parameter. + + URL to search for suitable parameter values. # noqa: E501 + + :return: The lookup_url of this Parameter. + :rtype: str + """ + return self._lookup_url + + @lookup_url.setter + def lookup_url(self, lookup_url: str): + """Sets the lookup_url of this Parameter. + + URL to search for suitable parameter values. # noqa: E501 + + :param lookup_url: The lookup_url of this Parameter. + :type lookup_url: str + """ + + self._lookup_url = lookup_url diff --git a/python-flask-server/swagger_server/models/transformer_info.py b/python-flask-server/swagger_server/models/transformer_info.py new file mode 100644 index 0000000..afc4c5b --- /dev/null +++ b/python-flask-server/swagger_server/models/transformer_info.py @@ -0,0 +1,276 @@ +# coding: utf-8 + +from __future__ import absolute_import +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server.models.parameter import Parameter # noqa: F401,E501 +from swagger_server.models.transformer_info_properties import TransformerInfoProperties # noqa: F401,E501 +from swagger_server import util + + +class TransformerInfo(Model): + """NOTE: This class is auto generated by the swagger code generator program. + + Do not edit the class manually. + """ + + def __init__(self, name: str=None, label: str=None, version: str=None, function: str=None, description: str=None, properties: TransformerInfoProperties=None, parameters: List[Parameter]=None, required_attributes: List[str]=None): # noqa: E501 + """TransformerInfo - a model defined in Swagger + + :param name: The name of this TransformerInfo. # noqa: E501 + :type name: str + :param label: The label of this TransformerInfo. # noqa: E501 + :type label: str + :param version: The version of this TransformerInfo. # noqa: E501 + :type version: str + :param function: The function of this TransformerInfo. # noqa: E501 + :type function: str + :param description: The description of this TransformerInfo. # noqa: E501 + :type description: str + :param properties: The properties of this TransformerInfo. # noqa: E501 + :type properties: TransformerInfoProperties + :param parameters: The parameters of this TransformerInfo. # noqa: E501 + :type parameters: List[Parameter] + :param required_attributes: The required_attributes of this TransformerInfo. # noqa: E501 + :type required_attributes: List[str] + """ + self.swagger_types = { + 'name': str, + 'label': str, + 'version': str, + 'function': str, + 'description': str, + 'properties': TransformerInfoProperties, + 'parameters': List[Parameter], + 'required_attributes': List[str] + } + + self.attribute_map = { + 'name': 'name', + 'label': 'label', + 'version': 'version', + 'function': 'function', + 'description': 'description', + 'properties': 'properties', + 'parameters': 'parameters', + 'required_attributes': 'required_attributes' + } + + self._name = name + self._label = label + self._version = version + self._function = function + self._description = description + self._properties = properties + self._parameters = parameters + self._required_attributes = required_attributes + + @classmethod + def from_dict(cls, dikt) -> 'TransformerInfo': + """Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The transformer_info of this TransformerInfo. # noqa: E501 + :rtype: TransformerInfo + """ + return util.deserialize_model(dikt, cls) + + @property + def name(self) -> str: + """Gets the name of this TransformerInfo. + + Name of the transformer. # noqa: E501 + + :return: The name of this TransformerInfo. + :rtype: str + """ + return self._name + + @name.setter + def name(self, name: str): + """Sets the name of this TransformerInfo. + + Name of the transformer. # noqa: E501 + + :param name: The name of this TransformerInfo. + :type name: str + """ + if name is None: + raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 + + self._name = name + + @property + def label(self) -> str: + """Gets the label of this TransformerInfo. + + Short label for GUI display. # noqa: E501 + + :return: The label of this TransformerInfo. + :rtype: str + """ + return self._label + + @label.setter + def label(self, label: str): + """Sets the label of this TransformerInfo. + + Short label for GUI display. # noqa: E501 + + :param label: The label of this TransformerInfo. + :type label: str + """ + + self._label = label + + @property + def version(self) -> str: + """Gets the version of this TransformerInfo. + + Transformer's version. # noqa: E501 + + :return: The version of this TransformerInfo. + :rtype: str + """ + return self._version + + @version.setter + def version(self, version: str): + """Sets the version of this TransformerInfo. + + Transformer's version. # noqa: E501 + + :param version: The version of this TransformerInfo. + :type version: str + """ + + self._version = version + + @property + def function(self) -> str: + """Gets the function of this TransformerInfo. + + Function of the transformer, one of 'producer', 'expander', 'filter'. # noqa: E501 + + :return: The function of this TransformerInfo. + :rtype: str + """ + return self._function + + @function.setter + def function(self, function: str): + """Sets the function of this TransformerInfo. + + Function of the transformer, one of 'producer', 'expander', 'filter'. # noqa: E501 + + :param function: The function of this TransformerInfo. + :type function: str + """ + allowed_values = ["producer", "expander", "filter"] # noqa: E501 + if function not in allowed_values: + raise ValueError( + "Invalid value for `function` ({0}), must be one of {1}" + .format(function, allowed_values) + ) + + self._function = function + + @property + def description(self) -> str: + """Gets the description of this TransformerInfo. + + Description of the transformer. # noqa: E501 + + :return: The description of this TransformerInfo. + :rtype: str + """ + return self._description + + @description.setter + def description(self, description: str): + """Sets the description of this TransformerInfo. + + Description of the transformer. # noqa: E501 + + :param description: The description of this TransformerInfo. + :type description: str + """ + if description is None: + raise ValueError("Invalid value for `description`, must not be `None`") # noqa: E501 + + self._description = description + + @property + def properties(self) -> TransformerInfoProperties: + """Gets the properties of this TransformerInfo. + + + :return: The properties of this TransformerInfo. + :rtype: TransformerInfoProperties + """ + return self._properties + + @properties.setter + def properties(self, properties: TransformerInfoProperties): + """Sets the properties of this TransformerInfo. + + + :param properties: The properties of this TransformerInfo. + :type properties: TransformerInfoProperties + """ + + self._properties = properties + + @property + def parameters(self) -> List[Parameter]: + """Gets the parameters of this TransformerInfo. + + Parameters used to control the transformer. # noqa: E501 + + :return: The parameters of this TransformerInfo. + :rtype: List[Parameter] + """ + return self._parameters + + @parameters.setter + def parameters(self, parameters: List[Parameter]): + """Sets the parameters of this TransformerInfo. + + Parameters used to control the transformer. # noqa: E501 + + :param parameters: The parameters of this TransformerInfo. + :type parameters: List[Parameter] + """ + if parameters is None: + raise ValueError("Invalid value for `parameters`, must not be `None`") # noqa: E501 + + self._parameters = parameters + + @property + def required_attributes(self) -> List[str]: + """Gets the required_attributes of this TransformerInfo. + + Gene attributes required by the transformer # noqa: E501 + + :return: The required_attributes of this TransformerInfo. + :rtype: List[str] + """ + return self._required_attributes + + @required_attributes.setter + def required_attributes(self, required_attributes: List[str]): + """Sets the required_attributes of this TransformerInfo. + + Gene attributes required by the transformer # noqa: E501 + + :param required_attributes: The required_attributes of this TransformerInfo. + :type required_attributes: List[str] + """ + if required_attributes is None: + raise ValueError("Invalid value for `required_attributes`, must not be `None`") # noqa: E501 + + self._required_attributes = required_attributes diff --git a/python-flask-server/swagger_server/models/transformer_info_properties.py b/python-flask-server/swagger_server/models/transformer_info_properties.py new file mode 100644 index 0000000..264eb19 --- /dev/null +++ b/python-flask-server/swagger_server/models/transformer_info_properties.py @@ -0,0 +1,150 @@ +# coding: utf-8 + +from __future__ import absolute_import +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server import util + + +class TransformerInfoProperties(Model): + """NOTE: This class is auto generated by the swagger code generator program. + + Do not edit the class manually. + """ + + def __init__(self, list_predicate: str=None, member_predicate: str=None, source_url: str=None, method: str=None): # noqa: E501 + """TransformerInfoProperties - a model defined in Swagger + + :param list_predicate: The list_predicate of this TransformerInfoProperties. # noqa: E501 + :type list_predicate: str + :param member_predicate: The member_predicate of this TransformerInfoProperties. # noqa: E501 + :type member_predicate: str + :param source_url: The source_url of this TransformerInfoProperties. # noqa: E501 + :type source_url: str + :param method: The method of this TransformerInfoProperties. # noqa: E501 + :type method: str + """ + self.swagger_types = { + 'list_predicate': str, + 'member_predicate': str, + 'source_url': str, + 'method': str + } + + self.attribute_map = { + 'list_predicate': 'list_predicate', + 'member_predicate': 'member_predicate', + 'source_url': 'source_url', + 'method': 'method' + } + + self._list_predicate = list_predicate + self._member_predicate = member_predicate + self._source_url = source_url + self._method = method + + @classmethod + def from_dict(cls, dikt) -> 'TransformerInfoProperties': + """Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The transformer_info_properties of this TransformerInfoProperties. # noqa: E501 + :rtype: TransformerInfoProperties + """ + return util.deserialize_model(dikt, cls) + + @property + def list_predicate(self) -> str: + """Gets the list_predicate of this TransformerInfoProperties. + + BioLink-model predicate describing relationship between input and output gene lists. # noqa: E501 + + :return: The list_predicate of this TransformerInfoProperties. + :rtype: str + """ + return self._list_predicate + + @list_predicate.setter + def list_predicate(self, list_predicate: str): + """Sets the list_predicate of this TransformerInfoProperties. + + BioLink-model predicate describing relationship between input and output gene lists. # noqa: E501 + + :param list_predicate: The list_predicate of this TransformerInfoProperties. + :type list_predicate: str + """ + + self._list_predicate = list_predicate + + @property + def member_predicate(self) -> str: + """Gets the member_predicate of this TransformerInfoProperties. + + BioLink-model predicate describing relationship between input and output genes. # noqa: E501 + + :return: The member_predicate of this TransformerInfoProperties. + :rtype: str + """ + return self._member_predicate + + @member_predicate.setter + def member_predicate(self, member_predicate: str): + """Sets the member_predicate of this TransformerInfoProperties. + + BioLink-model predicate describing relationship between input and output genes. # noqa: E501 + + :param member_predicate: The member_predicate of this TransformerInfoProperties. + :type member_predicate: str + """ + + self._member_predicate = member_predicate + + @property + def source_url(self) -> str: + """Gets the source_url of this TransformerInfoProperties. + + URL for underlying data or a wrapped service. # noqa: E501 + + :return: The source_url of this TransformerInfoProperties. + :rtype: str + """ + return self._source_url + + @source_url.setter + def source_url(self, source_url: str): + """Sets the source_url of this TransformerInfoProperties. + + URL for underlying data or a wrapped service. # noqa: E501 + + :param source_url: The source_url of this TransformerInfoProperties. + :type source_url: str + """ + + self._source_url = source_url + + @property + def method(self) -> str: + """Gets the method of this TransformerInfoProperties. + + A method used to generate output gene lists. # noqa: E501 + + :return: The method of this TransformerInfoProperties. + :rtype: str + """ + return self._method + + @method.setter + def method(self, method: str): + """Sets the method of this TransformerInfoProperties. + + A method used to generate output gene lists. # noqa: E501 + + :param method: The method of this TransformerInfoProperties. + :type method: str + """ + + self._method = method diff --git a/python-flask-server/swagger_server/models/transformer_query.py b/python-flask-server/swagger_server/models/transformer_query.py new file mode 100644 index 0000000..0774f55 --- /dev/null +++ b/python-flask-server/swagger_server/models/transformer_query.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +from __future__ import absolute_import +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from swagger_server.models.base_model_ import Model +from swagger_server.models.gene_info import GeneInfo # noqa: F401,E501 +from swagger_server.models.model_property import ModelProperty # noqa: F401,E501 +from swagger_server import util + + +class TransformerQuery(Model): + """NOTE: This class is auto generated by the swagger code generator program. + + Do not edit the class manually. + """ + + def __init__(self, genes: List[GeneInfo]=None, controls: List[ModelProperty]=None): # noqa: E501 + """TransformerQuery - a model defined in Swagger + + :param genes: The genes of this TransformerQuery. # noqa: E501 + :type genes: List[GeneInfo] + :param controls: The controls of this TransformerQuery. # noqa: E501 + :type controls: List[ModelProperty] + """ + self.swagger_types = { + 'genes': List[GeneInfo], + 'controls': List[ModelProperty] + } + + self.attribute_map = { + 'genes': 'genes', + 'controls': 'controls' + } + + self._genes = genes + self._controls = controls + + @classmethod + def from_dict(cls, dikt) -> 'TransformerQuery': + """Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The transformer_query of this TransformerQuery. # noqa: E501 + :rtype: TransformerQuery + """ + return util.deserialize_model(dikt, cls) + + @property + def genes(self) -> List[GeneInfo]: + """Gets the genes of this TransformerQuery. + + List of genes that will be transformed. Required for expanders and filters; should be omitted for producers. # noqa: E501 + + :return: The genes of this TransformerQuery. + :rtype: List[GeneInfo] + """ + return self._genes + + @genes.setter + def genes(self, genes: List[GeneInfo]): + """Sets the genes of this TransformerQuery. + + List of genes that will be transformed. Required for expanders and filters; should be omitted for producers. # noqa: E501 + + :param genes: The genes of this TransformerQuery. + :type genes: List[GeneInfo] + """ + + self._genes = genes + + @property + def controls(self) -> List[ModelProperty]: + """Gets the controls of this TransformerQuery. + + Values that control the behavior of the transformer. Names of the controls must match the names specified in the transformer's definition and values must match types (and possibly allowed_values) specified in the transformer's definition. # noqa: E501 + + :return: The controls of this TransformerQuery. + :rtype: List[ModelProperty] + """ + return self._controls + + @controls.setter + def controls(self, controls: List[ModelProperty]): + """Sets the controls of this TransformerQuery. + + Values that control the behavior of the transformer. Names of the controls must match the names specified in the transformer's definition and values must match types (and possibly allowed_values) specified in the transformer's definition. # noqa: E501 + + :param controls: The controls of this TransformerQuery. + :type controls: List[ModelProperty] + """ + if controls is None: + raise ValueError("Invalid value for `controls`, must not be `None`") # noqa: E501 + + self._controls = controls diff --git a/python-flask-server/swagger_server/swagger/swagger.yaml b/python-flask-server/swagger_server/swagger/swagger.yaml new file mode 100644 index 0000000..42a45b3 --- /dev/null +++ b/python-flask-server/swagger_server/swagger/swagger.yaml @@ -0,0 +1,350 @@ +--- +swagger: "2.0" +info: + description: "Gene-list expander based on gene-expression correlation using BigGIM\ + \ (http://biggim.ncats.io/api/)." + version: "1.3.0" + title: "BigGIM gene-expression correlation" +host: "sharpener.ncats.io" +basePath: "/expression_correlation" +schemes: +- "https" +paths: + /transformer_info: + get: + tags: + - "transformer" + summary: "Retrieve transformer info" + description: "Provides information about the transformer." + operationId: "transformer_info_get" + parameters: [] + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/transformer_info" + x-swagger-router-controller: "swagger_server.controllers.transformer_controller" + /transform: + post: + tags: + - "transformer" + operationId: "transform_post" + parameters: + - in: "body" + name: "query" + description: "Performs transformer query." + required: true + schema: + $ref: "#/definitions/transformer_query" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/gene_info" + 400: + description: "bad request" + schema: + $ref: "#/definitions/error_msg" + 500: + description: "internal server error" + schema: + $ref: "#/definitions/error_msg" + x-swagger-router-controller: "swagger_server.controllers.transformer_controller" +definitions: + transformer_query: + type: "object" + required: + - "controls" + properties: + genes: + type: "array" + description: "List of genes that will be transformed. Required for expanders\ + \ and filters; should be omitted for producers." + items: + $ref: "#/definitions/gene_info" + controls: + type: "array" + description: "Values that control the behavior of the transformer. Names of\ + \ the controls must match the names specified in the transformer's definition\ + \ and values must match types (and possibly allowed_values) specified in\ + \ the transformer's definition." + items: + $ref: "#/definitions/property" + gene_info: + type: "object" + required: + - "gene_id" + properties: + gene_id: + type: "string" + description: "Id of the gene." + identifiers: + $ref: "#/definitions/gene_info_identifiers" + attributes: + type: "array" + description: "Additional information about the gene and provenance about gene-list\ + \ membership. Sharpener will use myGene.info to add 'gene_symbol', 'synonyms',\ + \ and 'gene_name' to every gene. Multiple synonyms are separated by semicolons." + items: + $ref: "#/definitions/attribute" + source: + type: "string" + description: "Name of a transformer that added gene to the gene list." + example: + identifiers: + mim: "MIM:608958" + entrez: "NCBIGene:100" + ensembl: + - "ENSEMBL:ENSG00000196839" + - "ENSEMBL:ENSG00000196839" + hgnc: "HGNC:186" + mygene_info: "100" + attributes: + - name: "name" + source: "source" + value: "value" + url: "url" + - name: "name" + source: "source" + value: "value" + url: "url" + source: "source" + gene_id: "gene_id" + attribute: + type: "object" + required: + - "name" + - "source" + - "value" + properties: + name: + type: "string" + description: "Name of the attribute." + value: + type: "string" + description: "Value of the attribute." + source: + type: "string" + description: "Transformer that produced the attribute's value." + url: + type: "string" + description: "URL for additional information." + example: + name: "name" + source: "source" + value: "value" + url: "url" + property: + type: "object" + required: + - "name" + - "value" + properties: + name: + type: "string" + value: + type: "string" + transformer_info: + type: "object" + required: + - "description" + - "function" + - "name" + - "parameters" + - "required_attributes" + properties: + name: + type: "string" + description: "Name of the transformer." + label: + type: "string" + description: "Short label for GUI display." + version: + type: "string" + description: "Transformer's version." + function: + type: "string" + description: "Function of the transformer, one of 'producer', 'expander',\ + \ 'filter'." + enum: + - "producer" + - "expander" + - "filter" + description: + type: "string" + description: "Description of the transformer." + properties: + $ref: "#/definitions/transformer_info_properties" + parameters: + type: "array" + description: "Parameters used to control the transformer." + items: + $ref: "#/definitions/parameter" + required_attributes: + type: "array" + description: "Gene attributes required by the transformer" + items: + type: "string" + description: "Definition of the transformer." + example: + required_attributes: + - "required_attributes" + - "required_attributes" + function: "producer" + name: "name" + description: "description" + label: "label" + version: "version" + parameters: + - allowed_values: + - "allowed_values" + - "allowed_values" + biolink_class: "biolink_class" + default: "default" + allowed_range: + - 0.80082819046101150206595775671303272247314453125 + - 0.80082819046101150206595775671303272247314453125 + name: "name" + suggested_values: "suggested_values" + lookup_url: "lookup_url" + type: "Boolean" + - allowed_values: + - "allowed_values" + - "allowed_values" + biolink_class: "biolink_class" + default: "default" + allowed_range: + - 0.80082819046101150206595775671303272247314453125 + - 0.80082819046101150206595775671303272247314453125 + name: "name" + suggested_values: "suggested_values" + lookup_url: "lookup_url" + type: "Boolean" + properties: + list_predicate: "list_predicate" + method: "method" + member_predicate: "member_predicate" + source_url: "source_url" + parameter: + type: "object" + required: + - "default" + - "name" + - "type" + properties: + name: + type: "string" + description: "Name of the parameter." + type: + type: "string" + description: "Type of the parameter, one of 'Boolean', 'int', 'double', 'string'." + enum: + - "Boolean" + - "int" + - "double" + - "string" + default: + type: "string" + description: "Default value of the parameter." + biolink_class: + type: "string" + description: "Biolink class of the paramater. Applicable to producers only\ + \ and only one parameter can have a biolink class." + allowed_values: + type: "array" + description: "Allowed values for the parameter." + items: + type: "string" + allowed_range: + type: "array" + description: "Allowed range for values of the parameter." + items: + type: "number" + maxItems: 2 + minItems: 2 + suggested_values: + type: "string" + description: "Suggested value range for the parameter." + lookup_url: + type: "string" + description: "URL to search for suitable parameter values." + example: + allowed_values: + - "allowed_values" + - "allowed_values" + biolink_class: "biolink_class" + default: "default" + allowed_range: + - 0.80082819046101150206595775671303272247314453125 + - 0.80082819046101150206595775671303272247314453125 + name: "name" + suggested_values: "suggested_values" + lookup_url: "lookup_url" + type: "Boolean" + error_msg: + type: "object" + properties: + status: + type: "integer" + title: + type: "string" + detail: + type: "string" + type: + type: "string" + gene_info_identifiers: + properties: + entrez: + type: "string" + example: "NCBIGene:100" + description: "Entrez gene id (CURIE)." + hgnc: + type: "string" + example: "HGNC:186" + description: "HGNC gene id (CURIE)." + mim: + type: "string" + example: "MIM:608958" + description: "OMIM gene id (CURIE)." + ensembl: + type: "array" + description: "ENSEMBL gene id (CURIE)." + items: + type: "string" + example: "ENSEMBL:ENSG00000196839" + mygene_info: + type: "string" + example: "100" + description: "myGene.info primary id." + example: + mim: "MIM:608958" + entrez: "NCBIGene:100" + ensembl: + - "ENSEMBL:ENSG00000196839" + - "ENSEMBL:ENSG00000196839" + hgnc: "HGNC:186" + mygene_info: "100" + transformer_info_properties: + properties: + list_predicate: + type: "string" + description: "BioLink-model predicate describing relationship between input\ + \ and output gene lists." + member_predicate: + type: "string" + description: "BioLink-model predicate describing relationship between input\ + \ and output genes." + source_url: + type: "string" + description: "URL for underlying data or a wrapped service." + method: + type: "string" + description: "A method used to generate output gene lists." + description: "Additional metadata for the transformer." + example: + list_predicate: "list_predicate" + method: "method" + member_predicate: "member_predicate" + source_url: "source_url" diff --git a/python-flask-server/swagger_server/test/__init__.py b/python-flask-server/swagger_server/test/__init__.py new file mode 100644 index 0000000..6445063 --- /dev/null +++ b/python-flask-server/swagger_server/test/__init__.py @@ -0,0 +1,16 @@ +import logging + +import connexion +from flask_testing import TestCase + +from swagger_server.encoder import JSONEncoder + + +class BaseTestCase(TestCase): + + def create_app(self): + logging.getLogger('connexion.operation').setLevel('ERROR') + app = connexion.App(__name__, specification_dir='../swagger/') + app.app.json_encoder = JSONEncoder + app.add_api('swagger.yaml') + return app.app diff --git a/python-flask-server/swagger_server/test/test_transformer_controller.py b/python-flask-server/swagger_server/test/test_transformer_controller.py new file mode 100644 index 0000000..fe0c8ca --- /dev/null +++ b/python-flask-server/swagger_server/test/test_transformer_controller.py @@ -0,0 +1,46 @@ +# coding: utf-8 + +from __future__ import absolute_import + +from flask import json +from six import BytesIO + +from swagger_server.models.error_msg import ErrorMsg # noqa: E501 +from swagger_server.models.gene_info import GeneInfo # noqa: E501 +from swagger_server.models.transformer_info import TransformerInfo # noqa: E501 +from swagger_server.models.transformer_query import TransformerQuery # noqa: E501 +from swagger_server.test import BaseTestCase + + +class TestTransformerController(BaseTestCase): + """TransformerController integration test stubs""" + + def test_transform_post(self): + """Test case for transform_post + + + """ + query = TransformerQuery() + response = self.client.open( + '/expression_correlation/transform', + method='POST', + data=json.dumps(query), + content_type='application/json') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) + + def test_transformer_info_get(self): + """Test case for transformer_info_get + + Retrieve transformer info + """ + response = self.client.open( + '/expression_correlation/transformer_info', + method='GET') + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) + + +if __name__ == '__main__': + import unittest + unittest.main() diff --git a/python-flask-server/swagger_server/util.py b/python-flask-server/swagger_server/util.py new file mode 100644 index 0000000..527d142 --- /dev/null +++ b/python-flask-server/swagger_server/util.py @@ -0,0 +1,141 @@ +import datetime + +import six +import typing + + +def _deserialize(data, klass): + """Deserializes dict, list, str into an object. + + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. + """ + if data is None: + return None + + if klass in six.integer_types or klass in (float, str, bool): + return _deserialize_primitive(data, klass) + elif klass == object: + return _deserialize_object(data) + elif klass == datetime.date: + return deserialize_date(data) + elif klass == datetime.datetime: + return deserialize_datetime(data) + elif type(klass) == typing.GenericMeta: + if klass.__extra__ == list: + return _deserialize_list(data, klass.__args__[0]) + if klass.__extra__ == dict: + return _deserialize_dict(data, klass.__args__[1]) + else: + return deserialize_model(data, klass) + + +def _deserialize_primitive(data, klass): + """Deserializes to primitive type. + + :param data: data to deserialize. + :param klass: class literal. + + :return: int, long, float, str, bool. + :rtype: int | long | float | str | bool + """ + try: + value = klass(data) + except UnicodeEncodeError: + value = six.u(data) + except TypeError: + value = data + return value + + +def _deserialize_object(value): + """Return a original value. + + :return: object. + """ + return value + + +def deserialize_date(string): + """Deserializes string to date. + + :param string: str. + :type string: str + :return: date. + :rtype: date + """ + try: + from dateutil.parser import parse + return parse(string).date() + except ImportError: + return string + + +def deserialize_datetime(string): + """Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :type string: str + :return: datetime. + :rtype: datetime + """ + try: + from dateutil.parser import parse + return parse(string) + except ImportError: + return string + + +def deserialize_model(data, klass): + """Deserializes list or dict to model. + + :param data: dict, list. + :type data: dict | list + :param klass: class literal. + :return: model object. + """ + instance = klass() + + if not instance.swagger_types: + return data + + for attr, attr_type in six.iteritems(instance.swagger_types): + if data is not None \ + and instance.attribute_map[attr] in data \ + and isinstance(data, (list, dict)): + value = data[instance.attribute_map[attr]] + setattr(instance, attr, _deserialize(value, attr_type)) + + return instance + + +def _deserialize_list(data, boxed_type): + """Deserializes a list and its elements. + + :param data: list to deserialize. + :type data: list + :param boxed_type: class literal. + + :return: deserialized list. + :rtype: list + """ + return [_deserialize(sub_data, boxed_type) + for sub_data in data] + + +def _deserialize_dict(data, boxed_type): + """Deserializes a dict and its elements. + + :param data: dict to deserialize. + :type data: dict + :param boxed_type: class literal. + + :return: deserialized dict. + :rtype: dict + """ + return {k: _deserialize(v, boxed_type) + for k, v in six.iteritems(data)} diff --git a/python-flask-server/test-requirements.txt b/python-flask-server/test-requirements.txt new file mode 100644 index 0000000..7f8d96e --- /dev/null +++ b/python-flask-server/test-requirements.txt @@ -0,0 +1,6 @@ +flask_testing==0.6.1 +coverage>=4.0.3 +nose>=1.3.7 +pluggy>=0.3.1 +py>=1.4.31 +randomize>=0.13 diff --git a/python-flask-server/tox.ini b/python-flask-server/tox.ini new file mode 100644 index 0000000..3e0b644 --- /dev/null +++ b/python-flask-server/tox.ini @@ -0,0 +1,10 @@ +[tox] +envlist = py35 + +[testenv] +deps=-r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt + +commands= + nosetests \ + [] \ No newline at end of file From ae94899a526afc864ab5589512b55d963c4da032 Mon Sep 17 00:00:00 2001 From: vdancik Date: Fri, 6 Dec 2019 18:21:28 -0500 Subject: [PATCH 3/4] implement gene-transformer API ver 1.3 --- python-flask-server/setup.py | 4 +- .../swagger_server/__main__.py | 6 +- .../swagger_server/controllers/expander.py | 77 +++++++ .../controllers/transformer_controller.py | 6 +- .../swagger_server/controllers/wf8_module2.py | 209 ++++++++++++++++++ python-flask-server/transformer_info.json | 43 ++++ 6 files changed, 338 insertions(+), 7 deletions(-) create mode 100644 python-flask-server/swagger_server/controllers/expander.py create mode 100644 python-flask-server/swagger_server/controllers/wf8_module2.py create mode 100644 python-flask-server/transformer_info.json diff --git a/python-flask-server/setup.py b/python-flask-server/setup.py index d3c88c0..78d635a 100644 --- a/python-flask-server/setup.py +++ b/python-flask-server/setup.py @@ -3,8 +3,8 @@ import sys from setuptools import setup, find_packages -NAME = "swagger_server" -VERSION = "1.0.0" +NAME = "biggim expression-correlation" +VERSION = "1.3.0" # To install the library, run the following # diff --git a/python-flask-server/swagger_server/__main__.py b/python-flask-server/swagger_server/__main__.py index 7093c81..15b89a0 100644 --- a/python-flask-server/swagger_server/__main__.py +++ b/python-flask-server/swagger_server/__main__.py @@ -4,11 +4,11 @@ from swagger_server import encoder +app = connexion.App(__name__, specification_dir='./swagger/') +app.app.json_encoder = encoder.JSONEncoder +app.add_api('swagger.yaml', arguments={'title': 'BigGIM gene-expression correlation'}) def main(): - app = connexion.App(__name__, specification_dir='./swagger/') - app.app.json_encoder = encoder.JSONEncoder - app.add_api('swagger.yaml', arguments={'title': 'BigGIM gene-expression correlation'}) app.run(port=8080) diff --git a/python-flask-server/swagger_server/controllers/expander.py b/python-flask-server/swagger_server/controllers/expander.py new file mode 100644 index 0000000..89c7de1 --- /dev/null +++ b/python-flask-server/swagger_server/controllers/expander.py @@ -0,0 +1,77 @@ +from swagger_server.models.gene_info import GeneInfo +from swagger_server.models.gene_info import GeneInfoIdentifiers +from swagger_server.models.transformer_info import TransformerInfo + +from swagger_server.controllers.wf8_module2 import call_biggim + +import json + + +valid_controls = ['tissue', 'total'] +control_names = {'total': 'total', 'tissue': 'tissue'} +default_control_values = {'total': 64, 'tissue': 'liver'} +default_control_types = {'total': 'int', 'tissue': 'string'} + + +def get_control(controls, control): + value = controls[control_names[control]] if control_names[control] in controls else default_control_values[control] + if default_control_types[control] == 'double': + return float(value) + elif default_control_types[control] == 'Boolean': + return bool(value) + elif default_control_types[control] == 'int': + return int(value) + else: + return value + + +def entrez_gene_id(gene: GeneInfo): + """ + Return value of the entrez_gene_id attribute + """ + if (gene.identifiers is not None and gene.identifiers.entrez is not None): + if (gene.identifiers.entrez.startswith('NCBIGene:')): + return gene.identifiers.entrez[9:] + else: + return gene.identifiers.entrez + return None + + +def expand(query): + controls = {control.name:control.value for control in query.controls} + max_number = get_control(controls, 'total') + tissue = get_control(controls, 'tissue').split(',') + genes = [entrez_gene_id(gene) for gene in query.genes] + + output_genes = call_biggim(genes, tissue, average_columns=True, return_genes=True, N=max_number) + + genes = {} + gene_list = [] + for gene in query.genes: + genes[entrez_gene_id(gene)] = gene + gene_list.append(gene) + for gene_id in output_genes: + if gene_id not in genes: + gene_entrez_id = "NCBIGene:%s" % gene_id + gene = GeneInfo( + gene_id = gene_entrez_id, + identifiers = GeneInfoIdentifiers(entrez = gene_entrez_id), + attributes=[] + ) + genes[entrez_gene_id(gene)] = gene + gene_list.append(gene) + return gene_list + + +def expander_info(): + """ + Return information for this expander + """ + global control_names + + with open("transformer_info.json",'r') as f: + info = TransformerInfo.from_dict(json.loads(f.read())) + control_names = dict((name,parameter.name) for name, parameter in zip(valid_controls, info.parameters)) + return info + + diff --git a/python-flask-server/swagger_server/controllers/transformer_controller.py b/python-flask-server/swagger_server/controllers/transformer_controller.py index c6ca2c0..5def9f4 100644 --- a/python-flask-server/swagger_server/controllers/transformer_controller.py +++ b/python-flask-server/swagger_server/controllers/transformer_controller.py @@ -7,6 +7,8 @@ from swagger_server.models.transformer_query import TransformerQuery # noqa: E501 from swagger_server import util +from swagger_server.controllers.expander import expander_info +from swagger_server.controllers.expander import expand def transform_post(query): # noqa: E501 """transform_post @@ -20,7 +22,7 @@ def transform_post(query): # noqa: E501 """ if connexion.request.is_json: query = TransformerQuery.from_dict(connexion.request.get_json()) # noqa: E501 - return 'do some magic!' + return expand(query) def transformer_info_get(): # noqa: E501 @@ -31,4 +33,4 @@ def transformer_info_get(): # noqa: E501 :rtype: TransformerInfo """ - return 'do some magic!' + return expander_info() diff --git a/python-flask-server/swagger_server/controllers/wf8_module2.py b/python-flask-server/swagger_server/controllers/wf8_module2.py new file mode 100644 index 0000000..00d8915 --- /dev/null +++ b/python-flask-server/swagger_server/controllers/wf8_module2.py @@ -0,0 +1,209 @@ +import json +import requests +import pandas +import time +from multiprocessing import Pool +import logging +from requests.exceptions import HTTPError + +base_url = 'http://biggim.ncats.io/api' + +logger = logging.getLogger() +logger.setLevel(logging.INFO) +logging.debug("test") + +"""Linking tissues to columns""" +def get_columns(tissues,table='BigGIM_70_v1'): + + columns = [] + for t in tissues: + columns += get_column(t,table=table) + columns = list(set(columns)) # get rid of redundant columns + + a = columns + b = ['TCGA', 'Pvalue'] + columns = [sa for sa in a if not any(sb in sa for sb in b)] + + if len(columns) == 0: + raise Exception("No Big GIM columns related to %s" % (str(tissues))) + else: + print("Returned %i Big GIM columns" % (len(columns), )) + + return columns + +"""Running BigGIM""" +def call_biggim(genes, tissues, limit=1000000, average_columns=False, query_id2=False, return_genes=False, N=250): + """ + Parameters + ---------- + genes : list of str + + columns : list of str + + limit : int + + query_id2 : bool + If query_id2, the genes are duplicated for the ids2 field. + This forces biggim to return all interactions within genes. + """ + + columns = get_columns(tissues,table='BigGIM_70_v1') + print(columns) + + gene_list = ','.join(genes) + + example_query = { + "restriction_gt": ','.join(["%s,-2.0" % (c,) for c in columns]), + "table": "BigGIM_70_v1", + "columns": ','.join(columns), + "ids1": gene_list, + "limit": limit, + "average_columns": average_columns, + } + + if query_id2: + example_query["ids2"] = gene_list + + try: + query_submit = get('biggim/query', data=example_query) + jprint(query_submit) + except requests.HTTPError as e: + print(e) + + jprint(e.response.json()) + + error_counter = 0 + try: + while True: + try: + query_status = get('biggim/status/%s' % (query_submit['request_id'],)) + jprint(query_status) + + if query_status['status'] != 'running': + # query has finished + break + else: + time.sleep(5) + print("Checking again") + except requests.HTTPError as e: + print(e) + time.sleep(5) + error_counter += 1 + if error_counter > 3: + print("Giving up") + raise + else: + print("Trying again.") + except requests.HTTPError as e: + print(e) + + jprint(e.response.json()) + + result = pandas.concat(map(pandas.read_csv, query_status['request_uri'])) + result = result.iloc[:,1:] + + if return_genes: + df = result + print(df) + df = df.sort_values(by='mean',ascending=False) + df = df.reset_index() + print(df) + del df['index'] + gene_list = genes + i = len(gene_list) + for index, row in df.iterrows(): + if i>=(len(genes)+N): + break + gene_list.append(row['Gene1']) + gene_list.append(row['Gene2']) + gene_list = list(set(gene_list)) + i = len(gene_list) + + gene_list = [int(x) for x in gene_list] + gene_list = [str(x) for x in gene_list] + gene_list.sort() + + return gene_list + + return result + +"""Helpers""" + +def get_column(some_tissue, table='BigGIM_70_v1'): + columns = [] + try: + # query + md = get('metadata/tissue/%s' % some_tissue) + for st in md['substudies']: + for column in st.get('columns',[]): + #filter table + if column.get('table', {}).get('name', None) == table: + #filter r(spearman) +# if column.get('interactions_type',None) == 'Spearman Rank Correlation Coefficient': + #get the name of the columns + if column.get('name', None) is not None: + columns.append(column.get('name')) + except HTTPError as e: + #if 404 error, it could not find the tissue, otherwise something bad happend + if e.args[0].find('404') == -1: + raise + return columns + + + + + + + +# A few helper functions for posting and getting api requests +#a couple of simple helper functions +def post(endpoint, data={}, base_url=base_url): + req = requests.post('%s/%s' % (base_url,endpoint), data=data) + req.raise_for_status() + return req.json() + +def get(endpoint, data={}, base_url=base_url): + req = requests.get('%s/%s' % (base_url,endpoint), data=data) + try: + req.raise_for_status() + except requests.HTTPError as e: + print("Sent: GET %s?%s" % (req.request.url,req.request.body)) + if e.response.status_code == 400: + print(e.response) + jprint(e.response.json()) + raise + print("Sent: GET %s?%s" % (req.request.url,req.request.body)) + return req.json() + +def jprint(dct): + print(json.dumps(dct, indent=2)) + +def wrapper(endpoint, data={}, base_url=base_url): + try: + response = get(endpoint, data, base_url) + jprint(response) + except requests.HTTPError as e: + + print(e) + if e.response.status_code == 400: + jprint(e.response.json()) + raise + try: + ctr = 1 + while True: + query_status = get('%s/status/%s'% (endpoint.split('/')[0],response['request_id'],)) + jprint(query_status) + if query_status['status'] !='running': + # query has finished + break + else: + time.sleep(ctr) + ctr += 5 + #linear backoff + print("Checking again") + except requests.HTTPError as e: + print(e) + if e.response.status_code == 400: + jprint(e.response.json()) + raise + return pandas.concat(map(pandas.read_csv, query_status['request_uri'])) \ No newline at end of file diff --git a/python-flask-server/transformer_info.json b/python-flask-server/transformer_info.json new file mode 100644 index 0000000..2547c50 --- /dev/null +++ b/python-flask-server/transformer_info.json @@ -0,0 +1,43 @@ +{ + "name": "BigGIM gene-expression correlation", + "label": "BigGIM", + "version": "1.3.0", + "function": "expander", + "description": "Gene-list expander based on gene-expression correlation using BigGIM (http://biggim.ncats.io/api/).", + "properties": { + "list_predicate": "related_to", + "member_predicate": "related_to", + "source_url": "http://biggim.ncats.io/api/", + "method": "correlation" + }, + "parameters": [ + { + "default": "pancreas", + "name": "tissue", + "type": "string", + "allowed_values": [ + "adipose_tissue", + "brain", + "liver", + "muscleSkeletal_muscle", + "pancreas", + "blood_platelet", + "cardiac_muscle", + "heart" + ], + "suggested_values": null, + "lookup_url": null + }, + { + "default": "64", + "name": "total", + "type": "int", + "allowed_values": null, + "suggested_values": "e.g., 10, 100, 1000", + "lookup_url": null + } + ], + "required_attributes": [ + "identifiers.entrez" + ] +} From 25b766914e2ed6086e56624ca0537226596cdf39 Mon Sep 17 00:00:00 2001 From: vdancik Date: Fri, 6 Dec 2019 18:24:00 -0500 Subject: [PATCH 4/4] remove java play server --- .../.swagger-codegen-ignore | 23 -- .../.swagger-codegen/VERSION | 1 - java-play-framework-server/LICENSE | 8 - java-play-framework-server/README | 4 - java-play-framework-server/app/Module.java | 11 - .../app/apimodels/Attribute.java | 121 ------ .../app/apimodels/GeneInfo.java | 134 ------ .../app/apimodels/GeneInfoIdentifiers.java | 173 -------- .../app/apimodels/Parameter.java | 233 ----------- .../app/apimodels/Property.java | 99 ----- .../app/apimodels/TransformerInfo.java | 215 ---------- .../app/apimodels/TransformerQuery.java | 117 ------ .../app/controllers/ApiDocController.java | 15 - .../controllers/TransformerApiController.java | 72 ---- .../TransformerApiControllerImp.java | 28 -- .../TransformerApiControllerImpInterface.java | 20 - .../app/swagger/ApiCall.java | 27 -- .../app/swagger/ErrorHandler.java | 49 --- .../app/swagger/SwaggerUtils.java | 103 ----- .../app/transformer/Transformer.java | 118 ------ java-play-framework-server/build.sbt | 12 - .../conf/application.conf | 380 ------------------ java-play-framework-server/conf/logback.xml | 41 -- java-play-framework-server/conf/routes | 14 - .../project/build.properties | 1 - .../project/plugins.sbt | 3 - .../public/swagger.json | 286 ------------- .../scripts/runBigGIM.py | 15 - .../scripts/runBigGIM_expander.pl | 36 -- .../scripts/runBigGIM_filter.pl | 33 -- .../scripts/wf8_module1.py | 299 -------------- .../scripts/wf8_module2.py | 209 ---------- 32 files changed, 2900 deletions(-) delete mode 100644 java-play-framework-server/.swagger-codegen-ignore delete mode 100644 java-play-framework-server/.swagger-codegen/VERSION delete mode 100644 java-play-framework-server/LICENSE delete mode 100644 java-play-framework-server/README delete mode 100644 java-play-framework-server/app/Module.java delete mode 100644 java-play-framework-server/app/apimodels/Attribute.java delete mode 100644 java-play-framework-server/app/apimodels/GeneInfo.java delete mode 100644 java-play-framework-server/app/apimodels/GeneInfoIdentifiers.java delete mode 100644 java-play-framework-server/app/apimodels/Parameter.java delete mode 100644 java-play-framework-server/app/apimodels/Property.java delete mode 100644 java-play-framework-server/app/apimodels/TransformerInfo.java delete mode 100644 java-play-framework-server/app/apimodels/TransformerQuery.java delete mode 100644 java-play-framework-server/app/controllers/ApiDocController.java delete mode 100644 java-play-framework-server/app/controllers/TransformerApiController.java delete mode 100644 java-play-framework-server/app/controllers/TransformerApiControllerImp.java delete mode 100644 java-play-framework-server/app/controllers/TransformerApiControllerImpInterface.java delete mode 100644 java-play-framework-server/app/swagger/ApiCall.java delete mode 100644 java-play-framework-server/app/swagger/ErrorHandler.java delete mode 100644 java-play-framework-server/app/swagger/SwaggerUtils.java delete mode 100644 java-play-framework-server/app/transformer/Transformer.java delete mode 100644 java-play-framework-server/build.sbt delete mode 100644 java-play-framework-server/conf/application.conf delete mode 100644 java-play-framework-server/conf/logback.xml delete mode 100644 java-play-framework-server/conf/routes delete mode 100644 java-play-framework-server/project/build.properties delete mode 100644 java-play-framework-server/project/plugins.sbt delete mode 100644 java-play-framework-server/public/swagger.json delete mode 100644 java-play-framework-server/scripts/runBigGIM.py delete mode 100644 java-play-framework-server/scripts/runBigGIM_expander.pl delete mode 100644 java-play-framework-server/scripts/runBigGIM_filter.pl delete mode 100644 java-play-framework-server/scripts/wf8_module1.py delete mode 100644 java-play-framework-server/scripts/wf8_module2.py diff --git a/java-play-framework-server/.swagger-codegen-ignore b/java-play-framework-server/.swagger-codegen-ignore deleted file mode 100644 index c5fa491..0000000 --- a/java-play-framework-server/.swagger-codegen-ignore +++ /dev/null @@ -1,23 +0,0 @@ -# Swagger Codegen Ignore -# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen - -# Use this file to prevent files from being overwritten by the generator. -# The patterns follow closely to .gitignore or .dockerignore. - -# As an example, the C# client generator defines ApiClient.cs. -# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: -#ApiClient.cs - -# You can match any string of characters against a directory, file or extension with a single asterisk (*): -#foo/*/qux -# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux - -# You can recursively match patterns against a directory, file or extension with a double asterisk (**): -#foo/**/qux -# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux - -# You can also negate patterns with an exclamation (!). -# For example, you can ignore all files in a docs folder with the file extension .md: -#docs/*.md -# Then explicitly reverse the ignore rule for a single file: -#!docs/README.md diff --git a/java-play-framework-server/.swagger-codegen/VERSION b/java-play-framework-server/.swagger-codegen/VERSION deleted file mode 100644 index 752a79e..0000000 --- a/java-play-framework-server/.swagger-codegen/VERSION +++ /dev/null @@ -1 +0,0 @@ -2.4.8 \ No newline at end of file diff --git a/java-play-framework-server/LICENSE b/java-play-framework-server/LICENSE deleted file mode 100644 index 4baedcb..0000000 --- a/java-play-framework-server/LICENSE +++ /dev/null @@ -1,8 +0,0 @@ -This software is licensed under the Apache 2 license, quoted below. - -Licensed under the Apache License, Version 2.0 (the "License"); you may not use this project except in compliance with -the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. - -Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific -language governing permissions and limitations under the License. \ No newline at end of file diff --git a/java-play-framework-server/README b/java-play-framework-server/README deleted file mode 100644 index 2fce029..0000000 --- a/java-play-framework-server/README +++ /dev/null @@ -1,4 +0,0 @@ -This is your new Play application -================================= - -This file will be packaged with your application when using `activator dist`. \ No newline at end of file diff --git a/java-play-framework-server/app/Module.java b/java-play-framework-server/app/Module.java deleted file mode 100644 index 6da3857..0000000 --- a/java-play-framework-server/app/Module.java +++ /dev/null @@ -1,11 +0,0 @@ -import com.google.inject.AbstractModule; - -import controllers.*; - -public class Module extends AbstractModule { - - @Override - protected void configure() { - bind(TransformerApiControllerImpInterface.class).to(TransformerApiControllerImp.class); - } -} \ No newline at end of file diff --git a/java-play-framework-server/app/apimodels/Attribute.java b/java-play-framework-server/app/apimodels/Attribute.java deleted file mode 100644 index 3ad987f..0000000 --- a/java-play-framework-server/app/apimodels/Attribute.java +++ /dev/null @@ -1,121 +0,0 @@ -package apimodels; - -import com.fasterxml.jackson.annotation.*; -import java.util.Set; -import javax.validation.*; -import java.util.Objects; -import javax.validation.constraints.*; -/** - * Attribute - */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaPlayFrameworkCodegen", date = "2019-09-09T21:40:17.116Z") - -@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) -public class Attribute { - @JsonProperty("name") - private String name = null; - - @JsonProperty("value") - private String value = null; - - @JsonProperty("source") - private String source = null; - - public Attribute name(String name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @NotNull - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Attribute value(String value) { - this.value = value; - return this; - } - - /** - * Get value - * @return value - **/ - @NotNull - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public Attribute source(String source) { - this.source = source; - return this; - } - - /** - * Get source - * @return source - **/ - public String getSource() { - return source; - } - - public void setSource(String source) { - this.source = source; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Attribute attribute = (Attribute) o; - return Objects.equals(name, attribute.name) && - Objects.equals(value, attribute.value) && - Objects.equals(source, attribute.source); - } - - @Override - public int hashCode() { - return Objects.hash(name, value, source); - } - - @SuppressWarnings("StringBufferReplaceableByString") - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Attribute {\n"); - - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" value: ").append(toIndentedString(value)).append("\n"); - sb.append(" source: ").append(toIndentedString(source)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/java-play-framework-server/app/apimodels/GeneInfo.java b/java-play-framework-server/app/apimodels/GeneInfo.java deleted file mode 100644 index a8562fe..0000000 --- a/java-play-framework-server/app/apimodels/GeneInfo.java +++ /dev/null @@ -1,134 +0,0 @@ -package apimodels; - -import apimodels.Attribute; -import apimodels.GeneInfoIdentifiers; -import java.util.ArrayList; -import java.util.List; -import com.fasterxml.jackson.annotation.*; -import java.util.Set; -import javax.validation.*; -import java.util.Objects; -import javax.validation.constraints.*; -/** - * GeneInfo - */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaPlayFrameworkCodegen", date = "2019-09-09T21:40:17.116Z") - -@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) -public class GeneInfo { - @JsonProperty("gene_id") - private String geneId = null; - - @JsonProperty("identifiers") - private GeneInfoIdentifiers identifiers = null; - - @JsonProperty("attributes") - private List attributes = null; - - public GeneInfo geneId(String geneId) { - this.geneId = geneId; - return this; - } - - /** - * Id of the gene. - * @return geneId - **/ - @NotNull - public String getGeneId() { - return geneId; - } - - public void setGeneId(String geneId) { - this.geneId = geneId; - } - - public GeneInfo identifiers(GeneInfoIdentifiers identifiers) { - this.identifiers = identifiers; - return this; - } - - /** - * Get identifiers - * @return identifiers - **/ - @Valid - public GeneInfoIdentifiers getIdentifiers() { - return identifiers; - } - - public void setIdentifiers(GeneInfoIdentifiers identifiers) { - this.identifiers = identifiers; - } - - public GeneInfo attributes(List attributes) { - this.attributes = attributes; - return this; - } - - public GeneInfo addAttributesItem(Attribute attributesItem) { - if (attributes == null) { - attributes = new ArrayList<>(); - } - attributes.add(attributesItem); - return this; - } - - /** - * Additional information about the gene and provenance about gene-list membership. Sharpener will use myGene.info to add 'gene_symbol', 'synonyms', and 'gene_name' to every gene. Multiple synonyms are separated by semicolons. - * @return attributes - **/ - @Valid - public List getAttributes() { - return attributes; - } - - public void setAttributes(List attributes) { - this.attributes = attributes; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - GeneInfo geneInfo = (GeneInfo) o; - return Objects.equals(geneId, geneInfo.geneId) && - Objects.equals(identifiers, geneInfo.identifiers) && - Objects.equals(attributes, geneInfo.attributes); - } - - @Override - public int hashCode() { - return Objects.hash(geneId, identifiers, attributes); - } - - @SuppressWarnings("StringBufferReplaceableByString") - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class GeneInfo {\n"); - - sb.append(" geneId: ").append(toIndentedString(geneId)).append("\n"); - sb.append(" identifiers: ").append(toIndentedString(identifiers)).append("\n"); - sb.append(" attributes: ").append(toIndentedString(attributes)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/java-play-framework-server/app/apimodels/GeneInfoIdentifiers.java b/java-play-framework-server/app/apimodels/GeneInfoIdentifiers.java deleted file mode 100644 index 79f5adb..0000000 --- a/java-play-framework-server/app/apimodels/GeneInfoIdentifiers.java +++ /dev/null @@ -1,173 +0,0 @@ -package apimodels; - -import java.util.ArrayList; -import java.util.List; -import com.fasterxml.jackson.annotation.*; -import java.util.Set; -import javax.validation.*; -import java.util.Objects; -import javax.validation.constraints.*; -/** - * GeneInfoIdentifiers - */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaPlayFrameworkCodegen", date = "2019-09-09T21:40:17.116Z") - -@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) -public class GeneInfoIdentifiers { - @JsonProperty("entrez") - private String entrez = null; - - @JsonProperty("hgnc") - private String hgnc = null; - - @JsonProperty("mim") - private String mim = null; - - @JsonProperty("ensembl") - private List ensembl = null; - - @JsonProperty("mygene_info") - private String mygeneInfo = null; - - public GeneInfoIdentifiers entrez(String entrez) { - this.entrez = entrez; - return this; - } - - /** - * Entrez gene id (CURIE). - * @return entrez - **/ - public String getEntrez() { - return entrez; - } - - public void setEntrez(String entrez) { - this.entrez = entrez; - } - - public GeneInfoIdentifiers hgnc(String hgnc) { - this.hgnc = hgnc; - return this; - } - - /** - * HGNC gene id (CURIE). - * @return hgnc - **/ - public String getHgnc() { - return hgnc; - } - - public void setHgnc(String hgnc) { - this.hgnc = hgnc; - } - - public GeneInfoIdentifiers mim(String mim) { - this.mim = mim; - return this; - } - - /** - * OMIM gene id (CURIE). - * @return mim - **/ - public String getMim() { - return mim; - } - - public void setMim(String mim) { - this.mim = mim; - } - - public GeneInfoIdentifiers ensembl(List ensembl) { - this.ensembl = ensembl; - return this; - } - - public GeneInfoIdentifiers addEnsemblItem(String ensemblItem) { - if (ensembl == null) { - ensembl = new ArrayList<>(); - } - ensembl.add(ensemblItem); - return this; - } - - /** - * ENSEMBL gene id (CURIE). - * @return ensembl - **/ - public List getEnsembl() { - return ensembl; - } - - public void setEnsembl(List ensembl) { - this.ensembl = ensembl; - } - - public GeneInfoIdentifiers mygeneInfo(String mygeneInfo) { - this.mygeneInfo = mygeneInfo; - return this; - } - - /** - * myGene.info primary id. - * @return mygeneInfo - **/ - public String getMygeneInfo() { - return mygeneInfo; - } - - public void setMygeneInfo(String mygeneInfo) { - this.mygeneInfo = mygeneInfo; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - GeneInfoIdentifiers geneInfoIdentifiers = (GeneInfoIdentifiers) o; - return Objects.equals(entrez, geneInfoIdentifiers.entrez) && - Objects.equals(hgnc, geneInfoIdentifiers.hgnc) && - Objects.equals(mim, geneInfoIdentifiers.mim) && - Objects.equals(ensembl, geneInfoIdentifiers.ensembl) && - Objects.equals(mygeneInfo, geneInfoIdentifiers.mygeneInfo); - } - - @Override - public int hashCode() { - return Objects.hash(entrez, hgnc, mim, ensembl, mygeneInfo); - } - - @SuppressWarnings("StringBufferReplaceableByString") - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class GeneInfoIdentifiers {\n"); - - sb.append(" entrez: ").append(toIndentedString(entrez)).append("\n"); - sb.append(" hgnc: ").append(toIndentedString(hgnc)).append("\n"); - sb.append(" mim: ").append(toIndentedString(mim)).append("\n"); - sb.append(" ensembl: ").append(toIndentedString(ensembl)).append("\n"); - sb.append(" mygeneInfo: ").append(toIndentedString(mygeneInfo)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/java-play-framework-server/app/apimodels/Parameter.java b/java-play-framework-server/app/apimodels/Parameter.java deleted file mode 100644 index d8b76a6..0000000 --- a/java-play-framework-server/app/apimodels/Parameter.java +++ /dev/null @@ -1,233 +0,0 @@ -package apimodels; - -import java.util.ArrayList; -import java.util.List; -import com.fasterxml.jackson.annotation.*; -import java.util.Set; -import javax.validation.*; -import java.util.Objects; -import javax.validation.constraints.*; -/** - * Parameter - */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaPlayFrameworkCodegen", date = "2019-09-09T21:40:17.116Z") - -@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) -public class Parameter { - @JsonProperty("name") - private String name = null; - - /** - * Type of the parameter, one of 'Boolean', 'int', 'double', 'string'. - */ - public enum TypeEnum { - BOOLEAN("Boolean"), - - INT("int"), - - DOUBLE("double"), - - STRING("string"); - - private final String value; - - TypeEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static TypeEnum fromValue(String text) { - for (TypeEnum b : TypeEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("type") - private TypeEnum type = null; - - @JsonProperty("default") - private String _default = null; - - @JsonProperty("allowed_values") - private List allowedValues = null; - - @JsonProperty("suggested_values") - private String suggestedValues = null; - - @JsonProperty("lookup_url") - private String lookupUrl = null; - - public Parameter name(String name) { - this.name = name; - return this; - } - - /** - * Name of the parameter. - * @return name - **/ - @NotNull - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Parameter type(TypeEnum type) { - this.type = type; - return this; - } - - /** - * Type of the parameter, one of 'Boolean', 'int', 'double', 'string'. - * @return type - **/ - @NotNull - public TypeEnum getType() { - return type; - } - - public void setType(TypeEnum type) { - this.type = type; - } - - public Parameter _default(String _default) { - this._default = _default; - return this; - } - - /** - * Default value of the parameter. - * @return _default - **/ - @NotNull - public String getDefault() { - return _default; - } - - public void setDefault(String _default) { - this._default = _default; - } - - public Parameter allowedValues(List allowedValues) { - this.allowedValues = allowedValues; - return this; - } - - public Parameter addAllowedValuesItem(String allowedValuesItem) { - if (allowedValues == null) { - allowedValues = new ArrayList<>(); - } - allowedValues.add(allowedValuesItem); - return this; - } - - /** - * Allowed values for the parameter. - * @return allowedValues - **/ - public List getAllowedValues() { - return allowedValues; - } - - public void setAllowedValues(List allowedValues) { - this.allowedValues = allowedValues; - } - - public Parameter suggestedValues(String suggestedValues) { - this.suggestedValues = suggestedValues; - return this; - } - - /** - * Suggested value range for the parameter. - * @return suggestedValues - **/ - public String getSuggestedValues() { - return suggestedValues; - } - - public void setSuggestedValues(String suggestedValues) { - this.suggestedValues = suggestedValues; - } - - public Parameter lookupUrl(String lookupUrl) { - this.lookupUrl = lookupUrl; - return this; - } - - /** - * URL to search for suitable parameter values. - * @return lookupUrl - **/ - public String getLookupUrl() { - return lookupUrl; - } - - public void setLookupUrl(String lookupUrl) { - this.lookupUrl = lookupUrl; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Parameter parameter = (Parameter) o; - return Objects.equals(name, parameter.name) && - Objects.equals(type, parameter.type) && - Objects.equals(_default, parameter._default) && - Objects.equals(allowedValues, parameter.allowedValues) && - Objects.equals(suggestedValues, parameter.suggestedValues) && - Objects.equals(lookupUrl, parameter.lookupUrl); - } - - @Override - public int hashCode() { - return Objects.hash(name, type, _default, allowedValues, suggestedValues, lookupUrl); - } - - @SuppressWarnings("StringBufferReplaceableByString") - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Parameter {\n"); - - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" _default: ").append(toIndentedString(_default)).append("\n"); - sb.append(" allowedValues: ").append(toIndentedString(allowedValues)).append("\n"); - sb.append(" suggestedValues: ").append(toIndentedString(suggestedValues)).append("\n"); - sb.append(" lookupUrl: ").append(toIndentedString(lookupUrl)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/java-play-framework-server/app/apimodels/Property.java b/java-play-framework-server/app/apimodels/Property.java deleted file mode 100644 index 6809312..0000000 --- a/java-play-framework-server/app/apimodels/Property.java +++ /dev/null @@ -1,99 +0,0 @@ -package apimodels; - -import com.fasterxml.jackson.annotation.*; -import java.util.Set; -import javax.validation.*; -import java.util.Objects; -import javax.validation.constraints.*; -/** - * Property - */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaPlayFrameworkCodegen", date = "2019-09-09T21:40:17.116Z") - -@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) -public class Property { - @JsonProperty("name") - private String name = null; - - @JsonProperty("value") - private String value = null; - - public Property name(String name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @NotNull - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Property value(String value) { - this.value = value; - return this; - } - - /** - * Get value - * @return value - **/ - @NotNull - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Property property = (Property) o; - return Objects.equals(name, property.name) && - Objects.equals(value, property.value); - } - - @Override - public int hashCode() { - return Objects.hash(name, value); - } - - @SuppressWarnings("StringBufferReplaceableByString") - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Property {\n"); - - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" value: ").append(toIndentedString(value)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/java-play-framework-server/app/apimodels/TransformerInfo.java b/java-play-framework-server/app/apimodels/TransformerInfo.java deleted file mode 100644 index f852b12..0000000 --- a/java-play-framework-server/app/apimodels/TransformerInfo.java +++ /dev/null @@ -1,215 +0,0 @@ -package apimodels; - -import apimodels.Parameter; -import java.util.ArrayList; -import java.util.List; -import com.fasterxml.jackson.annotation.*; -import java.util.Set; -import javax.validation.*; -import java.util.Objects; -import javax.validation.constraints.*; -/** - * Definition of the transformer. - */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaPlayFrameworkCodegen", date = "2019-09-09T21:40:17.116Z") - -@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) -public class TransformerInfo { - @JsonProperty("name") - private String name = null; - - /** - * Function of the transformer, one of 'producer', 'expander', 'filter'. - */ - public enum FunctionEnum { - PRODUCER("producer"), - - EXPANDER("expander"), - - FILTER("filter"); - - private final String value; - - FunctionEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static FunctionEnum fromValue(String text) { - for (FunctionEnum b : FunctionEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("function") - private FunctionEnum function = null; - - @JsonProperty("description") - private String description = null; - - @JsonProperty("parameters") - private List parameters = new ArrayList<>(); - - @JsonProperty("required_attributes") - private List requiredAttributes = new ArrayList<>(); - - public TransformerInfo name(String name) { - this.name = name; - return this; - } - - /** - * Name of the transformer. - * @return name - **/ - @NotNull - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public TransformerInfo function(FunctionEnum function) { - this.function = function; - return this; - } - - /** - * Function of the transformer, one of 'producer', 'expander', 'filter'. - * @return function - **/ - @NotNull - public FunctionEnum getFunction() { - return function; - } - - public void setFunction(FunctionEnum function) { - this.function = function; - } - - public TransformerInfo description(String description) { - this.description = description; - return this; - } - - /** - * Description of the transformer. - * @return description - **/ - @NotNull - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public TransformerInfo parameters(List parameters) { - this.parameters = parameters; - return this; - } - - public TransformerInfo addParametersItem(Parameter parametersItem) { - parameters.add(parametersItem); - return this; - } - - /** - * Parameters used to control the transformer. - * @return parameters - **/ - @NotNull -@Valid - public List getParameters() { - return parameters; - } - - public void setParameters(List parameters) { - this.parameters = parameters; - } - - public TransformerInfo requiredAttributes(List requiredAttributes) { - this.requiredAttributes = requiredAttributes; - return this; - } - - public TransformerInfo addRequiredAttributesItem(String requiredAttributesItem) { - requiredAttributes.add(requiredAttributesItem); - return this; - } - - /** - * Gene attributes required by the transformer - * @return requiredAttributes - **/ - @NotNull - public List getRequiredAttributes() { - return requiredAttributes; - } - - public void setRequiredAttributes(List requiredAttributes) { - this.requiredAttributes = requiredAttributes; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - TransformerInfo transformerInfo = (TransformerInfo) o; - return Objects.equals(name, transformerInfo.name) && - Objects.equals(function, transformerInfo.function) && - Objects.equals(description, transformerInfo.description) && - Objects.equals(parameters, transformerInfo.parameters) && - Objects.equals(requiredAttributes, transformerInfo.requiredAttributes); - } - - @Override - public int hashCode() { - return Objects.hash(name, function, description, parameters, requiredAttributes); - } - - @SuppressWarnings("StringBufferReplaceableByString") - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class TransformerInfo {\n"); - - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" function: ").append(toIndentedString(function)).append("\n"); - sb.append(" description: ").append(toIndentedString(description)).append("\n"); - sb.append(" parameters: ").append(toIndentedString(parameters)).append("\n"); - sb.append(" requiredAttributes: ").append(toIndentedString(requiredAttributes)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/java-play-framework-server/app/apimodels/TransformerQuery.java b/java-play-framework-server/app/apimodels/TransformerQuery.java deleted file mode 100644 index 95c774e..0000000 --- a/java-play-framework-server/app/apimodels/TransformerQuery.java +++ /dev/null @@ -1,117 +0,0 @@ -package apimodels; - -import apimodels.GeneInfo; -import apimodels.Property; -import java.util.ArrayList; -import java.util.List; -import com.fasterxml.jackson.annotation.*; -import java.util.Set; -import javax.validation.*; -import java.util.Objects; -import javax.validation.constraints.*; -/** - * TransformerQuery - */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaPlayFrameworkCodegen", date = "2019-09-09T21:40:17.116Z") - -@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) -public class TransformerQuery { - @JsonProperty("genes") - private List genes = null; - - @JsonProperty("controls") - private List controls = new ArrayList<>(); - - public TransformerQuery genes(List genes) { - this.genes = genes; - return this; - } - - public TransformerQuery addGenesItem(GeneInfo genesItem) { - if (genes == null) { - genes = new ArrayList<>(); - } - genes.add(genesItem); - return this; - } - - /** - * List of genes that will be transformed. Required for expanders and filters; should be omitted for producers. - * @return genes - **/ - @Valid - public List getGenes() { - return genes; - } - - public void setGenes(List genes) { - this.genes = genes; - } - - public TransformerQuery controls(List controls) { - this.controls = controls; - return this; - } - - public TransformerQuery addControlsItem(Property controlsItem) { - controls.add(controlsItem); - return this; - } - - /** - * Values that control the behavior of the transformer. Names of the controls must match the names specified in the transformer's definition and values must match types (and possibly allowed_values) specified in the transformer's definition. - * @return controls - **/ - @NotNull -@Valid - public List getControls() { - return controls; - } - - public void setControls(List controls) { - this.controls = controls; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - TransformerQuery transformerQuery = (TransformerQuery) o; - return Objects.equals(genes, transformerQuery.genes) && - Objects.equals(controls, transformerQuery.controls); - } - - @Override - public int hashCode() { - return Objects.hash(genes, controls); - } - - @SuppressWarnings("StringBufferReplaceableByString") - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class TransformerQuery {\n"); - - sb.append(" genes: ").append(toIndentedString(genes)).append("\n"); - sb.append(" controls: ").append(toIndentedString(controls)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/java-play-framework-server/app/controllers/ApiDocController.java b/java-play-framework-server/app/controllers/ApiDocController.java deleted file mode 100644 index 53536fd..0000000 --- a/java-play-framework-server/app/controllers/ApiDocController.java +++ /dev/null @@ -1,15 +0,0 @@ -package controllers; - -import javax.inject.*; -import play.mvc.*; - -public class ApiDocController extends Controller { - - @Inject - private ApiDocController() { - } - - public Result api() { - return redirect("/assets/lib/swagger-ui/index.html?/url=/assets/swagger.json"); - } -} diff --git a/java-play-framework-server/app/controllers/TransformerApiController.java b/java-play-framework-server/app/controllers/TransformerApiController.java deleted file mode 100644 index ad08d6c..0000000 --- a/java-play-framework-server/app/controllers/TransformerApiController.java +++ /dev/null @@ -1,72 +0,0 @@ -package controllers; - -import apimodels.GeneInfo; -import apimodels.TransformerInfo; -import apimodels.TransformerQuery; - -import play.mvc.Controller; -import play.mvc.Result; -import play.mvc.Http; -import java.util.List; -import java.util.Map; -import java.util.ArrayList; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.JsonNode; -import com.google.inject.Inject; -import java.io.File; -import swagger.SwaggerUtils; -import com.fasterxml.jackson.core.type.TypeReference; - -import javax.validation.constraints.*; -import play.Configuration; - -import swagger.SwaggerUtils.ApiAction; - -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaPlayFrameworkCodegen", date = "2019-09-09T21:40:17.116Z") - -public class TransformerApiController extends Controller { - - private final TransformerApiControllerImpInterface imp; - private final ObjectMapper mapper; - private final Configuration configuration; - - @Inject - private TransformerApiController(Configuration configuration, TransformerApiControllerImpInterface imp) { - this.imp = imp; - mapper = new ObjectMapper(); - this.configuration = configuration; - } - - - @ApiAction - public Result transformPost() throws Exception { - JsonNode nodequery = request().body().asJson(); - TransformerQuery query; - if (nodequery != null) { - query = mapper.readValue(nodequery.toString(), TransformerQuery.class); - if (configuration.getBoolean("useInputBeanValidation")) { - SwaggerUtils.validate(query); - } - } else { - throw new IllegalArgumentException("'query' parameter is required"); - } - List obj = imp.transformPost(query); - if (configuration.getBoolean("useOutputBeanValidation")) { - for (GeneInfo curItem : obj) { - SwaggerUtils.validate(curItem); - } - } - JsonNode result = mapper.valueToTree(obj); - return ok(result); - } - - @ApiAction - public Result transformerInfoGet() throws Exception { - TransformerInfo obj = imp.transformerInfoGet(); - if (configuration.getBoolean("useOutputBeanValidation")) { - SwaggerUtils.validate(obj); - } - JsonNode result = mapper.valueToTree(obj); - return ok(result); - } -} diff --git a/java-play-framework-server/app/controllers/TransformerApiControllerImp.java b/java-play-framework-server/app/controllers/TransformerApiControllerImp.java deleted file mode 100644 index 8e46bd1..0000000 --- a/java-play-framework-server/app/controllers/TransformerApiControllerImp.java +++ /dev/null @@ -1,28 +0,0 @@ -package controllers; - -import apimodels.GeneInfo; -import apimodels.TransformerInfo; -import apimodels.TransformerQuery; - -import transformer.Transformer; - -import play.mvc.Http; -import java.util.List; -import java.util.ArrayList; -import java.util.HashMap; -import java.io.FileInputStream; -import javax.validation.constraints.*; -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaPlayFrameworkCodegen", date = "2019-09-09T21:40:17.116Z") - -public class TransformerApiControllerImp implements TransformerApiControllerImpInterface { - @Override - public List transformPost(TransformerQuery query) throws Exception { - return Transformer.produceGeneSet(query); - } - - @Override - public TransformerInfo transformerInfoGet() throws Exception { - return Transformer.transformerInfo(); - } - -} diff --git a/java-play-framework-server/app/controllers/TransformerApiControllerImpInterface.java b/java-play-framework-server/app/controllers/TransformerApiControllerImpInterface.java deleted file mode 100644 index b1d904a..0000000 --- a/java-play-framework-server/app/controllers/TransformerApiControllerImpInterface.java +++ /dev/null @@ -1,20 +0,0 @@ -package controllers; - -import apimodels.GeneInfo; -import apimodels.TransformerInfo; -import apimodels.TransformerQuery; - -import play.mvc.Http; -import java.util.List; -import java.util.ArrayList; -import java.util.HashMap; - -import javax.validation.constraints.*; - -@SuppressWarnings("RedundantThrows") -public interface TransformerApiControllerImpInterface { - List transformPost(TransformerQuery query) throws Exception; - - TransformerInfo transformerInfoGet() throws Exception; - -} diff --git a/java-play-framework-server/app/swagger/ApiCall.java b/java-play-framework-server/app/swagger/ApiCall.java deleted file mode 100644 index 2ca3080..0000000 --- a/java-play-framework-server/app/swagger/ApiCall.java +++ /dev/null @@ -1,27 +0,0 @@ -package swagger; - -import com.google.inject.Inject; -import play.mvc.Action; -import play.mvc.Http; -import play.mvc.Result; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; - -public class ApiCall extends Action { - - @Inject - private ApiCall() {} - - public CompletionStage call(Http.Context ctx) { - try { - //TODO: Do stuff you want to handle with each API call (metrics, logging, etc..) - return delegate.call(ctx); - } catch (Throwable t) { - //TODO: log the error in your metric - - //We rethrow this error so it will be caught in the ErrorHandler - throw t; - } - } -} \ No newline at end of file diff --git a/java-play-framework-server/app/swagger/ErrorHandler.java b/java-play-framework-server/app/swagger/ErrorHandler.java deleted file mode 100644 index 2c81341..0000000 --- a/java-play-framework-server/app/swagger/ErrorHandler.java +++ /dev/null @@ -1,49 +0,0 @@ -package swagger; - - -import play.*; -import play.api.OptionalSourceMapper; -import play.api.UsefulException; -import play.api.routing.Router; -import play.http.DefaultHttpErrorHandler; -import play.mvc.Http.*; -import play.mvc.*; - -import javax.inject.*; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; -import static play.mvc.Results.*; - -@Singleton -public class ErrorHandler extends DefaultHttpErrorHandler { - - @Inject - public ErrorHandler(Configuration configuration, Environment environment, OptionalSourceMapper sourceMapper, Provider routes) { - super(configuration, environment, sourceMapper, routes); - } - - @Override - protected CompletionStage onDevServerError(RequestHeader request, UsefulException exception) { - return CompletableFuture.completedFuture( - handleExceptions(exception) - ); - } - - @Override - protected CompletionStage onProdServerError(RequestHeader request, UsefulException exception) { - return CompletableFuture.completedFuture( - handleExceptions(exception) - ); - } - - @Override - protected void logServerError(RequestHeader request, UsefulException usefulException) { - //Since the error is already handled, we don't want to print anything on the console - //But if you want to have the error printed in the console, just delete this override - } - - private Result handleExceptions(Throwable t) { - //TODO: Handle exception that need special response (return a special apimodel, notFound(), etc..) - return ok(); - } -} diff --git a/java-play-framework-server/app/swagger/SwaggerUtils.java b/java-play-framework-server/app/swagger/SwaggerUtils.java deleted file mode 100644 index d4900e0..0000000 --- a/java-play-framework-server/app/swagger/SwaggerUtils.java +++ /dev/null @@ -1,103 +0,0 @@ -package swagger; - -import play.mvc.With; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.text.SimpleDateFormat; -import java.util.*; - -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; - -public class SwaggerUtils { - - @With(ApiCall.class) - @Target({ ElementType.TYPE, ElementType.METHOD }) - @Retention(RetentionPolicy.RUNTIME) - public @interface ApiAction { - } - - public static void validate(T obj) { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Set> constraintViolations = validator.validate(obj); - if (constraintViolations.size() > 0) { - StringBuilder errors = new StringBuilder(); - for (ConstraintViolation contraintes : constraintViolations) { - errors.append(String.format("%s.%s %s\n", - contraintes.getRootBeanClass().getSimpleName(), - contraintes.getPropertyPath(), - contraintes.getMessage())); - } - throw new RuntimeException("Bean validation : " + errors); - } - } - - public static List parametersToList(String collectionFormat, String[] values){ - List params = new ArrayList<>(); - - if (values == null) { - return params; - } - - if (values.length >= 1 && collectionFormat.equals("multi")) { - params.addAll(Arrays.asList(values)); - } else { - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - - String delimiter = ","; - - switch(collectionFormat) { - case "csv": { - delimiter = ","; - break; - } - case "ssv": { - delimiter = " "; - break; - } - case "tsv": { - delimiter = "\t"; - break; - } - case "pipes": { - delimiter = "|"; - break; - } - } - - params = Arrays.asList(values[0].split(delimiter)); - } - - return params; - } - - public static String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date) { - return formatDatetime((Date) param); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for (Object o : (Collection)param) { - if (b.length() > 0) { - b.append(","); - } - b.append(String.valueOf(o)); - } - - return b.toString(); - } else { - return String.valueOf(param); - } - } - - public static String formatDatetime(Date date) { - return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(date); - } -} \ No newline at end of file diff --git a/java-play-framework-server/app/transformer/Transformer.java b/java-play-framework-server/app/transformer/Transformer.java deleted file mode 100644 index f04cc1d..0000000 --- a/java-play-framework-server/app/transformer/Transformer.java +++ /dev/null @@ -1,118 +0,0 @@ -package transformer; - -import java.io.BufferedReader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.io.InputStreamReader; - -import apimodels.Attribute; -import apimodels.GeneInfo; -import apimodels.GeneInfoIdentifiers; -import apimodels.Parameter; -import apimodels.Property; -import apimodels.TransformerInfo; -import apimodels.TransformerQuery; - -public class Transformer { - - private static final String NAME = "Big GIM expression correlation"; - private static final String TOTAL = "total"; - private static final String TISSUE = "tissue"; - private static final String DEFAUL_TOTAL = "100"; - private static final String DEFAUL_TISSUE = "pancreas"; - - - public static TransformerInfo transformerInfo() { - - TransformerInfo transformerInfo = new TransformerInfo().name(NAME); - transformerInfo.function(TransformerInfo.FunctionEnum.EXPANDER); - transformerInfo.description("Gene expression correlation with BigGIM"); - transformerInfo.addParametersItem( - new Parameter() - .name(TISSUE) - .type(Parameter.TypeEnum.STRING) - ._default(DEFAUL_TISSUE) - .addAllowedValuesItem("adipose_tissue") - .addAllowedValuesItem("brain") - .addAllowedValuesItem("liver") - .addAllowedValuesItem("muscleSkeletal_muscle") - .addAllowedValuesItem("pancreas") - .addAllowedValuesItem("blood_platelet") - .addAllowedValuesItem("cardiac_muscle") - .addAllowedValuesItem("heart") - ); - transformerInfo.addParametersItem( - new Parameter() - .name(TOTAL) - .type(Parameter.TypeEnum.INT) - ._default(DEFAUL_TOTAL) - .suggestedValues("from 10 to 1000") - ); - - transformerInfo.addRequiredAttributesItem("identifiers.entrez"); - return transformerInfo; - } - - - public static List produceGeneSet(final TransformerQuery query) { - - String myTOTAL = DEFAUL_TOTAL; - String myTISSUE = DEFAUL_TISSUE; - for (Property property : query.getControls()) { - if (TOTAL.equals(property.getName())) { - myTOTAL = property.getValue(); - } - if (TISSUE.equals(property.getName())) { - myTISSUE = property.getValue(); - } - } - - StringBuilder myGENES = new StringBuilder(""); - ArrayList genes = new ArrayList(); - HashMap inputGenes = new HashMap(); - for (GeneInfo geneInfo : query.getGenes()) { - if (geneInfo.getIdentifiers() != null && geneInfo.getIdentifiers().getEntrez() != null) { - myGENES.append(myGENES.toString().equals("") ? "" : ",").append(geneInfo.getIdentifiers().getEntrez()); - inputGenes.put(geneInfo.getIdentifiers().getEntrez(), geneInfo); - } - genes.add(geneInfo); - } - - Runtime rt = Runtime.getRuntime(); - - String[] commands = {"perl", "scripts/runBigGIM_expander.pl", myTOTAL, myTISSUE, myGENES.toString()}; - - try { - Process proc = rt.exec(commands); - - BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); - BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); - - //Read the gene list from expander - String s; - while ((s = stdInput.readLine()) != null) { - String geneId = "NCBIGene:" + s; - GeneInfo gene = inputGenes.get(geneId); - if (gene == null) { - gene = new GeneInfo().geneId(geneId); - gene.addAttributesItem(new Attribute().name("source").value(NAME).source(NAME)); - gene.setIdentifiers(new GeneInfoIdentifiers().entrez(geneId)); - genes.add(gene); - inputGenes.put(geneId, gene); - } - } - - //Print any errors from the attempted command - while ((s = stdError.readLine()) != null) { - System.err.println(s); - } - } - catch(Exception e) { - System.err.println(e.toString()); - } - - return genes; - } - -} diff --git a/java-play-framework-server/build.sbt b/java-play-framework-server/build.sbt deleted file mode 100644 index dc9d836..0000000 --- a/java-play-framework-server/build.sbt +++ /dev/null @@ -1,12 +0,0 @@ -name := """expression-correlation""" - -version := "1.2.1" - -lazy val root = (project in file(".")).enablePlugins(PlayJava) - -scalaVersion := "2.11.8" - -libraryDependencies += "org.webjars" % "swagger-ui" % "3.1.5" -libraryDependencies += "javax.validation" % "validation-api" % "1.1.0.Final" -libraryDependencies += guice -libraryDependencies += filters diff --git a/java-play-framework-server/conf/application.conf b/java-play-framework-server/conf/application.conf deleted file mode 100644 index 17dafa7..0000000 --- a/java-play-framework-server/conf/application.conf +++ /dev/null @@ -1,380 +0,0 @@ -# This is the main configuration file for the application. -# https://www.playframework.com/documentation/latest/ConfigFile -# ~~~~~ -# Play uses HOCON as its configuration file format. HOCON has a number -# of advantages over other config formats, but there are two things that -# can be used when modifying settings. -# -# You can include other configuration files in this main application.conf file: -#include "extra-config.conf" -# -# You can declare variables and substitute for them: -#mykey = ${some.value} -# -# And if an environment variable exists when there is no other subsitution, then -# HOCON will fall back to substituting environment variable: -#mykey = ${JAVA_HOME} - -play.filters.headers.contentSecurityPolicy=null - -# When using bean validation with the swagger api, the validator will check that every constraint is respected -# This is very useful when testing but could add a lot of overhead if you return a lot of data. Benchmark have -# shown that the time it takes to validate is exponential. -# If this is a concern in your application, or if you don't want to validate the output coming from your API for -# respecting its contract, set the "output" property below to "false". Since there is not a lot of data as input for -# an endpoint, I highly suggest you let the "input" property set to true. -useInputBeanValidation=false -useOutputBeanValidation=false - -play.http.errorHandler="swagger.ErrorHandler" - -## Akka -# https://www.playframework.com/documentation/latest/ScalaAkka#Configuration -# https://www.playframework.com/documentation/latest/JavaAkka#Configuration -# ~~~~~ -# Play uses Akka internally and exposes Akka Streams and actors in Websockets and -# other streaming HTTP responses. -akka { -# "akka.log-config-on-start" is extraordinarily useful because it log the complete -# configuration at INFO level, including defaults and overrides, so it s worth -# putting at the very top. -# -# Put the following in your conf/logback.xml file: -# -# -# -# And then uncomment this line to debug the configuration. -# -#log-config-on-start = true -} - -play.server.http.idleTimeout = 3600s - -## Secret key -# http://www.playframework.com/documentation/latest/ApplicationSecret -# ~~~~~ -# The secret key is used to sign Play's session cookie. -# This must be changed for production, but we don't recommend you change it in this file. -play.http.secret.key = "changeme" - -## Modules -# https://www.playframework.com/documentation/latest/Modules -# ~~~~~ -# Control which modules are loaded when Play starts. Note that modules are -# the replacement for "GlobalSettings", which are deprecated in 2.5.x. -# Please see https://www.playframework.com/documentation/latest/GlobalSettings -# for more information. -# -# You can also extend Play functionality by using one of the publically available -# Play modules: https://playframework.com/documentation/latest/ModuleDirectory -play.modules { -# By default, Play will load any class called Module that is defined -# in the root package (the "app" directory), or you can define them -# explicitly below. -# If there are any built-in modules that you want to disable, you can list them here. -} - -play.assets { -path = "/public" -urlPrefix = "/assets" -} - -## IDE -# https://www.playframework.com/documentation/latest/IDE -# ~~~~~ -# Depending on your IDE, you can add a hyperlink for errors that will jump you -# directly to the code location in the IDE in dev mode. The following line makes -# use of the IntelliJ IDEA REST interface: -#play.editor="http://localhost:63342/api/file/?file=%s&line=%s" - -## Internationalisation -# https://www.playframework.com/documentation/latest/JavaI18N -# https://www.playframework.com/documentation/latest/ScalaI18N -# ~~~~~ -# Play comes with its own i18n settings, which allow the user's preferred language -# to map through to internal messages, or allow the language to be stored in a cookie. -play.i18n { -# The application languages -langs = [ "en" ] - -# Whether the language cookie should be secure or not -#langCookieSecure = true - -# Whether the HTTP only attribute of the cookie should be set to true -#langCookieHttpOnly = true -} - -## Play HTTP settings -# ~~~~~ -play.http { -## Router -# https://www.playframework.com/documentation/latest/JavaRouting -# https://www.playframework.com/documentation/latest/ScalaRouting -# ~~~~~ -# Define the Router object to use for this application. -# This router will be looked up first when the application is starting up, -# so make sure this is the entry point. -# Furthermore, it's assumed your route file is named properly. -# So for an application router like `my.application.Router`, -# you may need to define a router file `conf/my.application.routes`. -# Default to Routes in the root package (aka "apps" folder) (and conf/routes) -#router = my.application.Router - -## Action Creator -# https://www.playframework.com/documentation/latest/JavaActionCreator -# ~~~~~ -#actionCreator = null - -## ErrorHandler -# https://www.playframework.com/documentation/latest/JavaRouting -# https://www.playframework.com/documentation/latest/ScalaRouting -# ~~~~~ -# If null, will attempt to load a class called ErrorHandler in the root package, -#errorHandler = null - -## Filters -# https://www.playframework.com/documentation/latest/ScalaHttpFilters -# https://www.playframework.com/documentation/latest/JavaHttpFilters -# ~~~~~ -# Filters run code on every request. They can be used to perform -# common logic for all your actions, e.g. adding common headers. -# Defaults to "Filters" in the root package (aka "apps" folder) -# Alternatively you can explicitly register a class here. -#filters = my.application.Filters - -## Session & Flash -# https://www.playframework.com/documentation/latest/JavaSessionFlash -# https://www.playframework.com/documentation/latest/ScalaSessionFlash -# ~~~~~ -session { -# Sets the cookie to be sent only over HTTPS. -#secure = true - -# Sets the cookie to be accessed only by the server. -#httpOnly = true - -# Sets the max-age field of the cookie to 5 minutes. -# NOTE: this only sets when the browser will discard the cookie. Play will consider any -# cookie value with a valid signature to be a valid session forever. To implement a server side session timeout, -# you need to put a timestamp in the session and check it at regular intervals to possibly expire it. -#maxAge = 300 - -# Sets the domain on the session cookie. -#domain = "example.com" -} - -flash { -# Sets the cookie to be sent only over HTTPS. -#secure = true - -# Sets the cookie to be accessed only by the server. -#httpOnly = true -} -} - -## Netty Provider -# https://www.playframework.com/documentation/latest/SettingsNetty -# ~~~~~ -play.server.netty { -# Whether the Netty wire should be logged -#log.wire = true - -# If you run Play on Linux, you can use Netty's native socket transport -# for higher performance with less garbage. -#transport = "native" -} - -## WS (HTTP Client) -# https://www.playframework.com/documentation/latest/ScalaWS#Configuring-WS -# ~~~~~ -# The HTTP client primarily used for REST APIs. The default client can be -# configured directly, but you can also create different client instances -# with customized settings. You must enable this by adding to build.sbt: -# -# libraryDependencies += ws // or javaWs if using java -# -play.ws { -# Sets HTTP requests not to follow 302 requests -#followRedirects = false - -# Sets the maximum number of open HTTP connections for the client. -#ahc.maxConnectionsTotal = 50 - -## WS SSL -# https://www.playframework.com/documentation/latest/WsSSL -# ~~~~~ -ssl { -# Configuring HTTPS with Play WS does not require programming. You can -# set up both trustManager and keyManager for mutual authentication, and -# turn on JSSE debugging in development with a reload. -#debug.handshake = true -#trustManager = { -# stores = [ -# { type = "JKS", path = "exampletrust.jks" } -# ] -#} -} -} - -## Cache -# https://www.playframework.com/documentation/latest/JavaCache -# https://www.playframework.com/documentation/latest/ScalaCache -# ~~~~~ -# Play comes with an integrated cache API that can reduce the operational -# overhead of repeated requests. You must enable this by adding to build.sbt: -# -# libraryDependencies += cache -# -play.cache { -# If you want to bind several caches, you can bind the individually -#bindCaches = ["db-cache", "user-cache", "session-cache"] -} - -play.filters.enabled += "play.filters.cors.CORSFilter" - -## Filters -# https://www.playframework.com/documentation/latest/Filters -# ~~~~~ -# There are a number of built-in filters that can be enabled and configured -# to give Play greater security. You must enable this by adding to build.sbt: -# -# libraryDependencies += filters -# -play.filters { -## CORS filter configuration -# https://www.playframework.com/documentation/latest/CorsFilter -# ~~~~~ -# CORS is a protocol that allows web applications to make requests from the browser -# across different domains. -# NOTE: You MUST apply the CORS configuration before the CSRF filter, as CSRF has -# dependencies on CORS settings. -cors { -# Filter paths by a whitelist of path prefixes -#pathPrefixes = ["/some/path", ...] - -# The allowed origins. If null, all origins are allowed. -#allowedOrigins = ["http://www.example.com"] - -# The allowed HTTP methods. If null, all methods are allowed -allowedHttpMethods = ["GET", "POST"] - -serveForbiddenOrigins = true -} - -## CSRF Filter -# https://www.playframework.com/documentation/latest/ScalaCsrf#Applying-a-global-CSRF-filter -# https://www.playframework.com/documentation/latest/JavaCsrf#Applying-a-global-CSRF-filter -# ~~~~~ -# Play supports multiple methods for verifying that a request is not a CSRF request. -# The primary mechanism is a CSRF token. This token gets placed either in the query string -# or body of every form submitted, and also gets placed in the users session. -# Play then verifies that both tokens are present and match. -csrf { -# Sets the cookie to be sent only over HTTPS -#cookie.secure = true - -# Defaults to CSRFErrorHandler in the root package. -#errorHandler = MyCSRFErrorHandler -} - -## Security headers filter configuration -# https://www.playframework.com/documentation/latest/SecurityHeaders -# ~~~~~ -# Defines security headers that prevent XSS attacks. -# If enabled, then all options are set to the below configuration by default: -play.filters.headers { - -# The X-Frame-Options header. If null, the header is not set. -#frameOptions = "DENY" - -# The X-XSS-Protection header. If null, the header is not set. -#xssProtection = "1; mode=block" - -# The X-Content-Type-Options header. If null, the header is not set. -#contentTypeOptions = "nosniff" - -# The X-Permitted-Cross-Domain-Policies header. If null, the header is not set. -#permittedCrossDomainPolicies = "master-only" - -# The Content-Security-Policy header. If null, the header is not set. -contentSecurityPolicy = "default-src 'self'" - -# The Referrer-Policy header. If null, the header is not set. -#referrerPolicy = "origin-when-cross-origin, strict-origin-when-cross-origin" - -# If true, allow an action to use .withHeaders to replace one or more of the above headers -#allowActionSpecificHeaders = false -} - -## Allowed hosts filter configuration -# https://www.playframework.com/documentation/latest/AllowedHostsFilter -# ~~~~~ -# Play provides a filter that lets you configure which hosts can access your application. -# This is useful to prevent cache poisoning attacks. -hosts { -# Allow requests to example.com, its subdomains, and localhost:9000. -allowed = [".", "localhost:9000"] -} -} - -## Evolutions -# https://www.playframework.com/documentation/latest/Evolutions -# ~~~~~ -# Evolutions allows database scripts to be automatically run on startup in dev mode -# for database migrations. You must enable this by adding to build.sbt: -# -# libraryDependencies += evolutions -# -play.evolutions { -# You can disable evolutions for a specific datasource if necessary -#db.default.enabled = false -} - -## Database Connection Pool -# https://www.playframework.com/documentation/latest/SettingsJDBC -# ~~~~~ -# Play doesn't require a JDBC database to run, but you can easily enable one. -# -# libraryDependencies += jdbc -# -play.db { -# The combination of these two settings results in "db.default" as the -# default JDBC pool: -#config = "db" -#default = "default" - -# Play uses HikariCP as the default connection pool. You can override -# settings by changing the prototype: -prototype { -# Sets a fixed JDBC connection pool size of 50 -#hikaricp.minimumIdle = 50 -#hikaricp.maximumPoolSize = 50 -} -} - -## JDBC Datasource -# https://www.playframework.com/documentation/latest/JavaDatabase -# https://www.playframework.com/documentation/latest/ScalaDatabase -# ~~~~~ -# Once JDBC datasource is set up, you can work with several different -# database options: -# -# Slick (Scala preferred option): https://www.playframework.com/documentation/latest/PlaySlick -# JPA (Java preferred option): https://playframework.com/documentation/latest/JavaJPA -# EBean: https://playframework.com/documentation/latest/JavaEbean -# Anorm: https://www.playframework.com/documentation/latest/ScalaAnorm -# -db { -# You can declare as many datasources as you want. -# By convention, the default datasource is named `default` - -# https://www.playframework.com/documentation/latest/Developing-with-the-H2-Database -#default.driver = org.h2.Driver -#default.url = "jdbc:h2:mem:play" -#default.username = sa -#default.password = "" - -# You can turn on SQL logging for any datasource -# https://www.playframework.com/documentation/latest/Highlights25#Logging-SQL-statements -#default.logSql=true -} diff --git a/java-play-framework-server/conf/logback.xml b/java-play-framework-server/conf/logback.xml deleted file mode 100644 index 01f301a..0000000 --- a/java-play-framework-server/conf/logback.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - ${application.home:-.}/logs/application.log - - %date [%level] from %logger in %thread - %message%n%xException - - - - - - %coloredLevel %logger{15} - %message%n%xException{10} - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/java-play-framework-server/conf/routes b/java-play-framework-server/conf/routes deleted file mode 100644 index fa1bb5b..0000000 --- a/java-play-framework-server/conf/routes +++ /dev/null @@ -1,14 +0,0 @@ -# Routes -# This file defines all application routes (Higher priority routes first) -# ~~~~ - -GET /api controllers.ApiDocController.api - - -#Functions for Transformer API -POST /expression_correlation/transform controllers.TransformerApiController.transformPost() -GET /expression_correlation/transformer_info controllers.TransformerApiController.transformerInfoGet() - -# Map static resources from the /public folder to the /assets URL path -GET /assets/*file controllers.Assets.at(file) -GET /versionedAssets/*file controllers.Assets.versioned(file) \ No newline at end of file diff --git a/java-play-framework-server/project/build.properties b/java-play-framework-server/project/build.properties deleted file mode 100644 index cf19fd0..0000000 --- a/java-play-framework-server/project/build.properties +++ /dev/null @@ -1 +0,0 @@ -sbt.version=0.13.15 \ No newline at end of file diff --git a/java-play-framework-server/project/plugins.sbt b/java-play-framework-server/project/plugins.sbt deleted file mode 100644 index a9f0279..0000000 --- a/java-play-framework-server/project/plugins.sbt +++ /dev/null @@ -1,3 +0,0 @@ -// The Play plugin -addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.3") -addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "4.0.0") diff --git a/java-play-framework-server/public/swagger.json b/java-play-framework-server/public/swagger.json deleted file mode 100644 index 6a409d1..0000000 --- a/java-play-framework-server/public/swagger.json +++ /dev/null @@ -1,286 +0,0 @@ -{ - "swagger" : "2.0", - "info" : { - "description" : "API for expression-correlation expander.", - "version" : "1.2.0", - "title" : "API for expression-correlation expander" - }, - "host" : "sharpener.ncats.io", - "basePath" : "/expression_correlation", - "schemes" : [ "https" ], - "paths" : { - "/transformer_info" : { - "get" : { - "tags" : [ "transformer" ], - "summary" : "Retrieve transformer info", - "description" : "Provides information about the transformer.", - "parameters" : [ ], - "responses" : { - "200" : { - "description" : "successful operation", - "schema" : { - "$ref" : "#/definitions/transformer_info" - } - } - }, - "x-accepts" : "application/json" - } - }, - "/transform" : { - "post" : { - "tags" : [ "transformer" ], - "parameters" : [ { - "in" : "body", - "name" : "query", - "description" : "Performs transformer query.", - "required" : true, - "schema" : { - "$ref" : "#/definitions/transformer_query" - } - } ], - "responses" : { - "200" : { - "description" : "successful operation", - "schema" : { - "type" : "array", - "items" : { - "$ref" : "#/definitions/gene_info" - } - } - } - }, - "x-contentType" : "application/json", - "x-accepts" : "application/json" - } - } - }, - "definitions" : { - "transformer_query" : { - "type" : "object", - "required" : [ "controls" ], - "properties" : { - "genes" : { - "type" : "array", - "description" : "List of genes that will be transformed. Required for expanders and filters; should be omitted for producers.", - "items" : { - "$ref" : "#/definitions/gene_info" - } - }, - "controls" : { - "type" : "array", - "description" : "Values that control the behavior of the transformer. Names of the controls must match the names specified in the transformer's definition and values must match types (and possibly allowed_values) specified in the transformer's definition.", - "items" : { - "$ref" : "#/definitions/property" - } - } - } - }, - "gene_info" : { - "type" : "object", - "required" : [ "gene_id" ], - "properties" : { - "gene_id" : { - "type" : "string", - "description" : "Id of the gene." - }, - "identifiers" : { - "$ref" : "#/definitions/gene_info_identifiers" - }, - "attributes" : { - "type" : "array", - "description" : "Additional information about the gene and provenance about gene-list membership. Sharpener will use myGene.info to add 'gene_symbol', 'synonyms', and 'gene_name' to every gene. Multiple synonyms are separated by semicolons.", - "items" : { - "$ref" : "#/definitions/attribute" - } - } - }, - "example" : { - "identifiers" : { - "mim" : "MIM:608958", - "entrez" : "NCBIGene:100", - "ensembl" : [ "ENSEMBL:ENSG00000196839", "ENSEMBL:ENSG00000196839" ], - "hgnc" : "HGNC:186", - "mygene_info" : "100" - }, - "attributes" : [ { - "name" : "name", - "source" : "source", - "value" : "value" - }, { - "name" : "name", - "source" : "source", - "value" : "value" - } ], - "gene_id" : "gene_id" - } - }, - "attribute" : { - "type" : "object", - "required" : [ "name", "value" ], - "properties" : { - "name" : { - "type" : "string" - }, - "value" : { - "type" : "string" - }, - "source" : { - "type" : "string" - } - }, - "example" : { - "name" : "name", - "source" : "source", - "value" : "value" - } - }, - "property" : { - "type" : "object", - "required" : [ "name", "value" ], - "properties" : { - "name" : { - "type" : "string" - }, - "value" : { - "type" : "string" - } - } - }, - "transformer_info" : { - "type" : "object", - "required" : [ "description", "function", "name", "parameters", "required_attributes" ], - "properties" : { - "name" : { - "type" : "string", - "description" : "Name of the transformer." - }, - "function" : { - "type" : "string", - "description" : "Function of the transformer, one of 'producer', 'expander', 'filter'.", - "enum" : [ "producer", "expander", "filter" ] - }, - "description" : { - "type" : "string", - "description" : "Description of the transformer." - }, - "parameters" : { - "type" : "array", - "description" : "Parameters used to control the transformer.", - "items" : { - "$ref" : "#/definitions/parameter" - } - }, - "required_attributes" : { - "type" : "array", - "description" : "Gene attributes required by the transformer", - "items" : { - "type" : "string" - } - } - }, - "description" : "Definition of the transformer.", - "example" : { - "required_attributes" : [ "required_attributes", "required_attributes" ], - "function" : "producer", - "name" : "name", - "description" : "description", - "parameters" : [ { - "allowed_values" : [ "allowed_values", "allowed_values" ], - "default" : "default", - "name" : "name", - "suggested_values" : "suggested_values", - "lookup_url" : "lookup_url", - "type" : "Boolean" - }, { - "allowed_values" : [ "allowed_values", "allowed_values" ], - "default" : "default", - "name" : "name", - "suggested_values" : "suggested_values", - "lookup_url" : "lookup_url", - "type" : "Boolean" - } ] - } - }, - "parameter" : { - "type" : "object", - "required" : [ "default", "name", "type" ], - "properties" : { - "name" : { - "type" : "string", - "description" : "Name of the parameter." - }, - "type" : { - "type" : "string", - "description" : "Type of the parameter, one of 'Boolean', 'int', 'double', 'string'.", - "enum" : [ "Boolean", "int", "double", "string" ] - }, - "default" : { - "type" : "string", - "description" : "Default value of the parameter." - }, - "allowed_values" : { - "type" : "array", - "description" : "Allowed values for the parameter.", - "items" : { - "type" : "string" - } - }, - "suggested_values" : { - "type" : "string", - "description" : "Suggested value range for the parameter." - }, - "lookup_url" : { - "type" : "string", - "description" : "URL to search for suitable parameter values." - } - }, - "example" : { - "allowed_values" : [ "allowed_values", "allowed_values" ], - "default" : "default", - "name" : "name", - "suggested_values" : "suggested_values", - "lookup_url" : "lookup_url", - "type" : "Boolean" - } - }, - "gene_info_identifiers" : { - "properties" : { - "entrez" : { - "type" : "string", - "example" : "NCBIGene:100", - "description" : "Entrez gene id (CURIE)." - }, - "hgnc" : { - "type" : "string", - "example" : "HGNC:186", - "description" : "HGNC gene id (CURIE)." - }, - "mim" : { - "type" : "string", - "example" : "MIM:608958", - "description" : "OMIM gene id (CURIE)." - }, - "ensembl" : { - "type" : "array", - "description" : "ENSEMBL gene id (CURIE).", - "items" : { - "type" : "string", - "example" : "ENSEMBL:ENSG00000196839" - } - }, - "mygene_info" : { - "type" : "string", - "example" : "100", - "description" : "myGene.info primary id." - } - }, - "example" : { - "mim" : "MIM:608958", - "entrez" : "NCBIGene:100", - "ensembl" : [ "ENSEMBL:ENSG00000196839", "ENSEMBL:ENSG00000196839" ], - "hgnc" : "HGNC:186", - "mygene_info" : "100" - } - } - } -} \ No newline at end of file diff --git a/java-play-framework-server/scripts/runBigGIM.py b/java-play-framework-server/scripts/runBigGIM.py deleted file mode 100644 index aaa499b..0000000 --- a/java-play-framework-server/scripts/runBigGIM.py +++ /dev/null @@ -1,15 +0,0 @@ -import json -import sys -from pprint import pprint -from wf8_module1 import doid_to_genes_and_tissues -from wf8_module2 import call_biggim -import numpy as np -import pandas as pd -import time - -maxNumber = int(sys.argv[1]) -tissues = sys.argv[2].split(',') -inputGenes = sys.argv[3].split(',') - -outputGenes = call_biggim(inputGenes, tissues, average_columns=True, return_genes=True, N=maxNumber) -print(outputGenes) diff --git a/java-play-framework-server/scripts/runBigGIM_expander.pl b/java-play-framework-server/scripts/runBigGIM_expander.pl deleted file mode 100644 index f06537c..0000000 --- a/java-play-framework-server/scripts/runBigGIM_expander.pl +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/perl -w - -use File::Basename; -use JSON -support_by_pp; - -die "Usage: $0 maxNumber tisueList geneList" if @ARGV < 3; - -$dirname = dirname(__FILE__); -$python = "python3"; - -$maxNumber = $ARGV[0]; -$tisues = $ARGV[1]; -$genes = $ARGV[2]; - -$genes =~ s/NCBIGene://g; - -@output = split /\n/, `$python $dirname/runBigGIM.py $maxNumber $tisues $genes`; - -@outGenes = split /', '/, $output[$#output]; - -if($outGenes[0] =~ s/^\[\'// && $outGenes[$#outGenes] =~ s/\'\]$// && $outGenes[0]=~ /^\d+$/) { - foreach(split /,/, $genes) { - print STDOUT $_,"\n"; - $myGenes{$_} = 1; - } - foreach(sort {$a <=> $b } @outGenes) { - next if exists $myGenes{$_}; - print STDOUT $_,"\n"; - } -} -else { - foreach(@output) { - print STDERR $_,"\n"; - } - print STDERR "input:\n\t$maxNumber\n\t$tisues\n\t$genes\n"; -} diff --git a/java-play-framework-server/scripts/runBigGIM_filter.pl b/java-play-framework-server/scripts/runBigGIM_filter.pl deleted file mode 100644 index 35c30ee..0000000 --- a/java-play-framework-server/scripts/runBigGIM_filter.pl +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/perl -w - -use File::Basename; -use JSON -support_by_pp; - -die "Usage: $0 maxNumber tisueList geneList" if @ARGV < 3; - -$dirname = dirname(__FILE__); -$python = "python3"; - -$maxNumber = $ARGV[0]; -$tisues = $ARGV[1]; -$genes = $ARGV[2]; - -$genes =~ s/NCBIGene://g; - -@output = split /\n/, `$python $dirname/runBigGIM.py $maxNumber $tisues $genes`; - -@outGenes = split /', '/, $output[$#output]; - -if($outGenes[0] =~ s/^\[\'// && $outGenes[$#outGenes] =~ s/\'\]$// && $outGenes[0]=~ /^\d+$/) { - foreach(@outGenes) { - $myGenes{$_} = 1; - } - foreach(split /,/, $genes) { - print STDOUT $_,"\n" if exists $myGenes{$_}; - } -} -else { - foreach(@output) { - print STDERR $_,"\n"; - } -} diff --git a/java-play-framework-server/scripts/wf8_module1.py b/java-play-framework-server/scripts/wf8_module1.py deleted file mode 100644 index e1e73e9..0000000 --- a/java-play-framework-server/scripts/wf8_module1.py +++ /dev/null @@ -1,299 +0,0 @@ -import json -import requests -import pandas -import time -from multiprocessing import Pool -import logging - -base_url = 'http://biggim.ncats.io/api' - -logger = logging.getLogger() -logger.setLevel(logging.INFO) -logging.debug("test") - -# ============================================================================= -# N = 2 #maximum number of elements to query for -# print(N) -# ============================================================================= - -def doid_to_genes_and_tissues(doid, direct=True, N=10): - if direct==True: - genes = doid_to_genes_direct(doid,N=N) - else: - genes = doid_to_genes(doid, N=N) - - tissues = doid_to_tissues(doid, N=N) - - return genes,tissues - -def doid_to_genes_direct(doid, N=10): - """ - Parameters - ---------- - doid : list of str - """ - - if not isinstance(doid, list): - doid = [doid] - - logging.info("Geting HP ids from DOID") - - #http://disease-ontology.org/ - disease_doid = doid - genes = doid_to_ncbigene(disease_doid, limit=N) - if len(genes) == 0: - raise Exception("No genes related to %s" % (str(disease_doid))) - else: - print("Returned %i genes" % (len(genes), )) - - return genes - - -def doid_to_genes(doid, N=10): - """ - Parameters - ---------- - doid : list of str - """ - - if not isinstance(doid, list): - doid = [doid] - - logging.info("Geting HP ids from DOID") - - #http://disease-ontology.org/ - disease_doid = doid - hpids = doid_to_hp(disease_doid, limit=N) - if len(hpids) == 0: - raise Exception("No phenotypes related to %s" % (str(disease_doid))) - else: - print("Returned %i phenotypes" % (len(hpids), )) - - logging.info("Geting OMIM from HP ids") - #https://hpo.jax.org/app/ - omims = hp_to_omim(hpids, limit=N) - - if len(omims) == 0: - raise Exception("No mendelian diseases(OMIM) related to %s" % (str(hpids))) - else: - print("Returned %i mendelian diseases" % (len(omims), )) - - logging.info("Geting genes from OMIM") - #https://omim.org/ - genes = omim_to_gene(omims, limit=N) - #genes are ncbi - if len(genes) == 0: - raise Exception("No genes associated with %s" % (str(omims),)) - else: - print("Returned %i genes" % (len(genes,))) - - return genes - -def doid_to_tissues(doid, N=10): - """ - Parameters - ---------- - doid : list of str - """ - - if not isinstance(doid, list): - doid = [doid] - - logging.info("Geting HP ids from DOID") - #http://disease-ontology.org/ - disease_doid = doid - hpids = doid_to_hp(disease_doid, limit=N) - if len(hpids) == 0: - raise Exception("No phenotypes related to %s" % (str(disease_doid))) - else: - print("Returned %i phenotypes" % (len(hpids), )) - - logging.info("Geting uberon from HP ids") - uberontissues = hp_to_uberon(hpids, limit=N) - if len(uberontissues) == 0: - raise Exception("No tissues related to %s" % (str(hpids))) - else: - print("Returned %i uberon tissues" % (len(uberontissues), )) - - #tissues = uberontissues - logging.info("Geting brenda tissue names from uberon tissue identifiers") - tissues = uberon_to_bto(uberontissues, limit=N) - if len(tissues) == 0: - raise Exception("No tissues related to %s" % (str(uberontissues))) - else: - print("Returned %i brenda tissues" % (len(tissues), )) - - return tissues - - -def query_single_edge(_input, _output, _value): - """ - Retrieve results using one API call from input to output. - :param _input: the input prefix, for a list of input prefix in BioThings Explorer, visit: http://biothings.io/explorer/api/v2/metadata/bioentities - :param _output: the output prefix, for a list of output prefix in BioThings Explorer, visit: http://biothings.io/explorer/api/v2/metadata/bioentities - :_value: The value of the input - :return: - """ - """ - endpoint = 'directinput2output' - base_url = 'http://biothings.io/explorer/api/v2' - data = {'output_prefix':_output, - 'input_prefix': _input, - 'input_value': _value, - 'format': 'translator' - }""" - #doc = get(endpoint, data=data, base_url=base_url) - qurl = 'http://biothings.io/explorer/api/v2/directinput2output?' - qurl += 'input_prefix=%s&output_prefix=%s&input_value=%s&format=translator' - qurl = qurl % (_input, _output, _value) - print(qurl) - try: - req = requests.get(qurl.strip(), timeout=10) - except: - print("timeout") - return [] - #print("Sent: GET %s?%s" % (req.request.url,req.request.body)) - return req.json() - - -"""Helpers""" - -def el(result): - try: - return result['result_list']['edge_list'] - except: - logging.warning(result) - return [] - - -def _doid_to_ncbigene(doid): - - - qse = query_single_edge(_input='doid', - _output='ncbigene', - _value=doid - ) - results = el(qse) - ts = set([x['target_id'] for x in results]) - return [x.split(':')[-1] for x in ts if x] - -def doid_to_ncbigene(doids, limit=None): - - #res = my_pool.map(_doid_to_hp, doids) - res = [] - - for doid in doids: - if limit is None or len(set(res)) < limit: - res += _doid_to_ncbigene(doid) - return res - -def _doid_to_hp(doid): - - - qse = query_single_edge(_input='doid', - _output='hp', - _value=doid - ) - results = el(qse) - ts = set([x['target_id'] for x in results]) - return [x.split(':')[-1] for x in ts if x] - -def doid_to_hp(doids, limit=None): - - #res = my_pool.map(_doid_to_hp, doids) - res = [] - - for doid in doids: - if limit is None or len(set(res)) < limit: - res += _doid_to_hp(doid) - return res - - -def _hp_to_omim(hpid): - qse = query_single_edge(_input='hp', - _output='omim.disease', - _value=hpid) - results = el(qse) - ts = set([x['target_id'] for x in results]) - return [x.split(':')[-1] for x in ts if x] - -def hp_to_omim(hpids, limit=None): - #res = my_pool.map(_hp_to_omim, hpids) - res = [] - for hpid in hpids: - if limit is None or len(set(res)) < limit: - res += _hp_to_omim(hpid) - return res - -def _omim_to_gene(omim): - qse = query_single_edge(_input='omim.disease', - _output='ncbigene', - _value=omim) - results = el(qse) - ts = set([x['target_id'] for x in results]) - return [x.split(':')[-1] for x in ts if x] - -def omim_to_gene(omims, limit=None): - #res = my_pool.map(_omim_to_gene, omims) - res = [] - for omim in omims: - if limit is None or len(set(res)) < limit: - res += _omim_to_gene(omim) - return res - -def _hp_to_uberon(hpid): - - qse = query_single_edge(_input='hp', - _output='uberon', - _value=hpid) - - results = el(qse) - ts = set([x['target_id'] for x in results]) - return [x.split(':')[-1] for x in ts if x] - -def hp_to_uberon(hpids, limit=None): - #res = my_pool.map(_hp_to_uberon,hpids) - res = [] - - for hpid in hpids: - if limit is None or len(set(res)) < limit: - res += _hp_to_uberon(hpid) - return res - - -def uberon_to_bto(ubid, limit=None): - res = [] - s = ["UBERON:"+y for y in ubid] - uberon_to_bto = json.load(open('bto_uberon_bg.json')) - for x in uberon_to_bto: - if x['uberon_id'] in s and x['bg_label']: - res += [x['bg_label']] - return res - - -# A few helper functions for posting and getting api requests -#a couple of simple helper functions -def post(endpoint, data={}, base_url=base_url): - req = requests.post('%s/%s' % (base_url,endpoint), data=data) - req.raise_for_status() - return req.json() - -def get(endpoint, data={}, base_url=base_url): - req = requests.get('%s/%s' % (base_url,endpoint), data=data) - try: - req.raise_for_status() - except requests.HTTPError as e: - print("Sent: GET %s?%s" % (req.request.url,req.request.body)) - if e.response.status_code == 400: - print(e.response) - jprint(e.response.json()) - raise - print("Sent: GET %s?%s" % (req.request.url,req.request.body)) - return req.json() - -def jprint(dct): - print(json.dumps(dct, indent=2)) - - - - \ No newline at end of file diff --git a/java-play-framework-server/scripts/wf8_module2.py b/java-play-framework-server/scripts/wf8_module2.py deleted file mode 100644 index 49952dc..0000000 --- a/java-play-framework-server/scripts/wf8_module2.py +++ /dev/null @@ -1,209 +0,0 @@ -import json -import requests -import pandas -import time -from multiprocessing import Pool -import logging -from requests.exceptions import HTTPError - -base_url = 'http://biggim.ncats.io/api' - -logger = logging.getLogger() -logger.setLevel(logging.INFO) -logging.debug("test") - -"""Linking tissues to columns""" -def get_columns(tissues,table='BigGIM_70_v1'): - - columns = [] - for t in tissues: - columns += get_column(t,table=table) - columns = list(set(columns)) # get rid of redundant columns - - a = columns - b = ['TCGA', 'Pvalue'] - columns = [sa for sa in a if not any(sb in sa for sb in b)] - - if len(columns) == 0: - raise Exception("No Big GIM columns related to %s" % (str(tissues))) - else: - print("Returned %i Big GIM columns" % (len(columns), )) - - return columns - -"""Running BigGIM""" -def call_biggim(genes, tissues, limit=1000000, average_columns=False, query_id2=False, return_genes=False, N=250): - """ - Parameters - ---------- - genes : list of str - - columns : list of str - - limit : int - - query_id2 : bool - If query_id2, the genes are duplicated for the ids2 field. - This forces biggim to return all interactions within genes. - """ - - columns = get_columns(tissues,table='BigGIM_70_v1') - print(columns) - - gene_list = ','.join(genes) - - example_query = { - "restriction_gt": ','.join(["%s,-2.0" % (c,) for c in columns]), - "table": "BigGIM_70_v1", - "columns": ','.join(columns), - "ids1": gene_list, - "limit": limit, - "average_columns": average_columns, - } - - if query_id2: - example_query["ids2"] = gene_list - - try: - query_submit = get('biggim/query', data=example_query) - jprint(query_submit) - except requests.HTTPError as e: - print(e) - - jprint(e.response.json()) - - error_counter = 0 - try: - while True: - try: - query_status = get('biggim/status/%s' % (query_submit['request_id'],)) - jprint(query_status) - - if query_status['status'] != 'running': - # query has finished - break - else: - time.sleep(5) - print("Checking again") - except requests.HTTPError as e: - print(e) - time.sleep(5) - error_counter += 1 - if error_counter > 3: - print("Giving up") - raise - else: - print("Trying again.") - except requests.HTTPError as e: - print(e) - - jprint(e.response.json()) - - result = pandas.concat(map(pandas.read_csv, query_status['request_uri'])) - result = result.iloc[:,1:] - - if return_genes: - df = result - print(df) - df = df.sort_values(by='mean',ascending=False) - df = df.reset_index() - print(df) - del df['index'] - gene_list = genes - i = len(gene_list) - for index, row in df.iterrows(): - if i>=(len(genes)+N): - break - gene_list.append(row['Gene1']) - gene_list.append(row['Gene2']) - gene_list = list(set(gene_list)) - i = len(gene_list) - - gene_list = [int(x) for x in gene_list] - gene_list = [str(x) for x in gene_list] - gene_list.sort() - - return gene_list - - return result - -"""Helpers""" - -def get_column(some_tissue, table='BigGIM_70_v1'): - columns = [] - try: - # query - md = get('metadata/tissue/%s' % some_tissue) - for st in md['substudies']: - for column in st.get('columns',[]): - #filter table - if column.get('table', {}).get('name', None) == table: - #filter r(spearman) -# if column.get('interactions_type',None) == 'Spearman Rank Correlation Coefficient': - #get the name of the columns - if column.get('name', None) is not None: - columns.append(column.get('name')) - except HTTPError as e: - #if 404 error, it could not find the tissue, otherwise something bad happend - if e.args[0].find('404') == -1: - raise - return columns - - - - - - - -# A few helper functions for posting and getting api requests -#a couple of simple helper functions -def post(endpoint, data={}, base_url=base_url): - req = requests.post('%s/%s' % (base_url,endpoint), data=data) - req.raise_for_status() - return req.json() - -def get(endpoint, data={}, base_url=base_url): - req = requests.get('%s/%s' % (base_url,endpoint), data=data) - try: - req.raise_for_status() - except requests.HTTPError as e: - print("Sent: GET %s?%s" % (req.request.url,req.request.body)) - if e.response.status_code == 400: - print(e.response) - jprint(e.response.json()) - raise - print("Sent: GET %s?%s" % (req.request.url,req.request.body)) - return req.json() - -def jprint(dct): - print(json.dumps(dct, indent=2)) - -def wrapper(endpoint, data={}, base_url=base_url): - try: - response = get(endpoint, data, base_url) - jprint(response) - except requests.HTTPError as e: - - print(e) - if e.response.status_code == 400: - jprint(e.response.json()) - raise - try: - ctr = 1 - while True: - query_status = get('%s/status/%s'% (endpoint.split('/')[0],response['request_id'],)) - jprint(query_status) - if query_status['status'] !='running': - # query has finished - break - else: - time.sleep(ctr) - ctr += 5 - #linear backoff - print("Checking again") - except requests.HTTPError as e: - print(e) - if e.response.status_code == 400: - jprint(e.response.json()) - raise - return pandas.concat(map(pandas.read_csv, query_status['request_uri'])) \ No newline at end of file