Commit 445f1a20 authored by Marco Govoni's avatar Marco Govoni
Browse files


parent 828d0564
......@@ -16,7 +16,8 @@ setup(name='westpy',
python_requires='>=2.7, >=3.0, !=3.0.*, !=3.1.*, !=3.2.*, <4',
import json
import requests
class Connection(object):
"""Class for setting up the Connection to the Rest API Server.
>>> from westpy import *
>>> session = Connection("emailId")
def __init__(self,emailId=None) :
self.output = {}
response = None
if emailId:
self.emailId = str(emailId)
data = {'emailId':str(emailId),'sessionTime':str(600)}
output ="", data=json.dumps(data))
response = json.loads(output.text)
except Exception as e:
print('The West Rest API is not responding, Please try again later',e)
if response:
if "Error" in response:
print("Execution failed with the following error \n",response['Error'])
return None
print("Check the inbox/spam folder of your email and click on link to activate session")
self.output = response
print('The West Rest API response to longer than usual, Please try again later')
print("Email Id is mandatory to establish Connection")
def getOutput(self):
"""returns the token to setup the session.
if self.output:
return self.output
raise ValueError("No Email id found")
def stop(self):
"""stops the executable using the token
>>> session = Session("emailId")
>>> session, "pw" )
>>> session.stop()
headers = {'Content-Type':'application/json; charset=utf-8','emailId':self.output['emailId'],'token':self.output['token']}
response = requests.get("", headers=headers, timeout=None)
except Exception as e:
print('The West Rest API response to longer than usual, Please try again later',e)
return json.loads(response.text)
\ No newline at end of file
......@@ -7,6 +7,7 @@ from westpy.geometry import *
from westpy.groundState import *
from westpy.dataContainer import *
from westpy.electronicStructure import *
from westpy.Connection import *
__version__ = '3.1.0'
from __future__ import print_function
import requests
import json
from ast import literal_eval
class GroundState() :
"""Class for representing a ground state calculation with DFT.
......@@ -33,7 +36,8 @@ class GroundState() :
self.nempty = 0
self.kmesh = "gamma"
self.isolated = False
self.spin = {}
self.spin = {}
self.inputFile = ""
def setNempty(self,nempty) :
"""Sets the number of empty bands.
......@@ -175,6 +179,7 @@ class GroundState() :
print("Generated file: ", fname )
self.inputFile = fname
else :
print("Cannot generate input for QuantumEspresso, pseudo are not upf.")
......@@ -258,4 +263,90 @@ class GroundState() :
.. note:: You can use this method to add either upf or xml pseudopotentials. However it is forbidded to mix them.
def run(self,session,executable=None,inputFile=None,outputFile=None,number_of_cores=2) :
"""runs the executable using rest api remotely..
:param session: object of instance Connection
:type symbol: Session
:param executable: name of executable
:type executable: string
:param executable: name of input file
:type executable: string
:param executable: name of output file
:type executable: string
:param executable: number of cores to run in
:type executable: int
>>> session = Session("emailId")
>>> session, "pw" )
>>> session, "wstat" )
>>> session, "pw", "", "pw.out", 3 )
from westpy import Connection
assert( isinstance(session,Connection))
download_urls = []
output_dict = {}
if executable and ("pw" in str(executable).lower() or "wstat" in str(executable).lower() or "wfreq" in str(executable).lower()) :
if inputFile is None:
inputFile = str(executable)+".in"
if outputFile is None:
outputFile = str(executable)+".out"
for key in self.geom.species.keys() :
resturl = ""
output = self.__runExecutable(executable,resturl,inputFile,session.getOutput(),download_urls,str(number_of_cores))
output_json = json.loads(output)
if "Error" in output_json:
print("Execution failed with the following error \n",output_json['Error'])
return None
elif "JOB DONE." not in str(output_json['output']).strip():
print("MPI execution failed with the following error: \n"+str(output))
return None
output_data = str(output_json['output']).strip()
if "pw" in executable:
output_dict = json.loads(output_json['output_dict'])
output_dict = output_json['output_dict']
with open(outputFile, "w") as file :
except Exception as e:
print("Session Expired! Invalid Request sent, Please recreate session and recheck your input. \n"+ e)
return None
raise ValueError("Invalid Executable")
print("Generated ",outputFile)
return output_dict
def __runExecutable(self,executable,resturl,input_file,session_values,download_urls,number_of_cores) :
"""runs the executable using rest api remotely.
file_content = ""
with open(input_file,'r') as f :
for line in f :
file_content = file_content + line + "\\n"
except FileNotFoundError:
error = "Could not find "+ input_file + ". \n Generate input file "+ input_file+" and try again."
return None
body = {'urls':download_urls,'file':file_content,'cmd_timeout':'600','script_type':str(executable),'no_of_cores':number_of_cores}
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('utf-8') # needs to be bytes
headers = {'Content-Type':'application/json; charset=utf-8','emailId':session_values['emailId'],'token':session_values['token']}
response = ""
response =, data = jsondataasbytes, headers=headers, timeout=None)
return response.text
except Exception as e:
print('The West Rest API response to longer than usual, Please try again later',e)
return None
return None
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment