mgltools-webservices-1.5.7~rc1~cvs.20130519/ 0000755 0001750 0001750 00000000000 12146216236 017555 5 ustar debian debian mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/ 0000755 0001750 0001750 00000000000 12146216237 021777 5 ustar debian debian mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/VisionInterface/ 0000755 0001750 0001750 00000000000 12146216240 025061 5 ustar debian debian mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/VisionInterface/download_rec.py 0000644 0001750 0001750 00000001736 11412523335 030103 0 ustar debian debian import os
import urlparse
import urllib2
from binaries import findExecModule
def recursive_download(url=None, local_dir=None):
urldir = False
if url == "" or local_dir == "":
import sys
print "ERROR: input URL or Directory empty"
sys.exit()
wget = findExecModule('wget')
if url.endswith('/'):
urldir = True
else:
urldir = True
tmp_url = url + '/'
try:
resp = urllib2.urlopen(tmp_url)
resp.close()
except urllib2.URLError, e:
urldir = False
sep = ";"
if urldir == True:
cutdirs = urlparse.urlparse(url).path.count('/')
if url.endswith("/"):
cutdirs = cutdirs - 1
wget = wget + " -np -nH -r --cut-dirs=" + str(cutdirs)
else:
wget = wget + " "
# TBD, add sep
cmd = "cd " + local_dir + sep + " " + wget + " " + url
os.system(cmd)
mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/VisionInterface/WSNodes.py 0000644 0001750 0001750 00000076242 12003371761 026772 0 ustar debian debian # $Header: /opt/cvs/WebServices/VisionInterface/WSNodes.py,v 1.75 2012/07/24 01:01:37 sanner Exp $
#
# $Id: WSNodes.py,v 1.75 2012/07/24 01:01:37 sanner Exp $
import os, os.path, time, urllib, tkMessageBox, webbrowser
import xml.dom.minidom
import shutil
from NetworkEditor.items import NetworkNode, FunctionNode
from Vision import UserLibBuild
from urlparse import urlparse
from WebServices.OpalCache import OpalCache
from mglutil.util.packageFilePath import getResourceFolderWithVersion
from urlparse import urlparse
from time import strftime
from datetime import datetime
def Get_Opal_WS(url):
"""
Retruns the list of available Opal Web Services
output - list of Opal Web Services
"""
if not url:
tkMessageBox.showerror("Error!","No URL was provided")
return
services = []
if url.find("/opal2") != -1:
#this is opal2 let's use the registry
url = url + "/opalServices.xml"
opener = urllib.FancyURLopener({})
socket = opener.open(url)
text = socket.read()
feed = xml.dom.minidom.parseString(text)
for entry in feed.getElementsByTagName('entry'):
#getting the link element
link = entry.getElementsByTagName('link')[0]
service = link.getAttribute('href')
services.append(str(service))
else:
#this is opal1
url = url + '/servlet/AxisServlet'
#print "url", url
opener = urllib.FancyURLopener({})
servlet = opener.open(url)
text = servlet.read()
text = text.split('
')
text = text[1:]
for line in text[:-1]:
#print "Line: " + line
tmp_text = line.split(url)
#print "tmp_text: " + str(tmp_text)
port = tmp_text[-1].split('?wsdl')
#print "port: " + str(port)
wsdl_url = port[0].split('href="')[-1] + "?wsdl"
#print "wsdl_url: " + str(wsdl_url)
if ( isOpalService(wsdl_url) ):
#print "adding a service: " + str(wsdl_url)
services.append(wsdl_url[:-5])
#else: do nothing just skeep it
return services
def isOpalService(wsdl_url):
"""
Given a wsdl_url which point to a wsdl it return true
if the wsdl pointed by the url is a Opal Service
"""
filehandle = urllib.urlopen(wsdl_url)
string = filehandle.read()
if ( string.find("wsdl:service name=\"AppService\"") != -1 ):
return True
else:
return False
def isVersionValid(version):
"""this function check that the input string version
is a valid version number, which means that it should
be in the form of
....etc.
"""
import math
numbers = version.split(".")
decimalCounter = 0
returnValue = 0
for i in reversed(numbers):
try:
number = int(i)
except:
return 0
#we count under the base 100 because sometime
#version number are bigger than 10
returnValue = returnValue + number * math.pow(100,decimalCounter)
decimalCounter = decimalCounter + 1
return int(returnValue)
def addOpalServerAsCategory(host, replace=True):
"""
Adds Category named `host` to Web Services Libary.
replace=True: If the Nodes in `host` Category already exist, this function updates them.
"""
if replace is False and wslib.libraryDescr.has_key(host):
# this category is already loaded
return
oc = OpalCache()
mglrd = getResourceFolderWithVersion()
mglwsdir = os.path.join(mglrd, "ws")
inactivedir = os.path.join(mglwsdir, "inactives")
hn = urlparse(host).hostname
port = urlparse(host).port
if port != None:
hn = hn + '+' + str(port)
inactivehostdir = os.path.join(inactivedir, hn)
host_cache_dir = os.path.join(mglwsdir, hn)
if not os.path.exists(mglwsdir):
os.mkdir(mglwsdir)
if not os.path.exists(inactivedir):
os.mkdir(inactivedir)
if not os.path.exists(inactivehostdir):
os.mkdir(inactivehostdir)
try:
services = Get_Opal_WS(host) # get list of opal services on host
active_services = []
cached_services = []
for s in services:
sn = os.path.basename(s)
active_services.append(sn)
# old inactive services that are now active
old_inactives = os.listdir(inactivehostdir)
now_actives = set(old_inactives) & set(active_services)
for s in now_actives:
os.remove(os.path.join(inactivehostdir, s))
if os.path.exists(host_cache_dir):
cached_services = os.listdir(host_cache_dir)
inactive_services = set(cached_services) - set(active_services)
for s in inactive_services:
iaf = os.path.join(inactivehostdir, s)
if not os.path.exists(iaf):
shutil.copy(os.path.join(host_cache_dir, s), iaf)
new_inactives = os.listdir(inactivehostdir)
for s in new_inactives:
print "*** [WARNING]: " + host + '/services/' + s + " IS NO LONGER AVAILBLE ON THE SERVER!"
except: # no internet connection?
print "WARNING: Loading services for " + host + " from cache"
services = oc.getServicesFromCache(host, mglwsdir)
for s in services:
try:
if not(os.path.exists(mglwsdir)):
os.mkdir(mglwsdir)
oc.writeCache(s, mglwsdir)
except:
pass
if not services:
print "No Opal web service is found on ", host
return
#print "services ", services
#short_name = host.split('http://')[-1]
#short_name = short_name.split('.')
#short_name = short_name[0] + "." + short_name[1]
for service in services:
serviceNameOriginal = service.split('/')[-1]
serviceName = serviceNameOriginal.replace('.','_')
serverName = urlparse(service)[1]
serverName = serverName.replace('.','_')
serverName = serverName.split(':')[0]
serverName = serverName.replace('-', '_')
serviceOpalWrap = serviceName + "_" + serverName
#print serviceOpalWrap
if wslib.libraryDescr.has_key(host):
for node in wslib.libraryDescr[host]['nodes']:
if node.name == serviceOpalWrap:
wslib.deleteNodeFromCategoryFrame(host, FunctionNode, nodeName=serviceOpalWrap)
from WebServices.OpalWrapper import OpalWrapper
wrapper = OpalWrapper()
try:
wrap = wrapper.generate(service) #generate the python wrapper class for the service
except:
wrap = wrapper.generate(service, False)
if wrap is not None:
#mod = __import__('__main__')
#for modItemName in set(dir(mod)).difference(dir()):
# locals()[modItemName] = getattr(mod, modItemName)
from mglutil.util.misc import importMainOrIPythonMain
lMainDict = importMainOrIPythonMain()
for modItemName in set(lMainDict).difference(dir()):
locals()[modItemName] = lMainDict[modItemName]
exec(wrap)
#print "wrap: ", wrap
lServiceOpalClass = eval(serviceOpalWrap)
lServiceOpalClass.sourceCodeWrap = wrap
# sourceCodeWrap is the source of the Python class wrapping this service
# An instance of this object will be available in the __main__ scope
# The source code can be obtained from an instance of this service in a Vision
# network as follows: node.function.sourceCodeWrap
# ALternatively one can type .sourceCodeWrap in the Python shell
# e.g. print Pdb2pqrOpalService_ws_nbcr_net.sourceCodeWrap
#checking the service name if it contains the version or not
versionStr = serviceNameOriginal.split("_")[-1]
versionInt = isVersionValid(versionStr)
if ( versionInt > 0 ):
#ok we have a version in the serviceName
#let's update it in the lServiceOpalClass
serviceNameNoVersion = serviceNameOriginal.rstrip("_" + versionStr)
serviceNameNoVersion.replace('.','_')
#print "Setting service " + serviceNameNoVersion + " with version " + str( versionInt)
lServiceOpalClass.serviceName = serviceNameNoVersion
else:
#we don't have a version, let's just use the serviceName
#as it is...
#print "Setting service with no version " + serviceName
lServiceOpalClass.serviceName = serviceName
lServiceOpalClass.version = versionInt
lServiceOpalClass.serviceOriginalName = serviceNameOriginal.replace('.','_')
#setattr(mod, serviceOpalWrap, lServiceOpalClass)
lMainDict[serviceOpalWrap] = lServiceOpalClass
# the python wrapper class is callable
# here we create a Vision FunctionNode to add this Python object
# to the Vision library
from WebServices.OpalUtil import OpalWSNode
wslib.addNode(OpalWSNode, serviceOpalWrap, host,
kw={'functionOrString':serviceOpalWrap,
'host':host
}
)
class GetWSNode(NetworkNode):
"""Drug and drop 'Load WS' node into a network to load web services.
Input Port: host (bound to ComboBox widget)
Change to host as needed to load additional web services.
"""
def __init__(self, name='WS_List', host=None, **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
self.inNodeWidgetsVisibleByDefault = True
self.widgetDescr['host'] = {
'class':'NEComboBox', 'master':'node',
'choices':['http://ws.nbcr.net/opal2',
'http://kryptonite.ucsd.edu/opal2',
#'http://nbcrdemo.ucsd.edu:8080/opal',
'http://krusty.ucsd.edu:8081/opal2',
],
'initialValue':'http://ws.nbcr.net/opal2',
'entryfield_entry_width':30,
'labelGridCfg':{'sticky':'w'},
'widgetGridCfg':{'sticky':'w', 'columnspan':2},
'labelCfg':{'text':'Host:'},
}
self.inputPortsDescr.append( {'name':'host', 'datatype':'string'} )
code = """def doit(self, host):
addOpalServerAsCategory(host)
"""
if code:
self.setFunction(code)
class OpalServiceNode(NetworkNode):
"""A generic Opal Web Service Node that extends NetworkEditor.items.NetworkNode
and impliments common functionalty among Opal Web Service Nodes.
http://nbcr.net/services/opal
"""
def __init__(self, service=None, **kw):
apply( NetworkNode.__init__, (self,), kw )
self.inNodeWidgetsVisibleByDefault = True
from mglutil.web.services.AppService_client import AppServiceLocator, launchJobRequest, \
getOutputsRequest, queryStatusRequest
from mglutil.web.services.AppService_types import ns0
self.appLocator = AppServiceLocator()
self.req = launchJobRequest()
self.inputFile = ns0.InputFileType_Def('inputFile')
self.widgetDescr['outputURL'] = {
'class':'NECheckButton', 'master':'ParamPanel',
'labelCfg':{'text':'output URL'},
}
self.inputPortsDescr.append(datatype='boolean', name='outputURL')
self.outputPortsDescr.append(datatype='string', name='URL')
if service:
self.constrkw['service'] = `service`
self.service = service
self.host = self.service[:7+self.service[7:].find('/')] #to get rid of part after http://ws.nbcr.net:8080
def runws(self):
"""
Runs Opal Web Service on a given port:
Returns resp if succeeded or
prints obID and resp._baseURL message if failed, and returns ""
"""
appServicePort = self.appLocator.getAppServicePort(self.service)
try:
self.resp = appServicePort.launchJob(self.req)
jobID = self.resp._jobID
self.resp = appServicePort.queryStatus(queryStatusRequest(jobID))
except Exception, inst:
from ZSI import FaultException
if isinstance(inst, FaultException):
tmp_str = inst.fault.AsSOAP()
tmp_str = tmp_str.split('')
tmp_str = tmp_str[1].split('')
if len(tmp_str[0]) > 500:
print tmp_str[0]
tmp_str[0] = tmp_str[0][0:500] + '...'
tkMessageBox.showerror("ERROR: ",tmp_str[0])
self.resp = None
return
while self.resp._code != 8:
time.sleep(1)
self.resp = appServicePort.queryStatus(queryStatusRequest(jobID))
if self.resp._code == 4:
print "jobID:",jobID, 'failed on', self.resp._baseURL
opener = urllib.FancyURLopener({})
errorMsg = opener.open(self.resp._baseURL+"/std.err").read()
tkMessageBox.showerror("Error!",errorMsg)
webbrowser.open(self.host + '/' + jobID)
return ""
self.outurl = self.host + '/' + jobID
self.resp = appServicePort.getOutputs(getOutputsRequest(jobID))
class pdb2pqrNode(OpalServiceNode):
"""Web Service for pdb2pqr
Input Ports
either
input_file: string that holds the path to the input file supported by Babel
or
input_mol: MolKit.Molecule instance
options: command line options (bound to Entry widget)
Output Ports
output_file_url: URL of the output file
"""
def __init__(self, name='pdb2pqr', service=None, **kw):
kw['name']=name
OpalServiceNode.__init__(self, service=service, **kw )
self.inputPortsDescr.append(datatype='string', name='input_file')
self.inputPortsDescr.append(datatype='Molecule', name='input_mol')
self.widgetDescr['options'] = {'class':'NEEntry', 'master':'node',
'labelCfg':{'text':'options:'},
'labelGridCfg':{'sticky':'e'},
'width':10,
}
self.inputPortsDescr.append( {'name':'options', 'datatype':'string',
'required':False})
self.widgetDescr['ff'] = {
'class':'NEComboBox', 'master':'node',
'choices':['amber', 'charmm', 'parse' ],
'fixedChoices':True,
'initialValue':'amber',
'entryfield_entry_width':7,
'labelCfg':{'text':'forcefield:'},
}
self.inputPortsDescr.append(datatype='string', name='ff')
self.outputPortsDescr.append(datatype='string', name='output_file_url')
code = """def doit(self, outputURL, input_file, input_mol, options, ff ):
if input_mol:
self.inputPorts[1].required = False
input_file_base = os.path.basename(input_mol.parser.filename)
self.inputFile._name = input_file_base
sampleFileString = ''
for line in input_mol.parser.allLines:
sampleFileString += line
else:
self.inputPorts[2].required = False
input_file_base = os.path.basename(input_file)
self.inputFile._name = input_file_base
sampleFile = open(input_file, 'r')
sampleFileString = sampleFile.read()
sampleFile.close()
options = options + ' --ff='+ff + ' ' + input_file_base + ' ' + input_file_base +'.pqr'
self.req._argList = options
inputFiles = []
self.inputFile._contents = sampleFileString
inputFiles.append(self.inputFile)
self.req._inputFile = inputFiles
self.runws()
output_file_url = None
if self.resp:
for files in self.resp._outputFile:
if files._url[-4:] == input_file_base +'.pqr':
output_file_url = files._url
if not output_file_url:
self.outputData(URL = self.outurl)
return
print outputURL, self.outurl
if not outputURL:
import urllib
opener = urllib.FancyURLopener({})
in_file = opener.open(output_file_url)
self.outputData(URL = self.outurl, output_file_url = in_file.read())
else:
self.outputData(URL = self.outurl, output_file_url=output_file_url)
"""
if code:
self.setFunction(code)
codeAfterConnect_input_mol = """def afterConnect(self, conn):
# self refers to the port
# conn is the connection that has been created
self.node.getInputPortByName('input_file').required = False
"""
self.inputPortsDescr[2]['afterConnect']= codeAfterConnect_input_mol
codeAfterConnect_input_file = """def afterConnect(self, conn):
# self refers to the port
# conn is the connection that has been created
self.node.getInputPortByName('input_mol').required = False
"""
self.inputPortsDescr[1]['afterConnect']= codeAfterConnect_input_file
from WebServices import checkURL
class DownloadNode(NetworkNode):
"""Downloads remote files from the URL.
Input Ports
url: URL for the remote file
Output Ports
output: string containing the contents of the remote file
"""
def __init__(self, name='Download', host = None, **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
self.widgetDescr['url'] = {'class':'NEEntry', 'master':'node',
'labelCfg':{'text':'URL'},
}
self.inputPortsDescr.append( {'name':'url', 'datatype':'string'} )
self.outputPortsDescr.append(datatype='string', name='output')
code = """def doit(self, url):
import time
from time import strftime
opener = urllib.FancyURLopener({})
try:
infile = opener.open(url)
except IOError:
s = -1
while s == -1:
try:
urllib.urlopen(url)
infile = opener.open(url)
s = 0
except IOError:
t = strftime("%Y-%m-%d %H:%M:%S", time.localtime())
cte = time.mktime(datetime.now().timetuple())
ete = cte + 30
print "WARNING: " + t + " cannot connect to " + url
print " Are you connected to the internet?"
print " Will try again in about 30 seconds"
while time.mktime(datetime.now().timetuple()) < ete:
if self.opalNode._vpe is not None:
self.opalNode._vpe.updateGuiCycle()
if net.execStatus == 'stop':
self.onStoppingExecution()
return None
time.sleep(30)
pass
self.outputData(output=infile.read())
"""
if code:
self.setFunction(code)
class DownloadToFileNode(NetworkNode):
"""Downloads the URL file to local machine.
Input Ports
url: URL for the remote file
filename: file name to save the remote file. Default is the remote file name.
overwrite: if checked - ovewrite existing file with the same name.
if not checked - give the file a unique file name.
Output Ports
output: local file path
"""
def __init__(self, name='DownloadToFile', host = None, **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
self.widgetDescr['url'] = {'class':'NEEntry', 'master':'node',
'width':16, 'labelCfg':{'text':'URL'},
}
self.widgetDescr['filename'] = {
'class':'NEEntryWithFileBrowser', 'master':'node', 'width':16,
'initialValue':'', 'lockedOnPort':False,
'labelCfg':{'text':'Filename: '}
}
self.widgetDescr['overwrite'] = {
'class':'NECheckButton', 'master':'node', 'initialValue':1,
'labelGridCfg':{'sticky':'w', 'columnspan':1},
'widgetGridCfg':{'sticky':'w'},
'labelCfg':{'text':'Overwrite'},
}
self.inputPortsDescr.append( {'name':'url', 'datatype':'string', 'required':'True'} )
self.inputPortsDescr.append( {'name':'filename', 'datatype':'string', 'required':'False'} )
self.inputPortsDescr.append( {'name':'overwrite', 'datatype':'int'} )
self.outputPortsDescr.append(datatype='string', name='filename')
code = """def doit(self, url, filename, overwrite):
import tempfile
import time
from time import strftime
if filename == None or filename == "":
filename = os.path.basename(url)
filename = os.path.abspath(filename)
if overwrite == 0 and os.path.exists(filename):
fdir = os.path.dirname(filename)
filename = tempfile.mktemp(prefix=filename+'.', dir=fdir)
opener = urllib.FancyURLopener({})
try:
infile = opener.open(url)
except IOError:
s = -1
while s == -1:
try:
urllib.urlopen(url)
infile = opener.open(url)
s = 0
except IOError:
t = strftime("%Y-%m-%d %H:%M:%S", time.localtime())
cte = time.mktime(datetime.now().timetuple())
ete = cte + 30
print "WARNING: " + t + " cannot connect to " + url
print " Are you connected to the internet?"
print " Will try again in about 30 seconds"
while time.mktime(datetime.now().timetuple()) < ete:
if self.opalNode._vpe is not None:
self.opalNode._vpe.updateGuiCycle()
if net.execStatus == 'stop':
self.onStoppingExecution()
return None
time.sleep(30)
pass
f = open(filename, 'w')
f.write(infile.read())
f.close()
self.outputData(filename=filename)
"""
if code:
self.setFunction(code)
class DownloadSaveDirNode(NetworkNode):
"""Downloads and saves all files from the URL directory.
Input Ports
url: URL for the remote directory
path: Path to downloaded directory on local machine.
cutdirs: Number of directories to cut for wget. Equivalent to the --cut-dirs option.
Output Ports
output: Local path to download remote directory to.
"""
def __init__(self, name='DownloadSaveDir', host = None, **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
self.widgetDescr['url'] = {'class':'NEEntry', 'master':'node',
'labelCfg':{'text':'URL'},
}
self.inputPortsDescr.append( {'name':'url', 'datatype':'string'} )
self.inputPortsDescr.append( {'name':'path', 'datatype':'string'} )
self.inputPortsDescr.append( {'name':'cutdirs', 'datatype':'string', 'required':False} )
self.outputPortsDescr.append(datatype='string', name='output')
code = """def doit(self, url, path, cutdirs):
from binaries import findExecModule
if os.name == 'dos' or os.name == 'nt':
wget = findExecModule('wget')
wget = '\"' + wget + '\"'
elif os.uname()[0] == "Darwin":
wget = findExecModule('wget')
else:
wget = "wget"
opener = urllib.FancyURLopener({})
if not os.path.exists(path):
os.mkdir(path)
if os.name == 'dos' or os.name == 'nt':
sep = '&&'
else:
sep = ';'
url.strip('''/''')
if cutdirs == None:
num_dirs = 1
else:
num_dirs = cutdirs
ddct = time.ctime(os.path.getmtime(path))
dflc = wget + ' --spider -r -l inf --no-remove-listing --no-parent --no-host-directories -nH --cut-dirs=''' + str(num_dirs) + ' ' + url
os.system(dflc + ' >& /tmp/spider.pig')
download_cmd = 'cd ' + path + ' ' + sep + ' ' + wget + ' -r -l inf --no-remove-listing --no-parent --no-host-directories -nH --cut-dirs=''' + str(num_dirs) + ' ' + url
print download_cmd
os.system(download_cmd)
ddnct = time.ctime(os.path.getmtime(path))
if ddct != ddnct:
self.outputData(output = path)
pass
# self.outputData(output=path)
"""
if code:
self.setFunction(code)
class GetMainURLNode(NetworkNode):
"""Get the directory URL of a remote file URL
Input Ports
url: URL for the remote file
Output Ports
newurl: string containing the directory URL of a remote file URL
"""
def __init__(self, name='Download', host = None, **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
self.widgetDescr['url'] = {'class':'NEEntry', 'master':'node',
'labelCfg':{'text':'URL'},
}
self.inputPortsDescr.append( {'name':'url', 'datatype':'string'} )
self.outputPortsDescr.append(datatype='string', name='newurl')
code = """def doit(self, url):
filename = url.split('/')[len(url.split('/'))-1]
nurl = url.strip(filename)
pass
self.outputData(newurl=nurl)
"""
if code:
self.setFunction(code)
class GetMainURLFromListNode(NetworkNode):
"""Get the Opal output main URL from a list of Opal result URLs
Input Ports
url: list of Opal output URLs for one particular job
Output Ports
newurl: string containing the directory URL of a remote file URL
"""
def __init__(self, name='Download', host = None, **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
self.widgetDescr['url'] = {'class':'NEEntry', 'master':'node',
'labelCfg':{'text':'URL'},
}
self.inputPortsDescr.append( {'name':'urls', 'datatype':'list'} )
self.outputPortsDescr.append(datatype='string', name='newurl')
code = """def doit(self, urls):
url = urls[0]
filename = url.split('/')[len(url.split('/'))-1]
nurl = url.strip(filename)
pass
self.outputData(newurl=nurl)
"""
if code:
self.setFunction(code)
class GetURLFromListNode(NetworkNode):
"""Get the first URL that matches the extension in the URL list.
Input Ports
urllist: list of urls
ext: extension
Output Ports
url: the first url that matches the extension in urllist
"""
def __init__(self, name='GetURLFromList', host = None, **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
self.widgetDescr['ext'] = {'class':'NEEntry', 'master':'node',
'width':8,
'labelCfg':{'text':'extension'},
}
self.inputPortsDescr.append( {'name':'urllist', 'datatype':'list'} )
self.inputPortsDescr.append( {'name':'ext', 'datatype':'string'} )
self.outputPortsDescr.append(datatype='string', name='url')
code = """def doit(self, urllist, ext):
ext = '.' + ext
found = False
for i in urllist:
if i.endswith(ext):
url = i
found = True
break
if found == False:
print "ERROR: No matching URL found in the list"
url = ""
pass
self.outputData(url=url)
"""
if code:
self.setFunction(code)
class IsURLNode(NetworkNode):
"""Returns true if input is an URL and false otherwise.
Input Ports
url_str: a string
Output Ports
is_url: true if input if an URL and false otherwise.
"""
def __init__(self, name='Download', host = None, **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
self.widgetDescr['url'] = {'class':'NEEntry', 'master':'node',
'labelCfg':{'text':'URL'},
}
self.inputPortsDescr.append( {'name':'url_str', 'datatype':'string'} )
self.outputPortsDescr.append(datatype='boolean', name='is_url')
code = """def doit(self, url_str):
from urlparse import urlparse
scheme = urlparse(url_str)[0]
pass
if scheme == "http" or scheme == "ftp" or url_str.find('www.') != -1 or url_str.find('.edu') != -1 or url_str.find('.com') != -1 or url_str.find('.org') != -1:
self.outputData(is_url=1)
else:
self.outputData(is_url=0)
"""
if code:
self.setFunction(code)
class ReplaceURLNode(NetworkNode):
"""Replace filename in the URL with a new filename
Input Ports
url: URL for the remote file
filename: new filename for the URL
Output Ports
newurl: string containing URL with old file name replaced with the new filename
"""
def __init__(self, name='Download', host = None, **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
self.widgetDescr['url'] = {'class':'NEEntry', 'master':'node',
'labelCfg':{'text':'URL'},
}
self.inputPortsDescr.append( {'name':'url', 'datatype':'string'} )
self.inputPortsDescr.append( {'name':'newfilename', 'datatype':'string'} )
self.outputPortsDescr.append(datatype='string', name='newurl')
code = """def doit(self, url, newfilename):
oldfilename = url.split('/')[len(url.split('/'))-1]
nurl = url.strip(oldfilename) + newfilename
pass
self.outputData(newurl=nurl)
"""
if code:
self.setFunction(code)
class WebBrowserNode(NetworkNode):
"""Opens a URL with default Web Browser.
Input Ports
url: URL
"""
def __init__(self, name='Download', host = None, **kw):
kw['name'] = name
apply( NetworkNode.__init__, (self,), kw )
self.widgetDescr['url'] = {'class':'NEEntry', 'master':'node',
'labelCfg':{'text':'URL'},
}
self.inputPortsDescr.append( {'name':'url', 'datatype':'string'} )
code = """def doit(self, url):
url = self.getInputPortByName('url').data
webbrowser.open(url)
"""
if code:
self.setFunction(code)
from Vision.VPE import NodeLibrary
wslib = NodeLibrary('Web Services', '#d7fdf9')
wslib.addNode(GetWSNode, 'Load WS', 'Generic')
wslib.addNode(DownloadNode, 'Download', 'Generic')
wslib.addNode(DownloadSaveDirNode, 'DownloadSaveDir', 'Generic')
wslib.addNode(DownloadToFileNode, 'DownloadToFile', 'Generic')
wslib.addNode(GetMainURLNode, 'GetMainURL', 'Generic')
wslib.addNode(GetMainURLFromListNode, 'GetMainURLFromList', 'Generic')
wslib.addNode(GetURLFromListNode, 'GetURLFromList', 'Generic')
wslib.addNode(IsURLNode, 'IsURL', 'Generic')
wslib.addNode(ReplaceURLNode, 'ReplaceURL', 'Generic')
wslib.addNode(WebBrowserNode, 'WebBrowser', 'Generic')
#addOpalServerAsCategory('http://ws.nbcr.net/opal2')
#addOpalServerAsCategory('http://krusty.ucsd.edu:8081/opal2')
#addOpalServerAsCategory('http://kryptonite.ucsd.edu/opal2')
try:
UserLibBuild.addTypes(wslib, 'MolKit.VisionInterface.MolKitTypes')
except:
pass
mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/VisionInterface/msms_ws.py 0000644 0001750 0001750 00000033717 11260744150 027140 0 ustar debian debian ########################################################################
#
# Vision Macro - Python source code - file generated by vision
# Monday 16 January 2006 12:29:40
#
# The Scripps Research Institute (TSRI)
# Molecular Graphics Lab
# La Jolla, CA 92037, USA
#
# Copyright: Daniel Stoffler, Michel Sanner and TSRI
#
# revision: Guillaume Vareille
#
#########################################################################
#
# $Header$
#
# $Id$
#
from NetworkEditor.macros import MacroNode
class msms_wsMacroNode(MacroNode):
"""Macro Node for MSMS Web Services
Input Ports
Assign Radii_molecules: MoleculeSet object for which to calculate molecular surface
Output Ports
IndexedPolygons_indexedPolygons: geom object that represents molecular surface
"""
def __init__(self, name='WebMSMS', host = None, **kw):
kw['name'] = name
apply( MacroNode.__init__, (self,), kw)
self.host = self.constrkw['host'] = `host`
from WebServices.VisionInterface.WSNodes import OpalService
self.opal_service = OpalService(self.host)
def beforeAddingToNetwork(self, net):
MacroNode.beforeAddingToNetwork(self, net)
## loading libraries ##
from MolKit.VisionInterface.MolKitNodes import molkitlib
net.editor.addLibraryInstance(molkitlib,"MolKit.VisionInterface.MolKitNodes", "molkitlib")
from DejaVu.VisionInterface.DejaVuNodes import vizlib
net.editor.addLibraryInstance(vizlib,"DejaVu.VisionInterface.DejaVuNodes", "vizlib")
from Vision.StandardNodes import stdlib
net.editor.addLibraryInstance(stdlib,"Vision.StandardNodes", "stdlib")
if self.library and not self.library.libraryDescr.has_key(self.host[1:-1]):
from WebServices.VisionInterface.WSNodes import addreplaceCategory
addreplaceCategory(self.host[1:-1])
def afterAddingToNetwork(self):
from NetworkEditor.macros import MacroNode
MacroNode.afterAddingToNetwork(self)
## loading libraries ##
from MolKit.VisionInterface.MolKitNodes import molkitlib
from DejaVu.VisionInterface.DejaVuNodes import vizlib
from Vision.StandardNodes import stdlib
## building macro network ##
WebMSMS = self
from traceback import print_exc
## loading libraries ##
from MolKit.VisionInterface.MolKitNodes import molkitlib
self.macroNetwork.getEditor().addLibraryInstance(molkitlib,"MolKit.VisionInterface.MolKitNodes", "molkitlib")
from DejaVu.VisionInterface.DejaVuNodes import vizlib
self.macroNetwork.getEditor().addLibraryInstance(vizlib,"DejaVu.VisionInterface.DejaVuNodes", "vizlib")
from Vision.StandardNodes import stdlib
self.macroNetwork.getEditor().addLibraryInstance(stdlib,"Vision.StandardNodes", "stdlib")
try:
## saving node input Ports ##
input_Ports = self.macroNetwork.ipNode
input_Ports.move(13, 4)
except:
print "WARNING: failed to restore MacroInputNode named input Ports in network self.macroNetwork"
print_exc()
input_Ports=None
try:
## saving node output Ports ##
output_Ports = self.macroNetwork.opNode
output_Ports.move(256, 220)
except:
print "WARNING: failed to restore MacroOutputNode named output Ports in network self.macroNetwork"
print_exc()
output_Ports=None
try:
## saving node Assign Radii ##
from MolKit.VisionInterface.MolKitNodes import AssignRadii
Assign_Radii = AssignRadii(constrkw = {}, name='Assign Radii', library=molkitlib)
self.macroNetwork.addNode(Assign_Radii,30,68)
apply(Assign_Radii.getInputPortByName('molecules').configure, (), {'color': '#c64e70', 'cast': True, 'shape': 'oval'})
apply(Assign_Radii.getInputPortByName('united').configure, (), {'color': 'yellow', 'cast': True, 'shape': 'circle'})
apply(Assign_Radii.getOutputPortByName('molecules').configure, (), {'color': '#c64e70', 'shape': 'oval'})
apply(Assign_Radii.getOutputPortByName('radii').configure, (), {'color': 'cyan', 'shape': 'oval'})
except:
print "WARNING: failed to restore AssignRadii named Assign Radii in network self.macroNetwork"
print_exc()
Assign_Radii=None
try:
## saving node Select Nodes ##
from MolKit.VisionInterface.MolKitNodes import NodeSelector
Select_Nodes = NodeSelector(constrkw = {}, name='Select Nodes', library=molkitlib)
self.macroNetwork.addNode(Select_Nodes,29,135)
apply(Select_Nodes.getInputPortByName('nodes').configure, (), {'color': '#c64e70', 'cast': True, 'shape': 'oval'})
apply(Select_Nodes.getInputPortByName('nodeType').configure, (), {'color': 'white', 'cast': True, 'shape': 'oval'})
apply(Select_Nodes.getInputPortByName('selectionString').configure, (), {'color': 'white', 'cast': True, 'shape': 'oval'})
apply(Select_Nodes.getOutputPortByName('nodes').configure, (), {'color': '#fe92a0', 'shape': 'oval'})
Select_Nodes.getInputPortByName("selectionString").widget.set(".*")
except:
print "WARNING: failed to restore NodeSelector named Select Nodes in network self.macroNetwork"
print_exc()
Select_Nodes=None
try:
## saving node Get xyzr ##
from Vision.StandardNodes import Generic
Get_xyzr = Generic(constrkw = {}, name='Get xyzr', library=stdlib)
self.macroNetwork.addNode(Get_xyzr,30,194)
apply(Get_xyzr.addInputPort, (), {'name': 'atoms', 'cast': True, 'datatype': 'AtomSet', 'height': 8, 'width': 12, 'shape': 'oval', 'color': '#fe92a0'})
apply(Get_xyzr.addOutputPort, (), {'name': 'output', 'datatype': 'string', 'height': 12, 'width': 12, 'shape': 'oval', 'color': 'white'})
code = """def doit(self, atoms):
lines = ''
for atom in atoms:
lines += str(atom.coords[0]) + ' ' + str(atom.coords[1]) + ' ' + str(atom.coords[2]) + ' '+ str(atom.radius)
lines += "\\n"
self.outputData(output=lines)
"""
Get_xyzr.configure(function=code)
except:
print "WARNING: failed to restore Generic named Get xyzr in network self.macroNetwork"
print_exc()
Get_xyzr=None
try:
## saving node IndexedPolygons ##
from DejaVu.VisionInterface.GeometryNode import IndexedPolygonsNE
IndexedPolygons = IndexedPolygonsNE(constrkw = {}, name='IndexedPolygons', library=vizlib)
self.macroNetwork.addNode(IndexedPolygons,273,147)
apply(IndexedPolygons.getInputPortByName('coords').configure, (), {'color': 'purple', 'cast': True, 'shape': 'circle'})
apply(IndexedPolygons.getInputPortByName('indices').configure, (), {'color': 'yellow', 'cast': True, 'shape': 'circle'})
apply(IndexedPolygons.getInputPortByName('vnormals').configure, (), {'cast': True, 'shape': 'circle'})
apply(IndexedPolygons.getInputPortByName('colors').configure, (), {'cast': True, 'shape': 'circle'})
apply(IndexedPolygons.getInputPortByName('name').configure, (), {'color': 'white', 'cast': True, 'shape': 'oval'})
apply(IndexedPolygons.getInputPortByName('instanceMatrices').configure, (), {'cast': True})
apply(IndexedPolygons.getInputPortByName('geomOptions').configure, (), {'color': 'cyan', 'cast': True, 'shape': 'oval'})
apply(IndexedPolygons.getInputPortByName('parent').configure, (), {'color': 'red', 'cast': True, 'shape': 'rect'})
apply(IndexedPolygons.getOutputPortByName('indexedPolygons').configure, (), {'color': 'red', 'shape': 'rect'})
apply(IndexedPolygons.getOutputPortByName('allGeometries').configure, (), {'color': 'red', 'shape': 'rect'})
except:
print "WARNING: failed to restore IndexedPolygonsNE named IndexedPolygons in network self.macroNetwork"
print_exc()
IndexedPolygons=None
try:
## saving node MSMS WS ##
from Vision.StandardNodes import Generic
MSMS_WS = Generic(constrkw = {}, name='MSMS WS', library=stdlib)
self.macroNetwork.addNode(MSMS_WS,273,37)
apply(MSMS_WS.addInputPort, (), {'name': 'input_str', 'cast': True,
'datatype': 'string', 'height': 12, 'width': 12, 'shape': 'oval', 'color': 'white'})
apply(MSMS_WS.addInputPort, (), {'name': 'density', 'datatype': 'float', 'required':False})
apply(MSMS_WS.getInputPortByName('density').createWidget, (),
{'descr':{'initialValue': 1.0, 'increment':0.1, 'type':'float',
'master': 'ParamPanel', 'oneTurn':10, 'min':1.0, 'labelCfg': {'text': 'density'}, 'class': 'NEDial'}})
apply(MSMS_WS.addInputPort, (), {'name': 'probe_radius', 'datatype': 'float', 'required':False})
apply(MSMS_WS.getInputPortByName('probe_radius').createWidget, (),
{'descr':{'initialValue': 1.5, 'increment':0.1, 'type':'float',
'master': 'ParamPanel', 'oneTurn':10, 'min':0.5, 'labelCfg': {'text': 'probe radius'}, 'class': 'NEDial'}})
apply(MSMS_WS.addInputPort, (), {'name': 'allComp', 'datatype': 'int', 'required':False})
apply(MSMS_WS.getInputPortByName('allComp').createWidget, (),
{'descr':{'initialValue': 0, 'master': 'ParamPanel', 'labelCfg':
{'text': 'all components'}, 'class': 'NECheckButton'}})
apply(MSMS_WS.addInputPort, (), {'name': 'getfile', 'datatype': 'boolean'})
apply(MSMS_WS.getInputPortByName('getfile').createWidget, (),
{'descr':{'master': 'ParamPanel', 'labelCfg': {'text': 'upload output'}, 'class': 'NECheckButton', 'initialValue':True }})
apply(MSMS_WS.addOutputPort, (), {'name': 'vertices', 'datatype': 'coordinates3D', 'height': 8, 'width': 12, 'shape': 'rect', 'color': 'green'})
apply(MSMS_WS.addOutputPort, (), {'name': 'indices', 'datatype': 'faceIndices', 'height': 8, 'width': 12, 'shape': 'rect', 'color': 'purple'})
apply(MSMS_WS.addOutputPort, (), {'name': 'vnormals', 'datatype': 'normals3D', 'height': 8, 'width': 12, 'shape': 'rect', 'color': 'blue'})
MSMS_WS.host = self.host
MSMS_WS.opal_service = self.opal_service
code = """def doit(self, input_str, probe_radius, density, allComp, getfile):
self.opal_service.inputFile.Set_name('msms.xyzr')
self.opal_service.inputFile.Set_contents(input_str)
options = '-if msms.xyzr -of ws_out '
options += '-probe_radius ' + str(probe_radius)
options += ' -density ' + str(density)
if allComp:
options += ' -all_components'
self.opal_service.req._argList = options
inputFiles = []
inputFiles.append(self.opal_service.inputFile)
self.opal_service.req._inputFile = inputFiles
resp = self.opal_service.run('msmsServicePort')
if resp:
for files in resp._outputFile:
if files._url.split('/')[-1] == 'ws_out.face':
face_file = files._url
if files._url.split('/')[-1] == 'ws_out.vert':
vert_file = files._url
if getfile:
from Pmv.msmsParser import MSMSParser
msmsParser = MSMSParser()
import urllib
opener = urllib.FancyURLopener({})
in_file = opener.open(face_file)
msmsParser.getFaces(in_file.readlines())
in_file = opener.open(vert_file)
msmsParser.getVert(in_file.readlines())
self.outputData(vertices = msmsParser.vertices, indices = msmsParser.faces,
vnormals = msmsParser.normals)
else:
self.outputData(vertices = vert_file, indices = face_file,
vnormals = None)
"""
MSMS_WS.configure(function=code)
except:
print "WARNING: failed to restore Generic named MSMS WS in network self.macroNetwork"
print_exc()
MSMS_WS=None
self.macroNetwork.freeze()
## saving connections for network WebMSMS ##
if Assign_Radii is not None and Select_Nodes is not None:
self.macroNetwork.connectNodes(
Assign_Radii, Select_Nodes, "molecules", "nodes", blocking=True)
if Select_Nodes is not None and Get_xyzr is not None:
self.macroNetwork.connectNodes(
Select_Nodes, Get_xyzr, "nodes", "atoms", blocking=True)
if Get_xyzr is not None and MSMS_WS is not None:
self.macroNetwork.connectNodes(
Get_xyzr, MSMS_WS, "output", "input_str", blocking=True)
if MSMS_WS is not None and IndexedPolygons is not None:
self.macroNetwork.connectNodes(
MSMS_WS, IndexedPolygons, "vertices", "coords", blocking=True)
if MSMS_WS is not None and IndexedPolygons is not None:
self.macroNetwork.connectNodes(
MSMS_WS, IndexedPolygons, "indices", "indices", blocking=True)
if MSMS_WS is not None and IndexedPolygons is not None:
self.macroNetwork.connectNodes(
MSMS_WS, IndexedPolygons, "vnormals", "vnormals", blocking=True)
output_Ports = self.macroNetwork.opNode
if IndexedPolygons is not None and output_Ports is not None:
self.macroNetwork.connectNodes(
IndexedPolygons, output_Ports, "indexedPolygons", "new", blocking=True)
input_Ports = self.macroNetwork.ipNode
if input_Ports is not None and Assign_Radii is not None:
self.macroNetwork.connectNodes(
input_Ports, Assign_Radii, "new", "molecules", blocking=True)
self.macroNetwork.unfreeze()
WebMSMS.shrink()
## reset modifications ##
WebMSMS.resetTags()
WebMSMS.buildOriginalList()
mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/VisionInterface/__init__.py 0000644 0001750 0001750 00000000000 10366464453 027175 0 ustar debian debian mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/OpalCache.py 0000644 0001750 0001750 00000016277 11612421534 024200 0 ustar debian debian import sys
import time
import httplib
import urllib
import xml.dom.minidom
import os
import shutil
import subprocess
import copy
import urlparse
import pickle
from mglutil.web.services import AppService_client
class OpalCache:
def getServices(self, opal_url):
services = []
if opal_url.find("/opal2") != -1:
service_list_url = opal_url + "/opalServices.xml"
opener = urllib.FancyURLopener({})
socket = opener.open(service_list_url)
text = socket.read()
feed = xml.dom.minidom.parseString(text)
for entry in feed.getElementsByTagName('entry'):
link = entry.getElementsByTagName('link')[0]
service = link.getAttribute('href')
services.append(str(service))
else:
print "ERROR: No opal2 contained in URL"
return services
def getFileName(self, url):
hostname = url.split('http://')[1].split('/')[0]
hostname = hostname.replace(':', '+')
servicename = os.path.basename(url)
filename = os.path.join(hostname, servicename)
return filename
def getBinaryLocation(self, url, dir):
(bl, x2, x3) = self.getCache(url, dir)
return bl
def getParams(self, url, dir):
(x1, params, x3) = self.getCache(url, dir)
return params
def getSeparator(self, url, dir):
(x1, x2, separator) = self.getCache(url, dir)
return separator
def getServicesFromCache(self, url, dir, disable_inactives=True):
hostname = url.split('http://')[1].split('/')[0]
hostname = hostname.replace(':', '+')
hostcd = os.path.join(dir, hostname)
inactivedir = os.path.join(os.path.join(dir, "inactives"), hostname)
files = []
inactives = []
try:
files = os.listdir(hostcd)
inactives = os.listdir(inactivedir)
actives = set(files) - set(inactives)
except:
print "ERROR: Cache directory for " + url + " does not exist!"
print " Are you connected to the internet???"
return []
if disable_inactives:
services = map(lambda x: url + '/services/' + x, actives)
else:
services = map(lambda x: url + '/services/' + x, files)
return services
def getCache(self, url, dir):
file = os.path.join(dir, self.getFileName(url))
params = pickle.load(open(file))
return params
def isCacheValid(self, url, dir, days=30):
fn = self.getFileName(url)
cachedir = os.path.join(dir, os.path.dirname(fn))
filename = os.path.join(dir, fn)
if not(os.path.exists(cachedir)) or not(os.path.exists(filename)):
return False
if (time.time() - os.path.getmtime(filename) > days * 86400):
print "*** [WARNING]: Cache for " + url + " is older than " + days + " days!"
return False
return True
def writeCache(self, url, dir, days=30):
fn = self.getFileName(url)
cachedir = os.path.join(dir, os.path.dirname(fn))
if not(os.path.exists(cachedir)):
os.mkdir(cachedir)
filename = os.path.join(dir, fn)
if not(self.isCacheValid(url, dir, days)):
print "[INFO]: Writing cache for " + url + " in " + filename
appLocator = AppService_client.AppServiceLocator()
appServicePort = appLocator.getAppServicePort(url)
req = AppService_client.getAppMetadataRequest()
metadata = appServicePort.getAppMetadata(req)
appLocator = AppService_client.AppServiceLocator()
appServicePort = appLocator.getAppServicePort(url)
# req = AppService_client.getAppConfigRequest()
# metadata2 = appServicePort.getAppConfig(req)
# executable = metadata2._binaryLocation
try:
req = AppService_client.getAppConfigRequest()
metadata2 = appServicePort.getAppConfig(req)
executable = metadata2._binaryLocation
except:
executable = 'NA'
pass
separator = None
params = {}
try:
rawlist = metadata._types._flags._flag
order = 0
for i in rawlist:
myhash = {}
myhash = {'type': 'boolean'}
myhash['config_type'] = 'FLAG'
myhash['tag'] = str(i._tag)
myhash['default'] = 'True' if str(i._default)=='True' else 'False'
myhash['description'] = str(i._textDesc) if i._textDesc else 'No Description'
myhash['order'] = order
params[str(i._id).replace('-','_')] = copy.deepcopy(myhash)
order = order + 1
except AttributeError:
pass
try:
rawlist = metadata._types._taggedParams._param
separator = metadata._types._taggedParams._separator
order = 0
for i in rawlist:
myhash = {}
myhash['config_type'] = 'TAGGED'
if i._value:
myhash['type'] = 'selection'
myhash['values'] = [str(z) for z in i._value]
else:
myhash['type'] = str(i._paramType)
if(str(i._paramType)=="FILE"):
myhash['ioType'] = str(i._ioType)
myhash['description'] = str(i._textDesc) if i._textDesc else 'No Description'
myhash['default'] = str(i._default) if i._default else None
myhash['tag'] = str(i._tag)
myhash['separator'] = separator
myhash['order'] = order
params[str(i._id).replace('-','_')] = copy.deepcopy(myhash)
order = order + 1
except AttributeError:
pass
try:
rawlist = metadata._types._untaggedParams._param
order = 0
for i in rawlist:
myhash = {}
myhash['config_type'] = 'UNTAGGED'
myhash['type'] = str(i._paramType)
if(str(i._paramType)=="FILE"):
myhash['ioType'] = str(i._ioType)
myhash['description'] = str(i._textDesc)
myhash['default'] = str(i._default) if i._default else None
myhash['tag'] = str(i._tag)
myhash['order'] = order
params[str(i._id).replace('-','_')] = copy.deepcopy(myhash)
order = order + 1
except AttributeError:
pass
lock = filename + '.lock'
if os.path.exists(lock) and time.time() - os.path.getmtime(lock) > 100:
os.remove(lock)
if not(os.path.exists(lock)):
open(lock, 'w').close()
pickle.dump((executable, params, separator), open(filename, "wb"))
os.remove(lock)
mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/listGUI.py 0000755 0001750 0001750 00000014627 10773016216 023705 0 ustar debian debian # Author: Sargis Dallakyan (sargis@scripps.edu)
# $Header: /opt/cvs/WebServices/listGUI.py,v 1.2 2008/03/27 22:15:42 sargis Exp $
# $Id: listGUI.py,v 1.2 2008/03/27 22:15:42 sargis Exp $
"GUI for listing available Web Service"
import sys,time
import Tkinter
import Pmw
import urllib
from mglutil.web.services.AppService_client import AppServiceLocator, launchJobRequest, \
getOutputsRequest, queryStatusRequest, getAppMetadataRequest
from mglutil.web.services.AppService_types import ns0
class ListWS:
"""
This class tries to list the deployed Web services
"""
def __init__(self, parent = None):
if not parent:
parent = Tkinter.Tk()
Pmw.initialise(parent)
title = 'View the list of deployed Web services'
parent.title(title)
exitButton = Tkinter.Button(parent, text = 'Exit', command = parent.destroy)
exitButton.pack(side = 'bottom')
self.parent = parent
# Create a group widget to contain the ComboBox for the Hosts.
Hosts_Group = Pmw.Group(parent, tag_pyclass = None)
Hosts_Group.pack(fill='x')
self.Hosts_ComboBox = Pmw.ComboBox(Hosts_Group.interior(),
label_text = 'Hosts:',
labelpos = 'ws',
entry_width = 30,
scrolledlist_items=('http://ws.nbcr.net:8080/opal',),
selectioncommand = self.update_services
)
self.Hosts_ComboBox.pack(padx = 1, pady = 1)
# ScrolledListBox for listing Services
from mglutil.gui.BasicWidgets.Tk.TreeWidget.tree import TreeView
frame = Tkinter.Frame(parent)
frame.pack(side = 'left',fill='both')
label = Tkinter.Label(frame,text = 'Services')
label.pack()
self.Services_Tree = TreeView(master=frame,treeWidth=230,width=230)
self.Services_Tree.setAction(event='select',
function=self.getDescription)
# ScrolledText for providing information about Web Services
self.Description_Text = Pmw.ScrolledText(parent,
labelpos='nsew',
label_text='Description',
text_state = 'disabled'
)
#self.Services_Box.pack(side = 'left',fill='both')
self.Description_Text.pack(side = 'right',expand = 1,fill='both')
self.Hosts_ComboBox.selectitem(0)
self.Services_dict = {}
self.update_services(None)
parent.mainloop()
def update_services(self,event):
self.parent.config(cursor='watch')
self.Description_Text.configure(text_state = 'normal')
self.Description_Text.clear()
self.URL = self.Hosts_ComboBox.get()
opener = urllib.FancyURLopener({})
for key in self.Services_dict:
self.Services_Tree.deleteNode(key)
self.Services_dict = {}
try:
servlet = opener.open(self.URL+"/servlet/AxisServlet")
except IOError:
errorMsg = self.URL+"/servlet/AxisServlet could not be found"
errorMsg += "\nPlease make sure that server is up and running"
import tkMessageBox
tkMessageBox.showerror("Error!",errorMsg)
self.parent.config(cursor='')
return
text = servlet.read()
text = text.split('')
if text[0].find('And now... Some Services
') == -1:
errorMsg = self.URL+"/servlet/AxisServlet could not be found"
errorMsg += "\nPlease make sure that server is up and running"
import tkMessageBox
tkMessageBox.showerror("Error!",errorMsg)
self.parent.config(cursor='')
return
text = text[1:]
last_service = ""
for line in text[:-1]:
methods = line.split('
')
if len(methods) > 1:
methods = methods[0]
methods = methods.split('- ')
methods = methods[1:]
for method in methods:
self.Services_Tree.addNode(method.strip(),parent=last_service)
tmp_text = line.split(self.URL+"/services/")
port = tmp_text[-1].split('wsdl')
self.Services_Tree.addNode(port[0][:-1])
self.Services_dict[port[0][:-1]] = self.URL+"/services/" + \
port[0][:-1] + "?wsdl"
last_service = port[0][:-1]
methods = line.split('
')
if len(methods) > 1:
methods = methods[0]
methods = methods.split('')
methods = methods[1:]
for method in methods:
self.Services_Tree.addNode(method.strip(),parent=last_service)
self.parent.config(cursor='')
#self.Services_Tree.deleteNode('AdminService')
#self.Services_Tree.deleteNode('Version')
#self.Services_Tree.deleteNode('APBSJobSubPort')
def getDescription(self, tree_node):
if tree_node.parent:
service = tree_node.parent.GetFullName()
else:
service = tree_node.GetFullName()
import ZSI
self.Description_Text.configure(text_state = 'normal')
self.Description_Text.clear()
from ZSI.generate.wsdl2python import WriteServiceModule
from ZSI.wstools import WSDLTools
reader = WSDLTools.WSDLReader()
wsdl = reader.loadFromURL(self.Services_dict[service])
try:
wsdl.services['AppService']
except:
self.Description_Text.insert('end', 'Sorry, only Opal based web services are supported http://nbcr.net/services/opal')
self.Description_Text.configure(text_state = 'disabled')
return
appLocator = AppServiceLocator()
appServicePort = appLocator.getAppServicePort(\
self.URL + "/services/"+service)
req = getAppMetadataRequest()
resp = appServicePort.getAppMetadata(req)
self.Description_Text.configure(text_state = 'normal')
if resp._info:
self.Description_Text.insert('end',resp._usage+"\n\n")
self.Description_Text.insert('end',resp._info[0])
else:
self.Description_Text.insert('end',resp._usage)
self.Description_Text.configure(text_state = 'disabled')
######################################################################
# Create demo in root window for testing.
if __name__ == '__main__':
ListWS()
mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/OpalUtil.py 0000644 0001750 0001750 00000052201 11616604627 024107 0 ustar debian debian # Author: Wes Goodman
# Module for launching Opal jobs within Vision
import sys
import traceback
import time
import httplib
import urllib
import os
import shutil
import subprocess
import tempfile
import urlparse
from mglutil.web.services.AppService_client import AppServiceLocator, \
launchJobRequest, getOutputsRequest, queryStatusRequest, destroyRequest
from mglutil.web.services.AppService_types import ns0
from ZSI.TC import String
from ZSI import *
from time import strftime
from datetime import datetime
from NetworkEditor.items import FunctionNode
class OpalWSNode(FunctionNode):
def getNodeSourceCodeForWidgetValue(self, networkName, portIndex,
indent="", ignoreOriginal=False,
full=0, nodeName=None):
lines = FunctionNode.getNodeSourceCodeForWidgetValue(
self, networkName, portIndex, indent=indent,
ignoreOriginal=ignoreOriginal, full=full, nodeName=nodeName)
line = lines[0]
nsindent = len(line.split(indent)) - 1
sindent = ''
for i in range(0, nsindent):
sindent += indent
for i in range(0, len(lines)):
lines[i] = indent + lines[i]
if nodeName == None:
nodeName = self.getUniqueNodeName()
hn = nodeName[nodeName.find('_')+1:nodeName.rfind('_')].replace('_', '.')
sn = nodeName.split('_')[0]
mmsg = '[WARNING] Opal web service option <' + \
self.inputPortsDescr[portIndex]['name'] + \
'> no longer exists for ' + sn + ' on ' + hn
mmsg = "\'" + mmsg + "\'"
lines.insert(0, sindent + 'try:\n')
lines.append(sindent + 'except KeyError:\n')
lines.append(sindent + indent + 'print ' + mmsg + '\n')
lines.append(sindent + indent + 'pass\n')
return lines
class OpalUtil(object):
"""
OpalUtil: Static class containing generic utility wrappers for exectuting Opal Web Service calls
"""
def __init__(self, opalNode):
"""
initialize OpalUtil object
"""
self.opalNode = opalNode
self.jobID = None
#add link to OpalObject
def onStoppingExecution(self):
#kill running job
#TODO kill local running job
if (self.jobID != None):
#ok let's kill the running job
print "Killing job: " + self.jobID
appLocator = AppServiceLocator()
appServicePort = appLocator.getAppServicePort(self.opalNode.url)
destroyReq = destroyRequest(self.jobID)
resp = appServicePort.destroy(destroyReq)
def launchJob(self,url,flags,taggedparams,untaggedparams,meta,localRun=False,executable=''):
"""
launchJob description:
@input:
-url: for application endpoint
-flags: list of flag ids for the application
-taggedparams: list of tuples: [(tag_id,value),...]
-untaggedparams: list of tuples: [(tag_id,value),...]
-meta: getAppMetadata output object
@output:
-returns tuple: (job code, status message, output url)
"""
#print "launchJob"
# build two hashes: flaghash, taggedhash from xml
# Index on id, value will be tag
flaghash = self.buildHash(meta,'flags')
taggedhash = self.buildHash(meta,'taggedParams')
separator = meta._types._taggedParams._separator
if ( separator == None ):
separator=' '
# map from flag ids to flag tags
flagtags = map(lambda x: flaghash[x],flags)
command = ' '.join(flagtags)
inputFiles = []
for (tagid,val) in taggedparams:
#let's create the tagged params part of the command line
taggedobject = self.getTaggedParam(meta,tagid)
if (taggedobject._paramType=='FILE') and (taggedobject._ioType=='INPUT'):
inputFiles.append(val)
command += ' '+taggedobject._tag+separator+os.path.basename(val)
else:
#this is not an input file handle normally
command += ' '+taggedobject._tag+separator+val
for (tagid,val) in untaggedparams:
#now let's see the untagged part of the command line
#match id to ioType
# if input, determine if file or string
# if output, just put the string
untaggedobject = self.getUntaggedParam(meta,tagid)
if (untaggedobject._paramType=='FILE') and (untaggedobject._ioType=='INPUT'):
inputFiles.append(val)
command += ' '+os.path.basename(val)
else:
command += ' '+val
print "The node " + self.opalNode.__class__.__name__ + " is going to execute the command: " + command
#common code
if (localRun==False):
#print "Local run is: " + str(localRun) + " running remotely"
results = self.executeWebJob(url, command, inputFiles, None)
else :
results = self.executeLocal(url, command, inputFiles, executable)
return results
def launchJobCachedParams(self,url,flags,taggedparams,untaggedparams,params,localRun=False,executable=''):
"""
launchJob description:
@input:
-url: for application endpoint
-flags: list of flag ids for the application
-taggedparams: list of tuples: [(tag_id,value),...]
-untaggedparams: list of tuples: [(tag_id,value),...]
-meta: getAppMetadata output object
@output:
-returns tuple: (job code, status message, output url)
"""
flaghash = {}
taggedhash = {}
untagged_count = 0
tagged_count = 0
flag_count = 0
untagged_order = {}
tagged_order = {}
flag_order = {}
for k, v in params.iteritems():
if v['config_type'] == 'FLAG':
flaghash[k] = v['tag']
flag_count = flag_count + 1
elif v['config_type'] == 'TAGGED':
taggedhash[k] = v['tag']
tagged_count = tagged_count + 1
separator = v['separator']
elif v['config_type'] == 'UNTAGGED':
untagged_count = untagged_count + 1
try:
if separator == None:
separator = ' '
except:
separtor = ' '
#if separator == None:
# separator = ' '
# map from flag ids to flag tags
# flagtags = map(lambda x: flaghash[x],flags)
# command = ' '.join(flagtags)
command = ' '
for tagid in flags:
order = params[tagid]['order']
flag_order[order] = tagid
for i in range(flag_count):
try:
tagid = flag_order[i]
if tagid:
command += ' ' + params[tagid]['tag']
except:
pass
inputFiles = []
for (tagid, val) in taggedparams:
order = params[tagid]['order']
tagged_order[order] = (tagid, val)
for i in range(tagged_count):
try:
(tagid, val) = tagged_order[i]
if params[tagid]['type'] == 'FILE' and params[tagid]['ioType'] == 'INPUT':
inputFiles.append(val)
command += ' ' + params[tagid]['tag'] + separator + os.path.basename(val)
else:
#this is not an input file handle normally
command += ' ' + params[tagid]['tag'] + separator + val
except:
pass
for (tagid, val) in untaggedparams:
order = params[tagid]['order']
untagged_order[order] = (tagid, val)
for i in range(untagged_count):
try:
(tagid, val) = untagged_order[i]
if params[tagid]['type'] == 'FILE' and params[tagid]['ioType'] == 'INPUT':
inputFiles.append(val)
command += ' ' + os.path.basename(val)
else:
#this is not an input file handle normally
command += ' ' + val
except:
pass
print "The node " + self.opalNode.__class__.__name__ + " is going to execute the command: " + command
#common code
if (localRun==False):
#print "Local run is: " + str(localRun) + " running remotely"
results = self.executeWebJob(url, command, inputFiles, None)
else :
results = self.executeLocal(url, command, inputFiles, executable)
return results
def getUntaggedParam(self,meta,tagid):
"""
getUntaggedParam description:
@input:
-meta: application's metadata
-tagid: id for parameter
@output:
-returns param object
"""
untaggedlist = meta._types._untaggedParams._param
for i in untaggedlist:
if(i._id==tagid):
return i
return "NOT AN UNTAGGED PARAM"
def getTaggedParam(self,meta,tagid):
"""
getTaggedParam description:
@input:
-meta: application's metadata
-tagid: id for parameter
@output:
-returns param object
"""
taggedlist = meta._types._taggedParams._param
for i in taggedlist:
if(i._id==tagid):
return i
return "NOT AN UNTAGGED PARAM"
def buildHash(self,meta,tagtype):
"""
buildHash description:
@input:
-meta: application's metadata
-id: an ID to use to know where to start building the hash
@output:
-returns hash[param_id] = param_tag
"""
if(tagtype=='flags'):
mylist = meta._types._flags._flag
elif(tagtype=='taggedParams'):
mylist = meta._types._taggedParams._param
myhash = {}
for i in mylist:
myhash[str(i._id)] = str(i._tag)
return myhash
def launchBasicJob(self,url,commandline,inFilesPath,numProcs=None,localRun=False,executable=''):
"""
launchBasicJob description:
@input:
-url: for application endpoint
-inFilesPath: list of input files, an array of strings containing the paths
"""
#print "launchBasicJob"
#this should be moved in the constructor...
print "The node " + self.opalNode.__class__.__name__ + " is going to execute the command: " + commandline
if (localRun==False):
results = self.executeWebJob(url, commandline, inFilesPath, numProcs)
else :
#local execution do not support number of cpu
results = self.executeLocal(url, commandline, inFilesPath, executable)
return results
def executeWebJob(self, url, commandline, inFilesPath, numProcs):
"""
executeWebJob description:
it execute a job through OpalInterface
@input:
-url: the url where to reach the Opal service
-commandline the command line to use for the execution
-inputFiles an array of input file to upload, it should contains an array of string with the path to the file
-numProcs the number of processors to use
"""
inputFiles = []
if inFilesPath != None:
for i in inFilesPath:
inputFile = ns0.InputFileType_Def('inputFile')
inputFile._name = os.path.basename(i)
if self.isOpal2(url):
#use attachment this is opal2 server
if os.name == 'dos' or os.name == 'nt':
inputFile._attachment = open(i, "rb")
else:
inputFile._attachment = open(i, "r")
else:
#it's not a opal2 server don't user attachment
infile = open(i, "r")
inputFile._contents = infile.read()
infile.close()
inputFiles.append(inputFile)
appLocator = AppServiceLocator()
appServicePort = appLocator.getAppServicePort(url)
req = launchJobRequest()
req._argList = commandline
req._inputFile = inputFiles
req._numProcs = numProcs
if inputFiles != []:
print "Uploading input files..."
resp_s = -1
while resp_s == -1:
try:
resp = appServicePort.launchJob(req)
resp_s = 0
except FaultException, inst:
estr = inst.fault.AsSOAP()
estr = estr.split("")[1].split("")[0]
t = strftime("%Y-%m-%d %H:%M:%S", time.localtime())
cte = time.mktime(datetime.now().timetuple())
ete = cte + 60 * 60 + 10
print "WARNING: " + t + " Opal FaultException from server: " + estr
print " will try again in about an hour"
while time.mktime(datetime.now().timetuple()) < ete:
if self.opalNode._vpe is not None:
self.opalNode._vpe.updateGuiCycle()
net = self.opalNode._node.network
if net.execStatus == 'stop':
#if self.opalNode._vpe.buttonBar.toolbarButtonDict['stop'].state == "disabled":
self.onStoppingExecution()
return None
time.sleep(0.5)
pass
except: # no internet
s = -1
while s == -1:
try:
urllib.urlopen(url)
s = 0
except IOError:
t = strftime("%Y-%m-%d %H:%M:%S", time.localtime())
cte = time.mktime(datetime.now().timetuple())
ete = cte + 60
print "WARNING: " + t + " cannot connect to " + url
print " Are you connected to the internet?"
print " Will try again in about a minute"
while time.mktime(datetime.now().timetuple()) < ete:
if self.opalNode._vpe is not None:
self.opalNode._vpe.updateGuiCycle()
net = self.opalNode._node.network
if net.execStatus == 'stop':
#if self.opalNode._vpe.buttonBar.toolbarButtonDict['stop'].state == "disabled":
#stop running job and return
self.onStoppingExecution()
return None
time.sleep(0.5)
pass
pass
if inputFiles != []:
print "Done uploading input files."
self.jobID = resp._jobID
print "Job outputs URL: " + resp._status._baseURL # urlparse.urljoin(url, '/' + self.jobID)
status = resp._status._code
while(status!=4 and status!=8):
try:
status = appServicePort.queryStatus(queryStatusRequest(self.jobID))._code
except FaultException, inst:
estr = inst.fault.AsSOAP()
estr = estr.split("")[1].split("")[0]
t = strftime("%Y-%m-%d %H:%M:%S", time.localtime())
cte = time.mktime(datetime.now().timetuple())
ete = cte + 60 * 60 + 10
print "WARNING: " + t + " Opal FaultException from server: " + estr
print " will try again in about an hour"
while time.mktime(datetime.now().timetuple()) < ete:
if self.opalNode._vpe is not None:
self.opalNode._vpe.updateGuiCycle()
net = self.opalNode._node.network
if net.execStatus == 'stop':
#if self.opalNode._vpe.buttonBar.toolbarButtonDict['stop'].state == "disabled":
self.onStoppingExecution()
return None
time.sleep(0.5)
pass
except:
status = -2
try:
urllib.urlopen(url)
except IOError:
status = -1
t = strftime("%Y-%m-%d %H:%M:%S", time.localtime())
cte = time.mktime(datetime.now().timetuple())
ete = cte + 60
print "WARNING: " + t + " cannot connect to " + url
print " Are you connected to the internet?"
print " Will try again in about a minute"
while time.mktime(datetime.now().timetuple()) < ete:
if self.opalNode._vpe is not None:
self.opalNode._vpe.updateGuiCycle()
net = self.opalNode._node.network
if net.execStatus == 'stop':
#if self.opalNode._vpe.buttonBar.toolbarButtonDict['stop'].state == "disabled":
self.onStoppingExecution()
return None
time.sleep(0.5)
pass
if status == -1:
pass
if self.opalNode._vpe is not None:
self.opalNode._vpe.updateGuiCycle()
net = self.opalNode._node.network
if net.execStatus == 'stop':
#if self.opalNode._vpe.buttonBar.toolbarButtonDict['stop'].state == "disabled":
#stop running job and return
self.onStoppingExecution()
return None
if(status==8):
#Job completed successfully
resp = appServicePort.getOutputs(getOutputsRequest(self.jobID))
outurls = [str(resp._stdOut),str(resp._stdErr)]
if(resp._outputFile!=None):
for i in resp._outputFile:
outurls.append(str(i._url))
else:
#Job died or something else went wrong
resp = appServicePort.getOutputs(getOutputsRequest(self.jobID))
outurls = [str(resp._stdOut),str(resp._stdErr)]
return tuple(outurls)
def isOpal2(self, url):
""" it returns true if this service points to a opal2 server
false in the other cases
"""
if url.find("/opal2/") != -1:
return True
else:
return False
def executeLocal(self, url, command, inputFiles, executable):
"""
executeLocal description:
this functions is used to exectute a job on the local machine
@input:
-url: the url where to reach the Opal service
-commandline the command line to use for the execution
-inputFiles an array of input file to upload to the server (array of strings path)
-numProcs the number of processors to use
"""
#print "executeLocal"
#setting up workind dir and input files
#workingDir = os.tempnam()
workingDir = tempfile.mkdtemp()
print "Job output files directory is: " + workingDir
#workingDir = workingDir + '/app' + str(int(time.time()*100 ))
#os.mkdir(workingDir)
if inputFiles != None:
for i in inputFiles:
shutil.copy(i,workingDir)
#setting up input and error file
output = open(workingDir + os.sep + 'stdout.txt', 'w')
error = open(workingDir + os.sep + 'stderr.txt', 'w')
#working directory
cwd = os.getcwd()
os.chdir(workingDir)
#environmental variables
pythonpath = os.getenv('PYTHONPATH')
pythonhome = os.getenv('PYTHONHOME')
pathorig = os.getenv('PATH')
if ( pathorig.partition(':')[0].find('MGL') ): # there is the MGL python let's remove it
os.putenv('PATH',pathorig.partition(':')[2])
os.unsetenv('PYTHONPATH')
os.unsetenv('PYTHONHOME')
cmdExec=executable + ' ' + command
#print 'going to exectute: ' + cmdExec + ' with input files: ' + str(inputFiles)
p = subprocess.Popen(cmdExec.split(), stdout=output, stderr=error)
while p.poll() == None:
if self.opalNode._vpe is not None:
self.opalNode._vpe.updateGuiCycle()
time.sleep(0.5)
#job finished cleaning up
#files
output.close()
error.close()
#evironment variables
if pythonpath != None:
os.putenv('PYTHONPATH', pythonpath)
if pythonhome != None:
os.putenv('PYTHONHOME', pythonhome)
os.putenv('PATH', pathorig)
#going back to previous working dir
os.chdir(cwd)
outputFiles=[]
for i in os.listdir(workingDir):
#outputFiles.append('file://' + workingDir + '/' + i)
outputFiles.append(workingDir + os.sep + i)
return outputFiles
mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/LICENSE 0000644 0001750 0001750 00000004364 11033235127 023004 0 ustar debian debian This software is copyrighted by Michel F. Sanner (sanner@scripps.edu) and TSRI.
The following terms apply to all files associated with the software
unless explicitly disclaimed in individual files.
MGLTOOLS SOFTWARE LICENSE AGREEMENT.
1. Grant Of Limited License; Software Use Restrictions. The programs
received by you will be used only for NON COMMERCIAL purposes.
This license is issued to you as an individual.
For COMMERCIAL use done with the software please contact Michel F.
Sanner for details about commercial usage license agreements.
For any question regarding license agreements, please contact
Michel Sanner:
TSRI, Molecular Biology Department, TCP 26,
10550 North Torrey Pines Road, La Jolla, CA 92037
sanner@scripps.edu
tel (858) 784-7742
fax (858) 784-2341
2. COMMERCIAL USAGE is defined as revenues generating activities. These
include using this software for consulting activities and selling
applications built on top of, or using this software. Scientific
research in an academic environment and teaching are considered
NON COMMERCIAL.
3. Copying Restrictions. You will not sell or otherwise distribute commercially
these programs or derivatives to any other party, whether with or without
consideration.
4. Ownership of Software. You will not obtain, and will not attempt to
obtain copyright coverage thereon without the express purpose written
consent of The Scripps Research Institute and Dr. Sanner.
5. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
6. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.
mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/OpalWrapper.py 0000644 0001750 0001750 00000040202 12003371761 024577 0 ustar debian debian import copy
import os
import OpalUtil
from mglutil.web.services import AppService_client
from mglutil.web.services.AppService_types import ns0
from urlparse import urlparse
from OpalCache import OpalCache
from mglutil.util.packageFilePath import getResourceFolderWithVersion
tab = " "
class OpalWrapper(object):
"""docstring for OpalWrapper"""
def __init__(self):
pass
def generate(self,url,conn=True):
oc = OpalCache()
if conn == True:
if oc.isCacheValid(url, os.path.join(getResourceFolderWithVersion(), 'ws')):
conn = False
if conn == True:
self.metadata = self.getAppMetadata(url)
else:
print "[INFO]: Generating Opal Wrapper for " + url + " from cache"
self.url = url
#setting up for local execution
if conn == True:
try:
executable = self.getAppConfig(url)._binaryLocation
except:
executable = 'NA'
pass
else:
dir = os.path.join(getResourceFolderWithVersion(), 'ws')
executable = oc.getBinaryLocation(url, dir)
params = oc.getParams(self.url, dir)
self.params = oc.getParams(self.url, dir)
# assuming the server is a unix
executable = executable.rpartition("/")[2]
if self.which(executable) == None:
self.executable = ""
else:
self.executable = self.which(executable)
if conn == True:
classdec = self.buildClassDeclaration(self.metadata,self.url)
if (self.metadata._types):
initmethod = self.buildInitMethod(self.metadata, self.url)
callmethod = self.buildCallMethod(self.metadata)
else:
initmethod = self.buildDefaultInitMethod(self.url)
callmethod = self.buildDefaultCallMethod()
else:
classdec = self.buildClassDeclarationFromCache(self.url, params)
if params:
initmethod = self.buildInitMethodFromCache(params, self.url)
callmethod = self.buildCallMethodFromCache(params)
else:
initmethod = self.buildDefaultInitMethodFromCache(self.url)
callmethod = self.buildDefaultCallMethod()
retclass = ""
for i in classdec:
retclass+=(str(i)+"\n")
allmethods = []
allmethods.extend(initmethod)
allmethods.extend(callmethod)
for i in allmethods:
retclass+=(tab+str(i)+"\n")
#add the onStoppingExecution before returning
return retclass
def getAppMetadata(self,url):
"""docstring for getAppMetadata"""
appLocator = AppService_client.AppServiceLocator()
appServicePort = appLocator.getAppServicePort(url)
req = AppService_client.getAppMetadataRequest()
metadata = appServicePort.getAppMetadata(req)
return metadata
def getAppConfig(self,url):
"""
getAppConfig description: give the URL of the service it returns the appConfig of that service
"""
appLocator = AppService_client.AppServiceLocator()
appServicePort = appLocator.getAppServicePort(url)
req = AppService_client.getAppConfigRequest()
metadata = appServicePort.getAppConfig(req)
return metadata
def buildClassDeclaration(self,metadata,url):
"""docstring for buildClassDeclaration"""
myclassname = url.split('/')[-1].replace('-','_')
myclassname = myclassname.replace('.','_')
#LC 042308 added the server name to the generated classname
servername = urlparse(url)[1]
servername = servername.replace('.','_')
servername = servername.split(':')[0]
myclassname = myclassname + "_" + servername
myclassname = myclassname.replace('-','_')
myret = []
myret.append('class %s:' % myclassname)
params = {}
try:
rawlist = metadata._types._flags._flag
for i in rawlist:
myhash = {}
myhash = {'type':'boolean'}
myhash['default'] = 'True' if str(i._default)=='1' else 'False'
myhash['description'] = str(i._textDesc) if i._textDesc else 'No Description'
params[str(i._id).replace('-','_')] = copy.deepcopy(myhash)
except AttributeError:
pass
try:
rawlist = metadata._types._taggedParams._param
for i in rawlist:
myhash = {}
if i._value:
myhash['type'] = 'selection'
myhash['values'] = [str(z) for z in i._value]
else:
myhash['type'] = str(i._paramType)
if(str(i._paramType)=="FILE"):
myhash['ioType'] = str(i._ioType)
myhash['description'] = str(i._textDesc) if i._textDesc else 'No Description'
myhash['default'] = str(i._default) if i._default else None
params[str(i._id).replace('-','_')] = copy.deepcopy(myhash)
except AttributeError:
pass
try:
rawlist = metadata._types._untaggedParams._param
for i in rawlist:
myhash = {}
myhash['type'] = str(i._paramType)
if(str(i._paramType)=="FILE"):
myhash['ioType'] = str(i._ioType)
myhash['description'] = str(i._textDesc)
myhash['default'] = str(i._default) if i._default else None
params[str(i._id).replace('-','_')] = copy.deepcopy(myhash)
except AttributeError:
pass
myret.append(tab+'params='+str(params))
return myret
def buildClassDeclarationFromCache(self, url, params):
"""docstring for buildClassDeclaration"""
myclassname = url.split('/')[-1].replace('-','_')
myclassname = myclassname.replace('.','_')
#LC 042308 added the server name to the generated classname
servername = urlparse(url)[1]
servername = servername.replace('.','_')
servername = servername.split(':')[0]
myclassname = myclassname + "_" + servername
myclassname = myclassname.replace('-','_')
myret = []
myret.append('class %s:' % myclassname)
oc = OpalCache()
myret.append(tab+'params='+str(params))
return myret
def buildInitMethod(self,metadata,url):
"""docstring for buildInitMethod"""
myret = []
myret = ['def __init__(self):',\
tab+'self.url=\''+url+'\'',\
tab+'from mglutil.web.services.AppService_client import AppServiceLocator,getAppMetadataRequest',\
tab+'appLocator = AppServiceLocator()',\
tab+'appServicePort = appLocator.getAppServicePort(self.url)',\
tab+'req = getAppMetadataRequest()',\
tab+'self.metadata = appServicePort.getAppMetadata(req)'
]
try:
rawlist = metadata._types._flags._flag
flaglist = [str(i._id) for i in rawlist]
except AttributeError:
flaglist = []
try:
rawlist = metadata._types._taggedParams._param
taglist = [str(i._id) for i in rawlist]
except AttributeError:
taglist = []
try:
rawlist = metadata._types._untaggedParams._param
untaglist = [str(i._id) for i in rawlist]
except AttributeError:
untaglist = []
if flaglist:
myret.append(tab+'self.flags='+str(flaglist))
else:
myret.append(tab+'self.flags=[]')
if taglist:
myret.append(tab+'self.taggedparams='+str(taglist))
else:
myret.append(tab+'self.taggedparams=[]')
if untaglist:
myret.append(tab+'self.untaggedparams='+str(untaglist))
else:
myret.append(tab+'self.untaggedparams=[]')
return myret
def buildInitMethodFromCache(self, params, url):
"""docstring for buildInitMethod"""
myret = []
myret = ['def __init__(self):',\
tab+'self.url=\''+url+'\'',\
# tab+'from mglutil.web.services.AppService_client import AppServiceLocator,getAppMetadataRequest',\
# tab+'appLocator = AppServiceLocator()',\
# tab+'appServicePort = appLocator.getAppServicePort(self.url)',\
# tab+'req = getAppMetadataRequest()',\
# tab+'self.metadata = appServicePort.getAppMetadata(req)'
]
flaglist = []
taglist = []
untaglist = []
for k, v in params.iteritems():
if v['config_type'] == 'FLAG':
flaglist.append(k)
elif v['config_type'] == 'TAGGED':
taglist.append(k)
elif v['config_type'] == 'UNTAGGED':
untaglist.append(k)
else:
print "ERROR: Invalid config_type"
if flaglist:
myret.append(tab+'self.flags='+str(flaglist))
else:
myret.append(tab+'self.flags=[]')
if taglist:
myret.append(tab+'self.taggedparams='+str(taglist))
else:
myret.append(tab+'self.taggedparams=[]')
if untaglist:
myret.append(tab+'self.untaggedparams='+str(untaglist))
else:
myret.append(tab+'self.untaggedparams=[]')
return myret
def buildCallMethod(self,metadata):
"""docstring for buildCallMethod"""
myret = []
try:
rawlist = metadata._types._flags._flag
flaglist = [(str(i._id),True) if i._default else (str(i._id),False) for i in rawlist]
except AttributeError:
flaglist = []
try:
rawlist = metadata._types._taggedParams._param
taglist = [(str(i._id),"'"+str(i._default)+"'") if i._default else (str(i._id),"''") for i in rawlist]
except AttributeError:
taglist = []
try:
rawlist = metadata._types._untaggedParams._param
untaglist = [(str(i._id),"''") for i in rawlist]
except AttributeError:
untaglist = []
myparams = []
myparams.extend(flaglist)
myparams.extend(taglist)
myparams.extend(untaglist)
myparams=map(lambda x: (x[0].replace('-','_'),x[1]),myparams)
# add call function start to return array
myret.append('def __call__(self,'+','.join('='.join((i[0],str(i[1]))) for i in myparams)+',localRun=False, execPath=' + repr(self.executable) + '):')
# add variable assignment lines
myret.extend([tab+'self._'+i[0]+'='+i[0] for i in myparams])
# add boilerplate
myret.extend([tab+'myflags=[]',\
tab+'mytaggedparams=[]',\
tab+'myuntaggedparams=[]',\
tab+'for i in self.flags:',\
tab+tab+'varname=\'_\' + i.replace(\'-\',\'_\')',\
tab+tab+'if getattr(self,varname):',\
tab+tab+tab+'myflags.append(i)',\
tab+'for i in self.taggedparams:',\
tab+tab+'varname=\'_\' + i.replace(\'-\',\'_\')',\
tab+tab+'if getattr(self,varname):',\
tab+tab+tab+'mytaggedparams.append((i,getattr(self,varname)))',\
tab+'for i in self.untaggedparams:',\
tab+tab+'varname=\'_\' + i.replace(\'-\',\'_\')',\
tab+tab+'if getattr(self,varname):',\
tab+tab+tab+'myuntaggedparams.append((i,getattr(self,varname)))',\
tab+'from WebServices import OpalUtil',\
tab+'self.myOpalUtil = OpalUtil.OpalUtil(self)',\
tab+'outurls = self.myOpalUtil.launchJob(self.url,myflags,mytaggedparams,myuntaggedparams,self.metadata,localRun,execPath)',\
tab+'return outurls'])
return myret
def buildCallMethodFromCache(self, params):
"""docstring for buildCallMethod"""
myret = []
flaglist = []
taglist = []
untaglist = []
for k, v in params.iteritems():
if v['config_type'] == 'FLAG':
if v['default'] == 'True':
flaglist.append((k, True))
else:
flaglist.append((k, False))
elif v['config_type'] == 'TAGGED':
if v['default']:
taglist.append((k, "'" + v['default'] + "'"))
else:
taglist.append((k, "''"))
elif v['config_type'] == 'UNTAGGED':
untaglist.append((k, "''"))
else:
print "ERROR: Invalid config_type"
myparams = []
myparams.extend(flaglist)
myparams.extend(taglist)
myparams.extend(untaglist)
myparams=map(lambda x: (x[0].replace('-','_'),x[1]),myparams)
# add call function start to return array
myret.append('def __call__(self,'+','.join('='.join((i[0],str(i[1]))) for i in myparams)+',localRun=False, execPath=' + repr(self.executable) + '):')
# add variable assignment lines
myret.extend([tab+'self._'+i[0]+'='+i[0] for i in myparams])
# add boilerplate
myret.extend([tab+'myflags=[]',\
tab+'mytaggedparams=[]',\
tab+'myuntaggedparams=[]',\
tab+'for i in self.flags:',\
tab+tab+'varname=\'_\' + i.replace(\'-\',\'_\')',\
tab+tab+'if getattr(self,varname):',\
tab+tab+tab+'myflags.append(i)',\
tab+'for i in self.taggedparams:',\
tab+tab+'varname=\'_\' + i.replace(\'-\',\'_\')',\
tab+tab+'if getattr(self,varname):',\
tab+tab+tab+'mytaggedparams.append((i,getattr(self,varname)))',\
tab+'for i in self.untaggedparams:',\
tab+tab+'varname=\'_\' + i.replace(\'-\',\'_\')',\
tab+tab+'if getattr(self,varname):',\
tab+tab+tab+'myuntaggedparams.append((i,getattr(self,varname)))',\
tab+'from WebServices import OpalUtil',\
tab+'self.myOpalUtil = OpalUtil.OpalUtil(self)',\
tab+'outurls = self.myOpalUtil.launchJobCachedParams(self.url,myflags,mytaggedparams,myuntaggedparams,self.params,localRun,execPath)',\
tab+'return outurls'])
return myret
def buildDefaultInitMethod(self,url):
"""docstring for buildDefaultInit"""
myret = ['def __init__(self):',\
tab+'self.url=\''+url+'\'',\
tab+'from mglutil.web.services.AppService_client import AppServiceLocator,getAppMetadataRequest',\
tab+'appLocator = AppServiceLocator()',\
tab+'appServicePort = appLocator.getAppServicePort(self.url)',\
tab+'req = getAppMetadataRequest()',\
tab+'self.metadata = appServicePort.getAppMetadata(req)'
]
myret.append(tab+'self.commandline=\'\'')
myret.append(tab+'self.inputfiles=[]')
return myret
def buildDefaultInitMethodFromCache(self,url):
"""docstring for buildDefaultInit"""
myret = ['def __init__(self):',\
tab+'self.url=\''+url+'\'',\
tab+'from mglutil.web.services.AppService_client import AppServiceLocator,getAppMetadataRequest',\
# tab+'appLocator = AppServiceLocator()',\
# tab+'appServicePort = appLocator.getAppServicePort(self.url)',\
# tab+'req = getAppMetadataRequest()',\
# tab+'self.metadata = appServicePort.getAppMetadata(req)'
]
myret.append(tab+'self.commandline=\'\'')
myret.append(tab+'self.inputfiles=[]')
return myret
def buildDefaultCallMethod(self):
"""docstring for buildDefaultCallMethod"""
myret = ["def __call__(self,commandline='',inputfiles=[], numProcs='1',localRun=False,execPath=" + repr(self.executable) + "):",\
tab+'from WebServices import OpalUtil',\
tab+'from string import atoi',\
tab+'self.myOpalUtil = OpalUtil.OpalUtil(self)',\
tab+'outurls = self.myOpalUtil.launchBasicJob(self.url,commandline,inputfiles,atoi(numProcs),localRun,execPath)',\
tab+'return outurls']
return myret
def addOnStoppingExecution(self):
""" this function adds the onStoppingExecution
to destroy running job when users terminate the
workflow
TODO not used anymore
"""
retstring = tab + "def onStoppingExecution(self):\n" +\
tab+tab+ "print \"calling the onStopping execution\"\n" +\
tab+tab+ "#self.myOpalUtil.onStoppingExecution()\n"
return retstring
def which (self, filename):
"""
which definition: given an executable if found on the current path it return the full path to the executable
otherwise it returns ""
"""
if not os.environ.has_key('PATH') or os.environ['PATH'] == '':
p = os.defpath
else:
p = os.environ['PATH']
pathlist = p.split (os.pathsep)
for path in pathlist:
f = os.path.join(path, filename)
if os.access(f, os.X_OK):
return f
#let's try harder to look for the command .bat .sh .exe
#expecially for windows
fAlternative = f + '.exe'
if os.access(fAlternative, os.X_OK):
return fAlternative
fAlternative = f + '.sh'
if os.access(fAlternative, os.X_OK):
return fAlternative
fAlternative = f + '.bat'
if os.access(fAlternative, os.X_OK):
return fAlternative
return ""
#wrap = OpalWrapper()
#print wrap.generate('http://ws.nbcr.net/opal2/services/pdb2pqr_1.4.0')
mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/__init__.py 0000644 0001750 0001750 00000001072 11406004316 024077 0 ustar debian debian ## this version stopped working :( (MS)
## from httplib import HTTP
## from urlparse import urlparse
## def checkURL(url):
## # checking for existence over HTTP
## p = urlparse(url)
## assert p.scheme=='http'
## h = HTTP(p.netloc)
## h.putrequest('HEAD', p.path)
## h.endheaders()
## if h.getreply()[0] == 200: return True
## else: return False
import urllib2
def checkURL(url):
try:
request = urllib2.Request(url, None, {})
response = urllib2.urlopen(request)
return True
except:
return False
mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/Examples/ 0000755 0001750 0001750 00000000000 12146216237 023555 5 ustar debian debian mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/Examples/viperdb_net.py 0000644 0001750 0001750 00000024626 10372426075 026444 0 ustar debian debian ########################################################################
#
# Vision Network - Python source code - file generated by vision
# Wednesday 08 February 2006 09:22:09
#
# The Scripps Research Institute (TSRI)
# Molecular Graphics Lab
# La Jolla, CA 92037, USA
#
# Copyright: Daniel Stoffler, Michel Sanner and TSRI
#
# revision: Guillaume Vareille
#
#########################################################################
#
# $Header: /opt/cvs/WebServices/Examples/viperdb_net.py,v 1.2 2006/02/08 17:37:01 sargis Exp $
#
# $Id: viperdb_net.py,v 1.2 2006/02/08 17:37:01 sargis Exp $
#
from traceback import print_exc
## loading libraries ##
from Pmv.VisionInterface.PmvNodes import pmvlib
masterNet.getEditor().addLibraryInstance(pmvlib,"Pmv.VisionInterface.PmvNodes", "pmvlib")
from symserv.VisionInterface.SymservNodes import symlib
masterNet.getEditor().addLibraryInstance(symlib,"symserv.VisionInterface.SymservNodes", "symlib")
from WebServices.VisionInterface.WSNodes import wslib
masterNet.getEditor().addLibraryInstance(wslib,"WebServices.VisionInterface.WSNodes", "wslib")
from Vision.StandardNodes import stdlib
masterNet.getEditor().addLibraryInstance(stdlib,"Vision.StandardNodes", "stdlib")
try:
## saving node Save Lines ##
from Vision.StandardNodes import SaveLines
Save_Lines_0 = SaveLines(constrkw = {}, name='Save Lines', library=stdlib)
masterNet.addNode(Save_Lines_0,25,112)
Save_Lines_0.inputPortByName['filename'].widget.set("2plv.pdb", run=False)
except:
print "WARNING: failed to restore SaveLines named Save Lines in network masterNet"
print_exc()
Save_Lines_0=None
try:
## saving node Pmv ##
from Pmv.VisionInterface.PmvNodes import PmvNode
Pmv_1 = PmvNode(vf=masterNet.editor.vf, constrkw = {'vf': 'masterNet.editor.vf'}, name='Pmv', library=pmvlib)
masterNet.addNode(Pmv_1,231,8)
except:
print "WARNING: failed to restore PmvNode named Pmv in network masterNet"
print_exc()
Pmv_1=None
try:
## saving node Choose Cmd ##
from Pmv.VisionInterface.PmvNodes import PmvChooseCommand
Choose_Cmd_2 = PmvChooseCommand(constrkw = {}, name='Choose Cmd', library=pmvlib)
masterNet.addNode(Choose_Cmd_2,231,92)
apply(Choose_Cmd_2.inputPortByName['cmdName'].widget.configure, (), {'choices': ['readPDB']})
Choose_Cmd_2.inputPortByName['cmdName'].widget.set("readPDB", run=False)
except:
print "WARNING: failed to restore PmvChooseCommand named Choose Cmd in network masterNet"
print_exc()
Choose_Cmd_2=None
try:
## saving node Run readPDB ##
from Pmv.VisionInterface.PmvNodes import PmvRunCommand
Run_readPDB_3 = PmvRunCommand(sortedArgNames=['topCommand', 'redraw', 'setupUndo', 'log'], command=masterNet.editor.vf.readPDB, namedArgs={'topCommand': True, 'redraw': True, 'setupUndo': True, 'log': True}, posArgsNames=['filename'], constrkw = {'sortedArgNames': "['topCommand', 'redraw', 'setupUndo', 'log']", 'command': 'masterNet.editor.vf.readPDB', 'namedArgs': "{'topCommand': True, 'redraw': True, 'setupUndo': True, 'log': True}", 'posArgsNames': "['filename']"}, name='Run readPDB', library=pmvlib)
masterNet.addNode(Run_readPDB_3,231,175)
apply(Run_readPDB_3.addInputPort, (), {'name': 'filename', 'cast': True, 'datatype': 'string', 'height': 12, 'width': 12, 'shape': 'oval', 'color': 'white'})
apply(Run_readPDB_3.addInputPort, (), {'name': 'topCommand', 'cast': True, 'datatype': 'boolean', 'balloon': 'Defaults toTrue', 'required': False, 'height': 10, 'width': 10, 'shape': 'rect', 'color': 'yellow'})
apply(Run_readPDB_3.addInputPort, (), {'name': 'redraw', 'cast': True, 'datatype': 'boolean', 'balloon': 'Defaults toTrue', 'required': False, 'height': 10, 'width': 10, 'shape': 'rect', 'color': 'yellow'})
apply(Run_readPDB_3.addInputPort, (), {'name': 'setupUndo', 'cast': True, 'datatype': 'boolean', 'balloon': 'Defaults toTrue', 'required': False, 'height': 10, 'width': 10, 'shape': 'rect', 'color': 'yellow'})
apply(Run_readPDB_3.addInputPort, (), {'name': 'log', 'cast': True, 'datatype': 'boolean', 'balloon': 'Defaults toTrue', 'required': False, 'height': 10, 'width': 10, 'shape': 'rect', 'color': 'yellow'})
apply(Run_readPDB_3.inputPortByName['topCommand'].createWidget, (), {'descr':{'initialValue': True, 'labelGridCfg': {'column': 0, 'row': 1, 'sticky': 'w'}, 'master': 'ParamPanel', 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 1}, 'labelCfg': {'text': 'topCommand'}, 'class': 'NECheckButton'}})
apply(Run_readPDB_3.inputPortByName['redraw'].createWidget, (), {'descr':{'initialValue': True, 'labelGridCfg': {'column': 0, 'row': 3, 'sticky': 'w'}, 'master': 'ParamPanel', 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 3}, 'labelCfg': {'text': 'redraw'}, 'class': 'NECheckButton'}})
apply(Run_readPDB_3.inputPortByName['setupUndo'].createWidget, (), {'descr':{'initialValue': True, 'labelGridCfg': {'column': 0, 'row': 5, 'sticky': 'w'}, 'master': 'ParamPanel', 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 5}, 'labelCfg': {'text': 'setupUndo'}, 'class': 'NECheckButton'}})
apply(Run_readPDB_3.inputPortByName['log'].createWidget, (), {'descr':{'initialValue': True, 'labelGridCfg': {'column': 0, 'row': 7, 'sticky': 'w'}, 'master': 'ParamPanel', 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 7}, 'labelCfg': {'text': 'log'}, 'class': 'NECheckButton'}})
code = """
def doit(self, command, filename, topCommand, redraw, setupUndo, log):
if command is None:
return
if command is not self.command and command is not None:
# remember current command
self.command = command
self.rename('Run '+command.name)
# remove all ports beyond the command input port
for p in self.inputPorts[1:]:
self.deletePort(p, updateSignature=False)
# get arguments description
from inspect import getargspec
args = getargspec(command.__call__.im_func)
allNames = args[0][1:] # get rid of self
defaultValues = args[3]
if defaultValues is None:
defaultValues = []
nbNamesArgs = len(defaultValues)
if nbNamesArgs > 0:
self.posArgsNames = args[0][1:-nbNamesArgs]
else:
self.posArgsNames = args[0][1:]
d = {}
for name, val in zip(args[0][-nbNamesArgs:], defaultValues):
d[name] = val
for name, val in zip(self.defaultNamedArgs, self.defaultNamedArgsdefaults):
d[name] = val
self.namedArgs = d
# create input ports for positional arguments
self.createPortsForPositionalArgs(self.posArgsNames)
# create widgets and ports for named arguments
self.sortedArgNames = self.buildPortsForNamedArgs(self.namedArgs)
# create the constructor arguments such that when the node is restored
# from file it will have all the info it needs
self.constrkw['command'] = 'masterNet.editor.vf.%s'%command.name
self.constrkw['posArgsNames'] = str(self.posArgsNames)
self.constrkw['namedArgs'] = str(self.namedArgs)
self.constrkw['sortedArgNames'] = str(self.sortedArgNames)
elif self.command is not None:
# get all positional arguments
posargs = []
for pn in self.posArgsNames:
posargs.append(locals()[pn])
# build named arguments
kw = {}
for arg in self.sortedArgNames:
kw[arg] = locals()[arg]
# call command
value = apply( self.command.__call__, posargs, kw )
self.outputData(result=value)
"""
Run_readPDB_3.configure(function=code)
except:
print "WARNING: failed to restore PmvRunCommand named Run readPDB in network masterNet"
print_exc()
Run_readPDB_3=None
try:
## saving node Set Instances ##
from Pmv.VisionInterface.PmvNodes import PmvSetInstanceMatrices
Set_Instances_4 = PmvSetInstanceMatrices(constrkw = {}, name='Set Instances', library=pmvlib)
masterNet.addNode(Set_Instances_4,233,252)
except:
print "WARNING: failed to restore PmvSetInstanceMatrices named Set Instances in network masterNet"
print_exc()
Set_Instances_4=None
try:
## saving node Icosahedral ##
from symserv.VisionInterface.SymservNodes import Icos1
Icosahedral_5 = Icos1(constrkw = {}, name='Icosahedral', library=symlib)
masterNet.addNode(Icosahedral_5,372,177)
## saving connections for network Icosahedral ##
Icosahedral_5.macroNetwork.freeze()
Icosahedral_5.macroNetwork.unfreeze()
## modifying MacroOutputNode dynamic ports
output_Ports_7 = Icosahedral_5.macroNetwork.opNode
output_Ports_7.inputPorts[1].configure(singleConnection=True)
Icosahedral_5.shrink()
except:
print "WARNING: failed to restore Icos1 named Icosahedral in network masterNet"
print_exc()
Icosahedral_5=None
try:
## saving node viperdb@mgldev.scripps ##
from WebServices.VisionInterface.WSNodes import viperdbNode
viperdb_mgldev_scripps_14 = viperdbNode(host='http://mgldev.scripps.edu/services', constrkw = {'host': "'http://mgldev.scripps.edu/services'"}, name='viperdb@mgldev.scripps', library=wslib)
masterNet.addNode(viperdb_mgldev_scripps_14,8,6)
viperdb_mgldev_scripps_14.inputPortByName['pdb_id'].widget.set("2plv", run=False)
except:
print "WARNING: failed to restore viperdbNode named viperdb@mgldev.scripps in network masterNet"
print_exc()
viperdb_mgldev_scripps_14=None
masterNet.freeze()
## saving connections for network viperdb ##
if Pmv_1 is not None and Choose_Cmd_2 is not None:
masterNet.connectNodes(
Pmv_1, Choose_Cmd_2, "PMV", "viewer", blocking=True)
if Choose_Cmd_2 is not None and Run_readPDB_3 is not None:
masterNet.connectNodes(
Choose_Cmd_2, Run_readPDB_3, "cmd", "command", blocking=True)
if Save_Lines_0 is not None and Run_readPDB_3 is not None:
masterNet.connectNodes(
Save_Lines_0, Run_readPDB_3, "filename", "filename", blocking=True)
if Run_readPDB_3 is not None and Set_Instances_4 is not None:
masterNet.connectNodes(
Run_readPDB_3, Set_Instances_4, "result", "molecule", blocking=True)
if Icosahedral_5 is not None and Set_Instances_4 is not None:
masterNet.connectNodes(
Icosahedral_5, Set_Instances_4, "Merge_outMatrices", "matrices", blocking=True)
if viperdb_mgldev_scripps_14 is not None and Save_Lines_0 is not None:
masterNet.connectNodes(
viperdb_mgldev_scripps_14, Save_Lines_0, "output", "data", blocking=True)
masterNet.unfreeze()
mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/Examples/babel_net.py 0000644 0001750 0001750 00000022766 10372426012 026050 0 ustar debian debian ########################################################################
#
# Vision Network - Python source code - file generated by vision
# Tuesday 07 February 2006 16:20:41
#
# The Scripps Research Institute (TSRI)
# Molecular Graphics Lab
# La Jolla, CA 92037, USA
#
# Copyright: Daniel Stoffler, Michel Sanner and TSRI
#
# revision: Guillaume Vareille
#
#########################################################################
#
# $Header: /opt/cvs/WebServices/Examples/babel_net.py,v 1.2 2006/02/08 17:36:10 sargis Exp $
#
# $Id: babel_net.py,v 1.2 2006/02/08 17:36:10 sargis Exp $
#
from traceback import print_exc
## loading libraries ##
from Pmv.VisionInterface.PmvNodes import pmvlib
masterNet.getEditor().addLibraryInstance(pmvlib,"Pmv.VisionInterface.PmvNodes", "pmvlib")
from WebServices.VisionInterface.WSNodes import wslib
masterNet.getEditor().addLibraryInstance(wslib,"WebServices.VisionInterface.WSNodes", "wslib")
from Vision.StandardNodes import stdlib
masterNet.getEditor().addLibraryInstance(stdlib,"Vision.StandardNodes", "stdlib")
try:
## saving node Save Lines ##
from Vision.StandardNodes import SaveLines
Save_Lines_0 = SaveLines(constrkw = {}, name='Save Lines', library=stdlib)
masterNet.addNode(Save_Lines_0,44,211)
Save_Lines_0.inputPortByName['filename'].widget.set("HISH.pdb", run=False)
except:
print "WARNING: failed to restore SaveLines named Save Lines in network masterNet"
print_exc()
Save_Lines_0=None
try:
## saving node Pmv ##
from Pmv.VisionInterface.PmvNodes import PmvNode
Pmv_1 = PmvNode(vf=masterNet.editor.vf, constrkw = {'vf': 'masterNet.editor.vf'}, name='Pmv', library=pmvlib)
masterNet.addNode(Pmv_1,286,14)
except:
print "WARNING: failed to restore PmvNode named Pmv in network masterNet"
print_exc()
Pmv_1=None
try:
## saving node Choose Cmd ##
from Pmv.VisionInterface.PmvNodes import PmvChooseCommand
Choose_Cmd_2 = PmvChooseCommand(constrkw = {}, name='Choose Cmd', library=pmvlib)
masterNet.addNode(Choose_Cmd_2,286,104)
apply(Choose_Cmd_2.inputPortByName['cmdName'].widget.configure, (), {'choices': ['readPDB']})
Choose_Cmd_2.inputPortByName['cmdName'].widget.set("readPDB", run=False)
except:
print "WARNING: failed to restore PmvChooseCommand named Choose Cmd in network masterNet"
print_exc()
Choose_Cmd_2=None
try:
## saving node Run readPDB ##
from Pmv.VisionInterface.PmvNodes import PmvRunCommand
Run_readPDB_3 = PmvRunCommand(sortedArgNames=['topCommand', 'redraw', 'setupUndo', 'log'], command=masterNet.editor.vf.readPDB, namedArgs={'topCommand': True, 'redraw': True, 'setupUndo': True, 'log': True}, posArgsNames=['filename'], constrkw = {'sortedArgNames': "['topCommand', 'redraw', 'setupUndo', 'log']", 'command': 'masterNet.editor.vf.readPDB', 'namedArgs': "{'topCommand': True, 'redraw': True, 'setupUndo': True, 'log': True}", 'posArgsNames': "['filename']"}, name='Run readPDB', library=pmvlib)
masterNet.addNode(Run_readPDB_3,286,211)
apply(Run_readPDB_3.addInputPort, (), {'name': 'filename', 'cast': True, 'datatype': 'string', 'height': 12, 'width': 12, 'shape': 'oval', 'color': 'white'})
apply(Run_readPDB_3.addInputPort, (), {'name': 'topCommand', 'cast': True, 'datatype': 'boolean', 'balloon': 'Defaults toTrue', 'required': False, 'height': 10, 'width': 10, 'shape': 'rect', 'color': 'yellow'})
apply(Run_readPDB_3.addInputPort, (), {'name': 'redraw', 'cast': True, 'datatype': 'boolean', 'balloon': 'Defaults toTrue', 'required': False, 'height': 10, 'width': 10, 'shape': 'rect', 'color': 'yellow'})
apply(Run_readPDB_3.addInputPort, (), {'name': 'setupUndo', 'cast': True, 'datatype': 'boolean', 'balloon': 'Defaults toTrue', 'required': False, 'height': 10, 'width': 10, 'shape': 'rect', 'color': 'yellow'})
apply(Run_readPDB_3.addInputPort, (), {'name': 'log', 'cast': True, 'datatype': 'boolean', 'balloon': 'Defaults toTrue', 'required': False, 'height': 10, 'width': 10, 'shape': 'rect', 'color': 'yellow'})
apply(Run_readPDB_3.inputPortByName['topCommand'].createWidget, (), {'descr':{'initialValue': True, 'labelGridCfg': {'column': 0, 'row': 1, 'sticky': 'w'}, 'master': 'ParamPanel', 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 1}, 'labelCfg': {'text': 'topCommand'}, 'class': 'NECheckButton'}})
apply(Run_readPDB_3.inputPortByName['redraw'].createWidget, (), {'descr':{'initialValue': True, 'labelGridCfg': {'column': 0, 'row': 3, 'sticky': 'w'}, 'master': 'ParamPanel', 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 3}, 'labelCfg': {'text': 'redraw'}, 'class': 'NECheckButton'}})
apply(Run_readPDB_3.inputPortByName['setupUndo'].createWidget, (), {'descr':{'initialValue': True, 'labelGridCfg': {'column': 0, 'row': 5, 'sticky': 'w'}, 'master': 'ParamPanel', 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 5}, 'labelCfg': {'text': 'setupUndo'}, 'class': 'NECheckButton'}})
apply(Run_readPDB_3.inputPortByName['log'].createWidget, (), {'descr':{'initialValue': True, 'labelGridCfg': {'column': 0, 'row': 7, 'sticky': 'w'}, 'master': 'ParamPanel', 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 7}, 'labelCfg': {'text': 'log'}, 'class': 'NECheckButton'}})
code = """
def doit(self, command, filename, topCommand, redraw, setupUndo, log):
if command is None:
return
if command is not self.command and command is not None:
# remember current command
self.command = command
self.rename('Run '+command.name)
# remove all ports beyond the command input port
for p in self.inputPorts[1:]:
self.deletePort(p, updateSignature=False)
# get arguments description
from inspect import getargspec
args = getargspec(command.__call__.im_func)
allNames = args[0][1:] # get rid of self
defaultValues = args[3]
if defaultValues is None:
defaultValues = []
nbNamesArgs = len(defaultValues)
if nbNamesArgs > 0:
self.posArgsNames = args[0][1:-nbNamesArgs]
else:
self.posArgsNames = args[0][1:]
d = {}
for name, val in zip(args[0][-nbNamesArgs:], defaultValues):
d[name] = val
for name, val in zip(self.defaultNamedArgs, self.defaultNamedArgsdefaults):
d[name] = val
self.namedArgs = d
# create input ports for positional arguments
self.createPortsForPositionalArgs(self.posArgsNames)
# create widgets and ports for named arguments
self.sortedArgNames = self.buildPortsForNamedArgs(self.namedArgs)
# create the constructor arguments such that when the node is restored
# from file it will have all the info it needs
self.constrkw['command'] = 'masterNet.editor.vf.%s'%command.name
self.constrkw['posArgsNames'] = str(self.posArgsNames)
self.constrkw['namedArgs'] = str(self.namedArgs)
self.constrkw['sortedArgNames'] = str(self.sortedArgNames)
elif self.command is not None:
# get all positional arguments
posargs = []
for pn in self.posArgsNames:
posargs.append(locals()[pn])
# build named arguments
kw = {}
for arg in self.sortedArgNames:
kw[arg] = locals()[arg]
# call command
value = apply( self.command.__call__, posargs, kw )
self.outputData(result=value)
"""
Run_readPDB_3.configure(function=code)
except:
print "WARNING: failed to restore PmvRunCommand named Run readPDB in network masterNet"
print_exc()
Run_readPDB_3=None
try:
## saving node HIS ##
import WebServices
path = WebServices.__path__[0]
import os
path = path + os.sep + 'Examples' + os.sep + 'HIS.pdb'
mol = masterNet.editor.vf.loadMoleculeIfNeeded(path)
from Pmv.VisionInterface.PmvNodes import PmvMolecule
HIS_4 = PmvMolecule(molecule=masterNet.editor.vf.expandNodes("HIS")[0], constrkw = {'molecule': 'masterNet.editor.vf.expandNodes("HIS")[0]'}, name='HIS', library=pmvlib)
masterNet.addNode(HIS_4,44,5)
except:
print "WARNING: failed to restore PmvMolecule named HIS in network masterNet"
print_exc()
HIS_4=None
try:
## saving node Babel@mgldev.scripps ##
from WebServices.VisionInterface.WSNodes import BabelNode
Babel_mgldev_scripps_6 = BabelNode(host='http://mgldev.scripps.edu/services', constrkw = {'host': "'http://mgldev.scripps.edu/services'"}, name='Babel@mgldev.scripps', library=wslib)
masterNet.addNode(Babel_mgldev_scripps_6,27,86)
except:
print "WARNING: failed to restore BabelNode named Babel@mgldev.scripps in network masterNet"
print_exc()
Babel_mgldev_scripps_6=None
masterNet.freeze()
## saving connections for network babel ##
if Pmv_1 is not None and Choose_Cmd_2 is not None:
masterNet.connectNodes(
Pmv_1, Choose_Cmd_2, "PMV", "viewer", blocking=True)
if Choose_Cmd_2 is not None and Run_readPDB_3 is not None:
masterNet.connectNodes(
Choose_Cmd_2, Run_readPDB_3, "cmd", "command", blocking=True)
if Save_Lines_0 is not None and Run_readPDB_3 is not None:
masterNet.connectNodes(
Save_Lines_0, Run_readPDB_3, "filename", "filename", blocking=True)
if HIS_4 is not None and Babel_mgldev_scripps_6 is not None:
masterNet.connectNodes(
HIS_4, Babel_mgldev_scripps_6, "Molecule", "input_mol", blocking=True)
if Babel_mgldev_scripps_6 is not None and Save_Lines_0 is not None:
masterNet.connectNodes(
Babel_mgldev_scripps_6, Save_Lines_0, "output_file_url", "data", blocking=True)
masterNet.unfreeze()
mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/Examples/msms_net.py 0000644 0001750 0001750 00000011047 10372426032 025752 0 ustar debian debian ########################################################################
#
# Vision Network - Python source code - file generated by vision
# Tuesday 07 February 2006 17:06:32
#
# The Scripps Research Institute (TSRI)
# Molecular Graphics Lab
# La Jolla, CA 92037, USA
#
# Copyright: Daniel Stoffler, Michel Sanner and TSRI
#
# revision: Guillaume Vareille
#
#########################################################################
#
# $Header: /opt/cvs/WebServices/Examples/msms_net.py,v 1.2 2006/02/08 17:36:26 sargis Exp $
#
# $Id: msms_net.py,v 1.2 2006/02/08 17:36:26 sargis Exp $
#
from traceback import print_exc
## loading libraries ##
from Pmv.VisionInterface.PmvNodes import pmvlib
masterNet.getEditor().addLibraryInstance(pmvlib,"Pmv.VisionInterface.PmvNodes", "pmvlib")
from WebServices.VisionInterface.WSNodes import wslib
masterNet.getEditor().addLibraryInstance(wslib,"WebServices.VisionInterface.WSNodes", "wslib")
from Vision.StandardNodes import stdlib
masterNet.getEditor().addLibraryInstance(stdlib,"Vision.StandardNodes", "stdlib")
from MolKit.VisionInterface.MolKitNodes import molkitlib
masterNet.getEditor().addLibraryInstance(molkitlib,"MolKit.VisionInterface.MolKitNodes", "molkitlib")
from DejaVu.VisionInterface.DejaVuNodes import vizlib
masterNet.getEditor().addLibraryInstance(vizlib,"DejaVu.VisionInterface.DejaVuNodes", "vizlib")
try:
## saving node Pmv Viewer ##
from Pmv.VisionInterface.PmvNodes import PmvViewer
Pmv_Viewer_0 = PmvViewer(viewer=masterNet.editor.vf.GUI.VIEWER, constrkw = {'viewer': 'masterNet.editor.vf.GUI.VIEWER'}, name='Pmv Viewer', library=pmvlib)
masterNet.addNode(Pmv_Viewer_0,67,184)
except:
print "WARNING: failed to restore PmvViewer named Pmv Viewer in network masterNet"
print_exc()
Pmv_Viewer_0=None
try:
import WebServices
path = WebServices.__path__[0]
import os
path = path + os.sep + 'Examples' + os.sep + 'HIS.pdb'
mol = masterNet.editor.vf.loadMoleculeIfNeeded(path)
from Pmv.VisionInterface.PmvNodes import PmvMolecule
HIS_1 = PmvMolecule(molecule=masterNet.editor.vf.expandNodes("HIS")[0], constrkw = {'molecule': 'masterNet.editor.vf.expandNodes("HIS")[0]'}, name='HIS', library=pmvlib)
masterNet.addNode(HIS_1,69,17)
except:
print "WARNING: failed to restore PmvMolecule named HIS in network masterNet"
print_exc()
HIS_1=None
try:
## saving node MSMS@mgldev.scripps ##
from WebServices.VisionInterface.msms_ws import msms_wsMacroNode
MSMS_mgldev_scripps_10 = msms_wsMacroNode(host='http://mgldev.scripps.edu/services', constrkw = {'host': "'http://mgldev.scripps.edu/services'"}, name='MSMS@mgldev.scripps', library=wslib)
masterNet.addNode(MSMS_mgldev_scripps_10,67,90)
MSMS_WS_17 = MSMS_mgldev_scripps_10.macroNetwork.nodes[6]
apply(MSMS_WS_17.inputPortByName['density'].createWidget, (), {'descr':{'initialValue': 1.0, 'min': 1.0, 'labelGridCfg': {'column': 0, 'row': 3}, 'master': 'ParamPanel', 'increment': 0.10000000000000001, 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 3}, 'labelCfg': {'text': 'density'}, 'class': 'NEDial', 'oneTurn': 10}})
apply(MSMS_WS_17.inputPortByName['probe_radius'].createWidget, (), {'descr':{'initialValue': 1.5, 'min': 0.5, 'labelGridCfg': {'column': 0, 'row': 5}, 'master': 'ParamPanel', 'increment': 0.10000000000000001, 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 5}, 'labelCfg': {'text': 'probe radius'}, 'class': 'NEDial', 'oneTurn': 10}})
apply(MSMS_WS_17.inputPortByName['allComp'].createWidget, (), {'descr':{'initialValue': 0, 'labelGridCfg': {'column': 0, 'row': 7}, 'master': 'ParamPanel', 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 7}, 'labelCfg': {'text': 'all components'}, 'class': 'NECheckButton'}})
## saving connections for network MSMS@mgldev.scripps ##
MSMS_mgldev_scripps_10.macroNetwork.freeze()
MSMS_mgldev_scripps_10.macroNetwork.unfreeze()
MSMS_mgldev_scripps_10.shrink()
except:
print "WARNING: failed to restore msms_wsMacroNode named MSMS@mgldev.scripps in network masterNet"
print_exc()
MSMS_mgldev_scripps_10=None
masterNet.freeze()
## saving connections for network msms ##
if HIS_1 is not None and MSMS_mgldev_scripps_10 is not None:
masterNet.connectNodes(
HIS_1, MSMS_mgldev_scripps_10, "Molecule", "Assign Radii_molecules", blocking=True)
if MSMS_mgldev_scripps_10 is not None and Pmv_Viewer_0 is not None:
masterNet.connectNodes(
MSMS_mgldev_scripps_10, Pmv_Viewer_0, "IndexedPolygons_indexedPolygons", "geometries", blocking=True)
masterNet.unfreeze()
mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/Examples/pdb2pqr_pmvnet.py 0000644 0001750 0001750 00000007543 10746477474 027123 0 ustar debian debian ########################################################################
#
# Vision Network - Python source code - file generated by vision
# Friday 25 January 2008 16:17:06
#
# The Scripps Research Institute (TSRI)
# Molecular Graphics Lab
# La Jolla, CA 92037, USA
#
# Copyright: Daniel Stoffler, Michel Sanner and TSRI
#
# revision: Guillaume Vareille
#
#########################################################################
#
# $Header: /opt/cvs/WebServices/Examples/pdb2pqr_pmvnet.py,v 1.1 2008/01/26 00:30:52 sargis Exp $
#
# $Id: pdb2pqr_pmvnet.py,v 1.1 2008/01/26 00:30:52 sargis Exp $
#
from traceback import print_exc
## loading libraries ##
from Vision.StandardNodes import stdlib
masterNet.getEditor().addLibraryInstance(stdlib,"Vision.StandardNodes", "stdlib")
from WebServices.VisionInterface.WSNodes import wslib
masterNet.getEditor().addLibraryInstance(wslib,"WebServices.VisionInterface.WSNodes", "wslib")
try:
## saving node pdb2pqr@ws.nbcr ##
from WebServices.VisionInterface.WSNodes import pdb2pqrNode
pdb2pqr_ws_nbcr_1 = pdb2pqrNode(service='http://ws.nbcr.net:8080/opal/services/Pdb2pqrOpalService', name='pdb2pqr@ws.nbcr', library=wslib)
masterNet.addNode(pdb2pqr_ws_nbcr_1,360,146)
except:
print "WARNING: failed to restore pdb2pqrNode named pdb2pqr@ws.nbcr in network masterNet"
print_exc()
pdb2pqr_ws_nbcr_1=None
try:
## saving node Download ##
from WebServices.VisionInterface.WSNodes import DownloadNode
Download_2 = DownloadNode(name='Download', library=wslib)
masterNet.addNode(Download_2,31,108)
Download_2.inputPortByName['url'].widget.set("http://www.pdb.org/pdb/download/downloadFile.do?fileFormat=pdb&compression=NO&structureId=1CRN", run=False)
apply(Download_2.configure, (), {'expanded': True})
except:
print "WARNING: failed to restore DownloadNode named Download in network masterNet"
print_exc()
Download_2=None
try:
## saving node Save Lines ##
from Vision.StandardNodes import SaveLines
Save_Lines_3 = SaveLines(name='Save Lines', library=stdlib)
masterNet.addNode(Save_Lines_3,56,207)
Save_Lines_3.inputPortByName['filename'].widget.set("1crn.pdb", run=False)
apply(Save_Lines_3.configure, (), {'expanded': True})
except:
print "WARNING: failed to restore SaveLines named Save Lines in network masterNet"
print_exc()
Save_Lines_3=None
try:
## saving node WebBrowser ##
from WebServices.VisionInterface.WSNodes import WebBrowserNode
WebBrowser_4 = WebBrowserNode(name='WebBrowser', library=wslib)
masterNet.addNode(WebBrowser_4,331,262)
WebBrowser_4.inputPortByName['url'].widget.set("", run=False)
WebBrowser_4.inputPortByName['url'].unbindWidget()
except:
print "WARNING: failed to restore WebBrowserNode named WebBrowser in network masterNet"
print_exc()
WebBrowser_4=None
masterNet.run()
masterNet.freeze()
## saving connections for network Network0 ##
if Download_2 is not None and Save_Lines_3 is not None:
try:
masterNet.connectNodes(
Download_2, Save_Lines_3, "output", "data", blocking=True)
except:
print "WARNING: failed to restore connection between Download_2 and Save_Lines_3 in network masterNet"
if Save_Lines_3 is not None and pdb2pqr_ws_nbcr_1 is not None:
try:
masterNet.connectNodes(
Save_Lines_3, pdb2pqr_ws_nbcr_1, "filename", "input_file", blocking=True)
except:
print "WARNING: failed to restore connection between Save_Lines_3 and pdb2pqr_ws_nbcr_1 in network masterNet"
if pdb2pqr_ws_nbcr_1 is not None and WebBrowser_4 is not None:
try:
masterNet.connectNodes(
pdb2pqr_ws_nbcr_1, WebBrowser_4, "URL", "url", blocking=True)
except:
print "WARNING: failed to restore connection between pdb2pqr_ws_nbcr_1 and WebBrowser_4 in network masterNet"
masterNet.unfreeze()
#masterNet.run()
mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/Examples/pdb2pqr_net.py 0000644 0001750 0001750 00000023025 10372426054 026350 0 ustar debian debian ########################################################################
#
# Vision Network - Python source code - file generated by vision
# Tuesday 07 February 2006 17:08:06
#
# The Scripps Research Institute (TSRI)
# Molecular Graphics Lab
# La Jolla, CA 92037, USA
#
# Copyright: Daniel Stoffler, Michel Sanner and TSRI
#
# revision: Guillaume Vareille
#
#########################################################################
#
# $Header: /opt/cvs/WebServices/Examples/pdb2pqr_net.py,v 1.2 2006/02/08 17:36:44 sargis Exp $
#
# $Id: pdb2pqr_net.py,v 1.2 2006/02/08 17:36:44 sargis Exp $
#
from traceback import print_exc
## loading libraries ##
from Pmv.VisionInterface.PmvNodes import pmvlib
masterNet.getEditor().addLibraryInstance(pmvlib,"Pmv.VisionInterface.PmvNodes", "pmvlib")
from WebServices.VisionInterface.WSNodes import wslib
masterNet.getEditor().addLibraryInstance(wslib,"WebServices.VisionInterface.WSNodes", "wslib")
from Vision.StandardNodes import stdlib
masterNet.getEditor().addLibraryInstance(stdlib,"Vision.StandardNodes", "stdlib")
try:
## saving node Save Lines ##
from Vision.StandardNodes import SaveLines
Save_Lines_10 = SaveLines(constrkw = {}, name='Save Lines', library=stdlib)
masterNet.addNode(Save_Lines_10,49,201)
Save_Lines_10.inputPortByName['filename'].widget.set("HIS.pqr", run=False)
except:
print "WARNING: failed to restore SaveLines named Save Lines in network masterNet"
print_exc()
Save_Lines_10=None
try:
## saving node Pmv ##
from Pmv.VisionInterface.PmvNodes import PmvNode
Pmv_11 = PmvNode(vf=masterNet.editor.vf, constrkw = {'vf': 'masterNet.editor.vf'}, name='Pmv', library=pmvlib)
masterNet.addNode(Pmv_11,224,25)
except:
print "WARNING: failed to restore PmvNode named Pmv in network masterNet"
print_exc()
Pmv_11=None
try:
## saving node Choose Cmd ##
from Pmv.VisionInterface.PmvNodes import PmvChooseCommand
Choose_Cmd_12 = PmvChooseCommand(constrkw = {}, name='Choose Cmd', library=pmvlib)
masterNet.addNode(Choose_Cmd_12,224,123)
apply(Choose_Cmd_12.inputPortByName['cmdName'].widget.configure, (), {'choices': ['readPQR']})
Choose_Cmd_12.inputPortByName['cmdName'].widget.set("readPQR", run=False)
except:
print "WARNING: failed to restore PmvChooseCommand named Choose Cmd in network masterNet"
print_exc()
Choose_Cmd_12=None
try:
## saving node Run readPQR ##
from Pmv.VisionInterface.PmvNodes import PmvRunCommand
Run_readPQR_13 = PmvRunCommand(sortedArgNames=['topCommand', 'redraw', 'setupUndo', 'log'], command=masterNet.editor.vf.readPQR, namedArgs={'topCommand': True, 'redraw': True, 'setupUndo': True, 'log': True}, posArgsNames=['filename'], constrkw = {'sortedArgNames': "['topCommand', 'redraw', 'setupUndo', 'log']", 'command': 'masterNet.editor.vf.readPQR', 'namedArgs': "{'topCommand': True, 'redraw': True, 'setupUndo': True, 'log': True}", 'posArgsNames': "['filename']"}, name='Run readPQR', library=pmvlib)
masterNet.addNode(Run_readPQR_13,224,230)
apply(Run_readPQR_13.addInputPort, (), {'name': 'filename', 'cast': True, 'datatype': 'string', 'height': 12, 'width': 12, 'shape': 'oval', 'color': 'white'})
apply(Run_readPQR_13.addInputPort, (), {'name': 'topCommand', 'cast': True, 'datatype': 'boolean', 'balloon': 'Defaults toTrue', 'required': False, 'height': 10, 'width': 10, 'shape': 'rect', 'color': 'yellow'})
apply(Run_readPQR_13.addInputPort, (), {'name': 'redraw', 'cast': True, 'datatype': 'boolean', 'balloon': 'Defaults toTrue', 'required': False, 'height': 10, 'width': 10, 'shape': 'rect', 'color': 'yellow'})
apply(Run_readPQR_13.addInputPort, (), {'name': 'setupUndo', 'cast': True, 'datatype': 'boolean', 'balloon': 'Defaults toTrue', 'required': False, 'height': 10, 'width': 10, 'shape': 'rect', 'color': 'yellow'})
apply(Run_readPQR_13.addInputPort, (), {'name': 'log', 'cast': True, 'datatype': 'boolean', 'balloon': 'Defaults toTrue', 'required': False, 'height': 10, 'width': 10, 'shape': 'rect', 'color': 'yellow'})
apply(Run_readPQR_13.inputPortByName['topCommand'].createWidget, (), {'descr':{'initialValue': True, 'labelGridCfg': {'column': 0, 'row': 1, 'sticky': 'w'}, 'master': 'ParamPanel', 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 1}, 'labelCfg': {'text': 'topCommand'}, 'class': 'NECheckButton'}})
apply(Run_readPQR_13.inputPortByName['redraw'].createWidget, (), {'descr':{'initialValue': True, 'labelGridCfg': {'column': 0, 'row': 3, 'sticky': 'w'}, 'master': 'ParamPanel', 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 3}, 'labelCfg': {'text': 'redraw'}, 'class': 'NECheckButton'}})
apply(Run_readPQR_13.inputPortByName['setupUndo'].createWidget, (), {'descr':{'initialValue': True, 'labelGridCfg': {'column': 0, 'row': 5, 'sticky': 'w'}, 'master': 'ParamPanel', 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 5}, 'labelCfg': {'text': 'setupUndo'}, 'class': 'NECheckButton'}})
apply(Run_readPQR_13.inputPortByName['log'].createWidget, (), {'descr':{'initialValue': True, 'labelGridCfg': {'column': 0, 'row': 7, 'sticky': 'w'}, 'master': 'ParamPanel', 'widgetGridCfg': {'column': 1, 'labelSide': 'left', 'row': 7}, 'labelCfg': {'text': 'log'}, 'class': 'NECheckButton'}})
code = """
def doit(self, command, filename, topCommand, redraw, setupUndo, log):
if command is None:
return
if command is not self.command and command is not None:
# remember current command
self.command = command
self.rename('Run '+command.name)
# remove all ports beyond the command input port
for p in self.inputPorts[1:]:
self.deletePort(p, updateSignature=False)
# get arguments description
from inspect import getargspec
args = getargspec(command.__call__.im_func)
allNames = args[0][1:] # get rid of self
defaultValues = args[3]
if defaultValues is None:
defaultValues = []
nbNamesArgs = len(defaultValues)
if nbNamesArgs > 0:
self.posArgsNames = args[0][1:-nbNamesArgs]
else:
self.posArgsNames = args[0][1:]
d = {}
for name, val in zip(args[0][-nbNamesArgs:], defaultValues):
d[name] = val
for name, val in zip(self.defaultNamedArgs, self.defaultNamedArgsdefaults):
d[name] = val
self.namedArgs = d
# create input ports for positional arguments
self.createPortsForPositionalArgs(self.posArgsNames)
# create widgets and ports for named arguments
self.sortedArgNames = self.buildPortsForNamedArgs(self.namedArgs)
# create the constructor arguments such that when the node is restored
# from file it will have all the info it needs
self.constrkw['command'] = 'masterNet.editor.vf.%s'%command.name
self.constrkw['posArgsNames'] = str(self.posArgsNames)
self.constrkw['namedArgs'] = str(self.namedArgs)
self.constrkw['sortedArgNames'] = str(self.sortedArgNames)
elif self.command is not None:
# get all positional arguments
posargs = []
for pn in self.posArgsNames:
posargs.append(locals()[pn])
# build named arguments
kw = {}
for arg in self.sortedArgNames:
kw[arg] = locals()[arg]
# call command
value = apply( self.command.__call__, posargs, kw )
self.outputData(result=value)
"""
Run_readPQR_13.configure(function=code)
except:
print "WARNING: failed to restore PmvRunCommand named Run readPQR in network masterNet"
print_exc()
Run_readPQR_13=None
try:
import WebServices
path = WebServices.__path__[0]
import os
path = path + os.sep + 'Examples' + os.sep + 'HIS.pdb'
mol = masterNet.editor.vf.loadMoleculeIfNeeded(path)
from Pmv.VisionInterface.PmvNodes import PmvMolecule
HIS_14 = PmvMolecule(molecule=masterNet.editor.vf.expandNodes("HIS")[0], constrkw = {'molecule': 'masterNet.editor.vf.expandNodes("HIS")[0]'}, name='HIS', library=pmvlib)
masterNet.addNode(HIS_14,49,8)
except:
print "WARNING: failed to restore PmvMolecule named HIS in network masterNet"
print_exc()
HIS_14=None
try:
## saving node pdb2pqr@ws.nbcr ##
from WebServices.VisionInterface.WSNodes import pdb2pqrNode
pdb2pqr_ws_nbcr_16 = pdb2pqrNode(host='http://ws.nbcr.net:8080', constrkw = {'host': "'http://ws.nbcr.net:8080'"}, name='pdb2pqr@ws.nbcr', library=wslib)
masterNet.addNode(pdb2pqr_ws_nbcr_16,32,87)
apply(pdb2pqr_ws_nbcr_16.configure, (), {'expanded': False})
except:
print "WARNING: failed to restore pdb2pqrNode named pdb2pqr@ws.nbcr in network masterNet"
print_exc()
pdb2pqr_ws_nbcr_16=None
masterNet.freeze()
## saving connections for network pdb2pqr ##
if Pmv_11 is not None and Choose_Cmd_12 is not None:
masterNet.connectNodes(
Pmv_11, Choose_Cmd_12, "PMV", "viewer", blocking=True)
if Choose_Cmd_12 is not None and Run_readPQR_13 is not None:
masterNet.connectNodes(
Choose_Cmd_12, Run_readPQR_13, "cmd", "command", blocking=True)
if Save_Lines_10 is not None and Run_readPQR_13 is not None:
masterNet.connectNodes(
Save_Lines_10, Run_readPQR_13, "filename", "filename", blocking=True)
if HIS_14 is not None and pdb2pqr_ws_nbcr_16 is not None:
masterNet.connectNodes(
HIS_14, pdb2pqr_ws_nbcr_16, "Molecule", "input_mol", blocking=True)
if pdb2pqr_ws_nbcr_16 is not None and Save_Lines_10 is not None:
masterNet.connectNodes(
pdb2pqr_ws_nbcr_16, Save_Lines_10, "output_file_url", "data", blocking=True)
masterNet.unfreeze()
mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/Examples/README 0000644 0001750 0001750 00000001774 10746477474 024466 0 ustar debian debian This folder contains the following examples of Vision network:
pdb2pqr_net.py: reads 1crn from pdb.org saves it and runs pdb2pqr web service
The following networks are here for historic reasons
babel_net.py: reads HIS.pdb, sends it to Babel web service at
http://mgldev.scripps.edu/services, that adds missing Hydrogens,
which we then retrieve and display in PMV.
msms_net.py: reads HIS.pdb, sends it to MSMS web service at
http://mgldev.scripps.edu/services, that computes molecular
surface which we then retrieve and display in PMV.
pdb2pqr_net.py: reads HIS.pdb, sends it to pdb2pqr web service at
http://ws.nbcr.net:8080, that converts pdb to pqr
which we then retrieve and display in PMV.
viperdb_met.py: sends '2plv' pdb_id to viperdb web service at
http://mgldev.scripps.edu/services that retrieves 2plv.pdb
which we then display in PMV.
mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/Examples/HIS.pdb 0000644 0001750 0001750 00000001643 10366464453 024702 0 ustar debian debian ATOM 1845 N HIS C 239 -22.680 -32.902 -2.959 1.00 9.05 1HSL N
ATOM 1846 CA HIS C 239 -21.660 -33.527 -3.789 1.00 9.25 1HSL C
ATOM 1847 C HIS C 239 -21.225 -34.791 -3.116 1.00 11.67 1HSL C
ATOM 1848 O HIS C 239 -20.505 -35.546 -3.735 1.00 11.76 1HSL O
ATOM 1849 CB HIS C 239 -20.371 -32.684 -4.038 1.00 11.61 1HSL C
ATOM 1850 CG HIS C 239 -19.377 -32.207 -2.957 1.00 16.21 1HSL C
ATOM 1851 ND1 HIS C 239 -18.132 -31.775 -3.210 1.00 13.83 1HSL N
ATOM 1852 CD2 HIS C 239 -19.599 -32.044 -1.604 1.00 13.47 1HSL C
ATOM 1853 CE1 HIS C 239 -17.602 -31.360 -2.085 1.00 14.22 1HSL C
ATOM 1854 NE2 HIS C 239 -18.490 -31.526 -1.152 1.00 14.78 1HSL N
ATOM 1855 OXT HIS C 239 -21.677 -35.049 -1.996 1.00 10.51 1HSL O
TER 1856 HIS C 239
mgltools-webservices-1.5.7~rc1~cvs.20130519/WebServices/CHANGELOG 0000644 0001750 0001750 00000000101 11162273573 023204 0 ustar debian debian
2008/03/24
- Implemented stop execution for Opal node LC
mgltools-webservices-1.5.7~rc1~cvs.20130519/setup.py 0000644 0001750 0001750 00000006222 10770253764 021301 0 ustar debian debian
from distutils.core import setup
from distutils.command.sdist import sdist
from distutils.command.install_data import install_data
import os
from string import find
########################################################################
# Had to overwrite the prunrefile_list method of sdist to not
# remove automatically the RCS/CVS directory from the distribution.
########################################################################
class modified_sdist(sdist):
def prune_file_list(self):
"""
Prune off branches that might slip into the file list as created
by 'read_template()', but really don't belong there:
* the build tree (typically 'build')
* the release tree itself (only an issue if we ran 'sdist
previously with --keep-temp, or it aborted)
"""
build = self.get_finalized_command('build')
base_dir = self.distribution.get_fullname()
self.filelist.exclude_pattern(None, prefix=build.build_base)
self.filelist.exclude_pattern(None, prefix=base_dir)
class modified_install_data(install_data):
def run(self):
install_cmd = self.get_finalized_command('install')
self.install_dir = getattr(install_cmd, 'install_lib')
return install_data.run(self)
########################################################################
# list of the python packages to be included in this distribution.
# sdist doesn't go recursively into subpackages so they need to be
# explicitaly listed.
# From these packages only the python modules will be taken
packages = ['WebServices',
#'WebServices.Tests',
'WebServices.VisionInterface',
'WebServices.Examples']
# list of the files that are not python packages but are included in the
# distribution and need to be installed at the proper place by distutils.
# The list in MANIFEST.in lists is needed for including those files in
# the distribution, data_files in setup.py is needed to install them
# at the right place.
data_files = []
def getDataFiles(file_list, directory, names):
fs = []
if find(directory, "doc") >= 0:
#do not include doc directory in data_files
return
for name in names:
ext = os.path.splitext(name)[1]
#print directory, name, ext, len(ext)
if ext !=".py" and ext !=".pyc":
fullname = os.path.join(directory,name)
if not os.path.isdir(fullname):
fs.append(fullname)
if len(fs):
file_list.append((directory, fs))
os.path.walk("WebServices", getDataFiles, data_files)
# description of what is going to be included in the distribution and
# installed.
from version import VERSION
setup (name = 'WebServices',
version = VERSION,
description = "A library to access Opal Web Services from NBCR",
author = 'Molecular Graphics Laboratory',
author_email = 'mgltools@scripps.edu',
download_url = 'http://mgltools.scripps.edu/downloads',
url = '',
packages = packages,
data_files = data_files,
cmdclass = {'sdist': modified_sdist,
'install_data': modified_install_data,
},
)
mgltools-webservices-1.5.7~rc1~cvs.20130519/version.py 0000644 0001750 0001750 00000000020 11475262456 021615 0 ustar debian debian VERSION="1.5.6"
mgltools-webservices-1.5.7~rc1~cvs.20130519/MANIFEST.in 0000644 0001750 0001750 00000001017 11033237714 021310 0 ustar debian debian # This list all other files to be included in the distribution
# which are not python modules
# include, exclude.... which are not described in the setup.py.
include MANIFEST.in
# list of the non python module to be included in the distribution
include WebServices/Examples/*
#include WebServices//Tests/*
# include all the CVS directories
include WebServices/CVS/*
include WebServices/Examples/CVS/*
#include WebServices/Tests/CVS/*
include WebServices/VisionInterface/CVS/*
include version.py
include WebServices/LICENSE