Comments (3)
Hi Mike,
This is something that @sidneymbell and I were talking about a few days ago. There's currently nothing in place within the repo itself, but I've written this snippet to do it semi-manually:
from datetime import datetime as dt
import json
nexus_tree=bt.loadNexus('/mnt/c/Users/evogytis/Downloads/aln_03_0816.mcc.tree')
nexus_tree.treeStats()
def convertToJSON(node,index,most_recent_tip):
json_node={'name': None,
'node_attrs': {'num_date': {'value': node.absoluteTime}},
'branch_attrs': {}
}
if 'height_95%_HPD' in node.traits: ## height 95% HPD available, compute from most recent tip date
lower,upper=node.traits['height_95%_HPD']
time_range = [most_recent_tip-upper, most_recent_tip-lower]
json_node['node_attrs']['num_date']['confidence']=time_range
if node.branchType=='node': ## node
json_node['children']=[] ## has children
json_node['name']='NODE_%07d'%(index) ## different name
for child in node.children: ## iterate over children
if child.branchType=='node': index+=1 ## increment index if child is node too
index,json_child=convertToJSON(child,index,most_recent_tip) ## get the json-formatted child
json_node['children'].append(json_child) ## attach resulting json-formatted children to current json node
else:
json_node['node_attrs']['country']={'value': node.name.split('|')[2], 'confidence': {node.name.split('|')[2]: 1.0}}
json_node['node_attrs']['location']={'value': node.name.split('|')[3], 'confidence': {node.name.split('|')[3]: 1.0}}
json_node['name']=node.name.split('|')[0] ## leaf, name is simple
return index,json_node
def toNextstrainJSON(tree,output):
out_file=open(output,'w')
_,json_tree=convertToJSON(tree.root,0,tree.mostRecent)
output_json={'version': 'v2',
'meta': {'updated': '%s'%(dt.strftime(dt.now(),'%Y-%m-%d')),
'colorings': [{'key': 'country', 'title': 'Country', 'type': 'categorical'},
{'key': 'location', 'title': 'Location', 'type': 'categorical'}],
'panels': ['tree'],
'display_defaults': {'color_by': 'country',
'distance_measure': 'num_date',
'geo_resolution': 'country',
'map_triplicate': 'true'},
'filters': ['country','location']
},
'tree': json_tree}
json.dump(output_json,out_file,indent=1)
out_file.close()
out='/mnt/c/Users/evogytis/Downloads/aln_03_816.json'
toNextstrainJSON(nexus_tree,out)
Hopefully it's clear enough to adapt to your own case but if not - let me know. I intend to include some way of exporting auspice JSON files in the future but it's not a priority at the moment.
from baltic.
@evogytis Amazing! Thanks much for this code snippet, and prompt reply.
To give a bit more background: we are trying to visualize mutations for each sample on the tree. We have the back end for the visualization worked out, but need total mutations as a key:value
for each leaf to provide the data to drive things. I have the tree traversal worked out with the newick formatted tree and muts_nt.json
. I am trying to find an easy way to make the last step to add that information back to the Auspice JSON. So, I am going from Nextstrain JSON, modifying each leaf, and then back to Nextstrain. I was having a terrible time parsing the JSON format until I hit upon baltic. This is an amazing set of tools!
So, I think my case might be easier than even the snippet you provided. I should be able to work from your example. I will close for now, and if I hit an issue I will re-open the ticket.
from baltic.
In case anyone comes across this issue and needs nextstrain to nextstrain. Here is the code snippet I modified from above.
import baltic as bt
import json
def convertToJSON(node,index,most_recent_tip):
json_node={'name': None,
'node_attrs': {'num_date': {'value': node.absoluteTime}}
}
if node.branchType=='node': ## node
json_node['children']=[] ## has children
json_node['name']=node.name ## different name
json_node['node_attrs']=node.traits['node_attrs']
try:
json_node['branch_attrs']=node.traits['branch_attrs']
except:
pass
for child in node.children: ## iterate over children
if child.branchType=='node': index+=1 ## increment index if child is node too
index,json_child=convertToJSON(child,index,most_recent_tip) ## get the json-formatted child
json_node['children'].append(json_child) ## attach resulting json-formatted children to current json node
else:
json_node['node_attrs']=node.traits['node_attrs']
json_node['branch_attrs']=node.traits['branch_attrs']
json_node['name']=node.name
# make a change to specific leaf node here.
return index,json_node
def toNextstrainJSON(tree,meta,output):
out_file=open(output,'w')
_,json_tree=convertToJSON(tree.root,0,tree.mostRecent)
output_json={'meta': meta,
'tree': json_tree,
'version': 'v2'} #
json.dump(output_json,out_file,indent=1)
out_file.close()
nextstrainPath='<PATH>/ncov_example.json'
myTree, myMeta = bt.loadJSON(nextstrainPath)
out='auspice_modified_output.json'
toNextstrainJSON(myTree,myMeta,out)
from baltic.
Related Issues (20)
- Write basic unit tests
- Set up continuous integration HOT 1
- Add magic methods to baltic classes
- Set up sphinx for auto-documentation of classes and functions from docstrings
- Adding extra elements on tree plots HOT 8
- Booleans as values of traits dict incorrectly output to string. HOT 1
- loadJSON translation needs to be accessing `node_attrs` within traits instead of traits directly
- loadJSON needs to be updated for the new nextstrain json format HOT 2
- AttributeError: 'NoneType' object has no attribute 'traverse_tree' HOT 2
- TypeError: unsupported operand type(s) for -: 'function' and 'int' HOT 2
- Add exports HOT 2
- No way of adding text to circular tree. HOT 2
- Unicode Errors
- Take singleton as a baltic tree object
- commonAncestor returns wrong node when MRCA is root of tree HOT 1
- Tree regex tricky to use HOT 1
- Ascending branch sort? HOT 4
- Typo in assertion that checks if new coordinates were computed by the drawTree function HOT 1
- Unable to extract assigned color, clade id, and leaf id into tsv/dataframe HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from baltic.