Skip to content

Commit

Permalink
Merge branch 'release/0.3.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
emanuel-schmid committed Jun 2, 2023
2 parents 71ab4f0 + 78b05d8 commit 381e000
Show file tree
Hide file tree
Showing 3 changed files with 132 additions and 35 deletions.
129 changes: 104 additions & 25 deletions envirest/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from requests import Session
from getpass import getpass


DEFAULT_HOST = "envipath.org"
ANONYMOUS = "anonymous"

Expand Down Expand Up @@ -37,10 +38,10 @@ def delete(self, url):
url = url.replace("http://", "https://")
r = self.session.delete(url, verify=self.verify)
if r.status_code > 299:
raise Exception("Failed with status code {}, text:\n{}".format(r.status_code, r.text.decode()))
raise Exception("Failed with status code {}, text:\n{}".format(r.status_code, r.text))

def get(self, url):
return getjson(self.session, url, self.verify, secure=self.secure)
def get(self, url, timeout=None):
return getjson(self.session, url, self.verify, secure=self.secure, timeout=timeout)

def post(self, url, data):
return post(self.session, url, data, self.verify, secure=self.secure)
Expand Down Expand Up @@ -73,25 +74,30 @@ def addscenario(self, objecturl, scenariourl):
return addScenario(session=self.session, url=objecturl,
scenario=scenariourl, verify=self.verify, secure=self.secure)

