I have been trying to add different images to nodes in a phylogenetic tree using the ete2 software in Python, but have no success.
from ete2 import Tree, TreeStyle, NodeStyle, TextFace, faces, add_face_to_node, AttrFace
ts.show_leaf_name = True
ts.show_branch_support = True
nw = """
(((Dre:0.008339,Dme:0.300613)1.000000:0.596401,
(Cfa:0.640858,Hsa:0.753230)1.000000:0.182035)1.000000:0.106234,
((Dre:0.271621,Cfa:0.046042)1.000000:0.953250,
(Hsa:0.061813,Mms:0.110769)1.000000:0.204419)1.000000:0.973467);
"""
t = Tree(nw)
img_path = "/home/leonard/Desktop/img_faces/"
humanFace = faces.ImgFace(img_path+"human.png")
mouseFace = faces.ImgFace(img_path+"mouse.png")
def my_layout(node):
if name.startswith("Dre"):
faces.add_face_to_node(humanface, node, column=1)
t.show(my_layout)
ts = TreeStyle()
t.render("img_faces.png", w=600, tree_style = ts)
These are error messages that I have been getting:
File "abc1.py", line 34, in <module>
t.show(my_layout)
File "/usr/local/lib/python2.7/dist-packages/ete2-2.1rev544-py2.7.egg/ete2/coretype/tree.py", line 1283, in show
drawer.show_tree(self, layout=layout, tree_style=tree_style)
File "/usr/local/lib/python2.7/dist-packages/ete2-2.1rev544-py2.7.egg/ete2/treeview/drawer.py", line 84, in show_tree
tree_item, n2i, n2f = render(t, img)
File "/usr/local/lib/python2.7/dist-packages/ete2-2.1rev544-py2.7.egg/ete2/treeview/qt4_render.py", line 258, in render
set_style(n, layout_fn)
File "/usr/local/lib/python2.7/dist-packages/ete2-2.1rev544-py2.7.egg/ete2/treeview/qt4_render.py", line 746, in set_style
layout_func(n)
File "abc1.py", line 29, in my_layout
if name.startswith("Dre"):
NameError: global name 'name' is not defined
Any help is much appreciated!
This is the solution from Jaime Huerta Cepas in google group, and I quote:
"There is a general Python programming error in your script ("name" variable does not exist). I guess that what you meant is "node.name.startswith()" instead of "name.startswith()""
It worked.
According to the documentation (ete2) you need to create a faces ready to read the name attribute of nodes.
Try to add the following to your code:
#nameFace = faces.TextFace(open("text").readline().strip(), fsize=20, fgcolor="#009000")
nameFace = faces.AttrFace("name", fsize=20, fgcolor="#009000")
Related
I have been struggling with the webcolors module, and when I use the rgb_to_name() function, It raises this/these error(s)(keep in mind im also using the tkinter colorchooser):
File "C:\Users\15CharacterName\PycharmProjects\python\main4.py", line 16, in color_choose
color = webcolors.rgb_to_name(rg_blist)
File "C:\Users\15CharacterName\PycharmProjects\python\venv\lib\site-packages\webcolors.py", line 470, in rgb_to_name return hex_to_name(rgb_to_hex(normalize_integer_triplet(rgb_triplet)), spec=spec)
File "C:\Users\15CharacterName\PycharmProjects\python\venv\lib\site-packages\webcolors.py", line 430, in hex_to_name
raise ValueError("'{}' has no defined color name in {}".format(hex_value, spec))
ValueError: '#56eb62' has no defined color name in css3
Here is the normal code:
color = colorchooser.askcolor()
rg_blist = list(color[0])
color = webcolors.rgb_to_name(rg_blist)
This is the modified code to check if it was a hexadecimal value(it wasn't):
color = colorchooser.askcolor()
rg_blist = list(color[0])
try:
color = webcolors.rgb_to_name(rg_blist)
except Exception:
print(rg_blist)
output:
[109, 210, 40]
made it print the color variable and reran it- this is what I got:
((105, 150, 216), '#6996d8')
Why is this? I would like to know- I thought it would behave like the .hex_to_name method/function. If an alternate method/function should be used, please notify me!
I'm pretty new to the webcolors module, so it wouldn't suprise me if the answer is simple! Thanks in advance!
I have the following function and the following call (with the connection setup before it)
from neo4j import GraphDatabase
from pypher import Pypher
# from WebScraper import *
py = Pypher()
# server connection link
uri = "bolt://localhost:7687"
driver = GraphDatabase.driver(uri, auth=("neo4j", "cs411fpl"))
session = driver.session()
username = 'a'
varray = []
# adds a user node
def add_user(username_):
q1 = "CREATE (u:User) SET u.name= $username_"
nodes = session.run(q1)
add_user(username)
This leads to the error:
File "UserHandler.py", line 37, in <module>
add_user(username)
File "UserHandler.py", line 14, in add_user
nodes = session.run(q1)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/neo4j/work/simple.py", line 217, in run
self._autoResult._run(query, parameters, self._config.database, self._config.default_access_mode, self._bookmarks, **kwparameters)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/neo4j/work/result.py", line 101, in _run
self._attach()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/neo4j/work/result.py", line 202, in _attach
self._connection.fetch_message()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/neo4j/io/_bolt4.py", line 363, in fetch_message
response.on_failure(summary_metadata or {})
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/neo4j/io/_common.py", line 179, in on_failure
raise Neo4jError.hydrate(**metadata)
neo4j.exceptions.ClientError: {code: Neo.ClientError.Statement.ParameterMissing} {message: Expected parameter(s): username_}
Any suggestions would be great. Thanks!
You are missing the connectiong between Cypher and Python (a second argument to run). It is not enough to have spelled username_ the same way both places.
def add_user(username_):
q1 = "CREATE (u:User) SET u.name= $username_"
nodes = session.run(q1, username_=username_)
I think the following would work as well, notice how the second argument for run must describe the coupling between the Cypher and Python:
def add_user(username_):
q1 = "CREATE (u:User) SET u.name= $login"
nodes = session.run(q1, login=username_)
You might be able to find more here:
https://neo4j.com/developer/python/
I am trying to learn how to use the backtrader module on Python. I copied the code directly from the website but receiving an error message.
Here is the website: https://www.backtrader.com/docu/quickstart/quickstart/
I downloaded S&P500 stock data from Yahoo Finance and saved it into an excel file named 'SPY'. Here is the code so far:
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import datetime # For datetime objects
import os.path # To manage paths
import sys # To find out the script name (in argv[0])
# Import the backtrader platform
import backtrader as bt
if __name__ == '__main__':
# Create a cerebro entity
cerebro = bt.Cerebro()
# Datas are in a subfolder of the samples. Need to find where the script is
# because it could have been called from anywhere
modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
datapath = os.path.join(modpath, 'C:\\Users\\xboss\\Desktop\\SPY.csv')
# Create a Data Feed
data = bt.feeds.YahooFinanceCSVData(
dataname=datapath,
# Do not pass values before this date
fromdate=datetime.datetime(2000, 1, 1),
# Do not pass values after this date
todate=datetime.datetime(2000, 12, 31),
reverse=False)
# Add the Data Feed to Cerebro
cerebro.adddata(data)
# Set our desired cash start
cerebro.broker.setcash(100000.0)
# Print out the starting conditions
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
# Run over everything
cerebro.run()
# Print out the final result
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
Here is the error that I am receiving:
C:\Users\xboss\PycharmProjects\BackTraderDemo\venv\Scripts\python.exe C:/Users/xboss/PycharmProjects/BackTraderDemo/backtrader_quickstart.py
Traceback (most recent call last):
File "C:/Users/xboss/PycharmProjects/BackTraderDemo/backtrader_quickstart.py", line 39, in <module>
cerebro.run()
File "C:\Users\xboss\PycharmProjects\BackTraderDemo\venv\lib\site-packages\backtrader\cerebro.py", line 1127, in run
runstrat = self.runstrategies(iterstrat)
File "C:\Users\xboss\PycharmProjects\BackTraderDemo\venv\lib\site-packages\backtrader\cerebro.py", line 1212, in runstrategies
data.preload()
File "C:\Users\xboss\PycharmProjects\BackTraderDemo\venv\lib\site-packages\backtrader\feed.py", line 688, in preload
while self.load():
Starting Portfolio Value: 100000.00
File "C:\Users\xboss\PycharmProjects\BackTraderDemo\venv\lib\site-packages\backtrader\feed.py", line 479, in load
_loadret = self._load()
File "C:\Users\xboss\PycharmProjects\BackTraderDemo\venv\lib\site-packages\backtrader\feed.py", line 710, in _load
return self._loadline(linetokens)
File "C:\Users\xboss\PycharmProjects\BackTraderDemo\venv\lib\site-packages\backtrader\feeds\yahoo.py", line 129, in _loadline
dt = date(int(dttxt[0:4]), int(dttxt[5:7]), int(dttxt[8:10]))
ValueError: invalid literal for int() with base 10: '1/29'
Process finished with exit code 1
Does anyone have any suggestions? Any help would be greatly appreciated. Thank you so much for your time!
You get the error because of using custom csv with YahooFinanceCSVData method.
You should import them using GenericCSVData method.
data = btfeed.GenericCSVData(
dataname='SPY.csv',
fromdate=datetime.datetime(2000, 1, 1),
todate=datetime.datetime(2000, 12, 31),
nullvalue=0.0,
dtformat=('%Y-%m-%d'),
datetime=0,
high=1,
low=2,
open=3,
close=4,
volume=5,
openinterest=-1
)
For more information you can see the instruction here
Rather than do this as in the urwid example:
simple_walker = urwid.SimpleFocusListWalker([
urwid.AttrMap(urwid.Text([u'\n ',caption]), 'heading'),
urwid.AttrMap(line, 'line'),
urwid.Divider()] + choices + [urwid.Divider()])
self.listbox=urwid.ListBox(simple_walker)
I'd like to do this:
simple_walker = urwid.SimpleFocusListWalker([])
simple_walker.append(urwid.AttrMap(urwid.Text([u'\n ',caption]), 'heading'))
simple_walker.append(urwid.AttrMap(line, 'line'))
simple_walker.append(urwid.Divider())
simple_walker.append(choices)
simple_walker.append(urwid.Divider())
self.listbox=urwid.ListBox(simple_walker)
However, when I do this I get a long exception dump ending in:
File ".../listbox.py", line 717, in _set_focus_complete
(maxcol,maxrow), focus)
File ".../listbox.py", line 687, in _set_focus_first_selectable
(maxcol, maxrow), focus=focus)
File ".../listbox.py", line 419, in calculate_visible
n_rows = next.rows( (maxcol,) )
AttributeError: 'list' object has no attribute 'rows'
What is the correct way to append items to a SimpleFocusListWalker.
I'm trying to build a menu from the top down without specifying the whole thing in the constructor.
The problem above was that "choices" is a list. Needs to be the following:
for ii in choices:
simple_walker.append(ii)
I am using rpy2 to run some R commands. Dont ask why. It's necessary at this moment. So here's a part of the code.
import pandas.rpy.common as com
from rpy2.robjects import r
#Load emotionsCART decision tree. Successful.
r_dataframe = com.convert_to_r_dataframe(data)
print type(r_dataframe)
(<class 'rpy2.robjects.vectors.DataFrame'>)
r('pred = predict(emotionsCART, newdata = %s)') %(r_dataframe)
Here what I want to do is pass this r_dataframe into the calculation. I'm using the decision tree that I'd loaded earlier to predict the values. But the last line gives me an error. It says
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
r('pred = predict(emotionsCART, newdata = %s)') %(r_dataframe)
File "C:\Python27\lib\site-packages\rpy2\robjects\__init__.py", line 245, in __call__
p = rinterface.parse(string)
ValueError: Error while parsing the string.
Ideas why this is happening?
I think that:
r('pred = predict(emotionsCART, newdata = %s)') %(r_dataframe)
SHould be:
r('pred = predict(emotionsCART, newdata = %s)' % (r_dataframe) )
The %(r_dataframe) was associated with the r() part, while it should be associated with the '' (string).
But it is hard to check without a reproducible example.