rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
try: url = 'http://localhost:7080/rhq-rhq-enterprise-server-ejb3/WebServiceTestBean?wsdl' start(url) client = Client(url, faults=False) print 'testExceptions() faults=No' result = client.service.testExceptions() sent = client.last_sent() rcvd = client.last_received() print '\nreply( %s )\n' % str(result) except WebFaul...
def basic_doc_literal(): global errors try: url = 'http://localhost:7080/rhq-rhq-enterprise-server-ejb3/WebServiceTestBean?wsdl' start(url) client = Client(url, transport=mytransport) print client # # create name # name = client.factory.create('name') name.first = u'Jeff'+unichr(1234) name.last = 'Ortel < Comp...
basic_doc_literal() basic_rpc_literal() authentication() perspectives() content_source()
rhqTest()
def content_source(): global subject, errors try: url = 'http://localhost:7080/rhq-rhq-enterprise-server-ejb3/ContentSourceManagerBean?wsdl' start(url) client = Client(url, xstq=False) print client # # create a configuration # configuration = client.factory.create('configuration') entry = client.factory.create('confi...
LOCAL = ( 0-time.timezone/60/60 )
LOCAL = ( 0-time.timezone/60/60 ) + time.daylight
def __init__(self, date=None): if date is None: date = dt.datetime.utcnow() DateTime.__init__(self, date) self.tz.local = 0
child_vals = [l.get() for l in self.get().keys()]
child_vals = [listvar.get() for listvar in self.listvars.values()]
def get_args(self): """Return a list of arguments for the contained list(s). """ args = [] # Add parent args, if parent was defined here if not self.parent_is_copy: args.extend(self.parent.get_args()) # FIXME: Most of this is a total hack to support 'index' and # 'repeat' keywords # If child list(s) are nonempty, and w...
if not self.repeat:
child_vals = [l.get() for l in self.mapped] if any(child_vals) and not self.repeat:
def get_args(self): """Return a list of arguments for the contained list(s). """ args = [] # Add parent args, if parent was defined here if not self.parent_is_copy: args.extend(self.parent.get_args()) # Add child args, for one or many children if self.correspondence == '1:*': # FIXME: Most of this is a total hack to su...
print("Installing tovid to %s" % self.prefix)
def run(self): """Install tovid, and write a list of installed files to $prefix/lib/tovid/.install.log. """ print("Installing tovid to %s" % self.prefix) install.run(self) # Move temporary install log to $prefix/lib/tovid install_log = os.path.join(self.prefix, 'lib', 'tovid', '.install.log') print("Moving install.log ...
install_log = os.path.join(self.prefix, 'lib', 'tovid', '.install.log')
install_log = os.path.join(prefix, 'lib', 'tovid', '.install.log')
def run(self): """Install tovid, and write a list of installed files to $prefix/lib/tovid/.install.log. """ print("Installing tovid to %s" % self.prefix) install.run(self) # Move temporary install log to $prefix/lib/tovid install_log = os.path.join(self.prefix, 'lib', 'tovid', '.install.log') print("Moving install.log ...
rev_line = os.popen('svn info 2>/dev/null | grep ^Revision').read()
from commands import getoutput rev_line = getoutput('svn info 2>/dev/null | grep ^Revision')
def svn_version(): """Return the current SVN revision number, as reported by 'svn info', as a string like 'svn-r1234'. If svn is not installed, or if something goes wrong, return 'svn-unknown' """ rev_line = os.popen('svn info 2>/dev/null | grep ^Revision').read() # If rev_line is empty, either svn is missing or the co...
return 'svn-unknown'
rev_line = getoutput('bzr log -l 1 2>/dev/null | grep "^svn revno"') if rev_line: return 'svn-r' + rev_line.split(':')[1].strip().split(' ')[0] return 'svn-unknown'
def svn_version(): """Return the current SVN revision number, as reported by 'svn info', as a string like 'svn-r1234'. If svn is not installed, or if something goes wrong, return 'svn-unknown' """ rev_line = os.popen('svn info 2>/dev/null | grep ^Revision').read() # If rev_line is empty, either svn is missing or the co...
self.args.append(str(arg))
self.args.append(unicode(arg))
def add(self, *args): """Append one or more arguments to the command. Each argument passed to this function is converted to string form, and treated as a single argument in the command. No special quoting or escaping of argument contents is necessary. """ for arg in args: self.args.append(str(arg))
print(self)
print(unicode(self))
def run_redir(self, stdin=None, stdout=None, stderr=None): """Execute the command using the given stream redirections.
commands = [str(cmd) for cmd in self.commands]
commands = [unicode(cmd) for cmd in self.commands]
def __str__(self): """Return a string representation of the Pipe. """ commands = [str(cmd) for cmd in self.commands] return ' | '.join(commands)
'normal|oval|plectrum|egg|wave|galaxy|boomerang|spiral|flattube|tilde|none', 'dropdown')
thumb_masks, 'dropdown')
def strip_all(filename): return ''
self.commands = []
def __init__(self, master, text, icon): Frame.__init__(self, master) self.pages = [] self.index = IntVar() self.text = text self.icon = icon self.master = master self.commands = [] self.is_running = BooleanVar() self.is_running.set(True) self.waitVar = BooleanVar() self.waitVar.set(False)
print index
def next(self): index = wizard.index.get() print index try: self.pages[index].hide_page() wizard.index.set(index + 1) self.pages[index+1].frame.pack(side='right') self.pages[index+1].show_page() except IndexError: pass
set_env = []
def run_gui(self, args=[], index='', script=''): """Run the tovid GUI, collecting options, and saving to wizard """ title = 'load saved script' script = 'todisc_commands.bash' set_env = [] if index: print "DEBUG: setting os.environ['METAGUI_WIZARD'] =", "%s" %index os.environ['METAGUI_WIZARD'] = '%s' %index cmd = ['tod...
yscroll = Scrollbar(frame1, command=self.listbox.yview, orient='vertica')
yscroll = Scrollbar(frame1, command=self.listbox.yview, \ orient='vertical')
def draw(self): text = '''ROOT MENU (VMGM)
def get_id(self):
def set(self, program):
def get_id(self): """Create and pack container frame, then get X11 identifier for it (converted to base 10). Return the identifier """ self.frame = Frame(self.master, container=1, borderwidth=1, width=self.width, height=self.height) id = self.tk.call('winfo', 'id', self.frame) self.frame_id = '%s' %int(id, 16) return s...
id = self.tk.call('winfo', 'id', self.frame) self.frame_id = '%s' %int(id, 16) return self.frame_id
_id = self.tk.call('winfo', 'id', self.frame) if program == 'mplayer': return _id else: return '%s' %int(_id, 16)
def get_id(self): """Create and pack container frame, then get X11 identifier for it (converted to base 10). Return the identifier """ self.frame = Frame(self.master, container=1, borderwidth=1, width=self.width, height=self.height) id = self.tk.call('winfo', 'id', self.frame) self.frame_id = '%s' %int(id, 16) return s...
cmd = Popen(command, stderr=PIPE, stdout=PIPE)
cmd = Popen(command, stderr=PIPE)
def run(self, command): """Execute self.command, call the callback from self.master""" self.is_running.set(True) self.frame.pack() cmd = Popen(command, stderr=PIPE, stdout=PIPE) self.after(200, self.poll()) self.callback()
def demo(app):
def demo(program):
def demo(app): def callback(): """Called upon creation and exiting of container app, Set a BooleanVar() to track whether the app is running. """ if container.is_running.get() == True: app_is_running.set(True) else: app_is_running.set(False) root_frame.pack_forget() label.pack(side='top', fill='both', expand=1) label.c...
if container.is_running.get() == True:
if app.is_running.get() == True:
def callback(): """Called upon creation and exiting of container app, Set a BooleanVar() to track whether the app is running. """ if container.is_running.get() == True: app_is_running.set(True) else: app_is_running.set(False) root_frame.pack_forget() label.pack(side='top', fill='both', expand=1) label.configure(text='...
root_frame.pack(fill='both', expand=1) xid = container.get_id()
root_frame.pack(side='top', fill='both', expand=1) xid = app.set(program)
def execute(): label.pack_forget() button.pack_forget() root_frame.pack(fill='both', expand=1) xid = container.get_id() font = '-misc-fixed-medium-r-normal--13-100-100-100-c-70-iso8859-1' if app == 'xterm': geometry = '80x40+0+0' command = 'xterm -geometry %s -fn %s -into %s &' \ %(geometry, font, xid)
if app == 'xterm':
if program == 'xterm':
def execute(): label.pack_forget() button.pack_forget() root_frame.pack(fill='both', expand=1) xid = container.get_id() font = '-misc-fixed-medium-r-normal--13-100-100-100-c-70-iso8859-1' if app == 'xterm': geometry = '80x40+0+0' command = 'xterm -geometry %s -fn %s -into %s &' \ %(geometry, font, xid)
elif app == 'mplayer':
elif program == 'mplayer':
def execute(): label.pack_forget() button.pack_forget() root_frame.pack(fill='both', expand=1) xid = container.get_id() font = '-misc-fixed-medium-r-normal--13-100-100-100-c-70-iso8859-1' if app == 'xterm': geometry = '80x40+0+0' command = 'xterm -geometry %s -fn %s -into %s &' \ %(geometry, font, xid)
container.frame.destroy()
app.frame.destroy()
def exit_mplayer(): # send bogus edl command so mplayer sends last edl_mark send_command('edl_mark') # send quit and destroy frame send_command('quit') container.frame.destroy() # need a sleep to make sure mplayer gives up its data time.sleep(1) f = open(editlist) c = f.read() f.close() # convert text from opened file ...
time.sleep(1)
time.sleep(0.2)
def exit_mplayer(): # send bogus edl command so mplayer sends last edl_mark send_command('edl_mark') # send quit and destroy frame send_command('quit') container.frame.destroy() # need a sleep to make sure mplayer gives up its data time.sleep(1) f = open(editlist) c = f.read() f.close() # convert text from opened file ...
times.pop(-1)
if times: times.pop(-1)
def exit_mplayer(): # send bogus edl command so mplayer sends last edl_mark send_command('edl_mark') # send quit and destroy frame send_command('quit') container.frame.destroy() # need a sleep to make sure mplayer gives up its data time.sleep(1) f = open(editlist) c = f.read() f.close() # convert text from opened file ...
command = 'mplayer -nomouseinput -xy 400 \
command = 'mplayer -nomouseinput \
def exit_mplayer(): # send bogus edl command so mplayer sends last edl_mark send_command('edl_mark') # send quit and destroy frame send_command('quit') container.frame.destroy() # need a sleep to make sure mplayer gives up its data time.sleep(1) f = open(editlist) c = f.read() f.close() # convert text from opened file ...
%s -wid %s %s > /tmp/mplayer.log 2>&1' %(cmd_pipe, editlist, xid, media_file) but_frame = Frame(root_frame)
%s -wid %s %s ' %(cmd_pipe, editlist, xid, media_file)
def exit_mplayer(): # send bogus edl command so mplayer sends last edl_mark send_command('edl_mark') # send quit and destroy frame send_command('quit') container.frame.destroy() # need a sleep to make sure mplayer gives up its data time.sleep(1) f = open(editlist) c = f.read() f.close() # convert text from opened file ...
b1 = Button(but_frame, command=set_chapter, text='set chapter')
def exit_mplayer(): # send bogus edl command so mplayer sends last edl_mark send_command('edl_mark') # send quit and destroy frame send_command('quit') container.frame.destroy() # need a sleep to make sure mplayer gives up its data time.sleep(1) f = open(editlist) c = f.read() f.close() # convert text from opened file ...
b2 = Button(but_frame, command=exit_mplayer, text='Exit')
def exit_mplayer(): # send bogus edl command so mplayer sends last edl_mark send_command('edl_mark') # send quit and destroy frame send_command('quit') container.frame.destroy() # need a sleep to make sure mplayer gives up its data time.sleep(1) f = open(editlist) c = f.read() f.close() # convert text from opened file ...
container.frame.configure(width=600, height=450) container.run(command)
app.frame.configure(width=600, height=450) app.run(command)
def exit_mplayer(): # send bogus edl command so mplayer sends last edl_mark send_command('edl_mark') # send quit and destroy frame send_command('quit') container.frame.destroy() # need a sleep to make sure mplayer gives up its data time.sleep(1) f = open(editlist) c = f.read() f.close() # convert text from opened file ...
if app == 'xterm':
if program == 'xterm':
def confirm_exit(): if app_is_running.get() == 1: if app == 'xterm': text = "Close the xterm by typing 'exit', before exiting this demo" elif app == 'mplayer': text = "Close mplayer first, before exiting this demo" showerror(message=text) return quit()
elif app == 'mplayer':
elif program == 'mplayer':
def confirm_exit(): if app_is_running.get() == 1: if app == 'xterm': text = "Close the xterm by typing 'exit', before exiting this demo" elif app == 'mplayer': text = "Close mplayer first, before exiting this demo" showerror(message=text) return quit()
container = AppContainer(root_frame, 640, 480, callback)
app = AppContainer(root_frame, 640, 480, callback)
def confirm_exit(): if app_is_running.get() == 1: if app == 'xterm': text = "Close the xterm by typing 'exit', before exiting this demo" elif app == 'mplayer': text = "Close mplayer first, before exiting this demo" showerror(message=text) return quit()
HPanel('', _thumb_columns, _align),
_thumb_columns, _align,
def nodupes(seq): noDupes = [] [noDupes.append(i) for i in seq if not noDupes.count(i)] return noDupes
_thumb_rows = Choice('Rows', '', 'none', 'tooltip text ....', 'none|-tile-3x1|-tile-4x1', 'dropdown')
_thumb_columns = Choice('Thumb columns', '-thumb-columns', 'none', 'Use a montage tile of 3x1 or 4x1 instead of the usual 2x2 for 3 videos. ' 'If you want 1 row with 3 thumbs choose "3", or for 1 row with 4 thumbs ' 'choose "4".', 'none|3|4', 'dropdown')
def nodupes(seq): noDupes = [] [noDupes.append(i) for i in seq if not noDupes.count(i)] return noDupes
HPanel('', _thumb_rows, _align),
HPanel('', _thumb_columns, _align),
def nodupes(seq): noDupes = [] [noDupes.append(i) for i in seq if not noDupes.count(i)] return noDupes
_SubList.draw(self, master, allow_add_remove=False)
_SubList.draw(self, master, allow_add_remove=True)
def draw(self, master): """Draw the parent copy and related list Control, side by side in the given master. """ _SubList.draw(self, master, allow_add_remove=False) # Add callbacks to handle changes in parent self.add_callbacks()
prefix = Command('tovid', "-prefix") prefix.run(capture=True) sys_dir = prefix.get_output() + '/masks'
os_path = os.environ['PATH'].rsplit(':') sys_dir = os_path[-1] + '/masks'
def nodupes(seq): noDupes = [] [noDupes.append(i) for i in seq if not noDupes.count(i)] return noDupes
m = MATCHER_IMG.search(data) self._img_urls.append(m.group(1)) m = MATCHER_SHOW.search(data)
m = MATCHER_TAG.search(data) self._img_urls.append(m.group(2))
def _upload(self, image): self._curl.setopt(pycurl.HTTPHEADER, ['Expect:']) self.post('http://imageshack.us/', [ ('fileupload', (pycurl.FORM_FILE, image)), ('uploadtype', 'on'), ('refer', 'http://www.imageshack.us/'), ('brand', ''), ('email', ''), ('MAX_FILE_SIZE', '13145728'), ('optsize', '320x320'), ('url', 'paste im...
community this will not be what you want.
community the default behaviour is not what you want.
def __init__(self, cmap=None, inputFile=None, N_nodes=None): """Create node cover from data.
def create_commIDs(self):
def getCommIDs(self):
def create_commIDs(self): """Construct commIDs.
cID_A = create_commIDs(self) cID_B = create_commIDs(other)
cID_A = self.getCommIDs() cID_B = other.getCommIDs()
def _getOverlapNetwork(self, other): """Create a bipartite network from overlapping nodes.
if src>=nNodes:
while nNodes<=src or nNodes<=dest:
def _setEdge(self,src,dest,val): nNodes=len(self._nodeList) if src>=nNodes: self._addNode() if dest>=nNodes: self._addNode() if val==0: try: del self._nodeList[src][dest,0] except KeyError: pass try: del self._nodeList[dest][src,0] except KeyError: pass else: self._nodeList[src][dest,0]=val self._nodeList[dest][src,0]=...
if dest>=nNodes: self._addNode()
nNodes+=1
def _setEdge(self,src,dest,val): nNodes=len(self._nodeList) if src>=nNodes: self._addNode() if dest>=nNodes: self._addNode() if val==0: try: del self._nodeList[src][dest,0] except KeyError: pass try: del self._nodeList[dest][src,0] except KeyError: pass else: self._nodeList[src][dest,0]=val self._nodeList[dest][src,0]=...
axes.annotate(showthislabel,(xy[node][0]+nodeLabel_xOffset,xy[node][1]),
axes.annotate(showthislabel,(xy[node][0],xy[node][1]), textcoords='offset points', xytext=(nodeLabel_xOffset, 0),
def VisualizeNet(net, xy, figsize=(6,6), coloredNodes=True, equalsize=False, equalshape=True, labels=None, fontsize=7, showAllNodes=True, nodeColor=None, nodeShape='o', nodeEdgeColor='k', nodeSize=1.0, minnode=2.0, maxnode=6.0, nodeColors=None, nodeSizes=None, nodeShapes=None, bgcolor='white', maxwidth=2.0, minwidth=0....
""" Finds connected components of a network.
"""Get connected components of a network NOTE! This method currently discards nodes with no edges (proper behaviour would be to turn them into components, so this should be fixed).
def getComponents(net): """ Finds connected components of a network. Parameters ---------- net : A network object Returns ------- Connected components as a NodePartition object. """ edges=net.edges ee=EvaluationList(edges) ee.setLastEvaluation() p=Percolator(ee,buildNet=False) for cs in p: return cs
for neigh in self[nodeName]: self[node,neigh]=0 self[neigh,node]=0
for neigh in list(self[nodeName]): self[nodeName,neigh]=0 self[neigh,nodeName]=0
def _removeNodeEdges(self,nodeName): for neigh in self[nodeName]: self[node,neigh]=0 self[neigh,node]=0
self.result=[self.Nclones,self.clones,self.keeptheserows,self.m]
self.result=[self.Nclones,self.clones,self.keeptheserows,self.m,self.msdata]
def applyme(self):
for i in xdict: if i!=None: for j in ydict: if j!=None: dist += float(i-j)**2*xdict[i]/NElementsX*ydict[j]/NElementsY distList.append(dist) return sum(distList)/self.getNumberofLoci()
if NElementsX!=0 and NElementsY!=0: for i in xdict: if i!=None: for j in ydict: if j!=None: dist += float(i-j)**2*xdict[i]/NElementsX*ydict[j]/NElementsY distList.append(dist) return sum(distList)/len(distList)
def getGroupwiseDistance_Goldstein(self,x,y): """ Returns the goldstein distance between two populations
Example ------- >>> ms=eden.MicrosatelliteData(open("../data/microsatellites/microsatellites.txt",'r')) >>> ms_u = ms.getUniqueSubset() >>> ms_u.getGroupwiseDistance_Goldstein([1,2,3,4],[1,2,3,4]) == 1330.5 True
def getGroupwiseDistance_Goldstein(self,x,y): """ Returns the goldstein distance between two populations
for i in xdict: for j in ydict: dist += 1.0*(i-j)**2*xdict[i]/(len(x))*ydict[j]/(len(y))/self.getNumberofLoci() distList.append(dist) return sum(distList)
NElementsX=float(sum(xdict.itervalues())-xdict.get(None,0)) NElementsY=float(sum(ydict.itervalues())-ydict.get(None,0)) if NElementsX!=0 and NElementsY!=0: for i in xdict: if i!=None: for j in ydict: if j!=None: dist += float(i-j)**2*xdict[i]/NElementsX*ydict[j]/NElementsY distList.append(dist) return sum(distList)/l...
def getGroupwiseDistance_Goldstein(self,x,y): """ Returns the goldstein distance between two populations
matrix / network using the formula W = 1 - D / max(D).
matrix / network using the formula W = 1 - D / max(D)+epsilon.
def dist_to_weights(net,epsilon=0.001): '''Transforms a distance matrix / network to a weight matrix / network using the formula W = 1 - D / max(D). Returns a matrix/network''' N=len(net._nodes) if (isinstance(net,pynet.SymmFullNet)): newmat=pynet.SymmFullNet(N) else: newmat=pynet.SymmNet() edges=list(net.edges) ma...
maxd=maxd+epsilon
def dist_to_weights(net,epsilon=0.001): '''Transforms a distance matrix / network to a weight matrix / network using the formula W = 1 - D / max(D). Returns a matrix/network''' N=len(net._nodes) if (isinstance(net,pynet.SymmFullNet)): newmat=pynet.SymmFullNet(N) else: newmat=pynet.SymmNet() edges=list(net.edges) ma...
newmat[edge[0]][edge[1]]=1-edge[2]/maxd
newmat[edge[0]][edge[1]]=1-edge[2]/maxd+epsilon
def dist_to_weights(net,epsilon=0.001): '''Transforms a distance matrix / network to a weight matrix / network using the formula W = 1 - D / max(D). Returns a matrix/network''' N=len(net._nodes) if (isinstance(net,pynet.SymmFullNet)): newmat=pynet.SymmFullNet(N) else: newmat=pynet.SymmNet() edges=list(net.edges) ma...
max_node_diameter = max(node_diameters.values()) y_coords = sorted(map(operator.itemgetter(1), coords.values())) x_coords = sorted(map(operator.itemgetter(0), coords.values())) ax_pos = axes.get_position() x_span = x_coords[-1] - x_coords[0] y_span = y_coords[-1] - y_coords[0] ax_width_inches = ax_pos.width*axes.get_fi...
if scaling: max_node_diameter = max(node_diameters.values()) y_coords = sorted(map(operator.itemgetter(1), coords.values())) x_coords = sorted(map(operator.itemgetter(0), coords.values())) ax_pos = axes.get_position() x_span = x_coords[-1] - x_coords[0] y_span = y_coords[-1] - y_coords[0] ax_width_inches = ax_pos....
def draw_node(axes, x, y, shape, color, size, edgecolor, edgewidth, zorder): axes.plot([x], [y], shape, markerfacecolor=color, markeredgecolor=edgecolor, markeredgewidth=edgewidth, markersize=size, zorder=zorder)
axes.set_autoscale_on(prev_autoscale)
def draw_node(axes, x, y, shape, color, size, edgecolor, edgewidth, zorder): axes.plot([x], [y], shape, markerfacecolor=color, markeredgecolor=edgecolor, markeredgewidth=edgewidth, markersize=size, zorder=zorder)
return self.totalDeg(nodeIndex)
return self._totalDeg(nodeIndex)
def _degIndex(self,nodeIndex): return self.totalDeg(nodeIndex)
runTests()
test_pynet()
def test_pynet(): suite = unittest.TestSuite() #symmetric tests: suite.addTest(TestPynet("test_basic_symm_ScipySparseSymmNet")) suite.addTest(TestPynet("test_basic_symm_NumpyFullSymmNet")) suite.addTest(TestPynet("test_basic_symm_LCELibSparseSymmNet")) #dir tests: suite.addTest(TestPynet("test_basic_dir_ScipySparseDir...
normalizedValue = normalizeValue(value,valueLimits) color = colorMap(normalizedValue)
normalizedValue = normalizeValue(value,valueLimits) print " ",normalizedValue color = colorMap(normalizedValue)
def setColor(value,valueLimits,colorMap): """Converts a numerical value to a color. The value is scaled linearly to the range (0...1) using the function normalizeValue and the limits valueLimits. This scaled value is used to pick a color from the given colormap. The colormap should take in values in the range (0...1) ...
axes : matplotlib.axes object (default: None) If given, the network will be drawn in this axis. Otherwise a separate figure is created (which you then have to give as an argument to the pylab.FigureCanvasBase method be able to plot it.) Note that if `baseFig` is also give this parameter has no effect.
def VisualizeNet(net, xy, figsize=(6,6), coloredNodes=True, equalsize=False, equalshape=True, labels=None, fontsize=7, showAllNodes=True, nodeColor=None, nodeShape='o', nodeEdgeColor='k', nodeSize=1.0, minnode=2.0, maxnode=6.0, nodeColors=None, nodeSizes=None, nodeShapes=None, bgcolor='white', maxwidth=2.0, minwidth=0....
if axes is None: axes = thisfigure.add_subplot(111)
axes = thisfigure.add_subplot(111)
def VisualizeNet(net, xy, figsize=(6,6), coloredNodes=True, equalsize=False, equalshape=True, labels=None, fontsize=7, showAllNodes=True, nodeColor=None, nodeShape='o', nodeEdgeColor='k', nodeSize=1.0, minnode=2.0, maxnode=6.0, nodeColors=None, nodeSizes=None, nodeShapes=None, bgcolor='white', maxwidth=2.0, minwidth=0....
cm = get_cmap() cm._segmentdata={
cm={
def getConstantColorMap(rgb=(0,0,0)): """Return a colormap with constant color. Parameters ---------- rgb : tuple (r, g, b) The color as RGB tuple. Each value must be between 0 and 1. Return ------ cm : colorMap The colormap that has just one constant color. """ cm = get_cmap() cm._segmentdata={ 'red': ( (0,rgb[0],r...
return cm
return matplotlib.colors.LinearSegmentedColormap("constant colormap",cm)
def getConstantColorMap(rgb=(0,0,0)): """Return a colormap with constant color. Parameters ---------- rgb : tuple (r, g, b) The color as RGB tuple. Each value must be between 0 and 1. Return ------ cm : colorMap The colormap that has just one constant color. """ cm = get_cmap() cm._segmentdata={ 'red': ( (0,rgb[0],r...
if colorMap=='primary': myMap=get_cmap() myMap._segmentdata={ 'red': ( (0,1,1), (0.5,0,0), (1,1,1) ), 'green': ( (0,1,1), (0.5,0.5,0.5), (1,0,0) ), 'blue': ( (0,0,0), (0.5,1,1), (1,0,0) ), } elif colorMap=='orange': myMap=get_cmap() myMap._segmentdata = { 'red' : ( (0.,.99,.99), (0.2,.98,.98), (0.4,.99,.99), (0.6,...
known_colormaps = ('primary', 'orange', 'bluered') if colorMap in known_colormaps: if colorMap == 'primary': segmentdata={'red': ( (0,1,1),(0.5,0,0), (1,1,1) ), 'green': ( (0,1,1), (0.5,0.5,0.5), (1,0,0) ), 'blue': ( (0,0,0), (0.5,1,1), (1,0,0) )} elif colorMap=='orange': segmentdata = { 'red' : ( (0.,.99,.99), (0....
def setColorMap(colorMap): """Set a colormap for edges. Two options of our own ('orange' and 'primary') are available in addition to the 150 pylab readymade colormaps (which can be listed with help matplotlib.cm ). Usage: myMap = setColorMap('bone') """ if hasattr(colorMap, '_segmentdata'): return colorMap if colorM...
if valueLimits[0] != valueLimits[1]:
if valueLimits[0] < valueLimits[1]:
def setColor(value,valueLimits,colorMap): """Converts a numerical value to a color. The value is scaled linearly to the range (0...1) using the function normalizeValue and the limits valueLimits. This scaled value is used to pick a color from the given colormap. The colormap should take in values in the range (0...1) ...
minwidth=0.2, uselabels='none', edgeColorMap='winter',
minwidth=0.2, uselabels='some', edgeColorMap='winter',
def VisualizeNet(net, xy, figsize=(6,6), coloredNodes=True, equalsize=False, labels=None, fontsize=7, showAllNodes=True, nodeColor=None, nodeSize=1.0, minnode=2.0, maxnode=6.0, nodeColors=None, nodeSizes=None, bgcolor='white', maxwidth=2.0, minwidth=0.2, uselabels='none', edgeColorMap='winter', weightLimits=None, setNo...
uselabels : str, either 'none' or 'all' If 'all', the node index is shown as label for those nodes that are not listed in `labels`.
uselabels : either 'some' (default), 'none' or 'all' If 'some', the label is shown for the nodes whose label is given in `labels`. If 'all', the node index is shown also for those nodes that are not listed in `labels`. If 'none', no node labels are printed.
def VisualizeNet(net, xy, figsize=(6,6), coloredNodes=True, equalsize=False, labels=None, fontsize=7, showAllNodes=True, nodeColor=None, nodeSize=1.0, minnode=2.0, maxnode=6.0, nodeColors=None, nodeSizes=None, bgcolor='white', maxwidth=2.0, minwidth=0.2, uselabels='none', edgeColorMap='winter', weightLimits=None, setNo...
node_edgecolor='w'
def VisualizeNet(net, xy, figsize=(6,6), coloredNodes=True, equalsize=False, labels=None, fontsize=7, showAllNodes=True, nodeColor=None, nodeSize=1.0, minnode=2.0, maxnode=6.0, nodeColors=None, nodeSizes=None, bgcolor='white', maxwidth=2.0, minwidth=0.2, uselabels='none', edgeColorMap='winter', weightLimits=None, setNo...
node_edgecolor='k'
def VisualizeNet(net, xy, figsize=(6,6), coloredNodes=True, equalsize=False, labels=None, fontsize=7, showAllNodes=True, nodeColor=None, nodeSize=1.0, minnode=2.0, maxnode=6.0, nodeColors=None, nodeSizes=None, bgcolor='white', maxwidth=2.0, minwidth=0.2, uselabels='none', edgeColorMap='winter', weightLimits=None, setNo...
color=color, size=nodesize,edgecolor=node_edgecolor) if not (uselabels=='none'): if uselabels == 'all': axes.annotate(str(node),(xy[node][0]+nodeLabel_xOffset,xy[node][1]),
color=color, size=nodesize, edgecolor=nodeEdgeColor) if node in labels or uselabels == 'all': if node in labels: if isinstance(labels[node],float): showthislabel="%2.2f" % labels[node] else: showthislabel=labels[node] else: showthislabel = str(node) axes.annotate(showthislabel,(xy[node][0]+nodeLabel_xOffset,xy[node][...
def VisualizeNet(net, xy, figsize=(6,6), coloredNodes=True, equalsize=False, labels=None, fontsize=7, showAllNodes=True, nodeColor=None, nodeSize=1.0, minnode=2.0, maxnode=6.0, nodeColors=None, nodeSizes=None, bgcolor='white', maxwidth=2.0, minwidth=0.2, uselabels='none', edgeColorMap='winter', weightLimits=None, setNo...
elif node in labels: if isinstance(labels[node],float): showthislabel="%2.2f" % labels[node] else: showthislabel=labels[node] axes.annotate(showthislabel,(xy[node][0]+nodeLabel_xOffset,xy[node][1]),color=fontcolor,size=fontsize)
def VisualizeNet(net, xy, figsize=(6,6), coloredNodes=True, equalsize=False, labels=None, fontsize=7, showAllNodes=True, nodeColor=None, nodeSize=1.0, minnode=2.0, maxnode=6.0, nodeColors=None, nodeSizes=None, bgcolor='white', maxwidth=2.0, minwidth=0.2, uselabels='none', edgeColorMap='winter', weightLimits=None, setNo...
for nodeIndex in self.net: lenght+=len(self.net[nodeIndex].edges)
def __len__(self): lenght=0 for nodeIndex in self.net: lenght+=len(self.net[nodeIndex].edges) if self.net.isSymmetric(): return lenght/2 else: return lenght
self.tree[thisLevel][communityIndex]=fatherIndex self.net[self._getNameByNode((thisLevel,communityIndex)),self._getNameByNode((thisLevel-1,fatherIndex))]=len(cslist)+1-thisLevel break
bestFatherIndex=fatherIndex self.tree[thisLevel][communityIndex]=bestFatherIndex self.net[self._getNameByNode((thisLevel,communityIndex)),self._getNameByNode((thisLevel-1,bestFatherIndex))]=len(cslist)+1-thisLevel
def __init__(self,cslist): cslist.reverse() self.tree=[] self.cslist=cslist self.tree.append([])
order=[(0,0)]
order=map(lambda x:(0,x),range(len(self.tree[0])))
def _getLeafOrderInTree(self): order=[(0,0)] for level in range(1,len(self.tree)): replace={} for i in range(0,len(self.tree[level])): father=(level-1,self.tree[level][i]) if father in replace: replace[father]+=[(level,i)] else: replace[father]=[(level,i)] for father in replace.keys(): fi=order.index(father) order=orde...
for j,jName in enumerate(nodeNames[i+1:]):
for j in range(i+1,numberOfSpecimens): jName=nodeNames[j]
def getDistanceMatrix(self,distance="lm",nodeNames=None): """ Computes the distance between each node and returns the corresponding distance matrix. """ if distance=="lm": getMSDistance=self.getMSDistance_linearManhattan elif distance=="nsa": getMSDistance=self.getMSDistance_nonsharedAlleles elif distance=="ap": getMSD...
return self.getCommunitySizes()[0]
communitySizes=self.getCommunitySizes() if len(communitySizes)>0: return communitySizes[0] else: return 0
def getGiantSize(self): """Get the size of the largest component. """ return self.getCommunitySizes()[0]
If False, the frame and axis will be not be shown in the plot.
If False, the frame will be not be shown in the plot. You can still use axis labels.
def visualizeNet(net, coords=None, axes=None, frame=False, nodeShapes=None, defaultNodeShape='o', nodeColors=None, defaultNodeColor=None, nodeEdgeColors=None, defaultNodeEdgeColor='black', edgeColors=None, defaultEdgeColor=None, nodeSizes=None, defaultNodeSize=None, edgeWidths=None, defaultEdgeWidth=None, nodeEdgeWidth...
axes.set_axis_off()
axes.set_frame_on(False) axes.set_xticklabels([]) axes.xaxis.set_ticks_position('none') axes.set_yticklabels([]) axes.yaxis.set_ticks_position('none')
def draw_node(axes, x, y, shape, color, size, edgecolor, edgewidth, zorder): axes.plot([x], [y], shape, markerfacecolor=color, markeredgecolor=edgecolor, markeredgewidth=edgewidth, markersize=size, zorder=zorder)
yield self.node.net[self.node.index,index]
yield self.node.net[self.node.name,index]
def __iter__(self): for index in self.node: yield self.node.net[self.node.index,index]
kcliqueList=kcliquesWeight(net,k,lambda x:getIntensity(x,net))
kcliqueList=kcliquesWeight(net,k,getIntensity)
def kcliquePercolator(net,k,start,stop,evaluations,reverse=False,weightFunction=None): if weightFunction==None: edges=list(net.edges) edges.sort(lambda x, y: cmp(x[2],y[2]),reverse=reverse) edgesAndEvaluations=EvaluationList(edges) edgesAndEvaluations.setLinearEvaluations(start,stop,evaluations) kcliques=kcliquesByEdge...
newNet = pynet.Net()
newNet = net.__class__()
def collapseIndices(net,returnIndexMap=False): """ Chances the indices of net to run from 0 to len(net)-1 """ newNet = pynet.Net() indexmap = {} index = 0 for i in net: if net[i].deg() != 0: indexmap[i] = index; index += 1 for i in net: for j in net[i]: if net[j][i] != 0: newNet[indexmap[i]][indexmap[j]] = net[i][j]...
if net[i].deg() != 0: indexmap[i] = index; index += 1 for i in net: for j in net[i]: if net[j][i] != 0: newNet[indexmap[i]][indexmap[j]] = net[i][j] newNet[indexmap[j]][indexmap[i]] = net[j][i]
newNet.addNode(index) indexmap[i] = index; index += 1 for edge in net.edges: i,j,w=edge newNet[indexmap[i]][indexmap[j]] = w
def collapseIndices(net,returnIndexMap=False): """ Chances the indices of net to run from 0 to len(net)-1 """ newNet = pynet.Net() indexmap = {} index = 0 for i in net: if net[i].deg() != 0: indexmap[i] = index; index += 1 for i in net: for j in net[i]: if net[j][i] != 0: newNet[indexmap[i]][indexmap[j]] = net[i][j]...
class SliderDialog(MySimpleDialog):
class SliderDialog2(MySimpleDialog):
def applyme(self): self.result=[self.scale_1.get(),self.e1.get()]
return self._totalDeg(nodeIndex)
return self._totalDeg[nodeIndex]
def _degIndex(self,nodeIndex): return self._totalDeg(nodeIndex)
edgesAndEvaluations=EvaluationList(edges,evaluations,evaluationType)
edgesAndEvaluations=EvaluationList(edges,evaluations=evaluations,evaluationType=evaluationType)
def cliquePercolator(net,k,evaluations,weightFunction="minweight",evaluationType="fraclist",reverse=False): """ Weighted and unweighted clique percolation with sequential clique percolation algorithm. Parameters ---------- net : Network object k : Size of the clique to be used. evaluations : The evaluation data. weigh...
kcliques=EvaluationList(kcliqueList,evaluations,evaluationType,weightFunction=lambda x:getIntensity(x,net))
kcliques=EvaluationList(kcliqueList,evaluations=evaluations,evaluationType=evaluationType,weightFunction=lambda x:getIntensity(x,net))
def cliquePercolator(net,k,evaluations,weightFunction="minweight",evaluationType="fraclist",reverse=False): """ Weighted and unweighted clique percolation with sequential clique percolation algorithm. Parameters ---------- net : Network object k : Size of the clique to be used. evaluations : The evaluation data. weigh...
return self._indexToNameIter(self.net._iterNodeIn(self.net._nodes[name]))
return self._indexToNameIter(self.net._iterNodeIn(self.net._nodes[self.name]))
def iterIn(self): if not self.name in self.net: raise KeyError, "Node not in the network." #name -> index -> backend iterator -> index -> name return self._indexToNameIter(self.net._iterNodeIn(self.net._nodes[name]))
return self._indexToNameIter(self.net._iterNodeOut(self.net._nodes[name]))
return self._indexToNameIter(self.net._iterNodeOut(self.net._nodes[self.name]))
def iterOut(self): if not self.name in self.net: raise KeyError, "Node not in the network." #name -> index -> backend iterator -> index -> name return self._indexToNameIter(self.net._iterNodeOut(self.net._nodes[name]))
for neigh in self._nodeList[nodeIndex]: yield neigh
for neigh in self._nodeList[nodeIndex].iterkeys(): yield neigh[0]
def _iterNode(self,nodeIndex): #First iter through all outgoing neighbors: for neigh in self._nodeList[nodeIndex]: yield neigh #Then iter through only incoming neighbors for neigh in self._backNodeList[nodeIndex]: if not (neigh,0) in self._nodeList[nodeIndex]: yield neigh
for neigh in self._backNodeList[nodeIndex]: if not (neigh,0) in self._nodeList[nodeIndex]: yield neigh
for neigh in self._backNodeList[nodeIndex].iterkeys(): if not neigh in self._nodeList[nodeIndex]: yield neigh[0]
def _iterNode(self,nodeIndex): #First iter through all outgoing neighbors: for neigh in self._nodeList[nodeIndex]: yield neigh #Then iter through only incoming neighbors for neigh in self._backNodeList[nodeIndex]: if not (neigh,0) in self._nodeList[nodeIndex]: yield neigh
def getNumberOfLines(filename,nfields):
def getNumberOfLines(input,nfields):
def getNumberOfLines(filename,nfields): """ Returns length of the given file in lines. Throws IOError if the file does not exist. """ theFile=open(filename,'rU') i=0 for line in theFile: fields=line.split(splitterChar) if len(fields)!=nfields: f.close() raise Exception("Invalid number of fields on row: "+str(i+1)) i+=1...
theFile=open(filename,'rU')
if isinstance(input, str): theFile = open(input, 'rU') else: theFile = input
def getNumberOfLines(filename,nfields): """ Returns length of the given file in lines. Throws IOError if the file does not exist. """ theFile=open(filename,'rU') i=0 for line in theFile: fields=line.split(splitterChar) if len(fields)!=nfields: f.close() raise Exception("Invalid number of fields on row: "+str(i+1)) i+=1...
def checkNodes(filename,net,fieldNames,hasHeader,splitterChar):
def checkNodes(input,net,fieldNames,hasHeader,splitterChar):
def checkNodes(filename,net,fieldNames,hasHeader,splitterChar): """ Returns ------- A tuple where: The first element is True if each node in a network is in the property file, and otherwise False The second element is True if each node in the property file is in the network, and otherwise False """
f=open(filename,'rU')
def checkNodes(filename,net,fieldNames,hasHeader,splitterChar): """ Returns ------- A tuple where: The first element is True if each node in a network is in the property file, and otherwise False The second element is True if each node in the property file is in the network, and otherwise False """
fileHasAllNodes,netHasAllNodes=checkNodes(filename,net,fieldNames,propertyNames==None,splitterChar)
fileHasAllNodes,netHasAllNodes=checkNodes(input,net,fieldNames,propertyNames==None,splitterChar)
def addProperty(net,node,propertyName,theString): if isanum(theString): # if it is a number net.nodeProperty[propertyName][node]=float(theString) if isint(theString): # if it is integer net.nodeProperty[propertyName][node]=int(theString) else: # if it is a string net.nodeProperty[propertyName][node]=theString
nPropertyLines=getNumberOfLines(filename,nfields)
nPropertyLines=getNumberOfLines(input,nfields)
def addProperty(net,node,propertyName,theString): if isanum(theString): # if it is a number net.nodeProperty[propertyName][node]=float(theString) if isint(theString): # if it is integer net.nodeProperty[propertyName][node]=int(theString) else: # if it is a string net.nodeProperty[propertyName][node]=theString
self._alleles[i/2].append(None)
self._alleles[i/2].append((None,fields[i]))
def __init__(self,input,missingValue="999999"): """ The microsatellite data must be given as a input where each row has microsatellites for one node/specimen. Alleles should be given as integer numbers representing the number of repetitions. The data should have even number of columns where each pair represents two hom...