import copy


def modify_tree_with_weights(tree, weights):
    """

    Given an ete3 Tree object and a dictionary where keys are node names in the tree and values are multipliers (can
    be generated with read_weights_file), returns a new tree where each branch in the weights dictionary is multiplied
    by the multiplier specified.

    :param tree: an ete3.Tree object
    :param weights: Dictionary where keys are names of nodes/tips in the tree, and values are weights by which branch lengths will be multiplied
    :return: A new ete3.Tree where branch lengths have been modified.
    """
    newtree = copy.deepcopy(tree)
    for node in weights:
        # Make sure that we can actually find the node, and that more than one branch doesn't have the same name.
        branch = newtree.get_leaves_by_name(node)
        if len(branch) != 1:
            raise AttributeError('The branch {} either could not be found in your tree or was found more than once. '
                                 'Please verify your tree/weights dictionary and try again.'.format(node))
        else:
            branch[0].dist *= weights[node]
    return newtree