def updatescenario(self, scenariourl,
def updatescenario(self, scenariourl, plainname=None, description=None, date=None,
soilsource=None, soiltexture1=None, soiltexture2=None,
soilclassificationsystem=None, redox=None, acidity=None, temperature=None,
waterstoragecapacity=None, humidity=None, omcontent=None, cec=None, bulkdens=None,
biomass=None, spikecompoundsmiles=None, spikeconcentration=None, halflife=None,
minormajor=None, proposedintermediate=None, confidencelevel=None,
referringscenario=None, enzyme=None,
referringscenario=None, enzyme=None, organism=None,
infotypes=[], infodata={}):
return updateScenario(self.session, scenario=scenariourl,
return updateScenario(self.session, scenario=scenariourl, plainname=plainname, description=description, date=date,
soilsource=soilsource, soiltexture1=soiltexture1, soiltexture2=soiltexture2,
soilclassificationsystem=soilclassificationsystem, redox=redox, acidity=acidity,
temperature=temperature, waterstoragecapacity=waterstoragecapacity, humidity=humidity,
omcontent=omcontent, cec=cec, bulkdens=bulkdens, biomass=biomass,
spikecompoundsmiles=spikecompoundsmiles, spikeconcentration=spikeconcentration,
halflife=halflife, minormajor=minormajor, proposedintermediate=proposedintermediate,
confidencelevel=confidencelevel, referringscenario=referringscenario, enzyme=enzyme,
confidencelevel=confidencelevel, referringscenario=referringscenario,
enzyme=enzyme, organism=organism,
addInfoTypes=infotypes, addInfoInput=infodata,
verify=self.verify, secure=self.secure)

def removeAddInf(self, scenariourl, aiurl):
return remove_addinf(self.session, scenario_url=scenariourl, ai_url=aiurl,
verify=self.verify, secure=self.secure)

def createrule(self, packageurl,
ruletype='SIMPLE',
smirks=None,
Expand Down Expand Up @@ -201,7 +207,8 @@ def createscenario(self, packageurl,
proposedintermediate=None,
confidencelevel=None,
referringscenario=None,
enzyme=None):
enzyme=None,
organism=None):
return createScenario(self.session, packageurl,
plainname=plainname,
description=description,
Expand All @@ -228,6 +235,7 @@ def createscenario(self, packageurl,
halflife=halflife,
referringscenario=referringscenario,
enzyme=enzyme,
organism=organism,
verify=self.verify,
secure=self.secure)

Expand Down Expand Up @@ -263,9 +271,9 @@ def add_ec_number(self, rule_url,
verify=self.verify, secure=self.secure)

def get_enviLink(self, package=None, rule=None):
if not package:
if package is None:
package_url = self.findpackage('EAWAG-BBD')
elif package.starts_with(self.hosturl):
elif package.startswith(self.hosturl):
package_url = package
else:
package_url = self.findpackage(package)
Expand Down Expand Up @@ -310,6 +318,9 @@ def get_enviLink(self, package=None, rule=None):

return envi_links

def update_pathway(self, pathway_url, **kwargs):
return update_pathway(self.session, pathway_url, **kwargs)


def login(hosturl, username, password, verify=True, secure=False):
session = Session()
Expand All @@ -323,9 +334,8 @@ def login(hosturl, username, password, verify=True, secure=False):
if secure:
hosturl = hosturl.replace("http://", "https://")

response = session.post(hosturl, data=data, headers=TEXTHEADERS, allow_redirects=True,
session.post(hosturl, data=data, headers=TEXTHEADERS, allow_redirects=True,
verify=verify)
#print(response)
return session


Expand Down Expand Up @@ -370,16 +380,16 @@ def commonparser(prog, description):
return parser


def getjson(session, url, verify=True, secure=False):
def getjson(session, url, verify=True, secure=False, timeout=None):
if secure:
url = url.replace("http://", "https://")
r = session.get(url, headers=JSONHEADERS, allow_redirects=True,
verify=verify)
verify=verify, timeout=timeout)
return r.json()


def get(session, url, verify=True, secure=False):
return getjson(session=session, url=url, verify=verify, secure=secure)
def get(session, url, verify=True, secure=False, timeout=None):
return getjson(session=session, url=url, verify=verify, secure=secure, timeout=timeout)


def post(session, url, data, verify=True, secure=False):
Expand All @@ -399,7 +409,6 @@ def rename(session, object, newname, verify=True, secure=False):
r = session.post(url, data=data, headers=JSONHEADERS, allow_redirects=True,
verify=verify)
if r.json().get("name") != newname:
print(r.json())
raise Exception("renaming to {} failed for {}".format(newname, object))


Expand Down Expand Up @@ -440,16 +449,27 @@ def runRule(session, ruleurl, smiles, verify=True, secure=False):
return r.content.decode().strip().split("\n")


def updateScenario(session, scenario, soilsource=None, soiltexture1=None, soiltexture2=None,
def updateScenario(session, scenario, plainname=None, description=None, date=None,
soilsource=None, soiltexture1=None, soiltexture2=None,
soilclassificationsystem=None, redox=None, acidity=None, temperature=None,
waterstoragecapacity=None, humidity=None, omcontent=None, cec=None, bulkdens=None,
biomass=None, spikecompoundsmiles=None, spikeconcentration=None, halflife=None,
minormajor=None, proposedintermediate=None, confidencelevel=None, referringscenario=None, enzyme=None,
minormajor=None, proposedintermediate=None, confidencelevel=None, referringscenario=None,
enzyme=None, organism=None,
addInfoTypes=[], addInfoInput={}, verify=True, secure=False):
url = scenario
if secure:
url = url.replace("http://", "https://")
data = {"updateScenario": "true"}

(year, month, day) = date.split('-') if date else (None, None, None)
data = {
"updateScenario": "true",
"scenarioName": plainname,
"scenarioDescription": description,
"dateYear": year,
"dateMonth": month,
"dateDay": day,
}
addinfos = collectData(data,
soilsource=soilsource,
soiltexture1=soiltexture1,
Expand All @@ -471,7 +491,8 @@ def updateScenario(session, scenario, soilsource=None, soiltexture1=None, soilte
proposedintermediate=proposedintermediate,
confidencelevel=confidencelevel,
referringscenario=referringscenario,
enzyme=enzyme)
enzyme=enzyme,
organism=organism)
for k,v in addInfoInput.items():
data[k] = v
if addinfos:
Expand Down Expand Up @@ -581,18 +602,22 @@ def createScenario(
referringscenario=None,

enzyme=None,
organism=None,

verify=True,
secure=False):

url = package+"/scenario"
if secure:
url = url.replace("http://", "https://")
year, month, day = studydate.split("-")
data = {
#scenario
'studyname': plainname,
'studydescription': description,
'date': studydate,
'dateYear': year,
'dateMonth': month,
'dateDay': day,
'type': scenariotype,
}
addinfos = collectData(data=data,
Expand All @@ -616,7 +641,8 @@ def createScenario(
proposedintermediate=proposedintermediate,
confidencelevel=confidencelevel,
referringscenario=referringscenario,
enzyme=enzyme)
enzyme=enzyme,
organism=organism)

# count the blessings
if addinfos:
Expand Down Expand Up @@ -652,7 +678,8 @@ def collectData(data,
proposedintermediate=None,
confidencelevel=None,
referringscenario=None,
enzyme=None):
enzyme=None,
organism=None):

addinfos = []

Expand Down Expand Up @@ -790,6 +817,10 @@ def collectData(data,
data['enzymeName'] = enzyme['name']
data['enzymeECNumber'] = enzyme['ECNumber']

if organism:
addinfos.append('initorganism')
data['organism'] = organism

return addinfos


Expand Down Expand Up @@ -946,7 +977,7 @@ def predictPathway(session, package_url, root_smiles, settings_url=None, hangon=
break
import time
time.sleep(5.0)
pw = getjson(session, pwurl, verify=verify, secure=secure)
pw = getjson(session, pwurl, verify=verify, secure=secure, timeout=None)

return pw

Expand Down Expand Up @@ -1088,10 +1119,31 @@ def _post_ec_number(evidence, description, url, mut_data):


def remove_ec_number(session, eclink_url, verify=True, secure=False):
pieces = eclink_url.split('/')
try:
assert len(pieces) == 9
assert pieces[7] == 'enzymelink'
assert pieces[5] in ['parallel-rule', 'sequential-rule', 'simple-rule']
except AssertionError:
raise ValueError("{} is not part of enviLink".format(eclink_url))

if secure: eclink_url = eclink_url.replace("http://", "https://")
session.delete(eclink_url, headers=JSONHEADERS, verify=verify)


def remove_addinf(session, scenario_url, ai_url, verify=True, secure=False):
data={
'hidden': 'delete',
'aiUri': ai_url,
}
if secure: scenario_url = scenario_url.replace("http://", "https://")
r = session.post(scenario_url, headers=JSONHEADERS, data=data, verify=verify)
if r.status_code < 300:
return r.json()
else:
raise Exception("Failed with status code {}, text:\n{}".format(r.status_code, r.text))


def updateReaction(session, reaction_url,
name=None,
alias=None,
Expand Down Expand Up @@ -1138,3 +1190,30 @@ def createReaction(session, package_url,

response = session.post("{}/reaction".format(package_url), data=data, headers=JSONHEADERS, verify=verify)
return respond_or_raise(response)


def url_format(text):
return text\
.replace("\n", '<br>')\
.encode('UTF-8')


def update_pathway(session, pathway_url, description=None, name=None, **kwargs):
headers = JSONHEADERS.copy()
headers["referer"] = pathway_url

params = kwargs

if description:
params['pathwayDescription'] = url_format(description)

if name:
params['pathwayName'] = url_format(name)

r = session.post(pathway_url, params=params,
headers=headers, allow_redirects=True, verify=False)

if r.status_code == 200:
return r.json()
else:
raise Exception(r.content.decode())
36 changes: 27 additions & 9 deletions envirest_test/client_test.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import unittest
import re
from requests.exceptions import ReadTimeout

from envirest import EnviPathClient
from getpass import getpass


USER = 'anonymous'
TESTHOST = 'envipath.org:8181'
PACKAGE = 'anonymous'

DIOXANE_PW = 'https://envipath.org/package/32de3cf4-e3e6-4168-956e-32fa5ddb0ce1/pathway/19a53ddd-7bbe-43b3-bd56-c1c35302d185'

class MyTestCase(unittest.TestCase):

class PostTestCase(unittest.TestCase):

def setUp(self):
self.client = EnviPathClient(host=TESTHOST, username=USER, secure=False, verify=False)
self.package = self.client.findpackage(PACKAGE)

def test_scenario(self):

scenariourl = self.client.createscenario(self.package, halflife={
'lower': 0,
'upper': 0,
Expand All @@ -27,8 +29,9 @@ def test_scenario(self):
'fit': ''
})

for lower, upper, source, comment, model, fit in [(2.5, 2.5, '', 'some comment; some more', 'SFO', 'chi2'),
('4.0E-12', 2.6, '', 'some comment; some more', 'SFO+', '')]:
for lower, upper, source, comment, model, fit in [
(2.5, 2.5, '', 'some comment; some more', 'SFO', 'chi2'),
('4.0E-12', 2.6, '', 'some comment; some more', 'SFO+', '')]:

whatyouget = self.client.updatescenario(scenariourl, halflife={
'lower': lower,
Expand All @@ -52,17 +55,32 @@ def test_scenario(self):
def test_reaction(self):
rule = self.client.createrule(self.package, smirks='[Pb]>>[Au]')['id']
reaction = self.client.createreaction(self.package, smirks='[Pb]>>[Au]')['id']
updated = self.client.updaterreaction(reaction, name='the little alchemist', related_rule=rule)
updated = self.client.updaterreaction(reaction,
name='the little alchemist', related_rule=rule)
assert updated['rules'][0]['id'] == rule
assert updated['name'] == 'the little alchemist'
assert updated['smirks'] == '[Pb]>>[Au]'
self.client.delete(reaction)
self.client.delete(rule)

def test_enviLink(self):

class GetTestCase(unittest.TestCase):
"""Testing GET calls on the productive server
"""

def test_envi_link(self):
"""check whether get_enviLink is correct"""
client = EnviPathClient('envipath.org')
assert len(client.get_enviLink(rule='bt0028')) == 1

self.assertEqual(len(client.get_enviLink(rule='bt0028')), 1)

def test_timeout(self):
"""check timeout functionality for plain get calls"""
client = EnviPathClient('envipath.org')
with self.assertRaises(ReadTimeout):
client.get(DIOXANE_PW, 0.1)
dpw = client.get(DIOXANE_PW, 10)
self.assertEqual(len(dpw['nodes']), 12)


if __name__ == '__main__':
unittest.main()
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from setuptools import setup

setup(name='envipath-api',
version='0.2.0',
version='0.3.0',
description="wrapper for rest calls to envipath",
author='Emanuel Schmid',
author_email='[email protected]',
Expand Down

0 comments on commit 381e000

Please sign in to comment.