I believe there are a number of ways to construct a tree metric from a distance metric. A very straightforward method, neighbor joining, is available in the Sciki-Bio package. A less straightforward option with more freedom is by using the scipy.cluster.hierarchy module to obtain a linkage matrix, then using the to_tree()
method to obtain a scipy Tree
object, and finally writing a script to convert a scipy Tree object to a newick string.
I've copied the example from scikit-bio below:
>>> from skbio import DistanceMatrix
>>> from skbio.tree import nj
>>>
>>> data = [[0, 5, 9, 9, 8],
... [5, 0, 10, 10, 9],
... [9, 10, 0, 8, 7],
... [9, 10, 8, 0, 3],
... [8, 9, 7, 3, 0]]
>>> ids = list('abcde')
>>>
>>> dm = DistanceMatrix(data, ids)
>>> # Or from a tsv file with header, no column 0
>>> reader = csv.reader(open(args.inputfile), delimiter="\t")
>>> x = list(reader)
>>> dm = DistanceMatrix(x[1:],x[0])
>>>
>>> newick_str = nj(dm, result_constructor=str)
>>> print(newick_str[:55], "...")
(d:2.000000, (c:4.000000, (b:3.000000, a:2.000000):3.00 ...
- Note: Both methods require you to supply the input as a numpy distance matrix