def test_Node_custom_length(self): root = Node.create(length=100., length_formatter="{:0.1e}".format) self.assertEqual(root.newick, ':1.0e+02') weird_numbers_tree = "((a:1.e2,b:3j),(c:0x0BEFD6B0,d:003))" root = loads(weird_numbers_tree, length_parser=None)[0] self.assertEqual(weird_numbers_tree, root.newick) with self.assertRaises(ValueError): root = Node.create(length=1., length_formatter="({:0.1e})".format) root.newick
def upgma(distance_matrix, names=None): """Cluster based on distance matrix dist using UPGMA That is, the Unweighted Pair Group Method with Arithmetic Mean algorithm If node names are given (not None), they must be a sequence of the same length as the size of the square distance_matrix. The edge lengths in the tree are not useful for the time being. """ # Initialize nodes nodes = [Node(name) for name in (names or range(len(distance_matrix)))] # Iterate until the number of clusters is k nc = len(distance_matrix) while nc > 1: # Calculate the pairwise distance of each cluster, while searching for pair with least distance minimum_distance = numpy.inf i, j = 0, 1 for i in range(nc - 1): for j in range(i + 1, nc): dis = distance_matrix[i, j] if dis < minimum_distance: minimum_distance = dis cluster = nodes[i], nodes[j] indices = i, j # Merge these two nodes into one new node i, j = indices distance_matrix[i] = 0.5 * (distance_matrix[i]) + 0.5 * ( distance_matrix[j]) distance_matrix[:, i] = 0.5 * (distance_matrix[:, i]) + 0.5 * ( distance_matrix[:, j]) nodes[i] = Node.create(descendants=cluster) for c in cluster: c.length = distance_matrix[i, i] distance_matrix = numpy.delete(distance_matrix, j, 0) distance_matrix = numpy.delete(distance_matrix, j, 1) del nodes[j] nc -= 1 return nodes[0]
def test_Node_custom_length(): root = Node.create(length='1e2', length_parser=lambda l: l + 'i') assert root.length == '1e2i' root = Node.create(length_formatter=lambda l: 5) root.length = 10 assert root.length == pytest.approx(5)
def test_Node_custom_length(self): root = Node.create(length='1e2', length_parser=lambda l: l + 'i') self.assertEqual(root.length, '1e2i') root = Node.create(length_formatter=lambda l: 5) root.length = 10 self.assertAlmostEqual(root.length, 5)